Skip to contentSkip to conversation

Linux RISC-V IOMMU Support

PATCH Superseded Tomasz Jeznach 5 participants 34 messages Apr 30, 2024 – May 8, 2024

Subsystems (4)

v3 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

v3 cover Linux RISC-V IOMMU Support

This patch series introduces support for RISC-V IOMMU architected hardware into the Linux kernel.

The RISC-V IOMMU specification, which this series is based on, is ratified and available at GitHub/riscv-non-isa [1].

At a high level, the RISC-V IOMMU specification defines:

1) Data structures:
- Device-context: Associates devices with address spaces and holds per-device parameters for address translations.
- Process-contexts: Associates different virtual address spaces based on device-provided process identification numbers.
- MSI page table configuration used to direct an MSI to a guest interrupt file in an IMSIC.
2) In-memory queue interface:
- Command-queue for issuing commands to the IOMMU.
- Fault/event queue for reporting faults and events.
- Page-request queue for reporting "Page Request" messages received from PCIe devices.
- Message-signaled and wire-signaled interrupt mechanisms.
3) Memory-mapped programming interface:
- Mandatory and optional register layout and description.
- Software guidelines for device initialization and capabilities discovery.

This series introduces RISC-V IOMMU hardware initialization and complete single-stage translation with paging domain support.

The patches are organized as follows:

Patch 1: Introduces minimal required device tree bindings for the driver. Patch 2: Defines RISC-V IOMMU data structures, hardware programming interface
registers layout, and minimal initialization code for enabling global pass-through for all connected masters.
Patch 3: Implements the device driver for PCIe implementation of RISC-V IOMMU
architected hardware.
Patch 4: Introduces IOMMU interfaces to the kernel subsystem.
Patch 5: Implements device directory management with discovery sequences for
I/O mapped or in-memory device directory table location, hardware capabilities discovery, and device to domain attach implementation.
Patch 6: Implements command and fault queue, and introduces directory cache
invalidation sequences.
Patch 7: Implements paging domain, with page table using the same format as the
CPU’s MMU. This patch series enables only 4K mappings; complete support for large page mappings will be introduced in follow-up patch series.

Follow-up patch series, providing large page support and updated walk cache management based on the revised specification, and complete ATS/PRI/SVA support, will be posted to GitHub [2].

Changes from v2:
- rebase on top of v6.9-rc6 and applied series for iommu-next:
IOMMU memory observability, v6 [3]
iommu, dma-mapping: Simplify arch_setup_dma_ops(), v4 [4]
- dt-bindings: compatible string
- Kconfig: optional built-in driver; removed module info
- kdump support added, interrupts and binding fixes, pcim_*
- use iommu allocation accounting wrappers
- use new dma-mapping setup, removed probe_finalize
- release domain added, memory allocations moved to domain alloc
- updated domain attach flow, fixes for domain to device bond locking
- fixed alignment check, fixed non-leaf page release
- driver warnings cleaned up

Best regards,
Tomasz Jeznach

[1] link: https://github.com/riscv-non-isa/riscv-iommu
[2] link: https://github.com/tjeznach/linux
[3] link: https://lore.kernel.org/linux-iommu/[email protected]/
[4] link: https://lore.kernel.org/linux-iommu/[email protected]/

v2 link:  https://lore.kernel.org/linux-iommu/[email protected]/
v1 link:  https://lore.kernel.org/linux-iommu/[email protected]/

Tomasz Jeznach (7):
dt-bindings: iommu: riscv: Add bindings for RISC-V IOMMU iommu/riscv: Add RISC-V IOMMU platform device driver iommu/riscv: Add RISC-V IOMMU PCIe device driver iommu/riscv: Enable IOMMU registration and device probe. iommu/riscv: Device directory management. iommu/riscv: Command and fault queue support iommu/riscv: Paging domain support

 .../bindings/iommu/riscv,iommu.yaml           |  150 ++
 MAINTAINERS                                   |    8 +
 drivers/iommu/Kconfig                         |    1 +
 drivers/iommu/Makefile                        |    2 +-
 drivers/iommu/riscv/Kconfig                   |   20 +
 drivers/iommu/riscv/Makefile                  |    3 +
 drivers/iommu/riscv/iommu-bits.h              |  782 +++++++++
 drivers/iommu/riscv/iommu-pci.c               |  119 ++
 drivers/iommu/riscv/iommu-platform.c          |   92 +
 drivers/iommu/riscv/iommu.c                   | 1549 +++++++++++++++++
 drivers/iommu/riscv/iommu.h                   |   88 +
 11 files changed, 2813 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
 create mode 100644 drivers/iommu/riscv/Kconfig
 create mode 100644 drivers/iommu/riscv/Makefile
 create mode 100644 drivers/iommu/riscv/iommu-bits.h
 create mode 100644 drivers/iommu/riscv/iommu-pci.c
 create mode 100644 drivers/iommu/riscv/iommu-platform.c
 create mode 100644 drivers/iommu/riscv/iommu.c
 create mode 100644 drivers/iommu/riscv/iommu.h

base-commit: e67572cd2204894179d89bd7b984072f19313b03
message-id: [email protected]
message-id: [email protected]

Signature · 1 line
2.34.1
#1 lore raw

PATCH v3 1/7 dt-bindings: iommu: riscv: Add bindings for RISC-V IOMMU

Add bindings for the RISC-V IOMMU device drivers.

---
 .../bindings/iommu/riscv,iommu.yaml           | 150 ++++++++++++++++++
 MAINTAINERS                                   |   7 +
 2 files changed, 157 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +150 -0
new file mode 100644
index 000000000000..16817525e157
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/iommu/riscv,iommu.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: RISC-V IOMMU Architecture Implementation
+
+maintainers:
+  - Tomasz Jeznach <[email protected]>
+
+description: |
+  The RISC-V IOMMU provides memory address translation and isolation for
+  input and output devices, supporting per-device translation context,
+  shared process address spaces including the ATS and PRI components of
+  the PCIe specification, two stage address translation and MSI remapping.
+  It supports identical translation table format to the RISC-V address
+  translation tables with page level access and protection attributes.
+  Hardware uses in-memory command and fault reporting queues with wired
+  interrupt or MSI notifications.
+
+  Visit https://github.com/riscv-non-isa/riscv-iommu for more details.
+
+  For information on assigning RISC-V IOMMU to its peripheral devices,
+  see generic IOMMU bindings.
+
+properties:
+  # For PCIe IOMMU hardware compatible property should contain the vendor
+  # and device ID according to the PCI Bus Binding specification.
+  # Since PCI provides built-in identification methods, compatible is not
+  # actually required. For non-PCIe hardware implementations 'riscv,iommu'
+  # should be specified along with 'reg' property providing MMIO location.
+  compatible:
+    oneOf:
+      - items:
+          - enum:
+              - qemu,iommu
+          - const: riscv,iommu
+      - items:
+          - enum:
+              - pci1efd,edf1
+          - const: riscv,pci-iommu
+
+  reg:
+    maxItems: 1
+    description:
+      For non-PCI devices this represents base address and size of for the
+      IOMMU memory mapped registers interface.
+      For PCI IOMMU hardware implementation this should represent an address
+      of the IOMMU, as defined in the PCI Bus Binding reference. The reg
+      property is a five-cell address encoded as (phys.hi phys.mid phys.lo
+      size.hi size.lo), where phys.hi should contain the device's BDF as
+      0b00000000 bbbbbbbb dddddfff 00000000. The other cells should be zero.
+
+  '#iommu-cells':
+    const: 1
+    description:
+      Has to be one. The single cell describes the requester id emitted
+      by a master to the IOMMU.
+
+  interrupts:
+    minItems: 1
+    maxItems: 4
+    description:
+      Wired interrupt vectors available for RISC-V IOMMU to notify the
+      RISC-V HARTS. The cause to interrupt vector is software defined
+      using IVEC IOMMU register.
+
+  msi-parent: true
+
+  power-domains:
+    maxItems: 1
+
+required:
+  - compatible
+  - reg
+  - '#iommu-cells'
+
+additionalProperties: false
+
+examples:
+  - |+
+    /* Example 1 (IOMMU device with wired interrupts) */
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    iommu1: iommu@1bccd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        interrupt-parent = <&aplic_smode>;
+        interrupts = <32 IRQ_TYPE_LEVEL_HIGH>,
+                     <33 IRQ_TYPE_LEVEL_HIGH>,
+                     <34 IRQ_TYPE_LEVEL_HIGH>,
+                     <35 IRQ_TYPE_LEVEL_HIGH>;
+        #iommu-cells = <1>;
+    };
+
+    /* Device with two IOMMU device IDs, 0 and 7 */
+    master1 {
+        iommus = <&iommu1 0>, <&iommu1 7>;
+    };
+
+  - |+
+    /* Example 2 (IOMMU device with shared wired interrupt) */
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    iommu2: iommu@1bccd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        interrupt-parent = <&aplic_smode>;
+        interrupts = <32 IRQ_TYPE_LEVEL_HIGH>;
+        #iommu-cells = <1>;
+    };
+
+  - |+
+    /* Example 3 (IOMMU device with MSIs) */
+    iommu3: iommu@1bcdd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        msi-parent = <&imsics_smode>;
+        #iommu-cells = <1>;
+    };
+
+  - |+
+    /* Example 4 (IOMMU PCIe device with MSIs) */
+    bus {
+        #address-cells = <2>;
+        #size-cells = <2>;
+
+        pcie@30000000 {
+            device_type = "pci";
+            #address-cells = <3>;
+            #size-cells = <2>;
+            reg = <0x0 0x30000000  0x0 0x1000000>;
+            ranges = <0x02000000 0x0 0x41000000  0x0 0x41000000  0x0 0x0f000000>;
+
+            /*
+             * The IOMMU manages all functions in this PCI domain except
+             * itself. Omit BDF 00:01.0.
+             */
+            iommu-map = <0x0 &iommu0 0x0 0x8
+                         0x9 &iommu0 0x9 0xfff7>;
+
+            /* The IOMMU programming interface uses slot 00:01.0 */
+            iommu0: iommu@1,0 {
+               compatible = "pci1efd,edf1", "riscv,pci-iommu";
+               reg = <0x800 0 0 0 0>;
+               #iommu-cells = <1>;
+            };
+        };
+    };
MAINTAINERS +7 -0
index f6dc90559341..7fcf7c27ef6b 100644
@@ -18958,6 +18958,13 @@ F:	arch/riscv/
 N:	riscv
 K:	riscv
 
+RISC-V IOMMU
+M:	Tomasz Jeznach <[email protected]>
+L:	[email protected]
+L:	[email protected]
+S:	Maintained
+F:	Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
+
 RISC-V MICROCHIP FPGA SUPPORT
 M:	Conor Dooley <[email protected]>
 M:	Daire McNamara <[email protected]>
Signature · 1 line
2.34.1
maintainer
#3 lore raw

Re: [PATCH v3 1/7] dt-bindings: iommu: riscv: Add bindings for RISC-V IOMMU

In reply to Tomasz Jeznach
Quoted 44 lines · Tomasz Jeznach

Add bindings for the RISC-V IOMMU device drivers.

---
 .../bindings/iommu/riscv,iommu.yaml           | 150 ++++++++++++++++++
 MAINTAINERS                                   |   7 +
 2 files changed, 157 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +27 -0
new file mode 100644
index 000000000000..16817525e157
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/iommu/riscv,iommu.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: RISC-V IOMMU Architecture Implementation
+
+maintainers:
+  - Tomasz Jeznach <[email protected]>
+
+description: |
+  The RISC-V IOMMU provides memory address translation and isolation for
+  input and output devices, supporting per-device translation context,
+  shared process address spaces including the ATS and PRI components of
+  the PCIe specification, two stage address translation and MSI remapping.
+  It supports identical translation table format to the RISC-V address
+  translation tables with page level access and protection attributes.
+  Hardware uses in-memory command and fault reporting queues with wired
+  interrupt or MSI notifications.
+
+  Visit https://github.com/riscv-non-isa/riscv-iommu for more details.
+
+  For information on assigning RISC-V IOMMU to its peripheral devices,
+  see generic IOMMU bindings.
+
+properties:

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 37

Quoted 10 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +10 -0
+  # For PCIe IOMMU hardware compatible property should contain the vendor
+  # and device ID according to the PCI Bus Binding specification.
+  # Since PCI provides built-in identification methods, compatible is not
+  # actually required. For non-PCIe hardware implementations 'riscv,iommu'
+  # should be specified along with 'reg' property providing MMIO location.
+  compatible:
+    oneOf:
+      - items:
+          - enum:
+              - qemu,iommu

'qemu,iommu' is too broad. Could be other QEMU implementations of an IOMMU. So 'qemu,riscv-iommu'.

Quoted 6 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +6 -0
+          - const: riscv,iommu
+      - items:
+          - enum:
+              - pci1efd,edf1
+          - const: riscv,pci-iommu
+

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 53

Quoted 10 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +10 -0
+  reg:
+    maxItems: 1
+    description:
+      For non-PCI devices this represents base address and size of for the
+      IOMMU memory mapped registers interface.
+      For PCI IOMMU hardware implementation this should represent an address
+      of the IOMMU, as defined in the PCI Bus Binding reference. The reg
+      property is a five-cell address encoded as (phys.hi phys.mid phys.lo
+      size.hi size.lo), where phys.hi should contain the device's BDF as
+      0b00000000 bbbbbbbb dddddfff 00000000. The other cells should be zero.

No need to describe what the PCI address looks like.

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 58

Quoted 5 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +5 -0
+
+  '#iommu-cells':
+    const: 1
+    description:
+      Has to be one. The single cell describes the requester id emitted

Drop 'Has to be one'. You already said that with the schema.

Quoted 73 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +73 -0
+      by a master to the IOMMU.
+
+  interrupts:
+    minItems: 1
+    maxItems: 4
+    description:
+      Wired interrupt vectors available for RISC-V IOMMU to notify the
+      RISC-V HARTS. The cause to interrupt vector is software defined
+      using IVEC IOMMU register.
+
+  msi-parent: true
+
+  power-domains:
+    maxItems: 1
+
+required:
+  - compatible
+  - reg
+  - '#iommu-cells'
+
+additionalProperties: false
+
+examples:
+  - |+
+    /* Example 1 (IOMMU device with wired interrupts) */
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    iommu1: iommu@1bccd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        interrupt-parent = <&aplic_smode>;
+        interrupts = <32 IRQ_TYPE_LEVEL_HIGH>,
+                     <33 IRQ_TYPE_LEVEL_HIGH>,
+                     <34 IRQ_TYPE_LEVEL_HIGH>,
+                     <35 IRQ_TYPE_LEVEL_HIGH>;
+        #iommu-cells = <1>;
+    };
+
+    /* Device with two IOMMU device IDs, 0 and 7 */
+    master1 {
+        iommus = <&iommu1 0>, <&iommu1 7>;
+    };
+
+  - |+
+    /* Example 2 (IOMMU device with shared wired interrupt) */
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    iommu2: iommu@1bccd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        interrupt-parent = <&aplic_smode>;
+        interrupts = <32 IRQ_TYPE_LEVEL_HIGH>;
+        #iommu-cells = <1>;
+    };
+
+  - |+
+    /* Example 3 (IOMMU device with MSIs) */
+    iommu3: iommu@1bcdd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        msi-parent = <&imsics_smode>;
+        #iommu-cells = <1>;
+    };
+
+  - |+
+    /* Example 4 (IOMMU PCIe device with MSIs) */
+    bus {
+        #address-cells = <2>;
+        #size-cells = <2>;
+
+        pcie@30000000 {
+            device_type = "pci";
+            #address-cells = <3>;

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 141

Quoted 10 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +10 -0
+            #size-cells = <2>;
+            reg = <0x0 0x30000000  0x0 0x1000000>;
+            ranges = <0x02000000 0x0 0x41000000  0x0 0x41000000  0x0 0x0f000000>;
+
+            /*
+             * The IOMMU manages all functions in this PCI domain except
+             * itself. Omit BDF 00:01.0.
+             */
+            iommu-map = <0x0 &iommu0 0x0 0x8
+                         0x9 &iommu0 0x9 0xfff7>;

Bracket each entry.

Quoted 30 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +9 -0
+
+            /* The IOMMU programming interface uses slot 00:01.0 */
+            iommu0: iommu@1,0 {
+               compatible = "pci1efd,edf1", "riscv,pci-iommu";
+               reg = <0x800 0 0 0 0>;
+               #iommu-cells = <1>;
+            };
+        };
+    };
MAINTAINERS +7 -0
index f6dc90559341..7fcf7c27ef6b 100644
@@ -18958,6 +18958,13 @@ F:	arch/riscv/
 N:	riscv
 K:	riscv
 
+RISC-V IOMMU
+M:	Tomasz Jeznach <[email protected]>
+L:	[email protected]
+L:	[email protected]
+S:	Maintained
+F:	Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
+
 RISC-V MICROCHIP FPGA SUPPORT
 M:	Conor Dooley <[email protected]>
 M:	Daire McNamara <[email protected]>
Signature · 1 line
2.34.1
#4 lore raw

Re: [PATCH v3 1/7] dt-bindings: iommu: riscv: Add bindings for RISC-V IOMMU

Quoted 52 lines · Rob Herring
Quoted 50 lines · Tomasz Jeznach

Add bindings for the RISC-V IOMMU device drivers.

---
 .../bindings/iommu/riscv,iommu.yaml           | 150 ++++++++++++++++++
 MAINTAINERS                                   |   7 +
 2 files changed, 157 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +33 -0
new file mode 100644
index 000000000000..16817525e157
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/iommu/riscv,iommu.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: RISC-V IOMMU Architecture Implementation
+
+maintainers:
+  - Tomasz Jeznach <[email protected]>
+
+description: |
+  The RISC-V IOMMU provides memory address translation and isolation for
+  input and output devices, supporting per-device translation context,
+  shared process address spaces including the ATS and PRI components of
+  the PCIe specification, two stage address translation and MSI remapping.
+  It supports identical translation table format to the RISC-V address
+  translation tables with page level access and protection attributes.
+  Hardware uses in-memory command and fault reporting queues with wired
+  interrupt or MSI notifications.
+
+  Visit https://github.com/riscv-non-isa/riscv-iommu for more details.
+
+  For information on assigning RISC-V IOMMU to its peripheral devices,
+  see generic IOMMU bindings.
+
+properties:
+  # For PCIe IOMMU hardware compatible property should contain the vendor
+  # and device ID according to the PCI Bus Binding specification.
+  # Since PCI provides built-in identification methods, compatible is not
+  # actually required. For non-PCIe hardware implementations 'riscv,iommu'
+  # should be specified along with 'reg' property providing MMIO location.
+  compatible:
Quoted 9 lines

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 37

Quoted 4 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +4 -0
+    oneOf:
+      - items:
+          - enum:
+              - qemu,iommu

'qemu,iommu' is too broad. Could be other QEMU implementations of an IOMMU. So 'qemu,riscv-iommu'.

I'm ok with that. Any objections from others?

Quoted 130 lines
Quoted 6 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +6 -0
+          - const: riscv,iommu
+      - items:
+          - enum:
+              - pci1efd,edf1
+          - const: riscv,pci-iommu
+

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 53

Quoted 10 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +10 -0
+  reg:
+    maxItems: 1
+    description:
+      For non-PCI devices this represents base address and size of for the
+      IOMMU memory mapped registers interface.
+      For PCI IOMMU hardware implementation this should represent an address
+      of the IOMMU, as defined in the PCI Bus Binding reference. The reg
+      property is a five-cell address encoded as (phys.hi phys.mid phys.lo
+      size.hi size.lo), where phys.hi should contain the device's BDF as
+      0b00000000 bbbbbbbb dddddfff 00000000. The other cells should be zero.

No need to describe what the PCI address looks like.

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 58

Quoted 5 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +5 -0
+
+  '#iommu-cells':
+    const: 1
+    description:
+      Has to be one. The single cell describes the requester id emitted

Drop 'Has to be one'. You already said that with the schema.

Quoted 73 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +73 -0
+      by a master to the IOMMU.
+
+  interrupts:
+    minItems: 1
+    maxItems: 4
+    description:
+      Wired interrupt vectors available for RISC-V IOMMU to notify the
+      RISC-V HARTS. The cause to interrupt vector is software defined
+      using IVEC IOMMU register.
+
+  msi-parent: true
+
+  power-domains:
+    maxItems: 1
+
+required:
+  - compatible
+  - reg
+  - '#iommu-cells'
+
+additionalProperties: false
+
+examples:
+  - |+
+    /* Example 1 (IOMMU device with wired interrupts) */
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    iommu1: iommu@1bccd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        interrupt-parent = <&aplic_smode>;
+        interrupts = <32 IRQ_TYPE_LEVEL_HIGH>,
+                     <33 IRQ_TYPE_LEVEL_HIGH>,
+                     <34 IRQ_TYPE_LEVEL_HIGH>,
+                     <35 IRQ_TYPE_LEVEL_HIGH>;
+        #iommu-cells = <1>;
+    };
+
+    /* Device with two IOMMU device IDs, 0 and 7 */
+    master1 {
+        iommus = <&iommu1 0>, <&iommu1 7>;
+    };
+
+  - |+
+    /* Example 2 (IOMMU device with shared wired interrupt) */
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    iommu2: iommu@1bccd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        interrupt-parent = <&aplic_smode>;
+        interrupts = <32 IRQ_TYPE_LEVEL_HIGH>;
+        #iommu-cells = <1>;
+    };
+
+  - |+
+    /* Example 3 (IOMMU device with MSIs) */
+    iommu3: iommu@1bcdd000 {
+        compatible = "qemu,iommu", "riscv,iommu";
+        reg = <0x1bccd000 0x1000>;
+        msi-parent = <&imsics_smode>;
+        #iommu-cells = <1>;
+    };
+
+  - |+
+    /* Example 4 (IOMMU PCIe device with MSIs) */
+    bus {
+        #address-cells = <2>;
+        #size-cells = <2>;
+
+        pcie@30000000 {
+            device_type = "pci";
+            #address-cells = <3>;

Documentation/devicetree/bindings/iommu/riscv,iommu.yaml line 141

Quoted 10 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +10 -0
+            #size-cells = <2>;
+            reg = <0x0 0x30000000  0x0 0x1000000>;
+            ranges = <0x02000000 0x0 0x41000000  0x0 0x41000000  0x0 0x0f000000>;
+
+            /*
+             * The IOMMU manages all functions in this PCI domain except
+             * itself. Omit BDF 00:01.0.
+             */
+            iommu-map = <0x0 &iommu0 0x0 0x8
+                         0x9 &iommu0 0x9 0xfff7>;

Bracket each entry.

Quoted 17 lines
Documentation/devicetree/bindings/iommu/riscv,iommu.yaml new file +9 -0
+
+            /* The IOMMU programming interface uses slot 00:01.0 */
+            iommu0: iommu@1,0 {
+               compatible = "pci1efd,edf1", "riscv,pci-iommu";
+               reg = <0x800 0 0 0 0>;
+               #iommu-cells = <1>;
+            };
+        };
+    };
MAINTAINERS +0 -0
index f6dc90559341..7fcf7c27ef6b 100644
@@ -18958,6 +18958,13 @@ F:   arch/riscv/
 N:   riscv
 K:   riscv
 
Quoted 13 lines
Quoted 11 lines
MAINTAINERS +7 -1
+RISC-V IOMMU
+M:   Tomasz Jeznach <[email protected]>
+L:   [email protected]
+L:   [email protected]
+S:   Maintained
+F:   Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
+
 RISC-V MICROCHIP FPGA SUPPORT
 M:   Conor Dooley <[email protected]>
 M:   Daire McNamara <[email protected]>
--
Quoted 2 lines

2.34.1

ack to other comments.

Thank you for review,
- Tomasz

#5 lore raw

Re: [PATCH v3 1/7] dt-bindings: iommu: riscv: Add bindings for RISC-V IOMMU

Quoted 5 lines · Tomasz Jeznach
Quoted 4 lines

'qemu,iommu' is too broad. Could be other QEMU implementations of an IOMMU. So 'qemu,riscv-iommu'.

I'm ok with that. Any objections from others?

None here, you can keep my tag with the things Rob noticed.

#6 lore raw

PATCH v3 2/7 iommu/riscv: Add RISC-V IOMMU platform device driver

In reply to Tomasz Jeznach

Introduce platform device driver for implementation of RISC-V IOMMU architected hardware.

Hardware interface definition located in file iommu-bits.h is based on ratified RISC-V IOMMU Architecture Specification version 1.0.0.

This patch implements platform device initialization, early check and configuration of the IOMMU interfaces and enables global pass-through address translation mode (iommu_mode == BARE), without registering hardware instance in the IOMMU subsystem.

---
 MAINTAINERS                          |   1 +
 drivers/iommu/Kconfig                |   1 +
 drivers/iommu/Makefile               |   2 +-
 drivers/iommu/riscv/Kconfig          |  15 +
 drivers/iommu/riscv/Makefile         |   2 +
 drivers/iommu/riscv/iommu-bits.h     | 707 +++++++++++++++++++++++++++
 drivers/iommu/riscv/iommu-platform.c |  92 ++++
 drivers/iommu/riscv/iommu.c          | 103 ++++
 drivers/iommu/riscv/iommu.h          |  62 +++
 9 files changed, 984 insertions(+), 1 deletion(-)
 create mode 100644 drivers/iommu/riscv/Kconfig
 create mode 100644 drivers/iommu/riscv/Makefile
 create mode 100644 drivers/iommu/riscv/iommu-bits.h
 create mode 100644 drivers/iommu/riscv/iommu-platform.c
 create mode 100644 drivers/iommu/riscv/iommu.c
 create mode 100644 drivers/iommu/riscv/iommu.h
MAINTAINERS +1 -0
index 7fcf7c27ef6b..42df3b3871f4 100644
@@ -18964,6 +18964,7 @@ L:	[email protected]
 L:	[email protected]
 S:	Maintained
 F:	Documentation/devicetree/bindings/iommu/riscv,iommu.yaml
+F:	drivers/iommu/riscv/
 
 RISC-V MICROCHIP FPGA SUPPORT
 M:	Conor Dooley <[email protected]>
drivers/iommu/Kconfig +1 -0
index 0af39bbbe3a3..ae762db0365e 100644
@@ -195,6 +195,7 @@ config MSM_IOMMU
 source "drivers/iommu/amd/Kconfig"
 source "drivers/iommu/intel/Kconfig"
 source "drivers/iommu/iommufd/Kconfig"
+source "drivers/iommu/riscv/Kconfig"
 
 config IRQ_REMAP
 	bool "Support for Interrupt Remapping"
drivers/iommu/Makefile +1 -1
index 542760d963ec..5e5a83c6c2aa 100644
@@ -1,5 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0
-obj-y += amd/ intel/ arm/ iommufd/
+obj-y += amd/ intel/ arm/ iommufd/ riscv/
 obj-$(CONFIG_IOMMU_API) += iommu.o
 obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
drivers/iommu/riscv/Kconfig new file +15 -0
new file mode 100644
index 000000000000..5dcc5c45aa50
@@ -0,0 +1,15 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# RISC-V IOMMU support
+
+config RISCV_IOMMU
+	bool "RISC-V IOMMU Support"
+	depends on RISCV && 64BIT
+	default y
+	select IOMMU_API
+	help
+	  Support for implementations of the RISC-V IOMMU architecture that
+	  complements the RISC-V MMU capabilities, providing similar address
+	  translation and protection functions for accesses from I/O devices.
+
+	  Say Y here if your SoC includes an IOMMU device implementing
+	  the RISC-V IOMMU architecture.
drivers/iommu/riscv/Makefile new file +2 -0
new file mode 100644
index 000000000000..e4c189de58d3
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+obj-$(CONFIG_RISCV_IOMMU) += iommu.o iommu-platform.o
drivers/iommu/riscv/iommu-bits.h new file +707 -0

707 lines not on this page · raw message

drivers/iommu/riscv/iommu-platform.c new file +92 -0

92 lines not on this page · raw message

drivers/iommu/riscv/iommu.c new file +103 -0

103 lines not on this page · raw message

drivers/iommu/riscv/iommu.h new file +62 -0

62 lines not on this page · raw message

Signature · 1 line
2.34.1
#7 lore raw

Re: [PATCH v3 2/7] iommu/riscv: Add RISC-V IOMMU platform device driver

Quoted 5 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c new file +5 -0
+static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
+{
+	u64 ddtp;
+
+	/*

drivers/iommu/riscv/iommu.c line 53

Quoted 10 lines
drivers/iommu/riscv/iommu.c new file +10 -0
+	 * Make sure the IOMMU is switched off or in pass-through mode during regular
+	 * boot flow and disable translation when we boot into a kexec kernel and the
+	 * previous kernel left them enabled.
+	 */
+	ddtp = riscv_iommu_readq(iommu, RISCV_IOMMU_REG_DDTP);
+	if (ddtp & RISCV_IOMMU_DDTP_BUSY)
+		return -EBUSY;
+
+	if (FIELD_GET(RISCV_IOMMU_DDTP_MODE, ddtp) > RISCV_IOMMU_DDTP_MODE_BARE) {
+		if (!is_kdump_kernel())

Is kdump supported for RISC-V architectures? If so, the documentation in Documentation/admin-guide/kdump/kdump.rst might need an update.

There is a possibility of ongoing DMAs during the boot process of the kdump capture kernel because there's a small chance of legacy DMA setups targeting any memory location. Kdump typically allows these ongoing DMA transfers to complete, assuming they were intended for valid memory regions.

The IOMMU subsystem implements a default domain deferred attachment mechanism for this. In the kdump capture kernel, the whole device context tables are copied from the original kernel and will be overridden once the device driver calls the kernel DMA interface for the first time. This assumes that all old DMA transfers are completed after the driver's takeover.

Will you consider this for RISC-V architecture as well?

Quoted 7 lines
drivers/iommu/riscv/iommu.c new file +7 -0
+			return -EBUSY;
+		riscv_iommu_disable(iommu);
+	}
+
+	/* Configure accesses to in-memory data structures for CPU-native byte order. */
+	if (IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) != !!(iommu->fctl & RISCV_IOMMU_FCTL_BE)) {
+		if (!(iommu->caps & RISCV_IOMMU_CAP_END))

drivers/iommu/riscv/iommu.c line 70

Quoted 10 lines
drivers/iommu/riscv/iommu.c new file +10 -0
+			return -EINVAL;
+		riscv_iommu_writel(iommu, RISCV_IOMMU_REG_FCTL,
+				   iommu->fctl ^ RISCV_IOMMU_FCTL_BE);
+		iommu->fctl = riscv_iommu_readl(iommu, RISCV_IOMMU_REG_FCTL);
+		if (IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) != !!(iommu->fctl & RISCV_IOMMU_FCTL_BE))
+			return -EINVAL;
+	}
+
+	return 0;
+}

Best regards,
baolu

#8 lore raw

Re: [PATCH v3 2/7] iommu/riscv: Add RISC-V IOMMU platform device driver

Quoted 26 lines · Baolu Lu
Quoted 5 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c new file +5 -0
+static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
+{
+	u64 ddtp;
+
+	/*

drivers/iommu/riscv/iommu.c line 53

Quoted 10 lines
drivers/iommu/riscv/iommu.c new file +10 -0
+	 * Make sure the IOMMU is switched off or in pass-through mode during regular
+	 * boot flow and disable translation when we boot into a kexec kernel and the
+	 * previous kernel left them enabled.
+	 */
+	ddtp = riscv_iommu_readq(iommu, RISCV_IOMMU_REG_DDTP);
+	if (ddtp & RISCV_IOMMU_DDTP_BUSY)
+		return -EBUSY;
+
+	if (FIELD_GET(RISCV_IOMMU_DDTP_MODE, ddtp) > RISCV_IOMMU_DDTP_MODE_BARE) {
+		if (!is_kdump_kernel())

Is kdump supported for RISC-V architectures? If so, the documentation in Documentation/admin-guide/kdump/kdump.rst might need an update.

There is a possibility of ongoing DMAs during the boot process of the kdump capture kernel because there's a small chance of legacy DMA setups targeting any memory location. Kdump typically allows these ongoing DMA transfers to complete, assuming they were intended for valid memory regions.

Quoted 8 lines

The IOMMU subsystem implements a default domain deferred attachment mechanism for this. In the kdump capture kernel, the whole device context tables are copied from the original kernel and will be overridden once the device driver calls the kernel DMA interface for the first time. This assumes that all old DMA transfers are completed after the driver's takeover.

Will you consider this for RISC-V architecture as well?

It seems we decided not to do that mess in ARM..

New architectures doing kdump should put the iommu in a full blocking state before handing over the next kernel, and this implies that devices drivers need to cleanly suspend their DMAs before going into the next kernel.

Jason

#9 lore raw

Re: [PATCH v3 2/7] iommu/riscv: Add RISC-V IOMMU platform device driver

Quoted 33 lines · Jason Gunthorpe
Quoted 32 lines · Baolu Lu
Quoted 5 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c new file +5 -0
+static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
+{
+	u64 ddtp;
+
+	/*

drivers/iommu/riscv/iommu.c line 53

Quoted 10 lines
drivers/iommu/riscv/iommu.c new file +10 -0
+	 * Make sure the IOMMU is switched off or in pass-through mode during regular
+	 * boot flow and disable translation when we boot into a kexec kernel and the
+	 * previous kernel left them enabled.
+	 */
+	ddtp = riscv_iommu_readq(iommu, RISCV_IOMMU_REG_DDTP);
+	if (ddtp & RISCV_IOMMU_DDTP_BUSY)
+		return -EBUSY;
+
+	if (FIELD_GET(RISCV_IOMMU_DDTP_MODE, ddtp) > RISCV_IOMMU_DDTP_MODE_BARE) {
+		if (!is_kdump_kernel())

Is kdump supported for RISC-V architectures? If so, the documentation in Documentation/admin-guide/kdump/kdump.rst might need an update.

There is a possibility of ongoing DMAs during the boot process of the kdump capture kernel because there's a small chance of legacy DMA setups targeting any memory location. Kdump typically allows these ongoing DMA transfers to complete, assuming they were intended for valid memory regions.

The IOMMU subsystem implements a default domain deferred attachment mechanism for this. In the kdump capture kernel, the whole device context tables are copied from the original kernel and will be overridden once the device driver calls the kernel DMA interface for the first time. This assumes that all old DMA transfers are completed after the driver's takeover.

Quoted 7 lines
Quoted 1 line

Will you consider this for RISC-V architecture as well?

It seems we decided not to do that mess in ARM..

New architectures doing kdump should put the iommu in a full blocking state before handing over the next kernel, and this implies that devices drivers need to cleanly suspend their DMAs before going into the next kernel.

Glad to hear that. :-)

With the above consideration, the driver should consider it an error case where the iommu is not in the blocking state, and it's in the kdump kernel, right?

If so, probably the iommu driver should always return failure when the iommu is not in the blocking state. However, the RISC-V's logic is:

- if this is a kdump kernel, just disable iommu;
- otherwise, failure case.

This logic seems problematic.

Best regards,
baolu

#10 lore raw

Re: [PATCH v3 2/7] iommu/riscv: Add RISC-V IOMMU platform device driver

Quoted 49 lines · Baolu Lu
Quoted 33 lines · Jason Gunthorpe
Quoted 32 lines · Baolu Lu
Quoted 5 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c new file +5 -0
+static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
+{
+   u64 ddtp;
+
+   /*

drivers/iommu/riscv/iommu.c line 53

Quoted 10 lines
drivers/iommu/riscv/iommu.c new file +10 -0
+    * Make sure the IOMMU is switched off or in pass-through mode during regular
+    * boot flow and disable translation when we boot into a kexec kernel and the
+    * previous kernel left them enabled.
+    */
+   ddtp = riscv_iommu_readq(iommu, RISCV_IOMMU_REG_DDTP);
+   if (ddtp & RISCV_IOMMU_DDTP_BUSY)
+           return -EBUSY;
+
+   if (FIELD_GET(RISCV_IOMMU_DDTP_MODE, ddtp) > RISCV_IOMMU_DDTP_MODE_BARE) {
+           if (!is_kdump_kernel())

Is kdump supported for RISC-V architectures? If so, the documentation in Documentation/admin-guide/kdump/kdump.rst might need an update.

There is a possibility of ongoing DMAs during the boot process of the kdump capture kernel because there's a small chance of legacy DMA setups targeting any memory location. Kdump typically allows these ongoing DMA transfers to complete, assuming they were intended for valid memory regions.

The IOMMU subsystem implements a default domain deferred attachment mechanism for this. In the kdump capture kernel, the whole device context tables are copied from the original kernel and will be overridden once the device driver calls the kernel DMA interface for the first time. This assumes that all old DMA transfers are completed after the driver's takeover.

Quoted 7 lines
Quoted 1 line

Will you consider this for RISC-V architecture as well?

It seems we decided not to do that mess in ARM..

New architectures doing kdump should put the iommu in a full blocking state before handing over the next kernel, and this implies that devices drivers need to cleanly suspend their DMAs before going into the next kernel.

Glad to hear that. :-)

With the above consideration, the driver should consider it an error case where the iommu is not in the blocking state, and it's in the kdump kernel, right?

Quoted 8 lines

If so, probably the iommu driver should always return failure when the iommu is not in the blocking state. However, the RISC-V's logic is:

- if this is a kdump kernel, just disable iommu;
- otherwise, failure case.

This logic seems problematic.

Initial implementation recognize this as an error and failed to initialize IOMMU was in non-default state (disabled or pass-through). Ideally we should have proper shutdown sequence for kdump case, and quiesce IOMMU before kdump kernel runs. However, this path is problematic enough that I'd prefer not to add any other complications to this patch set. Definitely setting IOMMU in a full blocking state before handling over to kdump kernel. Will get back to that at some point.

Dropping all IOMMU config in kdump path is IMHO the compromise we can accept, leaving kdump kernel an option to reconfigure IOMMU in later stages of the IOMMU initialization.

Quoted 2 lines

Best regards,
baolu

Best,
- Tomasz

#11 lore raw

PATCH v3 3/7 iommu/riscv: Add RISC-V IOMMU PCIe device driver

In reply to Tomasz Jeznach

Introduce device driver for PCIe implementation
of RISC-V IOMMU architected hardware.

IOMMU hardware and system support for MSI or MSI-X is required by this implementation.

Vendor and device identifiers used in this patch matches QEMU implementation of the RISC-V IOMMU PCIe device, from Rivos VID (0x1efd) range allocated by the PCI-SIG.

MAINTAINERS | added iommu-pci.c already covered by matching pattern.

---
 drivers/iommu/riscv/Kconfig     |   5 ++
 drivers/iommu/riscv/Makefile    |   1 +
 drivers/iommu/riscv/iommu-pci.c | 119 ++++++++++++++++++++++++++++++++
 3 files changed, 125 insertions(+)
 create mode 100644 drivers/iommu/riscv/iommu-pci.c
drivers/iommu/riscv/Kconfig +5 -0
index 5dcc5c45aa50..c071816f59a6 100644
@@ -13,3 +13,8 @@ config RISCV_IOMMU
 
 	  Say Y here if your SoC includes an IOMMU device implementing
 	  the RISC-V IOMMU architecture.
+
+config RISCV_IOMMU_PCI
+	def_bool y if RISCV_IOMMU && PCI_MSI
+	help
+	  Support for the PCIe implementation of RISC-V IOMMU architecture.
drivers/iommu/riscv/Makefile +1 -0
index e4c189de58d3..f54c9ed17d41 100644
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0-only
 obj-$(CONFIG_RISCV_IOMMU) += iommu.o iommu-platform.o
+obj-$(CONFIG_RISCV_IOMMU_PCI) += iommu-pci.o
drivers/iommu/riscv/iommu-pci.c new file +119 -0

119 lines not on this page · raw message

Signature · 1 line
2.34.1
Reviewed-by on v3 3/7
#12 lore raw

Re: [PATCH v3 3/7] iommu/riscv: Add RISC-V IOMMU PCIe device driver

Quoted 16 lines · Tomasz Jeznach

Introduce device driver for PCIe implementation of RISC-V IOMMU architected hardware.

IOMMU hardware and system support for MSI or MSI-X is required by this implementation.

Vendor and device identifiers used in this patch matches QEMU implementation of the RISC-V IOMMU PCIe device, from Rivos VID (0x1efd) range allocated by the PCI-SIG.

MAINTAINERS | added iommu-pci.c already covered by matching pattern.

Quoted 6 lines
---
  drivers/iommu/riscv/Kconfig     |   5 ++
  drivers/iommu/riscv/Makefile    |   1 +
  drivers/iommu/riscv/iommu-pci.c | 119 ++++++++++++++++++++++++++++++++
  3 files changed, 125 insertions(+)

create mode 100644 drivers/iommu/riscv/iommu-pci.c

Best regards,
baolu

#13 lore raw

PATCH v3 4/7 iommu/riscv: Enable IOMMU registration and device probe.

In reply to Tomasz Jeznach

Advertise IOMMU device and its core API.
Only minimal implementation for single identity domain type, without per-group domain protection.

---
 drivers/iommu/riscv/iommu.c | 64 +++++++++++++++++++++++++++++++++++++
 1 file changed, 64 insertions(+)
drivers/iommu/riscv/iommu.c +64 -0
index 07c2bcb08afd..17dc6431fd37 100644
@@ -17,6 +17,7 @@
 #include <linux/init.h>
 #include <linux/iommu.h>
 #include <linux/kernel.h>
+#include <linux/pci.h>
 
 #include "iommu-bits.h"
 #include "iommu.h"
@@ -36,6 +37,60 @@ static void riscv_iommu_disable(struct riscv_iommu_device *iommu)
 	riscv_iommu_writel(iommu, RISCV_IOMMU_REG_PQCSR, 0);
 }
 
+static int riscv_iommu_attach_identity_domain(struct iommu_domain *domain,
+					      struct device *dev)
+{
+	/* Global pass-through already enabled, do nothing for now. */
+	return 0;
+}
+
+static struct iommu_domain riscv_iommu_identity_domain = {
+	.type = IOMMU_DOMAIN_IDENTITY,
+	.ops = &(const struct iommu_domain_ops) {
+		.attach_dev = riscv_iommu_attach_identity_domain,
+	}
+};
+
+static int riscv_iommu_device_domain_type(struct device *dev)
+{
+	return IOMMU_DOMAIN_IDENTITY;
+}
+
+static struct iommu_group *riscv_iommu_device_group(struct device *dev)
+{
+	if (dev_is_pci(dev))
+		return pci_device_group(dev);
+	return generic_device_group(dev);
+}
+
+static int riscv_iommu_of_xlate(struct device *dev, const struct of_phandle_args *args)
+{
+	return iommu_fwspec_add_ids(dev, args->args, 1);
+}
+
+static struct iommu_device *riscv_iommu_probe_device(struct device *dev)
+{
+	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
+	struct riscv_iommu_device *iommu;
+
+	if (!fwspec->iommu_fwnode->dev || !fwspec->num_ids)
+		return ERR_PTR(-ENODEV);
+
+	iommu = dev_get_drvdata(fwspec->iommu_fwnode->dev);
+	if (!iommu)
+		return ERR_PTR(-ENODEV);
+
+	return &iommu->iommu;
+}
+
+static const struct iommu_ops riscv_iommu_ops = {
+	.of_xlate = riscv_iommu_of_xlate,
+	.identity_domain = &riscv_iommu_identity_domain,
+	.def_domain_type = riscv_iommu_device_domain_type,
+	.device_group = riscv_iommu_device_group,
+	.probe_device = riscv_iommu_probe_device,
+};
+
 static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
 {
 	u64 ddtp;
@@ -71,6 +126,7 @@ static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
 
 void riscv_iommu_remove(struct riscv_iommu_device *iommu)
 {
+	iommu_device_unregister(&iommu->iommu);
 	iommu_device_sysfs_remove(&iommu->iommu);
 }
 
@@ -96,8 +152,16 @@ int riscv_iommu_init(struct riscv_iommu_device *iommu)
 		goto err_sysfs;
 	}
 
+	rc = iommu_device_register(&iommu->iommu, &riscv_iommu_ops, iommu->dev);
+	if (rc) {
+		dev_err_probe(iommu->dev, rc, "cannot register iommu interface\n");
+		goto err_iommu;
+	}
+
 	return 0;
 
+err_iommu:
+	iommu_device_sysfs_remove(&iommu->iommu);
 err_sysfs:
 	return rc;
 }
Signature · 1 line
2.34.1
Reviewed-by on v3 4/7
#14 lore raw

Re: [PATCH v3 4/7] iommu/riscv: Enable IOMMU registration and device probe.

Quoted 5 lines · Tomasz Jeznach

Advertise IOMMU device and its core API.
Only minimal implementation for single identity domain type, without per-group domain protection.

with some nits below.

Quoted 3 lines
---
  drivers/iommu/riscv/iommu.c | 64 +++++++++++++++++++++++++++++++++++++
  1 file changed, 64 insertions(+)

[..]

Quoted 18 lines
  static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
  {
  	u64 ddtp;
drivers/iommu/riscv/iommu.c +4 -0
@@ -71,6 +126,7 @@ static int riscv_iommu_init_check(struct riscv_iommu_device *iommu)
 
  void riscv_iommu_remove(struct riscv_iommu_device *iommu)
  {
+	iommu_device_unregister(&iommu->iommu);
  	iommu_device_sysfs_remove(&iommu->iommu);
  }
 
@@ -96,8 +152,16 @@ int riscv_iommu_init(struct riscv_iommu_device *iommu)
  		goto err_sysfs;
  	}
 
+	rc = iommu_device_register(&iommu->iommu, &riscv_iommu_ops, iommu->dev);
+	if (rc) {
+		dev_err_probe(iommu->dev, rc, "cannot register iommu interface\n");

drivers/iommu/riscv/iommu.c int riscv_iommu_init(struct riscv_iommu_device *iommu) · line 167

Quoted 10 lines
drivers/iommu/riscv/iommu.c +5 -0
+		goto err_iommu;
+	}
+
  	return 0;
 
+err_iommu:
+	iommu_device_sysfs_remove(&iommu->iommu);
  err_sysfs:
  	return rc;
  }

It's better to make the goto label indicate what is going to be handled. So it's more readable to make it like this:

err_remove_sysfs:

	iommu_device_sysfs_remove(&iommu->iommu);

Best regards,
baolu

#15 lore raw

PATCH v3 5/7 iommu/riscv: Device directory management.

In reply to Tomasz Jeznach

Introduce device context allocation and device directory tree management including capabilities discovery sequence, as described in Chapter 2.1 of the RISC-V IOMMU Architecture Specification.

Device directory mode will be auto detected using DDTP WARL property, using highest mode supported by the driver and hardware. If none supported can be configured, driver will fall back to global pass-through.

First level DDTP page can be located in I/O (detected using DDTP WARL) and system memory.

Only simple identity and release (blocking) protection domains are supported by this implementation.

---
 drivers/iommu/riscv/iommu.c | 381 +++++++++++++++++++++++++++++++++++-
 drivers/iommu/riscv/iommu.h |   5 +
 2 files changed, 378 insertions(+), 8 deletions(-)
drivers/iommu/riscv/iommu.c +373 -8
index 17dc6431fd37..e874e3c97726 100644
@@ -16,15 +16,166 @@
 #include <linux/crash_dump.h>
 #include <linux/init.h>
 #include <linux/iommu.h>
+#include <linux/iopoll.h>
 #include <linux/kernel.h>
 #include <linux/pci.h>
 
+#include "../iommu-pages.h"
 #include "iommu-bits.h"
 #include "iommu.h"
 
 /* Timeouts in [us] */
 #define RISCV_IOMMU_DDTP_TIMEOUT	50000
 
+/* RISC-V IOMMU PPN <> PHYS address conversions, PHYS <=> PPN[53:10] */
+#define phys_to_ppn(va)  (((va) >> 2) & (((1ULL << 44) - 1) << 10))
+#define ppn_to_phys(pn)	 (((pn) << 2) & (((1ULL << 44) - 1) << 12))
+
+#define dev_to_iommu(dev) iommu_get_iommu_dev(dev, struct riscv_iommu_device, iommu)
+
+/* Device resource-managed allocations */
+struct riscv_iommu_devres {
+	void *addr;
+	int order;
+};
+
+static void riscv_iommu_devres_pages_release(struct device *dev, void *res)
+{
+	struct riscv_iommu_devres *devres = res;
+
+	iommu_free_pages(devres->addr, devres->order);
+}
+
+static int riscv_iommu_devres_pages_match(struct device *dev, void *res, void *p)
+{
+	struct riscv_iommu_devres *devres = res;
+	struct riscv_iommu_devres *target = p;
+
+	return devres->addr == target->addr;
+}
+
+static void *riscv_iommu_get_pages(struct riscv_iommu_device *iommu, int order)
+{
+	struct riscv_iommu_devres *devres;
+	void *addr;
+
+	addr = iommu_alloc_pages_node(dev_to_node(iommu->dev), GFP_KERNEL_ACCOUNT, order);
+	if (unlikely(!addr))
+		return NULL;
+
+	devres = devres_alloc(riscv_iommu_devres_pages_release,
+			      sizeof(struct riscv_iommu_devres), GFP_KERNEL);
+
+	if (unlikely(!devres)) {
+		iommu_free_pages(addr, order);
+		return NULL;
+	}
+
+	devres->addr = addr;
+	devres->order = order;
+
+	devres_add(iommu->dev, devres);
+
+	return addr;
+}
+
+static void riscv_iommu_free_pages(struct riscv_iommu_device *iommu, void *addr)
+{
+	struct riscv_iommu_devres devres = { .addr = addr };
+
+	devres_release(iommu->dev, riscv_iommu_devres_pages_release,
+		       riscv_iommu_devres_pages_match, &devres);
+}
+
+/* Lookup and initialize device context info structure. */
+static struct riscv_iommu_dc *riscv_iommu_get_dc(struct riscv_iommu_device *iommu,
+						 unsigned int devid)
+{
+	const bool base_format = !(iommu->caps & RISCV_IOMMU_CAP_MSI_FLAT);
+	unsigned int depth;
+	unsigned long ddt, old, new;
+	void *ptr;
+	u8 ddi_bits[3] = { 0 };
+	u64 *ddtp = NULL;
+
+	/* Make sure the mode is valid */
+	if (iommu->ddt_mode < RISCV_IOMMU_DDTP_MODE_1LVL ||
+	    iommu->ddt_mode > RISCV_IOMMU_DDTP_MODE_3LVL)
+		return NULL;
+
+	/*
+	 * Device id partitioning for base format:
+	 * DDI[0]: bits 0 - 6   (1st level) (7 bits)
+	 * DDI[1]: bits 7 - 15  (2nd level) (9 bits)
+	 * DDI[2]: bits 16 - 23 (3rd level) (8 bits)
+	 *
+	 * For extended format:
+	 * DDI[0]: bits 0 - 5   (1st level) (6 bits)
+	 * DDI[1]: bits 6 - 14  (2nd level) (9 bits)
+	 * DDI[2]: bits 15 - 23 (3rd level) (9 bits)
+	 */
+	if (base_format) {
+		ddi_bits[0] = 7;
+		ddi_bits[1] = 7 + 9;
+		ddi_bits[2] = 7 + 9 + 8;
+	} else {
+		ddi_bits[0] = 6;
+		ddi_bits[1] = 6 + 9;
+		ddi_bits[2] = 6 + 9 + 9;
+	}
+
+	/* Make sure device id is within range */
+	depth = iommu->ddt_mode - RISCV_IOMMU_DDTP_MODE_1LVL;
+	if (devid >= (1 << ddi_bits[depth]))
+		return NULL;
+
+	/* Get to the level of the non-leaf node that holds the device context */
+	for (ddtp = iommu->ddt_root; depth-- > 0;) {
+		const int split = ddi_bits[depth];
+		/*
+		 * Each non-leaf node is 64bits wide and on each level
+		 * nodes are indexed by DDI[depth].
+		 */
+		ddtp += (devid >> split) & 0x1FF;
+
+		/*
+		 * Check if this node has been populated and if not
+		 * allocate a new level and populate it.
+		 */
+		do {
+			ddt = READ_ONCE(*(unsigned long *)ddtp);
+			if (ddt & RISCV_IOMMU_DDTE_VALID) {
+				ddtp = __va(ppn_to_phys(ddt));
+				break;
+			}
+
+			ptr = riscv_iommu_get_pages(iommu, 0);
+			if (!ptr)
+				return NULL;
+
+			new = phys_to_ppn(__pa(ptr)) | RISCV_IOMMU_DDTE_VALID;
+			old = cmpxchg_relaxed((unsigned long *)ddtp, ddt, new);
+
+			if (old == ddt) {
+				ddtp = (u64 *)ptr;
+				break;
+			}
+
+			/* Race setting DDT detected, re-read and retry. */
+			riscv_iommu_free_pages(iommu, ptr);
+		} while (1);
+	}
+
+	/*
+	 * Grab the node that matches DDI[depth], note that when using base
+	 * format the device context is 4 * 64bits, and the extended format
+	 * is 8 * 64bits, hence the (3 - base_format) below.
+	 */
+	ddtp += (devid & ((64 << base_format) - 1)) << (3 - base_format);
+
+	return (struct riscv_iommu_dc *)ddtp;
+}
+
 /*
  * This is best effort IOMMU translation shutdown flow.
  * Disable IOMMU without waiting for hardware response.
@@ -37,10 +188,198 @@ static void riscv_iommu_disable(struct riscv_iommu_device *iommu)
 	riscv_iommu_writel(iommu, RISCV_IOMMU_REG_PQCSR, 0);
 }
 
-static int riscv_iommu_attach_identity_domain(struct iommu_domain *domain,
+#define riscv_iommu_read_ddtp(iommu) ({ \
+	u64 ddtp; \
+	riscv_iommu_readq_timeout((iommu), RISCV_IOMMU_REG_DDTP, ddtp, \
+				  !(ddtp & RISCV_IOMMU_DDTP_BUSY), 10, \
+				  RISCV_IOMMU_DDTP_TIMEOUT); \
+	ddtp; })
+
+static int riscv_iommu_iodir_alloc(struct riscv_iommu_device *iommu)
+{
+	u64 ddtp;
+	unsigned int mode;
+
+	ddtp = riscv_iommu_read_ddtp(iommu);
+	if (ddtp & RISCV_IOMMU_DDTP_BUSY)
+		return -EBUSY;
+
+	/*
+	 * It is optional for the hardware to report a fixed address for device
+	 * directory root page when DDT.MODE is OFF or BARE.
+	 */
+	mode = FIELD_GET(RISCV_IOMMU_DDTP_MODE, ddtp);
+	if (mode == RISCV_IOMMU_DDTP_MODE_BARE || mode == RISCV_IOMMU_DDTP_MODE_OFF) {
+		/* Use WARL to discover hardware fixed DDT PPN */
+		riscv_iommu_writeq(iommu, RISCV_IOMMU_REG_DDTP,
+				   FIELD_PREP(RISCV_IOMMU_DDTP_MODE, mode));
+		ddtp = riscv_iommu_read_ddtp(iommu);
+		if (ddtp & RISCV_IOMMU_DDTP_BUSY)
+			return -EBUSY;
+
+		iommu->ddt_phys = ppn_to_phys(ddtp);
+		if (iommu->ddt_phys)
+			iommu->ddt_root = devm_ioremap(iommu->dev, iommu->ddt_phys, PAGE_SIZE);
+		if (iommu->ddt_root)
+			memset(iommu->ddt_root, 0, PAGE_SIZE);
+	}
+
+	if (!iommu->ddt_root) {
+		iommu->ddt_root = riscv_iommu_get_pages(iommu, 0);
+		iommu->ddt_phys = __pa(iommu->ddt_root);
+	}
+
+	if (!iommu->ddt_root)
+		return -ENOMEM;
+
+	return 0;
+}
+
+/*
+ * Discover supported DDT modes starting from requested value,
+ * configure DDTP register with accepted mode and root DDT address.
+ * Accepted iommu->ddt_mode is updated on success.
+ */
+static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu,
+				      unsigned int ddtp_mode)
+{
+	struct device *dev = iommu->dev;
+	u64 ddtp, rq_ddtp;
+	unsigned int mode, rq_mode = ddtp_mode;
+
+	ddtp = riscv_iommu_read_ddtp(iommu);
+	if (ddtp & RISCV_IOMMU_DDTP_BUSY)
+		return -EBUSY;
+
+	/* Disallow state transition from xLVL to xLVL. */
+	mode = FIELD_GET(RISCV_IOMMU_DDTP_MODE, ddtp);
+	if (mode != RISCV_IOMMU_DDTP_MODE_BARE && rq_mode != RISCV_IOMMU_DDTP_MODE_BARE &&
+	    mode != RISCV_IOMMU_DDTP_MODE_OFF && rq_mode != RISCV_IOMMU_DDTP_MODE_OFF)
+		return -EINVAL;
+
+	do {
+		rq_ddtp = FIELD_PREP(RISCV_IOMMU_DDTP_MODE, rq_mode);
+		if (rq_mode > RISCV_IOMMU_DDTP_MODE_BARE)
+			rq_ddtp |= phys_to_ppn(iommu->ddt_phys);
+
+		riscv_iommu_writeq(iommu, RISCV_IOMMU_REG_DDTP, rq_ddtp);
+		ddtp = riscv_iommu_read_ddtp(iommu);
+		if (ddtp & RISCV_IOMMU_DDTP_BUSY) {
+			dev_err(dev, "timeout when setting ddtp (ddt mode: %u, read: %llx)\n",
+				rq_mode, ddtp);
+			return -EBUSY;
+		}
+
+		/* Verify IOMMU hardware accepts new DDTP config. */
+		mode = FIELD_GET(RISCV_IOMMU_DDTP_MODE, ddtp);
+
+		if (rq_mode == mode)
+			break;
+
+		/* Hardware mandatory DDTP mode has not been accepted. */
+		if (rq_mode < RISCV_IOMMU_DDTP_MODE_1LVL && rq_ddtp != ddtp) {
+			dev_err(dev, "DDTP update failed hw: %llx vs %llx\n", ddtp, rq_ddtp);
+			return -EINVAL;
+		}
+
+		/*
+		 * Mode field is WARL, an IOMMU may support a subset of
+		 * directory table levels in which case if we tried to set
+		 * an unsupported number of levels we'll readback either
+		 * a valid xLVL or off/bare. If we got off/bare, try again
+		 * with a smaller xLVL.
+		 */
+		if (mode < RISCV_IOMMU_DDTP_MODE_1LVL && rq_mode > RISCV_IOMMU_DDTP_MODE_1LVL) {
+			dev_dbg(dev, "DDTP hw mode %u vs %u\n", mode, rq_mode);
+			rq_mode--;
+			continue;
+		}
+
+		/*
+		 * We tried all supported modes and IOMMU hardware failed to
+		 * accept new settings, something went very wrong since off/bare
+		 * and at least one xLVL must be supported.
+		 */
+		dev_err(dev, "DDTP hw mode %u, failed to set %u\n", mode, ddtp_mode);
+		return -EINVAL;
+	} while (1);
+
+	iommu->ddt_mode = mode;
+	if (mode != ddtp_mode)
+		dev_dbg(dev, "DDTP hw mode %u, requested %u\n", mode, ddtp_mode);
+
+	return 0;
+}
+
+#define RISCV_IOMMU_FSC_BARE 0
+
+/*
+ * Update IODIR for the device.
+ *
+ * During the execution of riscv_iommu_probe_device(), IODIR entries are
+ * allocated for the device's identifiers.  Device context invalidation
+ * becomes necessary only if one of the updated entries was previously
+ * marked as valid, given that invalid device context entries are not
+ * cached by the IOMMU hardware.
+ * In this implementation, updating a valid device context while the
+ * device is not quiesced might be disruptive, potentially causing
+ * interim translation faults.
+ */
+static void riscv_iommu_iodir_update(struct riscv_iommu_device *iommu,
+				     struct device *dev, u64 fsc, u64 ta)
+{
+	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
+	struct riscv_iommu_dc *dc;
+	u64 tc;
+	int i;
+
+	/* Device context invalidation ignored for now. */
+
+	/*
+	 * For device context with DC_TC_PDTV = 0, translation attributes valid bit
+	 * is stored as DC_TC_V bit (both sharing the same location at BIT(0))..
+	 */
+	for (i = 0; i < fwspec->num_ids; i++) {
+		dc = riscv_iommu_get_dc(iommu, fwspec->ids[i]);
+		tc = READ_ONCE(dc->tc);
+		tc |= ta & RISCV_IOMMU_DC_TC_V;
+
+		/* Update device context, write TC.V as the last step. */
+		WRITE_ONCE(dc->fsc, fsc);
+		WRITE_ONCE(dc->ta, ta & RISCV_IOMMU_PC_TA_PSCID);
+		WRITE_ONCE(dc->tc, tc);
+	}
+}
+
+static int riscv_iommu_attach_release_domain(struct iommu_domain *iommu_domain,
+					     struct device *dev)
+{
+	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+
+	if (iommu->ddt_mode > RISCV_IOMMU_DDTP_MODE_BARE)
+		riscv_iommu_iodir_update(iommu, dev, RISCV_IOMMU_FSC_BARE, 0);
+
+	return 0;
+}
+
+static struct iommu_domain riscv_iommu_release_domain = {
+	.type = IOMMU_DOMAIN_BLOCKED,
+	.ops = &(const struct iommu_domain_ops) {
+		.attach_dev = riscv_iommu_attach_release_domain,
+	}
+};
+
+static int riscv_iommu_attach_identity_domain(struct iommu_domain *iommu_domain,
 					      struct device *dev)
 {
-	/* Global pass-through already enabled, do nothing for now. */
+	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+
+	/* Global pass-through already enabled, do nothing. */
+	if (iommu->ddt_mode == RISCV_IOMMU_DDTP_MODE_BARE)
+		return 0;
+
+	riscv_iommu_iodir_update(iommu, dev, RISCV_IOMMU_FSC_BARE, RISCV_IOMMU_PC_TA_V);
+
 	return 0;
 }
 
@@ -72,6 +411,9 @@ static struct iommu_device *riscv_iommu_probe_device(struct device *dev)
 {
 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 	struct riscv_iommu_device *iommu;
+	struct riscv_iommu_dc *dc;
+	u64 tc;
+	int i;
 
 	if (!fwspec->iommu_fwnode->dev || !fwspec->num_ids)
 		return ERR_PTR(-ENODEV);
@@ -80,12 +422,31 @@ static struct iommu_device *riscv_iommu_probe_device(struct device *dev)
 	if (!iommu)
 		return ERR_PTR(-ENODEV);
 
+	if (iommu->ddt_mode > RISCV_IOMMU_DDTP_MODE_BARE) {
+		/*
+		 * Allocate and pre-configure device context entries in
+		 * the device directory. Do not mark the context valid yet.
+		 */
+		tc = 0;
+		if (iommu->caps & RISCV_IOMMU_CAP_AMO_HWAD)
+			tc |= RISCV_IOMMU_DC_TC_SADE;
+		for (i = 0; i < fwspec->num_ids; i++) {
+			dc = riscv_iommu_get_dc(iommu, fwspec->ids[i]);
+			if (!dc)
+				return ERR_PTR(-ENODEV);
+			if (READ_ONCE(dc->tc) & RISCV_IOMMU_DC_TC_V)
+				dev_warn(dev, "already attached to IOMMU device directory\n");
+			WRITE_ONCE(dc->tc, tc);
+		}
+	}
+
 	return &iommu->iommu;
 }
 
 static const struct iommu_ops riscv_iommu_ops = {
 	.of_xlate = riscv_iommu_of_xlate,
 	.identity_domain = &riscv_iommu_identity_domain,
+	.release_domain = &riscv_iommu_release_domain,
 	.def_domain_type = riscv_iommu_device_domain_type,
 	.device_group = riscv_iommu_device_group,
 	.probe_device = riscv_iommu_probe_device,
@@ -128,6 +489,7 @@ void riscv_iommu_remove(struct riscv_iommu_device *iommu)
 {
 	iommu_device_unregister(&iommu->iommu);
 	iommu_device_sysfs_remove(&iommu->iommu);
+	riscv_iommu_iodir_set_mode(iommu, RISCV_IOMMU_DDTP_MODE_OFF);
 }
 
 int riscv_iommu_init(struct riscv_iommu_device *iommu)
@@ -138,12 +500,13 @@ int riscv_iommu_init(struct riscv_iommu_device *iommu)
 	if (rc)
 		return dev_err_probe(iommu->dev, rc, "unexpected device state\n");
 
-	/*
-	 * Placeholder for a complete IOMMU device initialization.
-	 * For now, only bare minimum: enable global identity mapping mode and register sysfs.
-	 */
-	riscv_iommu_writeq(iommu, RISCV_IOMMU_REG_DDTP,
-			   FIELD_PREP(RISCV_IOMMU_DDTP_MODE, RISCV_IOMMU_DDTP_MODE_BARE));
+	rc = riscv_iommu_iodir_alloc(iommu);
+	if (rc)
+		goto err_init;
+
+	rc = riscv_iommu_iodir_set_mode(iommu, RISCV_IOMMU_DDTP_MODE_MAX);
+	if (rc)
+		goto err_init;
 
 	rc = iommu_device_sysfs_add(&iommu->iommu, NULL, NULL, "riscv-iommu@%s",
 				    dev_name(iommu->dev));
@@ -163,5 +526,7 @@ int riscv_iommu_init(struct riscv_iommu_device *iommu)
 err_iommu:
 	iommu_device_sysfs_remove(&iommu->iommu);
 err_sysfs:
+	riscv_iommu_iodir_set_mode(iommu, RISCV_IOMMU_DDTP_MODE_OFF);
+err_init:
 	return rc;
 }
drivers/iommu/riscv/iommu.h +5 -0
index 700e33dc2446..f1696926582c 100644
@@ -34,6 +34,11 @@ struct riscv_iommu_device {
 	/* available interrupt numbers, MSI or WSI */
 	unsigned int irqs[RISCV_IOMMU_INTR_COUNT];
 	unsigned int irqs_count;
+
+	/* device directory */
+	unsigned int ddt_mode;
+	dma_addr_t ddt_phys;
+	u64 *ddt_root;
 };
 
 int riscv_iommu_init(struct riscv_iommu_device *iommu);
Signature · 1 line
2.34.1
#16 lore raw

Re: [PATCH v3 5/7] iommu/riscv: Device directory management.

Quoted 8 lines · Tomasz Jeznach

Introduce device context allocation and device directory tree management including capabilities discovery sequence, as described in Chapter 2.1 of the RISC-V IOMMU Architecture Specification.

Device directory mode will be auto detected using DDTP WARL property, using highest mode supported by the driver and hardware. If none supported can be configured, driver will fall back to global pass-through.

Quoted 5 lines

First level DDTP page can be located in I/O (detected using DDTP WARL) and system memory.

Only simple identity and release (blocking) protection domains are supported by this implementation.

Why rename the concept? We call it a BLOCKING domain, just use that name please.

Quoted 7 lines
drivers/iommu/riscv/iommu.c +7 -0
+static int riscv_iommu_attach_release_domain(struct iommu_domain *iommu_domain,
+					     struct device *dev)
+{
+	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+
+	if (iommu->ddt_mode > RISCV_IOMMU_DDTP_MODE_BARE)
+		riscv_iommu_iodir_update(iommu, dev, RISCV_IOMMU_FSC_BARE, 0);

drivers/iommu/riscv/iommu.c static void riscv_iommu_disable(struct riscv_iommu_device *iommu) · line 370

Quoted 10 lines
drivers/iommu/riscv/iommu.c +10 -0
+
+	return 0;
+}
+
+static struct iommu_domain riscv_iommu_release_domain = {
+	.type = IOMMU_DOMAIN_BLOCKED,
+	.ops = &(const struct iommu_domain_ops) {
+		.attach_dev = riscv_iommu_attach_release_domain,
+	}
+};

'riscv_iommu_release_domain' doesn't make sense..

Jason

#17 lore raw

Re: [PATCH v3 5/7] iommu/riscv: Device directory management.

In reply to Tomasz Jeznach
Quoted 18 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c +1 -6
@@ -128,6 +489,7 @@ void riscv_iommu_remove(struct riscv_iommu_device *iommu)
  {
  	iommu_device_unregister(&iommu->iommu);
  	iommu_device_sysfs_remove(&iommu->iommu);
+	riscv_iommu_iodir_set_mode(iommu, RISCV_IOMMU_DDTP_MODE_OFF);
  }
 
  int riscv_iommu_init(struct riscv_iommu_device *iommu)
@@ -138,12 +500,13 @@ int riscv_iommu_init(struct riscv_iommu_device *iommu)
  	if (rc)
  		return dev_err_probe(iommu->dev, rc, "unexpected device state\n");
 
-	/*
-	 * Placeholder for a complete IOMMU device initialization.
-	 * For now, only bare minimum: enable global identity mapping mode and register sysfs.
-	 */
-	riscv_iommu_writeq(iommu, RISCV_IOMMU_REG_DDTP,
-			   FIELD_PREP(RISCV_IOMMU_DDTP_MODE, RISCV_IOMMU_DDTP_MODE_BARE));

drivers/iommu/riscv/iommu.c int riscv_iommu_init(struct riscv_iommu_device *iommu) · line 512

Quoted 10 lines
drivers/iommu/riscv/iommu.c +7 -0
+	rc = riscv_iommu_iodir_alloc(iommu);
+	if (rc)
+		goto err_init;
+
+	rc = riscv_iommu_iodir_set_mode(iommu, RISCV_IOMMU_DDTP_MODE_MAX);
+	if (rc)
+		goto err_init;
 
  	rc = iommu_device_sysfs_add(&iommu->iommu, NULL, NULL, "riscv-iommu@%s",
  				    dev_name(iommu->dev));

The device directory root page might be allocated in riscv_iommu_iodir_alloc(),

+ if (!iommu->ddt_root) {
+ iommu->ddt_root = riscv_iommu_get_pages(iommu, 0);
+ iommu->ddt_phys = __pa(iommu->ddt_root);
+ }

But I didn't find any place to free it in the error paths. Did I overlook anything?

Best regards,
baolu

#18 lore raw

Re: [PATCH v3 5/7] iommu/riscv: Device directory management.

Quoted 34 lines · Baolu Lu
Quoted 21 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c +1 -3
@@ -128,6 +489,7 @@ void riscv_iommu_remove(struct riscv_iommu_device 
 *iommu)
   {
       iommu_device_unregister(&iommu->iommu);
       iommu_device_sysfs_remove(&iommu->iommu);
+    riscv_iommu_iodir_set_mode(iommu, RISCV_IOMMU_DDTP_MODE_OFF);
   }
   int riscv_iommu_init(struct riscv_iommu_device *iommu)
@@ -138,12 +500,13 @@ int riscv_iommu_init(struct riscv_iommu_device 
 *iommu)
       if (rc)
           return dev_err_probe(iommu->dev, rc, "unexpected device state\n");
-    /*
-     * Placeholder for a complete IOMMU device initialization.
-     * For now, only bare minimum: enable global identity mapping 

mode and register sysfs.
-     */
-    riscv_iommu_writeq(iommu, RISCV_IOMMU_REG_DDTP, -               FIELD_PREP(RISCV_IOMMU_DDTP_MODE, RISCV_IOMMU_DDTP_MODE_BARE));
+    rc = riscv_iommu_iodir_alloc(iommu);

Quoted 8 lines

+    if (rc)
+        goto err_init;
+
+    rc = riscv_iommu_iodir_set_mode(iommu, RISCV_IOMMU_DDTP_MODE_MAX); +    if (rc)
+        goto err_init;
      rc = iommu_device_sysfs_add(&iommu->iommu, NULL, NULL, "riscv-iommu@%s", dev_name(iommu->dev));

The device directory root page might be allocated in riscv_iommu_iodir_alloc(),

Quoted 7 lines

+    if (!iommu->ddt_root) {
+        iommu->ddt_root = riscv_iommu_get_pages(iommu, 0); +        iommu->ddt_phys = __pa(iommu->ddt_root); +    }

But I didn't find any place to free it in the error paths. Did I overlook anything?

I found the answer by myself. devres_alloc() is used so the page memory resources are managed by the driver core automatically. Please ignore the above comment.

Not sure about the pages for paging domain. If all pages release is deferred, it may cause big memory consumption. We have a trade-off here. On one hand, this might speed up the domain mapping since all pages might be preallocated; on the other hand, it will cost more memory.

Best regards,
baolu

Reviewed-by on v3 5/7
#19 lore raw

Re: [PATCH v3 5/7] iommu/riscv: Device directory management.

In reply to Tomasz Jeznach
Quoted 11 lines · Tomasz Jeznach

Introduce device context allocation and device directory tree management including capabilities discovery sequence, as described in Chapter 2.1 of the RISC-V IOMMU Architecture Specification.

Device directory mode will be auto detected using DDTP WARL property, using highest mode supported by the driver and hardware. If none supported can be configured, driver will fall back to global pass-through.

First level DDTP page can be located in I/O (detected using DDTP WARL) and system memory.

Quoted 6 lines

Only simple identity and release (blocking) protection domains are supported by this implementation.

Best regards,
baolu

#20 lore raw

PATCH v3 6/7 iommu/riscv: Command and fault queue support

In reply to Tomasz Jeznach

Introduce device command submission and fault reporting queues, as described in Chapter 3.1 and 3.2 of the RISC-V IOMMU Architecture Specification.

Command and fault queues are instantiated in contiguous system memory local to IOMMU device domain, or mapped from fixed I/O space provided by the hardware implementation. Detection of the location and maximum allowed size of the queue utilize WARL properties of queue base control register. Driver implementation will try to allocate up to 128KB of system memory, while respecting hardware supported maximum queue size.

Interrupts allocation is based on interrupt vectors availability and distributed to all queues in simple round-robin fashion. For hardware Implementation with fixed event type to interrupt vector assignment IVEC WARL property is used to discover such mappings.

Address translation, command and queue fault handling in this change is limited to simple fault reporting without taking any action.

---
 drivers/iommu/riscv/iommu-bits.h |  75 +++++
 drivers/iommu/riscv/iommu.c      | 481 ++++++++++++++++++++++++++++++-
 drivers/iommu/riscv/iommu.h      |  21 ++
 3 files changed, 576 insertions(+), 1 deletion(-)
drivers/iommu/riscv/iommu-bits.h +75 -0
index ba093c29de9f..40c379222821 100644
@@ -704,4 +704,79 @@ struct riscv_iommu_msi_pte {
 #define RISCV_IOMMU_MSI_MRIF_NPPN	RISCV_IOMMU_PPN_FIELD
 #define RISCV_IOMMU_MSI_MRIF_NID_MSB	BIT_ULL(60)
 
+/* Helper functions: command structure builders. */
+
+static inline void riscv_iommu_cmd_inval_vma(struct riscv_iommu_command *cmd)
+{
+	cmd->dword0 = FIELD_PREP(RISCV_IOMMU_CMD_OPCODE, RISCV_IOMMU_CMD_IOTINVAL_OPCODE) |
+		      FIELD_PREP(RISCV_IOMMU_CMD_FUNC, RISCV_IOMMU_CMD_IOTINVAL_FUNC_VMA);
+	cmd->dword1 = 0;
+}
+
+static inline void riscv_iommu_cmd_inval_set_addr(struct riscv_iommu_command *cmd,
+						  u64 addr)
+{
+	cmd->dword1 = FIELD_PREP(RISCV_IOMMU_CMD_IOTINVAL_ADDR, phys_to_pfn(addr));
+	cmd->dword0 |= RISCV_IOMMU_CMD_IOTINVAL_AV;
+}
+
+static inline void riscv_iommu_cmd_inval_set_pscid(struct riscv_iommu_command *cmd,
+						   int pscid)
+{
+	cmd->dword0 |= FIELD_PREP(RISCV_IOMMU_CMD_IOTINVAL_PSCID, pscid) |
+		       RISCV_IOMMU_CMD_IOTINVAL_PSCV;
+}
+
+static inline void riscv_iommu_cmd_inval_set_gscid(struct riscv_iommu_command *cmd,
+						   int gscid)
+{
+	cmd->dword0 |= FIELD_PREP(RISCV_IOMMU_CMD_IOTINVAL_GSCID, gscid) |
+		       RISCV_IOMMU_CMD_IOTINVAL_GV;
+}
+
+static inline void riscv_iommu_cmd_iofence(struct riscv_iommu_command *cmd)
+{
+	cmd->dword0 = FIELD_PREP(RISCV_IOMMU_CMD_OPCODE, RISCV_IOMMU_CMD_IOFENCE_OPCODE) |
+		      FIELD_PREP(RISCV_IOMMU_CMD_FUNC, RISCV_IOMMU_CMD_IOFENCE_FUNC_C) |
+		      RISCV_IOMMU_CMD_IOFENCE_PR | RISCV_IOMMU_CMD_IOFENCE_PW;
+	cmd->dword1 = 0;
+}
+
+static inline void riscv_iommu_cmd_iofence_set_av(struct riscv_iommu_command *cmd,
+						  u64 addr, u32 data)
+{
+	cmd->dword0 = FIELD_PREP(RISCV_IOMMU_CMD_OPCODE, RISCV_IOMMU_CMD_IOFENCE_OPCODE) |
+		      FIELD_PREP(RISCV_IOMMU_CMD_FUNC, RISCV_IOMMU_CMD_IOFENCE_FUNC_C) |
+		      FIELD_PREP(RISCV_IOMMU_CMD_IOFENCE_DATA, data) |
+		      RISCV_IOMMU_CMD_IOFENCE_AV;
+	cmd->dword1 = addr >> 2;
+}
+
+static inline void riscv_iommu_cmd_iodir_inval_ddt(struct riscv_iommu_command *cmd)
+{
+	cmd->dword0 = FIELD_PREP(RISCV_IOMMU_CMD_OPCODE, RISCV_IOMMU_CMD_IODIR_OPCODE) |
+		      FIELD_PREP(RISCV_IOMMU_CMD_FUNC, RISCV_IOMMU_CMD_IODIR_FUNC_INVAL_DDT);
+	cmd->dword1 = 0;
+}
+
+static inline void riscv_iommu_cmd_iodir_inval_pdt(struct riscv_iommu_command *cmd)
+{
+	cmd->dword0 = FIELD_PREP(RISCV_IOMMU_CMD_OPCODE, RISCV_IOMMU_CMD_IODIR_OPCODE) |
+		      FIELD_PREP(RISCV_IOMMU_CMD_FUNC, RISCV_IOMMU_CMD_IODIR_FUNC_INVAL_PDT);
+	cmd->dword1 = 0;
+}
+
+static inline void riscv_iommu_cmd_iodir_set_did(struct riscv_iommu_command *cmd,
+						 unsigned int devid)
+{
+	cmd->dword0 |= FIELD_PREP(RISCV_IOMMU_CMD_IODIR_DID, devid) |
+		       RISCV_IOMMU_CMD_IODIR_DV;
+}
+
+static inline void riscv_iommu_cmd_iodir_set_pid(struct riscv_iommu_command *cmd,
+						 unsigned int pasid)
+{
+	cmd->dword0 |= FIELD_PREP(RISCV_IOMMU_CMD_IODIR_PID, pasid);
+}
+
 #endif /* _RISCV_IOMMU_BITS_H_ */
drivers/iommu/riscv/iommu.c +480 -1

540 lines not on this page · raw message

drivers/iommu/riscv/iommu.h +21 -0
index f1696926582c..03e0c45bc7e1 100644
@@ -17,6 +17,22 @@
 
 #include "iommu-bits.h"
 
+struct riscv_iommu_device;
+
+struct riscv_iommu_queue {
+	atomic_t prod;				/* unbounded producer allocation index */
+	atomic_t head;				/* unbounded shadow ring buffer consumer index */
+	atomic_t tail;				/* unbounded shadow ring buffer producer index */
+	unsigned int mask;			/* index mask, queue length - 1 */
+	unsigned int irq;			/* allocated interrupt number */
+	struct riscv_iommu_device *iommu;	/* iommu device handling the queue when active */
+	void *base;				/* ring buffer kernel pointer */
+	dma_addr_t phys;			/* ring buffer physical address */
+	u16 qbr;				/* base register offset, head and tail reference */
+	u16 qcr;				/* control and status register offset */
+	u8 qid;					/* queue identifier, same as RISCV_IOMMU_INTR_XX */
+};
+
 struct riscv_iommu_device {
 	/* iommu core interface */
 	struct iommu_device iommu;
@@ -34,6 +50,11 @@ struct riscv_iommu_device {
 	/* available interrupt numbers, MSI or WSI */
 	unsigned int irqs[RISCV_IOMMU_INTR_COUNT];
 	unsigned int irqs_count;
+	unsigned int ivec;
+
+	/* hardware queues */
+	struct riscv_iommu_queue cmdq;
+	struct riscv_iommu_queue fltq;
 
 	/* device directory */
 	unsigned int ddt_mode;
Signature · 1 line
2.34.1
Reviewed-by on v3 6/7
#21 lore raw

Re: [PATCH v3 6/7] iommu/riscv: Command and fault queue support

Quoted 16 lines · Tomasz Jeznach

Introduce device command submission and fault reporting queues, as described in Chapter 3.1 and 3.2 of the RISC-V IOMMU Architecture Specification.

Command and fault queues are instantiated in contiguous system memory local to IOMMU device domain, or mapped from fixed I/O space provided by the hardware implementation. Detection of the location and maximum allowed size of the queue utilize WARL properties of queue base control register. Driver implementation will try to allocate up to 128KB of system memory, while respecting hardware supported maximum queue size.

Interrupts allocation is based on interrupt vectors availability and distributed to all queues in simple round-robin fashion. For hardware Implementation with fixed event type to interrupt vector assignment IVEC WARL property is used to discover such mappings.

Quoted 4 lines

Address translation, command and queue fault handling in this change is limited to simple fault reporting without taking any action.

Best regards,
baolu

#22 lore raw

PATCH v3 7/7 iommu/riscv: Paging domain support

In reply to Tomasz Jeznach

Introduce first-stage address translation support.

Page table configured by the IOMMU driver will use the same format as the CPU’s MMU, and will fallback to identity translation if the page table format configured for the MMU is not supported by the IOMMU hardware.

This change introduces IOTINVAL.VMA command, required to invalidate any cached IOATC entries after mapping is updated and/or removed from the paging domain. Invalidations for the non-leaf page entries use IOTINVAL for all addresses assigned to the protection domain for hardware not supporting more granular non-leaf page table cache invalidations.

---
 drivers/iommu/riscv/iommu.c | 544 +++++++++++++++++++++++++++++++++++-
 1 file changed, 541 insertions(+), 3 deletions(-)
drivers/iommu/riscv/iommu.c +541 -3
index 98c325cb0591..60b146adfcbb 100644
@@ -40,6 +40,10 @@
 
 #define dev_to_iommu(dev) iommu_get_iommu_dev(dev, struct riscv_iommu_device, iommu)
 
+/* IOMMU PSCID allocation namespace. */
+static DEFINE_IDA(riscv_iommu_pscids);
+#define RISCV_IOMMU_MAX_PSCID		(BIT(20) - 1)
+
 /* Device resource-managed allocations */
 struct riscv_iommu_devres {
 	void *addr;
@@ -747,6 +751,136 @@ static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu,
 	return 0;
 }
 
+/* This struct contains protection domain specific IOMMU driver data. */
+struct riscv_iommu_domain {
+	struct iommu_domain domain;
+	struct list_head bonds;
+	spinlock_t lock;		/* protect bonds list updates. */
+	int pscid;
+	int numa_node;
+	int amo_enabled:1;
+	unsigned int pgd_mode;
+	unsigned long *pgd_root;
+};
+
+#define iommu_domain_to_riscv(iommu_domain) \
+	container_of(iommu_domain, struct riscv_iommu_domain, domain)
+
+#define dev_to_domain(dev) \
+	iommu_domain_to_riscv(dev_iommu_priv_get(dev))
+
+/* Linkage between an iommu_domain and attached devices. */
+struct riscv_iommu_bond {
+	struct list_head list;
+	struct rcu_head rcu;
+	struct device *dev;
+};
+
+static int riscv_iommu_bond_link(struct riscv_iommu_domain *domain, struct device *dev)
+{
+	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+	struct riscv_iommu_bond *bond;
+	struct list_head *bonds;
+	unsigned long flags;
+
+	bond = kzalloc(sizeof(*bond), GFP_KERNEL);
+	if (!bond)
+		return -ENOMEM;
+	bond->dev = dev;
+
+	/* List od devices attached to the domain are arranged based on managed IOMMU device */
+	spin_lock_irqsave(&domain->lock, flags);
+	list_for_each_rcu(bonds, &domain->bonds)
+		if (dev_to_iommu(list_entry(bonds, struct riscv_iommu_bond, list)->dev) == iommu)
+			break;
+	list_add_rcu(&bond->list, bonds);
+	spin_unlock_irqrestore(&domain->lock, flags);
+
+	return 0;
+}
+
+static void riscv_iommu_bond_unlink(struct riscv_iommu_domain *domain, struct device *dev)
+{
+	struct riscv_iommu_bond *bond, *found = NULL;
+	unsigned long flags;
+
+	if (!domain)
+		return;
+
+	spin_lock_irqsave(&domain->lock, flags);
+	list_for_each_entry_rcu(bond, &domain->bonds, list) {
+		if (bond->dev == dev) {
+			list_del_rcu(&bond->list);
+			found = bond;
+		}
+	}
+	spin_unlock_irqrestore(&domain->lock, flags);
+
+	/* Release and wait for all read-rcu critical sections have completed. */
+	kfree_rcu(found, rcu);
+	synchronize_rcu();
+}
+
+/*
+ * Send IOTLB.INVAL for whole address space for ranges larger than 2MB.
+ * This limit will be replaced with range invalidations, if supported by
+ * the hardware, when RISC-V IOMMU architecture specification update for
+ * range invalidations update will be available.
+ */
+#define RISCV_IOMMU_IOTLB_INVAL_LIMIT	(2 << 20)
+
+static void riscv_iommu_iotlb_inval(struct riscv_iommu_domain *domain,
+				    unsigned long start, unsigned long end)
+{
+	struct riscv_iommu_bond *bond;
+	struct riscv_iommu_device *iommu, *prev;
+	struct riscv_iommu_command cmd;
+	unsigned long len = end - start + 1;
+	unsigned long iova;
+
+	rcu_read_lock();
+
+	prev = NULL;
+	list_for_each_entry_rcu(bond, &domain->bonds, list) {
+		iommu = dev_to_iommu(bond->dev);
+
+		riscv_iommu_cmd_inval_vma(&cmd);
+		riscv_iommu_cmd_inval_set_pscid(&cmd, domain->pscid);
+		if (len && len >= RISCV_IOMMU_IOTLB_INVAL_LIMIT) {
+			for (iova = start; iova < end; iova += PAGE_SIZE) {
+				riscv_iommu_cmd_inval_set_addr(&cmd, iova);
+				riscv_iommu_cmd_send(iommu, &cmd, 0);
+			}
+		} else {
+			riscv_iommu_cmd_send(iommu, &cmd, 0);
+		}
+
+		/*
+		 * IOTLB invalidation request can be safely omitted if already sent
+		 * to the IOMMU for the same PSCID, and with domain->bonds list
+		 * arranged based on the device's IOMMU, it's sufficient to check
+		 * last device the invalidation was sent to.
+		 */
+		if (iommu == prev)
+			continue;
+
+		prev = iommu;
+		riscv_iommu_cmd_send(iommu, &cmd, 0);
+	}
+
+	prev = NULL;
+	list_for_each_entry_rcu(bond, &domain->bonds, list) {
+		iommu = dev_to_iommu(bond->dev);
+		if (iommu == prev)
+			continue;
+
+		prev = iommu;
+		riscv_iommu_cmd_iofence(&cmd);
+		riscv_iommu_cmd_send(iommu, &cmd, RISCV_IOMMU_QUEUE_TIMEOUT);
+	}
+	rcu_read_unlock();
+}
+
 #define RISCV_IOMMU_FSC_BARE 0
 
 /*
@@ -766,10 +900,29 @@ static void riscv_iommu_iodir_update(struct riscv_iommu_device *iommu,
 {
 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 	struct riscv_iommu_dc *dc;
+	struct riscv_iommu_command cmd;
+	bool sync_required = false;
 	u64 tc;
 	int i;
 
-	/* Device context invalidation ignored for now. */
+	for (i = 0; i < fwspec->num_ids; i++) {
+		dc = riscv_iommu_get_dc(iommu, fwspec->ids[i]);
+		tc = READ_ONCE(dc->tc);
+		if (tc & RISCV_IOMMU_DC_TC_V) {
+			WRITE_ONCE(dc->tc, tc & ~RISCV_IOMMU_DC_TC_V);
+
+			/* Invalidate device context cached values */
+			riscv_iommu_cmd_iodir_inval_ddt(&cmd);
+			riscv_iommu_cmd_iodir_set_did(&cmd, fwspec->ids[i]);
+			riscv_iommu_cmd_send(iommu, &cmd, 0);
+			sync_required = true;
+		}
+	}
+
+	if (sync_required) {
+		riscv_iommu_cmd_iofence(&cmd);
+		riscv_iommu_cmd_send(iommu, &cmd, RISCV_IOMMU_IOTINVAL_TIMEOUT);
+	}
 
 	/*
 	 * For device context with DC_TC_PDTV = 0, translation attributes valid bit
@@ -787,13 +940,389 @@ static void riscv_iommu_iodir_update(struct riscv_iommu_device *iommu,
 	}
 }
 
+/*
+ * IOVA page translation tree management.
+ */
+
+#define IOMMU_PAGE_SIZE_4K     BIT_ULL(12)
+#define IOMMU_PAGE_SIZE_2M     BIT_ULL(21)
+#define IOMMU_PAGE_SIZE_1G     BIT_ULL(30)
+#define IOMMU_PAGE_SIZE_512G   BIT_ULL(39)
+
+#define PT_SHIFT (PAGE_SHIFT - ilog2(sizeof(pte_t)))
+
+static void riscv_iommu_iotlb_flush_all(struct iommu_domain *iommu_domain)
+{
+	struct riscv_iommu_domain *domain = iommu_domain_to_riscv(iommu_domain);
+
+	riscv_iommu_iotlb_inval(domain, 0, ULONG_MAX);
+}
+
+static void riscv_iommu_iotlb_sync(struct iommu_domain *iommu_domain,
+				   struct iommu_iotlb_gather *gather)
+{
+	struct riscv_iommu_domain *domain = iommu_domain_to_riscv(iommu_domain);
+
+	riscv_iommu_iotlb_inval(domain, gather->start, gather->end);
+}
+
+static inline size_t get_page_size(size_t size)
+{
+	if (size >= IOMMU_PAGE_SIZE_512G)
+		return IOMMU_PAGE_SIZE_512G;
+	if (size >= IOMMU_PAGE_SIZE_1G)
+		return IOMMU_PAGE_SIZE_1G;
+	if (size >= IOMMU_PAGE_SIZE_2M)
+		return IOMMU_PAGE_SIZE_2M;
+	return IOMMU_PAGE_SIZE_4K;
+}
+
+#define _io_pte_present(pte)	((pte) & (_PAGE_PRESENT | _PAGE_PROT_NONE))
+#define _io_pte_leaf(pte)	((pte) & _PAGE_LEAF)
+#define _io_pte_none(pte)	((pte) == 0)
+#define _io_pte_entry(pn, prot)	((_PAGE_PFN_MASK & ((pn) << _PAGE_PFN_SHIFT)) | (prot))
+
+static void riscv_iommu_pte_free(struct riscv_iommu_domain *domain,
+				 unsigned long pte, struct list_head *freelist)
+{
+	unsigned long *ptr;
+	int i;
+
+	if (!_io_pte_present(pte) || _io_pte_leaf(pte))
+		return;
+
+	ptr = (unsigned long *)pfn_to_virt(__page_val_to_pfn(pte));
+
+	/* Recursively free all sub page table pages */
+	for (i = 0; i < PTRS_PER_PTE; i++) {
+		pte = READ_ONCE(ptr[i]);
+		if (!_io_pte_none(pte) && cmpxchg_relaxed(ptr + i, pte, 0) == pte)
+			riscv_iommu_pte_free(domain, pte, freelist);
+	}
+
+	if (freelist)
+		list_add_tail(&virt_to_page(ptr)->lru, freelist);
+	else
+		iommu_free_page(ptr);
+}
+
+static unsigned long *riscv_iommu_pte_alloc(struct riscv_iommu_domain *domain,
+					    unsigned long iova, size_t pgsize, gfp_t gfp)
+{
+	unsigned long *ptr = domain->pgd_root;
+	unsigned long pte, old;
+	int level = domain->pgd_mode - RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV39 + 2;
+	void *addr;
+
+	do {
+		const int shift = PAGE_SHIFT + PT_SHIFT * level;
+
+		ptr += ((iova >> shift) & (PTRS_PER_PTE - 1));
+		/*
+		 * Note: returned entry might be a non-leaf if there was existing mapping
+		 * with smaller granularity. Up to the caller to replace and invalidate.
+		 */
+		if (((size_t)1 << shift) == pgsize)
+			return ptr;
+pte_retry:
+		pte = READ_ONCE(*ptr);
+		/*
+		 * This is very likely incorrect as we should not be adding new mapping
+		 * with smaller granularity on top of existing 2M/1G mapping. Fail.
+		 */
+		if (_io_pte_present(pte) && _io_pte_leaf(pte))
+			return NULL;
+		/*
+		 * Non-leaf entry is missing, allocate and try to add to the page table.
+		 * This might race with other mappings, retry on error.
+		 */
+		if (_io_pte_none(pte)) {
+			addr = iommu_alloc_page_node(domain->numa_node, gfp);
+			if (!addr)
+				return NULL;
+			old = pte;
+			pte = _io_pte_entry(virt_to_pfn(addr), _PAGE_TABLE);
+			if (cmpxchg_relaxed(ptr, old, pte) != old) {
+				iommu_free_page(addr);
+				goto pte_retry;
+			}
+		}
+		ptr = (unsigned long *)pfn_to_virt(__page_val_to_pfn(pte));
+	} while (level-- > 0);
+
+	return NULL;
+}
+
+static unsigned long *riscv_iommu_pte_fetch(struct riscv_iommu_domain *domain,
+					    unsigned long iova, size_t *pte_pgsize)
+{
+	unsigned long *ptr = domain->pgd_root;
+	unsigned long pte;
+	int level = domain->pgd_mode - RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV39 + 2;
+
+	do {
+		const int shift = PAGE_SHIFT + PT_SHIFT * level;
+
+		ptr += ((iova >> shift) & (PTRS_PER_PTE - 1));
+		pte = READ_ONCE(*ptr);
+		if (_io_pte_present(pte) && _io_pte_leaf(pte)) {
+			*pte_pgsize = (size_t)1 << shift;
+			return ptr;
+		}
+		if (_io_pte_none(pte))
+			return NULL;
+		ptr = (unsigned long *)pfn_to_virt(__page_val_to_pfn(pte));
+	} while (level-- > 0);
+
+	return NULL;
+}
+
+static int riscv_iommu_map_pages(struct iommu_domain *iommu_domain,
+				 unsigned long iova, phys_addr_t phys,
+				 size_t pgsize, size_t pgcount, int prot,
+				 gfp_t gfp, size_t *mapped)
+{
+	struct riscv_iommu_domain *domain = iommu_domain_to_riscv(iommu_domain);
+	size_t size = 0;
+	size_t page_size = get_page_size(pgsize);
+	unsigned long *ptr;
+	unsigned long pte, old, pte_prot;
+	int rc = 0;
+	LIST_HEAD(freelist);
+
+	if (!(prot & IOMMU_WRITE))
+		pte_prot = _PAGE_BASE | _PAGE_READ;
+	else if (domain->amo_enabled)
+		pte_prot = _PAGE_BASE | _PAGE_READ | _PAGE_WRITE;
+	else
+		pte_prot = _PAGE_BASE | _PAGE_READ | _PAGE_WRITE | _PAGE_DIRTY;
+
+	while (pgcount) {
+		ptr = riscv_iommu_pte_alloc(domain, iova, page_size, gfp);
+		if (!ptr) {
+			rc = -ENOMEM;
+			break;
+		}
+
+		old = READ_ONCE(*ptr);
+		pte = _io_pte_entry(phys_to_pfn(phys), pte_prot);
+		if (cmpxchg_relaxed(ptr, old, pte) != old)
+			continue;
+
+		riscv_iommu_pte_free(domain, old, &freelist);
+
+		size += page_size;
+		iova += page_size;
+		phys += page_size;
+		--pgcount;
+	}
+
+	*mapped = size;
+
+	if (!list_empty(&freelist)) {
+		/*
+		 * In 1.0 spec version, the smallest scope we can use to invalidate
+		 * all levels of page table (i.e. leaf and non-leaf) is an
+		 * invalidate-all-PSCID IOTINVAL.VMA with AV=0. This will be updated
+		 * with hardware support for capability.NL (non-leaf) IOTINVAL command.
+		 */
+		riscv_iommu_iotlb_inval(domain, 0, ULONG_MAX);
+		iommu_put_pages_list(&freelist);
+	}
+
+	return rc;
+}
+
+static size_t riscv_iommu_unmap_pages(struct iommu_domain *iommu_domain,
+				      unsigned long iova, size_t pgsize, size_t pgcount,
+				      struct iommu_iotlb_gather *gather)
+{
+	struct riscv_iommu_domain *domain = iommu_domain_to_riscv(iommu_domain);
+	size_t size = pgcount << __ffs(pgsize);
+	unsigned long *ptr, old;
+	size_t unmapped = 0;
+	size_t pte_size;
+
+	while (unmapped < size) {
+		ptr = riscv_iommu_pte_fetch(domain, iova, &pte_size);
+		if (!ptr)
+			return unmapped;
+
+		/* partial unmap is not allowed, fail. */
+		if (iova & (pte_size - 1))
+			return unmapped;
+
+		old = READ_ONCE(*ptr);
+		if (cmpxchg_relaxed(ptr, old, 0) != old)
+			continue;
+
+		iommu_iotlb_gather_add_page(&domain->domain, gather, iova,
+					    pte_size);
+
+		iova += pte_size;
+		unmapped += pte_size;
+	}
+
+	return unmapped;
+}
+
+static phys_addr_t riscv_iommu_iova_to_phys(struct iommu_domain *iommu_domain, dma_addr_t iova)
+{
+	struct riscv_iommu_domain *domain = iommu_domain_to_riscv(iommu_domain);
+	unsigned long pte_size;
+	unsigned long *ptr;
+
+	ptr = riscv_iommu_pte_fetch(domain, iova, &pte_size);
+	if (_io_pte_none(*ptr) || !_io_pte_present(*ptr))
+		return 0;
+
+	return pfn_to_phys(__page_val_to_pfn(*ptr)) | (iova & (pte_size - 1));
+}
+
+static void riscv_iommu_free_paging_domain(struct iommu_domain *iommu_domain)
+{
+	struct riscv_iommu_domain *domain = iommu_domain_to_riscv(iommu_domain);
+	const unsigned long pfn = virt_to_pfn(domain->pgd_root);
+
+	WARN_ON(!list_empty(&domain->bonds));
+
+	if ((int)domain->pscid > 0)
+		ida_free(&riscv_iommu_pscids, domain->pscid);
+
+	riscv_iommu_pte_free(domain, _io_pte_entry(pfn, _PAGE_TABLE), NULL);
+	kfree(domain);
+}
+
+static bool riscv_iommu_pt_supported(struct riscv_iommu_device *iommu, int pgd_mode)
+{
+	switch (pgd_mode) {
+	case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV39:
+		return iommu->caps & RISCV_IOMMU_CAP_S_SV39;
+
+	case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV48:
+		return iommu->caps & RISCV_IOMMU_CAP_S_SV48;
+
+	case RISCV_IOMMU_DC_FSC_IOSATP_MODE_SV57:
+		return iommu->caps & RISCV_IOMMU_CAP_S_SV57;
+	}
+	return false;
+}
+
+static int riscv_iommu_attach_paging_domain(struct iommu_domain *iommu_domain,
+					    struct device *dev)
+{
+	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+	struct riscv_iommu_domain *domain = iommu_domain_to_riscv(iommu_domain);
+	u64 fsc, ta;
+
+	if (!riscv_iommu_pt_supported(iommu, domain->pgd_mode))
+		return -ENODEV;
+
+	if (domain->numa_node == NUMA_NO_NODE)
+		domain->numa_node = dev_to_node(iommu->dev);
+
+	if (riscv_iommu_bond_link(domain, dev))
+		return -ENOMEM;
+
+	/*
+	 * Invalidate PSCID.
+	 * This invalidation might be redundant if IOATC has been already cleared,
+	 * however we are not keeping track for domains not linked to a device.
+	 */
+	riscv_iommu_iotlb_inval(domain, 0, ULONG_MAX);
+
+	fsc = FIELD_PREP(RISCV_IOMMU_PC_FSC_MODE, domain->pgd_mode) |
+	      FIELD_PREP(RISCV_IOMMU_PC_FSC_PPN, virt_to_pfn(domain->pgd_root));
+	ta = FIELD_PREP(RISCV_IOMMU_PC_TA_PSCID, domain->pscid) | RISCV_IOMMU_PC_TA_V;
+
+	riscv_iommu_iodir_update(iommu, dev, fsc, ta);
+	riscv_iommu_bond_unlink(dev_to_domain(dev), dev);
+	dev_iommu_priv_set(dev, domain);
+
+	return 0;
+}
+
+static const struct iommu_domain_ops riscv_iommu_paging_domain_ops = {
+	.attach_dev = riscv_iommu_attach_paging_domain,
+	.free = riscv_iommu_free_paging_domain,
+	.map_pages = riscv_iommu_map_pages,
+	.unmap_pages = riscv_iommu_unmap_pages,
+	.iova_to_phys = riscv_iommu_iova_to_phys,
+	.iotlb_sync = riscv_iommu_iotlb_sync,
+	.flush_iotlb_all = riscv_iommu_iotlb_flush_all,
+};
+
+static struct iommu_domain *riscv_iommu_alloc_paging_domain(struct device *dev)
+{
+	struct riscv_iommu_domain *domain;
+	struct riscv_iommu_device *iommu;
+
+	iommu = dev ? dev_to_iommu(dev) : NULL;
+	domain = kzalloc(sizeof(*domain), GFP_KERNEL);
+	if (!domain)
+		return ERR_PTR(-ENOMEM);
+
+	INIT_LIST_HEAD_RCU(&domain->bonds);
+	spin_lock_init(&domain->lock);
+	domain->numa_node = NUMA_NO_NODE;
+
+	/*
+	 * Follow system address translation mode.
+	 * RISC-V IOMMU ATP mode values match RISC-V CPU SATP mode values.
+	 */
+	domain->pgd_mode = satp_mode >> SATP_MODE_SHIFT;
+	if (iommu) {
+		if (!riscv_iommu_pt_supported(iommu, domain->pgd_mode)) {
+			dev_err(dev, "unsupported page table mode %x\n", domain->pgd_mode);
+			kfree(domain);
+			return ERR_PTR(-ENODEV);
+		}
+		domain->numa_node = dev_to_node(iommu->dev);
+		domain->amo_enabled = !!(iommu->caps & RISCV_IOMMU_CAP_AMO_HWAD);
+	}
+
+	domain->pgd_root = iommu_alloc_page_node(domain->numa_node, GFP_KERNEL_ACCOUNT);
+	if (!domain->pgd_root) {
+		kfree(domain);
+		return ERR_PTR(-ENOMEM);
+	}
+
+	domain->pscid = ida_alloc_range(&riscv_iommu_pscids, 1, RISCV_IOMMU_MAX_PSCID, GFP_KERNEL);
+	if (domain->pscid < 0) {
+		iommu_free_page(domain->pgd_root);
+		kfree(domain);
+		return ERR_PTR(-ENOMEM);
+	}
+
+	/*
+	 * Note: RISC-V Privilege spec mandates that virtual addresses
+	 * need to be sign-extended, so if (VA_BITS - 1) is set, all
+	 * bits >= VA_BITS need to also be set or else we'll get a
+	 * page fault. However the code that creates the mappings
+	 * above us (e.g. iommu_dma_alloc_iova()) won't do that for us
+	 * for now, so we'll end up with invalid virtual addresses
+	 * to map. As a workaround until we get this sorted out
+	 * limit the available virtual addresses to VA_BITS - 1.
+	 */
+	domain->domain.geometry.aperture_start = 0;
+	domain->domain.geometry.aperture_end = DMA_BIT_MASK(VA_BITS - 1);
+	domain->domain.geometry.force_aperture = true;
+
+	domain->domain.ops = &riscv_iommu_paging_domain_ops;
+
+	return &domain->domain;
+}
+
 static int riscv_iommu_attach_release_domain(struct iommu_domain *iommu_domain,
 					     struct device *dev)
 {
 	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
 
-	if (iommu->ddt_mode > RISCV_IOMMU_DDTP_MODE_BARE)
+	if (iommu->ddt_mode > RISCV_IOMMU_DDTP_MODE_BARE) {
 		riscv_iommu_iodir_update(iommu, dev, RISCV_IOMMU_FSC_BARE, 0);
+		riscv_iommu_bond_unlink(dev_to_domain(dev), dev);
+		dev_iommu_priv_set(dev, NULL);
+	}
 
 	return 0;
 }
@@ -815,6 +1344,8 @@ static int riscv_iommu_attach_identity_domain(struct iommu_domain *iommu_domain,
 		return 0;
 
 	riscv_iommu_iodir_update(iommu, dev, RISCV_IOMMU_FSC_BARE, RISCV_IOMMU_PC_TA_V);
+	riscv_iommu_bond_unlink(dev_to_domain(dev), dev);
+	dev_iommu_priv_set(dev, NULL);
 
 	return 0;
 }
@@ -828,7 +1359,12 @@ static struct iommu_domain riscv_iommu_identity_domain = {
 
 static int riscv_iommu_device_domain_type(struct device *dev)
 {
-	return IOMMU_DOMAIN_IDENTITY;
+	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+
+	if (iommu->ddt_mode == RISCV_IOMMU_DDTP_MODE_BARE)
+		return IOMMU_DOMAIN_IDENTITY;
+
+	return 0;
 }
 
 static struct iommu_group *riscv_iommu_device_group(struct device *dev)
@@ -880,9 +1416,11 @@ static struct iommu_device *riscv_iommu_probe_device(struct device *dev)
 }
 
 static const struct iommu_ops riscv_iommu_ops = {
+	.pgsize_bitmap = SZ_4K,
 	.of_xlate = riscv_iommu_of_xlate,
 	.identity_domain = &riscv_iommu_identity_domain,
 	.release_domain = &riscv_iommu_release_domain,
+	.domain_alloc_paging = riscv_iommu_alloc_paging_domain,
 	.def_domain_type = riscv_iommu_device_domain_type,
 	.device_group = riscv_iommu_device_group,
 	.probe_device = riscv_iommu_probe_device,
Signature · 1 line
2.34.1
#23 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 770

Quoted 5 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c +5 -0
+#define iommu_domain_to_riscv(iommu_domain) \
+	container_of(iommu_domain, struct riscv_iommu_domain, domain)
+
+#define dev_to_domain(dev) \
+	iommu_domain_to_riscv(dev_iommu_priv_get(dev))

Please use the priv properly and put a struct around it, you'll certainly need this eventually to do the rest of the advanced features.

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 810

Quoted 9 lines
drivers/iommu/riscv/iommu.c +9 -0
+static void riscv_iommu_bond_unlink(struct riscv_iommu_domain *domain, struct device *dev)
+{
+	struct riscv_iommu_bond *bond, *found = NULL;
+	unsigned long flags;
+
+	if (!domain)
+		return;
+
+	spin_lock_irqsave(&domain->lock, flags);

This is never locked from an irq, you don't need to use the irqsave variations.

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 821

Quoted 11 lines
drivers/iommu/riscv/iommu.c +11 -0
+	list_for_each_entry_rcu(bond, &domain->bonds, list) {
+		if (bond->dev == dev) {
+			list_del_rcu(&bond->list);
+			found = bond;
+		}
+	}
+	spin_unlock_irqrestore(&domain->lock, flags);
+
+	/* Release and wait for all read-rcu critical sections have completed. */
+	kfree_rcu(found, rcu);
+	synchronize_rcu();

Please no, synchronize_rcu() on a path like this is not so reasonable.. Also you don't need kfree_rcu() if you write it like this.

This still looks better to do what I said before, put the iommu not the dev in the bond struct.

Quoted 9 lines
drivers/iommu/riscv/iommu.c +9 -0
+static struct iommu_domain *riscv_iommu_alloc_paging_domain(struct device *dev)
+{
+	struct riscv_iommu_domain *domain;
+	struct riscv_iommu_device *iommu;
+
+	iommu = dev ? dev_to_iommu(dev) : NULL;
+	domain = kzalloc(sizeof(*domain), GFP_KERNEL);
+	if (!domain)
+		return ERR_PTR(-ENOMEM);

drivers/iommu/riscv/iommu.c static void riscv_iommu_iodir_update(struct riscv_iommu_device *iommu, · line 1273

Quoted 10 lines
drivers/iommu/riscv/iommu.c +10 -0
+
+	INIT_LIST_HEAD_RCU(&domain->bonds);
+	spin_lock_init(&domain->lock);
+	domain->numa_node = NUMA_NO_NODE;
+
+	/*
+	 * Follow system address translation mode.
+	 * RISC-V IOMMU ATP mode values match RISC-V CPU SATP mode values.
+	 */
+	domain->pgd_mode = satp_mode >> SATP_MODE_SHIFT;

This seems really strange, the iommu paging domains should be unrelated to what the CPU is doing. There is no connection between these two concepts.

Just pick a size that the iommu supports.

The number of radix levels is a tunable alot of iommus have that we haven't really exposed to anything else yet.

drivers/iommu/riscv/iommu.c static void riscv_iommu_iodir_update(struct riscv_iommu_device *iommu, · line 1309

Quoted 13 lines
drivers/iommu/riscv/iommu.c +13 -0
+	/*
+	 * Note: RISC-V Privilege spec mandates that virtual addresses
+	 * need to be sign-extended, so if (VA_BITS - 1) is set, all
+	 * bits >= VA_BITS need to also be set or else we'll get a
+	 * page fault. However the code that creates the mappings
+	 * above us (e.g. iommu_dma_alloc_iova()) won't do that for us
+	 * for now, so we'll end up with invalid virtual addresses
+	 * to map. As a workaround until we get this sorted out
+	 * limit the available virtual addresses to VA_BITS - 1.
+	 */
+	domain->domain.geometry.aperture_start = 0;
+	domain->domain.geometry.aperture_end = DMA_BIT_MASK(VA_BITS - 1);
+	domain->domain.geometry.force_aperture = true;

Yikes.. This is probably the best solution long term anyhow, unless you need to use the last page in VFIO for some reason.

drivers/iommu/riscv/iommu.c static struct iommu_domain riscv_iommu_identity_domain = { · line 1366

Quoted 8 lines

static int riscv_iommu_device_domain_type(struct device *dev) {

drivers/iommu/riscv/iommu.c +5 -1
-	return IOMMU_DOMAIN_IDENTITY;
+	struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+
+	if (iommu->ddt_mode == RISCV_IOMMU_DDTP_MODE_BARE)
+		return IOMMU_DOMAIN_IDENTITY;
+

Is there even a point of binding an iommu driver if the HW can't support a DDT table? Just return -ENODEV from probe_device?

Logically a iommu block that can't decode the RID has no association at all with a Linux struct device :)

Jason

#24 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 13 lines · Jason Gunthorpe

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 770

Quoted 5 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c +5 -0
+#define iommu_domain_to_riscv(iommu_domain) \
+     container_of(iommu_domain, struct riscv_iommu_domain, domain)
+
+#define dev_to_domain(dev) \
+     iommu_domain_to_riscv(dev_iommu_priv_get(dev))

Please use the priv properly and put a struct around it, you'll certainly need this eventually to do the rest of the advanced features.

Done. Yes, indeed, I was going to introduce proper struct in follow up patches anyway. Pulled this change sooner.

Quoted 4 lines
Quoted 4 lines
drivers/iommu/riscv/iommu.c +4 -0
+static void riscv_iommu_bond_unlink(struct riscv_iommu_domain *domain, struct device *dev)
+{
+     struct riscv_iommu_bond *bond, *found = NULL;
+     unsigned long flags;
Quoted 9 lines

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 810

Quoted 5 lines
drivers/iommu/riscv/iommu.c +5 -0
+
+     if (!domain)
+             return;
+
+     spin_lock_irqsave(&domain->lock, flags);

This is never locked from an irq, you don't need to use the irqsave variations.

Good point. done in v4.

Quoted 12 lines

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 821

Quoted 11 lines
drivers/iommu/riscv/iommu.c +11 -0
+     list_for_each_entry_rcu(bond, &domain->bonds, list) {
+             if (bond->dev == dev) {
+                     list_del_rcu(&bond->list);
+                     found = bond;
+             }
+     }
+     spin_unlock_irqrestore(&domain->lock, flags);
+
+     /* Release and wait for all read-rcu critical sections have completed. */
+     kfree_rcu(found, rcu);
+     synchronize_rcu();
Quoted 7 lines

Please no, synchronize_rcu() on a path like this is not so reasonable.. Also you don't need kfree_rcu() if you write it like this.

This still looks better to do what I said before, put the iommu not the dev in the bond struct.

I was trying not to duplicate data in bond struct and use whatever is available to be referenced from dev pointer (eg iommu / ids / private iommu dev data). If I'm reading core iommu code correctly, device pointer and iommu pointers should be valid between _probe_device and _release_device calls. I've moved synchronize_rcu out of the domain attach path to _release_device, LMK if that would be ok for now. I'll have a second another to rework other patches to avoid storing dev pointers at all.

Quoted 24 lines
Quoted 9 lines
drivers/iommu/riscv/iommu.c +9 -0
+static struct iommu_domain *riscv_iommu_alloc_paging_domain(struct device *dev)
+{
+     struct riscv_iommu_domain *domain;
+     struct riscv_iommu_device *iommu;
+
+     iommu = dev ? dev_to_iommu(dev) : NULL;
+     domain = kzalloc(sizeof(*domain), GFP_KERNEL);
+     if (!domain)
+             return ERR_PTR(-ENOMEM);

drivers/iommu/riscv/iommu.c static void riscv_iommu_iodir_update(struct riscv_iommu_device *iommu, · line 1273

Quoted 10 lines
drivers/iommu/riscv/iommu.c +10 -0
+
+     INIT_LIST_HEAD_RCU(&domain->bonds);
+     spin_lock_init(&domain->lock);
+     domain->numa_node = NUMA_NO_NODE;
+
+     /*
+      * Follow system address translation mode.
+      * RISC-V IOMMU ATP mode values match RISC-V CPU SATP mode values.
+      */
+     domain->pgd_mode = satp_mode >> SATP_MODE_SHIFT;

This seems really strange, the iommu paging domains should be unrelated to what the CPU is doing. There is no connection between these two concepts.

Quoted 5 lines

Just pick a size that the iommu supports.

The number of radix levels is a tunable alot of iommus have that we haven't really exposed to anything else yet.

Makes sense. I've left an option to pick mode from MMU for cases where dev/iommu is not known at allocation time (with iommu_domain_alloc()). I'd guess it's reasonable to assume IOMMU supported page modes will match MMU.

Quoted 29 lines

drivers/iommu/riscv/iommu.c static void riscv_iommu_iodir_update(struct riscv_iommu_device *iommu, · line 1309

Quoted 13 lines
drivers/iommu/riscv/iommu.c +13 -0
+     /*
+      * Note: RISC-V Privilege spec mandates that virtual addresses
+      * need to be sign-extended, so if (VA_BITS - 1) is set, all
+      * bits >= VA_BITS need to also be set or else we'll get a
+      * page fault. However the code that creates the mappings
+      * above us (e.g. iommu_dma_alloc_iova()) won't do that for us
+      * for now, so we'll end up with invalid virtual addresses
+      * to map. As a workaround until we get this sorted out
+      * limit the available virtual addresses to VA_BITS - 1.
+      */
+     domain->domain.geometry.aperture_start = 0;
+     domain->domain.geometry.aperture_end = DMA_BIT_MASK(VA_BITS - 1);
+     domain->domain.geometry.force_aperture = true;

Yikes.. This is probably the best solution long term anyhow, unless you need to use the last page in VFIO for some reason.

drivers/iommu/riscv/iommu.c static struct iommu_domain riscv_iommu_identity_domain = { · line 1366

Quoted 8 lines

static int riscv_iommu_device_domain_type(struct device *dev) {

drivers/iommu/riscv/iommu.c +5 -1
-     return IOMMU_DOMAIN_IDENTITY;
+     struct riscv_iommu_device *iommu = dev_to_iommu(dev);
+
+     if (iommu->ddt_mode == RISCV_IOMMU_DDTP_MODE_BARE)
+             return IOMMU_DOMAIN_IDENTITY;
+

Is there even a point of binding an iommu driver if the HW can't support a DDT table? Just return -ENODEV from probe_device?

Quoted 3 lines

Logically a iommu block that can't decode the RID has no association at all with a Linux struct device :)

Done. Good point ;)

Thanks for review,
- Tomasz

Quoted 1 line

Jason

#25 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 15 lines · Tomasz Jeznach
Quoted 15 lines

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 821

Quoted 11 lines
drivers/iommu/riscv/iommu.c +11 -0
+     list_for_each_entry_rcu(bond, &domain->bonds, list) {
+             if (bond->dev == dev) {
+                     list_del_rcu(&bond->list);
+                     found = bond;
+             }
+     }
+     spin_unlock_irqrestore(&domain->lock, flags);
+
+     /* Release and wait for all read-rcu critical sections have completed. */
+     kfree_rcu(found, rcu);
+     synchronize_rcu();

Please no, synchronize_rcu() on a path like this is not so reasonable.. Also you don't need kfree_rcu() if you write it like this.

Quoted 8 lines
Quoted 4 lines

This still looks better to do what I said before, put the iommu not the dev in the bond struct.

I was trying not to duplicate data in bond struct and use whatever is available to be referenced from dev pointer (eg iommu / ids / private iommu dev data).

I'm not sure that is a valuable goal considering the RCU complexity.. But I suppose it would be a bit of a hassle to replicate the ids list into bond structurs. Maybe something to do when you get to ATS since you'll probably want to replicate the ATS RIDs. (see what Intel did, which I think is pretty good)

Quoted 6 lines

If I'm reading core iommu code correctly, device pointer and iommu pointers should be valid between _probe_device and _release_device calls. I've moved synchronize_rcu out of the domain attach path to _release_device, LMK if that would be ok for now. I'll have a second another to rework other patches to avoid storing dev pointers at all.

Yes, that seems better.. I'm happier to see device hot-unplug be slow than un attach

There is another issue with the RCU that I haven't wrapped my head around..

Technically we can have concurrent map/unmap/invalidation along side device attach/detach. Does the invalidation under RCU work correctly?

For detach I think yes:

Inv CPU Detach CPU

write io_pte Update device descriptor
rcu_read_lock
list_for_each
<make invalidation command> <make description inv cmd>
dma_wmb() dma_wmb()
<doorbell> <cmd doorbell>
rcu_read_unlock

                                             list_del_rcu()
                                             <wipe ASID>

In this case I think we never miss an invalidation, the list_del is always after the HW has been fully fenced, so I don't think we can have any issue. Maybe a suprious invalidation if the ASID gets re-used, but who cares.

Attach is different..

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() Update device descriptor <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

As above shows we can "miss" an invalidation. The issue is narrow, the io_pte could still be sitting in write buffers in "Inv CPU" and not yet globally visiable. "Attach CPU" could get the device descriptor installed in the IOMMU and the IOMMU could walk an io_pte that is in the old state. Effectively this is because there is no release/acquire barrier passing the io_pte store from the Inv CPU to the Attach CPU to the IOMMU.

It seems like it should be solvable somehow:
1) Inv CPU releases all the io ptes
2) Attach CPU acquires the io ptes before updating the DDT
3) Inv CPU acquires the RCU list in such a way that either attach CPU will acquire the io_pte or inv CPU will acquire the RCU list.
4) Either invalidation works or we release the new iopte to the SMMU and don't need it.

But #3 is a really weird statement. smb_mb() on both sides may do the job??

Quoted 7 lines
Quoted 2 lines

The number of radix levels is a tunable alot of iommus have that we haven't really exposed to anything else yet.

Makes sense. I've left an option to pick mode from MMU for cases where dev/iommu is not known at allocation time (with iommu_domain_alloc()). I'd guess it's reasonable to assume IOMMU supported page modes will match MMU.

Reasonable, but for this case you'd be best to have a global static that unifies the capability of all the iommu instances. Then you can pick the right thing from the installed iommus, and arguably, that is the right thing to do in all cases as we'd slightly prefer domains that work everywhere in that edge case.

Jason

#26 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 97 lines · Jason Gunthorpe
Quoted 15 lines · Tomasz Jeznach
Quoted 15 lines

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 821

Quoted 11 lines
drivers/iommu/riscv/iommu.c +11 -0
+     list_for_each_entry_rcu(bond, &domain->bonds, list) {
+             if (bond->dev == dev) {
+                     list_del_rcu(&bond->list);
+                     found = bond;
+             }
+     }
+     spin_unlock_irqrestore(&domain->lock, flags);
+
+     /* Release and wait for all read-rcu critical sections have completed. */
+     kfree_rcu(found, rcu);
+     synchronize_rcu();

Please no, synchronize_rcu() on a path like this is not so reasonable.. Also you don't need kfree_rcu() if you write it like this.

Quoted 8 lines
Quoted 4 lines

This still looks better to do what I said before, put the iommu not the dev in the bond struct.

I was trying not to duplicate data in bond struct and use whatever is available to be referenced from dev pointer (eg iommu / ids / private iommu dev data).

I'm not sure that is a valuable goal considering the RCU complexity.. But I suppose it would be a bit of a hassle to replicate the ids list into bond structurs. Maybe something to do when you get to ATS since you'll probably want to replicate the ATS RIDs. (see what Intel did, which I think is pretty good)

Quoted 6 lines

If I'm reading core iommu code correctly, device pointer and iommu pointers should be valid between _probe_device and _release_device calls. I've moved synchronize_rcu out of the domain attach path to _release_device, LMK if that would be ok for now. I'll have a second another to rework other patches to avoid storing dev pointers at all.

Yes, that seems better.. I'm happier to see device hot-unplug be slow than un attach

There is another issue with the RCU that I haven't wrapped my head around..

Technically we can have concurrent map/unmap/invalidation along side device attach/detach. Does the invalidation under RCU work correctly?

For detach I think yes:

Inv CPU Detach CPU

write io_pte Update device descriptor
rcu_read_lock
list_for_each
<make invalidation command> <make description inv cmd>
dma_wmb() dma_wmb()
<doorbell> <cmd doorbell>
rcu_read_unlock

                                             list_del_rcu()
                                             <wipe ASID>

In this case I think we never miss an invalidation, the list_del is always after the HW has been fully fenced, so I don't think we can have any issue. Maybe a suprious invalidation if the ASID gets re-used, but who cares.

Attach is different..

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() Update device descriptor <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

As above shows we can "miss" an invalidation. The issue is narrow, the io_pte could still be sitting in write buffers in "Inv CPU" and not yet globally visiable. "Attach CPU" could get the device descriptor installed in the IOMMU and the IOMMU could walk an io_pte that is in the old state. Effectively this is because there is no release/acquire barrier passing the io_pte store from the Inv CPU to the Attach CPU to the IOMMU.

It seems like it should be solvable somehow:
1) Inv CPU releases all the io ptes
2) Attach CPU acquires the io ptes before updating the DDT
3) Inv CPU acquires the RCU list in such a way that either attach CPU will acquire the io_pte or inv CPU will acquire the RCU list.
4) Either invalidation works or we release the new iopte to the SMMU and don't need it.

Quoted 3 lines

But #3 is a really weird statement. smb_mb() on both sides may do the job??

Actual attach sequence is slightly different.

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() IOTLB.INVAL(PSCID) <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

I've tried to cover this case with riscv_iommu_iotlb_inval() called before the attached domain is visible to the device. This is something to optimize to avoid invalidating the whole PSCID if the domain was already attached to the same IOMMU, but I'd leave it for a separate patch series.

Quoted 8 lines
Quoted 7 lines
Quoted 2 lines

The number of radix levels is a tunable alot of iommus have that we haven't really exposed to anything else yet.

Makes sense. I've left an option to pick mode from MMU for cases where dev/iommu is not known at allocation time (with iommu_domain_alloc()). I'd guess it's reasonable to assume IOMMU supported page modes will match MMU.

Quoted 6 lines

Reasonable, but for this case you'd be best to have a global static that unifies the capability of all the iommu instances. Then you can pick the right thing from the installed iommus, and arguably, that is the right thing to do in all cases as we'd slightly prefer domains that work everywhere in that edge case.

That is a viable option. If you're ok I'll address this as a separate patch. I've been trying to avoid adding more global variables, but it might not be avoidable.

Quoted 1 line

Jason

Best,
- Tomasz

#27 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 67 lines · Tomasz Jeznach
Quoted 49 lines

For detach I think yes:

Inv CPU Detach CPU

write io_pte Update device descriptor
rcu_read_lock
list_for_each
<make invalidation command> <make description inv cmd>
dma_wmb() dma_wmb()
<doorbell> <cmd doorbell>
rcu_read_unlock

                                             list_del_rcu()
                                             <wipe ASID>

In this case I think we never miss an invalidation, the list_del is always after the HW has been fully fenced, so I don't think we can have any issue. Maybe a suprious invalidation if the ASID gets re-used, but who cares.

Attach is different..

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() Update device descriptor <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

As above shows we can "miss" an invalidation. The issue is narrow, the io_pte could still be sitting in write buffers in "Inv CPU" and not yet globally visiable. "Attach CPU" could get the device descriptor installed in the IOMMU and the IOMMU could walk an io_pte that is in the old state. Effectively this is because there is no release/acquire barrier passing the io_pte store from the Inv CPU to the Attach CPU to the IOMMU.

It seems like it should be solvable somehow:
1) Inv CPU releases all the io ptes
2) Attach CPU acquires the io ptes before updating the DDT
3) Inv CPU acquires the RCU list in such a way that either attach CPU will acquire the io_pte or inv CPU will acquire the RCU list.
4) Either invalidation works or we release the new iopte to the SMMU and don't need it.

Quoted 3 lines

But #3 is a really weird statement. smb_mb() on both sides may do the job??

Actual attach sequence is slightly different.

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() IOTLB.INVAL(PSCID) <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

Quoted 2 lines

I've tried to cover this case with riscv_iommu_iotlb_inval() called before the attached domain is visible to the device.

That invalidation shouldn't do anything. If this is the first attach of a PSCID then the PSCID had better already be empty, it won't become non-empty until the DDT entry is installed.

And if it is the second attach then the Inv CPU is already taking care of things, no need to invalidate at all.

Regardless, there is still a theortical race that the IOPTEs haven't been made visible yet because there is still no synchronization with the CPU writing them.

So, I don't think this solves any problem. I belive you need the appropriate kind of CPU barrier here instead of an invalidation.

Jason

#28 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 79 lines · Jason Gunthorpe
Quoted 67 lines · Tomasz Jeznach
Quoted 49 lines

For detach I think yes:

Inv CPU Detach CPU

write io_pte Update device descriptor
rcu_read_lock
list_for_each
<make invalidation command> <make description inv cmd>
dma_wmb() dma_wmb()
<doorbell> <cmd doorbell>
rcu_read_unlock

                                             list_del_rcu()
                                             <wipe ASID>

In this case I think we never miss an invalidation, the list_del is always after the HW has been fully fenced, so I don't think we can have any issue. Maybe a suprious invalidation if the ASID gets re-used, but who cares.

Attach is different..

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() Update device descriptor <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

As above shows we can "miss" an invalidation. The issue is narrow, the io_pte could still be sitting in write buffers in "Inv CPU" and not yet globally visiable. "Attach CPU" could get the device descriptor installed in the IOMMU and the IOMMU could walk an io_pte that is in the old state. Effectively this is because there is no release/acquire barrier passing the io_pte store from the Inv CPU to the Attach CPU to the IOMMU.

It seems like it should be solvable somehow:
1) Inv CPU releases all the io ptes
2) Attach CPU acquires the io ptes before updating the DDT
3) Inv CPU acquires the RCU list in such a way that either attach CPU will acquire the io_pte or inv CPU will acquire the RCU list.
4) Either invalidation works or we release the new iopte to the SMMU and don't need it.

Quoted 3 lines

But #3 is a really weird statement. smb_mb() on both sides may do the job??

Actual attach sequence is slightly different.

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() IOTLB.INVAL(PSCID) <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

Quoted 2 lines

I've tried to cover this case with riscv_iommu_iotlb_inval() called before the attached domain is visible to the device.

That invalidation shouldn't do anything. If this is the first attach of a PSCID then the PSCID had better already be empty, it won't become non-empty until the DDT entry is installed.

And if it is the second attach then the Inv CPU is already taking care of things, no need to invalidate at all.

Quoted 7 lines

Regardless, there is still a theortical race that the IOPTEs haven't been made visible yet because there is still no synchronization with the CPU writing them.

So, I don't think this solves any problem. I belive you need the appropriate kind of CPU barrier here instead of an invalidation.

Yes. There was a small, but still plausible race w/ IOPTEs visibility to the IOMMU.
For v5 I'm adding two barriers to the inval/detach flow, I believe should cover it.

1) In riscv_iommu_iotlb_inval() unconditional dma_wmb() to make any pending writes to PTEs visible to the IOMMU device. This should cover the case when list_add_rcu() update is not yet visible in the _iotlb_inval() sequence, for the first time the domain is attached to the IOMMU.

Inv CPU Attach CPU
write io_pte
dma_wmb (1)
rcu_read_lock
list_for_each // empty list_add_rcu()
smp_wmb (2)
Update device descriptor <make description inv cmd> // PTEs are visible to the HW (*1) dma_wmb()
<cmd doorbell>
rcu_read_unlock

2) In riscv_iommu_bond_link() write memory barrier to ensure list update is visible before IOMMU descriptor update. If stale data has been fetched by the HW, inval CPU will run iotlb-invalidation sequence. There is a possibility that IOMMU will fetch correct PTEs and will receive unnecessary IOTLB inval, but I don't think anyone would care.

Inv CPU Attach CPU
write io_pte list_add_rcu()

                                             smp_wmb (2)
                                             Update device descriptor
                                             <make description inv cmd>
                                             // HW might fetch stale PTEs
                                             dma_wmb()
                                             <cmd doorbell>
  dma_wmb (1)
  rcu_read_lock
    list_for_each // non-empty (*2)
      <make iotlb inval cmd>
      dma_wmb()
      <cmd doorbell>

rcu_read_unlock

3) I've also updated riscv_iommu_bond_unlink() to wipe the PSCID cache on the last domain unlink from the IOMMU.

Thank you for pointing this out. Let me know if that makes sense.

Best,
- Tomasz

Quoted 1 line

Jason

#29 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 133 lines · Tomasz Jeznach
Quoted 79 lines · Jason Gunthorpe
Quoted 67 lines · Tomasz Jeznach
Quoted 49 lines

For detach I think yes:

Inv CPU Detach CPU

write io_pte Update device descriptor
rcu_read_lock
list_for_each
<make invalidation command> <make description inv cmd>
dma_wmb() dma_wmb()
<doorbell> <cmd doorbell>
rcu_read_unlock

                                             list_del_rcu()
                                             <wipe ASID>

In this case I think we never miss an invalidation, the list_del is always after the HW has been fully fenced, so I don't think we can have any issue. Maybe a suprious invalidation if the ASID gets re-used, but who cares.

Attach is different..

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() Update device descriptor <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

As above shows we can "miss" an invalidation. The issue is narrow, the io_pte could still be sitting in write buffers in "Inv CPU" and not yet globally visiable. "Attach CPU" could get the device descriptor installed in the IOMMU and the IOMMU could walk an io_pte that is in the old state. Effectively this is because there is no release/acquire barrier passing the io_pte store from the Inv CPU to the Attach CPU to the IOMMU.

It seems like it should be solvable somehow:
1) Inv CPU releases all the io ptes
2) Attach CPU acquires the io ptes before updating the DDT
3) Inv CPU acquires the RCU list in such a way that either attach CPU will acquire the io_pte or inv CPU will acquire the RCU list.
4) Either invalidation works or we release the new iopte to the SMMU and don't need it.

Quoted 3 lines

But #3 is a really weird statement. smb_mb() on both sides may do the job??

Actual attach sequence is slightly different.

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() IOTLB.INVAL(PSCID) <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

Quoted 2 lines

I've tried to cover this case with riscv_iommu_iotlb_inval() called before the attached domain is visible to the device.

That invalidation shouldn't do anything. If this is the first attach of a PSCID then the PSCID had better already be empty, it won't become non-empty until the DDT entry is installed.

And if it is the second attach then the Inv CPU is already taking care of things, no need to invalidate at all.

Quoted 7 lines

Regardless, there is still a theortical race that the IOPTEs haven't been made visible yet because there is still no synchronization with the CPU writing them.

So, I don't think this solves any problem. I belive you need the appropriate kind of CPU barrier here instead of an invalidation.

Yes. There was a small, but still plausible race w/ IOPTEs visibility to the IOMMU.
For v5 I'm adding two barriers to the inval/detach flow, I believe should cover it.

1) In riscv_iommu_iotlb_inval() unconditional dma_wmb() to make any pending writes to PTEs visible to the IOMMU device. This should cover the case when list_add_rcu() update is not yet visible in the _iotlb_inval() sequence, for the first time the domain is attached to the IOMMU.

Inv CPU Attach CPU
write io_pte
dma_wmb (1)
rcu_read_lock
list_for_each // empty list_add_rcu()
smp_wmb (2)
Update device descriptor <make description inv cmd> // PTEs are visible to the HW (*1) dma_wmb()
<cmd doorbell>
rcu_read_unlock

2) In riscv_iommu_bond_link() write memory barrier to ensure list update is visible before IOMMU descriptor update. If stale data has been fetched by the HW, inval CPU will run iotlb-invalidation sequence. There is a possibility that IOMMU will fetch correct PTEs and will receive unnecessary IOTLB inval, but I don't think anyone would care.

Inv CPU Attach CPU
write io_pte list_add_rcu()

                                             smp_wmb (2)
                                             Update device descriptor
                                             <make description inv cmd>
                                             // HW might fetch stale PTEs
                                             dma_wmb()
                                             <cmd doorbell>
  dma_wmb (1)
  rcu_read_lock
    list_for_each // non-empty (*2)
      <make iotlb inval cmd>
      dma_wmb()
      <cmd doorbell>
Quoted 6 lines

rcu_read_unlock

3) I've also updated riscv_iommu_bond_unlink() to wipe the PSCID cache on the last domain unlink from the IOMMU.

Thank you for pointing this out. Let me know if that makes sense.

I'm not an expert in barriers, but I think you need the more expensive "mb" in both cases.

The inv side is both releasing the write and acquiring the list read. IIRC READ_ONCE is not a full acquire?

The Attach side is both releasing the list_add_rcu() and acquiring the iopte.

rcu is still a benefit, there is no cache line sharing and there is only one full barrier, not two, like a spinlock.

And a big fat comment in both sides explaining this :)

Jason

#30 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 148 lines · Jason Gunthorpe
Quoted 133 lines · Tomasz Jeznach
Quoted 79 lines · Jason Gunthorpe
Quoted 67 lines · Tomasz Jeznach
Quoted 49 lines

For detach I think yes:

Inv CPU Detach CPU

write io_pte Update device descriptor
rcu_read_lock
list_for_each
<make invalidation command> <make description inv cmd>
dma_wmb() dma_wmb()
<doorbell> <cmd doorbell>
rcu_read_unlock

                                             list_del_rcu()
                                             <wipe ASID>

In this case I think we never miss an invalidation, the list_del is always after the HW has been fully fenced, so I don't think we can have any issue. Maybe a suprious invalidation if the ASID gets re-used, but who cares.

Attach is different..

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() Update device descriptor <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

As above shows we can "miss" an invalidation. The issue is narrow, the io_pte could still be sitting in write buffers in "Inv CPU" and not yet globally visiable. "Attach CPU" could get the device descriptor installed in the IOMMU and the IOMMU could walk an io_pte that is in the old state. Effectively this is because there is no release/acquire barrier passing the io_pte store from the Inv CPU to the Attach CPU to the IOMMU.

It seems like it should be solvable somehow:
1) Inv CPU releases all the io ptes
2) Attach CPU acquires the io ptes before updating the DDT
3) Inv CPU acquires the RCU list in such a way that either attach CPU will acquire the io_pte or inv CPU will acquire the RCU list.
4) Either invalidation works or we release the new iopte to the SMMU and don't need it.

Quoted 3 lines

But #3 is a really weird statement. smb_mb() on both sides may do the job??

Actual attach sequence is slightly different.

Inv CPU Attach CPU

write io_pte
rcu_read_lock
list_for_each // empty
list_add_rcu() IOTLB.INVAL(PSCID) <make description inv cmd> dma_wmb()
<cmd doorbell>
rcu_read_unlock

Quoted 2 lines

I've tried to cover this case with riscv_iommu_iotlb_inval() called before the attached domain is visible to the device.

That invalidation shouldn't do anything. If this is the first attach of a PSCID then the PSCID had better already be empty, it won't become non-empty until the DDT entry is installed.

And if it is the second attach then the Inv CPU is already taking care of things, no need to invalidate at all.

Quoted 7 lines

Regardless, there is still a theortical race that the IOPTEs haven't been made visible yet because there is still no synchronization with the CPU writing them.

So, I don't think this solves any problem. I belive you need the appropriate kind of CPU barrier here instead of an invalidation.

Yes. There was a small, but still plausible race w/ IOPTEs visibility to the IOMMU.
For v5 I'm adding two barriers to the inval/detach flow, I believe should cover it.

1) In riscv_iommu_iotlb_inval() unconditional dma_wmb() to make any pending writes to PTEs visible to the IOMMU device. This should cover the case when list_add_rcu() update is not yet visible in the _iotlb_inval() sequence, for the first time the domain is attached to the IOMMU.

Inv CPU Attach CPU
write io_pte
dma_wmb (1)
rcu_read_lock
list_for_each // empty list_add_rcu()
smp_wmb (2)
Update device descriptor <make description inv cmd> // PTEs are visible to the HW (*1) dma_wmb()
<cmd doorbell>
rcu_read_unlock

2) In riscv_iommu_bond_link() write memory barrier to ensure list update is visible before IOMMU descriptor update. If stale data has been fetched by the HW, inval CPU will run iotlb-invalidation sequence. There is a possibility that IOMMU will fetch correct PTEs and will receive unnecessary IOTLB inval, but I don't think anyone would care.

Inv CPU Attach CPU
write io_pte list_add_rcu()

                                             smp_wmb (2)
                                             Update device descriptor
                                             <make description inv cmd>
                                             // HW might fetch stale PTEs
                                             dma_wmb()
                                             <cmd doorbell>
  dma_wmb (1)
  rcu_read_lock
    list_for_each // non-empty (*2)
      <make iotlb inval cmd>
      dma_wmb()
      <cmd doorbell>
Quoted 6 lines

rcu_read_unlock

3) I've also updated riscv_iommu_bond_unlink() to wipe the PSCID cache on the last domain unlink from the IOMMU.

Thank you for pointing this out. Let me know if that makes sense.

I'm not an expert in barriers, but I think you need the more expensive "mb" in both cases.

The inv side is both releasing the write and acquiring the list read. IIRC READ_ONCE is not a full acquire?

Quoted 8 lines

The Attach side is both releasing the list_add_rcu() and acquiring the iopte.

rcu is still a benefit, there is no cache line sharing and there is only one full barrier, not two, like a spinlock.

And a big fat comment in both sides explaining this :)

I'm not an expert in barriers as well, but I've checked offline with one ;)

And the conclusion is that we need FENCE W,W (or stronger) on the attach side, and FENCE RW,RW in the invalidation sequence. Hardware access to PTE/DC is sequential, with implied FENCE R,R barriers.

As 'attach' sequence is a rare event anyway, I'll go on "mb" on both sides, as suggested.
Unless there are other opinions on that I'll update barriers to match this conclusion and try to capture in long comment for bond / inval / attach synchronization assumptions.

Jason, thanks again for pointing this out.

Quoted 1 line

Jason

Best,
- Tomasz

#31 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

In reply to Tomasz Jeznach
Quoted 36 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c +36 -0
+/*
+ * Send IOTLB.INVAL for whole address space for ranges larger than 2MB.
+ * This limit will be replaced with range invalidations, if supported by
+ * the hardware, when RISC-V IOMMU architecture specification update for
+ * range invalidations update will be available.
+ */
+#define RISCV_IOMMU_IOTLB_INVAL_LIMIT	(2 << 20)
+
+static void riscv_iommu_iotlb_inval(struct riscv_iommu_domain *domain,
+				    unsigned long start, unsigned long end)
+{
+	struct riscv_iommu_bond *bond;
+	struct riscv_iommu_device *iommu, *prev;
+	struct riscv_iommu_command cmd;
+	unsigned long len = end - start + 1;
+	unsigned long iova;
+
+	rcu_read_lock();
+
+	prev = NULL;
+	list_for_each_entry_rcu(bond, &domain->bonds, list) {
+		iommu = dev_to_iommu(bond->dev);
+
+		riscv_iommu_cmd_inval_vma(&cmd);
+		riscv_iommu_cmd_inval_set_pscid(&cmd, domain->pscid);
+		if (len && len >= RISCV_IOMMU_IOTLB_INVAL_LIMIT) {
+			for (iova = start; iova < end; iova += PAGE_SIZE) {
+				riscv_iommu_cmd_inval_set_addr(&cmd, iova);
+				riscv_iommu_cmd_send(iommu, &cmd, 0);
+			}
+		} else {
+			riscv_iommu_cmd_send(iommu, &cmd, 0);
+		}
+
+		/*
+		 * IOTLB invalidation request can be safely omitted if already sent

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 869

Quoted 10 lines
drivers/iommu/riscv/iommu.c +10 -0
+		 * to the IOMMU for the same PSCID, and with domain->bonds list
+		 * arranged based on the device's IOMMU, it's sufficient to check
+		 * last device the invalidation was sent to.
+		 */
+		if (iommu == prev)
+			continue;
+
+		prev = iommu;
+		riscv_iommu_cmd_send(iommu, &cmd, 0);
+	}

I don't quite follow why not moving "if (iommu == prev)" check to the top and removing the last riscv_iommu_cmd_send(). My understanding is that we could make it simply like below:

	prev = NULL;
	list_for_each_entry_rcu(bond, &domain->bonds, list) {
		iommu = dev_to_iommu(bond->dev);
		if (iommu == prev)
			continue;

		/*
		 * Send an invalidation request to the request queue
		 * without wait.
		 */
		... ...

		prev = iommu;
	}

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 882

Quoted 13 lines
drivers/iommu/riscv/iommu.c +13 -0
+
+	prev = NULL;
+	list_for_each_entry_rcu(bond, &domain->bonds, list) {
+		iommu = dev_to_iommu(bond->dev);
+		if (iommu == prev)
+			continue;
+
+		prev = iommu;
+		riscv_iommu_cmd_iofence(&cmd);
+		riscv_iommu_cmd_send(iommu, &cmd, RISCV_IOMMU_QUEUE_TIMEOUT);
+	}
+	rcu_read_unlock();
+}

Best regards,
baolu

#32 lore raw

Re: [PATCH v3 7/7] iommu/riscv: Paging domain support

Quoted 53 lines · Baolu Lu
Quoted 36 lines · Tomasz Jeznach
drivers/iommu/riscv/iommu.c +36 -0
+/*
+ * Send IOTLB.INVAL for whole address space for ranges larger than 2MB.
+ * This limit will be replaced with range invalidations, if supported by
+ * the hardware, when RISC-V IOMMU architecture specification update for
+ * range invalidations update will be available.
+ */
+#define RISCV_IOMMU_IOTLB_INVAL_LIMIT        (2 << 20)
+
+static void riscv_iommu_iotlb_inval(struct riscv_iommu_domain *domain,
+                                 unsigned long start, unsigned long end)
+{
+     struct riscv_iommu_bond *bond;
+     struct riscv_iommu_device *iommu, *prev;
+     struct riscv_iommu_command cmd;
+     unsigned long len = end - start + 1;
+     unsigned long iova;
+
+     rcu_read_lock();
+
+     prev = NULL;
+     list_for_each_entry_rcu(bond, &domain->bonds, list) {
+             iommu = dev_to_iommu(bond->dev);
+
+             riscv_iommu_cmd_inval_vma(&cmd);
+             riscv_iommu_cmd_inval_set_pscid(&cmd, domain->pscid);
+             if (len && len >= RISCV_IOMMU_IOTLB_INVAL_LIMIT) {
+                     for (iova = start; iova < end; iova += PAGE_SIZE) {
+                             riscv_iommu_cmd_inval_set_addr(&cmd, iova);
+                             riscv_iommu_cmd_send(iommu, &cmd, 0);
+                     }
+             } else {
+                     riscv_iommu_cmd_send(iommu, &cmd, 0);
+             }
+
+             /*
+              * IOTLB invalidation request can be safely omitted if already sent

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 869

Quoted 10 lines
drivers/iommu/riscv/iommu.c +10 -0
+              * to the IOMMU for the same PSCID, and with domain->bonds list
+              * arranged based on the device's IOMMU, it's sufficient to check
+              * last device the invalidation was sent to.
+              */
+             if (iommu == prev)
+                     continue;
+
+             prev = iommu;
+             riscv_iommu_cmd_send(iommu, &cmd, 0);
+     }

I don't quite follow why not moving "if (iommu == prev)" check to the top and removing the last riscv_iommu_cmd_send(). My understanding is that we could make it simply like below:

Quoted 15 lines
        prev = NULL;
        list_for_each_entry_rcu(bond, &domain->bonds, list) {
                iommu = dev_to_iommu(bond->dev);
                if (iommu == prev)
                        continue;

                /*
                 * Send an invalidation request to the request queue
                 * without wait.
                 */
                ... ...

                prev = iommu;
        }

Oh. Thanks for spotting that.
Code section reordered very likely during rebasing patches...

Quoted 8 lines
Quoted 8 lines
drivers/iommu/riscv/iommu.c +8 -0
+
+     prev = NULL;
+     list_for_each_entry_rcu(bond, &domain->bonds, list) {
+             iommu = dev_to_iommu(bond->dev);
+             if (iommu == prev)
+                     continue;
+
+             prev = iommu;
Quoted 8 lines

drivers/iommu/riscv/iommu.c static int riscv_iommu_iodir_set_mode(struct riscv_iommu_device *iommu, · line 882

Quoted 5 lines
drivers/iommu/riscv/iommu.c +5 -0
+             riscv_iommu_cmd_iofence(&cmd);
+             riscv_iommu_cmd_send(iommu, &cmd, RISCV_IOMMU_QUEUE_TIMEOUT);
+     }
+     rcu_read_unlock();
+}

Best regards,
baolu

Best regards,
- Tomasz

#33 lore raw
In reply to Tomasz Jeznach
Quoted 2 lines · Tomasz Jeznach

This patch series introduces support for RISC-V IOMMU architected hardware into the Linux kernel.

It seems in reasonable shape now, at least in terms of implementing the domain logic.

It would be nice if you'd run it through clang-format and correct some of the minor misformatting it will point out. We still like to have a 80 col line limit in most cases. There are many overages here that aren't well justified.

And you could consider the nitpicky style advice to use 'reverse christmas tree' for the variable declarations like most of the subsystem is trending toward.

Jason