diff --git a/Documentation/accel/apple-ane.rst b/Documentation/accel/apple-ane.rst new file mode 100644 index 0000000000000..d5cde48c710a2 --- /dev/null +++ b/Documentation/accel/apple-ane.rst @@ -0,0 +1,684 @@ +.. SPDX-License-Identifier: GPL-2.0-only + +Apple ANE firmware preflight +=========================== + +The shared ANE firmware module recognizes the H16 (``apple,t6041-ane``, +physical T6040/M4 Pro) and H17 (``apple,t8140-ane``) generations. Recognition +is not an inference support claim: both remain unavailable for execution. +They never enter the H13 task-manager or H14 disk-firmware boot paths. + +H17 ownership +------------- + +Linux has no ANE exclave ownership handoff. The module refuses registration +with ``-EOPNOTSUPP`` and one informational message when an H17 node is +present, including a disabled node. This check occurs before platform core +DMA configuration and automatic power-domain attachment. A probe-time +check alone would be too late. Removing ``apple,exclave-assigned`` does not +establish ownership and does not bypass refusal. + +H16 preload handoff +------------------ + +The bootloader must reserve the personalized TEXT and DATA preload segments +as separate, non-reusable ``no-map`` reserved-memory nodes, attach them in +that order through ``memory-region`` and name them ``firmware-text`` and +``firmware-data``. It must also supply ``apple,firmware-iovas`` as two 64-bit +values: ``0x10000000000`` and ``0x100000c0000``. Their sizes must be +``0xc0000`` and ``0x2ac000``. Physical placement is boot-dependent; board DT +sources must not contain captured physical addresses. The reservations must +remain intact until reboot, including after driver failure. + +Metadata preflight checks resource geometry and these ranges without MMIO +or power access. Missing reservations fail with ``-ENODATA`` and malformed +reservations with ``-EINVAL``. Without ``h16_stage`` the module still refuses +registration before power access. An explicit stage enables the diagnostic +backend described below. The original-container userspace load ABI and +process installation remain unavailable. No accel node or program-loading +interface is published for these stages. + +The H16 DT nodes stay disabled. The five real PMGR providers already encode +the system/CPU/MPM/task/base dependency graph. The PMGR binding does not +represent the virtual no-state gates, so no fictitious register-backed +domains are created for them. SID 0 and SID 11 on all three DARTs use the +shared DMA description. The staged diagnostic backend requires the +SID-0-only test description discussed below; no untested remapping is added. + +Implemented SPEC-r2 components +------------------------------ + +The shared transport has an eight-descriptor dynamic channel parser with +unique names, bounded counts, owned-surface bounds and overlap checks. The +runtime uses copied descriptor geometry, verifies the descriptor snapshot, +and checks the complete IO reply envelope. Zero acknowledgment is success; +a nonzero acknowledgment is a firmware refusal, never a retry or success. +Malformed replies, guard changes and timeouts quarantine the instance. A +quarantined queue cannot allocate another BO, and no reset is attempted. + +The version-12 RTKit management state machine validates HELLO, endpoint maps, +system endpoint start, IOP/AP power acknowledgments and application endpoint +start ordering. It does not invent responses for unknown message types or +unimplemented system endpoint buffer requests. Its caller must provide one +absolute session deadline and a bounded 64-bit mailbox transport. + +H16 task streams begin with little-endian ``u32 1`` and twelve reserved zero +bytes. This marker precedes the first aligned task; it is not a task count. +The initial H16 gate rejects a zero marker, other values and nonzero reserved +bytes. The public H16 encoder fixes this prologue at commit +``927013f5480768b07c8e62a866e1514c41aba778`` of +``joshuaswarren/mil-hwx-compiler``, in +``plugins/H16G/Encoding/H16GALUEncoder.mm``. + +H16 validation helpers walk nine fixed task-header words, the documented +conditional extra word, dense/scatter records and the nine allowed register +blocks. A separate helper checks the eight-byte Mach-O relocation entries, +unique aligned offsets, the actual kernel-section ordinal and addend bounds. +Original-container, tensor, program and aperture validation is provided +separately as described below. + +The device-free selftest in ``tools/testing/selftests/drivers/ane`` generates +the SPEC-r2 fp16 add-128 inputs and CPU oracle and verifies all three pinned +buffer hashes. It can also check a supplied HWX against the pinned size/hash. +It never opens an accel device or claims a Linux inference result. + +Remaining implementation gates +------------------------------ + +The preload validator authenticates stable, owned snapshots of the normalized +resident image with 42 ordered patchbay records. The staged backend provides +live snapshot acquisition and cold startup. The original-container userspace +load ABI and resolved program bindings still need installation. Off-list +preload mutations remain refused. + +The 2026-10-31 H16 runtime observation did not capture cold boot, scratch +negotiation, RTKit management, CONFIG_GET or RESOURCE_INFO_GET. The round-5 H16 facts define the staged cold-start path below. RTKit +version 12 is negotiated if offered, without waiting on management progress. +The CONFIG_GET tick must be nonzero and is logged; it is not pinned to +24 MHz. Resource ceilings remain conservative host policy. H17 additionally +requires a Linux ownership backend before direct access; h16_stage does not +bypass that refusal. + +Resident image identity +----------------------- + +The preload checker requires exactly ``0xc0000`` TEXT bytes and ``0x2ac000`` +DATA bytes. It validates the raw four-byte tag and little-endian width of +each of the 42 packed patchbay records, including records at odd offsets. +It then hashes TEXT followed by DATA, substituting zero only for the 20 +reviewed mutable value cells and the DATA-relative tunables interval +``[0x17c80, 0x18320)``. The expected SHA-256 is compiled into the validator: +``1f865ed04c4c38f6fdcc4543a8814f818d3cea583de64d22ffe96e3a93ca4697``. +Tags, widths, unlisted values, all TEXT bytes and the DATA zerofill tail +remain authenticated. An off-list change is never accepted merely because +a zero word became nonzero or a value resembles an address. + +Validation never changes its input snapshots. A future boot backend must +prove ownership and snapshot stability before calling it, preserving the +resident pages, their personalized mutable values and the reservations. +The checker is not connected to preflight yet: a generic CPU resource claim +cannot distinguish an ordinary busy ``no-map`` reservation from another +owner. No live pages are read by this preparatory path. A successful identity +check does not establish RTKit state, ownership of a running firmware +instance or permission to publish new DMA mappings. + +Original-container import and load planning +------------------------------------------ + +The internal original-HWX import helper bounds the complete 64-bit byte +count before allocation, copies userspace memory once, then validates and +digests that private snapshot. It accepts no caller-provided digest or +section metadata. A failed import leaves the destination untouched, and an +occupied snapshot cannot be overwritten. No ioctl exposes this helper yet. + +Validated metadata retains whole-segment geometry and file extents, so one +TEXT allocation covers both task and constant sections. Scratch and external +surfaces have zero file bytes. The load planner reparses the authenticated +original instead of trusting cached metadata, rounds allocations to 16 KiB +and applies a 512 MiB aggregate host ceiling before any DMA allocation. + +The resource geometry helper requires one backend-owned mapping per planned +segment and one binding per external surface, resolved by the backend from +the validated program contract. It checks exact sizes, permissions, +alignment, full-width DVA overflow and overlap against every other mapping +and the resident firmware aperture. Binding VMs, classes and unique indices +must match the validated surface requirements. +Failure publishes no partial resource map. The helper checks geometry; +the backend must separately prove mapping ownership and lifetime. + +There is no H16 LOAD_PROGRAM or CREATE_PROCESS body serializer or backend +that resolves resources and installs a process here. CREATE_PROCESS reply +IDs do not supply resource bindings. The backend must resolve them from the +validated program contract and verify mapping ownership. No user ID or +surface ordinal substitutes for that authority, and no load plan installs +an executable process. The original-HWX userspace ABI remains deferred until +the backend can return a program capability backed by validated resources. +Channel-5 allocation replies, boot publication and H17 direct ownership +remain refused. + +H16 macOS 27.0 runtime contract +------------------------------ + +J616s has one ANE interrupt, 1054, used as the shared-memory channel +doorbell/completion line for all firmware-to-host replies and events. +It has no ANE exclave assignment. This identifies the interrupt role, not +its cold-start masking/acknowledgment sequence. H17's two IRQ roles remain +unknown. ANE runtime uses its own channel transport; it does not establish +an A7IOP/RTBuddy boot sequence. + +Host command bytes 0..3 are zero, the little-endian u16 ID is at +4 and +the u16 acknowledgment at +6. All observed successful replies had zero +acknowledgment. Nonzero meanings remain unknown and are refused. + +================== ====== ======= ================== +Command ID Channel Bytes +================== ====== ======= ================== +LOAD_PROGRAM 0x0200 1 0x1c0 +UNLOAD_PROGRAM 0x0201 1 0xc +CREATE_PROCESS 0x0202 1 0x258 +TERMINATE_PROCESS 0x0203 1 0x10 +EXECUTE 0x020c 7 0xca8/0xcc0/0xcd8 +POWER_GATE 0x002d 7 0xc +EVENT_REPORT 0x0300 6 0x60 (firmware to host) +================== ====== ======= ================== + +These sizes bound the observed version, not future firmware. POWER_GATE has +a u32 Boolean at +8. The execute-size increment of 0x18 counts custom BAR +records. The channel numbers are observed table indices; +the clean cold-boot facts identify their channel names. The parser retains each +descriptor's original index rather than assuming name order is wire order. + +The transport prepares the H16 envelope and rejects unrecognized runtime +IDs, wrong sizes, channels and power-gate values before publication. +H14's 0x0204 procedure packet and short CREATE_PROCESS body remain H14-only; +H16's serializer and UUID completion table are connected to the shared +submission and event paths, subject to validated process resources. +The H16 runtime command table does not authorize startup commands. + +H16 execute and event fields +--------------------------- + +The macOS 27.0 field contract has a fixed 0xca8-byte execute body followed +by zero, one or two observed 0x18-byte custom BAR records. The 64-slot +ordinary buffer array starts at +0x60 with a 0x30-byte stride; the valid +count is at +0x28. A descriptor carries flags at +0, resource index at +4, +numeric class at +8, the fixed value 3 at +0x10, a u64 DVA at +0x18 and a +u64 byte span at +0x20. Other descriptor bytes are zero. The UUID at +execute +0x20 is independent of program/process/procedure IDs at +8/+0xc/+0x10. +The observed priority is 5 at +0x18; request flags and reserved bytes are zero. + +The custom BAR count is at +0xca0 and records start at +0xca8. Each carries +u32 configuration/value-type/BAR selectors, u8 bit offset/width, u16 flags +and a u64 value. ``ane_h16_execute_encode()`` accepts kernel-owned resource +metadata, checks nonempty counts up to 64 and overflow-free mapping spans, +and zeroes unused slots and reserved space. The caller must first match +indices, numeric classes, permissions, selectors and values to immutable +validated process metadata and keep mappings pinned. The helper does not +establish that authority. Its two-BAR ceiling, 64-bit field bound and +same-configuration/BAR overlap refusal are conservative draft restrictions, +not established firmware-wide limits. Unknown class and selector semantics +are not guessed. There is no userspace interface for these structures. + +Channel 7 acknowledges submission only. Channel 6 carries 0x60-byte 0x0300 +events, with UUID at +8, program/process/procedure at +0x10/+0x14/+0x18 and +state at +0x1c. State 0 is start, 3 hardware-start, 1 successful terminal +completion and 2 terminal failure. Failure was established from field use; +it was not present in the runtime sample. The first word selects report +slots or rolls independently; 0xfe00..0xfe03 is not a universal prefix or a +completion key. CPU-load and timestamp fields are diagnostic. + +``ane_h16_event_decode()`` validates the channel, exact size, command and +zero u16 acknowledgment before returning fields. The result helper requires +all four identity fields to match an outstanding request. Destination 1 is +routed away from the general scheduler; unknown states/destinations refuse. +A caller must register a unique pending UUID before publication, consume it +atomically once on a terminal report, synchronize DMA, and apply quarantine +rules before considering any mapping release. A classifier result alone +cannot prove safe release or reject duplicate events without pending state. + +The shared H16 submission path allocates a non-reused 64-bit UUID, installs +it in a bounded pending table before publishing channel 7, and waits for +both the transport reply and its own terminal event. Events may arrive +before the acknowledgment. States 0 and 3 leave the UUID pending; states +1 and 2 retire it once after matching every identifier. Unknown, duplicate +and late UUIDs cannot retire another request. An identifier mismatch for a pending UUID or a malformed report +quarantines the queue. ISP-destination reports and short +CPU-load notifications cannot complete a general-scheduler request. + +One absolute deadline covers acknowledgment and terminal completion; a +report at or beyond that deadline cannot succeed. Failure state 2, +transport refusal, timeout or corruption prevents output copy-back and +quarantines the queue without retry or reset. Firmware-visible process +mappings remain resident, including after file close. Closing a file +revokes its process capabilities before freeing its staging BO handles. + +Only private coherent DMA mappings may appear in H16 execute descriptors. +Userspace BOs serve as staging buffers: inputs are snapshotted before +publication and outputs are copied back after validated terminal success. +Write barriers order input and command stores before publication; DMA read +barriers order output reads after completion. Streaming DMA sync APIs must +not be applied to these coherent allocations. There is no userspace alias +to code, scratch or live firmware buffers. + +The backend must resolve the resource map from the original HWX and the +reviewed program contract, rather than decode it from CREATE_PROCESS reply +IDs. A userspace index, numeric class or program/process ID cannot +create that map or confer ownership. Only established input/output classes +are admitted; custom BAR requests require a validated selector map and +remain unavailable. The legacy 0x28-byte completion predicate remains +H14-only. Channel-5 allocation/control/free operations require a validated +H16 reply provider and remain unavailable; H14 allocation replies are never +reused for H16. + +No original-container load ABI or H16 process installer is supplied +by this change. Consequently no H16 process can yet be installed, inference +remains refused and no accel node is registered. The submission integration +is preparatory and does not open the boot, preload, ownership, firmware +version or resource gates. + +KUnit covers byte-exact synthetic execute fields, all 1..64 buffer counts, +zero/one/two custom BAR lengths, wide DVAs/spans, reserved-zero output, +boundary and overflow refusal, all event states, interleaved identities, +ISP routing and malformed reports. No test packet is copied from a capture. + +Shared H16/H17 firmware transport +-------------------------------- + +``ane_fw_transport.h`` supplies device-independent ring operations over owned +coherent surfaces and caller-provided memory, DMA-barrier, MMIO, clock and +allocation accessors. Engine-relative doorbell and pending/acknowledge offsets +come from ``ane_fw_platform`` match data. The caller must establish ownership, +firmware identity, power and the private DMA domain before using it. This +helper does not change probe or enable either generation. + +Initialization copies exactly eight 0x100-byte descriptors from the IPC +surface and validates their names, types, bits, slot counts, alignment and +non-overlapping ranges, including exclusion of the table itself. IO and +DATA_CHAIN_H2T require type 0; SHAREDMALLOC and IO_T2H require type 1. Each +operation checks the immutable table snapshot. Only type-0 slots are armed, +in word-1, word-2, word-0 order, with values 0, 0, 1 and a DMA write barrier. +Descriptor geometry and doorbell bits remain authoritative. Logical channel +names are independent of their descriptor order. + +Publication copies a command into a 64-byte-aligned arena inside the pool, +after the caller's reserved boot prefix. It publishes both length words, +a DMA write barrier, the command DVA, another barrier and the descriptor's +doorbell bit. There is one outstanding transaction per sending channel; +heads advance modulo the descriptor slot count only after a successful +reply. A reply requires the exact DVA with bit 0 set, unchanged length, +zero result word, zero command prefix, unchanged u16 ID and zero u16 ack. +Bit 1 is corruption even before ownership returns. Nonzero ack is returned +as ``-EREMOTEIO`` and retained for diagnosis. + +IO_T2H is present when word 0 has bit 0 clear and either word 0 or word 1 is +nonzero. Reports must be four-byte aligned and wholly inside one owned +surface. The transport copies the report before setting word 0 bit 0 and +ringing the descriptor doorbell, without changing the other slot words. +Report dispatch and pending UUID lookup belong to the caller. In particular, +consuming a stale UUID report cannot complete an unrelated request, and the +DATA_CHAIN reply acknowledges submission rather than inference completion. + +The SHAREDMALLOC provider accepts allocation tuples only. Requests are +rounded to 16 KiB, with a 1 MiB request ceiling, the exact 2 MiB allocation +with tag 0x45585050 exception, 12 MiB in rounded allocations and 64 handles. +The allocation callback supplies a zeroed, pinned private-domain mapping; +the transport checks its size, DVA alignment, overflow and exclusion from +all other owned surfaces before publishing it. Handles are nonzero ordinals. +By default, FREE and distinguishable control tuples return ``-EOPNOTSUPP`` +through the mandatory refusal logger. The pinned H16 build enables the +proved native FREE reply described below. An all-zero slot is empty and +cannot distinguish a control request; its lookup request layout remains +unproved. No control reply is invented. + +IRQ service reads pending once, rejects bits above 7 and writes the exact +nonzero snapshot to acknowledge. The wait helper services one allocation at +a time and checks the original absolute monotonic deadline, including time +spent inside the allocation callback. Servicing never starts a new timeout. + +The caller serializes all entry points. Initialize a fresh transport only +before firmware starts or after a proved reset. The pool arena is monotonic +and returns ``-ENOSPC`` when exhausted; command storage is not recycled. +Successful reply bodies remain in the pool transaction span. A timeout, +malformed firmware tuple, allocation failure or firmware refusal latches an +error, retains the transaction and mappings and stops further publication. +No surface is freed by these helpers, including a rejected allocation result. +The backend must retain mappings, power and module references until reset. + +The field contract follows the clean H16/H17 cold-boot facts, sections 1, +7 through 11, and the SPEC-r2 channel and deadline rules. Allocation limits +are conservative host policy observed sufficient on H17, rather than +firmware-advertised authority. The KUnit suite uses synthetic memory and +accessor traces, with no MMIO or hardware access. Its configuration fragment +is ``drivers/accel/ane/transport.kunitconfig`` and runs on x86_64 and arm64. + + +Original HWX validation +----------------------- + +The validator consumes one kernel-owned immutable snapshot of the complete +HWX. It requires subtype 7 and bounded, exactly consumed load commands; +rejects unknown command kinds, duplicate descriptors, overlapping segments, +sections and file regions; and validates symbols against the complete +section-ordinal table. Tensor names, directions, normalized fp16 dimensions, +overflow-checked strides and full batched spans must agree with their +surfaces and buffer references. There must be at least one input and one +output, with the single output last. + +The linear and scratch program descriptors have exact fixed fields and +zero reserved bytes. All five 16-byte aperture records must equal whole +surface segment bases in order, followed by the optional kernel base; +reserved halves and unused records are zero. Interior, duplicate, reordered +and scratch/text aperture addresses are refused. Task counts and word counts +must agree with the independent stream walk. Relocations use the actual +kernel section ordinal, unique bounded offsets and valid addends, and may +patch only packed-record payload words. Headers, register selectors and +padding remain immutable. + +SHA-256 covers the entire original snapshot, including load commands and +padding. The snapshot digest is rechecked before execution. Validation +provides metadata, not allocation authority or permission to load a program; +the original-container ABI and firmware resource map remain required. + +The hardware-free KUnit suites cover pending UUID lifecycle, acknowledgment +versus completion, interleaving, progress, failures, malformed and mismatched +reports, routing, duplicates, timeouts, capacity and UUID exhaustion. HWX +tests generate synthetic linear/scratch forms with optional kernel data, +then exercise command, geometry, tensor, aperture, symbol, relocation and +digest refusal paths. No hardware inference result is implied. + +Staged H16 cold boot +------------------- + +The read-only module parameter ``h16_stage`` accepts ``preflight``, ``map``, +``boot`` or ``startup``. Each includes the preceding stages. No H14 boot +parameter changes the H16 path. H17 still refuses ownership and registration. +All build-dependent boot values and ordered masked updates belong to the +H16 27.0 (26A428) match-data profile. The existing preload validator must +accept the resident image before that profile can run. Live mutable patchbay +and firmware tunable values are preserved, with no disk firmware owner. + +``preflight`` raises the five real domains through genpd, in DT order, and +checks every requested/ACTUAL low byte twice before reading the engine. +CPU control must be zero and RVBAR must be ``0x10000000001``. It reads all +three DART fault status/address words, version/protect/lock headers and four +DAPF records per instance against ``apple,dapf-ranges``. The ANE backend +writes no engine, DART or DAPF register at this rung. Genpd owns power writes. + +``map`` claims an exclusive, singleton IOMMU group and an unmanaged domain +covering the three SID-0 DART instances. Private surfaces currently require +a DMA-coherent client; noncoherent clients refuse pool allocation before RUN. No +unexported architecture cache helper is called from the module. It checks +the finalized aperture +rather than widening geometry in the client. TEXT is read-only, DATA is +read/write, and the four range-containing 16 KiB pages use identity addresses +and MMIO attributes. Every DAPF lock is checked before any record changes; +a locked mismatch refuses. Unlocked changes preserve unrelated flag bits +and are read back. The backend does not change protect or lock registers. + +The DT must describe only SID 0 on these three instances for this backend. +The generic IOMMU attachment API attaches every stream in ``iommus``; it +cannot select a subset from the six-stream production description. Until +the test DT supplies only SID 0, map and later stages explicitly refuse +extra streams. The inherited test DTS currently enables the six-stream +node and therefore needs this integration adjustment before rung 2. The +production node stays disabled. The driver does not rewrite the live DT +or access the DART driver's private stream configuration. + +``boot`` allocates the zeroed command pool at ``0x10000384000`` and completes +the H16 CE request/ack protocol, bounded to 5001 delays of 10 us. Ordered +ANEAXI2AF, ANEXLAXI2AF and selected C1PPT updates follow before any scratch +write. A pre-existing C1PPT lock requires matching values. There is no H17 +PWGATE sequence. The host clears scratch 0 through 7 in order, prepares the +polled management client, writes scratch 6 = 1 and 7 = 0, rechecks RVBAR, +and writes CPU control 0 then 0x10. RVBAR is never rewritten. + +The host polls READY ``0x08042006`` every 1 ms, with at most 1000 polls and +one absolute deadline. Scratch 0 is a channel count below 0x21. IPC bytes +are scratch 1 plus one; heap bytes are scratch 3; scratch 4 is a Boolean. +IPC and heap allocations are rounded to 16 KiB and bounded before use. +The IPC allocation at ``0x100003d0000`` must fit below the fixed heap base +``0x100003e4000``. The heap has a 16 MiB host-policy limit and must also fit +below shared allocations. These limits are not firmware capability claims. + +The 0x174-byte init record at pool + 0x180 has a zero first qword, IPC DVA, +0x380000 configured span, the corresponding 0xfc80000 remainder, requested +heap DVA/bytes, unrounded IPC bytes and pool DVA/bytes. Reserved bytes and +the cold-start retained value are zero. Template count is 64 and record ++0x12c is 4. A DMA write barrier precedes publication to scratch 0 low, +scratch 1 high, then scratch 7 ``0xf7fbdff9``. The reply must contain both +READY and the exact IPC base; unchanged init-record addresses time out. +The shared transport validates the table before arming any type-0 ring. +Only then does the host write READY to scratch 3 and wait for zero. + +``startup`` sends only PRINT_ENABLE (0x4, 12 bytes), START (0x0, 12), +CONFIG_GET (0x3, 16) and RESOURCE_INFO_GET (0x22, 100) on IO. SHAREDMALLOC +allocation requests are serviced under the shared transport's bounded host +policy while waiting. The pinned H16 profile also acknowledges native FREE +for its own live allocations with a zero tuple. Backing storage and quota +stay pinned until reboot; retired allocations cannot authorize reports or +a second FREE. Foreign frees and control forms without a proved request +layout quarantine without an invented reply. Other firmware profiles retain +the default refusal of FREE/control. Each command keeps one absolute +deadline and requires a zero acknowledgment. The CONFIG_GET tick must be nonzero and is logged; +24 MHz is a comparison value, not a refusal predicate. All 100 resource-info +reply bytes are logged and do not grant allocation authority. + +Mailbox service uses 64-bit pop-on-read accesses and bounded, nonblocking +receive/transmit batches. Offered HELLO, EPMAP and power messages use the +shared version-12 parser. Unknown or incompatible messages are logged and +receive no invented response. A missing or stalled RTKit session never +blocks the scratch protocol. IRQ 1054 remains disabled through all stages. + +Before RUN, errors unwind mappings and genpd references with a rollback log. +Immediately before the first RUN write the backend pins the module. Every +later failure latches quarantine, dumps scratch 0 through 7 and DART fault +words, and retains mappings, pages and power. Probe stays bound on such an +error so automatic devres cleanup cannot reclaim firmware DMA. A successful +boot also stays pinned because no safe in-place shutdown/reset is proved. +Further attempts are refused until reboot. There is no writable stage knob. + +Hardware test plan +------------------ + +Use a matching kernel/module set and the tether-loaded J616s ANE test DTB. +The test DT needs the SID-0-only adjustment above, the two loader-provided +reserved preload ranges and an aperture covering the identity pages. Keep +shipping DT nodes disabled and persistent boot storage untouched. Boot with +``user4k=on modprobe.blacklist=ane,ane_t6021`` and the tether console args. +Each command below is a separate stage attempt. Preserve full dmesg at the +first unexpected value. + +Before RUN the module can be removed between rungs:: + + modprobe ane_t6021 h16_stage=preflight + rmmod ane_t6021 + modprobe ane_t6021 h16_stage=map + rmmod ane_t6021 + +Expected preflight messages include ``H16 preload identity H16 27.0 26A428 +accepted``, ``H16 power ACTUAL`` twice for each of the five words with low +byte ff, ``H16 CPU control/RVBAR 0 10000000001``, DART status/address and +DAPF comparisons, then ``H16 stage 1 complete``. Map adds TEXT/DATA mapping +messages and four ``H16 identity MMIO`` messages, clean fault words and +``H16 stage 2 complete``. An unchanged six-stream test tree instead logs +``H16 map requires only SID 0 on three DARTs; refusing extra streams``. + +On a fresh boot run the boot rung:: + + modprobe ane_t6021 h16_stage=boot + +Expect CE state/ack and ``H16 tunables applied`` (or locked-match) logs, +then ``H16 READY 8042006 0``, request logs (the comparator values are +channels 8, IPC-minus-one c440, heap f00000, mode 0), then +``H16 table validated 100003d0000 8``, ``H16 scratch 3 cleared 0 0`` and +``H16 stage 3 complete; held until reboot``. Comparator sizing values are +not additional admission checks. Never unload after this command. + +Reboot through the tether route before testing startup:: + + modprobe ane_t6021 h16_stage=startup + +Expect the boot messages, SHAREDMALLOC allocation messages as offered, +``H16 startup ack`` for IDs 4, 0, 3 and 22 with zero status, +``H16 CONFIG_GET tick`` with a nonzero value, ``H16 stage 4 complete; held +until reboot`` and exactly 100 bytes under ``H16 RESOURCE_INFO``. A failure +after RUN must instead show the scratch/fault dump and ``H16 quarantine``. +Do not retry or unload; collect logs and reboot. No inference result is +claimed by these diagnostic rungs. + +The ``ane-h16-boot`` KUnit suite uses a simulated engine, scratch cells, +mailbox polling and rings. It covers startup including allocation service, +missing READY, wrong/stale table publication, oversized IPC/heap requests, +channel bounds, locked DAPF differences, nonzero acks, scratch-3 timeout, +zero tick, default refusal and quarantine after RUN. It also covers matching +locked DAPF, heap/shared overlap, native FREE, foreign FREE and control refusal. + +H13 timeout and engine recovery +============================== + +The host task-manager path (``ane.ko``) gives each submission one second, +including DART fault-drain retries. An expired submission returns +``-ETIMEDOUT``; recovery never silently retries a program whose output may be +partial. The task's GEM lookup references are released when the ioctl returns. + +Recovery holds the engine and PM-entry locks, drops the current consumer +runtime-PM reference, synchronously suspends its power-domain suppliers, and +checks both the PMGR ACTUAL fields and every attached genpd for power-off. +The SET window omits the shared SYS_CPU parent, whose DART consumers can +suspend asynchronously; it must also turn off before the consumer resumes. +Recovery then restores the consumer +reference, checks power-on before engine MMIO, and runs the probe task-manager +enable sequence. BO handles and mappings remain valid for resubmission. +The system-sleep force helpers are unsuitable here: a forced, in-use supplier +can retain its active runtime status and keep its parent domains powered. + +A power-off acknowledgment is required before reinitializing the engine. +Only after power-on and task-manager readiness are also verified does recovery +release the exceptional module pin and reclaim preserved BOs. If any step +fails, mappings, backing pages and the pin remain held; new submissions fail. +This also covers a partially resumed engine whose retained queue state is +uncertain. The ``reset`` sysfs write retries recovery. Module reload cannot +recover a device while that pin is held. Direct PMGR SET writes and speculative +writes to undocumented task-error registers are not part of this reset path. + +The ``ane-pm-recovery`` KUnit suite exercises the shared PM transaction against +real runtime-PM device links, including repeated cycles, single-domain devices, +consumer/supplier suspend errors, a missing power-off acknowledgment and a +failed resume. It checks that every exit restores the caller's PM reference. +The minimal config is +``tools/testing/selftests/drivers/ane/pm.kunitconfig``. + +Destructive recovery selftest +---------------------------- + +``tools/testing/selftests/drivers/ane/recovery.py`` is an explicitly invoked +hardware test, excluded from the default device-free selftests. It requires +exclusive ownership of an M1-family ANE, Python 3, the packaged H13 add fixture, +and a deliberately invalid convolution program. Run it through the hardware +controller with a watchdog and kernel-log capture:: + + python3 recovery.py /usr/share/omarchy-ane/fixtures/h13-anec/add/program-0.anec hang.anec + +The test keeps both clients open, submits the invalid program three times, +requires a bounded ``ETIMEDOUT`` and ``wedged=0`` each time, and runs twenty +bit-exact add jobs on the surviving client's original fd and mappings after +each reset. Every call changes its inputs and poisons the valid output lanes, +so stale output cannot pass. Its oracle uses exact fp16 quarter values and checks the complete +output, including padding. Closing both clients must return the module +reference count to its initial value; the boot identity must remain unchanged. +An operator should also verify three power-off acknowledgments in the kernel +log and a normal module unload/reload after all clients close. A failed reset +is a test failure, not permission to force unload the module. + +Generate ``hang.anec`` on a build host with ``make-hang-fixture.py`` and a clean +checkout of the MIT-licensed public compiler at commit +``ef2dbceefedff38ecce4f3dc593e148c5e7a6d54`` from +https://github.com/aurora-silicon/mil-hwx-compiler/pull/2:: + + python3 make-hang-fixture.py /path/to/mil-hwx-compiler hang.anec --cxx clang++ + +This first checks that the normal encoder refuses the shape. It bypasses only +that refusal in a temporary translation unit to generate a deterministic +stride-2 1x1 128-to-256 convolution at 56-to-28 spatial size, the refused family +reported to hang the M1 Pro. The compiler checkout is unchanged. No Apple +binary or private program capture is used. The generator writes a hash receipt; +the hardware test must fail if this particular instance does not actually +produce a timeout. The loader pins both fixture hashes and uses ABI 1 ioctls directly, so no +shared libane library is needed. ``--check-fixtures`` validates the two containers without +opening a device. + +H14 recovery lifecycle +---------------------- + +The firmware path (``ane_t6021.ko``) uses one bounded deadline for the command +acknowledgment and its finish event. H14 engine reset is not enabled by this +change. Reusing only the H13 task-manager re-arm would leave the firmware and +its program cache invalid. The corresponding recovery implementation needs to: + +* Serialize firmware commands and stop the RX worker before releasing the + consumer's runtime-PM reference and synchronously suspending its suppliers. +* Verify power-off for the CPU and engine partitions through their providers + before dropping boot pins or reclaiming firmware-visible allocations. +* Retain metadata for every firmware-owned BO and boot allocation, including + objects whose last userspace reference disappeared. The current release + path discards some of this metadata while retaining the backing memory. +* Restore the validated firmware image and run the existing fenced probe boot + sequence, including channel-table validation, host acknowledgment and + CONFIG_GET. A failed boot remains quarantined with its DMA backing held. +* Invalidate the cached program/process IDs across the restart and prevent a + stale userspace ID from aliasing a newly allocated firmware ID. Clients must + reload their programs before resubmitting. + +Those ownership and identifier changes require their own H14 reset test. +Quarantine must not be cleared solely because a power transition returned zero. + +J616c / 25F84 diagnostic inference measurements +============================================= + +The explicit ``h16_stage=startup h16_job=1`` debugfs job path can load the +resident 25F84 profile and run host-built inference records on J616c. It is a +private bring-up interface, not a production accel ABI. The loader must fill +both disabled preload reservations from the live ADT; this series does not +include that m1n1 handoff or distribute Apple firmware/HWX files. + +An optional serial governor chooses a 30 us hold after a matching dedicated +SUCCESS token and a 125 us recovery after an ordinary or unknown completion. +It invalidates feedback before each new EXECUTE and across overlap, and never +delays an already outstanding submission. Its parameters remain off by default. + +Tiny-convolution measurements on one J616c/M4 Max with 25F84 firmware: + +======================= ============ =========== ================== +Configuration Timed calls Rate / s Dedicated SUCCESS +======================= ============ =========== ================== +Fixed 30 us hold 1,000 7,929 286 / 1,000 +Adaptive 30 / 125 us 1,000 12,045 996 / 1,000 +Adaptive exact repeat 1,000 12,229 999 / 1,000 +Adaptive longer run 3,000 12,078 2,993 / 3,000 +======================= ============ =========== ================== + +The longer run is the retained result (campaign run242, kernel +``c597f3ae89ff81273af692120032cc62a5ca22b9``). All gaps and preparation are +included in the kernel EVENT-return span, about 0.25 s. Two full output +comparisons bracket each timed block; the input is constant within it. All +four cells pass with zero DART faults and IRQ fallbacks. The selected module +arguments, in addition to the startup/job selection, were:: + + h16_startup_drain_ms=10 h16_postboot=1 h16_job_irq=1 h16_map_batch=1 + h16_job_result_mb=32 h16_job_return_trace=1 h16_job_gap_us=30 + h16_job_gap_every=1 h16_job_drain_us=0 h16_job_recovery_us=125 + +The worker and IRQ handler ran on CPU0; PCPU1 requested its maximum floor and +fabric requests were DCS5/SOC2. These requests do not prove achieved ANE clocks. +Native fresh-process checked loops reach 12.4--12.9k/s with userspace work and +per-call comparisons, so these results do not establish full API, correctness +cadence, long-duration stability or energy parity. Large-model logits/masks and +mixed independent-buffer jobs also match the retained native outputs. + +Spin200, natural report-notification batching and firmware PMU registration +followed by disable-gating did not establish a throughput improvement. Keep +these experiments and the governor opt-in. Intermittent boot/startup failures, +production lifetime/recovery and matched userspace/energy comparisons remain +open. The review branch replays the ANE changes onto the GPU dependency; the +campaign measurements apply to the source identity above, not a new boot of +that rebased tree. diff --git a/Documentation/accel/index.rst b/Documentation/accel/index.rst index cbc7d4c3876a1..ba0f4f8dc6cef 100644 --- a/Documentation/accel/index.rst +++ b/Documentation/accel/index.rst @@ -8,6 +8,7 @@ Compute Accelerators :maxdepth: 1 introduction + apple-ane amdxdna/index qaic/index rocket/index diff --git a/Documentation/devicetree/bindings/gpu/apple,agx.yaml b/Documentation/devicetree/bindings/gpu/apple,agx.yaml index f5b1afd7d7dd3..ecada84f98f86 100644 --- a/Documentation/devicetree/bindings/gpu/apple,agx.yaml +++ b/Documentation/devicetree/bindings/gpu/apple,agx.yaml @@ -18,6 +18,7 @@ properties: - apple,agx-g14g - apple,agx-g14s - apple,agx-t6040 + - apple,agx-t6041 - apple,agx-t8132 - apple,agx-t8140 - items: @@ -307,6 +308,15 @@ allOf: apple,afr-leak-coef: minItems: 1 maxItems: 1 + - if: + properties: + compatible: + contains: + enum: + - apple,agx-t6040 + - apple,agx-t6041 + then: + properties: reg: items: - description: GFX coprocessor control registers @@ -354,6 +364,7 @@ allOf: contains: enum: - apple,agx-t6040 + - apple,agx-t6041 - apple,agx-t8132 - apple,agx-t8140 then: diff --git a/Documentation/devicetree/bindings/npu/apple,ane.yaml b/Documentation/devicetree/bindings/npu/apple,ane.yaml index feae5b133ac2f..cade9c9b77ccb 100644 --- a/Documentation/devicetree/bindings/npu/apple,ane.yaml +++ b/Documentation/devicetree/bindings/npu/apple,ane.yaml @@ -15,9 +15,11 @@ description: drives the engine through its register window. On T602x and T8112 a coprocessor runs the ANE firmware and the host talks to it through an ASC mailbox. T8140 has two interrupts and one system power domain; its - coprocessor uses a different firmware interface. T6041 likewise needs a - generation-specific firmware backend; it has one interrupt and its CPU - power state supplies the engine through the ANE system domain. + coprocessor is exclave-assigned and cannot be used directly without a + Linux ownership provider. T6041 has one interrupt and preloaded firmware; + its CPU, MPM and task domains depend on the ANE system domain, and its + base domain depends on the task domain. Interrupt roles on T6041 and + T8140 are not yet established. properties: compatible: @@ -34,20 +36,34 @@ properties: reg: minItems: 1 items: - - description: Engine registers. On T602x and T8112 this is the whole - ANE block, including the coprocessor. + - description: Engine registers, including the coprocessor on firmware + managed generations - description: Power manager (PMGR) registers of the ANE - - description: ANE power state registers in the PMGR - - description: eFuse words that give the SoC revision to the ANE - firmware + - description: Power state registers or first auxiliary window + - description: Revision registers or second auxiliary window + - description: Third auxiliary window + - description: Fourth auxiliary window + - description: Fifth auxiliary window reg-names: minItems: 1 - items: - - const: engine - - const: pmgr - - const: set - - const: fuse + maxItems: 7 + + apple,performance-controller: + $ref: /schemas/types.yaml#/definitions/phandle + description: + PMP report provider that owns the ANE clock-level request interface. + Only supported on T6000. The ANE and report SRAM must remain powered + while the driver holds a request. + + interconnects: + maxItems: 1 + + interconnect-names: + const: memory + description: DRAM/fabric path; bandwidth requests come from the level OPP. + + operating-points-v2: true interrupts: minItems: 1 @@ -58,11 +74,16 @@ properties: - const: ane iommus: - maxItems: 3 + description: + Stream 0 of each of the three DARTs, followed on T6041 by stream 11 of + each, which the ANE's MPM uses. + minItems: 3 + maxItems: 6 power-domains: description: - The power states the engine needs, five on T8103 and T6000, eight on + The power states the engine needs, five on T8103, six on T6000 with + ANE level control (including PMP report SRAM), eight on T602x, seven on T8112 and one system domain on T8140. minItems: 1 maxItems: 8 @@ -76,10 +97,64 @@ properties: description: Mailbox of the ANE coprocessor memory-region: - maxItems: 1 + minItems: 1 + maxItems: 2 description: - IOVA-only reservation of the firmware entry alias in the ANE DART - address space. + On T602x, the IOVA-only reservation of the firmware entry alias. + On T6041 and T8140, bootloader-provided physical TEXT and DATA preload + reservations in that order. Each reservation must have no-map, must + not be reusable, and must remain reserved until reboot. Physical + addresses vary per boot and must not be hard-coded in a board DTS. + + memory-region-names: + items: + - const: firmware-text + - const: firmware-data + + apple,firmware-iovas: + $ref: /schemas/types.yaml#/definitions/uint64-array + items: + - const: 0x10000000000 + - const: 0x100000c0000 + 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. + + apple,dapf-ranges: + $ref: /schemas/types.yaml#/definitions/uint64-matrix + minItems: 4 + maxItems: 4 + items: + items: + - description: Physical start address, inclusive + - description: Physical end address, inclusive + description: + Four 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 + containing 16 KiB pages in its private domain. These are MMIO ranges, + not allocatable DMA memory or additional preload segments. + + apple,ane-type: + $ref: /schemas/types.yaml#/definitions/uint32 + enum: [0x110, 0x200] + description: Firmware generation identifier supplied by the bootloader + + apple,firmware-preloaded: + type: boolean + description: + Firmware has been personalized and preloaded by iBoot. The driver + must preserve its runtime patches and must not stage a disk image. + + apple,exclave-assigned: + type: boolean + description: + The ANE belongs to an exclave. Direct access requires a separate + Linux ownership provider to acquire a quiesced device and isolate + the exclave DART contexts. Absence does not prove a handoff on T8140. required: - compatible @@ -90,6 +165,24 @@ required: - power-domains allOf: + - if: + required: + - interconnects + then: + required: + - interconnect-names + - operating-points-v2 + - if: + required: + - apple,performance-controller + then: + properties: + compatible: + const: apple,t6000-ane + power-domains: + minItems: 6 + maxItems: 6 + - if: properties: compatible: @@ -98,6 +191,56 @@ allOf: properties: interrupts: minItems: 2 + power-domains: + maxItems: 1 + apple,ane-type: + const: 0x200 + - if: + properties: + compatible: + const: apple,t8140-ane + then: + properties: + reg: + maxItems: 6 + reg-names: + minItems: 1 + items: + - const: engine + - const: pmgr + - const: aux-0 + - const: aux-1 + - const: aux-2 + - const: aux-3 + - if: + required: + - apple,firmware-iovas + then: + properties: + memory-region: + minItems: 2 + required: + - memory-region + - memory-region-names + - apple,firmware-preloaded + - if: + properties: + compatible: + enum: + - apple,t6041-ane + - apple,t8140-ane + required: + - memory-region + then: + required: + - memory-region-names + - apple,firmware-iovas + - if: + required: + - memory-region-names + then: + required: + - apple,firmware-iovas - if: properties: compatible: @@ -106,6 +249,32 @@ allOf: properties: interrupts: maxItems: 1 + reg: + minItems: 7 + reg-names: + items: + - const: engine + - const: pmgr + - const: aux-0 + - const: aux-1 + - const: aux-2 + - const: aux-3 + - const: aux-4 + iommus: + minItems: 6 + power-domains: + minItems: 5 + maxItems: 5 + apple,ane-type: + const: 0x110 + required: + - apple,ane-type + - apple,firmware-preloaded + - apple,dapf-ranges + else: + properties: + iommus: + maxItems: 3 - if: properties: compatible: @@ -115,24 +284,34 @@ allOf: - apple,t6041-ane then: properties: - reg: - maxItems: 1 - reg-names: - maxItems: 1 interrupt-names: false iommus: minItems: 3 - power-domains: - maxItems: 1 resets: false mboxes: false - memory-region: false else: properties: interrupts: maxItems: 1 power-domains: minItems: 5 + reg: + maxItems: 4 + reg-names: + minItems: 1 + items: + - const: engine + - const: pmgr + - const: set + - const: fuse + memory-region: + maxItems: 1 + memory-region-names: false + apple,firmware-iovas: false + apple,ane-type: false + apple,firmware-preloaded: false + apple,exclave-assigned: false + apple,dapf-ranges: false required: - interrupt-names @@ -150,7 +329,7 @@ allOf: reg-names: maxItems: 1 power-domains: - maxItems: 5 + maxItems: 6 resets: false mboxes: false memory-region: false @@ -268,3 +447,41 @@ examples: memory-region = <&ane_alias_iova>; }; }; + + - | + #include + #include + + soc { + #address-cells = <2>; + #size-cells = <2>; + + ane@484000000 { + compatible = "apple,t6041-ane"; + reg = <0x4 0x84000000 0x0 0x2000000>, + <0x5 0x02280000 0x0 0x18000>, + <0x5 0x022a0000 0x0 0x4000>, + <0x5 0x003c0000 0x0 0x30000>, + <0x2 0x12000000 0x0 0xff4000>, + <0x5 0x22000000 0x0 0x2000000>, + <0x5 0x08374000 0x0 0x4000>; + reg-names = "engine", "pmgr", "aux-0", "aux-1", "aux-2", + "aux-3", "aux-4"; + interrupt-parent = <&aic>; + interrupts = ; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>, + <&ane_dart0 11>, <&ane_dart1 11>, <&ane_dart2 11>; + power-domains = <&ps_ane_sys>, <&ps_ane_cpu>, <&ps_ane_mpm>, + <&ps_ane_td>, <&ps_ane_base>; + apple,ane-type = <0x110>; + apple,firmware-preloaded; + apple,dapf-ranges = /bits/ 64 <0x5022803c0 0x5022803c3>, + <0x50228c000 0x50228c01b>, + <0x581668000 0x581668003>, + <0x28a668000 0x28a668003>; + memory-region = <&ane_fw_text>, <&ane_fw_data>; + memory-region-names = "firmware-text", "firmware-data"; + apple,firmware-iovas = /bits/ 64 <0x10000000000 0x100000c0000>; + status = "disabled"; + }; + }; diff --git a/arch/arm64/boot/dts/apple/Makefile b/arch/arm64/boot/dts/apple/Makefile index 0f6e6714f7de7..560c4219027b7 100644 --- a/arch/arm64/boot/dts/apple/Makefile +++ b/arch/arm64/boot/dts/apple/Makefile @@ -96,6 +96,7 @@ dtb-$(CONFIG_ARCH_APPLE) += t6034-j514m.dtb dtb-$(CONFIG_ARCH_APPLE) += t6034-j516m.dtb dtb-$(CONFIG_ARCH_APPLE) += t6040-j616s.dtb dtb-$(CONFIG_ARCH_APPLE) += t6040-j616s-tether.dtb +dtb-$(CONFIG_ARCH_APPLE) += t6041-j616c.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j413.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j415.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j473.dtb diff --git a/arch/arm64/boot/dts/apple/t6040-j616s.dts b/arch/arm64/boot/dts/apple/t6040-j616s.dts index 6c28c95f8155d..d1383c7a51344 100644 --- a/arch/arm64/boot/dts/apple/t6040-j616s.dts +++ b/arch/arm64/boot/dts/apple/t6040-j616s.dts @@ -9,11 +9,22 @@ /dts-v1/; -#include "t6040.dtsi" +#include "t604x.dtsi" #include #include #include +/delete-node/ &cpu_p05; +/delete-node/ &cpu_p15; + +&{/cpus/cpu-map/cluster1} { + /delete-node/ core5; +}; + +&{/cpus/cpu-map/cluster2} { + /delete-node/ core5; +}; + / { compatible = "apple,j616s", "apple,t6040", "apple,arm-platform"; model = "Apple MacBook Pro (16-inch, M4 Pro, Nov 2024)"; diff --git a/arch/arm64/boot/dts/apple/t6041-j616c-ane.dtsi b/arch/arm64/boot/dts/apple/t6041-j616c-ane.dtsi new file mode 100644 index 0000000000000..b8e3476c7caba --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-j616c-ane.dtsi @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The Neural Engine (H16) of the J616c. + * + * Same windows, interrupt, DAPF records, firmware IOVAs and PMGR offsets as + * the J616s (t6040.dtsi, t6040-j616s.dts), checked against this board's ADT + * (/arm-io/ane0, dart-ane0, ANE_SYS/MPM/CPU/TD/BASE). None of the ANE domains + * is PMP-notified. + * + * iBoot pre-loads the personalized firmware. Every node stays disabled here: + * the boot loader fills the two firmware reservations from this boot's ane0 + * segment-ranges, renames them to their physical addresses and enables them, + * the ANE, its DARTs and its power domains. The driver uses SID 0 on each + * DART. + */ + +/ { + aliases { + ane = &ane; + }; + + reserved-memory { + ane_fw_text: ane-firmware-text@0 { + compatible = "apple,asc-mem"; + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + ane_fw_data: ane-firmware-data@0 { + compatible = "apple,asc-mem"; + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + }; +}; + +&ane { + reg = <0x4 0x84000000 0x0 0x2000000>, + <0x5 0x02280000 0x0 0x18000>, + <0x5 0x022a0000 0x0 0x4000>, + <0x5 0x003c0000 0x0 0x30000>, + <0x2 0x12000000 0x0 0xff4000>, + <0x5 0x22000000 0x0 0x2000000>, + <0x5 0x08374000 0x0 0x4000>; + reg-names = "engine", "pmgr", "aux-0", "aux-1", "aux-2", "aux-3", "aux-4"; + iommus = <&ane0_dart0 0>, <&ane0_dart1 0>, <&ane0_dart2 0>; + power-domains = <&ps_ane_sys>, <&ps_ane_cpu>, <&ps_ane_mpm>, + <&ps_ane_td>, <&ps_ane_base>; + apple,ane-type = <0x110>; + apple,firmware-preloaded; + /* Inclusive DAPF bounds, in hardware record order. */ + apple,dapf-ranges = /bits/ 64 <0x5022803c0 0x5022803c3 + 0x50228c000 0x50228c01b + 0x581668000 0x581668003 + 0x28a668000 0x28a668003>; + memory-region = <&ane_fw_text>, <&ane_fw_data>; + memory-region-names = "firmware-text", "firmware-data"; + apple,firmware-iovas = /bits/ 64 <0x10000000000 0x100000c0000>; + /* + * The ANE's DART descriptors are cacheable and its accesses cohere with + * the CPU caches, as on M1/M2 (accel/ane map_mode 3 buffer-reuse checks). + */ + dma-coherent; +}; + +/* + * ANE_SYS's parents FAB5_SOC and FAB4_SOC are critical and on from iBoot; the + * T6041 device tree does not describe them, so nothing turns them off. + */ +&ps_ane_sys { + /delete-property/ power-domains; +}; + +/* Include the firmware identity MMIO pages below the preload IOVAs. */ +&ane0_dart0 { + apple,dma-range = <0x0 0x0 0x400 0x0>; +}; + +&ane0_dart1 { + apple,dma-range = <0x0 0x0 0x400 0x0>; +}; + +&ane0_dart2 { + apple,dma-range = <0x0 0x0 0x400 0x0>; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts new file mode 100644 index 0000000000000..8f3d7330d4966 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -0,0 +1,891 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +// Copyright The Asahi Linux Contributors + +/dts-v1/; + +#include "t6041.dtsi" +#include +#include + +/ { + compatible = "apple,j616c", "apple,t6041", "apple,arm-platform"; + model = "Apple MacBook Pro (16-inch, M4 Max, Nov 2024)"; + chassis-type = "laptop"; + + aliases { + serial0 = &serial0; + keyboard = &keyboard; + wifi0 = "/pcie@1cb0000000/pci@0,0/wifi@0,0"; + bluetooth0 = "/pcie@1cb0000000/pci@0,0/bluetooth@0,1"; + mtp = &mtp; + dcp = &dcp; + disp0 = &display; + disp0-piodma = &disp0_piodma; + gpu = &gpu; + }; + + chosen { + #address-cells = <2>; + #size-cells = <2>; + ranges; + + stdout-path = "serial0:115200n8"; + + framebuffer0: framebuffer@0 { + compatible = "apple,simple-framebuffer", "simple-framebuffer"; + reg = <0 0 0 0>; + status = "disabled"; + }; + }; + + reserved-memory { + #address-cells = <2>; + #size-cells = <2>; + ranges; + }; + + memory@0 { + device_type = "memory"; + reg = <0 0 0 0>; + }; + + serial0: serial@429200000 { + compatible = "apple,s5l-uart"; + reg = <0x4 0x29200000 0x0 0x1000>; + reg-io-width = <4>; + interrupt-parent = <&aic>; + interrupts = ; + clocks = <&clkref>, <&clkref>; + clock-names = "uart", "clk_uart_baud0"; + }; + + clk_disp0: clock-disp0 { + compatible = "fixed-clock"; + #clock-cells = <0>; + clock-frequency = <712000000>; + clock-output-names = "disp0"; + }; + + thermal-zones { + cpu-die-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + thermal-sensors = <&smc_hwmon 0>; + + trips { + cpu_die_passive: cpu-die-passive { + temperature = <113000>; + hysteresis = <5000>; + type = "passive"; + }; + + cpu-die-critical { + temperature = <118000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map-e { + trip = <&cpu_die_passive>; + cooling-device = + <&cpu_e0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_e1 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_e2 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_e3 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + + map-p0 { + trip = <&cpu_die_passive>; + cooling-device = + <&cpu_p00 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p01 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p02 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p03 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p04 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p05 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + + map-p1 { + trip = <&cpu_die_passive>; + cooling-device = + <&cpu_p10 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p11 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p12 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p13 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p14 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu_p15 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + }; +}; + +&cpufreq_e { + /delete-property/ apple,fast-die-effort; +}; + +&cpufreq_p0 { + /delete-property/ apple,fast-die-effort; +}; + +&cpufreq_p1 { + /delete-property/ apple,fast-die-effort; +}; + +&wdt { + timeout-sec = <140>; +}; + +&smc { + status = "okay"; + + smc_gpio_low: gpio-low { + compatible = "apple,smc-low-gpio"; + gpio-controller; + #gpio-cells = <2>; + }; +}; + +&smc_mbox { + status = "okay"; +}; + +&nub_spmi0 { + status = "okay"; +}; + +&smc_hwmon { + temperature-TCMz { + apple,key-id = "TCMz"; + label = "CPU Die Max"; + }; + temperature-TCMb { apple,key-id = "TCMb"; label = "CPU TCMb"; }; + temperature-Tpx0 { apple,key-id = "Tpx0"; label = "CPU Tpx0"; }; + temperature-Tpx1 { apple,key-id = "Tpx1"; label = "CPU Tpx1"; }; + temperature-Tpx2 { apple,key-id = "Tpx2"; label = "CPU Tpx2"; }; + temperature-Tpx3 { apple,key-id = "Tpx3"; label = "CPU Tpx3"; }; + temperature-Tpx4 { apple,key-id = "Tpx4"; label = "CPU Tpx4"; }; + temperature-Tpx5 { apple,key-id = "Tpx5"; label = "CPU Tpx5"; }; + temperature-Tpx8 { apple,key-id = "Tpx8"; label = "CPU Tpx8"; }; + temperature-Tpx9 { apple,key-id = "Tpx9"; label = "CPU Tpx9"; }; + temperature-TpxA { apple,key-id = "TpxA"; label = "CPU TpxA"; }; + temperature-TpxB { apple,key-id = "TpxB"; label = "CPU TpxB"; }; + temperature-TpxC { apple,key-id = "TpxC"; label = "CPU TpxC"; }; + temperature-TpxD { apple,key-id = "TpxD"; label = "CPU TpxD"; }; + temperature-Tex0 { apple,key-id = "Tex0"; label = "CPU Tex0"; }; + temperature-Tex1 { apple,key-id = "Tex1"; label = "CPU Tex1"; }; + temperature-Tex2 { apple,key-id = "Tex2"; label = "CPU Tex2"; }; + temperature-Tex3 { apple,key-id = "Tex3"; label = "CPU Tex3"; }; + temperature-TH0x { apple,key-id = "TH0x"; label = "NAND Flash Temperature"; }; + temperature-TB0T { apple,key-id = "TB0T"; label = "Battery Hotspot"; }; + temperature-TCHP { apple,key-id = "TCHP"; label = "Charge Regulator Temp"; }; + temperature-TW0P { apple,key-id = "TW0P"; label = "WiFi/BT Module Temp"; }; + power-PSTR { apple,key-id = "PSTR"; label = "Total System Power"; }; + power-PHPC { apple,key-id = "PHPC"; label = "Heatpipe Power"; }; + power-PDTR { apple,key-id = "PDTR"; label = "AC Input Power"; }; + voltage-VD0R { apple,key-id = "VD0R"; label = "AC Input Voltage"; }; + voltage-SBAV { apple,key-id = "SBAV"; label = "Battery Voltage"; }; + current-ID0R { apple,key-id = "ID0R"; label = "AC Input Current"; }; +}; + +&pinctrl { + status = "okay"; + + wifi_clkreq_pins: wifi-clkreq-pins { + pinmux = ; + }; +}; + +&pinctrl_nub { + status = "okay"; + /delete-property/ interrupt-controller; + /delete-property/ #interrupt-cells; + /delete-property/ interrupts; +}; + +&mtp { + status = "okay"; +}; + +&mtp_mbox { + status = "okay"; +}; + +&mtp_dart { + status = "okay"; +}; + +&mtp_dockchannel { + status = "okay"; +}; + +&mtp_hid { + compatible = "apple,dockchannel-hid"; + apple,afe-reset-gpios = <&smc_gpio_low 25 GPIO_ACTIVE_LOW>; + apple,stm-reset-gpios = <&smc_gpio_low 26 GPIO_ACTIVE_LOW>; + + multi-touch { + firmware-name = "apple/tpmtfw-j616c.bin"; + apple,power-method = <2>; + }; + + keyboard: keyboard { + hid-country-code = <0>; + apple,keyboard-layout-id = <0>; + }; + + stm { + }; + + actuator { + }; + + tp-accel { + }; + + mtp { + }; +}; + +&pcie_dart { + status = "okay"; +}; + +/ { + pcie0: pcie@1cb0000000 { + compatible = "apple,t6041-pcie", "apple,t6020-pcie"; + reg = <0x1c 0xb0000000 0x0 0x1000000>, + <0x4 0x14000000 0x0 0x4000>, + <0x4 0x10028000 0x0 0x4000>, + <0x4 0x11028000 0x0 0x4000>, + <0x4 0x12028000 0x0 0x4000>, + <0x4 0x13028000 0x0 0x4000>, + <0x4 0x17020000 0x0 0x4000>, + <0x4 0x17024000 0x0 0x4000>, + <0x4 0x17028000 0x0 0x4000>, + <0x4 0x1702c000 0x0 0x4000>; + reg-names = "config", "rc", + "port0", "port1", "port2", "port3", + "phy0", "phy1", "phy2", "phy3"; + ranges = <0x43000000 0xb 0xc0000000 0xb 0xc0000000 0 0x20000000 0x2000000 0 0x80000000 0xb 0x80000000 0 0x40000000>; + pinctrl-names = "default"; + pinctrl-0 = <&wifi_clkreq_pins>; + #size-cells = <2>; + #address-cells = <3>; + bus-range = <0 1>; + iommu-map-mask = <0xffff>; + iommu-map = <0x100 &pcie_dart 1 2>; + msi-ranges = <&aic AIC_IRQ 2071 IRQ_TYPE_EDGE_RISING 32>; + msi-parent = <&pcie0>; + msi-controller; + interrupts = <0 0x6bb 4>; + interrupt-parent = <&aic>; + device_type = "pci"; + + port00: pci@0,0 { + compatible = "pciclass,0604"; + reg = <0 0 0 0 0>; + ranges; + 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>; + interrupt-map-mask = <0 0 0 7>; + #interrupt-cells = <1>; + interrupt-controller; + #size-cells = <2>; + #address-cells = <3>; + pwren-gpios = <&smc_gpio 0x13 0>; + reset-gpios = <&pinctrl 4 1>; + device_type = "pci"; + + bluetooth@0,1 { + compatible = "pci14e4,5f72"; + reg = <0x100 0 0 0 0>; + local-bd-address = [00 00 00 00 00 00]; + brcm,board-type = "apple,hostomel"; + status = "okay"; + }; + + wifi@0,0 { + compatible = "brcm,bcm4329-fmac"; + reg = <0 0 0 0 0>; + brcm,ccode-map-trivial; + brcm,board-type = "apple,hostomel"; + }; + }; + }; +}; + +&ans_mbox { + status = "okay"; +}; + +&ans_sart { + status = "okay"; +}; + +&nvme { + status = "okay"; +}; + +&display { + phandle = <&display>; + status = "okay"; +}; + +&dcp { + clocks = <&clk_disp0>; + phandle = <&dcp>; + + panel { + compatible = "apple,panel-j616", "apple,panel-mini-led", "apple,panel"; + width-mm = <346>; + height-mm = <223>; + adj-height-mm = <216>; + apple,max-brightness = <500>; + }; +}; + +&disp0_piodma { + phandle = <&disp0_piodma>; +}; + +&nub_spmi_a0 { + status = "okay"; + + hpm1: usb-pd@a { + compatible = "apple,sn201202x"; + reg = <0xa SPMI_USID>; + interrupts = <37 IRQ_TYPE_EDGE_RISING>, + <39 IRQ_TYPE_EDGE_RISING>, + <43 IRQ_TYPE_EDGE_RISING>, + <45 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "select", "sleep", "wake"; + + 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_con_hs: endpoint { + remote-endpoint = <&usb_drd1_hs>; + }; + }; + }; + }; + }; +}; + +&nub_spmi_a1 { + status = "okay"; + + hpm2: usb-pd@c { + compatible = "apple,sn201202x"; + reg = <0xc SPMI_USID>; + interrupts = <11 IRQ_TYPE_EDGE_RISING>, + <13 IRQ_TYPE_EDGE_RISING>, + <17 IRQ_TYPE_EDGE_RISING>, + <19 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "select", "sleep", "wake"; + + 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_con_hs: endpoint { + remote-endpoint = <&usb_drd2_hs>; + }; + }; + }; + }; + }; +}; + +&atcphy1 { + apple,tunable-usb2-host = <0x8 0x7003 0x3>; + status = "okay"; +}; + +&usb_drd1_dart_0 { + status = "okay"; +}; + +&usb_drd1_dart_1 { + status = "okay"; +}; + +&usb_drd1 { + maximum-speed = "high-speed"; + phys = <&atcphy1 PHY_TYPE_USB2>; + phy-names = "usb2-phy"; + apple,tunable-gbl-host = <0x4 0x0001ef00 0x00002f00>, <0x1c 0x00000100 0x0>, + <0x2c 0x000a07ff 0x000800c8>, <0x100 0x02000100 0x02000100>, + <0x504 0x00001000 0x0>, <0x528 0xff0000ff 0x06000006>, + <0x52c 0xff0000ff 0x08000008>, <0x538 0x00000800 0x00000800>, + <0x580 0xffffffff 0x6f000006>; + apple,tunable-cfg-host = <0x20 0xff 0x1b>; + status = "okay"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + usb_drd1_hs: endpoint { + remote-endpoint = <&typec1_con_hs>; + }; + }; + }; +}; + +&atcphy2 { + apple,tunable-usb2-host = <0x8 0x7003 0x3>; + status = "okay"; +}; + +&usb_drd2_dart_0 { + status = "okay"; +}; + +&usb_drd2_dart_1 { + status = "okay"; +}; + +&usb_drd2 { + maximum-speed = "high-speed"; + phys = <&atcphy2 PHY_TYPE_USB2>; + phy-names = "usb2-phy"; + apple,tunable-gbl-host = <0x4 0x0001ef00 0x00002f00>, <0x1c 0x00000100 0x0>, + <0x2c 0x000a07ff 0x000800c8>, <0x100 0x02000100 0x02000100>, + <0x504 0x00001000 0x0>, <0x528 0xff0000ff 0x06000006>, + <0x52c 0xff0000ff 0x08000008>, <0x538 0x00000800 0x00000800>, + <0x580 0xffffffff 0x6f000006>; + apple,tunable-cfg-host = <0x20 0xff 0x1b>; + status = "okay"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + usb_drd2_hs: endpoint { + remote-endpoint = <&typec2_con_hs>; + }; + }; + }; +}; + +/ { + reserved-memory { + #address-cells = <2>; + #size-cells = <2>; + ranges; + + gpu_uat_ttbs: uat-ttbs { + no-map; + status = "disabled"; + }; + + gpu_uat_pagetables: uat-pagetables { + no-map; + status = "disabled"; + }; + + gpu_uat_l2_pagetables: uat-l2-pagetables { + no-map; + status = "disabled"; + }; + + gpu_uat_handoff: uat-handoff { + no-map; + status = "disabled"; + }; + + gpu_fw_text: gpu-fw-text { + no-map; + status = "disabled"; + }; + + gpu_fw_data: gpu-fw-data { + no-map; + status = "disabled"; + }; + }; + + gpu_opp: opp-table-gpu { + compatible = "operating-points-v2"; + + opp00 { + opp-hz = /bits/ 64 <0>; + opp-microvolt = <125000 125000 125000 125000>; + }; + opp01 { + opp-hz = /bits/ 64 <338000000>; + opp-microvolt = <600000 600000 600000 600000>; + }; + opp02 { + opp-hz = /bits/ 64 <618000000>; + opp-microvolt = <665000 665000 660000 660000>; + }; + opp03 { + opp-hz = /bits/ 64 <796000000>; + opp-microvolt = <705000 705000 700000 705000>; + }; + opp04 { + opp-hz = /bits/ 64 <924000000>; + opp-microvolt = <725000 725000 715000 730000>; + }; + opp05 { + opp-hz = /bits/ 64 <952000000>; + opp-microvolt = <770000 770000 770000 780000>; + }; + opp06 { + opp-hz = /bits/ 64 <1056000000>; + opp-microvolt = <770000 770000 770000 780000>; + }; + opp07 { + opp-hz = /bits/ 64 <1062000000>; + opp-microvolt = <810000 810000 805000 810000>; + }; + opp08 { + opp-hz = /bits/ 64 <1182000000>; + opp-microvolt = <810000 810000 805000 810000>; + }; + opp09 { + opp-hz = /bits/ 64 <1182000000>; + opp-microvolt = <860000 860000 860000 860000>; + }; + opp10 { + opp-hz = /bits/ 64 <1312000000>; + opp-microvolt = <860000 860000 860000 860000>; + }; + opp11 { + opp-hz = /bits/ 64 <1242000000>; + opp-microvolt = <900000 895000 900000 900000>; + }; + opp12 { + opp-hz = /bits/ 64 <1380000000>; + opp-microvolt = <900000 895000 900000 900000>; + }; + opp13 { + opp-hz = /bits/ 64 <1326000000>; + opp-microvolt = <940000 925000 940000 940000>; + }; + opp14 { + opp-hz = /bits/ 64 <1470000000>; + opp-microvolt = <940000 925000 940000 940000>; + }; + opp15 { + opp-hz = /bits/ 64 <1578000000>; + opp-microvolt = <1020000 1020000 1020000 1020000>; + }; + }; + + gpu_cs_opp: opp-table-gpucs { + compatible = "operating-points-v2"; + + opp00 { + opp-hz = /bits/ 64 <24000000>; + opp-microvolt = <585000>; + }; + opp01 { + opp-hz = /bits/ 64 <338000000>; + opp-microvolt = <585000>; + }; + opp02 { + opp-hz = /bits/ 64 <618000000>; + opp-microvolt = <635000>; + }; + opp03 { + opp-hz = /bits/ 64 <796000000>; + opp-microvolt = <685000>; + }; + opp04 { + opp-hz = /bits/ 64 <992000000>; + opp-microvolt = <720000>; + }; + opp05 { + opp-hz = /bits/ 64 <1188000000>; + opp-microvolt = <770000>; + }; + opp06 { + opp-hz = /bits/ 64 <1380000000>; + opp-microvolt = <855000>; + }; + opp07 { + opp-hz = /bits/ 64 <1470000000>; + opp-microvolt = <885000>; + }; + }; + + gpu_afr_opp: opp-table-gpuafr { + compatible = "operating-points-v2"; + + opp00 { + opp-hz = /bits/ 64 <24000000>; + opp-microvolt = <585000>; + }; + opp01 { + opp-hz = /bits/ 64 <338000000>; + opp-microvolt = <585000>; + }; + opp02 { + opp-hz = /bits/ 64 <618000000>; + opp-microvolt = <635000>; + }; + opp03 { + opp-hz = /bits/ 64 <796000000>; + opp-microvolt = <685000>; + }; + opp04 { + opp-hz = /bits/ 64 <992000000>; + opp-microvolt = <720000>; + }; + opp05 { + opp-hz = /bits/ 64 <1188000000>; + opp-microvolt = <770000>; + }; + opp06 { + opp-hz = /bits/ 64 <1380000000>; + opp-microvolt = <855000>; + }; + opp07 { + opp-hz = /bits/ 64 <1470000000>; + opp-microvolt = <885000>; + }; + }; +}; + +&gpu { + memory-region = <&gpu_uat_ttbs>, <&gpu_uat_pagetables>, + <&gpu_uat_handoff>, <&gpu_fw_data>, + <&gpu_uat_l2_pagetables>, <&gpu_fw_text>; + memory-region-names = "ttbs", "pagetables", "handoff", "fw-data", + "l2-pagetables", "fw-text"; + operating-points-v2 = <&gpu_opp>; + apple,cs-opp = <&gpu_cs_opp>; + apple,afr-opp = <&gpu_afr_opp>; + apple,firmware-version = <26 5 2>; +}; + +/ { + aliases { + aop = &aop; + }; + speaker_sdz: regulator-sn012776-sdz { + compatible = "regulator-fixed"; + regulator-name = "sn012776-sdz"; + gpios = <&pinctrl 54 GPIO_ACTIVE_HIGH>; + enable-active-high; + }; + + sound: sound { + compatible = "apple,j616-macaudio", "apple,macaudio"; + model = "MacBook Pro J616"; + #address-cells = <1>; + #size-cells = <0>; + + dai-link@0 { + reg = <0>; + link-name = "Speakers"; + dai-tdm-idle-mode-0 = "zero"; + dai-tdm-idle-mode-1 = "zero"; + dai-tdm-slot-tx-idle-mask-0 = <0xf0f0f0>; + dai-tdm-slot-tx-idle-mask-1 = <0x0f0f0f>; + + 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>; + }; + }; + }; + + sound_jack: sound-jack { + compatible = "apple,j616-macaudio-jack", "apple,macaudio"; + model = "MacBook Pro J616 Jack"; + #address-cells = <1>; + #size-cells = <0>; + + dai-link@0 { + reg = <0>; + link-name = "Headphone Jack"; + + cpu { + sound-dai = <&aop_audio 4>; + }; + + codec { + sound-dai = <&jack_codec>; + }; + }; + }; +}; + +&aop { + status = "okay"; +}; + +&aop_mbox { + status = "okay"; +}; + +&aop_dart { + status = "okay"; +}; + +&admac0 { + status = "okay"; +}; + +&admac1 { + status = "okay"; +}; + +&aop_audio { + apple,chassis-name = "J616"; + apple,machine-kind = "MacBook Pro"; +}; + +&i2c1 { + status = "okay"; + + speaker_left_woof1: codec@38 { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x38>; + SDZ-supply = <&speaker_sdz>; + apple,sdz-group-fail-closed; + #sound-dai-cells = <0>; + sound-name-prefix = "Left Woofer 1"; + interrupts-extended = <&pinctrl 55 IRQ_TYPE_LEVEL_LOW>; + ti,imon-slot-no = <0>; + ti,vmon-slot-no = <2>; + }; + + speaker_left_woof2: codec@39 { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x39>; + SDZ-supply = <&speaker_sdz>; + apple,sdz-group-fail-closed; + #sound-dai-cells = <0>; + sound-name-prefix = "Left Woofer 2"; + interrupts-extended = <&pinctrl 55 IRQ_TYPE_LEVEL_LOW>; + ti,imon-slot-no = <8>; + ti,vmon-slot-no = <10>; + }; + + speaker_left_tweet: codec@3a { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x3a>; + SDZ-supply = <&speaker_sdz>; + apple,sdz-group-fail-closed; + #sound-dai-cells = <0>; + sound-name-prefix = "Left Tweeter"; + interrupts-extended = <&pinctrl 55 IRQ_TYPE_LEVEL_LOW>; + ti,imon-slot-no = <16>; + ti,vmon-slot-no = <18>; + }; +}; + +&i2c3 { + status = "okay"; + + speaker_right_woof1: codec@3b { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x3b>; + SDZ-supply = <&speaker_sdz>; + apple,sdz-group-fail-closed; + #sound-dai-cells = <0>; + sound-name-prefix = "Right Woofer 1"; + interrupts-extended = <&pinctrl 55 IRQ_TYPE_LEVEL_LOW>; + ti,imon-slot-no = <4>; + ti,vmon-slot-no = <6>; + }; + + speaker_right_woof2: codec@3c { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x3c>; + SDZ-supply = <&speaker_sdz>; + apple,sdz-group-fail-closed; + #sound-dai-cells = <0>; + sound-name-prefix = "Right Woofer 2"; + interrupts-extended = <&pinctrl 55 IRQ_TYPE_LEVEL_LOW>; + ti,imon-slot-no = <12>; + ti,vmon-slot-no = <14>; + }; + + speaker_right_tweet: codec@3d { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x3d>; + SDZ-supply = <&speaker_sdz>; + apple,sdz-group-fail-closed; + #sound-dai-cells = <0>; + sound-name-prefix = "Right Tweeter"; + interrupts-extended = <&pinctrl 55 IRQ_TYPE_LEVEL_LOW>; + ti,imon-slot-no = <20>; + ti,vmon-slot-no = <22>; + }; +}; + +&i2c2 { + status = "okay"; + + jack_codec: codec@4b { + compatible = "cirrus,cs42l84"; + reg = <0x4b>; + reset-gpios = <&pinctrl_nub 58 GPIO_ACTIVE_HIGH>; + #sound-dai-cells = <0>; + interrupts-extended = <&pinctrl 106 IRQ_TYPE_LEVEL_LOW>; + sound-name-prefix = "Jack"; + }; +}; + +&aop { nonposted-mmio; }; + +&aop_als { status = "disabled"; }; +&aop_las { status = "disabled"; }; + +&admac1 { dma-channels = <26>; nonposted-mmio; }; +&admac0 { nonposted-mmio; }; +&aop_dart { nonposted-mmio; }; +&i2c1 { nonposted-mmio; }; +&i2c2 { nonposted-mmio; }; +&i2c3 { nonposted-mmio; }; + +/ { + reserved-memory { + aop_mmio_pmgr: aop-mmio-pmgr@508304000 { + reg = <0x5 0x08304000 0x0 0x4000>; + iommu-addresses = <&aop 0x5 0x08304000 0x0 0x4000>; + no-map; + }; + }; +}; + +&aop { + dma-noncoherent; + memory-region = <&aop_mmio_pmgr>; +}; + +#include "t6041-j616c-ane.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi new file mode 100644 index 0000000000000..63ad5121d02a3 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -0,0 +1,518 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +// Copyright The Asahi Linux Contributors + +#include "t604x.dtsi" + + +/* Keep the validated T6041 topology independent of unqualified T6040 blocks. */ +/delete-node/ &clk_200m; +/delete-node/ &sio; +/delete-node/ &ave0_dart1; +/delete-node/ &ave0_dart0; +/delete-node/ &apr0_dart; +/delete-node/ &usb4_0_dart; +/delete-node/ &apciec0_dart; +/delete-node/ &usb4_1_dart; +/delete-node/ &apciec1_dart; +/delete-node/ &usb4_2_dart; +/delete-node/ &apciec2_dart; +/delete-node/ &dispext0_dart; +/delete-node/ &dcpext0_dart; +/delete-node/ &sep_dart; +/delete-node/ &apcie1_dart; +/delete-node/ &sio_dart; +/delete-node/ &jpeg0_dart; +/delete-node/ &jpeg1_dart; +/delete-node/ &scaler0_dart; +/delete-node/ &dispext1_dart; +/delete-node/ &dcpext1_dart; +/delete-node/ &usb4_0_mbox; +/delete-node/ &usb4_1_mbox; +/delete-node/ &usb4_2_mbox; +/delete-node/ &sep_mbox; +/delete-node/ &sio_mbox; +/delete-node/ &pinctrl_smc; +/delete-node/ &pinctrl_aop; +/delete-node/ &ps_gpx; +/delete-node/ &ps_apcie_gp; +/delete-node/ &ps_fab4_soc; +/delete-node/ &ps_sio_cpu; +/delete-node/ &ps_fpwm1; +/delete-node/ &ps_fpwm2; +/delete-node/ &ps_i2c0; +/delete-node/ &ps_i2c5; +/delete-node/ &ps_i2c7; +/delete-node/ &ps_spi_p; +/delete-node/ &ps_uart_p; +/delete-node/ &ps_dpa_p; +/delete-node/ &ps_aes; +/delete-node/ &ps_spi0; +/delete-node/ &ps_spi1; +/delete-node/ &ps_spi2; +/delete-node/ &ps_spi3; +/delete-node/ &ps_spi4; +/delete-node/ &ps_spi5; +/delete-node/ &ps_qspi; +/delete-node/ &ps_uart_n; +/delete-node/ &ps_uart0; +/delete-node/ &ps_uart1; +/delete-node/ &ps_uart2; +/delete-node/ &ps_uart3; +/delete-node/ &ps_uart4; +/delete-node/ &ps_uart5; +/delete-node/ &ps_uart6; +/delete-node/ &ps_dpa0; +/delete-node/ &ps_dpa1; +/delete-node/ &ps_dpa2; +/delete-node/ &ps_dpa3; +/delete-node/ &ps_dpa4; +/delete-node/ &ps_disp_sys; +/delete-node/ &ps_amcc4; +/delete-node/ &ps_amcc5; +/delete-node/ &ps_amcc6; +/delete-node/ &ps_amcc7; +/delete-node/ &ps_amcc12; +/delete-node/ &ps_amcc13; +/delete-node/ &ps_amcc14; +/delete-node/ &ps_amcc15; +/delete-node/ &ps_dcs_04; +/delete-node/ &ps_dcs_05; +/delete-node/ &ps_dcs_06; +/delete-node/ &ps_dcs_07; +/delete-node/ &ps_dcs_12; +/delete-node/ &ps_dcs_13; +/delete-node/ &ps_dcs_14; +/delete-node/ &ps_dcs_15; +/delete-node/ &ps_disp_fe; +/delete-node/ &ps_apcie_sys_gp; +/delete-node/ &ps_apcie_phy_sw; +/delete-node/ &ps_jpg; +/delete-node/ &ps_sep; +/delete-node/ &pmgr_disp; +/delete-node/ &ps_ecpu_0; +/delete-node/ &ps_ecpu_2; +/delete-node/ &ps_dwi; +/delete-node/ &ps_aic; +/delete-node/ &ps_pmc; +/delete-node/ &ps_pms_c1ppt; +/delete-node/ &ps_soc_dpe; +/delete-node/ &ps_pmgr_soc_ocla; +/delete-node/ &ps_pms_fpwm0; +/delete-node/ &ps_pms_fpwm1; +/delete-node/ &ps_pms_fpwm2; +/delete-node/ &ps_pms_fpwm3; +/delete-node/ &ps_pms_fpwm4; +/delete-node/ &ps_fab0_soc; +/delete-node/ &ps_ecpu_3; +/delete-node/ &ps_amcc0; +/delete-node/ &ps_dcs_00; +/delete-node/ &ps_rom; +/delete-node/ &ps_amcc1; +/delete-node/ &ps_dcs_01; +/delete-node/ &ps_amcc2; +/delete-node/ &ps_dcs_02; +/delete-node/ &ps_amcc3; +/delete-node/ &ps_dcs_03; +/delete-node/ &ps_amcc8; +/delete-node/ &ps_dcs_08; +/delete-node/ &ps_amcc9; +/delete-node/ &ps_dcs_09; +/delete-node/ &ps_amcc10; +/delete-node/ &ps_dcs_10; +/delete-node/ &ps_amcc11; +/delete-node/ &ps_pcpu0_0; +/delete-node/ &ps_dcs_11; +/delete-node/ &ps_venc0_sys; +/delete-node/ &ps_pcpu0_1; +/delete-node/ &ps_fab_gw_0; +/delete-node/ &ps_fab_gw_1; +/delete-node/ &ps_fab_afr; +/delete-node/ &ps_fab1_soc; +/delete-node/ &ps_pcpu0_2; +/delete-node/ &ps_scodec; +/delete-node/ &ps_scodec_streaming; +/delete-node/ &ps_fab2_soc; +/delete-node/ &ps_dispext0_sys; +/delete-node/ &ps_dispext0_fe; +/delete-node/ &ps_dispext0_cpu; +/delete-node/ &ps_pcpu0_3; +/delete-node/ &ps_atc0_cio; +/delete-node/ &ps_atc0_pcie; +/delete-node/ &ps_atc0_cio_pcie; +/delete-node/ &ps_atc0_cio_usb; +/delete-node/ &ps_atc1_cio; +/delete-node/ &ps_atc1_pcie; +/delete-node/ &ps_atc1_cio_pcie; +/delete-node/ &ps_atc1_cio_usb; +/delete-node/ &ps_atc2_cio; +/delete-node/ &ps_atc2_pcie; +/delete-node/ &ps_atc2_cio_pcie; +/delete-node/ &ps_pcpu0_4; +/delete-node/ &ps_atc2_cio_usb; +/delete-node/ &ps_atc3_common; +/delete-node/ &ps_atc3_cio; +/delete-node/ &ps_atc3_pcie; +/delete-node/ &ps_atc3_cio_pcie; +/delete-node/ &ps_atc3_cio_usb; +/delete-node/ &ps_fab5_soc; +/delete-node/ &ps_sbr; +/delete-node/ &ps_gpio; +/delete-node/ &ps_msg; +/delete-node/ &ps_ap_tmm; +/delete-node/ &ps_msr0; +/delete-node/ &ps_msr0_ase_core; +/delete-node/ &ps_pcpu0_5; +/delete-node/ &ps_fab7_soc; +/delete-node/ &ps_dispext1_sys; +/delete-node/ &ps_dispext1_fe; +/delete-node/ &ps_dispext1_cpu; +/delete-node/ &ps_pcpu1_0; +/delete-node/ &ps_pcpu1_1; +/delete-node/ &ps_pcpu1_2; +/delete-node/ &ps_pcpu1_3; +/delete-node/ &ps_pcpu1_4; +/delete-node/ &ps_pcpu1_5; +/delete-node/ &ps_ecpu_1; +/delete-node/ &ps_ecpm; +/delete-node/ &ps_pcpm0; +/delete-node/ &ps_pcpm1; +/delete-node/ &pmgr_venc; +/delete-node/ &ps_debug_gated; +/delete-node/ &ps_nub_fabric; +/delete-node/ &ps_nub_sram; +/delete-node/ &ps_debug_switch; +/delete-node/ &ps_atc3_usb; +/delete-node/ &ps_atc3_phymxwrap; +/delete-node/ &ps_nub_spmi_ahb; +/delete-node/ &ps_nub_spmi0; +/delete-node/ &ps_nub_spmi_a2; +/delete-node/ &ps_nub_spi0; +/delete-node/ &ps_nub_aon; +/delete-node/ &ps_nub_ocla; +/delete-node/ &ps_atc3_common_dp; +/delete-node/ &ps_nub_spmi1; +/delete-node/ &ps_atc3_usb_aon; +/delete-node/ &ps_nub_spmi2; +/delete-node/ &ps_nub_spmi3; +/delete-node/ &ps_nub_spmi4; +/delete-node/ &sep; +/delete-node/ &dcuart; +/delete-node/ &spi2; +/delete-node/ &spi4; +/delete-node/ &qspi; +/delete-node/ &nub_spmi1; +/delete-node/ &nub_spmi2; +/delete-node/ &nub_spmi3; +/delete-node/ &nub_spmi4; +/delete-node/ &aop_spmi0; +/delete-node/ &ave; + +&ps_avd_sys { + /delete-property/ power-domains; +}; + +&ps_atc0_common { + /delete-property/ power-domains; +}; + +&ps_atc1_common { + /delete-property/ power-domains; +}; + +&ps_atc2_common { + /delete-property/ power-domains; +}; + +&ps_pmp { + /delete-property/ power-domains; +}; + +&ps_pms_sram { + /delete-property/ power-domains; +}; + +&serial0 { + /delete-property/ power-domains; + /delete-property/ status; +}; + +/delete-node/ &gpu; +/delete-node/ &gfx_mbox; +/delete-node/ &opp_p0; +/delete-node/ &opp_p1; + +/ { + opp_p0: opp-table-p0 { + compatible = "operating-points-v2"; + opp-shared; + + opp01 { + opp-hz = /bits/ 64 <1260000000>; + opp-level = <1>; + clock-latency-ns = <7200>; + }; + opp02 { + opp-hz = /bits/ 64 <1512000000>; + opp-level = <2>; + clock-latency-ns = <19000>; + }; + opp03 { + opp-hz = /bits/ 64 <1800000000>; + opp-level = <3>; + clock-latency-ns = <20000>; + }; + opp04 { + opp-hz = /bits/ 64 <2088000000>; + opp-level = <4>; + clock-latency-ns = <22000>; + }; + opp05 { + opp-hz = /bits/ 64 <2352000000>; + opp-level = <5>; + clock-latency-ns = <30000>; + }; + opp06 { + opp-hz = /bits/ 64 <2616000000>; + opp-level = <6>; + clock-latency-ns = <34000>; + }; + opp07 { + opp-hz = /bits/ 64 <2868000000>; + opp-level = <7>; + clock-latency-ns = <37000>; + }; + opp08 { + opp-hz = /bits/ 64 <3096000000>; + opp-level = <8>; + clock-latency-ns = <38000>; + }; + opp09 { + opp-hz = /bits/ 64 <3300000000>; + opp-level = <9>; + clock-latency-ns = <40000>; + }; + opp10 { + opp-hz = /bits/ 64 <3468000000>; + opp-level = <10>; + clock-latency-ns = <41000>; + }; + opp11 { + opp-hz = /bits/ 64 <3624000000>; + opp-level = <11>; + clock-latency-ns = <43000>; + }; + opp12 { + opp-hz = /bits/ 64 <3756000000>; + opp-level = <12>; + clock-latency-ns = <44000>; + }; + opp13 { + opp-hz = /bits/ 64 <3828000000>; + opp-level = <13>; + clock-latency-ns = <45000>; + }; + opp14 { + opp-hz = /bits/ 64 <3888000000>; + opp-level = <14>; + clock-latency-ns = <46000>; + }; + opp15 { + opp-hz = /bits/ 64 <3948000000>; + opp-level = <15>; + clock-latency-ns = <47000>; + }; + opp16 { + opp-hz = /bits/ 64 <3996000000>; + opp-level = <16>; + clock-latency-ns = <48000>; + }; + opp17 { + opp-hz = /bits/ 64 <4044000000>; + opp-level = <17>; + clock-latency-ns = <49000>; + }; + opp18 { + opp-hz = /bits/ 64 <4104000000>; + opp-level = <18>; + clock-latency-ns = <50000>; + }; + opp19 { + opp-hz = /bits/ 64 <4416000000>; + opp-level = <19>; + clock-latency-ns = <55000>; + turbo-mode; + }; + opp20 { + opp-hz = /bits/ 64 <4512000000>; + opp-level = <20>; + clock-latency-ns = <56000>; + turbo-mode; + }; + }; + + opp_p1: opp-table-p1 { + compatible = "operating-points-v2"; + opp-shared; + + opp01 { + opp-hz = /bits/ 64 <1260000000>; + opp-level = <1>; + clock-latency-ns = <7200>; + }; + opp02 { + opp-hz = /bits/ 64 <1512000000>; + opp-level = <2>; + clock-latency-ns = <19000>; + }; + opp03 { + opp-hz = /bits/ 64 <1800000000>; + opp-level = <3>; + clock-latency-ns = <20000>; + }; + opp04 { + opp-hz = /bits/ 64 <2088000000>; + opp-level = <4>; + clock-latency-ns = <22000>; + }; + opp05 { + opp-hz = /bits/ 64 <2352000000>; + opp-level = <5>; + clock-latency-ns = <30000>; + }; + opp06 { + opp-hz = /bits/ 64 <2616000000>; + opp-level = <6>; + clock-latency-ns = <34000>; + }; + opp07 { + opp-hz = /bits/ 64 <2868000000>; + opp-level = <7>; + clock-latency-ns = <37000>; + }; + opp08 { + opp-hz = /bits/ 64 <3096000000>; + opp-level = <8>; + clock-latency-ns = <38000>; + }; + opp09 { + opp-hz = /bits/ 64 <3300000000>; + opp-level = <9>; + clock-latency-ns = <40000>; + }; + opp10 { + opp-hz = /bits/ 64 <3468000000>; + opp-level = <10>; + clock-latency-ns = <41000>; + }; + opp11 { + opp-hz = /bits/ 64 <3624000000>; + opp-level = <11>; + clock-latency-ns = <43000>; + }; + opp12 { + opp-hz = /bits/ 64 <3756000000>; + opp-level = <12>; + clock-latency-ns = <44000>; + }; + opp13 { + opp-hz = /bits/ 64 <3828000000>; + opp-level = <13>; + clock-latency-ns = <45000>; + }; + opp14 { + opp-hz = /bits/ 64 <3888000000>; + opp-level = <14>; + clock-latency-ns = <46000>; + }; + opp15 { + opp-hz = /bits/ 64 <3948000000>; + opp-level = <15>; + clock-latency-ns = <47000>; + }; + opp16 { + opp-hz = /bits/ 64 <3996000000>; + opp-level = <16>; + clock-latency-ns = <48000>; + }; + opp17 { + opp-hz = /bits/ 64 <4044000000>; + opp-level = <17>; + clock-latency-ns = <49000>; + }; + opp18 { + opp-hz = /bits/ 64 <4104000000>; + opp-level = <18>; + clock-latency-ns = <50000>; + }; + opp19 { + opp-hz = /bits/ 64 <4416000000>; + opp-level = <19>; + clock-latency-ns = <55000>; + turbo-mode; + }; + opp20 { + opp-hz = /bits/ 64 <4512000000>; + opp-level = <20>; + clock-latency-ns = <56000>; + turbo-mode; + }; + }; + +}; + +&cpu_p00 { + enable-method = "spin-table"; + cpu-release-addr = <0 0>; +}; + +&aic { + reg = <0x5 0x02400000 0x0 0x1cc000>, + <0x5 0x02440000 0x0 0x4>; +}; + +&smc { + reg = <0x5 0x0c600000 0x0 0x4000>, + <0x5 0x0de00000 0x0 0x170000>; +}; + +&pmc { + /delete-property/ apple,pmp; + apple,static-voters = <1 3>; +}; + +/ { + gpu: gpu@288000000 { + compatible = "apple,agx-t6041"; + reg = <0x2 0x8a600000 0x0 0x88000>, + <0x2 0x88000000 0x0 0x3758000>; + reg-names = "asc", "sgx"; + mboxes = <&gfx_mbox>; + power-domains = <&ps_gfx>; + status = "disabled"; + }; + + gfx_mbox: mailbox@28a600000 { + compatible = "apple,t6041-ascwrap-v6", "apple,t6040-ascwrap-v6"; + reg = <0x2 0x8a600000 0x0 0x88000>, + <0x2 0x8a050000 0x0 0x8>; + reg-names = "wrapper", "iop-vbar"; + interrupt-parent = <&aic>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + apple,firmware-role = "GFX"; + power-domains = <&ps_gfx>; + #mbox-cells = <0>; + status = "disabled"; + }; +}; + +&ps_afr { + apple,always-on; + apple,no-auto-pm; +}; + +&ps_gfx { + apple,always-on; + apple,no-auto-pm; +}; diff --git a/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi b/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi similarity index 100% rename from arch/arm64/boot/dts/apple/t6040-pmgr.dtsi rename to arch/arm64/boot/dts/apple/t604x-pmgr.dtsi diff --git a/arch/arm64/boot/dts/apple/t6040.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi similarity index 98% rename from arch/arm64/boot/dts/apple/t6040.dtsi rename to arch/arm64/boot/dts/apple/t604x.dtsi index 961af1b7b5bd4..f81aba8d8c012 100644 --- a/arch/arm64/boot/dts/apple/t6040.dtsi +++ b/arch/arm64/boot/dts/apple/t604x.dtsi @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * Apple T6040 "M4 Pro" SoC + * Apple T604x SoC base * * Unit addresses are the Apple Device Tree's /arm-io addresses plus the * 0x2_00000000 arm-io base. The nodes sit at the root, not under a @@ -68,6 +68,9 @@ core4 { cpu = <&cpu_p04>; }; + core5 { + cpu = <&cpu_p05>; + }; }; cluster2 { @@ -86,9 +89,13 @@ core4 { cpu = <&cpu_p14>; }; + core5 { + cpu = <&cpu_p15>; + }; }; }; + /* m1n1 requires CPU nodes in MPIDR order. */ cpu_e0: cpu@0 { compatible = "apple,brava-e"; device_type = "cpu"; @@ -205,6 +212,19 @@ #cooling-cells = <2>; }; + cpu_p05: cpu@10105 { + compatible = "apple,brava-p"; + device_type = "cpu"; + reg = <0x0 0x10105>; + enable-method = "spin-table"; + cpu-release-addr = <0 0>; + next-level-cache = <&l2_cache_p0>; + operating-points-v2 = <&opp_p0>; + capacity-dmips-mhz = <1024>; + performance-domains = <&cpufreq_p0>; + #cooling-cells = <2>; + }; + cpu_p10: cpu@10200 { compatible = "apple,brava-p"; device_type = "cpu"; @@ -269,6 +289,19 @@ performance-domains = <&cpufreq_p1>; #cooling-cells = <2>; }; + + cpu_p15: cpu@10205 { + compatible = "apple,brava-p"; + device_type = "cpu"; + reg = <0x0 0x10205>; + enable-method = "spin-table"; + cpu-release-addr = <0 0>; + next-level-cache = <&l2_cache_p1>; + operating-points-v2 = <&opp_p1>; + capacity-dmips-mhz = <1024>; + performance-domains = <&cpufreq_p1>; + #cooling-cells = <2>; + }; }; l2_cache_e: l2-cache-cluster0 { @@ -2268,4 +2301,4 @@ }; -#include "t6040-pmgr.dtsi" +#include "t604x-pmgr.dtsi" diff --git a/drivers/accel/Makefile b/drivers/accel/Makefile index 235ebf723025c..2aa8f41d91dfc 100644 --- a/drivers/accel/Makefile +++ b/drivers/accel/Makefile @@ -2,6 +2,8 @@ obj-$(CONFIG_DRM_ACCEL_AMDXDNA) += amdxdna/ obj-$(CONFIG_DRM_ACCEL_ANE) += ane/ +obj-$(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) += ane/ +obj-$(CONFIG_DRM_ACCEL_ANE_PM_KUNIT_TEST) += ane/ obj-$(CONFIG_DRM_ACCEL_ARM_ETHOSU) += ethosu/ obj-$(CONFIG_DRM_ACCEL_HABANALABS) += habanalabs/ obj-$(CONFIG_DRM_ACCEL_IVPU) += ivpu/ diff --git a/drivers/accel/ane/Kconfig b/drivers/accel/ane/Kconfig index a14e621707a54..41c2643e0c815 100644 --- a/drivers/accel/ane/Kconfig +++ b/drivers/accel/ane/Kconfig @@ -7,11 +7,17 @@ config DRM_ACCEL_ANE depends on APPLE_RTKIT depends on APPLE_DART || COMPILE_TEST depends on MMU + select INTERCONNECT + select PM_OPP select CRYPTO_LIB_SHA256 + select DRM_ACCEL_ANE_H16_VALIDATION help Choose this option if you have an Apple SoC with a Neural Engine: M1 (T8103), M1 Pro, Max and Ultra (T6000, T6001, T6002), M2 (T8112), or M2 Pro, Max and Ultra (T6020, T6021, T6022). + H16 (M4 Pro) and H17 are recognized for firmware preflight and + ownership refusal by default. An explicit h16_stage module parameter + enables H16 cold-boot diagnostics. Inference is not available. The interface exposed to userspace is described in include/uapi/drm/ane_accel.h. @@ -33,3 +39,32 @@ config DRM_ACCEL_ANE_KUNIT_TEST past them and with a size product that overflows. If unsure, say N. + +config DRM_ACCEL_ANE_H16_VALIDATION + tristate + select CRYPTO_LIB_SHA256 + +config DRM_ACCEL_ANE_FW_KUNIT_TEST + tristate "KUnit tests for ANE firmware validation" if !KUNIT_ALL_TESTS + depends on DRM_ACCEL && KUNIT + select DRM_ACCEL_ANE_H16_VALIDATION + default KUNIT_ALL_TESTS + help + Check preload identity/ranges, channel validation, RTKit ordering, + H16 HWX/resource bounds, UUID retirement, shared transport and bounded + allocation and staged H16 cold boot without hardware. + These tests can run on architectures other than Apple arm64. + + If unsure, say N. + +config DRM_ACCEL_ANE_PM_KUNIT_TEST + tristate "KUnit tests for ANE runtime-PM recovery" if !KUNIT_ALL_TESTS + depends on DRM_ACCEL && KUNIT && PM + default KUNIT_ALL_TESTS + help + Exercise supplier suspension, power-off verification failure and + runtime resume errors against the runtime-PM and device-link core. + No ANE hardware is required. These tests can run independently of + the ANE driver on non-Apple platforms. + + If unsure, say N. diff --git a/drivers/accel/ane/Makefile b/drivers/accel/ane/Makefile index 8103e33a112a4..6cc9a422eae1f 100644 --- a/drivers/accel/ane/Makefile +++ b/drivers/accel/ane/Makefile @@ -1,15 +1,24 @@ # SPDX-License-Identifier: GPL-2.0-only obj-$(CONFIG_DRM_ACCEL_ANE) += ane.o ane_t6021.o +obj-$(CONFIG_DRM_ACCEL_ANE_PM_KUNIT_TEST) += ane_pm_test.o +obj-$(CONFIG_DRM_ACCEL_ANE_H16_VALIDATION) += ane_h16_hwx.o ane_h16_preload.o ane_h16_load.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_fw_irq_wait_test.o ane_fw_report_fifo_test.o ane_h16_boot_test.o \ + ane_h16_pending_test.o ane_h16_hwx_test.o ane_h16_preload_test.o ane-y := \ ane_drv.o \ ane_tm.o \ ane_dart.o \ + ane_perf.o \ ane_boost.o ane_t6021-y := \ + ane_fw_platform.o \ + ane_h16_backend.o \ ane_t6021_rtclient_main.o \ ane_t6021_fwload.o \ ane_t6021_boot.o diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index f974f8a31194e..913fa0a7a8d94 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -64,6 +64,8 @@ struct ane_device { * and protects bo_list, preserved_list and removed. */ struct mutex engine_lock; + /* Serializes runtime-PM references across a recovery cycle. */ + struct mutex pm_lock; struct list_head bo_list; /* @@ -110,11 +112,32 @@ struct ane_device { */ bool tm_retention; + /* Protected independently of engine_lock so idle work can release votes. */ + struct ane_perf { + struct mutex lock; /* protects votes, idle work and status */ + struct delayed_work idle; + struct device_node *report; + struct icc_path *memory; + unsigned int high_level; + unsigned int level; + u32 avg_bw; + u32 peak_bw; + int error; + unsigned int release_retries; + bool initialized; + bool busy; + bool voted; + bool clock_held; + bool pinned; + bool cpu_boost; + } perf; + /* * Engine-busy CPU cluster boost (ane_boost.c): min-frequency QoS on * every cpufreq policy while a submit runs and until boost_idle_ms - * after the last one completes: on T8103 bandwidth-bound programs - * run ~2x slower while schedutil parks the idle clusters low. + * after the last one completes. Used only when the DT binds no + * performance controller, so the engine keeps the boost it had + * until it gets a clock level instead. */ struct ane_boost { struct mutex lock; /* protects the fields below */ @@ -159,6 +182,12 @@ int ane_submit_check_sizes(const struct drm_ane_submit *args, size_t cmd_size, */ void ane_reclaim_preserved(struct ane_device *ane); +int ane_perf_init(struct ane_device *ane, unsigned int high_level); +int ane_perf_exit(struct ane_device *ane); +int ane_perf_begin(struct ane_device *ane); +void ane_perf_end(struct ane_device *ane); +int ane_perf_suspend(struct ane_device *ane); + int ane_boost_init(struct ane_device *ane); void ane_boost_exit(struct ane_device *ane); void ane_boost_begin(struct ane_device *ane); diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 1b61d3f981bd9..120d900973cd2 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -690,17 +690,24 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) goto unlock; } + err = ane_perf_begin(ane); + if (err) { + dev_err_ratelimited(ane->dev, "performance request failed: %d\n", err); + ane_perf_end(ane); + goto unlock; + } err = ane_tm_enqueue(ane, &req); - if (err < 0) + if (err < 0) { + ane_perf_end(ane); goto unlock; + } if (ane->stats_slots) stats_idx = ane_stats_begin(&ane->stats_ctrs, &ane->stats_ring, ktime_get_ns(), req.td_count); - ane_boost_begin(ane); err = ane_tm_execute(ane, &req); - ane_boost_end(ane); + ane_perf_end(ane); if (ane->stats_slots) ane_stats_complete(&ane->stats_ctrs, &ane->stats_ring, @@ -746,18 +753,19 @@ static ssize_t reset_store(struct device *dev, struct device_attribute *attr, /* Recovery power-cycles the partitions and then writes the engine: * hold a reference so that autosuspend cannot gate it in between. */ + mutex_lock(&ane->pm_lock); err = pm_runtime_resume_and_get(dev); if (err < 0) - return err; + goto out_pm; mutex_lock(&ane->engine_lock); if (!ane->removed) err = ane_tm_recover(ane); mutex_unlock(&ane->engine_lock); pm_runtime_put_autosuspend(dev); - if (err) - return err; - return count; +out_pm: + mutex_unlock(&ane->pm_lock); + return err < 0 ? err : count; } static DEVICE_ATTR_WO(reset); @@ -811,12 +819,13 @@ static int ane_drm_open(struct drm_device *drm, struct drm_file *file) /* Bring up power while the file context is created. A failed * resume propagates; nothing is released that was not acquired. */ + mutex_lock(&ane->pm_lock); err = pm_runtime_resume_and_get(ane->dev); - if (err < 0) - return err; + if (err >= 0) + pm_runtime_put_autosuspend(ane->dev); - pm_runtime_put_autosuspend(ane->dev); - return 0; + mutex_unlock(&ane->pm_lock); + return err < 0 ? err : 0; } /* Retry recovery on close, retaining quarantine if DMA cannot be quiesced. */ @@ -872,14 +881,17 @@ static long ane_drm_ioctl(struct file *file, unsigned int cmd, _IOC_NR(cmd) >= DRM_COMMAND_END) return -ENOTTY; + mutex_lock(&ane->pm_lock); err = pm_runtime_resume_and_get(ane->dev); if (err < 0) - return err; + goto unlock_pm; err = dispatch(file, cmd, arg); pm_runtime_put_autosuspend(ane->dev); +unlock_pm: + mutex_unlock(&ane->pm_lock); return err; } @@ -911,11 +923,19 @@ static int ane_drm_release(struct inode *inode, struct file *file) { struct drm_file *priv = file->private_data; struct device *dev = get_device(priv->minor->dev->dev); + struct ane_device *ane = priv->minor->dev->dev_private; int err; + /* drm_release may drop the last drm reference; keep ane alive until + * pm_lock is unlocked. + */ + drm_dev_get(&ane->drm); + mutex_lock(&ane->pm_lock); pm_runtime_get_sync(dev); err = drm_release(inode, file); pm_runtime_put_autosuspend(dev); + mutex_unlock(&ane->pm_lock); + drm_dev_put(&ane->drm); put_device(dev); return err; } @@ -1113,6 +1133,7 @@ struct ane_soc { * retention and recovery must drain it (see ane_tm_drain_retained). */ bool tm_retention; + unsigned int high_level; }; static const struct ane_soc ane_soc_t8103 = { @@ -1128,6 +1149,7 @@ static const struct ane_soc ane_soc_t6000 = { */ .ps_base = 0x28e08c000ULL, .tm_retention = true, + .high_level = 5, }; static const struct of_device_id ane_of_match[] = { @@ -1217,9 +1239,10 @@ static int ane_platform_probe(struct platform_device *pdev) mutex_init(&ane->iommu_lock); mutex_init(&ane->engine_lock); + mutex_init(&ane->pm_lock); INIT_LIST_HEAD(&ane->bo_list); INIT_LIST_HEAD(&ane->preserved_list); - err = ane_boost_init(ane); + err = ane_perf_init(ane, soc->high_level); if (err < 0) goto detach_genpd; @@ -1279,7 +1302,7 @@ static int ane_platform_probe(struct platform_device *pdev) pm_runtime_dont_use_autosuspend(dev); drm_mm_takedown(&ane->mm); detach_genpd: - ane_boost_exit(ane); + ane_perf_exit(ane); ane_detach_genpd(ane); return err; } @@ -1288,10 +1311,12 @@ static void ane_platform_remove(struct platform_device *pdev) { struct ane_device *ane = platform_get_drvdata(pdev); struct ane_bo *bo, *tmp; + int err; /* Powered and pinned for the teardown: the unmaps below flush the * DART TLBs, and no autosuspend may race the genpd detach. */ + mutex_lock(&ane->pm_lock); pm_runtime_get_sync(ane->dev); mutex_lock(&ane->engine_lock); @@ -1302,6 +1327,15 @@ static void ane_platform_remove(struct platform_device *pdev) dev_err(ane->dev, "forced removal of a wedged device is unsafe; reboot required\n"); mutex_unlock(&ane->engine_lock); + mutex_unlock(&ane->pm_lock); + return; + } + + err = ane_perf_exit(ane); + if (err) { + dev_err(ane->dev, + "retaining power-domain attachments after failed performance release; reboot required\n"); + mutex_unlock(&ane->engine_lock); return; } @@ -1310,13 +1344,13 @@ static void ane_platform_remove(struct platform_device *pdev) ane_reclaim_preserved(ane); drm_mm_takedown(&ane->mm); - ane_boost_exit(ane); ane_detach_genpd(ane); pm_runtime_disable(ane->dev); pm_runtime_dont_use_autosuspend(ane->dev); pm_runtime_put_noidle(ane->dev); mutex_unlock(&ane->engine_lock); + mutex_unlock(&ane->pm_lock); } static int __maybe_unused ane_runtime_suspend(struct device *dev) @@ -1331,7 +1365,7 @@ static int __maybe_unused ane_runtime_suspend(struct device *dev) if (atomic_read(&ane->wedged) && !ane->recovering) return -EBUSY; - return 0; + return ane_perf_suspend(ane); } static int __maybe_unused ane_runtime_resume(struct device *dev) @@ -1365,6 +1399,10 @@ static int __maybe_unused ane_runtime_resume(struct device *dev) eng); } + /* Recovery verifies the power-on ACK before its first engine access. */ + if (ane->recovering) + return 0; + ane_tm_enable(ane, first); /* First enable is the engine's fresh signature; recovery compares diff --git a/drivers/accel/ane/ane_fw_ack_pending.h b/drivers/accel/ane/ane_fw_ack_pending.h new file mode 100644 index 0000000000000..3c1785ca7cfaa --- /dev/null +++ b/drivers/accel/ane/ane_fw_ack_pending.h @@ -0,0 +1,50 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ANE_FW_ACK_PENDING_H_ +#define _ANE_FW_ACK_PENDING_H_ + +#include + +struct ane_fw_ack_pending_trace { + u64 counters[6]; /* before-read pair, existing-write pair, after-read pair */ + u32 before_value, after_value, before_cpu, after_cpu; + u32 mode, calls, bit, valid; +}; + +struct ane_fw_ack_pending_ops { + u64 (*counter)(void *ctx); + u32 (*cpu)(void *ctx); + u32 (*read_pending)(void *ctx); + void (*write_doorbell)(void *ctx, u32 value); +}; + +/* Caller validates mode0..2 and scopes this to a selected consume's original + * doorbell. There is exactly ONE write in every mode. No delay, retry, IRQ mask, + * transport action or pointer lifetime is introduced here. Private mode1 keeps + * bookkeeping but never interprets its zero values as pending observations. + */ +static inline void ane_fw_ack_pending_observe(void *ctx, + const struct ane_fw_ack_pending_ops *ops, struct ane_fw_ack_pending_trace *t, + u32 mode, u32 bit, u32 value) +{ + if (!mode || !t) { + ops->write_doorbell(ctx, value); + return; + } + t->calls++; + t->mode = mode; + t->bit = bit; + t->valid = mode == 2; + t->before_cpu = ops->cpu(ctx); + t->counters[0] = ops->counter(ctx); + t->before_value = mode == 2 ? ops->read_pending(ctx) : 0; + t->counters[1] = ops->counter(ctx); + t->counters[2] = ops->counter(ctx); + ops->write_doorbell(ctx, value); + t->counters[3] = ops->counter(ctx); + t->counters[4] = ops->counter(ctx); + t->after_value = mode == 2 ? ops->read_pending(ctx) : 0; + t->counters[5] = ops->counter(ctx); + t->after_cpu = ops->cpu(ctx); +} + +#endif diff --git a/drivers/accel/ane/ane_fw_irq_coalesce.h b/drivers/accel/ane/ane_fw_irq_coalesce.h new file mode 100644 index 0000000000000..962b027442d54 --- /dev/null +++ b/drivers/accel/ane/ane_fw_irq_coalesce.h @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ANE_FW_IRQ_COALESCE_H_ +#define _ANE_FW_IRQ_COALESCE_H_ +#include +#include + +#define ANE_FW_IRQ_COALESCE_MAX_US 25 +struct ane_fw_irq_coalesce_ops { + u64 (*now_ns)(void *ctx); + int (*error)(void *ctx); + void (*delay_us)(void *ctx, u32 us); +}; +struct ane_fw_irq_coalesce_result { + u64 elapsed_ns; + u32 iterations; + bool clipped; +}; +struct ane_fw_irq_coalesce_stats { + u64 calls, total_ns, min_ns, max_ns, iterations, clipped, errors; +}; + +/* Worker only, after a condition-observed IRQ wake. Never extend the original + * deadline or restart the window for another notification. IRQs/preemption stay + * enabled; their overshoot remains visible. Cap work if a diagnostic clock stalls. + */ +static inline int ane_fw_irq_coalesce(void *ctx, const struct ane_fw_irq_coalesce_ops *ops, + u32 us, u64 deadline, struct ane_fw_irq_coalesce_result *out) +{ + u64 began, now, until; + int error; + + if (!out || !ops || !ops->now_ns || !ops->error || !ops->delay_us || + !us || us > ANE_FW_IRQ_COALESCE_MAX_US) + return -EINVAL; + *out = (struct ane_fw_irq_coalesce_result) {}; + began = now = ops->now_ns(ctx); + until = began + (u64)us * 1000; + if (until < began) + return -EOVERFLOW; + out->clipped = deadline < until; + if (out->clipped) + until = deadline; + while (!(error = ops->error(ctx)) && now < until) { + if (out->iterations == 128) { + error = -EIO; + break; + } + ops->delay_us(ctx, 1); + out->iterations++; + now = ops->now_ns(ctx); + } + now = ops->now_ns(ctx); /* include preemption during the final error check */ + out->elapsed_ns = now - began; + if (error) + return error; + return now >= deadline ? -ETIMEDOUT : 0; +} +#endif diff --git a/drivers/accel/ane/ane_fw_irq_wait.h b/drivers/accel/ane/ane_fw_irq_wait.h new file mode 100644 index 0000000000000..75fd954158099 --- /dev/null +++ b/drivers/accel/ane/ane_fw_irq_wait.h @@ -0,0 +1,61 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ANE_FW_IRQ_WAIT_H_ +#define _ANE_FW_IRQ_WAIT_H_ + +#include +#include +#include +#include + +/* Capture sequence BEFORE checking/draining queues. A notification arriving + * between that check and wait preparation must make the wait a no-op. + * IRQ context owns notification/error only; transport state stays with worker. + */ +struct ane_fw_irq_event { + wait_queue_head_t queue; + atomic_t sequence; + atomic_t error; +}; + +static inline void ane_fw_irq_event_init(struct ane_fw_irq_event *event) +{ + init_waitqueue_head(&event->queue); + atomic_set(&event->sequence, 0); + atomic_set(&event->error, 0); +} + +static inline unsigned int ane_fw_irq_event_sequence(struct ane_fw_irq_event *event) +{ + return atomic_read(&event->sequence); +} + +static inline int ane_fw_irq_event_error(struct ane_fw_irq_event *event) +{ + return atomic_read(&event->error); +} + +static inline void ane_fw_irq_event_notify(struct ane_fw_irq_event *event, int error) +{ + if (error) + atomic_cmpxchg(&event->error, 0, error); + atomic_inc(&event->sequence); + smp_mb__after_atomic(); + wake_up_all(&event->queue); +} + +/* Return 1 for a notification,0 for bounded fallback,or the sticky error. + * Caller caps relative timeout against its ORIGINAL absolute deadline. + */ +static inline int ane_fw_irq_event_wait(struct ane_fw_irq_event *event, + unsigned int sequence, ktime_t timeout) +{ + int ret, error; + + ret = wait_event_hrtimeout(event->queue, + ane_fw_irq_event_sequence(event) != sequence || + ane_fw_irq_event_error(event), timeout); + error = ane_fw_irq_event_error(event); + return error ? error : ret == -ETIME ? 0 : 1; +} + +#endif diff --git a/drivers/accel/ane/ane_fw_irq_wait_test.c b/drivers/accel/ane/ane_fw_irq_wait_test.c new file mode 100644 index 0000000000000..ad856c233f515 --- /dev/null +++ b/drivers/accel/ane/ane_fw_irq_wait_test.c @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include +#include +#include + +#include "ane_fw_irq_wait.h" + +static void ane_irq_signal_before_prepare_test(struct kunit *test) +{ + struct ane_fw_irq_event event; + unsigned int sequence; + + ane_fw_irq_event_init(&event); + sequence = ane_fw_irq_event_sequence(&event); + /* The worker found its ring empty; IRQ lands before wait preparation. */ + ane_fw_irq_event_notify(&event, 0); + KUNIT_EXPECT_EQ(test, ane_fw_irq_event_wait(&event, sequence, + ns_to_ktime(NSEC_PER_MSEC)), 1); +} + +struct ane_irq_wait_thread { + struct ane_fw_irq_event event; + struct completion entered, exited; + int result; +}; + +static int ane_irq_wait_thread_fn(void *data) +{ + struct ane_irq_wait_thread *wait = data; + unsigned int sequence = ane_fw_irq_event_sequence(&wait->event); + + complete(&wait->entered); + wait->result = ane_fw_irq_event_wait(&wait->event, sequence, + ns_to_ktime(NSEC_PER_SEC)); + complete(&wait->exited); + return 0; +} + +static void ane_irq_signal_waiter_test(struct kunit *test) +{ + struct ane_irq_wait_thread wait; + struct task_struct *task; + unsigned long entered, exited; + unsigned int i; + bool prepared; + + ane_fw_irq_event_init(&wait.event); + init_completion(&wait.entered); + init_completion(&wait.exited); + wait.result = -EINVAL; + task = kthread_run(ane_irq_wait_thread_fn, &wait, "ane-irq-test"); + KUNIT_ASSERT_FALSE(test, IS_ERR(task)); + entered = wait_for_completion_timeout(&wait.entered, HZ); + for (i = 0; i < 50 && !waitqueue_active(&wait.event.queue); i++) + usleep_range(1000, 2000); + prepared = waitqueue_active(&wait.event.queue); + ane_fw_irq_event_notify(&wait.event, 0); + exited = wait_for_completion_timeout(&wait.exited, 2 * HZ); + /* Always wake/stop before stack storage goes out of scope. */ + ane_fw_irq_event_notify(&wait.event, -ECANCELED); + kthread_stop(task); + KUNIT_EXPECT_NE(test, entered, 0UL); + KUNIT_EXPECT_TRUE(test, prepared); + KUNIT_EXPECT_NE(test, exited, 0UL); + KUNIT_EXPECT_EQ(test, wait.result, 1); +} + +static void ane_irq_error_sticky_test(struct kunit *test) +{ + struct ane_fw_irq_event event; + unsigned int sequence; + + ane_fw_irq_event_init(&event); + sequence = ane_fw_irq_event_sequence(&event); + ane_fw_irq_event_notify(&event, -EPROTO); + ane_fw_irq_event_notify(&event, -EIO); + KUNIT_EXPECT_EQ(test, ane_fw_irq_event_wait(&event, sequence, + ns_to_ktime(NSEC_PER_MSEC)), -EPROTO); + sequence = ane_fw_irq_event_sequence(&event); + KUNIT_EXPECT_EQ(test, ane_fw_irq_event_wait(&event, sequence, + ns_to_ktime(NSEC_PER_MSEC)), -EPROTO); +} + +static void ane_irq_bounded_fallback_test(struct kunit *test) +{ + struct ane_fw_irq_event event; + + ane_fw_irq_event_init(&event); + KUNIT_EXPECT_EQ(test, ane_fw_irq_event_wait(&event, 0, + ns_to_ktime(NSEC_PER_MSEC)), 0); + KUNIT_EXPECT_EQ(test, ane_fw_irq_event_error(&event), 0); +} + +static struct kunit_case ane_irq_wait_cases[] = { + KUNIT_CASE(ane_irq_signal_before_prepare_test), + KUNIT_CASE(ane_irq_signal_waiter_test), + KUNIT_CASE(ane_irq_error_sticky_test), + KUNIT_CASE(ane_irq_bounded_fallback_test), + {} +}; + +static struct kunit_suite ane_irq_wait_suite = { + .name = "ane-fw-irq-wait", + .test_cases = ane_irq_wait_cases, +}; +kunit_test_suite(ane_irq_wait_suite); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_pending.h b/drivers/accel/ane/ane_fw_pending.h new file mode 100644 index 0000000000000..32ab2aad14658 --- /dev/null +++ b/drivers/accel/ane/ane_fw_pending.h @@ -0,0 +1,62 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ANE_FW_PENDING_H_ +#define _ANE_FW_PENDING_H_ + +#include +#include + +#define ANE_FW_PENDING_MAX 256 +#define ANE_FW_PENDING_ACTIVE_US 200 + +struct ane_fw_pending_sample { + u64 before, after; + u32 value, before_cpu, after_cpu, valid; +}; + +struct ane_fw_pending_ops { + u64 (*now_ns)(void *ctx); + u64 (*counter)(void *ctx); + u32 (*cpu)(void *ctx); + u32 (*read_pending)(void *ctx); + void (*delay_us)(void *ctx, u32 us); +}; + +static inline bool ane_fw_pending_config_valid(u32 mode, u32 gap_us, u32 gap_at) +{ + return mode <= 2 && (!mode || (gap_us == 2000 && gap_at && gap_at <= 128)); +} + +/* Read-only callback; no IRQ/preemption changes, transport service or writes. + * Cap bounds work even if the clock stops advancing. A sample begun before the + * deadline may finish after it. Interrupt/preemption overshoot remains visible. + * Control mode keeps the same loop/counters/delay but performs no pending read. + */ +static inline int ane_fw_pending_capture(void *ctx, const struct ane_fw_pending_ops *ops, + struct ane_fw_pending_sample *samples, u32 capacity, u64 until_ns, + bool read_pending, u32 *count) +{ + u32 n = 0; + + if (!count) + return -EINVAL; + *count = 0; + if (!ops || !samples || !capacity || capacity > ANE_FW_PENDING_MAX || + !ops->now_ns || !ops->counter || !ops->cpu || !ops->delay_us || + (read_pending && !ops->read_pending)) + return -EINVAL; + while (n < capacity && ops->now_ns(ctx) < until_ns) { + struct ane_fw_pending_sample *s = &samples[n++]; + + s->before_cpu = ops->cpu(ctx); + s->before = ops->counter(ctx); + s->value = read_pending ? ops->read_pending(ctx) : 0; + s->after = ops->counter(ctx); + s->after_cpu = ops->cpu(ctx); + s->valid = read_pending; + ops->delay_us(ctx, 1); + } + *count = n; + return n == capacity && ops->now_ns(ctx) < until_ns ? -ENOSPC : 0; +} + +#endif diff --git a/drivers/accel/ane/ane_fw_platform.c b/drivers/accel/ane/ane_fw_platform.c new file mode 100644 index 0000000000000..eac3b2146ebff --- /dev/null +++ b/drivers/accel/ane/ane_fw_platform.c @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * H16/H17 facts from the 2026-10-31 H16/H17 specification, sections 3-7, + * 12 and 15, and the H16 cold-boot facts, round 5. Metadata preflight + * performs no MMIO, DMA mapping or power access. + */ +#include +#include +#include +#include +#include +#include + +#include "ane_fw_platform.h" +#include "ane_h16_boot_data.h" + +static char *h16_stage; +module_param(h16_stage, charp, 0444); +MODULE_PARM_DESC(h16_stage, "H16 opt-in stage: preflight, map, boot, startup; unset refuses"); + +static const char * const ane_h16_reg_names[] = { + "engine", "pmgr", "aux-0", "aux-1", "aux-2", "aux-3", "aux-4", +}; + +static const u32 ane_h16_reg_sizes[] = { + 0x2000000, 0x18000, 0x4000, 0x30000, 0xff4000, 0x2000000, 0x4000, +}; + +/* Offsets in reg[1]; genpd, never the ANE driver, owns transitions. */ +static const u32 ane_h16_power_words[] = { + 0x3c0, 0xc008, 0xc000, 0xc010, 0xc018, +}; + +const struct ane_fw_platform ane_h16_platform = { + .h16_boot = &ane_h16_build_26a428, + .h16_builds = ane_h16_builds, + /* The DT compatible is t6041; the physical M4 Pro is T6040. */ + .soc = 0x6040, + .chip_family = 16, + .ane_type = 0x110, + .hwx_subtype = 7, + .task_generation = 17, + .interrupt_count = 1, + /* J616s IRQ 1054 drains replies and events from all F2H channels. */ + .irq_role = ANE_FW_IRQ_CHANNELS, + .owner = ANE_FW_OWNER_AP, + .reg_names = ane_h16_reg_names, + .reg_sizes = ane_h16_reg_sizes, + .reg_count = ARRAY_SIZE(ane_h16_reg_names), + .wrapper = 0x1600000, + .mailbox = 0x1608000, + .scratch = 0x1880020, + .doorbell = 0x1884000, + .irq_status = 0x188c000, + .irq_ack = 0x1890000, + .power_words = ane_h16_power_words, + .power_count = ARRAY_SIZE(ane_h16_power_words), + .preload_dva = { 0x10000000000, 0x100000c0000 }, + .preload_size = { 0xc0000, 0x2ac000 }, + .stream_mask = BIT(0) | BIT(11), + .firmware_preloaded = true, + .safe_reset = false, +}; + +const struct ane_fw_platform ane_h17_platform = { + .soc = 0x8140, + .chip_family = 17, + .ane_type = 0x200, + .hwx_subtype = 9, + .task_generation = 19, + .interrupt_count = 2, + .owner = ANE_FW_OWNER_EXCLAVE, + .preload_dva = { 0x10000000000, 0x100000c0000 }, + .preload_size = { 0xc0000, 0x2ac000 }, + .stream_mask = BIT(0) | BIT(11), + .firmware_preloaded = true, + .safe_reset = false, + /* No H16 register-map inference is executable on H17. */ +}; + +static int ane_fw_preload_check(struct device *dev, + const struct ane_fw_platform *soc) +{ + struct device_node *np = dev->of_node; + struct device_node *reserved __free(device_node) = + of_find_node_by_path("/reserved-memory"); + u64 phys[2], size[2], dva[2]; + unsigned int i; + + if (!reserved || + of_property_count_u32_elems(np, "memory-region") != 2 || + of_property_count_strings(np, "memory-region-names") != 2 || + of_property_count_u64_elems(np, "apple,firmware-iovas") != 2 || + of_property_read_u64_array(np, "apple,firmware-iovas", dva, 2)) + return -ENODATA; + + for (i = 0; i < 2; i++) { + struct device_node *mem; + struct reserved_mem *rmem; + const char *name; + bool valid; + + if (of_property_read_string_index(np, "memory-region-names", i, + &name) || + strcmp(name, i ? "firmware-data" : "firmware-text")) + return -EINVAL; + mem = of_parse_phandle(np, "memory-region", i); + if (!mem) + return -EINVAL; + rmem = of_reserved_mem_lookup(mem); + valid = rmem && mem->parent == reserved && + of_device_is_available(mem) && + of_property_read_bool(mem, "no-map") && + !of_property_read_bool(mem, "reusable"); + if (valid) { + phys[i] = rmem->base; + size[i] = rmem->size; + } + of_node_put(mem); + if (!valid) + return -EINVAL; + } + + return ane_fw_preload_ranges_valid(soc, phys, size, dva) ? 0 : -EINVAL; +} + +int ane_fw_platform_preflight(struct platform_device *pdev, + const struct ane_fw_platform *soc) +{ + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + struct resource *res; + u32 ane_type; + unsigned int i; + int ret; + + /* No backend has acquired ownership, even if DT omits the marker. + * Check before resources, firmware, power, IOMMU or engine access. + */ + if (soc->owner == ANE_FW_OWNER_EXCLAVE) { + dev_info(dev, "H17 ANE: Linux exclave ownership handoff unavailable; refusing probe\n"); + return -EOPNOTSUPP; + } + if (of_property_read_bool(np, "apple,exclave-assigned")) { + dev_info(dev, "ANE: exclave-assigned device has no Linux ownership provider\n"); + return -EOPNOTSUPP; + } + + if (!of_property_read_bool(np, "apple,firmware-preloaded") || + of_property_read_u32(np, "apple,ane-type", &ane_type) || + ane_type != soc->ane_type) + return dev_err_probe(dev, -EINVAL, "H16 firmware identity missing or invalid\n"); + + if (of_property_count_strings(np, "reg-names") != soc->reg_count || + platform_get_resource(pdev, IORESOURCE_MEM, soc->reg_count) || + of_irq_count(np) != soc->interrupt_count) + return dev_err_probe(dev, -EINVAL, "H16 resource count mismatch\n"); + + for (i = 0; i < soc->reg_count; i++) { + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, + soc->reg_names[i]); + if (!res || resource_size(res) != soc->reg_sizes[i]) + return dev_err_probe(dev, -EINVAL, "H16 resource geometry mismatch\n"); + } + + ret = ane_fw_preload_check(dev, soc); + if (ret) + return dev_err_probe(dev, ret, + "H16 requires bootloader-reserved no-map TEXT/DATA preload ranges\n"); + + ret = ane_h16_stage_parse(h16_stage); + if (ret < 0) + return ret; + if (!ret) { + dev_info(dev, "H16 ANE: staged backend requires h16_stage opt-in; refusing before power access\n"); + return -EOPNOTSUPP; + } + if (!soc->h16_boot || of_property_count_u64_elems(np, "apple,dapf-ranges") != 8) + return -ENODATA; + return 0; +} + +int ane_fw_platform_probe(struct platform_device *pdev, const struct ane_fw_platform *soc) +{ + int ret = ane_fw_platform_preflight(pdev, soc); + + if (ret) + return ret; + return ane_h16_backend_probe(pdev, soc, ane_h16_stage_parse(h16_stage)); +} + +void ane_fw_platform_remove(struct platform_device *pdev) +{ + ane_h16_backend_remove(pdev); +} diff --git a/drivers/accel/ane/ane_fw_platform.h b/drivers/accel/ane/ane_fw_platform.h new file mode 100644 index 0000000000000..13c77f6f803fb --- /dev/null +++ b/drivers/accel/ane/ane_fw_platform.h @@ -0,0 +1,86 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_FW_PLATFORM_H__ +#define __ANE_FW_PLATFORM_H__ + +#include +#include +#include +#include +#include +#include + +struct platform_device; +struct ane_h16_build; + +enum ane_fw_owner { + ANE_FW_OWNER_AP, + ANE_FW_OWNER_EXCLAVE, +}; + +enum ane_fw_irq_role { + ANE_FW_IRQ_UNKNOWN, + ANE_FW_IRQ_CHANNELS, +}; + +/* Later firmware generations must never enter the H14 staging path. */ +struct ane_fw_platform { + const struct ane_h16_build *h16_boot; + /* Indexed like ane_h16_preload_layouts. */ + const struct ane_h16_build *const *h16_builds; + u32 soc; + u16 chip_family; + u16 ane_type; + u8 hwx_subtype; + u8 task_generation; + u8 interrupt_count; + enum ane_fw_irq_role irq_role; + enum ane_fw_owner owner; + const char * const *reg_names; + const u32 *reg_sizes; + u32 reg_count; + u32 wrapper; + u32 mailbox; + u32 scratch; + u32 doorbell; + u32 irq_status; + u32 irq_ack; + const u32 *power_words; + u32 power_count; + u64 preload_dva[2]; + u64 preload_size[2]; + u16 stream_mask; + bool firmware_preloaded; + bool safe_reset; +}; + +/* 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], + const u64 size[2], const u64 dva[2]) +{ + u64 end[2]; + unsigned int i; + + for (i = 0; i < 2; i++) { + if (!phys[i] || !IS_ALIGNED(phys[i], SZ_16K) || + size[i] != soc->preload_size[i] || + dva[i] != soc->preload_dva[i] || + check_add_overflow(phys[i], size[i], &end[i])) + return false; + } + return end[0] <= phys[1] || end[1] <= phys[0]; +} + +extern const struct ane_fw_platform ane_h16_platform, ane_h17_platform; +int ane_fw_platform_preflight(struct platform_device *pdev, + const struct ane_fw_platform *soc); + +int ane_fw_platform_probe(struct platform_device *pdev, + const struct ane_fw_platform *soc); +void ane_fw_platform_remove(struct platform_device *pdev); +int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_platform *soc, + unsigned int stage); +void ane_h16_backend_remove(struct platform_device *pdev); +void ane_h16_backend_exit(void); + +#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 new file mode 100644 index 0000000000000..0f7171ec95a7e --- /dev/null +++ b/drivers/accel/ane/ane_fw_platform_test.c @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +#include "ane_fw_platform.h" + +static void ane_preload_ranges_test(struct kunit *test) +{ + const struct ane_fw_platform soc = { + .preload_dva = { 0x10000000000, 0x100000c0000 }, + .preload_size = { 0xc0000, 0x2ac000 }, + }; + u64 phys[] = { 0x100000000, 0x200000000 }; + u64 size[] = { 0xc0000, 0x2ac000 }; + u64 dva[] = { 0x10000000000, 0x100000c0000 }; + + KUNIT_EXPECT_TRUE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + /* Physical placement may change independently on every boot. */ + phys[0] = 0x300000000; + KUNIT_EXPECT_TRUE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + phys[0] = phys[1] + SZ_16K; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + phys[0] = phys[1] - size[0]; + KUNIT_EXPECT_TRUE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + phys[0]++; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + phys[0] = 0; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + phys[0] = U64_MAX - SZ_16K + 1; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + phys[0] = 0x100000000; + size[1] -= SZ_16K; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); + size[1] = 0x2ac000; + dva[0] = 0x100000c0000; + dva[1] = 0x10000000000; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); +} + +static struct kunit_case ane_fw_platform_cases[] = { + KUNIT_CASE(ane_preload_ranges_test), + {} +}; + +static struct kunit_suite ane_fw_platform_suite = { + .name = "ane-fw-platform", + .test_cases = ane_fw_platform_cases, +}; + +kunit_test_suite(ane_fw_platform_suite); + +MODULE_DESCRIPTION("KUnit tests for ANE firmware preload range validation"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_protocol.h b/drivers/accel/ane/ane_fw_protocol.h new file mode 100644 index 0000000000000..8b37679063a6e --- /dev/null +++ b/drivers/accel/ane/ane_fw_protocol.h @@ -0,0 +1,262 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_FW_PROTOCOL_H__ +#define __ANE_FW_PROTOCOL_H__ + +#include +#include +#include +#include +#include +#include + +#define ANE_FW_CHANNELS 8 +#define ANE_FW_DESCRIPTOR_SIZE 0x100 +#define ANE_FW_TABLE_SIZE (ANE_FW_CHANNELS * ANE_FW_DESCRIPTOR_SIZE) +#define ANE_FW_SLOT_SIZE 64 +#define ANE_FW_TICK_RATE 24000000U + +struct ane_fw_channel { + u64 offset; + u32 slots; + u32 type; + u32 bit; + u32 index; +}; + +static inline bool ane_fw_contains(u64 base, u64 bytes, u64 addr, u64 size) +{ + return bytes <= U64_MAX - base && size <= bytes && addr >= base && + addr - base <= bytes - size; +} + +/* Parse a host-owned descriptor snapshot; output indices are logical names. */ +static inline int +ane_fw_channels_parse(const void *table, u64 ipc_dva, size_t ipc_size, + u64 table_dva, struct ane_fw_channel channels[ANE_FW_CHANNELS]) +{ + static const char * const names[ANE_FW_CHANNELS] = { + "TERMINAL", "IO", "DEBUG", "BUF_H2T", "BUF_T2H", + "SHAREDMALLOC", "IO_T2H", "DATA_CHAIN_H2T", + }; + struct ane_fw_channel parsed[ANE_FW_CHANNELS] = {}; + u64 table_off; + u32 seen = 0; + unsigned int i, j; + + if (!table || !channels || + !ane_fw_contains(ipc_dva, ipc_size, table_dva, ANE_FW_TABLE_SIZE)) + return -EPROTO; + table_off = table_dva - ipc_dva; + for (i = 0; i < ANE_FW_CHANNELS; i++) { + const u8 *desc = (const u8 *)table + i * ANE_FW_DESCRIPTOR_SIZE; + struct ane_fw_channel *c; + u64 slots, ring, end; + + if (!memchr(desc, 0, 64)) + return -EPROTO; + for (j = 0; j < ANE_FW_CHANNELS; j++) + if (!strcmp((const char *)desc, names[j])) + break; + if (j == ANE_FW_CHANNELS || (seen & BIT(j))) + return -EPROTO; + seen |= BIT(j); + c = &parsed[j]; + c->index = i; + c->type = get_unaligned_le32(desc + 0x40); + c->bit = get_unaligned_le32(desc + 0x44); + slots = get_unaligned_le64(desc + 0x48); + ring = get_unaligned_le64(desc + 0x50); + if (c->type > 2 || c->bit >= 32 || !slots || slots > 0x400 || + (ring & (ANE_FW_SLOT_SIZE - 1)) || + !ane_fw_contains(ipc_dva, ipc_size, ring, + slots * ANE_FW_SLOT_SIZE)) + return -EPROTO; + c->offset = ring - ipc_dva; + c->slots = slots; + end = c->offset + slots * ANE_FW_SLOT_SIZE; + if (c->offset < table_off + ANE_FW_TABLE_SIZE && end > table_off) + return -EPROTO; + } + if (seen != GENMASK(ANE_FW_CHANNELS - 1, 0) || + parsed[1].type != 0 || parsed[5].type != 1 || + parsed[6].type != 1 || parsed[7].type != 0) + return -EPROTO; + for (i = 0; i < ANE_FW_CHANNELS; i++) { + u64 end = parsed[i].offset + parsed[i].slots * ANE_FW_SLOT_SIZE; + + for (j = i + 1; j < ANE_FW_CHANNELS; j++) + if (parsed[i].offset < parsed[j].offset + + parsed[j].slots * ANE_FW_SLOT_SIZE && + parsed[j].offset < end) + return -EPROTO; + } + memcpy(channels, parsed, sizeof(parsed)); + return 0; +} + +/* Call only after parsing the table and checking its immutable snapshot. */ +static inline void +ane_fw_channels_host_init(void *ipc, const struct ane_fw_channel *channels) +{ + unsigned int i, slot; + + for (i = 0; i < ANE_FW_CHANNELS; i++) { + const struct ane_fw_channel *c = &channels[i]; + + if (c->type) + continue; + for (slot = 0; slot < c->slots; slot++) { + u8 *p = (u8 *)ipc + c->offset + slot * ANE_FW_SLOT_SIZE; + + memset(p, 0, 24); + put_unaligned_le64(1, p); + } + } +} + +/* H14 preserves its reserved word; H16 requires bytes 0..3 to be zero. */ +static inline void ane_fw_command_header(void *command, u16 opcode, bool zero_reserved) +{ + u8 *p = command; + + if (zero_reserved) + put_unaligned_le32(0, p); + put_unaligned_le16(opcode, p + 4); + put_unaligned_le16(0, p + 6); +} + +/* A firmware refusal is distinct from corruption and never means success. */ +static inline int +ane_fw_reply_status(u64 header, u64 slot_length, u64 slot_result, + u64 command_dva, size_t length, u16 opcode, const void *command, + bool zero_reserved) +{ + const u8 *p = command; + + if (header & 2) + return -EPROTO; + if (!(header & 1)) + return -EAGAIN; + if (!command || length < 8 || (command_dva & 1) || header != (command_dva | 1) || + slot_length != length || slot_result || + (zero_reserved && get_unaligned_le32(p)) || + get_unaligned_le16(p + 4) != opcode) + return -EPROTO; + return get_unaligned_le16(p + 6) ? -EREMOTEIO : 0; +} + +static inline int ane_fw_config_status(const void *command, size_t length) +{ + if (!command || length != 16 || get_unaligned_le32((const u8 *)command + 8) != + ANE_FW_TICK_RATE) + return -EPROTO; + return 0; +} + +/* Legacy H14/comparator layout only; H16 27.0 reports are 0x60 bytes. */ +static inline int +ane_fw_finished_event(const void *event, size_t length, u64 cookie, + u32 program, u32 process) +{ + const u8 *p = event; + u32 state; + + if (!p || length != 0x28 || get_unaligned_le32(p + 4) != 0x300 || + get_unaligned_le64(p + 8) != cookie || + get_unaligned_le32(p + 0x10) != program || + get_unaligned_le32(p + 0x14) != process || + get_unaligned_le32(p + 0x18)) + return -EPROTO; + state = get_unaligned_le32(p + 0x1c); + return state > 1 ? -EPROTO : state; +} + +enum ane_fw_rtk_phase { + ANE_FW_RTK_HELLO, + ANE_FW_RTK_EPMAP, + ANE_FW_RTK_IOP_ACK, + ANE_FW_RTK_AP_ACK, + ANE_FW_RTK_READY, +}; + +struct ane_fw_rtk { + u32 endpoints[8]; + u8 fragments; + enum ane_fw_rtk_phase phase; +}; + +#define ANE_FW_RTK_TYPE(t) ((u64)(t) << 52) +#define ANE_FW_RTK_LAST BIT_ULL(51) + +/* The caller owns one absolute deadline for the complete management session. */ +static inline int +ane_fw_rtk_receive(struct ane_fw_rtk *rtk, u64 word0, u64 word1, + void *ctx, int (*send)(void *ctx, u64 word0, u64 word1)) +{ + static const u8 system_eps[] = { 1, 2, 3, 4, 8, 10 }; + u32 type = (word0 >> 52) & 0xff; + unsigned int base, ep, i; + int ret; + + if (word1 & 0xff) + return -EOPNOTSUPP; + switch (type) { + case 1: + if (rtk->phase != ANE_FW_RTK_HELLO || (word0 & 0xffff) > 12 || + ((word0 >> 16) & 0xffff) < 12) + return -EPROTO; + ret = send(ctx, ANE_FW_RTK_TYPE(2) | (12 << 16) | 12, 0); + if (!ret) + rtk->phase = ANE_FW_RTK_EPMAP; + return ret; + case 8: + if (rtk->phase != ANE_FW_RTK_EPMAP) + return -EPROTO; + base = (word0 >> 32) & 7; + if (rtk->fragments & BIT(base)) + return -EPROTO; + rtk->fragments |= BIT(base); + rtk->endpoints[base] = word0; + ret = send(ctx, ANE_FW_RTK_TYPE(8) | ((u64)base << 32) | + (word0 & ANE_FW_RTK_LAST ? ANE_FW_RTK_LAST : 1), 0); + if (ret || !(word0 & ANE_FW_RTK_LAST)) + return ret; + for (i = 0; i < ARRAY_SIZE(system_eps); i++) { + ep = system_eps[i]; + if (!(rtk->endpoints[0] & BIT(ep))) + continue; + ret = send(ctx, ANE_FW_RTK_TYPE(5) | ((u64)ep << 32) | 2, 0); + if (ret) + return ret; + } + ret = send(ctx, ANE_FW_RTK_TYPE(6) | 0x20, 0); + if (!ret) + rtk->phase = ANE_FW_RTK_IOP_ACK; + return ret; + case 7: + if (rtk->phase != ANE_FW_RTK_IOP_ACK || (word0 & 0xffff) != 0x20) + return -EPROTO; + ret = send(ctx, ANE_FW_RTK_TYPE(0xb) | 0x20, 0); + if (!ret) + rtk->phase = ANE_FW_RTK_AP_ACK; + return ret; + case 0xb: + if (rtk->phase != ANE_FW_RTK_AP_ACK || (word0 & 0xffff) != 0x20) + return -EPROTO; + for (ep = 0x20; ep < 0x100; ep++) { + if (!(rtk->endpoints[ep / 32] & BIT(ep % 32))) + continue; + ret = send(ctx, ANE_FW_RTK_TYPE(5) | ((u64)ep << 32) | 2, 0); + if (ret) + return ret; + } + rtk->phase = ANE_FW_RTK_READY; + return 0; + case 0xc: + return 0; + default: + return -EOPNOTSUPP; + } +} + +#endif /* __ANE_FW_PROTOCOL_H__ */ diff --git a/drivers/accel/ane/ane_fw_protocol_test.c b/drivers/accel/ane/ane_fw_protocol_test.c new file mode 100644 index 0000000000000..fb98428f3f238 --- /dev/null +++ b/drivers/accel/ane/ane_fw_protocol_test.c @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include + +#include "ane_fw_protocol.h" +#include "ane_h16_protocol.h" + +static void ane_h16_id_table_test(struct kunit *test) +{ + static const struct ane_h16_command_info expected[] = { + { 0x200, 0x1c0, 0x1c0, 1, 1, false }, + { 0x201, 0xc, 0xc, 1, 1, false }, + { 0x202, 0x258, 0x258, 1, 1, false }, + { 0x203, 0x10, 0x10, 1, 1, false }, + { 0x20c, 0xca8, 0xcd8, 0x18, 7, false }, + { 0x2d, 0xc, 0xc, 1, 7, false }, + { 0x300, 0x60, 0x60, 1, 6, true }, + }; + u8 *command = kunit_kzalloc(test, 0xcd8, GFP_KERNEL); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, command); + for (i = 0; i < ARRAY_SIZE(expected); i++) { + const struct ane_h16_command_info *e = &expected[i]; + const struct ane_h16_command_info *info = ane_h16_command_info(e->id); + size_t length; + int ret; + + KUNIT_ASSERT_NOT_NULL(test, info); + KUNIT_EXPECT_EQ(test, info->min_size, e->min_size); + KUNIT_EXPECT_EQ(test, info->max_size, e->max_size); + KUNIT_EXPECT_EQ(test, info->size_step, e->size_step); + KUNIT_EXPECT_EQ(test, info->channel, e->channel); + KUNIT_EXPECT_EQ(test, info->from_firmware, e->from_firmware); + if (e->from_firmware) { + ret = ane_h16_command_prepare(command, e->min_size, e->id, e->channel); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + continue; + } + for (length = e->min_size; length <= e->max_size; length += e->size_step) { + ret = ane_h16_command_prepare(command, length, e->id, e->channel); + KUNIT_EXPECT_EQ(test, ret, 0); + } + ret = ane_h16_command_prepare(command, e->min_size - 1, e->id, e->channel); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_h16_command_prepare(command, e->max_size + 1, e->id, e->channel); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_h16_command_prepare(command, e->min_size, e->id, e->channel ^ 1); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + } + KUNIT_EXPECT_PTR_EQ(test, ane_h16_command_info(0x204), NULL); + KUNIT_EXPECT_PTR_EQ(test, ane_h16_command_info(0x301), NULL); + KUNIT_EXPECT_EQ(test, ane_h16_command_prepare(command, 0xca8, 0x204, 7), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, ane_h16_command_prepare(command, 0xca9, 0x20c, 7), -EINVAL); + /* The H14 CREATE_PROCESS size must never be sent to H16. */ + KUNIT_EXPECT_EQ(test, ane_h16_command_prepare(command, 0x10, 0x202, 1), -EINVAL); +} + +static void ane_h16_envelope_test(struct kunit *test) +{ + u8 command[0xc]; + const u64 dva = 0x30000000000; + + memset(command, 0xa5, sizeof(command)); + put_unaligned_le32(1, command + 8); + KUNIT_ASSERT_EQ(test, ane_h16_command_prepare(command, sizeof(command), 0x2d, 7), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(command), 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(command + 4), (u16)0x2d); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(command + 6), (u16)0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(command + 8), 1U); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 0xc, 0, dva, 0xc, + 0x2d, command, true), 0); + /* Test the upper byte too: acknowledgment is u16, not u8. */ + put_unaligned_le16(0x100, command + 6); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 0xc, 0, dva, 0xc, + 0x2d, command, true), -EREMOTEIO); + put_unaligned_le32(0, command + 8); + KUNIT_ASSERT_EQ(test, ane_h16_command_prepare(command, sizeof(command), 0x2d, 7), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(command + 6), (u16)0); + put_unaligned_le32(2, command + 8); + KUNIT_EXPECT_EQ(test, ane_h16_command_prepare(command, sizeof(command), 0x2d, 7), + -EINVAL); + KUNIT_EXPECT_EQ(test, ane_h16_command_prepare(NULL, sizeof(command), 0x2d, 7), + -EINVAL); +} + +static void ane_h16_report_test(struct kunit *test) +{ + u8 event[0x60] = {}; + unsigned int n; + + put_unaligned_le16(0x300, event + 4); + for (n = 0; n < 4; n++) { + put_unaligned_le32(0xfe00 | n, event); + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(event, sizeof(event), 6), 0); + /* A report can never satisfy the legacy completion predicate. */ + KUNIT_EXPECT_EQ(test, ane_fw_finished_event(event, sizeof(event), 0, 0, 0), + -EPROTO); + } + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(event, sizeof(event), 7), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(event, 0x28, 6), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(event, 0xc, 6), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(NULL, 0x60, 6), -EPROTO); + put_unaligned_le32(0xfe04, event); + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(event, sizeof(event), 6), 0); + put_unaligned_le32(0xfe00, event); + put_unaligned_le16(0x301, event + 4); + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(event, sizeof(event), 6), -EPROTO); + put_unaligned_le16(0x300, event + 4); + put_unaligned_le16(0x100, event + 6); + KUNIT_EXPECT_EQ(test, ane_h16_event_report_status(event, sizeof(event), 6), -EPROTO); +} + +#define TEST_IPC_SIZE 0x10000 +#define TEST_IPC_DVA 0x20000000000ULL +#define TEST_TABLE_OFF 0x1000 + +static void *ane_test_table(struct kunit *test) +{ + static const char * const names[] = { + "TERMINAL", "IO", "DEBUG", "BUF_H2T", "BUF_T2H", + "SHAREDMALLOC", "IO_T2H", "DATA_CHAIN_H2T", + }; + void *ipc = kunit_kzalloc(test, TEST_IPC_SIZE, GFP_KERNEL); + unsigned int i; + + if (!ipc) + return NULL; + for (i = 0; i < ANE_FW_CHANNELS; i++) { + u8 *d = ipc + TEST_TABLE_OFF + i * ANE_FW_DESCRIPTOR_SIZE; + + strscpy((char *)d, names[i], 64); + put_unaligned_le32(i == 0 ? 2 : (i == 4 || i == 5 || i == 6), d + 0x40); + put_unaligned_le32(31 - i, d + 0x44); + put_unaligned_le64(i + 1, d + 0x48); + put_unaligned_le64(TEST_IPC_DVA + 0x2000 + i * 0x400, d + 0x50); + } + return ipc; +} + +static int ane_test_channels_parse(void *ipc, struct ane_fw_channel *channels) +{ + return ane_fw_channels_parse(ipc + TEST_TABLE_OFF, TEST_IPC_DVA, TEST_IPC_SIZE, + TEST_IPC_DVA + TEST_TABLE_OFF, channels); +} + +static void ane_dynamic_channels_test(struct kunit *test) +{ + struct ane_fw_channel channels[ANE_FW_CHANNELS]; + u8 *ipc = ane_test_table(test); + u8 *io; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, ipc); + KUNIT_ASSERT_EQ(test, ane_test_channels_parse(ipc, channels), 0); + KUNIT_EXPECT_EQ(test, channels[1].bit, 30U); + KUNIT_EXPECT_EQ(test, channels[1].slots, 2U); + KUNIT_EXPECT_EQ(test, channels[1].offset, 0x2400ULL); + KUNIT_EXPECT_EQ(test, channels[1].index, 1U); + { + u8 saved[ANE_FW_DESCRIPTOR_SIZE]; + u8 *first = ipc + TEST_TABLE_OFF + ANE_FW_DESCRIPTOR_SIZE; + u8 *last = ipc + TEST_TABLE_OFF + 7 * ANE_FW_DESCRIPTOR_SIZE; + + memcpy(saved, first, sizeof(saved)); + memcpy(first, last, sizeof(saved)); + memcpy(last, saved, sizeof(saved)); + KUNIT_ASSERT_EQ(test, ane_test_channels_parse(ipc, channels), 0); + KUNIT_EXPECT_EQ(test, channels[1].offset, 0x2400ULL); + KUNIT_EXPECT_EQ(test, channels[1].index, 7U); + } + memset(ipc + 0x2000, 0xa5, 0x2000); + ane_fw_channels_host_init(ipc, channels); + io = ipc + channels[1].offset; + KUNIT_EXPECT_EQ(test, get_unaligned_le64(io), 1ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(io + 8), 0ULL); + KUNIT_EXPECT_EQ(test, io[24], (u8)0xa5); + for (i = 0; i < 24; i++) + KUNIT_EXPECT_EQ(test, ipc[0x2000 + i], (u8)0xa5); +} + +static void ane_channel_snapshot_test(struct kunit *test) +{ + struct ane_fw_channel channels[ANE_FW_CHANNELS]; + u8 *ipc = ane_test_table(test); + u8 *snapshot = kunit_kmalloc(test, ANE_FW_TABLE_SIZE, GFP_KERNEL); + int ret; + + KUNIT_ASSERT_NOT_NULL(test, ipc); + KUNIT_ASSERT_NOT_NULL(test, snapshot); + memcpy(snapshot, ipc + TEST_TABLE_OFF, ANE_FW_TABLE_SIZE); + put_unaligned_le64(0, ipc + TEST_TABLE_OFF + ANE_FW_DESCRIPTOR_SIZE + 0x48); + ret = ane_fw_channels_parse(snapshot, TEST_IPC_DVA, TEST_IPC_SIZE, + TEST_IPC_DVA + TEST_TABLE_OFF, channels); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, channels[1].slots, 2U); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); +} + +static void ane_channel_rejections_test(struct kunit *test) +{ + struct ane_fw_channel channels[ANE_FW_CHANNELS]; + u8 *ipc = ane_test_table(test); + u8 *d; + + KUNIT_ASSERT_NOT_NULL(test, ipc); + d = ipc + TEST_TABLE_OFF + ANE_FW_DESCRIPTOR_SIZE; + put_unaligned_le64(0, d + 0x48); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + put_unaligned_le64(0x401, d + 0x48); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + put_unaligned_le64(2, d + 0x48); + put_unaligned_le64(TEST_IPC_DVA + TEST_TABLE_OFF, d + 0x50); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + put_unaligned_le64(TEST_IPC_DVA + 0x2000, d + 0x50); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + put_unaligned_le64(TEST_IPC_DVA + TEST_IPC_SIZE - 64, d + 0x50); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + put_unaligned_le64(TEST_IPC_DVA + 0x2400, d + 0x50); + put_unaligned_le32(32, d + 0x44); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + put_unaligned_le32(30, d + 0x44); + put_unaligned_le32(1, d + 0x40); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + put_unaligned_le32(0, d + 0x40); + strscpy((char *)d, "TERMINAL", 64); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + memset(d, 0x41, 64); + KUNIT_EXPECT_EQ(test, ane_test_channels_parse(ipc, channels), -EPROTO); + KUNIT_EXPECT_FALSE(test, ane_fw_contains(16, 64, U64_MAX, 32)); + KUNIT_EXPECT_FALSE(test, ane_fw_contains(16, 64, 16, 65)); +} + +static void ane_reply_status_test(struct kunit *test) +{ + u8 command[16] = {}; + const u64 dva = 0x30000000000; + + put_unaligned_le16(3, command + 4); + put_unaligned_le32(ANE_FW_TICK_RATE, command + 8); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva, 16, 16, dva, 16, 3, + command, true), -EAGAIN); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 16, 0, dva, 16, 3, + command, true), 0); + KUNIT_EXPECT_EQ(test, ane_fw_config_status(command, sizeof(command)), 0); + put_unaligned_le16(1, command + 6); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 16, 0, dva, 16, 3, + command, true), -EREMOTEIO); + put_unaligned_le16(0xffff, command + 6); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 16, 0, dva, 16, 3, + command, true), -EREMOTEIO); + put_unaligned_le16(0, command + 6); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 15, 0, dva, 16, 3, + command, true), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 16, 1, dva, 16, 3, + command, true), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 16, 0, dva, 16, 4, + command, true), -EPROTO); + put_unaligned_le32(1, command); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 16, 0, dva, 16, 3, + command, true), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(dva | 1, 16, 0, dva, 16, 3, + command, false), 0); + put_unaligned_le32(1, command + 8); + KUNIT_EXPECT_EQ(test, ane_fw_config_status(command, sizeof(command)), -EPROTO); +} + +static void ane_finished_event_test(struct kunit *test) +{ + u8 event[0x28] = {}; + + put_unaligned_le32(0x300, event + 4); + put_unaligned_le64(42, event + 8); + put_unaligned_le32(3, event + 0x10); + put_unaligned_le32(4, event + 0x14); + KUNIT_EXPECT_EQ(test, ane_fw_finished_event(event, sizeof(event), 42, 3, 4), 0); + put_unaligned_le32(1, event + 0x1c); + KUNIT_EXPECT_EQ(test, ane_fw_finished_event(event, sizeof(event), 42, 3, 4), 1); + KUNIT_EXPECT_EQ(test, ane_fw_finished_event(event, sizeof(event), 41, 3, 4), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_finished_event(event, sizeof(event), 42, 3, 5), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_finished_event(event, 0x20, 42, 3, 4), -EPROTO); + put_unaligned_le32(2, event + 0x1c); + KUNIT_EXPECT_EQ(test, ane_fw_finished_event(event, sizeof(event), 42, 3, 4), -EPROTO); +} + +struct ane_test_tx { + u64 words[16]; + unsigned int count; +}; + +static int ane_test_send(void *ctx, u64 word0, u64 word1) +{ + struct ane_test_tx *tx = ctx; + + if (word1 || tx->count == ARRAY_SIZE(tx->words)) + return -EOVERFLOW; + tx->words[tx->count++] = word0; + return 0; +} + +static void ane_rtk_order_test(struct kunit *test) +{ + struct ane_fw_rtk rtk = {}; + struct ane_test_tx tx = {}; + + KUNIT_ASSERT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(1) | + (13 << 16) | 11, 0, &tx, ane_test_send), 0); + KUNIT_EXPECT_EQ(test, tx.words[0], ANE_FW_RTK_TYPE(2) | (12 << 16) | 12); + KUNIT_ASSERT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(8) | + BIT(2) | BIT(8), 0, &tx, ane_test_send), 0); + KUNIT_EXPECT_EQ(test, tx.words[1], ANE_FW_RTK_TYPE(8) | 1); + KUNIT_ASSERT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(8) | + BIT_ULL(32) | ANE_FW_RTK_LAST | BIT(0) | BIT(5), 0, + &tx, ane_test_send), 0); + KUNIT_EXPECT_EQ(test, rtk.phase, ANE_FW_RTK_IOP_ACK); + KUNIT_EXPECT_EQ(test, tx.count, 6U); + KUNIT_EXPECT_EQ(test, tx.words[2], ANE_FW_RTK_TYPE(8) | BIT_ULL(32) | + ANE_FW_RTK_LAST); + KUNIT_EXPECT_EQ(test, tx.words[3], ANE_FW_RTK_TYPE(5) | (2ULL << 32) | 2); + KUNIT_EXPECT_EQ(test, tx.words[4], ANE_FW_RTK_TYPE(5) | (8ULL << 32) | 2); + KUNIT_ASSERT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(7) | 0x20, + 0, &tx, ane_test_send), 0); + KUNIT_EXPECT_EQ(test, tx.words[6], ANE_FW_RTK_TYPE(0xb) | 0x20); + KUNIT_ASSERT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(0xb) | 0x20, + 0, &tx, ane_test_send), 0); + KUNIT_EXPECT_EQ(test, rtk.phase, ANE_FW_RTK_READY); + KUNIT_EXPECT_EQ(test, tx.words[7], ANE_FW_RTK_TYPE(5) | (32ULL << 32) | 2); + KUNIT_EXPECT_EQ(test, tx.words[8], ANE_FW_RTK_TYPE(5) | (37ULL << 32) | 2); +} + +static void ane_rtk_rejections_test(struct kunit *test) +{ + struct ane_fw_rtk rtk = {}; + struct ane_test_tx tx = {}; + u64 hello = ANE_FW_RTK_TYPE(1) | (12 << 16) | 12; + int ret; + + KUNIT_EXPECT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(1) | + (2 << 16) | 1, 0, &tx, ane_test_send), -EPROTO); + KUNIT_EXPECT_EQ(test, tx.count, 0U); + ret = ane_fw_rtk_receive(&rtk, hello, 2, &tx, ane_test_send); + KUNIT_EXPECT_EQ(test, ret, -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, tx.count, 0U); + KUNIT_EXPECT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(7) | 0x20, + 0, &tx, ane_test_send), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_rtk_receive(&rtk, ANE_FW_RTK_TYPE(0xff), + 0, &tx, ane_test_send), -EOPNOTSUPP); +} + +static struct kunit_case ane_protocol_cases[] = { + KUNIT_CASE(ane_h16_id_table_test), + KUNIT_CASE(ane_h16_envelope_test), + KUNIT_CASE(ane_h16_report_test), + KUNIT_CASE(ane_dynamic_channels_test), + KUNIT_CASE(ane_channel_snapshot_test), + KUNIT_CASE(ane_channel_rejections_test), + KUNIT_CASE(ane_reply_status_test), + KUNIT_CASE(ane_finished_event_test), + KUNIT_CASE(ane_rtk_order_test), + KUNIT_CASE(ane_rtk_rejections_test), + {} +}; + +static struct kunit_suite ane_protocol_suite = { + .name = "ane-fw-protocol", + .test_cases = ane_protocol_cases, +}; + +kunit_test_suite(ane_protocol_suite); +MODULE_DESCRIPTION("KUnit tests for ANE 27.x channel and RTKit contracts"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_report_fifo.h b/drivers/accel/ane/ane_fw_report_fifo.h new file mode 100644 index 0000000000000..75f71ad0dc6bc --- /dev/null +++ b/drivers/accel/ane/ane_fw_report_fifo.h @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ANE_FW_REPORT_FIFO_H_ +#define _ANE_FW_REPORT_FIFO_H_ +#include +#include +#include +#include + +#define ANE_FW_REPORT_FIFO_CAPACITY 256 +struct ane_fw_report { + size_t size; + u64 ns, counter; + u8 data[0x80]; +}; + +/* Process-context owner only. IRQ handler never reads or mutates this FIFO. */ +struct ane_fw_report_fifo { + STRUCT_KFIFO_PTR(struct ane_fw_report) packets; + u32 captured, peak, full_errors; +}; + +static inline int ane_fw_report_fifo_init(struct ane_fw_report_fifo *q) +{ + q->captured = q->peak = q->full_errors = 0; + return kfifo_alloc(&q->packets, ANE_FW_REPORT_FIFO_CAPACITY, GFP_KERNEL); +} + +static inline u32 ane_fw_report_fifo_count(struct ane_fw_report_fifo *q) +{ + return kfifo_initialized(&q->packets) ? kfifo_len(&q->packets) : 0; +} + +static inline void ane_fw_report_fifo_free(struct ane_fw_report_fifo *q) +{ + kfifo_free(&q->packets); +} + +static inline int ane_fw_report_fifo_pop(struct ane_fw_report_fifo *q, + struct ane_fw_report *packet) +{ + if (!kfifo_initialized(&q->packets)) + return -EAGAIN; + return kfifo_out(&q->packets, packet, 1) == 1 ? 0 : -EAGAIN; +} + +static inline int ane_fw_report_fifo_complete(struct ane_fw_report_fifo *q, + unsigned int outstanding) +{ + return ane_fw_report_fifo_count(q) || outstanding ? -EPROTO : 0; +} + +/* capture copies the payload BEFORE transport ACK; the private packet then + * survives FW buffer recycling. Check capacity before any capture/ACK and never + * overwrite/drop. A small budget lets caller recheck CMD and original deadline. + */ +static inline int ane_fw_report_fifo_prefetch(struct ane_fw_report_fifo *q, + int (*capture)(void *, struct ane_fw_report *), void *ctx, + unsigned int budget, bool *progress) +{ + unsigned int i; + + *progress = false; + if (!kfifo_initialized(&q->packets) || !capture || !budget) + return -EINVAL; + for (i = 0; i < budget; i++) { + struct ane_fw_report packet = {}; + int ret; + + if (kfifo_is_full(&q->packets)) { + q->full_errors++; + return -ENOSPC; + } + ret = capture(ctx, &packet); + if (ret == -EAGAIN) + return 0; + if (ret) + return ret; + if (packet.size < 8 || packet.size > sizeof(packet.data)) + return -EPROTO; + if (kfifo_in(&q->packets, &packet, 1) != 1) + return -EIO; + q->captured++; + q->peak = max(q->peak, ane_fw_report_fifo_count(q)); + *progress = true; + } + return 0; +} +#endif diff --git a/drivers/accel/ane/ane_fw_report_fifo_test.c b/drivers/accel/ane/ane_fw_report_fifo_test.c new file mode 100644 index 0000000000000..186c9287883e2 --- /dev/null +++ b/drivers/accel/ane/ane_fw_report_fifo_test.c @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include +#include "ane_fw_report_fifo.h" +#include "ane_fw_irq_wait.h" + +struct fifo_source { + unsigned int next, available, calls; + int error; + bool reverse; + struct ane_fw_irq_event *notify; + u8 source[0x30]; +}; + +static int fifo_capture(void *ctx, struct ane_fw_report *p) +{ + struct fifo_source *f = ctx; + + f->calls++; + if (f->next == f->available) + return f->error ?: -EAGAIN; + if (f->reverse) { + memset(f->source, 0, sizeof(f->source)); + put_unaligned_le16(0x300, f->source + 4); + put_unaligned_le64(2 - f->next, f->source + 8); + put_unaligned_le32(1, f->source + 0x1c); + } else { + put_unaligned_le64(f->next, f->source); + } + p->size = sizeof(f->source); + memcpy(p->data, f->source, p->size); + p->counter = 1000 + f->next; + p->ns = 100 + f->next; + f->next++; + /* Model immediate firmware reuse after the private copy/ACK. */ + memset(f->source, 0xa5, sizeof(f->source)); + if (f->notify) { + ane_fw_irq_event_notify(f->notify, 0); + f->notify = NULL; + } + return 0; +} + +static void fifo_copy_budget_and_order_test(struct kunit *test) +{ + struct ane_fw_report_fifo q = {}; + struct fifo_source f = { .available = 6 }; + struct ane_fw_report p; + bool progress; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_init(&q), 0); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 4, &progress), 0); + KUNIT_EXPECT_TRUE(test, progress); + KUNIT_EXPECT_EQ(test, f.calls, 4U); + KUNIT_EXPECT_EQ(test, q.peak, 4U); + for (i = 0; i < 4; i++) { + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_pop(&q, &p), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p.data), (u64)i); + KUNIT_EXPECT_EQ(test, p.counter, 1000ULL + i); + KUNIT_EXPECT_EQ(test, p.ns, 100ULL + i); + } + /* FIFO reads themselves must never touch the still-live source. */ + KUNIT_EXPECT_EQ(test, f.calls, 4U); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 4, &progress), 0); + KUNIT_EXPECT_EQ(test, f.calls, 7U); /* two reports plus EAGAIN */ + for (i = 4; i < 6; i++) { + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_pop(&q, &p), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p.data), (u64)i); + } + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_pop(&q, &p), -EAGAIN); + KUNIT_EXPECT_EQ(test, q.captured, 6U); + ane_fw_report_fifo_free(&q); +} + +static void fifo_full_never_captures_or_overwrites_test(struct kunit *test) +{ + struct ane_fw_report_fifo q = {}; + struct fifo_source f = { .available = ANE_FW_REPORT_FIFO_CAPACITY + 1 }; + struct ane_fw_report p; + bool progress; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_init(&q), 0); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, + ANE_FW_REPORT_FIFO_CAPACITY, &progress), 0); + KUNIT_EXPECT_EQ(test, q.peak, (u32)ANE_FW_REPORT_FIFO_CAPACITY); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 1, &progress), -ENOSPC); + KUNIT_EXPECT_EQ(test, f.calls, (unsigned int)ANE_FW_REPORT_FIFO_CAPACITY); + KUNIT_EXPECT_EQ(test, q.full_errors, 1U); + for (i = 0; i < ANE_FW_REPORT_FIFO_CAPACITY; i++) { + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_pop(&q, &p), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p.data), (u64)i); + } + /* Exercise wrap after consuming the full allocation. */ + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 1, &progress), 0); + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_pop(&q, &p), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p.data), (u64)ANE_FW_REPORT_FIFO_CAPACITY); + ane_fw_report_fifo_free(&q); +} + +static void fifo_error_and_completion_guard_test(struct kunit *test) +{ + struct ane_fw_report_fifo q = {}; + struct fifo_source f = { .available = 1, .error = -EIO }; + struct ane_fw_report p; + bool progress; + + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_init(&q), 0); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 4, &progress), -EIO); + KUNIT_EXPECT_TRUE(test, progress); + /* An early report survives a subsequent command/capture error. */ + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_complete(&q, 0), -EPROTO); + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_pop(&q, &p), 0); + KUNIT_EXPECT_EQ(test, p.counter, 1000ULL); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_complete(&q, 1), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_complete(&q, 0), 0); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_pop(&q, &p), -EAGAIN); + ane_fw_report_fifo_free(&q); +} + +static void fifo_irq_during_prefetch_prevents_lost_wait_test(struct kunit *test) +{ + struct ane_fw_report_fifo q = {}; + struct ane_fw_irq_event event; + struct fifo_source f = { .available = 1, .notify = &event }; + unsigned int sequence; + bool progress; + + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_init(&q), 0); + ane_fw_irq_event_init(&event); + sequence = ane_fw_irq_event_sequence(&event); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 4, &progress), 0); + KUNIT_EXPECT_EQ(test, ane_fw_irq_event_wait(&event, sequence, ms_to_ktime(1)), 1); + ane_fw_report_fifo_free(&q); +} + +static void fifo_uninitialized_never_captures_test(struct kunit *test) +{ + struct ane_fw_report_fifo q = {}; + struct fifo_source f = { .available = 1 }; + struct ane_fw_report p; + bool progress; + + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_pop(&q, &p), -EAGAIN); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 4, &progress), -EINVAL); + KUNIT_EXPECT_EQ(test, f.calls, 0U); + ane_fw_report_fifo_free(&q); +} + +/* Opaque FIFO preserves out-of-order terminal identities; actual UUID retirement + * remains the backend dispatcher's job and is covered separately on hardware. + */ +static void fifo_out_of_order_terminal_identity_test(struct kunit *test) +{ + struct ane_fw_report_fifo q = {}; + struct fifo_source f = { .available = 2, .reverse = true }; + struct ane_fw_report p; + bool progress; + + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_init(&q), 0); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_prefetch(&q, fifo_capture, &f, 4, &progress), 0); + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_pop(&q, &p), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p.data + 8), 2ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(p.data + 0x1c), 1U); + KUNIT_EXPECT_EQ(test, p.counter, 1000ULL); + KUNIT_ASSERT_EQ(test, ane_fw_report_fifo_pop(&q, &p), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p.data + 8), 1ULL); + KUNIT_EXPECT_EQ(test, p.counter, 1001ULL); + KUNIT_EXPECT_EQ(test, ane_fw_report_fifo_complete(&q, 0), 0); + ane_fw_report_fifo_free(&q); +} + +static struct kunit_case fifo_cases[] = { + KUNIT_CASE(fifo_copy_budget_and_order_test), + KUNIT_CASE(fifo_full_never_captures_or_overwrites_test), + KUNIT_CASE(fifo_error_and_completion_guard_test), + KUNIT_CASE(fifo_irq_during_prefetch_prevents_lost_wait_test), + KUNIT_CASE(fifo_uninitialized_never_captures_test), + KUNIT_CASE(fifo_out_of_order_terminal_identity_test), + {} +}; +static struct kunit_suite fifo_suite = { .name = "ane-fw-report-fifo", .test_cases = fifo_cases }; +kunit_test_suite(fifo_suite); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_transport.h b/drivers/accel/ane/ane_fw_transport.h new file mode 100644 index 0000000000000..34a4aae51424b --- /dev/null +++ b/drivers/accel/ane/ane_fw_transport.h @@ -0,0 +1,633 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_FW_TRANSPORT_H__ +#define __ANE_FW_TRANSPORT_H__ + +#include "ane_fw_platform.h" +#include "ane_fw_protocol.h" + +#define ANE_FW_TERMINAL 0 +#define ANE_FW_IO 1 +#define ANE_FW_SHAREDMALLOC 5 +#define ANE_FW_IO_T2H 6 +#define ANE_FW_DATA_CHAIN 7 +#define ANE_FW_SHARED_MAX 64 +#define ANE_FW_SHARED_LIMIT SZ_1M +#define ANE_FW_SHARED_TOTAL (12 * SZ_1M) +#define ANE_FW_SHARED_EXPP 0x45585050U + +struct ane_fw_surface { + void *cpu; + u64 dva; + size_t size; +}; + +/* + * Accessors operate on coherent owned memory and engine-relative registers. + * Barriers must supply DMA read/write ordering, not just compiler ordering. + * alloc returns a zeroed, pinned, private-domain mapping of exactly size bytes. + * It and its caller retain every mapping, including a rejected result, until + * reset. refused must log the tuple and error without exposing private data. + */ +struct ane_fw_transport_ops { + u64 (*load64)(void *ctx, const void *p); + void (*store64)(void *ctx, void *p, u64 value); + void (*read_barrier)(void *ctx); + void (*write_barrier)(void *ctx); + u32 (*read32)(void *ctx, u32 reg); + void (*write32)(void *ctx, u32 reg, u32 value); + u64 (*now_ns)(void *ctx); + void (*relax)(void *ctx); + int (*alloc)(void *ctx, size_t size, u32 tag, struct ane_fw_surface *surface); + void (*refused)(void *ctx, u64 word0, u64 word1, u64 word2, int error); +}; + +struct ane_fw_transaction { + u64 dva; + u64 deadline_ns; + u64 rung_ns; + u32 rerings; + size_t size; + u16 id; + bool active; +}; + +/* A doorbell the firmware misses while it initializes is not repeated by it. */ +#define ANE_FW_RERING_NS (10 * NSEC_PER_MSEC) + +/* Caller serializes all entry points. No surface is released by this object. */ +struct ane_fw_transport { + const struct ane_fw_transport_ops *ops; + const struct ane_fw_platform *soc; + void *ctx; + struct ane_fw_surface ipc; + struct ane_fw_surface pool; + struct ane_fw_surface shared[ANE_FW_SHARED_MAX]; + struct ane_fw_channel channels[ANE_FW_CHANNELS]; + struct ane_fw_transaction pending[ANE_FW_CHANNELS]; + u32 head[ANE_FW_CHANNELS]; + u8 table[ANE_FW_TABLE_SIZE]; + size_t table_offset; + size_t pool_used; + size_t shared_bytes; + u32 shared_count; + u64 terminal_messages; + u64 terminal_bytes; + /* Caller owns the drain scope; IRQ handler never accesses these fields. */ + u64 report_ack_slots, report_ack_doorbells; + u32 report_ack_pending, report_ack_peak; + bool report_ack_defer; + int error; + bool armed; + bool native_free; + bool shared_retired[ANE_FW_SHARED_MAX]; +}; + +static inline bool ane_fw_surface_valid(const struct ane_fw_surface *s) +{ + return s->cpu && s->size && s->size <= U64_MAX - s->dva; +} + +static inline bool +ane_fw_surfaces_overlap(const struct ane_fw_surface *a, const struct ane_fw_surface *b) +{ + return a->dva < b->dva + b->size && b->dva < a->dva + a->size; +} + +static inline int ane_fw_transport_fail(struct ane_fw_transport *t, int error) +{ + if (!t->error) + t->error = error; + return t->error; +} + +/* pool_reserved protects the init record and any other boot-owned pool bytes. */ +static inline int +ane_fw_transport_init(struct ane_fw_transport *t, const struct ane_fw_platform *soc, + const struct ane_fw_transport_ops *ops, void *ctx, + struct ane_fw_surface ipc, struct ane_fw_surface pool, + size_t pool_reserved, u64 table_dva, size_t table_size) +{ + int ret; + + if (!t || !soc || !ops || !ops->load64 || !ops->store64 || + !ops->read_barrier || !ops->write_barrier || !ops->read32 || + !ops->write32 || !ops->now_ns || !ops->relax || !ops->alloc || + !ops->refused || !ane_fw_surface_valid(&ipc) || + !ane_fw_surface_valid(&pool) || ane_fw_surfaces_overlap(&ipc, &pool) || + !IS_ALIGNED(pool.dva, ANE_FW_SLOT_SIZE) || pool_reserved > pool.size || + table_size != ANE_FW_TABLE_SIZE || + !ane_fw_contains(ipc.dva, ipc.size, table_dva, table_size)) + return -EINVAL; + memset(t, 0, sizeof(*t)); + t->ops = ops; + t->soc = soc; + t->ctx = ctx; + t->ipc = ipc; + t->pool = pool; + t->pool_used = pool_reserved; + t->table_offset = table_dva - ipc.dva; + ops->read_barrier(ctx); + memcpy(t->table, (u8 *)ipc.cpu + t->table_offset, sizeof(t->table)); + ret = ane_fw_channels_parse(t->table, ipc.dva, ipc.size, table_dva, t->channels); + return ret ? ane_fw_transport_fail(t, ret) : 0; +} + +static inline int ane_fw_transport_check(struct ane_fw_transport *t) +{ + if (t->error) + return t->error; + t->ops->read_barrier(t->ctx); + if (memcmp(t->table, (u8 *)t->ipc.cpu + t->table_offset, sizeof(t->table))) + return ane_fw_transport_fail(t, -EPROTO); + return 0; +} + +static inline void *ane_fw_transport_slot(struct ane_fw_transport *t, unsigned int ch) +{ + return (u8 *)t->ipc.cpu + t->channels[ch].offset + + t->head[ch] * ANE_FW_SLOT_SIZE; +} + +static inline void ane_fw_transport_advance(struct ane_fw_transport *t, unsigned int ch) +{ + t->head[ch] = (t->head[ch] + 1) % t->channels[ch].slots; +} + +static inline void ane_fw_transport_doorbell(struct ane_fw_transport *t, unsigned int ch) +{ + t->ops->write32(t->ctx, t->soc->doorbell, BIT(t->channels[ch].bit)); +} + +/* Each ownership store already has its original trailing DMA write barrier. + * Flush even after a sticky transport error: previously returned slots still + * need their notification. No ownership writes or new delay are added here. + */ +static inline void ane_fw_report_ack_flush(struct ane_fw_transport *t) +{ + if (!t->report_ack_pending) + return; + ane_fw_transport_doorbell(t, ANE_FW_IO_T2H); + t->report_ack_doorbells++; + t->report_ack_pending = 0; +} + +static inline bool ane_fw_report_batch_eligible(bool mode, u32 outstanding, bool pipelined) +{ + return mode && outstanding == 1 && !pipelined; +} + +static inline void ane_fw_report_batch_end(struct ane_fw_transport *t) +{ + t->report_ack_defer = false; + ane_fw_report_ack_flush(t); +} + +static inline int ane_fw_transport_arm(struct ane_fw_transport *t) +{ + unsigned int ch, i; + int ret = ane_fw_transport_check(t); + + if (ret) + return ret; + if (t->armed) + return -EBUSY; + for (ch = 0; ch < ANE_FW_CHANNELS; ch++) { + const struct ane_fw_channel *c = &t->channels[ch]; + + if (c->type) + continue; + for (i = 0; i < c->slots; i++) { + u8 *p = (u8 *)t->ipc.cpu + c->offset + i * ANE_FW_SLOT_SIZE; + + t->ops->store64(t->ctx, p + 8, 0); + t->ops->store64(t->ctx, p + 16, 0); + t->ops->store64(t->ctx, p, 1); + } + } + t->ops->write_barrier(t->ctx); + t->armed = true; + return 0; +} + +/* Commands are copied into a monotonic pool arena, never external DMA memory. */ +static inline int +ane_fw_transport_publish(struct ane_fw_transport *t, unsigned int ch, + const void *command, size_t size, u64 deadline_ns) +{ + struct ane_fw_transaction *tx; + size_t offset; + u8 *p; + u64 header; + int ret = ane_fw_transport_check(t); + + if (ret) + return ret; + if (!t->armed || (ch != ANE_FW_IO && ch != ANE_FW_DATA_CHAIN) || + !command || size < 8 || get_unaligned_le32(command) || + get_unaligned_le16((const u8 *)command + 6)) + return -EINVAL; + tx = &t->pending[ch]; + if (tx->active) + return -EBUSY; + if (t->ops->now_ns(t->ctx) >= deadline_ns) + return ane_fw_transport_fail(t, -ETIMEDOUT); + p = ane_fw_transport_slot(t, ch); + header = t->ops->load64(t->ctx, p); + if (header & 2) + return ane_fw_transport_fail(t, -EPROTO); + if (!(header & 1)) + return -EBUSY; + if (t->pool_used > SIZE_MAX - (ANE_FW_SLOT_SIZE - 1)) + return -ENOSPC; + offset = ALIGN(t->pool_used, ANE_FW_SLOT_SIZE); + if (offset > t->pool.size || size > t->pool.size - offset) + return -ENOSPC; + memcpy((u8 *)t->pool.cpu + offset, command, size); + *tx = (struct ane_fw_transaction) { + .dva = t->pool.dva + offset, + .deadline_ns = deadline_ns, + .size = size, + .id = get_unaligned_le16((const u8 *)command + 4), + .active = true, + .rung_ns = t->ops->now_ns(t->ctx), + }; + t->pool_used = offset + size; + t->ops->store64(t->ctx, p + 8, size); + t->ops->store64(t->ctx, p + 16, size); + t->ops->write_barrier(t->ctx); + t->ops->store64(t->ctx, p, tx->dva); + t->ops->write_barrier(t->ctx); + ane_fw_transport_doorbell(t, ch); + return 0; +} + +/* On success/refusal the reply remains in the pool for the caller to inspect. */ +static inline int ane_fw_transport_poll(struct ane_fw_transport *t, unsigned int ch) +{ + struct ane_fw_transaction *tx; + u64 header, length, result; + u8 *p; + int ret = ane_fw_transport_check(t); + + if (ret) + return ret; + if (ch != ANE_FW_IO && ch != ANE_FW_DATA_CHAIN) + return -EINVAL; + tx = &t->pending[ch]; + if (!tx->active) + return -EINVAL; + if (t->ops->now_ns(t->ctx) >= tx->deadline_ns) + return ane_fw_transport_fail(t, -ETIMEDOUT); + p = ane_fw_transport_slot(t, ch); + header = t->ops->load64(t->ctx, p); + if (header & 2) + return ane_fw_transport_fail(t, -EPROTO); + if (!(header & 1)) { + if (header != tx->dva) + return ane_fw_transport_fail(t, -EPROTO); + return -EAGAIN; + } + t->ops->read_barrier(t->ctx); + length = t->ops->load64(t->ctx, p + 8); + result = t->ops->load64(t->ctx, p + 16); + ret = ane_fw_reply_status(header, length, result, tx->dva, tx->size, + tx->id, (u8 *)t->pool.cpu + (tx->dva - t->pool.dva), true); + if (ret) + return ane_fw_transport_fail(t, ret); + tx->active = false; + ane_fw_transport_advance(t, ch); + return 0; +} + +static inline bool ane_fw_transport_present(u64 word0, u64 word1) +{ + return !(word0 & 1) && (word0 || word1); +} + +static inline const void * +ane_fw_transport_report(struct ane_fw_transport *t, u64 dva, u64 size) +{ + const struct ane_fw_surface *s; + unsigned int i; + + for (i = 0; i < t->shared_count + 2; i++) { + if (i >= 2 && t->shared_retired[i - 2]) + continue; + s = i == 0 ? &t->ipc : i == 1 ? &t->pool : &t->shared[i - 2]; + if (ane_fw_contains(s->dva, s->size, dva, size)) + return (u8 *)s->cpu + (dva - s->dva); + } + return NULL; +} + +/* Optional diagnostic RAM timestamps; clock is ops->now_ns, not FW ticks. + * No additional transport reads/writes or changes to ownership ordering. + */ +struct ane_fw_consume_trace { + u64 ns[8]; /* post-check, ready, resolved, copied, copy barrier, ownership, doorbell, advance */ + u64 dva, length; + u32 slot; +}; + +/* Copy before acknowledging. UUID dispatch is deliberately above the transport. */ +static inline int +ane_fw_transport_consume_traced(struct ane_fw_transport *t, void *report, size_t capacity, + size_t *size, struct ane_fw_consume_trace *trace) +{ + const void *src; + u64 word0, word1, word2; + u8 *p; + int ret = ane_fw_transport_check(t); + + if (ret) + return ret; + if (trace) + trace->ns[0] = t->ops->now_ns(t->ctx); + if (!t->armed || !report || !size || (trace && t->report_ack_defer)) + return -EINVAL; + p = ane_fw_transport_slot(t, ANE_FW_IO_T2H); + word0 = t->ops->load64(t->ctx, p); + t->ops->read_barrier(t->ctx); + word1 = t->ops->load64(t->ctx, p + 8); + if (!ane_fw_transport_present(word0, word1)) + return -EAGAIN; + if (trace) + trace->ns[1] = t->ops->now_ns(t->ctx); + t->ops->read_barrier(t->ctx); + word2 = t->ops->load64(t->ctx, p + 16); + if ((word0 & 3) || word1 < 8 || word2) + return ane_fw_transport_fail(t, -EPROTO); + src = ane_fw_transport_report(t, word0, word1); + if (!src) + return ane_fw_transport_fail(t, -EPROTO); + if (word1 > capacity) + return -ENOSPC; + if (trace) { + trace->dva = word0; + trace->length = word1; + trace->slot = t->head[ANE_FW_IO_T2H]; + trace->ns[2] = t->ops->now_ns(t->ctx); + } + memcpy(report, src, word1); + if (trace) + trace->ns[3] = t->ops->now_ns(t->ctx); + *size = word1; + /* The copy must finish before firmware is allowed to recycle the report. */ + t->ops->write_barrier(t->ctx); + if (trace) + trace->ns[4] = t->ops->now_ns(t->ctx); + t->ops->store64(t->ctx, p, word0 | 1); + t->ops->write_barrier(t->ctx); + if (trace) + trace->ns[5] = t->ops->now_ns(t->ctx); + t->report_ack_slots++; + t->report_ack_pending++; + t->report_ack_peak = max(t->report_ack_peak, t->report_ack_pending); + /* Bound a burst even if unsolicited reports keep the ring nonempty. */ + if (!t->report_ack_defer || t->report_ack_pending >= 4) + ane_fw_report_ack_flush(t); + if (trace) + trace->ns[6] = t->ops->now_ns(t->ctx); + ane_fw_transport_advance(t, ANE_FW_IO_T2H); + if (trace) + trace->ns[7] = t->ops->now_ns(t->ctx); + return 0; +} + +static inline int +ane_fw_transport_consume(struct ane_fw_transport *t, void *report, size_t capacity, + size_t *size) +{ + return ane_fw_transport_consume_traced(t, report, capacity, size, NULL); +} + +/* 25F84 _IOProcessorChannelUnidirectionalReceive (0x929a260): type-2 + * TERMINAL owns a slot when bit0 is clear, masks pointer bits[1:0], and + * returns only header=1 to the producer. It does not echo the DVA or ring + * a doorbell. Drain at most one ring per service; retain all backing pages. + * Text is deliberately discarded here, avoiding firmware printf backpressure. + */ +static inline int ane_fw_transport_terminal(struct ane_fw_transport *t) +{ + unsigned int i; + int ret = ane_fw_transport_check(t); + + if (ret) + return ret; + if (!t->armed) + return -EINVAL; + if (t->channels[ANE_FW_TERMINAL].type != 2) + return 0; + for (i = 0; i < t->channels[ANE_FW_TERMINAL].slots; i++) { + u8 *slot = ane_fw_transport_slot(t, ANE_FW_TERMINAL); + u64 header = t->ops->load64(t->ctx, slot), bytes, dva; + + t->ops->read_barrier(t->ctx); + if (header & 1) + break; + bytes = t->ops->load64(t->ctx, slot + 8); + dva = header & ~3ULL; + if (bytes && !ane_fw_transport_report(t, dva, bytes)) + return ane_fw_transport_fail(t, -EPROTO); + t->terminal_messages++; + t->terminal_bytes += bytes; + t->ops->write_barrier(t->ctx); + t->ops->store64(t->ctx, slot, 1); + t->ops->write_barrier(t->ctx); + ane_fw_transport_advance(t, ANE_FW_TERMINAL); + } + return 0; +} + +/* Conservative default allocation policy. Native FREE requires build opt-in. */ +static inline int ane_fw_shared_size(u64 word0, u64 bytes, u64 tag, size_t *size) +{ + if (word0 || !bytes) + return -EOPNOTSUPP; + if (tag > U32_MAX) + return -E2BIG; + if (bytes > ANE_FW_SHARED_LIMIT && + (bytes != SZ_2M || tag != ANE_FW_SHARED_EXPP)) + return -E2BIG; + *size = ALIGN(bytes, SZ_16K); + return 0; +} + +/* H16 26A428 native FREE, r5 section 6. Reply before revoking authority. + * The backend retains backing storage, mappings and quota until reset. + */ +static inline int +ane_fw_transport_native_free(struct ane_fw_transport *t, void *slot, u64 dva) +{ + unsigned int i; + + for (i = 0; i < t->shared_count; i++) + if (!t->shared_retired[i] && dva == t->shared[i].dva) + break; + if (i == t->shared_count) + return -ENOENT; + t->ops->store64(t->ctx, (u8 *)slot + 8, 0); + t->ops->store64(t->ctx, (u8 *)slot + 16, 0); + t->ops->write_barrier(t->ctx); + t->ops->store64(t->ctx, slot, 1); + t->ops->write_barrier(t->ctx); + ane_fw_transport_doorbell(t, ANE_FW_SHAREDMALLOC); + t->shared_retired[i] = true; + ane_fw_transport_advance(t, ANE_FW_SHAREDMALLOC); + return 0; +} + +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; + u8 *p; + int ret = ane_fw_transport_check(t); + + if (ret) + return ret; + if (!t->armed) + return -EINVAL; + p = ane_fw_transport_slot(t, ANE_FW_SHAREDMALLOC); + word0 = t->ops->load64(t->ctx, p); + t->ops->read_barrier(t->ctx); + word1 = t->ops->load64(t->ctx, p + 8); + if (word0 & 1) + return -EAGAIN; + t->ops->read_barrier(t->ctx); + word2 = t->ops->load64(t->ctx, p + 16); + if (!word0 && !word1 && !word2) + return -EAGAIN; + if (t->native_free && word0) { + ret = ane_fw_transport_native_free(t, p, word0); + if (ret) + goto refused; + return 0; + } + ret = ane_fw_shared_size(word0, word1, word2, &size); + if (ret) + goto refused; + 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); + 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[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->write_barrier(t->ctx); + t->ops->store64(t->ctx, p, s.dva | 1); + t->ops->write_barrier(t->ctx); + ane_fw_transport_doorbell(t, ANE_FW_SHAREDMALLOC); + ane_fw_transport_advance(t, ANE_FW_SHAREDMALLOC); + return 0; +refused: + t->ops->refused(t->ctx, word0, word1, word2, ret); + return ane_fw_transport_fail(t, ret); +} + +/* Drain one coalesced IRQ's allocation requests before sleeping. Bound a + * pass by the ring size; caller rechecks target/deadline after any progress. + */ +static inline int ane_fw_transport_shared_drain(struct ane_fw_transport *t, + bool *progress) +{ + unsigned int i; + int ret = ane_fw_transport_check(t); + + if (ret) + return ret; + if (!progress || !t->armed) + return -EINVAL; + *progress = false; + for (i = 0; i < t->channels[ANE_FW_SHAREDMALLOC].slots; i++) { + ret = ane_fw_transport_shared(t); + if (ret == -EAGAIN) + return 0; + if (ret) + return ret; + *progress = true; + } + return 0; +} + +/* Read once, reject unknown channels, acknowledge exactly that snapshot. */ +static inline int ane_fw_transport_irq(struct ane_fw_transport *t, u32 *pending) +{ + u32 value; + + if (t->error) + return t->error; + if (!pending) + return -EINVAL; + value = t->ops->read32(t->ctx, t->soc->irq_status); + if (value & ~GENMASK(7, 0)) + return ane_fw_transport_fail(t, -EPROTO); + *pending = value; + if (value) + t->ops->write32(t->ctx, t->soc->irq_ack, value); + return 0; +} + +/* + * Ring a still-pending command's doorbell again after ANE_FW_RERING_NS. Only + * called while the slot is still the firmware's (poll returned -EAGAIN). + */ +static inline void ane_fw_transport_rering(struct ane_fw_transport *t, unsigned int ch) +{ + struct ane_fw_transaction *tx = &t->pending[ch]; + u64 now = t->ops->now_ns(t->ctx); + + if (!tx->active || now - tx->rung_ns < ANE_FW_RERING_NS) + return; + tx->rung_ns = now; + tx->rerings++; + ane_fw_transport_doorbell(t, ch); +} + +/* The original absolute command deadline survives every provider/IRQ service. */ +static inline int ane_fw_transport_wait(struct ane_fw_transport *t, unsigned int ch) +{ + u32 pending; + int ret; + + for (;;) { + ret = ane_fw_transport_poll(t, ch); + if (ret != -EAGAIN) + return ret; + ret = ane_fw_transport_irq(t, &pending); + if (ret) + return ret; + ret = ane_fw_transport_shared(t); + if (ret && ret != -EAGAIN) + return ret; + ret = ane_fw_transport_terminal(t); + if (ret) + return ret; + /* Recheck before sleeping, including time spent in alloc(). */ + if (t->ops->now_ns(t->ctx) >= t->pending[ch].deadline_ns) + return ane_fw_transport_fail(t, -ETIMEDOUT); + ane_fw_transport_rering(t, ch); + t->ops->relax(t->ctx); + } +} + +#endif /* __ANE_FW_TRANSPORT_H__ */ diff --git a/drivers/accel/ane/ane_fw_transport_test.c b/drivers/accel/ane/ane_fw_transport_test.c new file mode 100644 index 0000000000000..94478dfcfd1f6 --- /dev/null +++ b/drivers/accel/ane/ane_fw_transport_test.c @@ -0,0 +1,1707 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include + +#include "ane_fw_transport.h" +#include "ane_fw_irq_wait.h" +#include "ane_fw_irq_coalesce.h" +#include "ane_fw_pending.h" +#include "ane_job_gap.h" +#include "ane_fw_ack_pending.h" +#include "ane_h16_execute.h" + +#define TEST_IPC_DVA 0x100003d0000ULL +#define TEST_POOL_DVA 0x10000384000ULL +#define TEST_SHARED_DVA 0x10002000000ULL +#define TEST_IPC_SIZE SZ_64K +#define TEST_POOL_SIZE SZ_256K +#define TEST_RESERVED SZ_16K +#define TEST_DEADLINE 100ULL + +struct ane_test_access { + char kind; + const void *p; + u64 value; +}; + +struct ane_transport_test { + struct kunit *test; + struct ane_fw_transport t; + struct ane_fw_platform soc; + struct ane_fw_surface ipc; + struct ane_fw_surface pool; + struct ane_test_access access[128]; + unsigned int count; + u64 now, now_step; + u64 alloc_time; + u64 next_dva; + u32 irq; + u32 last_reg; + u32 last_value; + unsigned int allocs; + unsigned int refusals; + u64 refused[3]; + int refused_error; + int alloc_error; + int alloc_bad; +}; + +static void ane_test_access(struct ane_transport_test *f, char kind, const void *p, u64 value) +{ + if (f->count < ARRAY_SIZE(f->access)) + f->access[f->count++] = (struct ane_test_access) { kind, p, value }; +} + +static u64 ane_test_load(void *ctx, const void *p) +{ + struct ane_transport_test *f = ctx; + u64 value = get_unaligned_le64(p); + + ane_test_access(f, 'r', p, value); + return value; +} + +static void ane_test_store(void *ctx, void *p, u64 value) +{ + struct ane_transport_test *f = ctx; + + ane_test_access(f, 'w', p, value); + put_unaligned_le64(value, p); +} + +static void ane_test_rmb(void *ctx) +{ + ane_test_access(ctx, 'R', NULL, 0); +} + +static void ane_test_wmb(void *ctx) +{ + ane_test_access(ctx, 'W', NULL, 0); +} + +static u32 ane_test_read32(void *ctx, u32 reg) +{ + struct ane_transport_test *f = ctx; + + f->last_reg = reg; + ane_test_access(f, 'i', NULL, reg); + return f->irq; +} + +static void ane_test_write32(void *ctx, u32 reg, u32 value) +{ + struct ane_transport_test *f = ctx; + + f->last_reg = reg; + f->last_value = value; + ane_test_access(f, 'o', NULL, value); +} + +static u64 ane_test_now(void *ctx) +{ + struct ane_transport_test *f = ctx; + u64 now = f->now; + + f->now += f->now_step; + return now; +} + +static void ane_test_relax(void *ctx) +{ + ((struct ane_transport_test *)ctx)->now++; +} + +static int ane_test_alloc(void *ctx, size_t size, u32 tag, struct ane_fw_surface *s) +{ + struct ane_transport_test *f = ctx; + + f->allocs++; + f->now += f->alloc_time; + if (f->alloc_error) + return f->alloc_error; + *s = (struct ane_fw_surface) { + .cpu = kunit_kzalloc(f->test, size, GFP_KERNEL), + .dva = f->next_dva, + .size = size, + }; + if (!s->cpu) + return -ENOMEM; + f->next_dva += size; + switch (f->alloc_bad) { + case 1: + s->dva++; + break; + case 2: + s->size--; + break; + case 3: + s->dva = f->pool.dva; + break; + case 4: + s->dva = f->ipc.dva; + break; + case 5: + s->dva = U64_MAX - SZ_16K + 1; + break; + case 6: + s->cpu = NULL; + break; + } + return 0; +} + +static void ane_test_refused(void *ctx, u64 word0, u64 word1, u64 word2, int error) +{ + struct ane_transport_test *f = ctx; + + f->refusals++; + f->refused[0] = word0; + f->refused[1] = word1; + f->refused[2] = word2; + f->refused_error = error; +} + +static const struct ane_fw_transport_ops ane_test_ops = { + .load64 = ane_test_load, + .store64 = ane_test_store, + .read_barrier = ane_test_rmb, + .write_barrier = ane_test_wmb, + .read32 = ane_test_read32, + .write32 = ane_test_write32, + .now_ns = ane_test_now, + .relax = ane_test_relax, + .alloc = ane_test_alloc, + .refused = ane_test_refused, +}; + +static void ane_test_table(struct ane_transport_test *f) +{ + static const char * const names[] = { + "TERMINAL", "IO", "DEBUG", "BUF_H2T", "BUF_T2H", + "SHAREDMALLOC", "IO_T2H", "DATA_CHAIN_H2T", + }; + unsigned int i; + + memset(f->ipc.cpu, 0, f->ipc.size); + for (i = 0; i < ANE_FW_CHANNELS; i++) { + u8 *p = (u8 *)f->ipc.cpu + i * ANE_FW_DESCRIPTOR_SIZE; + + strscpy((char *)p, names[i], 64); + put_unaligned_le32(i == 0 ? 2 : (i >= 4 && i <= 6), p + 0x40); + put_unaligned_le32(i, p + 0x44); + put_unaligned_le64(2, p + 0x48); + put_unaligned_le64(f->ipc.dva + 0x800 + i * 0x80, p + 0x50); + } +} + +static int ane_test_init_transport(struct ane_transport_test *f) +{ + return ane_fw_transport_init(&f->t, &f->soc, &ane_test_ops, f, + f->ipc, f->pool, TEST_RESERVED, + f->ipc.dva, ANE_FW_TABLE_SIZE); +} + +static int ane_transport_test_init(struct kunit *test) +{ + struct ane_transport_test *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + + if (!f) + return -ENOMEM; + test->priv = f; + f->test = test; + f->soc.doorbell = 0x1884000; + f->soc.irq_status = 0x188c000; + f->soc.irq_ack = 0x1890000; + f->ipc = (struct ane_fw_surface) { + .cpu = kunit_kzalloc(test, TEST_IPC_SIZE, GFP_KERNEL), + .dva = TEST_IPC_DVA, + .size = TEST_IPC_SIZE, + }; + f->pool = (struct ane_fw_surface) { + .cpu = kunit_kzalloc(test, TEST_POOL_SIZE, GFP_KERNEL), + .dva = TEST_POOL_DVA, + .size = TEST_POOL_SIZE, + }; + if (!f->ipc.cpu || !f->pool.cpu) + return -ENOMEM; + f->next_dva = TEST_SHARED_DVA; + ane_test_table(f); + return ane_test_init_transport(f); +} + +static u8 *ane_test_slot(struct ane_transport_test *f, unsigned int ch) +{ + return ane_fw_transport_slot(&f->t, ch); +} + +static int ane_test_publish(struct ane_transport_test *f, unsigned int ch) +{ + u8 command[16] = {}; + + put_unaligned_le16(ch == ANE_FW_IO ? 3 : 0x2d, command + 4); + return ane_fw_transport_publish(&f->t, ch, command, sizeof(command), TEST_DEADLINE); +} + +static void ane_test_reply(struct ane_transport_test *f, unsigned int ch) +{ + const struct ane_fw_transaction *tx = &f->t.pending[ch]; + u8 *p = ane_test_slot(f, ch); + + put_unaligned_le64(tx->dva | 1, p); + put_unaligned_le64(tx->size, p + 8); + put_unaligned_le64(0, p + 16); +} + +static void ane_test_shared_request(struct ane_transport_test *f, u64 w0, u64 w1, u64 w2) +{ + u8 *p = ane_test_slot(f, ANE_FW_SHAREDMALLOC); + + put_unaligned_le64(w0, p); + put_unaligned_le64(w1, p + 8); + put_unaligned_le64(w2, p + 16); +} + +static unsigned int ane_test_writes(struct ane_transport_test *f) +{ + unsigned int i, n = 0; + + for (i = 0; i < f->count; i++) + if (f->access[i].kind == 'w' || f->access[i].kind == 'o') + n++; + return n; +} + +static void ane_transport_table_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + struct ane_fw_channel parsed[ANE_FW_CHANNELS]; + u8 *d = (u8 *)f->ipc.cpu + ANE_FW_DESCRIPTOR_SIZE; + unsigned int i; + int ret; + + for (i = 0; i < 15; i++) { + ane_test_table(f); + switch (i) { + case 0: + put_unaligned_le64(0, d + 0x48); + break; + case 1: + put_unaligned_le64(0x401, d + 0x48); + break; + case 2: + put_unaligned_le64(U64_MAX, d + 0x48); + break; + case 3: + put_unaligned_le64(f->ipc.dva, d + 0x50); + break; + case 4: + put_unaligned_le64(f->ipc.dva + 0x800, d + 0x50); + break; + case 5: + put_unaligned_le64(f->ipc.dva + f->ipc.size - 64, d + 0x50); + break; + case 6: + put_unaligned_le64(f->ipc.dva + 0x881, d + 0x50); + break; + case 7: + put_unaligned_le64(f->ipc.dva - 64, d + 0x50); + break; + case 8: + put_unaligned_le32(32, d + 0x44); + break; + case 9: + put_unaligned_le32(3, d + 0x40); + break; + case 10: + put_unaligned_le32(1, d + 0x40); + break; + case 11: + strscpy((char *)d, "TERMINAL", 64); + break; + case 12: + memset(d, 'A', 64); + break; + case 13: + strscpy((char *)d, "UNKNOWN", 64); + break; + case 14: + put_unaligned_le64(U64_MAX - 63, d + 0x50); + break; + } + memset(parsed, 0xa5, sizeof(parsed)); + ret = ane_fw_channels_parse(f->ipc.cpu, f->ipc.dva, f->ipc.size, + f->ipc.dva, parsed); + KUNIT_EXPECT_EQ_MSG(test, ret, -EPROTO, "mutation %u", i); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(parsed, 0xa5, sizeof(parsed)), NULL); + } + KUNIT_EXPECT_FALSE(test, ane_fw_contains(U64_MAX - 15, 64, U64_MAX - 15, 8)); +} + +static void ane_transport_table_roles_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int ch; + + for (ch = 5; ch <= 7; ch++) { + u8 *d = (u8 *)f->ipc.cpu + ch * ANE_FW_DESCRIPTOR_SIZE; + + ane_test_table(f); + put_unaligned_le32(ch == 7 ? 1 : 0, d + 0x40); + KUNIT_EXPECT_EQ(test, ane_test_init_transport(f), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_transport_arm(&f->t), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + } +} + +static void ane_transport_table_bounds_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + struct ane_fw_channel channels[ANE_FW_CHANNELS]; + unsigned int i; + int ret; + + for (i = 0; i < ANE_FW_TABLE_SIZE; i++) { + ret = ane_fw_transport_init(&f->t, &f->soc, &ane_test_ops, f, + f->ipc, f->pool, 0, f->ipc.dva, i); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + } + ret = ane_fw_transport_init(&f->t, &f->soc, &ane_test_ops, f, f->ipc, + f->pool, 0, f->ipc.dva, ANE_FW_TABLE_SIZE + 1); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_fw_channels_parse(f->ipc.cpu, f->ipc.dva, f->ipc.size, + f->ipc.dva + f->ipc.size - 64, channels); + KUNIT_EXPECT_EQ(test, ret, -EPROTO); + ret = ane_fw_channels_parse(NULL, f->ipc.dva, f->ipc.size, f->ipc.dva, channels); + KUNIT_EXPECT_EQ(test, ret, -EPROTO); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); +} + +static void ane_transport_table_edges_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 *d; + + /* One 0x400-slot ring fits exactly after a relocated table and seven slots. */ + f->ipc.size = 2 * TEST_IPC_SIZE; + f->ipc.cpu = kunit_kzalloc(test, f->ipc.size, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, f->ipc.cpu); + ane_test_table(f); + d = f->ipc.cpu; + put_unaligned_le64(0x400, d + 0x48); + put_unaligned_le64(f->ipc.dva + TEST_IPC_SIZE, d + 0x50); + put_unaligned_le32(31, d + 0x44); + KUNIT_EXPECT_EQ(test, ane_test_init_transport(f), 0); + put_unaligned_le64(1, d + 0x48); + put_unaligned_le64(f->ipc.dva + ANE_FW_TABLE_SIZE, d + 0x50); + KUNIT_EXPECT_EQ(test, ane_test_init_transport(f), 0); +} + +static void ane_transport_arm_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int ch, slot, n = 1; + + memset((u8 *)f->ipc.cpu + 0x800, 0xa5, 0x400); + f->count = 0; + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + for (ch = 0; ch < ANE_FW_CHANNELS; ch++) { + for (slot = 0; slot < 2; slot++) { + u8 *p = ane_test_slot(f, ch) + slot * ANE_FW_SLOT_SIZE; + + if (f->t.channels[ch].type) { + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(p, 0xa5, 64), NULL); + continue; + } + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), 1ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 8), 0ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 16), 0ULL); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(p + 24, 0xa5, 40), NULL); + KUNIT_EXPECT_PTR_EQ(test, f->access[n++].p, p + 8); + KUNIT_EXPECT_PTR_EQ(test, f->access[n++].p, p + 16); + KUNIT_EXPECT_PTR_EQ(test, f->access[n++].p, p); + } + } + KUNIT_EXPECT_EQ(test, f->access[n].kind, 'W'); + KUNIT_EXPECT_EQ(test, ane_fw_transport_arm(&f->t), -EBUSY); +} + +static void ane_transport_publish_order_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int ch; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + for (ch = ANE_FW_IO; ch <= ANE_FW_DATA_CHAIN; ch += 6) { + u8 *p = ane_test_slot(f, ch); + u64 dva; + + f->count = 0; + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ch), 0); + dva = get_unaligned_le64(p); + KUNIT_EXPECT_TRUE(test, ane_fw_contains(f->pool.dva, f->pool.size, dva, 16)); + KUNIT_EXPECT_GE(test, dva, f->pool.dva + TEST_RESERVED); + KUNIT_EXPECT_EQ(test, dva & 63, 0ULL); + KUNIT_EXPECT_EQ(test, f->access[2].kind, 'w'); + KUNIT_EXPECT_PTR_EQ(test, f->access[2].p, p + 8); + KUNIT_EXPECT_EQ(test, f->access[2].value, 16ULL); + KUNIT_EXPECT_PTR_EQ(test, f->access[3].p, p + 16); + KUNIT_EXPECT_EQ(test, f->access[3].value, 16ULL); + KUNIT_EXPECT_EQ(test, f->access[4].kind, 'W'); + KUNIT_EXPECT_PTR_EQ(test, f->access[5].p, p); + KUNIT_EXPECT_EQ(test, f->access[5].value, dva); + KUNIT_EXPECT_EQ(test, f->access[6].kind, 'W'); + KUNIT_EXPECT_EQ(test, f->access[7].kind, 'o'); + KUNIT_EXPECT_EQ(test, f->last_reg, f->soc.doorbell); + KUNIT_EXPECT_EQ(test, f->last_value, (u32)BIT(ch)); + KUNIT_EXPECT_EQ(test, ane_test_publish(f, ch), -EBUSY); + KUNIT_EXPECT_EQ(test, ane_fw_transport_poll(&f->t, ch), -EAGAIN); + ane_test_reply(f, ch); + KUNIT_EXPECT_EQ(test, ane_fw_transport_poll(&f->t, ch), 0); + KUNIT_EXPECT_EQ(test, f->t.head[ch], 1U); + } +} + +static void ane_transport_wrap_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + for (i = 0; i < 5; i++) { + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_DATA_CHAIN), 0); + ane_test_reply(f, ANE_FW_DATA_CHAIN); + KUNIT_ASSERT_EQ(test, ane_fw_transport_poll(&f->t, ANE_FW_DATA_CHAIN), 0); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_DATA_CHAIN], (i + 1) % 2); + } +} + +static void ane_transport_reply_corruption_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int i; + + for (i = 0; i < 8; i++) { + u8 *p, *command; + u64 dva; + + KUNIT_ASSERT_EQ(test, ane_test_init_transport(f), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_IO), 0); + ane_test_reply(f, ANE_FW_IO); + p = ane_test_slot(f, ANE_FW_IO); + dva = f->t.pending[ANE_FW_IO].dva; + command = (u8 *)f->pool.cpu + (dva - f->pool.dva); + switch (i) { + case 0: + put_unaligned_le64(dva | 3, p); + break; + case 1: + put_unaligned_le64(dva | 2, p); + break; + case 2: + put_unaligned_le64((dva + 64) | 1, p); + break; + case 3: + put_unaligned_le64(15, p + 8); + break; + case 4: + put_unaligned_le64(1, p + 16); + break; + case 5: + put_unaligned_le32(0x1000000, command); + break; + case 6: + put_unaligned_le16(4, command + 4); + break; + case 7: + put_unaligned_le64(dva + 64, p); + break; + } + KUNIT_EXPECT_EQ_MSG(test, ane_fw_transport_poll(&f->t, ANE_FW_IO), + -EPROTO, "mutation %u", i); + KUNIT_EXPECT_TRUE(test, f->t.pending[ANE_FW_IO].active); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_IO], 0U); + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_test_publish(f, ANE_FW_DATA_CHAIN), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + } +} + +static void ane_transport_refusal_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 *command; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_IO), 0); + command = (u8 *)f->pool.cpu + (f->t.pending[ANE_FW_IO].dva - f->pool.dva); + ane_test_reply(f, ANE_FW_IO); + put_unaligned_le16(0x100, command + 6); + KUNIT_EXPECT_EQ(test, ane_fw_transport_poll(&f->t, ANE_FW_IO), -EREMOTEIO); + KUNIT_EXPECT_TRUE(test, f->t.pending[ANE_FW_IO].active); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_IO], 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(command + 6), (u16)0x100); +} + +static void ane_transport_pool_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 command[16] = {}; + + KUNIT_EXPECT_EQ(test, ane_test_publish(f, ANE_FW_IO), -EINVAL); + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_publish(&f->t, 2, command, 16, 100), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_fw_transport_publish(&f->t, 1, NULL, 16, 100), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_fw_transport_publish(&f->t, 1, command, 7, 100), -EINVAL); + command[0] = 1; + KUNIT_EXPECT_EQ(test, ane_fw_transport_publish(&f->t, 1, command, 16, 100), -EINVAL); + command[0] = 0; + command[6] = 1; + KUNIT_EXPECT_EQ(test, ane_fw_transport_publish(&f->t, 1, command, 16, 100), -EINVAL); + command[6] = 0; + memset(f->pool.cpu, 0xa5, TEST_RESERVED); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_IO), 0); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(f->pool.cpu, 0xa5, TEST_RESERVED), NULL); + ane_test_reply(f, ANE_FW_IO); + KUNIT_ASSERT_EQ(test, ane_fw_transport_poll(&f->t, ANE_FW_IO), 0); + f->t.pool_used = f->pool.size - 1; + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_test_publish(f, ANE_FW_IO), -ENOSPC); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + f->t.pool_used = SIZE_MAX; + KUNIT_EXPECT_EQ(test, ane_test_publish(f, ANE_FW_IO), -ENOSPC); +} + +static void ane_transport_snapshot_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + + ((u8 *)f->ipc.cpu)[0x58] = 1; + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_fw_transport_arm(&f->t), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); +} + +static void ane_transport_report_request(struct ane_transport_test *f, u64 dva, u64 size) +{ + u8 *p = ane_test_slot(f, ANE_FW_IO_T2H); + + put_unaligned_le64(dva, p); + put_unaligned_le64(size, p + 8); + put_unaligned_le64(0, p + 16); +} + +static void ane_transport_consume_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + struct ane_h16_request_key key = { .uuid = 9, .program = 1, .process = 2 }; + u8 report[0x60] = {}; + u8 *source = (u8 *)f->pool.cpu + 0x100; + u8 *p; + size_t size = 0; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), + -EAGAIN); + put_unaligned_le16(0x300, source + 4); + put_unaligned_le64(key.uuid, source + 8); + put_unaligned_le32(key.program, source + 0x10); + put_unaligned_le32(key.process, source + 0x14); + put_unaligned_le32(1, source + 0x1c); + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + p = ane_test_slot(f, ANE_FW_IO_T2H); + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume(&f->t, report, 8, &size), -ENOSPC); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), f->pool.dva + 0x100); + f->count = 0; + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), 0); + KUNIT_EXPECT_MEMEQ(test, report, source, sizeof(report)); + KUNIT_EXPECT_EQ(test, size, sizeof(report)); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), (f->pool.dva + 0x100) | 1); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 8), 0x60ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 16), 0ULL); + KUNIT_EXPECT_EQ(test, f->access[f->count - 4].kind, 'W'); + KUNIT_EXPECT_PTR_EQ(test, f->access[f->count - 3].p, p); + KUNIT_EXPECT_EQ(test, f->access[f->count - 2].kind, 'W'); + KUNIT_EXPECT_EQ(test, f->last_value, (u32)BIT(6)); + KUNIT_EXPECT_EQ(test, ane_h16_event_result(report, size, 6, &key), + ANE_H16_EVENT_COMPLETE); + /* A stale UUID is consumed, but cannot retire the current pending request. */ + key.uuid++; + KUNIT_EXPECT_EQ(test, ane_h16_event_result(report, size, 6, &key), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), + -EAGAIN); +} + +static void ane_transport_consume_trace_order_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + struct ane_test_access access[16]; + struct ane_fw_consume_trace trace; + u8 report[0x60], *p; + size_t size = 0; + u32 count, i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + p = ane_test_slot(f, ANE_FW_IO_T2H); + f->count = 0; + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), 0); + count = f->count; + KUNIT_ASSERT_LE(test, count, (u32)ARRAY_SIZE(access)); + memcpy(access, f->access, count * sizeof(access[0])); + /* Replay the same slot, proving tracing does not add or reorder transport access. */ + f->t.head[ANE_FW_IO_T2H] = 0; + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + f->count = 0; + f->now = 42; + f->now_step = 1; + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume_traced(&f->t, report, + sizeof(report), &size, &trace), 0); + KUNIT_ASSERT_EQ(test, f->count, count); + for (i = 0; i < count; i++) { + KUNIT_EXPECT_EQ(test, f->access[i].kind, access[i].kind); + KUNIT_EXPECT_PTR_EQ(test, f->access[i].p, access[i].p); + KUNIT_EXPECT_EQ(test, f->access[i].value, access[i].value); + } + KUNIT_EXPECT_EQ(test, trace.dva, f->pool.dva + 0x100); + KUNIT_EXPECT_EQ(test, trace.length, sizeof(report)); + KUNIT_EXPECT_EQ(test, trace.slot, 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), trace.dva | 1); + for (i = 0; i < ARRAY_SIZE(trace.ns); i++) + KUNIT_EXPECT_EQ(test, trace.ns[i], 42ULL + i); + KUNIT_EXPECT_EQ(test, f->now, 50ULL); +} + +static void ane_transport_consume_trace_refusal_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + struct ane_fw_consume_trace trace; + u8 report[0x60], *p; + size_t size = 0; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume_traced(&f->t, report, + sizeof(report), &size, &trace), -EAGAIN); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_IO_T2H], 0U); + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + p = ane_test_slot(f, ANE_FW_IO_T2H); + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume_traced(&f->t, report, + 8, &size, &trace), -ENOSPC); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_IO_T2H], 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), f->pool.dva + 0x100); + put_unaligned_le64(1, p + 16); + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume_traced(&f->t, report, + sizeof(report), &size, &trace), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_IO_T2H], 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), f->pool.dva + 0x100); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 16), 1ULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); +} + +static void ane_transport_report_bounds_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 report[0x60]; + size_t size; + unsigned int i; + int ret; + + for (i = 0; i < 7; i++) { + u64 dva = f->pool.dva, bytes = sizeof(report); + + KUNIT_ASSERT_EQ(test, ane_test_init_transport(f), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + switch (i) { + case 0: + dva += 2; + break; + case 1: + dva = f->pool.dva + f->pool.size - 4; + break; + case 2: + dva = TEST_SHARED_DVA; + break; + case 3: + bytes = U64_MAX; + break; + case 4: + bytes = 0; + break; + case 5: + bytes = 7; + break; + case 6: + dva = 0; + break; + } + ane_transport_report_request(f, dva, bytes); + f->count = 0; + ret = ane_fw_transport_consume(&f->t, report, sizeof(report), &size); + KUNIT_EXPECT_EQ_MSG(test, ret, -EPROTO, "mutation %u", i); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + } +} + +static void ane_transport_report_word2_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 report[12]; + size_t size; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + ane_transport_report_request(f, f->pool.dva, sizeof(report)); + put_unaligned_le64(1, ane_test_slot(f, ANE_FW_IO_T2H) + 16); + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), + -EPROTO); +} + +static void ane_transport_presence_test(struct kunit *test) +{ + KUNIT_EXPECT_FALSE(test, ane_fw_transport_present(0, 0)); + KUNIT_EXPECT_FALSE(test, ane_fw_transport_present(1, 0)); + KUNIT_EXPECT_FALSE(test, ane_fw_transport_present(0x1001, 96)); + KUNIT_EXPECT_TRUE(test, ane_fw_transport_present(0x1000, 0)); + KUNIT_EXPECT_TRUE(test, ane_fw_transport_present(0, 96)); + KUNIT_EXPECT_TRUE(test, ane_fw_transport_present(0x1000, 96)); +} + +static void ane_transport_shared_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 *p; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), -EAGAIN); + ane_test_shared_request(f, 0, 1, 0x1234); + p = ane_test_slot(f, ANE_FW_SHAREDMALLOC); + f->count = 0; + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), TEST_SHARED_DVA | 1); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 8), 0ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 16), 1ULL); + KUNIT_EXPECT_EQ(test, f->t.shared_bytes, (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, f->access[f->count - 6].value, 0ULL); + KUNIT_EXPECT_EQ(test, f->access[f->count - 5].value, 1ULL); + KUNIT_EXPECT_EQ(test, f->access[f->count - 4].kind, 'W'); + KUNIT_EXPECT_PTR_EQ(test, f->access[f->count - 3].p, p); + KUNIT_EXPECT_EQ(test, f->access[f->count - 2].kind, 'W'); + KUNIT_EXPECT_EQ(test, f->last_value, (u32)BIT(5)); + 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->t.shared_bytes, (size_t)(SZ_2M + SZ_16K)); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 2U); +} + +static void ane_transport_coalesced_shared_irq_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + struct ane_fw_irq_event event; + bool progress; + unsigned int sequence; + u8 *p; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + ane_fw_irq_event_init(&event); + sequence = ane_fw_irq_event_sequence(&event); + ane_test_shared_request(f, 0, SZ_16K, 0x1234); + p = ane_test_slot(f, ANE_FW_SHAREDMALLOC) + ANE_FW_SLOT_SIZE; + put_unaligned_le64(0, p); + put_unaligned_le64(SZ_16K, p + 8); + put_unaligned_le64(0x1235, p + 16); + /* One IRQ for both slots, between empty check and wait preparation. */ + ane_fw_irq_event_notify(&event, 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_drain(&f->t, &progress), 0); + KUNIT_EXPECT_TRUE(test, progress); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 2U); + KUNIT_EXPECT_EQ(test, ane_fw_irq_event_wait(&event, sequence, + ns_to_ktime(NSEC_PER_MSEC)), 1); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_drain(&f->t, &progress), 0); + KUNIT_EXPECT_FALSE(test, progress); +} + +static void ane_transport_shared_drain_refusal_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + bool progress; + u8 *p; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + ane_test_shared_request(f, 0, SZ_16K, 0x1234); + p = ane_test_slot(f, ANE_FW_SHAREDMALLOC) + ANE_FW_SLOT_SIZE; + put_unaligned_le64(2, p); + put_unaligned_le64(SZ_16K, p + 8); + put_unaligned_le64(0x1235, p + 16); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_drain(&f->t, &progress), -EOPNOTSUPP); + KUNIT_EXPECT_TRUE(test, progress); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 1U); +} + +static void ane_transport_shared_rejections_test(struct kunit *test) +{ + static const u64 tuples[][3] = { + { 0x10000, SZ_16K, 0 }, + { 0, 0, 1 }, + { 0, SZ_1M + 1, 0 }, + { 0, SZ_1M + 1, ANE_FW_SHARED_EXPP }, + { 0, SZ_2M, ANE_FW_SHARED_EXPP + 1 }, + { 0, SZ_2M + 1, ANE_FW_SHARED_EXPP }, + { 0, U64_MAX, 0 }, + { 0, SZ_16K, BIT_ULL(32) }, + }; + struct ane_transport_test *f = test->priv; + size_t size; + unsigned int i; + + KUNIT_EXPECT_EQ(test, ane_fw_shared_size(0, 0, 0, &size), -EOPNOTSUPP); + for (i = 0; i < ARRAY_SIZE(tuples); i++) { + int error = i < 2 ? -EOPNOTSUPP : -E2BIG; + + KUNIT_ASSERT_EQ(test, ane_test_init_transport(f), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + ane_test_shared_request(f, tuples[i][0], tuples[i][1], tuples[i][2]); + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), error); + KUNIT_EXPECT_EQ(test, f->refusals, i + 1); + KUNIT_EXPECT_MEMEQ(test, f->refused, tuples[i], sizeof(f->refused)); + KUNIT_EXPECT_EQ(test, f->refused_error, error); + KUNIT_EXPECT_EQ(test, f->allocs, 0U); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + } +} + +static void ane_transport_allocator_rejections_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int i; + + for (i = 1; i <= 6; i++) { + KUNIT_ASSERT_EQ(test, ane_test_init_transport(f), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->alloc_bad = i; + ane_test_shared_request(f, 0, SZ_16K, 0); + f->count = 0; + KUNIT_EXPECT_EQ_MSG(test, ane_fw_transport_shared(&f->t), -EPROTO, + "allocator result %u", i); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 0U); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + } + KUNIT_ASSERT_EQ(test, ane_test_init_transport(f), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->alloc_error = -ENOMEM; + ane_test_shared_request(f, 0, SZ_16K, 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), -ENOMEM); +} + +static void ane_transport_shared_overlap_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + ane_test_shared_request(f, 0, SZ_16K, 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + f->next_dva = TEST_SHARED_DVA; + ane_test_shared_request(f, 0, SZ_16K, 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), -EPROTO); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 1U); +} + +static void ane_transport_shared_count_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + for (i = 0; i < ANE_FW_SHARED_MAX; i++) { + ane_test_shared_request(f, 0, SZ_16K, 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + } + ane_test_shared_request(f, 0, SZ_16K, 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), -ENOSPC); + KUNIT_EXPECT_EQ(test, f->allocs, (unsigned int)ANE_FW_SHARED_MAX); +} + +static void ane_transport_shared_total_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + for (i = 0; i < 12; i++) { + ane_test_shared_request(f, 0, SZ_1M, 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + } + KUNIT_EXPECT_EQ(test, f->t.shared_bytes, (size_t)ANE_FW_SHARED_TOTAL); + ane_test_shared_request(f, 0, 1, 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), -ENOSPC); + KUNIT_EXPECT_EQ(test, f->allocs, 12U); +} + +static void ane_transport_shared_report_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 report[12]; + size_t size; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + ane_test_shared_request(f, 0, SZ_16K, 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + put_unaligned_le16(0x107, (u8 *)f->t.shared[0].cpu + 4); + ane_transport_report_request(f, TEST_SHARED_DVA, sizeof(report)); + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(report + 4), (u16)0x107); + KUNIT_EXPECT_EQ(test, size, sizeof(report)); +} + +static void ane_transport_irq_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u32 pending = 0; + + f->count = 0; + KUNIT_ASSERT_EQ(test, ane_fw_transport_irq(&f->t, &pending), 0); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); + f->irq = 0xa5; + KUNIT_ASSERT_EQ(test, ane_fw_transport_irq(&f->t, &pending), 0); + KUNIT_EXPECT_EQ(test, pending, 0xa5U); + KUNIT_EXPECT_EQ(test, f->last_reg, f->soc.irq_ack); + KUNIT_EXPECT_EQ(test, f->last_value, 0xa5U); + f->irq = BIT(8) | 1; + f->count = 0; + KUNIT_EXPECT_EQ(test, ane_fw_transport_irq(&f->t, &pending), -EPROTO); + KUNIT_EXPECT_EQ(test, pending, 0xa5U); + KUNIT_EXPECT_EQ(test, ane_test_writes(f), 0U); +} + +static void ane_transport_match_data_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 *d = (u8 *)f->ipc.cpu + ANE_FW_DESCRIPTOR_SIZE; + u32 pending; + + f->soc.doorbell = 0x100; + f->soc.irq_status = 0x200; + f->soc.irq_ack = 0x300; + put_unaligned_le32(31, d + 0x44); + KUNIT_ASSERT_EQ(test, ane_test_init_transport(f), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_IO), 0); + KUNIT_EXPECT_EQ(test, f->last_reg, 0x100U); + KUNIT_EXPECT_EQ(test, f->last_value, (u32)BIT(31)); + f->irq = 0xff; + KUNIT_ASSERT_EQ(test, ane_fw_transport_irq(&f->t, &pending), 0); + KUNIT_EXPECT_EQ(test, f->last_reg, 0x300U); + KUNIT_EXPECT_EQ(test, f->last_value, 0xffU); +} + +static void ane_transport_deadline_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_IO), 0); + f->now = TEST_DEADLINE - 1; + KUNIT_EXPECT_EQ(test, ane_fw_transport_poll(&f->t, ANE_FW_IO), -EAGAIN); + f->now++; + ane_test_reply(f, ANE_FW_IO); + KUNIT_EXPECT_EQ(test, ane_fw_transport_poll(&f->t, ANE_FW_IO), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, f->t.pending[ANE_FW_IO].active); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_IO], 0U); +} + +static void ane_transport_deadline_service_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_DATA_CHAIN), 0); + f->now = TEST_DEADLINE - 1; + f->alloc_time = 2; + f->irq = BIT(5); + ane_test_shared_request(f, 0, SZ_16K, 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_wait(&f->t, ANE_FW_DATA_CHAIN), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 1U); + KUNIT_EXPECT_EQ(test, f->t.pending[ANE_FW_DATA_CHAIN].deadline_ns, TEST_DEADLINE); + KUNIT_EXPECT_TRUE(test, f->t.pending[ANE_FW_DATA_CHAIN].active); +} + +static void ane_transport_wait_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_IO), 0); + ane_test_reply(f, ANE_FW_IO); + KUNIT_EXPECT_EQ(test, ane_fw_transport_wait(&f->t, ANE_FW_IO), 0); + KUNIT_ASSERT_EQ(test, ane_test_publish(f, ANE_FW_DATA_CHAIN), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_wait(&f->t, ANE_FW_DATA_CHAIN), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, f->now, TEST_DEADLINE); +} + +static void ane_transport_terminal_ack_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 *slot, *next; + u32 last_reg; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + slot = ane_test_slot(f, ANE_FW_TERMINAL); + next = slot + ANE_FW_SLOT_SIZE; + put_unaligned_le64(TEST_POOL_DVA | 2, slot); + put_unaligned_le64(1, slot + 8); + put_unaligned_le64(4, slot + 16); + put_unaligned_le64(3, next); + last_reg = f->last_reg; + KUNIT_EXPECT_EQ(test, ane_fw_transport_terminal(&f->t), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(slot), 1ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(slot + 8), 1ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(slot + 16), 4ULL); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_TERMINAL], 1U); + KUNIT_EXPECT_EQ(test, f->t.terminal_messages, 1ULL); + KUNIT_EXPECT_EQ(test, f->t.terminal_bytes, 1ULL); + KUNIT_EXPECT_EQ(test, f->last_reg, last_reg); /* no ACK doorbell */ + KUNIT_EXPECT_EQ(test, ane_fw_transport_terminal(&f->t), 0); + KUNIT_EXPECT_EQ(test, f->t.terminal_messages, 1ULL); +} + +static void ane_transport_terminal_bounds_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 *slot; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + slot = ane_test_slot(f, ANE_FW_TERMINAL); + put_unaligned_le64(0xdead0002, slot); + put_unaligned_le64(1, slot + 8); + KUNIT_EXPECT_EQ(test, ane_fw_transport_terminal(&f->t), -EPROTO); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(slot), 0xdead0002ULL); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_TERMINAL], 0U); +} + +static void ane_transport_terminal_wrap_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 *slot; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + slot = ane_test_slot(f, ANE_FW_TERMINAL); + for (unsigned int i = 0; i < 2; i++) { + put_unaligned_le64(TEST_POOL_DVA | 2, slot + i * ANE_FW_SLOT_SIZE); + put_unaligned_le64(i + 1, slot + i * ANE_FW_SLOT_SIZE + 8); + } + KUNIT_EXPECT_EQ(test, ane_fw_transport_terminal(&f->t), 0); + KUNIT_EXPECT_EQ(test, f->t.head[ANE_FW_TERMINAL], 0U); + KUNIT_EXPECT_EQ(test, f->t.terminal_messages, 2ULL); + KUNIT_EXPECT_EQ(test, f->t.terminal_bytes, 3ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(slot), 1ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(slot + ANE_FW_SLOT_SIZE), 1ULL); +} + +struct ane_ack_pending_test { + char access[16]; + u32 used, writes, written, reads; + u64 counter; +}; + +static u64 ane_ack_test_counter(void *ctx) +{ + return ++((struct ane_ack_pending_test *)ctx)->counter; +} + +static u32 ane_ack_test_cpu(void *ctx) +{ + return 0; +} + +static u32 ane_ack_test_read(void *ctx) +{ + struct ane_ack_pending_test *f = ctx; + + f->access[f->used++] = 'R'; + return f->reads++ ? 0 : BIT(6); +} + +static void ane_ack_test_write(void *ctx, u32 value) +{ + struct ane_ack_pending_test *f = ctx; + + f->access[f->used++] = 'W'; + f->writes++; + f->written = value; +} + +static const struct ane_fw_ack_pending_ops ane_ack_test_ops = { + .counter = ane_ack_test_counter, + .cpu = ane_ack_test_cpu, + .read_pending = ane_ack_test_read, + .write_doorbell = ane_ack_test_write, +}; + +static void ane_ack_pending_read_order_test(struct kunit *test) +{ + struct ane_ack_pending_test f = {}; + struct ane_fw_ack_pending_trace t = {}; + u32 i; + + ane_fw_ack_pending_observe(&f, &ane_ack_test_ops, &t, 2, 6, BIT(6)); + KUNIT_EXPECT_MEMEQ(test, f.access, "RWR", 3); + KUNIT_EXPECT_EQ(test, f.used, 3U); + KUNIT_EXPECT_EQ(test, f.writes, 1U); + KUNIT_EXPECT_EQ(test, f.written, (u32)BIT(6)); + KUNIT_EXPECT_EQ(test, t.calls, 1U); + KUNIT_EXPECT_EQ(test, t.mode, 2U); + KUNIT_EXPECT_EQ(test, t.bit, 6U); + KUNIT_EXPECT_EQ(test, t.valid, 1U); + KUNIT_EXPECT_EQ(test, t.before_value, (u32)BIT(6)); + KUNIT_EXPECT_EQ(test, t.after_value, 0U); + for (i = 0; i < ARRAY_SIZE(t.counters); i++) + KUNIT_EXPECT_EQ(test, t.counters[i], (u64)i + 1); +} + +static void ane_ack_pending_private_test(struct kunit *test) +{ + struct ane_ack_pending_test f = {}; + struct ane_fw_ack_pending_trace t = {}; + + ane_fw_ack_pending_observe(&f, &ane_ack_test_ops, &t, 1, 6, BIT(6)); + KUNIT_EXPECT_EQ(test, f.used, 1U); + KUNIT_EXPECT_EQ(test, f.access[0], 'W'); + KUNIT_EXPECT_EQ(test, f.writes, 1U); + KUNIT_EXPECT_EQ(test, f.reads, 0U); + KUNIT_EXPECT_EQ(test, t.calls, 1U); + KUNIT_EXPECT_EQ(test, t.valid, 0U); + KUNIT_EXPECT_EQ(test, t.before_value, 0U); + KUNIT_EXPECT_EQ(test, t.after_value, 0U); + KUNIT_EXPECT_EQ(test, t.counters[5], 6ULL); +} + +static void ane_ack_pending_disabled_test(struct kunit *test) +{ + struct ane_ack_pending_test f = {}; + struct ane_fw_ack_pending_trace t = {}; + + ane_fw_ack_pending_observe(&f, &ane_ack_test_ops, &t, 0, 6, BIT(6)); + KUNIT_EXPECT_EQ(test, f.writes, 1U); + KUNIT_EXPECT_EQ(test, f.reads, 0U); + KUNIT_EXPECT_EQ(test, f.counter, 0ULL); + KUNIT_EXPECT_EQ(test, t.calls, 0U); + ane_fw_ack_pending_observe(&f, &ane_ack_test_ops, NULL, 2, 6, BIT(6)); + KUNIT_EXPECT_EQ(test, f.writes, 2U); + KUNIT_EXPECT_EQ(test, f.reads, 0U); + KUNIT_EXPECT_EQ(test, f.counter, 0ULL); +} + +struct ane_pending_test { + u64 ns, counter; + u32 reads, delays, cpus; +}; + +static u64 ane_pending_test_now(void *ctx) +{ + return ((struct ane_pending_test *)ctx)->ns; +} + +static u64 ane_pending_test_counter(void *ctx) +{ + return ++((struct ane_pending_test *)ctx)->counter; +} + +static u32 ane_pending_test_cpu(void *ctx) +{ + return ((struct ane_pending_test *)ctx)->cpus++; +} + +static u32 ane_pending_test_read(void *ctx) +{ + struct ane_pending_test *f = ctx; + + return f->reads++ < 1 ? BIT(6) : 0; +} + +static void ane_pending_test_delay(void *ctx, u32 us) +{ + struct ane_pending_test *f = ctx; + + f->ns += (u64)us * NSEC_PER_USEC; + f->delays++; +} + +static const struct ane_fw_pending_ops ane_pending_test_ops = { + .now_ns = ane_pending_test_now, + .counter = ane_pending_test_counter, + .cpu = ane_pending_test_cpu, + .read_pending = ane_pending_test_read, + .delay_us = ane_pending_test_delay, +}; + +static void ane_pending_deadline_and_migration_test(struct kunit *test) +{ + struct ane_pending_test f = {}; + struct ane_fw_pending_sample samples[4] = {}; + u32 count = 99; + + KUNIT_ASSERT_EQ(test, ane_fw_pending_capture(&f, &ane_pending_test_ops, + samples, 4, 3000, true, &count), 0); + KUNIT_EXPECT_EQ(test, count, 3U); + KUNIT_EXPECT_EQ(test, f.reads, 3U); + KUNIT_EXPECT_EQ(test, f.delays, 3U); + KUNIT_EXPECT_EQ(test, samples[0].value, (u32)BIT(6)); + KUNIT_EXPECT_EQ(test, samples[1].value, 0U); + KUNIT_EXPECT_EQ(test, samples[0].before, 1ULL); + KUNIT_EXPECT_EQ(test, samples[0].after, 2ULL); + KUNIT_EXPECT_EQ(test, samples[0].before_cpu, 0U); + KUNIT_EXPECT_EQ(test, samples[0].after_cpu, 1U); + KUNIT_EXPECT_EQ(test, samples[0].valid, 1U); + KUNIT_EXPECT_EQ(test, samples[3].before, 0ULL); +} + +static void ane_pending_private_control_test(struct kunit *test) +{ + struct ane_pending_test f = {}; + struct ane_fw_pending_sample samples[4] = {}; + u32 count; + + KUNIT_ASSERT_EQ(test, ane_fw_pending_capture(&f, &ane_pending_test_ops, + samples, 4, 3000, false, &count), 0); + KUNIT_EXPECT_EQ(test, count, 3U); + KUNIT_EXPECT_EQ(test, f.reads, 0U); + KUNIT_EXPECT_EQ(test, f.delays, 3U); + KUNIT_EXPECT_EQ(test, samples[0].valid, 0U); + KUNIT_EXPECT_EQ(test, samples[0].value, 0U); +} + +static void ane_pending_capacity_test(struct kunit *test) +{ + struct ane_pending_test f = {}; + struct ane_fw_pending_sample samples[3] = {}; + u32 count; + + samples[2].before = 0xabc; + KUNIT_EXPECT_EQ(test, ane_fw_pending_capture(&f, &ane_pending_test_ops, + samples, 2, 5000, true, &count), -ENOSPC); + KUNIT_EXPECT_EQ(test, count, 2U); + KUNIT_EXPECT_EQ(test, f.reads, 2U); + KUNIT_EXPECT_EQ(test, samples[2].before, 0xabcULL); +} + +static void ane_pending_expired_test(struct kunit *test) +{ + struct ane_pending_test f = { .ns = 5000 }; + struct ane_fw_pending_sample samples[2] = {}; + u32 count; + + KUNIT_EXPECT_EQ(test, ane_fw_pending_capture(&f, &ane_pending_test_ops, + samples, 2, 5000, true, &count), 0); + KUNIT_EXPECT_EQ(test, count, 0U); + KUNIT_EXPECT_EQ(test, f.reads, 0U); + KUNIT_EXPECT_EQ(test, f.counter, 0ULL); + KUNIT_EXPECT_EQ(test, f.delays, 0U); +} + +static void ane_pending_test_stalled_delay(void *ctx, u32 us) +{ + ((struct ane_pending_test *)ctx)->delays++; +} + +static void ane_pending_stalled_clock_test(struct kunit *test) +{ + struct ane_pending_test f = {}; + struct ane_fw_pending_ops ops = ane_pending_test_ops; + struct ane_fw_pending_sample samples[3] = {}; + u32 count; + + ops.delay_us = ane_pending_test_stalled_delay; + samples[2].before = 0xabc; + KUNIT_EXPECT_EQ(test, ane_fw_pending_capture(&f, &ops, samples, 2, + 5000, true, &count), -ENOSPC); + KUNIT_EXPECT_EQ(test, count, 2U); + KUNIT_EXPECT_EQ(test, f.reads, 2U); + KUNIT_EXPECT_EQ(test, f.ns, 0ULL); + KUNIT_EXPECT_EQ(test, samples[2].before, 0xabcULL); +} + +static u32 ane_pending_test_slow_read(void *ctx) +{ + struct ane_pending_test *f = ctx; + + f->ns += 5000; + f->reads++; + return BIT(6); +} + +static void ane_pending_read_overshoot_test(struct kunit *test) +{ + struct ane_pending_test f = {}; + struct ane_fw_pending_ops ops = ane_pending_test_ops; + struct ane_fw_pending_sample samples[3] = {}; + u32 count; + + ops.read_pending = ane_pending_test_slow_read; + KUNIT_EXPECT_EQ(test, ane_fw_pending_capture(&f, &ops, samples, 3, + 3000, true, &count), 0); + KUNIT_EXPECT_EQ(test, count, 1U); + KUNIT_EXPECT_EQ(test, f.reads, 1U); + KUNIT_EXPECT_GT(test, f.ns, 3000ULL); + KUNIT_EXPECT_EQ(test, samples[0].value, (u32)BIT(6)); + KUNIT_EXPECT_EQ(test, samples[0].after, 2ULL); + KUNIT_EXPECT_EQ(test, samples[1].before, 0ULL); +} + +static void ane_pending_invalid_config_test(struct kunit *test) +{ + struct ane_pending_test f = {}; + struct ane_fw_pending_sample sample; + u32 count = 99; + + KUNIT_EXPECT_TRUE(test, ane_fw_pending_config_valid(0, 0, 0)); + KUNIT_EXPECT_TRUE(test, ane_fw_pending_config_valid(1, 2000, 10)); + KUNIT_EXPECT_TRUE(test, ane_fw_pending_config_valid(2, 2000, 128)); + KUNIT_EXPECT_FALSE(test, ane_fw_pending_config_valid(3, 2000, 10)); + KUNIT_EXPECT_FALSE(test, ane_fw_pending_config_valid(2, 1999, 10)); + KUNIT_EXPECT_FALSE(test, ane_fw_pending_config_valid(2, 2000, 0)); + KUNIT_EXPECT_FALSE(test, ane_fw_pending_config_valid(2, 2000, 129)); + KUNIT_EXPECT_EQ(test, ane_fw_pending_capture(&f, &ane_pending_test_ops, + &sample, 0, 5000, true, &count), -EINVAL); + KUNIT_EXPECT_EQ(test, count, 0U); + KUNIT_EXPECT_EQ(test, f.reads, 0U); +} + +static void ane_job_gap_schedule_test(struct kunit *test) +{ + u32 i, n6 = 0, n7 = 0; + + for (i = 0; i <= 1001; i++) { + n6 += ane_job_gap_selected(i, 0, 6); + n7 += ane_job_gap_selected(i, 0, 7); + } + KUNIT_EXPECT_EQ(test, n6, 166U); + KUNIT_EXPECT_EQ(test, n7, 143U); + KUNIT_EXPECT_FALSE(test, ane_job_gap_selected(5, 0, 6)); + KUNIT_EXPECT_TRUE(test, ane_job_gap_selected(6, 0, 6)); + KUNIT_EXPECT_TRUE(test, ane_job_gap_selected(10, 10, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_selected(11, 10, 0)); + KUNIT_EXPECT_TRUE(test, ane_job_gap_valid(0, 0, 0, false, false, false)); + KUNIT_EXPECT_TRUE(test, ane_job_gap_valid(125, 0, 6, false, false, false)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_valid(0, 0, 6, false, false, false)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_valid(2001, 0, 6, false, false, false)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_valid(125, 1, 6, false, false, false)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_valid(125, 0, 129, false, false, false)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_valid(125, 0, 6, true, false, false)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_valid(125, 0, 6, false, true, false)); + KUNIT_EXPECT_FALSE(test, ane_job_gap_valid(125, 0, 6, false, false, true)); +} + +struct ane_coalesce_fake { + u64 now, step, error_at, error_delay; + u32 error_calls, advance_on_call; +}; +static u64 ane_coalesce_test_now(void *ctx) +{ + return ((struct ane_coalesce_fake *)ctx)->now; +} +static int ane_coalesce_test_error(void *ctx) +{ + struct ane_coalesce_fake *f = ctx; + + if (++f->error_calls == f->advance_on_call) + f->now += f->error_delay; + return f->error_at && f->now >= f->error_at ? -EIO : 0; +} +static void ane_coalesce_test_delay(void *ctx, u32 us) +{ + struct ane_coalesce_fake *f = ctx; + + f->now += f->step * us; +} +static const struct ane_fw_irq_coalesce_ops ane_coalesce_test_ops = { + .now_ns = ane_coalesce_test_now, + .error = ane_coalesce_test_error, + .delay_us = ane_coalesce_test_delay, +}; +static void ane_irq_coalesce_deadline_test(struct kunit *test) +{ + struct ane_coalesce_fake f = { .step = 1000 }; + struct ane_fw_irq_coalesce_result r; + + KUNIT_ASSERT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 100000, &r), 0); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 5000ULL); + KUNIT_EXPECT_EQ(test, r.iterations, 5U); + KUNIT_EXPECT_FALSE(test, r.clipped); + f.now = 0; + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 3000, &r), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 3000ULL); + KUNIT_EXPECT_TRUE(test, r.clipped); + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 3000, &r), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 0ULL); +} +static void ane_irq_coalesce_error_and_overshoot_test(struct kunit *test) +{ + struct ane_coalesce_fake f = { .step = 1000, .error_at = 2000 }; + struct ane_fw_irq_coalesce_result r; + + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 100000, &r), -EIO); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 2000ULL); + f.now = 0; + f.error_at = 0; + f.step = 50000; + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 100000, &r), 0); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 50000ULL); /* retain preemption overshoot */ + f.now = 0; + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 25, 20000, &r), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 50000ULL); +} +static void ane_irq_coalesce_final_check_preemption_test(struct kunit *test) +{ + struct ane_coalesce_fake f = { .step = 1000, .advance_on_call = 6, + .error_delay = 200000 }; + struct ane_fw_irq_coalesce_result r; + + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 100000, &r), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 205000ULL); + f = (struct ane_coalesce_fake) { .step = 1000, .advance_on_call = 2, + .error_delay = 200000, .error_at = 1000 }; + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 100000, &r), -EIO); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 201000ULL); +} + +static void ane_irq_coalesce_bounds_test(struct kunit *test) +{ + struct ane_coalesce_fake f = {}; + struct ane_fw_irq_coalesce_result r; + + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 0, 100000, &r), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 26, 100000, &r), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, 100000, &r), -EIO); + KUNIT_EXPECT_EQ(test, r.iterations, 128U); + KUNIT_EXPECT_EQ(test, r.elapsed_ns, 0ULL); + f.now = U64_MAX - 1000; + KUNIT_EXPECT_EQ(test, ane_fw_irq_coalesce(&f, &ane_coalesce_test_ops, 5, U64_MAX, &r), -EOVERFLOW); +} + +static void ane_job_drain_schedule_test(struct kunit *test) +{ + u32 i; + + KUNIT_EXPECT_TRUE(test, ane_job_drain_valid(0, 0, 0, 0)); + KUNIT_EXPECT_TRUE(test, ane_job_drain_valid(2000, 20, 0, 1)); + KUNIT_EXPECT_FALSE(test, ane_job_drain_valid(2001, 20, 0, 1)); + KUNIT_EXPECT_FALSE(test, ane_job_drain_valid(2000, 0, 0, 1)); + KUNIT_EXPECT_FALSE(test, ane_job_drain_valid(2000, 101, 0, 1)); + KUNIT_EXPECT_FALSE(test, ane_job_drain_valid(2000, 20, 1, 1)); + KUNIT_EXPECT_FALSE(test, ane_job_drain_valid(2000, 20, 0, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_drain_valid(2000, 20, 0, 6)); + for (i = 1; i <= 1001; i++) { + KUNIT_EXPECT_TRUE(test, ane_job_gap_selected(i, 0, 1)); + KUNIT_EXPECT_EQ(test, ane_job_gap_duration(i, 20, 2000), + i == 1 ? 2000U : 20U); + KUNIT_EXPECT_EQ(test, ane_job_gap_duration(i, 20, 0), 20U); + } + KUNIT_EXPECT_EQ(test, ane_job_gap_duration(2, 3000, 0), 2000U); +} + +static void ane_report_batch_scope_test(struct kunit *test) +{ + KUNIT_EXPECT_TRUE(test, ane_fw_report_batch_eligible(true, 1, false)); + KUNIT_EXPECT_FALSE(test, ane_fw_report_batch_eligible(false, 1, false)); + KUNIT_EXPECT_FALSE(test, ane_fw_report_batch_eligible(true, 0, false)); + KUNIT_EXPECT_FALSE(test, ane_fw_report_batch_eligible(true, 2, false)); + KUNIT_EXPECT_FALSE(test, ane_fw_report_batch_eligible(true, 1, true)); +} + +static void ane_report_batch_burst_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 report[0x60], *p; + size_t size = 0; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->t.report_ack_defer = true; + for (i = 0; i < 3; i++) { + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + p = ane_test_slot(f, ANE_FW_IO_T2H); + f->count = 0; + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), (f->pool.dva + 0x100) | 1); + KUNIT_EXPECT_MEMEQ(test, report, (u8 *)f->pool.cpu + 0x100, sizeof(report)); + /* The ownership store keeps both original ordering barriers. */ + KUNIT_EXPECT_EQ(test, f->access[f->count - 3].kind, 'W'); + KUNIT_EXPECT_PTR_EQ(test, f->access[f->count - 2].p, p); + KUNIT_EXPECT_EQ(test, f->access[f->count - 1].kind, 'W'); + KUNIT_EXPECT_EQ(test, f->t.report_ack_doorbells, 0ULL); + } + KUNIT_EXPECT_EQ(test, f->t.report_ack_slots, 3ULL); + KUNIT_EXPECT_EQ(test, f->t.report_ack_pending, 3U); + ane_fw_report_batch_end(&f->t); + KUNIT_EXPECT_FALSE(test, f->t.report_ack_defer); + KUNIT_EXPECT_EQ(test, f->t.report_ack_pending, 0U); + KUNIT_EXPECT_EQ(test, f->t.report_ack_doorbells, 1ULL); + KUNIT_EXPECT_EQ(test, f->last_value, (u32)BIT(6)); + ane_fw_report_ack_flush(&f->t); + KUNIT_EXPECT_EQ(test, f->t.report_ack_doorbells, 1ULL); +} + +static void ane_report_batch_bound_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 report[0x60]; + size_t size = 0; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->t.report_ack_defer = true; + for (i = 0; i < 5; i++) { + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), 0); + } + KUNIT_EXPECT_EQ(test, f->t.report_ack_peak, 4U); + KUNIT_EXPECT_EQ(test, f->t.report_ack_pending, 1U); + KUNIT_EXPECT_EQ(test, f->t.report_ack_doorbells, 1ULL); + ane_fw_report_batch_end(&f->t); + KUNIT_EXPECT_EQ(test, f->t.report_ack_pending, 0U); + KUNIT_EXPECT_EQ(test, f->t.report_ack_doorbells, 2ULL); +} + +static void ane_report_batch_empty_error_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + struct ane_fw_consume_trace trace; + u8 report[0x60]; + size_t size = 0; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->t.report_ack_defer = true; + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume_traced(&f->t, report, sizeof(report), &size, &trace), -EINVAL); + KUNIT_EXPECT_EQ(test, f->t.report_ack_pending, 0U); + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), -EAGAIN); + ane_fw_report_ack_flush(&f->t); /* EMPTY boundary before wait. */ + KUNIT_EXPECT_EQ(test, f->t.report_ack_pending, 0U); + KUNIT_EXPECT_EQ(test, f->t.report_ack_doorbells, 1ULL); + ane_transport_report_request(f, f->pool.dva + 0x100, sizeof(report)); + KUNIT_ASSERT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), 0); + f->t.error = -EPROTO; + KUNIT_EXPECT_EQ(test, ane_fw_transport_consume(&f->t, report, sizeof(report), &size), -EPROTO); + ane_fw_report_batch_end(&f->t); /* Every error/timeout/terminal exit. */ + KUNIT_EXPECT_EQ(test, f->t.report_ack_pending, 0U); + KUNIT_EXPECT_EQ(test, f->t.report_ack_doorbells, 2ULL); + KUNIT_EXPECT_FALSE(test, f->t.report_ack_defer); +} + +static void ane_job_recovery_config_test(struct kunit *test) +{ + KUNIT_EXPECT_TRUE(test, ane_job_recovery_valid(0, 0, 0, 0, 0)); + KUNIT_EXPECT_TRUE(test, ane_job_recovery_valid(125, 30, 0, 1, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(2001, 30, 0, 1, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(125, 0, 0, 1, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(125, 101, 0, 1, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(30, 30, 0, 1, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(20, 30, 0, 1, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(125, 30, 1, 1, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(125, 30, 0, 6, 0)); + KUNIT_EXPECT_FALSE(test, ane_job_recovery_valid(125, 30, 0, 1, 2000)); +} + +static void ane_job_recovery_feedback_test(struct kunit *test) +{ + struct ane_job_recovery r = {}; + u32 a[3] = { 1, 2, 3 }, b[3] = { 1, 2, 4 }; + u32 token; + + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, a, 30, 125), 125U); + for (token = 0xfe00; token <= 0xfe03; token++) { + ane_job_recovery_observe(&r, true, token, a); + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, a, 30, 125), 30U); + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, b, 30, 125), 125U); + } + ane_job_recovery_reset(&r); + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, a, 30, 125), 125U); + ane_job_recovery_observe(&r, true, 1, a); + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, a, 30, 125), 125U); + ane_job_recovery_observe(&r, true, 0xfe04, a); + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, a, 30, 125), 125U); + ane_job_recovery_observe(&r, true, 0xfdff, a); + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, a, 30, 125), 125U); + /* Last terminal in an overlapped batch is still NOT serial feedback. */ + ane_job_recovery_observe(&r, false, 0xfe01, a); + KUNIT_EXPECT_FALSE(test, r.valid); + KUNIT_EXPECT_EQ(test, ane_job_recovery_duration(&r, a, 30, 125), 125U); +} + +static struct kunit_case ane_transport_cases[] = { + KUNIT_CASE(ane_job_recovery_config_test), + KUNIT_CASE(ane_job_recovery_feedback_test), + KUNIT_CASE(ane_report_batch_scope_test), + KUNIT_CASE(ane_report_batch_burst_test), + KUNIT_CASE(ane_report_batch_bound_test), + KUNIT_CASE(ane_report_batch_empty_error_test), + KUNIT_CASE(ane_job_drain_schedule_test), + KUNIT_CASE(ane_irq_coalesce_deadline_test), + KUNIT_CASE(ane_irq_coalesce_error_and_overshoot_test), + KUNIT_CASE(ane_irq_coalesce_bounds_test), + KUNIT_CASE(ane_irq_coalesce_final_check_preemption_test), + KUNIT_CASE(ane_job_gap_schedule_test), + KUNIT_CASE(ane_ack_pending_read_order_test), + KUNIT_CASE(ane_ack_pending_private_test), + KUNIT_CASE(ane_ack_pending_disabled_test), + KUNIT_CASE(ane_pending_deadline_and_migration_test), + KUNIT_CASE(ane_pending_private_control_test), + KUNIT_CASE(ane_pending_capacity_test), + KUNIT_CASE(ane_pending_expired_test), + KUNIT_CASE(ane_pending_invalid_config_test), + KUNIT_CASE(ane_pending_stalled_clock_test), + KUNIT_CASE(ane_pending_read_overshoot_test), + KUNIT_CASE(ane_transport_terminal_ack_test), + KUNIT_CASE(ane_transport_terminal_bounds_test), + KUNIT_CASE(ane_transport_terminal_wrap_test), + KUNIT_CASE(ane_transport_table_test), + KUNIT_CASE(ane_transport_table_roles_test), + KUNIT_CASE(ane_transport_table_bounds_test), + KUNIT_CASE(ane_transport_table_edges_test), + KUNIT_CASE(ane_transport_arm_test), + KUNIT_CASE(ane_transport_publish_order_test), + KUNIT_CASE(ane_transport_wrap_test), + KUNIT_CASE(ane_transport_reply_corruption_test), + KUNIT_CASE(ane_transport_refusal_test), + KUNIT_CASE(ane_transport_pool_test), + KUNIT_CASE(ane_transport_snapshot_test), + KUNIT_CASE(ane_transport_consume_test), + KUNIT_CASE(ane_transport_consume_trace_order_test), + KUNIT_CASE(ane_transport_consume_trace_refusal_test), + KUNIT_CASE(ane_transport_report_bounds_test), + KUNIT_CASE(ane_transport_report_word2_test), + KUNIT_CASE(ane_transport_presence_test), + KUNIT_CASE(ane_transport_shared_test), + KUNIT_CASE(ane_transport_coalesced_shared_irq_test), + KUNIT_CASE(ane_transport_shared_drain_refusal_test), + KUNIT_CASE(ane_transport_shared_rejections_test), + KUNIT_CASE(ane_transport_allocator_rejections_test), + KUNIT_CASE(ane_transport_shared_overlap_test), + KUNIT_CASE(ane_transport_shared_count_test), + KUNIT_CASE(ane_transport_shared_total_test), + KUNIT_CASE(ane_transport_shared_report_test), + KUNIT_CASE(ane_transport_irq_test), + KUNIT_CASE(ane_transport_match_data_test), + KUNIT_CASE(ane_transport_deadline_test), + KUNIT_CASE(ane_transport_deadline_service_test), + KUNIT_CASE(ane_transport_wait_test), + {} +}; + +static struct kunit_suite ane_transport_suite = { + .name = "ane-fw-transport", + .init = ane_transport_test_init, + .test_cases = ane_transport_cases, +}; + +kunit_test_suite(ane_transport_suite); +MODULE_DESCRIPTION("KUnit tests for the shared H16/H17 firmware transport"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_backend.c b/drivers/accel/ane/ane_h16_backend.c new file mode 100644 index 0000000000000..6c1a2fab46f3b --- /dev/null +++ b/drivers/accel/ane/ane_h16_backend.c @@ -0,0 +1,2325 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Staged H16 backend, using the accepted H16 cold-boot facts, round 5. */ +#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 "ane_h16_boot.h" +#include "ane_fw_irq_wait.h" +#include "ane_fw_irq_coalesce.h" +#include "ane_fw_report_fifo.h" +#include "ane_fw_pending.h" +#include "ane_job_gap.h" +#include "ane_fw_ack_pending.h" +#include "ane_h16_execute.h" +#include "ane_h16_preload.h" + +#define ANE_H16_TX_WORDS 272 + +struct ane_h16_mapping { + struct list_head node; + u64 dva; + size_t size; + size_t mapped; + struct page **pages; + u32 blocks; + void *cpu; +}; + +#define ANE_H16_CONSUME_TRACE_MAX 256 +struct ane_h16_consume_trace { + struct ane_fw_consume_trace transport; + struct ane_fw_ack_pending_trace ack_pending; + u64 begin_counter, end_counter, uuid; + u32 token, command_id, state, begin_cpu, end_cpu, irq_before, irq_after; +}; + +struct ane_h16_device { + struct ane_h16_boot boot; + struct device *dev; + void __iomem *window[ANE_H16_WINDOWS]; + struct device *power[5]; + struct device *dart[3]; + u32 powered; + u32 darts_powered; + u64 preload_phys[2]; + struct list_head mappings; + struct iommu_domain *domain; + struct iommu_group *group; + bool claimed; + bool attached; + bool pinned; + int irq; + bool job_irq_mode; + struct ane_h16_consume_trace *consume_trace; + struct ane_fw_ack_pending_trace *active_ack_pending; + u32 consume_trace_count, consume_trace_dropped; + u32 early_consumes, early_peak, early_remaining, early_full_errors; + u64 snapshot_sequence, snapshot_begin, snapshot_end; + u32 snapshot_begin_cpu, snapshot_end_cpu; + struct ane_fw_irq_event irq_event; + atomic_t irq_calls, irq_notifications, irq_empty, irq_empty_run, irq_disabled; + atomic_t irq_waits, irq_woken, irq_timeouts; + atomic_t irq_status_count[ANE_FW_CHANNELS]; + cpumask_t irq_seen_cpus; + u32 irq_job_base[6]; + struct ane_fw_irq_coalesce_stats coalesce_stats[2]; /* CMD, EVENT */ + u32 mailbox_rx_count; + struct ane_fw_rtk rtk; + struct { + u64 word0; + u64 word1; + } tx[ANE_H16_TX_WORDS]; + u32 tx_read; + u32 tx_write; + bool rtk_failed; + u64 shared_next; + bool startup_tracing; + u32 startup_trace_count, startup_trace_dropped; + struct { + u64 ns, counter; + u32 type, value, shared_count; + } startup_trace[128]; +}; + +static bool h16_job_irq; +module_param(h16_job_irq, bool, 0444); +MODULE_PARM_DESC(h16_job_irq, "Diagnostic IRQ completion after startup, default0; incompatible with quiet probes"); + +static unsigned int h16_job_ack_pending_mode; +module_param(h16_job_ack_pending_mode, uint, 0444); +MODULE_PARM_DESC(h16_job_ack_pending_mode, "Per-report ACK observer:0off,1private bookkeeping,2read FW pending; requires consume trace"); + +static bool h16_job_trace; +module_param(h16_job_trace, bool, 0444); +MODULE_PARM_DESC(h16_job_trace, "Bounded consume-stage RAM timestamps, max256 reports/default0; perturbs timing"); + +static bool h16_map_batch; +module_param(h16_map_batch, bool, 0444); +MODULE_PARM_DESC(h16_map_batch, "Diagnostic private surface DART mapping in one SG transaction, default0"); + +static bool h16_job_snapshot; +module_param(h16_job_snapshot, bool, 0444); +MODULE_PARM_DESC(h16_job_snapshot, "Allow bounded fixed firmware DATA snapshots after job, default0; non-atomic read only"); + +static bool h16_job_early_drain; +module_param(h16_job_early_drain, bool, 0444); +MODULE_PARM_DESC(h16_job_early_drain, "Copy/ACK T2H during EXEC CMD wait into bounded FIFO, default0; incompatible with quiet"); +static bool h16_job_return_trace; +module_param(h16_job_return_trace, bool, 0444); +MODULE_PARM_DESC(h16_job_return_trace, "Record actual EVENT helper return counter, default0; includes CMD acceptance/FIFO dispatch"); + +static DEFINE_MUTEX(ane_h16_lock); +static bool ane_h16_released; + +/* Diagnostic, workspace ane: observe an unknown resident image. */ +static unsigned int h16_startup_poll_us = 1000; +module_param(h16_startup_poll_us, uint, 0444); +MODULE_PARM_DESC(h16_startup_poll_us, "Startup wait service cadence10..1000us, default1000"); +static unsigned int h16_startup_drain_poll_us = 10; +module_param(h16_startup_drain_poll_us, uint, 0444); +MODULE_PARM_DESC(h16_startup_drain_poll_us, "Pre-IO service cadence10..1000us, default10"); +static bool h16_startup_trace; +module_param(h16_startup_trace, bool, 0444); +MODULE_PARM_DESC(h16_startup_trace, "Record bounded startup allocation/doorbell timestamps, print only after probe"); + +static char *h16_identity; +module_param(h16_identity, charp, 0444); +MODULE_PARM_DESC(h16_identity, "observe: accept an unknown resident image for preflight only and publish it in debugfs ane_h16/"); + +static const char *const ane_h16_build_names[ANE_H16_PRELOAD_BUILDS] = { + "H16 27.0 26A428", "H16 26.5.2 25F84", +}; + +static struct debugfs_blob_wrapper ane_h16_dump[2]; +static struct dentry *ane_h16_debugfs; +/* Failure-only copies; firmware remains live, so these are not atomic dumps. */ +static struct debugfs_blob_wrapper ane_h16_failure[4 + ANE_FW_SHARED_MAX]; + +static bool ane_h16_observing(void) +{ + return h16_identity && !strcmp(h16_identity, "observe"); +} + +static struct ane_h16_device *ane_h16_job_dev; +static struct debugfs_blob_wrapper ane_h16_job_result; + +void ane_h16_backend_exit(void) +{ + unsigned int i; + + debugfs_remove_recursive(ane_h16_debugfs); + ane_h16_debugfs = NULL; + vfree(ane_h16_dump[0].data); + vfree(ane_h16_dump[1].data); + vfree(ane_h16_job_result.data); + for (i = 0; i < ARRAY_SIZE(ane_h16_failure); i++) + vfree(ane_h16_failure[i].data); + ane_h16_job_dev = NULL; +} + +static u32 ane_h16_mmio_read32(void *ctx, enum ane_h16_window w, u32 off) +{ + struct ane_h16_device *h = ctx; + + return readl(h->window[w] + off); +} + +static u64 ane_h16_mmio_read64(void *ctx, enum ane_h16_window w, u32 off) +{ + struct ane_h16_device *h = ctx; + + return readq(h->window[w] + off); +} + +static void ane_h16_mmio_write32(void *ctx, enum ane_h16_window w, u32 off, u32 value) +{ + struct ane_h16_device *h = ctx; + + writel(value, h->window[w] + off); +} + +static void ane_h16_mmio_write64(void *ctx, enum ane_h16_window w, u32 off, u64 value) +{ + struct ane_h16_device *h = ctx; + + writeq(value, h->window[w] + off); +} + +static void ane_h16_delay(void *ctx, unsigned int us) +{ + if (us < 100) + udelay(us); + else + usleep_range(us, us + 50); +} + +static void ane_h16_log(void *ctx, const char *item, u64 a, u64 b) +{ + struct ane_h16_device *h = ctx; + + dev_info(h->dev, "H16 %s %llx %llx\n", item, a, b); +} + +static void ane_h16_quarantine(void *ctx, int error) +{ + struct ane_h16_device *h = ctx; + + dev_err(h->dev, "H16 quarantine error %d; mappings, power and module held until reboot\n", + error); +} + +static int ane_h16_pin(void *ctx) +{ + struct ane_h16_device *h = ctx; + + if (!try_module_get(THIS_MODULE)) + return -ENODEV; + h->pinned = true; + ane_h16_released = true; + return 0; +} + +/* Nonblocking transmit queue. RTKit progress never gates scratch progress. */ +static int ane_h16_mailbox_send(void *ctx, u64 word0, u64 word1) +{ + struct ane_h16_device *h = ctx; + + if (h->tx_write - h->tx_read == ARRAY_SIZE(h->tx)) + return -ENOSPC; + h->tx[h->tx_write % ARRAY_SIZE(h->tx)].word0 = word0; + h->tx[h->tx_write % ARRAY_SIZE(h->tx)].word1 = word1; + h->tx_write++; + return 0; +} + +static void ane_h16_mailbox(void *ctx) +{ + struct ane_h16_device *h = ctx; + void __iomem *mb = h->window[ANE_H16_ENGINE] + h->boot.soc->mailbox; + unsigned int i; + + for (i = 0; i < 16; i++) { + u64 word0, word1; + int ret; + + if (readl(mb + 0x114) & BIT(17)) + break; + /* Two 64-bit accesses. Reading the second word pops the entry. */ + word0 = readq(mb + 0x830); + word1 = readq(mb + 0x838); + h->mailbox_rx_count++; + dev_info(h->dev, "H16 ASC RX %016llx %016llx\n", word0, word1); + if (h->rtk_failed) + continue; + ret = ane_fw_rtk_receive(&h->rtk, word0, word1, h, ane_h16_mailbox_send); + if (ret) { + dev_info(h->dev, + "H16 RTKit message declined %d; scratch remains independent\n", + ret); + if (ret != -EOPNOTSUPP) + h->rtk_failed = true; + } + } + for (i = 0; i < 16 && h->tx_read != h->tx_write; i++) { + u32 index = h->tx_read % ARRAY_SIZE(h->tx); + + if (readl(mb + 0x110) & BIT(16)) + break; + writeq(h->tx[index].word0, mb + 0x800); + /* Publish word 0 before the word-1 FIFO commit. */ + wmb(); + writeq(h->tx[index].word1, mb + 0x808); + dev_info(h->dev, "H16 ASC TX %016llx %016llx\n", + h->tx[index].word0, h->tx[index].word1); + h->tx_read++; + } +} + +static int ane_h16_map_range(struct ane_h16_device *h, u64 dva, u64 pa, + size_t size, int prot) +{ + struct ane_h16_mapping *m; + int ret; + + m = kzalloc_obj(*m); + if (!m) + return -ENOMEM; + m->dva = dva; + m->size = size; + list_add_tail(&m->node, &h->mappings); + ret = iommu_map(h->domain, dva, pa, size, prot, GFP_KERNEL); + if (!ret) + m->mapped = size; + return ret; +} + +static int ane_h16_count_group(struct device *dev, void *data) +{ + unsigned int *count = data; + + (*count)++; + return 0; +} + +static int ane_h16_map(void *ctx) +{ + struct ane_h16_device *h = ctx; + struct ane_h16_boot *b = &h->boot; + unsigned int count = 0, i; + int ret; + + if (of_count_phandle_with_args(h->dev->of_node, "iommus", "#iommu-cells") != 3) { + dev_err(h->dev, "H16 map requires only SID 0 on three DARTs; refusing extra streams\n"); + return -EOPNOTSUPP; + } + h->group = iommu_group_get(h->dev); + if (!h->group) + return -ENODEV; + ret = iommu_group_for_each_dev(h->group, &count, ane_h16_count_group); + if (ret || count != 1) + return ret ?: -EBUSY; + ret = iommu_device_claim_dma_owner(h->dev, h); + if (ret) + return ret; + h->claimed = true; + h->domain = iommu_paging_domain_alloc(h->dev); + if (IS_ERR_OR_NULL(h->domain)) { + ret = h->domain ? PTR_ERR(h->domain) : -ENOMEM; + h->domain = NULL; + return ret; + } + if (h->domain->type != IOMMU_DOMAIN_UNMANAGED || + !(h->domain->pgsize_bitmap & SZ_16K)) + return -EOPNOTSUPP; + /* Never widen a finalized DART aperture by assigning geometry fields. */ + for (i = 0; i < 4; i++) { + u64 page = round_down(b->ranges[i][0], SZ_16K); + + if (!ane_fw_contains(h->domain->geometry.aperture_start, + h->domain->geometry.aperture_end - + h->domain->geometry.aperture_start + 1, + page, SZ_16K)) + return -ERANGE; + } + if (h->domain->geometry.aperture_end < b->build->shared_dva + ANE_FW_SHARED_TOTAL) + return -ERANGE; + ret = iommu_attach_device(h->domain, h->dev); + if (ret) + return ret; + h->attached = true; + for (i = 0; i < 2; i++) { + ret = ane_h16_map_range(h, b->soc->preload_dva[i], h->preload_phys[i], + b->soc->preload_size[i], + IOMMU_READ | IOMMU_CACHE | (i ? IOMMU_WRITE : 0)); + if (ret) + return ret; + dev_info(h->dev, "H16 preload %s mapped at %llx bytes %llx\n", + i ? "DATA" : "TEXT", b->soc->preload_dva[i], b->soc->preload_size[i]); + } + for (i = 0; i < 4; i++) { + u64 page = round_down(b->ranges[i][0], SZ_16K); + + ret = ane_h16_map_range(h, page, page, SZ_16K, + IOMMU_READ | IOMMU_WRITE | IOMMU_MMIO); + if (ret) + return ret; + dev_info(h->dev, "H16 identity MMIO %llx mapped\n", page); + } + return 0; +} + +static int ane_h16_alloc_at(void *ctx, u64 dva, size_t size, struct ane_fw_surface *out) +{ + struct ane_h16_device *h = ctx; + struct ane_h16_mapping *m; + u32 i, j, pages_per_block = SZ_16K / PAGE_SIZE; + unsigned int order = get_order(SZ_16K); + int ret; + + if (!dev_is_dma_coherent(h->dev)) { + dev_err(h->dev, "H16 private surfaces require a coherent client\n"); + return -EOPNOTSUPP; + } + if (!size || !IS_ALIGNED(size, SZ_16K) || !IS_ALIGNED(dva, SZ_16K) || + PAGE_SIZE > SZ_16K) + return -EINVAL; + m = kzalloc_obj(*m); + if (!m) + return -ENOMEM; + m->size = size; + m->dva = dva; + list_add_tail(&m->node, &h->mappings); + m->pages = kvcalloc(size / PAGE_SIZE, sizeof(*m->pages), GFP_KERNEL); + if (!m->pages) + return -ENOMEM; + for (i = 0; i < size / SZ_16K; i++) { + struct page *page = alloc_pages(GFP_KERNEL | __GFP_ZERO, order); + + if (!page) + return -ENOMEM; + for (j = 0; j < pages_per_block; j++) + m->pages[i * pages_per_block + j] = page + j; + m->blocks++; + } + /* The coherent-client gate permits matching cached CPU/device aliases. */ + m->cpu = vmap(m->pages, size / PAGE_SIZE, VM_MAP, PAGE_KERNEL); + if (!m->cpu) + return -ENOMEM; + /* One provider TLB synchronization for the complete surface, retaining + * identical pages/protection/DVA. iommu_map_sgtable rolls back on error. + */ + if (h16_map_batch) { + struct sg_table sgt; + ssize_t mapped; + + ret = sg_alloc_table_from_pages(&sgt, m->pages, size / PAGE_SIZE, + 0, size, GFP_KERNEL); + if (ret) + return ret; + mapped = iommu_map_sgtable(h->domain, dva, &sgt, + IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); + sg_free_table(&sgt); + if (mapped < 0) + return mapped; + m->mapped = mapped; + if ((size_t)mapped != size) + return -EIO; + } else { + /* Every backing page was allocated with __GFP_ZERO above. */ + for (i = 0; i < m->blocks; i++) { + ret = iommu_map(h->domain, dva + i * SZ_16K, + page_to_phys(m->pages[i * pages_per_block]), SZ_16K, + IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, GFP_KERNEL); + if (ret) + return ret; + m->mapped += SZ_16K; + } + } + *out = (struct ane_fw_surface) { .cpu = m->cpu, .dva = dva, .size = size }; + return 0; +} + +static u64 ane_h16_load64(void *ctx, const void *p) +{ + return le64_to_cpu(READ_ONCE(*(const __le64 *)p)); +} + +static void ane_h16_store64(void *ctx, void *p, u64 value) +{ + WRITE_ONCE(*(__le64 *)p, cpu_to_le64(value)); +} + +static void ane_h16_dma_read_barrier(void *ctx) +{ + dma_rmb(); +} + +static void ane_h16_dma_write_barrier(void *ctx) +{ + dma_wmb(); +} + +static u32 ane_h16_engine_read(void *ctx, u32 offset) +{ + return ane_h16_mmio_read32(ctx, ANE_H16_ENGINE, offset); +} + +static void ane_h16_startup_record(struct ane_h16_device *h, u32 type, u32 value) +{ + u32 i; + + if (!h->startup_tracing) + return; + i = h->startup_trace_count; + if (i == ARRAY_SIZE(h->startup_trace)) { + h->startup_trace_dropped++; + return; + } + h->startup_trace[i].ns = ktime_get_ns(); + h->startup_trace[i].counter = get_cycles(); + h->startup_trace[i].type = type; + h->startup_trace[i].value = value; + h->startup_trace[i].shared_count = h->boot.transport.shared_count; + h->startup_trace_count++; +} + +static u64 ane_h16_ack_counter(void *ctx) +{ + return get_cycles(); +} + +static u32 ane_h16_ack_cpu(void *ctx) +{ + return raw_smp_processor_id(); +} + +static u32 ane_h16_ack_read(void *ctx) +{ + struct ane_h16_device *h = ctx; + + return readl(h->window[ANE_H16_ENGINE] + 0x1888000); +} + +static void ane_h16_ack_write(void *ctx, u32 value) +{ + struct ane_h16_device *h = ctx; + + ane_h16_mmio_write32(h, ANE_H16_ENGINE, h->boot.soc->doorbell, value); +} + +static const struct ane_fw_ack_pending_ops ane_h16_ack_ops = { + .counter = ane_h16_ack_counter, + .cpu = ane_h16_ack_cpu, + .read_pending = ane_h16_ack_read, + .write_doorbell = ane_h16_ack_write, +}; + +static void ane_h16_engine_write(void *ctx, u32 offset, u32 value) +{ + struct ane_h16_device *h = ctx; + + if (h16_job_ack_pending_mode && h->active_ack_pending && + offset == h->boot.soc->doorbell && + value == BIT(h->boot.transport.channels[ANE_FW_IO_T2H].bit)) + ane_fw_ack_pending_observe(h, &ane_h16_ack_ops, h->active_ack_pending, + h16_job_ack_pending_mode, + h->boot.transport.channels[ANE_FW_IO_T2H].bit, value); + else + ane_h16_mmio_write32(ctx, ANE_H16_ENGINE, offset, value); + if (offset == h->boot.soc->doorbell) + ane_h16_startup_record(h, 1, value); + if (offset == h->boot.soc->irq_ack) { + /* Complete the snapshot acknowledgment before ring reads (r5). */ + mb(); + } +} + +static u64 ane_h16_now(void *ctx) +{ + return ktime_get_ns(); +} + +static void ane_h16_relax(void *ctx) +{ + struct ane_h16_device *h = ctx; + int ret; + + ane_h16_mailbox(h); + ret = ane_h16_faults(&h->boot, false); + if (ret) + ane_fw_transport_fail(&h->boot.transport, ret); + ane_h16_delay(h, clamp(h16_startup_poll_us, 10U, 1000U)); +} + +static int ane_h16_alloc_shared(void *ctx, size_t size, u32 tag, struct ane_fw_surface *out) +{ + struct ane_h16_device *h = ctx; + int ret; + + ane_h16_startup_record(h, 2, tag); + ret = ane_h16_alloc_at(h, h->shared_next, size, out); + + if (!ret) { + h->shared_next += size; + dev_info(h->dev, "H16 SHAREDMALLOC bytes %zx tag %08x DVA %llx\n", + size, tag, out->dva); + } + return ret; +} + +static void ane_h16_refused(void *ctx, u64 w0, u64 w1, u64 w2, int error) +{ + struct ane_h16_device *h = ctx; + + dev_err(h->dev, "H16 SHAREDMALLOC refused %llx %llx %llx error %d\n", + w0, w1, w2, error); +} + +static const struct ane_h16_boot_ops ane_h16_ops = { + .read32 = ane_h16_mmio_read32, + .read64 = ane_h16_mmio_read64, + .write32 = ane_h16_mmio_write32, + .write64 = ane_h16_mmio_write64, + .delay_us = ane_h16_delay, + .map = ane_h16_map, + .alloc_at = ane_h16_alloc_at, + .pin = ane_h16_pin, + .mailbox = ane_h16_mailbox, + .log = ane_h16_log, + .quarantine = ane_h16_quarantine, +}; + +static const struct ane_fw_transport_ops ane_h16_transport_ops = { + .load64 = ane_h16_load64, + .store64 = ane_h16_store64, + .read_barrier = ane_h16_dma_read_barrier, + .write_barrier = ane_h16_dma_write_barrier, + .read32 = ane_h16_engine_read, + .write32 = ane_h16_engine_write, + .now_ns = ane_h16_now, + .relax = ane_h16_relax, + .alloc = ane_h16_alloc_shared, + .refused = ane_h16_refused, +}; + +static void ane_h16_cleanup(struct ane_h16_device *h) +{ + struct ane_h16_mapping *m, *next; + unsigned int i, pages_per_block = SZ_16K / PAGE_SIZE; + + if (h->boot.ran || h->pinned) + return; + list_for_each_entry_safe_reverse(m, next, &h->mappings, node) { + if (m->mapped) + iommu_unmap(h->domain, m->dva, m->mapped); + if (m->cpu) + vunmap(m->cpu); + for (i = 0; i < m->blocks; i++) + __free_pages(m->pages[i * pages_per_block], get_order(SZ_16K)); + kvfree(m->pages); + list_del(&m->node); + kfree(m); + } + if (h->attached) + iommu_detach_device(h->domain, h->dev); + if (h->domain) + iommu_domain_free(h->domain); + if (h->claimed) + iommu_device_release_dma_owner(h->dev); + if (h->group) + iommu_group_put(h->group); + if (h->irq >= 0) + free_irq(h->irq, h); + for (i = ANE_H16_WINDOWS; i-- > 0; ) + if (h->window[i]) + iounmap(h->window[i]); + while (h->darts_powered) + pm_runtime_put_sync(h->dart[--h->darts_powered]); + for (i = 0; i < 3; i++) + if (h->dart[i]) + put_device(h->dart[i]); + while (h->powered) { + struct device *pd = h->power[--h->powered]; + + pm_runtime_put_sync(pd); + dev_pm_domain_detach(pd, true); + } + dev_info(h->dev, "H16 pre-RUN rollback complete; no CPU release\n"); + kfree(h->consume_trace); + kfree(h); +} + +/* Only this handler owns AP channel-status acknowledgment in IRQ mode. + * All transport/ring/allocation state remains in the process-context worker. + */ +static void ane_h16_irq_fault(struct ane_h16_device *h, int error) +{ + if (!atomic_cmpxchg(&h->irq_disabled, 0, 1)) + disable_irq_nosync(h->irq); + ane_fw_irq_event_notify(&h->irq_event, error); +} + +static irqreturn_t ane_h16_channel_irq(int irq, void *data) +{ + struct ane_h16_device *h = data; + u32 value; + unsigned int i; + + if (!READ_ONCE(h->job_irq_mode)) + return IRQ_NONE; + cpumask_set_cpu(raw_smp_processor_id(), &h->irq_seen_cpus); + atomic_inc(&h->irq_calls); + if (atomic_read(&h->irq_disabled)) + return IRQ_HANDLED; + value = ane_h16_engine_read(h, h->boot.soc->irq_status); + if (value & ~GENMASK(7, 0)) { + ane_h16_irq_fault(h, -EPROTO); + return IRQ_HANDLED; + } + if (!value) { + atomic_inc(&h->irq_empty); + /* A wrong source/clear mapping must not storm on this level line. */ + if (atomic_inc_return(&h->irq_empty_run) >= 32) { + ane_h16_irq_fault(h, -EIO); + return IRQ_HANDLED; + } + return IRQ_NONE; + } + atomic_set(&h->irq_empty_run, 0); + ane_h16_engine_write(h, h->boot.soc->irq_ack, value); + /* engine_write completes the ACK barrier BEFORE sequence publication. */ + for (i = 0; i < ANE_FW_CHANNELS; i++) + if (value & BIT(i)) + atomic_inc(&h->irq_status_count[i]); + atomic_inc(&h->irq_notifications); + ane_fw_irq_event_notify(&h->irq_event, 0); + return IRQ_HANDLED; +} + +static int ane_h16_acquire(struct platform_device *pdev, struct ane_h16_device *h) +{ + struct device_node *np = pdev->dev.of_node; + static const char * const names[] = { "engine", "pmgr", "aux-3" }; + unsigned int i, j; + int ret, irq; + + if (of_count_phandle_with_args(np, "power-domains", "#power-domain-cells") != 5) + return -EINVAL; + for (i = 0; i < 5; i++) { + struct device *pd = dev_pm_domain_attach_by_id(h->dev, i); + + if (IS_ERR_OR_NULL(pd)) + return pd ? PTR_ERR(pd) : -ENODEV; + ret = pm_runtime_resume_and_get(pd); + if (ret < 0) { + dev_pm_domain_detach(pd, true); + return ret; + } + h->power[h->powered++] = pd; + } + for (i = 0; i < ARRAY_SIZE(names); i++) { + struct resource *r = platform_get_resource_byname(pdev, IORESOURCE_MEM, names[i]); + + if (!r) + return -ENODEV; + h->window[i] = ioremap_np(r->start, resource_size(r)); + if (!h->window[i]) + return -ENOMEM; + } + for (i = 0; i < 3; i++) { + struct of_phandle_args args; + struct platform_device *dart; + struct resource r; + + ret = of_parse_phandle_with_args(np, "iommus", "#iommu-cells", i, &args); + if (ret) + return ret; + if (args.args_count != 1 || args.args[0] != 0 || + !of_device_is_compatible(args.np, "apple,t8110-dart") || + !of_device_is_available(args.np)) { + of_node_put(args.np); + return -EINVAL; + } + dart = of_find_device_by_node(args.np); + ret = of_address_to_resource(args.np, 0, &r); + of_node_put(args.np); + if (!dart) + return -EPROBE_DEFER; + h->dart[i] = &dart->dev; + for (j = 0; j < i; j++) + if (h->dart[j] == h->dart[i]) + return -EINVAL; + if (ret) + return ret; + ret = pm_runtime_resume_and_get(h->dart[i]); + if (ret < 0) + return ret; + h->darts_powered++; + h->window[ANE_H16_DART0 + i] = ioremap_np(r.start, resource_size(&r)); + h->window[ANE_H16_DAPF0 + i] = ioremap_np(r.start + 0x10000, SZ_16K); + if (!h->window[ANE_H16_DART0 + i] || !h->window[ANE_H16_DAPF0 + i]) + return -ENOMEM; + } + irq = platform_get_irq(pdev, 0); + if (irq < 0) + return irq; + ane_fw_irq_event_init(&h->irq_event); + cpumask_clear(&h->irq_seen_cpus); + atomic_set(&h->irq_calls, 0); + atomic_set(&h->irq_notifications, 0); + atomic_set(&h->irq_empty, 0); + atomic_set(&h->irq_empty_run, 0); + atomic_set(&h->irq_disabled, 0); + atomic_set(&h->irq_waits, 0); + atomic_set(&h->irq_woken, 0); + atomic_set(&h->irq_timeouts, 0); + for (i = 0; i < ANE_FW_CHANNELS; i++) + atomic_set(&h->irq_status_count[i], 0); + ret = request_irq(irq, ane_h16_channel_irq, IRQF_NO_AUTOEN, "ane-h16-channel", h); + if (ret) + return ret; + h->irq = irq; + dev_info(h->dev, "H16 startup polling; channel IRQ held masked until startup completes\n"); + return 0; +} + +static int ane_h16_preload_identity(struct ane_h16_device *h) +{ + struct ane_h16_boot *b = &h->boot; + void *snap[2] = {}, *second = NULL; + unsigned int i; + int ret = -ENOMEM; + + for (i = 0; i < 2; i++) { + struct device_node *np = of_parse_phandle(h->dev->of_node, "memory-region", i); + struct reserved_mem *rmem; + void *live; + + if (!np) { + ret = -ENODATA; + goto out; + } + rmem = of_reserved_mem_lookup(np); + of_node_put(np); + if (!rmem || rmem->size != b->soc->preload_size[i]) { + ret = -EINVAL; + goto out; + } + h->preload_phys[i] = rmem->base; + snap[i] = vzalloc(rmem->size); + second = vzalloc(rmem->size); + if (!snap[i] || !second) + goto out; + live = memremap(rmem->base, rmem->size, MEMREMAP_WB); + if (!live) + goto out; + memcpy(snap[i], live, rmem->size); + /* Separate the two observations used to reject an unstable preload. */ + rmb(); + memcpy(second, live, rmem->size); + memunmap(live); + if (memcmp(snap[i], second, rmem->size)) { + ret = -EBUSY; + goto out; + } + vfree(second); + second = NULL; + } + ret = ane_h16_preload_identify(snap[0], b->soc->preload_size[0], + snap[1], b->soc->preload_size[1]); + if (ret >= 0) { + if (b->soc->h16_builds) + b->build = b->soc->h16_builds[ret]; + h->shared_next = b->build->shared_dva; + dev_info(h->dev, "H16 preload identity %s accepted (boot values %s)\n", + ane_h16_build_names[ret], b->build->identity); + ret = 0; + } else if (ane_h16_observing() && !ane_h16_debugfs) { + dev_warn(h->dev, "H16 preload identity refused (%d); observing, image in debugfs ane_h16/\n", + ret); + for (i = 0; i < 2; i++) { + ane_h16_dump[i].data = snap[i]; + ane_h16_dump[i].size = b->soc->preload_size[i]; + snap[i] = NULL; + } + ane_h16_debugfs = debugfs_create_dir("ane_h16", NULL); + debugfs_create_blob("text", 0400, ane_h16_debugfs, &ane_h16_dump[0]); + debugfs_create_blob("data", 0400, ane_h16_debugfs, &ane_h16_dump[1]); + ret = 0; + } +out: + vfree(second); + vfree(snap[0]); + vfree(snap[1]); + return ret; +} + +/* + * Diagnostic job interface (workspace ane). With h16_job=1 and a completed + * startup stage, one write to debugfs ane_h16/job runs a sequence of records + * {u32 op, u32 length, payload} in order; ane_h16/result then holds one record + * {u32 op, s32 status, u64 ns, u32 length, u32 trailer, data} per job record. The + * host builds every firmware command; the kernel maps, sends and waits. + */ +static unsigned int h16_startup_drain_ms; +module_param(h16_startup_drain_ms, uint, 0444); +MODULE_PARM_DESC(h16_startup_drain_ms, "Service startup allocation/log channels before first IO, max1000ms, default0"); + +static bool h16_job; +module_param(h16_job, bool, 0444); +MODULE_PARM_DESC(h16_job, "Diagnostic: after startup, run host-built jobs from debugfs ane_h16/job"); + +enum { + ANE_H16_JOB_MAP = 1, /* u64 dva, u64 size, data: zero-filled 16K-aligned mapping */ + ANE_H16_JOB_WRITE, /* u64 dva, data */ + ANE_H16_JOB_FILL, /* u64 dva, u64 size, u32 byte */ + ANE_H16_JOB_CMD, /* u32 channel, u32 fill, command; result: the reply */ + ANE_H16_JOB_EVENT, /* u64 uuid, u32 timeout ms; result: reports up to the terminal one */ + ANE_H16_JOB_PEEK, /* u64 dva, u64 size; result: the bytes */ + ANE_H16_JOB_QUIET, /* result only: UUID, handles, requested us, busy, CPU; two counter anchors */ + ANE_H16_JOB_GAP, /* result only: UUID, requested us, CPU; two gap counter anchors */ + ANE_H16_JOB_RETURN, /* result only: UUID, CPU, reserved; one EVENT-return counter */ + ANE_H16_JOB_PENDING, /* result only: bounded quiet-window samples */ +}; + +#define ANE_H16_JOB_FILL_PROGRAM BIT(0) /* u32 program handle at +8 */ +#define ANE_H16_JOB_FILL_PROCESS BIT(1) /* u32 process handle at +0xc */ +#define ANE_H16_JOB_RESULT_MAX SZ_64M +static unsigned int h16_job_result_mb = 64; +module_param(h16_job_result_mb, uint, 0444); +MODULE_PARM_DESC(h16_job_result_mb, "Diagnostic result allocation1..64MiB, default64"); + +#define ANE_H16_JOB_DONE 64 + +struct ane_h16_job { + u8 *out; + size_t used, size; + u32 program, process; + u64 published_ns; + /* Terminal events consumed while waiting for another UUID (pipelined). */ + struct { + u64 uuid; + u32 state; + } done[ANE_H16_JOB_DONE]; + unsigned int done_next; + /* Pool offset where job commands start, and EXECUTEs not yet terminal. */ + size_t pool_mark; + bool marked; + unsigned int outstanding; + u64 last_exec_uuid; + u32 last_exec_handles[3], quiet_warm_handles[3]; + bool quiet_warmed, quiet_batch_pipelined; + struct ane_fw_report_fifo early; + u32 gap_warm_serial; + struct ane_job_recovery recovery; + struct ane_fw_pending_sample *pending_samples; + u8 *pending_record; +}; + +static void *ane_h16_job_cpu(struct ane_h16_device *h, u64 dva, u64 size) +{ + struct ane_h16_mapping *m; + + list_for_each_entry(m, &h->mappings, node) + if (m->cpu && dva >= m->dva && size <= m->size && dva - m->dva <= m->size - size) + return (u8 *)m->cpu + (dva - m->dva); + return NULL; +} + +/* @trailer counts host architectural-counter values after @data; they count + * in the length. Decode with the host arch_timer frequency, independently of + * the firmware event clock (M4 Linux1GHz host versus24MHz firmware). + */ +static int ane_h16_job_emit_counters(struct ane_h16_job *j, u32 op, int status, u64 ns, + const void *data, size_t length, + const u64 *counters, u32 trailer) +{ + size_t total = length + trailer * sizeof(u64); + u8 *r; + u32 i; + + if (j->size - j->used < 24 || total > j->size - j->used - 24) + return -ENOSPC; + r = j->out + j->used; + put_unaligned_le32(op, r); + put_unaligned_le32(status, r + 4); + put_unaligned_le64(ns, r + 8); + put_unaligned_le32(total, r + 16); + put_unaligned_le32(trailer, r + 20); + if (length) + memcpy(r + 24, data, length); + for (i = 0; i < trailer; i++) + put_unaligned_le64(counters[i], r + 24 + length + i * sizeof(u64)); + j->used += 24 + total; + return 0; +} + +static int ane_h16_job_emit(struct ane_h16_job *j, u32 op, int status, u64 ns, + const void *data, size_t length) +{ + return ane_h16_job_emit_counters(j, op, status, ns, data, length, NULL, 0); +} + +/* Optional short-request spin before sleeping; default preserves polled mode. + * Bound CPU cost to 1 ms per wait even if a larger diagnostic value is supplied. + */ +static unsigned int h16_job_spin_us; +module_param(h16_job_spin_us, uint, 0444); +MODULE_PARM_DESC(h16_job_spin_us, "Spin up to this many us before sleeping in job waits (max 1000, default 0)"); + +/* Mechanism probe, not a latency optimization: after the EXECUTE slot ACK, + * withhold transport/MMIO service briefly while firmware runs. At most 10 ms; + * the existing completion deadline and post-window servicing remain in force. + * Default zero leaves the diagnostic polling path unchanged. + */ +static unsigned int h16_job_quiet_us; +module_param(h16_job_quiet_us, uint, 0444); +MODULE_PARM_DESC(h16_job_quiet_us, "Diagnostic no-poll interval before event drain (0..10000 us, default 0)"); +static bool h16_job_quiet_busy; +module_param(h16_job_quiet_busy, bool, 0444); +MODULE_PARM_DESC(h16_job_quiet_busy, "Use private busy work instead of one sleep during no-poll interval"); + +static unsigned int h16_job_quiet_wake_us; +module_param(h16_job_quiet_wake_us, uint, 0444); +MODULE_PARM_DESC(h16_job_quiet_wake_us, "Optional private periodic wakes inside quiet window (10..1000 us,0 disables)"); +static unsigned int h16_job_quiet_work_ns; +module_param(h16_job_quiet_work_ns, uint, 0444); +MODULE_PARM_DESC(h16_job_quiet_work_ns, "Private work after each quiet wake, at most10000ns"); +static bool h16_job_ack_batch; +module_param(h16_job_ack_batch, bool, 0444); +MODULE_PARM_DESC(h16_job_ack_batch, "Private serial EVENT report ACK notification batching, defaultoff; flush before wait/exit, at most4slots"); +static unsigned int h16_job_irq_coalesce_us; +module_param(h16_job_irq_coalesce_us, uint, 0444); +MODULE_PARM_DESC(h16_job_irq_coalesce_us, "Experimental worker delay after IRQ wake,0off/1..25us; preserves original deadline/ACK writes"); + +static unsigned int h16_job_gap_us; +module_param(h16_job_gap_us, uint, 0444); +MODULE_PARM_DESC(h16_job_gap_us, "Diagnostic recovery gap before warmed serial EXECUTE, max2000us/default0; >100us sleeps; included in throughput"); +static unsigned int h16_job_gap_at; +module_param(h16_job_gap_at, uint, 0444); +MODULE_PARM_DESC(h16_job_gap_at, "Apply recovery gap only at this warmed serial EXEC ordinal1..128,0=every eligible call"); +static unsigned int h16_job_recovery_us; +module_param(h16_job_recovery_us, uint, 0444); +MODULE_PARM_DESC(h16_job_recovery_us, "Private serial recovery after ordinary/unknown SUCCESS; dedicated uses gap_us; default0, max2000us"); +static unsigned int h16_job_drain_us; +module_param(h16_job_drain_us, uint, 0444); +MODULE_PARM_DESC(h16_job_drain_us, "Private initial drain1..2000us before warmed ordinal1, followed by every-call hold1..100us; default0"); +static unsigned int h16_job_gap_every; +module_param(h16_job_gap_every, uint, 0444); +MODULE_PARM_DESC(h16_job_gap_every, "Periodic recovery gap every1..128 warmed serial EXECs, default0; excludes gap_at/pending/quiet probes"); + +/* Read-only firmware IRQ-delivery probe, only inside a one-time2ms gap. + * Mode1 is a private active-window control; mode2 also reads FW pending. + */ +static unsigned int h16_job_pending_mode; +module_param(h16_job_pending_mode, uint, 0444); +MODULE_PARM_DESC(h16_job_pending_mode, "Gap pending probe:0off,1private active control,2read FW pending; requires2ms one-shot gap"); + +static u64 ane_h16_pending_counter(void *ctx) +{ + return get_cycles(); +} + +static u32 ane_h16_pending_cpu(void *ctx) +{ + return raw_smp_processor_id(); +} + +static u32 ane_h16_pending_read(void *ctx) +{ + struct ane_h16_device *h = ctx; + + /* 25F84 FW0x8cd0 LDR32; explicit channel clear precedes ACK semaphore. + * Read only. A write here would ACK firmware pending and is forbidden. + */ + return readl(h->window[ANE_H16_ENGINE] + 0x1888000); +} + +static void ane_h16_pending_delay(void *ctx, u32 us) +{ + udelay(us); +} + +static const struct ane_fw_pending_ops ane_h16_pending_ops = { + .now_ns = ane_h16_now, + .counter = ane_h16_pending_counter, + .cpu = ane_h16_pending_cpu, + .read_pending = ane_h16_pending_read, + .delay_us = ane_h16_pending_delay, +}; + +#define ANE_H16_PENDING_HEADER 64 +#define ANE_H16_PENDING_STRIDE 32 +#define ANE_H16_PENDING_BYTES (ANE_H16_PENDING_HEADER + ANE_FW_PENDING_MAX * ANE_H16_PENDING_STRIDE) + +static int ane_h16_pending_record(struct ane_h16_device *h, struct ane_h16_job *j, + u64 uuid, u64 began, u64 until) +{ + u8 *p = j->pending_record; + u32 count, i, bit = h->boot.transport.channels[ANE_FW_IO_T2H].bit; + u64 active_begin = ktime_get_ns(), active_end; + int ret; + + ret = ane_fw_pending_capture(h, &ane_h16_pending_ops, j->pending_samples, + ANE_FW_PENDING_MAX, until, h16_job_pending_mode == 2, &count); + active_end = ktime_get_ns(); + if (ret && ret != -ENOSPC) + return ret; + put_unaligned_le64(uuid, p); + put_unaligned_le32(h16_job_pending_mode, p + 8); + put_unaligned_le32(count, p + 12); + put_unaligned_le32(bit, p + 16); + put_unaligned_le32(ANE_FW_PENDING_MAX, p + 20); + put_unaligned_le32(ANE_FW_PENDING_ACTIVE_US, p + 24); + put_unaligned_le32(2000, p + 28); + put_unaligned_le32(ret == -ENOSPC, p + 32); + put_unaligned_le32(0, p + 36); + put_unaligned_le64(active_begin, p + 40); + put_unaligned_le64(active_end, p + 48); + put_unaligned_le64(until, p + 56); + for (i = 0; i < count; i++) { + const struct ane_fw_pending_sample *sample = &j->pending_samples[i]; + u8 *d = p + ANE_H16_PENDING_HEADER + i * ANE_H16_PENDING_STRIDE; + + put_unaligned_le64(sample->before, d); + put_unaligned_le64(sample->after, d + 8); + put_unaligned_le32(sample->value, d + 16); + put_unaligned_le32(sample->before_cpu, d + 20); + put_unaligned_le32(sample->after_cpu, d + 24); + put_unaligned_le32(sample->valid, d + 28); + } + /* Serialization is inside the overall gap; its existing anchors include it. + * Sleep only the remainder to the SAME original2ms absolute deadline. + */ + until = began + 2000 * NSEC_PER_USEC; + active_end = ktime_get_ns(); + if (active_end < until) { + u32 remaining_us = DIV_ROUND_UP_ULL(until - active_end, NSEC_PER_USEC); + + usleep_range(remaining_us, remaining_us + 10); + } + return ane_h16_job_emit(j, ANE_H16_JOB_PENDING, 0, ktime_get_ns() - began, + p, ANE_H16_PENDING_HEADER + count * ANE_H16_PENDING_STRIDE); +} + +static unsigned int h16_job_poll_us = 10; +module_param(h16_job_poll_us, uint, 0444); +MODULE_PARM_DESC(h16_job_poll_us, "Diagnostic job polling sleep10..1000us, default10"); + +static int ane_h16_job_quiet(struct ane_h16_job *j, u64 uuid) +{ + unsigned int us = min_t(unsigned int, h16_job_quiet_us, 10000); + u64 until, start, counters[2], user_before, sys_before, user_after, sys_after; + u32 wake_us = h16_job_quiet_wake_us ? clamp(h16_job_quiet_wake_us, 10U, 1000U) : 0; + u32 work_ns = min(h16_job_quiet_work_ns, 10000U), wakes = 0, active_ns = 0; + u8 data[56]; + + /* Only a warmed, single outstanding EXEC with the exact same identity. + * Cached/pipelined completions must not masquerade as quiet execution. + */ + if (!us || !uuid || j->outstanding != 1 || j->quiet_batch_pipelined || + uuid != j->last_exec_uuid || + !j->quiet_warmed || memcmp(j->last_exec_handles, + j->quiet_warm_handles, sizeof(j->last_exec_handles))) + return 0; + put_unaligned_le64(uuid, data); + memcpy(data + 8, j->last_exec_handles, sizeof(j->last_exec_handles)); + put_unaligned_le32(us, data + 20); + put_unaligned_le32(h16_job_quiet_busy, data + 24); + put_unaligned_le32(raw_smp_processor_id(), data + 28); + task_cputime_adjusted(current, &user_before, &sys_before); + start = ktime_get_ns(); + counters[0] = get_cycles(); + if (wake_us) { + until = start + (u64)us * NSEC_PER_USEC; + while (ktime_get_ns() < until) { + u64 began, work_until; + + usleep_range(wake_us, wake_us + 10); + began = ktime_get_ns(); + if (began >= until) + break; + work_until = min(began + work_ns, until); + while (ktime_get_ns() < work_until) + cpu_relax(); + active_ns += ktime_get_ns() - began; + wakes++; + } + } else if (!h16_job_quiet_busy) { + usleep_range(us, us + 50); + } else { + until = start + (u64)us * NSEC_PER_USEC; + while (ktime_get_ns() < until) + cpu_relax(); + } + counters[1] = get_cycles(); + task_cputime_adjusted(current, &user_after, &sys_after); + put_unaligned_le32(wake_us, data + 32); + put_unaligned_le32(work_ns, data + 36); + put_unaligned_le32(wakes, data + 40); + /* Completed private blocks exclude the final wake beyond the deadline. + * active_ns is block wall time, including any preemption/IRQ service. + * Scheduler-accounted task CPU delta has its own resolution limits. + */ + put_unaligned_le32(active_ns, data + 44); + put_unaligned_le64(user_after + sys_after - user_before - sys_before, data + 48); + return ane_h16_job_emit_counters(j, ANE_H16_JOB_QUIET, 0, + ktime_get_ns() - start, data, sizeof(data), counters, 2); +} + +static u64 ane_h16_job_spin_deadline(void) +{ + if (!h16_job_spin_us) + return 0; + return ktime_get_ns() + (u64)min_t(unsigned int, h16_job_spin_us, 1000) * NSEC_PER_USEC; +} + +static void ane_h16_job_relax(u64 spin_deadline) +{ + if (spin_deadline && ktime_get_ns() < spin_deadline) + cpu_relax(); + else { + unsigned int us = clamp(h16_job_poll_us, 10U, 1000U); + + usleep_range(us, us + 10); + } +} + +static int ane_h16_job_irq_error(struct ane_h16_device *h) +{ + int error = h->job_irq_mode ? ane_fw_irq_event_error(&h->irq_event) : 0; + + return error ? ane_fw_transport_fail(&h->boot.transport, error) : 0; +} + +/* All coalesced auxiliary requests must be drained before blocking. */ +static int ane_h16_job_irq_service(struct ane_h16_device *h, bool *progress) +{ + struct ane_fw_transport *t = &h->boot.transport; + u64 terminal_before = t->terminal_messages; + u32 rx_before = h->mailbox_rx_count, tx_before = h->tx_read; + int ret = ane_fw_transport_shared_drain(t, progress); + + if (ret) + return ret; + ret = ane_fw_transport_terminal(t); + if (ret) + return ret; + ane_h16_mailbox(h); + if (terminal_before != t->terminal_messages || rx_before != h->mailbox_rx_count || + tx_before != h->tx_read) + *progress = true; + ret = ane_h16_faults(&h->boot, false); + return ret ? ret : ane_h16_job_irq_error(h); +} + +static u64 ane_h16_coalesce_now(void *ctx) +{ + return ktime_get_ns(); +} +static int ane_h16_coalesce_error(void *ctx) +{ + struct ane_h16_device *h = ctx; + + return ane_fw_irq_event_error(&h->irq_event); +} +static void ane_h16_coalesce_delay(void *ctx, u32 us) +{ + udelay(us); +} +static const struct ane_fw_irq_coalesce_ops ane_h16_coalesce_ops = { + .now_ns = ane_h16_coalesce_now, + .error = ane_h16_coalesce_error, + .delay_us = ane_h16_coalesce_delay, +}; + +static int ane_h16_job_irq_pause(struct ane_h16_device *h, unsigned int sequence, + u64 deadline, u64 spin_deadline, bool event_wait) +{ + u64 now = ktime_get_ns(), remaining; + int ret; + + if (now >= deadline) + return ane_fw_transport_fail(&h->boot.transport, -ETIMEDOUT); + if (spin_deadline && now < spin_deadline) { + cpu_relax(); + return ane_h16_job_irq_error(h); + } + remaining = min_t(u64, deadline - now, 10 * NSEC_PER_MSEC); + atomic_inc(&h->irq_waits); + ret = ane_fw_irq_event_wait(&h->irq_event, sequence, ns_to_ktime(remaining)); + if (ret < 0) + return ane_fw_transport_fail(&h->boot.transport, ret); + if (!ret) + atomic_inc(&h->irq_timeouts); + else { + atomic_inc(&h->irq_woken); + if (h16_job_irq_coalesce_us) { + struct ane_fw_irq_coalesce_result result; + struct ane_fw_irq_coalesce_stats *stats = &h->coalesce_stats[event_wait]; + + ret = ane_fw_irq_coalesce(h, &ane_h16_coalesce_ops, + h16_job_irq_coalesce_us, deadline, &result); + stats->calls++; + stats->total_ns += result.elapsed_ns; + if (stats->calls == 1 || result.elapsed_ns < stats->min_ns) + stats->min_ns = result.elapsed_ns; + stats->max_ns = max(stats->max_ns, result.elapsed_ns); + stats->iterations += result.iterations; + stats->clipped += result.clipped; + stats->errors += !!ret; + if (ret) + return ane_fw_transport_fail(&h->boot.transport, ret); + } + } + return ane_h16_job_irq_error(h); +} + +struct ane_h16_report_capture { + struct ane_h16_device *h; + struct ane_h16_job *j; +}; + +static int ane_h16_job_capture(void *ctx, struct ane_fw_report *packet) +{ + struct ane_h16_report_capture *c = ctx; + struct ane_h16_device *h = c->h; + struct ane_h16_job *j = c->j; + struct ane_fw_transport *t = &h->boot.transport; + struct ane_h16_consume_trace trace = {}; + bool tracing = h->consume_trace && h->consume_trace_count < ANE_H16_CONSUME_TRACE_MAX; + u8 *report = packet->data; + size_t size = 0; + u64 ns, counter; + int r; + + if (tracing) { + trace.begin_cpu = raw_smp_processor_id(); + trace.irq_before = atomic_read(&h->irq_calls); + trace.begin_counter = get_cycles(); + } + /* Valid only during this synchronous consume. Always clear before any + * return, including EAGAIN/ENOSPC/errors; IRQ ACK offsets never match. + */ + h->active_ack_pending = tracing && h16_job_ack_pending_mode ? &trace.ack_pending : NULL; + r = ane_fw_transport_consume_traced(t, report, sizeof(packet->data), &size, + tracing ? &trace.transport : NULL); + h->active_ack_pending = NULL; + if (r) + return r; + ns = ktime_get_ns() - j->published_ns; + counter = get_cycles(); + packet->size = size; + packet->ns = ns; + packet->counter = counter; + /* Original physical consume endpoint precedes FIFO/result bookkeeping. */ + if (tracing) { + trace.end_counter = counter; + trace.end_cpu = raw_smp_processor_id(); + trace.irq_after = atomic_read(&h->irq_calls); + trace.token = get_unaligned_le32(report); + trace.command_id = get_unaligned_le16(report + 4); + trace.uuid = 0; + trace.state = U32_MAX; + if (trace.command_id == ANE_H16_EVENT_REPORT && size >= 0x20) { + trace.uuid = get_unaligned_le64(report + 8); + trace.state = get_unaligned_le32(report + 0x1c); + } + h->consume_trace[h->consume_trace_count++] = trace; + } else if (h->consume_trace) { + h->consume_trace_dropped++; + } + return 0; +} + +/* ane_fw_transport_wait with a 10-20 us poll, so job timings are not 1 ms steps. */ +static int ane_h16_job_wait(struct ane_h16_device *h, struct ane_h16_job *j, + unsigned int ch, bool early) +{ + struct ane_fw_transport *t = &h->boot.transport; + u32 pending; + struct ane_h16_report_capture capture = { h, j }; + u64 spin_deadline = ane_h16_job_spin_deadline(); + int ret; + + for (;;) { + unsigned int sequence = ane_fw_irq_event_sequence(&h->irq_event); + bool progress, early_progress = false; + + ret = ane_h16_job_irq_error(h); + if (ret) + return ret; + if (early) { + if (ktime_get_ns() >= t->pending[ch].deadline_ns) + return ane_fw_transport_fail(t, -ETIMEDOUT); + ret = ane_fw_report_fifo_prefetch(&j->early, ane_h16_job_capture, + &capture, 4, &early_progress); + if (ret) + return ane_fw_transport_fail(t, ret); + } + ret = ane_fw_transport_poll(t, ch); + if (ret != -EAGAIN) + return ane_h16_job_irq_error(h) ?: ret; + if (h->job_irq_mode) { + ret = ane_h16_job_irq_service(h, &progress); + if (ret) + return ane_fw_transport_fail(t, ret); + if (ktime_get_ns() >= t->pending[ch].deadline_ns) + return ane_fw_transport_fail(t, -ETIMEDOUT); + ane_fw_transport_rering(t, ch); + if (progress || early_progress) + continue; + ret = ane_h16_job_irq_pause(h, sequence, t->pending[ch].deadline_ns, + spin_deadline, false); + if (ret) + return ret; + continue; + } + ret = ane_fw_transport_irq(t, &pending); + if (ret) + return ret; + ret = ane_fw_transport_shared(t); + if (ret && ret != -EAGAIN) + return ret; + ret = ane_fw_transport_terminal(t); + if (ret) + return ret; + if (ktime_get_ns() >= t->pending[ch].deadline_ns) + return ane_fw_transport_fail(t, -ETIMEDOUT); + ane_fw_transport_rering(t, ch); + ane_h16_mailbox(h); + ret = ane_h16_faults(&h->boot, false); + if (ret) + return ane_fw_transport_fail(t, ret); + if (early_progress) + continue; + ane_h16_job_relax(spin_deadline); + } +} + +static int ane_h16_job_cmd(struct ane_h16_device *h, struct ane_h16_job *j, + const u8 *p, u32 length, u64 *ns) +{ + struct ane_fw_transport *t = &h->boot.transport; + u32 channel, fill; + u8 *command; + u64 start, counters[2]; + int ret; + + if (length < 16) + return -EINVAL; + channel = get_unaligned_le32(p); + fill = get_unaligned_le32(p + 4); + length -= 8; + command = kmemdup(p + 8, length, GFP_KERNEL); + if (!command) + return -ENOMEM; + if (fill & ANE_H16_JOB_FILL_PROGRAM) + put_unaligned_le32(j->program, command + 8); + if ((fill & ANE_H16_JOB_FILL_PROCESS) && length >= 16) + put_unaligned_le32(j->process, command + 0xc); + /* + * The transport appends commands to its pool and never reuses it. Wrap to + * the job's first command once nothing is outstanding. + */ + if (!j->marked) { + j->pool_mark = t->pool_used; + j->marked = true; + } + if (ALIGN(t->pool_used, ANE_FW_SLOT_SIZE) + length > t->pool.size && !j->outstanding) + t->pool_used = j->pool_mark; + /* A diagnostic recovery interval for RPC report retirement. Never hold + * back an already-pipelined request or the first call of a new identity. + * Its separate record keeps the interval in complete cycle accounting. + */ + if (h16_job_gap_us && length >= 0x28 && + get_unaligned_le16(command + 4) == ANE_H16_EXECUTE && + !j->outstanding && j->quiet_warmed && + !memcmp(command + 8, j->quiet_warm_handles, sizeof(j->quiet_warm_handles))) { + j->gap_warm_serial++; + if (ane_job_gap_selected(j->gap_warm_serial, h16_job_gap_at, h16_job_gap_every)) { + u8 gap[16]; + u64 gap_counters[2], began; + u32 us = ane_job_gap_duration(j->gap_warm_serial, + h16_job_gap_us, h16_job_drain_us); + + if (h16_job_recovery_us) + us = ane_job_recovery_duration(&j->recovery, j->quiet_warm_handles, + h16_job_gap_us, h16_job_recovery_us); + put_unaligned_le64(get_unaligned_le64(command + 0x20), gap); + put_unaligned_le32(us, gap + 8); + put_unaligned_le32(raw_smp_processor_id(), gap + 12); + began = ktime_get_ns(); + gap_counters[0] = get_cycles(); + if (h16_job_pending_mode) { + ret = ane_h16_pending_record(h, j, get_unaligned_le64(command + 0x20), + began, began + ANE_FW_PENDING_ACTIVE_US * NSEC_PER_USEC); + if (ret) { + kfree(command); + return ret; + } + } else if (us > 100) { + usleep_range(us, us + 10); + } else { + udelay(us); + } + gap_counters[1] = get_cycles(); + ret = ane_h16_job_emit_counters(j, ANE_H16_JOB_GAP, 0, + ktime_get_ns() - began, gap, sizeof(gap), gap_counters, 2); + if (ret) { + kfree(command); + return ret; + } + } + } + /* Consume feedback once, before any new EXECUTE (including new identities + * and overlapping submissions). Only a matching serial SUCCESS restores it. + */ + if (h16_job_recovery_us && length >= 8 && + get_unaligned_le16(command + 4) == ANE_H16_EXECUTE) + ane_job_recovery_reset(&j->recovery); + start = ktime_get_ns(); + counters[0] = get_cycles(); + ret = ane_fw_transport_publish(t, channel, command, length, + start + h->boot.build->command_timeout_ns); + if (!ret) { + j->published_ns = start; + if (get_unaligned_le16(command + 4) == ANE_H16_EXECUTE) { + if (j->outstanding) + j->quiet_batch_pipelined = true; + j->outstanding++; + j->last_exec_uuid = 0; + if (length >= 0x28) { + j->last_exec_uuid = get_unaligned_le64(command + 0x20); + memcpy(j->last_exec_handles, command + 8, + sizeof(j->last_exec_handles)); + } + } + ret = ane_h16_job_wait(h, j, channel, h16_job_early_drain && + get_unaligned_le16(command + 4) == ANE_H16_EXECUTE); + } + counters[1] = get_cycles(); + *ns = ktime_get_ns() - start; + if (t->pending[channel].rerings) + dev_info(h->dev, "H16 job command %x on ch %u: %u doorbell re-rings, %d\n", + get_unaligned_le16(command + 4), channel, t->pending[channel].rerings, ret); + if (!ret || ret == -EREMOTEIO) { + const u8 *reply = (u8 *)t->pool.cpu + (t->pending[channel].dva - t->pool.dva); + u16 id = get_unaligned_le16(reply + 4); + + if (!ret && id == ANE_H16_LOAD_PROGRAM && length >= 0x1bc) + j->program = get_unaligned_le32(reply + 0x1b8); + if (!ret && id == ANE_H16_CREATE_PROCESS && length >= 0x10) + j->process = get_unaligned_le32(reply + 0xc); + memcpy(command, reply, length); + } + ret = ane_h16_job_emit_counters(j, ANE_H16_JOB_CMD, ret, *ns, command, length, + counters, 2) ?: ret; + kfree(command); + return ret; +} + +/* Collect IO_T2H reports until the terminal event of @uuid or the timeout. */ +static int ane_h16_job_event_inner(struct ane_h16_device *h, struct ane_h16_job *j, + u64 uuid, u32 timeout_ms) +{ + struct ane_fw_transport *t = &h->boot.transport; + u64 deadline = ktime_get_ns() + (u64)timeout_ms * NSEC_PER_MSEC; + struct ane_fw_report packet; + u8 *report = packet.data; + struct ane_h16_report_capture capture = { h, j }; + u64 spin_deadline = ane_h16_job_spin_deadline(); + int ret = -ETIMEDOUT; + unsigned int i; + + ret = ane_h16_job_irq_error(h); + if (ret) + return ret; + for (i = 0; i < ANE_H16_JOB_DONE; i++) { + if (j->done[i].uuid != uuid || !uuid) + continue; + j->done[i].uuid = 0; + return ane_h16_job_irq_error(h) ?: (j->done[i].state == ANE_H16_EVENT_SUCCESS ? 0 : -EIO); + } + ret = ane_h16_job_quiet(j, uuid); + if (ret) + return ret; + while (ktime_get_ns() < deadline) { + size_t size = 0; + u32 pending; + unsigned int sequence = ane_fw_irq_event_sequence(&h->irq_event); + bool progress; + int r = ane_h16_job_irq_error(h); + + if (r) + return r; + r = ane_fw_report_fifo_pop(&j->early, &packet); + if (r == -EAGAIN) + r = ane_h16_job_capture(&capture, &packet); + if (!r) { + u64 ns = packet.ns, counter = packet.counter; + + size = packet.size; + r = ane_h16_job_emit_counters(j, ANE_H16_JOB_EVENT, 0, ns, report, size, + &counter, 1); + if (r) + return r; + if (size >= 0x20 && get_unaligned_le16(report + 4) == ANE_H16_EVENT_REPORT) { + u64 id = get_unaligned_le64(report + 8); + u32 state = get_unaligned_le32(report + 0x1c); + bool terminal = state == ANE_H16_EVENT_SUCCESS || + state == ANE_H16_EVENT_FAILURE; + bool serial = j->outstanding == 1 && !j->quiet_batch_pipelined; + + if (terminal && j->outstanding) { + j->outstanding--; + if (!j->outstanding) + j->quiet_batch_pipelined = false; + } + if (id == uuid && terminal) { + if (state == ANE_H16_EVENT_SUCCESS && size >= 0x30 && + id == j->last_exec_uuid && + !memcmp(report + 0x10, j->last_exec_handles, + sizeof(j->last_exec_handles))) { + memcpy(j->quiet_warm_handles, j->last_exec_handles, + sizeof(j->quiet_warm_handles)); + j->quiet_warmed = true; + if (h16_job_recovery_us) + ane_job_recovery_observe(&j->recovery, serial, + get_unaligned_le32(report), j->last_exec_handles); + } + return ane_h16_job_irq_error(h) ?: (state == ANE_H16_EVENT_SUCCESS ? 0 : -EIO); + } + if (terminal) { + j->done[j->done_next].uuid = id; + j->done[j->done_next].state = state; + j->done_next = (j->done_next + 1) % ANE_H16_JOB_DONE; + } + } + continue; + } + if (r != -EAGAIN) + return r; + /* EMPTY is a flush boundary, before any service or sleep. */ + ane_fw_report_ack_flush(t); + if (h->job_irq_mode) { + r = ane_h16_job_irq_service(h, &progress); + if (r) + return ane_fw_transport_fail(t, r); + if (progress) + continue; + r = ane_h16_job_irq_pause(h, sequence, deadline, spin_deadline, true); + if (r) + return r; + ret = -ETIMEDOUT; + continue; + } + r = ane_fw_transport_irq(t, &pending); + if (r) + return r; + r = ane_fw_transport_shared(t); + if (r && r != -EAGAIN) + return r; + r = ane_fw_transport_terminal(t); + if (r) + return r; + ane_h16_mailbox(h); + ret = ane_h16_faults(&h->boot, false); + if (ret) + return ret; + ret = -ETIMEDOUT; + ane_h16_job_relax(spin_deadline); + } + /* A quiet/progress path may leave ret==0; expiry is never success. */ + return ane_h16_job_irq_error(h) ?: -ETIMEDOUT; +} + +/* All inner returns, including errors/timeout/terminal, pass this flush. */ +static int ane_h16_job_event(struct ane_h16_device *h, struct ane_h16_job *j, + u64 uuid, u32 timeout_ms) +{ + struct ane_fw_transport *t = &h->boot.transport; + int ret; + + t->report_ack_defer = ane_fw_report_batch_eligible(h16_job_ack_batch, + j->outstanding, j->quiet_batch_pipelined); + ret = ane_h16_job_event_inner(h, j, uuid, timeout_ms); + ane_fw_report_batch_end(t); + return ret; +} + +static int ane_h16_job_run(struct ane_h16_device *h, struct ane_h16_job *j, + const u8 *p, size_t size) +{ + while (size >= 8) { + u32 op = get_unaligned_le32(p), length = get_unaligned_le32(p + 4); + const u8 *a = p + 8; + u64 ns = 0; + int ret = 0; + + if (length > size - 8) + return -EINVAL; + switch (op) { + case ANE_H16_JOB_MAP: { + struct ane_fw_surface s; + u64 dva, bytes; + + if (length < 16) + return -EINVAL; + dva = get_unaligned_le64(a); + bytes = get_unaligned_le64(a + 8); + if (length - 16 > bytes) + return -EINVAL; + ns = ktime_get_ns(); + ret = ane_h16_alloc_at(h, dva, ALIGN(bytes, SZ_16K), &s); + if (!ret) + memcpy(s.cpu, a + 16, length - 16); + ns = ktime_get_ns() - ns; + break; + } + case ANE_H16_JOB_WRITE: + case ANE_H16_JOB_FILL: + case ANE_H16_JOB_PEEK: { + u64 dva, bytes; + u8 *cpu; + + if (length < (op == ANE_H16_JOB_WRITE ? 8 : 16)) + return -EINVAL; + dva = get_unaligned_le64(a); + bytes = op == ANE_H16_JOB_WRITE ? length - 8 : get_unaligned_le64(a + 8); + cpu = ane_h16_job_cpu(h, dva, bytes); + if (!cpu) { + ret = -ENOENT; + break; + } + if (op != ANE_H16_JOB_PEEK) + ns = ktime_get_ns(); + if (op == ANE_H16_JOB_WRITE) + memcpy(cpu, a + 8, bytes); + else if (op == ANE_H16_JOB_FILL) + memset(cpu, length >= 20 ? a[16] : 0, bytes); + else + ret = ane_h16_job_emit(j, op, 0, 0, cpu, bytes); + if (op != ANE_H16_JOB_PEEK) + ns = ktime_get_ns() - ns; + break; + } + case ANE_H16_JOB_CMD: + ret = ane_h16_job_cmd(h, j, a, length, &ns); + if (ret) + return ret; + break; + case ANE_H16_JOB_EVENT: + if (length < 12) + return -EINVAL; + ret = ane_h16_job_event(h, j, get_unaligned_le64(a), get_unaligned_le32(a + 8)); + if (h16_job_return_trace) { + u8 data[16] = {}; + u64 counter = get_cycles(); + int emitted; + + put_unaligned_le64(get_unaligned_le64(a), data); + put_unaligned_le32(raw_smp_processor_id(), data + 8); + emitted = ane_h16_job_emit_counters(j, ANE_H16_JOB_RETURN, ret, + 0, data, sizeof(data), &counter, 1); + if (emitted) + return emitted; + } + ns = ktime_get_ns() - j->published_ns; + break; + default: + return -EINVAL; + } + if (op != ANE_H16_JOB_PEEK && op != ANE_H16_JOB_CMD) + ane_h16_job_emit(j, op, ret, ns, NULL, 0); + if (ret) + return ret; + p += 8 + length; + size -= 8 + length; + } + return size ? -EINVAL : 0; +} + +static void ane_h16_irq_job_begin(struct ane_h16_device *h) +{ + h->boot.transport.report_ack_slots = 0; + h->boot.transport.report_ack_doorbells = 0; + h->boot.transport.report_ack_peak = 0; + memset(h->coalesce_stats, 0, sizeof(h->coalesce_stats)); + h->irq_job_base[0] = atomic_read(&h->irq_calls); + h->irq_job_base[1] = atomic_read(&h->irq_notifications); + h->irq_job_base[2] = atomic_read(&h->irq_empty); + h->irq_job_base[3] = atomic_read(&h->irq_waits); + h->irq_job_base[4] = atomic_read(&h->irq_woken); + h->irq_job_base[5] = atomic_read(&h->irq_timeouts); +} + +static int ane_h16_irq_stats_show(struct seq_file *s, void *unused) +{ + struct ane_h16_device *h = s->private; + const struct cpumask *effective = irq_get_effective_affinity_mask(h->irq); + u32 calls = (u32)atomic_read(&h->irq_calls) - h->irq_job_base[0]; + u32 notifications = (u32)atomic_read(&h->irq_notifications) - h->irq_job_base[1]; + u32 empty = (u32)atomic_read(&h->irq_empty) - h->irq_job_base[2]; + u32 waits = (u32)atomic_read(&h->irq_waits) - h->irq_job_base[3]; + u32 woken = (u32)atomic_read(&h->irq_woken) - h->irq_job_base[4]; + u32 timeouts = (u32)atomic_read(&h->irq_timeouts) - h->irq_job_base[5]; + int error = ane_fw_irq_event_error(&h->irq_event); + unsigned int i; + + if (!effective) + effective = cpu_possible_mask; + seq_printf(s, "{\"available\":true,\"mode\":%s,\"active\":%s,\"linux_irq\":%d,", + h->job_irq_mode ? "true" : "false", + h->job_irq_mode && !atomic_read(&h->irq_disabled) ? "true" : "false", h->irq); + seq_printf(s, "\"calls\":%u,\"notifications\":%u,\"empty\":%u,\"waits\":%u,\"woken\":%u,\"fallbacks\":%u,", + calls, notifications, empty, waits, woken, timeouts); + seq_printf(s, "\"delivered\":%s,\"wait_notified\":%s,\"error\":%d,\"ok\":%s,", + notifications ? "true" : "false", woken ? "true" : "false", error, + !error && !atomic_read(&h->irq_disabled) ? "true" : "false"); + seq_printf(s, "\"handler_cpus_since_enable\":\"%*pbl\",\"effective_affinity\":\"%*pbl\",\"status_counts_since_enable\":[", + cpumask_pr_args(&h->irq_seen_cpus), cpumask_pr_args(effective)); + for (i = 0; i < ANE_FW_CHANNELS; i++) + seq_printf(s, "%s%u", i ? "," : "", (u32)atomic_read(&h->irq_status_count[i])); + seq_printf(s, "],\"coalesce_us\":%u,\"coalesce\":[", h16_job_irq_coalesce_us); + for (i = 0; i < 2; i++) { + struct ane_fw_irq_coalesce_stats *c = &h->coalesce_stats[i]; + + seq_printf(s, "%s{\"source\":\"%s\",\"calls\":%llu,\"total_ns\":%llu,\"min_ns\":%llu,\"max_ns\":%llu,\"iterations\":%llu,\"clipped\":%llu,\"errors\":%llu}", + i ? "," : "", i ? "EVENT" : "CMD", c->calls, c->total_ns, + c->min_ns, c->max_ns, c->iterations, c->clipped, c->errors); + } + seq_printf(s, "],\"report_acks\":{\"batch\":%s,\"slots\":%llu,\"doorbells\":%llu,\"pending\":%u,\"peak\":%u,\"defer\":%s}}\n", + h16_job_ack_batch ? "true" : "false", + h->boot.transport.report_ack_slots, h->boot.transport.report_ack_doorbells, + h->boot.transport.report_ack_pending, h->boot.transport.report_ack_peak, + h->boot.transport.report_ack_defer ? "true" : "false"); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(ane_h16_irq_stats); + +static ssize_t ane_h16_job_write(struct file *file, const char __user *buf, size_t count, + loff_t *ppos) +{ + struct ane_h16_job j = {}; + u8 *in; + int ret; + + if (*ppos || count > SZ_256M || !h16_job_result_mb || h16_job_result_mb > 64) + return -EINVAL; + in = vmemdup_user(buf, count); + if (IS_ERR(in)) + return PTR_ERR(in); + j.size = (size_t)h16_job_result_mb * SZ_1M; + j.out = vzalloc(j.size); + if (!j.out) { + kvfree(in); + return -ENOMEM; + } + if (h16_job_pending_mode) { + j.pending_samples = kcalloc(ANE_FW_PENDING_MAX, sizeof(*j.pending_samples), GFP_KERNEL); + j.pending_record = kmalloc(ANE_H16_PENDING_BYTES, GFP_KERNEL); + if (!j.pending_samples || !j.pending_record) { + kfree(j.pending_samples); + kfree(j.pending_record); + vfree(j.out); + kvfree(in); + return -ENOMEM; + } + } + if (h16_job_early_drain) { + ret = ane_fw_report_fifo_init(&j.early); + if (ret) { + kfree(j.pending_samples); + kfree(j.pending_record); + vfree(j.out); + kvfree(in); + return ret; + } + } + mutex_lock(&ane_h16_lock); + if (!ane_h16_job_dev) { + ret = -ENODEV; + } else { + ane_h16_job_dev->consume_trace_count = 0; + ane_h16_job_dev->consume_trace_dropped = 0; + ane_h16_irq_job_begin(ane_h16_job_dev); + ret = ane_h16_job_irq_error(ane_h16_job_dev); + if (!ret) + ret = ane_h16_job_run(ane_h16_job_dev, &j, in, count); + ret = ane_h16_job_irq_error(ane_h16_job_dev) ?: ret; + if (!ret && h16_job_early_drain) { + ret = ane_fw_report_fifo_complete(&j.early, j.outstanding); + if (ret) { + ane_h16_job_emit(&j, ANE_H16_JOB_EVENT, ret, 0, NULL, 0); + ret = ane_fw_transport_fail(&ane_h16_job_dev->boot.transport, ret); + } + } + ane_h16_job_dev->early_consumes = j.early.captured; + ane_h16_job_dev->early_peak = j.early.peak; + ane_h16_job_dev->early_remaining = ane_fw_report_fifo_count(&j.early); + ane_h16_job_dev->early_full_errors = j.early.full_errors; + dev_info(ane_h16_job_dev->dev, "H16 job %zu bytes: %d, result %zu bytes\n", + count, ret, j.used); + } + vfree(ane_h16_job_result.data); + ane_h16_job_result.data = j.out; + ane_h16_job_result.size = j.used; + mutex_unlock(&ane_h16_lock); + ane_fw_report_fifo_free(&j.early); + kfree(j.pending_samples); + kfree(j.pending_record); + kvfree(in); + return ret ? ret : count; +} + +static const struct file_operations ane_h16_job_fops = { + .owner = THIS_MODULE, + .write = ane_h16_job_write, +}; + +/* + * Diagnostic, workspace ane: macOS 25F84 ends ANE_Init with these three engine + * writes after its startup commands (re/25F84-kext.md, epilogue 0x92dfbf0). + */ +static bool h16_postboot; +module_param(h16_postboot, bool, 0444); +MODULE_PARM_DESC(h16_postboot, "After startup, do macOS's post-boot writes 0x1880058=1, 0x1880060=0, 0x196c000|=1"); + +static void ane_h16_postboot(struct ane_h16_device *h) +{ + void __iomem *e = h->window[ANE_H16_ENGINE]; + u32 a = readl(e + 0x1880058), b = readl(e + 0x1880060), c = readl(e + 0x196c000); + + writel(1, e + 0x1880058); + writel(0, e + 0x1880060); + writel(c | 1, e + 0x196c000); + dev_info(h->dev, "H16 post-boot writes: 0x1880058 %x->%x 0x1880060 %x->%x 0x196c000 %x->%x\n", + a, readl(e + 0x1880058), b, readl(e + 0x1880060), c, readl(e + 0x196c000)); +} + +static int ane_h16_consume_trace_show(struct seq_file *m, void *unused) +{ + struct ane_h16_device *h = m->private; + u32 i, k; + + mutex_lock(&ane_h16_lock); + seq_printf(m, "{\"schema\":1,\"enabled\":%s,\"count\":%u,\"dropped\":%u,\"ack_pending_mode\":%u,\"records\":[", + h->consume_trace ? "true" : "false", h->consume_trace_count, + h->consume_trace_dropped, h16_job_ack_pending_mode); + for (i = 0; i < h->consume_trace_count; i++) { + struct ane_h16_consume_trace *r = &h->consume_trace[i]; + + seq_printf(m, "%s{\"index\":%u,\"dva\":%llu,\"length\":%llu,\"slot\":%u,\"token\":%u,\"command_id\":%u,\"uuid\":%llu,\"state\":%u,", + i ? "," : "", i, r->transport.dva, r->transport.length, + r->transport.slot, r->token, r->command_id, r->uuid, r->state); + seq_printf(m, "\"begin_counter\":%llu,\"end_counter\":%llu,\"begin_cpu\":%u,\"end_cpu\":%u,\"irq_before\":%u,\"irq_after\":%u,\"ns\":[", + r->begin_counter, r->end_counter, r->begin_cpu, r->end_cpu, + r->irq_before, r->irq_after); + for (k = 0; k < ARRAY_SIZE(r->transport.ns); k++) + seq_printf(m, "%s%llu", k ? "," : "", r->transport.ns[k]); + seq_printf(m, "],\"ack_pending\":{\"mode\":%u,\"calls\":%u,\"bit\":%u,\"valid\":%u,\"before_value\":%u,\"after_value\":%u,\"before_cpu\":%u,\"after_cpu\":%u,\"counters\":[", + r->ack_pending.mode, r->ack_pending.calls, r->ack_pending.bit, + r->ack_pending.valid, r->ack_pending.before_value, r->ack_pending.after_value, + r->ack_pending.before_cpu, r->ack_pending.after_cpu); + for (k = 0; k < ARRAY_SIZE(r->ack_pending.counters); k++) + seq_printf(m, "%s%llu", k ? "," : "", r->ack_pending.counters[k]); + seq_puts(m, "]}}"); + } + seq_puts(m, "]}\n"); + mutex_unlock(&ane_h16_lock); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(ane_h16_consume_trace); + +/* One immutable copy per open. Never dereference a firmware VA as a host pointer. */ +struct ane_h16_data_snapshot { + void *data; + size_t size; +}; + +static int ane_h16_data_snapshot_open(struct inode *inode, struct file *file) +{ + struct ane_h16_device *h = inode->i_private; + struct ane_h16_data_snapshot *snapshot = NULL; + void *live = NULL; + size_t size; + int ret = -ENOMEM; + + mutex_lock(&ane_h16_lock); + size = h->boot.soc->preload_size[1]; + if (!h16_job_snapshot || !h->boot.ran || size != 0x2ac000 || + h->boot.soc->preload_dva[1] != 0x100000c0000ULL) { + ret = -EOPNOTSUPP; + goto out; + } + snapshot = kzalloc_obj(*snapshot); + if (!snapshot) + goto out; + snapshot->data = vmalloc(size); + if (!snapshot->data) + goto out; + live = memremap(h->preload_phys[1], size, MEMREMAP_WB); + if (!live) + goto out; + snapshot->size = size; + h->snapshot_begin_cpu = raw_smp_processor_id(); + h->snapshot_begin = get_cycles(); + dma_rmb(); + memcpy(snapshot->data, live, size); + dma_rmb(); + h->snapshot_end = get_cycles(); + h->snapshot_end_cpu = raw_smp_processor_id(); + h->snapshot_sequence++; + file->private_data = snapshot; + ret = nonseekable_open(inode, file); + memunmap(live); + mutex_unlock(&ane_h16_lock); + return ret; + +out: + if (live) + memunmap(live); + if (snapshot) { + vfree(snapshot->data); + kfree(snapshot); + } + mutex_unlock(&ane_h16_lock); + return ret; +} + +static ssize_t ane_h16_data_snapshot_read(struct file *file, char __user *buf, + size_t count, loff_t *ppos) +{ + struct ane_h16_data_snapshot *snapshot = file->private_data; + + return simple_read_from_buffer(buf, count, ppos, snapshot->data, snapshot->size); +} + +static int ane_h16_data_snapshot_release(struct inode *inode, struct file *file) +{ + struct ane_h16_data_snapshot *snapshot = file->private_data; + + vfree(snapshot->data); + kfree(snapshot); + return 0; +} + +static const struct file_operations ane_h16_data_snapshot_fops = { + .owner = THIS_MODULE, + .open = ane_h16_data_snapshot_open, + .read = ane_h16_data_snapshot_read, + .release = ane_h16_data_snapshot_release, +}; + +static int ane_h16_data_snapshot_info_show(struct seq_file *m, void *unused) +{ + struct ane_h16_device *h = m->private; + + mutex_lock(&ane_h16_lock); + seq_printf(m, "{\"sequence\":%llu,\"begin_counter\":%llu,\"end_counter\":%llu,\"begin_cpu\":%u,\"end_cpu\":%u,\"dva\":%llu,\"size\":%llu,\"firmware_vm_base\":786432,\"atomic\":false}\n", + h->snapshot_sequence, h->snapshot_begin, h->snapshot_end, + h->snapshot_begin_cpu, h->snapshot_end_cpu, + h->boot.soc->preload_dva[1], h->boot.soc->preload_size[1]); + mutex_unlock(&ane_h16_lock); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(ane_h16_data_snapshot_info); + +static int ane_h16_early_stats_show(struct seq_file *m, void *unused) +{ + struct ane_h16_device *h = m->private; + + mutex_lock(&ane_h16_lock); + seq_printf(m, "{\"mode\":%s,\"return_trace\":%s,\"consumed\":%u,\"fifo_peak\":%u,\"remaining\":%u,\"full_errors\":%u}\n", + h16_job_early_drain ? "true" : "false", + h16_job_return_trace ? "true" : "false", h->early_consumes, + h->early_peak, h->early_remaining, h->early_full_errors); + mutex_unlock(&ane_h16_lock); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(ane_h16_early_stats); + +static void ane_h16_job_publish(struct ane_h16_device *h) +{ + if (!h16_job || ane_h16_job_dev) + return; + if (!ane_h16_debugfs) + ane_h16_debugfs = debugfs_create_dir("ane_h16", NULL); + if (h16_job_trace) { + h->consume_trace = kcalloc(ANE_H16_CONSUME_TRACE_MAX, + sizeof(*h->consume_trace), GFP_KERNEL); + if (!h->consume_trace) + return; + } + if (h16_job_irq) { + u32 pending; + int ret = ane_fw_transport_irq(&h->boot.transport, &pending); + + if (ret) { + dev_err(h->dev, "H16 IRQ preflight refused: %d\n", ret); + return; + } + WRITE_ONCE(h->job_irq_mode, true); + enable_irq(h->irq); + dev_info(h->dev, "H16 job IRQ mode enabled on Linux IRQ %d\n", h->irq); + } + ane_h16_job_dev = h; + if (h16_job_snapshot) { + debugfs_create_file("data_snapshot", 0400, ane_h16_debugfs, h, + &ane_h16_data_snapshot_fops); + debugfs_create_file("data_snapshot_info", 0400, ane_h16_debugfs, h, + &ane_h16_data_snapshot_info_fops); + } + debugfs_create_file("early_stats", 0400, ane_h16_debugfs, h, &ane_h16_early_stats_fops); + debugfs_create_file("consume_trace", 0400, ane_h16_debugfs, h, &ane_h16_consume_trace_fops); + debugfs_create_file("irq_stats", 0400, ane_h16_debugfs, h, &ane_h16_irq_stats_fops); + debugfs_create_file("job", 0200, ane_h16_debugfs, NULL, &ane_h16_job_fops); + debugfs_create_blob("result", 0400, ane_h16_debugfs, &ane_h16_job_result); + dev_info(h->dev, "H16 job interface in debugfs ane_h16/\n"); +} + +/* Never alter DMA ownership or reset the firmware while observing a failure. */ +static void ane_h16_failure_copy(struct ane_h16_device *h, unsigned int index, + const char *name, const void *cpu, size_t size, u64 dva) +{ + struct debugfs_blob_wrapper *blob = &ane_h16_failure[index]; + + if (!cpu || !size || blob->data) + return; + blob->data = vmalloc(size); + if (!blob->data) + return; + dma_rmb(); + memcpy(blob->data, cpu, size); + blob->size = size; + debugfs_create_blob(name, 0400, ane_h16_debugfs, blob); + dev_info(h->dev, "H16 failure snapshot %s DVA=%llx bytes=%zx\n", name, dva, size); +} + +static void ane_h16_failure_publish(struct ane_h16_device *h) +{ + struct ane_h16_boot *b = &h->boot; + struct ane_fw_transport *t = &b->transport; + void *live; + unsigned int i; + + /* 25F84 fw IRQ receiver reads this pending register (firmware 0x8c90). + * Read only: no inferred clear/ack semantics are used here. + */ + if (b->soc->doorbell == 0x1884000) { + u32 idle = readl(h->window[ANE_H16_ENGINE] + 0x1600048); + + dev_info(h->dev, "H16 failure firmware IRQ pending=%x\n", + readl(h->window[ANE_H16_ENGINE] + 0x1888000)); + /* 25F84 ANE_deInit reads32 and calls mask3 nonzero CPU-in-WFI. */ + dev_info(h->dev, "H16 failure ASCWRAP_IDLE_STATUS=%x AppleWFI=%u\n", + idle, !!(idle & 3)); + } + if (!ane_h16_debugfs) + ane_h16_debugfs = debugfs_create_dir("ane_h16", NULL); + live = memremap(h->preload_phys[1], b->soc->preload_size[1], MEMREMAP_WB); + if (live) { + ane_h16_failure_copy(h, 0, "failure-data", live, + b->soc->preload_size[1], b->soc->preload_dva[1]); + memunmap(live); + } + ane_h16_failure_copy(h, 1, "failure-ipc", b->ipc.cpu, b->ipc.size, b->ipc.dva); + ane_h16_failure_copy(h, 2, "failure-pool", b->pool.cpu, b->pool.size, b->pool.dva); + ane_h16_failure_copy(h, 3, "failure-heap", b->heap.cpu, b->heap.size, b->heap.dva); + for (i = 0; i < t->shared_count; i++) { + char name[32]; + + snprintf(name, sizeof(name), "failure-shared-%u", i); + ane_h16_failure_copy(h, 4 + i, name, t->shared[i].cpu, + t->shared[i].size, t->shared[i].dva); + } +} + +int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_platform *soc, + unsigned int stage) +{ + struct ane_h16_device *h; + unsigned int i, j; + int ret; + + mutex_lock(&ane_h16_lock); + if (ane_h16_released) { + ret = -EBUSY; + goto unlock; + } + if ((h16_job_irq || h16_job_early_drain) && h16_job_quiet_us) { + dev_err(&pdev->dev, "H16 IRQ/early-drain and quiet probes cannot be combined\n"); + ret = -EINVAL; + goto unlock; + } + if (h16_job_irq_coalesce_us > ANE_FW_IRQ_COALESCE_MAX_US || + (h16_job_irq_coalesce_us && (!h16_job_irq || h16_job_quiet_us || + h16_job_gap_us || h16_job_early_drain || h16_job_pending_mode || + h16_job_ack_pending_mode))) { + dev_err(&pdev->dev, "H16 IRQ coalescing requires IRQ and excludes gap/quiet/early/pending probes\n"); + ret = -EINVAL; + goto unlock; + } + if (h16_job_ack_batch && (!h16_job_irq || h16_job_early_drain || + h16_job_trace || h16_job_quiet_us || h16_job_pending_mode || + h16_job_ack_pending_mode || h16_job_irq_coalesce_us)) { + dev_err(&pdev->dev, "H16 ACK batching requires IRQ and excludes trace/early/quiet/pending/coalescing probes\n"); + ret = -EINVAL; + goto unlock; + } + if (!ane_job_recovery_valid(h16_job_recovery_us, h16_job_gap_us, + h16_job_gap_at, h16_job_gap_every, h16_job_drain_us) || + (h16_job_recovery_us && (!h16_job_irq || h16_job_ack_batch || + h16_job_early_drain || h16_job_trace || h16_job_quiet_us || + h16_job_pending_mode || h16_job_ack_pending_mode || h16_job_irq_coalesce_us))) { + dev_err(&pdev->dev, "H16 adaptive recovery requires IRQ/every1, bounded hold/recovery and no drain/other probes\n"); + ret = -EINVAL; + goto unlock; + } + if (!ane_job_drain_valid(h16_job_drain_us, h16_job_gap_us, + h16_job_gap_at, h16_job_gap_every) || + (h16_job_drain_us && (!h16_job_irq || h16_job_early_drain || + h16_job_pending_mode || h16_job_ack_pending_mode || h16_job_quiet_us || + h16_job_irq_coalesce_us))) { + dev_err(&pdev->dev, "H16 drain requires IRQ/every-call hold and excludes other probes\n"); + ret = -EINVAL; + goto unlock; + } + if (!ane_job_gap_valid(h16_job_gap_us, h16_job_gap_at, h16_job_gap_every, + h16_job_pending_mode, h16_job_ack_pending_mode, h16_job_quiet_us)) { + dev_err(&pdev->dev, "H16 periodic gap requires1..128 interval,1..2000us and no one-shot/pending/quiet probes\n"); + ret = -EINVAL; + goto unlock; + } + if (!ane_fw_pending_config_valid(h16_job_pending_mode, h16_job_gap_us, h16_job_gap_at) || + (h16_job_pending_mode && (h16_job_quiet_us || h16_job_early_drain || + soc->doorbell != 0x1884000))) { + dev_err(&pdev->dev, "H16 pending probe requires one-shot2ms gap, no quiet/early mode and T6041 layout\n"); + ret = -EINVAL; + goto unlock; + } + if (h16_job_ack_pending_mode > 2 || (h16_job_ack_pending_mode && + (!h16_job_trace || h16_job_pending_mode || h16_job_quiet_us || + h16_job_early_drain || soc->doorbell != 0x1884000 || + !ane_fw_pending_config_valid(1, h16_job_gap_us, h16_job_gap_at)))) { + dev_err(&pdev->dev, "H16 ACK pending observer requires trace and one-shot2ms gap, without other observers\n"); + ret = -EINVAL; + goto unlock; + } + h = kzalloc_obj(*h); + if (!h) { + ret = -ENOMEM; + goto unlock; + } + h->dev = &pdev->dev; + h->irq = -1; + INIT_LIST_HEAD(&h->mappings); + h->boot.soc = soc; + h->boot.build = soc->h16_boot; + h->boot.ctx = h; + h->boot.ops = &ane_h16_ops; + h->boot.transport_ops = &ane_h16_transport_ops; + h->boot.startup_drain_ms = min(h16_startup_drain_ms, 1000U); + h->boot.startup_drain_poll_us = clamp(h16_startup_drain_poll_us, 10U, 1000U); + h->shared_next = soc->h16_boot->shared_dva; + ret = of_property_read_u64_array(h->dev->of_node, "apple,dapf-ranges", + &h->boot.ranges[0][0], 8); + if (ret) + goto cleanup; + for (i = 0; i < 4; i++) { + u64 start = h->boot.ranges[i][0], end = h->boot.ranges[i][1]; + + if (!start || end < start || round_down(start, SZ_16K) != round_down(end, SZ_16K)) { + ret = -EINVAL; + goto cleanup; + } + for (j = 0; j < i; j++) + if (round_down(start, SZ_16K) == round_down(h->boot.ranges[j][0], SZ_16K)) { + ret = -EINVAL; + goto cleanup; + } + } + if (ane_h16_observing() && stage != ANE_H16_PREFLIGHT) { + ret = -EPERM; + goto cleanup; + } + ret = ane_h16_preload_identity(h); + if (ret) + goto cleanup; + ret = ane_h16_acquire(pdev, h); + if (ret) + goto cleanup; + h->startup_tracing = h16_startup_trace; + ret = ane_h16_run(&h->boot, stage); + h->startup_tracing = false; + for (i = 0; i < h->startup_trace_count; i++) + dev_info(h->dev, "H16 STARTUP_TRACE %u type=%u value=%x shared=%u ns=%llu cnt=%llu\n", + i, h->startup_trace[i].type, h->startup_trace[i].value, + h->startup_trace[i].shared_count, h->startup_trace[i].ns, + h->startup_trace[i].counter); + if (h->startup_trace_dropped) + dev_info(h->dev, "H16 STARTUP_TRACE dropped=%u\n", h->startup_trace_dropped); + if (ret && !h->boot.ran) + goto cleanup; + /* Bind even on a post-RUN error. devres teardown must never reclaim DMA. */ + platform_set_drvdata(pdev, h); + if (ret && h16_job) + ane_h16_failure_publish(h); + if (!ret) { + dev_info(h->dev, "H16 stage %u complete%s\n", stage, + h->boot.ran ? "; held until reboot" : ""); + if (stage == ANE_H16_STARTUP) { + print_hex_dump(KERN_INFO, "H16 RESOURCE_INFO ", DUMP_PREFIX_OFFSET, + 16, 1, h->boot.resource_info, + sizeof(h->boot.resource_info), false); + if (h16_postboot) + ane_h16_postboot(h); + ane_h16_job_publish(h); + } + } + ret = 0; + goto unlock; +cleanup: + dev_err(h->dev, "H16 stage %u refused before RUN, error %d\n", stage, ret); + ane_h16_cleanup(h); +unlock: + mutex_unlock(&ane_h16_lock); + return ret; +} + +void ane_h16_backend_remove(struct platform_device *pdev) +{ + struct ane_h16_device *h = platform_get_drvdata(pdev); + + mutex_lock(&ane_h16_lock); + if (h) { + if (h->boot.ran) + dev_warn(h->dev, "H16 remove held; reboot reclaims firmware DMA\n"); + else + ane_h16_cleanup(h); + } + mutex_unlock(&ane_h16_lock); +} diff --git a/drivers/accel/ane/ane_h16_boot.h b/drivers/accel/ane/ane_h16_boot.h new file mode 100644 index 0000000000000..1aab0f8960082 --- /dev/null +++ b/drivers/accel/ane/ane_h16_boot.h @@ -0,0 +1,628 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_BOOT_H__ +#define __ANE_H16_BOOT_H__ + +#include "ane_fw_transport.h" + +enum ane_h16_stage { + ANE_H16_REFUSE, + ANE_H16_PREFLIGHT, + ANE_H16_MAP, + ANE_H16_BOOT, + ANE_H16_STARTUP, +}; + +enum ane_h16_window { + ANE_H16_ENGINE, + ANE_H16_PMGR, + ANE_H16_XL, + ANE_H16_DART0, + ANE_H16_DART1, + ANE_H16_DART2, + ANE_H16_DAPF0, + ANE_H16_DAPF1, + ANE_H16_DAPF2, + ANE_H16_WINDOWS, +}; + +struct ane_h16_tunable { + u32 offset; + u32 mask; + u32 value; +}; + +struct ane_h16_tunables { + enum ane_h16_window window; + u32 base; + const struct ane_h16_tunable *values; + size_t count; + bool c1ppt; + u32 lock_offset; + u32 lock_mask; +}; + +/* Selected only after the immutable resident firmware identity passes. */ +struct ane_h16_build { + const char *identity; + u32 cpu_control; + u32 rvbar; + u32 ce; + u32 ce_delays; + u32 ce_delay_us; + u32 ready; + u32 run; + u32 scratch_polls; + u32 scratch_delay_us; + u64 command_timeout_ns; + u64 pool_dva; + u64 ipc_dva; + u64 heap_dva; + u64 shared_dva; + u64 expected_rvbar; + u32 pool_size; + u32 init_offset; + u32 init_size; + u32 config_span; + u32 config_window; + u32 template_count; + u32 template_word; + u32 template_value; + u32 max_channels; + u32 max_heap; + u32 dart_fault; + u32 dart_address_lo; + u32 dart_address_hi; + u32 dapf_version; + /* Expected low half of the DART word at dapf_version; DAPF instances. */ + u32 dapf_version_value; + u32 dapf_instances; + u32 dapf_protect; + u32 dapf_lock; + u32 dapf_records; + u32 dapf_stride; + bool native_free; + bool dapf_layout_known; + bool c1ppt; + const struct ane_h16_tunables *tunables; + size_t tunable_count; + struct { + u16 id; + u16 size; + } startup[4]; +}; + +struct ane_h16_boot; +struct ane_h16_boot_ops { + u32 (*read32)(void *ctx, enum ane_h16_window window, u32 offset); + u64 (*read64)(void *ctx, enum ane_h16_window window, u32 offset); + void (*write32)(void *ctx, enum ane_h16_window window, u32 offset, u32 value); + void (*write64)(void *ctx, enum ane_h16_window window, u32 offset, u64 value); + void (*delay_us)(void *ctx, unsigned int us); + int (*map)(void *ctx); + int (*alloc_at)(void *ctx, u64 dva, size_t size, struct ane_fw_surface *s); + int (*pin)(void *ctx); + void (*mailbox)(void *ctx); + void (*log)(void *ctx, const char *item, u64 a, u64 b); + void (*quarantine)(void *ctx, int error); +}; + +/* One caller, one attempt. No mapping is released here, even on success. */ +struct ane_h16_boot { + const struct ane_fw_platform *soc; + const struct ane_h16_build *build; + const struct ane_h16_boot_ops *ops; + const struct ane_fw_transport_ops *transport_ops; + void *ctx; + struct ane_fw_transport transport; + struct ane_fw_surface pool; + struct ane_fw_surface ipc; + struct ane_fw_surface heap; + u64 ranges[4][2]; + u32 requests[5]; + u32 tick; + u32 startup_drain_ms; /* Diagnostic only: service FW before first IO. */ + u32 startup_drain_poll_us; + u8 resource_info[100]; + int error; + bool attempted; + bool ran; + bool quarantined; +}; + +static inline int ane_h16_stage_parse(const char *name) +{ + if (!name || !*name) + return ANE_H16_REFUSE; + if (!strcmp(name, "preflight")) + return ANE_H16_PREFLIGHT; + if (!strcmp(name, "map")) + return ANE_H16_MAP; + if (!strcmp(name, "boot")) + return ANE_H16_BOOT; + if (!strcmp(name, "startup")) + return ANE_H16_STARTUP; + return -EINVAL; +} + +static inline u32 ane_h16_read(struct ane_h16_boot *b, u32 cell) +{ + return b->ops->read32(b->ctx, ANE_H16_ENGINE, b->soc->scratch + cell * 4); +} + +static inline void ane_h16_write(struct ane_h16_boot *b, u32 cell, u32 value) +{ + b->ops->write32(b->ctx, ANE_H16_ENGINE, b->soc->scratch + cell * 4, value); +} + +static inline int ane_h16_faults(struct ane_h16_boot *b, bool log) +{ + const struct ane_h16_build *f = b->build; + unsigned int i; + int ret = 0; + + for (i = 0; i < 3; i++) { + enum ane_h16_window w = ANE_H16_DART0 + i; + u32 status = b->ops->read32(b->ctx, w, f->dart_fault); + if (log || (status & BIT(31))) { + u64 address = b->ops->read32(b->ctx, w, f->dart_address_lo); + + address |= (u64)b->ops->read32(b->ctx, w, f->dart_address_hi) << 32; + b->ops->log(b->ctx, "DART status", i, status); + b->ops->log(b->ctx, "DART address", i, address); + } + if (status & BIT(31)) + ret = -EIO; + } + return ret; +} + +static inline int ane_h16_fail(struct ane_h16_boot *b, int error) +{ + unsigned int i; + + if (!b->error) + b->error = error; + if (b->ran && !b->quarantined) { + b->quarantined = true; + for (i = 0; i < 8; i++) + b->ops->log(b->ctx, "quarantine scratch", i, ane_h16_read(b, i)); + ane_h16_faults(b, true); + b->ops->quarantine(b->ctx, b->error); + } + return b->error; +} + +static inline int ane_h16_preflight(struct ane_h16_boot *b) +{ + const struct ane_h16_build *f = b->build; + unsigned int pass, i; + u64 rvbar; + u32 control; + int ret; + + /* All suppliers are raised by genpd before entry. Never write PMGR. */ + for (pass = 0; pass < 2; pass++) { + for (i = 0; i < b->soc->power_count; i++) { + u32 word = b->ops->read32(b->ctx, ANE_H16_PMGR, + b->soc->power_words[i]); + + b->ops->log(b->ctx, "power ACTUAL", i, word); + if ((word & 0xff) != 0xff) + return -EHOSTDOWN; + } + } + control = b->ops->read32(b->ctx, ANE_H16_ENGINE, f->cpu_control); + rvbar = b->ops->read64(b->ctx, ANE_H16_ENGINE, f->rvbar); + b->ops->log(b->ctx, "CPU control/RVBAR", control, rvbar); + if (control || rvbar != f->expected_rvbar) + return -EBUSY; + ret = ane_h16_faults(b, true); + if (ret) + return ret; + return 0; +} + +static inline bool ane_h16_dapf_record(struct ane_h16_boot *b, unsigned int dart, + unsigned int record) +{ + const struct ane_h16_build *f = b->build; + enum ane_h16_window w = ANE_H16_DAPF0 + dart; + u32 off = f->dapf_records + record * f->dapf_stride; + u32 flags = b->ops->read32(b->ctx, w, off); + u64 start = b->ops->read32(b->ctx, w, off + 8); + u64 end = b->ops->read32(b->ctx, w, off + 0x10); + u32 enabled = b->ops->read32(b->ctx, w, off + 0x20); + + b->ops->log(b->ctx, "DAPF instance/record", dart, record); + start |= (u64)b->ops->read32(b->ctx, w, off + 0xc) << 32; + end |= (u64)b->ops->read32(b->ctx, w, off + 0x14) << 32; + b->ops->log(b->ctx, "DAPF flags/enable", flags, enabled); + b->ops->log(b->ctx, "DAPF start/end", start, end); + return (flags & 0x333) == 0x31 && (enabled & 0xffff) == 1 && + start == b->ranges[record][0] && end == b->ranges[record][1]; +} + +static inline int ane_h16_dapf(struct ane_h16_boot *b, bool program) +{ + const struct ane_h16_build *f = b->build; + unsigned int dart, record; + + if (!f->dapf_layout_known) + return -ENODATA; + /* Check every lock before writing any record. */ + for (dart = 0; dart < 3; dart++) { + enum ane_h16_window w = ANE_H16_DART0 + dart; + u32 version = b->ops->read32(b->ctx, w, f->dapf_version); + u32 protect = b->ops->read32(b->ctx, w, f->dapf_protect); + u32 lock = b->ops->read32(b->ctx, w, f->dapf_lock); + + b->ops->log(b->ctx, "DAPF version", dart, version); + b->ops->log(b->ctx, "DAPF protect/lock", protect, lock); + if ((version & 0xffff) != f->dapf_version_value) + return -ENODEV; + if (dart >= f->dapf_instances) + continue; + for (record = 0; record < 4; record++) + if (!ane_h16_dapf_record(b, dart, record) && + program && (lock & BIT(2))) + return -EPERM; + } + if (!program) + return 0; + for (dart = 0; dart < f->dapf_instances; dart++) { + enum ane_h16_window w = ANE_H16_DAPF0 + dart; + + for (record = 0; record < 4; record++) { + u32 off = f->dapf_records + record * f->dapf_stride; + u32 value; + + if (ane_h16_dapf_record(b, dart, record)) + continue; + value = b->ops->read32(b->ctx, w, off); + b->ops->write32(b->ctx, w, off, (value & ~0x333) | 0x31); + b->ops->write32(b->ctx, w, off + 8, lower_32_bits(b->ranges[record][0])); + b->ops->write32(b->ctx, w, off + 0xc, upper_32_bits(b->ranges[record][0])); + b->ops->write32(b->ctx, w, off + 0x10, lower_32_bits(b->ranges[record][1])); + b->ops->write32(b->ctx, w, off + 0x14, upper_32_bits(b->ranges[record][1])); + value = b->ops->read32(b->ctx, w, off + 0x20); + b->ops->write32(b->ctx, w, off + 0x20, (value & ~0xffff) | 1); + if (!ane_h16_dapf_record(b, dart, record)) + return -EIO; + } + } + return 0; +} + +/* r5 section 1.1. H16 has CE, with no H17 PWGATE pair. */ +static inline int ane_h16_ce(struct ane_h16_boot *b) +{ + const struct ane_h16_build *f = b->build; + u64 state = b->ops->read64(b->ctx, ANE_H16_ENGINE, f->ce + 0x10); + u64 error = b->ops->read64(b->ctx, ANE_H16_ENGINE, f->ce + 0x18); + u64 wanted = (state & 3) ^ 3; + unsigned int i; + + b->ops->log(b->ctx, "CE state/error", state, error); + if (error & wanted) + return -EIO; + if ((state & 3) == 3) + return 0; + b->ops->write64(b->ctx, ANE_H16_ENGINE, f->ce, wanted); + for (i = 0; i <= f->ce_delays; i++) { + if ((b->ops->read64(b->ctx, ANE_H16_ENGINE, f->ce + 8) & 3) == wanted) + break; + if (i == f->ce_delays) + return -ETIMEDOUT; + b->ops->delay_us(b->ctx, f->ce_delay_us); + } + error = b->ops->read64(b->ctx, ANE_H16_ENGINE, f->ce + 0x18); + if (error & wanted) + return -EIO; + b->ops->write64(b->ctx, ANE_H16_ENGINE, f->ce + 8, wanted); + b->ops->log(b->ctx, "CE ack bits/delays", wanted, i); + return 0; +} + +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); + + if (ret) + return ret; + for (i = 0; i < f->tunable_count; i++) { + const struct ane_h16_tunables *group = &f->tunables[i]; + + if (group->c1ppt && !f->c1ppt) + continue; + if (group->lock_mask && + (b->ops->read32(b->ctx, group->window, group->base + + group->lock_offset) & group->lock_mask)) { + for (j = 0; j < group->count; j++) { + const struct ane_h16_tunable *v = &group->values[j]; + u32 value = b->ops->read32(b->ctx, group->window, + group->base + v->offset); + + if ((value & v->mask) != (v->value & v->mask)) { + b->ops->log(b->ctx, "locked tunable offset/value", + group->base + v->offset, value); + return -EPERM; + } + } + b->ops->log(b->ctx, "tunables locked match", group->window, group->count); + continue; + } + for (j = 0; j < group->count; j++) { + const struct ane_h16_tunable *v = &group->values[j]; + u32 off = group->base + v->offset; + u32 old = b->ops->read32(b->ctx, group->window, off); + + b->ops->write32(b->ctx, group->window, off, + (old & ~v->mask) | (v->value & v->mask)); + } + b->ops->log(b->ctx, "tunables applied", group->window, group->count); + } + return 0; +} + +static inline int ane_h16_wait(struct ane_h16_boot *b, u32 cell, u32 value, + bool table) +{ + const struct ane_h16_build *f = b->build; + unsigned int i; + int ret; + u64 deadline = b->transport_ops->now_ns(b->ctx) + + (u64)f->scratch_polls * f->scratch_delay_us * 1000; + + for (i = 0; i < f->scratch_polls; i++) { + if (b->transport_ops->now_ns(b->ctx) >= deadline) + break; + b->ops->mailbox(b->ctx); + ret = ane_h16_faults(b, false); + if (ret) + return ret; + if (ane_h16_read(b, cell) == value) { + u64 address; + + if (!table) + return 0; + address = ane_h16_read(b, 0); + address |= (u64)ane_h16_read(b, 1) << 32; + if (address == f->ipc_dva) + return 0; + /* READY can pre-exist publication. Never accept the init DVA. */ + if (address != f->pool_dva + f->init_offset) + return -EPROTO; + } + b->ops->delay_us(b->ctx, f->scratch_delay_us); + } + return -ETIMEDOUT; +} + +static inline int ane_h16_alloc(struct ane_h16_boot *b, u64 dva, size_t size, + struct ane_fw_surface *s) +{ + int ret = b->ops->alloc_at(b->ctx, dva, size, s); + + if (ret) + return ret; + if (!ane_fw_surface_valid(s) || s->dva != dva || s->size != size) + return -EPROTO; + return 0; +} + +static inline int ane_h16_scratch_boot(struct ane_h16_boot *b) +{ + const struct ane_h16_build *f = b->build; + u64 ipc_bytes, heap_bytes; + u8 *p; + unsigned int i; + int ret; + + ret = ane_h16_alloc(b, f->pool_dva, f->pool_size, &b->pool); + if (ret) + return ret; + ret = ane_h16_prepare(b); + if (ret) + return ret; + for (i = 0; i < 8; i++) + ane_h16_write(b, i, 0); + /* Endpoint-1 management client is installed, never awaited. */ + b->ops->mailbox(b->ctx); + ane_h16_write(b, 6, 1); + ane_h16_write(b, 7, 0); + if (b->ops->read64(b->ctx, ANE_H16_ENGINE, f->rvbar) != f->expected_rvbar) + return -EBUSY; + ret = b->ops->pin(b->ctx); + if (ret) + return ret; + b->ops->write32(b->ctx, ANE_H16_ENGINE, f->cpu_control, 0); + /* Latch before the first RUN store, including a failure at that store. */ + b->ran = true; + b->ops->write32(b->ctx, ANE_H16_ENGINE, f->cpu_control, f->run); + ret = ane_h16_wait(b, 7, f->ready, false); + if (ret) + return ret; + b->ops->log(b->ctx, "READY", f->ready, 0); + for (i = 0; i < ARRAY_SIZE(b->requests); i++) + b->requests[i] = ane_h16_read(b, i); + b->ops->log(b->ctx, "requests channels/IPC-minus-one", b->requests[0], b->requests[1]); + b->ops->log(b->ctx, "requests heap/mode", b->requests[3], b->requests[4]); + ipc_bytes = (u64)b->requests[1] + 1; + heap_bytes = b->requests[3]; + /* Host policy. IPC cannot reach the fixed heap; no guessed firmware ceiling. */ + if (!b->requests[0] || b->requests[0] >= f->max_channels || + ipc_bytes < ANE_FW_TABLE_SIZE || ipc_bytes > f->heap_dva - f->ipc_dva || + heap_bytes > f->max_heap || + ALIGN(heap_bytes, SZ_16K) > f->shared_dva - f->heap_dva || + b->requests[4] > 1) + return -E2BIG; + ret = ane_h16_alloc(b, f->ipc_dva, ALIGN(ipc_bytes, SZ_16K), &b->ipc); + if (ret) + return ret; + if (heap_bytes) { + ret = ane_h16_alloc(b, f->heap_dva, ALIGN(heap_bytes, SZ_16K), &b->heap); + if (ret) + return ret; + } + p = (u8 *)b->pool.cpu + f->init_offset; + memset(p, 0, f->init_size); + put_unaligned_le64(f->ipc_dva, p + 8); + put_unaligned_le64(f->config_span, p + 0x10); + put_unaligned_le64(f->config_window - f->config_span, p + 0x18); + put_unaligned_le64(heap_bytes ? f->heap_dva : 0, p + 0x20); + put_unaligned_le64(heap_bytes, p + 0x28); + put_unaligned_le64(ipc_bytes, p + 0x50); + put_unaligned_le64(f->pool_dva, p + 0x58); + put_unaligned_le64(f->pool_size, p + 0x60); + put_unaligned_le32(f->template_count, p + 0x68); + put_unaligned_le32(f->template_value, p + f->template_word); + b->transport_ops->write_barrier(b->ctx); + ane_h16_write(b, 0, lower_32_bits(f->pool_dva + f->init_offset)); + ane_h16_write(b, 1, upper_32_bits(f->pool_dva + f->init_offset)); + ane_h16_write(b, 7, ~f->ready); + ret = ane_h16_wait(b, 7, f->ready, true); + if (ret) + return ret; + ret = ane_fw_transport_init(&b->transport, b->soc, b->transport_ops, b->ctx, + b->ipc, b->pool, f->init_offset + f->init_size, + f->ipc_dva, ANE_FW_TABLE_SIZE); + if (ret) + return ret; + b->transport.native_free = f->native_free; + b->ops->log(b->ctx, "table validated", f->ipc_dva, ANE_FW_CHANNELS); + ret = ane_fw_transport_arm(&b->transport); + if (ret) + return ret; + ane_h16_write(b, 3, f->ready); + ret = ane_h16_wait(b, 3, 0, false); + if (!ret) + b->ops->log(b->ctx, "scratch 3 cleared", 0, 0); + return ret; +} + +static inline int ane_h16_startup(struct ane_h16_boot *b) +{ + const struct ane_h16_build *f = b->build; + unsigned int i; + int ret; + + /* Isolate early-IO ordering without withholding allocation/log service. */ + if (b->startup_drain_ms) { + u64 until = b->transport_ops->now_ns(b->ctx) + + (u64)min(b->startup_drain_ms, 1000U) * NSEC_PER_MSEC; + + do { + u32 pending; + + ret = ane_fw_transport_irq(&b->transport, &pending); + if (ret) + return ret; + ret = ane_fw_transport_shared(&b->transport); + if (ret && ret != -EAGAIN) + return ret; + ret = ane_fw_transport_terminal(&b->transport); + if (ret) + return ret; + b->ops->mailbox(b->ctx); + ret = ane_h16_faults(b, false); + if (ret) + return ret; + b->ops->delay_us(b->ctx, clamp(b->startup_drain_poll_us ?: 10U, 10U, 1000U)); + } while (b->transport_ops->now_ns(b->ctx) < until); + b->ops->log(b->ctx, "startup pre-IO shared/messages", + b->transport.shared_count, b->transport.terminal_messages); + } + + for (i = 0; i < ARRAY_SIZE(f->startup); i++) { + u8 command[100] = {}; + u8 *reply; + u64 deadline = b->transport_ops->now_ns(b->ctx) + f->command_timeout_ns; + + ane_fw_command_header(command, f->startup[i].id, true); + ret = ane_fw_transport_publish(&b->transport, ANE_FW_IO, command, + f->startup[i].size, deadline); + if (ret) + return ret; + ret = ane_fw_transport_wait(&b->transport, ANE_FW_IO); + reply = (u8 *)b->pool.cpu + + (b->transport.pending[ANE_FW_IO].dva - b->pool.dva); + if (ret) { + if (ret == -EREMOTEIO) + b->ops->log(b->ctx, "startup refusal ID/ack", + f->startup[i].id, get_unaligned_le16(reply + 6)); + b->ops->log(b->ctx, "startup wait failed ID/re-rings", f->startup[i].id, + b->transport.pending[ANE_FW_IO].rerings); + b->ops->log(b->ctx, "startup IO slot header/error", + b->transport_ops->load64(b->ctx, + ane_fw_transport_slot(&b->transport, ANE_FW_IO)), ret); + b->ops->log(b->ctx, "startup IRQ status/shared count", + b->transport_ops->read32(b->ctx, b->soc->irq_status), + b->transport.shared_count); + /* Read coherent ring state before quarantine; no ownership changes. */ + for (unsigned int ch = 0; ch < ANE_FW_CHANNELS; ch++) { + struct ane_fw_transport *t = &b->transport; + const struct ane_fw_channel *c = &t->channels[ch]; + u32 head = t->head[ch], prev = (head + c->slots - 1) % c->slots; + u8 *slot = (u8 *)t->ipc.cpu + c->offset + head * ANE_FW_SLOT_SIZE; + u8 *last = (u8 *)t->ipc.cpu + c->offset + prev * ANE_FW_SLOT_SIZE; + + b->transport_ops->read_barrier(b->ctx); + b->ops->log(b->ctx, "startup channel/head", ch, head); + b->ops->log(b->ctx, "startup current slot header/word1", + t->ops->load64(b->ctx, slot), t->ops->load64(b->ctx, slot + 8)); + b->ops->log(b->ctx, "startup previous slot header/word1", + t->ops->load64(b->ctx, last), t->ops->load64(b->ctx, last + 8)); + } + return ret; + } + b->ops->log(b->ctx, "startup ack", f->startup[i].id, get_unaligned_le16(reply + 6)); + b->ops->log(b->ctx, "startup doorbell re-rings", f->startup[i].id, + b->transport.pending[ANE_FW_IO].rerings); + if (f->startup[i].id == 3) { + b->tick = get_unaligned_le32(reply + 8); + b->ops->log(b->ctx, "CONFIG_GET tick", b->tick, 0); + if (!b->tick) + return -EPROTO; + } + if (f->startup[i].id == 0x22) + memcpy(b->resource_info, reply, sizeof(b->resource_info)); + b->ops->log(b->ctx, "startup terminal messages/bytes", + b->transport.terminal_messages, b->transport.terminal_bytes); + ret = ane_h16_faults(b, false); + if (ret) + return ret; + } + return 0; +} + +static inline int ane_h16_run(struct ane_h16_boot *b, enum ane_h16_stage stage) +{ + int ret; + + if (stage == ANE_H16_REFUSE) + return -EOPNOTSUPP; + if (stage < ANE_H16_PREFLIGHT || stage > ANE_H16_STARTUP) + return -EINVAL; + if (b->attempted || b->quarantined) + return -EBUSY; + b->attempted = true; + ret = ane_h16_preflight(b); + if (!ret) + ret = ane_h16_dapf(b, false); + if (!ret && stage >= ANE_H16_MAP) { + ret = b->ops->map(b->ctx); + if (!ret) + ret = ane_h16_dapf(b, true); + if (!ret) + ret = ane_h16_faults(b, true); + } + if (!ret && stage >= ANE_H16_BOOT) + ret = ane_h16_scratch_boot(b); + if (!ret && stage == ANE_H16_STARTUP) + ret = ane_h16_startup(b); + return ret ? ane_h16_fail(b, ret) : 0; +} + +#endif /* __ANE_H16_BOOT_H__ */ diff --git a/drivers/accel/ane/ane_h16_boot_data.h b/drivers/accel/ane/ane_h16_boot_data.h new file mode 100644 index 0000000000000..5345f5153f879 --- /dev/null +++ b/drivers/accel/ane/ane_h16_boot_data.h @@ -0,0 +1,233 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_BOOT_DATA_H__ +#define __ANE_H16_BOOT_DATA_H__ + +#include "ane_h16_boot.h" + +/* H16 27.0 (26A428), r5 sections 1.2-1.4. Ordered masked updates. */ +static const struct ane_h16_tunable ane_h16_axi[] = { + { 0x0000, 0x800000ff, 0x80000022 }, + { 0x0004, 0x80ff00ff, 0x80220003 }, + { 0x0008, 0x80ff00ff, 0x80220009 }, + { 0x000c, 0x80ff00ff, 0x80220003 }, + { 0x0010, 0x80ff00ff, 0x80220003 }, + { 0x0014, 0x80ff00ff, 0x80220003 }, + { 0x0018, 0x800000ff, 0x8000001b }, + { 0x001c, 0x800000ff, 0x80000022 }, + { 0x0020, 0x80ff00ff, 0x80220003 }, + { 0x0024, 0x80ff00ff, 0x80220003 }, + { 0x0028, 0x80ff00ff, 0x80220003 }, + { 0x002c, 0x80ff00ff, 0x80220003 }, + { 0x0030, 0x800000ff, 0x8000001b }, + { 0x0034, 0x800000ff, 0x8000001b }, + { 0x0038, 0x800000ff, 0x8000001b }, + { 0x0100, 0x000000ff, 0x000000ff }, + { 0x0108, 0xffff0006, 0x00100000 }, + { 0x0304, 0x3f3f0000, 0x02020000 }, + { 0x0308, 0x000fffff, 0x00001681 }, + { 0x030c, 0x000fffff, 0x00001680 }, + { 0x0310, 0x70000fff, 0x000001e0 }, + { 0x0314, 0xf0000fff, 0x800001e0 }, + { 0x0318, 0x70000fff, 0x000005a0 }, + { 0x031c, 0xf0000fff, 0x800005a0 }, + { 0x0320, 0x70000fff, 0x000005a0 }, + { 0x0324, 0xf0000fff, 0x800005a0 }, + { 0x0328, 0x70000fff, 0x000005a0 }, + { 0x032c, 0x70000fff, 0x000005a0 }, + { 0x0330, 0x70000fff, 0x000005a0 }, + { 0x0338, 0xffffffff, 0x00050020 }, + { 0x033c, 0xffffffff, 0x000a0030 }, + { 0x0408, 0xffff0020, 0x001e0020 }, + { 0x040c, 0x000fffff, 0x00001681 }, + { 0x0410, 0x000fffff, 0x00001680 }, + { 0x0414, 0x70000fff, 0x000001e0 }, + { 0x0418, 0x70000fff, 0x000001e0 }, + { 0x041c, 0x70000fff, 0x000005a0 }, + { 0x0420, 0x70000fff, 0x000005a0 }, + { 0x0424, 0x70000fff, 0x000005a0 }, + { 0x0428, 0x70000fff, 0x000005a0 }, + { 0x042c, 0x70000fff, 0x000005a0 }, + { 0x0430, 0x70000fff, 0x000005a0 }, + { 0x0434, 0x70000fff, 0x000005a0 }, + { 0x0748, 0x07ff07ff, 0x00200030 }, + { 0x0848, 0x07ff07ff, 0x00100030 }, + { 0x0948, 0x07ff07ff, 0x01880188 }, + { 0x0b00, 0xffffffff, 0x7fffffff }, + { 0x4008, 0x00000001, 0 }, + { 0x400c, 0x00000001, 1 }, + { 0x4014, 0x00000001, 0 }, + { 0x4018, 0x00000001, 0 }, + { 0x401c, 0x00000001, 1 }, +}; + +static const struct ane_h16_tunable ane_h16_xl[] = { + { 0x0000, 0x800000ff, 0x80000036 }, + { 0x0004, 0x80ff00ff, 0x80360003 }, + { 0x0008, 0x80ff00ff, 0x80360009 }, + { 0x000c, 0x80ff00ff, 0x80010000 }, + { 0x0010, 0x80ff00ff, 0x80360003 }, + { 0x0014, 0x800000ff, 0x8000002e }, + { 0x0018, 0x800000ff, 0x80000036 }, + { 0x001c, 0x80ff00ff, 0x80360003 }, + { 0x0020, 0x80ff00ff, 0x80020000 }, + { 0x0024, 0x80ff00ff, 0x80360003 }, + { 0x0028, 0x800000ff, 0x8000002e }, + { 0x002c, 0x800000ff, 0x8000002e }, + { 0x0030, 0x800000ff, 0x8000002e }, + { 0x0100, 0x000000ff, 0x000000ff }, + { 0x0108, 0xffff0006, 0x00100000 }, + { 0x0304, 0x3f3f0000, 0x02020000 }, + { 0x0308, 0x000fffff, 0x00001681 }, + { 0x030c, 0x000fffff, 0x00001680 }, + { 0x0310, 0x70000fff, 0x000005a0 }, + { 0x0314, 0xf0000fff, 0x800005a0 }, + { 0x0318, 0x70000fff, 0x000005a0 }, + { 0x031c, 0x70000fff, 0x000005a0 }, + { 0x0320, 0x70000fff, 0x000005a0 }, + { 0x0328, 0xffffffff, 0x0000ffff }, + { 0x032c, 0xffffffff, 0x0000ffff }, + { 0x0408, 0xffff0020, 0x00310020 }, + { 0x040c, 0x000fffff, 0x00001681 }, + { 0x0410, 0x000fffff, 0x00001680 }, + { 0x0414, 0x70000fff, 0x000005a0 }, + { 0x0418, 0x70000fff, 0x000005a0 }, + { 0x041c, 0x70000fff, 0x000005a0 }, + { 0x0420, 0x70000fff, 0x000005a0 }, + { 0x0424, 0x70000fff, 0x000005a0 }, + { 0x0648, 0x07ff07ff, 0x01880188 }, + { 0x0800, 0xffffffff, 0x7fffffff }, + { 0x4008, 0x00000001, 0 }, + { 0x400c, 0x00000001, 1 }, + { 0x4014, 0x00000001, 0 }, + { 0x4018, 0x00000001, 0 }, + { 0x401c, 0x00000001, 1 }, +}; + +static const struct ane_h16_tunable ane_h16_c1ppt[] = { + { 0x20, 0x0000ffff, 0x1838 }, + { 0x24, 0x0000ffff, 0x1034 }, + { 0x28, 0xffffffff, 0x07d00708 }, + { 0x2c, 0x000000ff, 4 }, + { 0x40, 0x000003ff, 0xbf }, + { 0x44, 0x000003ff, 0x19a }, + { 0x48, 0x0001ffff, 0x7800 }, + { 0x60, 0x00001f1f, 0x0103 }, + { 0x04, 0x1, 1 }, + { 0x3ff0, 0x007fffff, 0x0077ebf9 }, + { 0x3ffc, 0x1, 1 }, +}; + +static const struct ane_h16_tunables ane_h16_tunables_26a428[] = { + { .window = ANE_H16_ENGINE, .values = ane_h16_axi, + .count = ARRAY_SIZE(ane_h16_axi) }, + { .window = ANE_H16_XL, .values = ane_h16_xl, + .count = ARRAY_SIZE(ane_h16_xl) }, + { .window = ANE_H16_ENGINE, .base = 0x197c000, + .values = ane_h16_c1ppt, .count = ARRAY_SIZE(ane_h16_c1ppt), + .c1ppt = true, .lock_offset = 0x3ffc, .lock_mask = 1 }, +}; + +static const struct ane_h16_build ane_h16_build_26a428 = { + .identity = "H16 27.0 26A428", + .cpu_control = 0x1600044, + .rvbar = 0x1050000, + .ce = 0x18a4000, + .ce_delays = 5001, + .ce_delay_us = 10, + .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, + /* Host allocation policy, not a recovered firmware ceiling. */ + .max_heap = SZ_16M, + .dart_fault = 0x100, + .dart_address_lo = 0x170, + .dart_address_hi = 0x174, + .dapf_version = 8, + .dapf_version_value = 0x203, + .dapf_instances = 3, + .dapf_protect = 0x200, + .dapf_lock = 0x208, + .dapf_stride = 0x40, + /* Version/protect/lock are DART registers; DAPF records are separate. */ + .dapf_records = 0, + .dapf_layout_known = true, + .native_free = true, + .c1ppt = true, + .tunables = ane_h16_tunables_26a428, + .tunable_count = ARRAY_SIZE(ane_h16_tunables_26a428), + .startup = { { 4, 12 }, { 0, 12 }, { 3, 16 }, { 0x22, 100 } }, +}; + +/* + * 25F84 (macOS 26.5.2) on J616c: the 26A428 boot values until a 25F84 stage + * shows otherwise (rg-ane-00: power, CPU control and RVBAR as 26A428). + */ +static const struct ane_h16_build ane_h16_build_25f84 = { + .identity = "H16 26.5.2 25F84", + .cpu_control = 0x1600044, + .rvbar = 0x1050000, + .ce = 0x18a4000, + .ce_delays = 5001, + .ce_delay_us = 10, + .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, + /* Host allocation policy, not a recovered firmware ceiling. */ + .max_heap = SZ_16M, + .dart_fault = 0x100, + .dart_address_lo = 0x170, + .dart_address_hi = 0x174, + .dapf_version = 8, + /* J616c: DART word 0x2a2a0202; one DAPF (dart-ane0 reg 3, "DAPF LLT"). */ + .dapf_version_value = 0x202, + .dapf_instances = 1, + .dapf_protect = 0x200, + .dapf_lock = 0x208, + .dapf_stride = 0x40, + /* Version/protect/lock are DART registers; DAPF records are separate. */ + .dapf_records = 0, + .dapf_layout_known = true, + .native_free = true, + .c1ppt = true, + .tunables = ane_h16_tunables_26a428, + .tunable_count = ARRAY_SIZE(ane_h16_tunables_26a428), + .startup = { { 4, 12 }, { 0, 12 }, { 3, 16 }, { 0x22, 100 } }, +}; + +static const struct ane_h16_build *const ane_h16_builds[] = { + &ane_h16_build_26a428, &ane_h16_build_25f84, +}; + +#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 new file mode 100644 index 0000000000000..ae1351e884a72 --- /dev/null +++ b/drivers/accel/ane/ane_h16_boot_test.c @@ -0,0 +1,804 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +#include "ane_h16_boot_data.h" + +struct ane_h16_sim { + struct kunit *test; + struct ane_h16_boot boot; + struct ane_h16_build build; + struct ane_fw_platform soc; + u32 scratch[8]; + u32 dapf[3][SZ_16K / 4]; + u64 now; + u64 ce_ack; + u32 cpu; + u32 command_count; + u32 scratch_writes; + u32 tuning_writes; + u32 dapf_writes; + u32 mailbox_polls; + u32 maps; + u32 pins; + u32 quarantines; + u32 allocations; + u32 lock; + u32 fault; + u32 fault_address_reads; + u32 channel_request; + u32 ipc_request; + u32 heap_request; + u32 tick; + struct ane_fw_rtk rtk; + u32 mailbox_tx; + bool offered_mailbox; + bool fault_after_run; + u32 lifecycle_mode; + bool lifecycle_requested; + u16 refuse_id; + bool no_ready; + bool wrong_table; + bool stale_table; + bool no_clear; + bool shared_pending; + bool shared_replied; + bool ce_timeout; + bool bad_power; + bool bad_rvbar; + bool fail_map; + bool must_allocate_first; + bool fault_on_drain; +}; + +static const u32 sim_power_words[] = { 0x3c0, 0xc008, 0xc000, 0xc010, 0xc018 }; + +static u32 sim_read32(void *ctx, enum ane_h16_window w, u32 off) +{ + struct ane_h16_sim *s = ctx; + + if (w == ANE_H16_PMGR) + return s->bad_power ? 0xf : 0xff; + if (w >= ANE_H16_DART0 && w <= ANE_H16_DART2) { + if (off == s->build.dart_address_lo || off == s->build.dart_address_hi) + s->fault_address_reads++; + if (off == s->build.dapf_version) + return 0x203; + if (off == s->build.dapf_protect || off == s->build.dapf_lock) + return s->lock; + if (off == s->build.dart_fault) + return s->fault; + return 0; + } + if (w >= ANE_H16_DAPF0) + return s->dapf[w - ANE_H16_DAPF0][off / 4]; + if (w == ANE_H16_ENGINE) { + if (off == s->build.cpu_control) + return s->cpu; + if (off == 0x197fffc) + return 0; + if (off >= s->soc.scratch && off < s->soc.scratch + 32) + return s->scratch[(off - s->soc.scratch) / 4]; + if (off == s->soc.irq_status) + return 0; + } + return 0xa5a5a5a5; +} + +static u64 sim_read64(void *ctx, enum ane_h16_window w, u32 off) +{ + struct ane_h16_sim *s = ctx; + + if (off == s->build.rvbar) + return s->bad_rvbar ? 0 : s->build.expected_rvbar; + if (off == s->build.ce + 8) + return s->ce_ack; + return 0; +} + +static void sim_reply(struct ane_h16_sim *s) +{ + struct ane_fw_transport *t = &s->boot.transport; + struct ane_fw_transaction *tx = &t->pending[ANE_FW_IO]; + u8 *slot = ane_fw_transport_slot(t, ANE_FW_IO); + u8 *command = (u8 *)t->pool.cpu + (tx->dva - t->pool.dva); + + if (tx->id == 3) + put_unaligned_le32(s->tick, command + 8); + if (tx->id == 0x22) + memset(command + 8, 0x5a, 92); + if (tx->id == s->refuse_id) + put_unaligned_le16(7, command + 6); + put_unaligned_le64(0, slot + 16); + put_unaligned_le64(tx->dva | 1, slot); +} + +static void sim_write32(void *ctx, enum ane_h16_window w, u32 off, u32 value) +{ + struct ane_h16_sim *s = ctx; + const struct ane_h16_build *f = &s->build; + + if (w >= ANE_H16_DAPF0) { + s->dapf[w - ANE_H16_DAPF0][off / 4] = value; + s->dapf_writes++; + return; + } + if (w == ANE_H16_ENGINE && off == f->cpu_control) { + s->cpu = value; + if (value == f->run && s->fault_after_run) + s->fault = BIT(31); + if (value == f->run && !s->no_ready) { + s->scratch[0] = s->channel_request; + s->scratch[1] = s->ipc_request; + s->scratch[3] = s->heap_request; + s->scratch[4] = 0; + s->scratch[7] = f->ready; + } + return; + } + if (w == ANE_H16_ENGINE && off >= s->soc.scratch && off < s->soc.scratch + 32) { + u32 cell = (off - s->soc.scratch) / 4; + + if (s->scratch_writes < 8) { + KUNIT_EXPECT_EQ(s->test, cell, s->scratch_writes); + KUNIT_EXPECT_EQ(s->test, value, 0U); + KUNIT_EXPECT_EQ(s->test, s->tuning_writes, 103U); + } + s->scratch_writes++; + s->scratch[cell] = value; + if (cell == 7 && value == ~f->ready) { + u64 address = f->ipc_dva + (s->wrong_table ? SZ_16K : 0); + + if (!s->stale_table) { + s->scratch[0] = lower_32_bits(address); + s->scratch[1] = upper_32_bits(address); + } + s->scratch[7] = f->ready; + } + if (cell == 3 && value == f->ready && !s->no_clear) + s->scratch[3] = 0; + return; + } + if (w == ANE_H16_ENGINE && off == s->soc.doorbell) { + struct ane_fw_transport *t = &s->boot.transport; + + if (value == BIT(1)) { + struct ane_fw_transaction *tx = &t->pending[ANE_FW_IO]; + + KUNIT_EXPECT_LT(s->test, s->command_count, 4U); + if (s->command_count < 4) + KUNIT_EXPECT_EQ(s->test, tx->id, f->startup[s->command_count].id); + if (s->must_allocate_first) + KUNIT_EXPECT_TRUE(s->test, s->shared_replied); + s->command_count++; + if (tx->id == 3 && s->lifecycle_mode) { + u8 *slot = ane_fw_transport_slot(t, ANE_FW_SHAREDMALLOC); + u64 dva = s->lifecycle_mode == 2 ? 0 : s->build.shared_dva; + + if (s->lifecycle_mode == 3) + dva += SZ_16K; + + put_unaligned_le64(dva, slot); + put_unaligned_le64(0, slot + 8); + put_unaligned_le64(s->lifecycle_mode == 2 ? 1 : 0, slot + 16); + s->lifecycle_requested = true; + } else if (!tx->id) { + u8 *slot = ane_fw_transport_slot(t, ANE_FW_SHAREDMALLOC); + + put_unaligned_le64(0, slot); + put_unaligned_le64(SZ_16K, slot + 8); + put_unaligned_le64(0, slot + 16); + s->shared_pending = true; + } else { + sim_reply(s); + } + } + if (value == BIT(5)) { + s->shared_replied = true; + if (s->lifecycle_requested) { + u8 *slot = ane_fw_transport_slot(t, ANE_FW_SHAREDMALLOC); + + KUNIT_EXPECT_EQ(s->test, s->lifecycle_mode, 1U); + KUNIT_EXPECT_EQ(s->test, get_unaligned_le64(slot), 1ULL); + KUNIT_EXPECT_EQ(s->test, get_unaligned_le64(slot + 8), 0ULL); + KUNIT_EXPECT_EQ(s->test, get_unaligned_le64(slot + 16), 0ULL); + } + if (t->pending[ANE_FW_IO].active) + sim_reply(s); + } + return; + } + /* The selected AXI and XL tables must finish before scratch writes. */ + KUNIT_EXPECT_FALSE(s->test, s->boot.ran); + s->tuning_writes++; +} + +static void sim_write64(void *ctx, enum ane_h16_window w, u32 off, u64 value) +{ + struct ane_h16_sim *s = ctx; + + KUNIT_EXPECT_EQ(s->test, w, ANE_H16_ENGINE); + if (off == s->build.ce && !s->ce_timeout) + s->ce_ack = value; +} + +static void sim_delay(void *ctx, unsigned int us) +{ + struct ane_h16_sim *s = ctx; + + s->now += (u64)us * 1000; + if (s->fault_on_drain && s->boot.transport.armed) + s->fault = BIT(31); +} + +static int sim_map(void *ctx) +{ + struct ane_h16_sim *s = ctx; + + s->maps++; + return s->fail_map ? -ENOMEM : 0; +} + +static int sim_alloc_at(void *ctx, u64 dva, size_t size, struct ane_fw_surface *out) +{ + struct ane_h16_sim *s = ctx; + + /* Sparse simulated heap. The engine only accesses pool and IPC bytes. */ + out->cpu = kunit_kzalloc(s->test, min_t(size_t, size, SZ_256K), GFP_KERNEL); + if (!out->cpu) + return -ENOMEM; + out->dva = dva; + out->size = size; + s->allocations++; + if (dva == s->build.ipc_dva) { + static const char * const names[] = { + "TERMINAL", "IO", "DEBUG", "BUF_H2T", "BUF_T2H", + "SHAREDMALLOC", "IO_T2H", "DATA_CHAIN_H2T", + }; + unsigned int i; + + for (i = 0; i < 8; i++) { + u8 *p = (u8 *)out->cpu + i * ANE_FW_DESCRIPTOR_SIZE; + + strscpy(p, names[i], 64); + put_unaligned_le32(i == 0 ? 2 : i == 4 || i == 5 || i == 6, p + 0x40); + put_unaligned_le32(i, p + 0x44); + put_unaligned_le64(1, p + 0x48); + put_unaligned_le64(dva + ANE_FW_TABLE_SIZE + i * 64, p + 0x50); + } + } + return 0; +} + +static int sim_pin(void *ctx) +{ + ((struct ane_h16_sim *)ctx)->pins++; + return 0; +} + +static int sim_mailbox_send(void *ctx, u64 word0, u64 word1) +{ + struct ane_h16_sim *s = ctx; + static const u8 types[] = { 2, 8, 8, 5, 6, 0xb, 5 }; + + KUNIT_EXPECT_LT(s->test, s->mailbox_tx, ARRAY_SIZE(types)); + if (s->mailbox_tx < ARRAY_SIZE(types)) + KUNIT_EXPECT_EQ(s->test, (word0 >> 52) & 0xff, (u64)types[s->mailbox_tx]); + KUNIT_EXPECT_EQ(s->test, word1, 0ULL); + s->mailbox_tx++; + return 0; +} + +static void sim_mailbox(void *ctx) +{ + struct ane_h16_sim *s = ctx; + static const u64 offered[] = { + ANE_FW_RTK_TYPE(1) | (12 << 16) | 12, + ANE_FW_RTK_TYPE(8) | BIT(0) | BIT(1), + ANE_FW_RTK_TYPE(8) | BIT_ULL(32) | ANE_FW_RTK_LAST | BIT(0), + ANE_FW_RTK_TYPE(7) | 0x20, + ANE_FW_RTK_TYPE(0xb) | 0x20, + }; + unsigned int i; + + s->mailbox_polls++; + if (!s->offered_mailbox || !s->boot.ran || s->mailbox_tx) + return; + for (i = 0; i < ARRAY_SIZE(offered); i++) { + int ret = ane_fw_rtk_receive(&s->rtk, offered[i], 0, s, sim_mailbox_send); + + KUNIT_EXPECT_EQ(s->test, ret, 0); + } +} + +static void sim_log(void *ctx, const char *item, u64 a, u64 b) +{ +} + +static void sim_quarantine(void *ctx, int error) +{ + ((struct ane_h16_sim *)ctx)->quarantines++; +} + +static u64 sim_load64(void *ctx, const void *p) +{ + return get_unaligned_le64(p); +} + +static void sim_store64(void *ctx, void *p, u64 value) +{ + put_unaligned_le64(value, p); +} + +static void sim_barrier(void *ctx) +{ +} + +static u32 sim_engine_read(void *ctx, u32 off) +{ + return sim_read32(ctx, ANE_H16_ENGINE, off); +} + +static void sim_engine_write(void *ctx, u32 off, u32 value) +{ + sim_write32(ctx, ANE_H16_ENGINE, off, value); +} + +static u64 sim_now(void *ctx) +{ + return ((struct ane_h16_sim *)ctx)->now; +} + +static void sim_relax(void *ctx) +{ + sim_delay(ctx, 1000); +} + +static int sim_alloc_shared(void *ctx, size_t size, u32 tag, struct ane_fw_surface *out) +{ + struct ane_h16_sim *s = ctx; + + return sim_alloc_at(ctx, s->build.shared_dva + + s->boot.transport.shared_count * SZ_16K, size, out); +} + +static void sim_refused(void *ctx, u64 w0, u64 w1, u64 w2, int error) +{ +} + +static const struct ane_h16_boot_ops sim_ops = { + .read32 = sim_read32, + .read64 = sim_read64, + .write32 = sim_write32, + .write64 = sim_write64, + .delay_us = sim_delay, + .map = sim_map, + .alloc_at = sim_alloc_at, + .pin = sim_pin, + .mailbox = sim_mailbox, + .log = sim_log, + .quarantine = sim_quarantine, +}; + +static const struct ane_fw_transport_ops sim_transport_ops = { + .load64 = sim_load64, + .store64 = sim_store64, + .read_barrier = sim_barrier, + .write_barrier = sim_barrier, + .read32 = sim_engine_read, + .write32 = sim_engine_write, + .now_ns = sim_now, + .relax = sim_relax, + .alloc = sim_alloc_shared, + .refused = sim_refused, +}; + +static int sim_init(struct kunit *test) +{ + struct ane_h16_sim *s = kunit_kzalloc(test, sizeof(*s), GFP_KERNEL); + unsigned int i; + + if (!s) + return -ENOMEM; + test->priv = s; + s->test = test; + s->build = ane_h16_build_26a428; + /* Separate DART header and DAPF record windows. */ + s->soc.scratch = 0x1880020; + s->soc.doorbell = 0x1884000; + s->soc.irq_status = 0x188c000; + s->soc.irq_ack = 0x1890000; + s->soc.power_words = sim_power_words; + s->soc.power_count = ARRAY_SIZE(sim_power_words); + s->boot.soc = &s->soc; + s->boot.build = &s->build; + s->boot.ops = &sim_ops; + s->boot.transport_ops = &sim_transport_ops; + s->boot.ctx = s; + for (i = 0; i < 4; i++) { + s->boot.ranges[i][0] = 0x500000000ULL + i * SZ_16K; + s->boot.ranges[i][1] = s->boot.ranges[i][0] + 3; + } + s->channel_request = 8; + s->ipc_request = 0xc440; + s->heap_request = 0xf00000; + s->tick = 25000000; + s->refuse_id = 0xffff; + return 0; +} + +static void ane_h16_happy_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + u8 *p; + + KUNIT_ASSERT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), 0); + KUNIT_EXPECT_TRUE(test, s->boot.ran); + KUNIT_EXPECT_FALSE(test, s->boot.quarantined); + KUNIT_EXPECT_EQ(test, s->pins, 1U); + KUNIT_EXPECT_EQ(test, s->command_count, 4U); + KUNIT_EXPECT_TRUE(test, s->shared_replied); + KUNIT_EXPECT_GT(test, s->mailbox_polls, 0U); + KUNIT_EXPECT_EQ(test, s->boot.tick, 25000000U); + KUNIT_EXPECT_EQ(test, s->boot.resource_info[99], (u8)0x5a); + p = (u8 *)s->boot.pool.cpu + s->build.init_offset; + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p), 0ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 8), s->build.ipc_dva); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 0x10), 0x380000ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 0x18), 0xfc80000ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 0x28), 0xf00000ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 0x50), 0xc441ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(p + 0x12c), 4U); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 0x38), 0ULL); + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), -EBUSY); +} + +static void ane_h16_no_ready_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->no_ready = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_EQ(test, s->quarantines, 1U); + KUNIT_EXPECT_EQ(test, s->allocations, 1U); + KUNIT_EXPECT_EQ(test, s->now, 1000000000ULL); + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -EBUSY); +} + +static void ane_h16_wrong_table_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->wrong_table = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -EPROTO); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_FALSE(test, s->boot.transport.armed); +} + +static void ane_h16_stale_table_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->stale_table = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_FALSE(test, s->boot.transport.armed); +} + +static void ane_h16_oversized_ipc_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->ipc_request = U32_MAX; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -E2BIG); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_EQ(test, s->allocations, 1U); +} + +static void ane_h16_oversized_heap_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->heap_request = U32_MAX; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -E2BIG); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); +} + +static void ane_h16_channel_limit_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->channel_request = 0x21; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -E2BIG); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); +} + +static void ane_h16_locked_dapf_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->lock = BIT(2); + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_MAP), -EPERM); + KUNIT_EXPECT_FALSE(test, s->boot.ran); + KUNIT_EXPECT_EQ(test, s->dapf_writes, 0U); + KUNIT_EXPECT_EQ(test, s->pins, 0U); +} + +static void ane_h16_nonzero_ack_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->refuse_id = 0; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), -EREMOTEIO); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_EQ(test, s->command_count, 2U); + KUNIT_EXPECT_EQ(test, s->pins, 1U); +} + +static void ane_h16_preflight_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_PREFLIGHT), 0); + KUNIT_EXPECT_EQ(test, s->maps, 0U); + KUNIT_EXPECT_EQ(test, s->dapf_writes, 0U); + KUNIT_EXPECT_EQ(test, s->tuning_writes, 0U); + KUNIT_EXPECT_EQ(test, s->scratch_writes, 0U); +} + +static void ane_h16_default_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + KUNIT_EXPECT_EQ(test, ane_h16_stage_parse(NULL), ANE_H16_REFUSE); + KUNIT_EXPECT_EQ(test, ane_h16_stage_parse("unknown"), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_REFUSE), -EOPNOTSUPP); + KUNIT_EXPECT_FALSE(test, s->boot.attempted); + KUNIT_EXPECT_EQ(test, s->scratch_writes, 0U); +} + +static void ane_h16_ce_timeout_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->ce_timeout = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, s->boot.ran); + KUNIT_EXPECT_EQ(test, s->scratch_writes, 0U); + KUNIT_EXPECT_EQ(test, s->now, 50010000ULL); +} + +static void ane_h16_zero_tick_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->tick = 0; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), -EPROTO); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); +} + +static void ane_h16_scratch3_timeout_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->no_clear = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_TRUE(test, s->boot.transport.armed); + KUNIT_EXPECT_EQ(test, s->command_count, 0U); +} + +static void ane_h16_mailbox_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->offered_mailbox = true; + KUNIT_ASSERT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), 0); + KUNIT_EXPECT_EQ(test, s->rtk.phase, ANE_FW_RTK_READY); + KUNIT_EXPECT_EQ(test, s->mailbox_tx, 7U); +} + +static void ane_h16_no_heap_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + u8 *record; + + s->heap_request = 0; + KUNIT_ASSERT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), 0); + KUNIT_EXPECT_EQ(test, s->allocations, 2U); + record = (u8 *)s->boot.pool.cpu + s->build.init_offset; + KUNIT_EXPECT_EQ(test, get_unaligned_le64(record + 0x20), 0ULL); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(record + 0x28), 0ULL); +} + +static void ane_h16_power_actual_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->bad_power = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_PREFLIGHT), -EHOSTDOWN); + KUNIT_EXPECT_EQ(test, s->scratch_writes, 0U); + KUNIT_EXPECT_EQ(test, s->pins, 0U); +} + +static void ane_h16_rvbar_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->bad_rvbar = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -EBUSY); + KUNIT_EXPECT_EQ(test, s->scratch_writes, 0U); + KUNIT_EXPECT_EQ(test, s->maps, 0U); +} + +static void ane_h16_dart_fault_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->fault_after_run = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -EIO); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_EQ(test, s->pins, 1U); + KUNIT_EXPECT_EQ(test, s->quarantines, 1U); +} + +static void ane_h16_map_failure_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->fail_map = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -ENOMEM); + KUNIT_EXPECT_FALSE(test, s->boot.ran); + KUNIT_EXPECT_FALSE(test, s->boot.quarantined); + KUNIT_EXPECT_EQ(test, s->pins, 0U); +} + +static void ane_h16_locked_matching_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + unsigned int dart, i; + + s->lock = BIT(2); + for (dart = 0; dart < 3; dart++) { + for (i = 0; i < 4; i++) { + u32 *p = &s->dapf[dart][(s->build.dapf_records + i * 0x40) / 4]; + + p[0] = 0x80000031; + p[2] = lower_32_bits(s->boot.ranges[i][0]); + p[3] = upper_32_bits(s->boot.ranges[i][0]); + p[4] = lower_32_bits(s->boot.ranges[i][1]); + p[5] = upper_32_bits(s->boot.ranges[i][1]); + p[8] = 0xabcd0001; + } + } + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_MAP), 0); + KUNIT_EXPECT_EQ(test, s->dapf_writes, 0U); +} + +static void ane_h16_heap_overlap_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->heap_request = SZ_16M; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), -E2BIG); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); +} + +static void ane_h16_native_free_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->lifecycle_mode = 1; + KUNIT_ASSERT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), 0); + KUNIT_EXPECT_TRUE(test, s->lifecycle_requested); + KUNIT_EXPECT_TRUE(test, s->boot.transport.shared_retired[0]); + KUNIT_EXPECT_TRUE(test, s->boot.transport.shared[0].cpu); +} + +static void ane_h16_control_refusal_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->lifecycle_mode = 2; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), -EOPNOTSUPP); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_FALSE(test, s->boot.transport.shared_retired[0]); +} + +static void ane_h16_foreign_free_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->lifecycle_mode = 3; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), -ENOENT); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_FALSE(test, s->boot.transport.shared_retired[0]); +} + +static void ane_h16_pre_io_allocation_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + u8 *slot; + + KUNIT_ASSERT_EQ(test, ane_h16_run(&s->boot, ANE_H16_BOOT), 0); + slot = ane_fw_transport_slot(&s->boot.transport, ANE_FW_SHAREDMALLOC); + put_unaligned_le64(0, slot); + put_unaligned_le64(SZ_16K, slot + 8); + put_unaligned_le64(0, slot + 16); + s->must_allocate_first = true; + s->boot.startup_drain_ms = 1; + s->boot.startup_drain_poll_us = 1000; + KUNIT_ASSERT_EQ(test, ane_h16_startup(&s->boot), 0); + KUNIT_EXPECT_TRUE(test, s->shared_replied); + KUNIT_EXPECT_EQ(test, s->command_count, 4U); +} + +static void ane_h16_pre_io_fault_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->boot.startup_drain_ms = 10; + s->fault_on_drain = true; + KUNIT_EXPECT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), -EIO); + KUNIT_EXPECT_EQ(test, s->command_count, 0U); + KUNIT_EXPECT_TRUE(test, s->boot.quarantined); + KUNIT_EXPECT_EQ(test, s->quarantines, 1U); +} + +static void ane_h16_fault_address_on_demand_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + KUNIT_EXPECT_EQ(test, ane_h16_faults(&s->boot, false), 0); + KUNIT_EXPECT_EQ(test, s->fault_address_reads, 0U); + s->fault = BIT(31); + KUNIT_EXPECT_EQ(test, ane_h16_faults(&s->boot, false), -EIO); + KUNIT_EXPECT_EQ(test, s->fault_address_reads, 6U); + s->fault = 0; + KUNIT_EXPECT_EQ(test, ane_h16_faults(&s->boot, true), 0); + KUNIT_EXPECT_EQ(test, s->fault_address_reads, 12U); +} + +static struct kunit_case ane_h16_boot_cases[] = { + KUNIT_CASE(ane_h16_fault_address_on_demand_test), + KUNIT_CASE(ane_h16_pre_io_allocation_test), + KUNIT_CASE(ane_h16_pre_io_fault_test), + KUNIT_CASE(ane_h16_happy_test), + KUNIT_CASE(ane_h16_locked_matching_test), + KUNIT_CASE(ane_h16_heap_overlap_test), + KUNIT_CASE(ane_h16_native_free_test), + KUNIT_CASE(ane_h16_control_refusal_test), + KUNIT_CASE(ane_h16_foreign_free_test), + KUNIT_CASE(ane_h16_mailbox_test), + KUNIT_CASE(ane_h16_no_heap_test), + KUNIT_CASE(ane_h16_power_actual_test), + KUNIT_CASE(ane_h16_rvbar_test), + KUNIT_CASE(ane_h16_dart_fault_test), + KUNIT_CASE(ane_h16_map_failure_test), + KUNIT_CASE(ane_h16_no_ready_test), + KUNIT_CASE(ane_h16_wrong_table_test), + KUNIT_CASE(ane_h16_stale_table_test), + KUNIT_CASE(ane_h16_oversized_ipc_test), + KUNIT_CASE(ane_h16_oversized_heap_test), + KUNIT_CASE(ane_h16_channel_limit_test), + KUNIT_CASE(ane_h16_locked_dapf_test), + KUNIT_CASE(ane_h16_nonzero_ack_test), + KUNIT_CASE(ane_h16_preflight_test), + KUNIT_CASE(ane_h16_default_test), + KUNIT_CASE(ane_h16_ce_timeout_test), + KUNIT_CASE(ane_h16_zero_tick_test), + KUNIT_CASE(ane_h16_scratch3_timeout_test), + {} +}; + +static struct kunit_suite ane_h16_boot_suite = { + .name = "ane-h16-boot", + .init = sim_init, + .test_cases = ane_h16_boot_cases, +}; + +kunit_test_suite(ane_h16_boot_suite); + +MODULE_DESCRIPTION("KUnit simulated H16 cold boot engine"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_execute.h b/drivers/accel/ane/ane_h16_execute.h new file mode 100644 index 0000000000000..df3cb515e9e2c --- /dev/null +++ b/drivers/accel/ane/ane_h16_execute.h @@ -0,0 +1,208 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_EXECUTE_H__ +#define __ANE_H16_EXECUTE_H__ + +#include + +#include "ane_h16_protocol.h" + +#define ANE_H16_EXECUTE_BASE_SIZE 0xca8 +#define ANE_H16_BUFFER_OFFSET 0x60 +#define ANE_H16_BUFFER_STRIDE 0x30 +#define ANE_H16_MAX_BUFFERS 64 +#define ANE_H16_CUSTOM_BAR_STRIDE 0x18 +/* Conservative observed-version ceiling, not a firmware maximum. */ +#define ANE_H16_MAX_CUSTOM_BARS 2 + +struct ane_h16_request_key { + u64 uuid; + u32 program; + u32 process; + u32 procedure; +}; + +/* Kernel-owned, validated process resources and pinned mapping geometry. */ +struct ane_h16_execute_buffer { + u32 index; + u32 class; + u64 mapping_dva; + u64 mapping_size; + u64 offset; + u64 size; +}; + +/* Selectors and value interpretation must come from validated program metadata. */ +struct ane_h16_custom_bar { + u32 configuration; + u32 value_type; + u32 bar; + u8 bit_offset; + u8 bit_width; + u16 flags; + u64 value; +}; + +struct ane_h16_execute { + struct ane_h16_request_key key; + const struct ane_h16_execute_buffer *buffers; + unsigned int buffer_count; + const struct ane_h16_custom_bar *bars; + unsigned int bar_count; +}; + +/* + * Encode only after matching resources, permissions and BAR selectors to the + * immutable loaded program. This helper checks geometry, not mapping ownership. + * Inputs must remain immutable and must not alias the destination. On error the + * destination is untouched. No mapping is published or released by this helper. + */ +static inline int +ane_h16_execute_encode(void *command, size_t length, const struct ane_h16_execute *call) +{ + u8 *p = command; + unsigned int i, j; + size_t expected; + + if (!p || !call || !call->buffers || !call->buffer_count || + call->buffer_count > ANE_H16_MAX_BUFFERS || + call->bar_count > ANE_H16_MAX_CUSTOM_BARS || + (call->bar_count && !call->bars)) + return -EINVAL; + expected = ANE_H16_EXECUTE_BASE_SIZE + call->bar_count * ANE_H16_CUSTOM_BAR_STRIDE; + if (length != expected) + return -EINVAL; + for (i = 0; i < call->buffer_count; i++) { + const struct ane_h16_execute_buffer *b = &call->buffers[i]; + + if (!b->size || b->mapping_size > U64_MAX - b->mapping_dva || + b->offset > b->mapping_size || b->size > b->mapping_size - b->offset) + return -EINVAL; + } + for (i = 0; i < call->bar_count; i++) { + const struct ane_h16_custom_bar *b = &call->bars[i]; + unsigned int end = b->bit_offset + b->bit_width; + + /* Conservative 64-bit field bound until wider fields are established. */ + if (!b->bit_width || end > 64) + return -EINVAL; + for (j = 0; j < i; j++) { + const struct ane_h16_custom_bar *a = &call->bars[j]; + + if (a->configuration == b->configuration && a->bar == b->bar && + a->bit_offset < end && + b->bit_offset < a->bit_offset + a->bit_width) + return -EINVAL; + } + } + + memset(p, 0, length); + put_unaligned_le16(ANE_H16_EXECUTE, p + 4); + put_unaligned_le32(call->key.program, p + 8); + put_unaligned_le32(call->key.process, p + 0xc); + put_unaligned_le32(call->key.procedure, p + 0x10); + put_unaligned_le32(5, p + 0x18); + put_unaligned_le64(call->key.uuid, p + 0x20); + put_unaligned_le32(call->buffer_count, p + 0x28); + for (i = 0; i < call->buffer_count; i++) { + const struct ane_h16_execute_buffer *b = &call->buffers[i]; + u8 *d = p + ANE_H16_BUFFER_OFFSET + i * ANE_H16_BUFFER_STRIDE; + + put_unaligned_le32(1, d); + put_unaligned_le32(b->index, d + 4); + put_unaligned_le32(b->class, d + 8); + put_unaligned_le32(3, d + 0x10); + put_unaligned_le64(b->mapping_dva + b->offset, d + 0x18); + put_unaligned_le64(b->size, d + 0x20); + } + put_unaligned_le32(call->bar_count, p + 0xca0); + for (i = 0; i < call->bar_count; i++) { + const struct ane_h16_custom_bar *b = &call->bars[i]; + u8 *d = p + ANE_H16_EXECUTE_BASE_SIZE + i * ANE_H16_CUSTOM_BAR_STRIDE; + + put_unaligned_le32(b->configuration, d); + put_unaligned_le32(b->value_type, d + 4); + put_unaligned_le32(b->bar, d + 8); + d[0xc] = b->bit_offset; + d[0xd] = b->bit_width; + put_unaligned_le16(b->flags, d + 0xe); + put_unaligned_le64(b->value, d + 0x10); + } + return 0; +} + +enum ane_h16_event_state { + ANE_H16_EVENT_START, + ANE_H16_EVENT_SUCCESS, + ANE_H16_EVENT_FAILURE, + ANE_H16_EVENT_HW_START, +}; + +struct ane_h16_event { + struct ane_h16_request_key key; + u32 state; + u32 cpu_load; + u64 timestamp; + u8 destination; +}; + +/* Parse a bounded host-owned snapshot. Diagnostic words are not predicates. */ +static inline int +ane_h16_event_decode(const void *event, size_t length, unsigned int channel, + struct ane_h16_event *decoded) +{ + const u8 *p = event; + struct ane_h16_event e = {}; + + if (!decoded || ane_h16_event_report_status(event, length, channel)) + return -EPROTO; + e.key.uuid = get_unaligned_le64(p + 8); + e.key.program = get_unaligned_le32(p + 0x10); + e.key.process = get_unaligned_le32(p + 0x14); + e.key.procedure = get_unaligned_le32(p + 0x18); + e.state = get_unaligned_le32(p + 0x1c); + e.cpu_load = get_unaligned_le32(p + 0x20); + e.timestamp = get_unaligned_le64(p + 0x28); + e.destination = p[0x30]; + if (e.state > ANE_H16_EVENT_HW_START || e.destination > 1) + return -EPROTO; + *decoded = e; + return 0; +} + +enum ane_h16_event_result { + ANE_H16_EVENT_PROGRESS, + ANE_H16_EVENT_COMPLETE, + ANE_H16_EVENT_FAILED, +}; + +/* + * For the general scheduler only. Look up an outstanding UUID before calling; + * remove it atomically on terminal state to reject duplicates and late reports. + * COMPLETE/FAILED classify an event, not permission to unmap: DMA sync and + * failure quarantine remain the caller's responsibility. Never call on ch7 ACK. + */ +static inline int +ane_h16_event_result(const void *event, size_t length, unsigned int channel, + const struct ane_h16_request_key *pending) +{ + struct ane_h16_event e; + int ret; + + if (!pending) + return -EINVAL; + ret = ane_h16_event_decode(event, length, channel, &e); + if (ret) + return ret; + if (e.destination) + return -ENOMSG; + if (e.key.uuid != pending->uuid || e.key.program != pending->program || + e.key.process != pending->process || e.key.procedure != pending->procedure) + return -EPROTO; + if (e.state == ANE_H16_EVENT_SUCCESS) + return ANE_H16_EVENT_COMPLETE; + if (e.state == ANE_H16_EVENT_FAILURE) + return ANE_H16_EVENT_FAILED; + return ANE_H16_EVENT_PROGRESS; +} + +#endif /* __ANE_H16_EXECUTE_H__ */ diff --git a/drivers/accel/ane/ane_h16_execute_test.c b/drivers/accel/ane/ane_h16_execute_test.c new file mode 100644 index 0000000000000..933011c18a77a --- /dev/null +++ b/drivers/accel/ane/ane_h16_execute_test.c @@ -0,0 +1,317 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include + +#include "ane_h16_execute.h" + +#define TEST_COMMAND_SIZE 0xcd8 + +static const struct ane_h16_request_key test_key = { + .uuid = 0x8877665544332211ULL, + .program = 0x10203040, + .process = 0x50607080, + .procedure = 0x90a0b0c0, +}; + +static struct ane_h16_execute_buffer test_buffer(void) +{ + return (struct ane_h16_execute_buffer) { + .index = 7, + .class = 1, + .mapping_dva = 0x12300000000ULL, + .mapping_size = 0x300000000ULL, + .offset = 0x10000, + .size = 0x200000000ULL, + }; +} + +static void ane_h16_execute_layout_test(struct kunit *test) +{ + static const u8 header[] = { + 0, 0, 0, 0, 0x0c, 2, 0, 0, + 0x40, 0x30, 0x20, 0x10, 0x80, 0x70, 0x60, 0x50, + 0xc0, 0xb0, 0xa0, 0x90, 0, 0, 0, 0, + 5, 0, 0, 0, 0, 0, 0, 0, + 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, + 1, 0, 0, 0, + }; + static const u8 descriptor[] = { + 1, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, + 3, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0x23, 1, 0, 0, + 0, 0, 0, 0, 2, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + }; + struct ane_h16_execute_buffer buffer = test_buffer(); + struct ane_h16_execute call = { test_key, &buffer, 1, NULL, 0 }; + u8 *storage = kunit_kmalloc(test, TEST_COMMAND_SIZE + 2, GFP_KERNEL); + u8 *p; + + KUNIT_ASSERT_NOT_NULL(test, storage); + memset(storage, 0xa5, TEST_COMMAND_SIZE + 2); + p = storage + 1; /* Exercise unaligned output and both destination guards. */ + KUNIT_ASSERT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), 0); + KUNIT_EXPECT_MEMEQ(test, p, header, sizeof(header)); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(p + sizeof(header), 0, 0x60 - sizeof(header)), NULL); + KUNIT_EXPECT_MEMEQ(test, p + 0x60, descriptor, sizeof(descriptor)); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(p + 0x90, 0, 0xca8 - 0x90), NULL); + KUNIT_EXPECT_EQ(test, storage[0], (u8)0xa5); + KUNIT_EXPECT_EQ(test, p[0xca8], (u8)0xa5); +} + +static void ane_h16_execute_counts_test(struct kunit *test) +{ + struct ane_h16_execute_buffer *buffers; + struct ane_h16_execute call = { .key = test_key }; + u8 *p = kunit_kmalloc(test, TEST_COMMAND_SIZE, GFP_KERNEL); + unsigned int n, i; + + buffers = kunit_kcalloc(test, 64, sizeof(*buffers), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, p); + KUNIT_ASSERT_NOT_NULL(test, buffers); + for (i = 0; i < 64; i++) { + buffers[i] = test_buffer(); + buffers[i].index = i; + buffers[i].class = 8; /* Numeric classes have no guessed semantic name. */ + } + call.buffers = buffers; + for (n = 1; n <= 64; n++) { + size_t end = 0x60 + n * 0x30; + + call.buffer_count = n; + memset(p, 0xa5, TEST_COMMAND_SIZE); + KUNIT_ASSERT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(p + 0x28), n); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(p + end - 0x30 + 4), n - 1); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(p + end - 0x30 + 8), 8U); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(p + end, 0, 0xca8 - end), NULL); + } +} + +static void ane_h16_custom_bar_test(struct kunit *test) +{ + static const u8 first_bar[] = { + 4, 3, 2, 1, 8, 7, 6, 5, 12, 11, 10, 9, + 0, 32, 0x34, 0x12, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, + }; + struct ane_h16_execute_buffer buffer = test_buffer(); + struct ane_h16_custom_bar bars[2] = { + { 0x01020304, 0x05060708, 0x090a0b0c, 0, 32, 0x1234, + 0x1112131415161718ULL }, + { 0x01020304, 0x05060708, 0x090a0b0c, 32, 32, 0, 0x2122232425262728ULL }, + }; + struct ane_h16_execute call = { test_key, &buffer, 1, bars, 0 }; + u8 *p = kunit_kmalloc(test, TEST_COMMAND_SIZE + 1, GFP_KERNEL); + unsigned int n; + + KUNIT_ASSERT_NOT_NULL(test, p); + for (n = 0; n <= 2; n++) { + size_t length = 0xca8 + n * 0x18; + + call.bar_count = n; + memset(p, 0xa5, TEST_COMMAND_SIZE + 1); + KUNIT_ASSERT_EQ(test, ane_h16_execute_encode(p, length, &call), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(p + 0xca0), n); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(p + 0xca4), 0U); + KUNIT_EXPECT_EQ(test, p[length], (u8)0xa5); + if (n) + KUNIT_EXPECT_MEMEQ(test, p + 0xca8, first_bar, sizeof(first_bar)); + if (n == 2) { + KUNIT_EXPECT_EQ(test, p[0xccc], (u8)32); + KUNIT_EXPECT_EQ(test, p[0xccd], (u8)32); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(p + 0xcd0), + 0x2122232425262728ULL); + } + } +} + +static void ane_h16_execute_rejections_test(struct kunit *test) +{ + struct ane_h16_execute_buffer buffer = test_buffer(); + struct ane_h16_execute call = { test_key, &buffer, 1, NULL, 0 }; + u8 *p = kunit_kmalloc(test, TEST_COMMAND_SIZE, GFP_KERNEL); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, p); + memset(p, 0xa5, TEST_COMMAND_SIZE); + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(NULL, 0xca8, &call), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, NULL), -EINVAL); + for (i = 0; i < 4; i++) { + static const size_t lengths[] = { 0, 0xca7, 0xca9, 0xcc0 }; + + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, lengths[i], &call), -EINVAL); + } + call.buffer_count = 0; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + call.buffer_count = 65; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + call.buffer_count = 1; + call.buffers = NULL; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + call.buffers = &buffer; + call.bar_count = 3; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcf0, &call), -EINVAL); + call.bar_count = 1; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcc0, &call), -EINVAL); + call.bar_count = 0; + buffer.size = 0; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + buffer = test_buffer(); + buffer.offset = buffer.mapping_size + 1; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + buffer.offset = buffer.mapping_size; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + buffer = test_buffer(); + buffer.size = buffer.mapping_size - buffer.offset + 1; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + buffer = test_buffer(); + buffer.mapping_dva = U64_MAX - buffer.mapping_size + 1; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), -EINVAL); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(p, 0xa5, TEST_COMMAND_SIZE), NULL); + /* The exact last byte of a mapping is valid. */ + buffer = test_buffer(); + buffer.offset = buffer.mapping_size - 1; + buffer.size = 1; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xca8, &call), 0); +} + +static void ane_h16_bar_rejections_test(struct kunit *test) +{ + struct ane_h16_execute_buffer buffer = test_buffer(); + struct ane_h16_custom_bar bars[2] = { { .bit_width = 32 }, { .bit_width = 32 } }; + struct ane_h16_execute call = { test_key, &buffer, 1, bars, 2 }; + u8 *p = kunit_kmalloc(test, TEST_COMMAND_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, p); + memset(p, 0xa5, TEST_COMMAND_SIZE); + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), -EINVAL); + bars[1].bit_offset = 31; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), -EINVAL); + bars[1].bit_offset = 33; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), -EINVAL); + bars[1].bit_offset = 255; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), -EINVAL); + bars[1].bit_offset = 32; + bars[1].bit_width = 0; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), -EINVAL); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(p, 0xa5, TEST_COMMAND_SIZE), NULL); + bars[1].bit_width = 32; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), 0); + bars[1].bit_offset = 0; + bars[1].bar = 1; /* Distinct BARs do not overlap. */ + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), 0); + bars[1].bar = 0; + bars[1].configuration = 1; + KUNIT_EXPECT_EQ(test, ane_h16_execute_encode(p, 0xcd8, &call), 0); +} + +static void ane_h16_test_event(u8 *p, u32 state) +{ + memset(p, 0, 0x60); + put_unaligned_le32(0x12345678, p); /* A rolling word, not fe0N. */ + put_unaligned_le16(0x300, p + 4); + put_unaligned_le64(test_key.uuid, p + 8); + put_unaligned_le32(test_key.program, p + 0x10); + put_unaligned_le32(test_key.process, p + 0x14); + put_unaligned_le32(test_key.procedure, p + 0x18); + put_unaligned_le32(state, p + 0x1c); + put_unaligned_le32(10, p + 0x20); + put_unaligned_le64(0x123456789abcdef0ULL, p + 0x28); + memset(p + 0x31, 0xff, 0x2f); /* Diagnostics do not decide completion. */ +} + +static void ane_h16_event_correlation_test(struct kunit *test) +{ + static const int results[] = { 0, 1, 2, 0 }; + struct ane_h16_event e; + u8 storage[0x61], *p = storage + 1; + unsigned int state, n; + + for (state = 0; state < 4; state++) { + ane_h16_test_event(p, state); + KUNIT_ASSERT_EQ(test, ane_h16_event_decode(p, 0x60, 6, &e), 0); + KUNIT_EXPECT_EQ(test, e.key.uuid, test_key.uuid); + KUNIT_EXPECT_EQ(test, e.state, state); + KUNIT_EXPECT_EQ(test, e.cpu_load, 10U); + KUNIT_EXPECT_EQ(test, e.timestamp, 0x123456789abcdef0ULL); + KUNIT_EXPECT_EQ(test, ane_h16_event_result(p, 0x60, 6, &test_key), results[state]); + for (n = 0; n < 4; n++) { + put_unaligned_le32(0xfe00 + n, p); + KUNIT_EXPECT_EQ(test, ane_h16_event_result(p, 0x60, 6, &test_key), + results[state]); + } + } + ane_h16_test_event(p, 1); + for (n = 0; n < 4; n++) { + struct ane_h16_request_key other = test_key; + + switch (n) { + case 0: + other.uuid ^= BIT_ULL(63); + break; + case 1: + other.program++; + break; + case 2: + other.process++; + break; + case 3: + other.procedure++; + break; + } + KUNIT_EXPECT_EQ(test, ane_h16_event_result(p, 0x60, 6, &other), -EPROTO); + } + p[0x30] = 1; /* ISP traffic cannot retire a general scheduler request. */ + KUNIT_EXPECT_EQ(test, ane_h16_event_result(p, 0x60, 6, &test_key), -ENOMSG); +} + +static void ane_h16_event_rejections_test(struct kunit *test) +{ + struct ane_h16_event e; + u8 p[0x61]; + size_t n; + + ane_h16_test_event(p, 1); + memset(&e, 0xa5, sizeof(e)); + for (n = 0; n < 0x60; n++) + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(p, n, 6, &e), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(p, sizeof(p), 6, &e), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(p, 0x60, 7, &e), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(NULL, 0x60, 6, &e), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(p, 0x60, 6, NULL), -EPROTO); + put_unaligned_le16(0x20c, p + 4); /* An ACK is never a terminal event. */ + KUNIT_EXPECT_EQ(test, ane_h16_event_result(p, 0x60, 7, &test_key), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_result(p, 0x60, 6, &test_key), -EPROTO); + put_unaligned_le16(0x300, p + 4); + put_unaligned_le16(0x100, p + 6); + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(p, 0x60, 6, &e), -EPROTO); + put_unaligned_le16(0, p + 6); + put_unaligned_le32(4, p + 0x1c); + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(p, 0x60, 6, &e), -EPROTO); + put_unaligned_le32(1, p + 0x1c); + p[0x30] = 2; + KUNIT_EXPECT_EQ(test, ane_h16_event_decode(p, 0x60, 6, &e), -EPROTO); + KUNIT_EXPECT_EQ(test, ane_h16_event_result(p, 0x60, 6, NULL), -EINVAL); + KUNIT_EXPECT_PTR_EQ(test, memchr_inv(&e, 0xa5, sizeof(e)), NULL); +} + +static struct kunit_case ane_h16_execute_cases[] = { + KUNIT_CASE(ane_h16_execute_layout_test), + KUNIT_CASE(ane_h16_execute_counts_test), + KUNIT_CASE(ane_h16_custom_bar_test), + KUNIT_CASE(ane_h16_execute_rejections_test), + KUNIT_CASE(ane_h16_bar_rejections_test), + KUNIT_CASE(ane_h16_event_correlation_test), + KUNIT_CASE(ane_h16_event_rejections_test), + {} +}; + +static struct kunit_suite ane_h16_execute_suite = { + .name = "ane-h16-execute", + .test_cases = ane_h16_execute_cases, +}; + +kunit_test_suite(ane_h16_execute_suite); +MODULE_DESCRIPTION("KUnit tests for H16 execute serialization and event correlation"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_hwx.c b/drivers/accel/ane/ane_h16_hwx.c new file mode 100644 index 0000000000000..07d2b5809fcc1 --- /dev/null +++ b/drivers/accel/ane/ane_h16_hwx.c @@ -0,0 +1,662 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include +#include +#include + +#include "ane_h16_hwx.h" +#include "ane_h16_tasks.h" + +#define HWX_COMMANDS_MAX 64 +#define HWX_SYMBOLS_MAX 4096 +#define HWX_SEGMENTS_MAX 8 + +struct hwx_range { + u64 start, size; +}; + +struct hwx_parser { + const u8 *bytes; + size_t size, command_end; + struct ane_h16_hwx info; + struct hwx_range vm[HWX_SEGMENTS_MAX], file[HWX_SEGMENTS_MAX + 4]; + struct ane_h16_hwx_section sections[ANE_H16_SECTIONS]; + u32 tensors[ANE_H16_SURFACES], refs[ANE_H16_SURFACES]; + u32 tensor_count, ref_count, segment_count, file_count, section_count; + u32 symoff, nsyms, stroff, strsize; + bool guard, symtab, metadata; +}; + +static bool hwx_fits(u64 start, u64 length, u64 size) +{ + return start <= size && length <= size - start; +} + +static bool hwx_name(const u8 *p, const char *name) +{ + size_t length = strlen(name); + + return length < 16 && !memcmp(p, name, length) && + !memchr_inv(p + length, 0, 16 - length); +} + +static bool hwx_zero(const u8 *p, size_t start, size_t end) +{ + return !memchr_inv(p + start, 0, end - start); +} + +static int hwx_range_add(struct hwx_range *ranges, u32 *count, u32 max, + u64 start, u64 size) +{ + u64 end; + unsigned int i; + + if (!size || check_add_overflow(start, size, &end) || *count == max) + return -ENOEXEC; + for (i = 0; i < *count; i++) + if (start < ranges[i].start + ranges[i].size && + ranges[i].start < end) + return -ENOEXEC; + ranges[(*count)++] = (struct hwx_range) { start, size }; + return 0; +} + +static int hwx_file_add(struct hwx_parser *p, u64 start, u64 size) +{ + if (start < p->command_end || !hwx_fits(start, size, p->size)) + return -ENOEXEC; + return hwx_range_add(p->file, &p->file_count, ARRAY_SIZE(p->file), start, size); +} + +static int hwx_segment(struct hwx_parser *p, const u8 *c, u32 length) +{ + struct ane_h16_hwx_section *dest; + u64 vm, size, file, filesz; + u32 nsects, prot, i; + bool text, kernel, scratch, surface, guard; + + if (length < 72) + return -ENOEXEC; + vm = get_unaligned_le64(c + 24); + size = get_unaligned_le64(c + 32); + file = get_unaligned_le64(c + 40); + filesz = get_unaligned_le64(c + 48); + prot = get_unaligned_le32(c + 60); + nsects = get_unaligned_le32(c + 64); + if (nsects > ANE_H16_SECTIONS || length != 72 + nsects * 80 || + prot != get_unaligned_le32(c + 56) || + hwx_range_add(p->vm, &p->segment_count, ARRAY_SIZE(p->vm), vm, size)) + return -ENOEXEC; + text = hwx_name(c + 8, "__TEXT"); + kernel = hwx_name(c + 8, "__KERN_0"); + scratch = hwx_name(c + 8, "__DATA"); + surface = hwx_name(c + 8, "__FVMLIB"); + guard = hwx_name(c + 8, "__PAGEZERO"); + if (!text && !kernel && !scratch && !surface && !guard) + return -ENOEXEC; + if (guard) { + if (p->guard || vm || size != SZ_16K || file || filesz || prot || nsects) + return -ENOEXEC; + if (get_unaligned_le32(c + 68) != 4) + return -ENOEXEC; + p->guard = true; + return 0; + } + if (surface || scratch) { + if (file || filesz || !IS_ALIGNED(vm, SZ_16K) || + !IS_ALIGNED(size, SZ_16K) || nsects != 1 || size > SZ_256M) + return -ENOEXEC; + } else if (!filesz || filesz > size || size > SZ_256M || + !IS_ALIGNED(vm, SZ_16K) || !IS_ALIGNED(file, SZ_16K) || + hwx_file_add(p, file, filesz)) { + return -ENOEXEC; + } + if (get_unaligned_le32(c + 68) != (surface ? 6 : text ? + (p->info.scratch.size ? 4 : 0) : 4)) + return -ENOEXEC; + if ((text && (prot != 5 || nsects != 2 || p->info.text.size)) || + (kernel && (prot != 1 || nsects != 1 || p->info.kernel.size)) || + (scratch && (prot != 3 || p->info.scratch.size)) || + (surface && (prot < 1 || prot > 2 || + p->info.surface_count == ANE_H16_SURFACES))) + return -ENOEXEC; + + for (i = 0; i < nsects; i++) { + const u8 *s = c + 72 + i * 80; + struct ane_h16_hwx_section section = { + .vm = get_unaligned_le64(s + 32), + .size = get_unaligned_le64(s + 40), + .offset = get_unaligned_le32(s + 48), + .reloff = get_unaligned_le32(s + 56), + .nreloc = get_unaligned_le32(s + 60), + .ordinal = p->section_count + 1, + }; + u32 alignment = get_unaligned_le32(s + 52), j; + bool task = text && hwx_name(s, "__text"); + + if (p->section_count == ANE_H16_SECTIONS || !section.size || + memcmp(s + 16, c + 8, 16) || alignment > 31 || + !IS_ALIGNED(section.vm, 1ULL << alignment) || + section.vm < vm || !hwx_fits(section.vm - vm, section.size, size) || + !hwx_zero(s, 68, 80) || section.reloff > p->size) + return -ENOEXEC; + for (j = 0; j < p->section_count; j++) { + const struct ane_h16_hwx_section *a = &p->sections[j]; + + if (section.vm < a->vm + a->size && a->vm < section.vm + section.size) + return -ENOEXEC; + } + if (surface || scratch) { + if (section.offset || section.reloff || section.nreloc || section.vm != vm) + return -ENOEXEC; + } else if (section.offset < file || + !IS_ALIGNED(section.offset, 1ULL << alignment) || + !hwx_fits(section.offset - file, section.size, filesz) || + section.offset - file != section.vm - vm) { + return -ENOEXEC; + } + if (section.nreloc) { + if (!task || section.nreloc > ANE_H16_TASK_MAX / 4 || + hwx_file_add(p, section.reloff, (u64)section.nreloc * 8)) + return -ENOEXEC; + } + if (text) { + if (task) + dest = &p->info.text; + else if (hwx_name(s, "__const")) + dest = &p->info.constants; + else + return -ENOEXEC; + } else if (kernel && hwx_name(s, "__kern_0")) { + dest = &p->info.kernel; + if (!IS_ALIGNED(section.vm, 64) || section.size > SZ_256M) + return -ENOEXEC; + } else if (scratch && hwx_name(s, "__bss")) { + dest = &p->info.scratch; + } else if (surface && hwx_name(s, prot == 1 ? "__const" : "__data")) { + struct ane_h16_hwx_surface *b = &p->info.surfaces[p->info.surface_count++]; + + b->allocation = size; + b->direction = prot; + dest = &b->section; + } else { + return -ENOEXEC; + } + if (get_unaligned_le32(s + 64) != (task ? + (section.nreloc ? 0x128 : 0x28) : surface ? + (prot == 1 ? 0x21 : 0x23) : scratch ? 0x25 : 0x26)) + return -ENOEXEC; + if (dest->size) + return -ENOEXEC; + *dest = section; + p->sections[p->section_count++] = section; + } + if (p->info.region_count == ANE_H16_REGIONS) + return -ENOEXEC; + p->info.regions[p->info.region_count++] = (struct ane_h16_hwx_region) { + .vm = vm, + .size = size, + .file_offset = file, + .file_size = filesz, + .permissions = prot, + .kind = surface ? ANE_H16_REGION_SURFACE : text ? ANE_H16_REGION_TEXT : + kernel ? ANE_H16_REGION_KERNEL : ANE_H16_REGION_SCRATCH, + }; + return 0; +} + +static bool hwx_format(u32 code) +{ + static const u8 known[] = { + 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 15, 16, 17, + 18, 20, 21, 23, 27, 30, 31, 36, 41, 43, 72, 145, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(known); i++) + if (known[i] == code) + return true; + return false; +} + +static int hwx_program(struct hwx_parser *p) +{ + const u8 *c = p->bytes + p->info.program_offset; + struct ane_h16_hwx *info = &p->info; + u32 length = get_unaligned_le32(c + 4), records, i; + bool mixed = length == 0x8c0; + /* Nonzero cells only; every other byte is checked below. */ + static const u16 common[] = { + 0, 4, 8, 0xc, 0x10, 0x14, 0x20, 0x24, 0x40, 0x44, + 0x810, 0x814, 0x820, 0x824, 0x830, 0x838, 0x83c, + 0x844, 0x848, 0x858, 0x860, + }; + u8 *expected; + int ret = -ENOEXEC; + + if (length != 0x8a0 && !mixed) + return -ENOEXEC; + if (get_unaligned_le32(c + 0xc) != (mixed ? 0x22a : 0x222) || + get_unaligned_le64(c + 0x10) != info->text.vm || + get_unaligned_le64(c + 0x810) != info->text.vm || + get_unaligned_le64(c + 0x20) != info->constants.vm || + get_unaligned_le32(c + 0x820) != 4 || + (u64)get_unaligned_le32(c + 0x824) * 4 != info->text.size || + 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)) + return -ENOEXEC; + records = get_unaligned_le32(c + 0x860); + if (records != 0x10 && records != 0x12 && records != 0x1f && records != 0x20) + return -ENOEXEC; + info->tasks = get_unaligned_le32(c + 0x830); + if (mixed) { + u32 usable = get_unaligned_le32(c + 0x858); + + if (!info->scratch.size || !usable || usable > info->scratch.size || + get_unaligned_le64(c + 0x40) != info->scratch.vm || + get_unaligned_le32(c + 0x880) != usable) + return -ENOEXEC; + } else if (info->scratch.size || get_unaligned_le64(c + 0x40) || + get_unaligned_le32(c + 0x858)) { + return -ENOEXEC; + } + 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; + + if (get_unaligned_le64(c + 0x70 + i * 16) != base || + get_unaligned_le64(c + 0x78 + i * 16)) + return -ENOEXEC; + } + if (!hwx_format(get_unaligned_le32(c + (mixed ? 0x8b0 : 0x890)))) + return -ENOEXEC; + + /* Construct the exact fixed trailer and reserved-space expectation. */ + expected = kzalloc(length, GFP_KERNEL); + if (!expected) + return -ENOMEM; + for (i = 0; i < ARRAY_SIZE(common); i++) + memcpy(expected + common[i], c + common[i], 4); + for (i = 0; i < 5; i++) + memcpy(expected + 0x70 + i * 16, c + 0x70 + 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); + 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); + } + memcpy(expected + (mixed ? 0x8b0 : 0x890), c + (mixed ? 0x8b0 : 0x890), 4); + memcpy(expected + (mixed ? 0x8b8 : 0x898), "main", 5); + if (!memcmp(c, expected, length)) + ret = ane_h16_task_stream_validate(p->bytes + info->text.offset, + info->text.size, info->tasks); + kfree(expected); + return ret; +} + +static int hwx_tensor(struct hwx_parser *p, u32 index) +{ + struct ane_h16_hwx_surface *b = &p->info.surfaces[index]; + const u8 *c = p->bytes + p->tensors[index]; + const u8 *ref = p->bytes + p->refs[index]; + u32 length = get_unaligned_le32(c + 4), shortoff; + u64 n, channels, height, width, row, plane, batch, minimum; + size_t symbol_length, short_length; + unsigned int i; + + if (length < 0xd48 || length > SZ_16K || get_unaligned_le32(c + 0xc) != 0x34a || + get_unaligned_le32(c + 0x10) != 3 || + get_unaligned_le32(c + 0x14) != b->direction || + get_unaligned_le32(c + 0x18) != 0xd38 || !hwx_zero(c, 0x1c, 0x20) || + get_unaligned_le32(c + 0x20) != 0xd3d || + get_unaligned_le32(c + 0x24) != 5 || + get_unaligned_le32(c + 0x38) != 1 || !hwx_zero(c, 0x3c, 0x50) || + get_unaligned_le64(c + 0x68) != 2 || + get_unaligned_le32(c + 0x78) != 1 || !hwx_zero(c, 0x88, 0xd38) || + memcmp(c + 0xd38, "main", 5)) + return -ENOEXEC; + n = get_unaligned_le32(c + 0x28); + channels = get_unaligned_le32(c + 0x2c); + height = get_unaligned_le32(c + 0x30); + width = get_unaligned_le32(c + 0x34); + batch = get_unaligned_le64(c + 0x50); + plane = get_unaligned_le64(c + 0x58); + row = get_unaligned_le64(c + 0x60); + if (!n || !channels || !height || !width || + check_mul_overflow(width, 2ULL, &minimum) || row < minimum || + check_mul_overflow(height, row, &minimum) || plane < minimum || + check_mul_overflow(channels, plane, &minimum) || batch < minimum || + get_unaligned_le64(c + 0x70) != batch || + get_unaligned_le64(c + 0x80) != batch || + check_mul_overflow(n, batch, &b->span) || b->span > b->section.size) + return -ENOEXEC; + symbol_length = strnlen(c + 0xd3d, min_t(u32, 256, length - 0xd3d)); + if (!symbol_length || symbol_length == min_t(u32, 256, length - 0xd3d)) + return -ENOEXEC; + shortoff = get_unaligned_le32(c + 0x7c); + if (shortoff != 0xd3d + symbol_length + 1 || shortoff >= length) + return -ENOEXEC; + short_length = strnlen(c + shortoff, length - shortoff); + if (!short_length || short_length == length - shortoff || + short_length >= sizeof(b->name) || + !hwx_zero(c, shortoff + short_length + 1, length)) + return -ENOEXEC; + memcpy(b->name, c + shortoff, short_length); + b->symbol_offset = p->tensors[index] + 0xd3d; + if (get_unaligned_le64(ref + 8) != 0x18 || + get_unaligned_le64(ref + 0x10) != b->section.vm || + memcmp(ref + 0x18, b->name, sizeof(b->name))) + return -ENOEXEC; + for (i = 0; i < index; i++) + if (!strcmp(b->name, p->info.surfaces[i].name) || + !strcmp(p->bytes + b->symbol_offset, + p->bytes + p->info.surfaces[i].symbol_offset)) + return -ENOEXEC; + return 0; +} + +static int hwx_symbols(struct hwx_parser *p) +{ + u32 found = 0, i, j; + + if (!p->symtab || !p->nsyms || p->nsyms > HWX_SYMBOLS_MAX || + !p->strsize || p->strsize > SZ_256K || + hwx_file_add(p, p->symoff, (u64)p->nsyms * 16) || + hwx_file_add(p, p->stroff, p->strsize) || p->bytes[p->stroff]) + return -ENOEXEC; + for (i = 0; i < p->nsyms; i++) { + const u8 *s = p->bytes + p->symoff + i * 16; + u32 strx = get_unaligned_le32(s); + u64 value = get_unaligned_le64(s + 8); + const struct ane_h16_hwx_section *section; + const char *name; + + if (strx >= p->strsize || !s[5] || s[5] > p->section_count || + (s[4] & ~1) != 0xe) + return -ENOEXEC; + name = p->bytes + p->stroff + strx; + if (!*name || strnlen(name, min_t(u32, 256, p->strsize - strx)) == + min_t(u32, 256, p->strsize - strx)) + return -ENOEXEC; + for (j = 0; j < i; j++) { + u32 previous = get_unaligned_le32(p->bytes + p->symoff + j * 16); + + if (!strcmp(name, p->bytes + p->stroff + previous)) + return -ENOEXEC; + } + section = &p->sections[s[5] - 1]; + if (value < section->vm || value - section->vm >= section->size) + return -ENOEXEC; + for (j = 0; j < p->info.surface_count; j++) { + const struct ane_h16_hwx_surface *b = &p->info.surfaces[j]; + + if (strcmp(name, b->name)) + continue; + if ((found & BIT(j)) || s[5] != b->section.ordinal || + value != b->section.vm) + return -ENOEXEC; + found |= BIT(j); + } + } + return found == BIT(p->info.surface_count) - 1 ? 0 : -ENOEXEC; +} + +/* The stream has already passed the complete structural walk. Clear every + * payload site from the relocation bitmap: any remaining bit names a prefix, + * header, register selector or padding byte, which must never be relocated. + */ +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; + + while (pos < p->info.text.size) { + u32 words = (get_unaligned_le32(text + pos) >> 16) & 0x7ff; + size_t end, record; + + if (!words) { + pos += 16; + continue; + } + 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) +{ + struct hwx_parser *p; + const void *relocations; + const u8 *c = bytes; + size_t pos = 32; + u32 count, length, i; + unsigned long *seen = NULL; + int ret = -ENOEXEC; + + 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) != 7 || get_unaligned_le32(c + 12) != 2 || + get_unaligned_le32(c + 24) != 0x200000 || get_unaligned_le32(c + 28)) + 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)) + return -ENOEXEC; + p = kzalloc_obj(*p); + if (!p) + return -ENOMEM; + p->bytes = bytes; + p->size = size; + p->command_end = 32 + (size_t)length; + for (i = 0; i < count; i++) { + u32 cmd, len; + + if (!hwx_fits(pos, 8, p->command_end)) + goto invalid; + c = p->bytes + pos; + cmd = get_unaligned_le32(c); + len = get_unaligned_le32(c + 4); + if (len < 8 || (len & 7) || !hwx_fits(pos, len, p->command_end)) + goto invalid; + switch (cmd) { + case 0x19: + ret = hwx_segment(p, c, len); + if (ret) + goto out; + break; + case 2: + if (p->symtab || len != 24) + goto invalid; + p->symtab = true; + p->symoff = get_unaligned_le32(c + 8); + p->nsyms = get_unaligned_le32(c + 12); + p->stroff = get_unaligned_le32(c + 16); + p->strsize = get_unaligned_le32(c + 20); + break; + case 4: + if (len < 16) + goto invalid; + if (get_unaligned_le32(c + 8) == 3) { + if (p->tensor_count == ANE_H16_SURFACES || len < 0xd48) + 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)) + goto invalid; + p->info.program_offset = pos; + } else { + goto invalid; + } + break; + case 0x40: + if (len != 32 || p->ref_count == ANE_H16_SURFACES) + goto invalid; + p->refs[p->ref_count++] = pos; + break; + case 8: { + size_t annotation; + + /* Compiler annotation has no authority over mappings. */ + if (p->metadata || len > SZ_4K || len == 8) + goto invalid; + annotation = strnlen(c + 8, len - 8); + if (annotation == len - 8 || !hwx_zero(c, 8 + annotation, len)) + goto invalid; + p->metadata = true; + break; + } + default: + goto invalid; + } + pos += len; + } + if (pos != p->command_end || !p->guard || !p->info.program_offset || + !p->info.text.size || !p->info.constants.size || + p->info.surface_count < 2 || p->ref_count != p->info.surface_count || + p->tensor_count != p->info.surface_count) + goto invalid; + for (i = 0; i < p->info.surface_count; i++) { + /* Inputs in segment order, exactly one output last. */ + if (p->info.surfaces[i].direction != (i == p->info.surface_count - 1 ? 2 : 1)) + goto invalid; + ret = hwx_tensor(p, i); + if (ret) + goto out; + } + ret = hwx_program(p); + if (ret) + goto out; + ret = hwx_symbols(p); + if (ret) + goto out; + if (p->info.text.nreloc) { + seen = bitmap_zalloc(p->info.text.size / 4, GFP_KERNEL); + if (!seen) { + ret = -ENOMEM; + goto out; + } + } + relocations = p->info.text.nreloc ? p->bytes + p->info.text.reloff : NULL; + ret = ane_h16_relocations_validate(p->bytes + p->info.text.offset, + p->info.text.size, relocations, + p->info.text.nreloc, p->info.kernel.ordinal, + p->info.kernel.vm, p->info.kernel.size, + seen, p->info.text.size / 4); + if (!ret && p->info.text.nreloc && !hwx_relocations_in_payload(p, seen)) + ret = -ENOEXEC; + if (!ret) + *info = p->info; + goto out; +invalid: + ret = -ENOEXEC; +out: + bitmap_free(seen); + kfree(p); + return ret; +} +EXPORT_SYMBOL_GPL(ane_h16_hwx_validate); + +static int hwx_snapshot_finish(struct ane_h16_hwx_snapshot *copy, + struct ane_h16_hwx_snapshot *snapshot) +{ + int ret; + + ret = ane_h16_hwx_validate(copy->bytes, copy->size, ©->info); + if (ret) { + kvfree(copy->bytes); + return ret; + } + sha256(copy->bytes, copy->size, copy->digest); + *snapshot = *copy; + return 0; +} + +int ane_h16_hwx_snapshot_create(const void *bytes, size_t size, + struct ane_h16_hwx_snapshot *snapshot) +{ + struct ane_h16_hwx_snapshot copy = {}; + + if (!bytes || !snapshot || size < 32 || size > ANE_H16_HWX_MAX) + return -EINVAL; + if (snapshot->bytes) + return -EBUSY; + copy.bytes = kvmalloc(size, GFP_KERNEL); + if (!copy.bytes) + return -ENOMEM; + memcpy(copy.bytes, bytes, size); + copy.size = size; + return hwx_snapshot_finish(©, snapshot); +} +EXPORT_SYMBOL_GPL(ane_h16_hwx_snapshot_create); + +/* Import exactly once before parsing or hashing. No userspace digest, + * section list or resource IDs can substitute for this original container. + * Callers supply an empty destination and retain it until all firmware + * references end; importing alone grants no process or execution authority. + */ +int ane_h16_hwx_snapshot_from_user(const void __user *bytes, u64 size, + struct ane_h16_hwx_snapshot *snapshot) +{ + struct ane_h16_hwx_snapshot copy = {}; + + if (!bytes || !snapshot || size < 32 || size > ANE_H16_HWX_MAX) + return -EINVAL; + if (snapshot->bytes) + return -EBUSY; + copy.bytes = vmemdup_user(bytes, size); + if (IS_ERR(copy.bytes)) + return PTR_ERR(copy.bytes); + copy.size = size; + return hwx_snapshot_finish(©, snapshot); +} +EXPORT_SYMBOL_GPL(ane_h16_hwx_snapshot_from_user); + +int ane_h16_hwx_snapshot_check(const struct ane_h16_hwx_snapshot *snapshot) +{ + u8 digest[SHA256_DIGEST_SIZE]; + + if (!snapshot || !snapshot->bytes || snapshot->size < 32 || + snapshot->size > ANE_H16_HWX_MAX) + return -ENOEXEC; + sha256(snapshot->bytes, snapshot->size, digest); + return memcmp(digest, snapshot->digest, sizeof(digest)) ? -ENOEXEC : 0; +} +EXPORT_SYMBOL_GPL(ane_h16_hwx_snapshot_check); + +void ane_h16_hwx_snapshot_destroy(struct ane_h16_hwx_snapshot *snapshot) +{ + kvfree(snapshot->bytes); + memset(snapshot, 0, sizeof(*snapshot)); +} +EXPORT_SYMBOL_GPL(ane_h16_hwx_snapshot_destroy); + +MODULE_DESCRIPTION("H16 original HWX validation"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_hwx.h b/drivers/accel/ane/ane_h16_hwx.h new file mode 100644 index 0000000000000..7435231a469d4 --- /dev/null +++ b/drivers/accel/ane/ane_h16_hwx.h @@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_HWX_H__ +#define __ANE_H16_HWX_H__ + +#include +#include +#include + +#define ANE_H16_SURFACES 4 +#define ANE_H16_SECTIONS 8 +#define ANE_H16_REGIONS 7 +#define ANE_H16_HWX_MAX (SZ_256M + SZ_1M) + +struct ane_h16_hwx_section { + u64 vm; + u64 size; + u32 offset; + u32 reloff; + u32 nreloc; + u32 ordinal; +}; + +struct ane_h16_hwx_surface { + struct ane_h16_hwx_section section; + u64 allocation; + u64 span; + u32 direction; + u32 symbol_offset; + char name[8]; +}; + +enum ane_h16_region_kind { + ANE_H16_REGION_SURFACE, + ANE_H16_REGION_TEXT, + ANE_H16_REGION_KERNEL, + ANE_H16_REGION_SCRATCH, +}; + +/* Original segment geometry, not firmware section IDs or resource indices. */ +struct ane_h16_hwx_region { + u64 vm; + u64 size; + u64 file_offset; + u64 file_size; + u32 permissions; + enum ane_h16_region_kind kind; +}; + +struct ane_h16_hwx { + struct ane_h16_hwx_section text, constants, kernel, scratch; + struct ane_h16_hwx_surface surfaces[ANE_H16_SURFACES]; + u32 surface_count; + u32 tasks; + u32 program_offset; + struct ane_h16_hwx_region regions[ANE_H16_REGIONS]; + u32 region_count; +}; + +/* Input must be one immutable kernel-owned snapshot of the original file. */ +int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *info); + +struct ane_h16_hwx_snapshot { + void *bytes; + size_t size; + u8 digest[SHA256_DIGEST_SIZE]; + struct ane_h16_hwx info; +}; + +/* Snapshot before validation; callers never publish or mutate snapshot bytes. */ +int ane_h16_hwx_snapshot_create(const void *bytes, size_t size, + struct ane_h16_hwx_snapshot *snapshot); +int ane_h16_hwx_snapshot_from_user(const void __user *bytes, u64 size, + struct ane_h16_hwx_snapshot *snapshot); +int ane_h16_hwx_snapshot_check(const struct ane_h16_hwx_snapshot *snapshot); +void ane_h16_hwx_snapshot_destroy(struct ane_h16_hwx_snapshot *snapshot); + +#endif /* __ANE_H16_HWX_H__ */ diff --git a/drivers/accel/ane/ane_h16_hwx_test.c b/drivers/accel/ane/ane_h16_hwx_test.c new file mode 100644 index 0000000000000..3be0150a47640 --- /dev/null +++ b/drivers/accel/ane/ane_h16_hwx_test.c @@ -0,0 +1,612 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +#include "ane_h16_hwx.h" +#include "ane_h16_tasks.h" +#include "ane_h16_load.h" + +struct hwx_fixture { + u8 *bytes; + size_t size, cursor; + u32 commands, program, tensor[2], segment[2], text_command, symtab, reloc; + u32 symbols, strings; +}; + +static u8 *fixture_command(struct hwx_fixture *f, u32 command, u32 length) +{ + u8 *c = f->bytes + f->cursor; + + put_unaligned_le32(command, c); + put_unaligned_le32(length, c + 4); + f->cursor += length; + f->commands++; + return c; +} + +static u8 *fixture_segment(struct hwx_fixture *f, const char *name, u64 vm, + u64 size, u32 offset, u32 prot, u32 flags, u32 sections) +{ + u8 *c = fixture_command(f, 0x19, 72 + sections * 80); + + strscpy(c + 8, name, 16); + put_unaligned_le64(vm, c + 24); + put_unaligned_le64(size, c + 32); + put_unaligned_le64(offset, c + 40); + put_unaligned_le64(offset ? size : 0, c + 48); + put_unaligned_le32(prot, c + 56); + put_unaligned_le32(prot, c + 60); + put_unaligned_le32(sections, c + 64); + put_unaligned_le32(flags, c + 68); + return c + 72; +} + +static void fixture_section(u8 *s, const char *segment, const char *name, + u64 vm, u64 size, u32 offset, u32 alignment, u32 flags) +{ + strscpy(s, name, 16); + strscpy(s + 16, segment, 16); + put_unaligned_le64(vm, s + 32); + put_unaligned_le64(size, s + 40); + put_unaligned_le32(offset, s + 48); + put_unaligned_le32(alignment, s + 52); + put_unaligned_le32(flags, s + 64); +} + +static struct hwx_fixture *fixture_create(struct kunit *test, bool mixed, bool kernel) +{ + struct hwx_fixture *f; + u64 surface = 0x30000000 + (mixed ? SZ_16K : 0); + u64 text = surface + 2 * SZ_16K, kern = text + SZ_32K; + u32 i, strings_length = 1; + u8 *c, *s, *text_section; + static const char * const names[] = { "in", "out" }; + static const char * const symbols[] = { "input", "output" }; + + f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + if (!f) + return NULL; + f->size = kernel ? SZ_64K : SZ_32K + SZ_16K; + f->bytes = kunit_kzalloc(test, f->size, GFP_KERNEL); + if (!f->bytes) + return NULL; + f->cursor = 32; + fixture_segment(f, "__PAGEZERO", 0, SZ_16K, 0, 0, 4, 0); + if (mixed) { + s = fixture_segment(f, "__DATA", 0x30000000, SZ_16K, 0, 3, 4, 1); + fixture_section(s, "__DATA", "__bss", 0x30000000, SZ_16K, 0, 6, 0x25); + } + for (i = 0; i < 2; i++) { + f->segment[i] = f->cursor; + s = fixture_segment(f, "__FVMLIB", surface + i * SZ_16K, SZ_16K, + 0, i + 1, 6, 1); + fixture_section(s, "__FVMLIB", i ? "__data" : "__const", + surface + i * SZ_16K, SZ_16K, 0, 14, i ? 0x23 : 0x21); + } + f->text_command = f->cursor; + text_section = fixture_segment(f, "__TEXT", text, SZ_32K, SZ_16K, 5, + mixed ? 4 : 0, 2); + fixture_section(text_section, "__TEXT", "__text", text, 64, SZ_16K, + 14, kernel ? 0x128 : 0x28); + fixture_section(text_section + 80, "__TEXT", "__const", text + 64, + SZ_16K, SZ_16K + 64, 6, 0x26); + if (kernel) { + s = fixture_segment(f, "__KERN_0", kern, SZ_16K, SZ_32K + SZ_16K, 1, 4, 1); + fixture_section(s, "__KERN_0", "__kern_0", kern, 64, + SZ_32K + SZ_16K, 6, 0x26); + } + for (i = 0; i < 2; i++) { + c = fixture_command(f, 0x40, 32); + put_unaligned_le64(0x18, c + 8); + put_unaligned_le64(surface + i * SZ_16K, c + 0x10); + strscpy(c + 0x18, names[i], 8); + } + f->program = f->cursor; + c = fixture_command(f, 4, mixed ? 0x8c0 : 0x8a0); + put_unaligned_le32(4, c + 8); + put_unaligned_le32(mixed ? 0x22a : 0x222, c + 0xc); + put_unaligned_le64(text, c + 0x10); + put_unaligned_le64(text + 64, c + 0x20); + if (mixed) + put_unaligned_le64(0x30000000, c + 0x40); + for (i = 0; i < 2; i++) + put_unaligned_le64(surface + i * SZ_16K, c + 0x70 + i * 16); + if (kernel) + put_unaligned_le64(kern, c + 0x90); + put_unaligned_le64(text, c + 0x810); + put_unaligned_le32(4, c + 0x820); + put_unaligned_le32(16, c + 0x824); + put_unaligned_le32(1, c + 0x830); + put_unaligned_le32(U32_MAX, c + 0x838); + put_unaligned_le32(U32_MAX, c + 0x83c); + put_unaligned_le32(0xffff, c + 0x844); + put_unaligned_le32(mixed ? 0x8b8 : 0x898, c + 0x848); + put_unaligned_le32(0x10, c + 0x860); + put_unaligned_le32(4, c + 0x868); + put_unaligned_le32(mixed ? 4 : 2, c + 0x870); + put_unaligned_le32(mixed ? 2 : 7, c + 0x878); + put_unaligned_le32(8, c + 0x87c); + put_unaligned_le32(mixed ? 256 : 0x461c4000, c + 0x880); + put_unaligned_le32(mixed ? 3 : 9, c + 0x888); + put_unaligned_le32(8, c + 0x88c); + if (mixed) { + put_unaligned_le32(256, c + 0x858); + put_unaligned_le32(0x08020004, c + 0x890); + put_unaligned_le32(8, c + 0x894); + put_unaligned_le32(7, c + 0x898); + put_unaligned_le32(8, c + 0x89c); + put_unaligned_le32(0x461c4000, c + 0x8a0); + put_unaligned_le32(9, c + 0x8a8); + put_unaligned_le32(8, c + 0x8ac); + } + memcpy(c + (mixed ? 0x8b8 : 0x898), "main", 5); + for (i = 0; i < 2; i++) { + u32 shortoff = 0xd3d + strlen(symbols[i]) + 1; + + f->tensor[i] = f->cursor; + c = fixture_command(f, 4, 0xd48); + put_unaligned_le32(3, c + 8); + put_unaligned_le32(0x34a, c + 0xc); + put_unaligned_le32(3, c + 0x10); + put_unaligned_le32(i + 1, c + 0x14); + put_unaligned_le32(0xd38, c + 0x18); + put_unaligned_le32(0xd3d, c + 0x20); + put_unaligned_le32(5, c + 0x24); + put_unaligned_le32(1, c + 0x28); + put_unaligned_le32(1, c + 0x2c); + put_unaligned_le32(1, c + 0x30); + put_unaligned_le32(128, c + 0x34); + put_unaligned_le32(1, c + 0x38); + put_unaligned_le64(256, c + 0x50); + put_unaligned_le64(256, c + 0x58); + put_unaligned_le64(256, c + 0x60); + put_unaligned_le64(2, c + 0x68); + put_unaligned_le64(256, c + 0x70); + put_unaligned_le32(1, c + 0x78); + put_unaligned_le32(shortoff, c + 0x7c); + put_unaligned_le64(256, c + 0x80); + memcpy(c + 0xd38, "main", 5); + memcpy(c + 0xd3d, symbols[i], strlen(symbols[i]) + 1); + memcpy(c + shortoff, names[i], strlen(names[i]) + 1); + } + f->symtab = f->cursor; + c = fixture_command(f, 2, 24); + f->symbols = f->cursor; + f->strings = f->symbols + 2 * 16; + for (i = 0; i < 2; i++) { + u8 *symbol = f->bytes + f->symbols + i * 16; + + put_unaligned_le32(strings_length, symbol); + symbol[4] = 0xf; + symbol[5] = (mixed ? 2 : 1) + i; + put_unaligned_le64(surface + i * SZ_16K, symbol + 8); + memcpy(f->bytes + f->strings + strings_length, names[i], strlen(names[i]) + 1); + strings_length += strlen(names[i]) + 1; + } + put_unaligned_le32(f->symbols, c + 8); + put_unaligned_le32(2, c + 12); + put_unaligned_le32(f->strings, c + 16); + put_unaligned_le32(strings_length, c + 20); + f->reloc = ALIGN(f->strings + strings_length, 8); + if (kernel) { + put_unaligned_le32(f->reloc, text_section + 56); + put_unaligned_le32(1, text_section + 60); + put_unaligned_le32(56, f->bytes + f->reloc); + put_unaligned_le32(0x07000000 | (mixed ? 6 : 5), f->bytes + f->reloc + 4); + put_unaligned_le32(32, f->bytes + SZ_16K + 56); + } + put_unaligned_le32(1, f->bytes + SZ_16K); + put_unaligned_le32(11 << 16, f->bytes + SZ_16K + 16); + put_unaligned_le32(0x4100 / 4, f->bytes + SZ_16K + 52); + put_unaligned_le32(0xbeefface, f->bytes); + put_unaligned_le32(0x80, f->bytes + 4); + put_unaligned_le32(7, f->bytes + 8); + put_unaligned_le32(2, f->bytes + 12); + put_unaligned_le32(f->commands, f->bytes + 16); + put_unaligned_le32(f->cursor - 32, f->bytes + 20); + put_unaligned_le32(0x200000, f->bytes + 24); + return f; +} + +static void hwx_forms_test(struct kunit *test) +{ + unsigned int variant; + + for (variant = 0; variant < 4; variant++) { + struct hwx_fixture *f = fixture_create(test, variant & 1, variant & 2); + struct ane_h16_hwx info = {}; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0); + KUNIT_EXPECT_EQ(test, info.surface_count, 2U); + KUNIT_EXPECT_EQ(test, info.surfaces[0].span, 256ULL); + KUNIT_EXPECT_EQ(test, info.tasks, 1U); + KUNIT_EXPECT_EQ(test, info.text.ordinal, (variant & 1) ? 4U : 3U); + KUNIT_EXPECT_EQ(test, info.text.nreloc, (variant & 2) ? 1U : 0U); + } +} + +static void hwx_header_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx info; + u32 offset; + + KUNIT_ASSERT_NOT_NULL(test, f); + for (offset = 0; offset < 32; offset += 4) { + u32 saved = get_unaligned_le32(f->bytes + offset); + + put_unaligned_le32(U32_MAX, f->bytes + offset); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(saved, f->bytes + offset); + } + for (offset = 0; offset < 32; offset++) + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, offset, &info), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size - 1, &info), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, ANE_H16_HWX_MAX + 1, &info), -ENOEXEC); + /* A truncated command must not inherit a previous command's success. */ + put_unaligned_le32(f->cursor - 33, f->bytes + 20); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); +} + +static void hwx_command_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx info; + u32 pos; + + KUNIT_ASSERT_NOT_NULL(test, f); + for (pos = 32; pos < f->cursor;) { + u32 command = get_unaligned_le32(f->bytes + pos); + u32 length = get_unaligned_le32(f->bytes + pos + 4); + + put_unaligned_le32(0xffffffff, f->bytes + pos); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(command, f->bytes + pos); + put_unaligned_le32(0, f->bytes + pos + 4); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(length, f->bytes + pos + 4); + pos += length; + } +} + +static void hwx_tensor_test(struct kunit *test) +{ + static const u32 fields[] = { + 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20, 0x24, 0x28, 0x2c, + 0x30, 0x34, 0x38, 0x3c, 0x50, 0x58, 0x60, 0x68, 0x70, + 0x78, 0x7c, 0x80, 0x88, 0xd38, 0xd44, + }; + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx info; + u8 *tensor; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, f); + tensor = f->bytes + f->tensor[0]; + for (i = 0; i < ARRAY_SIZE(fields); i++) { + u32 saved = get_unaligned_le32(tensor + fields[i]); + + put_unaligned_le32(U32_MAX, tensor + fields[i]); + KUNIT_EXPECT_EQ_MSG(test, ane_h16_hwx_validate(f->bytes, f->size, &info), + -ENOEXEC, "tensor field %#x", fields[i]); + put_unaligned_le32(saved, tensor + fields[i]); + } + /* Four batches fit in the allocation; span is not just one batch. */ + put_unaligned_le32(4, tensor + 0x28); + KUNIT_ASSERT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0); + KUNIT_EXPECT_EQ(test, info.surfaces[0].span, 1024ULL); + put_unaligned_le64(U64_MAX, tensor + 0x50); + put_unaligned_le64(U64_MAX, tensor + 0x70); + put_unaligned_le64(U64_MAX, tensor + 0x80); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); +} + +static void hwx_program_test(struct kunit *test) +{ + static const u32 fields[] = { + 0xc, 0x10, 0x18, 0x20, 0x28, 0x40, 0x48, 0x70, 0x78, 0x80, 0x88, + 0x90, 0xa0, 0xb0, 0xb8, 0xc0, 0x80c, 0x810, 0x818, 0x820, 0x824, + 0x828, 0x830, 0x834, 0x838, 0x83c, 0x840, 0x844, 0x848, 0x84c, + 0x858, 0x85c, 0x860, 0x864, 0x868, 0x870, 0x878, 0x880, 0x890, 0x89c, + }; + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx info; + u8 *program; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, f); + program = f->bytes + f->program; + for (i = 0; i < ARRAY_SIZE(fields); i++) { + u32 saved = get_unaligned_le32(program + fields[i]); + + put_unaligned_le32(saved ^ U32_MAX, program + fields[i]); + KUNIT_EXPECT_EQ_MSG(test, ane_h16_hwx_validate(f->bytes, f->size, &info), + -ENOEXEC, "program field %#x", fields[i]); + put_unaligned_le32(saved, program + fields[i]); + } +} + +static void hwx_geometry_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx info; + u8 *segment; + unsigned int variant; + + KUNIT_ASSERT_NOT_NULL(test, f); + segment = f->bytes + f->segment[0]; + for (variant = 0; variant < 8; variant++) { + u32 fields[] = { 24, 32, 40, 48, 56, 60, 64, 72 + 52 }; + u32 saved = get_unaligned_le32(segment + fields[variant]); + + put_unaligned_le32(U32_MAX, segment + fields[variant]); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(saved, segment + fields[variant]); + } + put_unaligned_le64(U64_MAX - SZ_16K + 1, segment + 24); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); +} + +static void hwx_symbols_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx info; + u32 field; + + KUNIT_ASSERT_NOT_NULL(test, f); + for (field = 8; field < 24; field += 4) { + u32 saved = get_unaligned_le32(f->bytes + f->symtab + field); + + put_unaligned_le32(U32_MAX, f->bytes + f->symtab + field); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(saved, f->bytes + f->symtab + field); + } + f->bytes[f->symbols + 5] = 0; + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + f->bytes[f->symbols + 5] = 1; + f->bytes[f->strings + 1] = 'X'; + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); +} + +static void hwx_relocations_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, true, true); + struct ane_h16_hwx info; + + KUNIT_ASSERT_NOT_NULL(test, f); + /* Scratch changes the section ordinal; a fixed ordinal is invalid. */ + put_unaligned_le32(0x07000005, f->bytes + f->reloc + 4); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(0x07000006, f->bytes + f->reloc + 4); + put_unaligned_le32(64, f->bytes + SZ_16K + 56); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(32, f->bytes + SZ_16K + 56); + put_unaligned_le32(57, f->bytes + f->reloc); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + /* A small addend in a header or the prefix must not be patched. */ + put_unaligned_le32(20, f->bytes + f->reloc); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(4, f->bytes + f->reloc); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); +} + +static void hwx_snapshot_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx_snapshot snapshot = {}; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_EQ(test, ane_h16_hwx_snapshot_create(f->bytes, f->size, &snapshot), 0); + f->bytes[f->tensor[0] + 0x24] = 0; + KUNIT_EXPECT_EQ(test, ane_h16_hwx_snapshot_check(&snapshot), 0); + /* Even padding and original command bytes are covered by the digest. */ + ((u8 *)snapshot.bytes)[f->program + 0x100] = 1; + KUNIT_EXPECT_EQ(test, ane_h16_hwx_snapshot_check(&snapshot), -ENOEXEC); + ane_h16_hwx_snapshot_destroy(&snapshot); + KUNIT_EXPECT_PTR_EQ(test, snapshot.bytes, NULL); +} + +static void hwx_snapshot_free(void *snapshot) +{ + ane_h16_hwx_snapshot_destroy(snapshot); +} + +static struct ane_h16_hwx_snapshot *fixture_snapshot(struct kunit *test, + struct hwx_fixture *f) +{ + struct ane_h16_hwx_snapshot *snapshot; + + if (!f) + return NULL; + snapshot = kunit_kzalloc(test, sizeof(*snapshot), GFP_KERNEL); + if (!snapshot || ane_h16_hwx_snapshot_create(f->bytes, f->size, snapshot)) + return NULL; + if (kunit_add_action_or_reset(test, hwx_snapshot_free, snapshot)) + return NULL; + return snapshot; +} + +static void hwx_load_plan_test(struct kunit *test) +{ + unsigned int mixed, kernel; + + for (mixed = 0; mixed < 2; mixed++) { + for (kernel = 0; kernel < 2; kernel++) { + struct hwx_fixture *f = fixture_create(test, mixed, kernel); + struct ane_h16_hwx_snapshot *snapshot = fixture_snapshot(test, f); + struct ane_h16_load_plan plan; + unsigned int text = 2 + mixed; + + KUNIT_ASSERT_NOT_NULL(test, snapshot); + KUNIT_ASSERT_EQ(test, ane_h16_load_plan_create(snapshot, &plan), 0); + KUNIT_EXPECT_EQ(test, plan.count, 3 + mixed + kernel); + KUNIT_EXPECT_EQ(test, plan.total, (u64)(4 + mixed + kernel) * SZ_16K); + KUNIT_EXPECT_EQ(test, plan.regions[text].kind, ANE_H16_REGION_TEXT); + KUNIT_EXPECT_EQ(test, plan.regions[text].permissions, 5); + KUNIT_EXPECT_EQ(test, plan.regions[text].file_offset, (u64)SZ_16K); + KUNIT_EXPECT_EQ(test, plan.regions[text].file_size, (u64)SZ_32K); + /* One TEXT allocation includes task and constant sections. */ + KUNIT_EXPECT_EQ(test, plan.allocation[text], (u64)SZ_32K); + if (mixed) { + KUNIT_EXPECT_EQ(test, plan.regions[0].kind, ANE_H16_REGION_SCRATCH); + KUNIT_EXPECT_EQ(test, plan.regions[0].file_size, 0); + KUNIT_EXPECT_EQ(test, plan.regions[0].permissions, 3); + } + } + } +} + +static void hwx_load_original_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, false, false); + struct ane_h16_hwx_snapshot *snapshot = fixture_snapshot(test, f); + struct ane_h16_load_plan plan; + + KUNIT_ASSERT_NOT_NULL(test, snapshot); + /* Cached metadata cannot replace the original authenticated container. */ + memset(&snapshot->info, 0xff, sizeof(snapshot->info)); + KUNIT_ASSERT_EQ(test, ane_h16_load_plan_create(snapshot, &plan), 0); + KUNIT_EXPECT_EQ(test, plan.count, 3); + ((u8 *)snapshot->bytes)[f->program] ^= 1; + plan.count = 0x1234; + KUNIT_EXPECT_EQ(test, ane_h16_load_plan_create(snapshot, &plan), -ENOEXEC); + KUNIT_EXPECT_EQ(test, plan.count, 0x1234); +} + +static void fixture_mappings(const struct ane_h16_load_plan *plan, + struct ane_h16_load_mapping *mappings) +{ + unsigned int i; + + for (i = 0; i < plan->count; i++) { + mappings[i].dva = 0x20000000000ULL + (u64)i * SZ_1M; + mappings[i].size = plan->allocation[i]; + mappings[i].permissions = plan->regions[i].permissions; + } +} + +static void hwx_load_resources_test(struct kunit *test) +{ + struct hwx_fixture *f = fixture_create(test, true, true); + struct ane_h16_hwx_snapshot *snapshot = fixture_snapshot(test, f); + struct ane_h16_load_mapping mappings[ANE_H16_REGIONS] = {}; + struct ane_h16_process_binding bindings[2]; + struct ane_h16_resource resources[2] = {}; + struct ane_h16_load_plan plan; + unsigned int i; + int ret; + + KUNIT_ASSERT_NOT_NULL(test, snapshot); + KUNIT_ASSERT_EQ(test, ane_h16_load_plan_create(snapshot, &plan), 0); + fixture_mappings(&plan, mappings); + for (i = 0; i < 2; i++) { + bindings[i].hwx_vm = snapshot->info.surfaces[i].section.vm; + bindings[i].index = 123 + 11 * i; + bindings[i].class = i; + } + ret = ane_h16_load_resources_create(snapshot, mappings, plan.count, + bindings, 2, resources); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, resources[0].buffer.mapping_dva, mappings[1].dva); + KUNIT_EXPECT_EQ(test, resources[1].buffer.index, 134); + KUNIT_EXPECT_EQ(test, resources[1].permissions, 2); + for (i = 0; i < 7; i++) { + struct ane_h16_load_mapping saved = mappings[1]; + + switch (i) { + case 0: + mappings[1].dva++; + break; + case 1: + mappings[1].size++; + break; + case 2: + mappings[1].permissions = 3; + break; + case 3: + mappings[1].dva = mappings[3].dva; + break; + case 4: + mappings[1].dva = 0x10000000000ULL; + break; + case 5: + mappings[1].dva = U64_MAX - SZ_16K + 1; + break; + case 6: + mappings[1].dva = 0; + break; + } + resources[0].buffer.index = 0x1234; + ret = ane_h16_load_resources_create(snapshot, mappings, plan.count, + bindings, 2, resources); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + KUNIT_EXPECT_EQ(test, resources[0].buffer.index, 0x1234); + mappings[1] = saved; + } + bindings[1].index = bindings[0].index; + ret = ane_h16_load_resources_create(snapshot, mappings, plan.count, + bindings, 2, resources); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + bindings[1].index++; + bindings[1].class = 8; + ret = ane_h16_load_resources_create(snapshot, mappings, plan.count, + bindings, 2, resources); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + bindings[1].class = 1; + bindings[1].hwx_vm += SZ_16K; + ret = ane_h16_load_resources_create(snapshot, mappings, plan.count, + bindings, 2, resources); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_h16_load_resources_create(snapshot, mappings, plan.count - 1, + bindings, 2, resources); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_h16_load_resources_create(snapshot, mappings, plan.count, + bindings, 1, resources); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); +} + +static void hwx_import_bounds_test(struct kunit *test) +{ + const void __user *invalid = (const void __user *)1UL; + struct ane_h16_hwx_snapshot snapshot = {}; + struct hwx_fixture *f = fixture_create(test, false, false); + int ret; + + KUNIT_ASSERT_NOT_NULL(test, f); + ret = ane_h16_hwx_snapshot_from_user(invalid, U64_MAX, &snapshot); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_snapshot_from_user(invalid, 31, &snapshot), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_snapshot_from_user(invalid, 32, &snapshot), -EFAULT); + KUNIT_EXPECT_PTR_EQ(test, snapshot.bytes, NULL); + KUNIT_ASSERT_EQ(test, ane_h16_hwx_snapshot_create(f->bytes, f->size, &snapshot), 0); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_snapshot_create(f->bytes, f->size, &snapshot), -EBUSY); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_snapshot_from_user(invalid, 32, &snapshot), -EBUSY); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_snapshot_check(&snapshot), 0); + ane_h16_hwx_snapshot_destroy(&snapshot); +} + +static struct kunit_case hwx_cases[] = { + KUNIT_CASE(hwx_forms_test), + KUNIT_CASE(hwx_header_test), + KUNIT_CASE(hwx_command_test), + KUNIT_CASE(hwx_tensor_test), + KUNIT_CASE(hwx_program_test), + KUNIT_CASE(hwx_geometry_test), + KUNIT_CASE(hwx_symbols_test), + KUNIT_CASE(hwx_relocations_test), + KUNIT_CASE(hwx_snapshot_test), + KUNIT_CASE(hwx_load_plan_test), + KUNIT_CASE(hwx_load_original_test), + KUNIT_CASE(hwx_load_resources_test), + KUNIT_CASE(hwx_import_bounds_test), + {} +}; + +static struct kunit_suite hwx_suite = { + .name = "ane-h16-hwx", + .test_cases = hwx_cases, +}; + +kunit_test_suite(hwx_suite); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_load.c b/drivers/accel/ane/ane_h16_load.c new file mode 100644 index 0000000000000..66a41c7eeb8e4 --- /dev/null +++ b/drivers/accel/ane/ane_h16_load.c @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include + +#include "ane_h16_load.h" + +static int h16_load_plan(const struct ane_h16_hwx *hwx, struct ane_h16_load_plan *plan) +{ + struct ane_h16_load_plan next = {}; + unsigned int i; + + if (!hwx->region_count || hwx->region_count > ANE_H16_REGIONS) + return -ENOEXEC; + next.count = hwx->region_count; + for (i = 0; i < next.count; i++) { + const struct ane_h16_hwx_region *r = &hwx->regions[i]; + u64 rounded; + + if (!r->size || check_add_overflow(r->size, (u64)SZ_16K - 1, &rounded)) + return -ENOEXEC; + next.allocation[i] = round_down(rounded, SZ_16K); + if (check_add_overflow(next.total, next.allocation[i], &next.total) || + next.total > ANE_H16_LOAD_BYTES_MAX) + return -E2BIG; + next.regions[i] = *r; + } + *plan = next; + return 0; +} + +int ane_h16_load_plan_create(const struct ane_h16_hwx_snapshot *snapshot, + struct ane_h16_load_plan *plan) +{ + struct ane_h16_hwx hwx; + int ret; + + if (!plan) + return -EINVAL; + ret = ane_h16_hwx_snapshot_check(snapshot); + if (ret) + return ret; + /* Reparse the authenticated original, not caller-supplied cached metadata. */ + ret = ane_h16_hwx_validate(snapshot->bytes, snapshot->size, &hwx); + if (ret) + return ret; + return h16_load_plan(&hwx, plan); +} +EXPORT_SYMBOL_GPL(ane_h16_load_plan_create); + +int ane_h16_load_resources_create(const struct ane_h16_hwx_snapshot *snapshot, + const struct ane_h16_load_mapping *mappings, + unsigned int mapping_count, + const struct ane_h16_process_binding *bindings, + unsigned int binding_count, + struct ane_h16_resource *resources) +{ + struct ane_h16_resource next[ANE_H16_SURFACES] = {}; + struct ane_h16_load_plan plan; + struct ane_h16_hwx hwx; + unsigned int i, j; + int ret; + + if (!mappings || !bindings || !resources) + return -EINVAL; + ret = ane_h16_hwx_snapshot_check(snapshot); + if (ret) + return ret; + ret = ane_h16_hwx_validate(snapshot->bytes, snapshot->size, &hwx); + if (ret) + return ret; + ret = h16_load_plan(&hwx, &plan); + if (ret) + return ret; + if (mapping_count != plan.count || binding_count != hwx.surface_count) + return -EINVAL; + for (i = 0; i < mapping_count; i++) { + const struct ane_h16_load_mapping *m = &mappings[i]; + u64 end; + + if (!m->dva || !IS_ALIGNED(m->dva, SZ_16K) || + m->size != plan.allocation[i] || + m->permissions != plan.regions[i].permissions || + check_add_overflow(m->dva, m->size, &end) || + (m->dva < 0x1000036c000ULL && end > 0x10000000000ULL)) + return -EINVAL; + for (j = 0; j < i; j++) + if (m->dva < mappings[j].dva + mappings[j].size && + mappings[j].dva < end) + return -EINVAL; + } + for (i = 0; i < binding_count; i++) { + const struct ane_h16_hwx_surface *s = &hwx.surfaces[i]; + const struct ane_h16_process_binding *b = &bindings[i]; + + if (b->hwx_vm != s->section.vm || b->class != s->direction - 1) + return -EINVAL; + for (j = 0; j < plan.count; j++) + if (plan.regions[j].kind == ANE_H16_REGION_SURFACE && + plan.regions[j].vm == b->hwx_vm) + break; + if (j == plan.count) + return -EINVAL; + next[i].hwx_vm = b->hwx_vm; + next[i].permissions = s->direction; + next[i].buffer = (struct ane_h16_execute_buffer) { + .index = b->index, + .class = b->class, + .mapping_dva = mappings[j].dva, + .mapping_size = mappings[j].size, + .size = s->span, + }; + } + ret = ane_h16_resources_validate(&hwx, next, binding_count); + if (!ret) + memcpy(resources, next, binding_count * sizeof(*resources)); + return ret; +} +EXPORT_SYMBOL_GPL(ane_h16_load_resources_create); + +MODULE_DESCRIPTION("H16 original HWX load planning and resource geometry"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_load.h b/drivers/accel/ane/ane_h16_load.h new file mode 100644 index 0000000000000..044500394ae7a --- /dev/null +++ b/drivers/accel/ane/ane_h16_load.h @@ -0,0 +1,45 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_LOAD_H__ +#define __ANE_H16_LOAD_H__ + +#include "ane_h16_resources.h" + +/* Conservative host budget; firmware resource replies cannot enlarge it. */ +#define ANE_H16_LOAD_BYTES_MAX SZ_512M + +struct ane_h16_load_plan { + struct ane_h16_hwx_region regions[ANE_H16_REGIONS]; + u64 allocation[ANE_H16_REGIONS]; + u64 total; + u32 count; +}; + +struct ane_h16_load_mapping { + u64 dva; + u64 size; + u32 permissions; +}; + +/* Only the backend may resolve these bindings from the validated program + * contract. CREATE_PROCESS reply IDs do not describe resource bindings. + */ +struct ane_h16_process_binding { + u64 hwx_vm; + u32 index; + u32 class; +}; + +/* Geometry helpers do not prove DMA ownership or install a process. All + * mappings must be backend-owned and private, with the stated permissions. + * Wire serialization and process installation are separate backend operations. + */ +int ane_h16_load_plan_create(const struct ane_h16_hwx_snapshot *snapshot, + struct ane_h16_load_plan *plan); +int ane_h16_load_resources_create(const struct ane_h16_hwx_snapshot *snapshot, + const struct ane_h16_load_mapping *mappings, + unsigned int mapping_count, + const struct ane_h16_process_binding *bindings, + unsigned int binding_count, + struct ane_h16_resource *resources); + +#endif /* __ANE_H16_LOAD_H__ */ diff --git a/drivers/accel/ane/ane_h16_pending.h b/drivers/accel/ane/ane_h16_pending.h new file mode 100644 index 0000000000000..b74b20a0b0ea2 --- /dev/null +++ b/drivers/accel/ane/ane_h16_pending.h @@ -0,0 +1,143 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_PENDING_H__ +#define __ANE_H16_PENDING_H__ + +#include + +#include "ane_h16_execute.h" + +#define ANE_H16_PENDING_MAX 64 + +struct ane_h16_pending { + struct ane_h16_request_key key; + unsigned long deadline; + int status; + bool active; + bool terminal; +}; + +/* All operations, including event dispatch, require the firmware mutex. */ +struct ane_h16_pending_table { + struct ane_h16_pending *slots[ANE_H16_PENDING_MAX]; + u64 next_uuid; + int error; + bool quarantined; +}; + +static inline int +ane_h16_pending_insert(struct ane_h16_pending_table *table, + struct ane_h16_pending *request, unsigned long now) +{ + unsigned int i; + + if (table->quarantined) + return -EIO; + if (!request || request->active || time_after_eq(now, request->deadline)) + return -EINVAL; + for (i = 0; i < ANE_H16_PENDING_MAX; i++) + if (table->slots[i] == request) + return -EEXIST; + if (table->next_uuid == U64_MAX) + return -EOVERFLOW; + for (i = 0; i < ANE_H16_PENDING_MAX; i++) { + if (table->slots[i]) + continue; + /* Never reuse a UUID, including after pre-publication failure. */ + request->key.uuid = ++table->next_uuid; + request->status = -EINPROGRESS; + request->terminal = false; + request->active = true; + table->slots[i] = request; + return 0; + } + return -ENOSPC; +} + +/* Removal is not permission to release DMA backing. */ +static inline void +ane_h16_pending_remove(struct ane_h16_pending_table *table, + struct ane_h16_pending *request) +{ + unsigned int i; + + for (i = 0; i < ANE_H16_PENDING_MAX; i++) + if (table->slots[i] == request) + table->slots[i] = NULL; + request->active = false; +} + +/* A published command with an uncertain outcome pins all its mappings. */ +static inline void +ane_h16_pending_abort(struct ane_h16_pending_table *table, + struct ane_h16_pending *request, int status) +{ + table->quarantined = true; + table->error = status; + ane_h16_pending_remove(table, request); + request->status = status; +} + +static inline int +ane_h16_pending_event(struct ane_h16_pending_table *table, const void *bytes, + size_t length, unsigned int channel, unsigned long now) +{ + struct ane_h16_pending *request = NULL; + struct ane_h16_event event; + unsigned int i; + int ret; + + if (table->quarantined) + return -EIO; + ret = ane_h16_event_decode(bytes, length, channel, &event); + if (ret) + goto corrupt; + if (event.destination) + return -ENOMSG; + for (i = 0; i < ANE_H16_PENDING_MAX; i++) + if (table->slots[i] && table->slots[i]->key.uuid == event.key.uuid) { + request = table->slots[i]; + break; + } + /* Duplicates and late/foreign UUIDs can never retire another call. */ + if (!request) + return -ENOENT; + ret = ane_h16_event_result(bytes, length, channel, &request->key); + if (ret < 0) + goto corrupt; + if (time_after_eq(now, request->deadline)) { + ane_h16_pending_abort(table, request, -ETIMEDOUT); + return -ETIMEDOUT; + } + if (ret == ANE_H16_EVENT_PROGRESS) + return ret; + ane_h16_pending_remove(table, request); + request->terminal = true; + request->status = ret == ANE_H16_EVENT_COMPLETE ? 0 : -EIO; + if (request->status) { + table->error = request->status; + table->quarantined = true; + } + return ret; + +corrupt: + table->error = ret; + table->quarantined = true; + return ret; +} + +/* Channel-6 CPU-load notifications are diagnostics, never completions. */ +static inline int +ane_h16_pending_dispatch(struct ane_h16_pending_table *table, const void *bytes, + size_t length, unsigned int channel, unsigned long now) +{ + const u8 *p = bytes; + + if (table->quarantined) + return -EIO; + if (p && channel == 6 && length == 0xc && + get_unaligned_le16(p + 4) == 0x0107 && !get_unaligned_le16(p + 6)) + return ANE_H16_EVENT_PROGRESS; + return ane_h16_pending_event(table, bytes, length, channel, now); +} + +#endif /* __ANE_H16_PENDING_H__ */ diff --git a/drivers/accel/ane/ane_h16_pending_test.c b/drivers/accel/ane/ane_h16_pending_test.c new file mode 100644 index 0000000000000..891342b9a7a37 --- /dev/null +++ b/drivers/accel/ane/ane_h16_pending_test.c @@ -0,0 +1,325 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +#include "ane_h16_pending.h" +#include "ane_h16_resources.h" + +static void make_event(u8 *bytes, const struct ane_h16_pending *request, u32 state) +{ + memset(bytes, 0, 0x60); + put_unaligned_le32(0x12345678, bytes); + put_unaligned_le16(ANE_H16_EVENT_REPORT, bytes + 4); + put_unaligned_le64(request->key.uuid, bytes + 8); + put_unaligned_le32(request->key.program, bytes + 0x10); + put_unaligned_le32(request->key.process, bytes + 0x14); + put_unaligned_le32(request->key.procedure, bytes + 0x18); + put_unaligned_le32(state, bytes + 0x1c); +} + +static void pending_sequence_test(struct kunit *test) +{ + struct ane_h16_pending_table table = {}; + struct ane_h16_pending a = { .key = { .program = 7, .process = 8, .procedure = 9 }, + .deadline = 100 }; + struct ane_h16_pending b = { .key = a.key, .deadline = 100 }; + u8 event[0x60], ack[8] = {}; + u32 state; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &a, 0), 0); + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &b, 0), 0); + KUNIT_EXPECT_NE(test, a.key.uuid, b.key.uuid); + /* A valid transport acknowledgment leaves both UUIDs pending. */ + put_unaligned_le16(ANE_H16_EXECUTE, ack + 4); + KUNIT_EXPECT_EQ(test, ane_fw_reply_status(0x10001, 0xca8, 0, + 0x10000, 0xca8, ANE_H16_EXECUTE, ack, true), 0); + KUNIT_EXPECT_TRUE(test, a.active); + KUNIT_EXPECT_TRUE(test, b.active); + for (state = 0; state <= 3; state += 3) { + make_event(event, &a, state); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 1), + ANE_H16_EVENT_PROGRESS); + KUNIT_EXPECT_TRUE(test, a.active); + KUNIT_EXPECT_FALSE(test, a.terminal); + } + make_event(event, &b, 1); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 2), + ANE_H16_EVENT_COMPLETE); + KUNIT_EXPECT_TRUE(test, b.terminal); + KUNIT_EXPECT_EQ(test, b.status, 0); + KUNIT_EXPECT_FALSE(test, b.active); + KUNIT_EXPECT_TRUE(test, a.active); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 3), -ENOENT); + make_event(event, &a, 1); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 4), + ANE_H16_EVENT_COMPLETE); + KUNIT_EXPECT_FALSE(test, table.quarantined); +} + +static void pending_mismatched_ids_test(struct kunit *test) +{ + unsigned int offset; + + for (offset = 0x10; offset <= 0x18; offset += 4) { + struct ane_h16_pending_table table = {}; + struct ane_h16_pending request = { .deadline = 100 }; + u8 event[0x60]; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &request, 0), 0); + make_event(event, &request, 1); + put_unaligned_le32(1, event + offset); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 1), -EPROTO); + KUNIT_EXPECT_TRUE(test, request.active); + KUNIT_EXPECT_FALSE(test, request.terminal); + KUNIT_EXPECT_TRUE(test, table.quarantined); + KUNIT_EXPECT_EQ(test, table.error, -EPROTO); + ane_h16_pending_abort(&table, &request, -EIO); + KUNIT_EXPECT_FALSE(test, request.active); + } +} + +static void pending_malformed_test(struct kunit *test) +{ + unsigned int variant; + + for (variant = 0; variant < 9; variant++) { + struct ane_h16_pending_table table = {}; + struct ane_h16_pending request = { .deadline = 100 }; + u8 event[0x60]; + unsigned int channel = 6; + size_t length = sizeof(event); + const void *bytes = event; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &request, 0), 0); + make_event(event, &request, 1); + switch (variant) { + case 0: + bytes = NULL; + break; + case 1: + length--; + break; + case 2: + length++; + break; + case 3: + channel = 7; + break; + case 4: + put_unaligned_le16(ANE_H16_EXECUTE, event + 4); + break; + case 5: + event[6] = 1; + break; + case 6: + event[7] = 1; + break; + case 7: + put_unaligned_le32(4, event + 0x1c); + break; + case 8: + event[0x30] = 2; + break; + } + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, bytes, length, channel, 1), + -EPROTO); + KUNIT_EXPECT_TRUE(test, request.active); + KUNIT_EXPECT_TRUE(test, table.quarantined); + } +} + +static void pending_routing_test(struct kunit *test) +{ + struct ane_h16_pending_table table = {}; + struct ane_h16_pending request = { .deadline = 100 }; + u8 event[0x60]; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &request, 0), 0); + make_event(event, &request, 1); + event[0x30] = 1; + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 1), -ENOMSG); + event[0x30] = 0; + put_unaligned_le64(request.key.uuid + 1, event + 8); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 1), -ENOENT); + memset(event, 0, sizeof(event)); + put_unaligned_le16(0x0107, event + 4); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0xc, 6, 1), + ANE_H16_EVENT_PROGRESS); + KUNIT_EXPECT_TRUE(test, request.active); + KUNIT_EXPECT_FALSE(test, table.quarantined); + event[7] = 1; + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0xc, 6, 1), -EPROTO); + KUNIT_EXPECT_TRUE(test, table.quarantined); +} + +static void pending_failure_test(struct kunit *test) +{ + struct ane_h16_pending_table table = {}; + struct ane_h16_pending request = { .deadline = 100 }; + struct ane_h16_pending next = { .deadline = 100 }; + u8 event[0x60]; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &request, 0), 0); + make_event(event, &request, 2); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 1), + ANE_H16_EVENT_FAILED); + KUNIT_EXPECT_FALSE(test, request.active); + KUNIT_EXPECT_TRUE(test, request.terminal); + KUNIT_EXPECT_EQ(test, request.status, -EIO); + KUNIT_EXPECT_TRUE(test, table.quarantined); + KUNIT_EXPECT_EQ(test, ane_h16_pending_insert(&table, &next, 2), -EIO); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 2), -EIO); +} + +static void pending_timeout_test(struct kunit *test) +{ + struct ane_h16_pending_table table = {}; + struct ane_h16_pending request = { .deadline = 100 }; + u8 event[0x60]; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &request, 0), 0); + make_event(event, &request, 1); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 100), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, request.status, -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, table.error, -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, request.terminal); + KUNIT_EXPECT_FALSE(test, request.active); + KUNIT_EXPECT_TRUE(test, table.quarantined); + /* Late success never makes output readable after timeout. */ + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 101), -EIO); +} + +static void pending_transport_failure_test(struct kunit *test) +{ + static const int errors[] = { -ETIMEDOUT, -EPROTO, -EREMOTEIO, -EIO }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(errors); i++) { + struct ane_h16_pending_table table = {}; + struct ane_h16_pending request = { .deadline = 100 }; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &request, 0), 0); + ane_h16_pending_abort(&table, &request, errors[i]); + KUNIT_EXPECT_FALSE(test, request.active); + KUNIT_EXPECT_FALSE(test, request.terminal); + KUNIT_EXPECT_EQ(test, request.status, errors[i]); + KUNIT_EXPECT_TRUE(test, table.quarantined); + } +} + +static void pending_capacity_test(struct kunit *test) +{ + struct ane_h16_pending_table table = {}; + struct ane_h16_pending *requests; + unsigned int i; + + requests = kunit_kcalloc(test, ANE_H16_PENDING_MAX + 1, sizeof(*requests), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, requests); + for (i = 0; i <= ANE_H16_PENDING_MAX; i++) + requests[i].deadline = 100; + for (i = 0; i < ANE_H16_PENDING_MAX; i++) { + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &requests[i], 0), 0); + KUNIT_EXPECT_EQ(test, requests[i].key.uuid, (u64)i + 1); + } + KUNIT_EXPECT_EQ(test, ane_h16_pending_insert(&table, &requests[i], 0), -ENOSPC); + ane_h16_pending_remove(&table, &requests[0]); + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &requests[i], 0), 0); + KUNIT_EXPECT_EQ(test, requests[i].key.uuid, (u64)ANE_H16_PENDING_MAX + 1); + ane_h16_pending_remove(&table, &requests[i]); + table.next_uuid = U64_MAX; + KUNIT_EXPECT_EQ(test, ane_h16_pending_insert(&table, &requests[i], 0), -EOVERFLOW); +} + +static void pending_deadline_wrap_test(struct kunit *test) +{ + struct ane_h16_pending_table table = {}; + struct ane_h16_pending request = { .deadline = 3 }; + u8 event[0x60]; + + KUNIT_ASSERT_EQ(test, ane_h16_pending_insert(&table, &request, ULONG_MAX - 4), 0); + make_event(event, &request, 1); + KUNIT_EXPECT_EQ(test, ane_h16_pending_dispatch(&table, event, 0x60, 6, 1), + ANE_H16_EVENT_COMPLETE); + request.deadline = 3; + KUNIT_EXPECT_EQ(test, ane_h16_pending_insert(&table, &request, 3), -EINVAL); +} + +static void resources_test(struct kunit *test) +{ + struct ane_h16_hwx hwx = { .surface_count = 2 }; + struct ane_h16_resource resources[2] = {}; + unsigned int i, variant; + + for (i = 0; i < 2; i++) { + hwx.surfaces[i].section.vm = 0x30000000 + i * SZ_16K; + hwx.surfaces[i].section.size = SZ_16K; + hwx.surfaces[i].allocation = SZ_16K; + hwx.surfaces[i].span = 256; + hwx.surfaces[i].direction = i + 1; + resources[i].hwx_vm = hwx.surfaces[i].section.vm; + resources[i].permissions = i + 1; + resources[i].buffer = (struct ane_h16_execute_buffer) { + .index = i, .class = i, .mapping_dva = 0x100000000ULL + i * SZ_16K, + .mapping_size = SZ_16K, .size = 256, + }; + } + KUNIT_EXPECT_EQ(test, ane_h16_resources_validate(&hwx, resources, 2), 0); + KUNIT_EXPECT_EQ(test, ane_h16_resources_validate(&hwx, resources, 1), -EINVAL); + for (variant = 0; variant < 9; variant++) { + struct ane_h16_resource bad[2]; + + memcpy(bad, resources, sizeof(bad)); + switch (variant) { + case 0: + bad[0].permissions = 2; + break; + case 1: + bad[0].hwx_vm++; + break; + case 2: + bad[0].buffer.class = 8; + break; + case 3: + bad[0].buffer.size++; + break; + case 4: + bad[0].buffer.offset = 1; + break; + case 5: + bad[0].buffer.mapping_dva = U64_MAX - SZ_16K + 1; + break; + case 6: + bad[1].buffer.index = bad[0].buffer.index; + break; + case 7: + bad[1].buffer.mapping_dva = bad[0].buffer.mapping_dva; + break; + case 8: + bad[0].buffer.mapping_size--; + break; + } + KUNIT_EXPECT_EQ(test, ane_h16_resources_validate(&hwx, bad, 2), -EINVAL); + } +} + +static struct kunit_case pending_cases[] = { + KUNIT_CASE(pending_sequence_test), + KUNIT_CASE(pending_mismatched_ids_test), + KUNIT_CASE(pending_malformed_test), + KUNIT_CASE(pending_routing_test), + KUNIT_CASE(pending_failure_test), + KUNIT_CASE(pending_timeout_test), + KUNIT_CASE(pending_transport_failure_test), + KUNIT_CASE(pending_capacity_test), + KUNIT_CASE(pending_deadline_wrap_test), + KUNIT_CASE(resources_test), + {} +}; + +static struct kunit_suite pending_suite = { + .name = "ane-h16-pending", + .test_cases = pending_cases, +}; + +kunit_test_suite(pending_suite); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_preload.c b/drivers/accel/ane/ane_h16_preload.c new file mode 100644 index 0000000000000..e7103b14e3a71 --- /dev/null +++ b/drivers/accel/ane/ane_h16_preload.c @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include + +#include "ane_h16_preload.h" + +/* Ordered aether patchbay framing. Offsets are relative to DATA, whose + * original VM base is 0xc0000. Only explicitly mutable value bytes normalize. + */ +static const struct { + char tag[4]; + u32 value; + u8 width; + bool mutable; +} ane_h16_patchbay[] = { + { "BECA", 0x5a20, 8, true }, + { "SECA", 0x5a30, 8, false }, + { "GKTS", 0x5a40, 8, true }, + { "otcd", 0x5a50, 8, false }, + { "oscd", 0x5a60, 8, false }, + { "oecd", 0x5a70, 8, false }, + { "DILS", 0x5a80, 8, true }, + { "SRSA", 0x5a90, 8, false }, + { "GFCM", 0x5aa0, 8, false }, + { "SSSC", 0x5ab0, 8, true }, + { "qF8v", 0x5ac0, 4, true }, + { "LRSD", 0x5acc, 1, false }, + { "SVSD", 0x5ad5, 8, false }, + { "LCSD", 0x5ae5, 8, false }, + { "ZSTR", 0x5af5, 4, false }, + { "BPTP", 0x5b01, 8, false }, + { "TNGI", 0x5b11, 1, false }, + { "oeNS", 0x5b1a, 1, false }, + { "SEBC", 0x5b23, 8, false }, + { "ECAP", 0x5b33, 8, true }, + { "BVTP", 0x5b43, 8, true }, + { "sP1T", 0x5b53, 8, true }, + { "BtpG", 0x5b63, 8, true }, + { "StpG", 0x5b73, 8, false }, + { "BlpP", 0x5b83, 8, true }, + { "SPTP", 0x5b93, 8, false }, + { "SZSD", 0x5ba3, 8, false }, + { "LZSD", 0x5bb3, 8, false }, + { "S2xG", 0x5bc3, 8, true }, + { "SNUT", 0x5bd3, 8, true }, + { "ZNUT", 0x5be3, 4, false }, + { "OTTR", 0x5bef, 8, true }, + { "LLTR", 0x5bff, 1, false }, + { "_COS", 0x5c08, 4, true }, + { "RCOS", 0x5c14, 4, true }, + { "dApC", 0x5c20, 8, true }, + { "dArW", 0x5c30, 8, true }, + { "fVED", 0x5c40, 1, true }, + { "GLFp", 0x5c49, 8, true }, + { "ABOI", 0x5c59, 8, false }, + { "ZSOI", 0x5c69, 4, false }, + { "ARcM", 0x5c75, 4, true }, +}; + +/* + * Known resident images. 25F84 (macOS 26.5.2) has the 26A428 framing and + * tunables interval moved by +0x3f80 in DATA. + */ +const struct ane_h16_preload_layout ane_h16_preload_layouts[ANE_H16_PRELOAD_BUILDS] = { + { + .shift = 0, + .digest = { + 0x1f, 0x86, 0x5e, 0xd0, 0x4c, 0x4c, 0x38, 0xf6, + 0xfd, 0xcc, 0x45, 0x43, 0xa8, 0x81, 0x4f, 0x81, + 0x8d, 0x3c, 0xea, 0x58, 0x3d, 0xe6, 0x4d, 0x22, + 0xff, 0xe9, 0x6e, 0x3a, 0x93, 0xca, 0x46, 0x97, + }, + }, + { + /* Live J616c image, rg-ane-00-preflight: _rtk_patchbay DATA+0x9998, + * _rtk_tunables DATA+0x1bc00; iBoot fills TEXT ce_env, hashed as is. + */ + .shift = 0x3f80, + .digest = { + 0x17, 0xc3, 0xef, 0x19, 0x6b, 0x89, 0xe4, 0xf5, + 0x94, 0x9a, 0xc7, 0x77, 0x76, 0x0e, 0x5b, 0x05, + 0x80, 0x1f, 0xf5, 0xaa, 0x3b, 0x9f, 0x93, 0x77, + 0x57, 0xfb, 0xd4, 0xee, 0xf5, 0x6b, 0x00, 0x45, + }, + }, +}; +EXPORT_SYMBOL_GPL(ane_h16_preload_layouts); + +int ane_h16_preload_digest_layout(const struct ane_h16_preload_layout *layout, + const void *text, size_t text_size, + const void *data, size_t data_size, + u8 digest[SHA256_DIGEST_SIZE]) +{ + static const u8 zero[64]; + const u8 *bytes = data; + struct sha256_ctx ctx; + size_t cursor = 0, remaining; + unsigned int i; + + if (!layout || !text || !data || !digest || text_size != ANE_H16_PRELOAD_TEXT_SIZE || + data_size != ANE_H16_PRELOAD_DATA_SIZE) + return -EINVAL; + /* Validate all framing before producing a digest. Odd offsets are valid. */ + for (i = 0; i < ARRAY_SIZE(ane_h16_patchbay); i++) { + u32 value = ane_h16_patchbay[i].value + layout->shift; + + if (memcmp(bytes + value - 8, ane_h16_patchbay[i].tag, 4) || + get_unaligned_le32(bytes + value - 4) != ane_h16_patchbay[i].width) + return -ENOEXEC; + } + sha256_init(&ctx); + sha256_update(&ctx, text, text_size); + for (i = 0; i < ARRAY_SIZE(ane_h16_patchbay); i++) { + u32 value = ane_h16_patchbay[i].value + layout->shift; + + if (!ane_h16_patchbay[i].mutable) + continue; + sha256_update(&ctx, bytes + cursor, value - cursor); + sha256_update(&ctx, zero, ane_h16_patchbay[i].width); + cursor = value + ane_h16_patchbay[i].width; + } + sha256_update(&ctx, bytes + cursor, 0x17c80 + layout->shift - cursor); + for (remaining = 0x6a0; remaining; ) { + size_t length = min(remaining, sizeof(zero)); + + sha256_update(&ctx, zero, length); + remaining -= length; + } + cursor = 0x18320 + layout->shift; + sha256_update(&ctx, bytes + cursor, data_size - cursor); + sha256_final(&ctx, digest); + return 0; +} +EXPORT_SYMBOL_GPL(ane_h16_preload_digest_layout); + +int ane_h16_preload_digest(const void *text, size_t text_size, + const void *data, size_t data_size, + u8 digest[SHA256_DIGEST_SIZE]) +{ + return ane_h16_preload_digest_layout(&ane_h16_preload_layouts[0], text, text_size, + data, data_size, digest); +} +EXPORT_SYMBOL_GPL(ane_h16_preload_digest); + +/* Index of the known build whose identity the snapshots match, or -ENOEXEC. */ +int ane_h16_preload_identify(const void *text, size_t text_size, + const void *data, size_t data_size) +{ + u8 digest[SHA256_DIGEST_SIZE]; + unsigned int i; + int ret = -ENOEXEC; + + for (i = 0; i < ANE_H16_PRELOAD_BUILDS; i++) { + const struct ane_h16_preload_layout *l = &ane_h16_preload_layouts[i]; + int r = ane_h16_preload_digest_layout(l, text, text_size, data, data_size, + digest); + + if (r == -EINVAL) + return r; + if (!r && !l->unknown && !memcmp(digest, l->digest, sizeof(digest))) + return i; + } + return ret; +} +EXPORT_SYMBOL_GPL(ane_h16_preload_identify); + +int ane_h16_preload_validate(const void *text, size_t text_size, + const void *data, size_t data_size) +{ + const u8 *expected = ane_h16_preload_layouts[0].digest; + u8 digest[SHA256_DIGEST_SIZE]; + int ret; + + ret = ane_h16_preload_digest(text, text_size, data, data_size, digest); + if (ret) + return ret; + return memcmp(digest, expected, SHA256_DIGEST_SIZE) ? -ENOEXEC : 0; +} +EXPORT_SYMBOL_GPL(ane_h16_preload_validate); + +MODULE_DESCRIPTION("H16 resident firmware identity validation"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_preload.h b/drivers/accel/ane/ane_h16_preload.h new file mode 100644 index 0000000000000..9bcc5645be54f --- /dev/null +++ b/drivers/accel/ane/ane_h16_preload.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_PRELOAD_H__ +#define __ANE_H16_PRELOAD_H__ + +#include + +#define ANE_H16_PRELOAD_TEXT_SIZE 0xc0000 +#define ANE_H16_PRELOAD_DATA_SIZE 0x2ac000 +/* 0: H16 27.0 26A428, 1: H16 26.5.2 25F84 */ +#define ANE_H16_PRELOAD_BUILDS 2 + +/* A build's DATA framing offset (relative to 26A428) and its identity digest. */ +struct ane_h16_preload_layout { + u32 shift; + bool unknown; + u8 digest[SHA256_DIGEST_SIZE]; +}; + +extern const struct ane_h16_preload_layout ane_h16_preload_layouts[ANE_H16_PRELOAD_BUILDS]; + +/* Inputs are stable, host-owned snapshots of the reserved live pages. + * Digest computation is not validation against the pinned firmware identity. + * Neither function changes the snapshots or the live bootloader values. + */ +int ane_h16_preload_digest(const void *text, size_t text_size, + const void *data, size_t data_size, + u8 digest[SHA256_DIGEST_SIZE]); +int ane_h16_preload_validate(const void *text, size_t text_size, + const void *data, size_t data_size); +int ane_h16_preload_digest_layout(const struct ane_h16_preload_layout *layout, + const void *text, size_t text_size, + const void *data, size_t data_size, + u8 digest[SHA256_DIGEST_SIZE]); +int ane_h16_preload_identify(const void *text, size_t text_size, + const void *data, size_t data_size); + +#endif /* __ANE_H16_PRELOAD_H__ */ diff --git a/drivers/accel/ane/ane_h16_preload_test.c b/drivers/accel/ane/ane_h16_preload_test.c new file mode 100644 index 0000000000000..acc17c03b7a02 --- /dev/null +++ b/drivers/accel/ane/ane_h16_preload_test.c @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include +#include + +#include "ane_h16_preload.h" + +/* Synthetic framing only, with no firmware bytes. Walk records independently + * from their widths rather than sharing the production offset manifest. + */ +static const struct { + char tag[4]; + u8 width; + bool mutable; +} records[] = { + { "BECA", 8, true }, { "SECA", 8, false }, { "GKTS", 8, true }, + { "otcd", 8, false }, { "oscd", 8, false }, { "oecd", 8, false }, + { "DILS", 8, true }, { "SRSA", 8, false }, { "GFCM", 8, false }, + { "SSSC", 8, true }, { "qF8v", 4, true }, { "LRSD", 1, false }, + { "SVSD", 8, false }, { "LCSD", 8, false }, { "ZSTR", 4, false }, + { "BPTP", 8, false }, { "TNGI", 1, false }, { "oeNS", 1, false }, + { "SEBC", 8, false }, { "ECAP", 8, true }, { "BVTP", 8, true }, + { "sP1T", 8, true }, { "BtpG", 8, true }, { "StpG", 8, false }, + { "BlpP", 8, true }, { "SPTP", 8, false }, { "SZSD", 8, false }, + { "LZSD", 8, false }, { "S2xG", 8, true }, { "SNUT", 8, true }, + { "ZNUT", 4, false }, { "OTTR", 8, true }, { "LLTR", 1, false }, + { "_COS", 4, true }, { "RCOS", 4, true }, { "dApC", 8, true }, + { "dArW", 8, true }, { "fVED", 1, true }, { "GLFp", 8, true }, + { "ABOI", 8, false }, { "ZSOI", 4, false }, { "ARcM", 4, true }, +}; + +struct preload_fixture { + u8 *text; + u8 *data; +}; + +static void preload_free(void *allocation) +{ + kvfree(allocation); +} + +static int preload_fixture_init(struct kunit *test) +{ + struct preload_fixture *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + size_t pos = 0x5a18; + unsigned int i; + + if (!f) + return -ENOMEM; + test->priv = f; + f->text = kvmalloc(ANE_H16_PRELOAD_TEXT_SIZE, GFP_KERNEL); + if (!f->text) + return -ENOMEM; + if (kunit_add_action_or_reset(test, preload_free, f->text)) + return -ENOMEM; + f->data = kvmalloc(ANE_H16_PRELOAD_DATA_SIZE, GFP_KERNEL); + if (!f->data) + return -ENOMEM; + if (kunit_add_action_or_reset(test, preload_free, f->data)) + return -ENOMEM; + memset(f->text, 0x5a, ANE_H16_PRELOAD_TEXT_SIZE); + memset(f->data, 0xa5, ANE_H16_PRELOAD_DATA_SIZE); + for (i = 0; i < ARRAY_SIZE(records); i++) { + memcpy(f->data + pos, records[i].tag, 4); + put_unaligned_le32(records[i].width, f->data + pos + 4); + pos += 8 + records[i].width; + } + return pos == 0x5c79 ? 0 : -EINVAL; +} + +static int preload_digest(struct preload_fixture *f, u8 *digest) +{ + return ane_h16_preload_digest(f->text, ANE_H16_PRELOAD_TEXT_SIZE, + f->data, ANE_H16_PRELOAD_DATA_SIZE, digest); +} + +static void preload_identity_test(struct kunit *test) +{ + /* Independently normalized synthetic bytes, SHA-256 from Python hashlib. */ + static const u8 expected[SHA256_DIGEST_SIZE] = { + 0x67, 0xb5, 0x33, 0xc6, 0x0b, 0x11, 0x03, 0x2b, + 0x3e, 0x75, 0x27, 0x7b, 0x2d, 0xe1, 0x82, 0xc6, + 0xca, 0x53, 0xa7, 0x18, 0x1f, 0xfc, 0xcc, 0xfe, + 0xd3, 0xb5, 0xe8, 0x22, 0xaa, 0x12, 0xd0, 0xbb, + }; + struct preload_fixture *f = test->priv; + u8 digest[SHA256_DIGEST_SIZE]; + int ret; + + KUNIT_EXPECT_EQ(test, preload_digest(f, digest), 0); + KUNIT_EXPECT_MEMEQ(test, digest, expected, sizeof(digest)); + /* Correct framing alone cannot authenticate a synthetic image. */ + ret = ane_h16_preload_validate(f->text, ANE_H16_PRELOAD_TEXT_SIZE, + f->data, ANE_H16_PRELOAD_DATA_SIZE); + KUNIT_EXPECT_EQ(test, ret, -ENOEXEC); +} + +static void preload_mutable_test(struct kunit *test) +{ + struct preload_fixture *f = test->priv; + u8 baseline[SHA256_DIGEST_SIZE], digest[SHA256_DIGEST_SIZE]; + size_t pos = 0x5a18; + unsigned int i, mutable = 0; + + KUNIT_ASSERT_EQ(test, preload_digest(f, baseline), 0); + for (i = 0; i < ARRAY_SIZE(records); i++) { + if (records[i].mutable) { + memset(f->data + pos + 8, 0x3c, records[i].width); + KUNIT_ASSERT_EQ(test, preload_digest(f, digest), 0); + KUNIT_EXPECT_MEMEQ(test, digest, baseline, sizeof(digest)); + mutable++; + } + pos += 8 + records[i].width; + } + KUNIT_EXPECT_EQ(test, mutable, 20); + memset(f->data + 0x17c80, 0x7e, 0x6a0); + KUNIT_ASSERT_EQ(test, preload_digest(f, digest), 0); + KUNIT_EXPECT_MEMEQ(test, digest, baseline, sizeof(digest)); + /* Validation and normalization never erase the accepted boot data. */ + KUNIT_EXPECT_EQ(test, f->data[0x5a20], 0x3c); + KUNIT_EXPECT_EQ(test, f->data[0x17c80], 0x7e); + KUNIT_EXPECT_EQ(test, f->data[0x1831f], 0x7e); +} + +static void preload_framing_test(struct kunit *test) +{ + struct preload_fixture *f = test->priv; + u8 digest[SHA256_DIGEST_SIZE]; + size_t pos = 0x5a18; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(records); i++) { + f->data[pos] ^= 1; + KUNIT_EXPECT_EQ(test, preload_digest(f, digest), -ENOEXEC); + f->data[pos] ^= 1; + put_unaligned_le32(U32_MAX, f->data + pos + 4); + KUNIT_EXPECT_EQ(test, preload_digest(f, digest), -ENOEXEC); + put_unaligned_le32(records[i].width, f->data + pos + 4); + pos += 8 + records[i].width; + } + KUNIT_EXPECT_EQ(test, preload_digest(f, digest), 0); +} + +static void preload_immutable_test(struct kunit *test) +{ + static const u32 boundaries[] = { + 0, 0x5a17, 0x5c79, 0x17c7f, 0x18320, 0xb8000, 0x2abfff, + }; + struct preload_fixture *f = test->priv; + u8 baseline[SHA256_DIGEST_SIZE], digest[SHA256_DIGEST_SIZE]; + size_t pos = 0x5a18; + unsigned int i; + + KUNIT_ASSERT_EQ(test, preload_digest(f, baseline), 0); + for (i = 0; i < ARRAY_SIZE(records); i++) { + if (!records[i].mutable) { + f->data[pos + 8] ^= 1; + KUNIT_ASSERT_EQ(test, preload_digest(f, digest), 0); + KUNIT_EXPECT_NE(test, memcmp(digest, baseline, sizeof(digest)), 0); + f->data[pos + 8] ^= 1; + } + pos += 8 + records[i].width; + } + for (i = 0; i < ARRAY_SIZE(boundaries); i++) { + f->data[boundaries[i]] ^= 1; + KUNIT_ASSERT_EQ(test, preload_digest(f, digest), 0); + KUNIT_EXPECT_NE(test, memcmp(digest, baseline, sizeof(digest)), 0); + f->data[boundaries[i]] ^= 1; + } + f->text[ANE_H16_PRELOAD_TEXT_SIZE - 1] ^= 1; + KUNIT_ASSERT_EQ(test, preload_digest(f, digest), 0); + KUNIT_EXPECT_NE(test, memcmp(digest, baseline, sizeof(digest)), 0); +} + +static void preload_bounds_test(struct kunit *test) +{ + struct preload_fixture *f = test->priv; + u8 digest[SHA256_DIGEST_SIZE]; + int delta, ret; + + for (delta = -1; delta <= 1; delta += 2) { + ret = ane_h16_preload_digest(f->text, ANE_H16_PRELOAD_TEXT_SIZE + delta, + f->data, ANE_H16_PRELOAD_DATA_SIZE, digest); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_h16_preload_digest(f->text, ANE_H16_PRELOAD_TEXT_SIZE, + f->data, ANE_H16_PRELOAD_DATA_SIZE + delta, digest); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + } + ret = ane_h16_preload_digest(NULL, ANE_H16_PRELOAD_TEXT_SIZE, + f->data, ANE_H16_PRELOAD_DATA_SIZE, digest); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_h16_preload_digest(f->text, ANE_H16_PRELOAD_TEXT_SIZE, + NULL, ANE_H16_PRELOAD_DATA_SIZE, digest); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = ane_h16_preload_digest(f->text, ANE_H16_PRELOAD_TEXT_SIZE, + f->data, ANE_H16_PRELOAD_DATA_SIZE, NULL); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); +} + +/* 25F84 frames the same records 0x3f80 further into DATA. */ +static void preload_shifted_test(struct kunit *test) +{ + struct preload_fixture *f = test->priv; + u8 digest[SHA256_DIGEST_SIZE]; + size_t pos = 0x5a18; + + KUNIT_EXPECT_EQ(test, ane_h16_preload_digest_layout(&ane_h16_preload_layouts[1], + f->text, ANE_H16_PRELOAD_TEXT_SIZE, f->data, ANE_H16_PRELOAD_DATA_SIZE, + digest), -ENOEXEC); + memmove(f->data + pos + 0x3f80, f->data + pos, 0x5c79 - pos); + memset(f->data + pos, 0xa5, 0x3f80); + KUNIT_EXPECT_EQ(test, ane_h16_preload_digest_layout(&ane_h16_preload_layouts[1], + f->text, ANE_H16_PRELOAD_TEXT_SIZE, f->data, ANE_H16_PRELOAD_DATA_SIZE, + digest), 0); + KUNIT_EXPECT_EQ(test, ane_h16_preload_digest(f->text, ANE_H16_PRELOAD_TEXT_SIZE, + f->data, ANE_H16_PRELOAD_DATA_SIZE, digest), -ENOEXEC); + /* Framing alone identifies nothing. */ + KUNIT_EXPECT_EQ(test, ane_h16_preload_identify(f->text, ANE_H16_PRELOAD_TEXT_SIZE, + f->data, ANE_H16_PRELOAD_DATA_SIZE), -ENOEXEC); +} + +static struct kunit_case preload_cases[] = { + KUNIT_CASE(preload_shifted_test), + KUNIT_CASE(preload_identity_test), + KUNIT_CASE(preload_mutable_test), + KUNIT_CASE(preload_framing_test), + KUNIT_CASE(preload_immutable_test), + KUNIT_CASE(preload_bounds_test), + {} +}; + +static struct kunit_suite preload_suite = { + .name = "ane-h16-preload", + .init = preload_fixture_init, + .test_cases = preload_cases, +}; + +kunit_test_suite(preload_suite); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_protocol.h b/drivers/accel/ane/ane_h16_protocol.h new file mode 100644 index 0000000000000..a3ef6a9c25ae8 --- /dev/null +++ b/drivers/accel/ane/ane_h16_protocol.h @@ -0,0 +1,78 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_PROTOCOL_H__ +#define __ANE_H16_PROTOCOL_H__ + +#include "ane_fw_protocol.h" + +/* Derived field facts from H16/macOS 27.0, 2026-10-31. No payload bytes. */ +enum ane_h16_command { + ANE_H16_LOAD_PROGRAM = 0x0200, + ANE_H16_UNLOAD_PROGRAM = 0x0201, + ANE_H16_CREATE_PROCESS = 0x0202, + ANE_H16_TERMINATE_PROCESS = 0x0203, + ANE_H16_EXECUTE = 0x020c, + ANE_H16_POWER_GATE = 0x002d, + ANE_H16_EVENT_REPORT = 0x0300, +}; + +struct ane_h16_command_info { + u16 id; + u16 min_size; + u16 max_size; + u8 size_step; + u8 channel; + bool from_firmware; +}; + +static inline const struct ane_h16_command_info *ane_h16_command_info(u16 id) +{ + static const struct ane_h16_command_info commands[] = { + { ANE_H16_LOAD_PROGRAM, 0x1c0, 0x1c0, 1, 1, false }, + { ANE_H16_UNLOAD_PROGRAM, 0xc, 0xc, 1, 1, false }, + { ANE_H16_CREATE_PROCESS, 0x258, 0x258, 1, 1, false }, + { ANE_H16_TERMINATE_PROCESS, 0x10, 0x10, 1, 1, false }, + { ANE_H16_EXECUTE, 0xca8, 0xcd8, 0x18, 7, false }, + { ANE_H16_POWER_GATE, 0xc, 0xc, 1, 7, false }, + { ANE_H16_EVENT_REPORT, 0x60, 0x60, 1, 6, true }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(commands); i++) + if (commands[i].id == id) + return &commands[i]; + return NULL; +} + +/* Validate the runtime wire shape, never infer a body from the H14 ABI. */ +static inline int +ane_h16_command_prepare(void *command, size_t length, u16 id, unsigned int channel) +{ + const struct ane_h16_command_info *info = ane_h16_command_info(id); + + if (!info || info->from_firmware) + return -EOPNOTSUPP; + if (!command || channel != info->channel || length < info->min_size || + length > info->max_size || (length - info->min_size) % info->size_step) + return -EINVAL; + if (id == ANE_H16_POWER_GATE && + get_unaligned_le32((u8 *)command + 8) > 1) + return -EINVAL; + ane_fw_command_header(command, id, true); + return 0; +} + +/* The first word selects report slots; rolling words are also valid. */ +static inline int +ane_h16_event_report_status(const void *event, size_t length, unsigned int channel) +{ + const u8 *p = event; + const struct ane_h16_command_info *info = + ane_h16_command_info(ANE_H16_EVENT_REPORT); + + if (!p || channel != info->channel || length != info->min_size || + get_unaligned_le16(p + 4) != info->id || get_unaligned_le16(p + 6)) + return -EPROTO; + return 0; +} + +#endif /* __ANE_H16_PROTOCOL_H__ */ diff --git a/drivers/accel/ane/ane_h16_resources.h b/drivers/accel/ane/ane_h16_resources.h new file mode 100644 index 0000000000000..637237e72b134 --- /dev/null +++ b/drivers/accel/ane/ane_h16_resources.h @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_RESOURCES_H__ +#define __ANE_H16_RESOURCES_H__ + +#include "ane_h16_execute.h" +#include "ane_h16_hwx.h" + +/* Created only by the backend matching a validated HWX with reviewed program + * resource bindings. No userspace field may supply this authority. Each + * mapping is private, coherent DMA memory with no userspace alias, retained + * for process lifetime. + */ +struct ane_h16_resource { + u64 hwx_vm; + u32 permissions; + struct ane_h16_execute_buffer buffer; +}; + +static inline int +ane_h16_resources_validate(const struct ane_h16_hwx *hwx, + const struct ane_h16_resource *resources, unsigned int count) +{ + unsigned int i, j; + + if (!hwx || !resources || count < 2 || count > ANE_H16_SURFACES || + count != hwx->surface_count) + return -EINVAL; + for (i = 0; i < count; i++) { + const struct ane_h16_hwx_surface *s = &hwx->surfaces[i]; + const struct ane_h16_resource *r = &resources[i]; + const struct ane_h16_execute_buffer *b = &r->buffer; + u64 end; + + /* Only the established input/output classes are executable. */ + if (s->direction < 1 || s->direction > 2 || + r->hwx_vm != s->section.vm || r->permissions != s->direction || + b->class != s->direction - 1 || !s->span || + s->span > s->section.size || s->section.size > s->allocation || + !IS_ALIGNED(s->allocation, SZ_16K) || + b->size != s->span || b->offset || !b->mapping_dva || + !IS_ALIGNED(b->mapping_dva, SZ_16K) || + b->mapping_size != s->allocation || b->size > b->mapping_size || + check_add_overflow(b->mapping_dva, b->mapping_size, &end)) + return -EINVAL; + for (j = 0; j < i; j++) { + const struct ane_h16_execute_buffer *a = &resources[j].buffer; + + if (a->index == b->index || + (b->mapping_dva < a->mapping_dva + a->mapping_size && + a->mapping_dva < end)) + return -EINVAL; + } + } + return 0; +} + +#endif /* __ANE_H16_RESOURCES_H__ */ diff --git a/drivers/accel/ane/ane_h16_tasks.h b/drivers/accel/ane/ane_h16_tasks.h new file mode 100644 index 0000000000000..c270d748fbf0d --- /dev/null +++ b/drivers/accel/ane/ane_h16_tasks.h @@ -0,0 +1,147 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_H16_TASKS_H__ +#define __ANE_H16_TASKS_H__ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define ANE_H16_TASK_MAX 0x60000 + +/* Byte addresses in the source-backed H16 register image, exclusive ends. */ +static inline bool ane_h16_register_valid(u32 word) +{ + static const struct { + u32 start; + u32 end; + } blocks[] = { + { 0x0000, 0x005c }, { 0x4100, 0x41a4 }, { 0x44d0, 0x44d4 }, + { 0x4500, 0x453c }, { 0x4900, 0x4930 }, { 0x4d00, 0x4e44 }, + { 0x5100, 0x5154 }, { 0x5500, 0x5620 }, { 0x5900, 0x5930 }, + }; + u32 addr = word * 4; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(blocks); i++) + if (addr >= blocks[i].start && addr < blocks[i].end) + return true; + return false; +} + +/* + * H16 streams begin with little-endian u32 1 and twelve reserved zero bytes. + * This structural gate does not replace container/tensor/aperture validation. + */ +static inline int +ane_h16_task_stream_validate(const void *text, size_t size, u32 expected_tasks) +{ + const u8 *p = text; + size_t pos = 16; + u32 tasks = 0; + + if (!p || !expected_tasks || size < 16 || size > ANE_H16_TASK_MAX || + (size & 3) || get_unaligned_le32(p) != 1 || + memchr_inv(p + 4, 0, 12)) + return -ENOEXEC; + while (pos < size) { + u32 words, header_words = 9; + size_t end, padded, 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; + 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; + while (rec < end) { + u32 h = get_unaligned_le32(p + rec); + u32 base = h & 0x7fff; + u32 mask = (h >> 15) & 0xffff; + u32 count, 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)) + return -ENOEXEC; + if (h & BIT(31)) { + for (i = 0; i < 16; i++) + if ((mask & BIT(i)) && + !ane_h16_register_valid(base + i + 1)) + return -ENOEXEC; + } else { + for (i = 1; i < count; i++) + if (!ane_h16_register_valid(base + i)) + return -ENOEXEC; + } + rec += count * 4; + } + padded = ALIGN(end, 16); + if (padded > size || memchr_inv(p + end, 0, padded - end)) + return -ENOEXEC; + pos = padded; + if (++tasks > expected_tasks) + return -ENOEXEC; + } + return tasks == expected_tasks ? 0 : -ENOEXEC; +} + +/* Section ordinal is supplied only by the validated complete section table. + * This checks Mach-O relocation entries, not the distinct aperture records. + */ +static inline int +ane_h16_relocations_validate(const void *text, size_t text_size, + const void *relocs, size_t count, u32 ordinal, + u64 kernel_vm, u64 kernel_size, + unsigned long *seen, size_t seen_bits) +{ + const u8 *r = relocs; + u64 kernel_end; + size_t i; + + if (!count) + return 0; + if (!text || !relocs || !seen || !ordinal || ordinal > 0xffffff || + !kernel_size || text_size > ANE_H16_TASK_MAX || (text_size & 3) || + count > text_size / 4 || seen_bits < text_size / 4 || + check_add_overflow(kernel_vm, kernel_size, &kernel_end)) + return -ENOEXEC; + bitmap_zero(seen, text_size / 4); + for (i = 0; i < count; i++) { + u32 patch = get_unaligned_le32(r + i * 8); + u32 info = get_unaligned_le32(r + i * 8 + 4); + u32 addend; + u64 target; + + if ((patch & 3) || text_size < 4 || patch > text_size - 4 || + (info >> 24) != 7 || (info & 0xffffff) != ordinal || + test_and_set_bit(patch / 4, seen)) + return -ENOEXEC; + addend = get_unaligned_le32((const u8 *)text + patch); + if (addend >= kernel_size || + check_add_overflow(kernel_vm, (u64)addend, &target) || + target >= kernel_end) + return -ENOEXEC; + } + return 0; +} + +#endif /* __ANE_H16_TASKS_H__ */ diff --git a/drivers/accel/ane/ane_h16_tasks_test.c b/drivers/accel/ane/ane_h16_tasks_test.c new file mode 100644 index 0000000000000..f11aab0119c10 --- /dev/null +++ b/drivers/accel/ane/ane_h16_tasks_test.c @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +#include "ane_h16_tasks.h" + +static void ane_h16_dense_task_test(struct kunit *test) +{ + u8 text[64] = {}; + + put_unaligned_le32(1, text); + /* Nine header words, one dense record and its one-word payload. */ + put_unaligned_le32(11 << 16, text + 16); + put_unaligned_le32(0x4100 / 4, text + 16 + 9 * 4); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), 0); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 2), -ENOEXEC); + put_unaligned_le32(0x41a4 / 4, text + 16 + 9 * 4); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); + put_unaligned_le32(0x419c / 4 | (1 << 15), text + 16 + 9 * 4); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); + put_unaligned_le32(0x4100 / 4, text + 16 + 9 * 4); + text[63] = 1; + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); +} + +static void ane_h16_scatter_task_test(struct kunit *test) +{ + u8 text[64] = {}; + + put_unaligned_le32(1, text); + put_unaligned_le32(12 << 16, text + 16); + put_unaligned_le32(BIT(31) | BIT(15) | 21, text + 16 + 9 * 4); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), 0); + /* The second scatter write would leave the common register block. */ + put_unaligned_le32(BIT(31) | BIT(15) | 22, text + 16 + 9 * 4); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); +} + +static void ane_h16_extra_header_test(struct kunit *test) +{ + u8 text[64] = {}; + + put_unaligned_le32(1, text); + put_unaligned_le32(10 << 16, text + 16); + put_unaligned_le32(3, text + 16 + 8 * 4); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), 0); + put_unaligned_le32(9 << 16, text + 16); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); + KUNIT_EXPECT_FALSE(test, ane_h16_register_valid(0x44d4 / 4)); + KUNIT_EXPECT_TRUE(test, ane_h16_register_valid(0x44d0 / 4)); + KUNIT_EXPECT_FALSE(test, ane_h16_register_valid(0x5930 / 4)); +} + +static void ane_h16_prologue_test(struct kunit *test) +{ + u8 text[64] = {}; + unsigned int i; + + put_unaligned_le32(11 << 16, text + 16); + put_unaligned_le32(0x4100 / 4, text + 16 + 9 * 4); + /* A zero prologue is not the H16 stream marker. */ + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); + put_unaligned_le32(1, text); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), 0); + put_unaligned_le32(2, text); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); + put_unaligned_le32(0x01000000, text); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); + put_unaligned_le32(1, text); + for (i = 4; i < 16; i++) { + text[i] = 1; + KUNIT_EXPECT_EQ(test, + ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); + text[i] = 0; + } + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, 15, 1), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, 16, 1), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(NULL, sizeof(text), 1), -ENOEXEC); +} + +static void ane_h16_relocation_test(struct kunit *test) +{ + u8 text[64] = {}; + u8 relocs[16] = {}; + DECLARE_BITMAP(seen, 16); + int ret; + + put_unaligned_le32(4, relocs); + put_unaligned_le32(0x07000003, relocs + 4); + put_unaligned_le32(0x20, text + 4); + ret = ane_h16_relocations_validate(text, sizeof(text), + relocs, 1, 3, 0x30020000, 0x100, seen, 16); + KUNIT_EXPECT_EQ(test, ret, 0); + memcpy(relocs + 8, relocs, 8); + ret = ane_h16_relocations_validate(text, sizeof(text), + relocs, 2, 3, 0x30020000, 0x100, seen, 16); + KUNIT_EXPECT_EQ(test, ret, -ENOEXEC); + ret = ane_h16_relocations_validate(text, sizeof(text), + relocs, 1, 4, 0x30020000, 0x100, seen, 16); + KUNIT_EXPECT_EQ(test, ret, -ENOEXEC); + put_unaligned_le32(0x0f000003, relocs + 4); + ret = ane_h16_relocations_validate(text, sizeof(text), + relocs, 1, 3, 0x30020000, 0x100, seen, 16); + KUNIT_EXPECT_EQ(test, ret, -ENOEXEC); + put_unaligned_le32(0x07000003, relocs + 4); + put_unaligned_le32(0x100, text + 4); + ret = ane_h16_relocations_validate(text, sizeof(text), + relocs, 1, 3, 0x30020000, 0x100, seen, 16); + KUNIT_EXPECT_EQ(test, ret, -ENOEXEC); + ret = ane_h16_relocations_validate(text, sizeof(text), + relocs, 1, 3, U64_MAX - 8, 0x100, seen, 16); + KUNIT_EXPECT_EQ(test, ret, -ENOEXEC); + ret = ane_h16_relocations_validate(text, sizeof(text), + relocs, 1, 3, 0x30020000, 0, seen, 16); + KUNIT_EXPECT_EQ(test, ret, -ENOEXEC); +} + +static struct kunit_case ane_h16_task_cases[] = { + KUNIT_CASE(ane_h16_prologue_test), + KUNIT_CASE(ane_h16_dense_task_test), + KUNIT_CASE(ane_h16_scatter_task_test), + KUNIT_CASE(ane_h16_extra_header_test), + KUNIT_CASE(ane_h16_relocation_test), + {} +}; + +static struct kunit_suite ane_h16_task_suite = { + .name = "ane-h16-tasks", + .test_cases = ane_h16_task_cases, +}; + +kunit_test_suite(ane_h16_task_suite); +MODULE_DESCRIPTION("KUnit tests for H16 task and relocation validation"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_job_gap.h b/drivers/accel/ane/ane_job_gap.h new file mode 100644 index 0000000000000..45d3edb7021e1 --- /dev/null +++ b/drivers/accel/ane/ane_job_gap.h @@ -0,0 +1,68 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ANE_JOB_GAP_H_ +#define _ANE_JOB_GAP_H_ +#include +#include + +/* Preserve legacy one-shot clamping; periodic mode is explicitly bounded. */ +static inline bool ane_job_gap_valid(u32 us, u32 at, u32 every, + bool pending, bool ack_pending, bool quiet) +{ + return !every || (us && us <= 2000 && every <= 128 && !at && + !pending && !ack_pending && !quiet); +} + +/* ordinal1 is the second execution of the warmed identity, before publish. */ +static inline bool ane_job_gap_selected(u32 ordinal, u32 at, u32 every) +{ + if (!ordinal) + return false; + if (every) + return !(ordinal % every); + return !at || ordinal == (at > 128 ? 128 : at); +} +/* Private drain-and-hold discriminator: only every-call busy hold is allowed. */ +static inline bool ane_job_drain_valid(u32 drain, u32 hold, u32 at, u32 every) +{ + return !drain || (drain <= 2000 && hold && hold <= 100 && !at && every == 1); +} + +static inline u32 ane_job_gap_duration(u32 ordinal, u32 hold, u32 drain) +{ + return ordinal == 1 && drain ? drain : (hold > 2000 ? 2000 : hold); +} +/* Private serial feedback, never a predicate on firmware CPU-load telemetry. */ +struct ane_job_recovery { + bool valid, dedicated; + u32 handles[3]; +}; + +static inline bool ane_job_recovery_valid(u32 recovery, u32 hold, u32 at, + u32 every, u32 drain) +{ + return !recovery || (hold && hold <= 100 && recovery > hold && + recovery <= 2000 && !at && every == 1 && !drain); +} + +static inline void ane_job_recovery_reset(struct ane_job_recovery *r) +{ + r->valid = false; +} + +static inline void ane_job_recovery_observe(struct ane_job_recovery *r, + bool serial, u32 token, const u32 handles[3]) +{ + r->valid = serial; + if (!serial) + return; + r->dedicated = token >= 0xfe00 && token <= 0xfe03; + memcpy(r->handles, handles, sizeof(r->handles)); +} + +static inline u32 ane_job_recovery_duration(const struct ane_job_recovery *r, + const u32 handles[3], u32 hold, u32 recovery) +{ + return r->valid && r->dedicated && + !memcmp(r->handles, handles, sizeof(r->handles)) ? hold : recovery; +} +#endif diff --git a/drivers/accel/ane/ane_perf.c b/drivers/accel/ane/ane_perf.c new file mode 100644 index 0000000000000..468fd151c4886 --- /dev/null +++ b/drivers/accel/ane/ane_perf.c @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Workload-scoped ANE clock and memory bandwidth requests. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ane.h" + +/* Amortize clock transitions across a stream of short submissions. */ +#define ANE_PERF_IDLE_MS 32 + +static int ane_perf_drop(struct ane_device *ane) +{ + struct ane_perf *p = &ane->perf; + int ret; + + if (p->clock_held) { + ret = apple_pmp_report_ane_perf(p->report, ane->dev, 0, &p->clock_held); + p->level = 0; + if (ret) + return ret; + } + if (p->voted) { + ret = icc_set_bw(p->memory, 0, 0); + if (ret) + return ret; + p->voted = false; + } + return 0; +} + +static void ane_perf_idle(struct work_struct *work) +{ + struct ane_device *ane = container_of(to_delayed_work(work), + struct ane_device, perf.idle); + struct ane_perf *p = &ane->perf; + + mutex_lock(&p->lock); + if (!p->busy && !atomic_read(&ane->wedged)) { + p->error = ane_perf_drop(ane); + if (!p->error && p->pinned) { + p->pinned = false; + pm_runtime_put_autosuspend(ane->dev); + } + if (p->error && ++p->release_retries < 3) + mod_delayed_work(system_dfl_wq, &p->idle, + msecs_to_jiffies(ANE_PERF_IDLE_MS)); + } + mutex_unlock(&p->lock); +} + +int ane_perf_begin(struct ane_device *ane) +{ + struct ane_perf *p = &ane->perf; + int ret = 0; + + if (p->cpu_boost) + ane_boost_begin(ane); + + /* The submit ioctl already holds a runtime PM reference. */ + mutex_lock(&p->lock); + p->busy = true; + if (p->error) { + ret = ane_perf_drop(ane); + if (ret) + goto out; + } + if (p->memory && !p->voted) { + ret = icc_set_bw(p->memory, p->avg_bw, p->peak_bw); + if (ret) + goto out; + p->voted = true; + } + if (p->report && !p->clock_held) { + ret = apple_pmp_report_ane_perf(p->report, ane->dev, p->high_level, + &p->clock_held); + if (ret) + goto out; + p->level = p->high_level; + } +out: + p->error = ret; + /* Keep the windows powered until delayed release, including errors. */ + if (!p->pinned && (p->clock_held || p->voted)) { + pm_runtime_get_noresume(ane->dev); + p->pinned = true; + } + mutex_unlock(&p->lock); + return ret; +} + +void ane_perf_end(struct ane_device *ane) +{ + struct ane_perf *p = &ane->perf; + + if (p->cpu_boost) + ane_boost_end(ane); + + mutex_lock(&p->lock); + p->busy = false; + p->release_retries = 0; + mod_delayed_work(system_dfl_wq, &p->idle, msecs_to_jiffies(ANE_PERF_IDLE_MS)); + mutex_unlock(&p->lock); +} + +static ssize_t performance_level_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct ane_device *ane = dev_get_drvdata(dev); + struct ane_perf *p = &ane->perf; + ssize_t ret; + + mutex_lock(&p->lock); + ret = p->report ? sysfs_emit(buf, "%u\n", p->level) : + sysfs_emit(buf, "unsupported\n"); + mutex_unlock(&p->lock); + return ret; +} +static DEVICE_ATTR_RO(performance_level); + +static ssize_t memory_vote_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct ane_device *ane = dev_get_drvdata(dev); + struct ane_perf *p = &ane->perf; + ssize_t ret; + + mutex_lock(&p->lock); + ret = p->memory ? sysfs_emit(buf, "%u %u\n", + p->voted ? p->avg_bw : 0, + p->voted ? p->peak_bw : 0) : + sysfs_emit(buf, "unsupported\n"); + mutex_unlock(&p->lock); + return ret; +} +static DEVICE_ATTR_RO(memory_vote); + +static ssize_t performance_error_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct ane_device *ane = dev_get_drvdata(dev); + + return sysfs_emit(buf, "%d\n", READ_ONCE(ane->perf.error)); +} +static DEVICE_ATTR_RO(performance_error); + +static struct attribute *ane_perf_attrs[] = { + &dev_attr_performance_level.attr, + &dev_attr_memory_vote.attr, + &dev_attr_performance_error.attr, + NULL, +}; + +static const struct attribute_group ane_perf_group = { .attrs = ane_perf_attrs }; + +int ane_perf_init(struct ane_device *ane, unsigned int high_level) +{ + struct ane_perf *p = &ane->perf; + struct platform_device *supplier; + struct device_link *link; + struct dev_pm_opp *opp; + int ret; + + mutex_init(&p->lock); + p->initialized = true; + INIT_DELAYED_WORK(&p->idle, ane_perf_idle); + p->high_level = high_level; + p->report = of_parse_phandle(ane->dev->of_node, "apple,performance-controller", 0); + if (p->report) { + if (!high_level) + return -EINVAL; + supplier = of_find_device_by_node(p->report); + if (!supplier) + return -EPROBE_DEFER; + link = device_link_add(ane->dev, &supplier->dev, + DL_FLAG_AUTOREMOVE_CONSUMER); + put_device(&supplier->dev); + if (!link) + return -ENOMEM; + ret = apple_pmp_report_ane_available(p->report); + if (ret) + return ret; + } + + if (of_property_present(ane->dev->of_node, "interconnects")) { + p->memory = devm_of_icc_get(ane->dev, "memory"); + if (IS_ERR(p->memory)) + return PTR_ERR(p->memory); + if (!p->memory) + return -ENODEV; + ret = devm_pm_opp_of_add_table(ane->dev); + if (ret) + return ret; + opp = dev_pm_opp_find_level_exact(ane->dev, high_level); + if (IS_ERR(opp)) + return PTR_ERR(opp); + p->avg_bw = dev_pm_opp_get_bw(opp, false, 0); + p->peak_bw = dev_pm_opp_get_bw(opp, true, 0); + dev_pm_opp_put(opp); + if (!p->peak_bw || p->avg_bw > p->peak_bw) + return -EINVAL; + } + + ret = devm_device_add_group(ane->dev, &ane_perf_group); + if (ret) + return ret; + + /* + * Without a performance controller the engine runs at its boot + * clock, and the CPU cluster boost is what keeps bandwidth-bound + * programs and the submit tail fast. Keep it until the DT binds a + * controller. + */ + if (!p->report) { + ret = ane_boost_init(ane); + if (ret) + return ret; + p->cpu_boost = true; + dev_info(ane->dev, "no performance controller; keeping the CPU frequency boost\n"); + } + return 0; +} + +int ane_perf_exit(struct ane_device *ane) +{ + struct ane_perf *p = &ane->perf; + int ret; + + if (!p->initialized) + return 0; + if (p->cpu_boost) { + ane_boost_exit(ane); + p->cpu_boost = false; + } + cancel_delayed_work_sync(&p->idle); + mutex_lock(&p->lock); + p->error = ane_perf_drop(ane); + if (p->error) + dev_err(ane->dev, "performance release failed during removal: %d\n", + p->error); + if (p->pinned && !p->error) { + pm_runtime_put_noidle(ane->dev); + p->pinned = false; + } + ret = p->error; + mutex_unlock(&p->lock); + if (ret) + return ret; + of_node_put(p->report); + p->report = NULL; + return 0; +} + +int ane_perf_suspend(struct ane_device *ane) +{ + struct ane_perf *p = &ane->perf; + int ret; + + cancel_delayed_work_sync(&p->idle); + mutex_lock(&p->lock); + if (p->busy && !ane->recovering) { + ret = -EBUSY; + goto out; + } + ret = ane_perf_drop(ane); + p->error = ret; + if (!ret && p->pinned) { + pm_runtime_put_noidle(ane->dev); + p->pinned = false; + } +out: + mutex_unlock(&p->lock); + return ret; +} diff --git a/drivers/accel/ane/ane_pm.h b/drivers/accel/ane/ane_pm.h new file mode 100644 index 0000000000000..ccc08c88057a4 --- /dev/null +++ b/drivers/accel/ane/ane_pm.h @@ -0,0 +1,51 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_PM_H__ +#define __ANE_PM_H__ + +#include +#include + +/* + * The caller serializes PM entries and holds exactly one consumer reference. + * Its suspend callback must permit recovery and its resume callback must defer + * engine access until the caller verifies power-on. verify_off may only read + * always-accessible provider registers, never the powered-down engine. + * + * Kept independent of the H13 task manager: a firmware client can use the same + * PM transaction after stopping its RX worker and fencing submissions. + */ +static inline int ane_pm_cycle(struct device *dev, struct device **domains, + int count, int (*verify_off)(void *), void *ctx) +{ + int err, resume_err; + + if (count > 1) { + for (int i = 0; i < count; i++) + dev_pm_genpd_synced_poweroff(domains[i]); + } else { + dev_pm_genpd_synced_poweroff(dev); + } + + /* Normal runtime PM releases the consumer's supplier references. */ + err = pm_runtime_put_sync_suspend(dev); + if (err < 0) + goto resume; + + /* Finish asynchronous supplier idle work, then suspend leaves first. + * Runtime PM stays enabled so genpd can also suspend their parents. + */ + for (int i = count - 1; i >= 0 && count > 1; i--) { + pm_runtime_barrier(domains[i]); + err = pm_runtime_suspend(domains[i]); + if (err < 0) + goto resume; + } + err = verify_off(ctx); + +resume: + /* Restore the caller's reference even if resume itself fails. */ + resume_err = pm_runtime_get_sync(dev); + return err < 0 ? err : (resume_err < 0 ? resume_err : 0); +} + +#endif /* __ANE_PM_H__ */ diff --git a/drivers/accel/ane/ane_pm_test.c b/drivers/accel/ane/ane_pm_test.c new file mode 100644 index 0000000000000..5c372a2a73011 --- /dev/null +++ b/drivers/accel/ane/ane_pm_test.c @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Exercise recovery against the real runtime-PM and device-link core. */ +#include +#include +#include + +#include "ane_pm.h" + +struct ane_pm_test_dev { + struct device dev; + int suspend_error; + int resume_error; + unsigned int suspends; + unsigned int resumes; +}; + +struct ane_pm_test_ctx { + struct kunit *test; + struct device *consumer; + struct device *domains[2]; + struct device_link *links[2]; + unsigned int verified; + int verify_error; +}; + +static int ane_pm_test_suspend(struct device *dev) +{ + struct ane_pm_test_dev *d = container_of(dev, struct ane_pm_test_dev, dev); + + d->suspends++; + return d->suspend_error; +} + +static int ane_pm_test_resume(struct device *dev) +{ + struct ane_pm_test_dev *d = container_of(dev, struct ane_pm_test_dev, dev); + + d->resumes++; + return d->resume_error; +} + +static const struct dev_pm_ops ane_pm_test_ops = { + .runtime_suspend = ane_pm_test_suspend, + .runtime_resume = ane_pm_test_resume, +}; + +static const struct device_type ane_pm_test_type = { + .pm = &ane_pm_test_ops, +}; + +static void ane_pm_test_release(struct device *dev) +{ + kfree(container_of(dev, struct ane_pm_test_dev, dev)); +} + +static void ane_pm_test_unregister(void *data) +{ + struct device *dev = data; + + pm_runtime_barrier(dev); + pm_runtime_disable(dev); + /* Also releases supplier votes after an injected resume failure. */ + pm_runtime_set_suspended(dev); + device_unregister(dev); +} + +static struct device *ane_pm_test_register(struct kunit *test, const char *name) +{ + struct ane_pm_test_dev *d; + int ret; + + d = kzalloc_obj(*d); + if (!d) + return NULL; + device_initialize(&d->dev); + d->dev.release = ane_pm_test_release; + d->dev.type = &ane_pm_test_type; + ret = dev_set_name(&d->dev, "%s", name); + if (!ret) + ret = device_add(&d->dev); + if (ret) { + put_device(&d->dev); + return NULL; + } + pm_runtime_enable(&d->dev); + ret = kunit_add_action_or_reset(test, ane_pm_test_unregister, &d->dev); + return ret ? NULL : &d->dev; +} + +static void ane_pm_test_unlink(void *data) +{ + device_link_del(data); +} + +static int ane_pm_test_verify(void *data) +{ + struct ane_pm_test_ctx *ctx = data; + + ctx->verified++; + KUNIT_EXPECT_TRUE(ctx->test, pm_runtime_suspended(ctx->consumer)); + KUNIT_EXPECT_EQ(ctx->test, atomic_read(&ctx->consumer->power.usage_count), 0); + for (int i = 0; i < ARRAY_SIZE(ctx->domains); i++) { + if (!ctx->domains[i]) + continue; + KUNIT_EXPECT_TRUE(ctx->test, pm_runtime_suspended(ctx->domains[i])); + KUNIT_EXPECT_EQ(ctx->test, atomic_read(&ctx->domains[i]->power.usage_count), 0); + } + return ctx->verify_error; +} + +static int ane_pm_test_setup(struct kunit *test, struct ane_pm_test_ctx *ctx, + bool multiple) +{ + static const char * const names[] = { "ane-pm-domain0", "ane-pm-domain1" }; + + ctx->test = test; + ctx->consumer = ane_pm_test_register(test, "ane-pm-consumer"); + if (!ctx->consumer) + return -ENOMEM; + if (multiple) { + for (int i = 0; i < ARRAY_SIZE(ctx->domains); i++) { + ctx->domains[i] = ane_pm_test_register(test, names[i]); + if (!ctx->domains[i]) + return -ENOMEM; + ctx->links[i] = device_link_add(ctx->consumer, ctx->domains[i], + DL_FLAG_STATELESS | DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE); + if (!ctx->links[i]) + return -ENOMEM; + if (kunit_add_action_or_reset(test, ane_pm_test_unlink, + ctx->links[i])) + return -ENOMEM; + } + } + return pm_runtime_resume_and_get(ctx->consumer); +} + +static void ane_pm_test_finish(struct kunit *test, struct ane_pm_test_ctx *ctx) +{ + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->consumer->power.usage_count), 1); + KUNIT_EXPECT_GE(test, pm_runtime_put_sync_suspend(ctx->consumer), 0); +} + +static void ane_pm_cycle_domains_test(struct kunit *test) +{ + struct ane_pm_test_ctx ctx = {}; + + KUNIT_ASSERT_GE(test, ane_pm_test_setup(test, &ctx, true), 0); + for (int repeat = 0; repeat < 3; repeat++) { + KUNIT_EXPECT_EQ(test, ane_pm_cycle(ctx.consumer, ctx.domains, 2, + ane_pm_test_verify, &ctx), 0); + KUNIT_EXPECT_TRUE(test, pm_runtime_active(ctx.consumer)); + for (int i = 0; i < ARRAY_SIZE(ctx.domains); i++) { + KUNIT_EXPECT_TRUE(test, pm_runtime_active(ctx.domains[i])); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx.domains[i]->power.usage_count), 1); + } + } + KUNIT_EXPECT_EQ(test, ctx.verified, 3U); + ane_pm_test_finish(test, &ctx); +} + +static void ane_pm_cycle_single_test(struct kunit *test) +{ + struct ane_pm_test_ctx ctx = {}; + + KUNIT_ASSERT_GE(test, ane_pm_test_setup(test, &ctx, false), 0); + KUNIT_EXPECT_EQ(test, ane_pm_cycle(ctx.consumer, NULL, 1, + ane_pm_test_verify, &ctx), 0); + KUNIT_EXPECT_EQ(test, ctx.verified, 1U); + ane_pm_test_finish(test, &ctx); +} + +static void ane_pm_cycle_suspend_error_test(struct kunit *test) +{ + struct ane_pm_test_ctx ctx = {}; + struct ane_pm_test_dev *d; + + KUNIT_ASSERT_GE(test, ane_pm_test_setup(test, &ctx, true), 0); + d = container_of(ctx.consumer, struct ane_pm_test_dev, dev); + d->suspend_error = -EBUSY; + KUNIT_EXPECT_EQ(test, ane_pm_cycle(ctx.consumer, ctx.domains, 2, + ane_pm_test_verify, &ctx), -EBUSY); + KUNIT_EXPECT_EQ(test, ctx.verified, 0U); + d->suspend_error = 0; + ane_pm_test_finish(test, &ctx); +} + +static void ane_pm_cycle_supplier_error_test(struct kunit *test) +{ + struct ane_pm_test_ctx ctx = {}; + struct ane_pm_test_dev *d; + + KUNIT_ASSERT_GE(test, ane_pm_test_setup(test, &ctx, true), 0); + d = container_of(ctx.domains[1], struct ane_pm_test_dev, dev); + d->suspend_error = -EBUSY; + KUNIT_EXPECT_EQ(test, ane_pm_cycle(ctx.consumer, ctx.domains, 2, + ane_pm_test_verify, &ctx), -EBUSY); + KUNIT_EXPECT_EQ(test, ctx.verified, 0U); + d->suspend_error = 0; + ane_pm_test_finish(test, &ctx); +} + +static void ane_pm_cycle_verify_error_test(struct kunit *test) +{ + struct ane_pm_test_ctx ctx = { .verify_error = -ETIMEDOUT }; + + KUNIT_ASSERT_GE(test, ane_pm_test_setup(test, &ctx, true), 0); + KUNIT_EXPECT_EQ(test, ane_pm_cycle(ctx.consumer, ctx.domains, 2, + ane_pm_test_verify, &ctx), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, ctx.verified, 1U); + KUNIT_EXPECT_TRUE(test, pm_runtime_active(ctx.consumer)); + ane_pm_test_finish(test, &ctx); +} + +static void ane_pm_cycle_resume_error_test(struct kunit *test) +{ + struct ane_pm_test_ctx ctx = {}; + struct ane_pm_test_dev *d; + + KUNIT_ASSERT_GE(test, ane_pm_test_setup(test, &ctx, false), 0); + d = container_of(ctx.consumer, struct ane_pm_test_dev, dev); + d->resume_error = -EIO; + KUNIT_EXPECT_EQ(test, ane_pm_cycle(ctx.consumer, NULL, 1, + ane_pm_test_verify, &ctx), -EIO); + KUNIT_EXPECT_EQ(test, ctx.verified, 1U); + /* get_sync must leave exactly the reference the caller will put. */ + KUNIT_EXPECT_EQ(test, atomic_read(&ctx.consumer->power.usage_count), 1); + pm_runtime_put_noidle(ctx.consumer); +} + +static struct kunit_case ane_pm_test_cases[] = { + KUNIT_CASE(ane_pm_cycle_domains_test), + KUNIT_CASE(ane_pm_cycle_single_test), + KUNIT_CASE(ane_pm_cycle_suspend_error_test), + KUNIT_CASE(ane_pm_cycle_supplier_error_test), + KUNIT_CASE(ane_pm_cycle_verify_error_test), + KUNIT_CASE(ane_pm_cycle_resume_error_test), + {} +}; + +static struct kunit_suite ane_pm_test_suite = { + .name = "ane-pm-recovery", + .test_cases = ane_pm_test_cases, +}; + +kunit_test_suite(ane_pm_test_suite); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("ANE recovery runtime-PM transaction tests"); diff --git a/drivers/accel/ane/ane_t6021.h b/drivers/accel/ane/ane_t6021.h index cf04c6699710e..bf6d0f3e44202 100644 --- a/drivers/accel/ane/ane_t6021.h +++ b/drivers/accel/ane/ane_t6021.h @@ -742,6 +742,7 @@ bool ane_t6021_fwload_options_ok(void); bool ane_t6021_fwload_placement_ok(struct device *dev); bool ane_t6021_fwload_requested(void); +struct ane_fw_platform; struct ane_fw_image; struct ane_asc_tunables; @@ -753,8 +754,9 @@ struct ane_asc_tunables; * for this SoC (T6021 only), so fw_alias_reserved=1 may map it; the * other SoCs always run the firmware from driver-owned memory. * ps_cpu_off: the ANE CPU ps word in the DT "pmgr" window (probe guard). - * pwgate_off: the PWGATE word in the DT "set" window, checked - * open before any engine read; 0 = not checked. + * pwgate_off: the power gate word in the DT "set" window. The driver + * opens it before ane_sys_cpu powers on, closes it after that state + * powers off, and checks it open before any engine read; 0 = no gate. * pmu_pa: the page of the seven ANE ps words; the firmware's power * service writes them through its DART at IOVA == PA. ps_off: the * first of the seven in that page. @@ -762,6 +764,7 @@ struct ane_asc_tunables; * trace_td; 0 = trace_td unsupported. */ struct ane_t602x_soc { + const struct ane_fw_platform *platform; u32 soc; u32 soc_revision; bool revision_fuse; diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index 4dc4ce27b1674..f39e4b7e8b05c 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -533,11 +533,20 @@ int ane_t6021_fwload_check(struct device *dev) if (!fw_load) return 0; - ret = request_firmware(&fw, img->name, dev); + /* + * The image is installed on the machine itself from Apple's files, so + * a missing file is the normal state of a system that has not fetched + * it yet: say so once and leave the ANE off. Other errors are errors. + */ + ret = firmware_request_nowarn(&fw, img->name, dev); + if (ret == -ENOENT) { + dev_info(dev, + "firmware %s is not installed, so the ANE stays off; install it with omarchy-ane-firmware-fetch\n", + img->name); + return -ENODEV; + } if (ret) { - dev_err(dev, - "cannot load firmware %s: %d; install it with omarchy-ane-firmware-fetch (or equivalent for your distribution)\n", - img->name, ret); + dev_err(dev, "cannot load firmware %s: %d\n", img->name, ret); return ret; } diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index 40e643f58a8ca..f904234e40225 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -65,6 +65,8 @@ #include #include #include +#include +#include #include #include #include @@ -90,6 +92,11 @@ #include #include +#include "ane_fw_platform.h" +#include "ane_h16_protocol.h" +#include "ane_h16_pending.h" +#include "ane_h16_resources.h" +#include "ane_fw_protocol.h" #include "ane_stats.h" #include "ane_t6021.h" #include "ane_t6021_boot.h" @@ -191,6 +198,22 @@ struct ane_legacy_buffer { size_t size; }; +struct ane_t6021_fd; + +/* Populated only by an original-container loader and decoded process reply. + * Those interfaces remain refused until their complete wire contract exists. + * The firmware mutex protects this list and every pending UUID operation. + */ +struct ane_h16_process { + struct list_head node; + struct list_head owner_node; + struct ane_h16_hwx_snapshot original; + struct ane_h16_request_key key; + struct ane_h16_resource resources[ANE_H16_SURFACES]; + struct ane_legacy_buffer mappings[ANE_H16_SURFACES]; + u32 resource_count; +}; + struct ane_rtclient { struct device *dev; void __iomem *engine; @@ -213,6 +236,12 @@ struct ane_rtclient { /* ChMan descriptor table validated against the 'IPC ' surface. */ bool chman_ok; + struct ane_fw_channel channels[ANE_FW_CHANNELS]; + u8 channel_snapshot[ANE_FW_TABLE_SIZE]; + u64 channel_table_offset; + struct ane_h16_pending_table pending; + struct ane_h16_pending *waiting; + struct list_head h16_processes; struct ane_legacy_buffer *legacy_buffers; u32 legacy_allocated; size_t legacy_bytes; @@ -245,6 +274,7 @@ struct ane_rtclient { */ struct ane_t6021_fd { struct list_head bos; + struct list_head h16_processes; }; /* Per-file handle counter and every per-fd list against same-fd concurrent @@ -400,7 +430,10 @@ static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, struct ane_legacy_buffer *command, size_t length, u16 opcode, unsigned int channel, - unsigned int timeout_ms); + unsigned long deadline); + +static bool ane_rtclient_drain_t2h(struct ane_rtclient *ane, + unsigned int channel); /* ---- boot helpers (shared with boot.c / fwload.c) ---- */ @@ -442,6 +475,31 @@ static void ane_rtclient_validate_chman(struct ane_rtclient *ane) "chman: no host IPC surface — table not validated\n"); return; } + if (ane->soc->platform) { + int ret; + + if (!ane_fw_contains(a->boot_ipc_iova, a->boot_ipc_size, + a->boot_scratch_result, ANE_FW_TABLE_SIZE)) { + dev_err(ane->dev, "27.x channel table outside IPC\n"); + return; + } + ane->channel_table_offset = a->boot_scratch_result - a->boot_ipc_iova; + dma_rmb(); + memcpy(ane->channel_snapshot, + a->boot_ipc + ane->channel_table_offset, ANE_FW_TABLE_SIZE); + ret = ane_fw_channels_parse(ane->channel_snapshot, a->boot_ipc_iova, + a->boot_ipc_size, a->boot_scratch_result, + ane->channels); + dma_rmb(); + if (ret || memcmp(ane->channel_snapshot, + a->boot_ipc + ane->channel_table_offset, + ANE_FW_TABLE_SIZE)) { + dev_err(ane->dev, "27.x channel table rejected or changed\n"); + return; + } + ane->chman_ok = true; + return; + } if (a->boot_ipc_size < ANE_T6021_CHMAN_TOTAL) { dev_warn(ane->dev, "chman: IPC surface %#llx bytes < fw layout %#x — table not validated\n", @@ -465,10 +523,39 @@ static void ane_rtclient_validate_chman(struct ane_rtclient *ane) } ane->chman_ok = !bad; + if (!bad) + for (i = 0; i < ANE_FW_CHANNELS; i++) { + const struct ane_t6021_chman_static *c = &ane_t6021_chman_layout[i]; + + ane->channels[i] = (struct ane_fw_channel) { + .offset = c->off, .slots = c->size, + .type = c->type, .bit = c->bit, + }; + } dev_info(ane->dev, "chman: table %s (mismatch mask %#x)\n", bad ? "NOT VALIDATED" : "VALIDATED", bad); } +static bool ane_rtclient_channels_unchanged(struct ane_rtclient *ane) +{ + struct ane_t6021 *a = ane->fw; + + if (!a || !ane->chman_ok) + return false; + dma_rmb(); + if (ane->soc->platform) + return !memcmp(ane->channel_snapshot, + a->boot_ipc + ane->channel_table_offset, + ANE_FW_TABLE_SIZE); + return !ane_t6021_chman_check(a->boot_ipc, a->boot_ipc_iova); +} + +static void __iomem *ane_rtclient_doorbell(struct ane_rtclient *ane) +{ + return ane->engine + (ane->soc->platform ? + ane->soc->platform->doorbell : ANE_IPI_OFF); +} + /* Legacy ChMan exchange (post-DONE 13.5 transport). Resends to the same * 64-byte IO slot would wedge the ring; cursor advances after each * completed command (the fw treats bit0 as host-owned). @@ -477,46 +564,66 @@ static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, struct ane_legacy_buffer *command, size_t length, u16 opcode, unsigned int channel, - unsigned int timeout_ms) + unsigned long deadline) { struct ane_t6021 *a = ane->fw; u64 *io, *malloc_ring, header; - u64 *t2h_buf, *t2h_ioq; - void __iomem *ipi = ane->engine + ANE_IPI_OFF; + void __iomem *ipi = ane_rtclient_doorbell(ane); unsigned int cursor = ane->legacy_malloc_cursor; - unsigned long deadline; - u32 *reply; int result = -ETIMEDOUT; - if (!ane->held || !ane->chman_ok || - ane_t6021_chman_check(a->boot_ipc, a->boot_ipc_iova)) + if (!ane->held || !ane_rtclient_channels_unchanged(ane)) return -EPROTO; if (length < 8 || length > command->size || channel >= ANE_T6021_CHMAN_COUNT) { result = -EINVAL; goto out; } - io = a->boot_ipc + ane_t6021_chman_layout[channel].off + + io = a->boot_ipc + ane->channels[channel].offset + (size_t)ane->legacy_cmd_cursor[channel] * 64; - malloc_ring = a->boot_ipc + ane_t6021_chman_layout[5].off; - t2h_buf = a->boot_ipc + ane_t6021_chman_layout[4].off; - t2h_ioq = a->boot_ipc + ane_t6021_chman_layout[6].off; + malloc_ring = a->boot_ipc + ane->channels[5].offset; if (!(READ_ONCE(io[0]) & 1)) { result = -EBUSY; goto out; } - reply = command->cpu; - ((u16 *)reply)[2] = opcode; + if (time_after_eq(jiffies, deadline)) + goto out; + if (ane->soc->platform) { + result = ane_h16_command_prepare(command->cpu, length, opcode, + ane->channels[channel].index); + if (result) + goto out; + } else { + ane_fw_command_header(command->cpu, opcode, false); + } + if (ane->soc->platform) + memset((u8 *)command->cpu + length, 0xa5, command->size - length); WRITE_ONCE(io[1], length); WRITE_ONCE(io[2], length); dma_wmb(); WRITE_ONCE(io[0], command->dma); dma_wmb(); - writel(BIT(ane_t6021_chman_layout[channel].bit), ipi); - deadline = jiffies + msecs_to_jiffies(timeout_ms); + writel(BIT(ane->channels[channel].bit), ipi); while (time_before(jiffies, deadline)) { - u32 pending = readl(ipi + 0x8000); + u32 pending; + + if (atomic_read(&ane_t6021_quarantined)) { + result = -EIO; + goto out; + } + if (!ane_rtclient_channels_unchanged(ane)) { + result = -EPROTO; + goto out; + } + if (ane->soc->platform && opcode == ANE_H16_EXECUTE) { + ane_rtclient_drain_t2h(ane, 6); + if (ane->pending.quarantined) { + result = ane->pending.error ?: -EIO; + goto out; + } + } + pending = readl(ipi + 0x8000); if (pending) { writel(pending, ipi + 0xc000); @@ -538,6 +645,13 @@ static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, u64 size, tag; struct ane_legacy_buffer *buf; + /* H16 needs its own validated allocation/reply provider. + * Never answer it with the legacy H14 allocation index. + */ + if (ane->soc->platform) { + result = -EOPNOTSUPP; + goto out; + } dma_rmb(); size = READ_ONCE(slot[1]); tag = READ_ONCE(slot[2]); @@ -546,7 +660,7 @@ static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, * is a malformed ring and we stop. */ if (alloc_hdr || tag > U32_MAX) { - result = -EOPNOTSUPP; + result = -EPROTO; goto out; } if (ane_rtclient_legacy_alloc(ane, size)) { @@ -559,22 +673,36 @@ static int ane_rtclient_legacy_exchange(struct ane_rtclient *ane, dma_wmb(); WRITE_ONCE(slot[0], buf->dma | 1); dma_wmb(); - writel(BIT(5), ipi); + writel(BIT(ane->channels[5].bit), ipi); cursor = (cursor + 1) % - ane_t6021_chman_layout[5].size; + ane->channels[5].slots; } } + /* Allocation service cannot extend the command deadline. */ + if (time_after_eq(jiffies, deadline)) + goto out; header = READ_ONCE(io[0]); if (header & 1) { dma_rmb(); - result = (header == (command->dma | 1) && - READ_ONCE(io[1]) == length && - READ_ONCE(io[2]) == 0 && - ((u16 *)reply)[2] == opcode && - ((u16 *)reply)[3] == 0) ? 0 : -EPROTO; - ane->legacy_cmd_cursor[channel] = - (ane->legacy_cmd_cursor[channel] + 1) % - ane_t6021_chman_layout[channel].size; + result = ane_fw_reply_status(header, READ_ONCE(io[1]), + READ_ONCE(io[2]), command->dma, + length, opcode, command->cpu, + !!ane->soc->platform); + /* Corruption does not retire the unknown slot. A refusal + * retires ownership but remains a nonzero result. + */ + if (!ane_rtclient_channels_unchanged(ane) || + (ane->soc->platform && + memchr_inv((u8 *)command->cpu + length, 0xa5, + command->size - length))) + result = -EPROTO; + if (result == -EREMOTEIO) + dev_info(ane->dev, "firmware refused op=%#x ack=%#x; no retry\n", + opcode, get_unaligned_le16((u8 *)command->cpu + 6)); + if (!result || result == -EREMOTEIO) + ane->legacy_cmd_cursor[channel] = + (ane->legacy_cmd_cursor[channel] + 1) % + ane->channels[channel].slots; goto out; } /* Fast poll: check the rings every 50 us instead of @@ -766,18 +894,24 @@ static void ane_t6021_trace_free(void) static const void *ane_rtclient_fw_cpu(struct ane_rtclient *ane, u64 iova, size_t len) { + const void *found = NULL; u32 i; for (i = 0; i < ane->legacy_allocated; i++) { const struct ane_legacy_buffer *b = &ane->legacy_buffers[i]; - if (iova >= b->dma && iova - b->dma + len <= b->size) - return b->cpu + (iova - b->dma); + if (ane_fw_contains(b->dma, b->size, iova, len)) { + if (!ane->soc->platform) + return b->cpu + (iova - b->dma); + if (found) + return NULL; + found = b->cpu + (iova - b->dma); + } } - if (iova >= ane->fw->boot_ipc_iova && - iova - ane->fw->boot_ipc_iova + len <= ane->fw->boot_ipc_size) - return ane->fw->boot_ipc + (iova - ane->fw->boot_ipc_iova); - return NULL; + if (ane_fw_contains(ane->fw->boot_ipc_iova, ane->fw->boot_ipc_size, + iova, len)) + return found ? NULL : ane->fw->boot_ipc + (iova - ane->fw->boot_ipc_iova); + return found; } /* Return every firmware-owned slot on a target-to-host ring to the fw: @@ -790,23 +924,62 @@ static const void *ane_rtclient_fw_cpu(struct ane_rtclient *ane, u64 iova, static bool ane_rtclient_drain_t2h(struct ane_rtclient *ane, unsigned int channel) { - const struct ane_t6021_chman_static *c = &ane_t6021_chman_layout[channel]; + const struct ane_fw_channel *c = &ane->channels[channel]; unsigned int n = 0, slot_i = ane->legacy_cmd_cursor[channel]; - void __iomem *ipi = ane->engine + ANE_IPI_OFF; + void __iomem *ipi = ane_rtclient_doorbell(ane); bool finished = false; - if (!ane->fw || !ane->fw->boot_ipc) + if (!ane_rtclient_channels_unchanged(ane)) { + atomic_set(&ane_t6021_quarantined, 1); + if (ane->soc->platform) { + ane->pending.error = -EPROTO; + ane->pending.quarantined = true; + } return false; - while (n < c->size) { - u64 *slot = ane->fw->boot_ipc + c->off + (size_t)slot_i * 64; - u64 hdr = READ_ONCE(slot[0]), len = READ_ONCE(slot[1]); + } + if (c->type != 1) + return false; + while (n < c->slots) { + u64 *slot = ane->fw->boot_ipc + c->offset + (size_t)slot_i * 64; + u64 hdr = READ_ONCE(slot[0]), len; if (hdr & 1) break; dma_rmb(); - dev_dbg(ane->dev, "T2H ch=%s slot=%u hdr=%016llx len=%#llx\n", - c->name, slot_i, hdr, len); - if (channel == 6 && len >= ANE_T2H_CALL_STATE_OFF + 4) { + len = READ_ONCE(slot[1]); + dev_dbg(ane->dev, "T2H ch=%u slot=%u len=%#llx\n", + channel, slot_i, len); + if (ane->soc->platform) { + u8 snapshot[0x60]; + const void *ev; + int status; + + /* Other channels have different message types; never apply + * the event predicate to logs or allocation traffic. + */ + if (c->index != 6 || (len != sizeof(snapshot) && len != 0xc)) { + atomic_set(&ane_t6021_quarantined, 1); + ane->pending.error = -EPROTO; + ane->pending.quarantined = true; + return false; + } + ev = ane_rtclient_fw_cpu(ane, hdr, len); + if (!ev) { + atomic_set(&ane_t6021_quarantined, 1); + ane->pending.error = -EPROTO; + ane->pending.quarantined = true; + return false; + } + memcpy(snapshot, ev, len); + status = ane_h16_pending_dispatch(&ane->pending, snapshot, + len, c->index, jiffies); + if (ane->pending.quarantined) { + atomic_set(&ane_t6021_quarantined, 1); + return false; + } + if (status == ANE_H16_EVENT_COMPLETE) + finished = true; + } else if (channel == 6 && len >= ANE_T2H_CALL_STATE_OFF + 4) { const u8 *ev = ane_rtclient_fw_cpu(ane, hdr, ANE_T2H_CALL_STATE_OFF + 4); @@ -826,7 +999,7 @@ static bool ane_rtclient_drain_t2h(struct ane_rtclient *ane, WRITE_ONCE(slot[0], hdr | 1); dma_wmb(); writel(BIT(c->bit), ipi); - slot_i = (slot_i + 1) % c->size; + slot_i = (slot_i + 1) % c->slots; ane->legacy_cmd_cursor[channel] = slot_i; } return finished; @@ -885,24 +1058,38 @@ static int ane_rtclient_call_wait_traced(struct ane_rtclient *ane, * Return zero on the event, or -ETIMEDOUT. */ static int ane_rtclient_call_wait(struct ane_rtclient *ane, - unsigned int timeout_ms) + unsigned long deadline) { - unsigned long deadline = jiffies + msecs_to_jiffies(timeout_ms); - unsigned int poll_us = READ_ONCE(call_poll_us); + unsigned int poll_us = ane->soc->platform ? 0 : READ_ONCE(call_poll_us); ktime_t tight_end = ktime_add_ns(ktime_get(), (u64)poll_us * NSEC_PER_USEC); if (ane_t6021_tracing) return ane_rtclient_call_wait_traced(ane, deadline); + if (time_after_eq(jiffies, deadline)) + return -ETIMEDOUT; do { - if (ane_rtclient_drain_t2h(ane, 6)) + if (atomic_read(&ane_t6021_quarantined)) + return -EIO; + if (ane->soc->platform) { + ane_rtclient_drain_t2h(ane, 6); + if (atomic_read(&ane_t6021_quarantined)) + return ane->pending.error ?: -EIO; + if (ane->waiting && ane->waiting->terminal) + return ane->waiting->status; + } else if (ane_rtclient_drain_t2h(ane, 6)) { return 0; + } if (poll_us && ktime_before(ktime_get(), tight_end)) usleep_range(1, 2); else usleep_range(50, 100); } while (time_before(jiffies, deadline)); + if (atomic_read(&ane_t6021_quarantined)) + return -EIO; + if (ane->soc->platform) + return -ETIMEDOUT; return ane_rtclient_drain_t2h(ane, 6) ? 0 : -ETIMEDOUT; } @@ -912,9 +1099,12 @@ static int ane_rtclient_command(struct ane_rtclient *ane, unsigned int channel, unsigned int timeout_ms) { + unsigned long deadline; int ret; u64 stats_ticket = 0; u64 stats_submit_ns = 0; + bool execute = ane->soc->platform ? opcode == ANE_H16_EXECUTE : + opcode == CSNE_CMD_PROCEDURE_CALL; ane_t6021_tracing = opcode == CSNE_CMD_PROCEDURE_CALL && trace_td && ane->soc->trace_td_off; @@ -937,8 +1127,16 @@ static int ane_rtclient_command(struct ane_rtclient *ane, * ring, as on ane.ko: stats=0 or a failed probe allocation leaves * stats_slots NULL, and the hooks must not run on a NULL ring. */ - bool stats_call = ane->stats_slots && - opcode == CSNE_CMD_PROCEDURE_CALL; + bool stats_call = ane->stats_slots && execute; + + if (ane->soc->platform && execute && + (!ane->waiting || !ane->waiting->active || ane->pending.quarantined)) + return -EIO; + + /* One bounded budget covers both ACK and finish, including H14. */ + timeout_ms = min(timeout_ms, 5000U); + deadline = ane->soc->platform && ane->waiting ? + ane->waiting->deadline : jiffies + msecs_to_jiffies(timeout_ms); if (stats_call) { stats_submit_ns = ktime_get_ns(); @@ -947,7 +1145,7 @@ static int ane_rtclient_command(struct ane_rtclient *ane, stats_submit_ns, 1); } ret = ane_rtclient_legacy_exchange(ane, command, length, opcode, - channel, timeout_ms); + channel, deadline); if (ret) { ane_t6021_tracing = false; if (stats_call) @@ -959,12 +1157,14 @@ static int ane_rtclient_command(struct ane_rtclient *ane, atomic_set(&ane_t6021_quarantined, 1); return ret; } - if (opcode == CSNE_CMD_PROCEDURE_CALL) { + if (execute) { if (ane_t6021_tracing) ane_t6021_trace_add(ANE_TR_ACK, 0); - ret = ane_rtclient_call_wait(ane, timeout_ms); + ret = ane_rtclient_call_wait(ane, deadline); ane_t6021_tracing = false; - if (!ret && call_settle_us) + if (!ret) + dma_rmb(); + if (!ret && !ane->soc->platform && call_settle_us) usleep_range(call_settle_us, call_settle_us + 100); if (ret) { if (stats_call) @@ -974,7 +1174,7 @@ static int ane_rtclient_command(struct ane_rtclient *ane, ktime_get_ns(), (u32)ret, 0); dev_err(ane->dev, - "call completion wait failed %d: no finish event in %u ms\n", + "call completion failed %d within %u ms\n", ret, timeout_ms); atomic_set(&ane_t6021_quarantined, 1); return ret; @@ -987,8 +1187,11 @@ static int ane_rtclient_command(struct ane_rtclient *ane, * hand those slots back so the rings never fill (channels 4 * and 6). */ - ane_rtclient_drain_t2h(ane, 4); + if (!ane->soc->platform) + ane_rtclient_drain_t2h(ane, 4); ane_rtclient_drain_t2h(ane, 6); + if (atomic_read(&ane_t6021_quarantined)) + return -EIO; /* BOs are dma_alloc_coherent memory mapped write-combined for the * CPU, so no cache maintenance is needed on either side. */ @@ -1058,6 +1261,9 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, int ret, i, j; BUILD_BUG_ON(DRM_ANE_MAX_SECTIONS != ANE_T6021_LOAD_SEC_COUNT); + /* H16 requires the original HWX, not caller-asserted section identity. */ + if (ane->soc->platform) + return -EOPNOTSUPP; if (user->pad || user->section_count < 1 || user->section_count > ANE_T6021_LOAD_SEC_COUNT || user->generic_count > DRM_ANE_MAX_BINDS || !fd) @@ -1280,6 +1486,9 @@ static int ane_rtclient_create_process(struct ane_rtclient *ane, struct ane_t6021_prog *prog = ane_t6021_prog_by_id(prog_id); int ret; + /* H16 uses 0x258 bytes; its body is not the H14 0x10-byte body. */ + if (ane->soc->platform) + return -EOPNOTSUPP; if (!prog) return -ENOENT; if (prog->proc_id != U32_MAX) { @@ -1311,6 +1520,140 @@ static int ane_rtclient_create_process(struct ane_rtclient *ane, return ret; } +/* H16 consumes only backend-owned process resources. The ABI-2 section + * loader and short process packet cannot create an entry in h16_processes. + */ +static int ane_rtclient_h16_call(struct ane_rtclient *ane, struct drm_file *file, + const struct drm_ane_exec *user) +{ + struct ane_t6021_fd *fd = file->driver_priv; + struct ane_h16_process *process = NULL, *p; + struct ane_h16_execute_buffer buffers[ANE_H16_SURFACES]; + struct ane_t6021_bo *bos[ANE_H16_SURFACES] = {}; + struct drm_ane_exec_io *ios; + struct ane_h16_pending request = {}; + struct ane_h16_execute call = {}; + unsigned int i, j, pinned = 0; + int ret = -EOPNOTSUPP; + + if (!fd || user->pad || user->priority != 5 || user->count < 2 || + user->count > ANE_H16_SURFACES || user->timeout_ms > 30000) + return -EINVAL; + ios = memdup_user(u64_to_user_ptr(user->io_ptr), + array_size(user->count, sizeof(*ios))); + if (IS_ERR(ios)) + return PTR_ERR(ios); + mutex_lock(&ane_t6021_fw_lock); + if (atomic_read(&ane_t6021_quarantined) || ane->pending.quarantined) { + ret = -EIO; + goto out; + } + list_for_each_entry(p, &fd->h16_processes, owner_node) { + if (p->key.program == user->prog_id && + p->key.process == user->proc_id) { + process = p; + break; + } + } + if (!process) + goto out; + ret = ane_h16_hwx_snapshot_check(&process->original); + if (!ret) + ret = ane_h16_resources_validate(&process->original.info, + process->resources, process->resource_count); + if (ret) + goto out; + if (user->count != process->resource_count || !ane->cmd_buf || + process->key.program == U32_MAX || process->key.process == U32_MAX || + process->key.procedure == U32_MAX) { + ret = -EINVAL; + goto out; + } + for (i = 0; i < user->count; i++) { + struct ane_t6021_bo *b; + const struct ane_h16_resource *r = &process->resources[i]; + const struct ane_legacy_buffer *m = &process->mappings[i]; + + if (ios[i].flags || ios[i].reserved || + ios[i].buffer_id != r->buffer.index || ios[i].type != r->buffer.class || + ios[i].size != r->buffer.size || !m->cpu || + m->dma != r->buffer.mapping_dva || m->size != r->buffer.mapping_size) { + ret = -EINVAL; + goto out; + } + for (j = 0; j < i; j++) { + if (ios[j].bo_handle == ios[i].bo_handle) { + ret = -EINVAL; + goto out; + } + } + mutex_lock(&ane_t6021_bo_lock); + list_for_each_entry(b, &fd->bos, node) { + if (b->handle == ios[i].bo_handle && b->owner == fd && + b->size >= ios[i].size) { + kref_get(&b->refcount); + bos[pinned++] = b; + break; + } + } + mutex_unlock(&ane_t6021_bo_lock); + if (pinned != i + 1) { + ret = -ENOENT; + goto out; + } + buffers[i] = r->buffer; + } + /* All user-facing BOs are staging only. Concurrent mmap writes cannot + * change code, input snapshots or firmware-visible output allocations. + */ + for (i = 0; i < user->count; i++) { + if (process->resources[i].permissions == 1) + memcpy(process->mappings[i].cpu, bos[i]->cpu, buffers[i].size); + else + memset(process->mappings[i].cpu, 0xff, buffers[i].size); + } + request.key = process->key; + request.deadline = jiffies + msecs_to_jiffies(user->timeout_ms ?: 5000); + ret = ane_h16_pending_insert(&ane->pending, &request, jiffies); + if (ret) + goto out; + call.key = request.key; + call.buffers = buffers; + call.buffer_count = user->count; + /* Custom BAR selectors/values have no validated process map yet. */ + ret = ane_h16_execute_encode(ane->cmd_buf->cpu, ANE_H16_EXECUTE_BASE_SIZE, &call); + if (ret) { + ane_h16_pending_remove(&ane->pending, &request); + goto out; + } + ane->waiting = &request; + /* Coherent allocations require ordering, not streaming-map sync calls. */ + wmb(); + dma_wmb(); + ret = ane_rtclient_command(ane, ane->cmd_buf, ANE_H16_EXECUTE_BASE_SIZE, + ANE_H16_EXECUTE, 7, user->timeout_ms ?: 5000); + ane->waiting = NULL; + if (ret || !request.terminal || request.status) { + ret = ret ?: -EIO; + ane_h16_pending_abort(&ane->pending, &request, ret); + atomic_set(&ane_t6021_quarantined, 1); + goto out; + } + dma_rmb(); + for (i = 0; i < user->count; i++) + if (process->resources[i].permissions == 2) + memcpy(bos[i]->cpu, process->mappings[i].cpu, buffers[i].size); + /* Private DMA mappings remain resident for the entire process lifetime, + * including after terminal failure or an uncertain transport outcome. + */ +out: + while (pinned) + kref_put(&bos[--pinned]->refcount, ane_t6021_bo_release); + mutex_unlock(&ane_t6021_fw_lock); + kfree(ios); + return ret; +} + static int ane_rtclient_procedure_call(struct ane_rtclient *ane, struct drm_file *file, const struct drm_ane_exec *user) @@ -1323,6 +1666,8 @@ static int ane_rtclient_procedure_call(struct ane_rtclient *ane, size_t cmd_size; int ret, i, pinned = 0; + if (ane->soc->platform) + return ane_rtclient_h16_call(ane, file, user); if (user->pad || user->count < 1 || user->count > DRM_ANE_MAX_BINDS || user->priority < 2 || user->priority > 7 || !fd) return -EINVAL; @@ -1451,6 +1796,8 @@ static int ane_t6021_bo_init_ioctl(struct drm_device *drm, void *data, struct ane_t6021_bo *bo; struct ane_rtclient *ane; + if (atomic_read(&ane_t6021_quarantined)) + return -EIO; if (args->pad || args->size == 0 || args->size > ANE_T6021_BO_MAX || !fd) return -EINVAL; @@ -1611,6 +1958,7 @@ static int ane_t6021_open(struct drm_device *drm, struct drm_file *file) if (!fd) return -ENOMEM; INIT_LIST_HEAD(&fd->bos); + INIT_LIST_HEAD(&fd->h16_processes); file->driver_priv = fd; return 0; } @@ -1619,13 +1967,19 @@ static void ane_t6021_postclose(struct drm_device *drm, struct drm_file *file) { struct ane_t6021_fd *fd = file->driver_priv; struct ane_t6021_bo *bo, *tmp; + struct ane_h16_process *process, *next; if (!fd) return; + mutex_lock(&ane_t6021_fw_lock); + /* Revoke per-file authority, retaining device-owned DMA allocations. */ + list_for_each_entry_safe(process, next, &fd->h16_processes, owner_node) + list_del_init(&process->owner_node); mutex_lock(&ane_t6021_bo_lock); list_for_each_entry_safe(bo, tmp, &fd->bos, node) ane_t6021_bo_drop(bo); mutex_unlock(&ane_t6021_bo_lock); + mutex_unlock(&ane_t6021_fw_lock); kfree(fd); file->driver_priv = NULL; } @@ -1921,6 +2275,13 @@ struct ane_rtclient_pd { struct device **pd_dev; struct device_link **pd_link; int count; + + /* T8112 power gate, kept in step with power-domains[0]. */ + struct notifier_block pwgate_nb; + void __iomem *pwgate_base; + void __iomem *pwgate; + bool pwgate_nb_added; + bool pwgate_opened; }; static LIST_HEAD(ane_rtclient_pd_list); @@ -1932,11 +2293,103 @@ static DEFINE_MUTEX(ane_rtclient_probe_guard_lock); static void ane_rtclient_pd_free(struct ane_rtclient_pd *pd) { list_del(&pd->list); + if (pd->pwgate_base) + iounmap(pd->pwgate_base); kfree(pd->pd_dev); kfree(pd->pd_link); kfree(pd); } +/* + * T8112 power gate. A word in the "set" window gates the ANE: bits 29:28 + * set (the word reads 0x30000000) is closed, both clear is open. It must be + * open before the ANE CPU power state (ane_sys_cpu) turns on and is closed + * again after that state turns off, with ane_sys, the parent, on both + * times. power-domains[0] is ane_sys_cpu, and genpd calls this notifier + * after ane_sys is on and before ane_sys_cpu is written (PRE_ON), and + * after ane_sys_cpu is off and before ane_sys goes off (OFF), which is that + * order. Only the two known values are written. Any other word fails the + * power-up without a write. + */ +#define ANE_PWGATE_CLOSED GENMASK(29, 28) +#define ANE_PWGATE_POLL_US 10 +#define ANE_PWGATE_TIMEOUT_US 100000 + +static int ane_rtclient_pwgate_notify(struct notifier_block *nb, + unsigned long action, void *data) +{ + struct ane_rtclient_pd *pd = + container_of(nb, struct ane_rtclient_pd, pwgate_nb); + u32 gate; + int ret; + + switch (action) { + case GENPD_NOTIFY_PRE_ON: + gate = readl(pd->pwgate); + if (!(gate & ANE_PWGATE_CLOSED)) + return NOTIFY_OK; + if (gate != ANE_PWGATE_CLOSED) { + dev_err(pd->dev, "power gate word %#x is not a known state\n", + gate); + return notifier_from_errno(-EIO); + } + writel(0, pd->pwgate); + ret = readl_poll_timeout_atomic(pd->pwgate, gate, + !(gate & ANE_PWGATE_CLOSED), + ANE_PWGATE_POLL_US, + ANE_PWGATE_TIMEOUT_US); + if (ret) { + writel(ANE_PWGATE_CLOSED, pd->pwgate); + dev_err(pd->dev, "power gate did not open (word %#x)\n", + gate); + return notifier_from_errno(ret); + } + pd->pwgate_opened = true; + return NOTIFY_OK; + case GENPD_NOTIFY_OFF: + if (!pd->pwgate_opened) + return NOTIFY_OK; + pd->pwgate_opened = false; + writel(ANE_PWGATE_CLOSED, pd->pwgate); + ret = readl_poll_timeout_atomic(pd->pwgate, gate, + (gate & ANE_PWGATE_CLOSED) == + ANE_PWGATE_CLOSED, + ANE_PWGATE_POLL_US, + ANE_PWGATE_TIMEOUT_US); + if (ret) + dev_warn(pd->dev, "power gate did not close (word %#x)\n", + gate); + return NOTIFY_OK; + default: + return NOTIFY_DONE; + } +} + +/* + * Register the power gate notifier on power-domains[0] before its device + * link is created: the link resumes the domain at once. + */ +static int ane_rtclient_pwgate_add(struct ane_rtclient *ane, + struct ane_rtclient_pd *pd) +{ + int ret; + + if (!ane->soc->pwgate_off || pd->pwgate_nb_added) + return 0; + if (!pd->pwgate_base) { + pd->pwgate_base = of_iomap(ane->dev->of_node, 2); + if (!pd->pwgate_base) + return -ENOMEM; + pd->pwgate = pd->pwgate_base + ane->soc->pwgate_off; + } + pd->pwgate_nb.notifier_call = ane_rtclient_pwgate_notify; + ret = dev_pm_genpd_add_notifier(pd->pd_dev[0], &pd->pwgate_nb); + if (ret) + return ret; + pd->pwgate_nb_added = true; + return 0; +} + static int ane_rtclient_attach_genpd(struct ane_rtclient *ane) { struct device *dev = ane->dev; @@ -1985,6 +2438,11 @@ static int ane_rtclient_attach_genpd(struct ane_rtclient *ane) goto out; } } + if (i == 0) { + err = ane_rtclient_pwgate_add(ane, pd); + if (err) + goto out; + } if (!pd->pd_link[i]) { if (!ane_rtclient_pinned) { if (!try_module_get(THIS_MODULE)) { @@ -2029,6 +2487,15 @@ static void ane_rtclient_detach_genpd(struct device *dev) for (i = count - 1; i >= 0; i--) { if (pd->pd_link[i]) device_link_del(pd->pd_link[i]); + /* + * genpd keeps a notifier past detach, so drop it first. + * The domain may then go off with the gate open, the + * state between the two power-up steps. + */ + if (i == 0 && pd->pwgate_nb_added) { + dev_pm_genpd_remove_notifier(pd->pd_dev[0]); + pd->pwgate_nb_added = false; + } if (pd->pd_dev[i]) dev_pm_domain_detach(pd->pd_dev[i], true); } @@ -2093,6 +2560,7 @@ static int ane_rtclient_probe_inner(struct platform_device *pdev, if (!ane->legacy_buffers) return -ENOMEM; ane->dev = dev; + INIT_LIST_HEAD(&ane->h16_processes); ane->soc = of_device_get_match_data(dev); platform_set_drvdata(pdev, ane); INIT_DELAYED_WORK(&ane->poll_work, ane_rtclient_post_boot); @@ -2140,9 +2608,10 @@ static int ane_rtclient_probe_inner(struct platform_device *pdev, pm_runtime_disable(dev); return -EPROBE_DEFER; } - /* T8112: macOS (type 0x70) opens PWGATE (bits 29:28 = 0) before - * the ps words. This driver only reads it: an engine read behind a - * closed gate is untested, so it refuses first. + /* T8112: the power gate notifier opened the gate before ane_sys_cpu + * turned on. A gate that still reads closed means the state was + * already on without it (no power-up ran), so refuse before any + * engine read. */ if (ane->soc->pwgate_off) { void __iomem *set = devm_of_iomap(dev, dev->of_node, 2, NULL); @@ -2335,14 +2804,13 @@ static int ane_rtclient_probe_inner(struct platform_device *pdev, * reboot. */ struct ane_legacy_buffer *command = ane->cmd_buf; + unsigned long query_deadline = jiffies + msecs_to_jiffies(3000); int qret; if (command) { memset(command->cpu, 0, SZ_16K); - qret = ane_rtclient_legacy_exchange(ane, - command, - 16, 0x03, - 1, 3000); + qret = ane_rtclient_legacy_exchange(ane, command, 16, 0x03, 1, + query_deadline); dev_dbg(dev, "LEGACY CONFIG_GET words %08x %08x result=%d (DMA remains held)\n", READ_ONCE(((u32 *)command->cpu)[1]), @@ -2483,9 +2951,16 @@ static int ane_rtclient_probe_inner(struct platform_device *pdev, static int ane_rtclient_probe(struct platform_device *pdev) { + const struct ane_t602x_soc *soc = of_device_get_match_data(&pdev->dev); bool hardware_touched = false; int ret; + if (!soc) + return -ENODEV; + /* Later generations cannot enter H14 boot or parameter paths. */ + if (soc->platform) + return ane_fw_platform_probe(pdev, soc->platform); + mutex_lock(&ane_rtclient_probe_guard_lock); if (ane_rtclient_probe_failed_dirty) { mutex_unlock(&ane_rtclient_probe_guard_lock); @@ -2514,8 +2989,14 @@ static int ane_rtclient_probe(struct platform_device *pdev) static void ane_rtclient_remove(struct platform_device *pdev) { + const struct ane_t602x_soc *soc = of_device_get_match_data(&pdev->dev); struct ane_rtclient *ane = platform_get_drvdata(pdev); + if (soc->platform) { + ane_fw_platform_remove(pdev); + return; + } + if (READ_ONCE(ane_t6021_perf_ane) == ane) WRITE_ONCE(ane_t6021_perf_ane, NULL); @@ -2526,11 +3007,21 @@ static void ane_rtclient_remove(struct platform_device *pdev) "remove HELD: no teardown — reboot reclaims\n"); } +static const struct ane_t602x_soc ane_h16_soc = { + .platform = &ane_h16_platform, +}; + +static const struct ane_t602x_soc ane_h17_soc = { + .platform = &ane_h17_platform, +}; + static const struct of_device_id ane_rtclient_of_match[] = { { .compatible = "apple,t6020-ane", .data = &ane_t6020_soc }, { .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,t6041-ane", .data = &ane_h16_soc }, + { .compatible = "apple,t8140-ane", .data = &ane_h17_soc }, { } }; MODULE_DEVICE_TABLE(of, ane_rtclient_of_match); @@ -2558,8 +3049,12 @@ static struct attribute *ane_t6021_stats_attrs[] = { static umode_t ane_t6021_stats_is_visible(struct kobject *kobj, struct attribute *attr, int n) { - struct ane_rtclient *ane = dev_get_drvdata(kobj_to_dev(kobj)); + struct device *dev = kobj_to_dev(kobj); + const struct ane_t602x_soc *soc = of_device_get_match_data(dev); + struct ane_rtclient *ane = dev_get_drvdata(dev); + if (soc->platform) + return 0; if (attr == &dev_attr_ane_stats.attr && !ane->stats_slots) return 0; return attr->mode; @@ -2588,8 +3083,41 @@ static struct platform_driver ane_rtclient_driver = { static int __init ane_rtclient_init(void) { + const struct of_device_id *match; + struct device_node *np; int ret; + /* platform_probe() powers a single genpd, and DMA configuration + * happens even earlier. Refuse later generations before registering + * the driver, including disabled nodes, so these core paths cannot + * precede the ownership and firmware preflight. These SoCs have one + * ANE generation; refusing registration cannot hide an H14 engine. + */ + for_each_matching_node_and_match(np, ane_rtclient_of_match, &match) { + const struct ane_t602x_soc *soc = match->data; + struct platform_device *pdev; + + if (!soc->platform) + continue; + if (soc->platform->owner == ANE_FW_OWNER_EXCLAVE) { + of_node_put(np); + pr_info("ane: H17 ANE: Linux exclave ownership handoff unavailable; refusing registration\n"); + return -EOPNOTSUPP; + } + pdev = of_find_device_by_node(np); + of_node_put(np); + if (!pdev) { + pr_info("ane: H16 ANE: firmware transport unvalidated; keeping disabled\n"); + return -EOPNOTSUPP; + } + ret = ane_fw_platform_preflight(pdev, soc->platform); + put_device(&pdev->dev); + if (ret) + return ret; + ane_rtclient_driver.driver_managed_dma = true; + break; + } + WRITE_ONCE(ane_rtclient_probe_failed_dirty, false); ret = platform_driver_register(&ane_rtclient_driver); @@ -2602,9 +3130,10 @@ module_init(ane_rtclient_init); static void __exit ane_rtclient_exit(void) { platform_driver_unregister(&ane_rtclient_driver); + ane_h16_backend_exit(); ane_t6021_trace_free(); } module_exit(ane_rtclient_exit); MODULE_LICENSE("Dual MIT/GPL"); -MODULE_DESCRIPTION("Apple Neural Engine (T6021/M2) installed module"); +MODULE_DESCRIPTION("Apple Neural Engine firmware driver with H16/H17 preflight"); diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index e4fab5e3225ff..63ce4037d0ca7 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -6,6 +6,7 @@ #include #include #include "ane_tm.h" +#include "ane_pm.h" #define ANE_TQ_COUNT 8 static const int TQ_PRTY_TABLE[ANE_TQ_COUNT] = { 0x1, 0x2, 0x3, 0x4, @@ -266,6 +267,7 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) struct ane_dart_scratch *scratch = ane->scratch; bool faulted = false; int err, status; + ktime_t deadline = ktime_add_ms(ktime_get(), 1000); lockdep_assert_held(&ane->engine_lock); ane_dart_mask(ane); @@ -280,6 +282,10 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) ane_tm_push_tq(ane, req); for (;;) { + if (ktime_compare(ktime_get(), deadline) >= 0) { + err = -ETIMEDOUT; + break; + } /* Latch-first completion poll. Engine register reads hang * the SoC (T8103) once a DART fault has landed, inside the * 1-microsecond completion poll and before any fault @@ -289,10 +295,13 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) * iteration's latch read and engine read. */ err = read_poll_timeout(ane_tm_poll_step, status, - status != 0, 1, 1000000, false, + status != 0 || ktime_compare(ktime_get(), deadline) >= 0, + 1, 1000000, false, ane, req, &finished); if (!err && status < 0) err = status; + if (!err && !status) + err = -ETIMEDOUT; if (ane_dart_faulted(ane, &fault_iova, &fault_status)) { faulted = true; if (ane->scratch_pages >= ANE_DART_SCRATCH_MAX) @@ -366,38 +375,18 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) * and return to accepting work. Only a failed reset preserves * resources until reboot. */ - if (ane_tm_recover(ane) < 0) { - if (ane->tm_retention) - dev_err(ane->dev, - "recovery failed; preserving resources until module reload or reboot (tm/tq file retained through the cycle: the latched task error parks the TM in place; rmmod+insmod restores service)\n"); - else - dev_err(ane->dev, - "recovery failed; preserving resources until reboot\n"); - } + if (ane_tm_recover(ane) < 0) + dev_err(ane->dev, + "recovery failed; submissions disabled, resources retained while DMA may be active; retry reset or reboot\n"); return err; } /* - * Bounded recovery after a failed task. The only reset this driver knows - * is the partition power cycle system sleep already performs on this - * hardware. With the several ANE power partitions attached as genpd - * devices (T8103 five, T6001 similar), gating happens on those devices; - * with a single domain attached directly to the device, on the device - * itself. Gating the partitions stops any DMA still fetching the dead - * task and clears the tm register file; ungating brings the engine back - * through the probe resume path (ane_tm_enable), then the task manager - * must report idle. BO mappings deliberately stay in place: they remain - * coherent through the cycle and valid for the next submit, and once the - * wedge clears, BO_FREE unmaps them through the normal path again. - * Callers hold engine_lock. - * - * T6001 note: its set0/base islands are - * firmware-locked (direct pmgr writes external-abort; see the SET block - * comment above) and hold the tm/tq file in retention through any - * genpd cycle - TQ_EN still reads 0x3000 after a 20 ms and a 2 s gate, - * and tasks dispatched afterwards complete but compute nondeterministic - * garbage. The idle-or-fresh poll below therefore fails on T6001 and - * recovery preserves until reboot instead of serving wrong data. + * Recovery runs with engine_lock and pm_lock held and one consumer PM + * reference. Suspend through runtime PM, just as autosuspend does, so the + * supplier references and the domain hierarchy are released together. + * Never use the system-sleep force helpers here: an in-use forced supplier + * retains RPM_ACTIVE, which prevents its parent domain from powering off. */ /* No engine MMIO unless the owning partitions read powered on (ACTUAL @@ -426,67 +415,60 @@ static int ane_ps_verify_on(struct ane_device *ane) return err; } +static bool ane_partitions_off(struct ane_device *ane) +{ + if (ane_ps_act(ane)) + return false; + + /* The SET window does not include the shared SYS_CPU parent. Its + * DART consumers suspend asynchronously after our references drop. + * Wait for every attached domain as well, so resuming the consumer + * cannot race that work and leave the TM register file powered. + */ + if (ane->pd_count == 1) + return !dev_pm_genpd_is_on(ane->dev); + for (int i = 0; i < ane->pd_count; i++) + if (dev_pm_genpd_is_on(ane->pd_dev[i])) + return false; + return true; +} + +static int ane_verify_off(void *ctx) +{ + struct ane_device *ane = ctx; + bool off; + int err; + + /* genpd may retain a shared or busy parent even after suspend succeeds. + * Only PMGR and provider state are safe to read while the engine is off. + */ + if (!ane->ps) + return -EOPNOTSUPP; + err = read_poll_timeout(ane_partitions_off, off, off, + 100, 100000, false, ane); + dev_info(ane->dev, "recovery: engine power-off actual=%#x rc=%d\n", + ane_ps_act(ane), err); + return err; +} + static int ane_pd_cycle(struct ane_device *ane) { - int err = 0; + int err; + lockdep_assert_held(&ane->pm_lock); ane->recovering = true; - if (ane->pd_count > 1) { - int gated = 0; - - for (int i = 0; i < ane->pd_count; i++) { - pm_runtime_get_noresume(ane->pd_dev[i]); - gated = i + 1; - dev_dbg(ane->dev, - "ANERD pd[%d] %s force_suspend begin (ps act %#x)\n", - i, dev_name(ane->pd_dev[i]), ane_ps_act(ane)); - err = pm_runtime_force_suspend(ane->pd_dev[i]); - dev_dbg(ane->dev, - "ANERD pd[%d] force_suspend -> %d (ps act %#x)\n", - i, err, ane_ps_act(ane)); - if (err) - break; - } - if (!err) - for (int i = 0; i < ane->pd_count; i++) { - dev_dbg(ane->dev, - "ANERD pd[%d] %s force_resume begin (ps act %#x)\n", - i, dev_name(ane->pd_dev[i]), - ane_ps_act(ane)); - err = pm_runtime_force_resume(ane->pd_dev[i]); - dev_dbg(ane->dev, - "ANERD pd[%d] force_resume -> %d (ps act %#x)\n", - i, err, ane_ps_act(ane)); - if (err) - break; - } - while (gated--) - pm_runtime_put_noidle(ane->pd_dev[gated]); - } else { - /* Pin a second usage ref for the cycle: force_suspend only - * marks needs_force_resume when a ref beyond the caller's - * one (submit ioctl or reset write) is held, and without - * that mark force_resume would leave the partition gated. - */ - pm_runtime_get_noresume(ane->dev); - dev_dbg(ane->dev, "ANERD dev force_suspend begin\n"); - err = pm_runtime_force_suspend(ane->dev); - dev_dbg(ane->dev, "ANERD dev force_suspend -> %d\n", err); - if (!err) { - dev_dbg(ane->dev, "ANERD dev force_resume begin\n"); - err = pm_runtime_force_resume(ane->dev); - dev_dbg(ane->dev, "ANERD dev force_resume -> %d\n", - err); - } - pm_runtime_put_noidle(ane->dev); - } + /* Release the performance request before the domains go down. */ + err = ane_perf_suspend(ane); + if (!err) + err = ane_pm_cycle(ane->dev, ane->pd_dev, ane->pd_count, + ane_verify_off, ane); ane->recovering = false; - return err; } /* - * Drain the task-manager state a timed-out task leaves behind when the + * Drain the task-manager state a timed-out task leaves behind (from + * omarchy-ane ane_tm_drain_retained by Joshua Warren, MIT) when the * tm/tq file survives the power cycle in retention (T6001; descriptor * tm_retention). T8103 never runs this: its cycle is a full POR of the * file, and the re-arm below starts it clean. @@ -601,23 +583,23 @@ int ane_tm_recover(struct ane_device *ane) return err; } - /* T6001 (tm_retention): the cycle did NOT clear the tm/tq file — - * the timed-out task's events and queue entry are still latched. - * Drain them, or the TM below never reads idle and recovery - * degrades to preserve-until-reboot. + /* On T600x the tm/tq file survives the acknowledged power-off in + * retention (TQ_EN reads 0x3000 after every resume, healthy or not, + * and PMGR reset pulses on the ANE domains do not clear it). Drain + * the retained state there; this is what recovers a failed task + * ("-5, finish lines=1"). Anything the drain cannot clear fails the + * idle check below and stays wedged. */ if (ane->tm_retention) ane_tm_drain_retained(ane); - /* Power-on reset cleared the tm register file; re-arm it exactly - * like the probe resume path does. - */ ane_tm_enable(ane, true); err = readl_poll_timeout(ane->engine + ANE_TM_BASE + TM_STATUS, status, (status & TM_IS_IDLE) || - status == ane->tm_status_fresh, + (ane->tm_status_known && + status == ane->tm_status_fresh), 100, 1000000); status = ane_rec_read32(ane, "TM_STATUS tm+0x54", ane->engine + ANE_TM_BASE + TM_STATUS); @@ -628,7 +610,7 @@ int ane_tm_recover(struct ane_device *ane) } if (atomic_xchg(&ane->wedged, 0)) { - module_put(THIS_MODULE); /* drop the wedge pin */ + module_put(THIS_MODULE); /* verified reset releases the wedge pin */ /* The power cycle above quiesced every transaction, so the * wedge-preserved mappings (dead BOs kept alive only to * stop IOVA teardown under active DMA) can now be unmapped diff --git a/drivers/accel/ane/boot.kunitconfig b/drivers/accel/ane/boot.kunitconfig new file mode 100644 index 0000000000000..e42cb95da6483 --- /dev/null +++ b/drivers/accel/ane/boot.kunitconfig @@ -0,0 +1,9 @@ +CONFIG_KUNIT=y +CONFIG_DRM=y +CONFIG_DRM_ACCEL=y +CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST=y +CONFIG_KASAN=y +CONFIG_KASAN_GENERIC=y +CONFIG_UBSAN=y +CONFIG_UBSAN_BOUNDS=y +CONFIG_UBSAN_SHIFT=y diff --git a/drivers/accel/ane/transport.kunitconfig b/drivers/accel/ane/transport.kunitconfig new file mode 100644 index 0000000000000..21888e4786283 --- /dev/null +++ b/drivers/accel/ane/transport.kunitconfig @@ -0,0 +1,9 @@ +CONFIG_KUNIT=y +CONFIG_DRM=y +CONFIG_DRM_ACCEL=y +CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST=y +CONFIG_KASAN=y +CONFIG_KASAN_GENERIC=y +CONFIG_KASAN_INLINE=y +CONFIG_UBSAN=y +CONFIG_UBSAN_BOUNDS=y diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 8fc8cb7f7a6ab..5744a4a8a9743 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -470,7 +470,14 @@ static void apple_atomic_commit_tail(struct drm_atomic_commit *state) dcp_retain_framebuffer(to_apple_crtc(old->crtc)->dcp, entry); } - drm_atomic_helper_commit_tail_rpm(state); + drm_atomic_helper_commit_modeset_disables(state->dev, state); + drm_atomic_helper_commit_modeset_enables(state->dev, state); + drm_atomic_helper_commit_planes(state->dev, state, + DRM_PLANE_COMMIT_ACTIVE_ONLY); + drm_atomic_helper_fake_vblank(state); + drm_atomic_helper_commit_hw_done(state); + drm_atomic_helper_wait_for_flip_done(state->dev, state); + drm_atomic_helper_cleanup_planes(state->dev, state); } static const struct drm_mode_config_helper_funcs apple_mode_config_helpers = { diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b6af560ffc50a..7b3a9a304f369 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -238,6 +238,11 @@ bool dcp_t6041_ext_enabled(void) #include "iomfb_v26_6_swap.h" #include "dcp-peer-v26_6.inc" +static bool t6041_fw_26_5; +module_param(t6041_fw_26_5, bool, 0444); +MODULE_PARM_DESC(t6041_fw_26_5, + "T6041: drive DCP firmware 26.5.2 with the desktop 26.6 interface (unqualified)"); + /* * The backlight maximum of a desktop 26.x panel whose node has no * apple,max-brightness: the J616s panel's user-accessible SDR maximum (ADT @@ -4623,6 +4628,15 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) if (ret >= 0 && compat_ret >= 0 && !strcmp(fw_str, "26.6.2") && !strcmp(compat_str, "26.6.2")) return DCP_FIRMWARE_V_26_6_DESKTOP; + if (ret >= 0 && compat_ret >= 0 && !strcmp(fw_str, "26.5.2") && + !strcmp(compat_str, "26.5.2")) { + if (t6041_fw_26_5) { + dev_warn(dev, "T6041 DCP firmware 26.5.2 is unqualified; trying the desktop 26.6 interface\n"); + return DCP_FIRMWARE_V_26_6_DESKTOP; + } + dev_err(dev, "T6041 display not started: DCP firmware 26.5.2 is unqualified (appledrm.t6041_fw_26_5=1 tries it)\n"); + return DCP_FIRMWARE_UNKNOWN; + } dev_err(dev, "T6041 display not started: DCP firmware %s (compat %s) is not 26.6.2\n", ret >= 0 ? fw_str : "missing", compat_ret >= 0 ? compat_str : "missing"); diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index e5a8c8e6cc700..eafbe6cac84d6 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -2159,3 +2159,39 @@ int parse_panel_edid_data(const void *blob, size_t len, const u8 **edid, size_t ret = parse(blob, len, &ctx); return ret ?: parse_panel_edid_value(&ctx, 0, &budget, true, edid, size); } +int parse_system_log_mnits_pairs(const void *blob, size_t size, + struct dcp_system_ev_mnits *entry) +{ + struct dcp_parse_ctx ctx = { .blob = blob, .len = size, .pos = 0 }; + s64 mnits = -1, idac = -1, timestamp = 0; + int ret = 0; + + if (size > U32_MAX) + return -EINVAL; + + while (round_up(ctx.pos, 4) + sizeof(u32) <= size) { + char *key = parse_string(&ctx); + + if (IS_ERR(key)) + break; + if (!strcmp(key, "mNits")) + ret = parse_int(&ctx, &mnits); + else if (!strcmp(key, "iDAC")) + ret = parse_int(&ctx, &idac); + else if (!strcmp(key, "timestamp")) + ret = parse_int(&ctx, ×tamp); + else + ret = skip(&ctx); + kfree(key); + if (ret) + break; + } + + if (mnits < 0 || mnits > U32_MAX) + return -EINVAL; + + entry->millinits = mnits; + entry->idac = idac < 0 ? 0 : idac; + entry->timestamp = timestamp; + return 0; +} diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index 5e573371e0072..e2cf7b3f86ca8 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -255,5 +255,7 @@ struct dcp_system_ev_mnits { int parse_system_log_mnits(struct dcp_parse_ctx *handle, struct dcp_system_ev_mnits *entry); +int parse_system_log_mnits_pairs(const void *blob, size_t size, + struct dcp_system_ev_mnits *entry); #endif diff --git a/drivers/gpu/drm/apple/systemep.c b/drivers/gpu/drm/apple/systemep.c index 44e239c6016b0..392c2ca58f312 100644 --- a/drivers/gpu/drm/apple/systemep.c +++ b/drivers/gpu/drm/apple/systemep.c @@ -87,6 +87,13 @@ static int powerlog_report(struct apple_epic_service *service, enum epic_subtype ret = parse(data, data_size, &parse_ctx); if (ret) { + if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && + !parse_system_log_mnits_pairs(data, data_size, &mnits)) { + dev_info(dcp->dev, "systemep: powerlog mNits %u.%03u iDAC %u\n", + mnits.millinits / 1000, mnits.millinits % 1000, + mnits.idac); + goto have_mnits; + } dev_warn(service->ep->dcp->dev, "systemep: failed to parse report: %d\n", ret); return ret; } @@ -100,6 +107,7 @@ static int powerlog_report(struct apple_epic_service *service, enum epic_subtype dev_dbg(dcp->dev, "systemep: mNits event: Nits: %u.%03u, iDAC: %u\n", mnits.millinits / 1000, mnits.millinits % 1000, mnits.idac); +have_mnits: if ((dcp->fw_compat == DCP_FIRMWARE_H17P && dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) || dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) { diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index e6b4d0c9a088f..c53abbd8e7ae7 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -216,5 +216,13 @@ module! { default: 1, description: "G16: validate CDM/VDM stream records", }, + t6041_serial_render: u32 { + default: 0, + description: "T6041 25F84 diagnostic workaround: admit one render lease at a time (0: normal concurrency)", + }, + t6041_fw_log: u32 { + default: 0, + description: "T6041 bring-up: enable the firmware's log at boot (main configuration +0x250 = 1, status A debug flags 3)", + }, }, } diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index addabd04fe701..0153a992b8b49 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -154,6 +154,10 @@ macro_rules! asahi_of_device_table { of::DeviceId::new(c"apple,agx-t6040"), ProbeConfig::G17(&hw::t6040::CONFIG) ), + ( + of::DeviceId::new(c"apple,agx-t6041"), + ProbeConfig::G17(&hw::t6041::CONFIG) + ), ( of::DeviceId::new(c"apple,agx-t8103"), ProbeConfig::Legacy(&hw::t8103::HWCONFIG) diff --git a/drivers/gpu/drm/asahi/g17/fw/compute.rs b/drivers/gpu/drm/asahi/g17/fw/compute.rs index b1afdad816b6b..211a9e419e976 100644 --- a/drivers/gpu/drm/asahi/g17/fw/compute.rs +++ b/drivers/gpu/drm/asahi/g17/fw/compute.rs @@ -26,6 +26,33 @@ pub(crate) const COMPUTE_KICK_EVENT_MASK: [u64; 4] = [0, 0, 4, 0]; const COMPUTE_REGISTERS: usize = 41; const COMPUTE_REGISTERS_MAX: usize = COMPUTE_REGISTERS + 1; +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum ComputeProgram { + G17P = 0, + V25F84 = 1, +} + +static PROGRAM: core::sync::atomic::AtomicU8 = + core::sync::atomic::AtomicU8::new(ComputeProgram::G17P as u8); + +impl ComputeProgram { + pub(crate) fn select(self) { + PROGRAM.store(self as u8, core::sync::atomic::Ordering::Relaxed); + } + + pub(crate) fn current() -> Self { + match PROGRAM.load(core::sync::atomic::Ordering::Relaxed) { + 1 => Self::V25F84, + _ => Self::G17P, + } + } +} + +const V25F84_REGISTERS: usize = 36; +const V25F84_CHECKPOINTS: [u16; 4] = [34, 35, 35, V25F84_REGISTERS as u16]; +const V25F84_UNK_0A599_FIRST: u64 = 0x0000_0132_0040_0020; + /// Validated per-command shader-context scratch request. /// /// The layout word is Apple's packed SCS layout: depth (bits 0:15), levels @@ -134,7 +161,10 @@ impl ScratchRequest { } fn checkpoints(self) -> [u16; 4] { - CHECKPOINTS.map(|count| count + u16::from(self.enabled())) + match ComputeProgram::current() { + ComputeProgram::G17P => CHECKPOINTS.map(|count| count + u16::from(self.enabled())), + ComputeProgram::V25F84 => V25F84_CHECKPOINTS, + } } } const ALT_REGISTERS: usize = 4; @@ -187,6 +217,15 @@ impl OperandState { r0a5c9: 0x1e000, size: 0x44000, }; + pub(crate) const FOUR_BY_TEN: OperandState = OperandState { + r10229: 0x78800, + r140a8: 0x7a800, + r10099: 0x3c405, + r10091: 0x78400, + r0a5c1: 0x0005, + r0a5c9: 0x3c000, + size: 0x80000, + }; } /// Checkpoints into the main register array, as entry counts: after the @@ -392,6 +431,61 @@ fn compute_registers(args: &ComputeArgs) -> Result<[RegisterWrite; COMPUTE_REGIS ]) } +fn compute_registers_25f84(args: &ComputeArgs) -> Result<[RegisterWrite; V25F84_REGISTERS]> { + let preempt = args.preempt_va; + let operand = args.operand_state_va; + let state = args.operand; + let key = work_key(args.context_id, args.work_state); + let ids = OBJECT_IDS.word(); + let intersection = args.intersection.words(); + + Ok([ + RegisterWrite::new(0x1a510, preempt), + RegisterWrite::new(0x1a420, args.cdm_va), + RegisterWrite::new(0x1a4d0, offset_va(preempt, PREEMPT_STATE[0])?), + RegisterWrite::new(0x1a4d8, offset_va(preempt, PREEMPT_STATE[1])?), + RegisterWrite::new(0x1a4e0, offset_va(preempt, PREEMPT_STATE[2])?), + RegisterWrite::new(0x1a4e8, offset_va(preempt, PREEMPT_STATE[3])?), + RegisterWrite::new(0x1a440, UNK_1A440), + RegisterWrite::new(0x1a458, UNK_1A458), + RegisterWrite::new(0x101d9, UNK_101D9), + RegisterWrite::new(0x1a089, intersection[0]), + RegisterWrite::new(0x1a091, intersection[1]), + RegisterWrite::new(0x1a059, intersection[2]), + RegisterWrite::new(0x1a061, intersection[3]), + RegisterWrite::new(0x1a0b9, intersection[4]), + RegisterWrite::new(0x1a0c1, intersection[5]), + RegisterWrite::new(0x101d1, args.scratch.size_word()), + RegisterWrite::new( + 0x0d479, + if args.intersection.auxiliary == 0 { + args.scratch.tail_word() + } else { + u64::from(args.intersection.auxiliary) + }, + ), + RegisterWrite::new(0x1a0e9, args.scratch.stack_word()), + RegisterWrite::new(0x107a1, args.scratch.window_word()), + RegisterWrite::new(0x0a599, V25F84_UNK_0A599_FIRST), + RegisterWrite::new(0x0d411, UNK_0D411), + RegisterWrite::new(0x1a540, ids), + RegisterWrite::new(0x014a9, ids), + RegisterWrite::new(0x0a351, ids), + RegisterWrite::new(0x10201, key), + RegisterWrite::new(0x10428, key), + RegisterWrite::new(0x14028, u64::from(args.free_list_slot)), + RegisterWrite::new(0x14070, args.usage_va | 1), + RegisterWrite::new(0x10229, offset_va(operand, state.r10229)?), + RegisterWrite::new(0x140a8, offset_va(operand, state.r140a8)?), + RegisterWrite::new(0x10099, offset_va(operand, state.r10099)?), + RegisterWrite::new(0x10091, offset_va(operand, state.r10091)?), + RegisterWrite::new(0x0a5c1, offset_va(operand, state.r0a5c1)?), + RegisterWrite::new(0x0a5c9, offset_va(operand, state.r0a5c9)?), + RegisterWrite::new(0x1a440, UNK_1A440_FINAL), + RegisterWrite::new(0x0a599, UNK_0A599), + ]) +} + /// The second array exchanges the operand-state regions of registers /// 0x10099/0x0a5c1 and 0x10091/0x0a5c9. fn alt_registers(args: &ComputeArgs) -> Result<[RegisterWrite; ALT_REGISTERS]> { @@ -506,6 +600,8 @@ impl ComputeDescriptor { const UNK_FB0: u16 = 0x1a; const UNK_FBA: u32 = 0xe0a0_0001; const UNK_FC5: u8 = 0x9f; + const UNK_FBA_25F84: u32 = 0x6c00_0001; + const UNK_FC5_25F84: u8 = 0x5f; /// Fills a descriptor cleared by `Object::initialize`. The unused firmware /// fields and padding retain that zero initialization. @@ -516,7 +612,7 @@ impl ComputeDescriptor { { return Err(EINVAL); } - let registers = compute_registers(args)?; + let program = ComputeProgram::current(); let alt_registers = alt_registers(args)?; let registers_va = offset_va(args.descriptor_va, Self::REGISTERS_OFFSET)?; let alt_registers_va = offset_va(args.descriptor_va, Self::ALT_REGISTERS_OFFSET)?; @@ -527,10 +623,17 @@ impl ComputeDescriptor { self.context_id = args.context_id.into(); self.work_state_va = args.work_state_va; self.checkpoints = args.scratch.checkpoints(); - // The enabled program prepends one register; disabled descriptors keep - // the same forty writes, trailer count and resume checkpoints. - let first = usize::from(!args.scratch.enabled()); - self.registers.set(registers_va, ®isters[first..])?; + match program { + ComputeProgram::G17P => { + let registers = compute_registers(args)?; + let first = usize::from(!args.scratch.enabled()); + self.registers.set(registers_va, ®isters[first..])?; + } + ComputeProgram::V25F84 => { + self.registers + .set(registers_va, &compute_registers_25f84(args)?)?; + } + } self.alt_registers.set(alt_registers_va, &alt_registers)?; self.preempt_va = args.preempt_va; self.cdm_end_va = args.cdm_end_va; @@ -552,8 +655,18 @@ impl ComputeDescriptor { self.timestamp_end_va = timestamp_end_va; self.unk_fb0 = Self::UNK_FB0; self.free_list_control_va = args.free_list_control_va; - self.unk_fba = Self::UNK_FBA; - self.unk_fc5 = Self::UNK_FC5; + match program { + ComputeProgram::G17P => { + self.unk_fba = Self::UNK_FBA; + self.unk_fc5 = Self::UNK_FC5; + } + ComputeProgram::V25F84 => { + self.unk_fba = Self::UNK_FBA_25F84; + self.unk_fbe[0] = 0x06; + self.unk_fc5 = Self::UNK_FC5_25F84; + self.unk_fc6[0] = 0x04; + } + } self.usage_va = args.usage_fw_va; self.context_generation = args.context_generation; Ok(()) diff --git a/drivers/gpu/drm/asahi/g17/fw/compute_pool.rs b/drivers/gpu/drm/asahi/g17/fw/compute_pool.rs index 0f0614f6155a1..8ce8807cd71c0 100644 --- a/drivers/gpu/drm/asahi/g17/fw/compute_pool.rs +++ b/drivers/gpu/drm/asahi/g17/fw/compute_pool.rs @@ -18,9 +18,22 @@ pub(crate) fn extra_bytes(active_cores: u32, scs_pages: u16) -> Result { Ok(extra) } +static BASE_BLOCKS: core::sync::atomic::AtomicUsize = + core::sync::atomic::AtomicUsize::new(COMPUTE_BLOCKS); + +pub(crate) fn set_base_blocks(blocks: usize) -> Result { + if blocks < COMPUTE_BLOCKS || blocks > PAGE_LIST_SIZE / (FREE_LIST_BLOCK_PAGES as usize * 8) { + return Err(EINVAL); + } + BASE_BLOCKS.store(blocks, core::sync::atomic::Ordering::Relaxed); + Ok(()) +} + pub(crate) fn required_blocks(active_cores: u32, scs_pages: u16) -> Result { let extra = extra_bytes(active_cores, scs_pages)?; - let bytes = extra.checked_add((COMPUTE_BLOCKS * FREE_LIST_BLOCK_SIZE) as u64) + let base = BASE_BLOCKS.load(core::sync::atomic::Ordering::Relaxed); + let bytes = extra + .checked_add((base * FREE_LIST_BLOCK_SIZE) as u64) .ok_or(EOVERFLOW)?; let blocks = usize::try_from(bytes.div_ceil(FREE_LIST_BLOCK_SIZE as u64)) .map_err(|_| EOVERFLOW)?; diff --git a/drivers/gpu/drm/asahi/g17/fw/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/initdata.rs index 3092e599caa84..387cebb28a368 100644 --- a/drivers/gpu/drm/asahi/g17/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/initdata.rs @@ -781,6 +781,15 @@ impl PerfGroup { } } } + + pub(crate) fn replicate_first_lane(&mut self, lanes: usize) { + for index in 0..PERF_STATES { + for lane in lanes.max(1)..PERF_LANES { + self.core_mv[index][lane] = self.core_mv[index][0]; + self.sram_mv[index][lane] = self.sram_mv[index][0]; + } + } + } } /// Returns the performance states selected by `map` from `opps`. diff --git a/drivers/gpu/drm/asahi/g17/fw/initdata/v25g83.rs b/drivers/gpu/drm/asahi/g17/fw/initdata/v25g83.rs index f4c3ee5db22e2..6e2453f77ab52 100644 --- a/drivers/gpu/drm/asahi/g17/fw/initdata/v25g83.rs +++ b/drivers/gpu/drm/asahi/g17/fw/initdata/v25g83.rs @@ -1,20 +1,5 @@ // SPDX-License-Identifier: GPL-2.0-only -//! Initialization data of the 25G83 firmware build (macOS 26.6, `mBoot-18000.161.10`). -//! -//! The M4 Pro (T6040) runs this build. It has the interface version of the A18 Pro's -//! 26A428 build and the same objects, with these differences: -//! -//! - [`HwData25G83`]: the A18 Pro's hardware data up to `0x2554`, eight bytes inserted before -//! `0x2570` and four more before `0x2614`, and the CS and AFR performance tables; -//! - [`PowerConfig25G83`]: the power configuration with two blocks removed (`0xa8` and `0xa0` -//! bytes), at bundle `+0x5380`, followed by the auxiliary data; -//! - region C and the power state ([`POWER_STATE_WORDS`]) with other values; -//! - one firmware instance carrying both roles, with a larger status B ([`private`]), five -//! separately allocated views and a firmware area ([`kernel_window`]). -//! -//! The constant contents were derived from the G16 encoders of Gravity Linux, which run this -//! firmware on the M4 Pro, by evaluating them for this SoC; see the commit that added them. use super::{ fill_words, perf_states, CompletionRingDescriptor, HwDataArgs, Opp, PerfGroup, @@ -107,6 +92,7 @@ pub(crate) struct HwDataArgs25G83<'a> { pub(crate) cs_opps: &'a [Opp], /// Operating points of the AFR clock domain. pub(crate) afr_opps: &'a [Opp], + pub(crate) chip: Option<&'a Chip>, } /// The hardware data of the 25G83 build, at the base of the bundle. @@ -300,8 +286,12 @@ impl HwData25G83 { } self.register_map[window.slot] = RegisterMapEntry::window(window); } - if !args.reserved_slots.is_empty() { - return Err(EINVAL); + for &slot in args.reserved_slots { + match used.get_mut(slot) { + Some(used) if !*used => *used = true, + _ => return Err(EINVAL), + } + self.register_map[slot] = RegisterMapEntry::reserved(); } self.chip_id = args.chip_id; @@ -336,6 +326,9 @@ impl HwData25G83 { } self.perf_a.fill(&states_a, 1); self.perf_b.fill(&states_b, 1); + if ext.chip.is_some_and(|chip| chip.perf_a_replicate_lanes) { + self.perf_a.replicate_first_lane(states_a[0].cells); + } for (index, state) in states_b.iter().enumerate() { self.perf_b_freq_mhz[index] = state.freq_mhz; self.perf_a_states[index] = perf.states_a[index].into(); @@ -344,7 +337,9 @@ impl HwData25G83 { self.perf_a_relative = perf.relative_a; self.perf_b_relative = perf.relative_b; self.unk_1848 = [0x3f82_8f5c; 11]; - self.cs_perf.fill(ext.cs_opps, perf.sram_min_mv)?; + if ext.chip.is_none_or(|chip| chip.cs_perf_table) { + self.cs_perf.fill(ext.cs_opps, perf.sram_min_mv)?; + } self.afr_perf.fill(ext.afr_opps, perf.sram_min_mv)?; self.unk_2544 = 5; @@ -375,16 +370,46 @@ impl HwData25G83 { self.unk_26c0 = 1; self.unk_26c4 = 1; self.unk_26f4 = 1; + // SAFETY: `HwData25G83` consists of integers only and has no padding, so any bytes are a + // valid value. + let bytes = unsafe { + core::slice::from_raw_parts_mut((self as *mut Self).cast::(), size_of::()) + }; + if let Some(chip) = ext.chip { + overlay_words(bytes, chip.hw_data_words)?; + } Ok(()) } } +fn overlay_words(bytes: &mut [u8], words: Words) -> Result { + for &(offset, value, repeat) in words { + for index in 0..repeat { + let at = offset + 4 * index; + bytes + .get_mut(at..at + 4) + .ok_or(EINVAL)? + .copy_from_slice(&value.to_le_bytes()); + } + } + Ok(()) +} + /// Power configuration control period, in 24 MHz clocks (8 ms). const PERIOD_CLOCKS: u32 = 200_000; /// Temperature sensors read by the die and MTR temperature limiters. const TEMP_SENSOR_MASK: u32 = 0x2a22_2aa2; -/// Offset of the per-chip leakage coefficients in the power configuration. +pub(crate) struct Chip { + pub(crate) max_power_mw: u32, + pub(crate) leakage: [u32; 56], + pub(crate) aon_table: &'static [u32], + pub(crate) hw_data_words: Words, + pub(crate) power_config_words: Words, + pub(crate) perf_a_replicate_lanes: bool, + pub(crate) cs_perf_table: bool, +} + const LEAKAGE_OFFSET: usize = 0x642c; /// Offset in the power configuration of the GPU address of the configuration's status (the /// configuration named by the root, `+0x80`). @@ -597,10 +622,12 @@ impl PowerConfig25G83 { self.0[AON_POINTER..AON_POINTER + 8].copy_from_slice(&aon_va.to_le_bytes()); self.0[ENTROPY..ENTROPY + 4].copy_from_slice(&entropy.to_le_bytes()); } + + pub(crate) fn apply_chip(&mut self, chip: &Chip) -> Result { + overlay_words(&mut self.0, chip.power_config_words) + } } -/// The AON temperature-source rows the power configuration names: the GPU cluster 0, GPU -/// cluster 1 and SoC sensors. pub(crate) const AON_TABLE: [u32; 9] = [ u32::from_be_bytes(*b"g0TR"), 0x006b_0001, diff --git a/drivers/gpu/drm/asahi/g17/fw/kick.rs b/drivers/gpu/drm/asahi/g17/fw/kick.rs index ca2b6604a302b..2a035524bdffb 100644 --- a/drivers/gpu/drm/asahi/g17/fw/kick.rs +++ b/drivers/gpu/drm/asahi/g17/fw/kick.rs @@ -507,10 +507,46 @@ impl KickEntry { } } +pub(crate) fn ksm_slot_descriptor( + ring_va: u64, + data_master: super::queue::DataMaster, + priority: u8, +) -> Result { + if ring_va & !RenderRegistration::ADDRESS_MASK != 0 || priority >= Policy::PRIORITIES { + return Err(EINVAL); + } + let term = (3 * (4 - u64::from(priority)) + 0x3fe).wrapping_shl(54); + Ok(((data_master as u64 + 1) << 60) | ring_va | term) +} + +#[derive(Copy, Clone, Debug)] +pub(crate) struct KsmQueue { + pub(crate) qid: u8, + pub(crate) descriptor: u64, +} + +impl KsmQueue { + pub(crate) fn new( + qid: u8, + ring_va: u64, + data_master: super::queue::DataMaster, + priority: u8, + ) -> Result { + if qid > QID_MAX { + return Err(EINVAL); + } + Ok(Self { + qid, + descriptor: ksm_slot_descriptor(ring_va, data_master, priority)?, + }) + } +} + /// The complete write-only installation of a fragment/tiling queue pair. /// Firmware must see both queues configured before either outer command. pub(crate) struct RenderRegistration { writes: [(usize, u64); 8], + queues: [KsmQueue; 2], } impl RenderRegistration { @@ -540,8 +576,7 @@ impl RenderRegistration { if qid > QID_MAX || va & !Self::ADDRESS_MASK != 0 { return Err(EINVAL); } - let completion = (3 * (4 - u64::from(priority)) + 0x3fe).wrapping_shl(54); - let payload = ((engine as u64 + 1) << 60) | va | completion; + let payload = ksm_slot_descriptor(va, engine, priority)?; let (low, high) = if qid < 64 { (1u64 << qid, 0) } else { @@ -554,10 +589,30 @@ impl RenderRegistration { (Self::VALID_LOW, low), ]); } - Ok(Self { writes }) + Ok(Self { + writes, + queues: [ + KsmQueue::new( + fragment.0, + fragment.1, + super::queue::DataMaster::Fragment, + priority, + )?, + KsmQueue::new( + tiling.0, + tiling.1, + super::queue::DataMaster::Tiling, + priority, + )?, + ], + }) } pub(crate) fn writes(&self) -> &[(usize, u64); 8] { &self.writes } + + pub(crate) fn queues(&self) -> &[KsmQueue; 2] { + &self.queues + } } diff --git a/drivers/gpu/drm/asahi/g17/fw/render.rs b/drivers/gpu/drm/asahi/g17/fw/render.rs index a6bc1704d1418..ba3980abf5f3a 100644 --- a/drivers/gpu/drm/asahi/g17/fw/render.rs +++ b/drivers/gpu/drm/asahi/g17/fw/render.rs @@ -70,6 +70,10 @@ impl Deflake { sub: [0xa0, 0x820], viewport: false, }; + pub(crate) const FOUR_CLUSTERS: Deflake = Deflake { + sub: [0x120, 0xda0], + viewport: false, + }; } /// The register programs of a firmware build's render descriptors. @@ -366,6 +370,8 @@ pub(crate) struct RenderArgs<'a> { pub(crate) fragment: RenderStage, /// Register programs of the firmware build. pub(crate) programs: RegisterPrograms, + /// Device/build policy for register 0x1c890 in V25G83-format arrays. + pub(crate) ta_mode_1: bool, /// Deflake-buffer layout of the GPU. pub(crate) deflake: Deflake, } @@ -686,7 +692,7 @@ fn ta_registers_25g83( push(find(0x1c880, 0)?); push(RegisterWrite::new(0x1c948, gtp(4)?)); push(RegisterWrite::new(0x1c888, gtp(5)?)); - push(RegisterWrite::new(0x1c890, 0)); + push(RegisterWrite::new(0x1c890, u64::from(args.ta_mode_1))); push(RegisterWrite::new(0x1c918, 0)); push(find(0x1c079, 0)?); push(find(0x1c9d8, 0)?); @@ -1563,3 +1569,149 @@ impl FragmentSlot { Ok(Some(table)) } } + +#[kunit_tests(asahi_g17_ta_mode)] +mod ta_mode_tests { + use super::*; + use crate::g17::fw::{ + compute::{IntersectionTables, ScratchRequest}, + render_rt::RayQueryStage, + variant::{Firmware, Variant, V25F84, V25G83, V26A428}, + }; + + fn selected(firmware: &Firmware) -> &'static Variant { + match firmware { + Firmware::Fixed(variant) => variant, + Firmware::Identified(builds) => { + assert_eq!(builds.len(), 1); + builds[0].variant + } + } + } + + #[test] + fn policy_is_local_to_the_admitted_t6041_build() { + let max = selected(&crate::hw::t6041::CONFIG.firmware); + let pro = selected(&crate::hw::t6040::CONFIG.firmware); + assert!(max.is_25f84()); + assert_eq!(max.programs, RegisterPrograms::V25G83); + assert!(max.ta_mode_1); + assert!(!pro.ta_mode_1); + assert!(!V25F84.ta_mode_1); + assert!(!V25G83.ta_mode_1); + assert!(!V26A428.ta_mode_1); + } + + fn fixture() -> (RenderPass, RenderResources) { + // SAFETY: These two types contain only integers, bools and structs of + // those types, for which all-zero bytes are valid. Required render + // dimensions and user-window addresses are filled below. + let mut pass: RenderPass = unsafe { core::mem::zeroed() }; + // SAFETY: RenderResources contains only integers and integer structs. + let mut resources: RenderResources = unsafe { core::mem::zeroed() }; + pass.width = 64; + pass.height = 64; + pass.layers = 1; + pass.utile_width = 32; + pass.utile_height = 32; + pass.sample_size = 4; + pass.vdm_va = USER_BASE + 0x10000; + resources.tilemap_va = USER_BASE + 0x20000; + resources.layermeta_va = USER_BASE + 0x30000; + resources.heapmeta_va = USER_BASE + 0x40000; + resources.tpc_va = USER_BASE + 0x50000; + resources.deflake_va = USER_BASE + 0x60000; + resources.gtp_va = core::array::from_fn(|i| USER_BASE + 0x70000 + i as u64 * 0x1000); + (pass, resources) + } + + fn args<'a>(pass: &'a RenderPass, resources: &'a RenderResources, scs: bool) -> RenderArgs<'a> { + let stage = RenderStage { + qid: 1, + descriptor_va: USER_BASE + 0x80000, + state_word: 1, + stamp_va: USER_BASE + 0x90000, + aux_stamp_va: USER_BASE + 0x90008, + }; + // Exercise the optional SCS entry even though the currently admitted + // 25F84/25G83 profiles disable ray traversal. + let ray = RayQueryStage { + intersection: IntersectionTables::NONE, + scratch: ScratchRequest::new(if scs { (1 << 32) | (1 << 24) | 8 } else { 0 }).unwrap(), + }; + RenderArgs { + pass, + resources, + ray_query: [ray; 2], + ordinal: 0, + ta: stage, + fragment: stage, + programs: RegisterPrograms::V25G83, + ta_mode_1: false, + deflake: Deflake::FOUR_CLUSTERS, + } + } + + #[test] + fn ta_mode_changes_exactly_one_write_with_or_without_scs() { + let (mut pass, resources) = fixture(); + for (width, height, layers) in [(64, 64, 1), (3456, 2234, 2)] { + pass.width = width; + pass.height = height; + pass.layers = layers; + let geometry = Geometry::new(&pass).unwrap(); + let words = PassWords::new(&pass).unwrap(); + for scs in [false, true] { + let mut args = args(&pass, &resources, scs); + let (before, count) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + args.ta_mode_1 = selected(&crate::hw::t6041::CONFIG.firmware).ta_mode_1; + let (after, new_count) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count, 83 + usize::from(scs)); + assert_eq!(new_count, count); + let slot = after[79 + usize::from(scs)].reg; + assert_eq!(slot, 0x14308); + let mut changed = 0; + for (old, new) in before.iter().zip(&after).take(count) { + let old = (old.reg, old.value); + let new = (new.reg, new.value); + if old.0 == 0x1c890 { + assert_eq!(old.1, 0); + assert_eq!(new, (0x1c890, 1)); + changed += 1; + } else { + // Includes every merge-buffer write and 0x1c9a8. + assert_eq!(old, new); + } + } + assert_eq!(changed, 1); + } + } + } + + #[test] + fn mode_does_not_change_fragment_or_g17p_arrays() { + let (pass, resources) = fixture(); + let geometry = Geometry::new(&pass).unwrap(); + let words = PassWords::new(&pass).unwrap(); + for scs in [false, true] { + let mut args = args(&pass, &resources, scs); + let (before, count) = fragment_registers_25g83(&args, &geometry, &words).unwrap(); + args.ta_mode_1 = true; + let (after, new_count) = fragment_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count, 91 + usize::from(scs)); + assert_eq!(new_count, count); + for (old, new) in before.iter().zip(&after).take(count) { + assert_eq!((old.reg, old.value), (new.reg, new.value)); + } + args.programs = RegisterPrograms::G17P; + args.ta_mode_1 = false; + let before = ta_registers(&args, &geometry, &words).unwrap(); + args.ta_mode_1 = true; + let after = ta_registers(&args, &geometry, &words).unwrap(); + for (old, new) in before.iter().zip(&after) { + assert_eq!((old.reg, old.value), (new.reg, new.value)); + assert_ne!({ new.reg }, 0x1c890); + } + } + } +} diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index 39c8cfcd77a2a..11a79fe992404 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -36,7 +36,22 @@ pub(crate) enum InitGraph { V25G83, } +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum QueueRegistration { + Firmware, + PoweredRenderPairs, + Mailbox, +} + +#[derive(Copy, Clone, PartialEq, Eq)] +pub(crate) enum FirmwareVersion { + V26A428, + V25G83, + V25F84, +} + /// The layouts and rules of one G17 firmware build. +#[derive(Copy, Clone)] pub(crate) struct Variant { /// The initialization graph. pub(crate) graph: InitGraph, @@ -49,8 +64,7 @@ pub(crate) struct Variant { pub(crate) qid_floor: usize, /// Host words of a queue's pointer block. pub(crate) pointers: PointerLayout, - /// The host registers each render pair through the GPU's MMIO queue ports. - pub(crate) mmio_pair_registration: bool, + pub(crate) registration: QueueRegistration, /// Render kick entries may name an MCache table. pub(crate) mcache: bool, /// Renders may set the few-primitives auxiliary framebuffer flag. @@ -65,6 +79,12 @@ pub(crate) struct Variant { pub(crate) lead_commands: bool, /// Register programs of the render descriptors. pub(crate) programs: super::render::RegisterPrograms, + /// Use 0x1c890 = 1 in V25G83-format tiling arrays (device/build policy). + pub(crate) ta_mode_1: bool, + pub(crate) compute: super::compute::ComputeProgram, + pub(crate) opening_record: bool, + pub(crate) split_firmware_area: bool, + pub(crate) version: FirmwareVersion, } /// A firmware build a SoC supports, identified by its loaded TEXT. @@ -98,13 +118,18 @@ pub(crate) const V26A428: Variant = Variant { producer: 0x40, recovery_target: Some(0x50), }, - mmio_pair_registration: true, + registration: QueueRegistration::PoweredRenderPairs, mcache: true, few_primitives: true, ray_traversal: true, fragment_busy: true, lead_commands: false, programs: super::render::RegisterPrograms::G17P, + ta_mode_1: false, + compute: super::compute::ComputeProgram::G17P, + opening_record: true, + split_firmware_area: false, + version: FirmwareVersion::V26A428, }; /// The M4 Pro firmware (25G83, `mBoot-18000.161.10`). @@ -122,7 +147,7 @@ pub(crate) const V25G83: Variant = Variant { }, // Whether this build tolerates the MMIO registration is unknown; the M4 Pro has only run // without it. - mmio_pair_registration: false, + registration: QueueRegistration::Firmware, mcache: false, // A fragment stage with the few-primitives flag hangs. few_primitives: false, @@ -133,9 +158,31 @@ pub(crate) const V25G83: Variant = Variant { fragment_busy: false, lead_commands: true, programs: super::render::RegisterPrograms::V25G83, + ta_mode_1: false, + compute: super::compute::ComputeProgram::G17P, + opening_record: true, + split_firmware_area: false, + version: FirmwareVersion::V25G83, }; +pub(crate) const V25F84: Variant = Variant { + version: FirmwareVersion::V25F84, + qid_floor: 0, + registration: QueueRegistration::Mailbox, + compute: super::compute::ComputeProgram::V25F84, + opening_record: false, + split_firmware_area: true, + ..V25G83 +}; + +impl Variant { + pub(crate) const fn is_25f84(&self) -> bool { + matches!(self.version, FirmwareVersion::V25F84) + } +} + const _: () = { assert!(super::queue::PointerBlock::valid_layout(&V26A428.pointers)); assert!(super::queue::PointerBlock::valid_layout(&V25G83.pointers)); + assert!(super::queue::PointerBlock::valid_layout(&V25F84.pointers)); }; diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index c8763f40871d1..56b39db036c2e 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -838,7 +838,7 @@ impl InitData { clusters, }; if variant.graph == super::fw::variant::InitGraph::V25G83 { - return self.build_25g83(&env, cfg, metrics, active_cores); + return self.build_25g83(&env, cfg, metrics, active_cores, variant); } self.map_register_windows(&env, cfg.windows)?; let tables = self.build_descriptor_tables(&env, abi::private::SIZE)?; diff --git a/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs b/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs index 670f4b96dcb76..9aeab2a4f7fb1 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs @@ -18,6 +18,7 @@ use kernel::{c_str, prelude::*}; struct Objects { views: [usize; 5], firmware_area: usize, + firmware_area_2: Option, power_state: usize, aon: usize, } @@ -30,6 +31,7 @@ impl InitData { cfg: &Config, metrics: &KernelObject, active_cores: u32, + variant: &crate::g17::fw::Variant, ) -> Result { self.status_a = v::private::STATUS_A; self.status_b = v::private::STATUS_B; @@ -39,9 +41,9 @@ impl InitData { let first_block = self.build_render_pool(env)?; self.build_compute_pools(env, first_block)?; let bundle = self.build_bundle(env, cfg, metrics)?; - let objects = self.build_25g83_objects(env)?; + let objects = self.build_25g83_objects(env, variant.split_firmware_area)?; self.views = Some(objects.views); - self.initialize_25g83(env, cfg, active_cores, &tables, &bundle, &objects)?; + self.initialize_25g83(env, cfg, active_cores, &tables, &bundle, &objects, variant)?; if cfg.uat_quirks.clean_tables { // Write back every host-built byte before the firmware may read it. for object in self.objects.iter_mut() { @@ -53,8 +55,7 @@ impl InitData { Ok(()) } - /// The views, the firmware area, the power-state object and the AON table. - fn build_25g83_objects(&mut self, env: &BuildEnv<'_>) -> Result { + fn build_25g83_objects(&mut self, env: &BuildEnv<'_>, split: bool) -> Result { use mmu::{PROT_FW_PRIV_RW as FP, PROT_FW_SHARED_RW as FS}; use CpuMap::WriteCombined as WC; let mut views = [0; 5]; @@ -63,12 +64,17 @@ impl InitData { } let firmware_area = self.add(env.fixed(v::kernel_window::FIRMWARE_AREA, mmu::UAT_PGSZ, FP, WC)?)?; + let firmware_area_2 = match split { + true => Some(self.add(env.dynamic(mmu::UAT_PGSZ, mmu::UAT_PGSZ as u64, FP, WC)?)?), + false => None, + }; let power_state = self.add(env.fixed(v::kernel_window::POWER_STATE, mmu::UAT_PGSZ, FS, WC)?)?; let aon = self.add(env.fixed(v::kernel_window::AON_TABLE, mmu::UAT_PGSZ, FP, WC)?)?; Ok(Objects { views, firmware_area, + firmware_area_2, power_state, aon, }) @@ -84,15 +90,25 @@ impl InitData { tables: &DescriptorTables, bundle: &BundleObjects, objects: &Objects, + variant: &crate::g17::fw::Variant, ) -> Result { let bundle_va = self.object(self.bundle)?.gpu_va(); let cluster_va = self.object(self.cluster)?.gpu_va(); let config_va = cluster_va + v::private::CONFIG as u64; let status_a_va = cluster_va + v::private::STATUS_A as u64; let status_b_va = cluster_va + v::private::STATUS_B as u64; - let aon_va = self.object(objects.aon)?.gpu_va(); + let chip = cfg.chip; + let aon_table = chip.map_or(v::AON_TABLE.as_slice(), |chip| chip.aon_table); + let aon_va = match aon_table.is_empty() { + true => 0, + false => self.object(objects.aon)?.gpu_va(), + }; let power_state_va = self.object(objects.power_state)?.gpu_va(); let firmware_area_va = self.object(objects.firmware_area)?.gpu_va(); + let firmware_area_2_va = match objects.firmware_area_2 { + Some(index) => self.object(index)?.gpu_va(), + None => firmware_area_va, + }; let mut view_va = [0; 5]; for (va, index) in view_va.iter_mut().zip(objects.views) { *va = self.object(index)?.gpu_va(); @@ -101,14 +117,28 @@ impl InitData { let opps = Self::opps(env.dev, cfg.opps, env.clusters)?; let cs_opps = Self::opp_table(env.dev, c_str!("apple,cs-opp"))?; let afr_opps = Self::opp_table(env.dev, c_str!("apple,afr-opp"))?; - let calibration = Calibration::read(env.dev)?; - calibration.check_opps(&opps)?; + let calibration = if chip.is_none() { + let calibration = Calibration::read(env.dev)?; + calibration.check_opps(&opps)?; + Some(calibration) + } else { + None + }; + let (perf, max_power_mw, leakage) = match (calibration.as_ref(), chip) { + (Some(calibration), None) => ( + &calibration.perf, + calibration.max_power_mw, + &calibration.leakage, + ), + (None, Some(chip)) => (cfg.perf, chip.max_power_mw, &chip.leakage), + _ => return Err(EINVAL), + }; let hw_args = abi::HwDataArgs { chip_id: cfg.chip_id, windows: cfg.windows, reserved_slots: cfg.reserved_slots, opps: &opps, - perf: &calibration.perf, + perf, completion_rings: bundle.completion_rings, qos_va: self.object(bundle.qos)?.gpu_va(), }; @@ -116,6 +146,7 @@ impl InitData { active_cores, cs_opps: &cs_opps, afr_opps: &afr_opps, + chip, }; // SAFETY: Plain C entropy source. let entropy = unsafe { kernel::bindings::get_random_u32() }; @@ -126,28 +157,29 @@ impl InitData { })?; self.object_mut(self.bundle)? .initialize::(v::POWER_CONFIG, |power| { - power.init( - config_va, - aon_va, - entropy, - calibration.max_power_mw, - &calibration.leakage, - ); + power.init(config_va, aon_va, entropy, max_power_mw, leakage); + if let Some(chip) = chip { + power.apply_chip(chip)?; + } Ok(()) })?; self.object_mut(self.region_c)? .initialize::(0, |region| { region.init(cfg.region_c); - region.max_power_mw = calibration.max_power_mw; + region.max_power_mw = max_power_mw; Ok(()) })?; - for (index, word) in v::AON_TABLE.iter().enumerate() { + for (index, word) in aon_table.iter().enumerate() { self.object_mut(objects.aon)?.write(index * 4, *word)?; } // Status A and B: only the boot words and the firmware-control pointers. + let mut status_a = abi::StatusBlock::new(); + if variant.is_25f84() && crate::module_parameters::t6041_fw_log.value() != 0 { + status_a.unk_0 = 3; + } self.object_mut(self.cluster)? - .write(v::private::STATUS_A, abi::StatusBlock::new())?; + .write(v::private::STATUS_A, status_a)?; self.object_mut(self.cluster)? .write(v::private::STATUS_B, abi::StatusBlock::new())?; // Status B keeps the A18 Pro's field offsets up to its recovery words. @@ -180,19 +212,24 @@ impl InitData { .initialize::(main_offset, |main| { main.init_primary(&args, &views); main.view_va = view_va; - main.firmware_area_va = [firmware_area_va; 2]; + main.firmware_area_va = [firmware_area_va, firmware_area_2_va]; main.unk_18 = (cluster_va + v::private::MAIN_HEADER as u64).to_le_bytes(); // The secondary role's words, on the single instance. main.unk_300 = 4; main.power_config_va = bundle_va + v::POWER_CONFIG as u64; main.unk_32c = 0; main.unk_344 = 0; + if variant.is_25f84() && crate::module_parameters::t6041_fw_log.value() != 0 { + main.log_enable = 1; + } Ok(()) })?; - self.object_mut(self.bundle)?.write( - main_offset + abi::MainConfig::CONTROL_RING, - abi::OpeningRecord::new(abi::Role::Primary), - )?; + if variant.opening_record { + self.object_mut(self.bundle)?.write( + main_offset + abi::MainConfig::CONTROL_RING, + abi::OpeningRecord::new(abi::Role::Primary), + )?; + } // The merged root. let root = abi::RootArgs { @@ -214,12 +251,11 @@ impl InitData { } } - // The opening control record is staged in slot 0. - for (offset, value) in [ - (0, 0), - (0x10, 0), - (abi::ChannelState::PRODUCER, abi::OPENING_PRODUCER), - ] { + let producer = match variant.opening_record { + true => abi::OPENING_PRODUCER, + false => 0, + }; + for (offset, value) in [(0, 0), (0x10, 0), (abi::ChannelState::PRODUCER, producer)] { self.object(self.cluster)? .word(self.state_offset(Role::Primary) + abi::CONTROL_STATE_OFFSET + offset)? .store(value, Ordering::Relaxed); diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 6495ad2d98c13..b96715eaae321 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -191,6 +191,7 @@ pub(crate) struct Config { pub(crate) fabric_bridge: bool, /// The SoC's values of region C. pub(crate) region_c: &'static fw::initdata::RegionCConfig, + pub(crate) chip: Option<&'static fw::initdata::v25g83::Chip>, /// Physical address of the firmware's per-slot recovery keys, read while the firmware is /// halted to attribute a fault; `None` where it is unknown (recovery then relies on the /// firmware's own blame). @@ -212,6 +213,7 @@ pub(crate) struct CoreLayout { pub(crate) operand_state: fw::compute::OperandState, /// A render's deflake buffer. pub(crate) deflake: fw::render::Deflake, + pub(crate) compute_blocks: usize, } /// Where a G17 target's crash log buffers live. @@ -1108,8 +1110,9 @@ impl Shared { self.crashed.store(true, Ordering::Release); dev_err!( self.dev.as_ref(), - "GPU firmware ({:?}) crashed, device lost\n", - role + "GPU firmware ({:?}) crashed, device lost (crash log {} bytes)\n", + role, + crashlog.map_or(0, |log| log.len()) ); // The GPU dev coredump support this used is gone; the crash log is not published. @@ -1147,6 +1150,9 @@ impl Gpu { None }; let variant = Self::firmware_variant(dev, &cfg.firmware)?; + variant.compute.select(); + fw::compute_pool::set_base_blocks(cfg.core_layout.compute_blocks) + .inspect_err(|_| dev_err!(dev.as_ref(), "Invalid compute pool size\n"))?; let id = regs.get_g17_id()?; if let Some(calibration) = calibration { calibration.check_cores(&id.core_masks)?; @@ -1450,16 +1456,27 @@ impl Gpu { session.uat.confirm_firmware_root_entries(root_entries)?; } let mailbox: *const Mailbox = &*session.primary.rtkit; - session.port.attach(session.init.port_views(mailbox)?, session.bridge.regs.clone())?; + session.port.attach( + session.init.port_views(mailbox)?, + session.bridge.regs.clone(), + shared.variant.registration, + )?; session.uat.mirror_secondary_root()?; if cfg.fabric_bridge { session.bridge.regs.enable_g17_gating()?; } let ack = shared.variant.init_ack; - session.primary.init(session.init.root_va(Role::Primary)?, ack)?; + let root_va = session.init.root_va(Role::Primary)?; + dev_info!( + dev.as_ref(), + "bring-up: initialization data built, publishing root {:#x}\n", + root_va + ); + session.primary.init(root_va, ack)?; if ack == fw::variant::InitAck::Status { Self::wait_for_init_accepted(dev, &session.init, &session.primary)?; } + dev_info!(dev.as_ref(), "bring-up: initialization data accepted\n"); if let Some(secondary) = session.secondary.as_mut() { secondary.init(session.init.root_va(Role::Secondary)?, ack)?; } @@ -1469,10 +1486,25 @@ impl Gpu { secondary.notify(MSG_POWER_ON_DONE)?; } } - Self::wait_for_opening(dev, &session.init, &session.primary, session.secondary.as_ref())?; + if shared.variant.opening_record { + Self::wait_for_opening( + dev, + &session.init, + &session.primary, + session.secondary.as_ref(), + )?; + dev_info!(dev.as_ref(), "bring-up: opening record retired\n"); + } else { + dev_info!( + dev.as_ref(), + "bring-up: no opening record staged; device-control counters {:?}\n", + session.init.control_counters()? + ); + } session .uat .activate_render_context(&session._render_global)?; + dev_info!(dev.as_ref(), "bring-up: firmware running\n"); Ok(firmware) } diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 8c405c8cfb90f..5c76384db68f5 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -91,8 +91,8 @@ unsafe impl Sync for Views {} #[pin_data] pub(super) struct Port { views: SetOnce, - /// Register access for tracing the core power state at the doorbell. regs: SetOnce, + registration: SetOnce, /// Compute work-ring slots reserved by publishers that have not exposed them yet. #[pin] rings: SpinLock<[u32; PRIORITIES]>, @@ -167,6 +167,7 @@ impl Port { pin_init!(Self { views: SetOnce::new(), regs: SetOnce::new(), + registration: SetOnce::new(), rings <- new_spinlock!([0; PRIORITIES], "g17::Port::rings"), qos <- new_spinlock!(qos::Accounting::new(), "g17::Port::qos"), rx: SetOnce::new(), @@ -187,17 +188,37 @@ impl Port { } /// Called once while the session is built, before any publisher can see the port. - pub(super) fn attach(&self, views: Views, regs: crate::regs::G17Resources) -> Result { - // SAFETY: The session's primary coprocessor owns the mailbox and outlives the port, and - // with it every use of the handle. + pub(super) fn attach( + &self, + views: Views, + regs: crate::regs::G17Resources, + registration: super::fw::variant::QueueRegistration, + ) -> Result { + // SAFETY: The session owns the mailbox and outlives every port user. let rx = unsafe { (*views.mailbox).rx_util_min_handle() }; - if self.views.populate(views) && self.regs.populate(regs) && self.rx.populate(rx) { + if self.views.populate(views) + && self.regs.populate(regs) + && self.registration.populate(registration) + && self.rx.populate(rx) + { Ok(()) } else { Err(EBUSY) } } + pub(super) fn register_queues(&self, queues: &[super::fw::kick::KsmQueue]) -> Result { + use super::fw::variant::QueueRegistration; + if self.registration.as_ref() != Some(&QueueRegistration::Mailbox) { + return Ok(()); + } + let regs = self.regs.as_ref().ok_or(ENODEV)?; + for queue in queues { + regs.register_ksm_queue(queue.qid, queue.descriptor)?; + } + Ok(()) + } + fn views(&self) -> Result<&Views> { self.views.as_ref().ok_or(ENODEV) } diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index ed73323e34e6f..5490825f8b486 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -62,6 +62,7 @@ fn wait_slice_ms(deadline_ns: u64, now_ns: u64) -> Result { } struct State { + serial_render: bool, active: u64, refs: [u8; cfg::RENDER_SLOTS], owners: [u64; cfg::RENDER_SLOTS], @@ -88,6 +89,7 @@ impl State { const MASK: u64 = (u64::MAX >> (64 - cfg::RENDER_SLOTS)) & !1; const fn new() -> Self { Self { + serial_render: false, active: 0, refs: [0; cfg::RENDER_SLOTS], owners: [0; cfg::RENDER_SLOTS], @@ -334,8 +336,15 @@ impl State { ) } + fn serial_busy(&self) -> bool { + self.serial_render && self.refs.iter().any(|&count| count != 0) + } + /// Whether `pick` would return a slot, without taking it. fn can_pick(&self, owner: u64, plan: Plan) -> bool { + if self.serial_busy() { + return false; + } let usable = |slot: usize| { self.owners[slot] == owner && (self.quarantined | self.kill_hold) & (1u64 << slot) == 0 @@ -357,6 +366,9 @@ impl State { } fn pick(&mut self, owner: u64, plan: Plan) -> Option { + if self.serial_busy() { + return None; + } match plan { Plan::Any => self.acquire(owner), Plan::Wait => None, @@ -466,6 +478,10 @@ impl Pool { GFP_KERNEL, ) } + pub(crate) fn serialize_render(&self) { + self.state.lock().serial_render = true; + } + /// Every pair or lease return, owner close and quarantine change. fn returned(&self) { self.released.notify_all(); diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index e1bda516ee102..2b954b7908ed1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -2004,6 +2004,7 @@ pub(crate) trait Host { ) -> Result; fn qos_cancel(&mut self, publication: qos::Publication) -> Result; fn publish_qid(&mut self, id: kick::Id) -> Result; + fn register_queue(&mut self, queue: &crate::g17::fw::kick::KsmQueue) -> Result; fn publish_outer(&mut self, priority: u8, slot: &crate::g17::fw::channels::WorkSlot) -> Result; fn notify_compute(&mut self, priority: u8, message: u64) -> Result; @@ -2211,9 +2212,16 @@ impl Queue { NATIVE_WAIT_STRIDE, record)?; wait_vas.push(address, GFP_KERNEL)?; } + let kick_ring_va = self.kick.low_va(); let prepared_kick = self.kick.prepare_entry(&kick_args)?; let mut producer; if first { + host.register_queue(&crate::g17::fw::kick::KsmQueue::new( + qid, + kick_ring_va, + DataMaster::Compute, + policy.priority(), + )?)?; producer = self.graph.first_descriptor(descriptor_high)?; host.prepare_compute_shared()?; packet.mark_published(); diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index d22c0f617f374..128b5d7e0d99e 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -158,6 +158,7 @@ impl Queue { fn prune_frontier(&mut self, index: usize) { let failure = &mut self.failures[index]; + let transient_ok = self.variant.is_25f84(); // 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) @@ -174,7 +175,14 @@ impl Queue { } // One earliest failed ordinal covers every later prefix without // retaining its packet, mappings, or every failed fence. - if status < 0 && failure.as_ref().is_none_or(|(first, _)| *sequence < *first) { + let transient = transient_ok + && [ECANCELED, ENODATA, EBUSY] + .iter() + .any(|error| error.to_errno() == status); + if status < 0 + && !transient + && failure.as_ref().is_none_or(|(first, _)| *sequence < *first) + { *failure = Some((*sequence, fences.completed.clone())); } false diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 2254118f18140..08eaf696a437b 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -457,6 +457,7 @@ impl Pair { aux_stamp_va: addresses.stamps[1][1], }, programs: self.variant.programs, + ta_mode_1: self.variant.ta_mode_1, deflake: deflake_layout, }; self.memory.graph.claim(ordinal)?; diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index dcd8d59e4c412..8e815d3a3c737 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -285,7 +285,8 @@ pub(super) fn service( host.recovery_mut().pending = None; let (listed, exact, fallback) = (entries.listed, entries.exact, entries.fallback); - let (cancelled, blame) = classify(host, entries, request.blamed, attribution); + let lenient = sources.spare_reason_zero && sources.reason == Some(0); + let (cancelled, blame) = classify(host, entries, request.blamed, attribution, lenient); if listed != 0 { pr_warn!( "G17: GPU recovery: {} commands were in flight ({} matched by stamp, {} by queue); they fail instead of completing\n", @@ -340,7 +341,7 @@ fn read_entries(host: &mut H) -> Entries { /// 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. -fn classify(queues: &mut Q, entries: Entries, blamed: Option, attribution: Attribution) -> (u128, bool) { +fn classify(queues: &mut Q, entries: Entries, blamed: Option, attribution: Attribution, lenient: bool) -> (u128, bool) { let mut guilty_qids = entries.guilty | blamed.map_or(0, |qid| 1u128 << qid); let cancelled = entries.cancelled; match attribution { @@ -389,6 +390,9 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att if unresolved || (count == 0 && collateral == 0 && !no_culprit) { return (0, blame); } + if lenient && count != 0 { + pr_warn!("G17: GPU recovery reason 0 is not a decoded fault; a first-time blamed VM stays usable\n"); + } let spared = queues.classify_work(&|status| { guilty[..count] .iter() @@ -396,7 +400,13 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att known .as_ref() .filter(|known| Arc::ptr_eq(known, status)) - .map(|_| Class::Guilty) + .map(|_| { + if lenient && status.reported_error() == 0 { + Class::Spared + } else { + Class::Guilty + } + }) }) .unwrap_or(Class::Spared) }); diff --git a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs index 38ad8612a0b99..fc910df58b370 100644 --- a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs +++ b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs @@ -17,6 +17,7 @@ pub(super) struct Source { pub(crate) struct Sources { pub(crate) reason: Option, + pub(crate) spare_reason_zero: bool, mask: u32, records: [Source; SLOTS], count: usize, @@ -52,6 +53,7 @@ impl Sources { pub(crate) fn sample(mask: u32, mut read: impl FnMut(usize) -> Option<(u64, u32)>) -> Self { let mut sources = Self { reason: None, + spare_reason_zero: false, mask, records: [Source::default(); SLOTS], count: 0, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 108c9fe19a462..605397ec795cf 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -213,7 +213,14 @@ impl Registry { buffers <- BufferIds::new(), metrics: Arc::new(MetricsIds::new(), GFP_KERNEL)?, qos_ids: QosIds::new()?, - admission: admission::Pool::with_waiters(kick::queue_limit(variant.qid_floor), queues, renders)?, + admission: { + let admission = admission::Pool::with_waiters(kick::queue_limit(variant.qid_floor), queues, renders)?; + if variant.is_25f84() && crate::module_parameters::t6041_serial_render.value() != 0 { + admission.serialize_render(); + pr_warn!("T6041 25F84: serial render admission enabled (one outstanding render lease)\n"); + } + admission + }, render: render::RenderState::new(clusters, deflake, descriptor_flags)?, identities: queue::Identities::new(), compute: { @@ -1390,6 +1397,9 @@ impl compute::Host for ComputeHost<'_> { fn publish_qid(&mut self, id: kick::Id) -> Result { self.qids.publish(id) } + fn register_queue(&mut self, queue: &super::fw::kick::KsmQueue) -> Result { + self.port.register_queues(core::slice::from_ref(queue)) + } fn publish_outer(&mut self, _priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { self.port.publish_compute(self.outer.take().ok_or(EIO)?, slot).map(|_| ()) } @@ -1440,6 +1450,9 @@ impl compute::Host for DirectHost<'_> { // An installed queue published its identity with its first command. Ok(()) } + 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 { self.port.publish_compute(self.outer.take().ok_or(EIO)?, slot).map(|_| ()) } diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 74eb6b7228c72..2c8f38f103a79 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -134,7 +134,9 @@ impl recovery::Memory for Service<'_> { self.firmware.init.host_recovery() } fn fault_sources(&self) -> Result { - self.firmware.init.fault_sources() + let mut sources = self.firmware.init.fault_sources()?; + sources.spare_reason_zero = self.firmware.variant.is_25f84(); + Ok(sources) } fn transition(&self, expected: u32, next: u32) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 6657f83e9e738..fc2e01be761ae 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -572,10 +572,14 @@ impl crate::g17::queue::render::Host for Host<'_> { /// check let the firmware gate the cores between the host's configuration /// writes while several clients installed their first pairs at once. fn install_pair(&mut self, registration: &crate::g17::fw::kick::RenderRegistration) -> Result { - // Firmware builds without MMIO registration install the pair from its queue - // configuration alone. - if !self.firmware.variant.mmio_pair_registration { - return Ok(()); + use crate::g17::fw::variant::QueueRegistration; + match self.firmware.variant.registration { + QueueRegistration::Firmware => return Ok(()), + QueueRegistration::Mailbox => { + self.firmware.port.register_queues(registration.queues())?; + return Ok(()); + } + QueueRegistration::PoweredRenderPairs => {} } if !self.registration_powered { self.firmware.acquire_registration_power()?; diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index 2650131a4a293..c54ffb5c208fe 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -14,6 +14,8 @@ const MAX_POWERZONES: usize = 5; pub(crate) mod t600x; pub(crate) mod t602x; pub(crate) mod t6040; +pub(crate) mod t6041; +mod t604x; pub(crate) mod t8103; pub(crate) mod t8112; pub(crate) mod t8140; diff --git a/drivers/gpu/drm/asahi/hw/t6040.rs b/drivers/gpu/drm/asahi/hw/t6040.rs index 11ed37a7c1ef8..bc59194378ea1 100644 --- a/drivers/gpu/drm/asahi/hw/t6040.rs +++ b/drivers/gpu/drm/asahi/hw/t6040.rs @@ -11,6 +11,7 @@ use crate::g17::fw::{ }; use crate::g17::{Config, CoreLayout, CrashBuffers, FixedBuffer, Identity}; use crate::hw::{GpuGen, GpuVariant}; +use super::t604x::{instances, window}; use crate::mmu::UatQuirks; /// Static configuration of the T6040 GPU. @@ -51,6 +52,7 @@ pub(crate) const CONFIG: Config = Config { native_gpu_permissions: true, }, region_c: ®ION_C, + chip: None, adopt_root_entries: false, fabric_bridge: false, // The firmware's per-slot recovery keys are not known for this build; recovery relies on @@ -104,44 +106,13 @@ pub(crate) const CONFIG: Config = Config { cores: Some((2, 20)), operand_state: fw::compute::OperandState::TWO_BY_TEN, deflake: fw::render::Deflake::TWO_CLUSTERS, + compute_blocks: fw::freelist::COMPUTE_BLOCKS, }, }; /// Chip identifier written to the hardware data. pub(crate) const CHIP_ID: u32 = 0x6040; -/// Base of the firmware MMIO aperture in the kernel window. -const MMIO_APERTURE: u64 = 0xffff_fc21_8000_0000; - -const fn window( - slot: usize, - phys: u64, - offset: u64, - size: u32, - unk_18: u64, - unk_20: u32, -) -> RegisterWindow { - RegisterWindow { - slot, - phys, - va: MMIO_APERTURE + offset, - size, - unk_18, - unk_20, - instances: 1, - phys_stride: 0, - } -} - -/// `window` repeated `instances` times, `phys_stride` apart in physical memory. -const fn instances(window: RegisterWindow, instances: u32, phys_stride: u64) -> RegisterWindow { - RegisterWindow { - instances, - phys_stride, - ..window - } -} - /// Register windows the firmware maps, by register-map slot. Slot 3 holds the four memory /// controllers (ADT /arm-io/mcc), slot 20 the four AFR blocks. pub(crate) const REGISTER_WINDOWS: [RegisterWindow; 25] = [ diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs new file mode 100644 index 0000000000000..40ae028eca940 --- /dev/null +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -0,0 +1,496 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +use crate::g17::fw::{ + self, + initdata::{v25g83, PerfConfig, RegionCConfig, RegisterWindow, PERF_STATES}, +}; +use crate::g17::{Config, CoreLayout, CrashBuffers, FixedBuffer, Identity}; +use crate::hw::{GpuGen, GpuVariant}; +use super::t604x::{instances, window}; +use crate::mmu::UatQuirks; + +pub(crate) const CONFIG: Config = Config { + chip_id: CHIP_ID, + identity: Identity { + family: 0xa, + variant: 4, + num_dies: 1, + gpu_variant: GpuVariant::C, + usc_generation: 3, + hal_generation: 200, + }, + uat_ias: 42, + uat_oas: 42, + secondary_root_offset: None, + crash_buffers: CrashBuffers::FirmwareData, + // Unverified placement; use the M4 Pro layout. + pm_metrics: FixedBuffer { + va: 0x10_0008_0000, + size: 0x8000, + }, + windows: ®ISTER_WINDOWS, + reserved_slots: &RESERVED_SLOTS, + perf: &PERF, + opps: OPPS, + uat_quirks: UatQuirks { + reserved_tables: true, + clean_tables: true, + page_tlbi: true, + handoff_lock: false, + handoff_slot: 0xffff_ffff, + native_gpu_permissions: true, + }, + region_c: ®ION_C, + chip: Some(&CHIP), + adopt_root_entries: false, + fabric_bridge: false, + recovery_slot_keys: None, + gpu_generation: GpuGen::G16, + firmware: fw::variant::Firmware::Identified(&[fw::variant::Build { + os_version: [26, 5, 2], + name: "macOS 26.5.2 (25F84, iBoot mBoot-18000.121.3)", + images: &[crate::fwid::FirmwareBuild { + name: "Apple GFX 25F84 for T6041 (normalized loaded image)", + text_size: 0x60000, + data_size: 0x138000, + entropy: [0x5983a, 0x5991d], + text_sha256: [ + 0x6d, 0xa4, 0xd4, 0x42, 0x35, 0x35, 0x14, 0x44, 0xf6, 0xec, 0x00, 0x33, 0xf1, 0x9c, + 0xbf, 0x98, 0xd3, 0x43, 0x91, 0x28, 0x83, 0xe4, 0xe2, 0x94, 0xc1, 0x8b, 0xb8, 0xb8, + 0xa3, 0xc1, 0x83, 0xe8, + ], + }], + // Experimental TA-mode workaround: reported on another J616C/25G83 + // implementation, not yet hardware-verified here on 25F84. Keep the + // shared firmware profiles (in particular M4 Pro's) unchanged. + variant: &fw::variant::Variant { + ta_mode_1: true, + ..fw::variant::V25F84 + }, + }]), + core_layout: CoreLayout { + cores: Some((4, 40)), + operand_state: fw::compute::OperandState::FOUR_BY_TEN, + deflake: fw::render::Deflake::FOUR_CLUSTERS, + compute_blocks: 160, + }, +}; + +pub(crate) const CHIP_ID: u32 = 0x6041; + +pub(crate) const REGISTER_WINDOWS: [RegisterWindow; 25] = [ + window(0, 0x5_0241_4000, 0x0, 0x4000, 0, 2), + instances( + window(3, 0x2_201c_4000, 0x8000, 0x1_8000, 0, 2), + 8, + 0x200_0000, + ), + window(4, 0x5_0244_c000, 0xd_0000, 0x4000, 0, 0), + window(9, 0x5_003d_0000, 0xd_8000, 0x4000, 0, 2), + window(10, 0x5_003c_0000, 0xe_0000, 0x4000, 0, 0), + window(11, 0x5_003d_8000, 0xe_8000, 0x4000, 0, 2), + window(12, 0x4_8565_c000, 0xf_0000, 0x4000, 0, 2), + window(14, 0x5_0040_0000, 0xf_8000, 0x1_0000, 0, 0), + window(15, 0x5_0cdc_0000, 0x11_0000, 0x4000, 0, 0), + window(17, 0x2_8800_0000, 0x11_8000, 0x2_1400, 0, 2), + instances( + window(20, 0x2_8b00_0000, 0x14_0000, 0x4_0000, 0, 2), + 4, + 0x20_0000, + ), + window(22, 0x2_8900_0000, 0x24_8000, 0x8000, 0, 2), + window(26, 0x2_88d0_4000, 0x25_8000, 0x8000, 0xd0_4000, 2), + window(28, 0x2_88d5_8000, 0x26_8000, 0x8000, 0xd5_8000, 2), + window(29, 0x2_88d1_0000, 0x27_8000, 0x4000, 0xd1_0000, 2), + window(31, 0x2_88d4_0000, 0x28_0000, 0x4000, 0xd4_0000, 2), + window(32, 0x2_88d6_0000, 0x28_8000, 0x2_0000, 0xd6_0000, 2), + window(33, 0x2_88d4_4000, 0x2b_0000, 0x4000, 0xd4_4000, 2), + window(34, 0x2_88d4_c000, 0x2b_8000, 0x200, 0xd4_c000, 2), + window(35, 0x2_88e0_0000, 0x2c_0000, 0x4000, 0xe0_0000, 2), + window(37, 0x2_88e4_0000, 0x2c_8000, 0x4000, 0xe4_0000, 2), + window(39, 0x2_88e0_8000, 0x2d_0000, 0x8000, 0, 2), + window(40, 0x2_88e1_c000, 0x2e_0000, 0x4000, 0xe1_c000, 2), + window(41, 0x2_88e1_f800, 0x2e_b800, 0x4000, 0, 2), + window(43, 0x2_88e6_0000, 0x2f_8000, 0x58, 0xe6_0000, 2), +]; + +const RESERVED_SLOTS: [usize; 14] = [2, 5, 6, 7, 8, 27, 30, 38, 42, 46, 47, 48, 49, 52]; + +pub(crate) const PERF: PerfConfig = PerfConfig { + states_a: [0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 15], + states_b: [0, 1, 2, 3, 4, 6, 7, 9, 11, 13, 15], + relative_a: [0, 10, 18, 25, 31, 40, 50, 62, 70, 78, 100], + relative_b: [0, 0, 22, 36, 47, 57, 68, 78, 84, 91, 100], + sram_min_mv: 810, +}; + +pub(crate) const OPPS: usize = 16; + +const _: () = { + let mut index = 0; + while index < PERF_STATES { + assert!((PERF.states_a[index] as usize) < OPPS); + assert!((PERF.states_b[index] as usize) < OPPS); + index += 1; + } +}; + +const MAX_POWER_MW: u32 = 129_702; + +const REGION_C: RegionCConfig = RegionCConfig { + unk_54: 0x0fa0, + unk_78: [1, 0, 0], + max_power_mw: MAX_POWER_MW, + unk_9c: 0, + unk_a0: 0, + unk_7c4: 1500, + unk_9e0: [ + 1, + 0x0102_0200, + 0x010a_2801, + 0x2802_0101, + 0x0101_010a, + 0x010a_2802, + 0x2801_0101, + 0x0001_010a, + ], +}; + +const CHIP: v25g83::Chip = v25g83::Chip { + max_power_mw: MAX_POWER_MW, + leakage: { + let mut words = [0; 56]; + words[0] = 0x44f9_c000; + words[1] = 0x44f7_2000; + words[2] = 0x44f4_b000; + words[3] = 0x44f1_5000; + words[32] = 0x43e4_0000; + words[33] = 0x43e4_0000; + words[34] = 0x43e4_0000; + words[35] = 0x43e4_0000; + words[52] = 0x4404_0000; + words[54] = 0x43df_8000; + words + }, + aon_table: &[], + hw_data_words: HW_DATA_WORDS, + power_config_words: POWER_CONFIG_WORDS, + perf_a_replicate_lanes: true, + cs_perf_table: false, +}; + +const HW_DATA_WORDS: &[(usize, u32, usize)] = &[ + (0xe0, 0x2008, 1), + (0xe8, 0x20080000, 1), + (0xf4, 0x2008, 1), + (0xf8, 0x24cb, 1), + (0xfc, 0xc98a2cfa, 1), + (0x100, 0xf4f624cb, 1), + (0x104, 0x1877e917, 1), + (0x108, 0x38d924cb, 1), + (0x10c, 0xbdab0000, 1), + (0x2d8, 0xfff82000, 1), + (0x2dc, 0xd32d2cdb, 1), + (0x2e0, 0xf5002000, 1), + (0x2e4, 0x21dae926, 1), + (0x2e8, 0x38b62000, 1), + (0x2ec, 0xc7420008, 1), + (0x3e0, 0x7fe0, 1), + (0x3e8, 0x7fe00000, 1), + (0x3f4, 0x7fe0, 1), + (0x3f8, 0x8000, 1), + (0x400, 0x80000000, 1), + (0x40c, 0x8000, 1), + (0x5d8, 0x4b232645, 1), + (0x5dc, 0xe98, 1), + (0x5e0, 0xd5a2ea5f, 1), + (0x5e4, 0x40003fff, 1), + (0x5e8, 0xca5e4000, 1), + (0x5ec, 0x4000f5a2, 1), + (0xf6c, 0x1, 1), + (0xf8c, 0xff, 1), + (0xfac, 0x1, 1), + (0xfb8, 0x1d, 1), + (0x2594, 0x2e0000, 1), + (0x2610, 0x1, 1), +]; + +const POWER_CONFIG_WORDS: &[(usize, u32, usize)] = &[ + (0x0, 0x1, 1), + (0x44, 0xc, 1), + (0x9c, 0x43a90000, 1), + (0x200, 0x1, 1), + (0x208, 0x162, 1), + (0x210, 0xd89165f9, 1), + (0x218, 0x1254c, 1), + (0x698, 0xd8917807, 1), + (0x69c, 0x13, 1), + (0x6a8, 0x129a8, 1), + (0x728, 0x4a714, 1), + (0x7a8, 0x4a714, 1), + (0x920, 0x3dd00000, 1), + (0x9ec, 0xbbfca403, 1), + (0x9f0, 0x28, 1), + (0xa70, 0x4, 1), + (0xa7c, 0x0, 1), + (0xa84, 0x3f800000, 1), + (0xa8c, 0x3e0b4396, 1), + (0xa9c, 0x3e99999a, 1), + (0xaa8, 0x28, 1), + (0xab8, 0x43b10000, 1), + (0xac0, 0x162, 1), + (0xad0, 0x0, 1), + (0xae0, 0xc7fca200, 1), + (0xaf0, 0x3e8, 1), + (0xafc, 0x3f800000, 1), + (0xb00, 0x3e0b4396, 1), + (0xb04, 0x3e99999a, 1), + (0xb08, 0x162, 1), + (0xb2c, 0x2, 1), + (0xb88, 0x42a00000, 1), + (0xb90, 0x7, 1), + (0xbc8, 0x3f7eb852, 1), + (0xbcc, 0x3ba3d70a, 1), + (0xbd0, 0x3f64c986, 1), + (0xbd4, 0x403ea7f0, 1), + (0x21f4, 0x42200000, 1), + (0x2210, 0x28, 1), + (0x2264, 0x1020, 1), + (0x226c, 0x2a222aa2, 1), + (0x2294, 0x40baaaaa, 1), + (0x22a4, 0x42080000, 1), + (0x22b0, 0x28, 1), + (0x22c8, 0x1020, 1), + (0x2868, 0x389d8, 1), + (0x2874, 0x154, 1), + (0x28d8, 0x47fd5300, 1), + (0x29bc, 0x74, 1), + (0x29c8, 0x3f772c23, 1), + (0x29d0, 0x3d0d3dcb, 1), + (0x29d8, 0x3cf5c290, 1), + (0x29e8, 0x3f19999a, 1), + (0x2a04, 0x4304ad79, 1), + (0x2a0c, 0x162, 1), + (0x2a2c, 0xc7fd10a9, 1), + (0x2a44, 0x3f772c23, 1), + (0x2a48, 0x3d0d3dcb, 1), + (0x2a4c, 0x3cf5c290, 1), + (0x2a50, 0x3f19999a, 1), + (0x2a54, 0x162, 1), + (0x2b18, 0x2ef94, 2), + (0x2b20, 0x2e89, 1), + (0x2b24, 0xe36, 1), + (0x2b40, 0x1, 1), + (0x2b94, 0x46023400, 1), + (0x2b9c, 0x208d, 1), + (0x2bc4, 0x47800000, 1), + (0x2bcc, 0x3e8, 1), + (0x2be8, 0x208d, 1), + (0x2c40, 0x28, 1), + (0x2c88, 0x3e8, 1), + (0x2cec, 0x1, 1), + (0x2cf0, 0xf, 1), + (0x2cf4, 0x3, 1), + (0x2cfc, 0x6, 1), + (0x2f0c, 0x2a222aa2, 1), + (0x3140, 0x29, 1), + (0x3144, 0x24dd, 1), + (0x3148, 0x4, 1), + (0x314c, 0x20, 1), + (0x3150, 0x29, 1), + (0x3154, 0x10d2c39d, 1), + (0x315c, 0x1d441, 1), + (0x31e0, 0x29, 1), + (0x31e4, 0x24a0, 1), + (0x31e8, 0x4, 1), + (0x31ec, 0x20, 1), + (0x31f0, 0x29, 1), + (0x31f4, 0x10f5cfb4, 1), + (0x31fc, 0x1d4d8, 1), + (0x3230, 0x29, 1), + (0x3234, 0x24ba, 1), + (0x3238, 0x4, 1), + (0x323c, 0x20, 1), + (0x3240, 0x29, 1), + (0x3244, 0x10fe2d62, 1), + (0x324c, 0x1d554, 1), + (0x3280, 0x28, 1), + (0x3284, 0x245c, 1), + (0x3288, 0x4, 1), + (0x328c, 0x20, 1), + (0x3290, 0x28, 1), + (0x3294, 0x10ec3bb1, 1), + (0x329c, 0x1d5bc, 1), + (0x32d0, 0x28, 1), + (0x32d4, 0x246e, 1), + (0x32d8, 0x4, 1), + (0x32dc, 0x20, 1), + (0x32e0, 0x29, 1), + (0x32e4, 0x1101cc20, 1), + (0x32ec, 0x1d640, 1), + (0x3320, 0x28, 1), + (0x3324, 0x2439, 1), + (0x3328, 0x4, 1), + (0x332c, 0x20, 1), + (0x3330, 0x28, 1), + (0x3334, 0x10f01dbd, 1), + (0x333c, 0x1d6dd, 1), + (0x33c0, 0x29, 1), + (0x33c4, 0x2497, 1), + (0x33c8, 0x4, 1), + (0x33cc, 0x20, 1), + (0x33d0, 0x29, 1), + (0x33d4, 0x111077fe, 1), + (0x33dc, 0x1d847, 1), + (0x3460, 0x29, 1), + (0x3464, 0x2480, 1), + (0x3468, 0x4, 1), + (0x346c, 0x20, 1), + (0x3470, 0x29, 1), + (0x3474, 0x110f91ba, 1), + (0x347c, 0x1d8fa, 1), + (0x3500, 0x28, 1), + (0x3504, 0x243a, 1), + (0x3508, 0x4, 1), + (0x350c, 0x20, 1), + (0x3510, 0x28, 1), + (0x3514, 0x10f2bfe8, 1), + (0x351c, 0x1d9a7, 1), + (0x3550, 0x28, 1), + (0x3554, 0x246d, 1), + (0x3558, 0x4, 1), + (0x355c, 0x20, 1), + (0x3560, 0x28, 1), + (0x3564, 0x113b3172, 1), + (0x356c, 0x1da43, 1), + (0x35a0, 0x28, 1), + (0x35a4, 0x2483, 1), + (0x35a8, 0x4, 1), + (0x35ac, 0x20, 1), + (0x35b0, 0x29, 1), + (0x35b4, 0x114027af, 1), + (0x35bc, 0x1dace, 1), + (0x3640, 0x28, 1), + (0x3644, 0x2486, 1), + (0x3648, 0x4, 1), + (0x364c, 0x20, 1), + (0x3650, 0x29, 1), + (0x3654, 0x112421ab, 1), + (0x365c, 0x1db07, 1), + (0x36e0, 0x29, 1), + (0x36e4, 0x24ce, 1), + (0x36e8, 0x4, 1), + (0x36ec, 0x20, 1), + (0x36f0, 0x29, 1), + (0x36f4, 0x114de7b5, 1), + (0x36fc, 0x1dbaa, 1), + (0x3730, 0x29, 1), + (0x3734, 0x24a1, 1), + (0x3738, 0x4, 1), + (0x373c, 0x20, 1), + (0x3740, 0x29, 1), + (0x3744, 0x11342213, 1), + (0x374c, 0x1dc2e, 1), + (0x3780, 0x28, 1), + (0x3784, 0x2446, 1), + (0x3788, 0x4, 1), + (0x378c, 0x20, 1), + (0x3790, 0x28, 1), + (0x3794, 0x111ec867, 1), + (0x379c, 0x1dcb7, 1), + (0x37d0, 0x28, 1), + (0x37d4, 0x2453, 1), + (0x37d8, 0x4, 1), + (0x37dc, 0x20, 1), + (0x37e0, 0x29, 1), + (0x37e4, 0x11273f2d, 1), + (0x37ec, 0x1dd49, 1), + (0x3820, 0x28, 1), + (0x3824, 0x2470, 1), + (0x3828, 0x4, 1), + (0x382c, 0x20, 1), + (0x3830, 0x28, 1), + (0x3834, 0x1131becf, 1), + (0x383c, 0x1ddc8, 1), + (0x38c0, 0x29, 1), + (0x38c4, 0x249c, 1), + (0x38c8, 0x4, 1), + (0x38cc, 0x20, 1), + (0x38d0, 0x29, 1), + (0x38d4, 0x1153d78e, 1), + (0x38dc, 0x1df60, 1), + (0x3960, 0x29, 1), + (0x3964, 0x2484, 1), + (0x3968, 0x4, 1), + (0x396c, 0x20, 1), + (0x3970, 0x29, 1), + (0x3974, 0x114b8bd5, 1), + (0x397c, 0x1dfe3, 1), + (0x3a00, 0x29, 1), + (0x3a04, 0x2522, 1), + (0x3a08, 0x4, 1), + (0x3a0c, 0x20, 1), + (0x3a10, 0x29, 1), + (0x3a14, 0x116ebefa, 1), + (0x3a1c, 0x1e077, 1), + (0x3a50, 0x29, 1), + (0x3a54, 0x2494, 1), + (0x3a58, 0x4, 1), + (0x3a5c, 0x20, 1), + (0x3a60, 0x29, 1), + (0x3a64, 0x11455238, 1), + (0x3a6c, 0x1e0d8, 1), + (0x3aa0, 0x29, 1), + (0x3aa4, 0x24a1, 1), + (0x3aa8, 0x4, 1), + (0x3aac, 0x20, 1), + (0x3ab0, 0x29, 1), + (0x3ab4, 0x1157064b, 1), + (0x3abc, 0x1e165, 1), + (0x3b1c, 0x2522, 1), + (0x3b20, 0x4, 1), + (0x3b24, 0x20, 1), + (0x3b28, 0x29, 1), + (0x3b2c, 0x116cd390, 1), + (0x3b34, 0x1dbf1, 1), + (0x3b40, 0x29, 1), + (0x3b44, 0x34, 1), + (0x3b5c, 0x2a222aa2, 1), + (0x62c4, 0x1000000, 1), + (0x62cc, 0x1010202, 1), + (0x62d0, 0x1010a28, 1), + (0x62d4, 0xa280201, 1), + (0x62d8, 0x2010101, 1), + (0x62dc, 0x1010a28, 1), + (0x62e0, 0xa280101, 1), + (0x62e4, 0x45000101, 1), + (0x62e8, 0x4000200, 1), + (0x62f4, 0x4a000000, 1), + (0x62f8, 0x100, 1), + (0x6304, 0xd7000000, 1), + (0x6308, 0x29, 1), + (0x6328, 0x67325452, 1), + (0x632c, 0x67335452, 1), + (0x6360, 0xf, 1), + (0x63c8, 0x1, 1), + (0x63cc, 0xd88be35c, 1), + (0x63d0, 0x13, 1), + (0x63d8, 0x13, 1), + (0x63dc, 0xd891fc7b, 1), + (0x63e0, 0x13, 1), + (0x63e4, 0xd8633257, 1), + (0x63e8, 0x13, 1), + (0x63ec, 0xd863f8ef, 1), + (0x63f0, 0x13, 1), + (0x63f4, 0xd8903ed2, 1), + (0x63f8, 0x13, 1), + (0x63fc, 0xd89165f9, 1), + (0x6400, 0x13, 1), + (0x6404, 0xd891fc7b, 1), + (0x6408, 0x13, 1), + (0x6414, 0xab2ab62, 1), + (0x6418, 0x7, 1), + (0x641c, 0x30d40, 1), + (0x6428, 0x1, 1), + (0x650c, 0x89778246, 1), +]; diff --git a/drivers/gpu/drm/asahi/hw/t604x.rs b/drivers/gpu/drm/asahi/hw/t604x.rs new file mode 100644 index 0000000000000..961cef76cf4aa --- /dev/null +++ b/drivers/gpu/drm/asahi/hw/t604x.rs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +use crate::g17::fw::initdata::RegisterWindow; + +const MMIO_APERTURE: u64 = 0xffff_fc21_8000_0000; + +pub(super) const fn window( + slot: usize, + phys: u64, + offset: u64, + size: u32, + unk_18: u64, + unk_20: u32, +) -> RegisterWindow { + RegisterWindow { + slot, + phys, + va: MMIO_APERTURE + offset, + size, + unk_18, + unk_20, + instances: 1, + phys_stride: 0, + } +} + +pub(super) const fn instances(window: RegisterWindow, instances: u32, phys_stride: u64) -> RegisterWindow { + RegisterWindow { + instances, + phys_stride, + ..window + } +} diff --git a/drivers/gpu/drm/asahi/hw/t8140.rs b/drivers/gpu/drm/asahi/hw/t8140.rs index 47dc4d583a5fc..3bbc698889997 100644 --- a/drivers/gpu/drm/asahi/hw/t8140.rs +++ b/drivers/gpu/drm/asahi/hw/t8140.rs @@ -51,6 +51,7 @@ pub(crate) const CONFIG: Config = Config { opps: OPPS, uat_quirks: crate::mmu::UatQuirks::DEFAULT, region_c: &crate::g17::fw::initdata::REGION_C_26A428, + chip: None, adopt_root_entries: true, fabric_bridge: true, firmware: crate::g17::fw::variant::Firmware::Fixed(&crate::g17::fw::variant::V26A428), @@ -59,6 +60,7 @@ pub(crate) const CONFIG: Config = Config { cores: None, operand_state: crate::g17::fw::compute::OperandState::ONE_BY_SIX, deflake: crate::g17::fw::render::Deflake::ONE_CLUSTER, + compute_blocks: crate::g17::fw::freelist::COMPUTE_BLOCKS, }, }; diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index e8b845cba989f..2b04726e43878 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -46,6 +46,16 @@ const FAULT_INFO: usize = 0x17030; const G17_HOST_IRQ_SUMMARY: usize = 0xe01000; const G17_HOST_POWERED: u32 = 0xf; +const KSM_MAILBOX_TAG: usize = 0x4090; +const KSM_MAILBOX_DATA: usize = 0x4098; +const KSM_MAILBOX_FLAGS: u64 = (1 << 42) | (1 << 53); +const KSM_SLOT_DESCRIPTOR: u64 = 0x21008; +const KSM_SLOT_TIMESTAMP: u64 = 0x21020; +const KSM_SELECT: usize = 0x103a8; +const KSM_RUN_SET: usize = 0x21068; +const KSM_RUN_CLEAR: usize = 0x21078; +const KSM_RUNNING: [usize; 2] = [0x21038, 0x21040]; + const ID_VERSION: usize = 0xd04000; const ID_UNK08: usize = 0xd04008; const ID_COUNTS_1: usize = 0xd04010; @@ -602,6 +612,52 @@ impl G17Resources { Ok(true) } + /// Registers a queue KSM slot through the firmware mailbox. + pub(crate) fn register_ksm_queue(&self, qid: u8, descriptor: u64) -> Result { + if qid > 127 { + return Err(EINVAL); + } + let sgx = self.sgx.try_access().ok_or(ENODEV)?; + let sgx = (&*sgx).as_view(); + let tag = |reg: u64| reg | KSM_MAILBOX_FLAGS | (u64::from(qid) << 43); + let bit = 1u64 << (qid & 63); + let (low, high) = if qid < 64 { (bit, 0) } else { (0, bit) }; + let running = KSM_RUNNING[usize::from(qid >= 64)]; + if sgx.try_read64(running)? & bit != 0 { + sgx.try_write64(high, KSM_RUN_CLEAR + 8)?; + sgx.try_write64(low, KSM_RUN_CLEAR)?; + } + sgx.try_write64(tag(KSM_SLOT_DESCRIPTOR), KSM_MAILBOX_TAG)?; + sgx.try_write64(descriptor, KSM_MAILBOX_DATA)?; + sgx.try_write64(tag(KSM_SLOT_TIMESTAMP), KSM_MAILBOX_TAG)?; + sgx.try_read64(KSM_MAILBOX_DATA)?; + sgx.try_write64(tag(KSM_SLOT_DESCRIPTOR), KSM_MAILBOX_TAG)?; + let mut readback = sgx.try_read64(KSM_MAILBOX_DATA)?; + let direct = readback != descriptor; + if direct { + sgx.try_write64(u64::from(qid), KSM_SELECT)?; + sgx.try_write64(descriptor, KSM_SLOT_DESCRIPTOR as usize)?; + readback = sgx.try_read64(KSM_SLOT_DESCRIPTOR as usize)?; + } + if readback != descriptor { + dev_err!( + self.dev.as_ref(), + "KSM queue {} slot descriptor {:#x} did not take (reads {:#x})\n", + qid, + descriptor, + readback + ); + return Err(EIO); + } + if sgx.try_read64(running)? & bit == 0 { + sgx.try_write64(high, KSM_RUN_SET + 8)?; + sgx.try_write64(low, KSM_RUN_SET)?; + } + sgx.try_write64(tag(KSM_SLOT_TIMESTAMP), KSM_MAILBOX_TAG)?; + sgx.try_read64(KSM_MAILBOX_DATA)?; + Ok(()) + } + fn sgx_read32(&self) -> u32 { if let Some(sgx) = self.sgx.try_access() { (&*sgx).as_view().relaxed().read32(OFF) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index bf5bf96f4c62a..b0e593a59a700 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -11,6 +11,7 @@ * Copyright (C) 2011 Samsung Electronics Co., Ltd. */ +#include #include #include #include @@ -870,8 +871,17 @@ static const struct of_device_id avd_of_match[] = { MODULE_DEVICE_TABLE(of, avd_of_match); +static bool avd_t6041_hevc_supported(struct avd_dev *avd) +{ + return of_machine_is_compatible("apple,j616c") && + avd->variant == &avd_t6040_variant && + (avd->variant->quirks & AVD_QUIRK_HEVC_V5_HEADER) && + avd->fw->size == 0x12000; +} + static int avd_probe(struct platform_device *pdev) { + unsigned int variant_caps; struct avd_dev *avd; const struct of_device_id *match; const char *codec_info = NULL; @@ -919,12 +929,15 @@ static int avd_probe(struct platform_device *pdev) return ret; } + variant_caps = avd->variant->capabilities; + if (avd_t6041_hevc_supported(avd)) + variant_caps |= AVD_CAPABILITY_HEVC; + /* Determine firmware and HW variant capabilities */ if (avd->fw->size >= AVD_CODEC_INFO_MAX_SIZE) codec_info = avd->fw->data + avd->fw->size - AVD_CODEC_INFO_MAX_SIZE; if (codec_info && strncmp(codec_info, "CODECS:", 7) == 0) { unsigned int caps = 0; - unsigned int variant_caps = avd->variant->capabilities; if (strnstr(codec_info, "av1", AVD_CODEC_INFO_MAX_SIZE)) caps |= variant_caps & AVD_CAPABILITY_AV1; @@ -940,7 +953,7 @@ static int avd_probe(struct platform_device *pdev) avd->capabilities = caps; } else { /* Backward compatibility to old firmware, do not upstream. */ - avd->capabilities = avd->variant->capabilities; + avd->capabilities = variant_caps; } ret = dma_set_mask_and_coherent(avd->dev, diff --git a/drivers/pmdomain/apple/Kconfig b/drivers/pmdomain/apple/Kconfig index e25dd30281fc4..c442356fedde1 100644 --- a/drivers/pmdomain/apple/Kconfig +++ b/drivers/pmdomain/apple/Kconfig @@ -53,6 +53,15 @@ config APPLE_PMP_REPORT apple_t6031_display.enable=1. The start's state is in debugfs, in apple-pmp-report/. +config APPLE_PMP_ANE_KUNIT_TEST + tristate "KUnit tests for T600x ANE performance requests" if !KUNIT_ALL_TESTS + depends on KUNIT && PM + select PM_GENERIC_DOMAINS + default KUNIT_ALL_TESTS + help + Exercise ANE level transitions, ownership refusal and ACK-timeout + rollback against memory-backed registers without Apple hardware. + config APPLE_PMC bool "Apple PMC voter interface" depends on OF @@ -101,3 +110,15 @@ config APPLE_PMP_REPORT_KUNIT_TEST argument validation without accessing hardware. Includes malformed tables, address arithmetic and device ordering. The PMP report driver does not need to be enabled to run this suite. + +config APPLE_PMP_DRAM_KUNIT_TEST + tristate "Apple PMP DRAM description parsing tests" if !KUNIT_ALL_TESTS + depends on KUNIT && PM + select PM_GENERIC_DOMAINS + default KUNIT_ALL_TESTS + help + Parse synthetic firmware properties including unordered state IDs, + missing and duplicate states, incomplete descriptions and overflow. + Software-node fixtures exercise the parser without a DT boot image. + These tests access no hardware and do not need the PMP driver. They + are only useful for kernel developers. diff --git a/drivers/pmdomain/apple/Makefile b/drivers/pmdomain/apple/Makefile index ff7f9192b5e39..b03554cd70051 100644 --- a/drivers/pmdomain/apple/Makefile +++ b/drivers/pmdomain/apple/Makefile @@ -3,4 +3,6 @@ obj-$(CONFIG_APPLE_PMGR_PWRSTATE) += pmgr-pwrstate.o obj-$(CONFIG_APPLE_PMGR_PWRSTATE) += gfx-tvm.o obj-$(CONFIG_APPLE_PMP_REPORT) += pmp-report.o obj-$(CONFIG_APPLE_PMP_REPORT_KUNIT_TEST) += pmp-report-test.o +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 diff --git a/drivers/pmdomain/apple/pmp-ane-test.c b/drivers/pmdomain/apple/pmp-ane-test.c new file mode 100644 index 0000000000000..66b196b178cc0 --- /dev/null +++ b/drivers/pmdomain/apple/pmp-ane-test.c @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +#include "pmp-ane.h" + +struct ane_test { + struct apple_pmp_ane ane; + int requests; + int releases; + int request_error; + int release_error; + struct kunit *test; +}; + +static int ane_test_request(void *ctx, bool enable) +{ + struct ane_test *t = ctx; + + if (enable) { + KUNIT_EXPECT_EQ(t->test, readl(t->ane.dvfs + PMP_ANE_DVFS_ON), 1U); + KUNIT_EXPECT_EQ(t->test, readl(t->ane.dvfs + PMP_ANE_DVFS_CMD), 0x80000000U); + t->requests++; + t->ane.owned = true; + return t->request_error; + } + t->releases++; + if (t->release_error) + return t->release_error; + t->ane.owned = false; + return 0; +} + +static struct ane_test *ane_test_init(struct kunit *test) +{ + struct ane_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + + if (!t) + return NULL; + t->test = test; + t->ane.dvfs = (void __iomem *)kunit_kzalloc(test, 0x4000, GFP_KERNEL); + t->ane.report = (void __iomem *)kunit_kzalloc(test, 0x20000, GFP_KERNEL); + if (!t->ane.dvfs || !t->ane.report) + return NULL; + return t; +} + +static void ane_level_cycle(struct kunit *test) +{ + struct ane_test *t = ane_test_init(test); + + KUNIT_ASSERT_NOT_NULL(test, t); + KUNIT_ASSERT_EQ(test, apple_pmp_ane_set(&t->ane, 5, ane_test_request, t), 0); + KUNIT_EXPECT_EQ(test, t->ane.level, 5U); + KUNIT_EXPECT_EQ(test, readl(t->ane.dvfs + PMP_ANE_DVFS_CMD), 0x80000005U); + KUNIT_EXPECT_EQ(test, readq(t->ane.report + PMP_ANE_LEVEL_WRITE), PMP_ANE_LEVEL_TAG | 5); + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 5, ane_test_request, t), 0); + KUNIT_EXPECT_EQ(test, t->requests, 1); + KUNIT_ASSERT_EQ(test, apple_pmp_ane_set(&t->ane, 0, ane_test_request, t), 0); + KUNIT_EXPECT_EQ(test, t->ane.level, 0U); + KUNIT_EXPECT_FALSE(test, t->ane.owned); + KUNIT_EXPECT_EQ(test, t->releases, 1); + KUNIT_EXPECT_EQ(test, readl(t->ane.dvfs + PMP_ANE_DVFS_ON), 0U); + KUNIT_EXPECT_EQ(test, readl(t->ane.dvfs + PMP_ANE_DVFS_CMD), 0x80000000U); + KUNIT_EXPECT_EQ(test, readq(t->ane.report + PMP_ANE_LEVEL_WRITE), PMP_ANE_LEVEL_TAG); + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 0, ane_test_request, t), 0); + KUNIT_EXPECT_EQ(test, t->releases, 1); +} + +static void ane_level_busy(struct kunit *test) +{ + struct ane_test *t = ane_test_init(test); + + KUNIT_ASSERT_NOT_NULL(test, t); + writel(1, t->ane.dvfs + PMP_ANE_DVFS_ON); + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 5, ane_test_request, t), -EBUSY); + KUNIT_EXPECT_EQ(test, t->requests, 0); + writel(0, t->ane.dvfs + PMP_ANE_DVFS_ON); + writeq(0xdead, t->ane.report + PMP_ANE_LEVEL_READ); + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 5, ane_test_request, t), -EBUSY); + KUNIT_EXPECT_EQ(test, readl(t->ane.dvfs + PMP_ANE_DVFS_ON), 0U); + KUNIT_EXPECT_EQ(test, t->requests, 0); + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 6, ane_test_request, t), -EINVAL); +} + +static void ane_level_timeout(struct kunit *test) +{ + struct ane_test *t = ane_test_init(test); + int i; + + KUNIT_ASSERT_NOT_NULL(test, t); + t->request_error = -ETIMEDOUT; + for (i = 0; i < 4; i++) { + KUNIT_EXPECT_EQ(test, + apple_pmp_ane_set(&t->ane, 5, ane_test_request, t), + -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->ane.level, 0U); + KUNIT_EXPECT_EQ(test, readl(t->ane.dvfs + PMP_ANE_DVFS_ON), 0U); + KUNIT_EXPECT_FALSE(test, t->ane.owned); + } + KUNIT_EXPECT_EQ(test, t->requests, 3); + KUNIT_EXPECT_EQ(test, t->releases, 3); +} + +static void ane_level_release_timeout(struct kunit *test) +{ + struct ane_test *t = ane_test_init(test); + + KUNIT_ASSERT_NOT_NULL(test, t); + KUNIT_ASSERT_EQ(test, apple_pmp_ane_set(&t->ane, 5, ane_test_request, t), 0); + t->release_error = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 0, ane_test_request, t), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->ane.level, 0U); + KUNIT_EXPECT_EQ(test, t->ane.owned, true); + KUNIT_EXPECT_EQ(test, readl(t->ane.dvfs + PMP_ANE_DVFS_ON), 0U); + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 5, ane_test_request, t), -EBUSY); + t->release_error = 0; + KUNIT_EXPECT_EQ(test, apple_pmp_ane_set(&t->ane, 0, ane_test_request, t), 0); + KUNIT_EXPECT_FALSE(test, t->ane.owned); + KUNIT_EXPECT_EQ(test, t->releases, 2); +} + +static struct kunit_case ane_level_cases[] = { + KUNIT_CASE(ane_level_cycle), + KUNIT_CASE(ane_level_busy), + KUNIT_CASE(ane_level_timeout), + KUNIT_CASE(ane_level_release_timeout), + {} +}; + +static struct kunit_suite ane_level_suite = { + .name = "apple-pmp-ane", + .test_cases = ane_level_cases, +}; + +kunit_test_suite(ane_level_suite); + +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/pmdomain/apple/pmp-ane.h b/drivers/pmdomain/apple/pmp-ane.h new file mode 100644 index 0000000000000..e8e3838b042da --- /dev/null +++ b/drivers/pmdomain/apple/pmp-ane.h @@ -0,0 +1,96 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * T600x ANE level sequence, based on the public omarchy-ane implementation + * by Joshua Warren (ane/src/ane_dvfs.c, e20d25defb78). + * The report provider owns both windows and serializes request-word updates. + */ +#ifndef __APPLE_PMP_ANE_H__ +#define __APPLE_PMP_ANE_H__ + +#include +#include +#include + +#define PMP_ANE_DVFS_ON 0x2000 +#define PMP_ANE_DVFS_CMD 0xa00 +#define PMP_ANE_LEVEL_READ 0x10c0 +#define PMP_ANE_LEVEL_WRITE 0x10860 +#define PMP_ANE_LEVEL_TAG 0x2000000000000000ULL +#define PMP_ANE_MAX_LEVEL 5 +#define PMP_ANE_ID 10 + +struct apple_pmp_ane { + void __iomem *dvfs; + void __iomem *report; + unsigned int level; + unsigned int timeouts; + bool owned; + bool reserved; +}; + +static void apple_pmp_ane_cmd(struct apple_pmp_ane *ane, unsigned int old, + unsigned int new) +{ + writel(0x80000000U | old << 4 | new, ane->dvfs + PMP_ANE_DVFS_CMD); + usleep_range(1000, 2000); +} + +/* Caller serializes transitions and pins the ANE and report power domains. */ +static int apple_pmp_ane_set(struct apple_pmp_ane *ane, unsigned int level, + int (*request)(void *ctx, bool enable), void *ctx) +{ + u64 word; + int ret = 0; + + if (!ane->dvfs) + return -EOPNOTSUPP; + if (level > PMP_ANE_MAX_LEVEL) + return -EINVAL; + if (level == ane->level && (level || !ane->owned)) + return 0; + if (!level && !ane->level) + goto release; + if (level && !ane->level && ane->owned) + return -EBUSY; + if (level && ane->timeouts >= 3) + return -ETIMEDOUT; + + if (!ane->level) { + if (readl(ane->dvfs + PMP_ANE_DVFS_ON)) + return -EBUSY; + word = readq(ane->report + PMP_ANE_LEVEL_READ); + if (word && (word < PMP_ANE_LEVEL_TAG || + word > (PMP_ANE_LEVEL_TAG | PMP_ANE_MAX_LEVEL))) + return -EBUSY; + + writel(1, ane->dvfs + PMP_ANE_DVFS_ON); + usleep_range(1000, 2000); + apple_pmp_ane_cmd(ane, 0, 0); + ret = request(ctx, true); + if (ret) { + if (ret == -ETIMEDOUT) + ane->timeouts++; + goto release; + } + } + + apple_pmp_ane_cmd(ane, ane->level, level); + writeq(PMP_ANE_LEVEL_TAG | level, ane->report + PMP_ANE_LEVEL_WRITE); + ane->level = level; + if (level) + return 0; + usleep_range(1000, 2000); + +release: + if (ane->owned) { + int err = request(ctx, false); + + if (!ret) + ret = err; + } + apple_pmp_ane_cmd(ane, 0, 0); + writel(0, ane->dvfs + PMP_ANE_DVFS_ON); + return ret; +} + +#endif diff --git a/drivers/pmdomain/apple/pmp-dram-test.c b/drivers/pmdomain/apple/pmp-dram-test.c new file mode 100644 index 0000000000000..c662b99ff3df1 --- /dev/null +++ b/drivers/pmdomain/apple/pmp-dram-test.c @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Exercise the actual firmware-property parser without MMIO or firmware. */ +#include +#include + +#include "pmp-dram.h" + +struct pmp_dram_fixture { + struct software_node nodes[8]; + const struct software_node *group[9]; + struct software_node_ref_args ref[1]; + struct property_entry props[8]; + struct property_entry table_props[2]; + struct property_entry opp_props[6][4]; +}; + +static void pmp_dram_unregister(void *data) +{ + struct pmp_dram_fixture *f = data; + + software_node_unregister_node_group(f->group); +} + +static struct pmp_dram_fixture *pmp_dram_fixture(struct kunit *test, u32 count, + u32 width, u64 rate, u64 bandwidth_class) +{ + static const char * const names[] = { + "opp-0", "opp-1", "opp-2", "opp-3", "opp-4", "opp-5", + }; + struct pmp_dram_fixture *f; + unsigned int i; + + f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, f); + f->ref[0] = SOFTWARE_NODE_REFERENCE(&f->nodes[1]); + f->props[0] = PROPERTY_ENTRY_STRING("apple,dram-type", "lpddr5"); + f->props[1] = PROPERTY_ENTRY_U32("apple,data-bus-width", width); + f->props[2] = PROPERTY_ENTRY_U32("apple,dcs-state-count", count); + f->props[3] = PROPERTY_ENTRY_U64("apple,peak-bandwidth-bytes-per-second", + rate * (width / 8)); + f->props[4] = PROPERTY_ENTRY_U64("apple,bandwidth-class-bytes-per-second", bandwidth_class); + f->props[5] = PROPERTY_ENTRY_REF_ARRAY("operating-points-v2", f->ref); + f->nodes[0].name = "pmp-dram-test"; + f->nodes[0].properties = f->props; + f->table_props[0] = PROPERTY_ENTRY_STRING("compatible", "operating-points-v2-apple-dram"); + f->nodes[1].name = "opp-table-dram"; + f->nodes[1].properties = f->table_props; + for (i = 0; i < count; i++) { + struct software_node *opp = &f->nodes[i + 2]; + + opp->name = names[i]; + opp->parent = &f->nodes[1]; + opp->properties = f->opp_props[i]; + /* Reverse order: the highest state is not the last child. */ + f->opp_props[i][0] = PROPERTY_ENTRY_U32("opp-level", count - i - 1); + if (!i) { + f->opp_props[i][1] = PROPERTY_ENTRY_U64("apple,data-rate", rate); + f->opp_props[i][2] = PROPERTY_ENTRY_U64("opp-hz", rate / 2 + rate % 2); + } + } + for (i = 0; i < count + 2; i++) + f->group[i] = &f->nodes[i]; + return f; +} + +static int pmp_dram_parse_fixture(struct kunit *test, struct pmp_dram_fixture *f, + struct apple_pmp_dram *dram) +{ + int ret; + + ret = software_node_register_node_group(f->group); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = kunit_add_action_or_reset(test, pmp_dram_unregister, f); + KUNIT_ASSERT_EQ(test, ret, 0); + return apple_pmp_dram_parse(software_node_fwnode(&f->nodes[0]), dram); +} + +static void pmp_dram_valid(struct kunit *test) +{ + struct pmp_dram_fixture *f = pmp_dram_fixture(test, 4, 256, 6400000000ULL, 200000000000ULL); + struct apple_pmp_dram dram = {}; + + KUNIT_ASSERT_EQ(test, pmp_dram_parse_fixture(test, f, &dram), 0); + KUNIT_EXPECT_STREQ(test, dram.type, "lpddr5"); + KUNIT_EXPECT_EQ(test, dram.max_rate, 6400000000ULL); + KUNIT_EXPECT_EQ(test, dram.peak_bandwidth, 204800000000ULL); + KUNIT_EXPECT_EQ(test, dram.bandwidth_class, 200000000000ULL); + KUNIT_EXPECT_EQ(test, dram.state_count, 4U); + KUNIT_EXPECT_EQ(test, dram.width, 256U); +} + +static void pmp_dram_m2(struct kunit *test) +{ + struct pmp_dram_fixture *f = pmp_dram_fixture(test, 5, 128, 6400000000ULL, 100000000000ULL); + struct apple_pmp_dram dram = {}; + + KUNIT_ASSERT_EQ(test, pmp_dram_parse_fixture(test, f, &dram), 0); + KUNIT_EXPECT_EQ(test, dram.peak_bandwidth, 102400000000ULL); + KUNIT_EXPECT_EQ(test, dram.state_count, 5U); +} + +static void pmp_dram_m4pro(struct kunit *test) +{ + struct pmp_dram_fixture *f = pmp_dram_fixture(test, 6, 256, 8533333333ULL, 273000000000ULL); + struct apple_pmp_dram dram = {}; + + KUNIT_ASSERT_EQ(test, pmp_dram_parse_fixture(test, f, &dram), 0); + KUNIT_EXPECT_EQ(test, dram.max_rate, 8533333333ULL); + KUNIT_EXPECT_EQ(test, dram.peak_bandwidth, 273066666656ULL); + KUNIT_EXPECT_EQ(test, dram.state_count, 6U); +} + +static void pmp_dram_a18pro(struct kunit *test) +{ + struct pmp_dram_fixture *f = pmp_dram_fixture(test, 5, 64, 7500000000ULL, 60000000000ULL); + struct apple_pmp_dram dram = {}; + + KUNIT_ASSERT_EQ(test, pmp_dram_parse_fixture(test, f, &dram), 0); + KUNIT_EXPECT_EQ(test, dram.peak_bandwidth, 60000000000ULL); + KUNIT_EXPECT_EQ(test, dram.width, 64U); +} + +enum pmp_dram_fault { + DRAM_ZERO_WIDTH, DRAM_UNALIGNED_WIDTH, DRAM_ZERO_COUNT, DRAM_LARGE_COUNT, + DRAM_DUPLICATE, DRAM_MISSING, DRAM_UNKNOWN_LEVEL, DRAM_MISSING_LEVEL, + DRAM_NO_MAX, DRAM_ZERO_RATE, DRAM_BAD_CK, DRAM_CK_ONLY, DRAM_BAD_PEAK, + DRAM_OVERFLOW, DRAM_BAD_TYPE, DRAM_NO_CLASS, DRAM_ZERO_CLASS, + DRAM_NO_TABLE, DRAM_BAD_COMPATIBLE, DRAM_LOW_ABOVE_MAX, DRAM_WRONG_TYPE, +}; + +static void pmp_dram_bad_description(struct kunit *test) +{ + enum pmp_dram_fault fault = *(enum pmp_dram_fault *)test->param_value; + struct pmp_dram_fixture *f = pmp_dram_fixture(test, 4, 256, 6400000000ULL, 200000000000ULL); + struct apple_pmp_dram dram = { .max_rate = 123 }; + + switch (fault) { + case DRAM_ZERO_WIDTH: + f->props[1] = PROPERTY_ENTRY_U32("apple,data-bus-width", 0); + break; + case DRAM_UNALIGNED_WIDTH: + f->props[1] = PROPERTY_ENTRY_U32("apple,data-bus-width", 7); + break; + case DRAM_ZERO_COUNT: + f->props[2] = PROPERTY_ENTRY_U32("apple,dcs-state-count", 0); + break; + case DRAM_LARGE_COUNT: + f->props[2] = PROPERTY_ENTRY_U32("apple,dcs-state-count", 33); + break; + case DRAM_DUPLICATE: + f->opp_props[1][0] = PROPERTY_ENTRY_U32("opp-level", 3); + break; + case DRAM_MISSING: + f->group[5] = NULL; + break; + case DRAM_UNKNOWN_LEVEL: + f->opp_props[1][0] = PROPERTY_ENTRY_U32("opp-level", 4); + break; + case DRAM_MISSING_LEVEL: + memset(&f->opp_props[1][0], 0, sizeof(struct property_entry)); + break; + case DRAM_NO_MAX: + memset(&f->opp_props[0][1], 0, 2 * sizeof(struct property_entry)); + break; + case DRAM_ZERO_RATE: + f->opp_props[0][1] = PROPERTY_ENTRY_U64("apple,data-rate", 0); + break; + case DRAM_BAD_CK: + f->opp_props[0][2] = PROPERTY_ENTRY_U64("opp-hz", 6400000000ULL); + break; + case DRAM_CK_ONLY: + f->opp_props[0][1] = f->opp_props[0][2]; + memset(&f->opp_props[0][2], 0, sizeof(struct property_entry)); + break; + case DRAM_BAD_PEAK: + f->props[3] = PROPERTY_ENTRY_U64("apple,peak-bandwidth-bytes-per-second", + 200000000000ULL); + break; + case DRAM_OVERFLOW: + f->opp_props[0][1] = PROPERTY_ENTRY_U64("apple,data-rate", U64_MAX - 1); + f->opp_props[0][2] = PROPERTY_ENTRY_U64("opp-hz", (U64_MAX - 1) / 2); + break; + case DRAM_BAD_TYPE: + f->props[0] = PROPERTY_ENTRY_STRING("apple,dram-type", "lpddr5x"); + break; + case DRAM_NO_CLASS: + f->props[4] = PROPERTY_ENTRY_U64("unrelated", 1); + break; + case DRAM_ZERO_CLASS: + f->props[4] = PROPERTY_ENTRY_U64("apple,bandwidth-class-bytes-per-second", 0); + break; + case DRAM_NO_TABLE: + memset(&f->props[5], 0, sizeof(struct property_entry)); + break; + case DRAM_BAD_COMPATIBLE: + f->table_props[0] = PROPERTY_ENTRY_STRING("compatible", "operating-points-v2"); + break; + case DRAM_LOW_ABOVE_MAX: + f->opp_props[1][1] = PROPERTY_ENTRY_U64("apple,data-rate", 7500000000ULL); + f->opp_props[1][2] = PROPERTY_ENTRY_U64("opp-hz", 3750000000ULL); + break; + case DRAM_WRONG_TYPE: + f->props[2] = PROPERTY_ENTRY_STRING("apple,dcs-state-count", "four"); + break; + } + KUNIT_EXPECT_LT(test, pmp_dram_parse_fixture(test, f, &dram), 0); + /* Never publish partially parsed values or a fallback maximum. */ + KUNIT_EXPECT_EQ(test, dram.max_rate, 123ULL); +} + +static const enum pmp_dram_fault pmp_dram_faults[] = { + DRAM_ZERO_WIDTH, DRAM_UNALIGNED_WIDTH, DRAM_ZERO_COUNT, DRAM_LARGE_COUNT, + DRAM_DUPLICATE, DRAM_MISSING, DRAM_UNKNOWN_LEVEL, DRAM_MISSING_LEVEL, + DRAM_NO_MAX, DRAM_ZERO_RATE, DRAM_BAD_CK, DRAM_CK_ONLY, DRAM_BAD_PEAK, + DRAM_OVERFLOW, DRAM_BAD_TYPE, DRAM_NO_CLASS, DRAM_ZERO_CLASS, + DRAM_NO_TABLE, DRAM_BAD_COMPATIBLE, DRAM_LOW_ABOVE_MAX, DRAM_WRONG_TYPE, +}; + +KUNIT_ARRAY_PARAM(pmp_dram_fault, pmp_dram_faults, NULL); + +static void pmp_dram_old_dt(struct kunit *test) +{ + struct pmp_dram_fixture *f = pmp_dram_fixture(test, 4, 256, 6400000000ULL, 200000000000ULL); + struct apple_pmp_dram dram = {}; + + memset(f->props, 0, sizeof(f->props)); + KUNIT_EXPECT_EQ(test, pmp_dram_parse_fixture(test, f, &dram), -ENODATA); +} + +static void pmp_dram_partial_dt(struct kunit *test) +{ + struct pmp_dram_fixture *f = pmp_dram_fixture(test, 4, 256, 6400000000ULL, 200000000000ULL); + struct apple_pmp_dram dram = {}; + + f->props[0] = PROPERTY_ENTRY_U32("apple,data-bus-width", 128); + memset(&f->props[1], 0, sizeof(struct property_entry)); + KUNIT_EXPECT_EQ(test, pmp_dram_parse_fixture(test, f, &dram), -EINVAL); +} + +static struct kunit_case pmp_dram_cases[] = { + KUNIT_CASE(pmp_dram_valid), + KUNIT_CASE(pmp_dram_m2), + KUNIT_CASE(pmp_dram_m4pro), + KUNIT_CASE(pmp_dram_a18pro), + KUNIT_CASE_PARAM(pmp_dram_bad_description, pmp_dram_fault_gen_params), + KUNIT_CASE(pmp_dram_old_dt), + KUNIT_CASE(pmp_dram_partial_dt), + {} +}; + +static struct kunit_suite pmp_dram_suite = { + .name = "apple-pmp-dram", + .test_cases = pmp_dram_cases, +}; + +kunit_test_suite(pmp_dram_suite); + +MODULE_DESCRIPTION("KUnit tests for Apple PMP DRAM property parsing"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/pmdomain/apple/pmp-dram.h b/drivers/pmdomain/apple/pmp-dram.h new file mode 100644 index 0000000000000..08a7fcf9c17c8 --- /dev/null +++ b/drivers/pmdomain/apple/pmp-dram.h @@ -0,0 +1,114 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _APPLE_PMP_DRAM_H +#define _APPLE_PMP_DRAM_H + +#include +#include +#include +#include +#include + +#define APPLE_PMP_DRAM_MAX_STATES 32 + +struct apple_pmp_dram { + const char *type; + u32 width; + u32 state_count; + u64 max_rate; + u64 peak_bandwidth; + u64 bandwidth_class; +}; + +/* + * Read metadata only: never register these OPPs with a clock/voltage provider. + * Unknown lower-state rates are deliberately absent. Firmware state IDs, not + * child order or frequency sorting, identify the entries. + */ +static inline int apple_pmp_dram_parse(const struct fwnode_handle *node, + struct apple_pmp_dram *dram) +{ + struct apple_pmp_dram parsed = {}; + struct fwnode_reference_args ref; + struct fwnode_handle *opp; + u64 rates[APPLE_PMP_DRAM_MAX_STATES] = {}; + u64 seen = 0, peak; + u32 level; + unsigned int i; + int ret; + + /* Old DTs with no memory description retain the existing interface. */ + if (!fwnode_property_present(node, "apple,dram-type") && + !fwnode_property_present(node, "apple,data-bus-width") && + !fwnode_property_present(node, "apple,dcs-state-count") && + !fwnode_property_present(node, "apple,peak-bandwidth-bytes-per-second") && + !fwnode_property_present(node, "apple,bandwidth-class-bytes-per-second") && + !fwnode_property_present(node, "operating-points-v2")) + return -ENODATA; + + if (fwnode_property_read_string(node, "apple,dram-type", &parsed.type) || + strcmp(parsed.type, "lpddr5") || + fwnode_property_read_u32(node, "apple,data-bus-width", &parsed.width) || + !parsed.width || parsed.width % 8 || + fwnode_property_read_u32(node, "apple,dcs-state-count", &parsed.state_count) || + !parsed.state_count || parsed.state_count > APPLE_PMP_DRAM_MAX_STATES || + fwnode_property_read_u64(node, "apple,peak-bandwidth-bytes-per-second", + &parsed.peak_bandwidth) || + fwnode_property_read_u64(node, "apple,bandwidth-class-bytes-per-second", + &parsed.bandwidth_class) || !parsed.bandwidth_class) + return -EINVAL; + + ret = fwnode_property_get_reference_args(node, "operating-points-v2", NULL, 0, 0, &ref); + if (ret) + return ret; + if (fwnode_property_match_string(ref.fwnode, "compatible", + "operating-points-v2-apple-dram") != 0) { + ret = -EINVAL; + goto out; + } + fwnode_for_each_available_child_node(ref.fwnode, opp) { + u64 rate, ck; + + if (fwnode_property_read_u32(opp, "opp-level", &level) || + level >= parsed.state_count || (seen & BIT_ULL(level))) + goto bad_opp; + seen |= BIT_ULL(level); + if (!fwnode_property_present(opp, "apple,data-rate")) { + if (fwnode_property_present(opp, "opp-hz")) + goto bad_opp; + continue; + } + if (fwnode_property_read_u64(opp, "apple,data-rate", &rate) || !rate || + fwnode_property_read_u64(opp, "opp-hz", &ck) || !ck || + ck != rate / 2 + rate % 2) + goto bad_opp; + rates[level] = rate; + } + if (seen != GENMASK_ULL(parsed.state_count - 1, 0)) { + ret = -EINVAL; + goto out; + } + parsed.max_rate = rates[parsed.state_count - 1]; + if (!parsed.max_rate || + check_mul_overflow(parsed.max_rate, (u64)parsed.width / 8, &peak) || + peak != parsed.peak_bandwidth) { + ret = -EINVAL; + goto out; + } + for (i = 0; i + 1 < parsed.state_count; i++) { + if (rates[i] >= parsed.max_rate) { + ret = -EINVAL; + goto out; + } + } + /* Publish only a complete, internally consistent description. */ + *dram = parsed; +out: + fwnode_handle_put(ref.fwnode); + return ret; +bad_opp: + fwnode_handle_put(opp); + ret = -EINVAL; + goto out; +} + +#endif diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index aaa38c06daaaf..f09b38aa310ca 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -32,6 +32,8 @@ #include #include "pmp-report-validation.h" +#include "pmp-dram.h" +#include "pmp-ane.h" #define PMP_REPORT_READY 0x1 @@ -81,6 +83,9 @@ struct apple_pmp_start; struct apple_pmp_report { struct device *dev; + struct apple_pmp_dram dram; + struct apple_pmp_ane ane; + struct device *ane_owner; const struct apple_pmp_report_offsets *offsets; void __iomem *base; /* Protects the request word, @shadow, @known and @defer. */ @@ -105,11 +110,183 @@ static bool apple_pmp_report_running(const struct apple_pmp_report *rep) return rep->offsets->running_any ? status : status & PMP_REPORT_READY; } +static ssize_t type_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct apple_pmp_report *rep = dev_get_drvdata(dev); + + return sysfs_emit(buf, "%s\n", rep->dram.type); +} +static DEVICE_ATTR_RO(type); + +#define APPLE_PMP_DRAM_ATTR(_name, _field, _format) \ +static ssize_t _name##_show(struct device *dev, struct device_attribute *attr, char *buf) \ +{ \ + struct apple_pmp_report *rep = dev_get_drvdata(dev); \ + return sysfs_emit(buf, _format "\n", rep->dram._field); \ +} \ +static DEVICE_ATTR_RO(_name) + +APPLE_PMP_DRAM_ATTR(data_bus_width, width, "%u"); +APPLE_PMP_DRAM_ATTR(state_count, state_count, "%u"); +APPLE_PMP_DRAM_ATTR(max_data_rate, max_rate, "%llu"); +APPLE_PMP_DRAM_ATTR(peak_bandwidth, peak_bandwidth, "%llu"); +APPLE_PMP_DRAM_ATTR(bandwidth_class, bandwidth_class, "%llu"); + +static struct attribute *apple_pmp_dram_attrs[] = { + &dev_attr_type.attr, + &dev_attr_data_bus_width.attr, + &dev_attr_state_count.attr, + &dev_attr_max_data_rate.attr, + &dev_attr_peak_bandwidth.attr, + &dev_attr_bandwidth_class.attr, + NULL, +}; + +static const struct attribute_group apple_pmp_dram_group = { + .name = "dram", + .attrs = apple_pmp_dram_attrs, +}; + static const struct apple_pmp_report_offsets apple_pmp_offsets_t6030; /* Bound report regions, protected by RCU until managed teardown drains readers. */ static LIST_HEAD(apple_pmp_reports); static DEFINE_MUTEX(apple_pmp_reports_lock); + +/* The report lock also protects ANE_SYS against a genpd owner appearing. */ +static int apple_pmp_ane_request(void *ctx, bool enable) +{ + struct apple_pmp_report *rep = ctx; + struct apple_pmp_ane *ane = &rep->ane; + const u64 bit = BIT_ULL(PMP_ANE_ID); + unsigned long flags; + u64 val; + + spin_lock_irqsave(&rep->lock, flags); + val = readq(rep->base + rep->offsets->tgt_read); + if (enable) { + if ((rep->known | val) & bit) { + spin_unlock_irqrestore(&rep->lock, flags); + return -EBUSY; + } + ane->owned = true; + val |= bit; + } else { + val &= ~bit; + } + writeq(val, rep->base + rep->offsets->tgt_write); + spin_unlock_irqrestore(&rep->lock, flags); + if (!enable) { + int ret = readq_poll_timeout(rep->base + rep->offsets->actual, val, + !(val & bit), 200, 50000); + + if (!ret) { + spin_lock_irqsave(&rep->lock, flags); + ane->owned = false; + spin_unlock_irqrestore(&rep->lock, flags); + } + return ret; + } + return readq_poll_timeout(rep->base + rep->offsets->actual, val, + val & bit, 200, 50000); +} + +/* Probe-time availability check: deliberately no MMIO while the ANE is off. */ +int apple_pmp_report_ane_available(const struct device_node *np) +{ + struct apple_pmp_report *rep; + int ret = -EPROBE_DEFER; + + mutex_lock(&apple_pmp_reports_lock); + list_for_each_entry(rep, &apple_pmp_reports, list) { + if (rep->dev->of_node != np) + continue; + ret = !rep->ane.dvfs ? -EOPNOTSUPP : + (rep->ane_owner || rep->ane.reserved) ? -EBUSY : 0; + break; + } + mutex_unlock(&apple_pmp_reports_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_pmp_report_ane_available); + +/** + * apple_pmp_report_ane_perf() - request a T600x ANE performance level + * @np: report provider node + * @owner: ANE device holding the request + * @level: 0 to release, 1 through 5 to request a level + * @held: whether the caller still owns a request, including failed rollback + * + * The caller must keep its engine and the report SRAM powered throughout + * the request, and link itself to the report supplier. Other generations + * and reports without an ANE DVFS resource are unsupported. The returned + * level is a firmware request, not a measured frequency. + * + * Context: Process context. May sleep. + * Return: 0 on success, or a negative errno. Ownership and ACK failures + * are returned to the submitter; no CPU frequency request is substituted. + */ +int apple_pmp_report_ane_perf(const struct device_node *np, + struct device *owner, unsigned int level, bool *held) +{ + struct apple_pmp_report *rep; + int ret = -EPROBE_DEFER; + + if (!np || !owner || !held) + return -EINVAL; + *held = false; + mutex_lock(&apple_pmp_reports_lock); + list_for_each_entry(rep, &apple_pmp_reports, list) { + if (rep->dev->of_node != np) + continue; + if (!rep->ane.dvfs) { + ret = -EOPNOTSUPP; + break; + } + if (rep->ane_owner && rep->ane_owner != owner) { + ret = -EBUSY; + break; + } + if (level && !apple_pmp_report_running(rep)) { + ret = -EAGAIN; + break; + } + /* Claim before touching DVFS, and exclude genpd for the whole cycle. */ + if (level && !rep->ane.reserved) { + unsigned long flags; + u64 req; + + spin_lock_irqsave(&rep->lock, flags); + req = readq(rep->base + rep->offsets->tgt_read); + if ((rep->known | req) & BIT_ULL(PMP_ANE_ID)) { + spin_unlock_irqrestore(&rep->lock, flags); + ret = -EBUSY; + break; + } + rep->ane.reserved = true; + spin_unlock_irqrestore(&rep->lock, flags); + } + ret = apple_pmp_ane_set(&rep->ane, level, apple_pmp_ane_request, rep); + if (!rep->ane.level && !rep->ane.owned) { + unsigned long flags; + + spin_lock_irqsave(&rep->lock, flags); + rep->ane.reserved = false; + spin_unlock_irqrestore(&rep->lock, flags); + } + /* Failed rollback retains ownership until a successful retry. */ + if (rep->ane.level || rep->ane.owned) + rep->ane_owner = owner; + else + rep->ane_owner = NULL; + *held = rep->ane_owner == owner; + break; + } + mutex_unlock(&apple_pmp_reports_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_pmp_report_ane_perf); + static struct dentry *apple_pmp_report_debugfs; /** @@ -1143,10 +1320,36 @@ static int apple_pmp_report_probe(struct platform_device *pdev) if (IS_ERR(rep->base)) return PTR_ERR(rep->base); rep->offsets = of_device_get_match_data(dev); + if (of_property_match_string(np, "reg-names", "ane-dvfs") >= 0) { + struct resource *res; + + if (!of_device_is_compatible(np, "apple,t6000-pmp-v2-report")) + return -EINVAL; + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res || resource_size(res) != SZ_128K) + return -EINVAL; + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "ane-dvfs"); + if (!res || resource_size(res) != SZ_16K) + return -EINVAL; + rep->ane.dvfs = devm_ioremap_resource(dev, res); + if (IS_ERR(rep->ane.dvfs)) + return PTR_ERR(rep->ane.dvfs); + rep->ane.report = rep->base; + } + rep->defer = rep->offsets->defer_requests; INIT_DELAYED_WORK(&rep->ready_work, apple_pmp_report_ready_work); platform_set_drvdata(pdev, rep); + ret = apple_pmp_dram_parse(dev_fwnode(dev), &rep->dram); + if (ret && ret != -ENODATA) + return dev_err_probe(dev, ret, "invalid DRAM description\n"); + if (!ret) { + ret = devm_device_add_group(dev, &apple_pmp_dram_group); + if (ret) + return ret; + } + INIT_LIST_HEAD(&rep->list); ret = devm_add_action_or_reset(dev, apple_pmp_report_release, rep); if (ret) @@ -1338,6 +1541,10 @@ static int apple_pmp_report_set_state(struct apple_pmp_report *rep, u32 id, bool ready; spin_lock_irqsave(&rep->lock, flags); + if (id == PMP_ANE_ID && rep->ane.reserved) { + spin_unlock_irqrestore(&rep->lock, flags); + return -EBUSY; + } rep->known |= bit_val; if (enable) rep->shadow |= bit_val; diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index c59719d048158..ef91dec09df76 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -1585,16 +1585,34 @@ impl AopData { &self, aop_mmio: &Mmio<'_, Region>, patches: &[(u32, u64)], + word_access: bool, ) -> Result<()> { let offset = aop_mmio.read32(BOOTARGS_OFFSET) as usize; let size = aop_mmio.read32(BOOTARGS_SIZE) as usize; if offset > aop_mmio.size() || size > aop_mmio.size() - offset { return Err(EINVAL); } - let mut arg_bytes = KVec::::from_elem(0, size, GFP_KERNEL)?; + let start = if word_access { offset & !3 } else { offset }; + let end = if word_access { + (offset + size).checked_add(3).ok_or(EINVAL)? & !3 + } else { + offset + size + }; + if end > aop_mmio.size() || (word_access && size == 0) { + return Err(EINVAL); + } + let mut bytes = KVec::::from_elem(0, end - start, GFP_KERNEL)?; let aop_io_array: Mmio<'_, [u8; AOP_MMIO_SIZE]> = aop_mmio.try_cast()?; let bootargs = io_project!(aop_io_array, [try: offset .. offset+size]); - bootargs.copy_to_slice(&mut arg_bytes); + if word_access { + for (i, chunk) in bytes.chunks_exact_mut(4).enumerate() { + chunk.copy_from_slice(&aop_mmio.try_read32(start + i * 4)?.to_le_bytes()); + } + } else { + bootargs.copy_to_slice(&mut bytes); + } + let first = offset - start; + let arg_bytes = &mut bytes[first..first + size]; let mut idx = 0; while idx < size { if size - idx < 8 { @@ -1618,7 +1636,21 @@ impl AopData { } idx += len; } - bootargs.copy_from_slice(&arg_bytes); + if word_access { + for (i, chunk) in bytes.chunks_exact(4).enumerate() { + let address = start + i * 4; + let value = u32::from_le_bytes(chunk.try_into().unwrap()); + if aop_mmio.try_read32(address)? == value { + continue; + } + aop_mmio.try_write32(value, address)?; + if aop_mmio.try_read32(address)? != value { + return Err(EIO); + } + } + } else { + bootargs.copy_from_slice(arg_bytes); + } Ok(()) } @@ -2519,6 +2551,7 @@ struct AopHwConfig { /// and lists in `memory-region`; check their IOMMU mappings before /// starting it (T6040). fw_regions: bool, + bootargs_word_access: bool, /// Halt the co-processor again when its start fails (T6040). halt_on_failed_start: bool, } @@ -2533,6 +2566,7 @@ const HW_CFG_T8103: AopHwConfig = AopHwConfig { quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, + bootargs_word_access: false, halt_on_failed_start: false, }; const HW_CFG_T8112: AopHwConfig = AopHwConfig { @@ -2545,6 +2579,7 @@ const HW_CFG_T8112: AopHwConfig = AopHwConfig { quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, + bootargs_word_access: false, halt_on_failed_start: false, }; const HW_CFG_T6000: AopHwConfig = AopHwConfig { @@ -2557,6 +2592,7 @@ const HW_CFG_T6000: AopHwConfig = AopHwConfig { quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, + bootargs_word_access: false, halt_on_failed_start: false, }; const HW_CFG_T6020: AopHwConfig = AopHwConfig { @@ -2569,6 +2605,7 @@ const HW_CFG_T6020: AopHwConfig = AopHwConfig { quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, + bootargs_word_access: false, halt_on_failed_start: false, }; /// T6040 (J616s): macOS writes the same four boot arguments as for the @@ -2585,6 +2622,7 @@ const HW_CFG_T6040: AopHwConfig = AopHwConfig { quiesce_on_unbind: true, required_endpoints: &[], fw_regions: true, + bootargs_word_access: true, halt_on_failed_start: true, }; /// T8140: the firmware is started with the boot arguments the bootloader @@ -2602,6 +2640,7 @@ const HW_CFG_T8140: AopHwConfig = AopHwConfig { quiesce_on_unbind: true, required_endpoints: &[0x20, 0x21, 0x22, 0x23, 0x2b], fw_regions: false, + bootargs_word_access: false, halt_on_failed_start: false, }; @@ -2661,6 +2700,7 @@ impl platform::Driver for AopDriver { (from_fourcc(b"alig"), cfg.alig), (from_fourcc(b"AOPt"), cfg.aopt), ], + cfg.bootargs_word_access, )?; } let rtkit = rtkit::RtKit::::new(pdev.as_ref(), None, 0, data.clone())?; diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index f533953294f62..e1b8fa6a83972 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -53,6 +53,11 @@ #define APPLE_WDT_TIMEOUT_DEFAULT 30 +static bool nowayout = WATCHDOG_NOWAYOUT; +module_param(nowayout, bool, 0); +MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" + __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); + struct apple_wdt { struct watchdog_device wdd; void __iomem *regs; @@ -178,6 +183,7 @@ static int apple_wdt_probe(struct platform_device *pdev) platform_set_drvdata(pdev, wdt); + wdt->wdd.parent = dev; wdt->wdd.ops = &apple_wdt_ops; wdt->wdd.info = &apple_wdt_info; wdt->wdd.max_hw_heartbeat_ms = U32_MAX / wdt->clk_rate * 1000; @@ -187,6 +193,7 @@ static int apple_wdt_probe(struct platform_device *pdev) if (wdt_ctrl & APPLE_WDT_CTRL_RESET_EN) set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + watchdog_set_nowayout(&wdt->wdd, nowayout); watchdog_init_timeout(&wdt->wdd, 0, dev); apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); watchdog_stop_on_unregister(&wdt->wdd); diff --git a/include/linux/soc/apple/pmp-report.h b/include/linux/soc/apple/pmp-report.h index 1bfb4fc69f1f7..5e819681ba106 100644 --- a/include/linux/soc/apple/pmp-report.h +++ b/include/linux/soc/apple/pmp-report.h @@ -14,11 +14,26 @@ struct device_node; struct device; #if IS_ENABLED(CONFIG_APPLE_PMP_REPORT) +int apple_pmp_report_ane_available(const struct device_node *np); +int apple_pmp_report_ane_perf(const struct device_node *np, + struct device *owner, unsigned int level, bool *held); int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int timeout_ms); int apple_pmp_report_wait_ready(struct device_node *entry, unsigned long timeout); int apple_pmp_report_fast_die_effort(const struct device_node *np, unsigned int lane, u8 *effort); #else +static inline int apple_pmp_report_ane_available(const struct device_node *np) +{ + return -EOPNOTSUPP; +} + +static inline int apple_pmp_report_ane_perf(const struct device_node *np, + struct device *owner, unsigned int level, bool *held) +{ + *held = false; + return -EOPNOTSUPP; +} + static inline int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int timeout_ms) { diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index 1d1c8924eb2fb..32b567836594a 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -512,6 +512,9 @@ static void macaudio_vlimit_update(struct macaudio_snd_data *ma) atomic_inc(&ma->sw_gain_lock_epoch); schedule_work(&ma->sw_gain_stop_work); } + if (!unlock && !ma->pm_quiesced && ma->cfg->fe_cpu_is_platform && + ma->cfg->amp == AMP_SN012776) + schedule_work(&ma->sw_gain_stop_work); ma->speaker_volume_unlocked = unlock; snd_ctl_notify(ma->card.snd_card, SNDRV_CTL_EVENT_MASK_VALUE, &ma->speaker_lock_kctl->id); @@ -665,7 +668,7 @@ static void macaudio_sw_gain_stop_work(struct work_struct *work) struct macaudio_snd_data *ma = container_of(work, struct macaudio_snd_data, sw_gain_stop_work); - macaudio_stop_playback(ma, true); + macaudio_stop_playback(ma, ma->cfg->amp == AMP_MAX98360A); } static int macaudio_copy_link(struct device *dev, struct snd_soc_dai_link *target, diff --git a/tools/asahi/aop-bootargs-tests.py b/tools/asahi/aop-bootargs-tests.py new file mode 100644 index 0000000000000..aba3842077664 --- /dev/null +++ b/tools/asahi/aop-bootargs-tests.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise production bootarg patching with synthetic MMIO.""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + +HARNESS = r''' +#![allow(dead_code)] +use std::{cell::{Cell,RefCell},marker::PhantomData,mem,ops::{Deref,DerefMut}}; +type Result = std::result::Result; +const EINVAL:i32=-22; const EIO:i32=-5; const GFP_KERNEL:u32=0; +const AOP_MMIO_SIZE:usize=128; const BOOTARGS_OFFSET:usize=16; const BOOTARGS_SIZE:usize=20; +struct KVec(Vec); +impl KVec{fn from_elem(v:T,n:usize,_:u32)->Result{Ok(Self(vec![v;n]))}} +impl Deref for KVec{type Target=Vec;fn deref(&self)->&Vec{&self.0}} +impl DerefMut for KVec{fn deref_mut(&mut self)->&mut Vec{&mut self.0}} +struct Region; +struct Device{bytes:RefCell>,writes:RefCell>,fail:Cell} +struct Mmio<'a,T>{dev:&'a Device,_p:PhantomData} +impl<'a,T> Mmio<'a,T>{ + fn size(&self)->usize{self.dev.bytes.borrow().len()} + fn read32(&self,at:usize)->u32{self.try_read32(at).unwrap()} + fn try_read32(&self,at:usize)->Result{assert_eq!(at%4,0);Ok(u32::from_le_bytes(self.dev.bytes.borrow()[at..at+4].try_into().unwrap()))} + fn try_write32(&self,v:u32,at:usize)->Result{assert_eq!(at%4,0);self.dev.writes.borrow_mut().push(at);if !self.dev.fail.get(){self.dev.bytes.borrow_mut()[at..at+4].copy_from_slice(&v.to_le_bytes());}Ok(())} + fn try_cast(&self)->Result>{Ok(Mmio{dev:self.dev,_p:PhantomData})} +} +struct IoSlice<'a>{dev:&'a Device,start:usize,end:usize} +impl IoSlice<'_>{ + fn copy_to_slice(&self,v:&mut[u8]){v.copy_from_slice(&self.dev.bytes.borrow()[self.start..self.end]);} + fn copy_from_slice(&self,v:&[u8]){self.dev.bytes.borrow_mut()[self.start..self.end].copy_from_slice(v);} +} +macro_rules! io_project {($io:ident,[try: $start:ident .. $($end:tt)*])=>{IoSlice{dev:$io.dev,start:$start,end:$($end)*}};} +struct Aop; +impl Aop { METHOD } +fn fixture(offset:usize,table:&[u8])->Device{ + let mut bytes=vec![0xa5;AOP_MMIO_SIZE];bytes[16..20].copy_from_slice(&(offset as u32).to_le_bytes());bytes[20..24].copy_from_slice(&(table.len() as u32).to_le_bytes()); + if offset+table.len()<=bytes.len(){bytes[offset..offset+table.len()].copy_from_slice(table);} + Device{bytes:RefCell::new(bytes),writes:RefCell::new(Vec::new()),fail:Cell::new(false)} +} +fn patch(dev:&Device,word:bool)->Result{Aop.patch_bootargs(&Mmio{dev,_p:PhantomData::>},&[(1,0x12345678),(2,0x87654321)],word)} +fn main(){ + let table:[u8;24]=[1,0,0,0,4,0,0,0,0,0,0,0,2,0,0,0,4,0,0,0,0,0,0,0]; + for offset in 32..36 {for word in [false,true] { + let d=fixture(offset,&table);let mut expected=d.bytes.borrow().clone();expected[offset+8..offset+12].copy_from_slice(&0x12345678u32.to_le_bytes());expected[offset+20..offset+24].copy_from_slice(&0x87654321u32.to_le_bytes()); + assert_eq!(patch(&d,word),Ok(()));assert_eq!(*d.bytes.borrow(),expected,"adjacent bytes changed"); + assert!(d.writes.borrow().iter().all(|&x|x%4==0&&x>=offset&!3&&x+4<=(offset+table.len()+3)&!3)); + if word {assert!(!d.writes.borrow().is_empty());}else{assert!(d.writes.borrow().is_empty());} + let writes=d.writes.borrow().len();assert_eq!(patch(&d,word),Ok(()));assert_eq!(d.writes.borrow().len(),writes,"unchanged words rewritten"); + }} + let mut malformed=table;malformed[16..20].copy_from_slice(&9u32.to_le_bytes()); + for word in [false,true]{let d=fixture(35,&malformed);let before=d.bytes.borrow().clone();assert_eq!(patch(&d,word),Err(EINVAL));assert_eq!(*d.bytes.borrow(),before);assert!(d.writes.borrow().is_empty());} + for tail in 1..8 {let d=fixture(35,&table[..12+tail]);assert_eq!(patch(&d,true),Err(EINVAL));assert!(d.writes.borrow().is_empty());} + let d=fixture(35,&table);d.fail.set(true);assert_eq!(patch(&d,true),Err(EIO),"readback error ignored"); + assert_eq!(patch(&fixture(35,&[]),true),Err(EINVAL));assert_eq!(patch(&fixture(35,&[]),false),Ok(())); + assert_eq!(patch(&fixture(120,&table),true),Err(EINVAL)); + println!("PASS aligned/unaligned byte and word access, unchanged writes, malformed tables, bounds and failed readback"); +} +''' + + +def method(source): + start = source.index(' fn patch_bootargs(') + at = source.index('{', start) + depth = 1 + end = at + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--source', type=Path, default=Path(__file__).resolve().parents[2] / 'drivers/soc/apple/aop.rs') + args = parser.parse_args() + production = method(args.source.read_text()) + macros = ''.join('macro_rules! ' + name + ' {($($t:tt)*)=>{()};}\n' for name in ['dev_info', 'dev_err'] if name + '!' in production) + code = HARNESS.replace('METHOD', production).replace('struct Aop;', macros + 'struct Aop;') + with tempfile.TemporaryDirectory(prefix='aop-bootargs-') as tmp: + p = Path(tmp) / 'test.rs' + binary = p.with_suffix('') + p.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(p), '-o', str(binary)], check=True) + subprocess.run([str(binary)], check=True) + bad = code.replace('if aop_mmio.try_read32(address)? != value {', 'if false {') + assert bad != code + p.write_text(bad) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(p), '-o', str(binary)], check=True) + result = subprocess.run([str(binary)], capture_output=True, text=True) + assert result.returncode != 0 and 'readback error ignored' in result.stderr + print('PASS negative control: missing write verification') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-t6041-initdata-tests.py b/tools/asahi/g17-t6041-initdata-tests.py new file mode 100644 index 0000000000000..34815f80cf383 --- /dev/null +++ b/tools/asahi/g17-t6041-initdata-tests.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check T6041 initialization data against caller-supplied captures.""" + +import argparse +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +DRIVER = Path(__file__).resolve().parents[2] / "drivers/gpu/drm/asahi" + + +def item(source, start): + """Extract an item and its attributes.""" + at = source.index(start) + line = source.rfind("\n", 0, at) + 1 + while True: + previous = source.rfind("\n", 0, line - 1) + 1 + if line == 0 or not source[previous:line].lstrip().startswith("#["): + break + line = previous + depth = 0 + end = at + while True: + c = source[end] + if c in "([{": + depth += 1 + elif c in ")]}": + depth -= 1 + if depth == 0 and c == "}" and not re.match( + r"(pub\(crate\) )?(const|static) (?!fn )", source[at:] + ): + return source[line : end + 1] + elif c == ";" and depth == 0: + return source[line : end + 1] + end += 1 + + +HEADER = r""" +#![allow(dead_code, unused_imports, unused_variables, clippy::all)] +use core::mem::size_of; +#[derive(Debug)] +pub struct Error(i32); +pub const EINVAL: Error = Error(-22); +pub const EOVERFLOW: Error = Error(-75); +impl From for Error { + fn from(_: core::num::TryFromIntError) -> Self { EINVAL } +} +pub type Result = core::result::Result; +pub unsafe trait Zeroable {} +macro_rules! static_assert { ($e:expr $(,)?) => { const _: () = assert!($e); }; } +pub fn clear(object: &mut T) { + unsafe { core::ptr::write_bytes(object as *mut T, 0, 1) } +} +const PAGE_SIZE: usize = 0x4000; +""" + +INITDATA_ITEMS = [ + "pub(crate) const REGISTER_MAP_SLOTS", + "pub(crate) struct RegisterWindow", + "const RESERVED_SLOT_UNK_20", + "pub(crate) struct RegisterMapEntry", + "unsafe impl Zeroable for RegisterMapEntry", + "impl RegisterMapEntry", + "pub(crate) const PERF_STATES", + "const PERF_LANES", + "pub(crate) const OPP_CELLS", + "pub(crate) struct Opp ", + "pub(crate) struct PerfConfig", + "pub(crate) struct PerfGroup", + "unsafe impl Zeroable for PerfGroup", + "struct PerfState", + "impl PerfGroup", + "fn perf_states", + "pub(crate) struct CompletionRingDescriptor", + "unsafe impl Zeroable for CompletionRingDescriptor", + "const COMPLETION_RING_DESCRIPTORS", + "pub(crate) const COMPLETION_RING_INDEX", + "const COMPLETION_RING_ENTRIES", + "const COMPLETION_RING_ENTRY_SIZE", + "pub(crate) struct CompletionRing ", + "pub(crate) struct HwDataArgs", + "type Words", + "fn fill_words", + "pub(crate) const CONTEXT_SWITCH_TIMER_MASK", + "pub(crate) const CONTEXT_SWITCH_TIMER_MULTIPLIER", + "pub(crate) struct RegionCConfig", + "pub(crate) struct RegionC ", + "unsafe impl Zeroable for RegionC ", + "impl RegionC ", +] + +SOC_ITEMS = [ + "pub(crate) const CHIP_ID", + "pub(crate) const REGISTER_WINDOWS", + "pub(crate) const PERF", + "pub(crate) const OPPS", + "const REGION_C", +] + +T6041_ITEMS = SOC_ITEMS + [ + "const RESERVED_SLOTS", + "const MAX_POWER_MW", + "const CHIP: ", + "const HW_DATA_WORDS", + "const POWER_CONFIG_WORDS", +] + +T6041_OPP_HZ = [0, 338, 618, 796, 924, 952, 1056, 1062, 1182, 1182, 1312, 1242, 1380, 1326, + 1470, 1578] +T6041_OPP_MV = [ + [125, 600, 665, 705, 725, 770, 770, 810, 810, 860, 860, 900, 900, 940, 940, 1020], + [125, 600, 665, 705, 725, 770, 770, 810, 810, 860, 860, 895, 895, 925, 925, 1020], + [125, 600, 660, 700, 715, 770, 770, 805, 805, 860, 860, 900, 900, 940, 940, 1020], + [125, 600, 660, 705, 730, 780, 780, 810, 810, 860, 860, 900, 900, 940, 940, 1020], +] +T6041_AUX = [(24, 585000), (338, 585000), (618, 635000), (796, 685000), (992, 720000), + (1188, 770000), (1380, 855000), (1470, 885000)] + + +def opps(name, hz, mv): + rows = [] + for index, freq in enumerate(hz): + cells = [m[index] * 1000 for m in mv] + [0] * (16 - len(mv)) + rows.append( + "Opp { freq_hz: %d, volt_uv: [%s], cells: %d }" + % (freq * 1_000_000, ", ".join(map(str, cells)), len(mv)) + ) + return "const %s: [Opp; %d] = [%s];\n" % (name, len(rows), ",\n".join(rows)) + + +def aux(name, rows): + body = ",\n".join( + "Opp { freq_hz: %d, volt_uv: [%d, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], cells: 1 }" + % (mhz * 1_000_000, uv) + for mhz, uv in rows + ) + return "const %s: [Opp; %d] = [%s];\n" % (name, len(rows), body) + + +MAIN = r""" +fn build( + chip_id: u32, + windows: &[RegisterWindow], + reserved: &[usize], + perf: &PerfConfig, + opps: &[Opp], + aux: &[Opp], + chip: &v25g83::Chip, + region_c: &RegionCConfig, + cores: u32, +) -> (Vec, Vec, Vec) { + let args = HwDataArgs { + chip_id, + windows, + reserved_slots: reserved, + opps, + perf, + completion_rings: [ + CompletionRing { low_va: 0x70_03f0_0000, high_va: 0xffff_fc20_0000_0000 }, + CompletionRing { low_va: 0x70_03f2_8000, high_va: 0xffff_fc20_0002_8000 }, + ], + qos_va: 0xffff_fc20_0004_0000, + }; + let ext = v25g83::HwDataArgs25G83 { active_cores: cores, cs_opps: aux, afr_opps: aux, chip: Some(chip) }; + let mut hw: Box = unsafe { Box::new(core::mem::zeroed()) }; + hw.init(&args, &ext).unwrap(); + let mut power: Box = unsafe { Box::new(core::mem::zeroed()) }; + power.init(0xffff_fc20_000d_3440, 0, 0, chip.max_power_mw, &chip.leakage); + power.apply_chip(chip).unwrap(); + let mut region: Box = unsafe { Box::new(core::mem::zeroed()) }; + region.init(region_c); + region.max_power_mw = region_c.max_power_mw; + let hw_bytes = unsafe { + core::slice::from_raw_parts((&*hw as *const v25g83::HwData25G83).cast::(), + size_of::()) + }.to_vec(); + let region_bytes = unsafe { + core::slice::from_raw_parts((&*region as *const RegionC).cast::(), size_of::()) + }.to_vec(); + (hw_bytes, power.0.to_vec(), region_bytes) +} + +fn main() { + let out = std::env::args().nth(1).unwrap(); + let (hw, power, region) = build(t6041::CHIP_ID, &t6041::REGISTER_WINDOWS, + &t6041::RESERVED_SLOTS, &t6041::PERF, &T6041_OPPS, &T6041_AUX, &t6041::CHIP, + &t6041::REGION_C, 40); + println!("T6041 initialization objects built"); + std::fs::write(format!("{}/t6041-hwdata.bin", out), hw).unwrap(); + std::fs::write(format!("{}/t6041-power-config.bin", out), power).unwrap(); + std::fs::write(format!("{}/t6041-region-c.bin", out), region).unwrap(); +} +""" + + +def program(): + initdata = (DRIVER / "g17/fw/initdata.rs").read_text() + v25g83 = (DRIVER / "g17/fw/initdata/v25g83.rs").read_text() + t6041 = (DRIVER / "hw/t6041.rs").read_text() + v25g83 = re.sub(r"use super::\{[^}]*\};", "use super::*;", v25g83, count=1) + v25g83 = v25g83.replace("use kernel::prelude::*;", "") + float_source = (DRIVER / "float.rs").read_text().split("impl<'a> TryFrom +#include +#include +int main(int argc, char **argv) { + using namespace ane::h13; + ConvShape shape{1, 1, 2, 1, false, {128, 56, 56}, {256, 28, 28}}; + if (argc == 1) { + auto why = convGenericRefusal(shape); + std::cout << why << "\n"; + return why.find("8 interleaved lanes") == std::string::npos; + } + // Nonzero, exactly representable fp16 weights; no private compiler output. + std::vector weights(256 * 128 * 2); + for (unsigned i = 0; i < weights.size() / 2; ++i) { + const unsigned half = 0x2400 + (i * 17 % 0x400); + weights[2 * i] = half; weights[2 * i + 1] = half >> 8; + } + auto bytes = encodeANEC(encodeConvGeneric(shape, weights.data(), weights.size(), nullptr, 0)); + std::ofstream(argv[1], std::ios::binary).write((const char *)bytes.data(), bytes.size()); + return 0; +} +''' + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("compiler", type=Path, help="clean mil-hwx-compiler checkout at pinned PR 2 commit") + p.add_argument("output", type=Path) + p.add_argument("--cxx", default="c++") + args = p.parse_args() + source = args.compiler.resolve() + head = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip() + if head != COMMIT: + p.error(f"compiler HEAD must be {COMMIT}") + directory = source / "plugins/H13" + # Compare all encoder inputs with the licensed public commit. The bypass is + # confined to a temporary translation unit; the checkout stays unmodified. + for item in directory.iterdir(): + if item.suffix in (".cpp", ".h", ".inc"): + original = subprocess.check_output(["git", "-C", str(source), "show", f"HEAD:plugins/H13/{item.name}"]) + if item.read_bytes() != original: + p.error(f"modified encoder input: {item.name}") + program = (directory / "H13Program.cpp").read_text() + if program.count(GUARD) != 1: + p.error("expected refusal changed") + args.output = args.output.resolve() + args.output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="ane-hang-fixture-") as temporary: + tmp = Path(temporary) + (tmp / "fixture.cpp").write_text(DRIVER) + def build(unit): + subprocess.run([args.cxx, "-std=c++17", "-O2", "-I", str(directory), + str(unit), str(directory / "H13ANEC.cpp"), str(tmp / "fixture.cpp"), + "-o", str(tmp / "fixture")], check=True) + build(directory / "H13Program.cpp") + subprocess.run([str(tmp / "fixture")], check=True) # normal compiler must refuse + (tmp / "H13Program.cpp").write_text(program.replace(GUARD, "chunks.size() != 1")) + build(tmp / "H13Program.cpp") + subprocess.run([str(tmp / "fixture"), str(args.output)], check=True) + receipt = {"compiler": COMMIT, "shape": "1x1 s2 128->256 56->28", "bias": False, + "sha256": hashlib.sha256(args.output.read_bytes()).hexdigest(), + "bytes": args.output.stat().st_size} + args.output.with_suffix(".json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps(receipt)) + + +if __name__ == "__main__": + main() diff --git a/tools/testing/selftests/drivers/ane/pm.kunitconfig b/tools/testing/selftests/drivers/ane/pm.kunitconfig new file mode 100644 index 0000000000000..f98c6bc08df1f --- /dev/null +++ b/tools/testing/selftests/drivers/ane/pm.kunitconfig @@ -0,0 +1,5 @@ +CONFIG_KUNIT=y +CONFIG_PM=y +CONFIG_DRM=y +CONFIG_DRM_ACCEL=y +CONFIG_DRM_ACCEL_ANE_PM_KUNIT_TEST=y diff --git a/tools/testing/selftests/drivers/ane/recovery.py b/tools/testing/selftests/drivers/ane/recovery.py new file mode 100755 index 0000000000000..9d76725e0bb6e --- /dev/null +++ b/tools/testing/selftests/drivers/ane/recovery.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Destructive H13 hang/recovery test. Run only with exclusive device ownership.""" +import argparse +import errno +import fcntl +import hashlib +import json +import mmap +import os +from pathlib import Path +import signal +import struct +import sys +import time + +# include/uapi/drm/ane_accel.h, Linux arm64's generic ioctl encoding. +CAPS = struct.Struct("<8I") +BO_INIT = struct.Struct(" self.tsk_size or + self.size != ((self.tsk_size + 15) & ~15) + kernel or + len(self.data) - 4096 > self.size or self.size > 16 * 1024 * 1024 or + self.size > self.tiles[0] * TILE or self.tsk_size >= self.tiles[0] * TILE or + not self.tiles[4] or not self.tiles[5] or + bool(self.tiles[6]) != (self.inputs == 2) or + any(n for i, n in enumerate(self.tiles) if i not in (0, 4, 5, 6)) or + sum(self.tiles) * TILE > 64 * 1024 * 1024): + raise ValueError("unexpected canonical H13 ANEC layout") + self.payload = self.data[4096:].ljust(self.size, b"\0") + + +class Program: + def __init__(self, fixture, node): + self.fd = os.open(node, os.O_RDWR | os.O_CLOEXEC) + self.buffers = {} + self.bootstrap = None + self.fixture = fixture + try: + caps = bytearray(CAPS.size) + fcntl.ioctl(self.fd, request(0, CAPS), caps) + _, size, abi, chip, *_ = CAPS.unpack(caps) + if size != CAPS.size or abi != 1 or chip != 13: + raise RuntimeError("H13 ABI 1 required") + for channel, tiles in enumerate(fixture.tiles): + if tiles: + self.buffers[channel] = self.allocate(tiles * TILE) + self.bootstrap = self.allocate((fixture.td_size + TILE - 1) & ~(TILE - 1)) + self.buffers[0][1][:fixture.size] = fixture.payload + self.bootstrap[1][:fixture.td_size] = fixture.payload[:fixture.td_size] + header, = struct.unpack_from("