Skip to contentSkip to conversation

drm/amdkfd: keep queue storage until MES has retired the queue

PATCH New Armas Spann 2 participants 15 messages Dec 4

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

cover drm/amdkfd: keep queue storage until MES has retired the queue

KFD frees the storage of a user queue without requiring that MES has confirmed the removal of the queue. When a REMOVE_QUEUE fails or times out, the MQD, the doorbell id, the gang context, the GART mapping of the write pointer and the references on the user buffers are released all the same. On gfx12 the MQD comes from a first fit sub-allocator and the doorbell id from a first fit bitmap, so both go to the next queue the process creates. A REMOVE_QUEUE that MES completes after the driver gave up on it then writes queue state into an MQD that belongs to another queue, and a queue that MES never let go of keeps running on memory that has been freed. The same holds for an ADD_QUEUE that timed out and is executed later.

This series makes KFD keep everything a queue owns until MES has let go of it: the removal was confirmed, a command that timed out has completed after all, or the firmware has been restarted.

It is a new series and replaces the two postings of "drm/amdgpu/amdkfd:
fix MES queue lifecycle on multi-GPU" [1] [2], which are obsolete. Those were built around a failure that I only got with cwsr_enable=0. Felix pointed out [3] that this is not a supported configuration, and asked for the storage lifetime problem to be sent separately. This is that series. The patch that dealt with CWSR is gone, and nothing in here depends on, or tries to accommodate, a system without CWSR. The bug itself does not need that setting: any REMOVE_QUEUE or ADD_QUEUE that MES rejects or does not answer in time takes the paths below, as does every removal that cannot be sent because a GPU reset is under way.

1/8 MES: tell a command the firmware rejected from one it did not
answer. Let the caller of REMOVE_QUEUE keep the status slot of an unanswered command (a "ticket") and poll it later. Count the restarts of the scheduler firmware per XCC.
2/8 Make the helper that frees the per-queue MES resources usable
from the dqm. No functional change.
3/8 Record per queue what MES knows about it (unmapped, mapped,
unknown), from the result of every ADD_QUEUE and REMOVE_QUEUE. Give a REMOVE_QUEUE that timed out a grace period, and stop sending queue commands behind one that got no answer.
4/8 Add a quarantine: a per-device list of destroyed queues that MES
has not retired, a reaper that frees them once it has, and a hold on the process whose pdd, VM and doorbell page they use.
5/8 Convert the paths that free queue storage (destroy in the dqm
and in the pqm, failed create, process termination) to ask whether MES has retired the queue, and to quarantine it otherwise. This is the patch that closes the use-after-free.
6/8 Keep eviction and restore consistent when MES fails: evict every
queue, report -EIO as long as MES still has one, roll back a partial restore.
7/8 Apply queue property updates at the point where the queue is
unmapped, not before, so that a failed unmap does not leave the scheduler on a ring whose unmap protection is gone.
8/8 When the scheduler starts after a firmware restart, drop the
state that belonged to the old instance in one place.

Patches 1 to 4 add infrastructure and change behaviour only where the commit messages say so. Nothing is quarantined before 5/8. Every patch builds on its own.

What the series does not do:

- The hold a quarantined queue has on its process is per process, not per device. A process that has exited with a queue quarantined on one GPU keeps its pdds on all GPUs, so the removal of another GPU waits until that queue is retired, which takes a reset or the removal of the GPU it is on. The wait logs what it is waiting for. Lifting this means releasing the pdds device by device in the release worker and is left for a follow-up.
- A per-queue reset that KGD starts calls into the dqm without the dqm lock. That is the case today for is_active and the queue counters; the per-queue MES state and the quarantine list are now touched on that path as well. Taking the lock there needs a lock order between the KGD reset mutex and the dqm lock, which the KFD side takes the other way round. Not changed here.
- The quarantine keeps the storage of a queue allocated, pinned where it was pinned, and referenced. It does not keep TTM from moving the user buffers of a process that has exited; the eviction fence is signalled when the process is released, as before.
- amdgpu_gfx_reset_mes_compute() sends its RESUME also when a command before it got no answer. KGD code, not touched.

Compiled after each of the eight patches: all amdkfd objects and the amdgpu objects the series touches, x86_64, gcc 14.2. The final tree also without CONFIG_HSA_AMD_SVM.

Tested on two Radeon AI PRO R9700 (gfx 12.0.1, 32 GB each) in a PCIe 3.0 system, Gentoo 7.3.7 with the eight patches backported, default configuration (cwsr_enable=1). A third GPU (CUDA) ran an unrelated inference workload throughout.

Dual-GPU compute load, long run: an ML training job (F5-TTS, 20311 samples, dual-GPU via PyTorch/accelerate, ROCm 6.4) completed 2539 updates over 21 minutes at 1.98 updates/s with both GPUs above 95% load. The same workload on the earlier v2 series backported to 7.3.5 ran at 0.34 updates/s (2.93 s/update).
dmesg throughout: zero MES rejects, zero resets, zero KFD errors.

SIGKILL of a process under dual-GPU load: both GPUs dropped to idle immediately, VRAM returned to baseline. No MES errors, no quarantine activity, no reaper activity. The teardown paths in 5/8 were taken; the quarantine path was not because MES retired both queues before the driver gave up.

Forced GPU reset (debugfs amdgpu_gpu_recover) with a KFD process running at full load: one GPU reset without MODE1 ("device wedged, but no recovery needed" -- the sticky -EIO from 6/8 and the reconciliation from 8/8), the other took a MODE1 reset with MES firmware reload. Both GPUs: single reset, no cascading failure. A new process started afterwards reached the same throughput. The reconciliation path in 8/8 was taken on both GPUs.

Suspend to S3 and resume with idle KFD state: both GPUs took a MODE1 reset on suspend, MES firmware reloaded on resume. System functional.

Failure paths reached during testing: sticky -EIO (6/8), reconciliation after restart (8/8), per-queue MES state tracking (3/8). Not reached:
quarantine (4/8, 5/8), late completion polling (1/8), reaper (4/8). These require a REMOVE_QUEUE that MES does not answer within the timeout, which did not occur during the test runs.

Based on amd-staging-drm-next, f0e06b8eb4bb ("drm/amdgpu/gfx9: make room for the SPM VMID write in the compute rings").

[1] https://lore.kernel.org/all/[email protected]/T/#u
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/amd-gfx/[email protected]/

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

Armas Spann (8):
drm/amdgpu/mes: distinguish rejected from timed out commands drm/amdkfd: make the per-queue MES resource cleanup usable by the dqm 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

 drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h    |   1 +
 .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c  |  30 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c    |   5 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c       | 119 +++
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h       |  60 ++
 drivers/gpu/drm/amd/amdgpu/mes_v11_0.c        |  62 +-
 drivers/gpu/drm/amd/amdgpu/mes_v12_0.c        |  63 +-
 drivers/gpu/drm/amd/amdgpu/mes_v12_1.c        |  97 +-
 drivers/gpu/drm/amd/amdgpu/mes_v13_0.c        |  69 +-
 drivers/gpu/drm/amd/amdkfd/kfd_device.c       |  36 +-
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 917 ++++++++++++++++--
 .../drm/amd/amdkfd/kfd_device_queue_manager.h |  31 +
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  52 +
 drivers/gpu/drm/amd/amdkfd/kfd_process.c      |  65 +-
 .../amd/amdkfd/kfd_process_queue_manager.c    | 180 +++-
 drivers/gpu/drm/amd/amdkfd/kfd_queue.c        |  78 +-
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c          |  38 +-
 drivers/gpu/drm/amd/amdkfd/kfd_svm.h          |   7 +
 18 files changed, 1744 insertions(+), 166 deletions(-)
Signature · 1 line
2.47.3
#1 lore raw

PATCH 1/8 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. A caller cannot tell a firmware that stopped answering from one that answered at once and said no. KFD takes both for a hung scheduler.

Return AMDGPU_MES_CMD_REJECTED (-EREMOTEIO) when MES answered with a failure, and print the 64 bit status with it. -ETIMEDOUT now only means that MES did not answer. One place compares a result that can come from this path with -ETIMEDOUT, the retry of an SR-IOV reset. It accepts the new code as well, so a reset whose MES bring-up was refused is retried as before. The new code also reaches user space where the result of a MES command is returned from a KFD or user queue ioctl; it replaces -ETIMEDOUT there for a command that the firmware refused.

mes_v12_1 reads the status slot as 32 bits, so the upper half, where the firmware puts its error code, is never seen there. Read it as 64 bits like the other versions do.

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, once the new instance has answered its first command: 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.

The fence of the MES ring is not only moved by MES. A GPU reset forces it forward in amdgpu_device_pre_asic_reset(), long before the firmware is set up again, and the first command of the new instance moves it once more before fw_gen is incremented. A passed fence without a success status is therefore reported as a failure only while no reset is in progress and the generation still matches; otherwise the ticket is stale. The reset flag is set before the fence is forced and cleared after the generation went up, so the poll reads the fence, the flag and the generation in that order. The generation a ticket carries is sampled before the command is written to the ring.

A ticket is only written when the command is left in the ring. When the ring is full the command path returns -ETIMEDOUT without having queued anything and leaves the ticket alone; the header says so, and amdgpu_mes_ticket_answered() treats a ticket that was never filled in as nothing to wait for.

While at it, make mes_v12_1 and mes_v13_0 return -ETIMEDOUT when the MES ring is full. They return 0 there, which a caller takes for a completed command.

The ticket and the generation counter have no users yet. What changes in behaviour is the error code and the log line for rejected commands, and the result of the full ring case on GC 12.1 and GC 13.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c |   5 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c    | 119 +++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h    |  60 +++++++++++
 drivers/gpu/drm/amd/amdgpu/mes_v11_0.c     |  62 +++++++++--
 drivers/gpu/drm/amd/amdgpu/mes_v12_0.c     |  63 +++++++++--
 drivers/gpu/drm/amd/amdgpu/mes_v12_1.c     |  97 ++++++++++++++---
 drivers/gpu/drm/amd/amdgpu/mes_v13_0.c     |  69 ++++++++++--
 7 files changed, 434 insertions(+), 41 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +4 -1
index 988b22095..c182bdc7e 100644
@@ -105,7 +105,10 @@ MODULE_FIRMWARE("amdgpu/cyan_skillfish_gpu_info.bin");
 
 #define AMDGPU_RESUME_MS		2000
 #define AMDGPU_MAX_RETRY_LIMIT		2
-#define AMDGPU_RETRY_SRIOV_RESET(r) ((r) == -EBUSY || (r) == -ETIMEDOUT || (r) == -EINVAL)
+/* A MES command that the firmware rejected used to come back as -ETIMEDOUT */
+#define AMDGPU_RETRY_SRIOV_RESET(r) ((r) == -EBUSY || (r) == -ETIMEDOUT || \
+				     (r) == -EINVAL || \
+				     (r) == AMDGPU_MES_CMD_REJECTED)
 #define AMDGPU_PCIE_INDEX_FALLBACK (0x38 >> 2)
 #define AMDGPU_PCIE_INDEX_HI_FALLBACK (0x44 >> 2)
 #define AMDGPU_PCIE_DATA_FALLBACK (0x3C >> 2)
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +119 -0

131 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_mes.h +60 -0

84 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v11_0.c +55 -7

114 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v12_0.c +56 -7

121 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +80 -17

160 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/mes_v13_0.c +60 -9

128 lines not on this page · raw message

Signature · 1 line
2.47.3
#2 lore raw

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

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] drm/amdgpu/mes: failed reset breaks amdgpu_mes_ticket_poll() reset check - [Medium]…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] drm/amdgpu/mes: failed reset breaks amdgpu_mes_ticket_poll() reset check
- [Medium] drm/amdgpu/mes: mes_v*_submit_pkt_ticket() misclassifies reset-forced fence
- [Medium] drm/amdgpu: amdgpu_mes_ticket_poll() misreports state on failed reset/resume
- [Low] drm/amdgpu/mes: missing writer barriers pairing with ticket smp_rmb()
--

commit 1712012870309920f5ca4962dcbb7f16034640d2
Author: Armas Spann <[email protected]>

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

This commit returns AMDGPU_MES_CMD_REJECTED (-EREMOTEIO) instead of -ETIMEDOUT when MES answers a command with a failure status, and adds a per-XCC firmware generation counter and command tickets so callers can track late completions of timed out REMOVE_QUEUE commands.

Quoted 4 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +0 -0
index 27d6371d8d791..ef226183d7eb5 100644

[ ... ]

Quoted 9 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +9 -0
+	/*
+	 * The fence was passed without a success status. That is a failure
+	 * reported by MES only if MES moved the fence. A GPU reset moves it
+	 * as well (amdgpu_device_pre_asic_reset()), and so does the first
+	 * command of the next firmware instance, both before fw_gen is
+	 * incremented. Neither says anything about a command the old
+	 * instance never answered. The reset flag is set before the fence
+	 * is forced and cleared after fw_gen went up, so it is read after
+	 * the fence and before the generation.

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

Quoted 10 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +10 -0
+	 */
+	if (amdgpu_in_reset(adev))
+		return AMDGPU_MES_TICKET_STALE;
+	/* Read the generation after the reset flag, see above */
+	smp_rmb();
+	if (ticket->fw_gen != amdgpu_mes_fw_gen(&adev->mes, ticket->xcc_id))
+		return AMDGPU_MES_TICKET_STALE;
+
+	return AMDGPU_MES_TICKET_FAILED;
+}

[Severity: Medium]
Does the invariant that in_gpu_reset is only cleared after fw_gen goes up hold when a GPU reset fails or aborts?

amdgpu_device_pre_asic_reset() forces *mes_ring->fence_drv.cpu_addr to sync_seq before the reset runs. If amdgpu_device_asic_reset() then aborts early (for example, amdgpu_ras_is_rma() returning -ENODEV before MES is halted), amdgpu_device_gpu_recover() jumps to reset_unlock and clears in_gpu_reset without incrementing fw_gen.

Once in_gpu_reset is 0, amdgpu_mes_ticket_poll() permanently returns AMDGPU_MES_TICKET_FAILED and amdgpu_mes_ticket_answered() returns true for a command MES never processed. If KFD later resumes scheduling without reinitializing MES (such as on the unwind_userq path of amdgpu_device_suspend()), callers can call amdgpu_mes_ticket_release() and return the writeback status slot to adev->wb.used while the unanswered command is still in the live MES ring, allowing a late DMA write to corrupt the next owner of that slot.

Quoted 12 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +12 -0
+bool amdgpu_mes_ticket_answered(struct amdgpu_device *adev,
+				const struct amdgpu_mes_cmd_ticket *ticket)
+{
+	bool passed;
+
+	if (!ticket->valid ||
+	    ticket->fw_gen != amdgpu_mes_fw_gen(&adev->mes, ticket->xcc_id))
+		return true;
+
+	passed = amdgpu_mes_fence_passed(&adev->mes.ring[ticket->ring_idx],
+					 ticket->seq);
+

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

Quoted 10 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c +10 -0
+	/*
+	 * A GPU reset forces the fence, see amdgpu_mes_ticket_poll(). The
+	 * flag is set before that happens, so read it after the fence.
+	 */
+	smp_rmb();
+	if (amdgpu_in_reset(adev))
+		return false;
+
+	return passed;
+}

[Severity: Low]
Are the smp_rmb() barriers in amdgpu_mes_ticket_poll() and amdgpu_mes_ticket_answered() paired with explicit write barriers on the writer side?

atomic_inc(&adev->mes.fw_gen[...]) is relaxed, and amdgpu_device_unlock_reset_domain() clears in_gpu_reset with a relaxed atomic_set() before up_write(), so nothing explicitly orders the fw_gen increment before in_gpu_reset becomes 0. Likewise, amdgpu_device_lock_reset_domain() sets in_gpu_reset with a relaxed atomic_set() before acquire-only down_write(), and amdgpu_fence_write() writes *drv->cpu_addr with an unmarked plain store rather than WRITE_ONCE().

On weakly ordered SMP architectures, store reordering can let amdgpu_mes_ticket_poll() observe in_gpu_reset == 0 with the old fw_gen and return AMDGPU_MES_TICKET_FAILED instead of AMDGPU_MES_TICKET_STALE, or let amdgpu_mes_ticket_answered() observe the forced fence with in_gpu_reset == 0 and return true mid-reset. The unmarked store in amdgpu_fence_write() is also a KCSAN data race against READ_ONCE() in amdgpu_mes_fence_passed(). Adding smp_wmb() around the in_gpu_reset updates (or atomic_set_release() on unlock) and WRITE_ONCE() in amdgpu_fence_write() would pair the barriers properly.

Quoted 4 lines
drivers/gpu/drm/amd/amdgpu/mes_v11_0.c +0 -0
index 7d8a56859fce5..fc8822458adda 100644

[ ... ]

drivers/gpu/drm/amd/amdgpu/mes_v11_0.c static int mes_v11_0_submit_pkt_and_poll_completion(struct amdgpu_mes *mes, · line 278

Quoted 9 lines
drivers/gpu/drm/amd/amdgpu/mes_v11_0.c +4 -0
@@ -264,9 +271,20 @@ static int mes_v11_0_submit_pkt_and_poll_completion(struct amdgpu_mes *mes,
 			x_pkt->header.opcode);
 
 	r = amdgpu_fence_wait_polling(ring, seq, timeout);
+	/* The status is written before the fence, read it after the fence */
+	dma_rmb();
 	if (r < 1 || !*status_ptr) {
+		/* The fence was reached, so MES processed the command */
+		bool answered = r >= 1;

[Severity: Medium]
Can a reset-forced ring fence cause mes_v11_0_submit_pkt_ticket() to misclassify an unanswered command as rejected by MES?

CPU0 CPU1
kfd_dbg_set_mes_debug_mode() amdgpu_device_pre_asic_reset()
mes_v11_0_submit_pkt_ticket()
amdgpu_fence_wait_polling()
amdgpu_fence_driver_force_completion()
/* r >= 1, *status_ptr == 0 */
answered = true; <-- returns AMDGPU_MES_CMD_REJECTED

amdgpu_device_pre_asic_reset() forces every ready MES ring fence to sync_seq without holding adev->mes.mutex_hidden and before amdgpu_device_ip_suspend() stops MES. Several callers submit MES packets without adev->reset_domain->sem, including kfd_dbg_set_mes_debug_mode(), mes_notify_unmap_work_handler(), and amdgpu_userq_preempt_helper().

When the forced fence wakes a concurrent poller with status 0, this path logs a bogus rejection with status 0, returns AMDGPU_MES_CMD_REJECTED (-EREMOTEIO) instead of -ETIMEDOUT (propagating -EREMOTEIO to userspace on KFD debug ioctls), and frees the writeback slot before MES is stopped. The same issue is present in mes_v12_0_submit_pkt_ticket(), mes_v12_1_submit_pkt_ticket(), and mes_v13_0_submit_pkt_ticket().

Quoted 4 lines
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +0 -0
index 84a3693db6ad4..d7cdce5be4af3 100644

[ ... ]

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

Quoted 12 lines
drivers/gpu/drm/amd/amdgpu/mes_v12_1.c +6 -0
@@ -1909,6 +1966,12 @@ static int mes_v12_1_xcc_hw_init(struct amdgpu_ip_block *ip_block, int xcc_id)
 	if (r)
 		goto failure;
 
+	/*
+	 * A new scheduler instance is up on this XCC, it knows none of the
+	 * old queues. The other XCCs keep theirs.
+	 */
+	atomic_inc(&adev->mes.fw_gen[xcc_id]);
+
 	mes_v12_1_set_hw_resources_1(&adev->mes, AMDGPU_MES_SCHED_PIPE, xcc_id);
 	mes_v12_1_init_aggregated_doorbell(&adev->mes, xcc_id);

[Severity: Medium]
Does advancing the MES ring fence in mes_v12_1_set_hw_resources() before incrementing adev->mes.fw_gen[xcc_id] break ticket polling outside GPU reset?

During S3/S4 resume or a suspend error unwind, amdgpu_in_reset(adev) is 0. mes_v12_1_set_hw_resources() submits a command that moves *ring->fence_drv.cpu_addr past any prior ticket's seq before fw_gen is incremented, and if that command is rejected, goto failure skips the atomic_inc() altogether.

A ticket created before suspend then sees a passed fence with status 0, in_gpu_reset == 0, and an unchanged fw_gen, so amdgpu_mes_ticket_poll() returns AMDGPU_MES_TICKET_FAILED instead of AMDGPU_MES_TICKET_STALE and amdgpu_mes_ticket_answered() returns true. On a suspend unwind into amdgpu_amdkfd_resume(), that lets amdgpu_mes_ticket_release() free the writeback status slot prematurely. The same ordering exists in mes_v11_0_hw_init(), mes_v12_0_hw_init(), and mes_v13_0_hw_init().

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

PATCH 2/8 drm/amdkfd: make the per-queue MES resource cleanup usable by the dqm

In reply to Armas Spann

pqm_free_mes_queue_res() frees the parts of a queue that only exist for
MES: the gang context with its slot, and the GART mapping of the write pointer. It is static to the pqm, and both of its callers test for MES before they call it.

The dqm is about to free these resources itself, at the point where MES is known to have let go of a queue. Rename the helper to kfd_queue_free_mes_resources(), move the test for MES into it and declare it in kfd_priv.h.

No functional change.

---
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h          |  1 +
 .../drm/amd/amdkfd/kfd_process_queue_manager.c | 18 +++++++++++++-----
 2 files changed, 14 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_priv.h +1 -0
index 8eac086aa..74655b001 100644
@@ -1389,6 +1389,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 +13 -5
index 6a9d7d31c..700155f39 100644
@@ -187,8 +187,17 @@ int pqm_init(struct process_queue_manager *pqm, struct kfd_process *p)
 	return 0;
 }
 
-static void pqm_free_mes_queue_res(struct kfd_node *dev, struct queue *q)
+/*
+ * Free the storage that only exists so MES can run the queue: the gang
+ * context with its slot and the GART mapping of the write pointer. MES
+ * addresses them 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);
@@ -218,8 +227,7 @@ static void pqm_clean_queue_resource(struct process_queue_manager *pqm,
 		pdd->qpd.num_gws = 0;
 	}
 
-	if (dev->kfd->shared_resources.enable_mes)
-		pqm_free_mes_queue_res(dev, pqn->q);
+	kfd_queue_free_mes_resources(dev, pqn->q);
 }
 
 void pqm_uninit(struct process_queue_manager *pqm)
@@ -492,8 +500,8 @@ int pqm_create_queue(struct process_queue_manager *pqm,
 	return retval;
 
 err_create_queue:
-	if (q && dev->kfd->shared_resources.enable_mes)
-		pqm_free_mes_queue_res(dev, q);
+	if (q)
+		kfd_queue_free_mes_resources(dev, q);
 	uninit_queue(q);
 	if (kq)
 		kernel_queue_uninit(kq);
Signature · 1 line
2.47.3
#4 lore raw

PATCH 3/8 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:

- reset_queues_mes() returns success although the queue it was called for was not removed, when MES reported other queues as hung and those were reset.
- The result of the remove-after-reset command is ignored, and a queue that went through a per-queue reset counts as removed from then on, whatever MES said.
- Queues are added a second time after a halt that failed half way.
- A REMOVE_QUEUE that MES completes shortly after the 2.1 s poll gave up is handled like one that failed: the recovery queues more commands behind it, and its status is written to a slot that has been freed.

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 the command with a failure. If it is still unanswered after the grace period, or could not be queued at all because the MES ring is full, the commands the recovery would send would each time out as well; 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. Not so when MES reported the queue itself as hung: the per-queue reset has sent the removal that goes with a reset, and if MES rejected that one, a second REMOVE_QUEUE is not sent after it. The rejection is reported as it is.
- Once a command got no answer, the dqm sends no more queue commands 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. Commands that do not come from the dqm, the process context flush for one, are not held back.
- A fence is never left without a request for the GPU reset that lifts it. The recovery can be left unanswered for a queue other than the one it was started for; the caller asks for the reset then even if its own queue is gone, and so does the bad queue interrupt path, which only logged the result of the recovery. A fence that is in place is kept as it is, with the command it watches.
- 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 ticket of the queue like every other one.

The per-queue reset that KGD starts calls into the dqm without the dqm lock, as it does today for is_active and the queue counters. The new state is written on that path as well; changing that needs a lock order between the KGD reset mutex and the dqm lock and is not part of this.

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

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 425 +++++++++++++++++-
 .../drm/amd/amdkfd/kfd_device_queue_manager.h |  17 +
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |  16 +
 .../amd/amdkfd/kfd_process_queue_manager.c    |   2 +
 4 files changed, 438 insertions(+), 22 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +403 -22
index 58c7da599..3767c4465 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,165 @@ 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;
+}
+
+/* True when MES answered the REMOVE_QUEUE for @q, with a failure */
+static bool kfd_mes_ticket_failed(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_FAILED;
+}
+
+/* True while nothing may be sent to MES, see kfd_mes_fence() */
+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;
+}
+
+/*
+ * 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)
+{
+	/*
+	 * Fenced already, for a command that was sent earlier. Nothing went
+	 * out behind that one, so it stays the one whose answer lifts the
+	 * fence. A failure that is merely passed up by the callers must not
+	 * replace it with a fence that has nothing to watch.
+	 */
+	if (kfd_mes_fenced(dqm))
+		return;
+
+	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;
+}
+
+/*
+ * A command for @q, or the recovery that was run for it, failed with @r.
+ * Fence MES off if that was for want of an answer. Returns true when MES
+ * is fenced off, by this or by a failure further down that was only passed
+ * up: the caller then has to get the GPU reset, nothing else lifts the
+ * fence of a scheduler that does not answer.
+ */
+static bool kfd_mes_fence_unanswered(struct device_queue_manager *dqm,
+				     struct queue *q, int r)
+{
+	if (!kfd_mes_queue_retired(dqm, q) &&
+	    (r == -ETIMEDOUT || kfd_mes_ticket_pending(dqm, q)))
+		kfd_mes_fence(dqm, q);
+
+	return kfd_mes_fenced(dqm);
+}
+
+/*
+ * 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 +375,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 +440,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 +485,43 @@ 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, an earlier one for the same queue, or the
+ * commands that fill its ring, in which case nothing was queued and
+ * q->mes_ticket stays invalid.
+ */
+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,26 +529,105 @@ 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;
+	bool retired;
+	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. The removal is sent by whoever deals with the queue next.
+	 */
+	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;
+		}
+
+		/*
+		 * Only a command that MES answered with a failure points at
+		 * a hung queue. Anything else got no answer: the command is
+		 * still in the ring, or it never got there because the ring
+		 * is full and there is no ticket to look at. MES is not
+		 * working its ring then, and the recovery below would only
+		 * queue three more commands, each to time out under the dqm
+		 * lock. Stop talking to MES and leave it to the GPU reset.
+		 */
+		if (!kfd_mes_ticket_failed(dqm, q))
+			goto unanswered;
+
+		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) {
-		dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
-			q->properties.doorbell_off);
+	if (!r)
+		return 0;
+
+unanswered:
+	/*
+	 * MES may have let go of @q in the meantime, whatever else failed.
+	 * That settles @q, but not a fence: the recovery may have been left
+	 * without an answer for another queue it reset on the way, and this
+	 * is where the GPU reset that lifts the fence is asked for.
+	 */
+	retired = kfd_mes_queue_retired(dqm, q);
+	if (!kfd_mes_fence_unanswered(dqm, q, r) && retired)
+		return 0;
+
+	/* The caller of a remove-after-reset decides what a failure means */
+	if (is_for_reset)
+		return r;
+
+	if (amdgpu_gpu_recovery) {
+		if (!retired)
+			dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
+				q->properties.doorbell_off);
 		dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
 		kfd_hws_hang(dqm);
 	}
 
-	return r;
+	return retired ? 0 : r;
 }
 
 static int remove_queue_mes(struct device_queue_manager *dqm, struct queue *q,
@@ -372,7 +656,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 +720,24 @@ 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);
+	/* For reset_queues_mes(): @q is one of the queues MES reset */
+	q->mes_reset_seen = 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;
 }
 
@@ -462,6 +762,9 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	int r = 0;
 	struct mes_remove_queue_input queue_input;
 
+	/* Set again by reset_queue_mes() if MES reports @q itself as hung */
+	q->mes_reset_seen = false;
+
 	if (!amdgpu_mes_queue_reset_by_mes_supported(adev)) {
 		r = -ENOTRECOVERABLE;
 		goto fail;
@@ -471,6 +774,25 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	if (WARN_ON(dqm->detect_hang_count > 0))
 		return 0;
 
+	/* 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;
@@ -478,10 +800,24 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	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;
+	/* 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);
@@ -504,6 +840,27 @@ 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.
+	 *
+	 * Not if @q itself was among the hung queues. The per-queue reset
+	 * has sent the removal that goes with a reset then. Either that
+	 * retired @q, or MES rejected it, and a second REMOVE_QUEUE without
+	 * the after-reset flag is not going to fare better. Report the
+	 * rejection instead of asking again: the callers wanted @q out of
+	 * MES and it is still there.
+	 */
+	if (num_hung && !kfd_mes_queue_retired(dqm, q)) {
+		if (q->mes_reset_seen)
+			r = AMDGPU_MES_CMD_REJECTED;
+		else
+			r = __remove_queue_mes(dqm, q, false);
+	}
+
 fail:
 	dqm->detect_hang_count = 0;
 	return r;
@@ -1143,6 +1500,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)
@@ -3610,9 +3976,24 @@ int kfd_dqm_suspend_bad_queue_mes(struct kfd_node *knode, u32 pasid, u32 doorbel
 
 		list_for_each_entry(q, &qpd->queues_list, list) {
 			if (q->doorbell_id == doorbell_id && q->properties.is_active) {
-				if (reset_queues_mes(dqm, q))
+				int r = reset_queues_mes(dqm, q);
+
+				if (r)
 					dev_dbg(knode->adev->dev,
-					"Fail to remove bad queue. doorbell_id 0x%x\n", q->doorbell_id);
+						"Fail to remove bad queue. doorbell_id 0x%x\n",
+						q->doorbell_id);
+				/*
+				 * A command of the recovery got no answer and
+				 * MES is fenced off. Only a late answer or a
+				 * restart of the firmware lifts that, and no
+				 * one else is going to ask for the GPU reset.
+				 */
+				if (r && kfd_mes_fence_unanswered(dqm, q, r)) {
+					dev_err(knode->adev->dev,
+						"MES did not answer while suspending bad queue doorbell=0x%x, issue a GPU reset\n",
+						q->properties.doorbell_off);
+					kfd_hws_hang(dqm);
+				}
 				q->properties.is_evicted = true;
 				q->properties.is_active = false;
 				decrement_queue_count(dqm, qpd, q);
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.h +17 -0
index 2e4f1c467..964588d15 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 +16 -0
index 74655b001..76cbab619 100644
@@ -583,6 +583,13 @@ struct mqd_update_info {
 	enum mqd_update_flag update_flag;
 };
 
+/* 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
  *
@@ -644,6 +651,15 @@ 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;
+	/* MES reset the queue in the recovery that reset_queues_mes() runs */
+	bool mes_reset_seen;
+
 	/* 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 700155f39..3c2aea628 100644
@@ -198,6 +198,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 3/8] 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: unlocked KGD reset in reset_queue_mes() races on ticket and fence - [High] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [High] drm/amdkfd: unlocked KGD reset in reset_queue_mes() races on ticket and fence
- [High] drm/amdkfd: late REMOVE_QUEUE completion skips GPU reset and leaves scheds stopped
- [Medium] drm/amdkfd: kfd_mes_fence() installs permanent fence on answered ticket
- [Medium] drm/amdkfd: ticketless MES fence permanently locks DQM when gpu_recovery is 0
- [Medium] drm/amdkfd: TOCTOU in __remove_queue_mes() and reset_queues_mes() drops DONE
- [Medium] drm/amdkfd: reset_queue_mes() swallows -EIO from remove-after-reset cleanup
- [Medium] drm/amdkfd: reset_queues_mes() omits sched_halt and sched_running check
--

commit 5f554466aebb58f6575996926feaccfc3cb95937
Author: Armas Spann <[email protected]>

drm/amdkfd: track whether MES knows each queue

This commit adds per-queue MES state, firmware generation, and command ticket tracking in the device queue manager, along with a grace wait and MES fencing when queue commands time out.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index cc7a1f770408f..5e58509787385 100644

[ ... ]

Quoted 13 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +13 -0
+	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;
+}
+
+/*
+ * A command for @q, or the recovery that was run for it, failed with @r.
+ * Fence MES off if that was for want of an answer. Returns true when MES
+ * is fenced off, by this or by a failure further down that was only passed
+ * up: the caller then has to get the GPU reset, nothing else lifts the
+ * fence of a scheduler that does not answer.

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c static int convert_to_amdgpu_ring_type(int queue_type) · line 342

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+ */
+static bool kfd_mes_fence_unanswered(struct device_queue_manager *dqm,
+				     struct queue *q, int r)
+{
+	if (!kfd_mes_queue_retired(dqm, q) &&
+	    (r == -ETIMEDOUT || kfd_mes_ticket_pending(dqm, q)))
+		kfd_mes_fence(dqm, q);
+
+	return kfd_mes_fenced(dqm);
+}

[Severity: Medium]
Can kfd_mes_fence() install a permanent, sequence-less fence for a ticket that MES has already answered?

In reset_queues_mes() -> amdgpu_gfx_reset_mes_compute(), if remove_hw_queue() returns -ETIMEDOUT with a valid q->mes_ticket, amdgpu_mes_resume() still runs for up to 2.1 s before -ETIMEDOUT is returned. If MES catches up during resume and answers the ticket with AMDGPU_MES_TICKET_FAILED, kfd_mes_fence_unanswered() sees !kfd_mes_queue_retired() && r == -ETIMEDOUT and calls kfd_mes_fence().

Inside kfd_mes_fence(), kfd_mes_ticket_pending() returns false for an already-answered ticket, setting dqm->mes_fence_has_seq to false. The fence then can never be lifted by amdgpu_mes_ticket_answered() and only clears on a firmware restart, triggering spurious GPU resets (or wedging the DQM with -EIO when amdgpu_gpu_recovery is 0).

Checking whether q->mes_ticket is valid and already answered before fencing would avoid conflating an answered ticket with a ticketless command.

[ ... ]

Quoted 1 line
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
@@ -270,14 +440,30 @@ static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,

[ ... ]

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

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

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

[Severity: Medium]
Does arming a ticketless fence here permanently wedge the DQM when amdgpu_gpu_recovery is 0?

ADD_QUEUE carries no ticket, so kfd_mes_fence() sets mes_fence_has_seq to false, meaning only an increment of mes.fw_gen lifts the fence. When amdgpu_gpu_recovery is 0, kfd_hws_hang() -> amdgpu_amdkfd_gpu_reset() skips scheduling reset_work, so every later KFD queue command fails with -EIO even if MES recovers.

The same happens at the unanswered: label in remove_queue_mes_on_reset_option() on a ring-full REMOVE_QUEUE, where kfd_mes_fence_unanswered() runs before checking amdgpu_gpu_recovery. Only arming a ticketless fence when GPU recovery is enabled would keep the fence paired with the reset that lifts it.

[ ... ]

Quoted 22 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +11 -6
+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.

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

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

[Severity: Medium]
Can a late AMDGPU_MES_TICKET_DONE completion be dropped between kfd_mes_queue_retired() and kfd_mes_ticket_pending()?

If MES finishes an earlier timed-out REMOVE_QUEUE right after kfd_mes_queue_retired() returns false, kfd_mes_fenced() sees the fence passed and lifts the fence, and kfd_mes_ticket_pending() returns false because the state is now AMDGPU_MES_TICKET_DONE. The ticket is then released without setting q->mes_state to KFD_MES_QUEUE_UNMAPPED.

A duplicate REMOVE_QUEUE is sent for an already-removed queue, which MES rejects, escalating to recovery and a spurious GPU reset. The same window exists in reset_queues_mes(); re-checking kfd_mes_queue_retired() after kfd_mes_fenced() (or polling the ticket once) would close it.

[ ... ]

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +4 -3
+	/* remove_hw_queue failure indicates a queue hang. reset the queue */
 	r = reset_queues_mes(dqm, q);
-	if (r && amdgpu_gpu_recovery) {
-		dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
-			q->properties.doorbell_off);
+	if (!r)
+		return 0;
+

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 616

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+unanswered:
+	/*
+	 * MES may have let go of @q in the meantime, whatever else failed.
+	 * That settles @q, but not a fence: the recovery may have been left
+	 * without an answer for another queue it reset on the way, and this
+	 * is where the GPU reset that lifts the fence is asked for.
+	 */
+	retired = kfd_mes_queue_retired(dqm, q);
+	if (!kfd_mes_fence_unanswered(dqm, q, r) && retired)
+		return 0;

[Severity: High]
Can returning 0 here skip kfd_hws_hang() and leave all KGD compute DRM schedulers permanently stopped?

When reset_queues_mes() calls amdgpu_gfx_reset_mes_compute(), it stops the compute schedulers with amdgpu_gfx_reset_stop_compute_scheds(). If reset_queue_mes() times out on q's remove-after-reset cleanup, it fences MES on q->mes_ticket and returns -ETIMEDOUT, so amdgpu_gfx_reset_mes_compute() aborts its hung-queue loop, calls amdgpu_mes_resume(), and skips amdgpu_gfx_reset_start_compute_scheds() because ring_err is -ETIMEDOUT.

If MES finishes q's REMOVE_QUEUE with AMDGPU_MES_TICKET_DONE during amdgpu_mes_resume(), reset_queues_mes() still exits via goto fail without signaling reset or wedged events. Here, kfd_mes_queue_retired() returns true and kfd_mes_fence_unanswered() lifts the fence and returns false, so remove_queue_mes_on_reset_option() returns 0 without calling kfd_hws_hang().

Because no GPU reset is scheduled, the compute DRM schedulers stay stopped, any other hung queues in the batch remain unreset, and userspace receives no reset notification.

[ ... ]

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +2 -2
@@ -435,9 +720,24 @@ 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);
+	/* For reset_queues_mes(): @q is one of the queues MES reset */
+	q->mes_reset_seen = true;

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

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

[Severity: High]
Does calling remove_queue_mes_on_reset_option() from reset_queue_mes() without dqm_lock(dqm) introduce writeback pool corruption, torn fence state, and a widened use-after-free on struct queue?

KGD-initiated per-queue resets (for example gfx_v11_0_reset_kcq() -> amdgpu_gfx_reset_mes_compute() -> amdgpu_amdkfd_reset_mes_queue() -> kfd_reset_queue_mes() -> reset_queue_mes()) hold only adev->gfx.mec.reset_mutex without dqm_lock(dqm), racing with KFD threads tearing down or removing the same queue:

CPU0 (KGD reset, no dqm_lock) CPU1 (KFD destroy, holds dqm_lock)
reset_queue_mes()
remove_queue_mes_on_reset_option()

    __remove_queue_mes()
      amdgpu_mes_ticket_release()
        if (ticket->valid)
                                  remove_queue_mes() /
                                  kfd_queue_free_mes_resources()
                                    amdgpu_mes_ticket_release()
                                      if (ticket->valid)
                                      amdgpu_wb_free(status_offs)
                                      ticket->valid = false
        amdgpu_wb_free(status_offs)  <-- double free in adev->wb.used
        ticket->valid = false

Because amdgpu_wb_get() is a global first-fit allocator, double-freeing status_offs can clear a slot just reassigned to an unrelated ring or MES command.

Two other hazards occur on the same unlocked path. On timeout, kfd_mes_fence() writes dqm->mes_fenced = true before writing mes_fence_gen, mes_fence_has_seq, and mes_fence_ticket with no lock or barriers, so a concurrent kfd_mes_fenced() can observe stale state and drop the fence or poll a torn ticket. In addition, kfd_mes_wait_retired() now sleeps up to 4 s while dereferencing raw pointer q (looked up without a reference), widening the window for a concurrent KFD queue destroy to free q before set_queue_as_reset() runs.

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

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +6 -0
+	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]
Should reset_queue_mes() also propagate -EIO instead of returning 0?

remove_queue_mes_on_reset_option() returns -EIO without sending REMOVE_QUEUE when reset_domain->sem is write-locked, MES is fenced, or scheduling is halted/stopped. Swallowing -EIO lets KGD callers of amdgpu_gfx_reset_mes_compute() treat the reset as successful, resume MES with the reset KFD queue still mapped, and restart compute schedulers even while a GPU reset holds reset_domain->sem.

On the KFD path, leaving q->mes_reset_seen set while returning 0 also causes reset_queues_mes() to misreport the unsent -EIO cleanup as AMDGPU_MES_CMD_REJECTED.

[ ... ]

Quoted 6 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +2 -0
@@ -471,6 +774,25 @@ static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
 	if (WARN_ON(dqm->detect_hang_count > 0))
 		return 0;
 
+	/* Gone from MES in the meantime, nothing left to reset */
+	if (kfd_mes_queue_retired(dqm, 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 788

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

[Severity: Medium]
Should reset_queues_mes() and __remove_queue_mes() also check !dqm->sched_running || dqm->sched_halt?

halt_cpsch() (for example under enforce_isolation or S0ix suspend) sets dqm->sched_halt without clearing q->properties.is_active or flushing kfd->ih_wq. If remove_all_kfd_queues_mes() fails partway through without fencing MES, a bad-opcode interrupt for a remaining active queue enters kfd_dqm_suspend_bad_queue_mes() -> reset_queues_mes() while halted.

reset_queues_mes() then issues MES suspend/reset/resume commands in violation of the halt contract, and afterwards either calls __remove_queue_mes() directly (bypassing the halt check) or, if q itself was reset, misreports the -EIO from remove_queue_mes_on_reset_option() as AMDGPU_MES_CMD_REJECTED. Checking !dqm->sched_running || dqm->sched_halt in both functions and returning -EIO would keep them consistent with add_queue_mes() and remove_queue_mes_on_reset_option().

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

PATCH 4/8 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. While the scheduler is stopped, for a suspend or a GPU reset, the reaper leaves the list alone: nothing can be sent to MES then, and it is not the time to unmap and free buffers.

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. The eviction fence is signalled in the first run, where it always was: holding it back protects nothing, because a waiter that enables signaling after the process left the table gets the fence signalled anyway, and it has to be signalled before the context id is free for reuse.

The SVM restore work of the process is cancelled in the release worker and the userptr restore work when the last GPU VM goes away, both of which can now happen an unbounded time after the notifier release. Each looks up the mm of the task, which is a new one after an execve, fails on the old one and queues itself again. Stop both in the notifier release with the other works of the process. An eviction that found the process before it left the table is waited for; later ones find no process, and svm_range_evict() does not queue the restore work then, as the userptr path already does not. The SVM side goes through a helper in kfd_svm.c that is a stub without CONFIG_HSA_AMD_SVM, where svms.restore_work is never initialised. The userptr side takes the amdkfd_process_info from a GPU VM of the process, which is valid for as long as the VM is acquired.

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. At that point KFD has been suspended on a device that is still there, so the scheduler is stopped and no removal could be sent any more, or the device is gone; MES is shut down right after.

The hold is per process, not per device. A process that has exited with a zombie on one GPU therefore also keeps its pdds on every other GPU, and the removal of one of those waits until the zombie is retired, which is not for the departing device to decide. The wait says so after ten seconds. Releasing the pdds device by device would lift this and is left for a follow-up, it means taking the release worker apart.

The zombie list is also searched when a per-queue reset looks up a queue by its doorbell. The reset that KGD starts does that lookup without the dqm lock, as it does today for the queue lists of the processes.

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

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h    |   1 +
 .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c  |  30 +++
 drivers/gpu/drm/amd/amdkfd/kfd_device.c       |  36 +++-
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 179 +++++++++++++++++-
 .../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      |  58 ++++++
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c          |  38 +++-
 drivers/gpu/drm/amd/amdkfd/kfd_svm.h          |   7 +
 9 files changed, 378 insertions(+), 10 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h +1 -0
index 74dc307e5..734497081 100644
@@ -370,6 +370,7 @@ void amdgpu_amdkfd_ras_pasid_poison_consumption_handler(struct amdgpu_device *ad
 bool amdgpu_amdkfd_is_fed(struct amdgpu_device *adev);
 bool amdgpu_amdkfd_bo_mapped_to_dev(void *drm_priv, struct kgd_mem *mem);
 void amdgpu_amdkfd_block_mmu_notifications(void *p);
+void amdgpu_amdkfd_gpuvm_stop_userptr_restore(void *drm_priv);
 int amdgpu_amdkfd_criu_resume(void *p);
 int amdgpu_amdkfd_reserve_mem_limit(struct amdgpu_device *adev,
 		uint64_t size, u32 alloc_flag, int8_t xcp_id);
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +30 -0
index a6616447a..719484220 100644
@@ -1644,6 +1644,36 @@ uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)
 	return avm->pd_phys_addr;
 }
 
+/**
+ * amdgpu_amdkfd_gpuvm_stop_userptr_restore - stop the userptr restore work
+ * @drm_priv: drm private of a compute VM of a KFD process that has left the
+ *            process table
+ *
+ * The work is cancelled for good when the last VM of the process goes away.
+ * KFD can keep the VMs long after the process is gone, and until then the
+ * work would look up the task by pid, find the mm of a new program after an
+ * execve, fail on the user pages of the old one and queue itself again.
+ *
+ * All compute VMs of a process share one amdkfd_process_info, so one call
+ * with any of them is enough. An eviction that found the process before it
+ * left the table holds notifier_lock until it has queued the work, so wait
+ * for that one. A later first eviction gets -ESRCH from the quiesce and does
+ * not queue it.
+ */
+void amdgpu_amdkfd_gpuvm_stop_userptr_restore(void *drm_priv)
+{
+	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
+	struct amdkfd_process_info *pinfo = avm->process_info;
+
+	if (!pinfo)
+		return;
+
+	mutex_lock(&pinfo->notifier_lock);
+	mutex_unlock(&pinfo->notifier_lock);
+
+	cancel_delayed_work_sync(&pinfo->restore_userptr_work);
+}
+
 void amdgpu_amdkfd_block_mmu_notifications(void *p)
 {
 	struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;
drivers/gpu/drm/amd/amdkfd/kfd_device.c +30 -6
index 2200f5c7c..faf882986 100644
@@ -1817,15 +1817,11 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)
 	struct hlist_node *p_temp;
 	struct kfd_process *p;
 	struct kfd_node *dev;
+	unsigned long warn_at;
 	unsigned int temp;
 
 	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;
@@ -1840,12 +1836,40 @@ 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. The caller has
+	 * suspended KFD on a device that is still there, so the queues that
+	 * MES would give up are off the hardware and the scheduler is
+	 * stopped; nothing more could be sent for the others.
+	 */
+	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.
+	 *
+	 * A process holds every device until it is freed, and one that has
+	 * exited is not freed while a queue of it is quarantined on another
+	 * device. That queue is not ours to retire, the firmware it belongs
+	 * to keeps running. Say what the wait is for; a GPU reset of that
+	 * device ends it.
 	 */
-	while (!!atomic_read(&adev->kfd.dev->kfd_processes_count))
+	warn_at = jiffies + 10 * HZ;
+	while (!!atomic_read(&adev->kfd.dev->kfd_processes_count)) {
+		if (warn_at && time_after(jiffies, warn_at)) {
+			dev_warn(adev->dev,
+				 "waiting for %d KFD process(es) to release the device, exited ones are kept by queues quarantined on other GPUs until those GPUs are reset\n",
+				 atomic_read(&adev->kfd.dev->kfd_processes_count));
+			warn_at = 0;
+		}
 		cond_resched();
+	}
 }
 
 int kgd2kfd_reset_mes_queue(struct kfd_dev *kfd, uint32_t node_id,
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +178 -1

221 lines not on this page · raw message

drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.h +14 -0
index 964588d15..aeb807f1d 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(
@@ -358,6 +370,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 76cbab619..d9ab92647 100644
@@ -660,6 +660,19 @@ struct queue {
 	/* MES reset the queue in the recovery that reset_queues_mes() runs */
 	bool mes_reset_seen;
 
+	/*
+	 * 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.
@@ -965,6 +978,17 @@ struct kfd_process {
 	struct kref ref;
 	struct work_struct release_work;
 
+	/*
+	 * Holds on the storage of the process: one for the process itself,
+	 * one for each of its queues on a dqm->zombie_queues list. A zombie
+	 * uses the pdd, the process context, the doorbell page and the GPU
+	 * VM, so the release worker frees those only when the last hold is
+	 * gone.
+	 */
+	atomic_t mes_hold;
+	/* the release worker has dropped the hold of the process itself */
+	bool mes_hold_dropped;
+
 	struct mutex mutex;
 
 	/*
@@ -1452,6 +1476,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 +58 -0

94 lines not on this page · raw message

drivers/gpu/drm/amd/amdkfd/kfd_svm.c +35 -3
index 9affc79eb..e36bfba0f 100644
@@ -2150,9 +2150,19 @@ svm_range_evict(struct svm_range *prange, struct mm_struct *mm,
 			if (r)
 				pr_debug("failed to quiesce KFD\n");
 
-			pr_debug("schedule to restore svm %p ranges\n", svms);
-			queue_delayed_work(system_freezable_wq, &svms->restore_work,
-					   msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
+			/*
+			 * -ESRCH: the process is being released, there are
+			 * no queues to restore, and the restore work has
+			 * been stopped by svm_range_list_stop_restore().
+			 */
+			if (r != -ESRCH) {
+				unsigned long delay =
+					msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS);
+
+				pr_debug("schedule to restore svm %p ranges\n", svms);
+				queue_delayed_work(system_freezable_wq,
+						   &svms->restore_work, delay);
+			}
 		}
 		mutex_unlock(&svms->evict_lock);
 	} else {
@@ -3410,6 +3420,28 @@ svm_range_switch_xnack_reserve_mem(struct kfd_process *p, bool xnack_enabled)
 	return r;
 }
 
+/**
+ * svm_range_list_stop_restore - stop the restore work of a released process
+ * @p: process that has been removed from the process table
+ *
+ * The ranges and their notifiers stay until svm_range_list_fini(), which can
+ * be much later. The restore work must not run in between: it looks up the
+ * mm of the lead thread, which is a different one after an execve.
+ *
+ * An eviction that found the process before it left the table holds
+ * evict_lock until it has queued the work, so wait for that one. Every later
+ * eviction gets -ESRCH from the quiesce and leaves the work alone.
+ */
+void svm_range_list_stop_restore(struct kfd_process *p)
+{
+	struct svm_range_list *svms = &p->svms;
+
+	mutex_lock(&svms->evict_lock);
+	mutex_unlock(&svms->evict_lock);
+
+	cancel_delayed_work_sync(&svms->restore_work);
+}
+
 void svm_range_list_fini(struct kfd_process *p)
 {
 	struct svm_range *prange;
drivers/gpu/drm/amd/amdkfd/kfd_svm.h +7 -0
index 38744e716..c229072ef 100644
@@ -164,6 +164,7 @@ static inline struct svm_range_bo *svm_range_bo_ref(struct svm_range_bo *svm_bo)
 }
 
 int svm_range_list_init(struct kfd_process *p);
+void svm_range_list_stop_restore(struct kfd_process *p);
 void svm_range_list_fini(struct kfd_process *p);
 int svm_ioctl(struct kfd_process *p, enum kfd_ioctl_svm_op op, uint64_t start,
 	      uint64_t size, uint32_t nattrs,
@@ -222,6 +223,12 @@ static inline int svm_range_list_init(struct kfd_process *p)
 {
 	return 0;
 }
+
+static inline void svm_range_list_stop_restore(struct kfd_process *p)
+{
+	/* empty */
+}
+
 static inline void svm_range_list_fini(struct kfd_process *p)
 {
 	/* empty */
Signature · 1 line
2.47.3
#7 lore raw

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

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider: - [Critical] drm/amdkfd: unlocked zombie_queues walk and reset race with zombie reaper - [High] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider:
- [Critical] drm/amdkfd: unlocked zombie_queues walk and reset race with zombie reaper
- [High] drm/amdkfd: zombie_work races with suspend, S0ix halt, and GPU reset
- [High] drm/amdkfd: remove_all_kfd_queues_mes() skips quarantined zombie queues
- [High] drm/amdkfd: self-deadlock in restore workers calling synchronous mmput()
- [High] drm/amdkfd: per-process mes_hold deadlocks multi-GPU PCI bridge hot-unplug
- [High] drm/amdkfd: svm_range_list_stop_restore() fails for secondary kfd_process
- [Medium] drm/amdkfd: amdgpu_amdkfd_criu_resume() races with stop_userptr_restore()
- [Medium] drm/amdkfd: busy-spin in kgd2kfd_teardown_processes() during cross-GPU wait
- [Medium] drm/amdkfd: kfd_dqm_zombie_worker() runs during sched_halt S0ix suspend
--

commit 814b42641595b4e0eb635afb5ca2d6b3f95a1173
Author: Armas Spann <[email protected]>

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

This commit adds a per-device zombie queue list and delayed reaper worker to keep queue and process storage alive until MES confirms retirement or restarts. It also stops the SVM and userptr restore works during MMU notifier release and retires device queues during device teardown.

Quoted 8 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +0 -0
index 36840569b0377..9b79d43ab9ed4 100644
@@ -1643,6 +1643,36 @@ uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)
 	return avm->pd_phys_addr;
 }
 

[ ... ]

drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv) · line 1675

Quoted 13 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +13 -0
+void amdgpu_amdkfd_gpuvm_stop_userptr_restore(void *drm_priv)
+{
+	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
+	struct amdkfd_process_info *pinfo = avm->process_info;
+
+	if (!pinfo)
+		return;
+
+	mutex_lock(&pinfo->notifier_lock);
+	mutex_unlock(&pinfo->notifier_lock);
+
+	cancel_delayed_work_sync(&pinfo->restore_userptr_work);
+}

[Severity: Medium]
Can amdgpu_amdkfd_criu_resume() re-queue pinfo->restore_userptr_work after amdgpu_amdkfd_gpuvm_stop_userptr_restore() returns?

amdgpu_amdkfd_gpuvm_stop_userptr_restore() only drains pinfo->notifier_lock and does not record a stopped state under pinfo->lock:

CPU0 CPU1
criu_resume()
kfd_lookup_process_by_pid()
mutex_lock(&p->mutex)

                                  kfd_process_notifier_release_internal()
                                    kfd_process_table_remove(p)
                                    ..._stop_userptr_restore()
                                      cancel_delayed_work_sync()
                                    kfd_process_dequeue_from_all_devices()
                                      mutex_lock(&p->mutex)  (blocks)

amdgpu_amdkfd_criu_resume()
queue_delayed_work() <-- re-queued

If a queue is then quarantined, restore_userptr_work keeps running and rescheduling itself against the process pid until the zombie retires. Recording a stopped flag on pinfo under pinfo->lock and checking it in amdgpu_amdkfd_criu_resume() would close this race.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +0 -0
index 2200f5c7c38d6..faf882986f1bb 100644

[ ... ]

Quoted 7 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +3 -0
@@ -1840,12 +1836,40 @@ 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

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +10 -0
+	 * it has left the table. The device is going away, so stop waiting
+	 * for MES, whether the table is empty or not. The caller has
+	 * suspended KFD on a device that is still there, so the queues that
+	 * MES would give up are off the hardware and the scheduler is
+	 * stopped; nothing more could be sent for the others.
+	 */
+	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);
+	}

[Severity: High]
Can this deadlock multi-GPU PCIe bridge hot-unplug when a process has active queues on two MES GPUs behind the same bridge?

On surprise hot-unplug, pciehp_unconfigure_device() marks all downstream GPUs disconnected, takes pci_rescan_remove_lock, and removes them serially. kgd2kfd_teardown_processes() on GPU 0 signals the process with SIGBUS, calls kfd_dqm_retire_all() only on GPU 0, and waits for GPU 0's kfd_processes_count to reach zero.

When the process exits, GPU 1 has not entered amdgpu_pci_remove() yet, so its dqm->mes_retire_all is still false and kfd_mes_queue_retired() does not check pci_dev_is_disconnected(). remove_queue_mes() on disconnected GPU 1 times out, GPU reset aborts on the disconnected bus, and the queue is quarantined with a p->mes_hold reference. Because kfd_process_wq_release() defers kfd_process_destroy_pdds() for all GPUs until p->mes_hold reaches zero, GPU 0 waits forever while holding pci_rescan_remove_lock, preventing GPU 1's removal from ever running.

Checking pci_dev_is_disconnected(adev->pdev) in kfd_mes_queue_retired() would let disconnected sibling GPUs retire their queues instead of deadlocking bridge removal.

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device.c +9 -0
+	warn_at = jiffies + 10 * HZ;
+	while (!!atomic_read(&adev->kfd.dev->kfd_processes_count)) {
+		if (warn_at && time_after(jiffies, warn_at)) {
+			dev_warn(adev->dev,
+				 "waiting for %d KFD process(es) to release the device, exited ones are kept by queues quarantined on other GPUs until those GPUs are reset\n",
+				 atomic_read(&adev->kfd.dev->kfd_processes_count));
+			warn_at = 0;
+		}
 		cond_resched();
+	}

[Severity: Medium]
Should this loop sleep instead of busy-spinning with cond_resched()?

Now that this wait can last past 10 seconds or indefinitely when an exited process is held by a quarantined queue on another GPU, cond_resched() keeps the task in TASK_RUNNING and burns 100% of a CPU core for the entire wait. Pairing atomic_dec_and_test(&pdd->dev->kfd->kfd_processes_count) in kfd_process_destroy_pdds() with wake_up_var() and waiting via wait_var_event_timeout() / wait_var_event() would avoid pegging a CPU.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index 5e58509787385..f31765cb8cc5d 100644

[ ... ]

Quoted 3 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
@@ -1803,6 +1813,158 @@ static int dqm_repin_mqd_bo(struct device_queue_manager *dqm, struct queue *q)
 	return 0;
 }

[ ... ]

Quoted 11 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +11 -0
+static void kfd_dqm_zombie_worker(struct work_struct *work)
+{
+	struct device_queue_manager *dqm =
+		container_of(to_delayed_work(work),
+			     struct device_queue_manager, zombie_work);
+	struct queue *q, *tmp;
+	LIST_HEAD(retired);
+	bool more;
+
+	dqm_lock(dqm);
+	/*

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	 * The scheduler is stopped for a suspend or a GPU reset. Nothing can
+	 * be sent to MES then, and the device is in no state to have buffers
+	 * unmapped and freed. start_cpsch() kicks the reaper when that is
+	 * over. A device that is being removed stays stopped, and its
+	 * zombies have to go now.
+	 */
+	if (!dqm->sched_running && !dqm->mes_retire_all) {
+		dqm_unlock(dqm);
+		return;
+	}

[Severity: Medium]
Should this guard also check dqm->sched_halt?

During S0ix suspend, amdgpu_amdkfd_suspend() calls kgd2kfd_stop_sched_all_nodes() -> halt_cpsch(), which sets dqm->sched_halt = true while leaving dqm->sched_running true. Because zombie_work runs on the non-freezable system_dfl_wq and ignores sched_halt, it keeps polling every 500 ms across S0ix and will unmap, repin, and free BOs while the device is suspending into S0ix/D3 if a queue retires. Pausing on dqm->sched_halt and kicking zombie_work in unhalt_cpsch() (matching start_cpsch()) would handle S0ix suspend and resume.

[ ... ]

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

Quoted 12 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +12 -0
+	more = !list_empty(&dqm->zombie_queues);
+	dqm_unlock(dqm);
+
+	list_for_each_entry_safe(q, tmp, &retired, zombie_node) {
+		list_del(&q->zombie_node);
+		kfd_dqm_release_zombie(dqm, q);
+	}
+
+	if (more)
+		queue_delayed_work(system_dfl_wq, &dqm->zombie_work,
+				   msecs_to_jiffies(KFD_MES_ZOMBIE_POLL_MS));
+}

[Severity: High]
Can kfd_dqm_release_zombie() run concurrently with system suspend or a GPU reset after dqm_unlock(dqm)?

stop_cpsch() sets dqm->sched_running = false under dqm_lock(dqm) and returns without waiting for an in-flight zombie_work to finish:

kworker CPU1
kfd_dqm_zombie_worker()
dqm_lock(dqm)
list_move_tail(..., &retired)
dqm_unlock(dqm)

                                  amdgpu_device_suspend()
                                    stop_cpsch()
                                      dqm->sched_running = false
                                    amdgpu_device_evict_resources()
                                    amdgpu_ttm_disable_buffer_funcs()

kfd_dqm_release_zombie()
kfd_queue_unref_bo_vas() <-- races with suspend / reset
dqm_repin_mqd_bo()

kfd_dqm_release_zombie() unmaps BO VAs, repins VRAM MQDs, frees kernel BOs, and can trigger kfd_process_wq_release() while amdgpu_device_suspend() is evicting VRAM and tearing down fences (or while kgd2kfd_pre_reset() proceeds into a GPU reset). Cancelling zombie_work outside dqm_lock(dqm) when stopping the scheduler would prevent this overlap.

Quoted 7 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +7 -0
+/*
+ * The device is being removed. KFD has been suspended by then, which took
+ * every queue off the hardware that MES would let go of and stopped the
+ * scheduler, or the device is gone altogether. Either way no command can be
+ * sent for what is left, and MES is shut down right after, so nothing a
+ * queue holds can be handed to a new owner that MES would then corrupt.
+ * Treat every queue as retired and release all zombies, so that process

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+ * teardown can finish.
+ */
+void kfd_dqm_retire_all(struct device_queue_manager *dqm)
+{
+	dqm_lock(dqm);
+	dqm->mes_retire_all = true;
+	dqm_unlock(dqm);
+
+	mod_delayed_work(system_dfl_wq, &dqm->zombie_work, 0);
+}

[Severity: High]
Are KFD_MES_QUEUE_MAPPED zombies actually removed from MES before kfd_dqm_retire_all() frees their storage?

remove_all_kfd_queues_mes() (called from stop_cpsch() and halt_cpsch()) only walks dqm->queues and each qpd->queues_list, skipping dqm->zombie_queues. If a queue was quarantined in KFD_MES_QUEUE_MAPPED state (for example, destroyed while the scheduler was halted or a reset held reset_domain->sem), amdgpu_amdkfd_suspend() during amdgpu_device_ip_fini_early() leaves it mapped on MES. kfd_dqm_retire_all() then immediately marks it retired and kfd_dqm_release_zombie() frees its MQD, gang context, wptr mapping, and GPU VM while MES is still running, before amdgpu_ip_block_hw_fini() shuts MES down.

Walking dqm->zombie_queues in remove_all_kfd_queues_mes() would unmap still-mapped zombies on suspend and unload.

[ ... ]

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

Quoted 12 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +6 -0
@@ -3051,6 +3217,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: Critical]
Can this unlocked walk of dqm->zombie_queues race with kfd_dqm_zombie_worker() freeing a zombie?

KGD-initiated per-queue resets (amdgpu_gfx_reset_mes_compute() -> amdgpu_amdkfd_reset_mes_queue() -> kfd_reset_queue_mes()) call find_queue_by_doorbell_offset() for every hung doorbell holding only adev->gfx.mec.reset_mutex, without dqm_lock(dqm):

CPU0 kworker
amdgpu_gfx_reset_mes_compute()
kfd_reset_queue_mes()

    find_queue_by_doorbell_offset()
      walk dqm->zombie_queues
                                  kfd_dqm_zombie_worker()
                                    dqm_lock(dqm)
                                    list_move_tail(..., &retired)
                                    dqm_unlock(dqm)
                                    list_del(&q->zombie_node)
                                    kfd_dqm_release_zombie()
                                      uninit_queue(q)
      dereference q / next        <-- use-after-free / LIST_POISON1

Splicing a node onto the worker's stack-local retired list redirects the unlocked walker off dqm->zombie_queues onto the stack head or hits LIST_POISON1 written by list_del(). Even if find_queue_by_doorbell_offset() returns q first, nothing pins q, pdd, or p, so reset_queue_mes() can dereference freed memory after kfd_dqm_release_zombie() runs.

On the same unlocked path, reset_queue_mes() -> remove_queue_mes_on_reset_option() -> kfd_mes_queue_retired() -> amdgpu_mes_ticket_release() can also race with kfd_dqm_zombie_worker() and double free ticket->status_offs via amdgpu_wb_free().

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +0 -0
index d30386893c6aa..878a6666fc13a 100644

[ ... ]

Quoted 9 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +5 -0
@@ -1469,6 +1511,21 @@ 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() and to the destruction of the
+	 * GPU VMs: the release worker may now run long after this, and the
+	 * SVM and userptr restore works look up the mm of the task, which
+	 * can be a new one by then. Both keep queueing themselves as long

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_process.c +10 -0
+	 * as they fail.
+	 */
+	svm_range_list_stop_restore(p);
+	for (i = 0; i < p->n_pdds; i++) {
+		/* One call covers the process, its VMs share the work */
+		if (p->pdds[i]->drm_priv) {
+			amdgpu_amdkfd_gpuvm_stop_userptr_restore(p->pdds[i]->drm_priv);
+			break;
+		}
+	}

[Severity: High]
Does calling cancel_delayed_work_sync() for the SVM and userptr restore works here self-deadlock when either worker drops the final mm_users reference?

Both svm_range_restore_work() and amdgpu_amdkfd_restore_userptr_worker() take the mm via get_task_mm() and release it with synchronous mmput(mm) instead of mmput_async(mm). If the process exits or calls execve() while either worker is running, that worker holds the last mm_users reference:

svm_range_restore_work() [or amdgpu_amdkfd_restore_userptr_worker()]
mmput(mm)

    __mmput(mm) -> exit_mmap(mm) -> mmu_notifier_release(mm)
      kfd_process_notifier_release_internal(p)
        cancel_delayed_work_sync(&svms->restore_work)  <-- self-deadlock

The system_freezable_wq kworker waits forever for itself while holding the global mmu_notifier SRCU read lock, which also blocks later synchronize_srcu() calls in mm/mmu_notifier.c and prevents system suspend. Switching both workers to mmput_async(mm) (as svm_range_deferred_list_work() already does) avoids the self-deadlock.

Quoted 16 lines
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +5 -3
index 9affc79eb8330..e36bfba0fb644 100644
@@ -2150,9 +2150,19 @@ svm_range_evict(struct svm_range *prange, struct mm_struct *mm,
 			if (r)
 				pr_debug("failed to quiesce KFD\n");
 
-			pr_debug("schedule to restore svm %p ranges\n", svms);
-			queue_delayed_work(system_freezable_wq, &svms->restore_work,
-					   msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
+			/*
+			 * -ESRCH: the process is being released, there are
+			 * no queues to restore, and the restore work has
+			 * been stopped by svm_range_list_stop_restore().
+			 */

drivers/gpu/drm/amd/amdkfd/kfd_svm.c svm_range_evict(struct svm_range *prange, struct mm_struct *mm, · line 2167

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +8 -0
+			if (r != -ESRCH) {
+				unsigned long delay =
+					msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS);
+
+				pr_debug("schedule to restore svm %p ranges\n", svms);
+				queue_delayed_work(system_freezable_wq,
+						   &svms->restore_work, delay);
+			}
 		}
 		mutex_unlock(&svms->evict_lock);

[Severity: High]
Does relying on kgd2kfd_quiesce_mm() returning -ESRCH stop svms->restore_work for a secondary kfd_process?

kgd2kfd_quiesce_mm() looks up the process via find_process_by_mm(), which matches process->context_id == KFD_CONTEXT_ID_PRIMARY. When a secondary kfd_process is closed via kfd_release() -> kfd_process_notifier_release_internal() while the primary process for the same mm is still alive, a subsequent MMU invalidation on an unregistered SVM range (created via svm_range_restore_pages() on a GPU retry fault, with XNACK then disabled via kfd_ioctl_set_xnack_mode()) gets 0 from kgd2kfd_quiesce_mm() instead of -ESRCH and re-queues the secondary process's svms->restore_work.

If that invalidation runs during svm_range_list_fini() between cancel_delayed_work_sync(&p->svms.restore_work) and svm_range_remove_notifier(), svms->restore_work fires after kfree(p), causing a use-after-free in svm_range_restore_work(). Setting a per-svms stopped flag under svms->evict_lock in svm_range_list_stop_restore() and checking it before queueing svms->restore_work would handle secondary processes as well.

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

PATCH 5/8 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, the ids, the gang context and the write pointer mapping 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. An ADD_QUEUE that is executed late maps a queue whose MQD and gang context are gone.

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() drops the unmap protection of the ring, pointers, EOP and CWSR buffers before it asks the dqm to destroy the queue. When the dqm refuses, for a queue of a process that is being debugged, or for a second destroy while the first one sleeps on a queue the debugger has suspended, the queue stays as it is, but its buffers can now be unmapped under it. 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. If that fails, the queue remembers that it holds no reference on an SVM range for its CWSR area, and the reaper does not drop one: it would be the reference of another queue on the same range.

process_termination_cpsch() takes the process off dqm->queues and then frees the MQDs one by one, dropping the dqm lock for each. A queue that MES has not let go of is moved to the quarantine before the lock is dropped for the first time, so that a per-queue reset that runs in between finds it on one list or the other.

For user space a destroy that the dqm carried out now always removes the queue id; the value it returns is the one the dqm returned, as before.

Two 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.

What the quarantine keeps is the storage of the queue: allocated, pinned where it was pinned, and referenced. It does not stop TTM from moving the user buffers of a process that has exited, the eviction fence is signalled by then.

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 | 124 ++++++++++++++----
 drivers/gpu/drm/amd/amdkfd/kfd_priv.h         |   4 +
 .../amd/amdkfd/kfd_process_queue_manager.c    |  95 ++++++++++----
 drivers/gpu/drm/amd/amdkfd/kfd_queue.c        |  78 ++++++++++-
 4 files changed, 248 insertions(+), 53 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +95 -29
index 1e18bc63f..9c40a7cfd 100644
@@ -1396,6 +1396,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",
@@ -1832,9 +1833,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);
 
@@ -1876,7 +1877,8 @@ static void kfd_dqm_release_zombie(struct device_queue_manager *dqm,
 	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);
+	/* The last argument decides whether an SVM reference is dropped */
+	kfd_queue_release_buffers(pdd, &q->properties, q->zombie_no_svm_ref);
 	mutex_unlock(&p->mutex);
 
 	/* Device side */
@@ -3033,8 +3035,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:
@@ -3546,6 +3561,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) ||
@@ -3588,13 +3604,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);
@@ -3605,11 +3617,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--;
 
 	/*
@@ -3620,6 +3639,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);
 
 	/*
@@ -3630,9 +3664,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;
 
@@ -3816,7 +3852,7 @@ static int process_termination_cpsch(struct device_queue_manager *dqm,
 		struct qcm_process_device *qpd)
 {
 	int retval = 0;
-	struct queue *q;
+	struct queue *q, *q_next;
 	struct device *dev = dqm->dev->adev->dev;
 	struct kernel_queue *kq, *kq_next;
 	struct mqd_manager *mqd_mgr;
@@ -3838,20 +3874,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--;
@@ -3879,6 +3913,25 @@ static int process_termination_cpsch(struct device_queue_manager *dqm,
 		up_read(&dqm->dev->adev->reset_domain->sem);
 	}
 
+	/*
+	 * Quarantine what MES has not let go of. All of it now, before the
+	 * lock is dropped for the first time below: the process is off
+	 * dqm->queues, so from here on the zombie list is the only place
+	 * where a per-queue reset finds a queue that MES reports as hung.
+	 * Whether MES has let go is decided once per queue. What is left on
+	 * the list afterwards is retired and stays that way, and its SDMA id
+	 * goes with its MQD.
+	 */
+	list_for_each_entry_safe(q, q_next, &qpd->queues_list, list) {
+		if (kfd_mes_queue_retired(dqm, q))
+			continue;
+
+		list_del(&q->list);
+		q->dqm_dequeued = true;
+		qpd->queue_count--;
+		dqm_quarantine_queue(dqm, qpd, q);
+	}
+
 	/* Lastly, free mqd resources.
 	 * Do free_mqd() after dqm_unlock to avoid circular locking.
 	 */
@@ -3887,7 +3940,13 @@ 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--;
+
+		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);
@@ -4172,8 +4231,15 @@ int kfd_dqm_suspend_bad_queue_mes(struct kfd_node *knode, u32 pasid, u32 doorbel
 					kfd_hws_hang(dqm);
 				}
 				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 +4 -0
index d9ab92647..f8ab1bde8 100644
@@ -672,6 +672,8 @@ struct queue {
 	bool zombie_ready;
 	/* the dqm took the queue off its lists, the pqm has to finish */
 	bool dqm_dequeued;
+	/* no SVM reference on the CWSR area to drop. Set before zombie_ready */
+	bool zombie_no_svm_ref;
 
 	/* 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
@@ -1440,6 +1442,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 +72 -23

123 lines not on this page · raw message

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

90 lines not on this page · raw message

Signature · 1 line
2.47.3
#9 lore raw

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

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] drm/amdkfd: lockless zombie_queues walk and UAF in kfd_reset_queue_mes() - [Medium] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] drm/amdkfd: lockless zombie_queues walk and UAF in kfd_reset_queue_mes()
- [Medium] drm/amdkfd: remove_all_kfd_queues_mes() skips quarantined zombie queues
- [Medium] drm/amdkfd: kfd_process_dequeue_from_device() flushes MES ctx with zombies
- [Medium] drm/amdkfd: kfd_queue_hold_buffers() leaves zombie_no_svm_ref unset
- [Medium] drm/amdkfd: kfd_queue_hold_bo() calls amdgpu_vm_bo_find() unlocked
--

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

drm/amdkfd: keep queue storage until MES confirmed retirement

This commit wires up the MES queue quarantine across queue creation failure, queue destruction, and process termination so that doorbell and SDMA IDs, MQDs, MES resources, and user buffer references are kept until MES confirms queue retirement. It also defers releasing IDs and buffer references until after the DQM unlinks a queue and ensures is_active is cleared on deactivation.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
index f31765cb8cc5d..58c8efd168011 100644

[ ... ]

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

Quoted 13 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +3 -3
@@ -1832,9 +1833,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);
 

[Severity: High]
Can populating dqm->zombie_queues race with KGD-initiated per-queue resets in kfd_reset_queue_mes()?

dqm_quarantine_queue() and kfd_dqm_zombie_worker() mutate dqm->zombie_queues under dqm_lock(dqm). When KGD resets a hung compute queue via gfx_v11_0_reset_kcq() -> amdgpu_gfx_reset_mes_compute(), it holds only adev->gfx.mec.reset_mutex and calls kfd_reset_queue_mes() without dqm_lock(dqm):

CPU0 CPU1
gfx_v11_0_reset_kcq()
amdgpu_gfx_reset_mes_compute()

    kfd_reset_queue_mes()
      find_queue_by_doorbell_offset()
        /* walks dqm->zombie_queues
           without dqm_lock */
                                      kfd_dqm_zombie_worker()
                                        dqm_lock(dqm)
                                        list_move_tail(&q->zombie_node,
                                                       &retired)
                                        dqm_unlock(dqm)
                                        list_del(&q->zombie_node)
                                        kfd_dqm_release_zombie(dqm, q)
                                          uninit_queue(q)
      reset_queue_mes(dqm, q)
        q->mes_reset_seen = true      <-- use-after-free

CPU0 can follow LIST_POISON1 or walk into CPU1's stack-local retired list head during traversal, or write to the freed struct queue and concurrently release q->mes_ticket in reset_queue_mes(). Note that kfd_reset_queue_mes() cannot unconditionally take dqm_lock(dqm) because KFD's own reset_queues_mes() invokes amdgpu_gfx_reset_mes_compute() with dqm_lock(dqm) already held.

[ ... ]

Quoted 9 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +5 -0
@@ -3620,6 +3639,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.
+	 */

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

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

[Severity: Medium]
Should remove_all_kfd_queues_mes() also walk dqm->zombie_queues?

When remove_queue_mes() returns -EIO without submitting REMOVE_QUEUE (for example during reset_domain->sem contention or a temporary MES fence), destroy_queue_cpsch() and process_termination_cpsch() move the queue onto dqm->zombie_queues in KFD_MES_QUEUE_MAPPED state. remove_all_kfd_queues_mes() only iterates dqm->queues, so halt_cpsch() and stop_cpsch() return 0 with that zombie still mapped in MES.

Callers such as psp_performance_monitor_hw() then fail amdgpu_device_ip_wait_for_idle() on GFX, and stop_cpsch() clears dqm->sched_running so kfd_dqm_zombie_worker() cannot remove the zombie until resume.

[ ... ]

Quoted 13 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +9 -0
@@ -3879,6 +3913,25 @@ static int process_termination_cpsch(struct device_queue_manager *dqm,
 		up_read(&dqm->dev->adev->reset_domain->sem);
 	}
 
+	/*
+	 * Quarantine what MES has not let go of. All of it now, before the
+	 * lock is dropped for the first time below: the process is off
+	 * dqm->queues, so from here on the zombie list is the only place
+	 * where a per-queue reset finds a queue that MES reports as hung.
+	 * Whether MES has let go is decided once per queue. What is left on
+	 * the list afterwards is retired and stays that way, and its SDMA id
+	 * goes with its MQD.
+	 */

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+	list_for_each_entry_safe(q, q_next, &qpd->queues_list, list) {
+		if (kfd_mes_queue_retired(dqm, q))
+			continue;
+
+		list_del(&q->list);
+		q->dqm_dequeued = true;
+		qpd->queue_count--;
+		dqm_quarantine_queue(dqm, qpd, q);
+	}
+

[Severity: Medium]
Does kfd_process_dequeue_from_device() flush the MES process context even when process_termination_cpsch() quarantined queues for that process?

Right after process_termination_cpsch() returns, kfd_process_dequeue_from_device() unconditionally calls amdgpu_mes_flush_shader_debugger() with flags.process_ctx_flush = true. When MES is still responsive and owns a quarantined queue, this tells MES to retire the process context while that queue still references pdd->proc_ctx_gpu_addr and pdd->proc_ctx_array_index.

When MES is fenced off after a timed-out REMOVE_QUEUE, amdgpu_mes_flush_shader_debugger() also bypasses kfd_mes_fenced() and submits another blocking packet to the stalled MES ring, stalling process teardown and the GPU reset needed for recovery.

[ ... ]

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +0 -0
index 435393221930a..94b23009ca890 100644

[ ... ]

Quoted 16 lines
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +12 -0
@@ -426,6 +427,81 @@ int kfd_queue_unref_bo_vas(struct kfd_process_device *pdd,
 	return 0;
 }
 
+static void kfd_queue_hold_bo(struct amdgpu_vm *vm, struct amdgpu_bo *bo)
+{
+	struct amdgpu_bo_va *bo_va;
+
+	if (!bo)
+		return;
+
+	amdgpu_bo_ref(bo);
+	bo_va = amdgpu_vm_bo_find(vm, bo);
+	if (bo_va)
+		bo_va->queue_refcount++;
+}

[ ... ]

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +10 -0
+	err = amdgpu_bo_reserve(vm->root.bo, true);
+	if (err) {
+		/*
+		 * Nothing was taken. The pointers are copies of the ones
+		 * the caller of the create owns, forget them so that the
+		 * release has nothing to drop.
+		 */
+		properties->wptr_bo = NULL;
+		properties->rptr_bo = NULL;
+		properties->ring_bo = NULL;

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +10 -0
+		properties->eop_buf_bo = NULL;
+		properties->cwsr_bo = NULL;
+		return err;
+	}
+
+	kfd_queue_hold_bo(vm, properties->wptr_bo);
+	kfd_queue_hold_bo(vm, properties->rptr_bo);
+	kfd_queue_hold_bo(vm, properties->ring_bo);
+	kfd_queue_hold_bo(vm, properties->eop_buf_bo);
+	kfd_queue_hold_bo(vm, properties->cwsr_bo);

[Severity: Medium]
Can kfd_queue_hold_bo() trigger a use-after-free in amdgpu_vm_bo_find() because each queue BO is not reserved?

kfd_queue_hold_buffers() reserves only vm->root.bo, but KFD user BOs have individual dma_resv locks and amdgpu_vm_bo_find() walks bo->vm_bo across all VMs mapping the BO. If another VM shares the BO, it can concurrently unlink and free its amdgpu_bo_va under bo->tbo.base.resv:

CPU0 CPU1
kfd_queue_hold_buffers()
amdgpu_bo_reserve(vm->root.bo, ...)
kfd_queue_hold_bo(vm, bo)

    amdgpu_vm_bo_find(vm, bo)
      /* walks bo->vm_bo unlocked */
                                      amdgpu_vm_bo_del(adev, bo_va2)
                                        /* holds bo->tbo.base.resv */
                                        *base = bo_va2->base.next
                                        kfree(bo_va2)
      base = base->next               <-- use-after-free

This can also miss incrementing bo_va->queue_refcount, leaving an unbalanced decrement when the zombie is later released.

[ ... ]

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

Quoted 3 lines
drivers/gpu/drm/amd/amdkfd/kfd_queue.c +3 -0
+	/* The CWSR area of a compute queue is a BO, or an SVM range */
+	if (properties->type != KFD_QUEUE_TYPE_COMPUTE || properties->cwsr_bo)
+		return 0;

[Severity: Medium]
Does returning 0 here leave q->zombie_no_svm_ref unset for SDMA and BO-backed CWSR queues?

pqm_create_queue() only sets q->zombie_no_svm_ref = true when kfd_queue_hold_buffers() returns non-zero. When a quarantined SDMA or BO-backed CWSR queue from a failed create is later reaped, kfd_dqm_release_zombie() calls kfd_queue_release_buffers() with false, which unconditionally calls kfd_queue_buffer_svm_put() on properties->ctx_save_restore_area_address.

That drops an SVM queue_refcount belonging to another active compute queue sharing the range, allowing munmap() to skip kgd2kfd_quiesce_mm() while GPU waves are still running.

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

PATCH 6/8 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 until the reset is over.

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. The rollback ends with the TLB flush that an eviction ends with: the queues it takes off have been running, and the next eviction finds the process evicted already and does nothing.

That leaves the queues whose removal could not be sent, at the eviction or in the rollback. They stay on the hardware while the process counts as evicted, and two places take that for a clean state:

- An eviction that finds qpd->evicted set returns 0 without looking. Make it return -EIO as long as MES has a queue of the process, so that a second eviction does not signal the fence the first one held back.
- A restore finds such a queue mapped and leaves it as it is, with the page table base from before the eviction. Make it remove the queue first and fail, to be retried, if that is still not possible.

One case is left as it is: a queue that the bad queue interrupt path has deactivated and that MES would not give up is skipped by the first eviction of its process, which only looks at active queues. Its storage is safe, the destroy and termination paths ask kfd_mes_queue_retired() whatever is_active says.

---
 .../drm/amd/amdkfd/kfd_device_queue_manager.c | 114 ++++++++++++++++--
 drivers/gpu/drm/amd/amdkfd/kfd_process.c      |   7 +-
 2 files changed, 108 insertions(+), 13 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +103 -11
index 9c40a7cfd..468e22d18 100644
@@ -2017,6 +2017,23 @@ static int evict_process_queues_nocpsch(struct device_queue_manager *dqm,
 	return ret;
 }
 
+/*
+ * dqm lock held. True if MES still has a queue of a process that counts as
+ * evicted: a removal could not be sent, or was not confirmed.
+ */
+static bool kfd_mes_has_queue_of(struct device_queue_manager *dqm,
+				 struct qcm_process_device *qpd)
+{
+	struct queue *q;
+
+	list_for_each_entry(q, &qpd->queues_list, list) {
+		if (!kfd_mes_queue_retired(dqm, q))
+			return true;
+	}
+
+	return false;
+}
+
 static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
 				      struct qcm_process_device *qpd)
 {
@@ -2026,8 +2043,18 @@ static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
 	int retval = 0;
 
 	dqm_lock(dqm);
-	if (qpd->evicted++ > 0) /* already evicted, do nothing */
+	if (qpd->evicted++ > 0) { /* already evicted, do nothing */
+		/*
+		 * Nothing to do is not the same as nothing left running. If
+		 * the eviction that came first, or the rollback of a failed
+		 * restore, could not get a queue off the hardware, this
+		 * caller must not be told that its memory is safe to move
+		 * either.
+		 */
+		if (kfd_mes_has_queue_of(dqm, qpd))
+			retval = -EIO;
 		goto out;
+	}
 
 	pdd = qpd_to_pdd(qpd);
 
@@ -2056,11 +2083,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;
 			}
 		}
 
@@ -2270,25 +2310,48 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 	/* activate all active queues on the qpd */
 	list_for_each_entry(q, &qpd->queues_list, list) {
 		q->properties.is_evicted = false;
+
+		/*
+		 * The eviction, or the rollback of an earlier restore, could
+		 * not take this queue off the hardware (-EIO). MES still has
+		 * it, with the page table base it was added with, and
+		 * add_queue_mes() would leave it at that. Remove it first,
+		 * now that MES can be talked to again. A removal that was
+		 * sent and failed is not repeated; add_queue_mes() refuses
+		 * such a queue below.
+		 */
+		if (q->mes_state == KFD_MES_QUEUE_MAPPED &&
+		    !kfd_mes_queue_retired(dqm, q)) {
+			retval = remove_queue_mes(dqm, q, qpd);
+			if (retval) {
+				dev_err(dev, "Failed to evict queue %d before its restore\n",
+					q->properties.queue_id);
+				goto rollback;
+			}
+		}
+
 		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;
 			}
 		}
 	}
@@ -2302,6 +2365,35 @@ 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);
+	}
+
+	/*
+	 * As at the end of an eviction: the queues that were taken off
+	 * above have been running, MES does not flush the TLB for them, and
+	 * the next eviction finds qpd->evicted set and does nothing.
+	 */
+	if (dqm->dev->kfd->shared_resources.enable_mes)
+		kfd_flush_tlb(pdd);
+	goto out;
 }
 
 static int register_process(struct device_queue_manager *dqm,
drivers/gpu/drm/amd/amdkfd/kfd_process.c +5 -2
index f1b30d186..d2e349ae5 100644
@@ -2256,7 +2256,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;
 
@@ -2277,12 +2277,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 6/8] drm/amdkfd: keep eviction and restore consistent when MES fails

Thank you for your contribution! Sashiko AI review found 10 potential issues to consider: - [High] drm/amdkfd: interleaved stale queue removal and missing TLB flush on restore - [High] drm/amdkfd…

Thank you for your contribution! Sashiko AI review found 10 potential issues to consider:
- [High] drm/amdkfd: interleaved stale queue removal and missing TLB flush on restore
- [High] drm/amdkfd: first eviction skips inactive unretired MES queues
- [High] drm/amdkfd: eviction ignores quarantined queues on dqm->zombie_queues
- [High] drm/amdkfd: nested eviction increments qpd->evicted before returning -EIO
- [Medium] drm/amdkfd: premature kfd_last_flushed_seq update while MES holds queues
- [Medium] drm/amdkfd: kfd_flush_tlb() in restore rollback skips unchanged tlb_seq
- [Medium] drm/amdkfd: restore_process_queues_cpsch() re-adds reset hung MES queue
- [Medium] drm/amdkfd: kfd_flush_tlb() bypasses MES fence on evict/restore fail
- [Medium] drm/amdkfd: add_queue_mes() skips retired check while halted
- [Low] drm/amdkfd: missing Fixes trailers for MES eviction and -EIO bugs
--

commit 2506f1259cff9bbb9ada0657a6cfb1b38e190baa
Author: Armas Spann <[email protected]>

Quoted 44 lines

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

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 until the reset is over.

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. The rollback ends with the TLB flush that an eviction ends with: the queues it takes off have been running, and the next eviction finds the process evicted already and does nothing.

That leaves the queues whose removal could not be sent, at the eviction or in the rollback. They stay on the hardware while the process counts as evicted, and two places take that for a clean state:

- An eviction that finds qpd->evicted set returns 0 without looking. Make it return -EIO as long as MES has a queue of the process, so that a second eviction does not signal the fence the first one held back.
- A restore finds such a queue mapped and leaves it as it is, with the page table base from before the eviction. Make it remove the queue first and fail, to be retried, if that is still not possible.

Quoted 8 lines

One case is left as it is: a queue that the bad queue interrupt path has deactivated and that MES would not give up is skipped by the first eviction of its process, which only looks at active queues. Its storage is safe, the destroy and termination paths ask kfd_mes_queue_retired() whatever is_active says.

[Severity: Low]
This fixes pre-existing bugs in the MES eviction/restore path and in multi-device -EIO propagation in kfd_process_evict_queues(). Should this include:

Fixes cc009e613de6 ("drm/amdkfd: Add KFD support for soc21 v3")
Fixes b8c20c74ab8c ("drm/amd/amdkfd: Don't sent command to HWS on kfd reset")
Quoted 14 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +6 -0
index 58c8efd168011..f20fcccbe88f0 100644
@@ -2017,6 +2017,23 @@ static int evict_process_queues_nocpsch(struct device_queue_manager *dqm,
 	return ret;
 }
 
+/*
+ * dqm lock held. True if MES still has a queue of a process that counts as
+ * evicted: a removal could not be sent, or was not confirmed.
+ */
+static bool kfd_mes_has_queue_of(struct device_queue_manager *dqm,
+				 struct qcm_process_device *qpd)

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+{
+	struct queue *q;
+
+	list_for_each_entry(q, &qpd->queues_list, list) {
+		if (!kfd_mes_queue_retired(dqm, q))
+			return true;
+	}
+
+	return false;
+}

[Severity: High]
Does kfd_mes_has_queue_of() miss quarantined queues on dqm->zombie_queues?

When destroy_queue_cpsch() destroys a queue that MES has not retired, it unlinks the queue from qpd->queues_list and moves it to dqm->zombie_queues with q->zombie_pdd = pdd. If a first eviction fails with -EIO and userspace destroys that queue while the process stays alive, a subsequent eviction sees nothing unretired on qpd->queues_list and returns 0.

evict_process_worker() then signals p->ef, letting TTM move or reallocate the live process's VRAM BOs while MES still holds the quarantined queue mapped in its GPU VM. Scanning dqm->zombie_queues for entries with q->zombie_pdd == qpd_to_pdd(qpd) under the held dqm lock would cover those queues too.

Quoted 7 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +2 -1
@@ -2026,8 +2043,18 @@ static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
 	int retval = 0;
 
 	dqm_lock(dqm);
-	if (qpd->evicted++ > 0) /* already evicted, do nothing */
+	if (qpd->evicted++ > 0) { /* already evicted, do nothing */
+		/*

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +9 -0
+		 * Nothing to do is not the same as nothing left running. If
+		 * the eviction that came first, or the rollback of a failed
+		 * restore, could not get a queue off the hardware, this
+		 * caller must not be told that its memory is safe to move
+		 * either.
+		 */
+		if (kfd_mes_has_queue_of(dqm, qpd))
+			retval = -EIO;
 		goto out;
+	}

[Severity: High]
Can incrementing qpd->evicted before returning -EIO leak the eviction refcount and deadlock p->ef?

kfd_process_evict_queues() preserves -EIO without rolling back qpd->evicted, and evict_process_worker() takes its error branch on any non-zero return without calling kfd_process_restore_queues(), scheduling p->restore_work, or signaling p->ef:

restore_process_worker evict_process_worker
restore_process_helper()
...restore_process_bos()

    attach new p->ef
  restore_process_queues_cpsch()
    add Q1, fail Q2
    rollback: remove Q1 -> -EIO
    (qpd->evicted == 1, Q1 mapped)
  schedule retry
                                      kfd_process_evict_queues()
                                        evict_process_queues_cpsch()
                                          qpd->evicted++ (1 -> 2)
                                          kfd_mes_has_queue_of() -> true
                                          return -EIO
                                      return without restore or signal
restore_process_queues_cpsch()
  qpd->evicted > 1:
    qpd->evicted-- (2 -> 1)           <-- leaks refcount, p->ef stuck
    return 0

The retry stops because restore_process_queues_cpsch() returned 0, leaving the process permanently evicted across all its GPUs and TTM waiters blocked on p->ef indefinitely. criu_process_info() leaks the same +1 when kfd_process_evict_queues() returns -EIO.

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

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

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

[Severity: High]
Can the first eviction return 0 while MES still holds an unretired inactive queue?

Unlike the nested eviction branch above, this loop skips any queue with !q->properties.is_active and never checks kfd_mes_has_queue_of() afterward. In kfd_dqm_suspend_bad_queue_mes() and reset_queue_mes(), a queue is marked inactive even when MES rejects its removal, leaving it in KFD_MES_QUEUE_UNKNOWN.

While destroy and termination protect that queue's own MQD and ring storage, returning 0 from the first eviction lets evict_process_worker() signal p->ef so TTM can move or reallocate the process's user VRAM BOs while MES still holds the queue. Checking kfd_mes_has_queue_of(dqm, qpd) after the loop would keep the first eviction consistent with nested evictions.

Quoted 13 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +9 -0
@@ -2270,25 +2310,48 @@ static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
 	/* activate all active queues on the qpd */
 	list_for_each_entry(q, &qpd->queues_list, list) {
 		q->properties.is_evicted = false;
+
+		/*
+		 * The eviction, or the rollback of an earlier restore, could
+		 * not take this queue off the hardware (-EIO). MES still has
+		 * it, with the page table base it was added with, and
+		 * add_queue_mes() would leave it at that. Remove it first,
+		 * now that MES can be talked to again. A removal that was
+		 * sent and failed is not repeated; add_queue_mes() refuses
+		 * such a queue below.

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +10 -0
+		 */
+		if (q->mes_state == KFD_MES_QUEUE_MAPPED &&
+		    !kfd_mes_queue_retired(dqm, q)) {
+			retval = remove_queue_mes(dqm, q, qpd);
+			if (retval) {
+				dev_err(dev, "Failed to evict queue %d before its restore\n",
+					q->properties.queue_id);
+				goto rollback;
+			}
+		}

[Severity: Medium]
Does add_queue_mes() actually refuse a KFD_MES_QUEUE_UNKNOWN queue when dqm->sched_halt is set?

In add_queue_mes(), the early return for (!dqm->sched_running || dqm->sched_halt) runs before the !kfd_mes_queue_retired() check, so it returns 0 instead of -EBUSY while halted. If restore_process_queues_cpsch() runs during a halt_cpsch() window, it marks the unknown queue active and clears qpd->evicted to 0.

When unhalt_cpsch() later runs add_all_kfd_queues_mes(), add_queue_mes() returns -EBUSY on that queue and aborts remapping every remaining active queue across all processes on the device. Checking !kfd_mes_queue_retired() before the sched_halt check in add_queue_mes(), or rejecting KFD_MES_QUEUE_UNKNOWN queues here, would prevent that.

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

Quoted 2 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +0 -0
 		if (!QUEUE_IS_ACTIVE(q->properties))
 			continue;

[Severity: Medium]
Can this re-add a hung MES queue that was just reset by the pre-restore remove_queue_mes() above?

If the stale KFD_MES_QUEUE_MAPPED queue is hung, remove_queue_mes() triggers reset_queues_mes() -> reset_queue_mes(), which resets the queue, sets q->properties.is_reset = true and pdd->has_reset_queue = true, signals the reset and wedged events to userspace, and returns 0. Because QUEUE_IS_ACTIVE() does not check is_reset, the loop immediately marks the reset queue active and maps it back onto MES via add_queue_mes().

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

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

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

[Severity: High]
Can removing stale queues and re-adding queues in the same loop leave MES with a stale process-context page_table_base and unflushed TLB entries?

In MES, page_table_base_addr belongs to the process context. If Q1 is unmapped and Q2 is still KFD_MES_QUEUE_MAPPED, iteration 1 calls add_queue_mes() on Q1 while Q2 is still mapped under the old page_table_base (and if removing Q2 then fails, Q1 was already restarted on hardware).

Even with a single stale KFD_MES_QUEUE_MAPPED queue, remove_queue_mes() is followed immediately by add_queue_mes() without a heavyweight TLB flush, so stale TLB entries and in-flight accesses from the old page tables are not drained. Removing all stale mapped queues in a first pass, flushing the TLB if any were removed, and repinning/adding in a second pass would fix both.

Quoted 24 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +20 -0
@@ -2302,6 +2365,35 @@ 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);
+	}

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

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c +9 -0
+
+	/*
+	 * As at the end of an eviction: the queues that were taken off
+	 * above have been running, MES does not flush the TLB for them, and
+	 * the next eviction finds qpd->evicted set and does nothing.
+	 */
+	if (dqm->dev->kfd->shared_resources.enable_mes)
+		kfd_flush_tlb(pdd);
+	goto out;
 }

[Severity: Medium]
Can calling kfd_flush_tlb(pdd) here and in evict_process_queues_cpsch() while MES still holds queues suppress a later required TLB flush?

amdgpu_vm_flush_compute_tlb() advances vm->kfd_last_flushed_seq to vm->tlb_seq before flushing and never rolls it back if the flush fails. When remove_queue_mes() fails with -EIO and a queue remains mapped in MES, that running queue can refill the TLB after kfd_last_flushed_seq has already been updated, causing a later sequence-gated kfd_flush_tlb() for the same tlb_seq to return early as a no-op.

[Severity: Medium]
Can kfd_flush_tlb(pdd) in this rollback path become a no-op and fail to drain in-flight accesses from the queues that were just removed?

amdgpu_vm_flush_compute_tlb() skips amdgpu_gmc_flush_gpu_tlb_pasid_xccs() whenever vm->kfd_last_flushed_seq already equals vm->tlb_seq. On a restore retry (or a direct kfd_process_restore_queues() without a page-table update), vm->tlb_seq has not advanced since the previous flush, so kfd_flush_tlb(pdd) does nothing even though the rolled-back queues just ran on hardware.

[Severity: Medium]
Does calling kfd_flush_tlb(pdd) unconditionally here and after failed removals in evict_process_queues_cpsch() bypass kfd_mes_fenced(dqm) and stall GPU reset?

When remove_queue_mes() or add_queue_mes() times out, it fences MES and schedules GPU reset asynchronously. Before the reset worker takes down_write(&adev->reset_domain->sem), kfd_flush_tlb(pdd) acquires down_read_trylock() and on GFX12.0/GFX12.1 submits a synchronous MES TLB invalidation that busy-polls in amdgpu_fence_wait_polling() with udelay(2) for 2.1s (9s on SR-IOV) per master XCC while holding dqm_lock(dqm) and reset_domain->sem, starving the pending GPU reset. Skipping kfd_flush_tlb() when kfd_mes_fenced(dqm) is true (and in rollback when no queue was activated) would avoid that stall.

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

PATCH 7/8 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.

The update used to pass no mqd_update_info. It passes one now, and the gfx9 MQD manager derives a compute resource limit bit from its GWS flag on GC 9.4.2 and later, so the flag is set from the GWS state of the queue to leave that bit as pqm_set_gws() programmed it.

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 468e22d18..c31844cf5 100644
@@ -1466,6 +1466,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);
 
 	/*
@@ -1544,7 +1562,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 f8ab1bde8..40d3d481c 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;
 };
 
 /* What MES knows about a queue, see kfd_mes_queue_retired() */
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

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

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] drm/amdkfd: missing Fixes trailer for pre-unmap ring_bo drop --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] drm/amdkfd: missing Fixes trailer for pre-unmap ring_bo drop --

commit 362d257074216fcd562fb4d896a82eb30c53186f
Author: Armas Spann <[email protected]>

Quoted 21 lines

drm/amdkfd: apply queue property updates only after unmap

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.

The update used to pass no mqd_update_info. It passes one now, and the gfx9 MQD manager derives a compute resource limit bit from its GWS flag on GC 9.4.2 and later, so the flag is set from the GWS state of the queue to leave that bit as pqm_set_gws() programmed it.

Quoted 6 lines

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.

[Severity: Low]
This fixes dropping the old ring_bo reference and overwriting ring_bo before update_queue() unmaps the queue in pqm_update_queue_properties(). Should this include:

Fixes 305cd109b761 ("drm/amdkfd: Validate user queue update")
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#14 lore raw

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

In reply to Armas Spann

A GPU reset or a resume sets the MES firmware up from scratch, and the new instance knows no user queues. KFD keeps the processes that lived through a reset, evicted, 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, so they can still be recorded as mapped or as unconfirmed when the scheduler starts again. A REMOVE_QUEUE that was left unanswered before the restart still owns its status slot, and the fence that such a command raised is still in place.

kfd_mes_queue_retired() and kfd_mes_fenced() put each of these right when they are next asked, which for a queue of a process that just sits there until it exits can be a long time. Do it in one place instead, 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. Say how many queues the firmware forgot, so that a log shows the restart from the KFD side.

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 kgd2kfd_post_reset() marks them as reset before the scheduler starts. 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 c31844cf5..11a7c637a 100644
@@ -2883,6 +2883,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, so a queue can still be recorded as mapped or unconfirmed here.
+ * kfd_mes_queue_retired() would put that right when the queue is next
+ * looked at, which can be as late as the exit of its process.
+ *
+ * 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 an
+ * eviction marks every queue inactive whether MES confirmed its removal or
+ * not. 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;
@@ -2947,6 +3007,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