Skip to contentSkip to conversation

KVM: ITS hardening for pKVM

PATCH New Fuad Tabba 1 participant 14 messages Nov 18

Subsystems (6)
Documentation KVM arm64 KVM arm64 +2 more subsystems
lore
Share & tools
lore

Fuad Tabba

author reviewer
#0 lore raw

v4 cover KVM: ITS hardening for pKVM

Hi folks,

Changes since v3 [1]:
- The hypervisor never gives an ITT back to the host (patch 11).
- The limit on devices per ITS now counts every DeviceID mapped since

    boot (patch 11).

- A host read of an ITS register now aborts, unless the driver reads that register (patch 9).
- Rebased on 7.4-rc3.
- Various cleanups and wording fixes.

The ITS writes to the memory that its command queue and tables point to, and the host programs both, so a host that controls the ITS can write to hypervisor and protected-VM memory. With this series the hypervisor owns the command queue, the tables and the ITTs, traps every host access to the ITS control frame, and checks each command before forwarding it to the ITS. The cover letter for v3 [1] describes the design in more detail.

This series covers the ITS. The redistributors will follow in a series of their own.

Jinjie's series [2] lets the collection table have two levels, which this series doesn't handle. Once it's merged, I'll send patches that make the hypervisor handle that table the way it handles the device table.

Tested on QEMU with a program that writes forged commands, table entries and register values to the ITS through /dev/mem from the host's userspace. Also tested on FVP, where the ITS uses physical redistributor addresses (GITS_TYPER.PTA). There, every secondary CPU was hotplugged after the takeover, so that the driver maps each returning CPU's collection through the hypervisor with a MAPC that carries a physical address.

The series is structured as follows:

  01:     MMIO donation.
  02:     Taking host-registered MMIO regions at finalisation.
  03-06:  Driver preparation: GICv4 off, page-aligned ITTs, computing
          the wait target under the ITS lock, the shared command
          accessors.
  07:     Deprivileging the host under stop_machine().
  08-09:  The takeover: the driver's entry points, then the hypervisor
          trapping the control frame, taking the command queue and
          emulating GITS_CTLR and GITS_CBASER.
  10-11:  The tables and GITS_BASER<n>, then the ITTs.
  12:     Rejecting commands whose IDs are out of range.
  13:     Documentation.

Based on Linux 7.4-rc3 (aebb727447640).

Cheers,
/fuad

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

Bartłomiej Grzesik (2):
irqchip/gic-v3: Disable GICv4 features in pKVM irqchip/gic-v3-its: Page-align ITT allocations in pKVM

Fuad Tabba (7):
irqchip/gic-v3-its: Compute the wait target under the ITS lock
KVM: arm64: Share the ITS command field accessors with the hypervisor
KVM: arm64: Deprivilege the host under stop_machine()
KVM: arm64: Take the ITS tables and restrict GITS_BASER<n>
KVM: arm64: Take the ITT of every device the host maps
KVM: arm64: Reject ITS commands whose IDs are out of range
Documentation: KVM: arm64: Describe the ITS hardening

Mostafa Saleh (1):
KVM: arm64: Donate MMIO to the hypervisor

Sebastian Ene (3):
KVM: arm64: Take host-registered MMIO regions at pKVM finalisation irqchip/gic-v3-its: Add the pKVM takeover entry points
KVM: arm64: Emulate the ITS command queue

 .../admin-guide/kernel-parameters.txt         |   8 +-
 Documentation/virt/kvm/arm/pkvm.rst           |  34 +
 arch/arm64/include/asm/kvm_asm.h              |   2 +
 arch/arm64/include/asm/kvm_hcall.h            |   2 +
 arch/arm64/include/asm/kvm_pgtable.h          |   2 +
 arch/arm64/include/asm/kvm_pkvm.h             |  16 +
 arch/arm64/kvm/arm.c                          |   4 +
 arch/arm64/kvm/hyp/include/nvhe/its_emulate.h |  16 +
 arch/arm64/kvm/hyp/include/nvhe/mem_protect.h |   5 +
 arch/arm64/kvm/hyp/nvhe/Makefile              |   3 +-
 arch/arm64/kvm/hyp/nvhe/hyp-main.c            |   8 +
 arch/arm64/kvm/hyp/nvhe/its_emulate.c         | 765 ++++++++++++++++++
 arch/arm64/kvm/hyp/nvhe/mem_protect.c         | 130 ++-
 arch/arm64/kvm/hyp/nvhe/setup.c               |  22 +
 arch/arm64/kvm/hyp/pgtable.c                  |   8 +-
 arch/arm64/kvm/pkvm.c                         | 105 ++-
 arch/arm64/kvm/vgic/vgic-its.c                |  15 -
 drivers/irqchip/irq-gic-common.h              |  13 +
 drivers/irqchip/irq-gic-v3-its.c              | 301 ++++++-
 drivers/irqchip/irq-gic-v3.c                  |   8 +
 include/linux/irqchip/arm-gic-v3.h            |  65 ++
 21 files changed, 1475 insertions(+), 57 deletions(-)
 create mode 100644 arch/arm64/kvm/hyp/include/nvhe/its_emulate.h
 create mode 100644 arch/arm64/kvm/hyp/nvhe/its_emulate.c

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3

Signature · 1 line
2.47.3
author reviewer
#1 lore raw

PATCH v4 1/13 KVM: arm64: Donate MMIO to the hypervisor

From: Mostafa Saleh <[email protected]>

Add __pkvm_host_donate_hyp_mmio() so IOMMU drivers in the hypervisor can take ownership of the IOMMU MMIO. The range is mapped in the hypervisor private range and annotated as owned by the hypervisor in the host stage-2, so host accesses fault and further donations of the same range are refused. MMIO has no struct hyp_page, so the annotation is the only state, and a dedicated function is simpler than teaching the memory donation path about MMIO. Donation is only allowed before the host is de-privileged, which is when the hypervisor IOMMU drivers initialise.

Make kvm_pgtable_stage2_unmap() leave invalid counted PTEs (annotations) in place. host_stage2_unmap_dev_all() unmaps all non-memory ranges to recycle page-table pages under memory pressure, and would otherwise drop the annotation and let the host fault the MMIO back in. No caller depends on the old behaviour: host_stage2_unmap_dev_all() only covers non-memory ranges, where no annotation existed until now, and the guest unmap paths check that the PTE is valid first. Returning an error for counted PTEs instead is not an option, as a non-zero visitor return stops the walk, which would abort recycling at the first hypervisor-owned MMIO page and inject an abort into the host for an unrelated address.

[fuad: pass kvm_pgtable_get_leaf() the walk flags ee26443f3dd70 added;
drop __pkvm_hyp_donate_host_mmio(), which this series doesn't call]

---
 arch/arm64/include/asm/kvm_pgtable.h          |  2 +
 arch/arm64/kvm/hyp/include/nvhe/mem_protect.h |  5 ++
 arch/arm64/kvm/hyp/nvhe/mem_protect.c         | 62 ++++++++++++++++++-
 arch/arm64/kvm/hyp/pgtable.c                  |  8 +--
 4 files changed, 70 insertions(+), 7 deletions(-)
arch/arm64/include/asm/kvm_pgtable.h +2 -0
index 1c9c57cd6ae40..1a3f6e851c94f 100644
@@ -721,6 +721,8 @@ int kvm_pgtable_stage2_annotate(struct kvm_pgtable *pgt, u64 addr, u64 size,
  * freed. Unmapping a cacheable page will ensure that it is clean to the PoC if
  * FWB is not supported by the CPU.
  *
+ * Invalid counted PTEs (annotations) are left in place.
+ *
  * Return: 0 on success, negative error code on failure.
  */
 int kvm_pgtable_stage2_unmap(struct kvm_pgtable *pgt, u64 addr, u64 size);
arch/arm64/kvm/hyp/include/nvhe/mem_protect.h +5 -0
index ec85a95471207..16e5864ab7f08 100644
@@ -36,6 +36,11 @@ int __pkvm_guest_share_host(struct pkvm_hyp_vcpu *vcpu, u64 gfn);
 int __pkvm_guest_unshare_host(struct pkvm_hyp_vcpu *vcpu, u64 gfn);
 int __pkvm_host_unshare_hyp(u64 pfn);
 int __pkvm_host_donate_hyp(u64 pfn, u64 nr_pages);
+/*
+ * Donate MMIO range to the hypervisor, it will be mapped in the hypervisor's
+ * private range and unmapped from the host stage-2.
+ */
+int __pkvm_host_donate_hyp_mmio(u64 pfn, u64 nr_pages, unsigned long *haddr);
 int __pkvm_hyp_donate_host(u64 pfn, u64 nr_pages);
 int __pkvm_host_share_ffa(u64 pfn, u64 nr_pages);
 int __pkvm_host_unshare_ffa(u64 pfn, u64 nr_pages);
arch/arm64/kvm/hyp/nvhe/mem_protect.c +61 -1

74 lines not on this page · raw message

arch/arm64/kvm/hyp/pgtable.c +2 -6
index 9c83837b184d3..041bd0d522f2c 100644
@@ -1163,13 +1163,9 @@ static int stage2_unmap_walker(const struct kvm_pgtable_visit_ctx *ctx,
 	kvm_pte_t *childp = NULL;
 	bool need_flush = false;
 
-	if (!kvm_pte_valid(ctx->old)) {
-		if (stage2_pte_is_counted(ctx->old)) {
-			kvm_clear_pte(ctx->ptep);
-			mm_ops->put_page(ctx->ptep);
-		}
+	/* Invalid PTEs are left in place, including annotations. */
+	if (!kvm_pte_valid(ctx->old))
 		return 0;
-	}
 
 	if (kvm_pte_table(ctx->old, ctx->level)) {
 		childp = kvm_pte_follow(ctx->old, mm_ops);
Signature · 1 line
2.47.3
author reviewer
#2 lore raw

PATCH v4 2/13 KVM: arm64: Take host-registered MMIO regions at pKVM finalisation

In reply to Fuad Tabba

From: Sebastian Ene <[email protected]>

To emulate a device for the host, the hypervisor has to own the device's registers, so that a host access to them takes a stage-2 abort rather than reaching the device.

Allow the host to register MMIO regions before the hypervisor initialises, and have __pkvm_init_finalise() donate each one and record where it's mapped in the hypervisor's private range. The donation runs before pkvm_check_host_ownership(), which then covers those mappings too. A failed donation fails the hypervisor's initialisation before the host stage 2 is installed, so the hypervisor doesn't have to give anything back.

The host doesn't register a region yet.

---
 arch/arm64/include/asm/kvm_pkvm.h     | 12 ++++++++++++
 arch/arm64/kvm/hyp/nvhe/mem_protect.c |  3 +++
 arch/arm64/kvm/hyp/nvhe/setup.c       | 22 ++++++++++++++++++++++
 3 files changed, 37 insertions(+)
arch/arm64/include/asm/kvm_pkvm.h +12 -0
index fd042d2b54624..4695c35b31e1a 100644
@@ -17,6 +17,18 @@
 
 #define HYP_MEMBLOCK_REGIONS 128
 
+/* MMIO regions the host registers for the hypervisor to take at finalisation. */
+#define PKVM_PROTECTED_REGS_NUM	8
+
+struct pkvm_protected_reg {
+	u64			pfn;
+	u64			nr_pages;
+	void __iomem		*hyp_va;
+};
+
+extern struct pkvm_protected_reg kvm_nvhe_sym(pkvm_protected_regs)[];
+extern unsigned int kvm_nvhe_sym(num_protected_reg);
+
 int pkvm_init_host_vm(struct kvm *kvm);
 int pkvm_create_hyp_vm(struct kvm *kvm);
 bool pkvm_hyp_vm_is_created(struct kvm *kvm);
arch/arm64/kvm/hyp/nvhe/mem_protect.c +3 -0
index a6dacaca77610..8d45f45d30e6a 100644
@@ -28,6 +28,9 @@ struct host_mmu host_mmu;
 
 static struct hyp_pool host_s2_pool;
 
+unsigned int num_protected_reg;
+struct pkvm_protected_reg pkvm_protected_regs[PKVM_PROTECTED_REGS_NUM];
+
 static DEFINE_PER_CPU(struct pkvm_hyp_vm *, __current_vm);
 #define current_vm (*this_cpu_ptr(&__current_vm))
 
arch/arm64/kvm/hyp/nvhe/setup.c +22 -0
index 7bbc26b28faa5..18f348d1331a8 100644
@@ -295,6 +295,24 @@ static int fix_hyp_pgtable_refcnt(void)
 				&walker);
 }
 
+static int donate_protected_mmio_regions(void)
+{
+	struct pkvm_protected_reg *region;
+	unsigned long haddr;
+	int ret, i;
+
+	for (i = 0; i < num_protected_reg; i++) {
+		region = &pkvm_protected_regs[i];
+		ret = __pkvm_host_donate_hyp_mmio(region->pfn, region->nr_pages, &haddr);
+		if (ret)
+			return ret;
+
+		region->hyp_va = (void __iomem *)haddr;
+	}
+
+	return 0;
+}
+
 void __noreturn __pkvm_init_finalise(void)
 {
 	struct kvm_cpu_context *host_ctxt = host_data_ptr(host_ctxt);
@@ -335,6 +353,10 @@ void __noreturn __pkvm_init_finalise(void)
 	if (ret)
 		goto out;
 
+	ret = donate_protected_mmio_regions();
+	if (ret)
+		goto out;
+
 	ret = pkvm_check_host_ownership();
 	if (ret)
 		goto out;
Signature · 1 line
2.47.3
author reviewer
#3 lore raw

PATCH v4 3/13 irqchip/gic-v3: Disable GICv4 features in pKVM

In reply to Fuad Tabba

From: Bartłomiej Grzesik <[email protected]>

In subsequent patches the hypervisor takes the ITS from the host and checks each command the host queues. Those patches don't emulate the vLPI commands, as VMAPP's VPT_base, for one, is a host-chosen address the ITS and the redistributors write to.

Clear has_vlpis and has_rvpeid at redistributor probe in protected mode, so the host never issues a vLPI command, and print that GICv4 is off. The host loses GICv4 direct injection for its non-protected guests, a feature that's off unless kvm-arm.vgic_v4_enable is set. A guest migrated from a host with GICD_TYPER2.nASSGIcap set can't be restored either, as KVM rejects that GICD_TYPER2 value without GICv4.1. Document the loss of direct injection in kernel-parameters.txt.

Add gic_is_protected_kvm() to irq-gic-common.h to test for protected mode, as the ITS driver uses it too from the next patch on. It calls kvm_get_mode(), so the header now includes linux/kvm_host.h.

---
 Documentation/admin-guide/kernel-parameters.txt |  8 +++++---
 drivers/irqchip/irq-gic-common.h                | 13 +++++++++++++
 drivers/irqchip/irq-gic-v3.c                    |  8 ++++++++
 3 files changed, 26 insertions(+), 3 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +5 -3
index 0b3c140babd94..3e63e44609522 100644
@@ -3275,8 +3275,9 @@ Kernel parameters
 				hardware (with FEAT_NV2).
 
 			Defaults to VHE/nVHE based on hardware support. Setting
-			mode to "protected" will disable kexec and hibernation
-			for the host. To force nVHE on VHE hardware, add
+			mode to "protected" will disable kexec, hibernation and
+			GICv4 direct LPI injection for the host. To force nVHE
+			on VHE hardware, add
 			"arm64_sw.hvhe=0 id_aa64mmfr1.vh=0" to the
 			command-line.
 			"nested" and "protected" are experimental and should be
@@ -3296,7 +3297,8 @@ Kernel parameters
 
 	kvm-arm.vgic_v4_enable=
 			[KVM,ARM,EARLY] Allow use of GICv4 for direct
-			injection of LPIs.
+			injection of LPIs. Has no effect when
+			kvm-arm.mode=protected.
 
 	kvm-arm.wfe_trap_policy=
 			[KVM,ARM] Control when to set WFE instruction trap for
drivers/irqchip/irq-gic-common.h +13 -0
index 710cab61d9195..3ce1dc7abf648 100644
@@ -10,6 +10,9 @@
 #include <linux/irqdomain.h>
 #include <linux/msi.h>
 #include <linux/irqchip/arm-gic-common.h>
+#ifdef CONFIG_ARM64
+#include <linux/kvm_host.h>
+#endif
 
 struct gic_quirk {
 	const char *desc;
@@ -29,6 +32,16 @@ void gic_enable_quirks(u32 iidr, const struct gic_quirk *quirks,
 void gic_enable_of_quirks(const struct device_node *np,
 			  const struct gic_quirk *quirks, void *data);
 
+#ifdef CONFIG_ARM64
+/* is_protected_kvm_enabled() can't be used, as the GIC probes before the cpucaps are final. */
+static inline bool gic_is_protected_kvm(void)
+{
+	return kvm_get_mode() == KVM_MODE_PROTECTED;
+}
+#else
+static inline bool gic_is_protected_kvm(void) { return false; }
+#endif
+
 #define RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING    (1 << 0)
 #define RDIST_FLAGS_RD_TABLES_PREALLOCATED     (1 << 1)
 #define RDIST_FLAGS_FORCE_NON_SHAREABLE        (1 << 2)
drivers/irqchip/irq-gic-v3.c +8 -0
index 94873646d46fb..f02c568d95653 100644
@@ -1123,6 +1123,14 @@ static void gic_update_rdist_properties(void)
 	gic_iterate_rdists(__gic_update_rdist_properties);
 	if (WARN_ON(gic_data.ppi_nr == UINT_MAX))
 		gic_data.ppi_nr = 0;
+
+	/* pKVM doesn't emulate the vLPI commands. */
+	if (gic_is_protected_kvm() && gic_data.rdists.has_vlpis) {
+		pr_info("GICv4 features disabled in protected KVM mode\n");
+		gic_data.rdists.has_vlpis = false;
+		gic_data.rdists.has_rvpeid = false;
+	}
+
 	pr_info("GICv3 features: %d PPIs%s%s\n",
 		gic_data.ppi_nr,
 		gic_data.has_rss ? ", RSS" : "",
Signature · 1 line
2.47.3
author reviewer
#4 lore raw

PATCH v4 4/13 irqchip/gic-v3-its: Page-align ITT allocations in pKVM

In reply to Fuad Tabba

From: Bartłomiej Grzesik <[email protected]>

In a subsequent patch the host donates the pages of each device's ITT to the hypervisor. A page the hypervisor already owns can't be donated again, so the MAPD of a device whose ITT shares a page with another device's would be rejected.

Round each ITT up to whole pages in protected mode. This costs up to a page per MSI device, where several 256-byte ITTs would have shared one. That's tens of pages on a phone and thousands on a server with thousands of VFs.

---
 drivers/irqchip/irq-gic-v3-its.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/irqchip/irq-gic-v3-its.c +3 -0
index c952c069f9373..bbfea565149bb 100644
@@ -3493,6 +3493,9 @@ static struct its_device *its_create_device(struct its_node *its, u32 dev_id,
 	nr_ites = max(2, nvecs);
 	sz = nr_ites * (FIELD_GET(GITS_TYPER_ITT_ENTRY_SIZE, its->typer) + 1);
 	sz = max(sz, ITS_ITT_ALIGN);
+	/* The hypervisor takes whole pages for each ITT. */
+	if (gic_is_protected_kvm())
+		sz = PAGE_ALIGN(sz);
 
 	itt = itt_alloc_pool(its->numa_node, sz);
 
Signature · 1 line
2.47.3
author reviewer
#5 lore raw

PATCH v4 5/13 irqchip/gic-v3-its: Compute the wait target under the ITS lock

In reply to Fuad Tabba

its_wait_for_range_completion() converts the posted command pointer into a queue offset against its->cmd_base, after the caller has dropped its->lock. That's fine while cmd_base never changes, but the pKVM takeover in a subsequent patch switches cmd_base to a copy of the queue while the other CPUs are stopped, and a CPU stopped in the wait before it has converted the pointer would compute its target against the wrong base.

Compute the offset in its_post_commands(), under the lock, and pass it to the wait instead of the pointer.

No functional change intended.

---
 drivers/irqchip/irq-gic-v3-its.c | 17 ++++++++---------
 1 file changed, 8 insertions(+), 9 deletions(-)
drivers/irqchip/irq-gic-v3-its.c +8 -9
index bbfea565149bb..734fe4fb52bd6 100644
@@ -1144,13 +1144,13 @@ static struct its_cmd_block *its_allocate_entry(struct its_node *its)
 	return cmd;
 }
 
-static struct its_cmd_block *its_post_commands(struct its_node *its)
+static u64 its_post_commands(struct its_node *its)
 {
 	u64 wr = its_cmd_ptr_to_offset(its, its->cmd_write);
 
 	writel_relaxed(wr, its->base + GITS_CWRITER);
 
-	return its->cmd_write;
+	return wr;
 }
 
 static void its_flush_cmd(struct its_node *its, struct its_cmd_block *cmd)
@@ -1167,13 +1167,12 @@ static void its_flush_cmd(struct its_node *its, struct its_cmd_block *cmd)
 
 static int its_wait_for_range_completion(struct its_node *its,
 					 u64	prev_idx,
-					 struct its_cmd_block *to)
+					 u64	to_idx)
 {
-	u64 rd_idx, to_idx, linear_idx;
+	u64 rd_idx, linear_idx;
 	u32 count = 1000000;	/* 1s! */
 
 	/* Linearize to_idx if the command set has wrapped around */
-	to_idx = its_cmd_ptr_to_offset(its, to);
 	if (to_idx < prev_idx)
 		to_idx += ITS_CMD_QUEUE_SZ;
 
@@ -1216,10 +1215,10 @@ void name(struct its_node *its,						\
 	  buildtype builder,						\
 	  struct its_cmd_desc *desc)					\
 {									\
-	struct its_cmd_block *cmd, *sync_cmd, *next_cmd;		\
+	struct its_cmd_block *cmd, *sync_cmd;				\
 	synctype *sync_obj;						\
 	unsigned long flags;						\
-	u64 rd_idx;							\
+	u64 rd_idx, wr_idx;						\
 									\
 	raw_spin_lock_irqsave(&its->lock, flags);			\
 									\
@@ -1242,10 +1241,10 @@ void name(struct its_node *its,						\
 									\
 post:									\
 	rd_idx = readl_relaxed(its->base + GITS_CREADR);		\
-	next_cmd = its_post_commands(its);				\
+	wr_idx = its_post_commands(its);				\
 	raw_spin_unlock_irqrestore(&its->lock, flags);			\
 									\
-	if (its_wait_for_range_completion(its, rd_idx, next_cmd))	\
+	if (its_wait_for_range_completion(its, rd_idx, wr_idx))		\
 		pr_err_ratelimited("ITS cmd %ps failed\n", builder);	\
 }
 
Signature · 1 line
2.47.3
author reviewer
#6 lore raw

PATCH v4 6/13 KVM: arm64: Share the ITS command field accessors with the hypervisor

In reply to Fuad Tabba

The vgic's ITS emulation reads command fields with its_cmd_mask_field() and the its_cmd_get_*() accessors. struct its_cmd_block, the block they decode, is private to the ITS driver, but in a subsequent patch the hypervisor parses the host's commands too.

Move the command block and the accessors to arm-gic-v3.h, which already holds the GITS_CMD_* encodings, so there is one copy of each. Only KVM reads commands, but the accessors decode the block the driver writes, so they sit with it rather than in a KVM header.

No functional change intended.

---
 arch/arm64/kvm/vgic/vgic-its.c     | 15 ---------------
 drivers/irqchip/irq-gic-v3-its.c   | 10 ----------
 include/linux/irqchip/arm-gic-v3.h | 22 ++++++++++++++++++++++
 3 files changed, 22 insertions(+), 25 deletions(-)
arch/arm64/kvm/vgic/vgic-its.c +0 -15
index 7e9b265b1f521..78e480d112025 100644
@@ -802,21 +802,6 @@ static bool vgic_its_map_lpi(struct kvm *kvm, struct its_ite *ite,
 	return false;
 }
 
-static u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size)
-{
-	return (le64_to_cpu(its_cmd[word]) >> shift) & (BIT_ULL(size) - 1);
-}
-
-#define its_cmd_get_command(cmd)	its_cmd_mask_field(cmd, 0,  0,  8)
-#define its_cmd_get_deviceid(cmd)	its_cmd_mask_field(cmd, 0, 32, 32)
-#define its_cmd_get_size(cmd)		(its_cmd_mask_field(cmd, 1,  0,  5) + 1)
-#define its_cmd_get_id(cmd)		its_cmd_mask_field(cmd, 1,  0, 32)
-#define its_cmd_get_physical_id(cmd)	its_cmd_mask_field(cmd, 1, 32, 32)
-#define its_cmd_get_collection(cmd)	its_cmd_mask_field(cmd, 2,  0, 16)
-#define its_cmd_get_ittaddr(cmd)	(its_cmd_mask_field(cmd, 2,  8, 44) << 8)
-#define its_cmd_get_target_addr(cmd)	its_cmd_mask_field(cmd, 2, 16, 32)
-#define its_cmd_get_validbit(cmd)	its_cmd_mask_field(cmd, 2, 63,  1)
-
 /*
  * The DISCARD command frees an Interrupt Translation Table Entry (ITTE).
  * Must be called with the its_lock mutex held.
drivers/irqchip/irq-gic-v3-its.c +0 -10
index 734fe4fb52bd6..df6d7b2fc8611 100644
@@ -528,16 +528,6 @@ struct its_cmd_desc {
 	};
 };
 
-/*
- * The ITS command block, which is what the ITS actually parses.
- */
-struct its_cmd_block {
-	union {
-		u64	raw_cmd[4];
-		__le64	raw_cmd_le[4];
-	};
-};
-
 #define ITS_CMD_QUEUE_SZ		SZ_64K
 #define ITS_CMD_QUEUE_NR_ENTRIES	(ITS_CMD_QUEUE_SZ / sizeof(struct its_cmd_block))
 
include/linux/irqchip/arm-gic-v3.h +22 -0
index ea5fd2374ebe0..e0bec40adf2b7 100644
@@ -657,6 +657,28 @@ static inline bool gic_enable_sre(void)
 	return !!(val & ICC_SRE_EL1_SRE);
 }
 
+struct its_cmd_block {
+	union {
+		u64	raw_cmd[4];
+		__le64	raw_cmd_le[4];
+	};
+};
+
+static inline u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size)
+{
+	return (le64_to_cpu(its_cmd[word]) >> shift) & (BIT_ULL(size) - 1);
+}
+
+#define its_cmd_get_command(cmd)	its_cmd_mask_field(cmd, 0,  0,  8)
+#define its_cmd_get_deviceid(cmd)	its_cmd_mask_field(cmd, 0, 32, 32)
+#define its_cmd_get_size(cmd)		(its_cmd_mask_field(cmd, 1,  0,  5) + 1)
+#define its_cmd_get_id(cmd)		its_cmd_mask_field(cmd, 1,  0, 32)
+#define its_cmd_get_physical_id(cmd)	its_cmd_mask_field(cmd, 1, 32, 32)
+#define its_cmd_get_collection(cmd)	its_cmd_mask_field(cmd, 2,  0, 16)
+#define its_cmd_get_ittaddr(cmd)	(its_cmd_mask_field(cmd, 2,  8, 44) << 8)
+#define its_cmd_get_target_addr(cmd)	its_cmd_mask_field(cmd, 2, 16, 32)
+#define its_cmd_get_validbit(cmd)	its_cmd_mask_field(cmd, 2, 63,  1)
+
 #endif
 
 #endif
Signature · 1 line
2.47.3
author reviewer
#7 lore raw

PATCH v4 7/13 KVM: arm64: Deprivilege the host under stop_machine()

In reply to Fuad Tabba

pkvm_drop_host_privileges() installs the host stage 2 with on_each_cpu(), and each CPU goes back to running the host as soon as its own __pkvm_prot_finalize() returns. That doesn't work for the ITS takeover that a subsequent patch adds here. The other CPUs must not post ITS commands while the driver switches to its copy of the command queue, and a takeover that fails has to leave every CPU privileged.

Finalise from a stop_machine() callback instead, so that the takeover can run with the other CPUs stopped and before any CPU is finalised. An error from any CPU is still returned to finalize_pkvm().

---
 arch/arm64/kvm/pkvm.c | 13 ++++---------
 1 file changed, 4 insertions(+), 9 deletions(-)
arch/arm64/kvm/pkvm.c +4 -9
index 016997288fd23..16dfb249b4961 100644
@@ -11,6 +11,7 @@
 #include <asm/kvm_mmu.h>
 #include <linux/memblock.h>
 #include <linux/mutex.h>
+#include <linux/stop_machine.h>
 
 #include <asm/kvm_pkvm.h>
 
@@ -312,25 +313,19 @@ int pkvm_init_host_vm(struct kvm *kvm)
 	return 0;
 }
 
-static void __init _kvm_host_prot_finalize(void *arg)
+static int __init __pkvm_drop_host_privileges(void *arg)
 {
-	int *err = arg;
-
-	if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize)))
-		WRITE_ONCE(*err, -EINVAL);
+	return WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize)) ? -EINVAL : 0;
 }
 
 static int __init pkvm_drop_host_privileges(void)
 {
-	int ret = 0;
-
 	/*
 	 * Flip the static key upfront as that may no longer be possible
 	 * once the host stage 2 is installed.
 	 */
 	static_branch_enable(&kvm_protected_mode_initialized);
-	on_each_cpu(_kvm_host_prot_finalize, &ret, 1);
-	return ret;
+	return stop_machine(__pkvm_drop_host_privileges, NULL, cpu_online_mask);
 }
 
 static void __init pkvm_selftests(void)
Signature · 1 line
2.47.3
author reviewer
#8 lore raw

PATCH v4 8/13 irqchip/gic-v3-its: Add the pKVM takeover entry points

In reply to Fuad Tabba

From: Sebastian Ene <[email protected]>

In a subsequent patch the pKVM hypervisor takes the ITS command queue from the host. From then on, the driver writes its commands into a copy that the hypervisor checks before the ITS sees them.

Add the driver's side of the takeover, which KVM runs in three steps when it deprivileges the host. its_pkvm_setup_prepare() allocates the copy and the pages the hypervisor keeps its state in, and lists the devices already mapped, with their ITTs, as the ITS's own record of them is IMPLEMENTATION DEFINED. It holds every ITS's dev_alloc_lock until its_pkvm_setup_finish(), so the list stays exact.

its_pkvm_setup_commit() runs with every CPU stopped, and switches the driver to its copies only once the hypervisor has taken every ITS, so a failure leaves the driver on the hardware queues. If the commit fails, no CPU is deprivileged, and its_pkvm_setup_finish() frees everything prepare allocated, including the pages the hypervisor had taken.

its_pkvm_iter_its() gives KVM each ITS's base, so that KVM can register the control frames before the hypervisor initialises. These functions don't have a caller yet.

---
 drivers/irqchip/irq-gic-v3-its.c   | 183 +++++++++++++++++++++++++++++
 include/linux/irqchip/arm-gic-v3.h |  27 +++++
 2 files changed, 210 insertions(+)
drivers/irqchip/irq-gic-v3-its.c +183 -0
index df6d7b2fc8611..d98e05557a296 100644
@@ -92,6 +92,7 @@ struct its_baser {
 };
 
 struct its_device;
+struct its_pkvm_state;
 
 /*
  * The ITS structure - contains most of the infrastructure, with the
@@ -126,6 +127,7 @@ struct its_node {
 	unsigned int		msi_domain_flags;
 	u32			pre_its_base; /* for Socionext Synquacer */
 	int			vlpi_redist_offset;
+	struct its_pkvm_state	*pkvm;
 };
 
 static DEFINE_PER_CPU(struct its_node *, local_4_1_its);
@@ -5242,6 +5244,187 @@ static int __init its_compute_its_list_map(struct its_node *its)
 	return its_number;
 }
 
+/*
+ * In pKVM, the driver writes its commands into a copy of the command queue,
+ * and the hypervisor checks each one before the ITS sees it.
+ */
+struct its_pkvm_state {
+	void			*priv;
+	void			*cmdq;
+	struct its_pkvm_desc	*desc;
+	size_t			desc_size;
+};
+
+/* Held, with every ITS's dev_alloc_lock, from prepare to finish. */
+static DEFINE_MUTEX(its_pkvm_lock);
+
+/* Pages for the hypervisor's per-ITS state. */
+#define ITS_PKVM_PRIV_ORDER	3
+
+static int __init its_pkvm_alloc_copies(struct its_node *its,
+					struct its_pkvm_state *st)
+{
+	struct page *page;
+
+	page = its_alloc_pages_node(its->numa_node, GFP_KERNEL, ITS_PKVM_PRIV_ORDER);
+	if (!page)
+		return -ENOMEM;
+	st->priv = page_address(page);
+
+	page = its_alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO,
+				    get_order(ITS_CMD_QUEUE_SZ));
+	if (!page)
+		return -ENOMEM;
+	st->cmdq = page_address(page);
+
+	return 0;
+}
+
+static int __init its_pkvm_prepare_one(struct its_node *its)
+{
+	struct its_pkvm_desc *desc;
+	struct its_pkvm_state *st;
+	struct its_device *dev;
+	struct page *page;
+	u32 nr_devices;
+	int i, ret;
+
+	st = kzalloc_obj(*st);
+	if (!st)
+		return -ENOMEM;
+	its->pkvm = st;
+
+	mutex_lock_nest_lock(&its->dev_alloc_lock, &its_pkvm_lock);
+
+	ret = its_pkvm_alloc_copies(its, st);
+	if (ret)
+		return ret;
+
+	nr_devices = list_count_nodes(&its->its_device_list);
+	st->desc_size = PAGE_ALIGN(struct_size(desc, devices, nr_devices));
+	page = its_alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO,
+				    get_order(st->desc_size));
+	if (!page)
+		return -ENOMEM;
+	desc = page_address(page);
+	st->desc = desc;
+
+	desc->priv_pa = virt_to_phys(st->priv);
+	desc->priv_pages = 1 << ITS_PKVM_PRIV_ORDER;
+	desc->cmdq_copy_pa = virt_to_phys(st->cmdq);
+
+	i = 0;
+	list_for_each_entry(dev, &its->its_device_list, entry) {
+		desc->devices[i].itt_pa = virt_to_phys(dev->itt);
+		desc->devices[i].device_id = dev->device_id;
+		desc->devices[i].event_bits = ilog2(dev->nr_ites);
+		i++;
+	}
+	desc->nr_devices = nr_devices;
+
+	return 0;
+}
+
+static int __init its_pkvm_hand_over(struct its_node *its,
+				     its_pkvm_setup_fn setup)
+{
+	struct its_pkvm_state *st = its->pkvm;
+
+	return setup(its->phys_base, st->desc, st->desc_size);
+}
+
+static void __init its_pkvm_switch(struct its_node *its)
+{
+	struct its_pkvm_state *st = its->pkvm;
+
+	its->cmd_write = (struct its_cmd_block *)st->cmdq + (its->cmd_write - its->cmd_base);
+	its->cmd_base = st->cmdq;
+	st->cmdq = NULL;
+	st->priv = NULL;
+}
+
+static void __init its_pkvm_finish_one(struct its_node *its)
+{
+	struct its_pkvm_state *st = its->pkvm;
+
+	if (st->priv)
+		its_free_pages(st->priv, ITS_PKVM_PRIV_ORDER);
+	if (st->cmdq)
+		its_free_pages(st->cmdq, get_order(ITS_CMD_QUEUE_SZ));
+
+	if (st->desc)
+		its_free_pages(st->desc, get_order(st->desc_size));
+
+	mutex_unlock(&its->dev_alloc_lock);
+	kfree(st);
+	its->pkvm = NULL;
+}
+
+/*
+ * KVM calls prepare, commit and finish, in that order, to hand every ITS to the
+ * hypervisor. Commit runs with the other CPUs stopped. Finish must follow
+ * prepare, whatever prepare or commit returned.
+ */
+int __init its_pkvm_setup_prepare(void)
+{
+	struct its_node *its;
+	int ret;
+
+	mutex_lock(&its_pkvm_lock);
+
+	list_for_each_entry(its, &its_nodes, entry) {
+		ret = its_pkvm_prepare_one(its);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+int __init its_pkvm_setup_commit(its_pkvm_setup_fn setup)
+{
+	struct its_node *its;
+	int ret;
+
+	/* The driver switches to its copies only once every ITS is taken. */
+	list_for_each_entry(its, &its_nodes, entry) {
+		ret = its_pkvm_hand_over(its, setup);
+		if (ret)
+			return ret;
+	}
+
+	list_for_each_entry(its, &its_nodes, entry)
+		its_pkvm_switch(its);
+
+	return 0;
+}
+
+void __init its_pkvm_setup_finish(void)
+{
+	struct its_node *its;
+
+	list_for_each_entry(its, &its_nodes, entry) {
+		if (its->pkvm)
+			its_pkvm_finish_one(its);
+	}
+
+	mutex_unlock(&its_pkvm_lock);
+}
+
+int __init its_pkvm_iter_its(its_pkvm_its_fn fn)
+{
+	struct its_node *its;
+	int ret;
+
+	list_for_each_entry(its, &its_nodes, entry) {
+		ret = fn(its->phys_base);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
 static int __init its_probe_one(struct its_node *its)
 {
 	u64 baser, tmp;
include/linux/irqchip/arm-gic-v3.h +27 -0
index e0bec40adf2b7..1d31d5a72e009 100644
@@ -679,6 +679,33 @@ static inline u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size
 #define its_cmd_get_target_addr(cmd)	its_cmd_mask_field(cmd, 2, 16, 32)
 #define its_cmd_get_validbit(cmd)	its_cmd_mask_field(cmd, 2, 63,  1)
 
+/* A device the driver mapped before the hypervisor took over the ITS. */
+struct its_pkvm_device {
+	phys_addr_t	itt_pa;
+	u32		device_id;
+	u8		event_bits;
+};
+
+/* Passed to the hypervisor at setup. Every address is physical and page-aligned. */
+struct its_pkvm_desc {
+	phys_addr_t		priv_pa;
+	u64			priv_pages;
+	phys_addr_t		cmdq_copy_pa;
+	u32			nr_devices;
+	struct its_pkvm_device	devices[];
+};
+
+/* Called with every CPU stopped, so it must not sleep. */
+typedef int (*its_pkvm_setup_fn)(phys_addr_t its_base,
+				 struct its_pkvm_desc *desc, size_t desc_size);
+
+typedef int (*its_pkvm_its_fn)(phys_addr_t its_base);
+
+int its_pkvm_setup_prepare(void);
+int its_pkvm_setup_commit(its_pkvm_setup_fn setup);
+void its_pkvm_setup_finish(void);
+int its_pkvm_iter_its(its_pkvm_its_fn fn);
+
 #endif
 
 #endif
Signature · 1 line
2.47.3
author reviewer
#9 lore raw

PATCH v4 9/13 KVM: arm64: Emulate the ITS command queue

In reply to Fuad Tabba

From: Sebastian Ene <[email protected]>

The ITS writes to the memory its commands point to, so a host that queues commands freely can aim those writes at the hypervisor or a protected guest.

Register each ITS's control frame with the hypervisor, so that every host access to it traps once the host is deprivileged. Each ITS takes one of the hypervisor's eight MMIO region slots, so on a host with more than eight ITSes KVM doesn't initialise in protected mode. Inside the stop_machine() callback that deprivileges the host, the hypervisor reads GITS_CBASER, GITS_CWRITER and GITS_CREADR itself, takes the queue and pins the driver's copy. If that fails, no CPU is deprivileged and KVM_CREATE_VM fails with -ENODEV.

On a GITS_CWRITER write, the hypervisor reads each new command once from the driver's copy of the queue, checks it and copies it into the hardware queue. For a rejected command, the host's GITS_CWRITER write takes a data abort, after the commands before it have been forwarded. For now that's a vLPI command or an unknown encoding, neither of which the driver queues.

An access aborts if its syndrome isn't valid, or if it is narrower than four bytes or misaligned. Reads go to the hardware for the registers the driver reads, each at the size the driver uses, and other reads abort. GITS_CREADR, which the driver reads at 32 bits, can be read at 64 bits too.

Writes abort, except to GITS_CWRITER, GITS_BASER<n>, GITS_CTLR and GITS_CBASER. The next patch restricts GITS_BASER<n>, and the driver writes GITS_CTLR and GITS_CBASER on suspend and resume. A GITS_CBASER write is accepted only with the ITS disabled and quiescent, and the hypervisor writes the value it read at setup in place of the host's. A write that enables the ITS aborts unless GITS_CBASER holds that value. While the ITS isn't quiescent, the hypervisor drops such a write rather than abort it, which leaves the ITS disabled. The driver re-enables the ITS from a syscore callback when a quiesce times out, and an abort there would take the host down.

Add to arm-gic-v3.h the GITS_CBASER, GITS_CWRITER and GITS_CREADR fields that the hypervisor decodes.

---
 arch/arm64/include/asm/kvm_asm.h              |   2 +
 arch/arm64/include/asm/kvm_hcall.h            |   2 +
 arch/arm64/include/asm/kvm_pkvm.h             |   4 +
 arch/arm64/kvm/arm.c                          |   4 +
 arch/arm64/kvm/hyp/include/nvhe/its_emulate.h |  16 +
 arch/arm64/kvm/hyp/nvhe/Makefile              |   3 +-
 arch/arm64/kvm/hyp/nvhe/hyp-main.c            |   8 +
 arch/arm64/kvm/hyp/nvhe/its_emulate.c         | 323 ++++++++++++++++++
 arch/arm64/kvm/hyp/nvhe/mem_protect.c         |  65 ++++
 arch/arm64/kvm/pkvm.c                         |  98 +++++-
 include/linux/irqchip/arm-gic-v3.h            |   5 +
 11 files changed, 527 insertions(+), 3 deletions(-)
 create mode 100644 arch/arm64/kvm/hyp/include/nvhe/its_emulate.h
 create mode 100644 arch/arm64/kvm/hyp/nvhe/its_emulate.c
arch/arm64/include/asm/kvm_asm.h +2 -0
index abda476e023de..339850e2702d0 100644
@@ -122,6 +122,8 @@ enum __kvm_host_smccc_func {
 	__KVM_HOST_SMCCC_FUNC___pkvm_vcpu_put,
 	__KVM_HOST_SMCCC_FUNC___pkvm_vcpu_sync_state,
 	__KVM_HOST_SMCCC_FUNC___pkvm_tlb_flush_vmid,
+	/* Called with kvm_protected_mode_initialized on, before __pkvm_prot_finalize. */
+	__KVM_HOST_SMCCC_FUNC___pkvm_its_emulate_setup,
 
 	MARKER(__KVM_HOST_SMCCC_FUNC_MAX)
 };
arch/arm64/include/asm/kvm_hcall.h +2 -0
index 5f77a8aa29635..0748232c387ec 100644
@@ -254,5 +254,7 @@ DECLARE_KVM_HOST_HCALL0(void, __pkvm_vcpu_put)
 DECLARE_KVM_HOST_HCALL0(void, __pkvm_vcpu_sync_state)
 DECLARE_KVM_HOST_HCALL(void, __pkvm_tlb_flush_vmid,
 	pkvm_handle_t, handle)
+DECLARE_KVM_HOST_HCALL(int, __pkvm_its_emulate_setup,
+	phys_addr_t, its_base, phys_addr_t, desc_pa, size_t, desc_size)
 
 #endif /* __ARM64_KVM_HCALL_H__ */
arch/arm64/include/asm/kvm_pkvm.h +4 -0
index 4695c35b31e1a..e1203b06ec7b3 100644
@@ -24,11 +24,15 @@ struct pkvm_protected_reg {
 	u64			pfn;
 	u64			nr_pages;
 	void __iomem		*hyp_va;
+	/* The ITS's state once it is taken. */
+	void			*priv;
 };
 
 extern struct pkvm_protected_reg kvm_nvhe_sym(pkvm_protected_regs)[];
 extern unsigned int kvm_nvhe_sym(num_protected_reg);
 
+int pkvm_register_its_regions(void);
+
 int pkvm_init_host_vm(struct kvm *kvm);
 int pkvm_create_hyp_vm(struct kvm *kvm);
 bool pkvm_hyp_vm_is_created(struct kvm *kvm);
arch/arm64/kvm/arm.c +4 -0
index 157bf4b812020..789f6ca13ae12 100644
@@ -3128,6 +3128,10 @@ static int __init init_hyp_mode(void)
 		if (err)
 			goto out_err;
 
+		err = pkvm_register_its_regions();
+		if (err)
+			goto out_err;
+
 		err = kvm_hyp_init_protection(hyp_va_bits);
 		if (err) {
 			kvm_err("Failed to init hyp memory protection\n");
arch/arm64/kvm/hyp/include/nvhe/its_emulate.h new file +16 -0
new file mode 100644
index 0000000000000..0b0d4aa25a5b7
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2026 Google LLC
+ * Author: Sebastian Ene <[email protected]>
+ */
+#ifndef __ARM64_KVM_NVHE_ITS_EMULATE_H__
+#define __ARM64_KVM_NVHE_ITS_EMULATE_H__
+
+#include <asm/kvm_pkvm.h>
+
+int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
+			   size_t desc_size);
+bool pkvm_its_emulate_handler(struct pkvm_protected_reg *region, u64 offset,
+			      bool write, u64 *val, u8 size);
+
+#endif /* __ARM64_KVM_NVHE_ITS_EMULATE_H__ */
arch/arm64/kvm/hyp/nvhe/Makefile +2 -1
index 56a7e2c05f73a..2c50940849782 100644
@@ -24,7 +24,8 @@ CFLAGS_switch.nvhe.o += -Wno-override-init
 
 hyp-obj-y := timer-sr.o sysreg-sr.o debug-sr.o switch.o tlb.o hyp-init.o host.o \
 	 hyp-main.o hyp-smp.o psci-relay.o alloc.o early_alloc.o page_alloc.o \
-	 cache.o setup.o mm.o mem_protect.o sys_regs.o pkvm.o stacktrace.o ffa.o
+	 cache.o setup.o mm.o mem_protect.o sys_regs.o pkvm.o stacktrace.o ffa.o \
+	 its_emulate.o
 hyp-obj-y += ../vgic-v3-sr.o ../aarch32.o ../vgic-v2-cpuif-proxy.o ../entry.o \
 	 ../hyp-entry.o ../exception.o ../pgtable.o ../vgic-v5-sr.o
 hyp-obj-y += ../../../kernel/smccc-call.o
arch/arm64/kvm/hyp/nvhe/hyp-main.c +8 -0
index 179d7c8277b88..5efaa32037a5b 100644
@@ -22,6 +22,7 @@
 
 #include <nvhe/alloc.h>
 #include <nvhe/ffa.h>
+#include <nvhe/its_emulate.h>
 #include <nvhe/mem_protect.h>
 #include <nvhe/mm.h>
 #include <nvhe/pkvm.h>
@@ -1169,6 +1170,12 @@ DEFINE_KVM_HOST_HCALL(void, __pkvm_tlb_flush_vmid,
 	put_pkvm_hyp_vm(hyp_vm);
 }
 
+DEFINE_KVM_HOST_HCALL(int, __pkvm_its_emulate_setup,
+	phys_addr_t, its_base, phys_addr_t, desc_pa, size_t, desc_size)
+{
+	return pkvm_its_emulate_setup(its_base, desc_pa, desc_size);
+}
+
 DEFINE_KVM_HOST_HCALL(void, __kvm_flush_cpu_context,
 	struct kvm_s2_mmu __kern *, mmu)
 {
@@ -1603,6 +1610,7 @@ static const hcall_t host_hcall[] = {
 	HANDLE_FUNC(__pkvm_vcpu_put),
 	HANDLE_FUNC(__pkvm_vcpu_sync_state),
 	HANDLE_FUNC(__pkvm_tlb_flush_vmid),
+	HANDLE_FUNC(__pkvm_its_emulate_setup),
 };
 
 static void handle_host_hcall(struct kvm_cpu_context *host_ctxt)
arch/arm64/kvm/hyp/nvhe/its_emulate.c new file +323 -0

323 lines not on this page · raw message

arch/arm64/kvm/hyp/nvhe/mem_protect.c +65 -0

87 lines not on this page · raw message

arch/arm64/kvm/pkvm.c +96 -2

133 lines not on this page · raw message

include/linux/irqchip/arm-gic-v3.h +5 -0
index 1d31d5a72e009..01110162914f7 100644
@@ -435,6 +435,11 @@
 #define GITS_CBASER_RaWaWb	GIC_BASER_CACHEABILITY(GITS_CBASER, INNER, RaWaWb)
 
 #define GITS_CBASER_ADDRESS(cbaser)	((cbaser) & GENMASK_ULL(51, 12))
+#define GITS_CBASER_SIZE		GENMASK_ULL(7, 0)
+
+#define GITS_CWRITER_RETRY		(1ULL << 0)
+#define GITS_CWRITER_OFFSET		GENMASK_ULL(19, 5)
+#define GITS_CREADR_OFFSET		GENMASK_ULL(19, 5)
 
 #define GITS_BASER_NR_REGS		8
 
Signature · 1 line
2.47.3
author reviewer
#10 lore raw

PATCH v4 10/13 KVM: arm64: Take the ITS tables and restrict GITS_BASER<n>

In reply to Fuad Tabba

The ITS writes device and collection entries into the tables GITS_BASER<n> points to. At setup the hypervisor takes every such table and every level-2 page an indirect device table already points to. That includes the vPE table, which the driver allocates whether or not GICv4 is in use. With GICv4 off for the host, only the device table gains level-2 pages after setup.

From the takeover on, the driver writes new level-1 entries into a copy of the device table, which the hypervisor pins. On the first MAPD that needs a new entry, the hypervisor publishes the copy's entry if the entry holds only Valid and the address of an aligned level-2 page, and takes and zeroes that page. A MAPD whose entry stays invalid is rejected, and so is a MAPD past the end of a flat device table.

A GITS_BASER<n> write is now accepted only with the ITS disabled and quiescent, and only for a register that pointed to a table at setup. The hypervisor then writes the value it read at setup in place of the host's, and an enable aborts unless every such register still holds it.

---
 arch/arm64/kvm/hyp/nvhe/its_emulate.c | 252 +++++++++++++++++++++++++-
 drivers/irqchip/irq-gic-v3-its.c      |  30 ++-
 include/linux/irqchip/arm-gic-v3.h    |   7 +-
 3 files changed, 280 insertions(+), 9 deletions(-)
arch/arm64/kvm/hyp/nvhe/its_emulate.c +246 -6
index dd077abb1b24b..145997d54ce72 100644
@@ -17,11 +17,25 @@
 #include <nvhe/memory.h>
 #include <nvhe/spinlock.h>
 
+/* A GITS_BASER<n> table, as the register described it at setup. */
+struct its_table {
+	/* The hardware table, which is hyp-owned, and the host's pinned copy of its level 1. */
+	void			*hw;
+	void			*l1_copy;
+	u64			baser;
+	size_t			size;
+	u32			psz;
+	u8			esz;
+	bool			indirect;
+};
+
 /* Per-ITS state, in the pages the host donated at setup. */
 struct its_priv {
 	hyp_spinlock_t		lock;
 	void __iomem		*base;
 	u64			cbaser;
+	struct its_table	tables[GITS_BASER_NR_REGS];
+	struct its_table	*dev_table;
 
 	/* The hardware queue, which is hyp-owned, and the host's pinned copy of it. */
 	void			*cmdq_hw;
@@ -50,10 +64,75 @@ static int its_pin_host_pages(phys_addr_t pa, u64 nr_pages)
 	return hyp_pin_shared_mem(va, va + (nr_pages << PAGE_SHIFT));
 }
 
+static size_t its_l2_size(struct its_table *t)
+{
+	return PAGE_ALIGN(t->psz);
+}
+
+/*
+ * The ITS discards a device table write through an invalid level-1 entry, so
+ * make the entry for device_id valid from the host's copy. A hardware entry
+ * only ever goes from invalid to valid.
+ */
+static bool its_publish_l1(struct its_priv *its, u32 device_id)
+{
+	struct its_table *t = its->dev_table;
+	size_t l2_size;
+	u64 idx, entry;
+	phys_addr_t pa;
+	__le64 *hw;
+
+	/* Without a device table in memory there is no level-1 entry to publish. */
+	if (!t)
+		return true;
+
+	if (!t->indirect)
+		return device_id < t->size / t->esz;
+
+	idx = device_id / (t->psz / t->esz);
+	if (idx >= t->size / GITS_LVL1_ENTRY_SIZE)
+		return false;
+
+	hw = t->hw;
+	if (le64_to_cpu(hw[idx]) & GITS_BASER_VALID)
+		return true;
+
+	/* Read the entry once, as the host can change its copy. */
+	entry = le64_to_cpu(READ_ONCE(((__le64 *)t->l1_copy)[idx]));
+
+	l2_size = its_l2_size(t);
+	pa = GITS_LVL1_ADDRESS(entry);
+	if (entry != (pa | GITS_BASER_VALID) || !IS_ALIGNED(pa, l2_size))
+		return false;
+	if (__pkvm_host_donate_hyp(PHYS_PFN(pa), l2_size >> PAGE_SHIFT))
+		return false;
+
+	/* Using a new level-2 table that isn't all zeros is UNPREDICTABLE. */
+	memset(hyp_phys_to_virt(pa), 0, l2_size);
+	if (!(t->baser & GITS_BASER_SHAREABILITY_MASK))
+		gic_flush_dcache_to_poc(hyp_phys_to_virt(pa), l2_size);
+	/* The ITS can walk a valid entry at any time, so order the zeroing before it. */
+	dma_wmb();
+	hw[idx] = cpu_to_le64(entry);
+	if (!(t->baser & GITS_BASER_SHAREABILITY_MASK))
+		gic_flush_dcache_to_poc(&hw[idx], sizeof(*hw));
+	/* Make the entry visible to the ITS before the command that relies on it is queued. */
+	dsb(sy);
+	return true;
+}
+
+static bool its_mapd(struct its_priv *its, struct its_cmd_block *cmd)
+{
+	u32 device_id = its_cmd_get_deviceid(cmd->raw_cmd);
+
+	return its_publish_l1(its, device_id);
+}
+
 static bool its_process_cmd(struct its_priv *its, struct its_cmd_block *cmd)
 {
 	switch (its_cmd_get_command(cmd->raw_cmd)) {
 	case GITS_CMD_MAPD:
+		return its_mapd(its, cmd);
 	case GITS_CMD_MAPC:
 	case GITS_CMD_MAPTI:
 	case GITS_CMD_MAPI:
@@ -128,10 +207,26 @@ static bool its_cwriter_write(struct its_priv *its, u64 val)
 	return !rejected;
 }
 
-/* A reset clears GITS_CBASER.Valid, and an enable with it clear is UNPREDICTABLE. */
+/*
+ * A reset clears the Valid bits of GITS_CBASER and GITS_BASER<n>, and enabling the
+ * ITS with the Valid bit of GITS_CBASER or of the device table clear is UNPREDICTABLE.
+ */
 static bool its_bases_intact(struct its_priv *its)
 {
-	return readq_relaxed(its->base + GITS_CBASER) == its->cbaser;
+	unsigned int n;
+
+	if (readq_relaxed(its->base + GITS_CBASER) != its->cbaser)
+		return false;
+
+	for (n = 0; n < GITS_BASER_NR_REGS; n++) {
+		u64 baser = its->tables[n].baser;
+
+		if ((baser & GITS_BASER_VALID) &&
+		    readq_relaxed(its->base + GITS_BASER + n * sizeof(u64)) != baser)
+			return false;
+	}
+
+	return true;
 }
 
 static bool its_ctlr_write(struct its_priv *its, u64 val)
@@ -175,6 +270,21 @@ static bool its_cbaser_write(struct its_priv *its)
 	return true;
 }
 
+static bool its_baser_write(struct its_priv *its, unsigned int index)
+{
+	u64 baser = its->tables[index].baser;
+
+	if (!its_disabled_quiescent(its))
+		return false;
+
+	/* Refuse a table the hypervisor didn't take, as the driver never restores one. */
+	if (!(baser & GITS_BASER_VALID))
+		return false;
+
+	writeq_relaxed(baser, its->base + GITS_BASER + index * sizeof(u64));
+	return true;
+}
+
 static bool its_emulate(struct its_priv *its, u64 offset, bool write, u64 *val, u8 size)
 {
 	if (write) {
@@ -187,10 +297,8 @@ static bool its_emulate(struct its_priv *its, u64 offset, bool write, u64 *val,
 			/* The driver writes the low word, and the high word is RES0. */
 			return its_cwriter_write(its, *val);
 		case GITS_BASER ... GITS_BASER + (GITS_BASER_NR_REGS - 1) * sizeof(u64):
-			if (size != sizeof(u64))
-				return false;
-			writeq_relaxed(*val, its->base + offset);
-			return true;
+			return size == sizeof(u64) &&
+			       its_baser_write(its, (offset - GITS_BASER) / sizeof(u64));
 		default:
 			return false;
 		}
@@ -275,6 +383,134 @@ static int its_take_cmdq(struct its_priv *its, phys_addr_t copy_pa)
 	return 0;
 }
 
+static u32 its_baser_psz(u64 baser)
+{
+	switch (FIELD_GET(GITS_BASER_PAGE_SIZE_MASK, baser)) {
+	case GIC_PAGE_SIZE_4K:
+		return SZ_4K;
+	case GIC_PAGE_SIZE_16K:
+		return SZ_16K;
+	default:
+		/* 0b11 is reserved and treated as 64K. */
+		return SZ_64K;
+	}
+}
+
+static phys_addr_t its_baser_pa(u64 baser, u32 psz)
+{
+	/* With 64K pages, bits [15:12] of the register hold PA[51:48]. */
+	if (psz == SZ_64K)
+		return GITS_BASER_ADDR_48_to_52(baser);
+
+	return baser & GENMASK_ULL(47, 12);
+}
+
+static int its_take_level2(struct its_table *t)
+{
+	u64 nr_entries = t->size / GITS_LVL1_ENTRY_SIZE;
+	u64 l2_pages = its_l2_size(t) >> PAGE_SHIFT;
+	__le64 *table = t->hw;
+	u64 i, entry;
+	int ret;
+
+	for (i = 0; i < nr_entries; i++) {
+		entry = le64_to_cpu(table[i]);
+		if (!(entry & GITS_BASER_VALID))
+			continue;
+
+		ret = __pkvm_host_donate_hyp(PHYS_PFN(GITS_LVL1_ADDRESS(entry)), l2_pages);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+static int its_take_table(struct its_table *t, phys_addr_t copy_pa)
+{
+	u64 baser = t->baser, nr_pages;
+	phys_addr_t pa;
+	int ret;
+
+	t->psz = its_baser_psz(baser);
+	t->esz = GITS_BASER_ENTRY_SIZE(baser);
+	t->size = GITS_BASER_NR_PAGES(baser) * t->psz;
+	t->indirect = baser & GITS_BASER_INDIRECT;
+	pa = its_baser_pa(baser, t->psz);
+	nr_pages = DIV_ROUND_UP(t->size, PAGE_SIZE);
+
+	ret = __pkvm_host_donate_hyp(PHYS_PFN(pa), nr_pages);
+	if (ret)
+		return ret;
+	t->hw = hyp_phys_to_virt(pa);
+
+	if (!t->indirect)
+		return 0;
+
+	if (copy_pa) {
+		ret = its_pin_host_pages(copy_pa, nr_pages);
+		if (ret)
+			return ret;
+		t->l1_copy = hyp_phys_to_virt(copy_pa);
+	}
+
+	return its_take_level2(t);
+}
+
+/* GICv4.1 ITSes with a common affinity share one vPE table (GITS_TYPER.SVPET). */
+static bool its_vpe_table_taken(u64 baser)
+{
+	unsigned int i, n;
+
+	for (i = 0; i < num_protected_reg; i++) {
+		struct its_priv *its = pkvm_protected_regs[i].priv;
+
+		if (!its)
+			continue;
+
+		for (n = 0; n < GITS_BASER_NR_REGS; n++) {
+			if (its->tables[n].hw && its->tables[n].baser == baser)
+				return true;
+		}
+	}
+
+	return false;
+}
+
+static int its_take_tables(struct its_priv *its, struct its_pkvm_desc *desc)
+{
+	unsigned int n;
+	int ret;
+
+	for (n = 0; n < GITS_BASER_NR_REGS; n++) {
+		struct its_table *t = &its->tables[n];
+		phys_addr_t copy_pa = 0;
+
+		t->baser = readq_relaxed(its->base + GITS_BASER + n * sizeof(u64));
+		if (!(t->baser & GITS_BASER_VALID))
+			continue;
+
+		switch (GITS_BASER_TYPE(t->baser)) {
+		case GITS_BASER_TYPE_DEVICE:
+			/* The driver publishes level-1 entries through its copy. */
+			copy_pa = desc->dev_l1_copy_pa;
+			its->dev_table = t;
+			break;
+		case GITS_BASER_TYPE_VCPU:
+			/* Writing it while the ITS is enabled is UNPREDICTABLE, so take it. */
+			if (its_vpe_table_taken(t->baser))
+				continue;
+			break;
+		}
+
+		ret = its_take_table(t, copy_pa);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
 int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
 			   size_t desc_size)
 {
@@ -316,6 +552,10 @@ int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
 	if (ret)
 		return ret;
 
+	ret = its_take_tables(its, desc);
+	if (ret)
+		return ret;
+
 	WARN_ON(__pkvm_hyp_donate_host(PHYS_PFN(desc_pa), desc_pages));
 	/* Published by stop_machine()'s exit, and no host CPU traps until then. */
 	region->priv = its;
drivers/irqchip/irq-gic-v3-its.c +28 -2
index d98e05557a296..c00178249a04b 100644
@@ -5245,12 +5245,15 @@ static int __init its_compute_its_list_map(struct its_node *its)
 }
 
 /*
- * In pKVM, the driver writes its commands into a copy of the command queue,
- * and the hypervisor checks each one before the ITS sees it.
+ * In pKVM, the driver writes its commands into a copy of the command queue and
+ * its level-1 entries into a copy of the device table. The hypervisor checks
+ * each one before the ITS sees it.
  */
 struct its_pkvm_state {
 	void			*priv;
 	void			*cmdq;
+	struct its_baser	*dev_baser;
+	void			*dev_l1;
 	struct its_pkvm_desc	*desc;
 	size_t			desc_size;
 };
@@ -5264,6 +5267,7 @@ static DEFINE_MUTEX(its_pkvm_lock);
 static int __init its_pkvm_alloc_copies(struct its_node *its,
 					struct its_pkvm_state *st)
 {
+	struct its_baser *baser = its_get_baser(its, GITS_BASER_TYPE_DEVICE);
 	struct page *page;
 
 	page = its_alloc_pages_node(its->numa_node, GFP_KERNEL, ITS_PKVM_PRIV_ORDER);
@@ -5277,6 +5281,15 @@ static int __init its_pkvm_alloc_copies(struct its_node *its,
 		return -ENOMEM;
 	st->cmdq = page_address(page);
 
+	if (!baser || !(baser->val & GITS_BASER_INDIRECT))
+		return 0;
+
+	page = its_alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO, baser->order);
+	if (!page)
+		return -ENOMEM;
+	st->dev_baser = baser;
+	st->dev_l1 = page_address(page);
+
 	return 0;
 }
 
@@ -5312,6 +5325,8 @@ static int __init its_pkvm_prepare_one(struct its_node *its)
 	desc->priv_pa = virt_to_phys(st->priv);
 	desc->priv_pages = 1 << ITS_PKVM_PRIV_ORDER;
 	desc->cmdq_copy_pa = virt_to_phys(st->cmdq);
+	if (st->dev_l1)
+		desc->dev_l1_copy_pa = virt_to_phys(st->dev_l1);
 
 	i = 0;
 	list_for_each_entry(dev, &its->its_device_list, entry) {
@@ -5330,6 +5345,9 @@ static int __init its_pkvm_hand_over(struct its_node *its,
 {
 	struct its_pkvm_state *st = its->pkvm;
 
+	if (st->dev_l1)
+		memcpy(st->dev_l1, st->dev_baser->base, PAGE_ORDER_TO_SIZE(st->dev_baser->order));
+
 	return setup(its->phys_base, st->desc, st->desc_size);
 }
 
@@ -5341,6 +5359,12 @@ static void __init its_pkvm_switch(struct its_node *its)
 	its->cmd_base = st->cmdq;
 	st->cmdq = NULL;
 	st->priv = NULL;
+
+	/* val still holds the address of the hardware table, which the hypervisor now owns. */
+	if (st->dev_l1) {
+		st->dev_baser->base = st->dev_l1;
+		st->dev_l1 = NULL;
+	}
 }
 
 static void __init its_pkvm_finish_one(struct its_node *its)
@@ -5351,6 +5375,8 @@ static void __init its_pkvm_finish_one(struct its_node *its)
 		its_free_pages(st->priv, ITS_PKVM_PRIV_ORDER);
 	if (st->cmdq)
 		its_free_pages(st->cmdq, get_order(ITS_CMD_QUEUE_SZ));
+	if (st->dev_l1)
+		its_free_pages(st->dev_l1, st->dev_baser->order);
 
 	if (st->desc)
 		its_free_pages(st->desc, get_order(st->desc_size));
include/linux/irqchip/arm-gic-v3.h +6 -1
index 01110162914f7..5fc06ca11a53b 100644
@@ -498,6 +498,7 @@
 #define GITS_BASER_TYPE_RESERVED7	7
 
 #define GITS_LVL1_ENTRY_SIZE           (8UL)
+#define GITS_LVL1_ADDRESS(entry)	((entry) & GENMASK_ULL(51, 12))
 
 /*
  * ITS commands
@@ -691,11 +692,15 @@ struct its_pkvm_device {
 	u8		event_bits;
 };
 
-/* Passed to the hypervisor at setup. Every address is physical and page-aligned. */
+/*
+ * Passed to the hypervisor at setup. Every address is physical and page-aligned,
+ * and dev_l1_copy_pa is 0 unless the device table is indirect.
+ */
 struct its_pkvm_desc {
 	phys_addr_t		priv_pa;
 	u64			priv_pages;
 	phys_addr_t		cmdq_copy_pa;
+	phys_addr_t		dev_l1_copy_pa;
 	u32			nr_devices;
 	struct its_pkvm_device	devices[];
 };
Signature · 1 line
2.47.3
author reviewer
#11 lore raw

PATCH v4 11/13 KVM: arm64: Take the ITT of every device the host maps

In reply to Fuad Tabba

On a translation, the ITS indexes the collection and vPE tables with whatever ICID and vPEID the ITE holds. As "The format of the ITT entries is IMPLEMENTATION DEFINED" (IHI 0069H.b 5.3.10), the hypervisor can't check an ITT the host can write.

On a MAPD with V == 1, the hypervisor takes the ITT's pages and zeroes them before forwarding the command, and rejects the MAPD if the DeviceID is already mapped, the ITT isn't page-aligned or Size exceeds GITS_TYPER.ID_bits. It sizes the ITT from the MAPD's Size and GITS_TYPER.ITT_entry_size, except on QDF2400 rev 1, whose ITS writes 16-byte entries whatever ITT_entry_size holds (erratum 0065). The ITTs of the devices mapped before the takeover, which the driver lists, are taken without being zeroed.

A MAPD is UNPREDICTABLE when "There is an existing mapping for the DeviceID and the mapped ITT contains valid EventID mappings" (5.3.10), whether V is 0 or 1. If the host unmaps a device without discarding its events first, the ITS may go on using the ITT. The hypervisor doesn't track which events a device has mapped, so it never gives an ITT back. On a MAPD with V == 0 it marks the device retired, and a later MAPD for that DeviceID reuses the ITT, zeroed, if the command gives the same address and the ITT is large enough. If the command gives another address, the hypervisor takes the new ITT and keeps the old one too. The driver keeps a freed device's ITT as well, for the next device with its DeviceID, so in protected mode ITT memory doesn't go back to the kernel.

A GITS_CBASER write resets the queue, so it now aborts until the ITS has consumed every forwarded command, as a dropped MAPD would leave a device tracked that the ITS never mapped. The hypervisor counts the consumed commands from GITS_CREADR, which it reads when the host does and before a GITS_CWRITER or GITS_CTLR write. The driver writes GITS_CBASER only on resume, after its waits, so a resume aborts only if a wait timed out before suspend.

The hypervisor tracks a fixed number of DeviceIDs per ITS, about 1300 on a 4K host, and returns that number from the setup call. Retired ones are included, so that's a limit on the DeviceIDs mapped since boot. its_create_device() fails beyond that number rather than queue a MAPD the hypervisor would reject.

---
 arch/arm64/kvm/hyp/nvhe/its_emulate.c | 172 +++++++++++++++++++++++++-
 arch/arm64/kvm/pkvm.c                 |   2 +-
 drivers/irqchip/irq-gic-v3-its.c      |  66 +++++++++-
 include/linux/irqchip/arm-gic-v3.h    |   5 +-
 4 files changed, 231 insertions(+), 14 deletions(-)
arch/arm64/kvm/hyp/nvhe/its_emulate.c +166 -6
index 145997d54ce72..4a3659f727a94 100644
@@ -29,14 +29,31 @@ struct its_table {
 	bool			indirect;
 };
 
+/* A device the host has mapped. Once unmapped it is retired, and its ITT pages stay hyp-owned. */
+struct its_device_map {
+	phys_addr_t		itt_pa;
+	u32			device_id;
+	u32			nr_pages;
+	u8			event_bits;
+	bool			retired;
+};
+
 /* Per-ITS state, in the pages the host donated at setup. */
 struct its_priv {
 	hyp_spinlock_t		lock;
 	void __iomem		*base;
+	u64			typer;
 	u64			cbaser;
+	u8			id_bits;
+	u8			itt_entry_size;
 	struct its_table	tables[GITS_BASER_NR_REGS];
 	struct its_table	*dev_table;
 
+	/* Sorted by device_id, in the rest of the donated pages. */
+	struct its_device_map	*devices;
+	u32			nr_devices;
+	u32			max_devices;
+
 	/* The hardware queue, which is hyp-owned, and the host's pinned copy of it. */
 	void			*cmdq_hw;
 	void			*cmdq_copy;
@@ -47,6 +64,9 @@ struct its_priv {
 
 	/* The GITS_CREADR offset last read. */
 	u32			hw_creadr;
+	/* Commands forwarded to the ITS, and consumed by it. */
+	u64			seq_submitted;
+	u64			seq_completed;
 };
 
 static int its_pin_host_pages(phys_addr_t pa, u64 nr_pages)
@@ -121,11 +141,103 @@ static bool its_publish_l1(struct its_priv *its, u32 device_id)
 	return true;
 }
 
+/* The index of device_id, or where it would be inserted. */
+static u32 its_dev_search(struct its_priv *its, u32 device_id, bool *found)
+{
+	u32 lo = 0, hi = its->nr_devices;
+
+	while (lo < hi) {
+		u32 mid = lo + (hi - lo) / 2;
+
+		if (its->devices[mid].device_id < device_id)
+			lo = mid + 1;
+		else
+			hi = mid;
+	}
+
+	*found = lo < its->nr_devices && its->devices[lo].device_id == device_id;
+	return lo;
+}
+
+/*
+ * The driver page-aligns ITTs in pKVM. A MAPD on an ITT that isn't all zeros is
+ * UNPREDICTABLE, so @zero is set for a runtime MAPD. A retired device's ITT is
+ * reused if the MAPD gives its address and it is large enough.
+ */
+static int its_take_itt(struct its_priv *its, u32 device_id, u8 event_bits,
+			phys_addr_t itt_pa, bool zero)
+{
+	struct its_device_map *dev;
+	u32 idx, nr_pages;
+	size_t size;
+	bool found;
+	int ret;
+
+	if (event_bits > its->id_bits || !PAGE_ALIGNED(itt_pa))
+		return -EINVAL;
+
+	idx = its_dev_search(its, device_id, &found);
+	dev = &its->devices[idx];
+	if (found && !dev->retired)
+		return -EEXIST;
+	if (!found && its->nr_devices == its->max_devices)
+		return -ENOSPC;
+
+	size = PAGE_ALIGN(BIT_ULL(event_bits) * its->itt_entry_size);
+	nr_pages = size >> PAGE_SHIFT;
+	if (!found || itt_pa != dev->itt_pa || nr_pages > dev->nr_pages) {
+		ret = __pkvm_host_donate_hyp(PHYS_PFN(itt_pa), nr_pages);
+		if (ret)
+			return ret;
+	} else {
+		nr_pages = dev->nr_pages;
+	}
+
+	if (zero) {
+		memset(hyp_phys_to_virt(itt_pa), 0, size);
+		gic_flush_dcache_to_poc(hyp_phys_to_virt(itt_pa), size);
+	}
+
+	if (!found) {
+		memmove(dev + 1, dev, (its->nr_devices - idx) * sizeof(*dev));
+		its->nr_devices++;
+	}
+	*dev = (struct its_device_map) {
+		.itt_pa = itt_pa,
+		.device_id = device_id,
+		.nr_pages = nr_pages,
+		.event_bits = event_bits,
+	};
+	return 0;
+}
+
+/*
+ * A MAPD with V == 0 is UNPREDICTABLE while the ITT holds valid ITEs. The ITS may
+ * then go on using the ITT, so it is never given back to the host.
+ */
+static void its_retire(struct its_priv *its, u32 device_id)
+{
+	bool found;
+	u32 idx;
+
+	idx = its_dev_search(its, device_id, &found);
+	if (found)
+		its->devices[idx].retired = true;
+}
+
 static bool its_mapd(struct its_priv *its, struct its_cmd_block *cmd)
 {
 	u32 device_id = its_cmd_get_deviceid(cmd->raw_cmd);
 
-	return its_publish_l1(its, device_id);
+	if (!its_publish_l1(its, device_id))
+		return false;
+
+	if (its_cmd_get_validbit(cmd->raw_cmd))
+		return !its_take_itt(its, device_id, its_cmd_get_size(cmd->raw_cmd),
+				     its_cmd_get_ittaddr(cmd->raw_cmd), true);
+
+	its_retire(its, device_id);
+	return true;
 }
 
 static bool its_process_cmd(struct its_priv *its, struct its_cmd_block *cmd)
@@ -151,11 +263,19 @@ static bool its_process_cmd(struct its_priv *its, struct its_cmd_block *cmd)
 	}
 }
 
+/* Count the commands consumed since the last read. */
 static u64 its_read_creadr(struct its_priv *its)
 {
 	u64 creadr = readq_relaxed(its->base + GITS_CREADR);
 	u32 offset = creadr & GITS_CREADR_OFFSET;
 
+	/*
+	 * A disabled ITS consumes no commands, so GITS_CREADR moving while it is
+	 * disabled, as after a reset behind the hypervisor, isn't progress.
+	 */
+	if (readl_relaxed(its->base + GITS_CTLR) & GITS_CTLR_ENABLE)
+		its->seq_completed += ((offset + its->cmdq_size - its->hw_creadr) %
+				       its->cmdq_size) / sizeof(struct its_cmd_block);
 	its->hw_creadr = offset;
 
 	return creadr;
@@ -199,6 +319,7 @@ static bool its_cwriter_write(struct its_priv *its, u64 val)
 		 */
 		gic_flush_dcache_to_poc(its->cmdq_hw + its->cmd_offset, sizeof(cmd));
 		its->cmd_offset = (its->cmd_offset + sizeof(cmd)) % its->cmdq_size;
+		its->seq_submitted++;
 	}
 
 	dsb(ishst);
@@ -231,7 +352,11 @@ static bool its_bases_intact(struct its_priv *its)
 
 static bool its_ctlr_write(struct its_priv *its, u64 val)
 {
-	u32 ctlr = readl_relaxed(its->base + GITS_CTLR);
+	u32 ctlr;
+
+	/* Read while still disabled, so a reset GITS_CREADR isn't counted as progress. */
+	its_read_creadr(its);
+	ctlr = readl_relaxed(its->base + GITS_CTLR);
 
 	if ((val & GITS_CTLR_ENABLE) && !(ctlr & GITS_CTLR_ENABLE)) {
 		/*
@@ -258,12 +383,13 @@ static bool its_disabled_quiescent(struct its_priv *its)
 
 static bool its_cbaser_write(struct its_priv *its)
 {
-	if (!its_disabled_quiescent(its))
+	/* The write resets the queue, and the ITS drops any command it hasn't consumed. */
+	if (!its_disabled_quiescent(its) || its->seq_completed != its->seq_submitted)
 		return false;
 
 	writeq_relaxed(its->cbaser, its->base + GITS_CBASER);
 
-	/* The write reset GITS_CREADR to 0, and the ITS drops what was queued before it. */
+	/* The write reset GITS_CREADR to 0. */
 	its->cmd_offset = 0;
 	its->hw_creadr = 0;
 	writeq_relaxed(0, its->base + GITS_CWRITER);
@@ -320,7 +446,10 @@ static bool its_emulate(struct its_priv *its, u64 offset, bool write, u64 *val,
 			return false;
 		break;
 	case GITS_CREADR:
-		break;
+		*val = its_read_creadr(its);
+		if (size == sizeof(u32))
+			*val = lower_32_bits(*val);
+		return true;
 	default:
 		return false;
 	}
@@ -380,6 +509,8 @@ static int its_take_cmdq(struct its_priv *its, phys_addr_t copy_pa)
 	its->cmdq_size = size;
 	its->cmd_offset = cwriter;
 	its->hw_creadr = creadr;
+	/* Commands the host queued before setup are submitted, not yet consumed. */
+	its->seq_submitted = ((cwriter + size - creadr) % size) / sizeof(struct its_cmd_block);
 	return 0;
 }
 
@@ -511,6 +642,22 @@ static int its_take_tables(struct its_priv *its, struct its_pkvm_desc *desc)
 	return 0;
 }
 
+static int its_take_devices(struct its_priv *its, struct its_pkvm_desc *desc)
+{
+	int ret;
+	u32 i;
+
+	for (i = 0; i < desc->nr_devices; i++) {
+		struct its_pkvm_device dev = desc->devices[i];
+
+		ret = its_take_itt(its, dev.device_id, dev.event_bits, dev.itt_pa, false);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
 int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
 			   size_t desc_size)
 {
@@ -546,7 +693,16 @@ int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
 
 	hyp_spin_lock_init(&its->lock);
 	its->base = region->hyp_va;
+	its->typer = readq_relaxed(its->base + GITS_TYPER);
 	its->cbaser = readq_relaxed(its->base + GITS_CBASER);
+	its->id_bits = FIELD_GET(GITS_TYPER_IDBITS, its->typer) + 1;
+	its->itt_entry_size = FIELD_GET(GITS_TYPER_ITT_ENTRY_SIZE, its->typer) + 1;
+	its->devices = (void *)(its + 1);
+	its->max_devices = (priv_pages * PAGE_SIZE - sizeof(*its)) / sizeof(*its->devices);
+
+	/* QDF2400 rev 1.x, erratum 0065: the ITS writes 16-byte ITEs where GITS_TYPER says 8. */
+	if (readl_relaxed(its->base + GITS_IIDR) == 0x00001070)
+		its->itt_entry_size = 16;
 
 	ret = its_take_cmdq(its, desc->cmdq_copy_pa);
 	if (ret)
@@ -556,8 +712,12 @@ int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
 	if (ret)
 		return ret;
 
+	ret = its_take_devices(its, desc);
+	if (ret)
+		return ret;
+
 	WARN_ON(__pkvm_hyp_donate_host(PHYS_PFN(desc_pa), desc_pages));
 	/* Published by stop_machine()'s exit, and no host CPU traps until then. */
 	region->priv = its;
-	return 0;
+	return its->max_devices;
 }
arch/arm64/kvm/pkvm.c +1 -1
index ddd797d21d42d..03854cc84a9f9 100644
@@ -85,7 +85,7 @@ static int __init pkvm_init_its_emulation(phys_addr_t its_base,
 	int ret;
 
 	ret = kvm_call_hyp_nvhe(__pkvm_its_emulate_setup, its_base, virt_to_phys(desc), desc_size);
-	if (ret)
+	if (ret < 0)
 		kvm_err("ITS@%pa: emulation setup failed: %d\n", &its_base, ret);
 
 	return ret;
drivers/irqchip/irq-gic-v3-its.c +60 -6

153 lines not on this page · raw message

include/linux/irqchip/arm-gic-v3.h +4 -1
index 5fc06ca11a53b..cc6279087678f 100644
@@ -705,7 +705,10 @@ struct its_pkvm_desc {
 	struct its_pkvm_device	devices[];
 };
 
-/* Called with every CPU stopped, so it must not sleep. */
+/*
+ * Returns < 0 or the number of devices the hypervisor can track on this ITS.
+ * Called with every CPU stopped, so it must not sleep.
+ */
 typedef int (*its_pkvm_setup_fn)(phys_addr_t its_base,
 				 struct its_pkvm_desc *desc, size_t desc_size);
 
Signature · 1 line
2.47.3
author reviewer
#12 lore raw

PATCH v4 12/13 KVM: arm64: Reject ITS commands whose IDs are out of range

In reply to Fuad Tabba

The ITS can't be relied on to reject a command with an out-of-range ID. IHI 0069H.b 5.3.2 makes the response to a command error CONSTRAINED UNPREDICTABLE, and one permitted outcome is "The data that generated the error or errors is treated as having a legal value, and the command is processed accordingly". With an out-of-range DeviceID, EventID or ICID, the ITS then accesses memory past the device table, the ITT or the collection table.

Bound each ID before forwarding the command. The DeviceID is bounded by GITS_TYPER.Devbits and the device table, the EventID by the size its device was mapped with, and the ICID by the ICID width and the number of collections. A device that isn't mapped, a retired one included, has no EventID in range. The driver never allocates an out-of-range DeviceID or EventID, and never sends a command for a device it has unmapped. Its ICIDs are CPU numbers, and a CPU's number is out of range only where the ITS itself treats the MAPC for that CPU's collection as a command error. Once the hypervisor has the ITS, a command with such an ICID gives the host a data abort instead.

MAPTI's pINTID, which the ITS only stores in the ITE, and the RDbase of MAPC, MOVALL and SYNC are left to the redistributor series that will follow this one.

---
 arch/arm64/kvm/hyp/nvhe/its_emulate.c | 48 +++++++++++++++++++++++++--
 include/linux/irqchip/arm-gic-v3.h    |  3 ++
 2 files changed, 48 insertions(+), 3 deletions(-)
arch/arm64/kvm/hyp/nvhe/its_emulate.c +45 -3
index 4a3659f727a94..e7040de69a75a 100644
@@ -46,8 +46,12 @@ struct its_priv {
 	u64			cbaser;
 	u8			id_bits;
 	u8			itt_entry_size;
+	u8			dev_bits;
+	u8			icid_bits;
+	u32			max_collections;
 	struct its_table	tables[GITS_BASER_NR_REGS];
 	struct its_table	*dev_table;
+	struct its_table	*coll_table;
 
 	/* Sorted by device_id, in the rest of the donated pages. */
 	struct its_device_map	*devices;
@@ -229,7 +233,7 @@ static bool its_mapd(struct its_priv *its, struct its_cmd_block *cmd)
 {
 	u32 device_id = its_cmd_get_deviceid(cmd->raw_cmd);
 
-	if (!its_publish_l1(its, device_id))
+	if (device_id >= BIT_ULL(its->dev_bits) || !its_publish_l1(its, device_id))
 		return false;
 
 	if (its_cmd_get_validbit(cmd->raw_cmd))
@@ -240,21 +244,41 @@ static bool its_mapd(struct its_priv *its, struct its_cmd_block *cmd)
 	return true;
 }
 
+/* An event of a retired device is out of range too. */
+static bool its_event_in_range(struct its_priv *its, struct its_cmd_block *cmd)
+{
+	struct its_device_map *dev;
+	bool found;
+
+	dev = &its->devices[its_dev_search(its, its_cmd_get_deviceid(cmd->raw_cmd), &found)];
+	return found && !dev->retired && its_cmd_get_id(cmd->raw_cmd) < BIT_ULL(dev->event_bits);
+}
+
+static bool its_collection_in_range(struct its_priv *its, struct its_cmd_block *cmd)
+{
+	u32 icid = its_cmd_get_collection(cmd->raw_cmd);
+
+	return icid < BIT_ULL(its->icid_bits) && icid < its->max_collections;
+}
+
 static bool its_process_cmd(struct its_priv *its, struct its_cmd_block *cmd)
 {
 	switch (its_cmd_get_command(cmd->raw_cmd)) {
 	case GITS_CMD_MAPD:
 		return its_mapd(its, cmd);
 	case GITS_CMD_MAPC:
+	case GITS_CMD_INVALL:
+		return its_collection_in_range(its, cmd);
 	case GITS_CMD_MAPTI:
 	case GITS_CMD_MAPI:
 	case GITS_CMD_MOVI:
+		return its_event_in_range(its, cmd) && its_collection_in_range(its, cmd);
 	case GITS_CMD_DISCARD:
 	case GITS_CMD_INV:
-	case GITS_CMD_MOVALL:
-	case GITS_CMD_INVALL:
 	case GITS_CMD_INT:
 	case GITS_CMD_CLEAR:
+		return its_event_in_range(its, cmd);
+	case GITS_CMD_MOVALL:
 	case GITS_CMD_SYNC:
 		return true;
 	default:
@@ -627,6 +651,9 @@ static int its_take_tables(struct its_priv *its, struct its_pkvm_desc *desc)
 			copy_pa = desc->dev_l1_copy_pa;
 			its->dev_table = t;
 			break;
+		case GITS_BASER_TYPE_COLLECTION:
+			its->coll_table = t;
+			break;
 		case GITS_BASER_TYPE_VCPU:
 			/* Writing it while the ITS is enabled is UNPREDICTABLE, so take it. */
 			if (its_vpe_table_taken(t->baser))
@@ -642,6 +669,17 @@ static int its_take_tables(struct its_priv *its, struct its_pkvm_desc *desc)
 	return 0;
 }
 
+/* GITS_TYPER.CCT indicates whether the ITS's HCC collections add to those in the memory table. */
+static u32 its_collection_count(struct its_priv *its)
+{
+	u32 hcc = GITS_TYPER_HCC(its->typer), in_mem = 0;
+
+	if (its->coll_table)
+		in_mem = its->coll_table->size / its->coll_table->esz;
+
+	return its->typer & GITS_TYPER_CCT ? hcc + in_mem : max(hcc, in_mem);
+}
+
 static int its_take_devices(struct its_priv *its, struct its_pkvm_desc *desc)
 {
 	int ret;
@@ -697,6 +735,9 @@ int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
 	its->cbaser = readq_relaxed(its->base + GITS_CBASER);
 	its->id_bits = FIELD_GET(GITS_TYPER_IDBITS, its->typer) + 1;
 	its->itt_entry_size = FIELD_GET(GITS_TYPER_ITT_ENTRY_SIZE, its->typer) + 1;
+	its->dev_bits = FIELD_GET(GITS_TYPER_DEVBITS, its->typer) + 1;
+	its->icid_bits = its->typer & GITS_TYPER_CIL ?
+			 FIELD_GET(GITS_TYPER_CIDBITS, its->typer) + 1 : 16;
 	its->devices = (void *)(its + 1);
 	its->max_devices = (priv_pages * PAGE_SIZE - sizeof(*its)) / sizeof(*its->devices);
 
@@ -711,6 +752,7 @@ int pkvm_its_emulate_setup(phys_addr_t its_base, phys_addr_t desc_pa,
 	ret = its_take_tables(its, desc);
 	if (ret)
 		return ret;
+	its->max_collections = its_collection_count(its);
 
 	ret = its_take_devices(its, desc);
 	if (ret)
include/linux/irqchip/arm-gic-v3.h +3 -0
index cc6279087678f..b1b8fcc85fbe5 100644
@@ -392,6 +392,7 @@
 
 #define GITS_TYPER_PLPIS		(1UL << 0)
 #define GITS_TYPER_VLPIS		(1UL << 1)
+#define GITS_TYPER_CCT			(1UL << 2)
 #define GITS_TYPER_ITT_ENTRY_SIZE_SHIFT	4
 #define GITS_TYPER_ITT_ENTRY_SIZE	GENMASK_ULL(7, 4)
 #define GITS_TYPER_IDBITS		GENMASK_ULL(12, 8)
@@ -401,6 +402,8 @@
 #define GITS_TYPER_PTA			(1UL << 19)
 #define GITS_TYPER_HCC_SHIFT		24
 #define GITS_TYPER_HCC(r)		(((r) >> GITS_TYPER_HCC_SHIFT) & 0xff)
+#define GITS_TYPER_CIDBITS		GENMASK_ULL(35, 32)
+#define GITS_TYPER_CIL			(1ULL << 36)
 #define GITS_TYPER_VMOVP		(1ULL << 37)
 #define GITS_TYPER_VMAPP		(1ULL << 40)
 #define GITS_TYPER_SVPET		GENMASK_ULL(42, 41)
Signature · 1 line
2.47.3
author reviewer
#13 lore raw

PATCH v4 13/13 Documentation: KVM: arm64: Describe the ITS hardening

In reply to Fuad Tabba

Describe in pkvm.rst why the hypervisor emulates the host's ITS, and how protected mode differs from non-protected mode as a result.

---
 Documentation/virt/kvm/arm/pkvm.rst | 34 +++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
Documentation/virt/kvm/arm/pkvm.rst +34 -0
index b75bb8ad6f26d..c1b1b8089ff72 100644
@@ -89,6 +89,40 @@ DMA isolation using an IOMMU
 
 Status: **Unimplemented.**
 
+GICv3 ITS hardening
+-------------------
+
+Status: Host accesses to the ITS control registers are trapped and
+emulated by the hypervisor. The LPI configuration and pending tables
+remain under host control.
+
+The ITS reads and writes memory at addresses programmed by the host, so
+the hypervisor emulates the ITS control registers and command queue to
+ensure that the host cannot point the ITS command queue or tables at
+hypervisor or pVM memory. The hypervisor owns the command queue and
+the ITS tables for as long as the ITS can access them, and it owns each
+device's interrupt translation table from the device's first mapping
+onwards.
+
+This gives rise to some user-visible differences when compared to
+non-protected mode:
+
+* Protected mode requires the hypervisor to take control of every ITS
+  that the host uses. KVM does not initialise with more than 8 ITSes, and
+  if the takeover fails the host is not deprivileged and
+  ``KVM_CREATE_VM`` returns ``-ENODEV``.
+* An ITS command or register access that the hypervisor rejects is
+  delivered to the host as a data abort.
+* The number of device IDs used through each ITS since boot is limited
+  by the hypervisor, and MSI allocation fails with ``-ENOMEM`` beyond
+  that limit.
+* Interrupt translation tables are page-aligned and are not freed when
+  a device is removed, so each device ID used since boot holds at least
+  one page.
+* GICv4 is disabled. Direct injection of LPIs is not available to
+  non-protected guests, and restoring a guest migrated from a host with
+  ``GICD_TYPER2.nASSGIcap`` set fails with ``-EINVAL``.
+
 Proxying of Trustzone services
 ------------------------------
 
Signature · 1 line
2.47.3