Skip to contentSkip to conversation

drm/amdkfd: fix wedged teardown on surprise removal

PATCH Superseded Olivier Kaloudoff 4 participants 23 messages Oct 8 – Oct 28

Subsystems (3)

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v5 cover drm/amdkfd: fix wedged teardown on surprise removal

On surprise removal of a GPU behind Thunderbolt (MI50, PCIe slot power cut), the KFD teardown path wedges the host:

- the killed KFD process faults on its own SVM ranges during exit / coredump (SIGBUS -> get_dump_page -> do_swap_page -> svm_migrate_to_ram), submits SDMA work to an already-killed drm_sched entity, and waits uninterruptibly on a fence that can never signal;
- the dying task holds svms->lock, which wedges svm_range_restore_work() and prevents kfd_processes_count from draining;
- kgd2kfd_teardown_processes() therefore spins forever in cond_resched() while holding the pciehp removal thread, producing soft-lockup and hung-task splats.

This series:

1. tears KFD processes down in amdgpu_device_fini_hw() *before* amdgpu_amdkfd_device_fini_sw() frees kfd.dev on disconnect, so the drain happens while kfd.dev is still valid, and guards the second kgd2kfd_teardown_processes() call against kfd.dev already being gone;

2. makes the userptr and SVM range restore workers stop rescheduling themselves on -ENODEV;

3. guards the hardware-accessing SVM migration sections with drm_dev_enter()/drm_dev_exit() and bounds the job fence wait with AMDGPU_FENCE_JIFFIES_TIMEOUT, so a migration cannot race with unplug and a fence on a dead device cannot stall the critical section or the faulting task indefinitely.

Verified on MI50 behind Thunderbolt (2 GB SVM workload, PCIe slot power cut): the workload takes SIGBUS, coredump completes, kfd_processes_count drains in ~7s, pciehp removal finishes without warnings, and the device re-enumerates cleanly on slot re-power. Previously the same repro wedged the host every time.

Changes in v5:
- patch 3: dropped the drm_dev_is_unplugged() and pci_dev_is_disconnected() checks entirely; drm_dev_enter()/exit() plus the bounded fence wait is sufficient (Felix Kuehling)

Changes in v4:
- patch 3: AMDGPU_FENCE_JIFFIES_TIMEOUT instead of an open-coded 10s; drm_dev_enter()/exit() guarding the whole migration section including the bounded wait (Felix Kuehling)
- patch 2: folded in the svm_range_restore_work() -ENODEV change; fixed a latent uninitialized ret read on the evicted_bos-mismatch and confirm_valid-WARN paths

Changes in v3:
- patch 1: NULL guard for the second teardown call (Christian König)
- patch 3: new, fail fast on gone device in SVM migration paths

Changes in v2:
- patch 1: drain before fini_sw instead of bounding the wait (Christian König)
- patch 2: new, stop restore retries on unplug

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

Olivier Kaloudoff (3):
drm/amdkfd: tear down KFD processes before early fini_sw on disconnect drm/amdkfd: stop restore retries on device unplug drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c        |  5 ++-
 .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c      | 29 +++++++++++++----
 drivers/gpu/drm/amd/amdkfd/kfd_device.c           |  9 ++++-
 drivers/gpu/drm/amd/amdkfd/kfd_migrate.c          | 36 ++++++++++++++++++--
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c              |  2 +-
 5 files changed, 70 insertions(+), 11 deletions(-)
Signature · 1 line
2.47.3
#1 lore raw

PATCH v5 1/3 drm/amdkfd: tear down KFD processes before early fini_sw on disconnect

On surprise removal, amdgpu_device_fini_hw() calls amdgpu_amdkfd_device_fini_sw() when pci_dev_is_disconnected() is true. fini_sw frees kfd.dev, but KFD processes may still be alive and hold references to it: kfd_process_destroy() dereferences kfd.dev via kfd_processes_remove(), and svm_range_list_fini() / kfd_process_free_outstanding_kfd_bos() touch per-device SVM state.

The kfd_processes_count wait only happens later in kgd2kfd_teardown_processes(), called from the top-half remove path well after fini_sw. In the observed failure the killed KFD process (SIGBUS on unplug) stuck in D state on its exit path, so kfd_processes_count never drained and the PCIe removal thread wedged permanently in cond_resched(), producing soft-lockup and hung-task splats.

Tear KFD processes down before freeing kfd.dev on the disconnect path, and guard kgd2kfd_teardown_processes() against kfd.dev already being gone when it runs a second time.

---
Changes in v5:
- none

Changes in v4:
- none

Changes in v3:
- added NULL guard for the second teardown_processes call once kfd.dev is already freed (Christian König)
- dropped the bounded-wait mechanism from v1; the drain now happens before fini_sw instead (Christian König)

Changes in v2:
- none
---

drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +4 -1
index 9269e78..bd9d73a 100644
@@ -4315,8 +4315,11 @@ void amdgpu_device_fini_hw(struct amdgpu_device *adev)
 	 * before ip_fini_early to prevent kfd locking refcount issues by calling
 	 * amdgpu_amdkfd_suspend()
 	 */
-	if (pci_dev_is_disconnected(adev->pdev))
+	if (pci_dev_is_disconnected(adev->pdev)) {
+		/* Drain KFD processes while kfd.dev is still valid */
+		amdgpu_amdkfd_teardown_processes(adev);
 		amdgpu_amdkfd_device_fini_sw(adev);
+	}
 
 	amdgpu_coredump_fini(adev);
 	amdgpu_device_ip_fini_early(adev);
drivers/gpu/drm/amd/amdkfd/kfd_device.c +8 -1
index 586e640..43029b2 100644
@@ -1801,7 +1801,14 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)
 
 	mutex_unlock(&kfd_processes_mutex);
 
-	/* wait all kfd processes use adev terminate */
+	/* kfd.dev may already be freed on surprise removal */
+	if (!adev->kfd.dev)
+		return;
+
+	/*
+	 * Wait for all KFD processes using adev to terminate. Must be
+	 * unbounded: device state is freed once they are gone.
+	 */
 	while (!!atomic_read(&adev->kfd.dev->kfd_processes_count))
 		cond_resched();
 }
Signature · 1 line
2.47.3
#2 lore raw

PATCH v5 2/3 drm/amdkfd: stop restore retries on device unplug

In reply to Olivier Kaloudoff

amdgpu_amdkfd_restore_userptr_worker() and svm_range_restore_work() reschedule themselves when validation fails with evicted objects pending. After a surprise removal the restore paths fail with -ENODEV permanently, so rescheduling just spins the worker uselessly until cancel_delayed_work_sync() in fini finally stops it - which can take a while, since process teardown itself is delayed by the dead device.

Treat -ENODEV as terminal in both workers and also stop setting evicted_bos after it.

---
Changes in v5:
- none

Changes in v4:
- moved the svm_range_restore_work() change here from the SVM migration patch (Felix Kuehling)
- assign ret on the evicted_bos-mismatch and confirm_valid-WARN paths, fixing a latent uninitialized read introduced in v2

Changes in v3:
- retitled; now covers both restore workers

Changes in v2:
- new
---

drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +13 -5
index d668816..2ad6777 100644
@@ -2827,6 +2827,7 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
 	struct task_struct *usertask;
 	struct mm_struct *mm;
 	uint32_t evicted_bos;
+	int ret;
 
 	mutex_lock(&process_info->notifier_lock);
 	evicted_bos = process_info->evicted_bos;
@@ -2846,14 +2847,16 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
 
 	mutex_lock(&process_info->lock);
 
-	if (update_invalid_user_pages(process_info, mm))
+	ret = update_invalid_user_pages(process_info, mm);
+	if (ret)
 		goto unlock_out;
 	/* userptr_inval_list can be empty if all evicted userptr BOs
 	 * have been freed. In that case there is nothing to validate
 	 * and we can just restart the queues.
 	 */
 	if (!list_empty(&process_info->userptr_inval_list)) {
-		if (validate_invalid_user_pages(process_info))
+		ret = validate_invalid_user_pages(process_info);
+		if (ret)
 			goto unlock_out;
 	}
 	/* Final check for concurrent evicton and atomic update. If
@@ -2862,11 +2865,14 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
 	 * reference counting inside KFD will handle this case.
 	 */
 	mutex_lock(&process_info->notifier_lock);
-	if (process_info->evicted_bos != evicted_bos)
+	if (process_info->evicted_bos != evicted_bos) {
+		ret = -EAGAIN;
 		goto unlock_notifier_out;
+	}
 
 	if (confirm_valid_user_pages_locked(process_info)) {
 		WARN(1, "User pages unexpectedly invalid");
+		ret = -EINVAL;
 		goto unlock_notifier_out;
 	}
 
@@ -2884,8 +2890,10 @@ unlock_notifier_out:
 unlock_out:
 	mutex_unlock(&process_info->lock);
 
-	/* If validation failed, reschedule another attempt */
-	if (evicted_bos) {
+	/* If validation failed, reschedule another attempt, unless the
+	 * device is gone for good
+	 */
+	if (evicted_bos && ret != -ENODEV) {
 		queue_delayed_work(system_freezable_wq,
 			&process_info->restore_userptr_work,
 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +4 -2
index fa4054d..3dab456 100644
@@ -2013,8 +2013,10 @@ out_reschedule:
 	mmap_write_unlock(mm);
 	mutex_unlock(&process_info->lock);
 
-	/* If validation failed, reschedule another attempt */
-	if (evicted_ranges) {
+	/* If validation failed, reschedule another attempt, unless the
+	 * device is gone for good
+	 */
+	if (evicted_ranges && r != -ENODEV) {
 		pr_debug("reschedule to restore svm range\n");
 		queue_delayed_work(system_freezable_wq, &svms->restore_work,
 			msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
Signature · 1 line
2.47.3
#3 lore raw

PATCH v5 3/3 drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

In reply to Olivier Kaloudoff

On surprise removal the killed process's own exit path can fault on its SVM managed ranges: SIGBUS -> coredump -> get_dump_page() -> __get_user_pages() -> do_swap_page() -> svm_migrate_to_ram(). Without protection, svm_migrate_vram_to_ram() submits an SDMA copy job to an already-killed drm_sched entity (observed as "drm_sched_rq_add_entity: Trying to push to a killed entity" plus refcount_t saturation warnings), then svm_migrate_copy_done() waits uninterruptibly on a job fence that can never signal. The task dies in D state holding svms->lock, which wedges svm_range_restore_work() on the rwsem writer side, so kfd_processes_count never drains and the pciehp removal thread wedges for good.

Guard the hardware-accessing migration sections with drm_dev_enter()/drm_dev_exit() so unplug cannot proceed while a migration submits jobs and waits on them, and bound the job fence wait in svm_migrate_copy_done() with AMDGPU_FENCE_JIFFIES_TIMEOUT so a fence that can never signal does not stall the critical section (or the faulting task) indefinitely.

Verified on MI50 behind Thunderbolt: the workload takes SIGBUS, coredump completes, kfd_processes_count drains in ~7s, pciehp removal finishes, and the device re-enumerates cleanly on slot re-power. Previously the same repro wedged the host.

---
Changes in v5:
- dropped drm_dev_is_unplugged()/pci_dev_is_disconnected() checks; drm_dev_enter()/exit() alone is sufficient (Felix Kuehling)

Changes in v4:
- use AMDGPU_FENCE_JIFFIES_TIMEOUT instead of an open-coded 10s (Felix Kuehling)
- guard migration sections with drm_dev_enter()/exit() instead of racing flag checks (Felix Kuehling)
- keep pci_dev_is_disconnected() early-out for the dead-link window
- moved svm_range_restore_work() change to patch 2

Changes in v3:
- new
---

drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +22 -1
index 253365a..14f2273 100644
@@ -202,7 +202,17 @@ svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence)
 	int r = 0;
 
 	if (mfence) {
-		r = dma_fence_wait(mfence, false);
+		/* Bound the wait: on a dying device the fence may never
+		 * signal.
+		 */
+		long ret;
+
+		ret = dma_fence_wait_timeout(mfence, false,
+				AMDGPU_FENCE_JIFFIES_TIMEOUT);
+		if (!ret)
+			r = -ETIMEDOUT;
+		else if (ret < 0)
+			r = ret;
 		dma_fence_put(mfence);
 		pr_debug("sdma copy memory fence done\n");
 	}
@@ -494,6 +504,7 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
 	u64 ttm_res_offset;
 	struct kfd_node *node;
 	unsigned long mpages = 0;
+	int idx;
 	long r = 0;
 
 	if (start_mgr < prange->start || last_mgr > prange->last) {
@@ -507,6 +518,9 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
 		pr_debug("failed to get kfd node by id 0x%x\n", best_loc);
 		return -ENODEV;
 	}
+	/* Block unplug while the migration submits jobs and waits on them */
+	if (!drm_dev_enter(adev_to_drm(node->adev), &idx))
+		return -ENODEV;
 
 	pr_debug("svms 0x%p [0x%lx 0x%lx] in [0x%lx 0x%lx] to gpu 0x%x\n",
 		prange->svms, start_mgr, last_mgr, prange->start, prange->last,
@@ -521,6 +535,7 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
 					node->xcp ? node->xcp->id : 0);
 	if (r) {
 		dev_dbg(node->adev->dev, "failed to reserve VRAM, r: %ld\n", r);
+		drm_dev_exit(idx);
 		return -ENOSPC;
 	}
 
@@ -565,6 +580,7 @@ out:
 					prange->npages * PAGE_SIZE,
 					KFD_IOC_ALLOC_MEM_FLAGS_VRAM,
 					node->xcp ? node->xcp->id : 0);
+	drm_dev_exit(idx);
 	return r < 0 ? r : 0;
 }
 
@@ -821,6 +837,7 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
 	unsigned long start;
 	unsigned long end;
 	unsigned long mpages = 0;
+	int idx;
 	long r = 0;
 
 	/* this pragne has no any vram page to migrate to sys ram */
@@ -841,6 +858,9 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
 		pr_debug("failed to get kfd node by id 0x%x\n", prange->actual_loc);
 		return -ENODEV;
 	}
+	/* Block unplug while the migration submits jobs and waits on them */
+	if (!drm_dev_enter(adev_to_drm(node->adev), &idx))
+		return -ENODEV;
 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] from gpu 0x%x to ram\n",
 		 prange->svms, prange, start_mgr, last_mgr,
 		 prange->actual_loc);
@@ -885,6 +905,7 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
 		}
 	}
 
+	drm_dev_exit(idx);
 	return r < 0 ? r : 0;
 }
 
Signature · 1 line
2.47.3
maintainer
#4 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Quoted 52 lines · Olivier Kaloudoff

On surprise removal the killed process's own exit path can fault on its SVM managed ranges: SIGBUS -> coredump -> get_dump_page() -> __get_user_pages() -> do_swap_page() -> svm_migrate_to_ram(). Without protection, svm_migrate_vram_to_ram() submits an SDMA copy job to an already-killed drm_sched entity (observed as "drm_sched_rq_add_entity: Trying to push to a killed entity" plus refcount_t saturation warnings), then svm_migrate_copy_done() waits uninterruptibly on a job fence that can never signal. The task dies in D state holding svms->lock, which wedges svm_range_restore_work() on the rwsem writer side, so kfd_processes_count never drains and the pciehp removal thread wedges for good.

Guard the hardware-accessing migration sections with drm_dev_enter()/drm_dev_exit() so unplug cannot proceed while a migration submits jobs and waits on them, and bound the job fence wait in svm_migrate_copy_done() with AMDGPU_FENCE_JIFFIES_TIMEOUT so a fence that can never signal does not stall the critical section (or the faulting task) indefinitely.

Verified on MI50 behind Thunderbolt: the workload takes SIGBUS, coredump completes, kfd_processes_count drains in ~7s, pciehp removal finishes, and the device re-enumerates cleanly on slot re-power. Previously the same repro wedged the host.

---
Changes in v5:
- dropped drm_dev_is_unplugged()/pci_dev_is_disconnected() checks; drm_dev_enter()/exit() alone is sufficient (Felix Kuehling)

Changes in v4:
- use AMDGPU_FENCE_JIFFIES_TIMEOUT instead of an open-coded 10s (Felix Kuehling)
- guard migration sections with drm_dev_enter()/exit() instead of racing flag checks (Felix Kuehling)
- keep pci_dev_is_disconnected() early-out for the dead-link window
- moved svm_range_restore_work() change to patch 2

Changes in v3:
- new
---

drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +1 -1
index 253365a..14f2273 100644
@@ -202,7 +202,17 @@ svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence)
  	int r = 0;
 
  	if (mfence) {
-		r = dma_fence_wait(mfence, false);
+		/* Bound the wait: on a dying device the fence may never

drivers/gpu/drm/amd/amdkfd/kfd_migrate.c svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence) · line 215

Quoted 10 lines
drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +10 -0
+		 * signal.
+		 */
+		long ret;
+
+		ret = dma_fence_wait_timeout(mfence, false,
+				AMDGPU_FENCE_JIFFIES_TIMEOUT);
+		if (!ret)
+			r = -ETIMEDOUT;
+		else if (ret < 0)
+			r = ret;

You're adding more failure cases here.  But the callers of this function currently don't check for errors. We'll need to fix that. If the copy times out or fails otherwise, we should not pretend that the migration succeeded. It doesn't matter in the GPU-unplug and process termination case you're working on, but it could result in silent data corruption in other cases where we hit a timeout maybe because the DMA engine just takes too long for some reason.

We'll need to put all the migration pages and clear the migrate->dst array before calling migrate_vma_finalize.

Also pass the error code back to the caller.

Regards,
  Felix

Quoted 63 lines
drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +11 -0
  		dma_fence_put(mfence);
  		pr_debug("sdma copy memory fence done\n");
  	}
@@ -494,6 +504,7 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
  	u64 ttm_res_offset;
  	struct kfd_node *node;
  	unsigned long mpages = 0;
+	int idx;
  	long r = 0;
 
  	if (start_mgr < prange->start || last_mgr > prange->last) {
@@ -507,6 +518,9 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
  		pr_debug("failed to get kfd node by id 0x%x\n", best_loc);
  		return -ENODEV;
  	}
+	/* Block unplug while the migration submits jobs and waits on them */
+	if (!drm_dev_enter(adev_to_drm(node->adev), &idx))
+		return -ENODEV;
 
  	pr_debug("svms 0x%p [0x%lx 0x%lx] in [0x%lx 0x%lx] to gpu 0x%x\n",
  		prange->svms, start_mgr, last_mgr, prange->start, prange->last,
@@ -521,6 +535,7 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
  					node->xcp ? node->xcp->id : 0);
  	if (r) {
  		dev_dbg(node->adev->dev, "failed to reserve VRAM, r: %ld\n", r);
+		drm_dev_exit(idx);
  		return -ENOSPC;
  	}
 
@@ -565,6 +580,7 @@ out:
  					prange->npages * PAGE_SIZE,
  					KFD_IOC_ALLOC_MEM_FLAGS_VRAM,
  					node->xcp ? node->xcp->id : 0);
+	drm_dev_exit(idx);
  	return r < 0 ? r : 0;
  }
 
@@ -821,6 +837,7 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
  	unsigned long start;
  	unsigned long end;
  	unsigned long mpages = 0;
+	int idx;
  	long r = 0;
 
  	/* this pragne has no any vram page to migrate to sys ram */
@@ -841,6 +858,9 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
  		pr_debug("failed to get kfd node by id 0x%x\n", prange->actual_loc);
  		return -ENODEV;
  	}
+	/* Block unplug while the migration submits jobs and waits on them */
+	if (!drm_dev_enter(adev_to_drm(node->adev), &idx))
+		return -ENODEV;
  	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] from gpu 0x%x to ram\n",
  		 prange->svms, prange, start_mgr, last_mgr,
  		 prange->actual_loc);
@@ -885,6 +905,7 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
  		}
  	}
 
+	drm_dev_exit(idx);
  	return r < 0 ? r : 0;
  }
 
#5 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Hi Felix,

Quoted 6 lines

You're adding more failure cases here. But the callers of this function currently don't check for errors. We'll need to fix that. If the copy times out or fails otherwise, we should not pretend that the migration succeeded. [...] We'll need to put all the migration pages and clear the migrate->dst array before calling migrate_vma_finalize. Also pass the error code back to the caller.

Fixed in v6: both svm_migrate_vma_to_vram() and svm_migrate_vma_to_ram() now check the copy_done() return. On error the dst pages are released (VRAM pages via svm_migrate_put_vram_page, system pages unmapped + unlocked + put) and migrate->dst is cleared before migrate_vma_finalize(), so a failed copy can no longer complete as a successful migration. The error propagates to the caller.

The cleanup loops are the same logic the copy functions already run on their own error paths, factored into helpers (svm_migrate_vram_pages_put / svm_migrate_ram_pages_put) so both error paths share them.

Re-verified on the MI50/Thunderbolt repro: SIGBUS, drain ~9s, clean removal, re-enumerates on re-power.

Regards,
Olivier

#6 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

In reply to Kuehling, Felix

Hi Felix,

Quoted 6 lines

You're adding more failure cases here. But the callers of this function currently don't check for errors. We'll need to fix that. If the copy times out or fails otherwise, we should not pretend that the migration succeeded. [...] We'll need to put all the migration pages and clear the migrate->dst array before calling migrate_vma_finalize. Also pass the error code back to the caller.

Fixed in v6: both svm_migrate_vma_to_vram() and svm_migrate_vma_to_ram() now check the copy_done() return. On error the dst pages are released (VRAM pages via svm_migrate_put_vram_page, system pages unmapped + unlocked + put) and migrate->dst is cleared before migrate_vma_finalize(), so a failed copy can no longer complete as a successful migration. The error propagates to the caller.

The cleanup loops are the same logic the copy functions already run on their own error paths, factored into helpers (svm_migrate_vram_pages_put / svm_migrate_ram_pages_put) so both error paths share them.

Re-verified on the MI50/Thunderbolt repro: SIGBUS, drain ~9s, clean removal, re-enumerates on re-power.

Regards,
Olivier

maintainer
#7 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

In reply to Olivier Kaloudoff
Quoted 47 lines · Olivier Kaloudoff

On surprise removal the killed process's own exit path can fault on its SVM managed ranges: SIGBUS -> coredump -> get_dump_page() -> __get_user_pages() -> do_swap_page() -> svm_migrate_to_ram(). Without protection, svm_migrate_vram_to_ram() submits an SDMA copy job to an already-killed drm_sched entity (observed as "drm_sched_rq_add_entity: Trying to push to a killed entity" plus refcount_t saturation warnings), then svm_migrate_copy_done() waits uninterruptibly on a job fence that can never signal. The task dies in D state holding svms->lock, which wedges svm_range_restore_work() on the rwsem writer side, so kfd_processes_count never drains and the pciehp removal thread wedges for good.

Guard the hardware-accessing migration sections with drm_dev_enter()/drm_dev_exit() so unplug cannot proceed while a migration submits jobs and waits on them, and bound the job fence wait in svm_migrate_copy_done() with AMDGPU_FENCE_JIFFIES_TIMEOUT so a fence that can never signal does not stall the critical section (or the faulting task) indefinitely.

Verified on MI50 behind Thunderbolt: the workload takes SIGBUS, coredump completes, kfd_processes_count drains in ~7s, pciehp removal finishes, and the device re-enumerates cleanly on slot re-power. Previously the same repro wedged the host.

---
Changes in v5:
- dropped drm_dev_is_unplugged()/pci_dev_is_disconnected() checks; drm_dev_enter()/exit() alone is sufficient (Felix Kuehling)

Changes in v4:
- use AMDGPU_FENCE_JIFFIES_TIMEOUT instead of an open-coded 10s (Felix Kuehling)
- guard migration sections with drm_dev_enter()/exit() instead of racing flag checks (Felix Kuehling)
- keep pci_dev_is_disconnected() early-out for the dead-link window
- moved svm_range_restore_work() change to patch 2

Changes in v3:
- new
---

drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +0 -0
index 253365a..14f2273 100644

drivers/gpu/drm/amd/amdkfd/kfd_migrate.c svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence) · line 207

Quoted 7 lines
drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +3 -1
@@ -202,7 +202,17 @@ svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence)
 	int r = 0;
 
 	if (mfence) {
-		r = dma_fence_wait(mfence, false);
+		/* Bound the wait: on a dying device the fence may never
+		 * signal.
+		 */

Fences *must* always signal especially when the device is hot removed.

drivers/gpu/drm/amd/amdkfd/kfd_migrate.c svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence) · line 215

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +8 -0
+		long ret;
+
+		ret = dma_fence_wait_timeout(mfence, false,
+				AMDGPU_FENCE_JIFFIES_TIMEOUT);
+		if (!ret)
+			r = -ETIMEDOUT;
+		else if (ret < 0)
+			r = ret;

That change makes no sense at all, a non interruptible wait with AMDGPU_FENCE_JIFFIES_TIMEOUT can never fail.

Regards,
Christian.

Quoted 63 lines
drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +11 -0
 		dma_fence_put(mfence);
 		pr_debug("sdma copy memory fence done\n");
 	}
@@ -494,6 +504,7 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
 	u64 ttm_res_offset;
 	struct kfd_node *node;
 	unsigned long mpages = 0;
+	int idx;
 	long r = 0;
 
 	if (start_mgr < prange->start || last_mgr > prange->last) {
@@ -507,6 +518,9 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
 		pr_debug("failed to get kfd node by id 0x%x\n", best_loc);
 		return -ENODEV;
 	}
+	/* Block unplug while the migration submits jobs and waits on them */
+	if (!drm_dev_enter(adev_to_drm(node->adev), &idx))
+		return -ENODEV;
 
 	pr_debug("svms 0x%p [0x%lx 0x%lx] in [0x%lx 0x%lx] to gpu 0x%x\n",
 		prange->svms, start_mgr, last_mgr, prange->start, prange->last,
@@ -521,6 +535,7 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
 					node->xcp ? node->xcp->id : 0);
 	if (r) {
 		dev_dbg(node->adev->dev, "failed to reserve VRAM, r: %ld\n", r);
+		drm_dev_exit(idx);
 		return -ENOSPC;
 	}
 
@@ -565,6 +580,7 @@ out:
 					prange->npages * PAGE_SIZE,
 					KFD_IOC_ALLOC_MEM_FLAGS_VRAM,
 					node->xcp ? node->xcp->id : 0);
+	drm_dev_exit(idx);
 	return r < 0 ? r : 0;
 }
 
@@ -821,6 +837,7 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
 	unsigned long start;
 	unsigned long end;
 	unsigned long mpages = 0;
+	int idx;
 	long r = 0;
 
 	/* this pragne has no any vram page to migrate to sys ram */
@@ -841,6 +858,9 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
 		pr_debug("failed to get kfd node by id 0x%x\n", prange->actual_loc);
 		return -ENODEV;
 	}
+	/* Block unplug while the migration submits jobs and waits on them */
+	if (!drm_dev_enter(adev_to_drm(node->adev), &idx))
+		return -ENODEV;
 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] from gpu 0x%x to ram\n",
 		 prange->svms, prange, start_mgr, last_mgr,
 		 prange->actual_loc);
@@ -885,6 +905,7 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
 		}
 	}
 
+	drm_dev_exit(idx);
 	return r < 0 ? r : 0;
 }
 
#8 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Hi Christian,

Quoted 1 line

Fences *must* always signal especially when the device is hot removed.

Agreed in principle — but the observed failure is precisely the counter-case. During teardown the dying process's fault path submits an SDMA job to an already-killed drm_sched entity:

drm_sched_rq_add_entity: Trying to push to a killed entity

The job never reaches a ring, nothing is left to signal its fence, and the uninterruptible wait in svm_migrate_copy_done() never returns. That orphaned fence is what kept the task in D state for good in the repro.

Quoted 2 lines

a non interruptible wait with AMDGPU_FENCE_JIFFIES_TIMEOUT can never fail.

The ret < 0 branch is indeed dead code — dropped it in v6, thanks.

The bound itself is needed for a subtler reason: the wait now runs inside a drm_dev_enter() critical section, and drm_dev_unplug() blocks until all such sections exit. An unbounded wait inside the section would deadlock the unplug path against any fence that fails to signal, for whatever reason. This is also the shape Felix asked for — guard HW access with dev_enter/exit and keep no unbounded fence waits inside those sections.

If you'd rather guarantee the invariant at the source — i.e. error out fences orphaned by jobs pushed to an already-killed entity in drm_sched — happy to look at that too, but it is a much wider change than the KFD-side guard.

Regards,
Olivier

maintainer
#9 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Quoted 8 lines · Olivier Kaloudoff

Hi Christian,

Quoted 1 line

Fences *must* always signal especially when the device is hot removed.

Agreed in principle — but the observed failure is precisely the counter-case. During teardown the dying process's fault path submits an SDMA job to an already-killed drm_sched entity:

Quoted 6 lines

drm_sched_rq_add_entity: Trying to push to a killed entity

The job never reaches a ring, nothing is left to signal its fence, and the uninterruptible wait in svm_migrate_copy_done() never returns. That orphaned fence is what kept the task in D state for good in the repro.

Yeah and you need to fix the fence orphaning and *NOT* the wait!

Quoted 11 lines
Quoted 3 lines

a non interruptible wait with AMDGPU_FENCE_JIFFIES_TIMEOUT can never fail.

The ret < 0 branch is indeed dead code — dropped it in v6, thanks.

The bound itself is needed for a subtler reason: the wait now runs inside a drm_dev_enter() critical section, and drm_dev_unplug() blocks until all such sections exit. An unbounded wait inside the section would deadlock the unplug path against any fence that fails to signal, for whatever reason.

Yes and that is completely intentional and mandatory!

Blocking for all fences is correct shutdown order. What is not correct is that the fences never signals.

There must be some problem with the error handling in the SDMA submission code.

Quoted 3 lines

This is also the shape Felix asked
for — guard HW access with dev_enter/exit and keep no unbounded fence waits inside those sections.

Clear NAK to that!

Regards,
Christian.

Quoted 8 lines

If you'd rather guarantee the invariant at the source — i.e. error out fences orphaned by jobs pushed to an already-killed entity in drm_sched — happy to look at that too, but it is a much wider change than the KFD-side guard.

Regards,
Olivier

#10 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Hi Christian,

Quoted 1 line

Yeah and you need to fix the fence orphaning and *NOT* the wait!

Agreed — found the exact orphan site. drm_sched_entity_push_job() pushes the job onto entity->job_queue first, then drm_sched_rq_add_entity() sees entity->stopped (under entity->lock) and returns NULL: the scheduler is never woken, the job strands on the spsc queue, and its fence never signals. In our repro the dying process's fault path submits the migration job on its own killed entity — it's the process-kill race, not a device-unplug race at all, which is why drm_dev_enter() doesn't cover it.

This is the same failure Tong Liu reported in August 2025 (task hang after job submission during process kill); that fix was rejected for checking entity->stopped without the lock. The clean fix is not to pre-check but to handle the NULL return while still under entity->lock: drain the queue / schedule the kill-jobs work so each stranded job's finished fence completes with -ESRCH.

Quoted 1 line

Blocking for all fences is correct shutdown order.

Agreed. v7 drops the timeout entirely — unbounded wait restored. With fences guaranteed to signal, the copy_done error path becomes genuinely reachable via the fence's error status, so the error propagation and migrate->dst rollback Felix asked for stay — now on a real error path instead of a timeout.

v7 is now implemented and tested on this machine (7.3.0-rc5 + p1/p2 teardown+restore-stop, sched orphan fix, KFD fence-error rework). Hot-unplug test: svmhog2 mid-migration + a second KFD process, then Thunderbolt deauthorize. With only the sched fix the host still wedges — the kill-jobs drain prevents the orphan, but the unplug path additionally needs the KFD teardown ordering (processes torn down before device early-fini) and the restore worker stopping on -ENODEV. With the full stack: fences complete with error instead of orphaning, both KFD processes get SIGBUS and reap cleanly, device tears down, host stays alive, and re-authorizing gives a clean re-enumeration. So your direction was right — the wait was never the bug — but the orphan fix is necessary rather than sufficient for unplug.

One question on layering: the push-to-killed-entity fix belongs to drm/sched, which is dri-devel/drm-misc territory — do you want it as a standalone patch there, or kept in this series? I can also guard the KFD submit side so it doesn't push to a stopped entity in the first place, but the sched-side drain is the airtight fix since entity kill can always race a locked pre-check.

Regards,
Olivier

maintainer
#11 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Quoted 42 lines · Olivier Kaloudoff

Hi Christian,

Quoted 1 line

Yeah and you need to fix the fence orphaning and *NOT* the wait!

Agreed — found the exact orphan site. drm_sched_entity_push_job() pushes the job onto entity->job_queue first, then drm_sched_rq_add_entity() sees entity->stopped (under entity->lock) and returns NULL: the scheduler is never woken, the job strands on the spsc queue, and its fence never signals. In our repro the dying process's fault path submits the migration job on its own killed entity — it's the process-kill race, not a device-unplug race at all, which is why drm_dev_enter() doesn't cover it.

This is the same failure Tong Liu reported in August 2025 (task hang after job submission during process kill); that fix was rejected for checking entity->stopped without the lock. The clean fix is not to pre-check but to handle the NULL return while still under entity->lock: drain the queue / schedule the kill-jobs work so each stranded job's finished fence completes with -ESRCH.

Quoted 1 line

Blocking for all fences is correct shutdown order.

Agreed. v7 drops the timeout entirely — unbounded wait restored. With fences guaranteed to signal, the copy_done error path becomes genuinely reachable via the fence's error status, so the error propagation and migrate->dst rollback Felix asked for stay — now on a real error path instead of a timeout.

v7 is now implemented and tested on this machine (7.3.0-rc5 + p1/p2 teardown+restore-stop, sched orphan fix, KFD fence-error rework). Hot-unplug test: svmhog2 mid-migration + a second KFD process, then Thunderbolt deauthorize. With only the sched fix the host still wedges — the kill-jobs drain prevents the orphan, but the unplug path additionally needs the KFD teardown ordering (processes torn down before device early-fini) and the restore worker stopping on -ENODEV. With the full stack: fences complete with error instead of orphaning, both KFD processes get SIGBUS and reap cleanly, device tears down, host stays alive, and re-authorizing gives a clean re-enumeration. So your direction was right — the wait was never the bug — but the orphan fix is necessary rather than sufficient for unplug.

Quoted 6 lines

One question on layering: the push-to-killed-entity fix belongs to drm/sched, which is dri-devel/drm-misc territory — do you want it as a standalone patch there, or kept in this series? I can also guard the KFD submit side so it doesn't push to a stopped entity in the first place, but the sched-side drain is the airtight fix since entity kill can always race a locked pre-check.

No that is another race in amdgpu and is not related to the scheduler at all.

entity->stopped should only be set to false *after* all potential users are gone because that potentially also frees up the scheduler.

Otherwise we run into tons of other race conditions with scheduler submission and teardown.

In the case of a hot remove the run_job callback should recognize that the device is gone and return an error, which is then bubbled up into the dma_fence again.

The warning from the scheduler is just pointing out that amdgpu is doing something very nasty here.

Regards,
Christian.

Quoted 3 lines

Regards,
Olivier

#12 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

In reply to Christian König

Hi Christian,

Quoted 1 line

Yeah and you need to fix the fence orphaning and *NOT* the wait!

Agreed — found the exact orphan site. drm_sched_entity_push_job() pushes the job onto entity->job_queue first, then drm_sched_rq_add_entity() sees entity->stopped (under entity->lock) and returns NULL: the scheduler is never woken, the job strands on the spsc queue, and its fence never signals. In our repro the dying process's fault path submits the migration job on its own killed entity — it's the process-kill race, not a device-unplug race at all, which is why drm_dev_enter() doesn't cover it.

This is the same failure Tong Liu reported in August 2025 (task hang after job submission during process kill); that fix was rejected for checking entity->stopped without the lock. The clean fix is not to pre-check but to handle the NULL return while still under entity->lock: drain the queue / schedule the kill-jobs work so each stranded job's finished fence completes with -ESRCH.

Quoted 1 line

Blocking for all fences is correct shutdown order.

Agreed. v7 drops the timeout entirely — unbounded wait restored. With fences guaranteed to signal, the copy_done error path becomes genuinely reachable via the fence's error status, so the error propagation and migrate->dst rollback Felix asked for stay — now on a real error path instead of a timeout.

v7 is now implemented and tested on this machine (7.3.0-rc5 + p1/p2 teardown+restore-stop, sched orphan fix, KFD fence-error rework). Hot-unplug test: svmhog2 mid-migration + a second KFD process, then Thunderbolt deauthorize. With only the sched fix the host still wedges — the kill-jobs drain prevents the orphan, but the unplug path additionally needs the KFD teardown ordering (processes torn down before device early-fini) and the restore worker stopping on -ENODEV. With the full stack: fences complete with error instead of orphaning, both KFD processes get SIGBUS and reap cleanly, device tears down, host stays alive, and re-authorizing gives a clean re-enumeration. So your direction was right — the wait was never the bug — but the orphan fix is necessary rather than sufficient for unplug.

One question on layering: the push-to-killed-entity fix belongs to drm/sched, which is dri-devel/drm-misc territory — do you want it as a standalone patch there, or kept in this series? I can also guard the KFD submit side so it doesn't push to a stopped entity in the first place, but the sched-side drain is the airtight fix since entity kill can always race a locked pre-check.

Regards,
Olivier

#13 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

In reply to Christian König

Hi Christian,

Quoted 1 line

Yeah and you need to fix the fence orphaning and *NOT* the wait!

Agreed — found the exact orphan site. drm_sched_entity_push_job() pushes the job onto entity->job_queue first, then drm_sched_rq_add_entity() sees entity->stopped (under entity->lock) and returns NULL: the scheduler is never woken, the job strands on the spsc queue, and its fence never signals. In our repro the dying process's fault path submits the migration job on its own killed entity — it's the process-kill race, not a device-unplug race at all, which is why drm_dev_enter() doesn't cover it.

This is the same failure Tong Liu reported in August 2025 (task hang after job submission during process kill); that fix was rejected for checking entity->stopped without the lock. The clean fix is not to pre-check but to handle the NULL return while still under entity->lock: drain the queue / schedule the kill-jobs work so each stranded job's finished fence completes with -ESRCH.

Quoted 1 line

Blocking for all fences is correct shutdown order.

Agreed. v7 drops the timeout entirely — unbounded wait restored. With fences guaranteed to signal, the copy_done error path becomes genuinely reachable via the fence's error status, so the error propagation and migrate->dst rollback Felix asked for stay — now on a real error path instead of a timeout.

v7 is now implemented and tested on this machine (7.3.0-rc5 + p1/p2 teardown+restore-stop, sched orphan fix, KFD fence-error rework). Hot-unplug test: svmhog2 mid-migration plus a second KFD process, then Thunderbolt deauthorize. With only the sched fix the host still wedges — the kill-jobs drain prevents the orphan, but the unplug path additionally needs the KFD teardown ordering (processes torn down before device early-fini) and the restore worker stopping on -ENODEV. With the full stack, across two unplug/replug cycles and a 60-round kill-under-memory-pressure
soak: fences complete with error instead of orphaning, the KFD processes get SIGBUS and reap cleanly, device tears down, host stays alive, and re-authorizing gives a clean re-enumeration. So your direction was right — the wait was never the bug — but the orphan fix is necessary rather than sufficient for unplug.

On layering: I'm posting the sched fix standalone to dri-devel ("drm/scheduler: signal fences of jobs pushed to a stopped entity") since it is drm-misc territory and also fixes the same hang for any other driver pushing to a killed entity. The KFD series then just needs the error propagation. Happy to fold it into this series instead if you prefer.

Regards,
Olivier

#14 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

In reply to Christian König

Hi Christian,

Quoted 1 line

Fences *must* always signal especially when the device is hot removed.

Agreed in principle — but the observed failure is precisely the counter-case. During teardown the dying process's fault path submits an SDMA job to an already-killed drm_sched entity:

drm_sched_rq_add_entity: Trying to push to a killed entity

The job never reaches a ring, nothing is left to signal its fence, and the uninterruptible wait in svm_migrate_copy_done() never returns. That orphaned fence is what kept the task in D state for good in the repro.

Quoted 2 lines

a non interruptible wait with AMDGPU_FENCE_JIFFIES_TIMEOUT can never fail.

The ret < 0 branch is indeed dead code — dropped it in v6, thanks.

The bound itself is needed for a subtler reason: the wait now runs inside a drm_dev_enter() critical section, and drm_dev_unplug() blocks until all such sections exit. An unbounded wait inside the section would deadlock the unplug path against any fence that fails to signal, for whatever reason. This is also the shape Felix asked for — guard HW access with dev_enter/exit and keep no unbounded fence waits inside those sections.

If you'd rather guarantee the invariant at the source — i.e. error out fences orphaned by jobs pushed to an already-killed entity in drm_sched — happy to look at that too, but it is a much wider change than the KFD-side guard.

Regards,
Olivier

maintainer
#15 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Hi Olivier,

looks like my mail from yesterday wasn't send out, so re-sending that again.

Don't be surprised if you receive two messages.

Quoted 9 lines · Olivier Kaloudoff

Hi Christian,

Quoted 1 line

Fences *must* always signal especially when the device is hot removed.

Agreed in principle — but the observed failure is precisely the counter-case. During teardown the dying process's fault path submits an SDMA job to an already-killed drm_sched entity:

drm_sched_rq_add_entity: Trying to push to a killed entity

Yeah and that needs to be prevented.

That is incorrect teardown order in the KFD. When the entity is killed no further submissions to it are possible.

Quoted 10 lines

The job never reaches a ring, nothing is left to signal its fence, and the uninterruptible wait in svm_migrate_copy_done() never returns. That orphaned fence is what kept the task in D state for good in the repro.

Quoted 2 lines

a non interruptible wait with AMDGPU_FENCE_JIFFIES_TIMEOUT can never fail.

The ret < 0 branch is indeed dead code — dropped it in v6, thanks.

Quoted 7 lines

The bound itself is needed for a subtler reason: the wait now runs inside a drm_dev_enter() critical section, and drm_dev_unplug() blocks until all such sections exit. An unbounded wait inside the section would deadlock the unplug path against any fence that fails to signal, for whatever reason. This is also the shape Felix asked for — guard HW access with dev_enter/exit and keep no unbounded fence waits inside those sections.

Yeah and that is perfectly correct. drm_dev_unplug() *must* be blocked until all fences are signaled.

Quoted 4 lines

If you'd rather guarantee the invariant at the source — i.e. error out fences orphaned by jobs pushed to an already-killed entity in drm_sched — happy to look at that too, but it is a much wider change than the KFD-side guard.

No, what we need to avoid killing the entity while KFD is still using it!

That is basically an use after free what you have here, only that the drm_sched can point that out with a warning instead of crashing immediately.

Regards,
Christian.

Quoted 3 lines

Regards,
Olivier

#16 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Hi Christian,

Quoted 6 lines

No, what we need to avoid killing the entity while KFD is still using it!

That is basically an use after free what you have here, only that the drm_sched can point that out with a warning instead of crashing immediately.

The exact "use" we hit is the dying process's own exit fault:
SIGBUS -> coredump -> get_dump_page -> do_swap_page -> svm_migrate_to_ram() submits the migration job on the process's own entity after drm_sched_entity_kill() already ran for it.

I think we actually need two complementary things rather than a choice between them:

b) The scheduler-level guarantee: a job pushed to an entity must have its fence complete. drm_sched_rq_add_entity() returning NULL for a stopped entity leaves the pushed job stranded on the spsc queue forever — that window exists independently of who killed the entity when. My patch closes it atomically under entity->lock: either the entity is live and the job queues normally, or it is stopped and the job goes through kill_jobs_work so its fence completes with -ESRCH. This is a generic scheduler invariant, not a KFD workaround, and it is the only fix demonstrated to prevent the fence-orphan hang.

It is also required on surprise removal even with perfect entity lifetime ordering: a job can be pushed while the entity is still live, then the device disappears before the job completes. Fences must still signal — which is exactly your "fences *must* always signal" requirement.

a) The KFD-side lifetime ordering you want: don't kill the entity while KFD can still submit. Worth doing, but the boundary is hard to place — the submitter is the dying task's own mm fault path (coredump -> do_swap_page), not a KFD-controlled context, and the "mm can no longer fault on SVM ranges" point is earlier than exit_mmap and not obviously under KFD's teardown control.

So my question: is there an existing KFD ordering point that guarantees no further SVM migration submission for a process's mm — for example after MMU-notifier release but before entity kill? If there is, I'll implement (a) there. If not, I'd like to land (b) as the scheduler-level guarantee, and then evaluate whether an additional KFD lifetime ordering is feasible on top.

Quoted 1 line

drm_dev_unplug() *must* be blocked until all fences are signaled.

Agreed — the drm_dev_enter/exit submit guard and the unbounded wait stay, and copy_done now propagates dma_fence_error() so a failed copy can never complete as a successful migration.

Regards,
Olivier

maintainer
#17 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Hi Olivier,

adding Philip and Danilo as DRM scheduler maintainers, just FYI on the technical background.

Quoted 5 lines · Olivier Kaloudoff

Hi Christian,

Quoted 3 lines

No, what we need to avoid killing the entity while KFD is still using it!

Quoted 8 lines
Quoted 3 lines

That is basically an use after free what you have here, only that the drm_sched can point that out with a warning instead of crashing immediately.

The exact "use" we hit is the dying process's own exit fault:
SIGBUS -> coredump -> get_dump_page -> do_swap_page -> svm_migrate_to_ram() submits the migration job on the process's own entity after drm_sched_entity_kill() already ran for it.

Well, thanks for confirming my worst fear :) That is exactly what I expected and it is essentially unfixable.

Quoted 5 lines

I think we actually need two complementary things rather than a choice between them:

b) The scheduler-level guarantee: a job pushed to an entity must have its fence complete.

Approaches like those were rejected many times before, but just for the record: Big *NAK* to any hacks with the dma_fence signaling, especially in this particular case here it will definitely cause data corruption.

Quoted 10 lines

drm_sched_rq_add_entity() returning NULL
for a stopped entity leaves the pushed job stranded on the spsc queue forever — that window exists independently of who killed the entity when. My patch closes it atomically under entity->lock: either the entity is live and the job queues normally, or it is stopped and the job goes through kill_jobs_work so its fence completes with -ESRCH. This is a generic scheduler invariant, not a KFD workaround, and it is the only fix demonstrated to prevent the fence-orphan hang.

Quoted 5 lines

It is also required on surprise removal even with perfect entity lifetime ordering: a job can be pushed while the entity is still live, then the device disappears before the job completes. Fences must still signal — which is exactly your "fences *must* always signal" requirement.

That plan is clearly not going to fly.

The problem is caused by a hotplug while memory is still migrated to the device. In other words svm_migrate_to_ram() tries to pull back the data from a device which is gone.

So the data is gone as well and if that is some memory mapping of a file it is perfectly possible that it is also written back to a storage device when the dma_fence signals.

This is similar to ripping out DRAM while it is still in use, the best thing you can do here to avoid further damage is to call panic().

Quoted 6 lines

a) The KFD-side lifetime ordering you want: don't kill the entity while KFD can still submit. Worth doing, but the boundary is hard to place — the submitter is the dying task's own mm fault path (coredump -> do_swap_page), not a KFD-controlled context, and the "mm can no longer fault on SVM ranges" point is earlier than exit_mmap and not obviously under KFD's teardown control.

Well that is not this much of a problem with the fences, but even that wouldn't help.

This is unfixable. You are running into unavoidable data corruption because of the SVM handling.

The only way you can avoid that is to make SVM and hotplug mutual exclusive.

Regards,
Christian.

Quoted 16 lines

So my question: is there an existing KFD ordering point that guarantees no further SVM migration submission for a process's mm — for example after MMU-notifier release but before entity kill? If there is, I'll implement (a) there. If not, I'd like to land (b) as the scheduler-level guarantee, and then evaluate whether an additional KFD lifetime ordering is feasible on top.

Quoted 1 line

drm_dev_unplug() *must* be blocked until all fences are signaled.

Agreed — the drm_dev_enter/exit submit guard and the unbounded wait stay, and copy_done now propagates dma_fence_error() so a failed copy can never complete as a successful migration.

Regards,
Olivier

#18 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Quoted 14 lines · Christian König

Hi Olivier,

adding Philip and Danilo as DRM scheduler maintainers, just FYI on the technical background.

Quoted 9 lines · Olivier Kaloudoff

Hi Christian,

Quoted 6 lines

No, what we need to avoid killing the entity while KFD is still using it!

That is basically an use after free what you have here, only that the drm_sched can point that out with a warning instead of crashing immediately.

Quoted 7 lines
Quoted 4 lines

The exact "use" we hit is the dying process's own exit fault:
SIGBUS -> coredump -> get_dump_page -> do_swap_page -> svm_migrate_to_ram() submits the migration job on the process's own entity after drm_sched_entity_kill() already ran for it.

Well, thanks for confirming my worst fear :) That is exactly what I expected and it is essentially unfixable.

What prevents you from having your own synchronisation primitive in the struct where your drm_sched_entity lives in?

Quoted 5 lines
Quoted 5 lines

I think we actually need two complementary things rather than a choice between them:

b) The scheduler-level guarantee: a job pushed to an entity must have its fence complete.

drm_sched_entity_kill() is part of this data structure's destructor- path. amdgpu does not even invoke it directly, just drm_sched_entity_fini().

After the destructor ran, all usage of the destructed data structure is effectively undefined behavior.

// Thread A
foo_fini(ptr);
kfree(ptr);

// Thread B
do_stuff_with(ptr); // explodes

You cannot fix this by modifying foo_fini() or kfree().

As Christian has pointed out, the only reason why you don't run into UAF is that amdgpu keeps the memory the entity lives in alive for longer.

The solution is to use the API correctly. You must stop thread A from killing your resources while B is still trying to use them. Or you must stop B from using something that was deconstructed.

You need a separate synchronisation primitive for that.

Quoted 10 lines

Approaches like those were rejected many times before, but just for the record: Big *NAK* to any hacks with the dma_fence signaling, especially in this particular case here it will definitely cause data corruption.

Quoted 4 lines

drm_sched_rq_add_entity() returning NULL
   for a stopped entity leaves the pushed job stranded on the spsc queue forever — that window exists independently of who killed the entity when.

No one must push to a killed entity, no matter where and when. This is a lifetime problem within amdgpu that must not be worked around in drm_sched.

Regarding your device unplug issue… as you know we're attempting to get those things right in Rust and really prevent this entire class of bugs.

A data structure that is very helpful in this regard is Revocable:

https://rust.docs.kernel.org/next/kernel/revocable/struct.Revocable.html

It revokes access to a device / hardware resource by setting an atomic bool, and then waits an RCU grace period until everyone has seen that access to this resource is now revoked.

Maybe you can draw inspiration from that for C?

P.

Quoted 1 line
maintainer
#19 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Quoted 20 lines · Philipp Stanner
Quoted 19 lines · Christian König

Hi Olivier,

adding Philip and Danilo as DRM scheduler maintainers, just FYI on the technical background.

Quoted 13 lines · Olivier Kaloudoff

Hi Christian,

Quoted 6 lines

No, what we need to avoid killing the entity while KFD is still using it!

That is basically an use after free what you have here, only that the drm_sched can point that out with a warning instead of crashing immediately.

The exact "use" we hit is the dying process's own exit fault:
SIGBUS -> coredump -> get_dump_page -> do_swap_page -> svm_migrate_to_ram() submits the migration job on the process's own entity after drm_sched_entity_kill() already ran for it.

Quoted 5 lines
Quoted 2 lines

Well, thanks for confirming my worst fear :) That is exactly what I expected and it is essentially unfixable.

What prevents you from having your own synchronisation primitive in the struct where your drm_sched_entity lives in?

The problem isn't really the synchronization nor the UAF of the scheduler entity.

The fundamental problem is that SVM/HMM means that the local memory of the PCIe device (VRAM) is registered as "normal" system memory but in a way so that the kernel wouldn't use it by default for get free page.

So you got struct pages for the device memory very similar to how for example DAX works. On GPU access the memory is then migrated to the device local memory and the system memory copy of the page is freed up.

When you then now howplug the GPU and with it the local memory the data is from one second to next completely lost. If the data is an anonymous page the application will just crash, if the data is a memory mapped file it will eventually be tried to written back to storage. So you can even corrupt your file system with that leading to the system not booting anymore at all.

I mean I have seen hot remove of DRAM modules like 30 years ago already, SPARC was really big with that. But in this case you got a red led where you ECC error was, pressed a button and halve a second later the OS removed all valuable data from this DRAM module and it was safe to remove.

Hotplug on the other hand is a completely different beast because you don't get a pre-notification that you need to save your data. So hotplug is essentially incompatible with SVM/HMM.

What Oliver tries to do here will never work even in theory.

Regards,
Christian.

maintainer
#20 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Quoted 23 lines · Christian König
Quoted 14 lines · Philipp Stanner
Quoted 13 lines · Christian König

Hi Olivier,

adding Philip and Danilo as DRM scheduler maintainers, just FYI on the technical background.

Quoted 8 lines · Olivier Kaloudoff

Hi Christian,

Quoted 6 lines

No, what we need to avoid killing the entity while KFD is still using it!

That is basically an use after free what you have here, only that the drm_sched can point that out with a warning instead of crashing immediately.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

The exact "use" we hit is the dying process's own exit fault:
SIGBUS -> coredump -> get_dump_page -> do_swap_page -> svm_migrate_to_ram() submits the migration job on the process's own entity after drm_sched_entity_kill() already ran for it.

Well, thanks for confirming my worst fear :) That is exactly what I expected and it is essentially unfixable.

What prevents you from having your own synchronisation primitive in the struct where your drm_sched_entity lives in?

Quoted 7 lines

The problem isn't really the synchronization nor the UAF of the scheduler entity.

The fundamental problem is that SVM/HMM means that the local memory of the PCIe device (VRAM) is registered as "normal" system memory but in a way so that the kernel wouldn't use it by default for get free page.

So you got struct pages for the device memory very similar to how for example DAX works. On GPU access the memory is then migrated to the device local memory and the system memory copy of the page is freed up.

When you then now howplug the GPU and with it the local memory the data is from one second to next completely lost. If the data is an anonymous page the application will just crash, if the data is a memory mapped file it will eventually be tried to written back to storage. So you can even corrupt your file system with that leading to the system not booting anymore at all.

Migration of file-backed VMAs is not supported by HMM, as far as I know.

Quoted 6 lines

I mean I have seen hot remove of DRAM modules like 30 years ago already, SPARC was really big with that. But in this case you got a red led where you ECC error was, pressed a button and halve a second later the OS removed all valuable data from this DRAM module and it was safe to remove.

Hotplug on the other hand is a completely different beast because you don't get a pre-notification that you need to save your data. So hotplug is essentially incompatible with SVM/HMM.

What Oliver tries to do here will never work even in theory.

What are we trying to achieve here? I think Olivier just wants the kernel to not hang or crash. It's obvious that any application using the unplugged GPU will die with a SIGBUS or some other catastrophic event. It doesn't really matter whether it used SVM or not. So if the result is that a migration of an anonymous page from unplugged VRAM back to system memory fails with a SIGBUS, that's not a big deal. That application was going to die anyway.

But we don't want the kernel to crash or panic if we can help it. And I don't see a fundamental reason why the kernel should crash.

Regards,
  Felix

Quoted 3 lines

Regards,
Christian.

maintainer
#21 lore raw

Re: [PATCH v5 3/3] drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

Quoted 26 lines · Felix
Quoted 25 lines · Christian König
Quoted 14 lines · Philipp Stanner
Quoted 13 lines · Christian König

Hi Olivier,

adding Philip and Danilo as DRM scheduler maintainers, just FYI on the technical background.

Quoted 8 lines · Olivier Kaloudoff

Hi Christian,

Quoted 6 lines

No, what we need to avoid killing the entity while KFD is still using it!

That is basically an use after free what you have here, only that the drm_sched can point that out with a warning instead of crashing immediately.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

The exact "use" we hit is the dying process's own exit fault:
SIGBUS -> coredump -> get_dump_page -> do_swap_page -> svm_migrate_to_ram() submits the migration job on the process's own entity after drm_sched_entity_kill() already ran for it.

Well, thanks for confirming my worst fear :) That is exactly what I expected and it is essentially unfixable.

What prevents you from having your own synchronisation primitive in the struct where your drm_sched_entity lives in?

The problem isn't really the synchronization nor the UAF of the scheduler entity.

Quoted 7 lines
Quoted 5 lines

The fundamental problem is that SVM/HMM means that the local memory of the PCIe device (VRAM) is registered as "normal" system memory but in a way so that the kernel wouldn't use it by default for get free page.

So you got struct pages for the device memory very similar to how for example DAX works. On GPU access the memory is then migrated to the device local memory and the system memory copy of the page is freed up.

When you then now howplug the GPU and with it the local memory the data is from one second to next completely lost. If the data is an anonymous page the application will just crash, if the data is a memory mapped file it will eventually be tried to written back to storage. So you can even corrupt your file system with that leading to the system not booting anymore at all.

Migration of file-backed VMAs is not supported by HMM, as far as I know.

That would solve quite a number of problems, but I don't think that this is covers all requirements.

On demand loading of files into device memory is one of the major reasons we do this in the first place.

Quoted 8 lines
Quoted 6 lines

I mean I have seen hot remove of DRAM modules like 30 years ago already, SPARC was really big with that. But in this case you got a red led where you ECC error was, pressed a button and halve a second later the OS removed all valuable data from this DRAM module and it was safe to remove.

Hotplug on the other hand is a completely different beast because you don't get a pre-notification that you need to save your data. So hotplug is essentially incompatible with SVM/HMM.

What Oliver tries to do here will never work even in theory.

What are we trying to achieve here? I think Olivier just wants the kernel to not hang or crash. It's obvious that any application using the unplugged GPU will die with a SIGBUS or some other catastrophic event. It doesn't really matter whether it used SVM or not. So if the result is that a migration of an anonymous page from unplugged VRAM back to system memory fails with a SIGBUS, that's not a big deal. That application was going to die anyway.

No applications usually survive a hotplug event for a GPU device. This is absolutely mandatory behavior for display servers for example.

The documented and implemented approach for all drivers is to return -ENODEV from all IOCTLs and redirect eventual memory mappings to a dummy page.

Quoted 1 line

But we don't want the kernel to crash or panic if we can help it. And I don't see a fundamental reason why the kernel should crash.

Yeah that's what I agree on. We should have a clear destruction order.

But another major question is what we do with SVM mappings which we can't migrate back because the device is gone? Just allocate a page and leave it like this? That will certainly result in corruption sooner or later.

Regards,
Christian.

Quoted 8 lines

Regards,
  Felix

Quoted 3 lines

Regards,
Christian.

maintainer
#22 lore raw
In reply to Olivier Kaloudoff
Quoted 38 lines · Olivier Kaloudoff

On surprise removal of a GPU behind Thunderbolt (MI50, PCIe slot power cut), the KFD teardown path wedges the host:

- the killed KFD process faults on its own SVM ranges during exit / coredump (SIGBUS -> get_dump_page -> do_swap_page -> svm_migrate_to_ram), submits SDMA work to an already-killed drm_sched entity, and waits uninterruptibly on a fence that can never signal;
- the dying task holds svms->lock, which wedges svm_range_restore_work() and prevents kfd_processes_count from draining;
- kgd2kfd_teardown_processes() therefore spins forever in cond_resched() while holding the pciehp removal thread, producing soft-lockup and hung-task splats.

This series:

1. tears KFD processes down in amdgpu_device_fini_hw() *before* amdgpu_amdkfd_device_fini_sw() frees kfd.dev on disconnect, so the drain happens while kfd.dev is still valid, and guards the second kgd2kfd_teardown_processes() call against kfd.dev already being gone;

2. makes the userptr and SVM range restore workers stop rescheduling

    themselves on -ENODEV;

3. guards the hardware-accessing SVM migration sections with drm_dev_enter()/drm_dev_exit() and bounds the job fence wait with AMDGPU_FENCE_JIFFIES_TIMEOUT, so a migration cannot race with unplug and a fence on a dead device cannot stall the critical section or the faulting task indefinitely.

Verified on MI50 behind Thunderbolt (2 GB SVM workload, PCIe slot power cut): the workload takes SIGBUS, coredump completes, kfd_processes_count drains in ~7s, pciehp removal finishes without warnings, and the device re-enumerates cleanly on slot re-power. Previously the same repro wedged the host every time.

Quoted 4 lines

Changes in v5:
- patch 3: dropped the drm_dev_is_unplugged() and pci_dev_is_disconnected() checks entirely; drm_dev_enter()/exit() plus the bounded fence wait is sufficient (Felix Kuehling)

Thanks. Patches 1 and 2 look good now. I found one more problem with the handling of the new timeout error conditions in patch 3 that will need to be addressed before this can be submitted.

Regards,
  Felix

Quoted 35 lines

Changes in v4:
- patch 3: AMDGPU_FENCE_JIFFIES_TIMEOUT instead of an open-coded 10s; drm_dev_enter()/exit() guarding the whole migration section including the bounded wait (Felix Kuehling)
- patch 2: folded in the svm_range_restore_work() -ENODEV change; fixed a latent uninitialized ret read on the evicted_bos-mismatch and confirm_valid-WARN paths

Changes in v3:
- patch 1: NULL guard for the second teardown call (Christian König)
- patch 3: new, fail fast on gone device in SVM migration paths

Changes in v2:
- patch 1: drain before fini_sw instead of bounding the wait (Christian König)
- patch 2: new, stop restore retries on unplug

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

Olivier Kaloudoff (3):
drm/amdkfd: tear down KFD processes before early fini_sw on disconnect drm/amdkfd: stop restore retries on device unplug drm/amdkfd: bound SVM migration fence wait and guard with drm_dev_enter

  drivers/gpu/drm/amd/amdgpu/amdgpu_device.c        |  5 ++-
  .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c      | 29 +++++++++++++----
  drivers/gpu/drm/amd/amdkfd/kfd_device.c           |  9 ++++-
  drivers/gpu/drm/amd/amdkfd/kfd_migrate.c          | 36 ++++++++++++++++++--
  drivers/gpu/drm/amd/amdkfd/kfd_svm.c              |  2 +-
  5 files changed, 70 insertions(+), 11 deletions(-)