Skip to contentSkip to conversation

amdkfd: survive PCIe surprise removal with live KFD processes

PATCH New Olivier Kaloudoff 1 participant 4 messages Oct 7

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

v4 cover amdkfd: survive PCIe surprise removal with live KFD processes

On PCIe surprise removal (Thunderbolt eGPU link drop) with KFD processes attached, three stacked problems wedge the removal path:

1. amdgpu_device_fini_hw() frees kfd.dev via the early amdgpu_amdkfd_device_fini_sw() on the disconnected path before amdgpu_amdkfd_teardown_processes() in ip_fini_early ever runs - the unguarded kfd_processes_count dereference then NULL-faults (or UAFs) the pciehp removal thread.

2. The KFD userptr and SVM restore workers reschedule themselves unconditionally on validation failure. On a gone device validation can never succeed; each 1ms retry takes process_info->lock and notifier_lock, observed as ~11k cycles until soft-lockup while process teardown cannot proceed.

3. The dying process's own exit path faults on its SVM ranges (SIGBUS -> coredump -> do_swap_page -> svm_migrate_to_ram) and submits a copy job to an already-killed drm_sched entity, then waits uninterruptibly on a fence that can never signal - holding svms->lock the whole time, so kfd_processes_count never drains.

Patch 1 moves the process teardown ahead of the early fini_sw() so the drain wait runs while kfd.dev is still valid, and keeps a NULL guard for the second teardown invocation. The wait stays unbounded by design - returning early would just defer a use-after-free.

Patch 2 stops both restore workers rescheduling on -ENODEV.

Patch 3 makes the SVM migration paths hold drm_dev_enter() across submit+wait so unplug cannot tear the sched entity down underneath, keeps pci_dev_is_disconnected() as the early-out for the physically-gone window, and bounds the fence wait with AMDGPU_FENCE_JIFFIES_TIMEOUT as a fallback.

All three verified together on MI50 32GB behind Thunderbolt 3 (Razer Core X, ~2GB of SVM managed ranges + queues, pciehp Surprise+ slot power-off): SIGBUS is delivered, coredump completes, the process count drains in ~7s, removal completes, and the device re-enumerates cleanly on slot re-power. ftrace confirms teardown now runs before fini_sw.

Changes in v4 (per Felix Kuehling's review):
- 3/3: drm_dev_enter/exit around the migration instead of bare flag checks; AMDGPU_FENCE_JIFFIES_TIMEOUT instead of open-coded 10s
- svm_range_restore_work() -ENODEV hunk moved from 3/3 to 2/3
- 2/3: also assign ret on the evicted_bos-mismatch and confirm_valid_user_pages paths - posted v2 read ret uninitialized on those two paths
- 1/3: unchanged

Changes in v3:
- 1/3: drop the 30s bound (Christian); run teardown before the early fini_sw; NULL guard for the second invocation
- 2/3: resubmission of the posted v2 userptr worker patch
- 3/3: new, SVM migration fail-fast

Changes in v2 of the userptr patch:
- ret not pre-initialized; no pr_warn_once (Christian König)

Olivier Kaloudoff (3):
drm/amdkfd: teardown processes before freeing kfd.dev on surprise removal drm/amdkfd: stop restore retries on device unplug
drm/amdkfd: fail fast on unplugged device in SVM migration paths

 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c       |  5 +++-
 drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 16 ++++++++---
 drivers/gpu/drm/amd/amdkfd/kfd_device.c          |  9 ++++++-
 drivers/gpu/drm/amd/amdkfd/kfd_migrate.c         | 33 ++++++++++++++++++++++--
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c             |  4 ++-
 5 files changed, 60 insertions(+), 8 deletions(-)
#1 lore raw

PATCH v4 1/3 drm/amdkfd: teardown processes before freeing kfd.dev on surprise removal

On surprise removal the PCI core runs amdgpu_device_fini_hw(), which calls amdgpu_amdkfd_device_fini_sw() as soon as pci_dev_is_disconnected() is set. That frees kfd.dev - including the kfd_processes_count it embeds - before amdgpu_amdkfd_teardown_processes() in amdgpu_device_ip_fini_early() ever runs. The unconditional adev->kfd.dev->kfd_processes_count dereference in the wait loop then crashes the pciehp removal thread (observed as a +0x1b4 NULL deref on MI50 Thunderbolt unplug).

Move the process teardown ahead of the early fini_sw() on the disconnected path so that terminate events are sent and the drain wait runs while kfd.dev is still valid. Keep a NULL guard in kgd2kfd_teardown_processes() for the second invocation from ip_fini_early, where kfd.dev is already NULL.

The wait itself stays unbounded: returning while processes still reference kfd.dev would just trade the NULL deref for a deferred use-after-free in kfd_process_remove_pdd() when it decrements kfd_processes_count on freed memory.

Fixes 28695ca09d32 ("drm/amd: Clean up kfd node on surprise disconnect")
Fixes d12d05c4bc4c ("drm/amdkfd: Check if there are kfd porcesses using adev by kfd_processes_count")
Cc Xiaogang Chen <[email protected]>

---
Changes in v4: unchanged.

Changes in v3:
- drop the 30s bound; the drain wait is unbounded again (CK)
- run teardown before the early fini_sw() on the disconnected path so the wait actually observes kfd_processes_count while kfd.dev is still valid; NULL guard kept for the second invocation from ip_fini_early
- v1 took a bounded-wait approach; v2 of this patch was never posted

 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 5 ++++-
 drivers/gpu/drm/amd/amdkfd/kfd_device.c    | 9 ++++++++-
 2 files changed, 12 insertions(+), 2 deletions(-)
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 v4 2/3 drm/amdkfd: stop restore retries on device unplug

In reply to Olivier Kaloudoff

amdgpu_amdkfd_restore_userptr_worker() reschedules itself every AMDGPU_USERPTR_RESTORE_DELAY_MS whenever validation of invalidated userptr BOs fails, and svm_range_restore_work() likewise reschedules itself every AMDGPU_SVM_RANGE_RESTORE_DELAY_MS when range validation fails. On PCIe surprise removal the underlying update/migration paths fail fast with -ENODEV (amdgpu_vm_update_pdes() and amdgpu_vm_update_range() return -ENODEV when drm_dev_enter() fails, which propagates up through validate_invalid_user_pages(); the SVM validation paths get -ENODEV once the migration paths check for a gone device, see patch 3). Both workers ignore the error code and reschedule unconditionally, producing endless retry loops on a device that is permanently gone. The worker cancel in the teardown paths only runs at last-VM/process destroy, which itself can be delayed arbitrarily on unplug.

Observed on MI50 eGPU TB3 surprise removal: ~11k rescheduled userptr restore cycles, the worker holding reclaim-related locks until the system soft-locked up.

Stop rescheduling when the failure is -ENODEV: the device is gone for good and the affected processes are being torn down anyway. Other errors keep the existing retry behavior, as they may be transient.

---
Changes in v4:
- also stop the svm_range_restore_work() retries on -ENODEV (moved from patch 3, per Felix Kuehling)
- assign ret on the evicted_bos-mismatch and confirm_valid_user_pages
paths: posted v2 read ret uninitialized on those two paths before the reschedule check
- retitle to cover both restore workers

Changes in v3: resubmission, unchanged from the v2 already posted.

Changes in v2:
- Don't pre-initialize ret; every path to the reschedule check is dominated by an assignment (Christian König)
- Drop the pr_warn_once; hot removal is a normal abort condition for the worker (Christian König)

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));
#3 lore raw

PATCH v4 3/3 drm/amdkfd: fail fast on unplugged device in SVM migration paths

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 an unplug check, 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.

Block unplug for the duration of a migration with drm_dev_enter()/ drm_dev_exit() instead of racy flag checks: the enter section covers both the job submission and the fence wait, so the sched entity cannot be torn down underneath. pci_dev_is_disconnected() is kept as an early-out since the PCI flag can be set well before drm_dev_unplug() runs. The fence wait in svm_migrate_copy_done() is additionally bounded by AMDGPU_FENCE_JIFFIES_TIMEOUT as a fallback for the submit->wait window on a device that dies electrically without a running removal.

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

---
Changes in v4 (per Felix Kuehling's review):
- replace the bare drm_dev_is_unplugged()/pci_dev_is_disconnected() checks with drm_dev_enter()/drm_dev_exit() around the migration; pci_dev_is_disconnected() is kept as the early-out for the physically-gone-before-unplug window
- bound the fence wait with AMDGPU_FENCE_JIFFIES_TIMEOUT instead of an open-coded 10 s
- move the svm_range_restore_work() -ENODEV hunk to patch 2

New in v3.

drivers/gpu/drm/amd/amdkfd/kfd_migrate.c +32 -1
index 253365a..e5faa2b 100644
@@ -202,7 +202,21 @@ svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence)
 	int r = 0;
 
 	if (mfence) {
-		r = dma_fence_wait(mfence, false);
+		/* Job fences on a dead device never signal */
+		if (drm_dev_is_unplugged(adev_to_drm(adev)) ||
+		    pci_dev_is_disconnected(adev->pdev)) {
+			r = -ENODEV;
+		} else {
+			long ret;
+
+			/* survive unplug between submit and wait */
+			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 +508,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 +522,12 @@ 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;
 	}
+	/* The device may be electrically gone before drm_dev_unplug() runs */
+	if (pci_dev_is_disconnected(node->adev->pdev))
+		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 +542,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 +587,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 +844,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 +865,12 @@ 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;
 	}
+	/* The device may be electrically gone before drm_dev_unplug() runs */
+	if (pci_dev_is_disconnected(node->adev->pdev))
+		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 +915,7 @@ int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm,
 		}
 	}
 
+	drm_dev_exit(idx);
 	return r < 0 ? r : 0;
 }