Skip to contentSkip to conversation

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

PATCH New Armas Spann 2 participants 15 messages Nov 26

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

v2 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):

- F5-TTS dual-GPU training (batch 4 + grad accum 2): 30 min,

    500+ updates, 2.93s/update, both GPUs 100%, stable
  - F5-TTS dual-GPU training (default frame batching, pretrained
    weights): 10 min, 319 updates, 1.58s/update, both GPUs 100%

- 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
- VRAM usage stable at 65% throughout, no OOM under normal batch sizes

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       |  85 ++
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h       |  53 ++
 drivers/gpu/drm/amd/amdgpu/mes_v11_0.c        |  54 +-
 drivers/gpu/drm/amd/amdgpu/mes_v12_0.c        |  55 +-
 drivers/gpu/drm/amd/amdgpu/mes_v12_1.c        |  89 ++-
 drivers/gpu/drm/amd/amdkfd/kfd_device.c       |  42 +-
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 747 ++++++++++++++++--
 .../drm/amd/amdkfd/kfd_device_queue_manager.h |  31 +
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  48 ++
 drivers/gpu/drm/amd/amdkfd/kfd_process.c      |  64 +-
 .../amd/amdkfd/kfd_process_queue_manager.c    | 183 +++--
 drivers/gpu/drm/amd/amdkfd/kfd_queue.c        |  63 +-
 14 files changed, 1460 insertions(+), 154 deletions(-)

Changes v1 -> v2:

Addresses the review of v1. Nine patches as before, the fixes went into the patches that introduced the problems.

1/9 drm/amdgpu/mes: distinguish rejected from timed out commands
- mes.fw_gen is one counter per XCC, incremented in the xcc_hw_init of each MES version; a ticket records the XCC it was submitted on and the poll compares against that entry
- mes_v12_1 reads the status slot as 64 bits and prints the firmware error code in the upper half; it was read as 32 bits, so the code the patch set out to print was never seen there
- dma_rmb() between the fence and the status read in amdgpu_mes_ticket_poll() and after the fence poll in the three submit paths

3/9 drm/amdkfd: track whether MES knows each queue
- fence MES on a timed out ADD_QUEUE, as the REMOVE path does
- a removal that cannot be sent because the scheduler is halted or stopped returns -EIO for a queue MES still has, instead of success; the is_reset shortcut is gone
- reset_queue_mes() looks at the result of the remove-after-reset:
a timeout fences MES and fails the per-queue reset so that the caller escalates to a GPU reset, a rejection keeps the queue UNKNOWN as before
- after the grace period, a REMOVE_QUEUE that is still unanswered fences MES and escalates directly; reset_queues_mes() and its three commands only run when MES answered
- __remove_queue_mes() retires a queue whose earlier REMOVE_QUEUE completed between the caller's check and its own, instead of sending a duplicate; after a failed reset_queues_mes() the retired state is re-checked before escalating
- reset_queues_mes() fills gang_context_array_index and the ticket of the REMOVE_QUEUE it hands to amdgpu_gfx_reset_mes_compute(), and refuses to run behind an unanswered command
- the explicit removal of a queue the recovery left in MES moved from remove_queue_mes_on_reset_option() into reset_queues_mes(), so kfd_dqm_suspend_bad_queue_mes() gets it too
- remove_all_kfd_queues_mes() keys on kfd_mes_queue_retired() instead of is_active, like the other teardown paths

4/9 drm/amdkfd: add a quarantine for queues MES has not retired
- kgd2kfd_teardown_processes() retires the queues and waits for the processes also when the process table is already empty; a process with zombies leaves the table before it is freed
- a per-queue reset of a zombie does the MES side only and skips set_queue_as_reset(): no counter change, no has_reset_queue and no is_reset for a queue the process no longer owns
- cancel svms.restore_work in the notifier release, next to the other works of the process, instead of in the deferred release
- kfd_queue_ref_bo_vas() dropped (see 5/9)

5/9 drm/amdkfd: keep queue storage until MES confirmed retirement
- pqm_destroy_queue() drops the bo_va queue_refcounts once, after the dqm has dequeued the queue, instead of before the destroy with a re-ref on failure; a second destroy of a queue id while the first one sleeps on a suspended queue no longer leaves one count too many
- a queue quarantined from a failed create takes its own references on the ring, pointer, EOP and CWSR buffers (kfd_queue_hold_buffers()) before the ioctl drops its set; zombie_no_user_bos is gone and the reaper releases the buffers of every zombie
- the cleanup path of create_queue_cpsch() clears is_active after it decremented the count, so a later per-queue reset of the zombie cannot decrement it again
- kfd_dqm_suspend_bad_queue_mes() decrements the active count only if the reset it asked for has not done so already (pre-existing)
- kfd_queue_unref_bo_vas() reserves the VM without being interruptible, it runs after the queue is gone now

6/9 drm/amdkfd: keep eviction and restore consistent when MES fails
- kfd_process_evict_queues() returns -EIO when any device returned it, instead of the result of the last device (pre-existing)
- a failed restore_process_queues_cpsch() takes the queues restored in that attempt off the hardware again, so the process is fully evicted and the retry starts from a known state (pre-existing)
- a queue is counted before ADD_QUEUE is sent and taken out of the count on failure, so the GFX11 oversubscription check in add_queue_mes() sees it

7/9 drm/amdkfd: apply queue property updates only after unmap
- the new properties travel in struct mqd_update_info (new_props) with the update_queue() call, q->pending_props is gone; a perfcount update from another process can no longer apply, or race with, the properties of an update in flight
- update_queue_locked() returns -EBUSY for a no-HWS queue updated while the scheduler is stopped, instead of 0 with nothing applied

8/9 drm/amdkfd: reconcile queue state with MES after a restart
- the deactivate/evict branch is gone; the reconcile retires the stale MES state, releases lost tickets and lifts the fence, and warns if it finds a queue still marked active. Deactivation stays in set_queue_as_reset() and evict_process_queues_cpsch()
- commit message reworded accordingly

Unchanged: 2/9, 9/9.

Not addressed here, pre-existing and for separate patches: the lock order between the KGD and KFD per-queue reset paths (kfd_reset_queue_mes() without the dqm lock), has_reset_queue tested after the unmap in update_queue(), context id 0 freed on an allocation failure in create_process(), and the queue_refcount taken on a mapping without a BO in kfd_queue_buffer_get().

Signature · 1 line
2.47.3
#1 lore raw

PATCH v2 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.

mes_v12_1 read the status slot as 32 bits, so the error code in the upper half was never seen there. Read it as 64 bits like mes_v11_0 and mes_v12_0 do, and print both halves.

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 of an XCC 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 per XCC because on GC 12.1 every XCC runs its own scheduler instance; a ticket records the XCC it was submitted on. 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.

MES writes the status before the trailing fence. Read the status after the fence with a dma_rmb() in between, in the command path and in the ticket poll, so that a weakly ordered CPU cannot see the new fence together with the old status.

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 | 85 +++++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h | 53 +++++++++++++++
 drivers/gpu/drm/amd/amdgpu/mes_v11_0.c  | 54 +++++++++++++--
 drivers/gpu/drm/amd/amdgpu/mes_v12_0.c  | 55 +++++++++++++--
 drivers/gpu/drm/amd/amdgpu/mes_v12_1.c  | 89 ++++++++++++++++++++-----
 5 files changed, 308 insertions(+), 28 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +85 -0
index 7864afab5..7958e5a23 100644
@@ -141,6 +141,8 @@ int amdgpu_mes_init(struct amdgpu_device *adev)
 				adev->gfx.disable_kq ? 0 : adev->gfx.num_compute_rings);
 
 	adev->mes.adev = adev;
+	for (i = 0; i < AMDGPU_MAX_GC_INSTANCES; i++)
+		atomic_set(&adev->mes.fw_gen[i], 0);
 
 	ida_init(&adev->mes.doorbell_ida);
 	spin_lock_init(&adev->mes.queue_id_lock);
@@ -345,6 +347,89 @@ 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 != amdgpu_mes_fw_gen(&adev->mes, ticket->xcc_id))
+		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, and
+	 * do not let that look be satisfied by a load made before the fence
+	 * was seen.
+	 */
+	dma_rmb();
+	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 != amdgpu_mes_fw_gen(&adev->mes, ticket->xcc_id))
+		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 +53 -0

77 lines not on this page · raw message

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

94 lines not on this page · raw message

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

101 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +73 -16

150 lines not on this page · raw message

Signature · 1 line
2.47.3
#2 lore raw

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

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] drm/amdgpu/mes: fence advances before fw_gen increment on MES reset/init - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] drm/amdgpu/mes: fence advances before fw_gen increment on MES reset/init
- [Medium] drm/amdgpu/mes: uninitialized ticket on ring-full timeout and poll check
--

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

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

This commit returns AMDGPU_MES_CMD_REJECTED (-EREMOTEIO) when MES responds to a command with a failure status instead of timing out, and adds a command ticket mechanism and per-XCC firmware generation counter to track timed-out REMOVE_QUEUE commands across late completions and MES restarts.

Quoted 4 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +0 -0
index b71684d79b21a..c7beee52a790b 100644

[ ... ]

Quoted 38 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +34 -0
@@ -329,6 +331,89 @@ 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 != amdgpu_mes_fw_gen(&adev->mes, ticket->xcc_id))
+		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;

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

Quoted 10 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +10 -0
+
+	/*
+	 * MES writes the status before the trailing fence. Look again, and
+	 * do not let that look be satisfied by a load made before the fence
+	 * was seen.
+	 */
+	dma_rmb();
+	return lower_32_bits(READ_ONCE(*status)) ?
+		AMDGPU_MES_TICKET_DONE : AMDGPU_MES_TICKET_FAILED;
+}

[Severity: Medium]
Can amdgpu_mes_ticket_poll() misreport a stale ticket as AMDGPU_MES_TICKET_FAILED across a reset or MES re-initialization?

Both during GPU reset and during MES hardware initialization, the scheduler ring's trailing fence advances to or past ticket->seq before adev->mes.fw_gen[xcc_id] is incremented:

1. In amdgpu_device_pre_asic_reset(), amdgpu_fence_driver_force_completion() writes ring->fence_drv.sync_seq (>= ticket->seq) to *ring->fence_drv.cpu_addr before MES is suspended or re-initialized.
2. In mes_v11_0_hw_init(), mes_v12_0_hw_init(), and mes_v12_1_xcc_hw_init(), mes_v*_queue_init() clears the scheduler ring and mes_v*_set_hw_resources() submits a command on that ring that waits for the new MES instance to write a new sequence number (> ticket->seq) to *ring->fence_drv.cpu_addr before atomic_inc() updates fw_gen.

CPU0 CPU1
amdgpu_mes_ticket_poll() mes_v12_0_hw_init()

                                        mes_v12_0_queue_init()
                                          amdgpu_ring_clear_ring()
                                        mes_v12_0_set_hw_resources()
                                          /* fence advances past ticket->seq */
  ticket->fw_gen == fw_gen
  amdgpu_mes_fence_passed() == true
  *status == 0
  return AMDGPU_MES_TICKET_FAILED;  <-- stale ticket reported as failed
                                        atomic_inc(&adev->mes.fw_gen[0]);

Because *status is still 0 after the unanswered command was wiped, amdgpu_mes_ticket_poll() returns AMDGPU_MES_TICKET_FAILED instead of AMDGPU_MES_TICKET_STALE, and amdgpu_mes_ticket_answered() returns true before MES is halted or fw_gen reflects the new instance. In addition, amdgpu_mes_ticket_poll() does not re-check fw_gen after observing amdgpu_mes_fence_passed(), and mes_v*_submit_pkt_ticket() records ticket->fw_gen after the 2.1s poll timeout rather than under ring_lock at submission time.

Quoted 35 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +19 -0
+
+/**
+ * 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 != amdgpu_mes_fw_gen(&adev->mes, ticket->xcc_id))
+		return true;
+
+	return amdgpu_mes_fence_passed(&adev->mes.ring[ticket->ring_idx],
+				       ticket->seq);
+}
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +4 -3
index 5c046f64b0229..5fabf05d5584a 100644
@@ -154,9 +154,10 @@ static const char *mes_v12_1_get_misc_op_string(union MESAPI__MISC *x_pkt)
 	return op_str;
 }
 
-static int mes_v12_1_submit_pkt_and_poll_completion(struct amdgpu_mes *mes,
-					    int xcc_id, int pipe, void *pkt,
-					    int size, int api_status_off)
+static int mes_v12_1_submit_pkt_ticket(struct amdgpu_mes *mes,
+				       int xcc_id, int pipe, void *pkt,
+				       int size, int api_status_off,
+				       struct amdgpu_mes_cmd_ticket *ticket)
 {

[ ... ]

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

Quoted 9 lines
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +3 -1
@@ -200,8 +201,10 @@ static int mes_v12_1_submit_pkt_and_poll_completion(struct amdgpu_mes *mes,
 	r = amdgpu_fence_wait_polling(ring,
 				      seq - ring->fence_drv.num_fences_mask,
 				      timeout);
-	if (r < 1)
+	if (r < 1) {
+		r = -ETIMEDOUT;
 		goto error_undo;
+	}

[Severity: Medium]
What happens to *ticket when mes_v11_0_submit_pkt_ticket(), mes_v12_0_submit_pkt_ticket(), or mes_v12_1_submit_pkt_ticket() returns -ETIMEDOUT on the error_undo path because the ring is full?

On that path the command is undone with amdgpu_ring_undo(), status_offset is freed, and the function returns -ETIMEDOUT without initializing or clearing *ticket. A caller that receives -ETIMEDOUT from remove_hw_queue() and inspects the ticket will either read uninitialized fields or, if the ticket was zeroed by the caller, see ticket->valid == false (which makes amdgpu_mes_ticket_poll() return AMDGPU_MES_TICKET_STALE) and ticket->fw_gen == 0 (which makes amdgpu_mes_ticket_answered(), as it does not check ticket->valid, compare 0 against fw_gen >= 1 and return true, or index adev->mes.fw_gen[ticket->xcc_id] and adev->mes.ring[ticket->ring_idx] with untrusted values).

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

PATCH v2 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.47.3
#4 lore raw

PATCH v2 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.
- The recovery path is only entered when MES answered. If the command is still unanswered after the grace period, the three commands the recovery would send would each time out behind it; MES is fenced off instead and the GPU reset takes over.
- When the recovery path returns success and the queue is still in MES, it is removed explicitly. Both callers of reset_queues_mes() get that, the one that answers a bad queue interrupt included.
- 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. This covers ADD_QUEUE and the remove-after-reset of a per-queue reset as well; the latter fails the per-queue reset when MES did not answer, so that every caller escalates to a GPU reset.
- A removal that cannot be sent because the scheduler is halted or stopped reports -EIO for a queue MES still has, instead of success. The callers keep the storage of such a queue and leave its MQD alone. The is_reset shortcut goes away with it: the retired check already covers a queue the reset removed, and for one it did not, the shortcut was wrong.
- update_queue() does not rewrite the MQD of an inactive queue whose removal is unconfirmed.
- The REMOVE_QUEUE that amdgpu_gfx_reset_mes_compute() sends on behalf of KFD carries the gang context array index and the ticket of the queue like every other one.

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

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 341 +++++++++++++++++-
 .../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, 357 insertions(+), 17 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +324 -17
index 03d3a739d..550ad428e 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,129 @@ 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.
+ */
+
+/* Generation of the scheduler instance this node talks to */
+static u32 kfd_mes_gen(struct device_queue_manager *dqm)
+{
+	return amdgpu_mes_fw_gen(&dqm->dev->adev->mes,
+				 ffs(dqm->dev->xcc_mask) - 1);
+}
+
+/*
+ * 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;
+}
+
+/* True while a REMOVE_QUEUE for @q is in the MES ring without an answer */
+static bool kfd_mes_ticket_pending(struct device_queue_manager *dqm,
+				   struct queue *q)
+{
+	return q->mes_ticket.valid &&
+	       amdgpu_mes_ticket_poll(dqm->dev->adev, &q->mes_ticket) ==
+	       AMDGPU_MES_TICKET_PENDING;
+}
+
+/*
+ * 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)
+{
+	dqm->mes_fenced = true;
+	dqm->mes_fence_gen = kfd_mes_gen(dqm);
+	dqm->mes_fence_has_seq = kfd_mes_ticket_pending(dqm, q);
+	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 (!kfd_mes_ticket_pending(dqm, q))
+			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 +339,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,14 +404,30 @@ 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);
 		dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
+		/*
+		 * No answer: anything sent from now on would time out behind
+		 * this command. ADD_QUEUE carries no ticket, so the fence is
+		 * lifted by the firmware restart that the GPU reset asked for
+		 * here performs. A rejection means MES answers, no fence.
+		 */
+		if (r == -ETIMEDOUT)
+			kfd_mes_fence(dqm, q);
 		kfd_hws_hang(dqm);
 		return r;
 	}
@@ -299,24 +449,41 @@ 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 0 without sending anything when MES has let go of the queue
+ * since the caller looked, -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)
+	/* An earlier REMOVE_QUEUE completed late: a second one is rejected */
+	if (kfd_mes_queue_retired(dqm, q))
 		return 0;
 
-	if (!dqm->sched_running || dqm->sched_halt)
-		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 (kfd_mes_ticket_pending(dqm, q))
+		return -ETIMEDOUT;
+
 	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,19 +491,91 @@ 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);
 
-	/* If is_for_reset set, it is a mes internal cleanup */
-	if (!r || is_for_reset)
+	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;
+
+	/*
+	 * Nothing can be sent while the scheduler is stopped or halted, and
+	 * MES still has the queue. Say so rather than report success: the
+	 * caller then keeps the storage of the queue and leaves its MQD
+	 * alone, and the removal is sent once the scheduler runs again.
+	 */
+	if (!dqm->sched_running || dqm->sched_halt)
+		return -EIO;
+
+	r = __remove_queue_mes(dqm, q, flush_mes_queue);
+	if (!r)
+		return 0;
+
+	if (r == -ETIMEDOUT) {
+		/* Not answered yet. The command is still queued and may complete. */
+		if (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;
+		}
+
+		/*
+		 * Still no answer. MES is not working its ring, and the
+		 * recovery below would only queue three more commands behind
+		 * the unanswered one, each to time out under the dqm lock.
+		 * Stop talking to MES and leave it to the GPU reset.
+		 */
+		if (kfd_mes_ticket_pending(dqm, q))
+			goto hang;
+
+		/* Answered after all, with a failure: a hung queue */
+		r = AMDGPU_MES_CMD_REJECTED;
+	}
+
+	/*
+	 * -EIO: nothing was sent, a GPU reset is under way or MES is fenced
+	 * off. is_for_reset: the cleanup after a per-queue reset, the caller
+	 * decides what its failure means.
+	 */
+	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) {
+	if (!r)
+		return 0;
+
+	/* MES let go of the queue in the meantime, whatever else failed */
+	if (kfd_mes_queue_retired(dqm, q))
+		return 0;
+
+hang:
+	if (r == -ETIMEDOUT || kfd_mes_ticket_pending(dqm, q))
+		kfd_mes_fence(dqm, q);
+
+	/* The caller of a remove-after-reset decides what a failure means */
+	if (is_for_reset)
+		return r;
+
+	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");
@@ -372,7 +611,8 @@ static int remove_all_kfd_queues_mes(struct device_queue_manager *dqm)
 	list_for_each_entry(cur, &dqm->queues, list) {
 		qpd = cur->qpd;
 		list_for_each_entry(q, &qpd->queues_list, list) {
-			if (q->properties.is_active) {
+			/* An inactive queue can be in MES after a failed evict */
+			if (!kfd_mes_queue_retired(dqm, q)) {
 				retval = remove_queue_mes(dqm, q, qpd);
 				if (retval) {
 					dev_err(dev, "%s: Failed to remove queue %d for dev %d",
@@ -435,9 +675,22 @@ static int reset_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 						ffs(dqm->dev->xcc_mask) - 1);
 	if (r)
 		return r;
-	/* Proceed remove_queue with reset=true */
-	remove_queue_mes_on_reset_option(dqm, q, &pdd->qpd, true, true);
+	/*
+	 * Proceed remove_queue with reset=true. Its result matters: a
+	 * REMOVE_QUEUE that MES did not answer fails this reset, so that the
+	 * caller escalates to a GPU reset instead of sending more commands
+	 * behind it. A rejected cleanup does not fail it, MES answers and
+	 * the queue itself has been reset; the queue stays UNKNOWN and keeps
+	 * its storage until MES is restarted.
+	 */
+	r = remove_queue_mes_on_reset_option(dqm, q, &pdd->qpd, true, true);
 	set_queue_as_reset(dqm, q, &pdd->qpd, true);
+	if (r == -ETIMEDOUT)
+		return r;
+	if (r)
+		dev_warn(adev->dev,
+			 "MES did not remove reset queue doorbell=0x%x (%d), keeping its storage\n",
+			 q->properties.doorbell_off, r);
 	return 0;
 }
 
@@ -476,16 +729,50 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 		goto fail;
 	}
 
+	/* Gone from MES in the meantime, nothing left to reset */
+	if (kfd_mes_queue_retired(dqm, q))
+		return 0;
+
+	/*
+	 * SUSPEND, DETECT_AND_RESET and RESUME would each time out behind
+	 * a command that MES has not answered.
+	 */
+	if (kfd_mes_fenced(dqm)) {
+		r = -EIO;
+		goto fail;
+	}
+	if (kfd_mes_ticket_pending(dqm, q)) {
+		r = -ETIMEDOUT;
+		goto fail;
+	}
+	/* An earlier REMOVE_QUEUE for @q was answered, its slot can go */
+	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;
 	queue_input.queue_type = convert_to_amdgpu_ring_type(q->properties.type);
 	queue_input.remove_queue_after_reset = false;
 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
+	queue_input.gang_context_array_index = q->gang_ctx_array_index;
+	/* The REMOVE_QUEUE sent from there can be left unanswered like any */
+	queue_input.ticket = &q->mes_ticket;
 	/* 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.
+	 */
+	if (!num_hung)
+		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);
@@ -508,6 +795,17 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	}
 	amdgpu_vm_put_task_info(ti);
 
+	/*
+	 * MES reported other queues as hung, reset those and resumed the
+	 * rest, @q among them: amdgpu_gfx_reset_mes_compute() removes the
+	 * queue it was given only when nothing was reported hung. Both
+	 * callers want @q out of MES, so remove it now that the scheduler
+	 * answers again. If @q itself was among the hung queues, the
+	 * per-queue reset has removed it already and it is retired.
+	 */
+	if (num_hung && !kfd_mes_queue_retired(dqm, q))
+		r = __remove_queue_mes(dqm, q, false);
+
 fail:
 	dqm->detect_hang_count = 0;
 	return r;
@@ -1147,6 +1445,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.47.3
#5 lore raw

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

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [High] drm/amdkfd: timeout misclassified in remove_queue_mes_on_reset_option() - [High] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [High] drm/amdkfd: timeout misclassified in remove_queue_mes_on_reset_option()
- [High] drm/amdkfd: duplicate REMOVE_QUEUE after reset in reset_queues_mes()
- [High] drm/amdkfd: unhandled reset_queues_mes() error on bad-queue interrupt
- [High] drm/amdkfd: clobbered fence and lost timeout in reset_queues_mes() recovery
- [Medium] drm/amdkfd: unlocked MES state access in kfd_reset_queue_mes()
- [Medium] drm/amdkfd: unhalt and restore skip queues left in KFD_MES_QUEUE_MAPPED
- [Low] drm/amdkfd: enum kfd_mes_queue_state detaches struct queue kernel-doc
--

commit 137dde38b7013d2a238e16d0644e2b934e97ed33
Author: Armas Spann <[email protected]>

drm/amdkfd: track whether MES knows each queue

This commit tracks per-queue MES mapping state, firmware generation, and pending removal tickets in KFD so queue add, remove, and reset paths can check whether MES still references a queue and fence off MES after an unanswered command.

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

[ ... ]

Quoted 1 line
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
@@ -324,19 +491,91 @@ static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, st

[ ... ]

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+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))

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 525

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+		return 0;
+
+	/*
+	 * Nothing can be sent while the scheduler is stopped or halted, and
+	 * MES still has the queue. Say so rather than report success: the
+	 * caller then keeps the storage of the queue and leaves its MQD
+	 * alone, and the removal is sent once the scheduler runs again.
+	 */
+	if (!dqm->sched_running || dqm->sched_halt)
+		return -EIO;

[Severity: Medium]
Does an evicted queue whose removal fails with -EIO ever get removed or re-added when the scheduler runs again?

When remove_queue_mes_on_reset_option() or __remove_queue_mes() returns -EIO during evict_process_queues_cpsch() (for example while halted, fenced, or when down_read_trylock(&adev->reset_domain->sem) fails during a soft reset), q->properties.is_active is cleared while q->mes_state remains KFD_MES_QUEUE_MAPPED. On unhalt, add_all_kfd_queues_mes() skips inactive queues instead of removing ones where !kfd_mes_queue_retired(dqm, q), leaving the evicted queue mapped in MES. When restore_process_queues_cpsch() later updates qpd->page_table_base and calls add_queue_mes(), add_queue_mes() sees q->mes_state == KFD_MES_QUEUE_MAPPED and returns 0 without re-adding the queue with the new page table base.

Quoted 16 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +16 -0
+
+	r = __remove_queue_mes(dqm, q, flush_mes_queue);
+	if (!r)
+		return 0;
+
+	if (r == -ETIMEDOUT) {
+		/* Not answered yet. The command is still queued and may complete. */
+		if (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;
+		}
+
+		/*
+		 * Still no answer. MES is not working its ring, and the

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 551

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+		 * recovery below would only queue three more commands behind
+		 * the unanswered one, each to time out under the dqm lock.
+		 * Stop talking to MES and leave it to the GPU reset.
+		 */
+		if (kfd_mes_ticket_pending(dqm, q))
+			goto hang;
+
+		/* Answered after all, with a failure: a hung queue */
+		r = AMDGPU_MES_CMD_REJECTED;
+	}

[Severity: High]
Can this overwrite -ETIMEDOUT with AMDGPU_MES_CMD_REJECTED when the MES ring is full or when the ticket completes between checks?

__remove_queue_mes() calls amdgpu_mes_ticket_release(adev, &q->mes_ticket) before adev->mes.funcs->remove_hw_queue(). If the MES ring is full, mes_v11_0_submit_pkt_ticket(), mes_v12_0_submit_pkt_ticket(), and mes_v12_1_submit_pkt_ticket() time out waiting for ring space and jump to error_undo without setting ticket->valid = true:

drivers/gpu/drm/amd/amdgpu/mes_v12_1.c:mes_v12_1_submit_pkt_ticket() {
    ...
	r = amdgpu_fence_wait_polling(ring,
				      seq - ring->fence_drv.num_fences_mask,
				      timeout);
	if (r < 1) {
		r = -ETIMEDOUT;
		goto error_undo;
	}
    ...
}

Because q->mes_ticket.valid is false, kfd_mes_wait_retired() and kfd_mes_ticket_pending() both return false, so r is overwritten with AMDGPU_MES_CMD_REJECTED. When is_for_reset is true, reset_queue_mes() sees AMDGPU_MES_CMD_REJECTED instead of -ETIMEDOUT and returns 0 without fencing MES or escalating to a GPU reset; when is_for_reset is false, it enters reset_queues_mes() and queues three more commands into the full ring under dqm_lock.

The same fallthrough happens if q->mes_ticket transitions to AMDGPU_MES_TICKET_DONE in the window between kfd_mes_queue_retired() and kfd_mes_ticket_pending(), treating a completed removal as AMDGPU_MES_CMD_REJECTED and releasing the completed ticket in reset_queues_mes() or __remove_queue_mes() without marking the queue retired.

Quoted 11 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +11 -0
+
+	/*
+	 * -EIO: nothing was sent, a GPU reset is under way or MES is fenced
+	 * off. is_for_reset: the cleanup after a per-queue reset, the caller
+	 * decides what its failure means.
+	 */
+	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);

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	if (!r)
+		return 0;
+
+	/* MES let go of the queue in the meantime, whatever else failed */
+	if (kfd_mes_queue_retired(dqm, q))
+		return 0;
+
+hang:
+	if (r == -ETIMEDOUT || kfd_mes_ticket_pending(dqm, q))
+		kfd_mes_fence(dqm, q);

[Severity: High]
What happens here when reset_queues_mes(dqm, q) fails with -ETIMEDOUT while resetting a different hung queue q2?

During amdgpu_gfx_reset_mes_compute(), the loop over num_hung calls reset_queue_mes() -> remove_queue_mes_on_reset_option(dqm, q2, ..., true, true) for each hung queue. If q2's remove-after-reset times out, that inner call runs kfd_mes_fence(dqm, q2) and returns -ETIMEDOUT without calling kfd_hws_hang(dqm).

If @q was already reset and retired in an earlier iteration of the num_hung loop before q2 timed out, kfd_mes_queue_retired(dqm, q) is true in the outer remove_queue_mes_on_reset_option() and it returns 0 before reaching hang:, silently dropping q2's timeout and leaving dqm->mes_fenced set with no GPU reset scheduled. If @q was not retired, the outer call reaches hang: with r == -ETIMEDOUT and calls kfd_mes_fence(dqm, q); because @q's ticket was released at the start of reset_queues_mes(), kfd_mes_fence(dqm, q) sets dqm->mes_fence_has_seq = false and wipes out q2's recorded fence ticket.

[ ... ]

Quoted 14 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +8 -2
@@ -435,9 +675,22 @@ static int reset_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 						ffs(dqm->dev->xcc_mask) - 1);
 	if (r)
 		return r;
-	/* Proceed remove_queue with reset=true */
-	remove_queue_mes_on_reset_option(dqm, q, &pdd->qpd, true, true);
+	/*
+	 * Proceed remove_queue with reset=true. Its result matters: a
+	 * REMOVE_QUEUE that MES did not answer fails this reset, so that the
+	 * caller escalates to a GPU reset instead of sending more commands
+	 * behind it. A rejected cleanup does not fail it, MES answers and
+	 * the queue itself has been reset; the queue stays UNKNOWN and keeps
+	 * its storage until MES is restarted.
+	 */

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -0
+	r = remove_queue_mes_on_reset_option(dqm, q, &pdd->qpd, true, true);
 	set_queue_as_reset(dqm, q, &pdd->qpd, true);
+	if (r == -ETIMEDOUT)
+		return r;
+	if (r)
+		dev_warn(adev->dev,
+			 "MES did not remove reset queue doorbell=0x%x (%d), keeping its storage\n",
+			 q->properties.doorbell_off, r);
 	return 0;
 }

[Severity: Medium]
Can reset_queue_mes() access q->mes_state, q->mes_ticket, and dqm->mes_fenced without holding dqm_lock(dqm)?

When amdgpu_gfx_reset_mes_compute() is called from gfx_v11_0_reset_kcq(), gfx_v12_0_reset_kcq(), or amdgpu_userq_reset_work() and MES detects a hung KFD queue, it calls amdgpu_amdkfd_reset_mes_queue() -> kfd_reset_queue_mes() -> reset_queue_mes() holding only adev->gfx.mec.reset_mutex:

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

    ...                                   remove_queue_mes(dqm, q, qpd)
      kfd_reset_queue_mes()                 __remove_queue_mes()
        reset_queue_mes()                     amdgpu_mes_ticket_release()
          remove_queue_mes_on_reset_option()
            __remove_queue_mes()
              amdgpu_mes_ticket_release()  <-- data race on q->mes_ticket

Concurrent KFD queue operations under dqm_lock(dqm) can race on q->mes_ticket (corrupting or double-freeing the writeback slot in adev->wb), q->mes_state, and dqm->mes_fenced.

Quoted 1 line
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
@@ -476,16 +729,50 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)

[ ... ]

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

Quoted 9 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +5 -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;
+	}

[Severity: High]
When kfd_dqm_suspend_bad_queue_mes() calls reset_queues_mes(), how does a timeout in reset_queues_mes() fence MES or escalate to a GPU reset?

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:kfd_dqm_suspend_bad_queue_mes() {
    ...
			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() ignores the return value of reset_queues_mes(). If a per-queue remove-after-reset inside amdgpu_gfx_reset_mes_compute() times out, remove_queue_mes_on_reset_option(..., is_for_reset = true) sets dqm->mes_fenced = true and returns -ETIMEDOUT without calling kfd_hws_hang(dqm) (and amdgpu_gfx_reset_mes_compute() still sends amdgpu_mes_resume() at out: before returning). Because kfd_dqm_suspend_bad_queue_mes() drops the error, kfd_hws_hang(dqm) is never called, and every subsequent add_queue_mes() or remove_queue_mes() sees kfd_mes_fenced(dqm) and returns -EIO without triggering a GPU reset, leaving the node permanently wedged. Timeouts in the other MES calls inside reset_queues_mes() (such as remove_hw_queue() when !num_hung or __remove_queue_mes() when num_hung > 0) also return without waiting the grace period, fencing MES, or calling kfd_hws_hang(dqm) on this path.

[ ... ]

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
@@ -508,6 +795,17 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	}
 	amdgpu_vm_put_task_info(ti);
 

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	/*
+	 * MES reported other queues as hung, reset those and resumed the
+	 * rest, @q among them: amdgpu_gfx_reset_mes_compute() removes the
+	 * queue it was given only when nothing was reported hung. Both
+	 * callers want @q out of MES, so remove it now that the scheduler
+	 * answers again. If @q itself was among the hung queues, the
+	 * per-queue reset has removed it already and it is retired.
+	 */
+	if (num_hung && !kfd_mes_queue_retired(dqm, q))
+		r = __remove_queue_mes(dqm, q, false);

[Severity: High]
What if @q was among the hung queues and MES rejected its remove-after-reset in reset_queue_mes()?

In that case reset_queue_mes() warns, sets q->properties.is_reset = true, leaves q->mes_state as KFD_MES_QUEUE_UNKNOWN, and returns 0 so the per-queue reset succeeds without escalating to a GPU reset. Because kfd_mes_queue_retired(dqm, q) is still false, reset_queues_mes() then sends a second __remove_queue_mes(dqm, q, false) with remove_queue_after_reset = false; when that also fails, reset_queues_mes() returns the error to remove_queue_mes_on_reset_option(), which calls kfd_hws_hang(dqm) and triggers a full GPU reset. Likewise, because the q->properties.is_reset check was removed from remove_queue_mes_on_reset_option(), remove_all_kfd_queues_mes() on halt or stop will also call remove_queue_mes() on any reset queue whose remove-after-reset was rejected.

Quoted 6 lines
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +0 -0
index a725fde9f11bd..8a506501a5349 100644
@@ -616,6 +616,13 @@ struct mqd_update_info {
  *

drivers/gpu/drm/amd/amdkfd/kfd_priv.h struct mqd_update_info { · line 626

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +7 -0
  */
 
+/* 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 {

[Severity: Low]
Placing enum kfd_mes_queue_state between the struct queue kernel-doc comment and struct queue detaches the comment from the struct and triggers a scripts/kernel-doc warning.

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

PATCH v2 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.

MES can report a quarantined queue as hung. The per-queue reset then does the MES side for it, the reset and the removal, and leaves the process alone: the queue is not counted any more, and the process is not marked as having a reset queue for one it no longer owns.

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.

The SVM restore work of the process was cancelled in the release worker, which now runs an unbounded time after the notifier release. Cancel it in the notifier release with the other works of the process, before the mm it would look up can be a different one.

Device removal must not wait for MES. kgd2kfd_teardown_processes() declares every queue of the device retired and waits for the processes to go, whether the process table still lists any or not: a process that has exited is off the table while its zombies keep it alive.

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

---
 drivers/gpu/drm/amd/amdkfd/kfd_device.c       |  16 +-
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 163 +++++++++++++++++-
 .../drm/amd/amdkfd/kfd_device_queue_manager.h |  14 ++
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  25 +++
 drivers/gpu/drm/amd/amdkfd/kfd_process.c      |  57 +++++-
 5 files changed, 260 insertions(+), 15 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device.c +11 -5
index edafbd937..f631047e8 100644
@@ -1805,11 +1805,6 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)
 
 	mutex_lock(&kfd_processes_mutex);
 
-	if (hash_empty(kfd_processes_table)) {
-		mutex_unlock(&kfd_processes_mutex);
-		return;
-	}
-
 	hash_for_each_safe(kfd_processes_table, temp, p_temp, p, kfd_processes) {
 		for (int i = 0; i < p->n_pdds; i++) {
 			dev = p->pdds[i]->dev;
@@ -1824,6 +1819,17 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)
 	if (!adev->kfd.dev)
 		return;
 
+	/*
+	 * Queues that MES never confirmed as removed keep their process
+	 * alive, and such a process is counted in kfd_processes_count after
+	 * it has left the table. The device is going away, so stop waiting
+	 * for MES, whether the table is empty or not.
+	 */
+	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 +162 -1

205 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 +25 -0
index b5eae33d8..711779665 100644
@@ -658,6 +658,19 @@ 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;
+	/* 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 +976,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;
 
 	/*
@@ -1446,6 +1470,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 +48 -9

92 lines not on this page · raw message

Signature · 1 line
2.47.3
#7 lore raw

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

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [High] drm/amdkfd: unlocked zombie_queues traversal in find_queue_by_doorbell_offset() - [High] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [High] drm/amdkfd: unlocked zombie_queues traversal in find_queue_by_doorbell_offset()
- [High] drm/amdkfd: unsignaled eviction fence and context_id alias on zombie wait
- [Medium] drm/amdkfd: per-process mes_hold stalls teardown on other GPUs
- [Medium] drm/amdkfd: cancel_delayed_work_sync() on uninitialized svms.restore_work
- [Medium] drm/amdkfd: restore_userptr_work not cancelled on notifier release
- [Medium] drm/amdkfd: svm_range_evict() can re-queue restore_work after notifier release
--

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

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

This commit introduces a per-device zombie queue list and a delayed reaper work item to hold queue and process storage until MES confirms that a destroyed queue has been retired.

Quoted 12 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +4 -0
index edafbd9377b5d..f631047e88b9d 100644
@@ -1824,6 +1819,17 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)
 	if (!adev->kfd.dev)
 		return;
 
+	/*
+	 * Queues that MES never confirmed as removed keep their process
+	 * alive, and such a process is counted in kfd_processes_count after
+	 * it has left the table. The device is going away, so stop waiting

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +7 -0
+	 * for MES, whether the table is empty or not.
+	 */
+	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: Medium]
Can an unretired zombie queue on another GPU cause kgd2kfd_teardown_processes() to spin forever on adev->kfd.dev->kfd_processes_count?

kfd_init_apertures() creates a PDD and increments kfd_processes_count on every GPU in the topology, while kfd_process_destroy_pdds() only decrements kfd_processes_count after p->mes_hold drops to zero for the whole process. If an exited process has a zombie queue on GPU B, kfd_dqm_retire_all() on GPU A does not retire GPU B's queue, so GPU A's kfd_processes_count never reaches zero and teardown of GPU A hangs waiting for GPU B.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index 646bc0ce05be8..0c72cf55224cc 100644

[ ... ]

Quoted 12 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -1
@@ -684,7 +688,13 @@ static int reset_queue_mes(struct device_queue_manager *dqm, struct queue *q,
 	 * its storage until MES is restarted.
 	 */
 	r = remove_queue_mes_on_reset_option(dqm, q, &pdd->qpd, true, true);
-	set_queue_as_reset(dqm, q, &pdd->qpd, true);
+	/*
+	 * A quarantined queue is destroyed as far as its process is
+	 * concerned: it is not counted, and the process is not punished
+	 * for a queue it no longer owns. Only the MES side was needed.
+	 */
+	if (!q->is_zombie)
+		set_queue_as_reset(dqm, q, &pdd->qpd, true);

[ ... ]

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

Quoted 12 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +6 -0
@@ -2993,6 +3143,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]
Can find_queue_by_doorbell_offset() and reset_queue_mes() race with kfd_dqm_zombie_worker() on dqm->zombie_queues and use a zombie queue after it is freed?

When amdgpu_gfx_reset_mes_compute() is called from KGD reset paths such as gfx_v11_0_reset_kcq(), gfx_v12_0_reset_kcq(), or amdgpu_userq_hang_detect_work(), only adev->gfx.mec.reset_mutex is held, not dqm_lock(dqm). kfd_reset_queue_mes() then walks dqm->zombie_queues and calls reset_queue_mes() without dqm_lock(dqm):

CPU0 CPU1 (kfd_dqm_zombie_worker)
amdgpu_gfx_reset_mes_compute()
...
kfd_reset_queue_mes()

    find_queue_by_doorbell_offset()
      /* walks dqm->zombie_queues
         without dqm_lock */
    reset_queue_mes(dqm, q, ...)
      remove_queue_mes_on_reset_option()
        q->mes_state = KFD_MES_QUEUE_UNMAPPED
                                      dqm_lock(dqm)
                                      kfd_mes_queue_retired(dqm, q) == true
                                      list_move_tail(&q->zombie_node, &retired)
                                      dqm_unlock(dqm)
                                      kfd_dqm_release_zombie(dqm, q)
                                        uninit_queue(q) /* frees q */
      if (!q->is_zombie)  <-- use-after-free

Even before reset_queue_mes() runs, walking dqm->zombie_queues in find_queue_by_doorbell_offset() without dqm_lock(dqm) races with dqm_quarantine_queue() and kfd_dqm_zombie_worker() modifying the list.

Quoted 38 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +9 -9
index 546721b4d59ac..51c3fa39fcc20 100644
@@ -1331,20 +1331,15 @@ static void kfd_process_wq_release(struct work_struct *work)
 					     release_work);
 	struct dma_fence *ef;
 
+	/* Second run, queued when the last quarantined queue was freed */
+	if (p->mes_hold_dropped)
+		goto release_storage;
+
 	/*
 	 * If GPU in reset, user queues may still running, wait for reset complete.
 	 */
 	kfd_process_wait_gpu_reset_complete(p);
 
-	/* Signal the eviction fence after user mode queues are
-	 * destroyed. This allows any BOs to be freed without
-	 * triggering pointless evictions or waiting for fences.
-	 */
-	synchronize_rcu();
-	ef = rcu_access_pointer(p->ef);
-	if (ef)
-		dma_fence_signal(ef);
-
 	if (p->context_id != KFD_CONTEXT_ID_PRIMARY)
 		kfd_process_free_id(p);
 	else
@@ -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

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +10 -0
+	 * 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;
+	}

[Severity: Medium]
When kfd_process_wq_release() returns early here, can p->kgd_process_info->restore_userptr_work keep running against a post-execve mm?

During exit_mmap(), mn_itree_release() invalidates userptr BOs and queues process_info->restore_userptr_work before mn_hlist_release() calls kfd_process_notifier_release_internal() and removes p from kfd_processes_table. Because restore_userptr_work is only cancelled in amdgpu_amdkfd_gpuvm_destroy_cb() during kfd_process_destroy_pdds(), deferring release_storage allows amdgpu_amdkfd_restore_userptr_worker() to look up process_info->pid after execve(), acquire the new mm, fail get_user_pages() on the old mm with -ESRCH, and reschedule itself every 10 ms against the new mm until all zombies retire.

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +10 -0
+
+release_storage:
+	/* Signal the eviction fence after user mode queues are
+	 * destroyed. This allows any BOs to be freed without
+	 * triggering pointless evictions or waiting for fences.
+	 */
+	synchronize_rcu();
+	ef = rcu_access_pointer(p->ef);
+	if (ef)
+		dma_fence_signal(ef);

[Severity: High]
Does deferring dma_fence_signal(ef) until release_storage stall in-flight TTM evictions and alias p->context_id while zombies are quarantined?

If TTM enabled signaling on p->ef before kfd_process_table_remove(p), amdkfd_fence_enable_signaling() scheduled p->eviction_work and returned true without signaling p->ef. kfd_process_notifier_release_internal() then cancels p->eviction_work, so returning early before dma_fence_signal(ef) leaves p->ef unsignaled with DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT set, stalling any TTM move job waiting on p->ef until every zombie queue retires.

In addition, for a secondary context, kfd_process_free_id(p) frees p->context_id before the early return while p->ef is still unsignaled and attached to p's BOs. If a new secondary context in the same mm reuses that context_id, a later eviction of the old context's BOs matches the new context in kfd_lookup_process_by_id(), evicting the new context while leaving the old p->ef unsignaled.

[ ... ]

drivers/gpu/drm/amd/amdkfd/kfd_process.c void kfd_process_notifier_release_internal(struct kfd_process *p) · line 1461

Quoted 9 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +5 -0
@@ -1422,6 +1454,12 @@ void kfd_process_notifier_release_internal(struct kfd_process *p)
 	kfd_process_table_remove(p);
 	cancel_delayed_work_sync(&p->eviction_work);
 	cancel_delayed_work_sync(&p->restore_work);
+	/*
+	 * Not left to svm_range_list_fini(): the release worker may now
+	 * run long after this, and the SVM restore work would look up the
+	 * mm of the lead thread, which can be a new one by then.
+	 */

[Severity: Medium]
Can svm_range_evict() re-queue p->svms.restore_work after cancel_delayed_work_sync() returns here?

prange->notifier is only unregistered in svm_range_list_fini() at release_storage, and mn_itree_release() leaves interval notifiers linked in the old mm until exit_mmap() finishes tearing down VMAs and page tables. Because svm_range_evict() ignores the -ESRCH return from kgd2kfd_quiesce_mm() and unconditionally queues svms->restore_work, any concurrent non-UNMAP invalidation on the old mm after this point can re-queue p->svms.restore_work, which then looks up p->lead_thread->mm after execve(). Using disable_delayed_work_sync(&p->svms.restore_work) (or checking r != -ESRCH in svm_range_evict()) would prevent it from being queued again.

drivers/gpu/drm/amd/amdkfd/kfd_process.c void kfd_process_notifier_release_internal(struct kfd_process *p) · line 1462

Quoted 1 line
drivers/gpu/drm/amd/amdkfd/kfd_process.c +1 -0
+	cancel_delayed_work_sync(&p->svms.restore_work);

[Severity: Medium]
Does calling cancel_delayed_work_sync(&p->svms.restore_work) unconditionally trigger WARN_ON(!work->func) in __flush_work() when CONFIG_HSA_AMD_SVM is disabled?

When CONFIG_HSA_AMD_SVM=n, svm_range_list_init() is a no-op stub and never initializes p->svms.restore_work, so every exiting KFD process hits the warning in __flush_work().

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

PATCH v2 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.

The user buffers of a queue go with it. pqm_destroy_queue() dropped the unmap protection of the ring, pointers, EOP and CWSR buffers before the queue was taken off the hardware, and took it back when that failed. While a debugger has the queue suspended the destroy sleeps without the locks, and a second destroy of the same queue id in that window ends with one unmap protection too many that nothing drops. Drop the references once, after the dqm has dequeued the queue. A quarantined queue keeps them until the reaper frees it. A quarantined queue from a failed create takes references of its own on the buffers, because the ioctl drops its set on the error path while the MQD keeps pointing at the buffers.

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

Three defects on the same paths are fixed along the way. Process termination and the cleanup of a failed create clear is_active when they deactivate a queue, so a per-queue reset later does not decrement the active count a second time, and kfd_dqm_suspend_bad_queue_mes() decrements only if the reset it asked for has not done so already. 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 and buffer references 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 | 109 +++++++++++++-----
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |   2 +
 .../amd/amdkfd/kfd_process_queue_manager.c    |  91 +++++++++++----
 drivers/gpu/drm/amd/amdkfd/kfd_queue.c        |  63 +++++++++-
 4 files changed, 216 insertions(+), 49 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +82 -27
index cb0263881..c691df753 100644
@@ -1341,6 +1341,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",
@@ -1777,9 +1778,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);
 
@@ -2962,8 +2963,21 @@ static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
 cleanup_queue:
 	qpd->queue_count--;
 	list_del(&q->list);
-	if (q->properties.is_active)
+	if (q->properties.is_active) {
 		decrement_queue_count(dqm, qpd, q);
+		/* Not counted any more, a reset must not count it down again */
+		q->properties.is_active = false;
+	}
+	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, the pqm
+		 * takes care of the user buffers.
+		 */
+		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:
@@ -3475,6 +3489,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) ||
@@ -3517,13 +3532,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);
@@ -3534,11 +3545,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--;
 
 	/*
@@ -3549,6 +3567,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);
 
 	/*
@@ -3559,9 +3592,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;
 
@@ -3767,20 +3802,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--;
@@ -3816,7 +3849,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);
@@ -4082,8 +4130,15 @@ int kfd_dqm_suspend_bad_queue_mes(struct kfd_node *knode, u32 pasid, u32 doorbel
 			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);
+				/*
+				 * When MES reported the queue itself as hung,
+				 * the per-queue reset has deactivated it and
+				 * counted it down already.
+				 */
+				if (q->properties.is_active) {
+					q->properties.is_active = false;
+					decrement_queue_count(dqm, qpd, q);
+				}
 				break;
 			}
 		}
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +2 -0
index 711779665..23fc74aa0 100644
@@ -1436,6 +1436,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);
+int kfd_queue_hold_buffers(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);
 
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +70 -21

119 lines not on this page · raw message

drivers/gpu/drm/amd/amdkfd/kfd_queue.c +62 -1

75 lines not on this page · raw message

Signature · 1 line
2.47.3
#9 lore raw

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

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] drm/amdkfd: unretired queue visibility gap in process_termination_cpsch() - [Medium] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] drm/amdkfd: unretired queue visibility gap in process_termination_cpsch()
- [Medium] drm/amdkfd: unbalanced SVM queue_refcount put when kfd_queue_hold_buffers() fails
--

commit 1de59d68e639f24ab5a36271e17baa8bd9d8fd34
Author: Armas Spann <[email protected]>

drm/amdkfd: keep queue storage until MES confirmed retirement

This commit quarantines queues whose retirement MES has not confirmed during queue creation error cleanup, queue destruction, and process termination, keeping their MQDs, IDs, and user buffer references until MES releases them.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index 0c72cf55224cc..eabb9a6953451 100644

[ ... ]

Quoted 13 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +8 -0
@@ -3813,7 +3846,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)) {

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -0
+			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);

[Severity: Medium]
Can an unretired queue in qpd->queues_list be missed by a concurrent MES per-queue reset while dqm_lock(dqm) is dropped to free an earlier retired queue's MQD?

process_termination_cpsch() unlinks qpd from dqm->queues before running this drain loop, and find_queue_by_doorbell_offset() only searches dqm->queues and dqm->zombie_queues:

CPU0 CPU1
process_termination_cpsch()
/* unlink qpd from dqm->queues */
/* q1 is retired, q2 is not */
list_del(&q1->list)
dqm_unlock(dqm)

                                      kfd_reset_queue_mes()
                                        dqm_lock(dqm)
                                        find_queue_by_doorbell_offset(..., q2)
                                          /* not in dqm->queues or
                                           * dqm->zombie_queues -> NULL
                                           */
                                        dqm_unlock(dqm)

mqd_mgr->free_mqd(..., q1->mqd, ...)
dqm_lock(dqm)
list_del(&q2->list)
dqm_quarantine_queue(dqm, qpd, q2)

If MES reports q2 as hung during that window, kfd_reset_queue_mes() fails to find q2 and skips resetting and removing it in MES. Moving unretired queues to dqm->zombie_queues before dropping dqm_lock(dqm), or unlinking qpd from dqm->queues after qpd->queues_list is drained, would keep q2 visible.

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

[ ... ]

Quoted 7 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +2 -1
@@ -518,7 +530,23 @@ int pqm_create_queue(struct process_queue_manager *pqm,
 	return retval;
 
 err_create_queue:
-	uninit_queue(q);
+	if (q && q->is_zombie) {
+		/*

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c int pqm_create_queue(struct process_queue_manager *pqm, · line 544

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +10 -0
+		 * The dqm still needs the MQD, the ids and what MES uses. The
+		 * user buffers are part of that: MES may yet execute the
+		 * ADD_QUEUE and run the queue from them. The ioctl drops its
+		 * references on them when this returns, so take our own. The
+		 * reaper drops them once MES has let go of the queue.
+		 */
+		if (kfd_queue_hold_buffers(pdd, &q->properties))
+			pr_warn("process pid %d: quarantined queue holds no reference on its CWSR area\n",
+				pqm->process->lead_thread->pid);
+		kfd_dqm_zombie_ready(dev->dqm, q);

[Severity: Medium]
If kfd_queue_hold_buffers() fails in kfd_queue_buffer_svm_get(), will the zombie reaper later underflow prange->queue_refcount?

When kfd_queue_hold_buffers() returns an error, no extra SVM reference is taken for the quarantined queue, and kfd_ioctl_create_queue() drops the initial reference taken by kfd_queue_acquire_buffers(). Because q->properties.ctx_save_restore_area_address and ctx_save_restore_area_size remain set, kfd_dqm_release_zombie() -> kfd_queue_release_buffers() -> kfd_queue_buffer_svm_put() still decrements prange->queue_refcount when the zombie queue is reaped:

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:kfd_dqm_release_zombie() {
    ...
	mutex_lock(&p->mutex);
	deallocate_doorbell(&pdd->qpd, q);
	kfd_queue_unref_bo_vas(pdd, &q->properties);
	kfd_queue_release_buffers(pdd, &q->properties, false);
	mutex_unlock(&p->mutex);
    ...
}

If another queue of the process shares or reuses that SVM range for its CWSR area before the zombie is reaped, its prange->queue_refcount is decremented early, allowing the range to be unmapped without evicting the active queue. Clearing q->properties.ctx_save_restore_area_address (or zeroing ctx_save_restore_area_size) when kfd_queue_buffer_svm_get() fails would avoid the unmatched put.

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

PATCH v2 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.

kfd_process_evict_queues() returns the result of the last device. When an earlier device reported -EIO, the caller is told that everything was saved, signals the eviction fence and schedules a restore for a process that still has a queue on the hardware of that device.

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. Until the retry, the process is half restored: an eviction that comes first finds qpd->evicted set and leaves the restored queues running while their buffers are moved.

Evict every queue and report MES failures as -EIO, which kfd_process_evict_queues() already takes to mean "evicted, do not add back", and let it keep that answer when any device gave it. On a failed restore, take the queues restored in this attempt off the hardware again, so that the process is fully evicted and the retry starts from a known state. A queue is counted before ADD_QUEUE is sent, because the oversubscription check in add_queue_mes() wants to see it, and taken out of the count again when the command fails.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 57 +++++++++++++++----
 drivers/gpu/drm/amd/amdkfd/kfd_process.c      |  7 ++-
 2 files changed, 52 insertions(+), 12 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +47 -10
index c691df753..eb75858bd 100644
@@ -1984,11 +1984,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;
 			}
 		}
 
@@ -2201,22 +2214,25 @@ 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);
-
 		retval = dqm_repin_mqd_bo(dqm, q);
 		if (retval) {
 			dev_err(dev, "Failed to repin MQD for queue %d\n",
 				q->properties.queue_id);
-			goto out;
+			goto rollback;
 		}
 
+		/* Counted first: add_queue_mes() looks at the active count */
+		q->properties.is_active = true;
+		increment_queue_count(dqm, &pdd->qpd, q);
+
 		if (dqm->dev->kfd->shared_resources.enable_mes) {
 			retval = add_queue_mes(dqm, q, qpd);
 			if (retval) {
 				dev_err(dev, "Failed to restore queue %d\n",
 					q->properties.queue_id);
-				goto out;
+				q->properties.is_active = false;
+				decrement_queue_count(dqm, &pdd->qpd, q);
+				goto rollback;
 			}
 		}
 	}
@@ -2230,6 +2246,27 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 out:
 	dqm_unlock(dqm);
 	return retval;
+
+rollback:
+	/*
+	 * A half restored process is a problem for the next eviction: it
+	 * finds qpd->evicted set and leaves the queues restored so far
+	 * running. Take those off the hardware again, so that the process
+	 * is fully evicted and the retry starts from a known state. A
+	 * removal that cannot be sent (-EIO) leaves the queue mapped and
+	 * marked evicted, as evict_process_queues_cpsch() does.
+	 */
+	list_for_each_entry(q, &qpd->queues_list, list) {
+		q->properties.is_evicted = true;
+		if (!q->properties.is_active)
+			continue;
+
+		q->properties.is_active = false;
+		decrement_queue_count(dqm, qpd, q);
+		if (dqm->dev->kfd->shared_resources.enable_mes)
+			remove_queue_mes(dqm, q, qpd);
+	}
+	goto out;
 }
 
 static int register_process(struct device_queue_manager *dqm,
drivers/gpu/drm/amd/amdkfd/kfd_process.c +5 -2
index 51c3fa39f..546aeef04 100644
@@ -2134,7 +2134,7 @@ struct kfd_process *kfd_lookup_process_by_id(const struct mm_struct *mm, u16 id)
  */
 int kfd_process_evict_queues(struct kfd_process *p, uint32_t trigger)
 {
-	int r = 0;
+	int r = 0, ret = 0;
 	int i;
 	unsigned int n_evicted = 0;
 
@@ -2155,12 +2155,15 @@ int kfd_process_evict_queues(struct kfd_process *p, uint32_t trigger)
 			dev_err(dev, "Failed to evict process queues\n");
 			goto fail;
 		}
+		/* One device that could not save its queues is enough */
+		if (r)
+			ret = r;
 		n_evicted++;
 
 		pdd->dev->dqm->is_hws_hang = false;
 	}
 
-	return r;
+	return ret;
 
 fail:
 	/* To keep state consistent, roll back partial eviction by
Signature · 1 line
2.47.3
#11 lore raw

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

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] drm/amdkfd: evict_process_queues_cpsch() returns 0 with unretired MES queues - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] drm/amdkfd: evict_process_queues_cpsch() returns 0 with unretired MES queues
- [Medium] drm/amdkfd: missing kfd_flush_tlb() in restore_process_queues_cpsch() rollback
--

commit 912d1284460b9827cb7b366431ada4596ab37d25
Author: Armas Spann <[email protected]>

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

This commit continues evicting remaining queues when MES queue removal fails, preserves -EIO across devices in kfd_process_evict_queues(), and rolls back already-added queues when restore_process_queues_cpsch() fails.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index eabb9a6953451..f952880a66657 100644

[ ... ]

Quoted 13 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +9 -0
@@ -2227,6 +2243,27 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 out:
 	dqm_unlock(dqm);
 	return retval;
+
+rollback:
+	/*
+	 * A half restored process is a problem for the next eviction: it
+	 * finds qpd->evicted set and leaves the queues restored so far
+	 * running. Take those off the hardware again, so that the process
+	 * is fully evicted and the retry starts from a known state. A
+	 * removal that cannot be sent (-EIO) leaves the queue mapped and
+	 * marked evicted, as evict_process_queues_cpsch() does.

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	 */
+	list_for_each_entry(q, &qpd->queues_list, list) {
+		q->properties.is_evicted = true;
+		if (!q->properties.is_active)
+			continue;
+
+		q->properties.is_active = false;
+		decrement_queue_count(dqm, qpd, q);
+		if (dqm->dev->kfd->shared_resources.enable_mes)
+			remove_queue_mes(dqm, q, qpd);

[Severity: Medium]
If remove_queue_mes() fails with -EIO here (or during an earlier call to evict_process_queues_cpsch()), can a subsequent eviction return 0 while unretired queues are still mapped in MES?

When a later queue fails add_queue_mes() (for instance with -ETIMEDOUT, which fences MES, or -EIO when a reset starts), remove_queue_mes() in this rollback returns -EIO and leaves the earlier queues mapped in MES with qpd->evicted still set to 1. Because restore_process_helper() has already armed a new eviction fence before calling kfd_process_restore_queues(), a TTM eviction that runs before the restore retry sees qpd->evicted++ > 0 in evict_process_queues_cpsch() and returns 0 instead of -EIO:

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c:evict_process_queues_cpsch() {
	dqm_lock(dqm);
	if (qpd->evicted++ > 0) /* already evicted, do nothing */
		goto out;
    ...
}

evict_process_worker() then signals the eviction fence and lets TTM move or unmap BOs while those unretired queues are still on the hardware.

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

Quoted 3 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +2 -0
+	}
+	goto out;
 }

[Severity: Medium]
Does this rollback path also need to call kfd_flush_tlb(pdd) after removing the already-restored queues from MES?

Queues added earlier in the loop may have started executing and issuing memory accesses before a later queue failed dqm_repin_mqd_bo() or add_queue_mes(). MES does not perform a heavyweight TLB flush on queue removal, and because qpd->evicted stays 1, a subsequent call to evict_process_queues_cpsch() before the restore retry takes the qpd->evicted++ > 0 early exit and skips kfd_flush_tlb(pdd) as well, allowing BOs or SVM ranges to be migrated or freed before in-flight memory accesses complete.

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

PATCH v2 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() in the mqd_update_info of the call 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. The properties travel with the call and not in the queue, because set_perfcount() updates every queue of every process under the dqm lock alone, and must not apply the properties of an update that is in flight for one of them.

A queue that is updated while the scheduler is stopped, in the no-HWS debug mode, now gets -EBUSY. The update is not applied in that state; it returned success before.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 21 +++++-
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  6 ++
 .../amd/amdkfd/kfd_process_queue_manager.c    | 69 +++++++++++--------
 3 files changed, 68 insertions(+), 28 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +20 -1
index eb75858bd..a75c88356 100644
@@ -1411,6 +1411,24 @@ 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. The
+	 * new properties travel with the update that carries them, so an
+	 * update of another kind (perfcount, debug) cannot apply them.
+	 */
+	if (minfo && minfo->new_props) {
+		const struct queue_properties *np = minfo->new_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;
+		minfo->new_props = NULL;
+	}
+
 	mqd_mgr->update_mqd(mqd_mgr, q->mqd, &q->properties, minfo);
 
 	/*
@@ -1489,7 +1507,8 @@ static int update_queue_locked(struct device_queue_manager *dqm, struct queue *q
 
 		if (!dqm->sched_running) {
 			WARN_ONCE(1, "Update non-HWS queue while stopped\n");
-			return retval;
+			/* Nothing was applied, say so */
+			return -EBUSY;
 		}
 
 		retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +6 -0
index 23fc74aa0..081085f3a 100644
@@ -581,6 +581,12 @@ struct mqd_update_info {
 		} cu_mask;
 	};
 	enum mqd_update_flag update_flag;
+	/*
+	 * New properties from pqm_update_queue_properties(). Applied by
+	 * update_queue() under the dqm lock once the queue is unmapped, and
+	 * cleared to report that it did.
+	 */
+	const struct queue_properties *new_props;
 };
 
 /**
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +42 -27

102 lines not on this page · raw message

Signature · 1 line
2.47.3
#13 lore raw

PATCH v2 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, release the status slots of commands that were lost with it, and lift the fence that was raised for such a command.

The queues are inactive by then. Every path that restarts the firmware with live processes evicts them first, through kgd2kfd_pre_reset() or kgd2kfd_suspend(), and set_queue_as_reset() takes care of what a partial eviction left active. The reconcile does not deactivate queues itself; a queue it finds still marked active is reported, because a restart path has then forgotten to evict.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 62 +++++++++++++++++++
 1 file changed, 62 insertions(+)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +62 -0
index a75c88356..41e97f74e 100644
@@ -2756,6 +2756,66 @@ 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. 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, return the status slots of commands
+ * that were lost with the old firmware, and lift the fence raised for one
+ * of them. The queues themselves are inactive at this point: every path
+ * that restarts the firmware with live processes evicts them first, and
+ * set_queue_as_reset() deactivates what a partial eviction left active.
+ * A queue that is still marked active means a restart path forgot to
+ * evict; say so, but leave the counters to the paths that own them.
+ *
+ * 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)
+				active++;
+		}
+	}
+
+	if (active)
+		dev_warn(dev,
+			 "MES was restarted with %u queue(s) still marked active, they were not evicted\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;
@@ -2820,6 +2880,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.47.3
#14 lore raw

PATCH v2 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 f631047e8..d2bbc78ad 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);
Signature · 1 line
2.47.3