Skip to contentSkip to conversation

Arm Core Local Accelerator Driver

RFC PATCH Superseded Ryan Roberts 8 participants 55 messages Oct 15 – Nov 22

Subsystems (7)
lore
Share & tools
lore
#0 lore raw

v2 cover Arm Core Local Accelerator Driver

Hi All,

This is v2 of an RFC to introduce a driver for the Arm Core Local Accelerator (CLA), a CPU-local interface for programming attached accelerators. While the interface is agnostic to the accelerator type, the initial (and currently only) target is a compute engine.

The RFC aims to engage the community and get feedback on some key aspects. This will help plan our approach for eventual upstreaming. Based on feedback from Will and Marc in RFCv1, the driver now supports both bare metal and virtualized environments. I also have commitments to publish the CLA spec, a supporting FVP and a representaive user space, all to support upstreaming the driver, as per Will's feedback.

For now you can find documentation included with patch 1, which describes the HW and driver design. Note that the CLA is not part of the Arm Architecture.

Patch 1 documents the hardware and driver design, and adds a driver skeleton. Patches 2-5 initialize and probe the device. Patches 6-9 add context management for switching the device between different users. Patches 10-12 add some (small) changes to KVM and VFIO, which then enables patches 13-15 to expose the HW for device assignment into a VM.

Aspects I'm seeking feedback for:

* The general structure of the driver: The current shape addresses the performance requirements we have for the use cases, and is therefore our preferred approach. But there are some unusual aspects due to the HW design.

* Driver interaction with architectural support: I've opted to treat the CLA as a device rather than a CPU extension, so it's implemented as a (mostly) self-contained driver. It has some unavoidable coupling to the arch code since it needs to share page tables and ASIDs/VMIDs. All arm64 arch interaction is contained in cla-mtc.c.

* The location of the driver: although most accelerators will likely be compute ones, CLA is a generic MMIO interface that could handle any kind of accelerator. It's currently implemented as a misc driver. accel is another potential option, but given the current SVA approach, we would not use any of the services (memory-management or otherwise) that accel provides.

* Virtualization support: since the HW uses the CPU's MMU, we introduced a new VFIO_CPU_MMU group type, and added the kvm_arch_[get|put]_guest_mmu() API to KVM/arm64 so that the CLA can share the stage2 pgtables and VMID. The CPU pinning problem remains unsolved; the vCPU must be pinned to the pCPU that owns the CLA in order to access it. If the pCPU goes offline or the vCPU is otherwise unpinned, it would look to the guest like the HW is faulty. This issue is therefore contained to the guest. I've additionally improved the robustness of the core driver to deal with this eventuality gracefully.

I consider the core driver to be well tested and robust. The virtualization portion is prototype and has known issues that would be addressed assuming the approach gets positive feedback.

Changes since RFCv1 [1]
=======================

- Added KVM guest support through VFIO mdev, including exclusive domain assignment, stage-2 memory translation and VMID pinning
- Changed the userspace ABI to expose one /dev/cla/<class-id> device per accelerator class; ARM_CLA_PARAM_DEV_ACCELS now reports only accelerators belonging to the opened class (per Arnd)
- Removed ARM_CLA_UABI_VERSION and the ARM_CLA_PARAM_UABI_VERSION query (per Arnd)
- Various driver bug fixes and robustness improvements

Source, along with some tests, is available at [2]. Patches based on v7.3-rc5.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://gitlab.arm.com/linux-arm/linux-rr/-/tree/features/cla-driver-v2-rfc-tests

Thanks,
Ryan

Jean-Philippe Brucker (10):
misc/arm-cla: Add driver skeleton and documentation misc/arm-cla: Add launch operation helpers misc/arm-cla: Probe firmware-described devices misc/arm-cla: Initialize devices on CPU bringup misc/arm-cla: Accelerator context save and restore
KVM: arm64: Export stage-2 MMU config
vfio: Support VFIO devices that access the CPU MMU misc/arm-cla: Add stage-2 MTC and VM context switch misc/arm-cla: Support exclusive context assignment misc/arm-cla: Add vfio-mdev user interface

Ryan Roberts (4):
dt-bindings: misc: Add Arm Core Local Accelerator misc/arm-cla: Set up memory translation context misc/arm-cla: Manage domain contexts misc/arm-cla: Add userspace interface

Shameer Kolothum (1):
KVM: arm64: Introduce support to pin VMIDs

 .../devicetree/bindings/misc/arm,cla.yaml     |  77 +++
 Documentation/misc-devices/arm-cla.rst        | 217 +++++++
 Documentation/misc-devices/index.rst          |   1 +
 MAINTAINERS                                   |   9 +
 arch/arm64/include/asm/kvm_host.h             |  14 +
 arch/arm64/include/asm/kvm_mmu.h              |   1 +
 arch/arm64/kvm/mmu.c                          | 102 ++++
 arch/arm64/kvm/sys_regs.c                     |  14 +-
 arch/arm64/kvm/vmid.c                         |  77 ++-
 drivers/misc/Kconfig                          |   1 +
 drivers/misc/Makefile                         |   1 +
 drivers/misc/arm-cla/Kconfig                  |  26 +
 drivers/misc/arm-cla/Makefile                 |  15 +
 drivers/misc/arm-cla/arm-cla-regs.h           | 192 ++++++
 drivers/misc/arm-cla/arm-cla.h                | 393 ++++++++++++
 drivers/misc/arm-cla/cla-ctx.c                | 229 +++++++
 drivers/misc/arm-cla/cla-init.c               | 562 ++++++++++++++++++
 drivers/misc/arm-cla/cla-mdev.c               | 469 +++++++++++++++
 drivers/misc/arm-cla/cla-mtc.c                | 335 +++++++++++
 drivers/misc/arm-cla/cla-ops.c                | 417 +++++++++++++
 drivers/misc/arm-cla/cla-regs.c               | 370 ++++++++++++
 drivers/misc/arm-cla/cla-sched.c              | 474 +++++++++++++++
 drivers/misc/arm-cla/cla-topology.c           | 202 +++++++
 drivers/misc/arm-cla/cla-user.c               | 541 +++++++++++++++++
 drivers/vfio/group.c                          |  37 +-
 drivers/vfio/vfio.h                           |   5 +
 drivers/vfio/vfio_main.c                      |  16 +-
 include/linux/vfio.h                          |   1 +
 include/uapi/linux/arm-cla.h                  | 198 ++++++
 29 files changed, 4969 insertions(+), 27 deletions(-)
 create mode 100644 Documentation/devicetree/bindings/misc/arm,cla.yaml
 create mode 100644 Documentation/misc-devices/arm-cla.rst
 create mode 100644 drivers/misc/arm-cla/Kconfig
 create mode 100644 drivers/misc/arm-cla/Makefile
 create mode 100644 drivers/misc/arm-cla/arm-cla-regs.h
 create mode 100644 drivers/misc/arm-cla/arm-cla.h
 create mode 100644 drivers/misc/arm-cla/cla-ctx.c
 create mode 100644 drivers/misc/arm-cla/cla-init.c
 create mode 100644 drivers/misc/arm-cla/cla-mdev.c
 create mode 100644 drivers/misc/arm-cla/cla-mtc.c
 create mode 100644 drivers/misc/arm-cla/cla-ops.c
 create mode 100644 drivers/misc/arm-cla/cla-regs.c
 create mode 100644 drivers/misc/arm-cla/cla-sched.c
 create mode 100644 drivers/misc/arm-cla/cla-topology.c
 create mode 100644 drivers/misc/arm-cla/cla-user.c
 create mode 100644 include/uapi/linux/arm-cla.h

--
2.43.0

#1 lore raw

RFC PATCH v2 1/15 misc/arm-cla: Add driver skeleton and documentation

From: Jean-Philippe Brucker <[email protected]>

Add the initial Kconfig and build-system plumbing for the Arm Core Local Accelerator driver.

Introduce the common driver header and register definitions used by later CLA support. The definitions cover the CLA MMIO frame, launch response and status fields, standard accelerator registers, launch opcodes, error codes and memory translation context state.

Add documentation describing the CLA programming model, its CPU-local MMIO access rules, userspace assignment model, domain grouping and expected boot state.

---
 Documentation/misc-devices/arm-cla.rst | 217 +++++++++++++++++++++++++
 Documentation/misc-devices/index.rst   |   1 +
 MAINTAINERS                            |   7 +
 drivers/misc/Kconfig                   |   1 +
 drivers/misc/Makefile                  |   1 +
 drivers/misc/arm-cla/Kconfig           |  10 ++
 drivers/misc/arm-cla/Makefile          |   1 +
 drivers/misc/arm-cla/arm-cla-regs.h    | 178 ++++++++++++++++++++
 drivers/misc/arm-cla/arm-cla.h         |  36 ++++
 9 files changed, 452 insertions(+)
 create mode 100644 Documentation/misc-devices/arm-cla.rst
 create mode 100644 drivers/misc/arm-cla/Kconfig
 create mode 100644 drivers/misc/arm-cla/Makefile
 create mode 100644 drivers/misc/arm-cla/arm-cla-regs.h
 create mode 100644 drivers/misc/arm-cla/arm-cla.h
Documentation/misc-devices/arm-cla.rst new file +217 -0
new file mode 100644
index 000000000000..6ce38b9b7e61
@@ -0,0 +1,217 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================================
+Arm Core Local Accelerator (CLA)
+================================
+
+Arm CLA is an interface local to a CPU for programming accelerators that access
+memory via the CPU's MMU::
+
+              ┌───────┬───────┬───────┐  ┌───────┐
+              │  CPU  │  MMU  │  CLA  │  │ Accel │─┐
+              │       │       │       │  │       │ │
+              │      ---MMIO-->       <-->       │ │
+              │       │       │       │  │       │ │
+              │       │    ,-----DMA----->       │ │
+              └───────┴────|──┴───────┘  └───────┘ │
+                ┌──────────v────────┐      └───────┘
+                │ Caches and memory │
+                └───────────────────┘
+
+
+Hardware
+========
+
+The CLA supports up to 8 attached accelerators, which are accessed by
+programming the CLA's MMIO registers. Operations are launched to an accelerator
+and are polled for completion. CLA does not raise interrupts.
+
+::
+
+            CPU                     CLA              Accel
+             |--- write DATA[7:0] -->|                 |
+             |--- write LAUNCH ----->|---- launch ---->|
+             |<--- poll LRESP -------|                 |
+             |                       |                 |
+             |<--- poll STATUS ------|<--- complete ---|
+
+Each operation can take a 512-bit payload in the DATA registers. After handling
+a LAUNCH write, CLA indicates the launch status in the LRESP register. A further
+operation can only be launched after LRESP indicates completion of the previous
+launch.
+
+Some operations continue to run asynchronously on the accelerator after launch
+completion. In this case progress is tracked by polling the STATUS register.
+When the CLA updates the STATUS register, it also raises an event which will
+wake an in-progress WFE (wait for event) instruction on the local CPU.
+
+The CLA's MMIO registers are not accessible from remote CPUs. Although each CLA
+has a unique physical address, accesses from remote CPUs are read as zero and
+write ignored.
+
+The CLA registers are accessible from four different Privilege Level (PL)
+frames, with usage inteded to map to EL0 - EL3. The PLxCTRL registers may be
+written via a higher PL frame to suppress access to accelerators via a lower PL
+frame.
+
+The CPU and CLA share an MMU, although FEAT_TTCNP (common not private) is
+implemented, allowing both CPU and CLA to independently opt into and out of
+sharing TLB entries at runtime. TLB invalidation is performed via the CPU TLBI
+instructions; any TLBI instruction that targets the CLA's local CPU will also
+implicitly target the CLA.
+
+CLA has its own set of Memory Translation Context (MTC) registers, distinct from
+the CPU. A PL can set the MTC registers corresponding to an equivalent CPU
+Exception Level (EL) (eg. TCR_EL2 configurable only from the PL2 and PL3 MMIO
+frame).
+
+Faults during address translation are reported by the accelerator in its
+registers and in STATUS. While polling for work completion, software fixes up
+the faults and notifies the accelerator with RESOLVE operations.
+
+Accesses to the MMIO registers must be aligned 64-bit loads and stores, and the
+registers are mapped with Device-nGnRE attribute. Invalid accesses (unaligned,
+atomic, badly sized, etc) to the MMIO frame are either read as zero and write
+ignored, or cause a data abort, depending on the platform. Invalid access will
+never cause an SError.
+
+
+Inter-Accelerator Communication
+-------------------------------
+
+On some platforms, multiple accelerators, each attached to a separate CLA within
+a cluster, are also directly connected to each other via a shared bus to
+accelerate cooperation between accelerators. The accelerators sharing a bus
+cannot be isolated from each other. When collaborative operations are launched
+on each of the participating accelerators, they synchronize over the bus,
+stalling until all are ready.
+
+
+Intended SW Usage Model
+=======================
+
+CLA is designed for its PL0 MMIO frame to be mapped into user space and for user
+space to directly launch accelerator operations and poll for completion. It has
+been observed that for some use cases, the operation execution time is small and
+a trip through the kernel would consume a significant amount of the CPU budget
+for preparing the next operation leading to a significant reduction in bandwidth
+through the accelerator.
+
+User space software is expected to create a thread to drive each CLA it is
+using, and for each thread to be pinned to the CLA's local CPU.
+
+Software should rely on WFE (wait for event) to reduce power consumption when
+polling STATUS.
+
+The CLA is intended to be configured, by privileged software via PL1 and/or PL2,
+so that it shares virtual addresses with the process to which it is assigned
+(SVA). In practice this means configuring the CLA's MTC to point to the same
+page tables and use the same ASID (and VMID if relevant) as the process to which
+it is assigned. This ensures the architectural TLB invalidations also correctly
+target the CLA's TLB entries.
+
+We investigated the possibility of having the CLA driver allocate private page
+tables, private ASIDs/VMIDs and implement an MMU notifier for invalidation, but
+that suffers from 2 issues; there is a possibility of over-invalidation since
+the ASID and VMID spaces overlap with the CPU's (minor), and when issuing a
+TLBI, VMID is implicitly taken from CPU's VTTBR_EL2.VMID, which won't match the
+CLA's private VMID - therefore, for a virtualization scenario, TLB invalidation
+becomes impossible (major).
+
+Because the CLA has its own MTC registers, it is correct and safe for it to be
+executing an operation on behalf of user process A, while its local CPU is
+executing a thread from user process B.
+
+
+Difficulties for software to deal with
+--------------------------------------
+
+Although each CLA is attached to a single CPU, not all CPUs have a CLA, and CLAs
+may have a different set of accelerators attached. Users need to probe around to
+find a suitable accelerator and bind their process to it.
+
+Since remote CPUs can't access the CLA, dealing with CPU hotplug migrating tasks
+is challenging. And virtualization breaks down if the hypervisor cannot
+guarantee that a vCPU is pinned to a CPU.
+
+Saving and restoring the internal state of the accelerator is an optional
+feature. If an accelerator cannot preserve in-flight work, preempting it cancels
+that work. Software must carefully consider how to balance forward-progress
+guarantees with preemption latency.
+
+
+Driver
+======
+
+Booting
+-------
+
+A host expects to be booted with CLAs in the following state:
+
+- All attached accelerators have STATUS_IDLE set.
+- PL2CTRL: AVAIL all enabled for attached accelerators.
+  DBG at the firmware's discretion, preferably all enabled.
+- TSCTRLOWNER.PL, TSOFFOWNER.PL, PMUOWNER.PL all EL2.
+
+A guest expects to be booted with CLAs in the following state:
+
+- All attached accelerators have STATUS_IDLE set.
+- PL1CTRL: AVAIL all enabled for attached accelerators.
+  DBG at the hypervisor's discretion, preferably all enabled.
+
+Linux discovers the base address of each CLA device in the firmware tables and
+creates platform devices. cla_dev behaves mostly like a regular platform device,
+but it can only be accessed from one specific CPU. CPU hotplug notifiers probe
+and teardown the CLA device.
+
+CLAs may be grouped into domains. The topology is described in the firmware
+tables, and the driver creates cla_domain objects containing one or more
+cla_dev.
+
+
+Assignment to userspace
+-----------------------
+
+One char device per accelerator class provides enumeration and mmap abilities
+through ``/dev/cla/<class-id>``. Accelerators belong to the same class when
+their IIDR.IMPLEMENTER and IIDR.PRODUCTID register values match. ``<class-id>``
+is encoded as ``<IIDR.IMPLEMENTER:IIDR.PRODUCTID>``, each part using 3 hex
+digits. All class files enumerate all physical CLAs, with the same device IDs,
+domain IDs and mmap offsets. ``ARM_CLA_PARAM_DEV_ACCELS`` reports only the
+accelerator slots belonging to the opened class, and may be zero.
+
+The user task queries the driver to find a suitable set of CLAs, and mmaps their
+registers. For each mapped domain, the driver creates a cla_ctx context. When
+the user accesses the registers, the driver's fault handler queues the cla_ctx
+and waits for assignment. A context reassignment switches the whole cla_domain,
+by calling each CPU in the domain to switch the CLA context. A time slice is
+given to each context before being deassigned.
+
+In order to access the registers, the task must be bound to the CLA's CPU with
+sched_setaffinity(). Accesses from remote CPUs are ignored. If the CPU gets
+offlined, the task is migrated to an online CPU, and the driver disables the
+offlined CLA. User space may choose to use a mechanism such as restartable
+sequences to be notified when its task has been migrated away from its intended
+CLA.
+
+The accelerators access memory using the CPU's MMU. When assigning a context,
+the driver sets up the CLA's Memory Translation Context (MTC) with the page
+directory (TTBR), address space ID (ASID) and configuration (TCR) of the
+context's mm. When receiving translation faults from the accelerator, the user
+space task accesses the faulting address from the CPU to trigger the fault to be
+fixed up by the kernel before launching a RESOLVE operation to the accelerator.
+
+
+Power management
+----------------
+
+When a CPU enters a deep low-power state, then depending on the platform, the
+attached CLA and accelerators might not retain their state. In that case the
+firmware is expected to save the CLA and accelerator states before entering CPU
+low-power state, and restore them after exiting. The CLA driver does not expect
+to notice a CPU deep idle. However, if an accelerator does not support context
+saving, userspace will notice from the STATUS register that its work was
+canceled during deep idle. Given that userspace would be polling STATUS, the CPU
+is unlikely to enter deep idle while the CLA is running. To ensure
+forward-progress the admin can disable deep idle states (see
+Documentation/admin-guide/pm/cpuidle.rst).
Documentation/misc-devices/index.rst +1 -0
index f911edaecbfa..419c8f5c04ef 100644
@@ -13,6 +13,7 @@ fit into other categories.
 
    ad525x_dpot
    amd-sbi
+   arm-cla
    bh1770glc
    c2port
    dw-xdata-pcie
MAINTAINERS +7 -0
index 72294ddfa5b7..735f6527f920 100644
@@ -2209,6 +2209,13 @@ F:	arch/arm64/include/asm/arch_timer.h
 F:	drivers/clocksource/arm_arch_timer.c
 F:	drivers/clocksource/arm_arch_timer_mmio.c
 
+ARM CORE LOCAL ACCELERATOR (CLA) DRIVER
+M:	Ryan Roberts <[email protected]>
+L:	[email protected] (moderated for non-subscribers)
+S:	Supported
+F:	Documentation/misc-devices/arm-cla.rst
+F:	drivers/misc/arm-cla/
+
 ARM ETHOS-U NPU DRIVER
 M:	Rob Herring (Arm) <[email protected]>
 M:	Tomeu Vizoso <[email protected]>
drivers/misc/Kconfig +1 -0
index 7364931dad3a..1f50c9d39b4c 100644
@@ -586,4 +586,5 @@ source "drivers/misc/keba/Kconfig"
 source "drivers/misc/amd-sbi/Kconfig"
 source "drivers/misc/rp1/Kconfig"
 source "drivers/misc/issei/Kconfig"
+source "drivers/misc/arm-cla/Kconfig"
 endmenu
drivers/misc/Makefile +1 -0
index e8d8d5d88c0d..2615190fee17 100644
@@ -71,3 +71,4 @@ obj-y				+= keba/
 obj-y				+= amd-sbi/
 obj-$(CONFIG_MISC_RP1)		+= rp1/
 obj-$(CONFIG_INTEL_SSEI)	+= issei/
+obj-$(CONFIG_ARM_CLA)		+= arm-cla/
drivers/misc/arm-cla/Kconfig new file +10 -0
new file mode 100644
index 000000000000..f8436a12c1e6
@@ -0,0 +1,10 @@
+config ARM_CLA
+	tristate "Arm Core Local Accelerator"
+	default n
+	depends on ARM64
+	help
+	  Arm Core Local Accelerator (CLA) is coupled with a specific CPU and
+	  provides an interface to enumerate and access attached hardware
+	  accelerators. It is only accessible from its associated CPU.
+
+	  If unsure, say N.
drivers/misc/arm-cla/Makefile new file +1 -0
new file mode 100644
index 000000000000..a4e40e534e6a
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-2.0-only
drivers/misc/arm-cla/arm-cla-regs.h new file +178 -0

178 lines not on this page · raw message

drivers/misc/arm-cla/arm-cla.h new file +36 -0
new file mode 100644
index 000000000000..1e8ffca28bc6
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Arm CLA driver - internal definitions
+ *
+ * Copyright 2026 Arm Limited.
+ */
+#ifndef _ARM_CLA_H_
+#define _ARM_CLA_H_
+
+#include "arm-cla-regs.h"
+
+/* Number of accelerators per CLA */
+#define CLA_NUM_ACC		8
+#define CLA_NUM_DATA_REGS	8
+#define CLA_SRSTATE_LEN		8
+
+/**
+ * struct cla_dev - CLA device
+ *
+ * Immutable state:
+ * @cpu:		The CPU this CLA is attached to.
+ * @dev:		The platform device.
+ */
+struct cla_dev {
+	unsigned int cpu;
+	struct device *dev;
+};
+
+#define cla_dbg(_dev, fmt, ...) \
+	dev_dbg((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)
+#define cla_info(_dev, fmt, ...) \
+	dev_info((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)
+#define cla_err(_dev, fmt, ...) \
+	dev_err((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)
+
+#endif /* _ARM_CLA_H_ */
Signature · 1 line
2.43.0
#2 lore raw

Re: [RFC PATCH v2 01/15] misc/arm-cla: Add driver skeleton and documentation

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] macro: multiple evaluation of macro argument _dev --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] macro: multiple evaluation of macro argument _dev
--

commit eeea2acb1fe471c02eee65ef8f991f70efeb7b69
Author: Jean-Philippe Brucker <[email protected]>

misc/arm-cla: Add driver skeleton and documentation

This commit introduces the initial driver skeleton and documentation for the Arm Core Local Accelerator (CLA). It adds the required Kconfig, Makefile, register definitions, and a common driver header.

Quoted 5 lines
drivers/misc/arm-cla/arm-cla.h new file +0 -0
new file mode 100644
index 0000000000000..1e8ffca28bc6e

[ ... ]

drivers/misc/arm-cla/arm-cla.h line 34

Quoted 11 lines
drivers/misc/arm-cla/arm-cla.h new file +11 -0
+struct cla_dev {
+	unsigned int cpu;
+	struct device *dev;
+};
+
+#define cla_dbg(_dev, fmt, ...) \
+	dev_dbg((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)
+#define cla_info(_dev, fmt, ...) \
+	dev_info((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)
+#define cla_err(_dev, fmt, ...) \
+	dev_err((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)

[Severity: Low]
The _dev macro parameter is evaluated twice here. Could this lead to unintended duplicate execution if a caller passes an expression with side-effects, such as get_device(dev++)?

Would it be safer to rewrite these as static inline functions, or use a statement expression with a local variable to evaluate _dev only once?

Quoted 2 lines
drivers/misc/arm-cla/arm-cla.h new file +2 -0
+
+#endif /* _ARM_CLA_H_ */
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

Re: [RFC PATCH v2 01/15] misc/arm-cla: Add driver skeleton and documentation

In reply to Ryan Roberts

Documentation/misc-devices/arm-cla.rst line 87

Quoted 9 lines · Ryan Roberts
Documentation/misc-devices/arm-cla.rst new file +9 -0
+Inter-Accelerator Communication
+-------------------------------
+
+On some platforms, multiple accelerators, each attached to a separate CLA within
+a cluster, are also directly connected to each other via a shared bus to
+accelerate cooperation between accelerators. The accelerators sharing a bus
+cannot be isolated from each other. When collaborative operations are launched
+on each of the participating accelerators, they synchronize over the bus,
+stalling until all are ready.

What the patch series needs to do is tell us how this topology is discovered. I.e. will it be discoverable from the hardware itself, or will this topology be described in device tree or ACPI for example?

The kernel must certainly know this topology to be able to synchronize work across several cores? What happens if an asynchronous acceleration task is running on some cores and no actual CPU load is on any of them and the kernel want to put them to idle or shut them down? Same problem on the cluster level?

Further since this appears to be hardware topology userspace must obtain this information from the kernel, not the other way around: we cannot have a situation where userspace "just knows" stuff about the hardware, keeping the kernel in the dark.

I think this is a wider question about the discovery of these CLA:s:
there must be a coherent story about how userspace finds it and maps it topology and that information must come from the kernel, so the kernel and userspace have the same map of the world.

Right now IIUC the driver probes from discovery in the hardware from CPU-specific registers so does this discovery also include the topology?

Yours,
Linus Walleij

#4 lore raw

Re: [RFC PATCH v2 01/15] misc/arm-cla: Add driver skeleton and documentation

Quoted 5 lines · Linus Walleij

On Thu, Oct 15, 2026 at 4:26 PM Ryan Roberts <[email protected]> wrote:

What the patch series needs to do is tell us how this topology is discovered. I.e. will it be discoverable from the hardware itself, or will this topology be described in device tree or ACPI for example?

Hm what about I read the whole series before replying to individual pathes. It's righ there in patch 4/15, mea culpa.

Yours,
Linus Walleij

#5 lore raw

Re: [RFC PATCH v2 01/15] misc/arm-cla: Add driver skeleton and documentation

In reply to Ryan Roberts

Hi Ryan, Jean-Philippe,

drivers/misc/arm-cla/arm-cla.h line 24

Quoted 8 lines · Ryan Roberts
drivers/misc/arm-cla/arm-cla.h new file +8 -0
+/**
+ * struct cla_dev - CLA device
+ *
+ * Immutable state:
+ * @cpu:               The CPU this CLA is attached to.
+ * @dev:               The platform device.
+ */
+struct cla_dev {

Don't abbreviate compulsively, cla is fine, I would call it cla_device.

drivers/misc/arm-cla/arm-cla.h line 27

Quoted 3 lines
drivers/misc/arm-cla/arm-cla.h new file +3 -0
+       unsigned int cpu;
+       struct device *dev;
+};

I will argue in other patches that this should be a proper struct device and not a pointer to a platform_devcive &pdev->dev.

Yours,
Linus Walleij

#6 lore raw

RFC PATCH v2 2/15 misc/arm-cla: Add launch operation helpers

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

CLA commands are issued by writing optional payload registers, programming the LAUNCH register and polling LRESP until the hardware accepts or rejects the operation.

Add a common launch helper that performs this sequence on the CLA's local CPU, waits for LRESP completion and translates launch response codes into Linux errors.

Build accelerator reset and register read and write support on top of it. The register read and write helpers split larger accesses into multiple launch operations when an access crosses an eight-register window.

---
 drivers/misc/arm-cla/Makefile   |   6 +
 drivers/misc/arm-cla/arm-cla.h  |  24 +++
 drivers/misc/arm-cla/cla-init.c |  12 ++
 drivers/misc/arm-cla/cla-ops.c  | 293 ++++++++++++++++++++++++++++++++
 4 files changed, 335 insertions(+)
 create mode 100644 drivers/misc/arm-cla/cla-init.c
 create mode 100644 drivers/misc/arm-cla/cla-ops.c
drivers/misc/arm-cla/Makefile +6 -0
index a4e40e534e6a..3fa8567c8b3e 100644
@@ -1 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
+
+arm-cla-y := \
+	cla-init.o \
+	cla-ops.o
+
+obj-$(CONFIG_ARM_CLA) += arm-cla.o
drivers/misc/arm-cla/arm-cla.h +24 -0
index 1e8ffca28bc6..4884e4804ab3 100644
@@ -7,6 +7,9 @@
 #ifndef _ARM_CLA_H_
 #define _ARM_CLA_H_
 
+#include <linux/device.h>
+#include <linux/io.h>
+
 #include "arm-cla-regs.h"
 
 /* Number of accelerators per CLA */
@@ -19,10 +22,12 @@
  *
  * Immutable state:
  * @cpu:		The CPU this CLA is attached to.
+ * @regs:		Registers accessed by the kernel.
  * @dev:		The platform device.
  */
 struct cla_dev {
 	unsigned int cpu;
+	void __iomem *regs;
 	struct device *dev;
 };
 
@@ -33,4 +38,23 @@ struct cla_dev {
 #define cla_err(_dev, fmt, ...) \
 	dev_err((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)
 
+static inline u64 cla_reg_read(struct cla_dev *dev, off_t reg)
+{
+	/* MMIO reads are all relaxed, since the driver doesn't use DMA. */
+	return readq_relaxed(dev->regs + reg);
+}
+
+static inline void cla_reg_write(struct cla_dev *dev, off_t reg, u64 val)
+{
+	/* MMIO writes are all relaxed, since the driver doesn't use DMA. */
+	return writeq_relaxed(val, dev->regs + reg);
+}
+
+int cla_op_wait_lresp(struct cla_dev *dev, u64 *lresp);
+int cla_op_reset(struct cla_dev *dev, unsigned int accid);
+int cla_op_regread(struct cla_dev *dev, unsigned int accid, unsigned int regidx,
+		   size_t nregs, u64 *regs);
+int cla_op_regwrite(struct cla_dev *dev, unsigned int accid,
+		    unsigned int regidx, size_t nregs, u64 *regs);
+
 #endif /* _ARM_CLA_H_ */
drivers/misc/arm-cla/cla-init.c new file +12 -0
new file mode 100644
index 000000000000..3d1f47592842
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Arm CLA driver - probing and initialization
+ *
+ * Copyright 2026 Arm Limited.
+ */
+
+#include <linux/module.h>
+
+MODULE_DESCRIPTION("Arm Core Local Accelerator");
+MODULE_AUTHOR("Arm Limited");
+MODULE_LICENSE("GPL");
drivers/misc/arm-cla/cla-ops.c new file +293 -0

293 lines not on this page · raw message

Signature · 1 line
2.43.0
#7 lore raw

Re: [RFC PATCH v2 02/15] misc/arm-cla: Add launch operation helpers

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] misc/arm-cla: 1-second busy loop in atomic poll function stalls CPU - [High] misc/arm-cla: 32-bit…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] misc/arm-cla: 1-second busy loop in atomic poll function stalls CPU
- [High] misc/arm-cla: 32-bit truncation of max_regidx breaks register access unconditionally --

commit 3a9a1e5f334e803060b4eaff6708691a049dc197
Author: Jean-Philippe Brucker <[email protected]>

misc/arm-cla: Add launch operation helpers

This commit introduces helpers for CLA commands that execute sequences on the local CPU, wait for hardware responses, and translate response codes into Linux errors. It also implements accelerator reset and register read/write operations built upon these helpers.

Quoted 5 lines
drivers/misc/arm-cla/cla-ops.c new file +0 -0
new file mode 100644
index 0000000000000..46026304a057a

[ ... ]

drivers/misc/arm-cla/cla-ops.c line 137

Quoted 13 lines
drivers/misc/arm-cla/cla-ops.c new file +13 -0
+/**
+ * cla_op_wait_lresp - Wait for any LAUNCH op to complete.
+ * @dev: CLA device.
+ * @lresp: last LRESP value read.
+ *
+ * Return: 0 on success, -ETIMEDOUT in case of timeout.
+ */
+int cla_op_wait_lresp(struct cla_dev *dev, u64 *lresp)
+{
+	return readq_relaxed_poll_timeout_atomic(dev->regs + CLA_REG_LRESP,
+			*lresp, FIELD_GET(CLA_LRESP_PENDING, *lresp) == 0,
+			CLA_LRESP_DELAY_US, CLA_LRESP_TIMEOUT_US);
+}

[Severity: High]
Does this atomic polling loop stall the CPU for up to 1 second?

The timeout here is CLA_LRESP_TIMEOUT_US (1,000,000 microseconds). Using the _atomic variant of the poll macro will busy-wait without yielding the CPU.

Since the surrounding code in cla_wait_status_dmb() uses the sleepable poll_timeout_us(), does this context permit sleeping? If so, using the non-atomic readq_relaxed_poll_timeout() macro might prevent long scheduler delays.

[ ... ]

Quoted 8 lines
drivers/misc/arm-cla/cla-ops.c new file +8 -0
+/* regidx is unsigned long here to avoid overflow during calculations */
+static int cla_op_access_reg(struct cla_dev *dev, u8 op,
+			     enum cla_launch_data_mode data_mode,
+			     unsigned int accid, unsigned long regidx,
+			     size_t nregs, u64 *regs)
+{
+	int ret = -EINVAL;
+	unsigned long max_regidx;

drivers/misc/arm-cla/cla-ops.c line 227

Quoted 10 lines
drivers/misc/arm-cla/cla-ops.c new file +10 -0
+	struct cla_launch launch = {
+		.op = op,
+		.accid = accid,
+		.data_mode = data_mode,
+	};
+
+	switch (op) {
+	case CLA_LAUNCH_OP_REGREAD:
+	case CLA_LAUNCH_OP_REGWRITE:
+		max_regidx = 0x100000000;

[Severity: High]
Will this unconditionally fail register accesses on 32-bit architectures?

The constant 0x100000000 requires 33 bits. When assigned to an unsigned long on 32-bit platforms, it is implicitly truncated to 0.

drivers/misc/arm-cla/cla-ops.c line 234

Quoted 7 lines
drivers/misc/arm-cla/cla-ops.c new file +7 -0
+		break;
+	default:
+		WARN_ON(1);
+		return -EINVAL;
+	}
+
+	if (WARN_ON(regidx + nregs > max_regidx))

Since max_regidx becomes 0 on 32-bit platforms, this bounds check evaluates to regidx + nregs > 0, which is always true when nregs is greater than zero.

Should max_regidx and regidx both be explicitly typed as u64 to prevent this truncation and correctly handle overflow calculations?

Quoted 1 line
drivers/misc/arm-cla/cla-ops.c new file +1 -0
+		return -EINVAL;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#8 lore raw

Re: [RFC PATCH v2 02/15] misc/arm-cla: Add launch operation helpers

In reply to Ryan Roberts
Quoted 10 lines · Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

CLA commands are issued by writing optional payload registers, programming the LAUNCH register and polling LRESP until the hardware accepts or rejects the operation.

Add a common launch helper that performs this sequence on the CLA's local CPU, waits for LRESP completion and translates launch response codes into Linux errors.

Quoted 6 lines

Build accelerator reset and register read and write support on top of it. The register read and write helpers split larger accesses into multiple launch operations when an access crosses an eight-register window.

You forgot to sign off on patches from others :(

#9 lore raw

Re: [RFC PATCH v2 02/15] misc/arm-cla: Add launch operation helpers

Quoted 11 lines · Greg Kroah-Hartman
Quoted 10 lines · Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

CLA commands are issued by writing optional payload registers, programming the LAUNCH register and polling LRESP until the hardware accepts or rejects the operation.

Add a common launch helper that performs this sequence on the CLA's local CPU, waits for LRESP completion and translates launch response codes into Linux errors.

Quoted 8 lines
Quoted 6 lines

Build accelerator reset and register read and write support on top of it. The register read and write helpers split larger accesses into multiple launch operations when an access crosses an eight-register window.

You forgot to sign off on patches from others :(

Ahh sh*t, sorry about that. Hopefully given this is "just" an RFC that's not a big deal? Else, let me know and I'll resend.

#10 lore raw

RFC PATCH v2 3/15 dt-bindings: misc: Add Arm Core Local Accelerator

In reply to Ryan Roberts

Arm Core Local Accelerator (CLA) provides a CPU-local interface to accelerators that access memory through the local CPU's MMU. CLAs whose accelerators cannot be isolated from each other form an isolation domain.

Add a binding for arm,cla describing the register range, CPU association, DMA coherency and isolation domain. Document the privilege-level register frames, including reduced ranges exposed to virtual machines, and provide an example of two CLAs sharing a domain.

---
 .../devicetree/bindings/misc/arm,cla.yaml     | 77 +++++++++++++++++++
 MAINTAINERS                                   |  1 +
 2 files changed, 78 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/misc/arm,cla.yaml
Documentation/devicetree/bindings/misc/arm,cla.yaml new file +77 -0
new file mode 100644
index 000000000000..b86a2befd09a
@@ -0,0 +1,77 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/misc/arm,cla.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Arm Core Local Accelerator (CLA)
+
+maintainers:
+  - Ryan Roberts <[email protected]>
+
+description:
+  A Core Local Accelerator (CLA) provides a CPU-local interface to up to eight
+  accelerators. The accelerators access memory through the local CPU's MMU. Each
+  CLA has its own register range, which can only be accessed by its local CPU.
+  Completion is polled through the registers; CLA does not generate interrupts.
+
+properties:
+  compatible:
+    const: arm,cla
+
+  reg:
+    maxItems: 1
+    description:
+      A single contiguous register range starting at the PL0 frame, aligned to
+      256 KiB. Each privilege-level frame occupies 64 KiB, with PL0, PL1, PL2
+      and PL3 at offsets 0, 0x10000, 0x20000 and 0x30000 respectively. The
+      complete range is 256 KiB. Higher-privilege frames may be omitted when
+      unavailable, for example in a virtual machine. The range must include at
+      least PL0 and PL1 when running at EL1 and additionally PL2 when running at
+      EL2.
+
+  cpu:
+    $ref: /schemas/types.yaml#/definitions/phandle
+    description:
+      Phandle to the CPU for which this CLA is local. Only that CPU can access
+      the CLA's registers.
+
+  dma-coherent: true
+
+  arm,domain:
+    $ref: /schemas/types.yaml#/definitions/uint32
+    description:
+      Identifier of the CLA isolation domain. CLAs whose attached accelerators
+      cannot be isolated from each other, for example because they share an
+      inter-accelerator communication bus, must have the same domain ID.
+      Different isolation domains must have different IDs. IDs need not be
+      consecutive. A CLA that can be isolated from all other CLAs has its own
+      domain ID.
+
+required:
+  - compatible
+  - reg
+  - cpu
+  - dma-coherent
+  - arm,domain
+
+additionalProperties: false
+
+examples:
+  - |
+    /* Two CPU-local CLAs in the same isolation domain. */
+    cla@10000000 {
+        compatible = "arm,cla";
+        reg = <0x10000000 0x40000>;
+        cpu = <&cpu0>;
+        dma-coherent;
+        arm,domain = <0>;
+    };
+
+    cla@10040000 {
+        compatible = "arm,cla";
+        reg = <0x10040000 0x40000>;
+        cpu = <&cpu1>;
+        dma-coherent;
+        arm,domain = <0>;
+    };
MAINTAINERS +1 -0
index 735f6527f920..98a25b3de9b4 100644
@@ -2213,6 +2213,7 @@ ARM CORE LOCAL ACCELERATOR (CLA) DRIVER
 M:	Ryan Roberts <[email protected]>
 L:	[email protected] (moderated for non-subscribers)
 S:	Supported
+F:	Documentation/devicetree/bindings/misc/arm,cla.yaml
 F:	Documentation/misc-devices/arm-cla.rst
 F:	drivers/misc/arm-cla/
 
Signature · 1 line
2.43.0
#11 lore raw

Re: [RFC PATCH v2 03/15] dt-bindings: misc: Add Arm Core Local Accelerator

Hi Ryan,

thanks for your patch!

The following review comments are based on my limited understanding of device tree, the actual maintainers should have the final word and need to look at it too.

Quoted 5 lines · Ryan Roberts

Arm Core Local Accelerator (CLA) provides a CPU-local interface to accelerators that access memory through the local CPU's MMU. CLAs whose accelerators cannot be isolated from each other form an isolation domain.

Quoted 8 lines

Add a binding for arm,cla describing the register range, CPU association, DMA coherency and isolation domain. Document the privilege-level register frames, including reduced ranges exposed to virtual machines, and provide an example of two CLAs sharing a domain.

 .../devicetree/bindings/misc/arm,cla.yaml     | 77 +++++++++++++++++++

No matter where the driver goes, this binding should (IMO) be in

Documentation/devicetree/bindings/arm/arm,core-local-accelerator.yaml

Documentation/devicetree/bindings/misc/arm,cla.yaml line 20

Quoted 3 lines
Documentation/devicetree/bindings/misc/arm,cla.yaml new file +3 -0
+properties:
+  compatible:
+    const: arm,cla

I would spell it out arm,core-local-accelerator but others may like the terse acronym. I just think it's too short to be unique and find Documentation | grep core is good to match for one.

Documentation/devicetree/bindings/misc/arm,cla.yaml

Quoted 6 lines
Documentation/devicetree/bindings/misc/arm,cla.yaml new file +6 -0
+  reg:
+    maxItems: 1
+    description:
+      A single contiguous register range starting at the PL0 frame, aligned to
+      256 KiB. Each privilege-level frame occupies 64 KiB, with PL0, PL1, PL2
+      and PL3 at offsets 0, 0x10000, 0x20000 and 0x30000 respectively.

So these registers only exist on each node (mention that here), is this address in the *physical memory* address of *that* CPU or of the entire system or what is it?

I'm just confused so looking for this to be explained here.

My guesswork is that each CPU has a slice of the physical memory in this reg, and that slice is then only visible from that one CPU. If it's like that, spell it out.

Documentation/devicetree/bindings/misc/arm,cla.yaml line 37

Quoted 5 lines
Documentation/devicetree/bindings/misc/arm,cla.yaml new file +5 -0
+  cpu:
+    $ref: /schemas/types.yaml#/definitions/phandle
+    description:
+      Phandle to the CPU for which this CLA is local. Only that CPU can access
+      the CLA's registers.

If this thing/address is local to the CPU, shouldn't this just be subnode inside of the CPU device tree node itself? I'm not sure so I'm asking.

Quoted 1 line

+ dma-coherent: true

Yeah, I guess ... on THAT CPU then?

I think this property is "as seen from the CPU", and assumes all CPUs and IIUC the other CPUs cannot even see it so that doesn't sound very coherent.

I'm just confused by this property being present here, but it's true, in a way, I guess? Do you have to specify it?

Quoted 1 line

+ arm,domain:

Domain is a bit generic don't you think? We have power domains and clock domains already.

At least use arm,cla-domain?

Documentation/devicetree/bindings/misc/arm,cla.yaml line 49

Quoted 8 lines
Documentation/devicetree/bindings/misc/arm,cla.yaml new file +8 -0
+    $ref: /schemas/types.yaml#/definitions/uint32
+    description:
+      Identifier of the CLA isolation domain. CLAs whose attached accelerators
+      cannot be isolated from each other, for example because they share an
+      inter-accelerator communication bus, must have the same domain ID.
+      Different isolation domains must have different IDs. IDs need not be
+      consecutive. A CLA that can be isolated from all other CLAs has its own
+      domain ID.

This doesn't explain what it means to isolate a domain, what isolation even means in this context.

I know about isolating network interfaces for example: it means to physically decouple it.

So express what "isolation" means here.

Quoted 8 lines
Documentation/devicetree/bindings/misc/arm,cla.yaml new file +8 -0
+examples:
+  - |
+    /* Two CPU-local CLAs in the same isolation domain. */
+    cla@10000000 {
+        compatible = "arm,cla";
+        reg = <0x10000000 0x40000>;
+        cpu = <&cpu0>;
+        dma-coherent;

Documentation/devicetree/bindings/misc/arm,cla.yaml line 77

Quoted 10 lines
Documentation/devicetree/bindings/misc/arm,cla.yaml new file +10 -0
+        arm,domain = <0>;
+    };
+
+    cla@10040000 {
+        compatible = "arm,cla";
+        reg = <0x10040000 0x40000>;
+        cpu = <&cpu1>;
+        dma-coherent;
+        arm,domain = <0>;
+    };

This example makes it look like these CLAs are all uniquely mapped into the (shared) physical address space. Is it so?

Yours,
Linus Walleij

#12 lore raw

RFC PATCH v2 4/15 misc/arm-cla: Probe firmware-described devices

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Discover CLA devices from firmware and instantiate the driver with platform_driver_probe(), since the set of devices is fixed at boot. Map the MMIO frame, select the kernel-accessible privilege-level frame and associate each CLA with the CPU named by firmware.

Add the topology code used to group CLAs into domains. Domains represent the smallest unit that can be assigned independently, because CLAs in the same domain cannot be isolated from each other. Build lookup tables indexed by CPU and by mmap page offset for later fast access.

Register CPU hotplug callbacks so that hardware setup and teardown can run on the CPU local to each CLA, which is the only CPU allowed to access that CLA's registers.

---
 drivers/misc/arm-cla/Makefile       |   3 +-
 drivers/misc/arm-cla/arm-cla.h      |  46 ++++++
 drivers/misc/arm-cla/cla-init.c     | 222 ++++++++++++++++++++++++++++
 drivers/misc/arm-cla/cla-topology.c | 172 +++++++++++++++++++++
 4 files changed, 442 insertions(+), 1 deletion(-)
 create mode 100644 drivers/misc/arm-cla/cla-topology.c
drivers/misc/arm-cla/Makefile +2 -1
index 3fa8567c8b3e..84ed1a054a21 100644
@@ -2,6 +2,7 @@
 
 arm-cla-y := \
 	cla-init.o \
-	cla-ops.o
+	cla-ops.o \
+	cla-topology.o
 
 obj-$(CONFIG_ARM_CLA) += arm-cla.o
drivers/misc/arm-cla/arm-cla.h +46 -0

77 lines not on this page · raw message

drivers/misc/arm-cla/cla-init.c +222 -0

229 lines not on this page · raw message

drivers/misc/arm-cla/cla-topology.c new file +172 -0

172 lines not on this page · raw message

Signature · 1 line
2.43.0
#13 lore raw

Re: [RFC PATCH v2 04/15] misc/arm-cla: Probe firmware-described devices

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] core: mixed goto-based error handling and scoped_guard in cla_module_init() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] core: mixed goto-based error handling and scoped_guard in cla_module_init() --

commit 0ee32d948034264a0bab6422d831ac58dbde58cd
Author: Jean-Philippe Brucker <[email protected]>

misc/arm-cla: Probe firmware-described devices

This commit discovers and instantiates CLA devices described by firmware using platform_driver_probe. It also adds topology grouping for domains and registers CPU hotplug callbacks to manage hardware setup per CLA-local CPU.

Quoted 4 lines
drivers/misc/arm-cla/cla-init.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 15 lines
drivers/misc/arm-cla/cla-init.c new file +15 -0
+static int __init cla_module_init(void)
+{
+	bool driver_registered = false;
+	int ret;
+
+	/*
+	 * For now, we reject any CLAs discovered via FW tables, whose CPU is
+	 * offline during init. This keeps things simple by allowing us to probe
+	 * all HW at init time. Keep the online CPU set stable so that the
+	 * cpu_online() check in cla_probe() is consistent with the online cpus
+	 * when we call cpuhp_setup_state().
+	 */
+	scoped_guard(cpus_read_lock) {
+		/*
+		 * CPUs may be hotplugged, but all CLAs are described by

drivers/misc/arm-cla/cla-init.c line 185

Quoted 10 lines
drivers/misc/arm-cla/cla-init.c new file +10 -0
+		 * firmware so the probe can be synchronous. This only sets up
+		 * the resources, and CPUHP callbacks do the actual peeking and
+		 * poking. This returns an error when no CLA has an online CPU.
+		 */
+		ret = platform_driver_probe(&cla_driver, cla_probe);
+		if (ret) {
+			if (ret != -ENODEV)
+				pr_err("arm-cla: probe failed with %d\n", ret);
+			/* Some domains may have been created during probe. */
+			goto err_hardware;

[Severity: Medium]
The function cla_module_init() uses a scoped_guard(cpus_read_lock) block while also jumping to a manual err_hardware cleanup label.

According to the cleanup and guard subsystem guidelines in include/linux/cleanup.h, mixing goto-based error handling with scope-based cleanups in the same function is considered an anti-pattern. This creates confusing ownership semantics and risks double-frees or resource leaks during future refactoring.

Could this function be refactored to consistently use either only scope-based cleanup or only goto-based error handling?

Quoted 1 line
drivers/misc/arm-cla/cla-init.c new file +1 -0
+		}

[ ... ]

Quoted 9 lines
drivers/misc/arm-cla/cla-init.c new file +9 -0
+
+err_hardware:
+	if (cla_cpuhp_state >= 0)
+		cpuhp_remove_state(cla_cpuhp_state);
+	cla_domains_free();
+	if (driver_registered)
+		platform_driver_unregister(&cla_driver);
+	return ret;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#14 lore raw

Re: [RFC PATCH v2 04/15] misc/arm-cla: Probe firmware-described devices

In reply to Ryan Roberts

Hi Ryan & Jean-Philippe,

thanks for your patch!

I see this framework is (ab)using platform_device, and Greg has many times pointed out that he doesn't like that, and I don't like it either, so I'm gonna complain about that.

Quoted 27 lines · Ryan Roberts
drivers/misc/arm-cla/cla-init.c +27 -0
+static int cla_of_to_cpu(struct device_node *of_node)
+{
+       int cpu;
+       int ret;
+       u32 cpu_phandle;
+       struct device_node *cpu_node;
+
+       if (!of_node)
+               return -ENODEV;
+
+       ret = of_property_read_u32(of_node, "cpu", &cpu_phandle);
+       if (WARN_ON(ret))
+               return -EINVAL;
+
+       cpu_node = of_find_node_by_phandle(cpu_phandle);
+       if (WARN_ON(!cpu_node))
+               return -EINVAL;
+
+       cpu = of_cpu_node_to_id(cpu_node);
+       of_node_put(cpu_node);
+
+       return cpu;
+}
+
+static struct cla_dev *cla_dev_alloc(struct device *parent, int cpu,
+                                    void __iomem *regs, phys_addr_t base)
+{

drivers/misc/arm-cla/cla-init.c line 86

Quoted 10 lines
drivers/misc/arm-cla/cla-init.c +10 -0
+       struct cla_dev *dev;
+
+       dev = devm_kzalloc(parent, sizeof(*dev), GFP_KERNEL);
+       if (!dev)
+               return ERR_PTR(-ENOMEM);
+
+       dev->pfn = __phys_to_pfn(base);
+       dev->regs = cla_get_regs(regs, cla_kernel_pl);
+       dev->cpu = cpu;
+       dev->dev = parent;

Why is struct cla_dev just a hollow thing without it's own struct device? This is free-riding on the parent device, which seems odd to me.

Should you rather have:

struct cla_device {
      unsigned int cpu;
       void __iomem *regs;
       struct device dev;

^ Not a pointer

       unsigned long pfn;
       unsigned long pg_offset;
       struct cla_domain *domain;
};

Instead of first creating platform devices, then spawn this hollow struct cla_dev from the platform device, what about just creating struct cla_device directly from the beginning if the platform_device has no real use?

Quoted 1 line

+static int cla_probe(struct platform_device *pdev)

Why send in a platform device here at all, just create the cla_device and pass this in here instead. It does exist right?

drivers/misc/arm-cla/cla-init.c line 111

Quoted 13 lines
drivers/misc/arm-cla/cla-init.c +13 -0
+{
+       int cpu;
+       void __iomem *reg;
+       size_t reg_size;
+       struct cla_dev *dev;
+       struct resource *res;
+
+       /*
+        * TODO: the firmware maps this as well to access PL3, and the guest
+        * will map PL1 and PL0. Avoid TLB attr mismatches by only mapping what
+        * we need.
+        */
+       reg = devm_platform_get_and_ioremap_resource(pdev, 0, &res);

And register resource to &cla->dev; etc.

Quoted 10 lines
drivers/misc/arm-cla/cla-init.c +10 -0
+static int __init cla_module_init(void)
+{
+       bool driver_registered = false;
+       int ret;
+
+       /*
+        * For now, we reject any CLAs discovered via FW tables, whose CPU is
+        * offline during init. This keeps things simple by allowing us to probe
+        * all HW at init time. Keep the online CPU set stable so that the
+        * cpu_online() check in cla_probe() is consistent with the online cpus

drivers/misc/arm-cla/cla-init.c line 180

Quoted 10 lines
drivers/misc/arm-cla/cla-init.c +10 -0
+        * when we call cpuhp_setup_state().
+        */
+       scoped_guard(cpus_read_lock) {
+               /*
+                * CPUs may be hotplugged, but all CLAs are described by
+                * firmware so the probe can be synchronous. This only sets up
+                * the resources, and CPUHP callbacks do the actual peeking and
+                * poking. This returns an error when no CLA has an online CPU.
+                */
+               ret = platform_driver_probe(&cla_driver, cla_probe);

Create your own cla_driver for cla_device instead.

Yours,
Linus Walleij

#15 lore raw

RFC PATCH v2 5/15 misc/arm-cla: Initialize devices on CPU bringup

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

CLA registers are only accessible from the CPU local to the CLA, so perform device initialization from the CPU hotplug online callback.

Clear the DATA registers, reset each attached accelerator and verify that it returns to the expected idle state. Record the set of usable accelerators and expose only those through PL0CTRL, and through PL1CTRL when the kernel is running at EL2.

Reset optional timestamp and PMU controls where available so userspace starts from a predictable state, but do not fail probing if those optional controls cannot be programmed.

On CPU teardown, reset all known accelerators and mark the device broken if reset fails, since the hotplug teardown path cannot safely fail.

---
 drivers/misc/arm-cla/arm-cla.h  |  14 +++
 drivers/misc/arm-cla/cla-init.c | 191 +++++++++++++++++++++++++++++++-
 drivers/misc/arm-cla/cla-ops.c  |  23 ++++
 3 files changed, 227 insertions(+), 1 deletion(-)
drivers/misc/arm-cla/arm-cla.h +14 -0
index 61176c4fce0f..6890c813a5c3 100644
@@ -27,16 +27,25 @@ struct cla_domain;
  * @regs:		Registers accessed by the kernel.
  * @dev:		The platform device.
  * @pfn:		Page of registers assigned to user.
+ * @accelerators:	Available accelerators.
  * @pg_offset:		Mmap offset of this device.
  * @domain:		The domain this CLA belongs to.
+ *
+ * Mutable, protected by CPU hotplug locking:
+ * @discovered:		Discovered state is cached.
+ * @broken:		Hardware failure.
  */
 struct cla_dev {
 	unsigned int cpu;
 	void __iomem *regs;
 	struct device *dev;
 	unsigned long pfn;
+	u8 accelerators;
 	unsigned long pg_offset;
 	struct cla_domain *domain;
+
+	bool discovered;
+	bool broken;
 };
 
 /**
@@ -61,6 +70,10 @@ extern struct cla_dev **cla_lut_cpu;
 extern struct cla_dev **cla_lut_pg;
 extern unsigned int cla_nr_devs;
 
+#define cla_for_each_accid(dev, accid) \
+	for ((accid) = 0; (accid) < CLA_NUM_ACC; (accid)++) \
+		for_each_if((dev)->accelerators & BIT(accid))
+
 #define cla_dbg(_dev, fmt, ...) \
 	dev_dbg((_dev)->dev, "[%u] " fmt, (_dev)->cpu, ##__VA_ARGS__)
 #define cla_info(_dev, fmt, ...) \
@@ -98,6 +111,7 @@ void cla_domains_free(void);
 
 int cla_op_wait_lresp(struct cla_dev *dev, u64 *lresp);
 int cla_op_reset(struct cla_dev *dev, unsigned int accid);
+int cla_op_reset_all(struct cla_dev *dev);
 int cla_op_regread(struct cla_dev *dev, unsigned int accid, unsigned int regidx,
 		   size_t nregs, u64 *regs);
 int cla_op_regwrite(struct cla_dev *dev, unsigned int accid,
drivers/misc/arm-cla/cla-init.c +190 -1

220 lines not on this page · raw message

drivers/misc/arm-cla/cla-ops.c +23 -0
index 46026304a057..5d053c6aa1f7 100644
@@ -207,6 +207,29 @@ int cla_op_reset(struct cla_dev *dev, unsigned int accid)
 	return 0;
 }
 
+/**
+ * cla_op_reset_all - Reset all attached accelerators
+ * @dev: CLA device.
+ *
+ * Return: 0 on success, or an error
+ */
+int cla_op_reset_all(struct cla_dev *dev)
+{
+	int ret, err = 0;
+	unsigned int accid;
+
+	cla_for_each_accid(dev, accid) {
+		ret = cla_op_reset(dev, accid);
+		if (ret && !err)
+			err = ret;
+	}
+	/*
+	 * Since all accelerators in this loop are present, cla_op_reset()
+	 * returning 1 is an error.
+	 */
+	return err <= 0 ? err : -ENODEV;
+}
+
 /* regidx is unsigned long here to avoid overflow during calculations */
 static int cla_op_access_reg(struct cla_dev *dev, u8 op,
 			     enum cla_launch_data_mode data_mode,
Signature · 1 line
2.43.0
#16 lore raw

RFC PATCH v2 6/15 misc/arm-cla: Accelerator context save and restore

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Add helpers to save and restore CLA context for later domain switching. The saved state includes DATA registers, LRESP, per-accelerator SRSTATE and any implementation-defined internal accelerator state exposed through the IAS register window.

Use ENTERSR to stop each accelerator and collect SRSTATE, then read the advertised internal register state with REGREAD. Restore by entering SR mode from a reset, idle accelerator, writing the saved internal state with REGWRITE and completing the transition with EXITSR.

Reject accelerators that require SAVE/RESTORE operations during setup, since that path needs a DMA buffer for state storage. Allocate per-device save areas for all CLAs in a domain, sized from the combined IASSIZE discovered at setup time.

---
 drivers/misc/arm-cla/Makefile   |   1 +
 drivers/misc/arm-cla/arm-cla.h  |  32 ++++
 drivers/misc/arm-cla/cla-init.c |  35 ++++
 drivers/misc/arm-cla/cla-ops.c  |  49 ++++++
 drivers/misc/arm-cla/cla-regs.c | 295 ++++++++++++++++++++++++++++++++
 5 files changed, 412 insertions(+)
 create mode 100644 drivers/misc/arm-cla/cla-regs.c
drivers/misc/arm-cla/Makefile +1 -0
index 84ed1a054a21..c1b14155454d 100644
@@ -3,6 +3,7 @@
 arm-cla-y := \
 	cla-init.o \
 	cla-ops.o \
+	cla-regs.o \
 	cla-topology.o
 
 obj-$(CONFIG_ARM_CLA) += arm-cla.o
drivers/misc/arm-cla/arm-cla.h +32 -0
index 6890c813a5c3..6d72d57e5422 100644
@@ -29,6 +29,7 @@ struct cla_domain;
  * @pfn:		Page of registers assigned to user.
  * @accelerators:	Available accelerators.
  * @pg_offset:		Mmap offset of this device.
+ * @iassizes:		Combined regstate of all accels in bytes.
  * @domain:		The domain this CLA belongs to.
  *
  * Mutable, protected by CPU hotplug locking:
@@ -42,6 +43,7 @@ struct cla_dev {
 	unsigned long pfn;
 	u8 accelerators;
 	unsigned long pg_offset;
+	unsigned long iassizes;
 	struct cla_domain *domain;
 
 	bool discovered;
@@ -64,6 +66,27 @@ struct cla_domain {
 	struct cla_dev **devs;
 };
 
+/**
+ * struct cla_regs_pl0 - Saved CLA register state (PL0)
+ *
+ * @data:		DATA registers.
+ * @lresp:		LRESP register.
+ * @accel_valid:	Accelerator state has been saved once.
+ * @srstate:		Save/restore state for each accelerator.
+ * @regstate:		Internal accelerator state.
+ */
+struct cla_regs_pl0 {
+	u64 data[CLA_NUM_DATA_REGS];
+	u64 lresp;
+	bool accel_valid;
+	u64 srstate[CLA_NUM_ACC][CLA_SRSTATE_LEN];
+	u64 regstate[];
+};
+
+struct cla_ctx {
+	void **regs;
+};
+
 extern struct xarray cla_domains;
 extern unsigned int cla_nr_domains;
 extern struct cla_dev **cla_lut_cpu;
@@ -116,5 +139,14 @@ int cla_op_regread(struct cla_dev *dev, unsigned int accid, unsigned int regidx,
 		   size_t nregs, u64 *regs);
 int cla_op_regwrite(struct cla_dev *dev, unsigned int accid,
 		    unsigned int regidx, size_t nregs, u64 *regs);
+int cla_op_entersr(struct cla_dev *dev, unsigned int accid, u64 *srstate);
+int cla_op_exitsr(struct cla_dev *dev, unsigned int accid, u64 *srstate);
+
+int cla_regs_install(struct cla_dev *dev, struct cla_ctx *ctx,
+		     unsigned int ctx_id);
+int cla_regs_uninstall(struct cla_dev *dev, struct cla_ctx *ctx,
+		       unsigned int ctx_id);
+int cla_ctx_alloc_regs(struct cla_domain *domain, struct cla_ctx *ctx);
+void cla_ctx_free_regs(struct cla_domain *domain, struct cla_ctx *ctx);
 
 #endif /* _ARM_CLA_H_ */
drivers/misc/arm-cla/cla-init.c +35 -0
index 2974bf71033c..a4d2ffaa3136 100644
@@ -7,8 +7,10 @@
 
 #include <linux/cpuhotplug.h>
 #include <linux/cpuhplock.h>
+#include <linux/math.h>
 #include <linux/module.h>
 #include <linux/of.h>
+#include <linux/overflow.h>
 #include <linux/platform_device.h>
 #include <linux/smp.h>
 
@@ -82,6 +84,38 @@ static int cla_reset_pmu(struct cla_dev *dev, unsigned int accid)
  */
 static int cla_dev_discover_accel(struct cla_dev *dev, unsigned int accid)
 {
+	unsigned long iassizes;
+	u64 iassize;
+	u64 acap;
+	int ret;
+
+	/*
+	 * This driver supports context switching with REGREAD and REGWRITE.
+	 * SROP (SAVE and RESTORE ops) requires DMA-backed state storage, which
+	 * is not implemented here.
+	 */
+	ret = cla_op_regread(dev, accid, CLA_REG_ACAP, 1, &acap);
+	if (ret)
+		return ret;
+	if (FIELD_GET(CLA_ACAP_SROP, acap)) {
+		cla_err(dev, "[%u] SROP not supported\n", accid);
+		return 1;
+	}
+
+	ret = cla_op_regread(dev, accid, CLA_REG_IASSIZE, 1, &iassize);
+	if (ret)
+		return ret;
+	if (FIELD_GET(CLA_ACAP_REGSTATE, acap)) {
+		/* Reserve whole u64 entries for each accelerator's state. */
+		if (check_add_overflow(iassize, sizeof(u64) - 1, &iassize) ||
+		    check_add_overflow(dev->iassizes, round_down(iassize,
+				       sizeof(u64)), &iassizes)) {
+			cla_err(dev, "[%u] IASSIZE total overflows\n", accid);
+			return -EOVERFLOW;
+		}
+		dev->iassizes = iassizes;
+	}
+
 	dev->accelerators |= (1 << accid);
 
 	return 0;
@@ -181,6 +215,7 @@ static int cla_dev_setup(unsigned int cpu)
 	if (!dev->discovered) {
 		/* Discard partial results from an earlier, failed discovery. */
 		dev->accelerators = 0;
+		dev->iassizes = 0;
 	}
 
 	/* Clear DATA and LRESP_DATANZ */
drivers/misc/arm-cla/cla-ops.c +49 -0

52 lines not on this page · raw message

drivers/misc/arm-cla/cla-regs.c new file +295 -0

295 lines not on this page · raw message

Signature · 1 line
2.43.0
#17 lore raw

Re: [RFC PATCH v2 06/15] misc/arm-cla: Accelerator context save and restore

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] misc: arm-cla: max_regidx truncated to 0 on 32-bit architectures - [High] misc: arm-cla: partially…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] misc: arm-cla: max_regidx truncated to 0 on 32-bit architectures
- [High] misc: arm-cla: partially overwritten context state left valid on error
- [High] misc: arm-cla: NULL pointer dereference in cla_ctx_free_regs()
- [High] misc: arm-cla: ctx->regs indexed by ctx_id instead of device index --

commit 3663e5cba865127a89c5cdad88c78f8b24a13ae0
Author: Jean-Philippe Brucker <[email protected]>

misc/arm-cla: Accelerator context save and restore

Add helpers to save and restore CLA context for later domain switching. The saved state includes DATA registers, LRESP, per-accelerator SRSTATE and any implementation-defined internal accelerator state exposed through the IAS register window.

Quoted 5 lines
drivers/misc/arm-cla/cla-regs.c new file +0 -0
new file mode 100644
index 0000000000000..2452a7601990f

[ ... ]

Quoted 3 lines
drivers/misc/arm-cla/cla-regs.c new file +3 -0
+static int cla_regs_save_accel(struct cla_dev *dev, unsigned int accid,
+			       struct cla_regs_pl0 *regs, size_t *regstate_off)
+{

[ ... ]

drivers/misc/arm-cla/cla-regs.c line 52

Quoted 3 lines
drivers/misc/arm-cla/cla-regs.c new file +3 -0
+	if (regstate_size) {
+		ret = cla_op_regread(dev, accid, CLA_REG_IASn, regstate_size,
+				     regs->regstate + *regstate_off);

[Severity: High]
Does this code unconditionally fail on 32-bit architectures?

cla_op_regread() calls cla_op_access_reg(). In that function:

drivers/misc/arm-cla/cla-ops.c:cla_op_access_reg() {
	...
	unsigned long max_regidx;
	...
	case CLA_LAUNCH_OP_REGREAD:
	case CLA_LAUNCH_OP_REGWRITE:
		max_regidx = 0x100000000;
		break;
	...
	if (WARN_ON(regidx + nregs > max_regidx))
		return -EINVAL;
}

max_regidx is declared as an unsigned long and assigned the 33-bit constant 0x100000000. On 32-bit platforms, unsigned long is 32 bits wide, so the assignment silently truncates the value to 0.

With max_regidx being 0, the bounds check regidx + nregs > 0 is unconditionally true since nregs must be greater than zero. This causes cla_op_access_reg() to unconditionally fail with -EINVAL, completely breaking the newly added context save and restore features here.

Quoted 5 lines
drivers/misc/arm-cla/cla-regs.c new file +5 -0
+		if (ret) {
+			cla_err(dev, "failed to save regstate: %d\n", ret);
+			return ret;
+		}
+	}

[ ... ]

drivers/misc/arm-cla/cla-regs.c line 120

Quoted 8 lines
drivers/misc/arm-cla/cla-regs.c new file +8 -0
+static int cla_regs_uninstall_pl0(struct cla_dev *dev, struct cla_ctx *ctx,
+				  unsigned int ctx_id)
+{
+	int i;
+	int ret;
+	unsigned int accid;
+	size_t regstate_off = 0;
+	struct cla_regs_pl0 *regs = ctx->regs[ctx_id];

[Severity: High]
Does this code index the ctx->regs array with the wrong identifier?

cla_ctx_alloc_regs() allocates ctx->regs as an array of size domain->nr_devs, where each element index corresponds directly to a specific device in the domain (domain->devs[i]).

However, this uses ctx_id to index the array. ctx_id represents the logical context number within the domain, not the hardware device index.

If a user allocates more contexts than the number of hardware devices (ctx_id >= domain->nr_devs), this causes an immediate out-of-bounds array access. Even if ctx_id is within bounds, using it instead of the device index results in reading and writing state to the wrong device's register array.

Quoted 10 lines
drivers/misc/arm-cla/cla-regs.c new file +10 -0
+
+	/*
+	 * When we interrupt the user process in the middle of launching a
+	 * command, we have to wait for LRESP_PENDING to clear before we can
+	 * launch a new command or save the DATA registers.
+	 */
+	ret = cla_op_wait_lresp(dev, &regs->lresp);
+	if (ret)
+		return ret;
+

drivers/misc/arm-cla/cla-regs.c line 140

Quoted 10 lines
drivers/misc/arm-cla/cla-regs.c new file +10 -0
+	for (i = 0; i < CLA_NUM_DATA_REGS; i++)
+		regs->data[i] = cla_reg_read(dev, CLA_REG_DATA(i));
+
+	cla_for_each_accid(dev, accid) {
+		ret = cla_regs_save_accel(dev, accid, regs, &regstate_off);
+		if (ret)
+			return ret;
+	}
+
+	regs->accel_valid = true;

[Severity: High]
Does this leave a partially overwritten context state marked as valid on error?

If cla_regs_save_accel() fails for an accelerator (e.g., due to a hardware timeout), the function returns the error immediately. Because regs->accel_valid is not cleared to false at the start of the function, it retains its prior value.

If the context was previously successfully saved (regs->accel_valid == true), it remains marked as valid, despite the buffer now holding a torn, inconsistent mix of old state and newly overwritten partial data.

On the next context switch, cla_regs_install_pl0() will see accel_valid == true and silently restore this corrupted partial state into the hardware, leading to unpredictable hardware behavior and data corruption.

Quoted 3 lines
drivers/misc/arm-cla/cla-regs.c new file +3 -0
+
+	/*
+	 * "If the accelerator is non idle when ENTERSR is launched, then a

[ ... ]

drivers/misc/arm-cla/cla-regs.c line 160

Quoted 8 lines
drivers/misc/arm-cla/cla-regs.c new file +8 -0
+static int cla_regs_install_pl0(struct cla_dev *dev, struct cla_ctx *ctx,
+				unsigned int ctx_id)
+{
+	int i;
+	int ret;
+	unsigned int accid;
+	size_t regstate_off = 0;
+	struct cla_regs_pl0 *regs = ctx->regs[ctx_id];

[Severity: High]
As with cla_regs_uninstall_pl0() above, does this code also index the ctx->regs array with the wrong identifier?

Using ctx_id instead of the device index will cause an out-of-bounds array access or access the wrong device's register array.

Quoted 2 lines
drivers/misc/arm-cla/cla-regs.c new file +2 -0
+
+	cla_for_each_accid(dev, accid) {

[ ... ]

drivers/misc/arm-cla/cla-regs.c line 293

Quoted 6 lines
drivers/misc/arm-cla/cla-regs.c new file +6 -0
+void cla_ctx_free_regs(struct cla_domain *domain, struct cla_ctx *ctx)
+{
+	int i;
+
+	for (i = 0; i < domain->nr_devs; i++)
+		kvfree(ctx->regs[i]);

[Severity: High]
Can this code cause a NULL pointer dereference?

In cla_ctx_alloc_regs(), if the initial memory allocation for regs_ptrs fails, the function returns -ENOMEM without assigning a value to ctx->regs. Assuming ctx was zero-initialized by the caller, ctx->regs remains NULL.

When the caller handles this failure by invoking this common teardown path, it iterates and unconditionally executes kvfree(ctx->regs[i]). Since ctx->regs is NULL, array indexing results in a NULL pointer dereference.

Quoted 2 lines
drivers/misc/arm-cla/cla-regs.c new file +2 -0
+	kfree(ctx->regs);
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#18 lore raw

Re: [RFC PATCH v2 06/15] misc/arm-cla: Accelerator context save and restore

In reply to Ryan Roberts

Hi Ryan, Jean-Philippe,

thanks for your patch!

Quoted 12 lines · Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Add helpers to save and restore CLA context for later domain switching. The saved state includes DATA registers, LRESP, per-accelerator SRSTATE and any implementation-defined internal accelerator state exposed through the IAS register window.

Use ENTERSR to stop each accelerator and collect SRSTATE, then read the advertised internal register state with REGREAD. Restore by entering SR mode from a reset, idle accelerator, writing the saved internal state with REGWRITE and completing the transition with EXITSR.

Quoted 6 lines

Reject accelerators that require SAVE/RESTORE operations during setup, since that path needs a DMA buffer for state storage. Allocate per-device save areas for all CLAs in a domain, sized from the combined IASSIZE discovered at setup time.

This just describes mechanism and not use.

I see what the code is doing but not how it is used.

E.g. part of me think: if it is technically a part of the CPU, why is the context not stored in pt_regs?

So I assume the context change at other points than when the process on the current CPU is preempted or scheduled in.

This context (ha!) is needed here so we can understand the *purpose* of this context switch.

Maybe the use of contexts and context switching need to be in the cover letter?

Yours,
Linus Walleij

#19 lore raw

RFC PATCH v2 7/15 misc/arm-cla: Set up memory translation context

In reply to Ryan Roberts

CLA accelerators use a Memory Translation Context to describe the page-table and memory-system configuration used for DMA through the CPU MMU. Set up the kernel-owned MTC during CLA bringup so later context switches only need to replace the user TTBR0 value.

Populate the MTC from the CPU EL1 configuration, including SCTLR, MAIR, TCR and TCR2 where present. Configure the accelerator to run as EL0, put the ASID in TTBR0 and disable TTBR1 translations because the driver only installs user contexts in the TTBR0 range. When running at EL2, also program the host HCR state.

Add SETCTX and GETCTX launch helpers for MTC register access. Use the first available accelerator ID for these operations, since the MTC is shared by the CLA but the operation still requires a valid accelerator ID.

Clear the MTC on CPU teardown, and add helpers to install and uninstall a user translation context by updating TTBR0 with the process page table, ASID and CnP state.

---
 drivers/misc/arm-cla/Makefile   |   1 +
 drivers/misc/arm-cla/arm-cla.h  |  24 ++++
 drivers/misc/arm-cla/cla-init.c |  10 +-
 drivers/misc/arm-cla/cla-mtc.c  | 206 ++++++++++++++++++++++++++++++++
 drivers/misc/arm-cla/cla-ops.c  |  52 ++++++++
 5 files changed, 291 insertions(+), 2 deletions(-)
 create mode 100644 drivers/misc/arm-cla/cla-mtc.c
drivers/misc/arm-cla/Makefile +1 -0
index c1b14155454d..df3ad7e4a1b4 100644
@@ -2,6 +2,7 @@
 
 arm-cla-y := \
 	cla-init.o \
+	cla-mtc.o \
 	cla-ops.o \
 	cla-regs.o \
 	cla-topology.o
drivers/misc/arm-cla/arm-cla.h +24 -0
index 6d72d57e5422..40e95d3128ad 100644
@@ -83,8 +83,20 @@ struct cla_regs_pl0 {
 	u64 regstate[];
 };
 
+/**
+ * struct cla_ctx_key - Unique context identifier
+ * @mm: For PL0 contexts, the mm.
+ * @file: for PL0 contexts, the file.
+ */
+struct cla_ctx_key {
+	struct mm_struct *mm;
+	struct file *file;
+};
+
 struct cla_ctx {
+	struct cla_ctx_key key;
 	void **regs;
+	unsigned int asid;
 };
 
 extern struct xarray cla_domains;
@@ -139,6 +151,10 @@ int cla_op_regread(struct cla_dev *dev, unsigned int accid, unsigned int regidx,
 		   size_t nregs, u64 *regs);
 int cla_op_regwrite(struct cla_dev *dev, unsigned int accid,
 		    unsigned int regidx, size_t nregs, u64 *regs);
+int cla_op_setctx(struct cla_dev *dev, unsigned int regidx, size_t nregs,
+		  u64 *regs);
+int cla_op_getctx(struct cla_dev *dev, unsigned int regidx, size_t nregs,
+		  u64 *regs);
 int cla_op_entersr(struct cla_dev *dev, unsigned int accid, u64 *srstate);
 int cla_op_exitsr(struct cla_dev *dev, unsigned int accid, u64 *srstate);
 
@@ -149,4 +165,12 @@ int cla_regs_uninstall(struct cla_dev *dev, struct cla_ctx *ctx,
 int cla_ctx_alloc_regs(struct cla_domain *domain, struct cla_ctx *ctx);
 void cla_ctx_free_regs(struct cla_domain *domain, struct cla_ctx *ctx);
 
+int cla_mtc_setup(struct cla_dev *dev);
+int cla_mtc_clear(struct cla_dev *dev);
+int cla_mtc_install(struct cla_dev *dev, struct cla_ctx *ctx);
+int cla_mtc_uninstall(struct cla_dev *dev, struct cla_ctx *ctx);
+int cla_mtc_get_ctx(struct cla_ctx *ctx);
+void cla_mtc_put_ctx(struct cla_ctx *ctx);
+void cla_mtc_leak_ctx(struct cla_ctx *ctx);
+
 #endif /* _ARM_CLA_H_ */
drivers/misc/arm-cla/cla-init.c +8 -2
index a4d2ffaa3136..58f37787a59c 100644
@@ -184,7 +184,8 @@ static void cla_dev_reinit(struct cla_dev *dev)
 	if (dev->broken)
 		return;
 
-	if (WARN_ON(cla_op_reset_all(dev))) {
+	if (WARN_ON(cla_op_reset_all(dev)) ||
+	    WARN_ON(cla_mtc_clear(dev))) {
 		dev->broken = true;
 		return;
 	}
@@ -242,9 +243,14 @@ static int cla_dev_setup(unsigned int cpu)
 
 	cla_reg_write(dev, CLA_REG_PL0CTRL, plxctrl_val);
 
-	if (dev->accelerators)
+	if (dev->accelerators) {
+		ret = cla_mtc_setup(dev);
+		if (ret)
+			goto err;
+
 		cla_info(dev, "available accelerators: 0x%02x\n",
 			 dev->accelerators);
+	}
 
 	dev->discovered = true;
 	return 0;
drivers/misc/arm-cla/cla-mtc.c new file +206 -0

206 lines not on this page · raw message

drivers/misc/arm-cla/cla-ops.c +52 -0

64 lines not on this page · raw message

Signature · 1 line
2.43.0
#20 lore raw

RFC PATCH v2 8/15 misc/arm-cla: Manage domain contexts

In reply to Ryan Roberts

A CLA domain cannot be used by multiple address spaces concurrently because its devices share a memory translation context and may communicate without isolation. Represent each user of a domain with a context keyed by the mm_struct and device file description, and track contexts in a per-domain hash table.

Add a domain scheduler that queues contexts for assignment and gives each one a fixed time slice. Before switching, revoke the outgoing context's mappings from all VMAs for the device file. Then save its accelerator state and remove its MTC, before installing the incoming context's MTC and restoring the incoming accelerator state.

Run hardware operations through CPU-bound kthread workers, since each CLA can only be accessed from its local CPU. Coordinate the per-device workers with a domain worker so that every CLA in the domain is switched as a single assignment unit.

Treat a failure on any device as a failure of the whole domain. Stop further assignments and wake all waiters when a domain becomes unusable.

---
 drivers/misc/arm-cla/Makefile       |   2 +
 drivers/misc/arm-cla/arm-cla.h      | 118 +++++++
 drivers/misc/arm-cla/cla-ctx.c      | 146 +++++++++
 drivers/misc/arm-cla/cla-init.c     |  62 ++++
 drivers/misc/arm-cla/cla-regs.c     |  26 +-
 drivers/misc/arm-cla/cla-sched.c    | 473 ++++++++++++++++++++++++++++
 drivers/misc/arm-cla/cla-topology.c |  23 ++
 7 files changed, 841 insertions(+), 9 deletions(-)
 create mode 100644 drivers/misc/arm-cla/cla-ctx.c
 create mode 100644 drivers/misc/arm-cla/cla-sched.c
drivers/misc/arm-cla/Makefile +2 -0
index df3ad7e4a1b4..a92c3594e5c9 100644
@@ -2,9 +2,11 @@
 
 arm-cla-y := \
 	cla-init.o \
+	cla-ctx.o \
 	cla-mtc.o \
 	cla-ops.o \
 	cla-regs.o \
+	cla-sched.o \
 	cla-topology.o
 
 obj-$(CONFIG_ARM_CLA) += arm-cla.o
drivers/misc/arm-cla/arm-cla.h +118 -0

179 lines not on this page · raw message

drivers/misc/arm-cla/cla-ctx.c new file +146 -0

146 lines not on this page · raw message

drivers/misc/arm-cla/cla-init.c +62 -0

113 lines not on this page · raw message

drivers/misc/arm-cla/cla-regs.c +17 -9
index 2452a7601990..d8ed74230e16 100644
@@ -128,16 +128,23 @@ static int cla_regs_uninstall_pl0(struct cla_dev *dev, struct cla_ctx *ctx,
 	if (ret)
 		return ret;
 
-	for (i = 0; i < CLA_NUM_DATA_REGS; i++)
-		regs->data[i] = cla_reg_read(dev, CLA_REG_DATA(i));
+	/*
+	 * No need to save a dying context. Note that we're not holding the
+	 * domain lock during this check and the context might be about to die,
+	 * but it's only an optimisation.
+	 */
+	if (!cla_ctx_is_dying(ctx)) {
+		for (i = 0; i < CLA_NUM_DATA_REGS; i++)
+			regs->data[i] = cla_reg_read(dev, CLA_REG_DATA(i));
 
-	cla_for_each_accid(dev, accid) {
-		ret = cla_regs_save_accel(dev, accid, regs, &regstate_off);
-		if (ret)
-			return ret;
-	}
+		cla_for_each_accid(dev, accid) {
+			ret = cla_regs_save_accel(dev, accid, regs, &regstate_off);
+			if (ret)
+				return ret;
+		}
 
-	regs->accel_valid = true;
+		regs->accel_valid = true;
+	}
 
 	/*
 	 * "If the accelerator is non idle when ENTERSR is launched, then a
@@ -218,7 +225,8 @@ int cla_regs_install(struct cla_dev *dev, struct cla_ctx *ctx,
  *
  * Uninstall a user context, and restore the kernel context if necessary.
  *
- * PL0 context: Save the DATA and LRESP registers and accelerator state.
+ * PL0 context: Save the DATA registers and accelerator state unless
+ * cla_ctx_is_dying() is true, since a dying context will not be restored.
  *
  * When this completes, all accelerators are idle. If this fails, some
  * accelerators may still be running.
drivers/misc/arm-cla/cla-sched.c new file +473 -0

473 lines not on this page · raw message

drivers/misc/arm-cla/cla-topology.c +23 -0
index 5137a0e041e5..ed7acec70019 100644
@@ -37,6 +37,8 @@ static struct cla_domain *cla_domain_alloc(struct cla_dev *dev, unsigned int fwi
 	if (!domain)
 		return ERR_PTR(-ENOMEM);
 
+	mutex_init(&domain->lock);
+
 	ret = xa_insert(&cla_domains, fwid, domain, GFP_KERNEL);
 	if (ret < 0)
 		goto err_free_domain;
@@ -49,8 +51,14 @@ static struct cla_domain *cla_domain_alloc(struct cla_dev *dev, unsigned int fwi
 	}
 	domain->devs[0] = dev;
 
+	ret = cla_domain_sched_init(domain);
+	if (ret)
+		goto err_free_devs;
+
 	return domain;
 
+err_free_devs:
+	kfree(domain->devs);
 err_free_id:
 	xa_erase(&cla_domains, fwid);
 err_free_domain:
@@ -149,6 +157,21 @@ int __init cla_domains_finalise(void)
 	return ret;
 }
 
+/**
+ * cla_domains_sched_exit - Drain and stop all domain schedulers
+ *
+ * All context users must have exited. Keep domains and lookup tables alive for
+ * CPU hotplug callbacks until those callbacks have been removed.
+ */
+void cla_domains_sched_exit(void)
+{
+	unsigned long fwid;
+	struct cla_domain *domain;
+
+	xa_for_each(&cla_domains, fwid, domain)
+		cla_domain_sched_exit(domain);
+}
+
 /**
  * cla_domains_free - free CLA domains and lookup tables
  *
Signature · 1 line
2.43.0
#21 lore raw

Re: [RFC PATCH v2 08/15] misc/arm-cla: Manage domain contexts

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] kthread: missing format argument in kthread_run_worker_on_cpu - [Medium] sched: timeslice…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] kthread: missing format argument in kthread_run_worker_on_cpu
- [Medium] sched: timeslice starvation via kthread_mod_delayed_work
--

commit 9e218cd8677c5cff035aa302edfc44906aa6b821
Author: Ryan Roberts <[email protected]>
misc/arm-cla: Manage domain contexts

This commit introduces a domain scheduler for the CLA driver that queues contexts for assignment with a fixed time slice. It runs hardware operations through CPU-bound kthread workers to coordinate per-device and domain switching. Failures on any device mark the entire domain as broken and wake all waiters.

Quoted 4 lines
drivers/misc/arm-cla/cla-init.c +0 -0
index 58f37787a59c1..e1694f84e05d0 100644

[ ... ]

drivers/misc/arm-cla/cla-init.c static void cla_dev_reinit(struct cla_dev *dev) · line 208

Quoted 9 lines
drivers/misc/arm-cla/cla-init.c +5 -0
@@ -198,6 +201,37 @@ static void cla_dev_reinit(struct cla_dev *dev)
 	cla_reg_write(dev, CLA_REG_LRESP, 0);
 }
 
+static int cla_dev_worker_init(struct cla_dev *dev, int cpu)
+{
+	struct kthread_worker *worker;
+
+	worker = kthread_run_worker_on_cpu(cpu, 0, "cla-dev-worker/%u");

[Severity: Medium]
Is this missing a format argument for the %u specifier?

It looks like kthread_run_worker_on_cpu() is being called with the format string "cla-dev-worker/%u", but without a corresponding unsigned int argument. Will vsnprintf read uninitialized memory from the stack or a register to satisfy the %u specifier, resulting in a garbage thread name?

Quoted 4 lines
drivers/misc/arm-cla/cla-init.c +4 -0
+	if (IS_ERR(worker))
+		return PTR_ERR(worker);
+
+	WARN_ON(dev->worker);

[ ... ]

Quoted 5 lines
drivers/misc/arm-cla/cla-sched.c new file +0 -0
new file mode 100644
index 0000000000000..6b5b782ac33e9

[ ... ]

Quoted 4 lines
drivers/misc/arm-cla/cla-sched.c new file +4 -0
+void cla_domain_schedule_reassignment(struct cla_domain *domain)
+{
+	struct cla_ctx *ctx = domain->assigned_ctx;
+	unsigned long delay_jfs = 0;

drivers/misc/arm-cla/cla-sched.c line 472

Quoted 10 lines
drivers/misc/arm-cla/cla-sched.c new file +10 -0
+
+	lockdep_assert_held(&domain->lock);
+
+	if (domain->broken || ctx == &invalid_ctx)
+		return;
+
+	if (ctx && !cla_ctx_is_dying(ctx))
+		delay_jfs = msecs_to_jiffies(CLA_SLICE_MS);
+
+	kthread_mod_delayed_work(domain->worker, &domain->reassign, delay_jfs);

[Severity: Medium]
Could this lead to timeslice starvation?

By using kthread_mod_delayed_work(), the timer is reset to delay_jfs (100ms) from the current time. If new contexts fault and are added to the queue, this function will be called again.

Does each call push the timer back, effectively giving the currently assigned context an infinite timeslice as long as new faults or wakeups keep arriving, starving all other contexts in the queue?

Would kthread_queue_delayed_work() be more appropriate here for normal timeslice tracking, since it does not push the timer back if it is already pending?

Quoted 1 line

+}

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#22 lore raw

Re: [RFC PATCH v2 08/15] misc/arm-cla: Manage domain contexts

In reply to Ryan Roberts

Hi Ryan,

thanks for your patch!

Quoted 1 line · Ryan Roberts

A CLA domain cannot be used by multiple address spaces concurrently

Which address space? The physical one? The virtual address space of the CPU for a certain CLA? The virtual address space of the CLA on a certain CPU, as found from it's TTBR0/1? I suspect the last one, but it needs clarifying.

And so the domain is definied in hardware but there is a footgun waiting to be fired by not defining the virtual address space exactly the same on all CLA:s in the domain?

Please elaborate.

Quoted 2 lines

because its devices share a memory translation context and may communicate without isolation.

Again I stumble here. "without isolation". So this kind of resoning implies I know of some isolation that I cannot have. But I don't know that, I have no idea what kind of isolation I would want here.

This needs to be explained differently.

Quoted 3 lines

Represent each user of a domain with a
context keyed by the mm_struct and device file description, and track contexts in a per-domain hash table.

This I understand.

Quoted 1 line

Add a domain scheduler that queues contexts for assignment

Are these contexts the software abstraction of hardware constraints (such as the virtual memory space) around a certain domain, and since they are scheduled, these constraints are then applied over a certain time window?

Quoted 5 lines

and gives
each one a fixed time slice. Before switching, revoke the outgoing context's mappings from all VMAs for the device file. Then save its accelerator state and remove its MTC, before installing the incoming context's MTC and restoring the incoming accelerator state.

I think I start to understand a little...

Quoted 11 lines

Run hardware operations through CPU-bound kthread workers, since each CLA can only be accessed from its local CPU. Coordinate the per-device workers with a domain worker so that every CLA in the domain is switched as a single assignment unit.

Treat a failure on any device as a failure of the whole domain. Stop further assignments and wake all waiters when a domain becomes unusable.

OK this is some kind of scheduler let's look, but right before we start you should probably define the principles of this scheduler? FIFO? round-robin? Something else?

Quoted 1 line

extern struct xarray cla_domains;

Nice use of xarray

drivers/misc/arm-cla/arm-cla.h static inline void cla_reg_write(struct cla_dev *dev, off_t reg, u64 val) · line 254

Quoted 9 lines
drivers/misc/arm-cla/arm-cla.h +9 -0
+static inline void cla_ctx_get(struct cla_ctx *ctx)
+{
+       kref_get(&ctx->refcnt);
+}
+
+static inline void cla_ctx_put(struct cla_ctx *ctx)
+{
+       kref_put(&ctx->refcnt, cla_ctx_free);
+}

Rename these something like _addref/_dropref or just inline the kref calls. These names upsets the kernel conventions for _get()/_put() of resources, see below.

Quoted 2 lines

+/**
+ * cla_ctx_create - Create a context or increase its user count

Something that creates or increase a context should be named cla_ctx_get() to avoid ambiguousness.

Quoted 2 lines

+/**
+ * cla_ctx_destroy - Drop a context user

No it drops the reference and drops the context (destroy it) if the usecount == 0.

Name it cla_ctx_put() to follow kernel patterns.

drivers/misc/arm-cla/cla-ctx.c line 128

Quoted 2 lines
drivers/misc/arm-cla/cla-ctx.c new file +2 -0
+       /* Release initial reference from cla_ctx_create(). */
+       cla_ctx_put(ctx);

So this needs a different name.

Quoted 1 line

+++ b/drivers/misc/arm-cla/cla-sched.c

I wanna spend some time here since this is RFC and we are looking more at design than code details.

drivers/misc/arm-cla/cla-sched.c line 3

Quoted 3 lines
drivers/misc/arm-cla/cla-sched.c new file +3 -0
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Arm CLA driver - domain scheduling

In this header explain the principles for the scheduling, as well as in the commit message.

drivers/misc/arm-cla/cla-sched.c line 20

Quoted 13 lines
drivers/misc/arm-cla/cla-sched.c new file +13 -0
+#include <linux/cpuhplock.h>
+#include <linux/rhashtable.h>
+
+#include "arm-cla.h"
+
+static struct cla_ctx invalid_ctx;
+
+static const struct rhashtable_params ctxs_rht_params = {
+       .head_offset = offsetof(struct cla_ctx, node),
+       .key_offset = offsetof(struct cla_ctx, key),
+       .key_len = sizeof(((struct cla_ctx *)0)->key),
+       .automatic_shrinking = true,
+};

Neat!

drivers/misc/arm-cla/cla-sched.c line 24

Quoted 3 lines
drivers/misc/arm-cla/cla-sched.c new file +3 -0
+static int __cla_domain_switch_ctx(struct cla_domain *domain,
+                                  struct cla_ctx *prev_ctx,
+                                  struct cla_ctx *next_ctx)

Is this one of those "__ means __inner_function()"?

Name it for exactly what it does instead.

drivers/misc/arm-cla/cla-sched.c line 71

Quoted 4 lines
drivers/misc/arm-cla/cla-sched.c new file +4 -0
+static int cla_domain_switch_ctx(struct cla_domain *domain,
+                                struct cla_ctx *prev_ctx,
+                                struct cla_ctx *next_ctx,
+                                struct cla_ctx **assigned_ctx)

Looks OK.

drivers/misc/arm-cla/cla-sched.c line 103

Quoted 9 lines
drivers/misc/arm-cla/cla-sched.c new file +9 -0
+/*
+ * Run on the cla's local CPU, either in its worker or a CPU hotplug callback.
+ * Work submitters hold cpus_read_lock() until completion, excluding hotplug
+ * callbacks and keeping the worker bound. Hotplug callbacks hold domain->lock
+ * to protect the assigned context. Other devices may switch concurrently.
+ * On failure, mark the device broken; the caller handles domain failure.
+ */
+int cla_dev_switch_ctx(struct cla_dev *dev, struct cla_ctx *prev_ctx,
+                      struct cla_ctx *next_ctx)

Good explanation and name, easy to understand.

Quoted 1 line

+void cla_dev_switch_ctx_work(struct kthread_work *work)

Here too

drivers/misc/arm-cla/cla-sched.c line 163

Quoted 5 lines
drivers/misc/arm-cla/cla-sched.c new file +5 -0
+static inline struct cla_ctx *cla_domain_get_next_ctx(struct cla_domain *domain)
+{
+       return list_first_entry_or_null(&domain->queued_ctxs, struct cla_ctx,
+                                       queue_node);
+}

This looks like a FIFO thing?

drivers/misc/arm-cla/cla-sched.c line 173

Quoted 9 lines
drivers/misc/arm-cla/cla-sched.c new file +9 -0
+static inline struct cla_ctx *cla_domain_get_prev_ctx(struct cla_domain *domain,
+                                                     struct cla_ctx *next_ctx)
+{
+       if (domain->assigned_ctx && (next_ctx || cla_ctx_is_dying(domain->assigned_ctx)))
+               return domain->assigned_ctx;
+       return NULL;
+}
+
+static void cla_vma_zap_domain(struct vm_area_struct *vma, struct cla_domain *domain)

"zap" is a very ambiguous word. This function needs to have a name that express exactly what it does.

It looks like it should rather be infixed _initialize_?

cla_domain_initialize_vma()?
cla_domain_reinitialize_vma()?

Quoted 6 lines
drivers/misc/arm-cla/cla-sched.c new file +6 -0
+{
+       unsigned long vma_start = vma->vm_pgoff;
+       unsigned long vma_end = vma_start + vma_pages(vma);
+       unsigned long domain_start = domain->pg_offset;
+       unsigned long domain_end = domain_start + domain->nr_devs;
+       unsigned long start = max(vma_start, domain_start);

drivers/misc/arm-cla/cla-sched.c line 189

Quoted 10 lines
drivers/misc/arm-cla/cla-sched.c new file +10 -0
+       unsigned long end = min(vma_end, domain_end);
+       unsigned long addr;
+       unsigned long size;
+
+       if (start >= end)
+               return;
+
+       addr = vma->vm_start + ((start - vma_start) << PAGE_SHIFT);
+       size = (end - start) << PAGE_SHIFT;
+       zap_special_vma_range(vma, addr, size);

That goes for that function too by the way. Two wrongs does not make one right.

It might be that everyone in memory management disagree with me and think this is crystal clear, then I can have other opinions.

Quoted 1 line

+static void cla_domain_zap(struct cla_domain *domain, struct cla_ctx *ctx)

And this one.

cla_domain_init()?
cla_domain_reinit()?

Quoted 1 line

+static void cla_domain_reassign(struct kthread_work *work)

What about a comment above this function explaining what is being reassigned to what?

Quoted 71 lines
drivers/misc/arm-cla/cla-sched.c new file +71 -0
+       /*
+        * Exclude cpuhp until assigned_ctx reflects the hardware again. cpuhp
+        * callbacks use it to save/restore the local device and must not see
+        * invalid_ctx. Take before domain->lock, also used by cpuhp callbacks.
+        */
+       cpus_read_lock();
+       mutex_lock(&domain->lock);
+       if (domain->broken)
+               goto out_unlock;
+
+       /* Figure out prev_ctx and next_ctx. NULL indicates don't [un]assign. */
+       next_ctx = cla_domain_get_next_ctx(domain);
+       prev_ctx = cla_domain_get_prev_ctx(domain, next_ctx);
+
+       if (!prev_ctx && !next_ctx)
+               goto out_unlock;
+
+       /* prev_ctx already holds its assignment reference. */
+       if (next_ctx)
+               cla_ctx_get(next_ctx);
+
+       /*
+        * We need to grab mmap_lock, but can't do so while holding the domain
+        * lock (since cla_vma_fault() grabs the domain lock while holding
+        * mmap_lock). The queue may change and contexts may be killed by
+        * cla_ctx_destroy() while the lock is dropped.
+        *
+        * No user is allowed to access CLA while we are reassigning. Disable
+        * assigned_ctx before zapping so cla_vma_fault() won't re-map the
+        * domain during reassignment. The sentinel also defers broken-domain
+        * cleanup until we know which context hardware may still access.
+        */
+       WRITE_ONCE(domain->assigned_ctx, &invalid_ctx);
+       mutex_unlock(&domain->lock);
+
+       /* Prevent prev_ctx from accessing any device in the domain. */
+       cla_domain_zap(domain, prev_ctx);
+
+       /* cpus_read_lock() ensures workers remain cpu-bound and alive. */
+       ret = cla_domain_switch_ctx(domain, prev_ctx, next_ctx, &assigned_ctx);
+
+       mutex_lock(&domain->lock);
+       WRITE_ONCE(domain->assigned_ctx, assigned_ctx);
+
+       /* Also handle failure reported by another thread during the switch. */
+       if (ret || domain->broken) {
+               cla_domain_set_broken(domain);
+               goto out_unlock;
+       }
+
+       /*
+        * Remove next_ctx from the queue and wake up all waiters so that the
+        * fault handler can map the domain into the newly assigned process.
+        * assigned_ctx must have been updated prior to waking the waiters.
+        *
+        * If next_ctx was killed while we were assigning it, schedule another
+        * reassignment to deassign it.
+        */
+       if (next_ctx) {
+               if (cla_ctx_is_dying(next_ctx)) {
+                       cla_domain_schedule_reassignment(domain);
+                       goto out_unlock;
+               }
+               list_del_init(&next_ctx->queue_node);
+               wake_up_all(&next_ctx->waitq);
+       }
+
+       /* If there are more queued ctxs, schedule the next reassignment. */
+       if (!list_empty(&domain->queued_ctxs))
+               cla_domain_schedule_reassignment(domain);
+

drivers/misc/arm-cla/cla-sched.c line 313

Quoted 10 lines
drivers/misc/arm-cla/cla-sched.c new file +10 -0
+out_unlock:
+       mutex_unlock(&domain->lock);
+       cpus_read_unlock();
+
+       /* Deliberately put references outside of the locks. */
+       if (next_ctx && next_ctx != assigned_ctx)
+               cla_ctx_put(next_ctx);
+       if (prev_ctx && prev_ctx != assigned_ctx)
+               cla_ctx_put(prev_ctx);
+}

This function contains a bunch of comments that are hard for me to understand without context (ha!) but it's probably all right, I bet they are helpful once you get the hang of it.

Quoted 1 line

+int cla_domain_sched_init(struct cla_domain *domain)

OK.

drivers/misc/arm-cla/cla-sched.c line 351

Quoted 8 lines
drivers/misc/arm-cla/cla-sched.c new file +8 -0
+/**
+ * cla_domain_sched_exit - Tear down scheduling for a CLA domain
+ * @domain: CLA domain
+ *
+ * Drain final deassignment, destroy the domain worker, and destroy the context
+ * table. All context users must have exited before calling this.
+ */
+void cla_domain_sched_exit(struct cla_domain *domain)

OK.

Quoted 1 line

+void cla_domain_set_broken(struct cla_domain *domain)

OK.

Quoted 2 lines
drivers/misc/arm-cla/cla-sched.c new file +2 -0
+struct cla_ctx *cla_domain_lookup_ctx(struct cla_domain *domain,
+                                     struct cla_ctx_key *key)

(...)

Quoted 1 line

+int cla_domain_insert_ctx(struct cla_domain *domain, struct cla_ctx *ctx)

(...)

Quoted 1 line

+void cla_domain_remove_ctx(struct cla_domain *domain, struct cla_ctx *ctx)

Clever use of rhashtable, good names.

drivers/misc/arm-cla/cla-sched.c line 459

Quoted 11 lines
drivers/misc/arm-cla/cla-sched.c new file +11 -0
+/**
+ * cla_domain_schedule_reassignment - Schedule domain reassignment
+ * @domain: CLA domain
+ *
+ * The caller must hold the domain lock. If a live context is currently
+ * assigned, schedule with a delay (CLA_SLICE_MS), otherwise reassign
+ * immediately. Do nothing if the domain is broken or a switch is in progress;
+ * the running switch handles new requests before returning. If reassignment is
+ * already scheduled, the delay is modified.
+ */
+void cla_domain_schedule_reassignment(struct cla_domain *domain)

Schedule reassign of the domain to ... what?

This use of verbs is really confusing me, I understand for example "assign timeslice to process" then I know a timeslice is assigned to a process. There is something implicit here making this really hard to understand.

Quoted 1 line

+void cla_domains_sched_exit(void)

OK.

But where is the cla_schedule() function in this scheduler akin to Linux' schedule() call? It feels like this is implicit in some call order semantic, and the function cla_domain_get_next_ctx() implements an implicit FIFO scheduling principle.

Alternatively the scheduling isn't actually driven here but from somehwere else, like userspace. Then that needs to be explained. Then this file doesn't actually implement any scheduling, it's a scheduling context library nothing more.

This kind of stuff needs to be explained so I can review the patch properly.

Yours,
Linus Walleij

#23 lore raw

RFC PATCH v2 9/15 misc/arm-cla: Add userspace interface

In reply to Ryan Roberts

Expose CLA devices through a character device so userspace can enumerate the available hardware and map accelerator register frames.

Provide ioctl interface to report device topology, CPU affinity, domain membership, mmap offsets, architecture version and attached accelerator masks, together with the IIDR, DEVARCH and REVIDR of each accelerator.

CLA registers can only be read from the CPU local to the device, while enumeration may occur on any CPU. Validate the supported CLA architecture version during device setup and cache the CLA and accelerator identification registers for later ioctl queries.

Support shared read-write mmap of one or more CLA register pages. Create a context for every domain covered by the mapping and resolve faults only while that context owns the domain. Queue unassigned contexts with the domain scheduler, drop mmap_lock while waiting for assignment and retry the fault after the context is woken.

---
 MAINTAINERS                         |   1 +
 drivers/misc/arm-cla/Makefile       |   3 +-
 drivers/misc/arm-cla/arm-cla-regs.h |   2 +
 drivers/misc/arm-cla/arm-cla.h      |  14 +
 drivers/misc/arm-cla/cla-init.c     |  27 ++
 drivers/misc/arm-cla/cla-regs.c     |  10 +
 drivers/misc/arm-cla/cla-user.c     | 541 ++++++++++++++++++++++++++++
 include/uapi/linux/arm-cla.h        | 198 ++++++++++
 8 files changed, 795 insertions(+), 1 deletion(-)
 create mode 100644 drivers/misc/arm-cla/cla-user.c
 create mode 100644 include/uapi/linux/arm-cla.h
MAINTAINERS +1 -0
index 98a25b3de9b4..f77d75e8a9a8 100644
@@ -2216,6 +2216,7 @@ S:	Supported
 F:	Documentation/devicetree/bindings/misc/arm,cla.yaml
 F:	Documentation/misc-devices/arm-cla.rst
 F:	drivers/misc/arm-cla/
+F:	include/uapi/linux/arm-cla.h
 
 ARM ETHOS-U NPU DRIVER
 M:	Rob Herring (Arm) <[email protected]>
drivers/misc/arm-cla/Makefile +2 -1
index a92c3594e5c9..f848c608e8f1 100644
@@ -7,6 +7,7 @@ arm-cla-y := \
 	cla-ops.o \
 	cla-regs.o \
 	cla-sched.o \
-	cla-topology.o
+	cla-topology.o \
+	cla-user.o
 
 obj-$(CONFIG_ARM_CLA) += arm-cla.o
drivers/misc/arm-cla/arm-cla-regs.h +2 -0
index d20a88780032..167e9ab64051 100644
@@ -64,6 +64,8 @@
 					 CLA_STATUS_EXCEPT | \
 					 CLA_STATUS_SRMODE)
 
+#define CLA_AIDR_PREP(maj, min)		((ULL(maj) << 8) | ULL(min))
+
 /* Standard accelerator registers */
 #define CLA_REG_IIDR			0x0000
 #define CLA_REG_DEVARCH			0x0001
drivers/misc/arm-cla/arm-cla.h +14 -0
index a797330956d9..e047094dd49c 100644
@@ -42,6 +42,12 @@ struct cla_call_on_cpu {
 	struct kthread_work switch_ctx;
 };
 
+struct cla_accel_desc {
+	u64 iidr;
+	u64 devarch;
+	u64 revidr;
+};
+
 /**
  * struct cla_dev - CLA device
  *
@@ -54,6 +60,8 @@ struct cla_call_on_cpu {
  * @pg_offset:		Mmap offset of this device.
  * @iassizes:		Combined regstate of all accels in bytes.
  * @domain:		The domain this CLA belongs to.
+ * @aidr:		CLA Architecture ID.
+ * @accel_descs:	Accelerator ID registers.
  *
  * Mutable, protected by CPU hotplug locking:
  * @discovered:		Discovered state is cached.
@@ -70,6 +78,8 @@ struct cla_dev {
 	unsigned long pg_offset;
 	unsigned long iassizes;
 	struct cla_domain *domain;
+	u64 aidr;
+	struct cla_accel_desc accel_descs[CLA_NUM_ACC];
 
 	bool discovered;
 	bool broken;
@@ -291,4 +301,8 @@ int cla_mtc_get_ctx(struct cla_ctx *ctx);
 void cla_mtc_put_ctx(struct cla_ctx *ctx);
 void cla_mtc_leak_ctx(struct cla_ctx *ctx);
 
+int cla_user_init(void);
+void cla_user_exit(void);
+u8 cla_user_accels(struct cla_dev *dev, struct file *file);
+
 #endif /* _ARM_CLA_H_ */
drivers/misc/arm-cla/cla-init.c +27 -0
index e1694f84e05d..1afe20aa877f 100644
@@ -84,6 +84,7 @@ static int cla_reset_pmu(struct cla_dev *dev, unsigned int accid)
  */
 static int cla_dev_discover_accel(struct cla_dev *dev, unsigned int accid)
 {
+	struct cla_accel_desc *desc = &dev->accel_descs[accid];
 	unsigned long iassizes;
 	u64 iassize;
 	u64 acap;
@@ -102,6 +103,20 @@ static int cla_dev_discover_accel(struct cla_dev *dev, unsigned int accid)
 		return 1;
 	}
 
+	/*
+	 * Cache some standard accelerator registers that user space may query
+	 * via ioctl from a remote CPU.
+	 */
+	ret = cla_op_regread(dev, accid, CLA_REG_IIDR, 1, &desc->iidr);
+	if (ret)
+		return ret;
+	ret = cla_op_regread(dev, accid, CLA_REG_DEVARCH, 1, &desc->devarch);
+	if (ret)
+		return ret;
+	ret = cla_op_regread(dev, accid, CLA_REG_REVIDR, 1, &desc->revidr);
+	if (ret)
+		return ret;
+
 	ret = cla_op_regread(dev, accid, CLA_REG_IASSIZE, 1, &iassize);
 	if (ret)
 		return ret;
@@ -248,6 +263,12 @@ static int cla_dev_setup(unsigned int cpu)
 		return -EINVAL;
 
 	if (!dev->discovered) {
+		dev->aidr = cla_reg_read(dev, CLA_REG_CLAAIDR);
+
+		/* Check for supported CLA architecture version. */
+		if (dev->aidr != CLA_AIDR_PREP(2, 0))
+			return -EPROTONOSUPPORT;
+
 		/* Discard partial results from an earlier, failed discovery. */
 		dev->accelerators = 0;
 		dev->iassizes = 0;
@@ -498,6 +519,11 @@ static int __init cla_module_init(void)
 		cla_cpuhp_state = ret;
 	}
 
+	/* Must be last fallible step; see cla_user_init(). */
+	ret = cla_user_init();
+	if (ret)
+		goto err_hardware;
+
 	return 0;
 
 err_hardware:
@@ -512,6 +538,7 @@ static int __init cla_module_init(void)
 
 static void __exit cla_module_exit(void)
 {
+	cla_user_exit();
 	cla_domains_sched_exit();
 	cpuhp_remove_state(cla_cpuhp_state);
 	cla_domains_free();
drivers/misc/arm-cla/cla-regs.c +10 -0
index d8ed74230e16..d48311d0ef92 100644
@@ -162,6 +162,8 @@ static int cla_regs_install_pl0(struct cla_dev *dev, struct cla_ctx *ctx,
 {
 	int i;
 	int ret;
+	u64 pl0ctrl = 0;
+	u8 accelerators;
 	unsigned int accid;
 	size_t regstate_off = 0;
 	struct cla_regs_pl0 *regs = ctx->regs[ctx_id];
@@ -192,6 +194,14 @@ static int cla_regs_install_pl0(struct cla_dev *dev, struct cla_ctx *ctx,
 		cla_reg_write(dev, CLA_REG_DATA(i), regs->data[i]);
 	cla_reg_write(dev, CLA_REG_LRESP, regs->lresp);
 
+	/* Restrict which accelerators this context can access at PL0. */
+	accelerators = cla_user_accels(dev, ctx->key.file);
+	cla_for_each_accid(dev, accid) {
+		if (accelerators & BIT(accid))
+			pl0ctrl |= CLA_PLxCTRL_PREP(accid, CLA_PLxCTRL_AVAIL);
+	}
+	cla_reg_write(dev, CLA_REG_PL0CTRL, pl0ctrl);
+
 	return 0;
 }
 
drivers/misc/arm-cla/cla-user.c new file +541 -0

541 lines not on this page · raw message

include/uapi/linux/arm-cla.h new file +198 -0

198 lines not on this page · raw message

Signature · 1 line
2.43.0
#24 lore raw

Re: [RFC PATCH v2 09/15] misc/arm-cla: Add userspace interface

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] core: format string mismatch in dev_set_name causes init failure on 32-bit archs - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] core: format string mismatch in dev_set_name causes init failure on 32-bit archs
- [Medium] misc/arm-cla: missing array_index_nospec in cla_vma_fault creates Spectre v1 gadget --

commit 91161eb49b1b380686ad6f07674f5b53c3cf7baa
Author: Ryan Roberts <[email protected]>

misc/arm-cla: Add userspace interface

Expose CLA devices through a character device so userspace can enumerate the available hardware and map accelerator register frames.

Quoted 6 lines
drivers/misc/arm-cla/cla-user.c new file +0 -0
new file mode 100644
index 0000000000000..41cd5e4a7d017
@@ -0,0 +1,541 @@

[ ... ]

Quoted 10 lines
drivers/misc/arm-cla/cla-user.c new file +10 -0
+static vm_fault_t cla_vma_fault(struct vm_fault *vmf)
+{
+	struct vm_area_struct *vma = vmf->vma;
+	struct cla_ctx_key key = CLA_CTX_KEY_PL0(vma->vm_mm, vma->vm_file);
+	struct cla_domain *domain;
+	struct cla_dev *dev;
+	struct cla_ctx *ctx;
+	unsigned long pg;
+
+	/*

drivers/misc/arm-cla/cla-user.c line 204

Quoted 10 lines
drivers/misc/arm-cla/cla-user.c new file +10 -0
+	 * Reassignment needs mmap_lock, so we cannot wait while holding it.
+	 * The private futex fault-in path can reach here without allowing
+	 * mmap_lock to be dropped. Reject faults that do not allow retry.
+	 */
+	if (!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))
+		return VM_FAULT_SIGBUS;
+
+	pg = vma->vm_pgoff + ((vmf->address - vma->vm_start) >> PAGE_SHIFT);
+	dev = cla_lut_pg[pg];
+	domain = dev->domain;

[Severity: Medium]
In cla_vma_fault(), pg is calculated from the user-controlled vmf->address and used to index the global cla_lut_pg array.

Is there a risk that speculative execution could bypass the VMA bounds checks prior to this handler, resulting in an out-of-bounds read that is immediately dereferenced? Could this create a Spectre v1 gadget, and should we use array_index_nospec() to clamp pg before indexing?

Quoted 3 lines
drivers/misc/arm-cla/cla-user.c new file +3 -0
+
+	mutex_lock(&domain->lock);
+	ctx = cla_domain_lookup_ctx(domain, &key);

[ ... ]

Quoted 5 lines
drivers/misc/arm-cla/cla-user.c new file +5 -0
+static int __init cla_accel_class_add(const struct cla_accel_desc *desc)
+{
+	struct cla_accel_class *aclass;
+	unsigned int i;
+	int ret;

[ ... ]

drivers/misc/arm-cla/cla-user.c line 407

Quoted 9 lines
drivers/misc/arm-cla/cla-user.c new file +9 -0
+	aclass->desc = *desc;
+	device_initialize(&aclass->dev);
+	aclass->dev.class = cla_class;
+	aclass->dev.devt = cla_devt + cla_nr_classes;
+	aclass->dev.release = cla_accel_class_release;
+
+	ret = dev_set_name(&aclass->dev, "%03lx:%03lx",
+			   FIELD_GET(CLA_IIDR_IMPLEMENTER, desc->iidr),
+			   FIELD_GET(CLA_IIDR_PRODUCTID, desc->iidr));

[Severity: High]
Does this format string cause argument misalignment on 32-bit architectures?

Because desc->iidr is a u64, FIELD_GET() returns a 64-bit value. Using %03lx expects a 32-bit unsigned long on 32-bit systems. This could cause the first %03lx to consume the lower 32 bits, and the second %03lx to consume the upper 32 bits, completely ignoring the intended PRODUCTID argument.

If devices share the same implementer but have different product IDs, could this result in identical names and cause device_add() to fail with -EEXIST?

Quoted 5 lines
drivers/misc/arm-cla/cla-user.c new file +5 -0
+	if (ret)
+		goto err_put;
+
+	/* The node cannot be opened until cla_user_init() adds the cdev. */
+	ret = device_add(&aclass->dev);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#25 lore raw

RFC PATCH v2 10/15 KVM: arm64: Introduce support to pin VMIDs

In reply to Ryan Roberts

From: Shameer Kolothum <[email protected]>

Introduce kvm_arm_pinned_vmid_get() and kvm_arm_pinned_vmid_put(), to pin a VMID associated with a KVM instance. This will guarantee that VMID remains the same after a rollover.

This will allow some devices, such as ones behind an SMMUv3, to have their TLB entries tagged with the KVM VMID. In some systems, TLB maintenance instructions from the CPU to the Inner Shareable domain can invalidate those entries.

---
 arch/arm64/include/asm/kvm_host.h |  3 ++
 arch/arm64/kvm/vmid.c             | 77 ++++++++++++++++++++++++++++---
 2 files changed, 73 insertions(+), 7 deletions(-)
arch/arm64/include/asm/kvm_host.h +3 -0
index cd9b9d2462f9..30d0082b15ec 100644
@@ -148,6 +148,7 @@ int topup_hyp_memcache(struct kvm_hyp_memcache *mc, unsigned long min_pages);
 
 struct kvm_vmid {
 	atomic64_t id;
+	refcount_t pinned;
 };
 
 struct kvm_s2_mmu {
@@ -1359,6 +1360,8 @@ int __init kvm_arm_vmid_alloc_init(void);
 void __init kvm_arm_vmid_alloc_free(void);
 void kvm_arm_vmid_update(struct kvm_vmid *kvm_vmid);
 void kvm_arm_vmid_clear_active(void);
+int kvm_arm_pinned_vmid_get(struct kvm *kvm);
+void kvm_arm_pinned_vmid_put(struct kvm *kvm);
 
 static inline void kvm_arm_pvtime_vcpu_init(struct kvm_vcpu_arch *vcpu_arch)
 {
arch/arm64/kvm/vmid.c +70 -7

111 lines not on this page · raw message

Signature · 1 line
2.43.0
#26 lore raw

Re: [RFC PATCH v2 10/15] KVM: arm64: Introduce support to pin VMIDs

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] kvm: arm64: integer underflow in max_pinned_vmids allows slab OOB write --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] kvm: arm64: integer underflow in max_pinned_vmids allows slab OOB write --

commit 5166cc2f774d24bbef4a1dfb451334ee93c6273a
Author: Shameer Kolothum <[email protected]>
KVM: arm64: Introduce support to pin VMIDs

Introduce kvm_arm_pinned_vmid_get() and kvm_arm_pinned_vmid_put(), to pin a VMID associated with a KVM instance. This will guarantee that VMID remains the same after a rollover.

Quoted 4 lines
arch/arm64/kvm/vmid.c +0 -0
index 7fe8ba1a2851c..322279f59e881 100644

[ ... ]

Quoted 9 lines
arch/arm64/kvm/vmid.c +5 -0
@@ -169,6 +175,49 @@ void kvm_arm_vmid_update(struct kvm_vmid *kvm_vmid)
 	raw_spin_unlock_irqrestore(&cpu_vmid_lock, flags);
 }
 
+int kvm_arm_pinned_vmid_get(struct kvm *kvm)
+{
+	struct kvm_vmid *kvm_vmid;
+	u64 vmid;
+

arch/arm64/kvm/vmid.c void kvm_arm_vmid_update(struct kvm_vmid *kvm_vmid) · line 192

Quoted 10 lines
arch/arm64/kvm/vmid.c +10 -0
+	kvm_vmid = &kvm->arch.mmu.vmid;
+
+	guard(raw_spinlock_irqsave)(&cpu_vmid_lock);
+	vmid = atomic64_read(&kvm_vmid->id);
+
+	if (refcount_inc_not_zero(&kvm_vmid->pinned))
+		return (vmid & ~VMID_MASK);
+
+	if (nr_pinned_vmids >= max_pinned_vmids)
+		return -EINVAL;

[Severity: Critical]
Does this capacity check protect against pinning exhaustion if max_pinned_vmids underflows?

On ARM64 systems with 8-bit VMIDs (NUM_USER_VMIDS=256) and 255 or more CPUs, the subtraction used to set max_pinned_vmids in kvm_arm_vmid_alloc_init() will wrap around to a huge unsigned value.

This allows userspace to bypass this check and exhaust all VMIDs by pinning them. Once fully exhausted, new_vmid()'s fallback find_next_zero_bit() returns 256, and then falls through to the set_vmid label:

arch/arm64/kvm/vmid.c:new_vmid() {
	...
set_vmid:
	__set_bit(vmid, vmid_map);
	...
}

Can this write past the end of the 256-bit bitmap and corrupt adjacent slab memory?

[ ... ]

Quoted 6 lines
arch/arm64/kvm/vmid.c +2 -0
@@ -186,10 +235,24 @@ int __init kvm_arm_vmid_alloc_init(void)
 	if (!vmid_map)
 		return -ENOMEM;
 
+	pinned_vmid_map = bitmap_zalloc(NUM_USER_VMIDS, GFP_KERNEL);
+	if (!pinned_vmid_map) {

arch/arm64/kvm/vmid.c int __init kvm_arm_vmid_alloc_init(void) · line 249

Quoted 10 lines
arch/arm64/kvm/vmid.c +10 -0
+		bitmap_free(vmid_map);
+		return -ENOMEM;
+	}
+	nr_pinned_vmids = 0;
+
+	/*
+	 * Ensure we have at least one empty slot available after rollover when
+	 * the maximum number of VMIDs are pinned. VMID#0 is reserved.
+	 */
+	max_pinned_vmids = NUM_USER_VMIDS - num_possible_cpus() - 2;

[Severity: Critical]
Is it possible for this subtraction to underflow?

If a system has 8-bit VMIDs (NUM_USER_VMIDS = 256) and 255 or more CPUs, this will result in a negative value that wraps around to ULONG_MAX.

While there is a WARN_ON(NUM_USER_VMIDS - 1 <= num_possible_cpus()) earlier in kvm_arm_vmid_alloc_init(), it only emits a warning and does not prevent the initialization from proceeding and setting this underflowed value.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#27 lore raw

RFC PATCH v2 11/15 KVM: arm64: Export stage-2 MMU config

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Provide an API to drivers that want to share the stage 2 configuration of a VM with their device. At the moment it is rather limited:

* No invalidation notifiers. The TLBs on the device side, if any, receive CPU TLB invalidations.

* No remote page fault support. All paging still takes the normal data abort route on the CPU. Options are pinning all guest memory or device-specific mechanism for reporting pending faults to the guest.

* No nested VMs. Although we could perhaps support assigning devices to the hyp context of a nested VM, it seems performative.

So for the moment this API works for devices that share the CPU MMU, but the SMMU driver could use it with DVM.

---
 arch/arm64/include/asm/kvm_host.h |  11 ++++
 arch/arm64/include/asm/kvm_mmu.h  |   1 +
 arch/arm64/kvm/mmu.c              | 102 ++++++++++++++++++++++++++++++
 arch/arm64/kvm/sys_regs.c         |  14 +---
 4 files changed, 117 insertions(+), 11 deletions(-)
arch/arm64/include/asm/kvm_host.h +11 -0
index 30d0082b15ec..c0932b43f959 100644
@@ -235,6 +235,14 @@ struct kvm_s2_mmu {
 	atomic_t refcnt;
 };
 
+/* stage 2 MMU configuration, for drivers that speak VMSA */
+struct kvm_arch_guest_mmu {
+	u64 hcr;
+	u64 hcrx;
+	u64 vtcr;
+	u64 vttbr;
+};
+
 struct kvm_arch_memory_slot {
 };
 
@@ -1720,4 +1728,7 @@ static __always_inline enum fgt_group_id __fgt_reg_to_group_id(enum vcpu_sysreg
 
 long kvm_get_cap_for_kvm_ioctl(unsigned int ioctl, long *ext);
 
+struct kvm_arch_guest_mmu *kvm_arch_get_guest_mmu(struct kvm *kvm);
+void kvm_arch_put_guest_mmu(struct kvm *kvm, struct kvm_arch_guest_mmu *mmu);
+
 #endif /* __ARM64_KVM_HOST_H__ */
arch/arm64/include/asm/kvm_mmu.h +1 -0
index 6eae7e7e2a68..8a9d385fe14d 100644
@@ -185,6 +185,7 @@ int kvm_handle_guest_sea(struct kvm_vcpu *vcpu);
 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu);
 
 phys_addr_t kvm_mmu_get_httbr(void);
+u64 kvm_mmu_get_hcr(struct kvm *kvm, u64 hcr);
 phys_addr_t kvm_get_idmap_vector(void);
 int __init kvm_mmu_init(u32 hyp_va_bits);
 
arch/arm64/kvm/mmu.c +102 -0

105 lines not on this page · raw message

arch/arm64/kvm/sys_regs.c +3 -11
index a2f4e769a428..20277f888380 100644
@@ -5798,8 +5798,8 @@ static void vcpu_set_hcr(struct kvm_vcpu *vcpu)
 {
 	struct kvm *kvm = vcpu->kvm;
 
-	if (has_vhe() || has_hvhe())
-		vcpu->arch.hcr_el2 |= HCR_E2H;
+	vcpu->arch.hcr_el2 = kvm_mmu_get_hcr(kvm, vcpu->arch.hcr_el2);
+
 	if (cpus_have_final_cap(ARM64_HAS_RAS_EXTN)) {
 		/* route synchronous external abort exceptions to EL2 */
 		vcpu->arch.hcr_el2 |= HCR_TEA;
@@ -5807,9 +5807,6 @@ static void vcpu_set_hcr(struct kvm_vcpu *vcpu)
 		vcpu->arch.hcr_el2 |= HCR_TERR;
 	}
 
-	if (cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
-		vcpu->arch.hcr_el2 |= HCR_FWB;
-
 	if (cpus_have_final_cap(ARM64_HAS_EVT) &&
 	    !cpus_have_final_cap(ARM64_MISMATCHED_CACHE_TYPE) &&
 	    kvm_read_vm_id_reg(kvm, SYS_CTR_EL0) == read_sanitised_ftr_reg(SYS_CTR_EL0))
@@ -5817,12 +5814,7 @@ static void vcpu_set_hcr(struct kvm_vcpu *vcpu)
 	else
 		vcpu->arch.hcr_el2 |= HCR_TID2;
 
-	if (vcpu_el1_is_32bit(vcpu))
-		vcpu->arch.hcr_el2 &= ~HCR_RW;
-
-	if (kvm_has_mte(vcpu->kvm))
-		vcpu->arch.hcr_el2 |= HCR_ATA;
-	else
+	if (!kvm_has_mte(vcpu->kvm))
 		vcpu->arch.hcr_el2 |= HCR_TID5;
 
 	/*
Signature · 1 line
2.43.0
#28 lore raw

Re: [RFC PATCH v2 11/15] KVM: arm64: Export stage-2 MMU config

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] cleanup: mixing goto-based cleanup and guard() in kvm_arch_get_guest_mmu() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] cleanup: mixing goto-based cleanup and guard() in kvm_arch_get_guest_mmu() --

commit 857dcf037db9acd0dfd4486a2d4b54b73644b090
Author: Jean-Philippe Brucker <[email protected]>

KVM: arm64: Export stage-2 MMU config

This commit provides an API to drivers that want to share the stage 2 configuration of a VM with their device. It introduces the kvm_arch_get_guest_mmu and kvm_arch_put_guest_mmu functions to expose the stage 2 MMU config of an EL1 VM.

Quoted 4 lines
arch/arm64/kvm/mmu.c +0 -0
index 9ba86450fe4af..56490226f973b 100644

[ ... ]

Quoted 9 lines
arch/arm64/kvm/mmu.c +9 -0
+struct kvm_arch_guest_mmu *kvm_arch_get_guest_mmu(struct kvm *kvm)
+{
+	int ret;
+	struct kvm_arch_guest_mmu *mmu;
+
+	guard(mutex)(&kvm->arch.config_lock);
+
+	if (is_protected_kvm_enabled())
+		return ERR_PTR(-EOPNOTSUPP);

[ ... ]

Quoted 9 lines
arch/arm64/kvm/mmu.c +9 -0
+	ret = kvm_arm_pinned_vmid_get(kvm);
+	if (ret < 0)
+		return ERR_PTR(ret);
+
+	ret = -ENOMEM;
+	mmu = kzalloc_obj(*mmu, GFP_KERNEL_ACCOUNT);
+	if (!mmu)
+		goto err_unpin_vmid;
+

arch/arm64/kvm/mmu.c void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled) · line 2901

Quoted 10 lines
arch/arm64/kvm/mmu.c +10 -0
+	mmu->vtcr = kvm->arch.mmu.vtcr;
+	mmu->vttbr = kvm_get_vttbr(&kvm->arch.mmu);
+	mmu->hcr = kvm_mmu_get_hcr(kvm, 0);
+
+	return mmu;
+
+err_unpin_vmid:
+	kvm_arm_pinned_vmid_put(kvm);
+	return ERR_PTR(ret);
+}

[Severity: Low]
Is it intentional to mix goto-based cleanup and guard macros in this function?

The function uses guard(mutex)(&kvm->arch.config_lock) for scope-based locking, but also relies on the goto err_unpin_vmid label to clean up the VMID when kzalloc_obj fails.

According to the cleanup helpers guidelines, mixing goto-based error handling with scope-based cleanup helpers in the same function creates confusing ownership semantics and increases the risk of double-free or resource leak bugs during future code edits.

Would it be better to convert this entirely to scope-based cleanup, or alternatively, use manual unlocks without the guard macro?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
maintainer
#29 lore raw

Re: [RFC PATCH v2 11/15] KVM: arm64: Export stage-2 MMU config

In reply to Ryan Roberts
Quoted 133 lines · Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Provide an API to drivers that want to share the stage 2 configuration of a VM with their device. At the moment it is rather limited:

* No invalidation notifiers. The TLBs on the device side, if any, receive CPU TLB invalidations.

* No remote page fault support. All paging still takes the normal data abort route on the CPU. Options are pinning all guest memory or device-specific mechanism for reporting pending faults to the guest.

* No nested VMs. Although we could perhaps support assigning devices to the hyp context of a nested VM, it seems performative.

So for the moment this API works for devices that share the CPU MMU, but the SMMU driver could use it with DVM.

---
 arch/arm64/include/asm/kvm_host.h |  11 ++++
 arch/arm64/include/asm/kvm_mmu.h  |   1 +
 arch/arm64/kvm/mmu.c              | 102 ++++++++++++++++++++++++++++++
 arch/arm64/kvm/sys_regs.c         |  14 +---
 4 files changed, 117 insertions(+), 11 deletions(-)
arch/arm64/include/asm/kvm_host.h +11 -0
index 30d0082b15ec..c0932b43f959 100644
@@ -235,6 +235,14 @@ struct kvm_s2_mmu {
 	atomic_t refcnt;
 };
 
+/* stage 2 MMU configuration, for drivers that speak VMSA */
+struct kvm_arch_guest_mmu {
+	u64 hcr;
+	u64 hcrx;
+	u64 vtcr;
+	u64 vttbr;
+};
+
 struct kvm_arch_memory_slot {
 };
 
@@ -1720,4 +1728,7 @@ static __always_inline enum fgt_group_id __fgt_reg_to_group_id(enum vcpu_sysreg
 
 long kvm_get_cap_for_kvm_ioctl(unsigned int ioctl, long *ext);
 
+struct kvm_arch_guest_mmu *kvm_arch_get_guest_mmu(struct kvm *kvm);
+void kvm_arch_put_guest_mmu(struct kvm *kvm, struct kvm_arch_guest_mmu *mmu);
+
 #endif /* __ARM64_KVM_HOST_H__ */
arch/arm64/include/asm/kvm_mmu.h +1 -0
index 6eae7e7e2a68..8a9d385fe14d 100644
@@ -185,6 +185,7 @@ int kvm_handle_guest_sea(struct kvm_vcpu *vcpu);
 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu);
 
 phys_addr_t kvm_mmu_get_httbr(void);
+u64 kvm_mmu_get_hcr(struct kvm *kvm, u64 hcr);
 phys_addr_t kvm_get_idmap_vector(void);
 int __init kvm_mmu_init(u32 hyp_va_bits);
 
arch/arm64/kvm/mmu.c +59 -0
index 2d44cd6a5aed..0bf1dff2a41f 100644
@@ -2805,3 +2805,105 @@ void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
 
 	trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
 }
+
+#define HCR_MMU_BITS (HCR_VM | HCR_PTW | HCR_DC | HCR_TGE | HCR_RW |	\
+		      HCR_CD | HCR_ID | HCR_E2H | HCR_NV | HCR_NV1 |	\
+		      HCR_FWB | HCR_ATA | HCR_DCT)
+
+/* Update MMU-specific host bits of HCR_EL2 */
+u64 kvm_mmu_get_hcr(struct kvm *kvm, u64 hcr)
+{
+	lockdep_assert_held(&kvm->arch.config_lock);
+
+	WARN_ON(!test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED,
+			  &kvm->arch.flags));
+
+	hcr &= ~HCR_MMU_BITS;
+	hcr |= HCR_VM | HCR_PTW;
+
+	if (has_vhe() || has_hvhe())
+		hcr |= HCR_E2H;
+
+	if (cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
+		hcr |= HCR_FWB;
+
+	if (kvm_has_mte(kvm))
+		hcr |= HCR_ATA;
+
+	if (!test_bit(KVM_ARM_VCPU_EL1_32BIT, kvm->arch.vcpu_features))
+		hcr |= HCR_RW;
+
+	return hcr;
+}
+
+/**
+ * kvm_arch_get_guest_mmu - Get a reference to the guest MMU config
+ * @kvm: KVM instance. Caller must hold a reference.
+ *
+ * Get the stage 2 MMU config of an EL1 VM. The returned object contains
+ * settings that do not change until the object is released with
+ * kvm_arch_put_guest_mmu(). This function does not support nested VMs.
+ *
+ * HCR has lots of settings, some of which differ between vCPUs, but most of
+ * them control traps. For EL1 VMs, the bits relevant to MMU translation are
+ * common to all vCPUs:
+ * - VM, PTW, DC, TGE, CD, ID, NV, NV1, DCT have fixed values.
+ * - E2H, FWB, ATA depend on host CPU features (respectively VHE, FWB and MTE2).
+ * - RW depends on vCPU features. This function does not support 32-bit VMs.
+ *
+ * HCRX: EnSDERR, EnSNERR set to 0. TODO: is GCSEn relevant?
+ *
+ * VTCR is set once for the VM, depends on the VM's IPA size.
+ *
+ * VTTBR:
+ * - VMID is pinned, until kvm_arch_put_guest_mmu() is called.
+ * - PGD is allocated and freed with the vm (the caller must hold their
+ *   reference to @kvm). KVM may create and remove page table mappings at any
+ *   moment, and uses normal TLB maintenance operations to synchronize with
+ *   page table walkers. KVM does not notify the caller about mapping changes.
+ * - CNP is a property of the host system.
+ *
+ * Return: a new kvm_arch_guest_mmu instance, or an error pointer on failure.

arch/arm64/kvm/mmu.c void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled) · line 2876

Quoted 10 lines
arch/arm64/kvm/mmu.c +10 -0
+ */
+struct kvm_arch_guest_mmu *kvm_arch_get_guest_mmu(struct kvm *kvm)
+{
+	int ret;
+	struct kvm_arch_guest_mmu *mmu;
+
+	guard(mutex)(&kvm->arch.config_lock);
+
+	if (is_protected_kvm_enabled())
+		return ERR_PTR(-EOPNOTSUPP);

How does this compose with CCA? Can it be restricted to exclusively running VHE rather than also dealing with the lesser configurations?

Quoted 8 lines
arch/arm64/kvm/mmu.c +8 -0
+
+	if (!test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags) ||
+	    test_bit(KVM_ARM_VCPU_EL1_32BIT, kvm->arch.vcpu_features) ||
+	    test_bit(KVM_ARM_VCPU_HAS_EL2, kvm->arch.vcpu_features))
+		return ERR_PTR(-EINVAL);
+
+	ret = kvm_arm_pinned_vmid_get(kvm);
+	if (ret < 0)

arch/arm64/kvm/mmu.c void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled) · line 2894

Quoted 10 lines
arch/arm64/kvm/mmu.c +10 -0
+		return ERR_PTR(ret);
+
+	ret = -ENOMEM;
+	mmu = kzalloc_obj(*mmu, GFP_KERNEL_ACCOUNT);
+	if (!mmu)
+		goto err_unpin_vmid;
+
+	mmu->vtcr = kvm->arch.mmu.vtcr;
+	mmu->vttbr = kvm_get_vttbr(&kvm->arch.mmu);
+	mmu->hcr = kvm_mmu_get_hcr(kvm, 0);

How about the hcrx field in the structure?

arch/arm64/kvm/mmu.c void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled) · line 2902

Quoted 8 lines
arch/arm64/kvm/mmu.c +8 -0
+
+	return mmu;
+
+err_unpin_vmid:
+	kvm_arm_pinned_vmid_put(kvm);
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(kvm_arch_get_guest_mmu);

It really feels like this is a bit upside down. Since you are actively pinning the S2 MMU context, it should only be a matter of taking a reference on the kvm struct (just like KVM devices do), and handing off the kvm_s2_mmu structure, rather than copying things. When you're done with it, drop the reference.

If there is a need to deal with a different value for HCR_EL2 (or anything else), it can be done in the code that makes use of it, rather than being in the KVM code.

Thanks,

	M.
Signature · 1 line
Without deviation from the norm, progress is not possible.
#30 lore raw

Re: [RFC PATCH v2 11/15] KVM: arm64: Export stage-2 MMU config

Quoted 11 lines · Marc Zyngier

arch/arm64/kvm/mmu.c void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled) · line 2876

Quoted 9 lines
arch/arm64/kvm/mmu.c +9 -0
+struct kvm_arch_guest_mmu *kvm_arch_get_guest_mmu(struct kvm *kvm)
+{
+	int ret;
+	struct kvm_arch_guest_mmu *mmu;
+
+	guard(mutex)(&kvm->arch.config_lock);
+
+	if (is_protected_kvm_enabled())
+		return ERR_PTR(-EOPNOTSUPP);

How does this compose with CCA?

This function would reject realm VMs once they're supported. If we wanted to assign a CLA device to a realm VM, I think it would be managed entirely outside the host:

* EL3 driver reconfigures the device's accesses to physical memory (security state, memory encryption etc),
* RMM driver owns the PL2 registers to program the stage 2 MTC,
* the VM owns the rest of the device.

Lack of interrupts should make this assignment relatively simple.

Quoted 2 lines

Can it be restricted to exclusively running VHE rather than also dealing with the lesser configurations?

Yes, I don't think we want to support any nVHE config at this point.

Quoted 5 lines

arch/arm64/kvm/mmu.c void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled) · line 2894

Quoted 3 lines
arch/arm64/kvm/mmu.c +3 -0
+	mmu->vtcr = kvm->arch.mmu.vtcr;
+	mmu->vttbr = kvm_get_vttbr(&kvm->arch.mmu);
+	mmu->hcr = kvm_mmu_get_hcr(kvm, 0);

How about the hcrx field in the structure?

It's 0 because HCRX doesn't seem to have bits relevant to MMU translation, except maybe EnSDERR and EnSNERR that KVM doesn't set. But it's not entirely clear which bits are relevant to this function, because other possible users may access memory differently (eg. no instruction fetch or CMO from a CLA device). Your suggestion below should simplify this.

Quoted 6 lines
Quoted 6 lines
arch/arm64/kvm/mmu.c +6 -0
+
+	return mmu;
+
+err_unpin_vmid:
+	kvm_arm_pinned_vmid_put(kvm);
+	return ERR_PTR(ret);
Quoted 8 lines

arch/arm64/kvm/mmu.c void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled) · line 2902

Quoted 2 lines
arch/arm64/kvm/mmu.c +2 -0
+}
+EXPORT_SYMBOL_GPL(kvm_arch_get_guest_mmu);

It really feels like this is a bit upside down. Since you are actively pinning the S2 MMU context, it should only be a matter of taking a reference on the kvm struct (just like KVM devices do), and handing off the kvm_s2_mmu structure, rather than copying things. When you're done with it, drop the reference.

OK, I'll update this. The reason for this copy was to keep a clear separation between KVM and the CLA driver, so the driver wouldn't have to use KVM internals like kvm_get_vttbr() and kvm_has_mte(). I think those are the only ones at the moment.

Quoted 3 lines

If there is a need to deal with a different value for HCR_EL2 (or anything else), it can be done in the code that makes use of it, rather than being in the KVM code.

Makes sense

Thanks,
Jean

#31 lore raw

RFC PATCH v2 12/15 vfio: Support VFIO devices that access the CPU MMU

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Support devices that are attached to a CPU and perform DMA through a MMU. They do not have an IOMMU and do not use a VFIO container. The VMM needs device-specific knowledge in order to create a virtual device (device tree, ACPI tables), so it also knows not to allocate a container.

---
 drivers/vfio/group.c     | 37 +++++++++++++++++++++++++++++--------
 drivers/vfio/vfio.h      |  5 +++++
 drivers/vfio/vfio_main.c | 16 +++++++++++++++-
 include/linux/vfio.h     |  1 +
 4 files changed, 50 insertions(+), 9 deletions(-)
drivers/vfio/group.c +29 -8
index b2299e5bc6df..99d85880a41c 100644
@@ -120,7 +120,7 @@ static int vfio_group_ioctl_set_container(struct vfio_group *group,
 		return -EBADF;
 
 	mutex_lock(&group->group_lock);
-	if (vfio_group_has_iommu(group)) {
+	if (vfio_group_has_iommu(group) || group->type == VFIO_CPU_MMU) {
 		ret = -EINVAL;
 		goto out_unlock;
 	}
@@ -173,7 +173,8 @@ static int vfio_df_group_open(struct vfio_device_file *df)
 	int ret;
 
 	mutex_lock(&device->group->group_lock);
-	if (!vfio_group_has_iommu(device->group)) {
+	if (!vfio_group_has_iommu(device->group) &&
+	    device->group->type != VFIO_CPU_MMU) {
 		ret = -EINVAL;
 		goto out_unlock;
 	}
@@ -635,7 +636,8 @@ static bool vfio_group_has_device(struct vfio_group *group, struct device *dev)
 	return false;
 }
 
-static struct vfio_group *vfio_group_find_or_alloc(struct device *dev)
+static struct vfio_group *vfio_group_find_or_alloc(struct device *dev,
+						   enum vfio_group_type type)
 {
 	struct iommu_group *iommu_group;
 	struct vfio_group *group;
@@ -662,12 +664,13 @@ static struct vfio_group *vfio_group_find_or_alloc(struct device *dev)
 	mutex_lock(&vfio.group_lock);
 	group = vfio_group_find_from_iommu(iommu_group);
 	if (group) {
-		if (WARN_ON(vfio_group_has_device(group, dev)))
+		if (WARN_ON(vfio_group_has_device(group, dev)) ||
+		    WARN_ON(group->type != type))
 			group = ERR_PTR(-EINVAL);
 		else
 			refcount_inc(&group->drivers);
 	} else {
-		group = vfio_create_group(iommu_group, VFIO_IOMMU);
+		group = vfio_create_group(iommu_group, type);
 	}
 	mutex_unlock(&vfio.group_lock);
 
@@ -681,10 +684,18 @@ int vfio_device_set_group(struct vfio_device *device,
 {
 	struct vfio_group *group;
 
-	if (type == VFIO_IOMMU)
-		group = vfio_group_find_or_alloc(device->dev);
-	else
+	switch (type) {
+	case VFIO_IOMMU:
+	case VFIO_CPU_MMU:
+		group = vfio_group_find_or_alloc(device->dev, type);
+		break;
+	case VFIO_EMULATED_IOMMU:
+	case VFIO_NO_IOMMU:
 		group = vfio_noiommu_group_alloc(device->dev, type);
+		break;
+	default:
+		group = ERR_PTR(-EINVAL);
+	}
 
 	if (IS_ERR(group))
 		return PTR_ERR(group);
@@ -761,6 +772,11 @@ int vfio_device_group_use_iommu(struct vfio_device *device)
 
 	lockdep_assert_held(&group->group_lock);
 
+	if (group->type == VFIO_CPU_MMU) {
+		get_file(group->opened_file);
+		return 0;
+	}
+
 	if (WARN_ON(!group->container))
 		return -EINVAL;
 
@@ -777,6 +793,11 @@ void vfio_device_group_unuse_iommu(struct vfio_device *device)
 
 	lockdep_assert_held(&group->group_lock);
 
+	if (group->type == VFIO_CPU_MMU) {
+		fput(group->opened_file);
+		return;
+	}
+
 	if (WARN_ON(!group->container))
 		return;
 
drivers/vfio/vfio.h +5 -0
index 7728bc99b63d..07c5223612d3 100644
@@ -64,6 +64,11 @@ enum vfio_group_type {
 	 * taint the kernel.
 	 */
 	VFIO_NO_IOMMU,
+
+	/*
+	 * Physical devices using the CPU MMU
+	 */
+	VFIO_CPU_MMU,
 };
 
 #if IS_ENABLED(CONFIG_VFIO_GROUP)
drivers/vfio/vfio_main.c +15 -1
index 423ead48aafe..41fee81a14cb 100644
@@ -344,7 +344,8 @@ static int __vfio_register_dev(struct vfio_device *device,
 {
 	int ret;
 
-	if (WARN_ON(IS_ENABLED(CONFIG_IOMMUFD) &&
+	if (type != VFIO_CPU_MMU &&
+	    WARN_ON(IS_ENABLED(CONFIG_IOMMUFD) &&
 		    (!device->ops->bind_iommufd ||
 		     !device->ops->unbind_iommufd ||
 		     !device->ops->attach_ioas ||
@@ -415,6 +416,19 @@ int vfio_register_emulated_iommu_dev(struct vfio_device *device)
 }
 EXPORT_SYMBOL_GPL(vfio_register_emulated_iommu_dev);
 
+/*
+ * Register a devices that accesses memory through the CPU MMU. Although it
+ * doesn't use an IOMMU, the device must have an IOMMU group.
+ */
+int vfio_register_cpu_mmu_dev(struct vfio_device *device)
+{
+	if (!IS_ENABLED(CONFIG_VFIO_GROUP))
+		return -EOPNOTSUPP;
+
+	return __vfio_register_dev(device, VFIO_CPU_MMU);
+}
+EXPORT_SYMBOL_GPL(vfio_register_cpu_mmu_dev);
+
 /*
  * Decrement the device reference count and wait for the device to be
  * removed.  Open file descriptors for the device... */
include/linux/vfio.h +1 -0
index 45f08986359e..7d3a5ff1ad00 100644
@@ -337,6 +337,7 @@ static inline void vfio_put_device(struct vfio_device *device)
 	put_device(&device->device);
 }
 
+int vfio_register_cpu_mmu_dev(struct vfio_device *device);
 int vfio_register_group_dev(struct vfio_device *device);
 int vfio_register_emulated_iommu_dev(struct vfio_device *device);
 void vfio_unregister_group_dev(struct vfio_device *device);
Signature · 1 line
2.43.0
#32 lore raw

Re: [RFC PATCH v2 12/15] vfio: Support VFIO devices that access the CPU MMU

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] vfio: NULL pointer dereference in vfio_df_iommufd_bind() via cdev ioctl - [High] vfio: NULL…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] vfio: NULL pointer dereference in vfio_df_iommufd_bind() via cdev ioctl
- [High] vfio: NULL pointer deref when binding IOMMUFD to CPU_MMU cdev
--

commit 147c0e7516a85b91b63d3c3d8f78088a9ca5c65f
Author: Jean-Philippe Brucker <[email protected]>

vfio: Support VFIO devices that access the CPU MMU

Support devices that are attached to a CPU and perform DMA through a MMU without an IOMMU or VFIO container. The VMM uses device-specific knowledge to handle virtual device creation.

Quoted 14 lines
drivers/vfio/vfio_main.c +2 -1
index 423ead48aafe3..41fee81a14cbb 100644
@@ -344,7 +344,8 @@ static int __vfio_register_dev(struct vfio_device *device,
 {
 	int ret;
 
-	if (WARN_ON(IS_ENABLED(CONFIG_IOMMUFD) &&
+	if (type != VFIO_CPU_MMU &&
+	    WARN_ON(IS_ENABLED(CONFIG_IOMMUFD) &&
 		    (!device->ops->bind_iommufd ||
 		     !device->ops->unbind_iommufd ||
 		     !device->ops->attach_ioas ||

drivers/vfio/vfio_main.c

Quoted 2 lines
drivers/vfio/vfio_main.c +0 -0
 		     !device->ops->detach_ioas)))
 		return -EINVAL;

[Severity: High]
Could this bypass lead to a NULL pointer dereference for users of the character device interface?

When CONFIG_VFIO_DEVICE_CDEV is enabled, vfio_device_add() automatically creates a character device node (e.g., /dev/vfio/devices/vfioX) for the registered device. If an untrusted user opens this cdev file and invokes the VFIO_DEVICE_BIND_IOMMUFD ioctl, the request routes through the following path:

vfio_df_ioctl_bind_iommufd()
vfio_df_open()
vfio_df_device_first_open()
vfio_df_iommufd_bind()

Inside vfio_df_iommufd_bind() in drivers/vfio/iommufd.c, the code unconditionally executes:

return vdev->ops->bind_iommufd(vdev, ictx, &df->devid);

Since the updated check permits VFIO_CPU_MMU devices to be registered without providing a bind_iommufd callback, this would result in an immediate NULL pointer dereference.

Similarly, calling the VFIO_DEVICE_ATTACH_IOMMUFD_PT ioctl on the cdev unconditionally dereferences the attach_ioas pointer in vfio_df_ioctl_attach_pt(), which would also crash the kernel.

Should there be explicit checks in the cdev ioctl handlers to return -EOPNOTSUPP for devices lacking these callbacks, or should VFIO_CPU_MMU devices perhaps be excluded from cdev creation entirely?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#33 lore raw

Re: [RFC PATCH v2 12/15] vfio: Support VFIO devices that access the CPU MMU

In reply to Ryan Roberts
Quoted 7 lines · Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Support devices that are attached to a CPU and perform DMA through a MMU. They do not have an IOMMU and do not use a VFIO container. The VMM needs device-specific knowledge in order to create a virtual device (device tree, ACPI tables), so it also knows not to allocate a container.

I'm not so excited to see new things built on top of the group interface.

Maybe in this case you just don't have to do a bind operation on the cdev to an iommufd? That feels kind of natural if you don't use a iommufd

However.. you still have to affirm which single mm is the mm that the device is going to be doing DMA against. The process the opens the fd should not be forced to be the mm that it gets linked to.

From that perspective maybe you should create an iommufd and a special "SVA" IOAS that it can attach to. This is more complicated but it makes the mm linkage and blocking beahvior explicit and controlled by userspace.

Jason

#34 lore raw

Re: [RFC PATCH v2 12/15] vfio: Support VFIO devices that access the CPU MMU

Hi Jason,

Quoted 9 lines · Jason Gunthorpe
Quoted 7 lines · Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Support devices that are attached to a CPU and perform DMA through a MMU. They do not have an IOMMU and do not use a VFIO container. The VMM needs device-specific knowledge in order to create a virtual device (device tree, ACPI tables), so it also knows not to allocate a container.

Quoted 6 lines

I'm not so excited to see new things built on top of the group interface.

Maybe in this case you just don't have to do a bind operation on the cdev to an iommufd? That feels kind of natural if you don't use a iommufd

Yes, that makes sense. I don't know enough to know what actually needs to change to make this work, but will look in this direction.

Quoted 4 lines

However.. you still have to affirm which single mm is the mm that the device is going to be doing DMA against. The process the opens the fd should not be forced to be the mm that it gets linked to.

What is the mm representing here? Ultimately we want to install the KVM instance's stage2 pgtables and (pinned) VMID. We currently get that via the bound KVM instance (which looks like it still works using the cdev interface?)

The guest will then install the stage1 pgtables and (pinned) ASID associated with the relevant (guest) mm_struct.

Do we _need_ an mm association in the host?

Thanks,
Ryan

Quoted 7 lines

From that perspective maybe you should create an iommufd and a special "SVA" IOAS that it can attach to. This is more complicated but it makes the mm linkage and blocking beahvior explicit and controlled by userspace.

Jason

#35 lore raw

Re: [RFC PATCH v2 12/15] vfio: Support VFIO devices that access the CPU MMU

Quoted 4 lines · Ryan Roberts
Quoted 3 lines

However.. you still have to affirm which single mm is the mm that the device is going to be doing DMA against. The process the opens the fd should not be forced to be the mm that it gets linked to.

Quoted 8 lines

What is the mm representing here? Ultimately we want to install the KVM instance's stage2 pgtables and (pinned) VMID. We currently get that via the bound KVM instance (which looks like it still works using the cdev interface?)

The guest will then install the stage1 pgtables and (pinned) ASID associated with the relevant (guest) mm_struct.

Do we _need_ an mm association in the host?

Ah.. I see, I didn't quite follow that. OK.. Ah everyone else doing this is using iommufd with a viommu to establish their connection between device an KVM. eg Jacob Pan's series. That's a probably a better idea to stay aligned with the common path. Though your reasons are a little different..

If you manage to get pinned VMID out of KVM then we can implement SMMU BTM as well!

Jason

#36 lore raw

Re: [RFC PATCH v2 12/15] vfio: Support VFIO devices that access the CPU MMU

Quoted 12 lines · Jason Gunthorpe
Quoted 11 lines · Ryan Roberts
Quoted 3 lines

However.. you still have to affirm which single mm is the mm that the device is going to be doing DMA against. The process the opens the fd should not be forced to be the mm that it gets linked to.

What is the mm representing here? Ultimately we want to install the KVM instance's stage2 pgtables and (pinned) VMID. We currently get that via the bound KVM instance (which looks like it still works using the cdev interface?)

The guest will then install the stage1 pgtables and (pinned) ASID associated with the relevant (guest) mm_struct.

Quoted 7 lines
Quoted 1 line

Do we _need_ an mm association in the host?

Ah.. I see, I didn't quite follow that. OK.. Ah everyone else doing this is using iommufd with a viommu to establish their connection between device an KVM. eg Jacob Pan's series. That's a probably a better idea to stay aligned with the common path. Though your reasons are a little different..

Just to check, you're referring to [1]?

I was under the impression that I could open the VFIO device through the cdev interface, then bind it to the KVM instance via KVM_DEV_VFIO_FILE_ADD... Why do I need an iommufd at all?

[1]
https://lore.kernel.org/all/[email protected]/#t

Thanks,
Ryan

Quoted 5 lines

If you manage to get pinned VMID out of KVM then we can implement SMMU BTM as well!

Jason

maintainer
#37 lore raw

Re: [RFC PATCH v2 12/15] vfio: Support VFIO devices that access the CPU MMU

Quoted 21 lines · On Tue, 20 Oct 2026 16:06:37 +0100 Ryan Roberts <[email protected]> wrote:
Quoted 12 lines · Jason Gunthorpe
Quoted 11 lines · Ryan Roberts
Quoted 3 lines

However.. you still have to affirm which single mm is the mm that the device is going to be doing DMA against. The process the opens the fd should not be forced to be the mm that it gets linked to.

What is the mm representing here? Ultimately we want to install the KVM instance's stage2 pgtables and (pinned) VMID. We currently get that via the bound KVM instance (which looks like it still works using the cdev interface?)

The guest will then install the stage1 pgtables and (pinned) ASID associated with the relevant (guest) mm_struct.

Quoted 7 lines
Quoted 1 line

Do we _need_ an mm association in the host?

Ah.. I see, I didn't quite follow that. OK.. Ah everyone else doing this is using iommufd with a viommu to establish their connection between device an KVM. eg Jacob Pan's series. That's a probably a better idea to stay aligned with the common path. Though your reasons are a little different..

Quoted 5 lines

Just to check, you're referring to [1]?

I was under the impression that I could open the VFIO device through the cdev interface, then bind it to the KVM instance via KVM_DEV_VFIO_FILE_ADD... Why do I need an iommufd at all?

The cdev is not unlocked to actually access the device until it's bound to iommufd. Thanks,

Alex

#38 lore raw

Re: [RFC PATCH v2 12/15] vfio: Support VFIO devices that access the CPU MMU

Quoted 24 lines · Alex Williamson
Quoted 21 lines · On Tue, 20 Oct 2026 16:06:37 +0100 Ryan Roberts <[email protected]> wrote:
Quoted 19 lines · Jason Gunthorpe
Quoted 4 lines · Ryan Roberts
Quoted 3 lines

However.. you still have to affirm which single mm is the mm that the device is going to be doing DMA against. The process the opens the fd should not be forced to be the mm that it gets linked to.

Quoted 8 lines

What is the mm representing here? Ultimately we want to install the KVM instance's stage2 pgtables and (pinned) VMID. We currently get that via the bound KVM instance (which looks like it still works using the cdev interface?)

The guest will then install the stage1 pgtables and (pinned) ASID associated with the relevant (guest) mm_struct.

Do we _need_ an mm association in the host?

Ah.. I see, I didn't quite follow that. OK.. Ah everyone else doing this is using iommufd with a viommu to establish their connection between device an KVM. eg Jacob Pan's series. That's a probably a better idea to stay aligned with the common path. Though your reasons are a little different..

Quoted 8 lines
Quoted 5 lines

Just to check, you're referring to [1]?

I was under the impression that I could open the VFIO device through the cdev interface, then bind it to the KVM instance via KVM_DEV_VFIO_FILE_ADD... Why do I need an iommufd at all?

The cdev is not unlocked to actually access the device until it's bound to iommufd. Thanks,

Ahh - got it! Thanks!

Quoted 2 lines

Alex

#39 lore raw

RFC PATCH v2 13/15 misc/arm-cla: Add stage-2 MTC and VM context switch

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Add functions to switch the guest MTC. Reset the accelerators and CLA registers on switch. No save/restore of accelerators at the moment, we only restore the kernel's PL0CTL.

---
 drivers/misc/arm-cla/arm-cla-regs.h |  12 ++
 drivers/misc/arm-cla/arm-cla.h      |  41 ++++++-
 drivers/misc/arm-cla/cla-ctx.c      |  55 +++++++++-
 drivers/misc/arm-cla/cla-mtc.c      | 163 +++++++++++++++++++++++++---
 drivers/misc/arm-cla/cla-regs.c     |  63 ++++++++++-
 drivers/misc/arm-cla/cla-sched.c    |   5 +-
 6 files changed, 308 insertions(+), 31 deletions(-)
drivers/misc/arm-cla/arm-cla-regs.h +12 -0
index 167e9ab64051..a7fc19f67893 100644
@@ -37,6 +37,18 @@
 #define CLA_PLxCTRL_DBGPERM		GENMASK(3, 1)
 #define CLA_PLxCTRL_PREP(accid, v)	((u64)(v) << (8 * (accid)))
 
+/* Valid bits of PLxCTRL. Other bits are RAZ/WI */
+#define _CLA_PLxCTRL_MASK (CLA_PLxCTRL_AVAIL | CLA_PLxCTRL_DBGPERM)
+#define CLA_PLxCTRL_MASK  \
+	(CLA_PLxCTRL_PREP(0, _CLA_PLxCTRL_MASK) | \
+	 CLA_PLxCTRL_PREP(1, _CLA_PLxCTRL_MASK) | \
+	 CLA_PLxCTRL_PREP(2, _CLA_PLxCTRL_MASK) | \
+	 CLA_PLxCTRL_PREP(3, _CLA_PLxCTRL_MASK) | \
+	 CLA_PLxCTRL_PREP(4, _CLA_PLxCTRL_MASK) | \
+	 CLA_PLxCTRL_PREP(5, _CLA_PLxCTRL_MASK) | \
+	 CLA_PLxCTRL_PREP(6, _CLA_PLxCTRL_MASK) | \
+	 CLA_PLxCTRL_PREP(7, _CLA_PLxCTRL_MASK))
+
 #define CLA_STATUS_AVAIL		BIT(0)
 #define CLA_STATUS_DMB			BIT(1)
 #define CLA_STATUS_EABORT		BIT(2)
drivers/misc/arm-cla/arm-cla.h +38 -3

81 lines not on this page · raw message

drivers/misc/arm-cla/cla-ctx.c +49 -6

84 lines not on this page · raw message

drivers/misc/arm-cla/cla-mtc.c +146 -17

234 lines not on this page · raw message

drivers/misc/arm-cla/cla-regs.c +60 -3

99 lines not on this page · raw message

drivers/misc/arm-cla/cla-sched.c +3 -2
index 6b5b782ac33e..dc0584d681af 100644
@@ -196,9 +196,10 @@ static void cla_domain_zap(struct cla_domain *domain, struct cla_ctx *ctx)
 
 	/*
 	 * If the context is dying it has already been unmapped, no need to zap
-	 * it here.
+	 * it here. PL1 contexts are not bound to a specific mm, but since
+	 * deassigning them requires unmapping them first, they must be dying.
 	 */
-	if (!ctx || cla_ctx_is_dying(ctx))
+	if (!ctx || cla_ctx_is_dying(ctx) || WARN_ON(!cla_ctx_is_pl0(ctx)))
 		return;
 
 	if (!mmget_not_zero(ctx->key.mm))
Signature · 1 line
2.43.0
#40 lore raw

Re: [RFC PATCH v2 13/15] misc/arm-cla: Add stage-2 MTC and VM context switch

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] kvm: use-after-free and refcount underflow in cla_ctx_create() - [Medium] arm-cla: late validation…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] kvm: use-after-free and refcount underflow in cla_ctx_create()
- [Medium] arm-cla: late validation of VHE mode breaks device domain
--

commit fd14d79171a8956e71dc07a1dfa6797aaef533a8
Author: Jean-Philippe Brucker <[email protected]>

misc/arm-cla: Add stage-2 MTC and VM context switch

Add functions to switch the guest MTC. Reset the accelerators and CLA registers on switch. No save/restore of accelerators at the moment, we only restore the kernel's PL0CTL.

Quoted 3 lines
drivers/misc/arm-cla/cla-ctx.c +0 -0

[ ... ]

drivers/misc/arm-cla/cla-ctx.c struct cla_ctx *cla_ctx_create(struct cla_domain *domain, · line 87

Quoted 12 lines
drivers/misc/arm-cla/cla-ctx.c +6 -2
@@ -48,8 +79,12 @@ struct cla_ctx *cla_ctx_create(struct cla_domain *domain,
 	INIT_LIST_HEAD(&ctx->queue_node);
 	init_waitqueue_head(&ctx->waitq);
 
-	mmgrab(key->mm);
-	get_file(key->file);
+	if (cla_ctx_is_pl0(ctx)) {
+		mmgrab(key->mm);
+		get_file(key->file);
+	} else {
+		WARN_ON(!cla_ctx_get_pl1(ctx));
+	}

[Severity: High]
If cla_ctx_get_pl1() fails and returns false (for example, if the KVM instance is dying and its refcount is zero), does execution continue here with an unreferenced and potentially freed kvm pointer?

If so, this unreferenced pointer is later passed to cla_mtc_get_ctx() and then cla_mtc_get_s2_ctx(), which calls kvm_arch_get_guest_mmu(). That function dereferences the invalid pointer when acquiring the config_lock:

arch/arm64/kvm/mmu.c:kvm_arch_get_guest_mmu() {
        ...
        guard(mutex)(&kvm->arch.config_lock);
        ...
}

Could this lead to a use-after-free? Furthermore, if execution reaches the err_free error path, cla_ctx_put_pl1() is called unconditionally, which calls kvm_put_kvm() and could cause a refcount underflow. Should this path return an error immediately if the KVM reference cannot be acquired?

Quoted 3 lines
drivers/misc/arm-cla/cla-mtc.c +0 -0

[ ... ]

drivers/misc/arm-cla/cla-mtc.c static int cla_mtc_uninstall_s1(struct cla_dev *dev) · line 214

Quoted 11 lines
drivers/misc/arm-cla/cla-mtc.c +7 -0
@@ -137,6 +205,49 @@ static int cla_mtc_uninstall_s1(struct cla_dev *dev)
 	return cla_op_setctx(dev, cla_kernel_mtc + CLA_MTC_TTBR0, 1, &ttbr0);
 }
 
+static int cla_mtc_install_s2(struct cla_dev *dev, struct cla_ctx *ctx)
+{
+	struct cla_mtc_s2 s2 = {};
+	const size_t num_regs = sizeof(s2) / sizeof(u64);
+
+	if (WARN_ON(cla_kernel_pl != 2))
+		return -EINVAL;

[Severity: Medium]
Because this validation occurs during the context switch path (called by the scheduler), is it too late to gracefully reject an unsupported VM configuration?

If this WARN_ON is hit after the PL1 context has already been created and queued, returning an error during the context switch might cause the hardware domain to be permanently marked as broken and leak resources. Would it be safer to perform this capability check upfront during context creation, for example in cla_mtc_get_s2_ctx()?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#41 lore raw

RFC PATCH v2 14/15 misc/arm-cla: Support exclusive context assignment

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Introduce a nr_contexts members to cla_domain to count the mapped contexts. At the moment PL0 contexts share the domain, while PL1 contexts require exclusive assignment, since there is no context save/restore. A negative count indicates the domain is exclusive.

---
 drivers/misc/arm-cla/arm-cla.h |  2 ++
 drivers/misc/arm-cla/cla-ctx.c | 44 ++++++++++++++++++++++++++++++++--
 2 files changed, 44 insertions(+), 2 deletions(-)
drivers/misc/arm-cla/arm-cla.h +2 -0
index c9ecab5ab6bf..43a58a329525 100644
@@ -105,6 +105,7 @@ struct cla_dev {
  * @lock:		Protects the following members.
  * @ctxs:		All live contexts, keyed on cla_ctx_key.
  * @queued_ctxs:	Queue of contexts waiting for assignment.
+ * @nr_ctxs:		Context count. Negative value for exclusive assignment.
  * @worker:		Kthread worker to coordinate reassignment.
  * @reassign:		Delayed work that switches contexts with time slicing.
  *
@@ -120,6 +121,7 @@ struct cla_domain {
 
 	struct mutex lock;
 	bool broken;
+	long nr_ctxs;
 	struct rhashtable ctxs;
 	struct list_head queued_ctxs;
 	struct cla_ctx *assigned_ctx;
drivers/misc/arm-cla/cla-ctx.c +42 -2

76 lines not on this page · raw message

Signature · 1 line
2.43.0
#42 lore raw

Re: [RFC PATCH v2 14/15] misc/arm-cla: Support exclusive context assignment

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] cla: missing KVM refcount failure handling causes UAF --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] cla: missing KVM refcount failure handling causes UAF
--

commit 2dbcc26b5b7fa32dbb9707b12991d8ab79134d92
Author: Jean-Philippe Brucker <[email protected]>

misc/arm-cla: Support exclusive context assignment

This commit introduces a nr_contexts member to cla_domain to track mapped contexts. It allows PL0 contexts to share the domain while enforcing exclusive assignment for PL1 contexts by using a negative count.

Quoted 4 lines
drivers/misc/arm-cla/cla-ctx.c +0 -0
index 0489bf7a103f9..f956cc88909f8 100644

[ ... ]

drivers/misc/arm-cla/cla-ctx.c struct cla_ctx *cla_ctx_create(struct cla_domain *domain, · line 160

Quoted 9 lines
drivers/misc/arm-cla/cla-ctx.c +2 -0
@@ -116,6 +153,8 @@ struct cla_ctx *cla_ctx_create(struct cla_domain *domain,
 		cla_ctx_put_pl1(ctx);
 	}
 	kfree(ctx);
+err_put_domain:
+	cla_domain_put(domain);
 err_unlock:
 	mutex_unlock(&domain->lock);
 	return ERR_PTR(ret);

[Severity: High]
Earlier in cla_ctx_create(), if cla_ctx_get_pl1() fails to acquire a reference to KVM (e.g., if the VM is being torn down concurrently and its refcount is already zero), the failure is ignored:

	} else {
		WARN_ON(!cla_ctx_get_pl1(ctx));
	}

The context creation continues with a potentially freed KVM pointer. If an error occurs later in the function (such as cla_mtc_get_ctx() failing) and we take the err_free path, or when the context is eventually destroyed, cla_ctx_put_pl1() is unconditionally called.

Does this cause a use-after-free and a refcount underflow of the kvm object, since the reference was never actually acquired?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#43 lore raw

RFC PATCH v2 15/15 misc/arm-cla: Add vfio-mdev user interface

In reply to Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Implement an interface to assign CLA devices to KVM guests. To creates a CLA instance:

    uuid=$(uuidgen)
    echo $uuid > /sys/class/mdev_bus/<pdev>/mdev_supported_types/arm-cla-pl1/create
    cla_cpu=$(< /sys/bus/mdev/devices/$uuid/cpu)

This creates a user interface in /dev/vfio: a VFIO group in /dev/vfio/<n>, discoverable by reading the symlink /sys/bus/mdev/devices/$uuid/iommu_group. Although CLA does not use an IOMMU, VFIO relies on IOMMU groups as an assignable unit. Here they correspond to CLA domains, whose devices communicate through a private bus.

The CLA device gets assigned exclusively to the first VMM that opens the VFIO group and device. To launch a VM with a CLA attached to vCPU #4, with kvmtool:

lkvm run -k Image --console virtio -c 8
--vfio-platform $uuid,type=arm-cla,vcpu=4
--vcpu-affinity 4=$cla_cpu # Bind vCPU 4 to the CLA's CPU

Opens the group, gets the device fd, mmaps the frame, and launches the guest. The given vCPU thread is pinned to the CLA's CPU.

Pinning vCPUs is not guaranteed. If the host decides to power off the CPUs with assigned CLAs, the guest application can't access the assigned device anymore. It would now access a RAZ/WI memory region.

For DMA, because the TLB entries tagged with VMID+ASID are shared between CPU and accelerator, we pin the VMID. The stage 2 page tables are shared between CPU and CLA. CLA reports DMA page faults directly to the user, who performs the access from the CPU to handle both stage 1 and stage 2 faults.

---
 drivers/misc/arm-cla/Kconfig        |  16 +
 drivers/misc/arm-cla/Makefile       |   2 +
 drivers/misc/arm-cla/arm-cla.h      |  48 +++
 drivers/misc/arm-cla/cla-init.c     |  11 +-
 drivers/misc/arm-cla/cla-mdev.c     | 469 ++++++++++++++++++++++++++++
 drivers/misc/arm-cla/cla-topology.c |   9 +-
 6 files changed, 553 insertions(+), 2 deletions(-)
 create mode 100644 drivers/misc/arm-cla/cla-mdev.c
drivers/misc/arm-cla/Kconfig +16 -0
index f8436a12c1e6..5def727b7a34 100644
@@ -8,3 +8,19 @@ config ARM_CLA
 	  accelerators. It is only accessible from its associated CPU.
 
 	  If unsure, say N.
+
+config ARM_CLA_MDEV
+	bool "Mediated device for Arm CLA"
+	default y
+	depends on KVM
+	depends on VFIO
+	depends on ARM_CLA
+	depends on VFIO_GROUP
+	select VFIO_MDEV
+	help
+	  Enable the VFIO mediated device interface for assigning Arm Core Local
+	  Accelerators (CLAs) to KVM guests. Guests can access the CLA PL0 and
+	  PL1 registers, while the host controls stage 2 address translation.
+	  Devices in the same CLA domain can only be assigned to the same guest.
+
+	  If unsure, say N.
drivers/misc/arm-cla/Makefile +2 -0
index f848c608e8f1..973390d0b428 100644
@@ -11,3 +11,5 @@ arm-cla-y := \
 	cla-user.o
 
 obj-$(CONFIG_ARM_CLA) += arm-cla.o
+
+arm-cla-$(CONFIG_ARM_CLA_MDEV) += cla-mdev.o
drivers/misc/arm-cla/arm-cla.h +48 -0

94 lines not on this page · raw message

drivers/misc/arm-cla/cla-init.c +10 -1
index 1afe20aa877f..a0067240809a 100644
@@ -393,6 +393,7 @@ static struct cla_dev *cla_dev_alloc(struct device *parent, int cpu,
 	dev->regs = cla_get_regs(regs, cla_kernel_pl);
 	dev->cpu = cpu;
 	dev->dev = parent;
+	dev_set_drvdata(parent, dev);
 
 	kthread_init_work(&dev->call.switch_ctx, cla_dev_switch_ctx_work);
 
@@ -519,13 +520,20 @@ static int __init cla_module_init(void)
 		cla_cpuhp_state = ret;
 	}
 
+	ret = cla_mdev_init();
+	if (ret)
+		goto err_hardware;
+
 	/* Must be last fallible step; see cla_user_init(). */
 	ret = cla_user_init();
 	if (ret)
-		goto err_hardware;
+		goto err_mdev_exit;
 
+	cla_mdev_enable();
 	return 0;
 
+err_mdev_exit:
+	cla_mdev_exit();
 err_hardware:
 	cla_domains_sched_exit();
 	if (cla_cpuhp_state >= 0)
@@ -539,6 +547,7 @@ static int __init cla_module_init(void)
 static void __exit cla_module_exit(void)
 {
 	cla_user_exit();
+	cla_mdev_exit();
 	cla_domains_sched_exit();
 	cpuhp_remove_state(cla_cpuhp_state);
 	cla_domains_free();
drivers/misc/arm-cla/cla-mdev.c new file +469 -0

469 lines not on this page · raw message

drivers/misc/arm-cla/cla-topology.c +8 -1
index ed7acec70019..ead6c25c6391 100644
@@ -51,12 +51,18 @@ static struct cla_domain *cla_domain_alloc(struct cla_dev *dev, unsigned int fwi
 	}
 	domain->devs[0] = dev;
 
-	ret = cla_domain_sched_init(domain);
+	ret = cla_domain_mdev_init(domain);
 	if (ret)
 		goto err_free_devs;
 
+	ret = cla_domain_sched_init(domain);
+	if (ret)
+		goto err_exit_mdev;
+
 	return domain;
 
+err_exit_mdev:
+	cla_domain_mdev_exit(domain);
 err_free_devs:
 	kfree(domain->devs);
 err_free_id:
@@ -187,6 +193,7 @@ void cla_domains_free(void)
 	cla_lut_cpu = NULL;
 	cla_lut_pg = NULL;
 	xa_for_each(&cla_domains, fwid, domain) {
+		cla_domain_mdev_exit(domain);
 		xa_erase(&cla_domains, fwid);
 		kfree(domain->devs);
 		kfree(domain);
Signature · 1 line
2.43.0
#44 lore raw

Re: [RFC PATCH v2 15/15] misc/arm-cla: Add vfio-mdev user interface

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] sysfs: NULL pointer dereference in cpu_show() during mdev probe - [Low] kconfig: ARM_CLA_MDEV…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] sysfs: NULL pointer dereference in cpu_show() during mdev probe
- [Low] kconfig: ARM_CLA_MDEV linkage error when VFIO or KVM are modules
- [Low] char: cla_mdev_ioctl() returns -EINVAL instead of -ENOTTY for unknown ioctls --

commit dd12438e45e5acb03e5d810526fd148e9b134169
Author: Jean-Philippe Brucker <[email protected]>

misc/arm-cla: Add vfio-mdev user interface

This commit implements an interface to assign CLA devices to KVM guests using the VFIO mediated device framework. It sets up the stage-2 MTC for the assigned VMs and exposes a sysfs interface for device discovery.

Quoted 5 lines
drivers/misc/arm-cla/Kconfig +0 -0
index f8436a12c1e64..5def727b7a342 100644

drivers/misc/arm-cla/Kconfig config ARM_CLA · line 16

Quoted 9 lines
drivers/misc/arm-cla/Kconfig +6 -0
@@ -8,3 +8,19 @@ config ARM_CLA
 	  accelerators. It is only accessible from its associated CPU.
 
 	  If unsure, say N.
+
+config ARM_CLA_MDEV
+	bool "Mediated device for Arm CLA"
+	default y
+	depends on KVM
+	depends on VFIO

[Severity: Low]
Will this cause linker errors if ARM_CLA is built-in but KVM or VFIO are built as modules?

Because ARM_CLA_MDEV is a bool depending on tristate symbols (KVM, VFIO), it evaluates to y even when KVM or VFIO are m. If ARM_CLA=y, cla-mdev.o is compiled into the kernel. Since cla-mdev.c references module symbols from vfio and kvm, this can result in undefined reference errors during the kernel build.

Should the Kconfig dependencies enforce that if ARM_CLA is built-in, its tristate dependencies must also be built-in?

Quoted 5 lines
drivers/misc/arm-cla/cla-mdev.c new file +0 -0
new file mode 100644
index 0000000000000..66c5dd197542e

[ ... ]

drivers/misc/arm-cla/cla-mdev.c line 34

Quoted 6 lines
drivers/misc/arm-cla/cla-mdev.c new file +6 -0
+static ssize_t cpu_show(struct device *dev, struct device_attribute *attr,
+			char *buf)
+{
+	struct cla_mdev *mdev = dev_get_drvdata(dev);
+
+	return sysfs_emit(buf, "%u\n", mdev->dev->cpu);

[Severity: High]
Can this result in a NULL pointer dereference during device probe?

The cla_mdev_driver defines dev_groups = cla_mdev_sysfs_groups, meaning the sysfs core creates the cpu file before cla_mdev_probe() is called. If userspace reads the newly created file concurrently, cpu_show() executes before the drvdata is set later in cla_mdev_probe():

static int cla_mdev_probe(struct mdev_device *mdev)

{
    ...
    dev_set_drvdata(&mdev->dev, cla_mdev);

This would cause dev_get_drvdata() to return NULL, leading to a crash when accessing mdev->dev->cpu.

[ ... ]

Quoted 10 lines
drivers/misc/arm-cla/cla-mdev.c new file +10 -0
+static long cla_mdev_ioctl(struct vfio_device *vdev, unsigned int cmd,
+			       unsigned long arg)
+{
+	struct cla_mdev *mdev =
+		container_of(vdev, struct cla_mdev, vdev);
+	unsigned long minsz;
+
+	switch (cmd) {
+	case VFIO_DEVICE_GET_INFO:
+	{

[ ... ]

drivers/misc/arm-cla/cla-mdev.c line 240

Quoted 9 lines
drivers/misc/arm-cla/cla-mdev.c new file +9 -0
+	}
+	case VFIO_DEVICE_RESET:
+		return cla_mdev_reset(mdev);
+	case VFIO_DEVICE_GET_IRQ_INFO:
+	case VFIO_DEVICE_SET_IRQS:
+	default:
+		return -EINVAL;
+	}
+	return -ENOTTY;

[Severity: Low]
Does this ioctl handler incorrectly return -EINVAL instead of -ENOTTY for unknown commands?

The default case catches all unknown ioctls and returns -EINVAL, which makes the final return -ENOTTY unreachable. Userspace applications probing for features often rely on -ENOTTY to properly detect unsupported commands. Returning -EINVAL could mislead them into thinking the command is supported but their arguments are invalid.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
#45 lore raw

Re: [RFC PATCH v2 15/15] misc/arm-cla: Add vfio-mdev user interface

In reply to Ryan Roberts
Quoted 8 lines · Ryan Roberts

From: Jean-Philippe Brucker <[email protected]>

Implement an interface to assign CLA devices to KVM guests. To creates a CLA instance:

    uuid=$(uuidgen)
    echo $uuid > /sys/class/mdev_bus/<pdev>/mdev_supported_types/arm-cla-pl1/create
    cla_cpu=$(< /sys/bus/mdev/devices/$uuid/cpu)

I think I said this last time, please don't use vfio mdev for anything. There is nothing mediated about this.

Jason

#46 lore raw

Re: [RFC PATCH v2 15/15] misc/arm-cla: Add vfio-mdev user interface

Quoted 2 lines · Jason Gunthorpe

I think I said this last time, please don't use vfio mdev for anything. There is nothing mediated about this.

We don't multiplex a device between guests, but the host driver must control part of the device registers while the remainder is assigned to a guest. The host configures accelerator access, stage-2 translation, handles CPUHP and context save/restore. So we can't bind the device to vfio-platform.

Thanks,
Jean

#47 lore raw

Re: [RFC PATCH v2 15/15] misc/arm-cla: Add vfio-mdev user interface

Quoted 9 lines · Jean-Philippe Brucker
Quoted 2 lines · Jason Gunthorpe

I think I said this last time, please don't use vfio mdev for anything. There is nothing mediated about this.

We don't multiplex a device between guests, but the host driver must control part of the device registers while the remainder is assigned to a guest. The host configures accelerator access, stage-2 translation, handles CPUHP and context save/restore. So we can't bind the device to vfio-platform.

That's fine, you can make a proper vfio-cla driver.

Jason

#48 lore raw

Re: [RFC PATCH v2 15/15] misc/arm-cla: Add vfio-mdev user interface

Quoted 5 lines · Jason Gunthorpe
Quoted 4 lines · Jean-Philippe Brucker
Quoted 2 lines · Jason Gunthorpe

I think I said this last time, please don't use vfio mdev for anything. There is nothing mediated about this.

Quoted 7 lines
Quoted 5 lines

We don't multiplex a device between guests, but the host driver must control part of the device registers while the remainder is assigned to a guest. The host configures accelerator access, stage-2 translation, handles CPUHP and context save/restore. So we can't bind the device to vfio-platform.

That's fine, you can make a proper vfio-cla driver.

Hi Jason,

Thanks for taking a look at this! I've been chewing on this comment and trying to educate myself deeper on the subject. I have a proposal...

Currently we create a struct device per CLA device instance. But multiple CLA device instances cooperate within a domain and the domain is the "unit of isolation"; we can't have some CLAs from a domain assigned to a VM, while others from the same domain are used by the host. Therefore it didn't feel like the correct model to unbind one of these devices from the native driver and rebind it to a cla-vfio driver. mdev seemed to solve this problem nicely for us.

But looking into it in more detail, I guess something like this might be a bit more standard:

- Split the existing CLA driver into three components:
- cla-core: Hardware discovery, domain configuration, struct device registration and CPU hotplug
- cla-native driver: Provides the user space accelerator interfaces
- cla-vfio driver: Enables domains to be assigned to virtual machines
- Each domain has a struct device (created by the core)
- An individual CLA is not represented by a struct device
- Either cla-native or cla-vfio can then bind to a domain device
- cla-native exposes a char device per domain, per accelerator class
- cla-vfio

For VFIO, I guess we could use one VFIO region per CLA, which would allow the VMM to construct a device tree. But it would need to additionally determine which CPU each CLA is bound to; perhaps that's a sysfs interface that cla-core could expose?

Does this feel like it's going in the right direction?

Thanks,
Ryan

Quoted 2 lines

Jason

#49 lore raw

Re: [RFC PATCH v2 15/15] misc/arm-cla: Add vfio-mdev user interface

Quoted 14 lines · Ryan Roberts
Quoted 5 lines · Jason Gunthorpe
Quoted 4 lines · Jean-Philippe Brucker
Quoted 2 lines · Jason Gunthorpe

I think I said this last time, please don't use vfio mdev for anything. There is nothing mediated about this.

Quoted 7 lines
Quoted 5 lines

We don't multiplex a device between guests, but the host driver must control part of the device registers while the remainder is assigned to a guest. The host configures accelerator access, stage-2 translation, handles CPUHP and context save/restore. So we can't bind the device to vfio-platform.

That's fine, you can make a proper vfio-cla driver.

Quoted 8 lines

Hi Jason,

Thanks for taking a look at this! I've been chewing on this comment and trying to educate myself deeper on the subject. I have a proposal...

Currently we create a struct device per CLA device instance. But multiple CLA device instances cooperate within a domain and the domain is the "unit of isolation";

Well that's weird and a bit confusing.

Quoted 19 lines

we can't have some CLAs from a domain assigned to a VM, while others from the same domain are used by the host. Therefore it didn't feel like the correct model to unbind one of these devices from the native driver and rebind it to a cla-vfio driver. mdev seemed to solve this problem nicely for us.

But looking into it in more detail, I guess something like this might be a bit more standard:

- Split the existing CLA driver into three components:
- cla-core: Hardware discovery, domain configuration, struct device registration and CPU hotplug
- cla-native driver: Provides the user space accelerator interfaces
- cla-vfio driver: Enables domains to be assigned to virtual machines
- Each domain has a struct device (created by the core)
- An individual CLA is not represented by a struct device
- Either cla-native or cla-vfio can then bind to a domain device
- cla-native exposes a char device per domain, per accelerator class
- cla-vfio

Quoted 4 lines

For VFIO, I guess we could use one VFIO region per CLA, which would allow the VMM to construct a device tree. But it would need to additionally determine which CPU each CLA is bound to; perhaps that's a sysfs interface that cla-core could expose?

I don't know alot about your CLA, but this sounds reasonable. There may be uses with containers to have the split exposed like this too.

Jason

#50 lore raw

Re: [RFC PATCH v2 15/15] misc/arm-cla: Add vfio-mdev user interface

Quoted 17 lines · Jason Gunthorpe
Quoted 16 lines · Ryan Roberts
Quoted 5 lines · Jason Gunthorpe
Quoted 4 lines · Jean-Philippe Brucker
Quoted 2 lines · Jason Gunthorpe

I think I said this last time, please don't use vfio mdev for anything. There is nothing mediated about this.

Quoted 7 lines
Quoted 5 lines

We don't multiplex a device between guests, but the host driver must control part of the device registers while the remainder is assigned to a guest. The host configures accelerator access, stage-2 translation, handles CPUHP and context save/restore. So we can't bind the device to vfio-platform.

That's fine, you can make a proper vfio-cla driver.

Hi Jason,

Quoted 8 lines
Quoted 6 lines

Thanks for taking a look at this! I've been chewing on this comment and trying to educate myself deeper on the subject. I have a proposal...

Currently we create a struct device per CLA device instance. But multiple CLA device instances cooperate within a domain and the domain is the "unit of isolation";

Well that's weird and a bit confusing.

Yes; this conversation is helping me to see that... :)

I was originally trying to avoid creating any globally visible entity that describes a "domain", since I thought there was a possibility that each process might want to define it's own view of a domain. But in hindsight I don't think that's helpful...

Quoted 20 lines
Quoted 20 lines

we can't have some CLAs from a domain assigned to a VM, while others from the same domain are used by the host. Therefore it didn't feel like the correct model to unbind one of these devices from the native driver and rebind it to a cla-vfio driver. mdev seemed to solve this problem nicely for us.

But looking into it in more detail, I guess something like this might be a bit more standard:

- Split the existing CLA driver into three components:
- cla-core: Hardware discovery, domain configuration, struct device registration and CPU hotplug
- cla-native driver: Provides the user space accelerator interfaces
- cla-vfio driver: Enables domains to be assigned to virtual machines
- Each domain has a struct device (created by the core)
- An individual CLA is not represented by a struct device
- Either cla-native or cla-vfio can then bind to a domain device
- cla-native exposes a char device per domain, per accelerator class
- cla-vfio

Quoted 7 lines
Quoted 4 lines

For VFIO, I guess we could use one VFIO region per CLA, which would allow the VMM to construct a device tree. But it would need to additionally determine which CPU each CLA is bound to; perhaps that's a sysfs interface that cla-core could expose?

I don't know alot about your CLA, but this sounds reasonable. There may be uses with containers to have the split exposed like this too.

...This all feels much clearer and simpler. I'll work on an approach like this.

Thanks,
Ryan

Quoted 2 lines

Jason

#51 lore raw

v2 cover Arm Core Local Accelerator Driver

In reply to Ryan Roberts

Hi All,

Just a polite bump; now that -rc1 is out, if anyone can spare any time to cast an eye and offer opinions, I'd be grateful. At this point, I'm most interested in feedback on the arm64 integration aspect; If you see blockers I'd like to discuss early.

Thanks,
Ryan

Quoted 147 lines · Ryan Roberts

Hi All,

This is v2 of an RFC to introduce a driver for the Arm Core Local Accelerator (CLA), a CPU-local interface for programming attached accelerators. While the interface is agnostic to the accelerator type, the initial (and currently only) target is a compute engine.

The RFC aims to engage the community and get feedback on some key aspects. This will help plan our approach for eventual upstreaming. Based on feedback from Will and Marc in RFCv1, the driver now supports both bare metal and virtualized environments. I also have commitments to publish the CLA spec, a supporting FVP and a representaive user space, all to support upstreaming the driver, as per Will's feedback.

For now you can find documentation included with patch 1, which describes the HW and driver design. Note that the CLA is not part of the Arm Architecture.

Patch 1 documents the hardware and driver design, and adds a driver skeleton. Patches 2-5 initialize and probe the device. Patches 6-9 add context management for switching the device between different users. Patches 10-12 add some (small) changes to KVM and VFIO, which then enables patches 13-15 to expose the HW for device assignment into a VM.

Aspects I'm seeking feedback for:

* The general structure of the driver: The current shape addresses the performance requirements we have for the use cases, and is therefore our preferred approach. But there are some unusual aspects due to the HW design.

* Driver interaction with architectural support: I've opted to treat the CLA as a device rather than a CPU extension, so it's implemented as a (mostly) self-contained driver. It has some unavoidable coupling to the arch code since it needs to share page tables and ASIDs/VMIDs. All arm64 arch interaction is contained in cla-mtc.c.

* The location of the driver: although most accelerators will likely be compute ones, CLA is a generic MMIO interface that could handle any kind of accelerator. It's currently implemented as a misc driver. accel is another potential option, but given the current SVA approach, we would not use any of the services (memory-management or otherwise) that accel provides.

* Virtualization support: since the HW uses the CPU's MMU, we introduced a new VFIO_CPU_MMU group type, and added the kvm_arch_[get|put]_guest_mmu() API to KVM/arm64 so that the CLA can share the stage2 pgtables and VMID. The CPU pinning problem remains unsolved; the vCPU must be pinned to the pCPU that owns the CLA in order to access it. If the pCPU goes offline or the vCPU is otherwise unpinned, it would look to the guest like the HW is faulty. This issue is therefore contained to the guest. I've additionally improved the robustness of the core driver to deal with this eventuality gracefully.

I consider the core driver to be well tested and robust. The virtualization portion is prototype and has known issues that would be addressed assuming the approach gets positive feedback.

Changes since RFCv1 [1]
=======================

- Added KVM guest support through VFIO mdev, including exclusive domain assignment, stage-2 memory translation and VMID pinning
- Changed the userspace ABI to expose one /dev/cla/<class-id> device per accelerator class; ARM_CLA_PARAM_DEV_ACCELS now reports only accelerators belonging to the opened class (per Arnd)
- Removed ARM_CLA_UABI_VERSION and the ARM_CLA_PARAM_UABI_VERSION query (per Arnd)
- Various driver bug fixes and robustness improvements

Source, along with some tests, is available at [2]. Patches based on v7.3-rc5.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://gitlab.arm.com/linux-arm/linux-rr/-/tree/features/cla-driver-v2-rfc-tests

Thanks,
Ryan

Jean-Philippe Brucker (10):
misc/arm-cla: Add driver skeleton and documentation misc/arm-cla: Add launch operation helpers misc/arm-cla: Probe firmware-described devices misc/arm-cla: Initialize devices on CPU bringup misc/arm-cla: Accelerator context save and restore
KVM: arm64: Export stage-2 MMU config
vfio: Support VFIO devices that access the CPU MMU misc/arm-cla: Add stage-2 MTC and VM context switch misc/arm-cla: Support exclusive context assignment misc/arm-cla: Add vfio-mdev user interface

Ryan Roberts (4):
dt-bindings: misc: Add Arm Core Local Accelerator misc/arm-cla: Set up memory translation context misc/arm-cla: Manage domain contexts misc/arm-cla: Add userspace interface

Shameer Kolothum (1):
KVM: arm64: Introduce support to pin VMIDs

 .../devicetree/bindings/misc/arm,cla.yaml     |  77 +++
 Documentation/misc-devices/arm-cla.rst        | 217 +++++++
 Documentation/misc-devices/index.rst          |   1 +
 MAINTAINERS                                   |   9 +
 arch/arm64/include/asm/kvm_host.h             |  14 +
 arch/arm64/include/asm/kvm_mmu.h              |   1 +
 arch/arm64/kvm/mmu.c                          | 102 ++++
 arch/arm64/kvm/sys_regs.c                     |  14 +-
 arch/arm64/kvm/vmid.c                         |  77 ++-
 drivers/misc/Kconfig                          |   1 +
 drivers/misc/Makefile                         |   1 +
 drivers/misc/arm-cla/Kconfig                  |  26 +
 drivers/misc/arm-cla/Makefile                 |  15 +
 drivers/misc/arm-cla/arm-cla-regs.h           | 192 ++++++
 drivers/misc/arm-cla/arm-cla.h                | 393 ++++++++++++
 drivers/misc/arm-cla/cla-ctx.c                | 229 +++++++
 drivers/misc/arm-cla/cla-init.c               | 562 ++++++++++++++++++
 drivers/misc/arm-cla/cla-mdev.c               | 469 +++++++++++++++
 drivers/misc/arm-cla/cla-mtc.c                | 335 +++++++++++
 drivers/misc/arm-cla/cla-ops.c                | 417 +++++++++++++
 drivers/misc/arm-cla/cla-regs.c               | 370 ++++++++++++
 drivers/misc/arm-cla/cla-sched.c              | 474 +++++++++++++++
 drivers/misc/arm-cla/cla-topology.c           | 202 +++++++
 drivers/misc/arm-cla/cla-user.c               | 541 +++++++++++++++++
 drivers/vfio/group.c                          |  37 +-
 drivers/vfio/vfio.h                           |   5 +
 drivers/vfio/vfio_main.c                      |  16 +-
 include/linux/vfio.h                          |   1 +
 include/uapi/linux/arm-cla.h                  | 198 ++++++
 29 files changed, 4969 insertions(+), 27 deletions(-)
 create mode 100644 Documentation/devicetree/bindings/misc/arm,cla.yaml
 create mode 100644 Documentation/misc-devices/arm-cla.rst
 create mode 100644 drivers/misc/arm-cla/Kconfig
 create mode 100644 drivers/misc/arm-cla/Makefile
 create mode 100644 drivers/misc/arm-cla/arm-cla-regs.h
 create mode 100644 drivers/misc/arm-cla/arm-cla.h
 create mode 100644 drivers/misc/arm-cla/cla-ctx.c
 create mode 100644 drivers/misc/arm-cla/cla-init.c
 create mode 100644 drivers/misc/arm-cla/cla-mdev.c
 create mode 100644 drivers/misc/arm-cla/cla-mtc.c
 create mode 100644 drivers/misc/arm-cla/cla-ops.c
 create mode 100644 drivers/misc/arm-cla/cla-regs.c
 create mode 100644 drivers/misc/arm-cla/cla-sched.c
 create mode 100644 drivers/misc/arm-cla/cla-topology.c
 create mode 100644 drivers/misc/arm-cla/cla-user.c
 create mode 100644 include/uapi/linux/arm-cla.h

--
2.43.0

#52 lore raw
Quoted 6 lines · Ryan Roberts

Hi All,

Just a polite bump; now that -rc1 is out, if anyone can spare any time to cast an eye and offer opinions, I'd be grateful. At this point, I'm most interested in feedback on the arm64 integration aspect; If you see blockers I'd like to discuss early.

We are _drowning_ in real patches right now, RFC ones go to the bottom of the pile. Please work to make this good enough that you feel it is no longer a RFC and submit it that way.

thanks,

greg k-h

#53 lore raw
In reply to Ryan Roberts

Hi Ryan,

please keep me on CC for future series for an SoC perspective on this.

Quoted 5 lines · Ryan Roberts

* The location of the driver: although most accelerators will likely be compute ones, CLA is a generic MMIO interface that could handle any kind of accelerator. It's currently implemented as a misc driver. accel is another potential option, but given the current SVA approach, we would not use any of the services (memory-management or otherwise) that accel provides.

Given the extremely ARM64-specific nature of the accelerator it has a lot to do with arch/arm64 but then again it is a platform device + driver associated with the cores and we don't want platform device drivers under arch/*, so it kind of falls between the chairs.

My spontaneous placement would be to put this in drivers/soc/arm/* what do you think about this option?

The argument would be that this is arm-specific, we do not expect the code to be reused by other archs, and it is used on some specific ARM SoCs, so it goes under drivers/soc/arm.

If a very similar feature arrives on other archs which use very similar code we may have to rethink this but for now I believe this is the best option.

Yours,
Linus Walleij

#54 lore raw
In reply to Ryan Roberts

Hi Ryan,

Quoted 3 lines · Ryan Roberts

* Driver interaction with architectural support: I've opted to treat the CLA as a device rather than a CPU extension, so it's implemented as a (mostly) self-contained driver.

What the current proposal does is to create nodes in the base of the device tree, which makes the device tree parser instantiate those into platform_device:s,
then each cla_device piggy-backs that platform device.

I don't think this is a good idea, I wouldn't use platform_device for this since you can just look up the nodes and instantiate the cla_device:s with a proper struct device inside all of them.

I think it's a better idea to put these inside the CPU nodes themselves, they are there after all, intuitive right? Init code can loop over the CPUs and instantiate a cla_device for each CPU directly without having to detour over an opaque platform_device.

Devices inside CPU nodes will not (I think??) be populated automatically, so you can add code to loop over the CPU nodes at device_initcall level or any time during the boot process deemed helpful. This also saves you from adding devices for CPU cores that are flagged with status = "disabled"; which could happen.

Yours,
Linus Walleij