Skip to contentSkip to conversation

drm/amdgpu/amdkfd: fix MES queue lifecycle on multi-GPU

PATCH In review Armas Spann 2 participants 19 messages Nov 24 – Nov 25

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

cover drm/amdgpu/amdkfd: fix MES queue lifecycle on multi-GPU

On a dual R9700 Pro (gfx 12.0.1) system running RCCL distributed training, MES hits 2-second preemption timeouts on REMOVE_QUEUE and SUSPEND after 90 to 120 seconds of operation. Both GPUs fail during RCCL collectives. The timeout triggers a MODE1 reset, which loses VRAM and cascades into a second reset on the peer GPU.

Root cause: cwsr_enable=0 prevents MES from preempting running compute waves. When an RCCL kernel on GPU0 waits for its peer on GPU1, and GPU1's queue gets evicted, MES cannot preempt GPU0's kernel because there is no CWSR. The 2s MES preemption timeout fires, MES rejects the command, and the driver treats it as a hang.

Separately, KFD frees queue storage (MQD, doorbell id, gang context) before MES has confirmed the removal. A REMOVE_QUEUE that completes late writes the queue state back into an MQD that has been given to the next queue. This is a use-after-free on the firmware side.

This series fixes both problems:

1/9 Distinguish rejected from timed-out MES commands so callers
can tell a firmware that said no from one that stopped answering. Add a ticket for late completion polling.
2/9 Factor out per-queue MES resource freeing into a helper. 3/9 Track per-queue MES state (mapped/unmapped/pending) so the rest
of the dqm knows whether MES may still reference storage.
4/9 Add a quarantine for queues that MES has not released. A reaper
workqueue polls for late completions and cleans up.
5/9 Defer freeing of queue storage until MES has confirmed retirement
in all four teardown paths (destroy, create failure, termination, process exit).
6/9 Keep eviction and restore consistent when MES fails. Do not
restore a queue whose eviction was not confirmed.
7/9 Apply queue property updates only after the queue is unmapped,
not while MES still owns it.
8/9 Reconcile KFD queue state with MES after a scheduler restart.
Queues from the previous firmware instance are retired.
9/9 Force cwsr_enable=1 on gfx11+ discrete GPUs when a second MES
GPU is present. Per-device decision, logged to dmesg.

Tested on a dual R9700 Pro system (gfx 12.0.1, Threadripper 1950X, 64GB, Gentoo, kernel 7.3.5-p1 with these patches):

- RCCL all_reduce stress 150s: 85,582 iters, 570.5 it/s, 0 errors
- RCCL all_reduce stress 600s: 343,647 iters, 572.7 it/s, 0 errors
- F5-TTS dual-GPU training 50,780 steps: completed, no MES errors
- dmesg after all tests: zero MES rejects, zero resets
- Patch 9 override test (cwsr_enable=0 in cmdline): kernel forces 1, logs warning per affected GPU

Related reports:

https://github.com/ROCm/hrx-system/issues/2938
https://github.com/ROCm/TheRock/issues/9279
https://github.com/ROCm/TheRock/issues/9299
https://github.com/ROCm/rccl/issues/2193

Cc Alex Deucher <[email protected]>
Cc Christian König <[email protected]>
Cc Felix Kuehling <[email protected]>

Armas Spann (9):
drm/amdgpu/mes: distinguish rejected from timed out commands drm/amdkfd: factor out freeing of per-queue MES resources drm/amdkfd: track whether MES knows each queue drm/amdkfd: add a quarantine for queues MES has not retired drm/amdkfd: keep queue storage until MES confirmed retirement drm/amdkfd: keep eviction and restore consistent when MES fails drm/amdkfd: apply queue property updates only after unmap drm/amdkfd: reconcile queue state with MES after a restart drm/amdkfd: force CWSR on with more than one MES GPU

 drivers/gpu/drm/amd/amdgpu/amdgpu.h           |   1 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c       |  99 ++-
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c       |  79 +++
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h       |  44 ++
 drivers/gpu/drm/amd/amdgpu/mes_v11_0.c        |  51 +-
 drivers/gpu/drm/amd/amdgpu/mes_v12_0.c        |  52 +-
 drivers/gpu/drm/amd/amdgpu/mes_v12_1.c        |  57 +-
 drivers/gpu/drm/amd/amdkfd/kfd_device.c       |  35 +-
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 627 ++++++++++++++++--
 .../drm/amd/amdkfd/kfd_device_queue_manager.h |  31 +
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  51 ++
 drivers/gpu/drm/amd/amdkfd/kfd_process.c      |  51 +-
 .../amd/amdkfd/kfd_process_queue_manager.c    | 167 +++--
 drivers/gpu/drm/amd/amdkfd/kfd_queue.c        |  30 +
 14 files changed, 1247 insertions(+), 128 deletions(-)
Signature · 1 line
2.56.1
#1 lore raw

PATCH 1/9 drm/amdgpu/mes: distinguish rejected from timed out commands

The MES command path reports two different outcomes as "MES failed to respond" and -ETIMEDOUT: the fence was not reached within the poll timeout, or the fence was reached and MES wrote a failure status. Callers cannot tell a firmware that stopped answering from one that answered promptly and said no. On an R9700 (gfx 12.0.1) three REMOVE_QUEUE failures were logged within 644 us of each other, which the 2.1 s poll timeout rules out, yet KFD handled them as a hung scheduler and reset the GPU.

Return AMDGPU_MES_CMD_REJECTED (-EREMOTEIO) when MES answered with a failure and print the 64 bit status, whose upper half carries the error code of the firmware. -ETIMEDOUT now only means that MES did not answer. No caller compares a MES result against -ETIMEDOUT today.

A command that timed out is still in the MES ring and may be executed later. Its status writeback slot is freed on timeout and the allocator is first fit, so a late status write lands in a slot that belongs to somebody else by then, and the caller cannot find out that the command completed after all. Add a ticket that the caller of REMOVE_QUEUE can pass in. When the command is left unanswered, the ticket takes over the status slot and remembers the fence sequence. The caller can poll it for a late completion and releases the slot once MES cannot write to it any more.

Add mes.fw_gen, incremented each time the scheduler pipe has been set up from scratch. A queue that was added under an older generation does not exist in the firmware any more, and a ticket from an older generation is stale. The counter is only incremented on the full init path, behind the pipe reset: a missed increment delays the release of resources, a spurious one would be unsafe.

While at it, make mes_v12_1 return -ETIMEDOUT when the MES ring is full. It returned 0 there, which a caller would take for a completed command.

The ticket and the generation counter have no users yet. The only change in behaviour is the error code and the log line for rejected commands.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c | 79 +++++++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h | 44 ++++++++++++++
 drivers/gpu/drm/amd/amdgpu/mes_v11_0.c  | 51 ++++++++++++++--
 drivers/gpu/drm/amd/amdgpu/mes_v12_0.c  | 52 ++++++++++++++--
 drivers/gpu/drm/amd/amdgpu/mes_v12_1.c  | 57 +++++++++++++++---
 5 files changed, 264 insertions(+), 19 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +79 -0
index 7864afab5..dd9366b99 100644
@@ -141,6 +141,7 @@ int amdgpu_mes_init(struct amdgpu_device *adev)
 				adev->gfx.disable_kq ? 0 : adev->gfx.num_compute_rings);
 
 	adev->mes.adev = adev;
+	atomic_set(&adev->mes.fw_gen, 0);
 
 	ida_init(&adev->mes.doorbell_ida);
 	spin_lock_init(&adev->mes.queue_id_lock);
@@ -345,6 +346,84 @@ void amdgpu_mes_fini(struct amdgpu_device *adev)
 	mutex_destroy(&adev->mes.dbgext_drain_lock);
 }
 
+/* True when MES has processed the command stream up to @seq. */
+static bool amdgpu_mes_fence_passed(struct amdgpu_ring *ring, u32 seq)
+{
+	u32 cur = le32_to_cpu(READ_ONCE(*ring->fence_drv.cpu_addr));
+
+	return (s32)(seq - cur) <= 0;
+}
+
+/**
+ * amdgpu_mes_ticket_poll - check on a command that timed out earlier
+ *
+ * @adev: amdgpu_device pointer
+ * @ticket: ticket filled in by the command path
+ *
+ * Does not sleep and takes no locks. The caller serialises against
+ * amdgpu_mes_ticket_release() on the same ticket.
+ */
+enum amdgpu_mes_ticket_state
+amdgpu_mes_ticket_poll(struct amdgpu_device *adev,
+		       const struct amdgpu_mes_cmd_ticket *ticket)
+{
+	const u64 *status;
+
+	if (!ticket->valid ||
+	    ticket->fw_gen != (u32)atomic_read(&adev->mes.fw_gen))
+		return AMDGPU_MES_TICKET_STALE;
+
+	status = (const u64 *)&adev->wb.wb[ticket->status_offs];
+	if (lower_32_bits(READ_ONCE(*status)))
+		return AMDGPU_MES_TICKET_DONE;
+
+	if (!amdgpu_mes_fence_passed(&adev->mes.ring[ticket->ring_idx],
+				     ticket->seq))
+		return AMDGPU_MES_TICKET_PENDING;
+
+	/* MES writes the status before the trailing fence. Look again. */
+	return lower_32_bits(READ_ONCE(*status)) ?
+		AMDGPU_MES_TICKET_DONE : AMDGPU_MES_TICKET_FAILED;
+}
+
+/**
+ * amdgpu_mes_ticket_answered - has MES got past a timed out command
+ *
+ * @adev: amdgpu_device pointer
+ * @ticket: ticket, or a copy of one
+ *
+ * Unlike amdgpu_mes_ticket_poll() this does not look at the status slot,
+ * so it may be used on a copy whose original has been released.
+ */
+bool amdgpu_mes_ticket_answered(struct amdgpu_device *adev,
+				const struct amdgpu_mes_cmd_ticket *ticket)
+{
+	if (ticket->fw_gen != (u32)atomic_read(&adev->mes.fw_gen))
+		return true;
+
+	return amdgpu_mes_fence_passed(&adev->mes.ring[ticket->ring_idx],
+				       ticket->seq);
+}
+
+/**
+ * amdgpu_mes_ticket_release - give back the status slot of a ticket
+ *
+ * @adev: amdgpu_device pointer
+ * @ticket: ticket to release, may be invalid already
+ *
+ * Only call this once MES cannot write the status any more: the command
+ * was answered, or the firmware instance that received it is gone.
+ */
+void amdgpu_mes_ticket_release(struct amdgpu_device *adev,
+			       struct amdgpu_mes_cmd_ticket *ticket)
+{
+	if (!ticket->valid)
+		return;
+
+	amdgpu_wb_free(adev, ticket->status_offs);
+	ticket->valid = false;
+}
+
 int amdgpu_mes_suspend(struct amdgpu_device *adev, u32 xcc_id)
 {
 	struct mes_suspend_gang_input input;
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h +44 -0

68 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v11_0.c +45 -6

90 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v12_0.c +46 -6

92 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +50 -7

103 lines not on this page · raw message

Signature · 1 line
2.56.1
#2 lore raw

Re: [PATCH v1 1/9] drm/amdgpu/mes: distinguish rejected from timed out commands

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] drm/amdgpu/mes: global fw_gen incremented per XCC in mes_v12_1_xcc_hw_init() - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] drm/amdgpu/mes: global fw_gen incremented per XCC in mes_v12_1_xcc_hw_init()
- [Medium] drm/amdgpu/mes: 32-bit status_ptr in mes_v12_1_submit_pkt_ticket() drops upper status
- [Medium] drm/amdgpu/mes: missing dma_rmb() in amdgpu_mes_ticket_poll() --

commit 8b562c80dbe629587cfa83feaa73d36461087d6f
Author: Armas Spann <[email protected]>

drm/amdgpu/mes: distinguish rejected from timed out commands

This commit returns AMDGPU_MES_CMD_REJECTED (-EREMOTEIO) when MES completes a command with a failure status instead of timing out, and adds command tickets and a firmware generation counter to track timed-out REMOVE_QUEUE commands.

Quoted 37 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +29 -0
index b71684d79b21a..fd1d3d7541a0a 100644
@@ -329,6 +330,84 @@ void amdgpu_mes_fini(struct amdgpu_device *adev)
 	mutex_destroy(&adev->mes.dbgext_drain_lock);
 }
 
+/* True when MES has processed the command stream up to @seq. */
+static bool amdgpu_mes_fence_passed(struct amdgpu_ring *ring, u32 seq)
+{
+	u32 cur = le32_to_cpu(READ_ONCE(*ring->fence_drv.cpu_addr));
+
+	return (s32)(seq - cur) <= 0;
+}
+
+/**
+ * amdgpu_mes_ticket_poll - check on a command that timed out earlier
+ *
+ * @adev: amdgpu_device pointer
+ * @ticket: ticket filled in by the command path
+ *
+ * Does not sleep and takes no locks. The caller serialises against
+ * amdgpu_mes_ticket_release() on the same ticket.
+ */
+enum amdgpu_mes_ticket_state
+amdgpu_mes_ticket_poll(struct amdgpu_device *adev,
+		       const struct amdgpu_mes_cmd_ticket *ticket)
+{
+	const u64 *status;
+
+	if (!ticket->valid ||
+	    ticket->fw_gen != (u32)atomic_read(&adev->mes.fw_gen))
+		return AMDGPU_MES_TICKET_STALE;
+
+	status = (const u64 *)&adev->wb.wb[ticket->status_offs];
+	if (lower_32_bits(READ_ONCE(*status)))

drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c void amdgpu_mes_fini(struct amdgpu_device *adev) · line 371

Quoted 10 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +10 -0
+		return AMDGPU_MES_TICKET_DONE;
+
+	if (!amdgpu_mes_fence_passed(&adev->mes.ring[ticket->ring_idx],
+				     ticket->seq))
+		return AMDGPU_MES_TICKET_PENDING;
+
+	/* MES writes the status before the trailing fence. Look again. */
+	return lower_32_bits(READ_ONCE(*status)) ?
+		AMDGPU_MES_TICKET_DONE : AMDGPU_MES_TICKET_FAILED;
+}

[Severity: Medium]
Should a dma_rmb() separate the load of *ring->fence_drv.cpu_addr in amdgpu_mes_fence_passed() from the second READ_ONCE(*status)?

The control dependency on amdgpu_mes_fence_passed() does not order load-to-load on weakly-ordered architectures. When a timed-out command completes concurrently with amdgpu_mes_ticket_poll(), the CPU can satisfy the second READ_ONCE(*status) from the stale 0 value loaded before the fence check, returning AMDGPU_MES_TICKET_FAILED for a command that succeeded.

[ ... ]

Quoted 4 lines
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +0 -0
index 5c046f64b0229..a2e0156ae66b7 100644

[ ... ]

Quoted 6 lines
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +1 -1
@@ -238,7 +241,18 @@ static int mes_v12_1_submit_pkt_and_poll_completion(struct amdgpu_mes *mes,
 
 	r = amdgpu_fence_wait_polling(ring, seq, timeout);
 	if (r < 1 || !*status_ptr) {
-		if (misc_op_str)
+		/* The fence was reached, so MES processed the command */

drivers/gpu/drm/amd/amdgpu/mes_v12_1.c static int mes_v12_1_submit_pkt_and_poll_completion(struct amdgpu_mes *mes, · line 254

Quoted 10 lines
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +10 -0
+		bool answered = r >= 1;
+
+		if (answered)
+			dev_err(adev->dev,
+				"MES(%d, %d) rejected msg=%s (opcode %d), status 0x%016llx\n",
+				xcc_id, pipe,
+				misc_op_str ? misc_op_str :
+				op_str ? op_str : "unknown",
+				x_pkt->header.opcode,
+				(unsigned long long)*status_ptr);

[Severity: Medium]
Does dereferencing status_ptr here always print 0x0000000000000000 when answered is true?

Unlike mes_v11_0 and mes_v12_0, which declare status_ptr as u64 *, mes_v12_1_submit_pkt_ticket() declares status_ptr as u32 *:

drivers/gpu/drm/amd/amdgpu/mes_v12_1.c:mes_v12_1_submit_pkt_ticket() {
	...
	u32 *status_ptr;
	...
	status_ptr = &adev->wb.wb[status_offset];
	*status_ptr = 0;
}

Because entering this branch with r >= 1 requires !*status_ptr, the 32-bit *status_ptr is guaranteed to be 0 and the firmware error code in the upper 32 bits of the 64-bit MES_API_STATUS writeback slot is never read (nor is the upper half cleared before submission).

[ ... ]

drivers/gpu/drm/amd/amdgpu/mes_v12_1.c static int mes_v12_1_xcc_hw_init(struct amdgpu_ip_block *ip_block, int xcc_id) · line 1948

Quoted 9 lines
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +3 -0
@@ -1901,6 +1941,9 @@ static int mes_v12_1_xcc_hw_init(struct amdgpu_ip_block *ip_block, int xcc_id)
 	if (r)
 		goto failure;
 
+	/* A new scheduler instance is up, it knows none of the old queues */
+	atomic_inc(&adev->mes.fw_gen);
+
 	mes_v12_1_set_hw_resources_1(&adev->mes, AMDGPU_MES_SCHED_PIPE, xcc_id);
 	mes_v12_1_init_aggregated_doorbell(&adev->mes, xcc_id);

[Severity: High]
Does incrementing a single device-wide adev->mes.fw_gen in mes_v12_1_xcc_hw_init() invalidate live tickets on other XCCs?

On GFX 12.1 each XCC runs its own MES scheduler instance and can be reinitialized independently during a partition reset via gfx_v12_1_xcp_resume() -> gfx_v12_1_xcc_cp_resume() -> amdgpu_mes_kiq_hw_init() -> mes_v12_1_xcc_hw_init(). Bumping the shared adev->mes.fw_gen causes amdgpu_mes_ticket_poll() to return AMDGPU_MES_TICKET_STALE and amdgpu_mes_ticket_answered() to return true for pending tickets on unreset XCCs, allowing amdgpu_mes_ticket_release() to free their status writeback slots while those XCCs' MES instances can still write to them. Tracking fw_gen per ring or per XCC would avoid this.

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

PATCH 2/9 drm/amdkfd: factor out freeing of per-queue MES resources

In reply to Armas Spann

The gang context and the GART mapping of the write pointer are the parts of a queue that only exist for MES. They are freed in pqm_clean_queue_resource() together with the GWS bookkeeping.

Move them into kfd_queue_free_mes_resources() so that code outside the pqm can free them at the point where MES is known to have let go of the queue.

No functional change.

---
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  1 +
 .../amd/amdkfd/kfd_process_queue_manager.c    | 21 ++++++++++++++-----
 2 files changed, 17 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +1 -0
index 3292e616d..0c276f7eb 100644
@@ -1387,6 +1387,7 @@ int kfd_criu_resume_queues(struct kfd_process *p);
 /* Queue Context Management */
 int init_queue(struct queue **q, const struct queue_properties *properties);
 void uninit_queue(struct queue *q);
+void kfd_queue_free_mes_resources(struct kfd_node *dev, struct queue *q);
 void print_queue_properties(struct queue_properties *q);
 void print_queue(struct queue *q);
 int kfd_queue_buffer_get(struct amdgpu_vm *vm, void __user *addr, struct amdgpu_bo **pbo,
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +16 -5
index b68e884b1..89e95b70e 100644
@@ -186,6 +186,21 @@ int pqm_init(struct process_queue_manager *pqm, struct kfd_process *p)
 	return 0;
 }
 
+/*
+ * Free the storage that only exists so MES can run the queue: the gang
+ * context and the GART mapping of the write pointer. MES addresses both
+ * directly, so the queue must be out of MES before this is called.
+ */
+void kfd_queue_free_mes_resources(struct kfd_node *dev, struct queue *q)
+{
+	if (!dev->kfd->shared_resources.enable_mes)
+		return;
+
+	amdgpu_mes_free_gang_ctx_index(&dev->adev->mes, q->gang_ctx_array_index);
+	amdgpu_amdkfd_free_kernel_mem(dev->adev, &q->gang_ctx_bo);
+	amdgpu_amdkfd_free_kernel_mem(dev->adev, (void **)&q->wptr_bo_gart);
+}
+
 static void pqm_clean_queue_resource(struct process_queue_manager *pqm,
 				     struct process_queue_node *pqn)
 {
@@ -210,11 +225,7 @@ static void pqm_clean_queue_resource(struct process_queue_manager *pqm,
 		pdd->qpd.num_gws = 0;
 	}
 
-	if (dev->kfd->shared_resources.enable_mes) {
-		amdgpu_mes_free_gang_ctx_index(&dev->adev->mes, pqn->q->gang_ctx_array_index);
-		amdgpu_amdkfd_free_kernel_mem(dev->adev, &pqn->q->gang_ctx_bo);
-		amdgpu_amdkfd_free_kernel_mem(dev->adev, (void **)&pqn->q->wptr_bo_gart);
-	}
+	kfd_queue_free_mes_resources(dev, pqn->q);
 }
 
 void pqm_uninit(struct process_queue_manager *pqm)
Signature · 1 line
2.56.1
#4 lore raw

Re: [PATCH v1 2/9] drm/amdkfd: factor out freeing of per-queue MES resources

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] drm/amdkfd: memory leak in…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] drm/amdkfd: memory leak in pqm_create_queue() [1] --

commit 287e7ae4498cc9b3a4da82d8515d5e0f04fa7f42
Author: Armas Spann <[email protected]>

drm/amdkfd: factor out freeing of per-queue MES resources

This commit factors out the cleanup of per-queue MES resources (gang_ctx_array_index, gang_ctx_bo, and wptr_bo_gart) from pqm_clean_queue_resource() into a new kfd_queue_free_mes_resources() helper.

Quoted 29 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +15 -0
index b68e884b1c37a..89e95b70e2763 100644
@@ -186,6 +186,21 @@ int pqm_init(struct process_queue_manager *pqm, struct kfd_process *p)
 	return 0;
 }
 
+/*
+ * Free the storage that only exists so MES can run the queue: the gang
+ * context and the GART mapping of the write pointer. MES addresses both
+ * directly, so the queue must be out of MES before this is called.
+ */
+void kfd_queue_free_mes_resources(struct kfd_node *dev, struct queue *q)
+{
+	if (!dev->kfd->shared_resources.enable_mes)
+		return;
+
+	amdgpu_mes_free_gang_ctx_index(&dev->adev->mes, q->gang_ctx_array_index);
+	amdgpu_amdkfd_free_kernel_mem(dev->adev, &q->gang_ctx_bo);
+	amdgpu_amdkfd_free_kernel_mem(dev->adev, (void **)&q->wptr_bo_gart);
+}
+
 static void pqm_clean_queue_resource(struct process_queue_manager *pqm,
 				     struct process_queue_node *pqn)
 {
@@ -210,11 +225,7 @@ static void pqm_clean_queue_resource(struct process_queue_manager *pqm,
 		pdd->qpd.num_gws = 0;
 	}

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c static void pqm_clean_queue_resource(struct process_queue_manager *pqm, · line 231

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +1 -5
 
-	if (dev->kfd->shared_resources.enable_mes) {
-		amdgpu_mes_free_gang_ctx_index(&dev->adev->mes, pqn->q->gang_ctx_array_index);
-		amdgpu_amdkfd_free_kernel_mem(dev->adev, &pqn->q->gang_ctx_bo);
-		amdgpu_amdkfd_free_kernel_mem(dev->adev, (void **)&pqn->q->wptr_bo_gart);
-	}
+	kfd_queue_free_mes_resources(dev, pqn->q);
 }
 
 void pqm_uninit(struct process_queue_manager *pqm)

[Severity: High]
This problem wasn't introduced by this patch, but should pqm_create_queue() also call kfd_queue_free_mes_resources() on the err_create_queue error path when q is non-NULL [1]?

init_user_queue() allocates gang_ctx_bo, gang_ctx_array_index, and wptr_bo_gart before pqm_create_queue() calls dev->dqm->ops.create_queue():

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c:pqm_create_queue() {
    ...
		retval = init_user_queue(pqm, dev, &q, properties, *qid);
		if (retval != 0)
			goto err_create_queue;
		pqn->q = q;
		pqn->kq = NULL;
		retval = dev->dqm->ops.create_queue(dev->dqm, q, &pdd->qpd, q_data,
						    restore_mqd, restore_ctl_stack);
    ...
	if (retval != 0) {
    ...
		goto err_create_queue;
	}
    ...
err_create_queue:
	uninit_queue(q);
	if (kq)
		kernel_queue_uninit(kq);
	kfree(pqn);
    ...
}

If dev->dqm->ops.create_queue() fails, err_create_queue only calls uninit_queue(q), leaking those MES resources and allowing a local user to exhaust kernel memory and MES gang context slots.

[1] https://sashiko.dev/#/bug/linux-0b93a0b0-d6d5-41d7-ac1d-c1955556cf28

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

PATCH 3/9 drm/amdkfd: track whether MES knows each queue

In reply to Armas Spann

KFD has no record of what MES knows about a queue. is_active is set before the MES command is sent and is not corrected from its result, and every failure of ADD_QUEUE or REMOVE_QUEUE is handled the same way. The consequences:

- REMOVE_QUEUE is sent for queues MES does not have. After a GPU reset the firmware starts empty, but queues that were active keep is_active and get a REMOVE_QUEUE when their process exits. MES rejects it and KFD answers with another GPU reset.
- reset_queues_mes() returns success although the queue that failed was not removed, when MES reported other queues as hung and those were reset.
- The result of the remove-after-reset command is ignored.
- Queues are added a second time after a halt that failed half way.
- The GPU is reset for a REMOVE_QUEUE that MES completes shortly after the 2.1 s poll gave up.

Record a per-queue state (unmapped, mapped, unknown) from the result of each command, together with the firmware generation the queue was added under. kfd_mes_queue_retired() answers the one question the rest of the dqm needs: can MES still reference this queue. It cannot when the queue was never added, its removal was confirmed, the firmware was restarted since, or an unanswered REMOVE_QUEUE has completed in the meantime.

With that in place:

- Remove and add do nothing for a queue that is already in the wanted state, and an add is refused while a removal is unconfirmed.
- A REMOVE_QUEUE that timed out gets 4 s more to complete before the recovery path runs. The wait holds the dqm lock, as the 2.1 s poll before it does.
- When the recovery path returns success and the queue is still in MES, it is removed explicitly.
- Once a command got no answer, nothing more is sent to MES until it answers or is restarted. Commands queued behind it would each time out under the dqm lock.
- update_queue() does not rewrite the MQD of an inactive queue whose removal is unconfirmed.

Queue storage is still freed as before. The following patches change that.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 263 ++++++++++++++++--
 .../drm/amd/amdkfd/kfd_device_queue_manager.h |  17 ++
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  14 +
 .../amd/amdkfd/kfd_process_queue_manager.c    |   2 +
 4 files changed, 278 insertions(+), 18 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +245 -18
index 03d3a739d..2d62c244c 100644
@@ -28,6 +28,7 @@
 #include <linux/list.h>
 #include <linux/types.h>
 #include <linux/bitops.h>
+#include <linux/delay.h>
 #include <linux/sched.h>
 #include "kfd_priv.h"
 #include "kfd_device_queue_manager.h"
@@ -207,6 +208,124 @@ static int convert_to_amdgpu_ring_type(int queue_type)
 	return amdgpu_ring_type;
 }
 
+/*
+ * MES queue state tracking
+ *
+ * The MQD, the gang context, the GART mapping of the write pointer and the
+ * doorbell id of a queue are all addressed by MES directly. q->mes_state
+ * records what MES knows about the queue, taken from the result of every
+ * ADD_QUEUE and REMOVE_QUEUE, so that the rest of the dqm can tell whether
+ * MES may still use that storage.
+ *
+ * All of this is protected by the dqm lock. The lock order is
+ *
+ *   p->mutex -> dqm lock -> reset_domain->sem (read, trylock) -> MES lock
+ *
+ * and none of the helpers below is called with the MES lock held.
+ */
+
+static u32 kfd_mes_gen(struct device_queue_manager *dqm)
+{
+	return (u32)atomic_read(&dqm->dev->adev->mes.fw_gen);
+}
+
+/*
+ * True when MES cannot reference the storage of @q: the queue was never
+ * added, its removal was confirmed, the firmware instance that knew it has
+ * been replaced, or a REMOVE_QUEUE that timed out has completed since.
+ *
+ * This is the only place where a queue becomes UNMAPPED without a command
+ * that succeeded.
+ */
+static bool kfd_mes_queue_retired(struct device_queue_manager *dqm,
+				  struct queue *q)
+{
+	struct amdgpu_device *adev = dqm->dev->adev;
+
+	if (!dqm->dev->kfd->shared_resources.enable_mes)
+		return true;
+	if (q->mes_state == KFD_MES_QUEUE_UNMAPPED)
+		return true;
+
+	/* The firmware instance that knew the queue is gone */
+	if (q->mes_fw_gen != kfd_mes_gen(dqm))
+		goto retired;
+
+	/* REMOVE_QUEUE completed after the driver stopped waiting for it */
+	if (q->mes_ticket.valid &&
+	    amdgpu_mes_ticket_poll(adev, &q->mes_ticket) ==
+	    AMDGPU_MES_TICKET_DONE)
+		goto retired;
+
+	return false;
+
+retired:
+	amdgpu_mes_ticket_release(adev, &q->mes_ticket);
+	q->mes_state = KFD_MES_QUEUE_UNMAPPED;
+	return true;
+}
+
+/*
+ * Stop talking to MES. Commands are handled in order, so anything sent
+ * behind one that got no answer only adds another timeout under the dqm
+ * lock. With no pending command to watch, only a firmware restart lifts
+ * the fence.
+ */
+static void kfd_mes_fence(struct device_queue_manager *dqm, struct queue *q)
+{
+	struct amdgpu_device *adev = dqm->dev->adev;
+
+	dqm->mes_fenced = true;
+	dqm->mes_fence_gen = kfd_mes_gen(dqm);
+	dqm->mes_fence_has_seq = q->mes_ticket.valid &&
+		amdgpu_mes_ticket_poll(adev, &q->mes_ticket) ==
+		AMDGPU_MES_TICKET_PENDING;
+	if (dqm->mes_fence_has_seq)
+		dqm->mes_fence_ticket = q->mes_ticket;
+}
+
+static bool kfd_mes_fenced(struct device_queue_manager *dqm)
+{
+	if (!dqm->mes_fenced)
+		return false;
+
+	if (dqm->mes_fence_gen != kfd_mes_gen(dqm) ||
+	    (dqm->mes_fence_has_seq &&
+	     amdgpu_mes_ticket_answered(dqm->dev->adev,
+					&dqm->mes_fence_ticket)))
+		dqm->mes_fenced = false;
+
+	return dqm->mes_fenced;
+}
+
+/*
+ * Wait for a REMOVE_QUEUE that timed out to complete after all. Sleeps with
+ * the dqm lock held. reset_domain->sem is not held, so a pending GPU reset
+ * is not held up by the wait.
+ */
+static bool kfd_mes_wait_retired(struct device_queue_manager *dqm,
+				 struct queue *q, unsigned int ms)
+{
+	struct amdgpu_device *adev = dqm->dev->adev;
+	unsigned long end = jiffies + msecs_to_jiffies(ms);
+
+	do {
+		if (kfd_mes_queue_retired(dqm, q))
+			return true;
+		/* Answered with a failure, or nothing left to wait for */
+		if (!q->mes_ticket.valid ||
+		    amdgpu_mes_ticket_poll(adev, &q->mes_ticket) !=
+		    AMDGPU_MES_TICKET_PENDING)
+			return false;
+		if (amdgpu_in_reset(adev) || amdgpu_amdkfd_is_fed(adev))
+			return false;
+		usleep_range(KFD_MES_REMOVE_POLL_US,
+			     2 * KFD_MES_REMOVE_POLL_US);
+	} while (time_before(jiffies, end));
+
+	return kfd_mes_queue_retired(dqm, q);
+}
+
 static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 			 struct qcm_process_device *qpd)
 {
@@ -215,9 +334,19 @@ static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 	struct mes_add_queue_input queue_input;
 	int r, queue_type;
 	uint64_t wptr_addr_off;
+	u32 gen;
 
 	if (!dqm->sched_running || dqm->sched_halt)
 		return 0;
+
+	/*
+	 * MES still has the queue (a halt that failed half way), or an
+	 * earlier REMOVE_QUEUE is unconfirmed. Never add a queue twice.
+	 */
+	if (!kfd_mes_queue_retired(dqm, q))
+		return q->mes_state == KFD_MES_QUEUE_MAPPED ? 0 : -EBUSY;
+	if (kfd_mes_fenced(dqm))
+		return -EIO;
 	if (!down_read_trylock(&adev->reset_domain->sem))
 		return -EIO;
 
@@ -270,10 +399,18 @@ static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 	queue_input.vm_cntx_cntl = qpd->vm_cntx_cntl;
 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
 
+	/* Cannot change under us, reset_domain->sem is held for reading */
+	gen = kfd_mes_gen(dqm);
+
 	amdgpu_mes_lock(&adev->mes);
 	r = adev->mes.funcs->add_hw_queue(&adev->mes, &queue_input);
 	amdgpu_mes_unlock(&adev->mes);
 	up_read(&adev->reset_domain->sem);
+
+	/* A failed ADD_QUEUE may still be executed, or may have been */
+	q->mes_fw_gen = gen;
+	q->mes_state = r ? KFD_MES_QUEUE_UNKNOWN : KFD_MES_QUEUE_MAPPED;
+
 	if (r) {
 		dev_err(adev->dev, "failed to add hardware queue to MES, doorbell=0x%x\n",
 			q->properties.doorbell_off);
@@ -299,24 +436,38 @@ static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 	return r;
 }
 
-static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, struct queue *q,
-					    struct qcm_process_device *qpd,
-					    bool is_for_reset,
-					    bool flush_mes_queue)
+/*
+ * Send one REMOVE_QUEUE and record the outcome in q->mes_state.
+ *
+ * Returns -EIO when nothing was sent because MES is fenced off or a GPU
+ * reset is in progress, and -ETIMEDOUT when MES did not answer (this
+ * command, or an earlier one for the same queue).
+ */
+static int __remove_queue_mes(struct device_queue_manager *dqm, struct queue *q,
+			      bool flush_mes_queue)
 {
-	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
-	int r;
+	struct amdgpu_device *adev = dqm->dev->adev;
 	struct mes_remove_queue_input queue_input;
+	int r;
 
-	/* queue was already removed during reset */
-	if (q->properties.is_reset)
-		return 0;
+	if (kfd_mes_fenced(dqm))
+		return -EIO;
+
+	/*
+	 * An earlier REMOVE_QUEUE for this queue is still in the MES ring.
+	 * Do not send another one behind it, and keep its status slot.
+	 */
+	if (q->mes_ticket.valid &&
+	    amdgpu_mes_ticket_poll(adev, &q->mes_ticket) ==
+	    AMDGPU_MES_TICKET_PENDING)
+		return -ETIMEDOUT;
 
-	if (!dqm->sched_running || dqm->sched_halt)
-		return 0;
 	if (!down_read_trylock(&adev->reset_domain->sem))
 		return -EIO;
 
+	/* The earlier command, if there was one, has been answered */
+	amdgpu_mes_ticket_release(adev, &q->mes_ticket);
+
 	memset(&queue_input, 0x0, sizeof(struct mes_remove_queue_input));
 	queue_input.doorbell_offset = q->properties.doorbell_off;
 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
@@ -324,23 +475,74 @@ static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, st
 	queue_input.remove_queue_after_reset = flush_mes_queue;
 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
 	queue_input.gang_context_array_index = q->gang_ctx_array_index;
+	queue_input.ticket = &q->mes_ticket;
 
 	amdgpu_mes_lock(&adev->mes);
 	r = adev->mes.funcs->remove_hw_queue(&adev->mes, &queue_input);
 	amdgpu_mes_unlock(&adev->mes);
 	up_read(&adev->reset_domain->sem);
 
+	q->mes_state = r ? KFD_MES_QUEUE_UNKNOWN : KFD_MES_QUEUE_UNMAPPED;
+
+	return r;
+}
+
+static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, struct queue *q,
+					    struct qcm_process_device *qpd,
+					    bool is_for_reset,
+					    bool flush_mes_queue)
+{
+	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
+	int r;
+
+	/* MES does not know the queue, or not any more: nothing to send */
+	if (kfd_mes_queue_retired(dqm, q))
+		return 0;
+
+	/* queue was already removed during reset */
+	if (q->properties.is_reset)
+		return 0;
+
+	if (!dqm->sched_running || dqm->sched_halt)
+		return 0;
+
+	r = __remove_queue_mes(dqm, q, flush_mes_queue);
+	if (!r)
+		return 0;
+
+	/* Not answered yet. The command is still queued and may complete. */
+	if (r == -ETIMEDOUT &&
+	    kfd_mes_wait_retired(dqm, q, KFD_MES_REMOVE_GRACE_MS)) {
+		dev_warn(adev->dev,
+			 "MES confirmed REMOVE_QUEUE late, doorbell=0x%x\n",
+			 q->properties.doorbell_off);
+		return 0;
+	}
+
 	/* If is_for_reset set, it is a mes internal cleanup */
-	if (!r || is_for_reset)
+	if (is_for_reset || r == -EIO)
 		return r;
 
 	/* remove_hw_queue failure indicates a queue hang. reset the queue */
 	r = reset_queues_mes(dqm, q);
-	if (r && amdgpu_gpu_recovery) {
-		dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
-			q->properties.doorbell_off);
-		dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
-		kfd_hws_hang(dqm);
+
+	/* The recovery dealt with other queues and left this one in MES */
+	if (!r && !kfd_mes_queue_retired(dqm, q))
+		r = __remove_queue_mes(dqm, q, false);
+
+	if (r) {
+		if (r == -ETIMEDOUT ||
+		    (q->mes_ticket.valid &&
+		     amdgpu_mes_ticket_poll(adev, &q->mes_ticket) ==
+		     AMDGPU_MES_TICKET_PENDING))
+			kfd_mes_fence(dqm, q);
+
+		if (amdgpu_gpu_recovery) {
+			dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
+				q->properties.doorbell_off);
+			dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
+			kfd_hws_hang(dqm);
+		}
 	}
 
 	return r;
@@ -484,8 +686,24 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
 	/* pass the known bad queue info to the reset function */
 	r = amdgpu_gfx_reset_mes_compute(adev, dqm->dev->xcp, NULL, NULL, NULL, &num_hung, &queue_input);
-	if (r)
+	if (r) {
+		/* The REMOVE_QUEUE for @q may have been sent and lost */
+		if (q->mes_state == KFD_MES_QUEUE_MAPPED)
+			q->mes_state = KFD_MES_QUEUE_UNKNOWN;
 		goto fail;
+	}
+
+	/*
+	 * With no hung queue reported, amdgpu_gfx_reset_mes_compute() sent
+	 * the REMOVE_QUEUE for @q itself and MES confirmed it. MES handles
+	 * its ring in order, so an earlier unanswered REMOVE_QUEUE for @q
+	 * has been dealt with as well and its status slot can go.
+	 */
+	if (!num_hung) {
+		amdgpu_mes_ticket_release(adev, &q->mes_ticket);
+		q->mes_state = KFD_MES_QUEUE_UNMAPPED;
+	}
+
 	pdd = kfd_get_process_device_data(q->device, q->process);
 	if (pdd) {
 		ti = amdgpu_vm_get_task_info_pasid(adev, pdd->pasid);
@@ -1147,6 +1365,15 @@ static int update_queue_locked(struct device_queue_manager *dqm, struct queue *q
 	/* Save the activity state for queue removal. */
 	prev_active = q->properties.is_active;
 
+	/*
+	 * The queue is inactive but MES has not confirmed its removal, so
+	 * MES may still read and write the MQD. Leave it alone.
+	 */
+	if (!prev_active && !kfd_mes_queue_retired(dqm, q)) {
+		retval = -EBUSY;
+		return retval;
+	}
+
 	/* Make sure the queue is unmapped before updating the MQD */
 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
 		if (!dqm->dev->kfd->shared_resources.enable_mes)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.h +17 -0
index c21da12d3..239168838 100644
@@ -37,6 +37,13 @@
 #define KFD_MES_PROCESS_QUANTUM		100000
 #define KFD_MES_GANG_QUANTUM		10000
 
+/*
+ * How long to keep waiting for a REMOVE_QUEUE after the 2.1 s command poll
+ * gave up, and the polling interval. The wait runs under the dqm lock.
+ */
+#define KFD_MES_REMOVE_GRACE_MS		4000
+#define KFD_MES_REMOVE_POLL_US		2000
+
 struct device_process_node {
 	struct qcm_process_device *qpd;
 	struct list_head list;
@@ -292,6 +299,16 @@ struct device_queue_manager {
 	/* for per-queue reset with mes */
 	u32 *hung_db_array;
 	struct amdgpu_mes_hung_queue_hqd_info *hqd_info;
+
+	/*
+	 * MES has a command it did not answer. Nothing more is sent until
+	 * it answers or the firmware is restarted. Protected by the dqm lock.
+	 */
+	bool			mes_fenced;
+	bool			mes_fence_has_seq;
+	u32			mes_fence_gen;
+	/* copy of the unanswered ticket, never released through this copy */
+	struct amdgpu_mes_cmd_ticket mes_fence_ticket;
 };
 
 void device_queue_manager_init_cik(
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +14 -0
index 0c276f7eb..b5eae33d8 100644
@@ -616,6 +616,13 @@ struct mqd_update_info {
  *
  */
 
+/* What MES knows about a queue, see kfd_mes_queue_retired() */
+enum kfd_mes_queue_state {
+	KFD_MES_QUEUE_UNMAPPED = 0,	/* never added, or removal confirmed */
+	KFD_MES_QUEUE_MAPPED,		/* ADD_QUEUE confirmed */
+	KFD_MES_QUEUE_UNKNOWN,		/* ADD or REMOVE sent, not confirmed */
+};
+
 struct queue {
 	struct list_head list;
 	void *mqd;
@@ -644,6 +651,13 @@ struct queue {
 
 	struct amdgpu_bo *wptr_bo_gart;
 
+	/* MES view of the queue. Protected by the dqm lock. */
+	enum kfd_mes_queue_state mes_state;
+	/* mes.fw_gen of the firmware instance the queue was added to */
+	u32 mes_fw_gen;
+	/* REMOVE_QUEUE that MES has not answered yet */
+	struct amdgpu_mes_cmd_ticket mes_ticket;
+
 	/* The VRAM-resident MQD BO (mqd_on_vram()) is unpinned at S4 suspend so
 	 * TTM evicts it into the hibernation image, and repinned on resume. Set
 	 * while the BO is unpinned so the resume path knows to repin it.
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +2 -0
index 89e95b70e..ef9ad6dc8 100644
@@ -196,6 +196,8 @@ void kfd_queue_free_mes_resources(struct kfd_node *dev, struct queue *q)
 	if (!dev->kfd->shared_resources.enable_mes)
 		return;
 
+	/* The status slot of an unanswered REMOVE_QUEUE goes with the queue */
+	amdgpu_mes_ticket_release(dev->adev, &q->mes_ticket);
 	amdgpu_mes_free_gang_ctx_index(&dev->adev->mes, q->gang_ctx_array_index);
 	amdgpu_amdkfd_free_kernel_mem(dev->adev, &q->gang_ctx_bo);
 	amdgpu_amdkfd_free_kernel_mem(dev->adev, (void **)&q->wptr_bo_gart);
Signature · 1 line
2.56.1
#6 lore raw

Re: [PATCH v1 3/9] drm/amdkfd: track whether MES knows each queue

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider: - [High] drm/amdkfd: ignored remove-after-reset error and unfenced timeout in reset_queue_mes() - [High]…

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider:
- [High] drm/amdkfd: ignored remove-after-reset error and unfenced timeout in reset_queue_mes()
- [High] drm/amdkfd: duplicate REMOVE_QUEUE after late completion in reset_queues_mes()
- [High] drm/amdkfd: false success in remove_queue_mes_on_reset_option() when queue is not retired
- [High] drm/amdkfd: kfd_dqm_suspend_bad_queue_mes() leaves unremoved queue in MES
- [Medium] drm/amdkfd: missing kfd_mes_fence() call on command timeout in add_queue_mes()
- [Medium] drm/amdkfd: reset_queues_mes() called behind unanswered REMOVE_QUEUE before fencing
- [Medium] drm/amdkfd: missing gang_context_array_index and ticket in reset_queues_mes()
- [Medium] drm/amdkfd: unlocked MES state access in kfd_reset_queue_mes()
It also noticed 1 related pre-existing issue this patch does not introduce:
- [High] drm/amdkfd: unbalanced queue unmap in update_queue() on reset queue [1]
--

commit 646aa63a006f03da9e5f44bcc16133cd8b988d3e
Author: Armas Spann <[email protected]>

drm/amdkfd: track whether MES knows each queue

This commit tracks the per-queue MES mapping state, firmware generation, and pending REMOVE_QUEUE ticket so KFD can tell whether MES still references a queue and avoid sending further commands behind an unanswered one.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index bd3dc4e9c9c77..684037d333bf1 100644

[ ... ]

Quoted 9 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +3 -0
@@ -270,10 +399,18 @@ static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 	queue_input.vm_cntx_cntl = qpd->vm_cntx_cntl;
 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
 
+	/* Cannot change under us, reset_domain->sem is held for reading */
+	gen = kfd_mes_gen(dqm);
+
 	amdgpu_mes_lock(&adev->mes);
 	r = adev->mes.funcs->add_hw_queue(&adev->mes, &queue_input);

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q, · line 416

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +5 -0
 	amdgpu_mes_unlock(&adev->mes);
 	up_read(&adev->reset_domain->sem);
+
+	/* A failed ADD_QUEUE may still be executed, or may have been */
+	q->mes_fw_gen = gen;
+	q->mes_state = r ? KFD_MES_QUEUE_UNKNOWN : KFD_MES_QUEUE_MAPPED;
+
 	if (r) {
 		dev_err(adev->dev, "failed to add hardware queue to MES, doorbell=0x%x\n",
 			q->properties.doorbell_off);

[Severity: Medium]
Should add_queue_mes() call kfd_mes_fence(dqm, q) when add_hw_queue() fails with -ETIMEDOUT?

kfd_hws_hang() only schedules an asynchronous reset work item, so without fencing MES here, callers that iterate over multiple queues under dqm_lock (such as kfd_resume_all_processes() or set_perfcount()) keep submitting commands behind the unanswered ADD_QUEUE and suffer cascading timeouts while holding reset_domain->sem.

Quoted 74 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +39 -11
@@ -299,24 +436,38 @@ static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 	return r;
 }
 
-static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, struct queue *q,
-					    struct qcm_process_device *qpd,
-					    bool is_for_reset,
-					    bool flush_mes_queue)
+/*
+ * Send one REMOVE_QUEUE and record the outcome in q->mes_state.
+ *
+ * Returns -EIO when nothing was sent because MES is fenced off or a GPU
+ * reset is in progress, and -ETIMEDOUT when MES did not answer (this
+ * command, or an earlier one for the same queue).
+ */
+static int __remove_queue_mes(struct device_queue_manager *dqm, struct queue *q,
+			      bool flush_mes_queue)
 {
-	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
-	int r;
+	struct amdgpu_device *adev = dqm->dev->adev;
 	struct mes_remove_queue_input queue_input;
+	int r;
 
-	/* queue was already removed during reset */
-	if (q->properties.is_reset)
-		return 0;
+	if (kfd_mes_fenced(dqm))
+		return -EIO;
+
+	/*
+	 * An earlier REMOVE_QUEUE for this queue is still in the MES ring.
+	 * Do not send another one behind it, and keep its status slot.
+	 */
+	if (q->mes_ticket.valid &&
+	    amdgpu_mes_ticket_poll(adev, &q->mes_ticket) ==
+	    AMDGPU_MES_TICKET_PENDING)
+		return -ETIMEDOUT;
 
-	if (!dqm->sched_running || dqm->sched_halt)
-		return 0;
 	if (!down_read_trylock(&adev->reset_domain->sem))
 		return -EIO;
 
+	/* The earlier command, if there was one, has been answered */
+	amdgpu_mes_ticket_release(adev, &q->mes_ticket);
+
 	memset(&queue_input, 0x0, sizeof(struct mes_remove_queue_input));
 	queue_input.doorbell_offset = q->properties.doorbell_off;
 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
@@ -324,23 +475,74 @@ static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, st
 	queue_input.remove_queue_after_reset = flush_mes_queue;
 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
 	queue_input.gang_context_array_index = q->gang_ctx_array_index;
+	queue_input.ticket = &q->mes_ticket;
 
 	amdgpu_mes_lock(&adev->mes);
 	r = adev->mes.funcs->remove_hw_queue(&adev->mes, &queue_input);
 	amdgpu_mes_unlock(&adev->mes);
 	up_read(&adev->reset_domain->sem);
 
+	q->mes_state = r ? KFD_MES_QUEUE_UNKNOWN : KFD_MES_QUEUE_UNMAPPED;
+
+	return r;
+}
+
+static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, struct queue *q,
+					    struct qcm_process_device *qpd,
+					    bool is_for_reset,
+					    bool flush_mes_queue)
+{
+	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
+	int r;
+

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, st · line 507

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	/* MES does not know the queue, or not any more: nothing to send */
+	if (kfd_mes_queue_retired(dqm, q))
+		return 0;
+
+	/* queue was already removed during reset */
+	if (q->properties.is_reset)
+		return 0;
+
+	if (!dqm->sched_running || dqm->sched_halt)
+		return 0;

[Severity: High]
When kfd_mes_queue_retired() returns false, MES may still have the queue; doesn't returning 0 on q->properties.is_reset, !dqm->sched_running, or dqm->sched_halt tell callers that the queue was unmapped while leaving it in MES?

Any queue that was genuinely removed during halt_cpsch(), stop_cpsch(), or reset_queue_mes() already returns 0 via kfd_mes_queue_retired(). If halt_cpsch() fails halfway through remove_all_kfd_queues_mes() and sets dqm->sched_halt = true with remaining active queues still mapped in MES, update_queue_locked() on one of those active queues gets 0 from remove_queue_mes() and rewrites its MQD in place while MES still has it mapped (or evict_process_queues_cpsch() unpins the MQD BO while MES can still access it).

[Severity: Medium]
Can remove_queue_mes_on_reset_option() also race on q->mes_ticket, q->mes_state, and dqm->mes_fenced when called from kfd_reset_queue_mes() without dqm_lock?

When a KCQ or AMDGPU userq reset runs amdgpu_gfx_reset_mes_compute() (from gfx_v11_0_reset_kcq(), gfx_v12_0_reset_kcq(), or amdgpu_userq_reset_work()), dqm_lock is not held:

CPU0 CPU1
destroy_queue_cpsch() gfx_v11_0_reset_kcq()
dqm_lock(dqm) amdgpu_gfx_reset_mes_compute()
remove_queue_mes() ...

    __remove_queue_mes()                    kfd_reset_queue_mes()
      amdgpu_mes_ticket_release()             reset_queue_mes()
      remove_hw_queue(...,                      remove_queue_mes_on_reset_option()
                      &q->mes_ticket)             kfd_mes_queue_retired()
                                                    amdgpu_mes_ticket_release()
                                                      <-- data race on q->mes_ticket

Concurrent updates to q->mes_ticket and q->mes_state can corrupt the state tracking or double-free the writeback slot in adev->wb.

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +8 -0
+
+	r = __remove_queue_mes(dqm, q, flush_mes_queue);
+	if (!r)
+		return 0;
+
+	/* Not answered yet. The command is still queued and may complete. */
+	if (r == -ETIMEDOUT &&
+	    kfd_mes_wait_retired(dqm, q, KFD_MES_REMOVE_GRACE_MS)) {

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, st · line 524

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -1
+		dev_warn(adev->dev,
+			 "MES confirmed REMOVE_QUEUE late, doorbell=0x%x\n",
+			 q->properties.doorbell_off);
+		return 0;
+	}
+
 	/* If is_for_reset set, it is a mes internal cleanup */
-	if (!r || is_for_reset)
+	if (is_for_reset || r == -EIO)
 		return r;

[Severity: High]
Does the is_for_reset path still ignore failures of the remove-after-reset command and skip kfd_mes_fence() on a timeout?

Returning early on is_for_reset skips kfd_mes_fence(dqm, q) when the remove-after-reset command times out, and the only caller passing is_for_reset = true ignores the return value:

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:reset_queue_mes() {
    ...
	/* Proceed remove_queue with reset=true */
	remove_queue_mes_on_reset_option(dqm, q, &pdd->qpd, true, true);
	set_queue_as_reset(dqm, q, &pdd->qpd, true);
	return 0;
}

When the remove-after-reset command fails or times out, reset_queue_mes() still marks the queue as is_reset = true and returns 0 to amdgpu_gfx_reset_mes_compute(), leaving q->mes_state as KFD_MES_QUEUE_UNKNOWN, skipping GPU reset recovery, and allowing further MES commands to be queued behind an unanswered command.

Quoted 19 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +11 -5
 	/* remove_hw_queue failure indicates a queue hang. reset the queue */
 	r = reset_queues_mes(dqm, q);
-	if (r && amdgpu_gpu_recovery) {
-		dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
-			q->properties.doorbell_off);
-		dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
-		kfd_hws_hang(dqm);
+
+	/* The recovery dealt with other queues and left this one in MES */
+	if (!r && !kfd_mes_queue_retired(dqm, q))
+		r = __remove_queue_mes(dqm, q, false);
+
+	if (r) {
+		if (r == -ETIMEDOUT ||
+		    (q->mes_ticket.valid &&
+		     amdgpu_mes_ticket_poll(adev, &q->mes_ticket) ==
+		     AMDGPU_MES_TICKET_PENDING))
+			kfd_mes_fence(dqm, q);

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, st · line 548

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -0
+
+		if (amdgpu_gpu_recovery) {
+			dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
+				q->properties.doorbell_off);
+			dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
+			kfd_hws_hang(dqm);
+		}
 	}
 
 	return r;

[Severity: Medium]
When __remove_queue_mes() returns -ETIMEDOUT and kfd_mes_wait_retired() returns false with q->mes_ticket still AMDGPU_MES_TICKET_PENDING (or because amdgpu_in_reset() is true), shouldn't this fence MES and skip reset_queues_mes()?

Calling reset_queues_mes() behind an unanswered REMOVE_QUEUE submits up to three more MES commands (suspend, detect_and_reset, and resume) to the same stalled ring before kfd_mes_fence() is reached, adding up to 6.3 seconds of udelay polling under dqm_lock and blocking amdgpu_amdkfd_pre_reset().

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q) · line 688

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
@@ -484,8 +686,24 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
 	/* pass the known bad queue info to the reset function */
 	r = amdgpu_gfx_reset_mes_compute(adev, dqm->dev->xcp, NULL, NULL, NULL, &num_hung, &queue_input);

[Severity: Medium]
Should queue_input in reset_queues_mes() also populate gang_context_array_index and ticket like __remove_queue_mes() does?

When num_hung == 0, amdgpu_gfx_reset_mes_compute() passes queue_input to adev->mes.funcs->remove_hw_queue(). Without setting queue_input.gang_context_array_index = q->gang_ctx_array_index and queue_input.ticket = &q->mes_ticket, MES v11 with use_rs64mem receives a gang context index of 0, and if that removal times out the writeback slot is freed early while the command is still in flight and q->mes_ticket is left untracked.

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +6 -1
-	if (r)
+	if (r) {
+		/* The REMOVE_QUEUE for @q may have been sent and lost */
+		if (q->mes_state == KFD_MES_QUEUE_MAPPED)
+			q->mes_state = KFD_MES_QUEUE_UNKNOWN;
 		goto fail;
+	}
+

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q) · line 705

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	/*
+	 * With no hung queue reported, amdgpu_gfx_reset_mes_compute() sent
+	 * the REMOVE_QUEUE for @q itself and MES confirmed it. MES handles
+	 * its ring in order, so an earlier unanswered REMOVE_QUEUE for @q
+	 * has been dealt with as well and its status slot can go.
+	 */
+	if (!num_hung) {
+		amdgpu_mes_ticket_release(adev, &q->mes_ticket);
+		q->mes_state = KFD_MES_QUEUE_UNMAPPED;
+	}

[Severity: High]
What happens if a timed-out REMOVE_QUEUE in the MES ring completes after kfd_mes_wait_retired() gives up, right before the SUSPEND command sent by amdgpu_gfx_reset_mes_compute()?

Because MES processes its ring in order, it executes the pending REMOVE_QUEUE (removing q and marking q->mes_ticket done) and then completes amdgpu_mes_suspend() with num_hung == 0. amdgpu_gfx_reset_mes_compute() then unconditionally calls remove_hw_queue() for queue_input a second time:

drivers/gpu/drm/amd/amdgpu/amdgpu_gfx.c:amdgpu_gfx_reset_mes_compute() {
    ...
	if (!num_hung && queue_input && !ring) {
		if (!down_read_trylock(&adev->reset_domain->sem)) {
			r = -EIO;
			goto out;
		}
		amdgpu_mes_lock(&adev->mes);
		r = adev->mes.funcs->remove_hw_queue(&adev->mes, queue_input);
		amdgpu_mes_unlock(&adev->mes);
		up_read(&adev->reset_domain->sem);
	}
    ...
}

MES rejects that duplicate removal with -EREMOTEIO, reset_queues_mes() takes the error path without checking kfd_mes_queue_retired(), and remove_queue_mes_on_reset_option() triggers a full GPU reset via kfd_hws_hang() for a queue removal that actually succeeded. Similarly, in __remove_queue_mes(), if an earlier ticket transitioned to AMDGPU_MES_TICKET_DONE after the caller's kfd_mes_queue_retired() check, __remove_queue_mes() releases the completed ticket and sends a duplicate REMOVE_QUEUE instead of retiring the queue.

[Severity: High]
Should the post-recovery removal when num_hung > 0 and !kfd_mes_queue_retired()
happen inside reset_queues_mes() (or in kfd_dqm_suspend_bad_queue_mes())
rather than only in remove_queue_mes_on_reset_option()?

When kfd_dqm_suspend_bad_queue_mes() calls reset_queues_mes(dqm, q) and MES reports other queues as hung (num_hung > 0), amdgpu_gfx_reset_mes_compute() resumes the non-hung queues without removing q:

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:kfd_dqm_suspend_bad_queue_mes() {
    ...
		list_for_each_entry(q, &qpd->queues_list, list) {
			if (q->doorbell_id == doorbell_id && q->properties.is_active) {
				reset_queues_mes(dqm, q);
				q->properties.is_evicted = true;
				q->properties.is_active = false;
				decrement_queue_count(dqm, qpd, q);
				break;
			}
		}
    ...
}

kfd_dqm_suspend_bad_queue_mes() then clears q->properties.is_active = false while q remains mapped in MES (q->mes_state == KFD_MES_QUEUE_MAPPED), and remove_all_kfd_queues_mes() later skips it because it gates remove_queue_mes() on q->properties.is_active instead of !kfd_mes_queue_retired(dqm, q).

Quoted 6 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +2 -0
@@ -1147,6 +1365,15 @@ static int update_queue_locked(struct device_queue_manager *dqm, struct queue *q
 	/* Save the activity state for queue removal. */
 	prev_active = q->properties.is_active;
 
+	/*
+	 * The queue is inactive but MES has not confirmed its removal, so

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int update_queue_locked(struct device_queue_manager *dqm, struct queue *q · line 1379

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -0
+	 * MES may still read and write the MQD. Leave it alone.
+	 */
+	if (!prev_active && !kfd_mes_queue_retired(dqm, q)) {
+		retval = -EBUSY;
+		return retval;
+	}
+
 	/* Make sure the queue is unmapped before updating the MQD */
 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
 		if (!dqm->dev->kfd->shared_resources.enable_mes)

[Severity: High]
This problem wasn't introduced by this patch, but in update_queue_locked() [1], pdd->has_reset_queue is checked only after unmapping dynamic queues or calling remove_queue_mes():

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:update_queue_locked() {
    ...
	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
		if (!dqm->dev->kfd->shared_resources.enable_mes)
			retval = unmap_queues_cpsch(dqm,
						    KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD, false);
		else if (prev_active)
			retval = remove_queue_mes(dqm, q, &pdd->qpd);

		/* queue is reset so inaccessable  */
		if (pdd->has_reset_queue) {
			return -EACCES;
		}
    ...
}

When pdd->has_reset_queue is set, returning -EACCES before the remapping step at the bottom of update_queue_locked() leaves all dynamic queues on the node unmapped on non-MES hardware scheduling, or on MES removes an unaffected active queue of the same process while leaving q->properties.is_active and dqm->active_queue_count set.

[1] https://sashiko.dev/#/bug/linux-39086475-ed69-4a54-b2b8-be02a185935b

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

PATCH 4/9 drm/amdkfd: add a quarantine for queues MES has not retired

In reply to Armas Spann

A queue that is destroyed while MES may still reference it has to keep its MQD, gang context, write pointer mapping, user buffers and its doorbell and SDMA ids. On gfx12 the MQD comes from a first fit sub-allocator and the doorbell id from a first fit bitmap, so both are normally handed to the very next queue the process creates.

Add the machinery to park such a queue: a per-device list of zombies and a delayed work that frees a zombie once kfd_mes_queue_retired() is true for it. The usual way out is the MES restart done by the GPU reset that the failed command asked for. start_cpsch() kicks the reaper for that case.

If the removal was skipped and did not fail (scheduler halted or stopped, GPU reset in progress), the reaper sends it once that becomes possible.

A zombie uses the pdd, the process context, the doorbell page and the GPU VM of its process, so it takes a hold on the process. The release worker frees those only when the last hold is gone. It must not block for that, because kfd_create_process() flushes the release workqueue and every new KFD process would hang behind it. The worker removes the debugfs and sysfs entries and the context id, which is what a new process with the same pid needs gone, and returns. The reaper queues the work again when it frees the last zombie of the process. As a side effect the eviction fence of every exiting process is now signalled after those entries are removed, no longer before.

Device removal must not wait for MES. kgd2kfd_teardown_processes() declares every queue of the device retired.

Nothing is quarantined yet. The next patch converts the paths that free queue storage.

---
 drivers/gpu/drm/amd/amdkfd/kfd_device.c       |   9 +
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 157 ++++++++++++++++++
 .../drm/amd/amdkfd/kfd_device_queue_manager.h |  14 ++
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  29 ++++
 drivers/gpu/drm/amd/amdkfd/kfd_process.c      |  51 +++++-
 drivers/gpu/drm/amd/amdkfd/kfd_queue.c        |  30 ++++
 6 files changed, 281 insertions(+), 9 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device.c +9 -0
index edafbd937..8080fbe3f 100644
@@ -1824,6 +1824,15 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)
 	if (!adev->kfd.dev)
 		return;
 
+	/*
+	 * Queues that MES never confirmed as removed keep their process
+	 * alive. The device is going away, so stop waiting for MES.
+	 */
+	if (adev->kfd.dev->init_complete) {
+		for (unsigned int i = 0; i < adev->kfd.dev->num_nodes; i++)
+			kfd_dqm_retire_all(adev->kfd.dev->nodes[i]->dqm);
+	}
+
 	/*
 	 * Wait for all KFD processes using adev to terminate. Must be
 	 * unbounded: device state is freed once they are gone.
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +157 -0

193 lines not on this page · raw message

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.h +14 -0
index 239168838..a2defcb99 100644
@@ -44,6 +44,9 @@
 #define KFD_MES_REMOVE_GRACE_MS		4000
 #define KFD_MES_REMOVE_POLL_US		2000
 
+/* How often the reaper looks at quarantined queues */
+#define KFD_MES_ZOMBIE_POLL_MS		500
+
 struct device_process_node {
 	struct qcm_process_device *qpd;
 	struct list_head list;
@@ -309,6 +312,15 @@ struct device_queue_manager {
 	u32			mes_fence_gen;
 	/* copy of the unanswered ticket, never released through this copy */
 	struct amdgpu_mes_cmd_ticket mes_fence_ticket;
+
+	/*
+	 * Destroyed queues that MES has not confirmed as removed, and the
+	 * reaper that frees them. The list is protected by the dqm lock.
+	 */
+	struct list_head	zombie_queues;
+	struct delayed_work	zombie_work;
+	/* the device is going away, treat every queue as retired */
+	bool			mes_retire_all;
 };
 
 void device_queue_manager_init_cik(
@@ -356,6 +368,8 @@ bool kfd_dqm_is_queue_in_process(struct device_queue_manager *dqm,
 void kfd_dqm_set_queues_as_reset(struct device_queue_manager *dqm);
 int kfd_reset_queue_mes(struct device_queue_manager *dqm, int queue_type,
 			int pipe, int queue, unsigned int db);
+void kfd_dqm_zombie_ready(struct device_queue_manager *dqm, struct queue *q);
+void kfd_dqm_retire_all(struct device_queue_manager *dqm);
 size_t mqd_size_from_queue_type(struct device_queue_manager *dqm,
 				enum kfd_queue_type type);
 
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +29 -0
index b5eae33d8..13e9e3ed8 100644
@@ -658,6 +658,21 @@ struct queue {
 	/* REMOVE_QUEUE that MES has not answered yet */
 	struct amdgpu_mes_cmd_ticket mes_ticket;
 
+	/*
+	 * Quarantine. A queue that is destroyed while MES may still use it
+	 * keeps all of its storage and waits on dqm->zombie_queues.
+	 */
+	struct list_head zombie_node;	/* dqm lock */
+	struct kfd_process_device *zombie_pdd;
+	/* written once under the dqm lock, stable afterwards */
+	bool is_zombie;
+	/* the pqm is done with the queue, the reaper may free it. dqm lock */
+	bool zombie_ready;
+	/* a failed create: the ioctl has dropped the user buffer references */
+	bool zombie_no_user_bos;
+	/* the dqm took the queue off its lists, the pqm has to finish */
+	bool dqm_dequeued;
+
 	/* The VRAM-resident MQD BO (mqd_on_vram()) is unpinned at S4 suspend so
 	 * TTM evicts it into the hibernation image, and repinned on resume. Set
 	 * while the BO is unpinned so the resume path knows to repin it.
@@ -963,6 +978,17 @@ struct kfd_process {
 	struct kref ref;
 	struct work_struct release_work;
 
+	/*
+	 * Holds on the storage of the process: one for the process itself,
+	 * one for each of its queues on a dqm->zombie_queues list. A zombie
+	 * uses the pdd, the process context, the doorbell page and the GPU
+	 * VM, so the release worker frees those only when the last hold is
+	 * gone.
+	 */
+	atomic_t mes_hold;
+	/* the release worker has dropped the hold of the process itself */
+	bool mes_hold_dropped;
+
 	struct mutex mutex;
 
 	/*
@@ -1412,6 +1438,8 @@ int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_prope
 void kfd_queue_unref_bo_va(struct amdgpu_vm *vm, struct amdgpu_bo **bo);
 int kfd_queue_unref_bo_vas(struct kfd_process_device *pdd,
 			   struct queue_properties *properties);
+void kfd_queue_ref_bo_vas(struct kfd_process_device *pdd,
+			  struct queue_properties *properties);
 void kfd_queue_ctx_save_restore_size(struct kfd_topology_device *dev);
 int kfd_queue_buffer_svm_get(struct kfd_process_device *pdd, u64 addr, u64 size);
 
@@ -1446,6 +1474,7 @@ struct process_queue_node {
 
 void kfd_process_dequeue_from_device(struct kfd_process_device *pdd);
 void kfd_process_dequeue_from_all_devices(struct kfd_process *p);
+void kfd_process_put_mes_hold(struct kfd_process *p);
 int pqm_init(struct process_queue_manager *pqm, struct kfd_process *p);
 void pqm_uninit(struct process_queue_manager *pqm);
 int pqm_create_queue(struct process_queue_manager *pqm,
drivers/gpu/drm/amd/amdkfd/kfd_process.c +42 -9

80 lines not on this page · raw message

drivers/gpu/drm/amd/amdkfd/kfd_queue.c +30 -0
index cd41b10e0..ad01308a7 100644
@@ -423,6 +423,36 @@ int kfd_queue_unref_bo_vas(struct kfd_process_device *pdd,
 	return 0;
 }
 
+static void kfd_queue_ref_bo_va(struct amdgpu_vm *vm, struct amdgpu_bo *bo)
+{
+	struct amdgpu_bo_va *bo_va;
+
+	if (!bo)
+		return;
+
+	bo_va = amdgpu_vm_bo_find(vm, bo);
+	if (bo_va)
+		bo_va->queue_refcount++;
+}
+
+/* Take back the unmap protection dropped by kfd_queue_unref_bo_vas(). */
+void kfd_queue_ref_bo_vas(struct kfd_process_device *pdd,
+			  struct queue_properties *properties)
+{
+	struct amdgpu_vm *vm = drm_priv_to_vm(pdd->drm_priv);
+
+	if (amdgpu_bo_reserve(vm->root.bo, true))
+		return;
+
+	kfd_queue_ref_bo_va(vm, properties->wptr_bo);
+	kfd_queue_ref_bo_va(vm, properties->rptr_bo);
+	kfd_queue_ref_bo_va(vm, properties->ring_bo);
+	kfd_queue_ref_bo_va(vm, properties->eop_buf_bo);
+	kfd_queue_ref_bo_va(vm, properties->cwsr_bo);
+
+	amdgpu_bo_unreserve(vm->root.bo);
+}
+
 #define DEBUGGER_BYTES_ALIGN	64
 #define DEBUGGER_BYTES_PER_WAVE	32
 
Signature · 1 line
2.56.1
#8 lore raw

Re: [PATCH v1 4/9] drm/amdkfd: add a quarantine for queues MES has not retired

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] drm/amdkfd: kgd2kfd_teardown_processes() misses exited processes with zombies - [High] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] drm/amdkfd: kgd2kfd_teardown_processes() misses exited processes with zombies
- [High] drm/amdkfd: broken zombie queue handling in reset_queue_mes()
- [High] drm/amdkfd: unlocked zombie_queues traversal in find_queue_by_doorbell_offset()
- [High] drm/amdkfd: kfd_process_wq_release() early return leaves svms.restore_work active
It also noticed 2 related pre-existing issues this patch does not introduce:
- [Critical] drm/amdkfd: invalid free of context ID 0 on alloc failure in create_process() [1]
- [High] drm/amdkfd: queue_refcount leak in kfd_queue_buffer_get() [2] --

commit b3a1e7e946a15fc197590f432e1ffb64a5706fc6
Author: Armas Spann <[email protected]>

drm/amdkfd: add a quarantine for queues MES has not retired

This commit adds per-device quarantine lists, a delayed reaper work item, and process storage holds to retain queue and process resources until MES confirms queue retirement or is restarted.

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +2 -0
index edafbd9377b5d..8080fbe3f7a17 100644
@@ -1824,6 +1824,15 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)
 	if (!adev->kfd.dev)
 		return;
 
+	/*
+	 * Queues that MES never confirmed as removed keep their process

drivers/gpu/drm/amd/amdkfd/kfd_device.c void kgd2kfd_teardown_processes(struct amdgpu_device *adev) · line 1838

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +7 -0
+	 * alive. The device is going away, so stop waiting for MES.
+	 */
+	if (adev->kfd.dev->init_complete) {
+		for (unsigned int i = 0; i < adev->kfd.dev->num_nodes; i++)
+			kfd_dqm_retire_all(adev->kfd.dev->nodes[i]->dqm);
+	}
+
 	/*
 	 * Wait for all KFD processes using adev to terminate. Must be
 	 * unbounded: device state is freed once they are gone.

[Severity: High]
Can kgd2kfd_teardown_processes() skip kfd_dqm_retire_all() and the kfd_processes_count wait when every KFD process has already exited user space but still has quarantined queues?

When a process exits, kfd_process_notifier_release_internal() removes it from kfd_processes_table before queue teardown, while its quarantined queues hold p->mes_hold and defer kfd_process_destroy_pdds() (keeping kfd_processes_count > 0). If no other live KFD processes remain when the device is removed, kgd2kfd_teardown_processes() returns early at if (hash_empty(kfd_processes_table)), so device_queue_manager_uninit() cancels dqm->zombie_work, hits WARN_ON(!list_empty(&dqm->zombie_queues)), and frees the device structures while the zombies and deferred kfd_process still reference them.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index 684037d333bf1..2f57cb06f540f 100644

[ ... ]

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static struct queue *find_queue_by_doorbell_offset(struct device_queue_manager * · line 3069

Quoted 12 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +6 -0
@@ -2913,6 +3059,12 @@ static struct queue *find_queue_by_doorbell_offset(struct device_queue_manager *
 		}
 	}
 
+	/* MES may report a quarantined queue as hung, it still has it */
+	list_for_each_entry(q, &dqm->zombie_queues, zombie_node) {
+		if (doorbell_offset == q->properties.doorbell_off)
+			return q;
+	}
+
 	return NULL;
 }

[Severity: High]
Does returning a quarantined queue to kfd_reset_queue_mes() -> reset_queue_mes() corrupt queue state and wedge the reaper?

In reset_queue_mes(), remove_queue_mes_on_reset_option() is called with its return value ignored, followed unconditionally by set_queue_as_reset():

1. If remove_queue_mes_on_reset_option() skips or fails removal (where is_for_reset == true returns early without calling kfd_hws_hang()), set_queue_as_reset() sets q->properties.is_reset = true while q->mes_state is still MAPPED or UNKNOWN. Every subsequent run of kfd_dqm_zombie_worker() calls remove_queue_mes(), which returns 0 early on q->properties.is_reset without retiring the queue, polling every 500 ms indefinitely and leaking the queue and process holds.
2. When a queue is quarantined from create_queue_cpsch() or process_termination_cpsch(), decrement_queue_count() has already run without clearing q->properties.is_active = false. set_queue_as_reset() sees q->properties.is_active == true and calls decrement_queue_count() a second time, underflowing dqm->active_queue_count.
3. set_queue_as_reset() sets pdd->has_reset_queue = true for a queue user space already destroyed (or that failed creation), causing later update_queue() calls on the process's remaining live queues to fail with -EACCES.

[Severity: High]
Can find_queue_by_doorbell_offset() walk dqm->zombie_queues without dqm_lock(dqm) held and race with kfd_dqm_zombie_worker() freeing the queue?

When KGD resets hung compute queues from gfx_v11_0_reset_kcq(), gfx_v12_0_reset_kcq(), or amdgpu_userq_hang_detect_work(), amdgpu_gfx_reset_mes_compute() holds only adev->gfx.mec.reset_mutex and does not acquire dqm_lock(dqm):

CPU0 (KGD reset) CPU1 (kworker)
amdgpu_gfx_reset_mes_compute() kfd_dqm_zombie_worker()
... dqm_lock(dqm)
kfd_reset_queue_mes() list_move_tail(&q->zombie_node,
find_queue_by_doorbell_offset() &retired)
/* walks dqm->zombie_queues dqm_unlock(dqm)
* without dqm_lock */ kfd_dqm_release_zombie(dqm, q)
uninit_queue(q)
reset_queue_mes(dqm, q, ...) kfree(q)
/* dereferences q */ <-- use-after-free

[ ... ]

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +0 -0
index 546721b4d59ac..3aa6ddf49ad49 100644

[ ... ]

Quoted 23 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +19 -0
@@ -1359,6 +1354,32 @@ static void kfd_process_wq_release(struct work_struct *work)
 	 */
 	kfd_process_remove_sysfs(p);
 
+	/*
+	 * Queues that MES has not let go of still use the pdds, the process
+	 * context, the doorbell page and the GPU VM. Everything that carries
+	 * the pid is gone at this point, so stop here. The reaper queues
+	 * this work again when it frees the last of those queues. Do not
+	 * wait instead: kfd_create_process() flushes this workqueue. A work
+	 * item never runs twice at the same time, so the second run cannot
+	 * free the process under us.
+	 */
+	p->mes_hold_dropped = true;
+	if (!atomic_dec_and_test(&p->mes_hold)) {
+		pr_warn("Process pid %d: release waits for MES to retire %d queue(s), a GPU reset retires them\n",
+			p->lead_thread->pid, atomic_read(&p->mes_hold));
+		return;
+	}
+
+release_storage:
+	/* Signal the eviction fence after user mode queues are
+	 * destroyed. This allows any BOs to be freed without

drivers/gpu/drm/amd/amdkfd/kfd_process.c static void kfd_process_wq_release(struct work_struct *work) · line 1385

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +7 -0
+	 * triggering pointless evictions or waiting for fences.
+	 */
+	synchronize_rcu();
+	ef = rcu_access_pointer(p->ef);
+	if (ef)
+		dma_fence_signal(ef);
+
 	kfd_process_kunmap_signal_bo(p);
 	kfd_process_free_outstanding_kfd_bos(p);
 	svm_range_list_fini(p);

[Severity: High]
Does returning early before svm_range_list_fini(p) leave p->svms.restore_work running against the wrong mm_struct across execve()?

kfd_process_notifier_release_internal() cancels p->eviction_work, p->restore_work, and p->signal_work when the old mm is torn down, but p->svms.restore_work is only cancelled in svm_range_list_fini(). If the process tore down its old mm via execve() and has a quarantined queue, p->lead_thread stays alive with a new mm while kfd_process_wq_release() returns early here. When svm_range_restore_work() runs during the quarantine window, get_task_mm(p->lead_thread) returns the post-execve() new_mm, locks new_mm->mmap_lock, and passes prange->notifier (whose notifier.mm still points to the destroyed old_mm) to amdgpu_hmm_range_get_pages() -> hmm_range_fault(), triggering mmap_assert_locked(old_mm) and walking the freed old_mm page tables.

[ ... ]

drivers/gpu/drm/amd/amdkfd/kfd_process.c struct kfd_process *create_process(const struct task_struct *thread, bool primar · line 1740

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +1 -0
@@ -1702,6 +1734,7 @@ struct kfd_process *create_process(const struct task_struct *thread, bool primar
 		goto err_alloc_process;
 
 	kref_init(&process->ref);
+	atomic_set(&process->mes_hold, 1);
 	mutex_init(&process->mutex);
 	process->mm = thread->mm;
 	process->lead_thread = thread->group_leader;

[Severity: Critical]
This problem wasn't introduced by this patch, but in create_process() [1], can a kfd_process_alloc_id() failure free context ID 0 while another secondary process is using it?

process is zero-initialized, so process->context_id starts at 0 (KFD_CONTEXT_ID_MIN). If kfd_process_alloc_id() fails for a secondary process, it leaves process->context_id at 0 and jumps to err_alloc_id, which calls kfd_process_free_id(process) -> ida_free(..., 0) on primary_process->id_table, releasing an active secondary process's context ID and allowing duplicate context ID assignment.

Quoted 9 lines
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +1 -0
index cd41b10e08731..ad01308a7d812 100644
@@ -423,6 +423,36 @@ int kfd_queue_unref_bo_vas(struct kfd_process_device *pdd,
 	return 0;
 }
 
+static void kfd_queue_ref_bo_va(struct amdgpu_vm *vm, struct amdgpu_bo *bo)

drivers/gpu/drm/amd/amdkfd/kfd_queue.c int kfd_queue_unref_bo_vas(struct kfd_process_device *pdd, · line 436

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +10 -0
+{
+	struct amdgpu_bo_va *bo_va;
+
+	if (!bo)
+		return;
+
+	bo_va = amdgpu_vm_bo_find(vm, bo);
+	if (bo_va)
+		bo_va->queue_refcount++;
+}

[Severity: High]
This problem wasn't introduced by this patch, but does kfd_queue_buffer_get() leak bo_va->queue_refcount [2] when a mapping's underlying BO is NULL (such as a PRT mapping)?

In kfd_queue_buffer_get(), *pbo is set to amdgpu_bo_ref(mapping->bo_va->base.bo) (which is NULL when base.bo is NULL), while mapping->bo_va->queue_refcount is still incremented. Because kfd_queue_unref_bo_va() (and kfd_queue_ref_bo_va() here) checks for a non-NULL bo before looking up bo_va, queue_refcount is never decremented on teardown, leaving the mapping permanently non-zero and blocking unmap with -EBUSY.

[1] https://sashiko.dev/#/bug/linux-73836404-f2c8-4863-97fc-8a10e19441a4
[2] https://sashiko.dev/#/bug/linux-7d2cfadd-e9fb-4657-8f39-fe57b15f1bfe

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

PATCH 5/9 drm/amdkfd: keep queue storage until MES confirmed retirement

In reply to Armas Spann

KFD frees and reuses the storage of a queue without requiring that MES confirmed the removal of the queue:

- destroy_queue_cpsch() gives the doorbell id back before REMOVE_QUEUE is sent, and frees the MQD whatever the command returned.
- pqm_destroy_queue() goes on to free the gang context, the write pointer mapping and the user buffer references on -ETIME and -EIO. On any other error it bails out and keeps the pqm node of a queue that the dqm has already unlinked and whose MQD is freed. A second destroy of that queue id corrupts the list and frees the MQD twice.
- The error path of queue creation frees the MQD and the ids when ADD_QUEUE failed, although a command that timed out can still be executed.
- process_termination_cpsch() logs REMOVE_QUEUE failures and frees everything.

A REMOVE_QUEUE that completes late writes the queue state back into an MQD that has been given to, and zeroed for, the next queue.

Make all four paths ask kfd_mes_queue_retired() and hand the queue to the quarantine when the answer is no. Ids are released after the unmap and no longer before it. The pqm completes a destroy whenever the dqm has unlinked the queue, and takes the buffer references back when it has not.

User space sees no difference. A destroy still removes the queue id and returns what it returned before.

Two defects on the same paths are fixed along the way. Process termination clears is_active when it deactivates a queue, so a per-queue reset during termination does not decrement the active count a second time. The gang context and write pointer mapping of a queue whose creation failed are freed. They were leaked.

On devices without MES kfd_mes_queue_retired() is always true. What changes there is that ids are released after the unmap, and that a destroy which failed after the queue was unlinked is completed.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 93 ++++++++++++++-----
 .../amd/amdkfd/kfd_process_queue_manager.c    | 77 +++++++++++----
 2 files changed, 127 insertions(+), 43 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +69 -24
index 842a3249e..e85bead1b 100644
@@ -1255,6 +1255,7 @@ static int destroy_queue_nocpsch_locked(struct device_queue_manager *dqm,
 		qpd->reset_wavefronts = true;
 
 	list_del(&q->list);
+	q->dqm_dequeued = true;
 	if (list_empty(&qpd->queues_list)) {
 		if (qpd->reset_wavefronts) {
 			pr_warn("Resetting wave fronts (nocpsch) on dev %p\n",
@@ -1691,9 +1692,9 @@ static int dqm_repin_mqd_bo(struct device_queue_manager *dqm, struct queue *q)
  */
 
 /* dqm lock held. @q is off qpd->queues_list already. */
-static void __maybe_unused dqm_quarantine_queue(struct device_queue_manager *dqm,
-						struct qcm_process_device *qpd,
-						struct queue *q)
+static void dqm_quarantine_queue(struct device_queue_manager *dqm,
+				 struct qcm_process_device *qpd,
+				 struct queue *q)
 {
 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
 
@@ -2880,6 +2881,16 @@ static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
 	list_del(&q->list);
 	if (q->properties.is_active)
 		decrement_queue_count(dqm, qpd, q);
+	if (!kfd_mes_queue_retired(dqm, q)) {
+		/*
+		 * ADD_QUEUE was not confirmed, MES may still map the queue.
+		 * The MQD and the doorbell and SDMA ids stay with it.
+		 */
+		q->zombie_no_user_bos = true;
+		dqm_quarantine_queue(dqm, qpd, q);
+		dqm_unlock(dqm);
+		return retval;
+	}
 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
 	dqm_unlock(dqm);
 out_deallocate_doorbell:
@@ -3391,6 +3402,7 @@ static int destroy_queue_cpsch(struct device_queue_manager *dqm,
 	uint64_t sdma_val = 0;
 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
 	struct device *dev = dqm->dev->adev->dev;
+	bool retired;
 
 	/* Get the SDMA queue stats */
 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
@@ -3433,13 +3445,9 @@ static int destroy_queue_cpsch(struct device_queue_manager *dqm,
 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
 			q->properties.type)];
 
-	deallocate_doorbell(qpd, q);
-
 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
-	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
-		deallocate_sdma_queue(dqm, q);
+	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI))
 		pdd->sdma_past_activity_counter += sdma_val;
-	}
 
 	if (q->properties.is_active) {
 		decrement_queue_count(dqm, qpd, q);
@@ -3450,11 +3458,18 @@ static int destroy_queue_cpsch(struct device_queue_manager *dqm,
 						      USE_DEFAULT_GRACE_PERIOD);
 			if (retval == -ETIME)
 				qpd->reset_wavefronts = true;
-		} else {
-			retval = remove_queue_mes(dqm, q, qpd);
 		}
 	}
+
+	/*
+	 * Not only for active queues: an evicted queue can be inactive with
+	 * a REMOVE_QUEUE that MES never confirmed.
+	 */
+	if (!kfd_mes_queue_retired(dqm, q))
+		retval = remove_queue_mes(dqm, q, qpd);
+
 	list_del(&q->list);
+	q->dqm_dequeued = true;
 	qpd->queue_count--;
 
 	/*
@@ -3465,6 +3480,21 @@ static int destroy_queue_cpsch(struct device_queue_manager *dqm,
 	pr_debug("Total of %d queues are accountable so far\n",
 			dqm->total_queue_count);
 
+	/*
+	 * MES identifies the queue by its doorbell. The doorbell and SDMA
+	 * ids can be handed out again only when MES has forgotten the queue.
+	 * Until then the queue keeps them, together with its MQD.
+	 */
+	retired = kfd_mes_queue_retired(dqm, q);
+	if (retired) {
+		deallocate_doorbell(qpd, q);
+		if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
+		    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
+			deallocate_sdma_queue(dqm, q);
+	} else {
+		dqm_quarantine_queue(dqm, qpd, q);
+	}
+
 	dqm_unlock(dqm);
 
 	/*
@@ -3475,9 +3505,11 @@ static int destroy_queue_cpsch(struct device_queue_manager *dqm,
 				qpd->pqm->process, q->device,
 				-1, false, NULL, 0);
 
-	/* Repin the MQD BO if still evicted for hibernation, before it is freed. */
-	dqm_repin_mqd_bo(dqm, q);
-	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
+	if (retired) {
+		/* Repin the MQD BO if still evicted for hibernation, before it is freed. */
+		dqm_repin_mqd_bo(dqm, q);
+		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
+	}
 
 	return retval;
 
@@ -3683,20 +3715,18 @@ static int process_termination_cpsch(struct device_queue_manager *dqm,
 
 	/* Clear all user mode queues */
 	list_for_each_entry(q, &qpd->queues_list, list) {
-		if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
-			deallocate_sdma_queue(dqm, q);
-		else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
-			deallocate_sdma_queue(dqm, q);
-
 		if (q->properties.is_active) {
 			decrement_queue_count(dqm, qpd, q);
+			/* set_queue_as_reset() must not count it down again */
+			q->properties.is_active = false;
+		}
 
-			if (dqm->dev->kfd->shared_resources.enable_mes) {
-				retval = remove_queue_mes(dqm, q, qpd);
-				if (retval)
-					dev_err(dev, "Failed to remove queue %d\n",
-						q->properties.queue_id);
-			}
+		/* Inactive queues can have an unconfirmed REMOVE_QUEUE too */
+		if (!kfd_mes_queue_retired(dqm, q)) {
+			retval = remove_queue_mes(dqm, q, qpd);
+			if (retval)
+				dev_err(dev, "Failed to remove queue %d\n",
+					q->properties.queue_id);
 		}
 
 		dqm->total_queue_count--;
@@ -3732,7 +3762,22 @@ static int process_termination_cpsch(struct device_queue_manager *dqm,
 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
 				q->properties.type)];
 		list_del(&q->list);
+		q->dqm_dequeued = true;
 		qpd->queue_count--;
+
+		/*
+		 * Decide once whether MES has let go. A late completion can
+		 * change the answer at any time, and the SDMA id has to
+		 * follow the same decision as the MQD.
+		 */
+		if (!kfd_mes_queue_retired(dqm, q)) {
+			dqm_quarantine_queue(dqm, qpd, q);
+			continue;
+		}
+		if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
+		    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
+			deallocate_sdma_queue(dqm, q);
+
 		dqm_unlock(dqm);
 		/* Repin the MQD BO if still evicted for hibernation, before free. */
 		dqm_repin_mqd_bo(dqm, q);
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +58 -19

107 lines not on this page · raw message

Signature · 1 line
2.56.1
#10 lore raw

Re: [PATCH v1 5/9] drm/amdkfd: keep queue storage until MES confirmed retirement

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] drm/amdkfd: active queue count underflow on reset of quarantined queue - [Medium] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] drm/amdkfd: active queue count underflow on reset of quarantined queue
- [Medium] drm/amdkfd: bo_va->queue_refcount race and imbalance in pqm_destroy_queue()
- [Medium] drm/amdkfd: premature release of user queue buffers when create_queue_cpsch() quarantines queue
It also noticed 1 related pre-existing issue this patch does not introduce:
- [High] drm/amdkfd: broken queue state and count in kfd_dqm_suspend_bad_queue_mes() [1]
--

commit 848d4620ce3c40efb53d488158a7d0f3fddf5733
Author: Armas Spann <[email protected]>

drm/amdkfd: keep queue storage until MES confirmed retirement

This commit quarantines queues whose retirement has not been confirmed by MES across queue creation failure, queue destruction, and process termination so their MQDs, doorbell IDs, SDMA IDs, and buffers are not reused while MES may still access them.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index 2f57cb06f540f..0d40053b34c88 100644

[ ... ]

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q, · line 2886

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +6 -0
@@ -2877,6 +2878,16 @@ static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
 	list_del(&q->list);
 	if (q->properties.is_active)
 		decrement_queue_count(dqm, qpd, q);
+	if (!kfd_mes_queue_retired(dqm, q)) {
+		/*
+		 * ADD_QUEUE was not confirmed, MES may still map the queue.
+		 * The MQD and the doorbell and SDMA ids stay with it.
+		 */
+		q->zombie_no_user_bos = true;

[Severity: Medium]
Does setting q->zombie_no_user_bos here allow the user queue buffers to be unmapped and freed while MES may still map the queue?

When pqm_create_queue() returns an error to kfd_ioctl_create_queue(), the ioctl error path calls kfd_queue_unref_bo_vas() and kfd_queue_release_buffers(), dropping the BO VA queue refcounts, the BO references, and the CWSR SVM range reference immediately. Because queue creation failed, userspace can unmap and reuse wptr_bo, rptr_bo, ring_bo, eop_buf_bo, and cwsr_bo while the MQD submitted to MES and the pinned wptr_bo_gart mapping still point to them. If the timed-out ADD_QUEUE executes late, MES, CP, or SDMA can read or write unmapped or reallocated user memory.

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q, · line 2893

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +4 -0
+		dqm_quarantine_queue(dqm, qpd, q);
+		dqm_unlock(dqm);
+		return retval;
+	}

[Severity: Medium]
Should this path also clear q->properties.is_active after calling decrement_queue_count(), the same way destroy_queue_cpsch() and process_termination_cpsch() do?

If MES later reports the quarantined queue as hung during a per-queue reset, kfd_reset_queue_mes() finds it on dqm->zombie_queues via find_queue_by_doorbell_offset() and calls reset_queue_mes() -> set_queue_as_reset():

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:set_queue_as_reset() {
    ...
	if (q->properties.is_active) {
		q->properties.is_active = false;
		decrement_queue_count(dqm, qpd, q);
	}
}

Because q->properties.is_active was left true, set_queue_as_reset() calls decrement_queue_count() a second time and underflows the DQM active queue counters.

[ ... ]

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
@@ -3680,20 +3712,18 @@ static int process_termination_cpsch(struct device_queue_manager *dqm,
 
 	/* Clear all user mode queues */
 	list_for_each_entry(q, &qpd->queues_list, list) {

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int process_termination_cpsch(struct device_queue_manager *dqm, · line 3719

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +3 -5
-		if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
-			deallocate_sdma_queue(dqm, q);
-		else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
-			deallocate_sdma_queue(dqm, q);
-
 		if (q->properties.is_active) {
 			decrement_queue_count(dqm, qpd, q);
+			/* set_queue_as_reset() must not count it down again */
+			q->properties.is_active = false;
+		}

[Severity: High]
This problem wasn't introduced by this patch, but kfd_dqm_suspend_bad_queue_mes() has the same double decrement and leaves the queue marked inactive on reset failure [1]:

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:kfd_dqm_suspend_bad_queue_mes() {
    ...
		list_for_each_entry(q, &qpd->queues_list, list) {
			if (q->doorbell_id == doorbell_id && q->properties.is_active) {
				reset_queues_mes(dqm, q);
				q->properties.is_evicted = true;
				q->properties.is_active = false;
				decrement_queue_count(dqm, qpd, q);
				break;
			}
		}
    ...
}

When reset_queues_mes() resets the queue as hung via reset_queue_mes() -> set_queue_as_reset(), set_queue_as_reset() already clears q->properties.is_active and calls decrement_queue_count(), so the unconditional decrement_queue_count() afterwards underflows dqm->active_queue_count. If reset_queues_mes() fails instead, clearing q->properties.is_active causes later paths to treat a still-mapped queue as inactive.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +0 -0
index ef9ad6dc874dc..29827a736f7d4 100644

[ ... ]

Quoted 17 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +5 -3
@@ -571,23 +590,43 @@ int pqm_destroy_queue(struct process_queue_manager *pqm, unsigned int qid)
 	}
 
 	if (pqn->q) {
-		retval = kfd_queue_unref_bo_vas(pdd, &pqn->q->properties);
+		struct queue *q = pqn->q;
+
+		retval = kfd_queue_unref_bo_vas(pdd, &q->properties);
 		if (retval)
 			goto err_destroy_queue;
 
-		dqm = pqn->q->device->dqm;
-		retval = dqm->ops.destroy_queue(dqm, &pdd->qpd, pqn->q);
+		dqm = q->device->dqm;
+		retval = dqm->ops.destroy_queue(dqm, &pdd->qpd, q);
 		if (retval) {
 			pr_err("Pasid 0x%x destroy queue %d failed, ret %d\n",

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c int pqm_destroy_queue(struct process_queue_manager *pqm, unsigned int qid) · line 610

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +6 -2
 				pdd->pasid,
-				pqn->q->properties.queue_id, retval);
-			if (retval != -ETIME && retval != -EIO)
+				q->properties.queue_id, retval);
+			/* The dqm left the queue alone, it stays usable */
+			if (!q->dqm_dequeued) {
+				kfd_queue_ref_bo_vas(pdd, &q->properties);
 				goto err_destroy_queue;
+			}
+		}

[Severity: Medium]
Can calling kfd_queue_unref_bo_vas() before dqm->ops.destroy_queue() race when wait_on_destroy_queue() drops q->process->mutex for a suspended queue of a debugged process?

CPU0 CPU1
pqm_destroy_queue(qid)
kfd_queue_unref_bo_vas()

    bo_va->queue_refcount-- (1 -> 0)
  destroy_queue_cpsch()
    wait_on_destroy_queue()
      q->properties.is_being_destroyed = true
      dqm_unlock(dqm)
      mutex_unlock(&q->process->mutex)
      wait_event_interruptible(...)
                                      pqm_destroy_queue(qid)
                                        kfd_queue_unref_bo_vas()
                                          /* refcount is 0, no-op */
                                        destroy_queue_cpsch()
                                          wait_on_destroy_queue()
                                            returns -EBUSY
                                        /* !q->dqm_dequeued */
                                        kfd_queue_ref_bo_vas()
                                          bo_va->queue_refcount++ (0 -> 1)
      /* interrupted by signal */
      returns -ERESTARTSYS
  /* !q->dqm_dequeued */
  kfd_queue_ref_bo_vas()
    bo_va->queue_refcount++ (1 -> 2)  <-- refcount leaked

Because kfd_queue_unref_bo_va() only decrements when bo_va->queue_refcount is non-zero while kfd_queue_ref_bo_va() increments unconditionally, a second destroy attempt during the wait_on_destroy_queue() sleep window permanently inflates bo_va->queue_refcount and prevents the BOs from being unmapped. While CPU0 is sleeping with bo_va->queue_refcount == 0, another thread can also unmap the queue's BOs via unmap_bo_from_gpuvm() before the queue is destroyed.

[1] https://sashiko.dev/#/bug/linux-7affa616-c8be-4685-80a8-eb0c3ae7d034

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

PATCH 6/9 drm/amdkfd: keep eviction and restore consistent when MES fails

In reply to Armas Spann

evict_process_queues_cpsch() returns at the first REMOVE_QUEUE that fails. The remaining queues are neither removed nor marked inactive and the TLB flush is skipped, while qpd->evicted is already raised. During a GPU reset every REMOVE_QUEUE fails with -EIO, so all queues but the first stay marked active across the reset.

restore_process_queues_cpsch() marks a queue active and counts it before ADD_QUEUE is sent. When a later queue fails, qpd->evicted stays set, and the retry counts the queues that were restored already and adds them again.

Evict every queue and report MES failures as -EIO, which kfd_process_evict_queues() already takes to mean "evicted, do not add back". Mark a queue active only after MES accepted it, and skip the ones an earlier attempt restored.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 34 +++++++++++++++----
 1 file changed, 27 insertions(+), 7 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +27 -7
index e85bead1b..feb3062e6 100644
@@ -1900,11 +1900,24 @@ static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
 		decrement_queue_count(dqm, qpd, q);
 
 		if (dqm->dev->kfd->shared_resources.enable_mes) {
-			retval = remove_queue_mes(dqm, q, qpd);
-			if (retval) {
-				dev_err(dev, "Failed to evict queue %d\n",
-					q->properties.queue_id);
-				goto out;
+			int r = remove_queue_mes(dqm, q, qpd);
+
+			if (r) {
+				/*
+				 * -EIO means a GPU reset is under way or MES
+				 * is fenced off, both reported already.
+				 */
+				if (r != -EIO)
+					dev_err(dev, "Failed to evict queue %d\n",
+						q->properties.queue_id);
+				/*
+				 * Keep going so that every queue ends up in
+				 * the evicted state. The caller treats -EIO
+				 * as evicted, not to be added back. MES may
+				 * still use this MQD, so it stays pinned.
+				 */
+				retval = -EIO;
+				continue;
 			}
 		}
 
@@ -2117,13 +2130,15 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 		if (!QUEUE_IS_ACTIVE(q->properties))
 			continue;
 
-		q->properties.is_active = true;
-		increment_queue_count(dqm, &pdd->qpd, q);
+		/* Restored by an earlier attempt that failed further down */
+		if (q->properties.is_active)
+			continue;
 
 		retval = dqm_repin_mqd_bo(dqm, q);
 		if (retval) {
 			dev_err(dev, "Failed to repin MQD for queue %d\n",
 				q->properties.queue_id);
+			q->properties.is_evicted = true;
 			goto out;
 		}
 
@@ -2132,9 +2147,14 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 			if (retval) {
 				dev_err(dev, "Failed to restore queue %d\n",
 					q->properties.queue_id);
+				q->properties.is_evicted = true;
 				goto out;
 			}
 		}
+
+		/* Count the queue as active only once MES has taken it */
+		q->properties.is_active = true;
+		increment_queue_count(dqm, &pdd->qpd, q);
 	}
 	if (!dqm->dev->kfd->shared_resources.enable_mes)
 		retval = execute_queues_cpsch(dqm,
Signature · 1 line
2.56.1
#12 lore raw

Re: [PATCH v1 6/9] drm/amdkfd: keep eviction and restore consistent when MES fails

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] drm/amdkfd: partial failure in restore_process_queues_cpsch() breaks eviction - [High] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] drm/amdkfd: partial failure in restore_process_queues_cpsch() breaks eviction
- [High] drm/amdkfd: kfd_process_evict_queues() overwrites -EIO across multiple PDDs
- [Medium] drm/amdkfd: restore_process_queues_cpsch() misses GFX11 oversubscription work
--

commit 96e422e9089ef50f901d8f75facedb9f1a4d5c7f
Author: Armas Spann <[email protected]>

drm/amdkfd: keep eviction and restore consistent when MES fails

This commit continues evicting remaining process queues when remove_queue_mes() fails and returns -EIO, and defers marking queues active in restore_process_queues_cpsch() until add_queue_mes() succeeds while skipping already-active queues on retry.

Quoted 23 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -5
index 0d40053b34c88..dbbc6c0794ed3 100644
@@ -1900,11 +1900,24 @@ static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
 		decrement_queue_count(dqm, qpd, q);
 
 		if (dqm->dev->kfd->shared_resources.enable_mes) {
-			retval = remove_queue_mes(dqm, q, qpd);
-			if (retval) {
-				dev_err(dev, "Failed to evict queue %d\n",
-					q->properties.queue_id);
-				goto out;
+			int r = remove_queue_mes(dqm, q, qpd);
+
+			if (r) {
+				/*
+				 * -EIO means a GPU reset is under way or MES
+				 * is fenced off, both reported already.
+				 */
+				if (r != -EIO)
+					dev_err(dev, "Failed to evict queue %d\n",
+						q->properties.queue_id);

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int evict_process_queues_cpsch(struct device_queue_manager *dqm, · line 1922

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +8 -0
+				/*
+				 * Keep going so that every queue ends up in
+				 * the evicted state. The caller treats -EIO
+				 * as evicted, not to be added back. MES may
+				 * still use this MQD, so it stays pinned.
+				 */
+				retval = -EIO;
+				continue;
 			}
 		}

[Severity: High]
Can kfd_process_evict_queues() lose this -EIO return value when a process spans multiple PDDs?

In kfd_process_evict_queues(), a single variable r is overwritten on each PDD iteration:

drivers/gpu/drm/amd/amdkfd/kfd_process.c:kfd_process_evict_queues() {
    ...
	for (i = 0; i < p->n_pdds; i++) {
		...
		r = pdd->dev->dqm->ops.evict_process_queues(pdd->dev->dqm,
							    &pdd->qpd);
		if (r && r != -EIO) {
			dev_err(dev, "Failed to evict process queues\n");
			goto fail;
		}
		n_evicted++;
	}

	return r;
}

When remove_queue_mes() fails on an earlier PDD and returns -EIO, the loop continues and a later PDD that succeeds overwrites r with 0. evict_process_worker() then sees a successful return, signals the eviction fence while the unremoved queue on the earlier PDD may still be active in MES, and schedules p->restore_work.

Quoted 23 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +5 -2
@@ -2114,13 +2127,15 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 		if (!QUEUE_IS_ACTIVE(q->properties))
 			continue;
 
-		q->properties.is_active = true;
-		increment_queue_count(dqm, &pdd->qpd, q);
+		/* Restored by an earlier attempt that failed further down */
+		if (q->properties.is_active)
+			continue;
 
 		retval = dqm_repin_mqd_bo(dqm, q);
 		if (retval) {
 			dev_err(dev, "Failed to repin MQD for queue %d\n",
 				q->properties.queue_id);
+			q->properties.is_evicted = true;
 			goto out;
 		}
 
@@ -2129,9 +2144,14 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 			if (retval) {
 				dev_err(dev, "Failed to restore queue %d\n",
 					q->properties.queue_id);
+				q->properties.is_evicted = true;

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int restore_process_queues_cpsch(struct device_queue_manager *dqm, · line 2157

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +4 -0
 				goto out;
 			}
 		}
+
+		/* Count the queue as active only once MES has taken it */
+		q->properties.is_active = true;
+		increment_queue_count(dqm, &pdd->qpd, q);
 	}
 	if (!dqm->dev->kfd->shared_resources.enable_mes)
 		retval = execute_queues_cpsch(dqm,

[Severity: High]
If dqm_repin_mqd_bo() or add_queue_mes() fails after earlier queues in qpd->queues_list have already been restored, does jumping to out with qpd->evicted still set to 1 prevent those active queues from being evicted?

The queues restored before the failure are now running in MES with is_active = true and is_evicted = false. Because qpd->evicted remains 1, a subsequent evict_process_queues_cpsch() hits "if (qpd->evicted++ > 0) goto out;" and returns 0 without removing the running queues from MES or flushing the TLB. With qpd->evicted now bumped to 2, the next restore_process_queues_cpsch() retry only decrements qpd->evicted back to 1 and exits without restoring the remaining queues.

[Severity: Medium]
Does moving increment_queue_count() after add_queue_mes() skip scheduling dqm->notify_unmap_work on GFX11 when the restored queue is the one that crosses the oversubscription threshold?

add_queue_mes() checks dqm->active_cp_queue_count > get_cp_queues_num(dqm) before returning. Because increment_queue_count() has not been called yet, the final restored compute queue that brings active_cp_queue_count to get_cp_queues_num(dqm) + 1 is not counted during that check, leaving dqm->notify_unmap_work unscheduled.

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

PATCH 7/9 drm/amdkfd: apply queue property updates only after unmap

In reply to Armas Spann

pqm_update_queue_properties() drops the references on the old ring buffer and overwrites the queue properties before update_queue() takes the queue off the hardware. If the unmap fails, the scheduler keeps running the old ring, which is no longer protected against being unmapped, while the driver describes the new one.

Hand the new properties to update_queue() and let it apply them at the point where the queue is unmapped, under the dqm lock. Swap the ring buffer reference afterwards, and only if the properties were applied.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 16 +++++
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  7 ++
 .../amd/amdkfd/kfd_process_queue_manager.c    | 67 +++++++++++--------
 3 files changed, 63 insertions(+), 27 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +16 -0
index feb3062e6..b93870421 100644
@@ -1325,6 +1325,22 @@ static void update_queue_mqd(struct device_queue_manager *dqm, struct queue *q,
 		dqm->mqd_mgrs[get_mqd_type_from_queue_type(q->properties.type)];
 	bool prev_active = q->properties.is_active;
 
+	/*
+	 * The queue is off the hardware now. Only from here on may its
+	 * properties change, otherwise a failed unmap would leave the
+	 * scheduler running the old ring under the new description.
+	 */
+	if (q->pending_props) {
+		const struct queue_properties *np = q->pending_props;
+
+		q->properties.queue_address = np->queue_address;
+		q->properties.queue_size = np->queue_size;
+		q->properties.queue_percent = np->queue_percent;
+		q->properties.priority = np->priority;
+		q->properties.pm4_target_xcc = np->pm4_target_xcc;
+		q->pending_props = NULL;
+	}
+
 	mqd_mgr->update_mqd(mqd_mgr, q->mqd, &q->properties, minfo);
 
 	/*
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +7 -0
index 13e9e3ed8..e2110e65e 100644
@@ -673,6 +673,13 @@ struct queue {
 	/* the dqm took the queue off its lists, the pqm has to finish */
 	bool dqm_dequeued;
 
+	/*
+	 * New properties from pqm_update_queue_properties(). Set under
+	 * p->mutex, applied and cleared by update_queue() under the dqm lock
+	 * once the queue is unmapped.
+	 */
+	const struct queue_properties *pending_props;
+
 	/* The VRAM-resident MQD BO (mqd_on_vram()) is unpinned at S4 suspend so
 	 * TTM evicts it into the hibernation image, and repinned on resume. Set
 	 * while the BO is unpinned so the resume path knows to repin it.
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +40 -27

100 lines not on this page · raw message

Signature · 1 line
2.56.1
#14 lore raw

Re: [PATCH v1 7/9] drm/amdkfd: apply queue property updates only after unmap

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] drm/amdkfd: race on q->pending_props between update_queue and set_perfcount - [Medium] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] drm/amdkfd: race on q->pending_props between update_queue and set_perfcount
- [Medium] drm/amdkfd: update_queue_locked() mutates MQD while active queue is in MES
- [Medium] drm/amdkfd: update_queue_locked() drops update with 0 return on stopped NO_HWS
--

commit 04bc122a04713e23b8e6ce8e16afe2c0ab475963
Author: Armas Spann <[email protected]>

drm/amdkfd: apply queue property updates only after unmap

This commit defers applying new queue properties and swapping the ring buffer BO reference until update_queue_mqd() runs after unmapping the queue.

Quoted 17 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +9 -0
index dbbc6c0794ed3..1c348f36cd3c3 100644
@@ -1325,6 +1325,22 @@ static void update_queue_mqd(struct device_queue_manager *dqm, struct queue *q,
 		dqm->mqd_mgrs[get_mqd_type_from_queue_type(q->properties.type)];
 	bool prev_active = q->properties.is_active;
 
+	/*
+	 * The queue is off the hardware now. Only from here on may its
+	 * properties change, otherwise a failed unmap would leave the
+	 * scheduler running the old ring under the new description.
+	 */
+	if (q->pending_props) {
+		const struct queue_properties *np = q->pending_props;
+
+		q->properties.queue_address = np->queue_address;

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static void update_queue_mqd(struct device_queue_manager *dqm, struct queue *q, · line 1346

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -0
+		q->properties.queue_size = np->queue_size;
+		q->properties.queue_percent = np->queue_percent;
+		q->properties.priority = np->priority;
+		q->properties.pm4_target_xcc = np->pm4_target_xcc;
+		q->pending_props = NULL;
+	}
+
 	mqd_mgr->update_mqd(mqd_mgr, q->mqd, &q->properties, minfo);
 
 	/*

[Severity: Medium]
Can update_queue_mqd() still overwrite q->properties and q->mqd while an active queue remains in MES?

In update_queue_locked(), the kfd_mes_queue_retired(dqm, q) check only runs when !prev_active. When prev_active is true and the scheduler is halted or stopped (!dqm->sched_running || dqm->sched_halt), remove_queue_mes() -> remove_queue_mes_on_reset_option() returns 0 without sending REMOVE_QUEUE to MES. If halt_cpsch() or stop_cpsch() left the queue unretired in MES, update_queue_locked() proceeds to update_queue_mqd(), clears q->pending_props, and lets pqm_update_queue_properties() drop the unmap protection and BO reference on old_ring_bo while MES still holds the queue.

[ ... ]

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +0 -0
index 29827a736f7d4..a7070e87305b0 100644
@@ -644,60 +644,73 @@ int pqm_update_queue_properties(struct process_queue_manager *pqm, unsigned int qid)
 int pqm_update_queue_properties(struct process_queue_manager *pqm,
 				unsigned int qid, struct queue_properties *p)
 {

[ ... ]

Quoted 25 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +20 -4
+	/*
+	 * The dqm applies the new properties once the queue is unmapped. If
+	 * it fails before that, the queue still runs on the old ring and
+	 * keeps its old properties.
+	 */
+	q->pending_props = p;
+	retval = q->device->dqm->ops.update_queue(q->device->dqm, q, NULL);
+
+	if (q->pending_props) {
+		/* Not applied. Drop the reference on the new ring. */
+		q->pending_props = NULL;
+		old_ring_bo = new_ring_bo;
+	} else if (new_ring_bo) {
+		old_ring_bo = q->properties.ring_bo;
+		q->properties.ring_bo = new_ring_bo;
+	} else {
+		old_ring_bo = NULL;
+	}
 
-	retval = pqn->q->device->dqm->ops.update_queue(pqn->q->device->dqm,
-							pqn->q, NULL);
-	if (retval != 0)
-		return retval;
+	/* There is an old ring to drop only if a new one was looked up */
+	if (old_ring_bo) {

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c int pqm_destroy_queue(struct process_queue_manager *pqm, unsigned int qid) · line 714

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +7 -1
+		if (!amdgpu_bo_reserve(vm->root.bo, true)) {
+			kfd_queue_unref_bo_va(vm, &old_ring_bo);
+			amdgpu_bo_unreserve(vm->root.bo);
+		}
+		kfd_queue_buffer_put(&old_ring_bo);
+	}
 
-	return 0;
+	return retval;
 }

[Severity: High]
Can set_perfcount() race with pqm_update_queue_properties() on q->pending_props and cause a stack use-after-return or map a queue with an unreferenced ring buffer?

kfd_ioctl_update_queue() allocates struct queue_properties on its stack and calls pqm_update_queue_properties() under p->mutex. However, q->pending_props is written before update_queue() acquires dqm_lock(dqm) and tested/cleared after update_queue() releases dqm_lock(dqm). Meanwhile, set_perfcount() iterates over all queues under dqm_lock(dqm) without holding p->mutex and calls update_queue_mqd(), which unconditionally consumes q->pending_props even when minfo != NULL:

CPU0 CPU1
kfd_ioctl_update_queue()
lock(&p->mutex)
pqm_update_queue_properties(..., &props)

    q->pending_props = &props
    update_queue()
      dqm_lock(dqm)
      /* fails before update_queue_mqd() */
      dqm_unlock(dqm)
                                       set_perfcount()
                                         dqm_lock(dqm)
                                         update_queue_mqd()
                                           np = q->pending_props
    if (q->pending_props)
      q->pending_props = NULL
      /* drops new_ring_bo ref */
  unlock(&p->mutex)
  return; /* pops props off stack */
                                           q->properties.queue_address =
                                             np->queue_address
                                             <-- stack use-after-return

If CPU1 clears q->pending_props before CPU0 checks it, CPU0 also sees q->pending_props == NULL after a failed update_queue(), swaps in new_ring_bo, drops old_ring_bo, and returns the error to userspace. Or if set_perfcount() runs after q->pending_props = p and before update_queue() takes dqm_lock(dqm), set_perfcount() consumes q->pending_props early; under KFD_SCHED_POLICY_NO_HWS, if that update activates the queue from another process context, update_queue_locked() triggers WARN(q->process->mm != current->mm) and skips load_mqd() while leaving q->properties.is_active true.

Only consuming q->pending_props when update_queue_mqd() is called for a property update (minfo == NULL), or setting and clearing q->pending_props strictly under dqm_lock(dqm), would avoid this race.

[Severity: Medium]
Under KFD_SCHED_POLICY_NO_HWS, does updating an active queue while !dqm->sched_running now silently discard the new properties while returning 0?

In update_queue_locked(), the NO_HWS branch checks !dqm->sched_running when prev_active is true and returns retval (which is 0) before calling update_queue_mqd():

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:update_queue_locked() {
	...
	} else if (prev_active &&
		   (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
		    q->properties.type == KFD_QUEUE_TYPE_SDMA ||
		    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {

		if (!dqm->sched_running) {
			WARN_ONCE(1, "Update non-HWS queue while stopped\n");
			return retval;
		}
	...
}

Because update_queue_mqd() is not reached, q->pending_props remains non-NULL, so pqm_update_queue_properties() drops the reference on new_ring_bo, leaves q->properties unchanged, and returns 0 to userspace.

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

PATCH 8/9 drm/amdkfd: reconcile queue state with MES after a restart

In reply to Armas Spann

A GPU reset restarts the MES firmware, which then knows no user queues. KFD keeps its processes, in an evicted state, until they exit. Their queues cannot be removed cleanly on the way into the reset, because every REMOVE_QUEUE fails with -EIO at that point.

On an R9700 this showed up as resets that come in pairs. A process that had lived through a GPU reset exited 62 s later. KFD sent REMOVE_QUEUE for queues the new firmware had never seen, MES rejected each command within a fraction of a millisecond, and KFD reset the GPU again.

The per-queue MES state already stops those commands one queue at a time. Put the driver state right in one place as well: when the scheduler starts, walk the queues of every process, drop the MES state that belongs to an earlier firmware instance and release the status slots of commands that were lost with it. A queue that is still counted as running is deactivated and marked evicted together with its process. That is the state kgd2kfd_pre_reset() leaves queues in when eviction works, and after a system resume kfd_resume_all_processes() maps the queues again from it.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 70 +++++++++++++++++++
 1 file changed, 70 insertions(+)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +70 -0
index b93870421..03f341c45 100644
@@ -2652,6 +2652,74 @@ static int init_dequeue_wait_counts_mes(struct device_queue_manager *dqm)
 	return 0;
 }
 
+/*
+ * Bring the queue bookkeeping in line with MES when the scheduler starts.
+ *
+ * If the MES firmware was set up from scratch since a queue was added (GPU
+ * reset, resume), it has no record of that queue. A GPU reset cannot evict
+ * cleanly: the REMOVE_QUEUE commands fail with -EIO while the reset is
+ * running, and whatever was not marked inactive at that point stays active
+ * in the driver. The next REMOVE_QUEUE for such a queue, typically when its
+ * process exits, is rejected by the new firmware instance and that failure
+ * is escalated to another GPU reset.
+ *
+ * So drop the stale MES state here, and deactivate every queue that the
+ * driver still counts as running although MES has lost it. KFD does not
+ * resume processes after a GPU reset. Such a queue is marked evicted, and
+ * its process with it, which is the state kgd2kfd_pre_reset() leaves all
+ * the queues in that it did manage to evict. After a system resume
+ * kfd_resume_all_processes() maps the queues again from that state.
+ *
+ * dqm lock held.
+ */
+static void kfd_dqm_reconcile_mes_queues(struct device_queue_manager *dqm)
+{
+	struct device *dev = dqm->dev->adev->dev;
+	struct device_process_node *cur;
+	struct qcm_process_device *qpd;
+	unsigned int stale = 0, active = 0;
+	struct queue *q;
+
+	if (!dqm->dev->kfd->shared_resources.enable_mes)
+		return;
+
+	/* A command that got no answer died with the old firmware */
+	kfd_mes_fenced(dqm);
+
+	list_for_each_entry(cur, &dqm->queues, list) {
+		qpd = cur->qpd;
+		list_for_each_entry(q, &qpd->queues_list, list) {
+			/* Not in MES, or added to the instance now running */
+			if (q->mes_state == KFD_MES_QUEUE_UNMAPPED ||
+			    q->mes_fw_gen == kfd_mes_gen(dqm))
+				continue;
+
+			/* Also returns the status slot of a lost command */
+			kfd_mes_queue_retired(dqm, q);
+			stale++;
+
+			if (!q->properties.is_active)
+				continue;
+
+			q->properties.is_active = false;
+			q->properties.is_evicted = true;
+			decrement_queue_count(dqm, qpd, q);
+			/* The process stays evicted from here on */
+			if (!qpd->evicted)
+				qpd->evicted = 1;
+			active++;
+		}
+	}
+
+	if (active)
+		dev_warn(dev,
+			 "MES was restarted with %u queue(s) still marked active, evicted them\n",
+			 active);
+	if (stale)
+		dev_info(dev, "MES was restarted, forgot %u user queue(s)\n",
+			 stale);
+}
+
 static int start_cpsch(struct device_queue_manager *dqm)
 {
 	struct device *dev = dqm->dev->adev->dev;
@@ -2716,6 +2784,8 @@ static int start_cpsch(struct device_queue_manager *dqm)
 		hqd_info_size * sizeof(struct amdgpu_mes_hung_queue_hqd_info),
 		GFP_KERNEL);
 
+	kfd_dqm_reconcile_mes_queues(dqm);
+
 	/* A restart of the MES firmware retires every quarantined queue */
 	if (!list_empty(&dqm->zombie_queues))
 		mod_delayed_work(system_dfl_wq, &dqm->zombie_work, 0);
Signature · 1 line
2.56.1
#16 lore raw

Re: [PATCH v1 8/9] drm/amdkfd: reconcile queue state with MES after a restart

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] drm/amdkfd: set_queue_as_reset() clears is_active before MES reconciliation - [Medium] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] drm/amdkfd: set_queue_as_reset() clears is_active before MES reconciliation
- [Medium] drm/amdkfd: kfd_dqm_reconcile_mes_queues() skips active unmapped queues
- [Medium] drm/amdkfd: incomplete process eviction in kfd_dqm_reconcile_mes_queues()
--

commit 57ed11ff8b41067e05295c9b1d33b02e617c5472
Author: Armas Spann <[email protected]>

drm/amdkfd: reconcile queue state with MES after a restart

This commit adds kfd_dqm_reconcile_mes_queues() to start_cpsch() to drop stale MES queue state, release lost command tickets, and mark active queues and their processes evicted after an MES firmware restart.

Quoted 39 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +31 -0
index 1c348f36cd3c3..f008b05e95993 100644
@@ -2649,6 +2649,74 @@ static int init_dequeue_wait_counts_mes(struct device_queue_manager *dqm)
 	return 0;
 }
 
+/*
+ * Bring the queue bookkeeping in line with MES when the scheduler starts.
+ *
+ * If the MES firmware was set up from scratch since a queue was added (GPU
+ * reset, resume), it has no record of that queue. A GPU reset cannot evict
+ * cleanly: the REMOVE_QUEUE commands fail with -EIO while the reset is
+ * running, and whatever was not marked inactive at that point stays active
+ * in the driver. The next REMOVE_QUEUE for such a queue, typically when its
+ * process exits, is rejected by the new firmware instance and that failure
+ * is escalated to another GPU reset.
+ *
+ * So drop the stale MES state here, and deactivate every queue that the
+ * driver still counts as running although MES has lost it. KFD does not
+ * resume processes after a GPU reset. Such a queue is marked evicted, and
+ * its process with it, which is the state kgd2kfd_pre_reset() leaves all
+ * the queues in that it did manage to evict. After a system resume
+ * kfd_resume_all_processes() maps the queues again from that state.
+ *
+ * dqm lock held.
+ */
+static void kfd_dqm_reconcile_mes_queues(struct device_queue_manager *dqm)
+{
+	struct device *dev = dqm->dev->adev->dev;
+	struct device_process_node *cur;
+	struct qcm_process_device *qpd;
+	unsigned int stale = 0, active = 0;
+	struct queue *q;
+
+	if (!dqm->dev->kfd->shared_resources.enable_mes)
+		return;
+

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int init_dequeue_wait_counts_mes(struct device_queue_manager *dqm) · line 2692

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	/* A command that got no answer died with the old firmware */
+	kfd_mes_fenced(dqm);
+
+	list_for_each_entry(cur, &dqm->queues, list) {
+		qpd = cur->qpd;
+		list_for_each_entry(q, &qpd->queues_list, list) {
+			/* Not in MES, or added to the instance now running */
+			if (q->mes_state == KFD_MES_QUEUE_UNMAPPED ||
+			    q->mes_fw_gen == kfd_mes_gen(dqm))
+				continue;

[Severity: Medium]
Can skipping queues with q->mes_state == KFD_MES_QUEUE_UNMAPPED leave an unmapped queue marked q->properties.is_active == true across stop_cpsch() and start_cpsch()?

When stop_cpsch() calls remove_all_kfd_queues_mes(), remove_queue_mes() transitions any still-active queue to KFD_MES_QUEUE_UNMAPPED without clearing q->properties.is_active (and add_queue_mes() similarly returns 0 without mapping into MES while !dqm->sched_running). Because start_cpsch() does not re-add active queues when MES is enabled and restore_process_queues_cpsch() skips queues whose q->properties.is_active is true, such a queue is never re-added to MES on resume.

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int init_dequeue_wait_counts_mes(struct device_queue_manager *dqm) · line 2702

Quoted 7 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -0
+
+			/* Also returns the status slot of a lost command */
+			kfd_mes_queue_retired(dqm, q);
+			stale++;
+
+			if (!q->properties.is_active)
+				continue;

[Severity: High]
Does set_queue_as_reset() clear q->properties.is_active before kfd_dqm_reconcile_mes_queues() runs on a GPU reset, preventing queues and their qpd from being marked evicted here?

In kgd2kfd_post_reset(), kfd_dqm_set_queues_as_reset() runs before kfd_resume() -> start_cpsch():

drivers/gpu/drm/amd/amdkfd/kfd_device.c:kgd2kfd_post_reset() {
    ...
	for (i = 0; i < kfd->num_nodes; i++)
		kfd_dqm_set_queues_as_reset(kfd->nodes[i]->dqm);

	for (i = 0; i < kfd->num_nodes; i++) {
		ret = kfd_resume(kfd->nodes[i]);
    ...
}

set_queue_as_reset() clears q->properties.is_active to false without setting q->properties.is_evicted = true or qpd->evicted = 1. When kfd_dqm_reconcile_mes_queues() then runs, it retires q->mes_state to KFD_MES_QUEUE_UNMAPPED and hits this !q->properties.is_active check, leaving any queue or process that kgd2kfd_pre_reset() did not evict (for example, after an earlier partial restore_process_queues_cpsch() failure left qpd->evicted == 1 with active queues) un-evicted and eligible to be re-added to MES.

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int init_dequeue_wait_counts_mes(struct device_queue_manager *dqm) · line 2712

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+
+			q->properties.is_active = false;
+			q->properties.is_evicted = true;
+			decrement_queue_count(dqm, qpd, q);
+			/* The process stays evicted from here on */
+			if (!qpd->evicted)
+				qpd->evicted = 1;
+			active++;
+		}
+	}

[Severity: Medium]
When this transitions qpd->evicted from 0 to 1, does it leave inactive sibling queues on qpd->queues_list with q->properties.is_evicted == false and leave pdd->last_evict_timestamp unset?

If a process has both a stale active queue and an inactive or suspended queue (whose mes_state is KFD_MES_QUEUE_UNMAPPED or is_active is false), only the active queue gets q->properties.is_evicted = true while qpd->evicted becomes 1. Because QUEUE_IS_ACTIVE(q->properties) checks !q->properties.is_evicted rather than qpd->evicted, a subsequent update_queue() or resume_single_queue() on the sibling queue will call add_queue_mes() while the process is evicted, and a later restore_process_queues_cpsch() will compute eviction duration from a zero or stale pdd->last_evict_timestamp.

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

PATCH 9/9 drm/amdkfd: force CWSR on with more than one MES GPU

In reply to Armas Spann

With amdgpu.cwsr_enable=0 the MQD of a compute queue carries no QSWITCH_MODE and no save area. Such a queue cannot be preempted. It leaves the hardware only when its running waves have finished. MES waits 2 s for that and then fails the command that asked for the unmap.

On a system with two R9700 (gfx 12.0.1, MES 0x97) that run RCCL collectives between them this ends the job. Between 90 and 118 s into a run MES answered the REMOVE_QUEUE of a queue eviction with 0x8100030100000000 and the SUSPEND that followed with 0x8100060200000000, each 2 s after the command, first on one GPU and 4 s later on the other, and one queue per GPU had to be reset. The timing fits a kernel on one GPU that waits for its peer on the other GPU while the queue of that peer is evicted: such a kernel cannot drain. With CWSR enabled the same machine ran an RCCL all_reduce load for 150 s and for 600 s, 343647 iterations in the longer run, without one MES error.

Nothing tells a user who sets cwsr_enable=0 that it takes preemption away. Ignore the setting on a discrete GPU that is scheduled by MES when there is a second one in the system, and say so in the log.

The timeout is that of MES, so this is limited to hardware that uses it, GC 11 and later. Older hardware does not have this path and keeps what the parameter says. So does an integrated GPU. The fan boost for multi-GPU systems draws the same line and counts discrete GPUs only.

The check is made per device in kfd_cwsr_init(), the one place that reads the parameter. The parameter itself is not changed. It also applies to the devices that are left alone, and one that is probed later must not get CWSR because of a device that was probed before it. The warning is printed for each device that is affected.

The GPUs are probed one after the other. A device is added to mgpu_info at the end of its initialization, after KFD has been set up, so when kfd_cwsr_init() runs for the first GPU nothing there shows the second one. kfd->num_nodes counts the partitions of one device. Add amdgpu_pci_has_mes_peer(), which walks the PCI bus instead. A device is a peer if it matches one of the class entries of the id table, which is how every GPU with MES is matched, if it is not left to radeon, and if no other driver has it or was assigned it with driver_override. That leaves out a GPU that is passed through with vfio-pci. For a device that is in mgpu_info already, its GC version and its APU flag decide.

A device that has not been probed yet is known by its PCI ID only. An integrated GPU, or a GPU older than GC 11 without an entry of its own in the id table, that is probed after the discrete GPU is taken for a peer. CWSR, the default, is then enforced where it was not needed. A GPU that is hot-added after another one has been set up without CWSR gets CWSR itself, but does not change the device that is already running.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu.h           |  1 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c       | 99 ++++++++++++++++++-
 drivers/gpu/drm/amd/amdkfd/kfd_device.c       | 26 ++++-
 3 files changed, 123 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu.h +1 -0
index 7e1b9a70f..c3ab385c8 100644
@@ -1306,6 +1306,7 @@ struct amdgpu_afmt_acr amdgpu_afmt_acr(uint32_t clock);
 
 void amdgpu_register_gpu_instance(struct amdgpu_device *adev);
 void amdgpu_unregister_gpu_instance(struct amdgpu_device *adev);
+bool amdgpu_pci_has_mes_peer(struct amdgpu_device *adev);
 
 pci_ers_result_t amdgpu_pci_error_detected(struct pci_dev *pdev,
 					   pci_channel_state_t state);
drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +97 -2

114 lines not on this page · raw message

drivers/gpu/drm/amd/amdkfd/kfd_device.c +25 -1
index 8080fbe3f..670567fc0 100644
@@ -512,7 +512,31 @@ struct kfd_dev *kgd2kfd_probe(struct amdgpu_device *adev, bool vf)
 
 static void kfd_cwsr_init(struct kfd_dev *kfd)
 {
-	if (cwsr_enable && kfd->device_info.supports_cwsr) {
+	struct amdgpu_device *adev = kfd->adev;
+	bool enable = cwsr_enable;
+
+	/*
+	 * Without CWSR a compute queue cannot be preempted. It is unmapped
+	 * only once its running waves have finished. MES waits 2 s for that
+	 * and then fails the command. With two GPUs a kernel on one of them
+	 * can wait for a kernel on the other one. If the queue of that one is
+	 * evicted, the wait does not end and the unmap times out. Do not let
+	 * cwsr_enable=0 through in that case.
+	 *
+	 * Only a discrete GPU that is scheduled by MES is concerned, which is
+	 * GC 11 and later. Older hardware and integrated GPUs keep what the
+	 * parameter says. The parameter itself is not changed, it also
+	 * applies to the devices that are left alone here.
+	 */
+	if (!enable && kfd->device_info.supports_cwsr &&
+	    amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0) &&
+	    !(adev->flags & AMD_IS_APU) && amdgpu_pci_has_mes_peer(adev)) {
+		dev_warn(adev->dev,
+			 "CWSR forced on: multi-GPU with MES requires preemption support\n");
+		enable = true;
+	}
+
+	if (enable && kfd->device_info.supports_cwsr) {
 		if (KFD_GC_VERSION(kfd) < IP_VERSION(9, 0, 1)) {
 			BUILD_BUG_ON(sizeof(cwsr_trap_gfx8_hex)
 					     > KFD_CWSR_TMA_OFFSET);

--
2.56.1

#18 lore raw
In reply to Armas Spann

On Tue, Nov 24, 2026, [email protected] wrote reviews for patches 1 through 8 of this series. Answering all of them in one place since several findings touch the same code. Line numbers are from the tree with v1 applied.

Thanks for the review. Of the 32 findings, 16 are real and get fixed in v2, 2 do not happen, and 14 are in the baseline. Six of the baseline ones get picked up in v2 anyway because the series leans on that code or already rewrites the function. Details per patch below, the v2 summary is at the end.

[PATCH v1 1/9] drm/amdgpu/mes: distinguish rejected from timed out commands

Quoted 1 line

[High] global fw_gen incremented per XCC in mes_v12_1_xcc_hw_init()

Correct in principle, not reachable today. The counter is bumped per XCC (mes_v12_1.c:1945) and compared device wide. The only per-XCC entry is gfx_v12_1_xcc_cp_resume() -> amdgpu_mes_kiq_hw_init() -> mes_v12_1_xcc_hw_init(), whose callers are the whole-device cp_resume and gfx_v12_1_xcp_resume(). amdgpu_xcp_resume() has no caller in the tree. A partition switch sets AMDGPU_XCP_OPS_KFD and goes through kgd2kfd_check_and_lock_kfd(), which refuses while kfd_processes_count is non-zero (quarantined queues keep it non-zero) and then tears KFD down before any MES instance is touched. So no KFD queue survives into a single-XCC restart.

Still, "the scheduler instance that knew the queue" is an XCC on 12.1, and a device-wide counter is a trap for the next per-XCC reset path. v2 makes fw_gen per XCC, tickets record the XCC they were submitted on, and kfd_mes_gen() reads the entry for the node's XCC.

Quoted 1 line

[Medium] 32-bit status_ptr in mes_v12_1_submit_pkt_ticket() drops upper status

Correct. mes_v12_1.c:173 has u32 *status_ptr, the branch at :243 is only entered with the low 32 bits zero, so the new "rejected" line prints 0x0000000000000000 every time. The firmware error code in bits 63:32 is exactly what the patch set out to print, and 12.1 is the hardware this was debugged on. v11 and v12.0 use u64 and are fine. v2 uses u64 on 12.1, zeroes all 64 bits and prints upper/lower like mes_v12_0 does.

Quoted 1 line

[Medium] missing dma_rmb() in amdgpu_mes_ticket_poll()

Correct for weakly ordered architectures. The two status loads are to the same address and stay ordered, but the second status load can be satisfied before the fence load it is control dependent on. Device order is status, then fence, so arm64 can see the new fence with the old status and return FAILED for a completed command. x86 cannot reorder loads against loads, which is why it did not show. The baseline submit path has the same shape (poll fence, then read status). v2 adds dma_rmb() in the ticket poll and after a successful fence wait in the submit paths.

[PATCH v1 2/9] drm/amdkfd: factor out freeing of per-queue MES resources

Quoted 1 line

[High] pre-existing: memory leak in pqm_create_queue()

Pre-existing and correct. Patch 2 is a pure move. Patch 5 adds kfd_queue_free_mes_resources() to err_create_queue, which is where the leak closes in v1. Since it is a standalone leak a local user can trigger, v2 moves that fix into its own patch at the front of the series with a Fixes tag so it can go to stable on its own.

[PATCH v1 3/9] drm/amdkfd: track whether MES knows each queue

Quoted 1 line

[Medium] missing kfd_mes_fence() call on command timeout in add_queue_mes()

Correct. kfd_hws_hang() only schedules the reset work; until that work takes reset_domain->sem for writing, down_read_trylock() keeps succeeding and callers that loop (kfd_resume_all_processes(), set_perfcount()) submit behind the unanswered ADD_QUEUE at 2.1 s a piece under the dqm lock. The REMOVE path fences, the ADD path does not, and the commit message claims both. v2 fences on -ETIMEDOUT in add_queue_mes(). ADD has no ticket, so the fence is lifted by the firmware restart the scheduled reset performs. A rejection does not fence, MES is answering.

Quoted 1 line

[High] false success in remove_queue_mes_on_reset_option() when queue is not retired

The three early return 0 paths (is_reset, !sched_running, sched_halt) are the baseline's. After a halt or stop that succeeded every active queue is UNMAPPED and kfd_mes_queue_retired() at :503 answers before them. They are only reached for a MAPPED queue after remove_all_kfd_queues_mes() failed half way, and that first failure went through the recovery path, which fences MES and schedules a GPU reset. The MQD rewrite in that window is the baseline's as well (evict_process_queues_cpsch() does not unpin the MQD BO, that is the S4 path and runs only after a successful removal).

With the state tracking there is no reason to report success for a queue MES still has, so v2 tightens it: the is_reset shortcut goes away (the retired check covers a queue the reset removed, and for one it did not the shortcut is wrong, see the zombie finding on 4/9), and the !sched_running || sched_halt case returns -EIO for a queue that is not retired. destroy then quarantines, update leaves the MQD alone, evict marks the queue evicted without pretending MES dropped it, and the reaper retries once the scheduler runs.

Quoted 1 line

[High] ignored remove-after-reset error and unfenced timeout in reset_queue_mes()

Two parts. Ignoring the return value and skipping recovery for is_for_reset are the baseline's (reset_queue_mes() returned 0 either way, and "if (!r || is_for_reset) return r;" skipped the reset). Not fencing a timed-out remove-after-reset is a hole in the new mechanism, agreed. The state is at least recorded, __remove_queue_mes() leaves the queue UNKNOWN so destroy quarantines it.

v2: reset_queue_mes() looks at the result. On -ETIMEDOUT it fences MES and returns the error, so amdgpu_gfx_reset_mes_compute() fails and each caller escalates (KFD through kfd_hws_hang(), userq through gpu_reset, KCQ through the ring reset result). A rejection keeps the queue UNKNOWN and returns 0 as before: MES is alive, the other hung queues should still be reset, and the quarantine handles the storage. set_queue_as_reset() still runs, the queue was reset.

Quoted 1 line

[Medium] unlocked MES state access in kfd_reset_queue_mes()

Pre-existing. kfd_reset_queue_mes() is unchanged from the baseline and runs without the dqm lock from gfx_v11_0_reset_kcq(), gfx_v12_0_reset_kcq() and amdgpu_userq_hang_detect_work(), under adev->gfx.mec.reset_mutex only. It already walks dqm->queues and writes is_active, has_reset_queue and the queue counters in that state. The series adds mes_state and mes_ticket to the fields touched there, which adds a wb slot double free to the possible outcomes, but the lock-less entry is the problem. It cannot be fixed by taking the dqm lock there:
reset_queues_mes() holds the dqm lock while calling amdgpu_gfx_reset_mes_compute(), which takes reset_mutex, so a KGD caller holding reset_mutex and wanting the dqm lock deadlocks against it. This needs a lock order decision between the KGD and KFD reset paths and is a separate series.

Quoted 1 line

[Medium] reset_queues_mes() called behind unanswered REMOVE_QUEUE before fencing

Correct. If the ticket is still PENDING after the 4 s grace period, MES has not moved its ring for 6.1 s, and SUSPEND, DETECT_AND_RESET and RESUME queue behind it for up to 6.3 s more under the dqm lock, which also blocks kgd2kfd_pre_reset(). kfd_mes_wait_retired() already returns early for a ticket answered with a failure, and that is the case where MES is alive and the per-queue reset makes sense. v2: still PENDING after the grace period (or amdgpu_in_reset()) fences MES and goes straight to the kfd_hws_hang() path. reset_queues_mes() runs only when MES answered.

Quoted 1 line

[Medium] missing gang_context_array_index and ticket in reset_queues_mes()

gang_context_array_index: pre-existing, the baseline queue_input in reset_queues_mes() lacks it too, and mes_v11_0_remove_hw_queue() copies it unconditionally. ticket: agreed, not passing it frees the status slot while the command may be in flight, which is what the ticket was added to prevent. v2 sets both; a non-pending ticket from the earlier REMOVE_QUEUE is released first so the slot is not leaked. With the previous fix this path is never entered with a pending ticket.

Quoted 1 line

[High] duplicate REMOVE_QUEUE after late completion in reset_queues_mes()

Correct, if narrow. The SUSPEND scenario needs MES to wake up after a 6 s stall right before the SUSPEND is processed, but the code must not reset the GPU for a removal that succeeded. The fix above (no reset_queues_mes() behind a pending ticket) removes that scenario, and v2 also re-checks kfd_mes_queue_retired() after a failed reset_queues_mes() before escalating. The second scenario, a ticket turning DONE between the caller's retired check and the PENDING test in __remove_queue_mes(), is a nanosecond window and a trivial fix: v2 makes __remove_queue_mes() retire the queue on DONE instead of releasing the ticket and sending a duplicate.

Quoted 1 line

[High] kfd_dqm_suspend_bad_queue_mes() leaves unremoved queue in MES

Pre-existing. kfd_dqm_suspend_bad_queue_mes() is untouched by the series; when MES reports other queues hung and not this one, amdgpu_gfx_reset_mes_compute() resumes it with the rest and never removes it, and the baseline marks it inactive and evicted regardless. The series moved the "recovery left this one in MES" removal only into remove_queue_mes_on_reset_option(), you are right that the other caller does not get it. What the series does change: destroy_queue_cpsch() and process_termination_cpsch() now send REMOVE_QUEUE based on kfd_mes_queue_retired() instead of is_active, so such a queue is removed at destroy time rather than leaking in MES, and update_queue_locked() refuses to rewrite its MQD.

v2 moves the explicit post-recovery removal into reset_queues_mes() so both callers get it, and remove_all_kfd_queues_mes() iterates on !kfd_mes_queue_retired() like the other teardown paths.

Quoted 1 line

[High] pre-existing: unbalanced queue unmap in update_queue() on reset queue

Pre-existing and correct: has_reset_queue is tested after the unmap at update_queue_locked():1407. The series only inserts the retired check above it. Moving the test ahead of the unmap is the fix; it is unrelated to this series and should go in on its own.

[PATCH v1 4/9] drm/amdkfd: add a quarantine for queues MES has not retired

Quoted 1 line

[High] kgd2kfd_teardown_processes() misses exited processes with zombies

Correct. The hash_empty() return at kfd_device.c:1832 comes before the new kfd_dqm_retire_all() loop and before the kfd_processes_count wait. kfd_process_table_remove() drops the process from the table at the start of the notifier release, kfd_processes_count is only decremented in kfd_process_destroy_pdds(), and the series defers that until the last mes_hold is gone. Last process exits with a quarantined queue, device is removed, teardown returns early, device_queue_manager_uninit() warns on the zombie list and frees the device under it. The baseline has the same early return and the same gap, but there the gap is until the release work runs; with the series it is until MES answers, which on an unplugged device is never. v2: the hash_empty() test only skips the signalling loop, retire and wait run whenever adev->kfd.dev is set.

Quoted 1 line

[High] broken zombie queue handling in reset_queue_mes()

Correct on all three points, with one correction. (1) A failed remove-after-reset followed by set_queue_as_reset() leaves the zombie MAPPED/UNKNOWN with is_reset set, and the reaper's remove_queue_mes() returns 0 at the is_reset shortcut forever. Fixed by dropping the shortcut and by fencing and escalating a timed-out remove-after-reset (see 3/9). (2) A queue quarantined from create_queue_cpsch() keeps is_active, the cleanup path decrements without clearing it, and set_queue_as_reset() decrements again. destroy_queue_cpsch() and process_termination_cpsch() do clear it, so the "or process_termination_cpsch()" part is not right, but the create path is a real underflow. (3) has_reset_queue for a queue user space already destroyed penalises the process for a queue it no longer owns.

v2: reset_queue_mes() does the MES side for a zombie (reset, remove-after-reset, state) and skips set_queue_as_reset() for q->is_zombie, no counter change, no has_reset_queue, no is_reset. create_queue_cpsch() clears is_active after the decrement.

Quoted 1 line

[High] unlocked zombie_queues traversal in find_queue_by_doorbell_offset()

Pre-existing, same root as the unlocked kfd_reset_queue_mes() above. find_queue_by_doorbell_offset() already walks dqm->queues and every qpd->queues_list without the dqm lock from the KGD paths, racing with destroy and termination freeing queues under it. The zombie list is one more list on the same walk and the reaper one more freer, not a new class of bug, and the fix is the same lock order work. Leaving zombies out of the lookup is not an option: a quarantined queue MES reports as hung has to be reset and removed, or it stays hung in MES and the reaper never frees it.

Quoted 1 line

[High] kfd_process_wq_release() early return leaves svms.restore_work active

Correct. The notifier release cancels eviction_work, restore_work and signal_work but not svms.restore_work, which only svm_range_list_fini() cancels, and that now runs after the early return. Nothing re-arms it after release (the interval notifier invalidate bails on mmget_not_zero() of the dying mm), but a delayed work queued before release can fire in the window, take get_task_mm(p->lead_thread) which is the new mm after an execve, and validate pranges whose notifiers belong to the old one. The baseline has the same window between release and svm_range_list_fini(); the series stretches it for as long as MES holds a queue. v2 cancels svms.restore_work in kfd_process_notifier_release_internal() next to the others, which closes the baseline window too.

Quoted 1 line

[Critical] pre-existing: invalid free of context ID 0 on alloc failure in create_process()

Pre-existing and correct: kzalloc leaves context_id at 0, KFD_CONTEXT_ID_MIN is 0, and err_alloc_id runs kfd_process_free_id() which ida_free()s id 0 from the primary's table. The series only adds the mes_hold init there. Deserves its own patch (jump to err_register_notifier instead).

Quoted 1 line

[High] pre-existing: queue_refcount leak in kfd_queue_buffer_get()

Pre-existing and correct: kfd_queue_buffer_get() bumps queue_refcount even when base.bo is NULL, and the unref keys on the BO pointer. The new kfd_queue_ref_bo_va() mirrors the unref and is consistent with it. Rejecting a mapping without a BO in kfd_queue_buffer_get() is the fix, separate patch.

[PATCH v1 5/9] drm/amdkfd: keep queue storage until MES confirmed retirement

Quoted 1 line

[Medium] premature release of user queue buffers when create_queue_cpsch() quarantines queue

Correct. zombie_no_user_bos exists because kfd_ioctl_create_queue() releases the buffers on its own copy of the properties on every error, and init_queue() memcpy'd the same BO pointers into q->properties. So the MQD, doorbell and gang context are kept while the ring, rptr, wptr, EOP and CWSR buffers that MQD points at lose their references and their unmap protection right away. That defeats the quarantine for the biggest part of the queue. v2: when pqm_create_queue() sees a zombie on its error path, the queue takes its own references (amdgpu_bo_ref() on the five BOs, the VA queue_refcounts, kfd_queue_buffer_svm_get() for the CWSR range) before the ioctl drops its set, and the reaper releases them through the normal path. zombie_no_user_bos goes away.

Quoted 1 line

[Medium] active queue count underflow on reset of quarantined queue

Correct, same as the second zombie point on 4/9. v2 clears is_active in the create_queue_cpsch() cleanup path, and set_queue_as_reset() no longer runs for zombies.

Quoted 1 line

[Medium] bo_va->queue_refcount race and imbalance in pqm_destroy_queue()

Correct. kfd_queue_unref_bo_va() clamps at zero and kfd_queue_ref_bo_va() always increments, so the second destroy's unref is a no-op and its re-ref is a net +1; after the first thread is interrupted and re-refs, the count is two above the single queue reference and the BOs can never be unmapped. In the baseline the same race leaves the count at zero while the queue lives, a transient loss of unmap protection; the series turns it into a permanent leak. v2 moves kfd_queue_unref_bo_vas() after dqm->ops.destroy_queue(), run only when the dqm dequeued the queue and it is not a zombie. References stay while the queue is on hardware and are dropped exactly once after it is gone. No re-ref on failure, and kfd_queue_ref_bo_vas() is dropped from 4/9.

Quoted 1 line

[High] pre-existing: broken queue state and count in kfd_dqm_suspend_bad_queue_mes()

Pre-existing and correct, same pattern patch 5 fixes in process_termination_cpsch(). Since v2 moves code into reset_queues_mes() right next to it, v2 adds a separate small patch: decrement only if is_active is still set after the reset. The "left inactive in MES on reset failure" half is the kfd_dqm_suspend_bad_queue_mes() finding on 3/9 and is covered by moving the explicit removal into reset_queues_mes().

[PATCH v1 6/9] drm/amdkfd: keep eviction and restore consistent when MES fails

Quoted 1 line

[High] kfd_process_evict_queues() overwrites -EIO across multiple PDDs

Pre-existing: the baseline has the same per-pdd overwrite and evict_process_queues_cpsch() already returned -EIO when the reset trylock failed. Patch 6 makes -EIO the return for every MES failure though, and documents the "evicted, do not add back" contract, so the lost value matters more than before. v2 keeps a sticky -EIO in kfd_process_evict_queues(), folded into patch 6.

Quoted 1 line

[High] partial failure in restore_process_queues_cpsch() breaks eviction

Pre-existing. The baseline ends a failed restore in the same state:
qpd->evicted == 1 with the queues restored so far running, the next evict skips on evicted++ > 0, the next restore decrements and quits. The baseline was worse in that it marked every queue active before sending anything and the retry added them twice; patch 6 fixes that. The window itself is unchanged. v2 goes further and rolls back: on failure the queues restored in that attempt are deactivated, counted down, marked evicted and removed from MES best effort (-EIO leaves them MAPPED and evicted, as evict does). The process is then either fully restored or fully evicted and the retry starts from a known state.

Quoted 1 line

[Medium] restore_process_queues_cpsch() misses GFX11 oversubscription work

Correct. Moving increment_queue_count() behind add_queue_mes() means the queue that crosses the threshold is not counted when add_queue_mes() checks it, and the notify timer is not armed. The handler only re-arms itself while already running. GFX11 only, but a regression. v2 restores the baseline order (count, then add) and undoes the count on failure instead, which is the same end state patch 6 intended.

[PATCH v1 7/9] drm/amdkfd: apply queue property updates only after unmap

Quoted 1 line

[High] race on q->pending_props between update_queue and set_perfcount

Correct, and the worst finding in the set. pending_props points into the ioctl's stack, is set under p->mutex before the dqm lock and cleared after it, and update_queue_mqd() consumes it whatever minfo says. set_perfcount() is reachable from kfd_ioctl_profiler() of any perfmon_capable() process, takes only the dqm lock and runs update_queue_locked() on every queue of every process. The other minfo users (GWS, CU mask, debug workaround) run under the same p->mutex as the properties ioctl; set_perfcount() is the cross-process one. The stack use after return and the NO_HWS mm WARN both follow.

v2 removes the queue field. The new properties travel with the call:
mqd_update_info gets a new_props pointer that pqm_update_queue_properties() sets in a local minfo (all other members zero, which every update_mqd() treats as nothing to do), update_queue_locked() applies it where update_queue_mqd() runs and clears it to report that it did. A perfcount or debug update carries no new_props and cannot apply somebody else's.

Quoted 1 line

[Medium] update_queue_locked() mutates MQD while active queue is in MES

Pre-existing, same path as the remove_queue_mes_on_reset_option() finding on 3/9: after a successful halt or stop every active queue is UNMAPPED and the retired check answers first, the shortcut is reached only after a half-failed halt with MES fenced and a reset scheduled. The v2 change there (-EIO for a non-retired queue while stopped or halted) makes update_queue_locked() fail before update_queue_mqd(), and pqm_update_queue_properties() then drops the new ring and keeps the old.

Quoted 1 line

[Medium] update_queue_locked() drops update with 0 return on stopped NO_HWS

Correct, minor. Before the series the properties were applied without the MQD, after it nothing is applied, and both return 0. This is a should-not-happen state (an active queue while the scheduler is stopped, hence the WARN_ONCE), NO_HWS only. v2 returns -EBUSY there so the pqm keeps the old ring and user space sees the failure.

[PATCH v1 8/9] drm/amdkfd: reconcile queue state with MES after a restart

Quoted 1 line

[High] set_queue_as_reset() clears is_active before MES reconciliation

Does not happen. The reset path is kgd2kfd_pre_reset() -> kgd2kfd_suspend(kfd, true) -> kfd_suspend_all_processes() -> evict_process_queues_cpsch(), which marks every queue evicted and deactivates the active ones with the counters adjusted, then stop_cpsch(). kgd2kfd_post_reset() runs kfd_dqm_set_queues_as_reset() and then kfd_resume() -> start_cpsch() -> reconcile. By then every queue is inactive and evicted, and set_queue_as_reset() adjusted the counters for anything a partial restore had left active. The !is_active continue skips queues that need nothing. The deactivate branch is a fallback for a firmware restart without a preceding eviction, which no current path
produces: every stop_cpsch() with live processes is preceded by eviction, and in_runpm is impossible while a pdd holds its runtime PM reference. Your residual case, a queue left active by a partial restore and then reset: set_queue_as_reset() deactivates it, has_reset_queue and is_reset are set, and nothing re-adds it. add_all_kfd_queues_mes() keys on is_active, restore is not run after a reset (processes stay evicted), update_queue_locked() fails with -EACCES. No second decrement, no re-add.

The commit message describes the fallback as the regular flow, which is misleading. v2 rewords it, and with the third finding the branch is gone.

Quoted 1 line

[Medium] kfd_dqm_reconcile_mes_queues() skips active unmapped queues

Intended. is_active with mes_state UNMAPPED is the state halt_cpsch() and stop_cpsch() leave every active queue in through remove_all_kfd_queues_mes(), and unhalt_cpsch() -> add_all_kfd_queues_mes() re-adds exactly the queues with is_active set. add_queue_mes() returning 0 while stopped is the same contract. mes_fw_gen carries no meaning for an UNMAPPED queue, there is nothing for the reconcile to compare. If the reconcile deactivated these queues, add_all_kfd_queues_mes() would skip them on unhalt and restore would too, and they would never come back. Your "never re-added on resume" needs a stop with active queues followed by a start with no unhalt and no restore; every resume path that stops the scheduler with live processes evicts them first and restores them through kgd2kfd_resume_process(), and S0ix uses halt/unhalt.

Quoted 1 line

[Medium] incomplete process eviction in kfd_dqm_reconcile_mes_queues()

Correct. When the branch does run it sets qpd->evicted = 1 while flagging only the stale active queue, inactive siblings keep is_evicted == false and last_evict_timestamp is not set. QUEUE_IS_ACTIVE() looks at is_evicted, not qpd->evicted, so an update or resume_single_queue() on a sibling would add it into an evicted process. It is a fallback nothing reaches today, but it is wrong as written. v2 drops the deactivate/evict branch. The reconcile keeps what is needed (retire the stale MES state, release lost tickets, lift the fence) and warns if it finds a queue still marked active, since that would mean a restart path forgot to evict. Deactivation stays in set_queue_as_reset() and evict_process_queues_cpsch(), where it is done right.

Summary of v2 changes

1/9: per-XCC fw_gen, tickets record their XCC; u64 status on 12.1 so
the firmware error code is printed; dma_rmb() between fence and status reads.
2/9: the pqm_create_queue() MES resource leak fix moves out of 5/9 into
its own patch at the front with a Fixes tag.
3/9: fence on a timed-out ADD_QUEUE; drop the is_reset shortcut and
return -EIO for a non-retired queue while stopped or halted; reset_queue_mes() fences and propagates -ETIMEDOUT of the remove-after-reset; a still pending ticket after the grace period fences and skips reset_queues_mes(); __remove_queue_mes() retires on DONE instead of sending a duplicate and the retired state is re-checked after a failed reset_queues_mes(); reset_queues_mes() fills gang_context_array_index and ticket; the post-recovery explicit removal moves into reset_queues_mes() and remove_all_kfd_queues_mes() keys on kfd_mes_queue_retired().

4/9: kgd2kfd_teardown_processes() always retires and waits;
     reset_queue_mes() skips set_queue_as_reset() for zombies;
     svms.restore_work is cancelled in the notifier release;
     kfd_queue_ref_bo_vas() is dropped.

5/9: a quarantined create failure keeps its own references on the user
buffers, zombie_no_user_bos goes away; create_queue_cpsch() clears is_active in the cleanup path; pqm_destroy_queue() unrefs the VAs after the dqm dequeued the queue, no re-ref; new small patch for the kfd_dqm_suspend_bad_queue_mes() double decrement.
6/9: kfd_process_evict_queues() keeps -EIO across pdds; a failed restore
rolls back the queues restored in that attempt; count before add_queue_mes() and undo on failure.
7/9: new properties travel in mqd_update_info, q->pending_props is
removed; the NO_HWS stopped case returns -EBUSY.
8/9: the deactivate/evict branch is dropped and replaced by a warning;
commit message reworded.

Left for separate patches, all pre-existing: the lock order between the KGD and KFD per-queue reset paths (two findings), has_reset_queue tested after the unmap in update_queue_locked(), context id 0 freed on alloc failure in create_process(), queue_refcount on a mapping without a BO.

v2 follows once the retest on the dual R9700 box is done.

Regards,
Armas Spann <[email protected]>