Skip to contentSkip to conversation

s390/vfio-ap: fix leaks when PQAP(AQIC) enable is not accepted

PATCH New Anthony Krowiak 1 participant 16 messages Nov 13 1 message not in the archive

Subsystems (4)
lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): [email protected]

Anthony Krowiak

author maintainer
#1 lore raw

PATCH 2/20 s390/vfio-ap: mark queue not passable if reset verification fails

When apq_reset_check() gets an invalid response code from PQAP(TAPQ) it returns without recording anything in q->reset_status. That indicates a hardware or firmware problem, and it cannot be determined whether the queue can still DMA-write to the NIB, so the AQIC resources are intentionally left allocated. However, q->reset_status still holds the result of the ZAPQ that started the reset, which is typically AP_RESPONSE_NORMAL. As a consequence _queue_passable(), which checks for AP_RESPONSE_NORMAL, considers the queue passable and it can be passed through to a guest even though the reset could not be verified.

Copy the TAPQ status to q->reset_status in the -EIO path so the queue is marked not passable.

Fixes 9261f0438835 ("s390/vfio-ap: use work struct to verify queue reset")
---
 drivers/s390/crypto/vfio_ap_ops.c | 28 +++++++++++++++++++++++++++-
 1 file changed, 27 insertions(+), 1 deletion(-)
drivers/s390/crypto/vfio_ap_ops.c +27 -1
index 742e42ea0ec0..e6ffdd75af8a 100644
@@ -1969,8 +1969,25 @@ static void apq_reset_check(struct work_struct *reset_work)
 		elapsed += AP_RESET_INTERVAL;
 		status = ap_tapq(q->apqn, NULL);
 		ret = apq_status_check(q->apqn, &status);
-		if (ret == -EIO)
+		if (ret == -EIO) {
+			/*
+			 * TAPQ returned an invalid response code indicating a
+			 * hardware or firmware bug. Since we cannot determine
+			 * whether the queue can still DMA-write to the NIB, the
+			 * AQIC resources are intentionally leaked lest the NIB
+			 * page is reallocated to a new owner. A subsequent
+			 * wild DMA-write to that physical address would corrupt
+			 * the new owner's memory which could crash or compromise
+			 * the host kernel.
+			 *
+			 * Record the TAPQ status so the queue is marked
+			 * not-passable - _queue_passable() checks
+			 * reset_status.response_code == AP_RESPONSE_NORMAL -
+			 * and the queue is not passed through to a guest.
+			 */
+			memcpy(&q->reset_status, &status, sizeof(status));
 			return;
+		}
 		if (ret == -ENODEV) {
 			vfio_ap_free_aqic_resources(q);
 			return;
@@ -2034,6 +2051,15 @@ static void vfio_ap_mdev_reset_queue(struct vfio_ap_queue *q)
 		vfio_ap_free_aqic_resources(q);
 		break;
 	default:
+		/*
+		 * An invalid response code indicates a hardware or firmware bug.
+		 * Since we cannot determine whether the queue can still
+		 * DMA-write to the NIB, the AQIC resources are intentionally
+		 * leaked lest the NIB page is reallocated to a new owner. A
+		 * subsequent hardware wild DMA-write to that physical address
+		 * would corrupt the new owner's memory which could crash or
+		 * compromise the host kernel.
+		 */
 		WARN(true,
 		     "PQAP/ZAPQ for %02x.%04x failed with invalid rc=%u\n",
 		     AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

PATCH 3/20 s390/vfio-ap: fix leaks when PQAP(AQIC) enable is not accepted

In reply to a message not in the archive

vfio_ap_irq_enable() pins the guest's NIB page and registers the guest ISC before it executes PQAP(AQIC) to enable interrupts. If the instruction does not return AP_RESPONSE_NORMAL, the newly acquired resources must be released and the previously saved resources, which hardware is still using, must be left intact.

The AP_RESPONSE_OTHERWISE_CHANGED case does that. Any other response code, however, ended up in a default case that only logged a message and called vfio_ap_irq_disable(). That leaked the newly pinned NIB page and the newly registered ISC, which can cause memory exhaustion and depletion of KVM interrupt subclass registrations over time. It also disabled interrupts that were enabled by an earlier, successful PQAP(AQIC), and freed the resources hardware was still using for them.

Handle all response codes other than AP_RESPONSE_NORMAL the same
way: release the newly pinned page and the newly registered ISC and leave the saved resources intact.

AP_RESPONSE_OTHERWISE_CHANGED is not a failure of the instruction, so it is no longer reported by the "PQAP(AQIC) failed" debug feature message.

The kernel-doc and comments are updated to describe how the resources are managed.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c | 64 ++++++++++++++++++++++---------
 1 file changed, 45 insertions(+), 19 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +45 -19
index e6ffdd75af8a..b78c164215a4 100644
@@ -401,22 +401,29 @@ static int ensure_nib_shared(unsigned long addr)
 }
 
 /**
- * vfio_ap_irq_enable - Enable Interruption for a APQN
+ * vfio_ap_irq_enable - enable interrupts for an AP queue on behalf of a guest
  *
- * @q:	 the vfio_ap_queue holding AQIC parameters
+ * @q:	 the vfio_ap_queue for which interrupts are to be enabled
  * @isc: the guest ISC to register with the GIB interface
- * @vcpu: the vcpu object containing the registers specifying the parameters
- *	  passed to the PQAP(AQIC) instruction.
+ * @vcpu: the vcpu whose registers contain the PQAP(AQIC) parameters
  *
- * Pin the NIB saved in *q
- * Register the guest ISC to GIB interface and retrieve the
- * host ISC to issue the host side PQAP/AQIC
+ * Pins the guest NIB page, registers the guest ISC with the GIB to obtain a
+ * host ISC, and reissues PQAP(AQIC) with the translated host-absolute NIB
+ * address and host ISC on behalf of the guest.
  *
- * status.response_code may be set to AP_RESPONSE_INVALID_ADDRESS in case the
- * vfio_pin_pages or kvm_s390_gisc_register failed.
+ * The condition code and AP-queue status word returned by PQAP(AQIC) are
+ * reflected back to the guest as-is. IRQ state verification (polling until
+ * IR=1) is the responsibility of the guest AP bus, not the host.
  *
- * Otherwise return the ap_queue_status returned by the ap_aqic(),
- * all retry handling will be done by the guest.
+ * Resource management is based solely on whether hardware accepted the new NIB:
+ * - AP_RESPONSE_NORMAL (CC=0): hardware accepted the new NIB; the old pinned
+ *   NIB page and registered guest ISC are freed and the new ones saved.
+ * - All other responses: hardware did not accept the new NIB; the newly pinned
+ *   page and registered ISC are freed and the previously saved resources are
+ *   left intact.
+ *
+ * AP_RESPONSE_INVALID_ADDRESS is returned if vfio_pin_pages() or
+ * kvm_s390_gisc_register() fails before the AQIC instruction is issued.
  *
  * Return: &struct ap_queue_status
  */
@@ -489,27 +496,46 @@ static struct ap_queue_status vfio_ap_irq_enable(struct vfio_ap_queue *q,
 	status = ap_aqic(q->apqn, aqic_gisa, h_nib);
 	switch (status.response_code) {
 	case AP_RESPONSE_NORMAL:
-		/* See if we did clear older IRQ configuration */
+		/*
+		 * Hardware accepted the new NIB address (CC=0). The old NIB and
+		 * guest ISC are no longer used by hardware and can be freed.
+		 * The new resources are saved for tracking and future teardown.
+		 *
+		 * IRQ state verification (polling until IR=1) is the
+		 * responsibility of the guest AP bus, not the host. The
+		 * condition code and status word are reflected back to the
+		 * guest to respond to the PQAP-AQIC instruction.
+		 */
 		vfio_ap_free_aqic_resources(q);
 		q->saved_iova = nib;
 		q->saved_isc = isc;
 		break;
 	case AP_RESPONSE_OTHERWISE_CHANGED:
-		/* We could not modify IRQ settings: clear new configuration */
+		/*
+		 * Interrupts are already enabled or a prior async request is still
+		 * completing. Either way, the hardware's current NIB is the one
+		 * saved in q->saved_iova/saved_isc — not the newly prepared resources.
+		 * Release the newly pinned page and registered ISC;
+		 * leave them intact.
+		 */
+		fallthrough;
+	default:
+		/*
+		 * Hardware did not accept the new NIB (CC=3 or error). The
+		 * previously saved NIB and guest ISC remain active and must
+		 * not be freed. Release the newly pinned page and registered
+		 * ISC that were prepared for this (rejected) request.
+		 */
 		ret = kvm_s390_gisc_unregister(kvm, isc);
 		if (ret)
 			VFIO_AP_DBF_WARN("%s: kvm_s390_gisc_unregister: rc=%d isc=%d, apqn=%#04x\n",
 					 __func__, ret, isc, q->apqn);
 		vfio_unpin_pages(&q->matrix_mdev->vdev, nib, 1);
 		break;
-	default:
-		pr_warn("%s: apqn %04x: response: %02x\n", __func__, q->apqn,
-			status.response_code);
-		vfio_ap_irq_disable(q);
-		break;
 	}
 
-	if (status.response_code != AP_RESPONSE_NORMAL) {
+	if (status.response_code != AP_RESPONSE_NORMAL &&
+	    status.response_code != AP_RESPONSE_OTHERWISE_CHANGED) {
 		VFIO_AP_DBF_WARN("%s: PQAP(AQIC) failed with status=%#02x: "
 				 "zone=%#x, ir=%#x, gisc=%#x, f=%#x,"
 				 "gisa=%#x, isc=%#x, apqn=%#04x\n",
Signature · 1 line
2.53.0
author maintainer
#3 lore raw

PATCH 5/20 s390/vfio-ap: unpin the NIB page from the container that pinned it

In reply to a message not in the archive

vfio_ap_free_aqic_resources() unpins the NIB page through &q->matrix_mdev->vdev. This is correct on the normal teardown path, but becomes wrong when a queue reset fails and the AQIC resources are intentionally retained across a guest lifecycle. If the mdev is subsequently opened by a new guest (new IOMMU container), a later call to vfio_ap_free_aqic_resources() would call vfio_unpin_pages(new_vdev, old_iova), which unpins from the wrong IOMMU container:

* The iommufd backend hits WARN_ON(!access).

* The type1 backend may silently unpin the wrong page or warn.

* The original pin in the old container is never dropped, causing vfio to warn about a non-empty pfn_list at container teardown.

Record the vfio_device that pinned the page in the AQIC resources when interrupts are enabled, and have vfio_ap_free_aqic_resources() unpin against it. If no vfio_device was recorded, the page cannot be unpinned; log a ratelimited warning rather than dereferencing q->matrix_mdev, which may be NULL.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c     | 23 +++++++++++++++++++----
 drivers/s390/crypto/vfio_ap_private.h |  6 +++++-
 2 files changed, 24 insertions(+), 5 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +19 -4
index 35399c5a63c7..2e54766ff161 100644
@@ -266,25 +266,38 @@ static void vfio_ap_wait_for_irqclear(int apqn)
 }
 
 /**
- * vfio_ap_free_aqic_resources - free vfio_ap_queue resources
+ * vfio_ap_free_aqic_resources - free vfio_ap_queue AQIC resources
  * @q: The vfio_ap_queue
  *
  * Unregisters the ISC in the GIB when the saved ISC not invalid.
  * Unpins the guest's page holding the NIB when it exists.
  * Resets the aqic_resources iova and isc to invalid values.
+ *
+ * For the NIB: always use q->aqic_resources.vdev — the vfio_device that owns
+ * the IOMMU container in which the page was pinned — regardless of what
+ * q->matrix_mdev currently points to.
  */
 static void vfio_ap_free_aqic_resources(struct vfio_ap_queue *q)
 {
 	if (!q)
 		return;
+
 	if (q->aqic_resources.isc != VFIO_AP_ISC_INVALID) {
 		if (!WARN_ON(!q->matrix_mdev) && q->matrix_mdev->kvm)
 			kvm_s390_gisc_unregister(q->matrix_mdev->kvm, q->aqic_resources.isc);
 		q->aqic_resources.isc = VFIO_AP_ISC_INVALID;
 	}
-	if (q->aqic_resources.iova && !WARN_ON(!q->matrix_mdev)) {
-		vfio_unpin_pages(&q->matrix_mdev->vdev, q->aqic_resources.iova, 1);
+
+	if (q->aqic_resources.iova) {
+		if (q->aqic_resources.vdev)
+			vfio_unpin_pages(q->aqic_resources.vdev, q->aqic_resources.iova, 1);
+		else
+			pr_warn_ratelimited("APQN %02x.%04x: Failed to unpin NIB page at %pad\n",
+					    AP_QID_CARD(q->apqn),
+					    AP_QID_QUEUE(q->apqn),
+					    &q->aqic_resources.iova);
 		q->aqic_resources.iova = 0;
+		q->aqic_resources.vdev = NULL;
 	}
 }
 
@@ -508,7 +521,8 @@ static struct ap_queue_status vfio_ap_irq_enable(struct vfio_ap_queue *q,
 		 */
 		vfio_ap_free_aqic_resources(q);
 		q->aqic_resources.iova = nib;
-		q->aqic_resources.isc = isc;
+		q->aqic_resources.isc  = isc;
+		q->aqic_resources.vdev = &q->matrix_mdev->vdev;
 		break;
 	case AP_RESPONSE_OTHERWISE_CHANGED:
 		/*
@@ -2536,6 +2550,7 @@ int vfio_ap_mdev_probe_queue(struct ap_device *apdev)
 
 	q->apqn = apqn;
 	q->aqic_resources.isc = VFIO_AP_ISC_INVALID;
+	/* aqic_res.iova, .vdev, .kvm all zero-initialised by kzalloc_obj */
 	memset(&q->reset_status, 0, sizeof(q->reset_status));
 	INIT_WORK(&q->reset_work, apq_reset_check);
 
drivers/s390/crypto/vfio_ap_private.h +5 -1
index 2794954894bb..e0d620dbd62a 100644
@@ -132,14 +132,18 @@ struct ap_matrix_mdev {
  *				   interrupts for an AP queue.
  *
  * @iova: the guest DMA address of the notification indicator byte (NIB) page,
- *	  pinned at enable time.
+ *	  pinned via @vdev at enable time.
  * @isc:  the guest interruption sub-class registered with the GIB at enable
  *	  time.
+ * @vdev: the vfio_device whose IOMMU container owns the pin on @iova. Must be
+ *	  used for vfio_unpin_pages() to ensure the correct container is used,
+ *	  even if the queue is later re-assigned or the mdev is reopened.
  */
 struct vfio_ap_aqic_resources {
 	dma_addr_t			iova;
 #define VFIO_AP_ISC_INVALID	0xff
 	unsigned char			isc;
+	struct vfio_device		*vdev;
 };
 
 /**
Signature · 1 line
2.53.0
author maintainer
#4 lore raw

PATCH 6/20 s390/vfio-ap: unregister the ISC from the KVM it was registered on

In reply to a message not in the archive

vfio_ap_free_aqic_resources() unregisters the guest ISC using q->matrix_mdev->kvm. This is correct on the normal teardown path, but becomes wrong when a queue reset fails and the AQIC resources are intentionally retained across a guest lifecycle. If the mdev is subsequently opened by a new guest, a later call to vfio_ap_free_aqic_resources() would call kvm_s390_gisc_unregister() against the new guest's KVM. If the old struct kvm was freed and a new one allocated at the same address (struct kvm is kzalloc'd and the slab allocator can reuse addresses), this silently drops an ISC registration the new guest still needs.

Record the VM file of the KVM instance on which the ISC is registered in the AQIC resources when interrupts are enabled, taking a reference on the file with get_file() to guarantee that the struct kvm remains valid, and have vfio_ap_free_aqic_resources() unregister the ISC against it. The file reference is dropped with fput() after the ISC is unregistered. fput() defers the final release of the file, so it is safe to call with the matrix_dev locks held and from the reset worker.

The mechanism that keeps the KVM instance alive is confined to vfio_ap_aqic_get_kvm() and vfio_ap_aqic_put_kvm(). A kernel that predates the file-based reference counting of KVM by VFIO needs only the bodies of these two helpers (and the type of the kvm_file field) adapted when this fix is backported.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c     | 49 ++++++++++++++++++++++++---
 drivers/s390/crypto/vfio_ap_private.h | 10 ++++--
 2 files changed, 52 insertions(+), 7 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +44 -5
index 2e54766ff161..227f18ccc822 100644
@@ -265,13 +265,48 @@ static void vfio_ap_wait_for_irqclear(int apqn)
 		  __func__, status.response_code, apqn);
 }
 
+/**
+ * vfio_ap_aqic_get_kvm - hold the guest's KVM instance for the AQIC resources
+ * @q: the vfio_ap_queue
+ *
+ * Takes a reference on the VM file of the guest to which @q is currently
+ * assigned and saves it in q->aqic_resources.kvm_file. Holding the file keeps
+ * the struct kvm alive until the ISC registered on it has been unregistered.
+ *
+ * All use of the mechanism that keeps the KVM instance alive is confined to
+ * this function and vfio_ap_aqic_put_kvm().
+ */
+static void vfio_ap_aqic_get_kvm(struct vfio_ap_queue *q)
+{
+	q->aqic_resources.kvm_file = get_file(q->matrix_mdev->vdev.kvm);
+}
+
+/**
+ * vfio_ap_aqic_put_kvm - drop the reference taken by vfio_ap_aqic_get_kvm()
+ * @q: the vfio_ap_queue
+ *
+ * The final release of the VM file is deferred by fput(), so it is safe to
+ * call this function with the matrix_dev locks held and from a worker.
+ */
+static void vfio_ap_aqic_put_kvm(struct vfio_ap_queue *q)
+{
+	if (q->aqic_resources.kvm_file) {
+		fput(q->aqic_resources.kvm_file);
+		q->aqic_resources.kvm_file = NULL;
+	}
+}
+
 /**
  * vfio_ap_free_aqic_resources - free vfio_ap_queue AQIC resources
  * @q: The vfio_ap_queue
  *
- * Unregisters the ISC in the GIB when the saved ISC not invalid.
- * Unpins the guest's page holding the NIB when it exists.
- * Resets the aqic_resources iova and isc to invalid values.
+ * Unregisters the ISC from the GIB and unpins the NIB page, using the KVM
+ * instance and vfio_device snapshotted at enable time in q->aqic_resources.
+ *
+ * For the ISC: always call kvm_s390_gisc_unregister() on the KVM that was
+ * passed to kvm_s390_gisc_register() at enable time. A reference is held on
+ * that KVM's VM file (q->aqic_resources.kvm_file) so the KVM is always valid
+ * here. The reference is dropped after unregistering.
  *
  * For the NIB: always use q->aqic_resources.vdev — the vfio_device that owns
  * the IOMMU container in which the page was pinned — regardless of what
@@ -283,8 +318,11 @@ static void vfio_ap_free_aqic_resources(struct vfio_ap_queue *q)
 		return;
 
 	if (q->aqic_resources.isc != VFIO_AP_ISC_INVALID) {
-		if (!WARN_ON(!q->matrix_mdev) && q->matrix_mdev->kvm)
-			kvm_s390_gisc_unregister(q->matrix_mdev->kvm, q->aqic_resources.isc);
+		if (q->aqic_resources.kvm_file) {
+			kvm_s390_gisc_unregister(file_to_kvm_s390(q->aqic_resources.kvm_file),
+						 q->aqic_resources.isc);
+			vfio_ap_aqic_put_kvm(q);
+		}
 		q->aqic_resources.isc = VFIO_AP_ISC_INVALID;
 	}
 
@@ -523,6 +561,7 @@ static struct ap_queue_status vfio_ap_irq_enable(struct vfio_ap_queue *q,
 		q->aqic_resources.iova = nib;
 		q->aqic_resources.isc  = isc;
 		q->aqic_resources.vdev = &q->matrix_mdev->vdev;
+		vfio_ap_aqic_get_kvm(q);
 		break;
 	case AP_RESPONSE_OTHERWISE_CHANGED:
 		/*
drivers/s390/crypto/vfio_ap_private.h +8 -2
index e0d620dbd62a..59bc9f8901fe 100644
@@ -133,17 +133,23 @@ struct ap_matrix_mdev {
  *
  * @iova: the guest DMA address of the notification indicator byte (NIB) page,
  *	  pinned via @vdev at enable time.
- * @isc:  the guest interruption sub-class registered with the GIB at enable
- *	  time.
+ * @isc:  the guest interruption sub-class registered with the GIB on the KVM of
+ *	  @kvm_file at enable time.
  * @vdev: the vfio_device whose IOMMU container owns the pin on @iova. Must be
  *	  used for vfio_unpin_pages() to ensure the correct container is used,
  *	  even if the queue is later re-assigned or the mdev is reopened.
+ * @kvm_file: the VM file of the KVM instance that owns the GISC registration
+ *	  for @isc, on which a reference is held. Its struct kvm must be used
+ *	  for kvm_s390_gisc_unregister() to ensure the correct guest's alert
+ *	  mask is updated, even if the queue is later re-assigned or the mdev
+ *	  is reopened with a different guest.
  */
 struct vfio_ap_aqic_resources {
 	dma_addr_t			iova;
 #define VFIO_AP_ISC_INVALID	0xff
 	unsigned char			isc;
 	struct vfio_device		*vdev;
+	struct file			*kvm_file;
 };
 
 /**
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

PATCH 7/20 s390/vfio-ap: force-unpin surviving NIB pages when KVM is unset

In reply to a message not in the archive

vfio_ap_mdev_unset_kvm() resets the mdev's queues, but the reset may not be able to confirm that all queues were zeroized (for example, the worker gets -EIO or an unexpected response code from ZAPQ). The AQIC resources of such a queue, including the pinned NIB page, are then retained.

The vfio contract requires every pinned page to be released before close_device() returns. After close_device() returns, vfio core removes the device from iommu->device_list. A subsequent VFIO_IOMMU_UNMAP_DMA will find the pin in dma->pfn_list, receive no response from the empty device list, retry 10 times, and hit BUG_ON(++retries > 10) in the type1 backend.

The same applies if userspace closes the container fd without calling VFIO_IOMMU_UNMAP_DMA first: vfio_remove_dma() hits WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list)) for any pin that was not released.

To prevent this, force-unpin any NIB pages that survive the reset, logging a pr_crit message, and drop the VM file reference and clear the ISC held in the AQIC resources, since the KVM of the closing session is no longer a valid target for releasing them. A guaranteed host panic is worse than the theoretical risk of a wild DMA write from hardware whose reset already failed. The loop runs after flush_work() has drained all reset workers.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c | 43 +++++++++++++++++++++++++++++++
 1 file changed, 43 insertions(+)
drivers/s390/crypto/vfio_ap_ops.c +43 -0
index 227f18ccc822..2d27c56a376e 100644
@@ -1972,6 +1972,8 @@ static void vfio_ap_mdev_dma_unmap(struct vfio_device *vdev, u64 iova,
 static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
 {
 	struct kvm *kvm = matrix_mdev->kvm;
+	unsigned long apid, apqi;
+	struct vfio_ap_queue *q;
 
 	if (kvm && kvm->arch.crypto.crycbd) {
 		get_update_locks_for_kvm(kvm);
@@ -1983,6 +1985,47 @@ static void vfio_ap_mdev_unset_kvm(struct ap_matrix_mdev *matrix_mdev)
 
 		release_update_locks_for_kvm(kvm);
 	}
+
+	/*
+	 * The reset above may not have been able to confirm that all queues
+	 * were zeroized (e.g. worker -EIO, unexpected ZAPQ rc). Any queue
+	 * that still has iova set holds a pin in the IOMMU container that is
+	 * about to go away. The vfio contract requires every pinned page to
+	 * be released before close_device() returns: vfio core removes the
+	 * device from iommu->device_list after close_device() returns, after
+	 * which vfio_notify_dma_unmap() becomes a no-op and a later
+	 * VFIO_IOMMU_UNMAP_DMA will hit BUG_ON(++retries > 10) in type1.
+	 *
+	 * Force-unpin any surviving NIB pages now, while vdev is still valid.
+	 * This carries the same theoretical wild-DMA risk as the force-unpin
+	 * in unmap_iova(), and is chosen for the same reason: a guaranteed
+	 * host panic is worse than a theoretical risk on already-misbehaving
+	 * hardware.
+	 */
+	for_each_set_bit_inv(apid, matrix_mdev->matrix.apm, AP_DEVICES) {
+		for_each_set_bit_inv(apqi, matrix_mdev->matrix.aqm, AP_DOMAINS) {
+			q = vfio_ap_mdev_get_queue(matrix_mdev,
+						   AP_MKQID(apid, apqi));
+			if (!q)
+				continue;
+
+			if (q->aqic_resources.iova) {
+				pr_crit("APQN %02x.%04x: NIB page at %pad could not be safely unpinned after queue reset failure; force-unpinning to prevent kernel panic\n",
+					AP_QID_CARD(q->apqn),
+					AP_QID_QUEUE(q->apqn),
+					&q->aqic_resources.iova);
+				if (q->aqic_resources.vdev)
+					vfio_unpin_pages(q->aqic_resources.vdev,
+							 q->aqic_resources.iova,
+							 1);
+				q->aqic_resources.iova = 0;
+				q->aqic_resources.vdev = NULL;
+			}
+
+			vfio_ap_aqic_put_kvm(q);
+			q->aqic_resources.isc = VFIO_AP_ISC_INVALID;
+		}
+	}
 }
 
 static struct vfio_ap_queue *vfio_ap_find_queue(int apqn)
Signature · 1 line
2.53.0
author maintainer
#6 lore raw

PATCH 8/20 s390/vfio-ap: reset queue if NIB cannot be unpinned on DMA unmap

In reply to a message not in the archive

unmap_iova() calls vfio_ap_irq_disable() for a queue whose NIB lies in the range being unmapped, but does not check whether the NIB was released. If the interrupt disable failed or could not be confirmed, the NIB remains pinned. The vfio core requires that the page be unpinned before the unmap notification returns, or it will hit BUG_ON(++retries > 10) in the type1 backend after 10 re-notification rounds.

Fall back to a queue reset via ZAPQ, which clears the hardware's internal NIB address and so eliminates the DMA risk, and wait for the reset worker to finish. If the reset completes, the worker frees the AQIC resources. If it fails or times out, force-unpin the NIB and log a pr_crit message: a host panic is worse than the theoretical risk of a wild DMA write from hardware whose reset already failed.

Fixes 2a54e347d990 ("vfio/ap: Validate iova during dma_unmap and trigger irq disable")
---
 drivers/s390/crypto/vfio_ap_ops.c | 40 ++++++++++++++++++++++++++++++-
 1 file changed, 39 insertions(+), 1 deletion(-)
drivers/s390/crypto/vfio_ap_ops.c +39 -1
index 2d27c56a376e..2695ae08a9b5 100644
@@ -1945,8 +1945,46 @@ static void unmap_iova(struct ap_matrix_mdev *matrix_mdev, u64 iova, u64 length)
 	int loop_cursor;
 
 	hash_for_each(qtable->queues, loop_cursor, q, mdev_qnode) {
-		if (q->aqic_resources.iova >= iova && q->aqic_resources.iova < iova + length)
+		if (q->aqic_resources.iova >= iova && q->aqic_resources.iova < iova + length) {
 			vfio_ap_irq_disable(q);
+			/*
+			 * If AQIC disable was unable to confirm that interrupts were
+			 * disabled (IR=0), q->aqic_resources.iova remains non-zero.
+			 * VFIO core requires the mapped pages to be unpinned during
+			 * DMA unmap notifications (the type1 IOMMU backend will
+			 * BUG_ON after 10 re-notification retries if the pin is not
+			 * released).
+			 *
+			 * To satisfy VFIO core safely, fall back to a queue reset
+			 * via ZAPQ. ZAPQ wipes the queue state and clears the
+			 * hardware's internal NIB address register, neutralizing
+			 * pending DMA. Flush the reset worker so that we know
+			 * whether the NIB was released before returning.
+			 */
+			if (q->aqic_resources.iova) {
+				vfio_ap_mdev_reset_queue(q);
+				flush_work(&q->reset_work);
+			}
+
+			/*
+			 * If the NIB is still pinned after the reset (reset failed
+			 * or timed out), force-unpin it anyway. A host kernel panic
+			 * from the VFIO BUG_ON is worse than the theoretical risk of
+			 * a wild DMA write from already-misbehaving hardware, and a
+			 * pr_crit message records that the forced unpin occurred.
+			 */
+			if (q->aqic_resources.iova) {
+				pr_crit("APQN %02x.%04x: NIB page at %pad could not be safely unpinned after queue reset failure; force-unpinning to prevent kernel panic\n",
+					AP_QID_CARD(q->apqn),
+					AP_QID_QUEUE(q->apqn),
+					&q->aqic_resources.iova);
+				if (q->aqic_resources.vdev)
+					vfio_unpin_pages(q->aqic_resources.vdev,
+							 q->aqic_resources.iova, 1);
+				q->aqic_resources.iova = 0;
+				q->aqic_resources.vdev = NULL;
+			}
+		}
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#7 lore raw

PATCH 9/20 s390/vfio-ap: free AQIC resources when unlinking a queue from its mdev

In reply to a message not in the archive

A queue that is unassigned from a running guest (hot unplug of an adapter or domain) is removed from the mdev's queue table and is no longer visited by unmap_iova() or by the loop in vfio_ap_mdev_unset_kvm(). If its reset does not complete, its NIB remains pinned with nothing able to find it, and the next VFIO_IOMMU_UNMAP_DMA of that page hits BUG_ON(++retries > 10) in the type1 backend.

Free the AQIC resources in vfio_ap_unlink_mdev_fr_queue() before the queue is dissociated from its mdev, logging a pr_crit message if a pinned NIB must be force-unpinned. It is the same trade-off as in unmap_iova() and vfio_ap_mdev_unset_kvm(): a host panic is worse than the theoretical risk of a wild DMA write from hardware whose reset already failed.

Use vfio_ap_unlink_mdev_fr_queue() in vfio_ap_mdev_unlink_fr_queues() so that every queue is handled the same way, and document the function.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c | 25 ++++++++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)
drivers/s390/crypto/vfio_ap_ops.c +24 -1
index 2695ae08a9b5..a618dceb31c8 100644
@@ -927,8 +927,31 @@ static void vfio_ap_unlink_queue_fr_mdev(struct vfio_ap_queue *q)
 	hash_del(&q->mdev_qnode);
 }
 
+/**
+ * vfio_ap_unlink_mdev_fr_queue - dissociate a queue from its matrix_mdev
+ * @q: the vfio_ap_queue
+ *
+ * Frees the queue's AQIC resources and dissociates @q from its matrix_mdev.
+ * This prevents a use-after-free if a reset did not complete (which retains
+ * the AQIC resources) and the mdev is subsequently freed before the queue is
+ * destroyed.
+ *
+ * If the reset did not complete (timeout, worker -EIO, unexpected ZAPQ rc),
+ * the NIB is still pinned. Once the queue is unlinked from its mdev, neither
+ * unmap_iova() nor vfio_ap_mdev_unset_kvm() can find it, and a later
+ * VFIO_IOMMU_UNMAP_DMA of that page would hit BUG_ON(++retries > 10) in
+ * type1. The NIB is therefore force-unpinned here, while the vdev
+ * snapshotted at enable time is still valid, for the same reason as in
+ * unmap_iova() and vfio_ap_mdev_unset_kvm().
+ */
 static void vfio_ap_unlink_mdev_fr_queue(struct vfio_ap_queue *q)
 {
+	if (q->aqic_resources.iova)
+		pr_crit("APQN %02x.%04x: NIB page at %pad could not be safely unpinned after queue reset failure; force-unpinning to prevent kernel panic\n",
+			AP_QID_CARD(q->apqn), AP_QID_QUEUE(q->apqn),
+			&q->aqic_resources.iova);
+
+	vfio_ap_free_aqic_resources(q);
 	q->matrix_mdev = NULL;
 }
 
@@ -943,7 +966,7 @@ static void vfio_ap_mdev_unlink_fr_queues(struct ap_matrix_mdev *matrix_mdev)
 			q = vfio_ap_mdev_get_queue(matrix_mdev,
 						   AP_MKQID(apid, apqi));
 			if (q)
-				q->matrix_mdev = NULL;
+				vfio_ap_unlink_mdev_fr_queue(q);
 		}
 	}
 }
Signature · 1 line
2.53.0
author maintainer
#8 lore raw

PATCH 10/20 s390/vfio-ap: free AQIC resources only if interrupts are confirmed disabled

In reply to a message not in the archive

vfio_ap_irq_disable() issues PQAP(AQIC) to disable interrupts, polls PQAP(TAPQ) until the IR bit is clear, and then frees the AQIC resources. The polling helper, vfio_ap_wait_for_irqclear(), returns nothing, so a failure to confirm IR=0 was ignored and the pinned NIB page and the registered guest ISC were freed anyway. If interrupts are not actually disabled, hardware can still write to the NIB. If the page were unpinned and returned to the allocator, a subsequent wild DMA write to that physical address would corrupt memory belonging to the new owner and could crash or compromise the host kernel.

PQAP(AQIC) disable initiates an asynchronous process, so a condition code 0 completion does not guarantee that the IR bit has been cleared. Change vfio_ap_wait_for_irqclear() to return:
* 0: IR=0 confirmed; safe to free the AQIC resources
* -ENODEV: the queue is non-operational; safe to free
* -ETIMEDOUT: IR=0 could not be confirmed within the polling window, or TAPQ returned the asynchronous association response code 0x35 or 0x36
* -EIO: TAPQ returned an unexpected response code

Free the AQIC resources in vfio_ap_irq_disable() only for the first two. In the others they are intentionally retained, and if the TAPQ status was NORMAL or BUSY, AP_RESPONSE_OTHERWISE_CHANGED is returned to the guest so that it does not conclude that the disable succeeded and reuse the NIB.

Also document in vfio_ap_mdev_remove_queue() why freeing the AQIC resources without a ZAPQ is safe when the queue is no longer in the host's AP configuration.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c | 172 +++++++++++++++++++++++++-----
 1 file changed, 144 insertions(+), 28 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +144 -28
index a618dceb31c8..97048d9fa2b0 100644
@@ -226,27 +226,48 @@ static struct vfio_ap_queue *vfio_ap_mdev_get_queue(
 }
 
 /**
- * vfio_ap_wait_for_irqclear - clears the IR bit or gives up after 5 tries
- * @apqn: The AP Queue number
- *
- * Checks the IRQ bit for the status of this APQN using ap_tapq.
- * Returns if the ap_tapq function succeeded and the bit is clear.
- * Returns if ap_tapq function failed with invalid, deconfigured or
- * checkstopped AP.
- * Otherwise retries up to 5 times after waiting 20ms.
+ * vfio_ap_wait_for_irqclear - wait for the IR bit to clear after a disable
+ *
+ * @apqn:		the APQN of the AP queue
+ * @tapq_status:	used to return the TAPQ status to the caller
+ *
+ * Repeatedly polls the AP queue status via PQAP(TAPQ) every 20ms until the IR
+ * bit is clear, the queue becomes non-operational, or 6 retries are exhausted.
+ *
+ * Because PQAP(AQIC) disable initiates an asynchronous process, a
+ * condition-code 0 completion does not guarantee the IR bit has been cleared.
+ * The host must confirm IR=0 before unpinning the NIB page to avoid a wild
+ * DMA write to a freed page.
+ *
+ * Return:
+ * 0		if the IR bit is clear (i.e., interrupts are disabled).
+ *
+ * -ENODEV	if the PQAP-TAPQ response code indicates the queue is not available,
+ *		is deconfigured, or is checkstopped (i.e., not operational).
+ *
+ * -ETIMEDOUT	the function timed out before the IR bit was cleared, or TAPQ
+ *		returned AP_RESPONSE_ASSOC_SECRET_NOT_UNIQUE or
+ *		AP_RESPONSE_ASSOC_FAILED, which mean the instruction was not
+ *		executed and will continue to be returned for all subsequent
+ *		instructions except ZAPQ until the queue is reset. Since IR=0
+ *		cannot be confirmed, the NIB must be treated as a potential DMA
+ *		target and leaked rather than freed.
+ *
+ * -EIO		PQAP-TAPQ returned an invalid response code
  */
-static void vfio_ap_wait_for_irqclear(int apqn)
+static int vfio_ap_wait_for_irqclear(int apqn, struct ap_queue_status *tapq_status)
 {
 	struct ap_queue_status status;
 	int retry = 5;
 
 	do {
 		status = ap_tapq(apqn, NULL);
+		memcpy(tapq_status, &status, sizeof(status));
 		switch (status.response_code) {
 		case AP_RESPONSE_NORMAL:
 		case AP_RESPONSE_RESET_IN_PROGRESS:
 			if (!status.irq_enabled)
-				return;
+				return 0;
 			fallthrough;
 		case AP_RESPONSE_BUSY:
 			msleep(20);
@@ -254,15 +275,34 @@ static void vfio_ap_wait_for_irqclear(int apqn)
 		case AP_RESPONSE_Q_NOT_AVAIL:
 		case AP_RESPONSE_DECONFIGURED:
 		case AP_RESPONSE_CHECKSTOPPED:
+			WARN_ONCE(1, "%s: tapq rc %02x: %04x\n", __func__,
+				  status.response_code, apqn);
+			return -ENODEV;
+		case AP_RESPONSE_ASSOC_SECRET_NOT_UNIQUE:
+		case AP_RESPONSE_ASSOC_FAILED:
+			/*
+			 * The TAPQ instruction was not executed. Executing TAPQ
+			 * again will result in the same error until the queue
+			 * is reset. We shouldn't, however, reset the queue in
+			 * this context, so log a warning and return -ETIMEDOUT
+			 * since that would happen anyway if we continued to
+			 * execute the TAPQ.
+			 */
+			WARN_ONCE(1, "%s: tapq rc %02x: %04x\n", __func__,
+				  status.response_code, apqn);
+			return -ETIMEDOUT;
 		default:
 			WARN_ONCE(1, "%s: tapq rc %02x: %04x\n", __func__,
 				  status.response_code, apqn);
-			return;
+			return -EIO;
 		}
 	} while (--retry);
 
-	WARN_ONCE(1, "%s: tapq rc %02x: %04x could not clear IR bit\n",
-		  __func__, status.response_code, apqn);
+	WARN_ONCE(1, "%s: tapq rc %02x: timed out waiting for interrupts disabled for %02x.%04x\n",
+		  __func__, status.response_code,
+		  AP_QID_CARD(apqn), AP_QID_QUEUE(apqn));
+
+	return -ETIMEDOUT;
 }
 
 /**
@@ -340,36 +380,87 @@ static void vfio_ap_free_aqic_resources(struct vfio_ap_queue *q)
 }
 
 /**
- * vfio_ap_irq_disable - disables and clears an ap_queue interrupt
- * @q: The vfio_ap_queue
+ * vfio_ap_irq_disable - disable interrupts for an AP queue
+ * @q: the vfio_ap_queue
+ *
+ * Issues PQAP(AQIC) to disable interrupts for the AP queue. On success
+ * (AP_RESPONSE_NORMAL or AP_RESPONSE_OTHERWISE_CHANGED), polls via
+ * vfio_ap_wait_for_irqclear() until the IR bit is confirmed clear before
+ * freeing the pinned NIB page and unregistering the guest ISC. This wait is
+ * necessary because AQIC disable is asynchronous: freeing the NIB before IR=0
+ * is confirmed risks a wild DMA write to a freed host page.
  *
- * Uses ap_aqic to disable the interruption and in case of success, reset
- * in progress or IRQ disable command already proceeded: calls
- * vfio_ap_wait_for_irqclear() to check for the IRQ bit to be clear
- * and calls vfio_ap_free_aqic_resources() to free the resources associated
- * with the AP interrupt handling.
+ * Retries up to 5 times (with 20ms sleep) if the queue is busy or a reset is
+ * in progress.
  *
- * In the case the AP is busy, or a reset is in progress,
- * retries after 20ms, up to 5 times.
+ * If the IR bit cannot be confirmed clear (timeout), the NIB page and guest
+ * ISC are intentionally leaked. If the page were unpinned and returned to the
+ * allocator, a subsequent hardware DMA write to that physical address would
+ * corrupt memory belonging to a new owner — a wild DMA write that could crash
+ * or compromise the host kernel.
  *
- * Returns if ap_aqic function failed with invalid, deconfigured or
- * checkstopped AP.
+ * If the queue is non-operational (deconfigured, checkstopped, not available),
+ * resources are freed immediately since the hardware can no longer write to
+ * the NIB.
  *
  * Return: &struct ap_queue_status
  */
 static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
 {
 	union ap_qirq_ctrl aqic_gisa = { .value = 0 };
-	struct ap_queue_status status;
-	int retries = 5;
+	struct ap_queue_status status, tapq_status;
+	int retries = 5, ret;
 
 	do {
 		status = ap_aqic(q->apqn, aqic_gisa, 0);
 		switch (status.response_code) {
 		case AP_RESPONSE_OTHERWISE_CHANGED:
 		case AP_RESPONSE_NORMAL:
-			vfio_ap_wait_for_irqclear(q->apqn);
-			goto end_free;
+			/*
+			 * AQIC disable was accepted (NORMAL), or the queue was
+			 * already disabled or a prior async request is still
+			 * completing (OTHERWISE_CHANGED).  In both cases, we must
+			 * wait until interrupt processing has been disabled
+			 * before proceeding.
+			 */
+			ret = vfio_ap_wait_for_irqclear(q->apqn, &tapq_status);
+			if (ret == 0 || ret == -ENODEV)
+				goto end_free;
+
+			if (ret == -EIO) {
+				/*
+				 * An unknown TAPQ response code was returned which
+				 * indicates a bug or some type of hardware I/O issue.
+				 * Since we don't know whether queue interrupts were
+				 * disabled or not, the AQIC resources must be leaked.
+				 */
+				memcpy(&status, &tapq_status, sizeof(status));
+				goto end_fail;
+			}
+
+			/* Timed out waiting to confirm interrupts are disabled */
+			if (tapq_status.response_code == AP_RESPONSE_NORMAL ||
+			    tapq_status.response_code == AP_RESPONSE_BUSY) {
+				/*
+				 * If AQIC returned NORMAL, the guest would incorrectly
+				 * interpret that as a successful disable and may free or
+				 * reuse the NIB while hardware can still write to it.
+				 * AP_RESPONSE_BUSY is not valid for PQAP-AQIC.
+				 *
+				 * Return OTHERWISE_CHANGED to signal to the guest that
+				 * the disable interrupts operation did not complete.
+				 */
+				memset(&status, 0, sizeof(status));
+				status.response_code = AP_RESPONSE_OTHERWISE_CHANGED;
+			} else {
+				/*
+				 * For all other TAPQ response codes,
+				 * return the TAPQ status directly since those
+				 * codes are also valid for AQIC.
+				 */
+				memcpy(&status, &tapq_status, sizeof(status));
+			}
+			goto end_fail;
 		case AP_RESPONSE_RESET_IN_PROGRESS:
 		case AP_RESPONSE_BUSY:
 			msleep(20);
@@ -388,7 +479,25 @@ static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
 
 	WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
 		  status.response_code);
+
+end_fail:
+	/*
+	 * IR=0 could not be confirmed. The NIB page and guest ISC cannot be
+	 * freed: hardware may still write to the NIB, and unpinning the page
+	 * would allow it to be reallocated to a new owner. A subsequent
+	 * hardware DMA write to that physical address would corrupt the new
+	 * owner's memory - a wild DMA write that could crash or compromise
+	 * the host kernel. The resources are therefore intentionally leaked.
+	 */
+	return status;
 end_free:
+	/*
+	 * This label is reached because the queue was successfully disabled,
+	 * or because the queue is not operational or not available, in which case
+	 * interrupts can not be processed, so free the AQIC resources - the pinned NIB
+	 * page and the registered guest ISC - used to enable interrupts so they will
+	 * not be leaked.
+	 */
 	vfio_ap_free_aqic_resources(q);
 	return status;
 }
@@ -2773,6 +2882,13 @@ void vfio_ap_mdev_remove_queue(struct ap_device *apdev)
 		vfio_ap_mdev_reset_queue(q);
 		flush_work(&q->reset_work);
 	} else {
+		/*
+		 * The queue is no longer in the host's AP configuration.
+		 * The hardware cannot DMA-write to the NIB, so it is safe
+		 * to free the AQIC resources directly without issuing a
+		 * ZAPQ. If the queue is not assigned to an mdev,
+		 * vfio_ap_free_aqic_resources() is a no-op.
+		 */
 		vfio_ap_free_aqic_resources(q);
 	}
 
Signature · 1 line
2.53.0
author maintainer
#9 lore raw

PATCH 11/20 s390/vfio-ap: retry PQAP(AQIC) disable while a state change is in progress

In reply to a message not in the archive

vfio_ap_irq_disable() retries PQAP(AQIC) after sleeping 20ms if the instruction returns AP_RESPONSE_RESET_IN_PROGRESS or AP_RESPONSE_BUSY. AP_RESPONSE_STATE_CHANGE_IN_PROGRESS (0A) is a valid response code for PQAP(AQIC) which is just as transient, but it was not handled explicitly and fell into the default case, which treated it as a non-operational queue and freed the AQIC resources without interrupts having been disabled.

Treat STATE_CHANGE_IN_PROGRESS like RESET_IN_PROGRESS and BUSY:
sleep for 20ms and execute the AQIC again.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c | 1 +
 1 file changed, 1 insertion(+)
drivers/s390/crypto/vfio_ap_ops.c +1 -0
index 97048d9fa2b0..dec69f3ffb8b 100644
@@ -463,6 +463,7 @@ static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
 			goto end_fail;
 		case AP_RESPONSE_RESET_IN_PROGRESS:
 		case AP_RESPONSE_BUSY:
+		case AP_RESPONSE_STATE_CHANGE_IN_PROGRESS:
 			msleep(20);
 			break;
 		case AP_RESPONSE_Q_NOT_AVAIL:
Signature · 1 line
2.53.0
author maintainer
#10 lore raw

PATCH 12/20 s390/vfio-ap: retain AQIC resources if PQAP(AQIC) disable is rejected

In reply to a message not in the archive

vfio_ap_irq_disable() treated every response code from PQAP(AQIC) that it did not handle explicitly as an indication that the queue is not operational, and freed the AQIC resources. The valid response codes for PQAP(AQIC) include AP_RESPONSE_INVALID_GISA (08), AP_RESPONSE_ASSOC_SECRET_NOT_UNIQUE (35) and AP_RESPONSE_ASSOC_FAILED (36). They mean the disable was not executed and the hardware still holds the NIB address, so freeing the pinned NIB page may allow hardware to write to memory that has been returned to the allocator.

Retain the AQIC resources for those response codes, for AP_RESPONSE_INVALID_ADDRESS and for any unrecognized response code. Responses that mean the queue is not operational (not available, deconfigured, checkstopped) still free the resources, since the hardware can no longer write to the NIB.

Fixes ec89b55e3bce ("s390: ap: implement PAPQ AQIC interception in kernel")
---
 drivers/s390/crypto/vfio_ap_ops.c | 30 ++++++++++++++++++++++--------
 1 file changed, 22 insertions(+), 8 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +22 -8
index dec69f3ffb8b..892ea938d14b 100644
@@ -469,12 +469,23 @@ static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
 		case AP_RESPONSE_Q_NOT_AVAIL:
 		case AP_RESPONSE_DECONFIGURED:
 		case AP_RESPONSE_CHECKSTOPPED:
+			/* AP not operational; no further interrupts possible */
+			WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
+				  status.response_code);
+			goto end_free;
 		case AP_RESPONSE_INVALID_ADDRESS:
+		case AP_RESPONSE_INVALID_GISA:
+		case AP_RESPONSE_ASSOC_SECRET_NOT_UNIQUE:
+		case AP_RESPONSE_ASSOC_FAILED:
 		default:
-			/* All cases in default means AP not operational */
+			/*
+			 * The AQIC disable was rejected; IRQ is still enabled
+			 * and the hardware still holds the NIB address. Do not
+			 * free resources.
+			 */
 			WARN_ONCE(1, "%s: ap_aqic status %d\n", __func__,
 				  status.response_code);
-			goto end_free;
+			goto end_fail;
 		}
 	} while (retries--);
 
@@ -483,14 +494,17 @@ static struct ap_queue_status vfio_ap_irq_disable(struct vfio_ap_queue *q)
 
 end_fail:
 	/*
-	 * IR=0 could not be confirmed. The NIB page and guest ISC cannot be
-	 * freed: hardware may still write to the NIB, and unpinning the page
-	 * would allow it to be reallocated to a new owner. A subsequent
-	 * hardware DMA write to that physical address would corrupt the new
-	 * owner's memory - a wild DMA write that could crash or compromise
-	 * the host kernel. The resources are therefore intentionally leaked.
+	 * We are here either because the AQIC instruction failed to disable
+	 * interrupts, or because IR=0 could not be confirmed. In either case
+	 * the NIB page and guest ISC cannot be freed: hardware may still write
+	 * to the NIB, and unpinning the page would allow it to be reallocated
+	 * to a new owner. A subsequent hardware DMA write to that physical
+	 * address would corrupt the new owner's memory — a wild DMA write that
+	 * could crash or compromise the host kernel. The resources are
+	 * therefore intentionally leaked.
 	 */
 	return status;
+
 end_free:
 	/*
 	 * This label is reached because the queue was successfully disabled,
Signature · 1 line
2.53.0
author maintainer
#11 lore raw

PATCH 13/20 s390/vfio-ap: Fix failure to release IRQ notification eventfd contexts

In reply to a message not in the archive

When userspace registers IRQ notification eventfds via the VFIO_DEVICE_SET_IRQS ioctl, vfio_ap_set_request_irq() and vfio_ap_set_cfg_change_irq() each call eventfd_ctx_fdget(), which takes a reference on the eventfd_ctx and stores it in matrix_mdev->req_trigger and matrix_mdev->cfg_chg_trigger respectively.

These references are dropped only when userspace explicitly replaces or clears them via a subsequent SET_IRQS call. If the device is closed without that explicit teardown - because the guest exits, the VM process crashes, or the device file is simply closed - neither vfio_ap_mdev_close_device() nor the remove path releases these references. The eventfd_ctx backing objects and their associated file references therefore leak for the lifetime of the kernel.

Fix this by introducing vfio_ap_mdev_release_eventfds() and calling it from vfio_ap_mdev_close_device() after vfio_ap_mdev_unset_kvm(). The VFIO core guarantees that close_device is called before vfio_unregister_group_dev() returns in the remove path, so fixing close_device is sufficient to cover both teardown paths.

Note:
~~~~
The matrix_dev->mdevs lock must be held during the call to vfio_ap_mdev_release_eventfds(). There is a small window between the calls to vfio_ap_mdev_unset_kvm() which gets and releases the update locks and the acquisition of the matrix_dev->mdevs_lock mutex during which it is possible - although highly unlikely during normal operation - whereby a concurrent SET_IRQS call can get in.

Taking matrix_dev->mdevs_lock around vfio_ap_mdev_release_eventfds() is sufficient to make this race-free. The SET_IRQS ioctl path writes req_trigger and cfg_chg_trigger only from vfio_ap_mdev_ioctl(), which holds mdevs_lock for its entire duration and always calls eventfd_ctx_put() on the previous value before storing the new one.

Any number of concurrent SET_IRQS calls during the window between vfio_ap_mdev_unset_kvm() and the acquisition of mdevs_lock are therefore safe: each ioctl invocation puts the reference it found and installs a new one, leaving exactly one live reference in the field when it releases the lock. When release_eventfds subsequently acquires mdevs_lock it finds that single surviving reference and puts it. Conversely, a SET_IRQS call that loses the race and blocks on mdevs_lock will find the field NULL after release_eventfds finishes, take ownership of the reference it just created, and install it into a field that will never be read again - a transient leak. To close that final case, callers must ensure no new SET_IRQS ioctls can be issued after close_device() is called, which the VFIO core guarantees by releasing the device file before invoking close_device().

Fixes bf48961f6f48 ("s390/vfio-ap: realize the VFIO_DEVICE_SET_IRQS ioctl")
Fixes 07d89045bffe ("s390/vfio-ap: Signal eventfd when guest AP configuration is changed")
---
 drivers/s390/crypto/vfio_ap_ops.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
drivers/s390/crypto/vfio_ap_ops.c +16 -0
index 892ea938d14b..729af61d8ad3 100644
@@ -2421,12 +2421,28 @@ static int vfio_ap_mdev_open_device(struct vfio_device *vdev)
 	return vfio_ap_mdev_set_kvm(matrix_mdev, vdev->kvm);
 }
 
+static void vfio_ap_mdev_release_eventfds(struct ap_matrix_mdev *matrix_mdev)
+{
+	if (matrix_mdev->req_trigger) {
+		eventfd_ctx_put(matrix_mdev->req_trigger);
+		matrix_mdev->req_trigger = NULL;
+	}
+	if (matrix_mdev->cfg_chg_trigger) {
+		eventfd_ctx_put(matrix_mdev->cfg_chg_trigger);
+		matrix_mdev->cfg_chg_trigger = NULL;
+	}
+}
+
 static void vfio_ap_mdev_close_device(struct vfio_device *vdev)
 {
 	struct ap_matrix_mdev *matrix_mdev =
 		container_of(vdev, struct ap_matrix_mdev, vdev);
 
 	vfio_ap_mdev_unset_kvm(matrix_mdev);
+
+	mutex_lock(&matrix_dev->mdevs_lock);
+	vfio_ap_mdev_release_eventfds(matrix_mdev);
+	mutex_unlock(&matrix_dev->mdevs_lock);
 }
 
 static void vfio_ap_mdev_request(struct vfio_device *vdev, unsigned int count)
Signature · 1 line
2.53.0
author maintainer
#12 lore raw

PATCH 14/20 s390/vfio-ap: bound the wait for a queue reset to complete

In reply to a message not in the archive

The apq_reset_check() worker polls ap_tapq() in a while(true) loop waiting for a queue reset to complete. When ap_tapq() returns AP_RESPONSE_BUSY or AP_RESPONSE_RESET_IN_PROGRESS, apq_status_check() returns -EBUSY and the loop continues after sleeping AP_RESET_INTERVAL (20ms). There is no upper bound on how many times the loop iterates, so if the hardware continuously returns a busy response the worker runs indefinitely.

This is particularly harmful because several callers of vfio_ap_mdev_reset_queue() - such as vfio_ap_mdev_reset_queues(), vfio_ap_mdev_reset_qlist() and vfio_ap_mdev_remove_queue() - call flush_work() on the queue's reset_work while holding one or more of the global matrix_dev locks (guests_lock, mdevs_lock) or the KVM lock. An indefinitely spinning worker permanently blocks access to all ap_matrix_mdev objects, which could hang other guests that are using them.

Fix this by introducing AP_RESET_MAX_WAIT (2000ms) and giving up when the elapsed time reaches that threshold. The check is made on every iteration that has not completed the reset, including those in which the ZAPQ was re-issued, so the loop is restructured to fall through to it instead of using continue and break.

If apq_reset_check() times out before verifying completion of the reset, the NIB page cannot be freed. The NIB is the active DMA target for AP interrupt delivery until the reset completes; freeing the pinned page would allow it to be reallocated to a new owner. A subsequent hardware wild DMA-write to that physical address would corrupt the new owner's memory and could crash or compromise the host kernel.

The ISC registration is not a DMA target and can be freed immediately at timeout. report_apq_reset_check_timeout() unregisters the ISC on the KVM that was used at enable time (kept alive by a reference on its VM file taken in vfio_ap_irq_enable()), preventing kvm_s390_gisa_destroy() from WARNing at VM teardown for every queue whose reset timed out.

If the reset eventually completes, interrupts will be terminated, but the pinned NIB page will be leaked. This is preferable to a compromised kernel or kernel crash, or waiting indefinitely and blocking access to all mdevs, hanging the guests to which they are attached.

Fixes dd174833e44e ("s390/vfio-ap: remove upper limit on wait for queue reset to complete")
---
 drivers/s390/crypto/vfio_ap_ops.c | 79 ++++++++++++++++++++++++++-----
 1 file changed, 67 insertions(+), 12 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +67 -12
index 729af61d8ad3..a8a0452fe029 100644
@@ -31,6 +31,7 @@
 #define AP_QUEUE_IN_USE "in use"
 
 #define AP_RESET_INTERVAL		20	/* Reset sleep interval (20ms)		*/
+#define AP_RESET_MAX_WAIT		2000	/* Maximum wait for reset (2000ms)	*/
 
 static int vfio_ap_mdev_reset_queues(struct ap_matrix_mdev *matrix_mdev);
 static int vfio_ap_mdev_reset_qlist(struct list_head *qlist);
@@ -2261,6 +2262,50 @@ static int apq_status_check(int apqn, struct ap_queue_status *status)
 	}
 }
 
+static void report_apq_reset_check_timeout(struct vfio_ap_queue *q)
+{
+	/*
+	 * The ISC registration updates the refcount in the GISA alert mask.
+	 * Unregister it now on the KVM that was used at enable time; the
+	 * reference held on its VM file since vfio_ap_irq_enable() guarantees
+	 * the KVM is valid here.  Leaving the ISC registered would prevent the
+	 * refcount from ever reaching zero, causing kvm_s390_gisa_destroy()
+	 * to WARN at VM teardown for every queue whose reset timed out.
+	 */
+	if (q->aqic_resources.isc != VFIO_AP_ISC_INVALID) {
+		if (q->aqic_resources.kvm_file) {
+			kvm_s390_gisc_unregister(file_to_kvm_s390(q->aqic_resources.kvm_file),
+						 q->aqic_resources.isc);
+			vfio_ap_aqic_put_kvm(q);
+		}
+		q->aqic_resources.isc = VFIO_AP_ISC_INVALID;
+	}
+
+	if (q->aqic_resources.iova) {
+		if (q->matrix_mdev) {
+			dev_warn_ratelimited(mdev_dev(q->matrix_mdev->mdev),
+					     "Reset timed out for APQN %02x.%04x: leaking NIB page to prevent host crash\n",
+					     AP_QID_CARD(q->apqn),
+					     AP_QID_QUEUE(q->apqn));
+		} else {
+			pr_warn_ratelimited("Reset timed out for APQN %02x.%04x: leaking NIB page to prevent host crash\n",
+					    AP_QID_CARD(q->apqn),
+					    AP_QID_QUEUE(q->apqn));
+		}
+	} else {
+		if (q->matrix_mdev) {
+			dev_warn_ratelimited(mdev_dev(q->matrix_mdev->mdev),
+					     "Reset timed out for APQN %02x.%04x\n",
+					     AP_QID_CARD(q->apqn),
+					     AP_QID_QUEUE(q->apqn));
+		} else {
+			pr_warn_ratelimited("Reset timed out for APQN %02x.%04x\n",
+					    AP_QID_CARD(q->apqn),
+					    AP_QID_QUEUE(q->apqn));
+		}
+	}
+}
+
 #define WAIT_MSG "Waited %dms for reset of queue %02x.%04x (%u, %u, %u)"
 
 static void apq_reset_check(struct work_struct *reset_work)
@@ -2299,14 +2344,7 @@ static void apq_reset_check(struct work_struct *reset_work)
 			vfio_ap_free_aqic_resources(q);
 			return;
 		}
-		if (ret == -EBUSY) {
-			pr_notice_ratelimited(WAIT_MSG, elapsed,
-					      AP_QID_CARD(q->apqn),
-					      AP_QID_QUEUE(q->apqn),
-					      status.response_code,
-					      status.queue_empty,
-					      status.irq_enabled);
-		} else {
+		if (ret != -EBUSY) {
 			if (q->reset_status.response_code == AP_RESPONSE_RESET_IN_PROGRESS ||
 			    q->reset_status.response_code == AP_RESPONSE_STATE_CHANGE_IN_PROGRESS ||
 			    ret == -EAGAIN) {
@@ -2326,12 +2364,29 @@ static void apq_reset_check(struct work_struct *reset_work)
 				 */
 				status = ap_zapq(q->apqn, 0);
 				memcpy(&q->reset_status, &status, sizeof(status));
-				continue;
+			} else {
+				if (q->aqic_resources.isc != VFIO_AP_ISC_INVALID)
+					vfio_ap_free_aqic_resources(q);
+				return;
 			}
-			if (q->aqic_resources.isc != VFIO_AP_ISC_INVALID)
-				vfio_ap_free_aqic_resources(q);
-			break;
 		}
+
+		/*
+		 * The reset is still in progress or is being retried. Give up
+		 * if it has not completed within the maximum wait time.
+		 */
+		if (elapsed >= AP_RESET_MAX_WAIT) {
+			report_apq_reset_check_timeout(q);
+			return;
+		}
+
+		if (ret == -EBUSY)
+			pr_notice_ratelimited(WAIT_MSG, elapsed,
+					      AP_QID_CARD(q->apqn),
+					      AP_QID_QUEUE(q->apqn),
+					      status.response_code,
+					      status.queue_empty,
+					      status.irq_enabled);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#13 lore raw

PATCH 15/20 s390/vfio-ap: confirm zeroization before treating a queue reset as complete

In reply to a message not in the archive

apq_status_check() treated AP_RESPONSE_NORMAL (0) returned from PQAP(TAPQ), as well as DECONFIGURED and CHECKSTOPPED, as confirmation that a queue reset had completed. AP_RESPONSE_NORMAL only indicates that the PQAP(ZAPQ) was accepted; zeroization is performed asynchronously. To confirm completion, the following bits in the status word returned from PQAP(TAPQ) must all be verified:

status->irq_enabled == 0
status->queue_empty == 1
status->replies_waiting == 0
status->async == 0

Keep waiting until they are. This relies on the bounded wait introduced by the previous patch: a guest can keep a queue non-empty, so the wait must not be able to last forever.

When TAPQ returns AP_RESPONSE_DECONFIGURED or AP_RESPONSE_CHECKSTOPPED, all status bits are zero, so there is no way to distinguish a zeroized queue from one that was not zeroized. Interrupts are not possible in these states, so the AQIC resources can be freed, but zeroization cannot be confirmed. Return -ENODEV rather than 0 so the caller does not record the reset as confirmed.

Add apq_reset_finalize() to store the final TAPQ status in q->reset_status and free the AQIC resources. If zeroization was confirmed, the response code is set to AP_RESPONSE_NORMAL so that _queue_passable() returns true. For DECONFIGURED and CHECKSTOPPED the non-zero response code is kept, so that these queues can be told apart from one whose zeroization was confirmed.

Document the handling of AP_RESPONSE_RESET_IN_PROGRESS and AP_RESPONSE_BUSY in apq_status_check(). A reset in progress may be the one started by our ZAPQ or a prior one, such as a RAPQ from the AP bus or the guest; either zeroizes the queue, so keep waiting until the status bits confirm it. BUSY says nothing about whether our ZAPQ was accepted, so it is treated the same way, without re-issuing the ZAPQ.

Fixes 0daf9878a799 ("s390/vfio_ap: check TAPQ response code when waiting for queue reset")
---
 drivers/s390/crypto/vfio_ap_ops.c | 151 +++++++++++++++++++++---------
 1 file changed, 106 insertions(+), 45 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +106 -45
index a8a0452fe029..4c252e19304e 100644
@@ -2235,12 +2235,50 @@ static int apq_status_check(int apqn, struct ap_queue_status *status)
 {
 	switch (status->response_code) {
 	case AP_RESPONSE_NORMAL:
+		/*
+		 * This response code only indicates that the PQAP(ZAPQ) has
+		 * been initiated. The following bit settings in the status
+		 * returned from TAPQ must be verified to confirm that the
+		 * asynchronous portion of the queue zeroization has completed.
+		 */
+		if (status->queue_empty && !status->replies_waiting &&
+		    !status->irq_enabled && !status->async)
+			return 0;
+
+		/* Async zeroization still in progress; keep waiting */
+		return -EBUSY;
+
 	case AP_RESPONSE_DECONFIGURED:
 	case AP_RESPONSE_CHECKSTOPPED:
-		return 0;
+		/*
+		 * The queue is non-operational: interrupts are not possible so
+		 * AQIC resources can be safely freed. However, zeroization
+		 * cannot be confirmed because all status bits are zeroed when
+		 * these response codes are returned — there is no way to
+		 * distinguish a zeroized queue from one that has not been
+		 * zeroized. Return -ENODEV to signal that AQIC resources should
+		 * be freed but that zeroization has not been confirmed.
+		 */
+		return -ENODEV;
+
 	case AP_RESPONSE_RESET_IN_PROGRESS:
+		/*
+		 * A reset is in progress. It may be our ZAPQ or a prior reset
+		 * (e.g. a RAPQ from the AP bus or guest). Either one zeroizes
+		 * the queue, so keep waiting; the status bits checked for
+		 * AP_RESPONSE_NORMAL confirm when zeroization has completed.
+		 */
+		return -EBUSY;
+
 	case AP_RESPONSE_BUSY:
+		/*
+		 * TAPQ returned BUSY (rc 05). This says the queue is busy but
+		 * tells us nothing about whether our ZAPQ was accepted: the
+		 * zeroization may already be in progress. Treat it the same as
+		 * RESET_IN_PROGRESS — keep waiting without re-issuing the ZAPQ.
+		 */
 		return -EBUSY;
+
 	case AP_RESPONSE_ASSOC_SECRET_NOT_UNIQUE:
 	case AP_RESPONSE_ASSOC_FAILED:
 		/*
@@ -2308,6 +2346,30 @@ static void report_apq_reset_check_timeout(struct vfio_ap_queue *q)
 
 #define WAIT_MSG "Waited %dms for reset of queue %02x.%04x (%u, %u, %u)"
 
+/**
+ * apq_reset_finalize - store final TAPQ status and free AQIC resources.
+ * @q:      the vfio_ap_queue
+ * @status: the final AP queue status returned by PQAP(TAPQ)
+ * @ret:    the return value from apq_status_check()
+ *
+ * Copies the full TAPQ status word to q->reset_status so that all status
+ * bits reflect the confirmed end state of the queue. If ret == 0,
+ * zeroization was confirmed and the response code is overridden with
+ * AP_RESPONSE_NORMAL so that _queue_passable() returns true. For
+ * ret == -ENODEV (DECONFIGURED or CHECKSTOPPED), the non-zero response
+ * code is left intact so _queue_passable() correctly returns false.
+ * AQIC resources are then freed.
+ */
+static void apq_reset_finalize(struct vfio_ap_queue *q,
+			       struct ap_queue_status *status, int ret)
+{
+	memcpy(&q->reset_status, status, sizeof(*status));
+	if (!ret)
+		q->reset_status.response_code = AP_RESPONSE_NORMAL;
+
+	vfio_ap_free_aqic_resources(q);
+}
+
 static void apq_reset_check(struct work_struct *reset_work)
 {
 	int ret = -EBUSY, elapsed = 0;
@@ -2319,61 +2381,59 @@ static void apq_reset_check(struct work_struct *reset_work)
 	while (true) {
 		msleep(AP_RESET_INTERVAL);
 		elapsed += AP_RESET_INTERVAL;
-		status = ap_tapq(q->apqn, NULL);
-		ret = apq_status_check(q->apqn, &status);
-		if (ret == -EIO) {
-			/*
-			 * TAPQ returned an invalid response code indicating a
-			 * hardware or firmware bug. Since we cannot determine
-			 * whether the queue can still DMA-write to the NIB, the
-			 * AQIC resources are intentionally leaked lest the NIB
-			 * page is reallocated to a new owner. A subsequent
-			 * wild DMA-write to that physical address would corrupt
-			 * the new owner's memory which could crash or compromise
-			 * the host kernel.
-			 *
-			 * Record the TAPQ status so the queue is marked
-			 * not-passable - _queue_passable() checks
-			 * reset_status.response_code == AP_RESPONSE_NORMAL -
-			 * and the queue is not passed through to a guest.
-			 */
+
+		if (q->reset_status.response_code == AP_RESPONSE_STATE_CHANGE_IN_PROGRESS) {
+			status = ap_zapq(q->apqn, 0);
 			memcpy(&q->reset_status, &status, sizeof(status));
-			return;
-		}
-		if (ret == -ENODEV) {
-			vfio_ap_free_aqic_resources(q);
-			return;
-		}
-		if (ret != -EBUSY) {
-			if (q->reset_status.response_code == AP_RESPONSE_RESET_IN_PROGRESS ||
-			    q->reset_status.response_code == AP_RESPONSE_STATE_CHANGE_IN_PROGRESS ||
-			    ret == -EAGAIN) {
+		} else {
+			status = ap_tapq(q->apqn, NULL);
+			ret = apq_status_check(q->apqn, &status);
+			if (ret == -EIO) {
 				/*
-				 * RESET_IN_PROGRESS in reset_status means the
-				 * initial ZAPQ was rejected because a prior reset
-				 * was already running. That reset does not zeroize
-				 * the queue; re-issue the ZAPQ once it clears.
-				 *
-				 * STATE_CHANGE_IN_PROGRESS in reset_status means
-				 * the initial ZAPQ was rejected because the queue
-				 * was mid-transition; re-issue once it clears.
+				 * TAPQ returned an invalid response code indicating a
+				 * hardware or firmware bug. Since we cannot determine
+				 * whether the queue can still DMA-write to the NIB, the
+				 * AQIC resources are intentionally leaked lest the NIB
+				 * page is reallocated to a new owner. A subsequent
+				 * wild DMA-write to that physical address would corrupt
+				 * the new owner's memory which could crash or compromise
+				 * the host kernel.
 				 *
-				 * -EAGAIN means TAPQ returned an ASSOC error code
-				 * (0x35/0x36): the queue is stuck until reset.
-				 * Re-issue the ZAPQ to recover.
+				 * Record the TAPQ status so the queue is marked
+				 * not-passable - _queue_passable() checks
+				 * reset_status.response_code == AP_RESPONSE_NORMAL -
+				 * and the queue is not passed through to a guest.
 				 */
+				memcpy(&q->reset_status, &status, sizeof(status));
+				return;
+			} else if (ret == -EAGAIN) {
 				status = ap_zapq(q->apqn, 0);
 				memcpy(&q->reset_status, &status, sizeof(status));
-			} else {
-				if (q->aqic_resources.isc != VFIO_AP_ISC_INVALID)
-					vfio_ap_free_aqic_resources(q);
+			} else if (!ret || ret == -ENODEV) {
+				/*
+				 * We are here for one of two reasons:
+				 *
+				 * Zeroization confirmed (ret == 0): the TAPQ status bits
+				 * indicate the async portion of the ZAPQ completed
+				 * successfully.
+				 *
+				 * Queue non-operational (ret == -ENODEV): the queue is
+				 * deconfigured or checkstopped; interrupts are not
+				 * possible. Zeroization cannot be confirmed in this state,
+				 * but the queue cannot generate interrupts, so the
+				 * NIB page is no longer a DMA target.
+				 *
+				 * In either case, it is safe to free up the AQIC
+				 * resources.
+				 */
+				apq_reset_finalize(q, &status, ret);
 				return;
 			}
 		}
 
 		/*
-		 * The reset is still in progress or is being retried. Give up
-		 * if it has not completed within the maximum wait time.
+		 * If we haven't returned above, the reset is still in progress
+		 * or being retried. Check for timeout before continuing.
 		 */
 		if (elapsed >= AP_RESET_MAX_WAIT) {
 			report_apq_reset_check_timeout(q);
@@ -2387,6 +2447,7 @@ static void apq_reset_check(struct work_struct *reset_work)
 					      status.response_code,
 					      status.queue_empty,
 					      status.irq_enabled);
+
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#14 lore raw

PATCH 16/20 s390/vfio-ap: do not pass through a queue not confirmed zeroized

In reply to a message not in the archive

_queue_passable() accepted AP_RESPONSE_DECONFIGURED and AP_RESPONSE_CHECKSTOPPED as passable states in addition to AP_RESPONSE_NORMAL. Neither DECONFIGURED nor CHECKSTOPPED confirms that the queue was zeroized; only AP_RESPONSE_NORMAL
(0) does. A queue not confirmed zeroized must not be passed through to a guest, as it may contain key material from a previous guest or host operation.

_queue_passable() is therefore changed to a two-step check. First, reset_status.response_code is verified to be AP_RESPONSE_NORMAL; if not, the queue is not passable regardless of its current hardware state. Second, a live PQAP(TAPQ) is issued to detect state changes that occurred after the last reset - such as a subsequent deconfigure or checkstop - without requiring a callback from the AP bus. If TAPQ returns AP_RESPONSE_BUSY or AP_RESPONSE_RESET_IN_PROGRESS, the queue state cannot yet be determined, so the TAPQ is retried after a 10 ms sleep for up to 5 attempts. This avoids filtering a queue that is only transiently busy. If the queue is still busy after the last attempt, it is treated as not passable; since reset_status was NORMAL this is expected to be transient and the queue will be re-evaluated on the next filter_matrix call.

Fixes a681226c675c ("s390/vfio-ap: handle hardware checkstop state on queue reset operation")
---
 drivers/s390/crypto/vfio_ap_ops.c | 60 +++++++++++++++++++++++++------
 1 file changed, 50 insertions(+), 10 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +50 -10
index 4c252e19304e..86eb48df27f1 100644
@@ -32,6 +32,8 @@
 
 #define AP_RESET_INTERVAL		20	/* Reset sleep interval (20ms)		*/
 #define AP_RESET_MAX_WAIT		2000	/* Maximum wait for reset (2000ms)	*/
+#define AP_TAPQ_RETRIES			5	/* Max TAPQ attempts when busy		*/
+#define AP_TAPQ_RETRY_INTERVAL		10	/* TAPQ retry sleep interval (10ms)	*/
 
 static int vfio_ap_mdev_reset_queues(struct ap_matrix_mdev *matrix_mdev);
 static int vfio_ap_mdev_reset_qlist(struct list_head *qlist);
@@ -891,19 +893,57 @@ static bool vfio_ap_mdev_filter_cdoms(struct ap_matrix_mdev *matrix_mdev)
 			     AP_DOMAINS);
 }
 
+/**
+ * _queue_passable:
+ *
+ * In order to prevent leaking of sensitive data to a guest, a queue must have
+ * been reset before passing it through. If the status stored for the most
+ * recent reset operation is anything other than AP_RESPONSE_NORMAL, then the
+ * queue can not be passed through. On the other hand, the status of the queue
+ * could have changed since the last reset; for example, the queue could have been
+ * deconfigured via the HMC/SE or the sysfs config interface for a crypto card,
+ * or something could have occurred - e.g., a hardware failure - that moved the
+ * queue status to check stop state. To verify the queue is still passable,
+ * the PQAP-TAPQ instruction will be executed to determine the current state
+ * of the queue. If TAPQ returns AP_RESPONSE_BUSY or
+ * AP_RESPONSE_RESET_IN_PROGRESS, the current state of the queue can not be
+ * determined, so the instruction is re-executed after sleeping for
+ * AP_TAPQ_RETRY_INTERVAL milliseconds, up to AP_TAPQ_RETRIES times. If the
+ * queue is still busy after the last attempt, it is treated as not passable.
+ *
+ * @q:	the object containing the data associated with a queue bound to the
+ *	vfio_ap device driver
+ *
+ * Returns:	true if the queue can be safely passed through to a guest;
+ *		otherwise,returns false
+ */
 static bool _queue_passable(struct vfio_ap_queue *q)
 {
+	struct ap_queue_status status;
+	int retries = AP_TAPQ_RETRIES;
+
 	if (!q)
 		return false;
 
-	switch (q->reset_status.response_code) {
-	case AP_RESPONSE_NORMAL:
-	case AP_RESPONSE_DECONFIGURED:
-	case AP_RESPONSE_CHECKSTOPPED:
-		return true;
-	default:
+	if (q->reset_status.response_code != AP_RESPONSE_NORMAL)
 		return false;
-	}
+
+	do {
+		status = ap_tapq(q->apqn, NULL);
+
+		switch (status.response_code) {
+		case AP_RESPONSE_NORMAL:
+			return true;
+		case AP_RESPONSE_BUSY:
+		case AP_RESPONSE_RESET_IN_PROGRESS:
+			msleep(AP_TAPQ_RETRY_INTERVAL);
+			break;
+		default:
+			return false;
+		}
+	} while (--retries);
+
+	return false;
 }
 
 /*
@@ -2400,9 +2440,9 @@ static void apq_reset_check(struct work_struct *reset_work)
 				 * the host kernel.
 				 *
 				 * Record the TAPQ status so the queue is marked
-				 * not-passable - _queue_passable() checks
-				 * reset_status.response_code == AP_RESPONSE_NORMAL -
-				 * and the queue is not passed through to a guest.
+				 * not-passable: _queue_passable() first checks
+				 * reset_status.response_code == AP_RESPONSE_NORMAL,
+				 * and the queue will not be passed through to a guest.
 				 */
 				memcpy(&q->reset_status, &status, sizeof(status));
 				return;
Signature · 1 line
2.53.0
author maintainer
#15 lore raw

PATCH 17/20 s390/vfio-ap: reset a queue when it is probed for an assigned mdev

In reply to a message not in the archive

When a queue is probed and its APQN is already assigned to a matrix mdev, nothing guarantees that the queue has been reset before it can be admitted to a guest. The new queue object starts with a zeroed reset_status, which _queue_passable() reads as AP_RESPONSE_NORMAL; a queue that this driver never reset therefore looks as if its zeroization had been confirmed.

Reset the queue in vfio_ap_mdev_probe_queue() and wait for the reset to complete with flush_work() before the queue can be added to a guest's AP configuration, so that _queue_passable() sees the status of a completed reset.

The reset is done while the update locks are held, which adds at least AP_RESET_INTERVAL (20 ms) of lock-hold time per probed queue, since apq_reset_check() sleeps before its first TAPQ. In theory this is O(N) serialized under the global mdevs_lock; in practice, AP hardware constraints and typical deployment sizes bound the number of queues allocated for guest use in a single LPAR to a modest number.

Deferring the reset until the locks are dropped is not safe:
apq_reset_check() accesses q->reset_status and q->aqic_resources without holding any lock, and vfio_ap_mdev_remove_queue() can run concurrently and free the queue, leaving the worker with a dangling pointer. Calling flush_work() inside the lock-held section ensures the worker has finished before the locks are dropped.

The fundamental remedy would be to replace the global mdevs_lock with a per-mdev lock, scoping the blocking to the single mdev whose queue is being probed and allowing resets across different mdevs to proceed in parallel. That is a non-trivial redesign of the locking architecture and is deferred to a separate effort.

Fixes 260f3ea14138 ("s390/vfio-ap: move probe and remove callbacks to vfio_ap_ops.c")
---
 drivers/s390/crypto/vfio_ap_ops.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/s390/crypto/vfio_ap_ops.c +2 -0
index 86eb48df27f1..19638fea0ed3 100644
@@ -2995,6 +2995,8 @@ int vfio_ap_mdev_probe_queue(struct ap_device *apdev)
 
 	if (matrix_mdev) {
 		vfio_ap_mdev_link_queue(matrix_mdev, q);
+		vfio_ap_mdev_reset_queue(q);
+		flush_work(&q->reset_work);
 
 		/*
 		 * If we're in the process of handling the adding of adapters or
Signature · 1 line
2.53.0
author maintainer
#16 lore raw

PATCH 18/20 s390/vfio-ap: filter the matrix when KVM is set for an mdev

In reply to a message not in the archive

The shadow APCB of an mdev reflects which of its assigned queues were operational the last time the matrix was filtered. A queue can become operational, or non-operational, after that and before the guest is started.

Call vfio_ap_mdev_filter_matrix() in vfio_ap_mdev_set_kvm(), before the guest's APCB is updated, so that a queue which changed state since the shadow APCB was last updated is correctly admitted to or excluded from the guest when it boots. Any adapters that are newly filtered out are reset, as is done in the other callers, to prevent stale state from reaching the guest.

Fixes 51dc562af09d ("s390/vfio-ap: allow hot plug/unplug of AP devices when assigned/unassigned")
---
 drivers/s390/crypto/vfio_ap_ops.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/s390/crypto/vfio_ap_ops.c +11 -0
index 19638fea0ed3..52bfe383cf43 100644
@@ -2101,6 +2101,8 @@ static const struct attribute_group *vfio_ap_mdev_attr_groups[] = {
 static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
 				struct file *kvm_file)
 {
+	DECLARE_BITMAP(apm_filtered, AP_DEVICES);
+
 	struct kvm *kvm;
 
 	if (!kvm_file)
@@ -2119,6 +2121,15 @@ static int vfio_ap_mdev_set_kvm(struct ap_matrix_mdev *matrix_mdev,
 		kvm->arch.crypto.pqap_hook = &matrix_mdev->pqap_hook;
 
 		matrix_mdev->kvm = kvm;
+		/*
+		 * Filter the matrix to ensure the shadow_apcb reflects the
+		 * current operational state of all assigned queues. A queue
+		 * may have become operational (or non-operational) since the
+		 * shadow_apcb was last updated. Any adapters newly filtered
+		 * out are reset to prevent stale state from reaching the guest.
+		 */
+		if (vfio_ap_mdev_filter_matrix(matrix_mdev, apm_filtered))
+			reset_queues_for_apids(matrix_mdev, apm_filtered);
 		vfio_ap_mdev_update_guest_apcb(matrix_mdev);
 		release_update_locks_for_kvm(kvm);
 	}
Signature · 1 line
2.53.0