Skip to contentSkip to conversation

drm/amdgpu: AMDGPU SVM support based on DRM (Phase 1: single GPU, XNACK on)

PATCH New Huang Rui 1 participant 23 messages Nov 27

Subsystems (5)
lore
Share & tools
lore

Huang Rui

author
#0 lore raw

v11 cover drm/amdgpu: AMDGPU SVM support based on DRM (Phase 1: single GPU, XNACK on)

Hi Christian, Philip, Alex, Felix, and all,

These series introduce a new Shared Virtual Memory (SVM) implementation for amdgpu that is built directly on top of the common DRM GPUSVM / drm_pagemap core (drivers/gpu/drm/drm_gpusvm.c, drm_pagemap.c) rather than on the existing KFD-private SVM code in amdkfd/kfd_svm.c.

The goal is to provide HMM-based unified memory through the same shared infrastructure that the Xe driver already uses, so that amdgpu and xe converge on one well-reviewed SVM/page-migration core instead of maintaining a separate amdgpu-specific stack.

Dependencies
============

This series is rebased on top of Christian's amdgpu VM rework series and depends on it. The SVM locking work in patches 13-15 builds directly on the eviction-lock critical section and the amdgpu_vm_update_range() split introduced there, so this series does not apply or build without it:

https://lore.kernel.org/amd-gfx/[email protected]/

Phased plan
===========

This work is being upstreamed in phases to keep each submission reviewable:

* Phase 1 (this series): single GPU, XNACK on (retry faults).
- v9 https://lore.kernel.org/amd-gfx/[email protected]/

* Phase 2 (in progress): single GPU, XNACK off (no-retry / eager mapping).
- https://lore.kernel.org/amd-gfx/[email protected]/
- https://lore.kernel.org/amd-gfx/[email protected]/

* Phase 3 (in progress): multiple GPUs (XGMI mapping, P2P device-to-device migration).
- https://lore.kernel.org/amd-gfx/[email protected]

Accordingly, this first submission targets the simplest useful configuration:

* Single GPU with local VRAM migration: transparent RAM <-> VRAM page migration on one GPU via SDMA, with TTM-based eviction for overcommit.
* XNACK on (retry faults): GPU page faults are retried after the driver lazily populates PTEs on demand. The XNACK-off/eager-mapping path is deferred to Phase 2.
* Compute VMs only (amdgpu_vm_make_compute()), matching the KFD SVM use case.

Everything is gated behind a new, default-n Kconfig option (CONFIG_DRM_AMDGPU_SVM) and is therefore opt-in and isolated from existing users until the feature matures.

UAPI
====

A new render-node ioctl, DRM_IOCTL_AMDGPU_GEM_SVM, lets userspace describe SVM attributes over a CPU virtual-address interval (patch 1):

- operations: SET_ATTR / GET_ATTR / RESET_ATTR
- access modes: INACCESSIBLE / IN_PLACE / ALLOW_MIGRATE
- location hints: SYSMEM / UNDEFINED / LOCAL / HIVE (preferred_loc, prefetch_loc). The location is a fixed enum rather than a device file descriptor on purpose: a descriptor has no stable meaning across a checkpoint/restore cycle.
- per-range flags: HOST_ACCESS, COHERENT, EXT_COHERENT, GPU_RO, GPU_EXEC, GPU_READ_MOSTLY, plus a granularity hint

GET_ATTR additionally returns, in @size, the length of the contiguous range starting at @start_addr over which the queried attributes are constant, so user space (e.g. CRIU) can walk the whole address space without knowing the range boundaries in advance.

Attributes are stored in a per-VM interval tree; the GPU page tables are populated lazily on demand by retry faults, or eagerly on a prefetch request.

User Space Work
===============

- libdrm exposes the new SVM ioctl:
https://gitlab.freedesktop.org/mesa/libdrm/-/merge_requests/485

- ROCm runtime adaptation for the new amdgpu DRM SVM API:

    https://github.com/ROCm/rocm-systems/pull/8318

Design Overview
===============

The implementation is split into clearly layered modules:

amdgpu_svm.c Core context (struct amdgpu_svm embeds
struct drm_gpusvm), kref lifecycle, PASID lookup, drm_gpusvm_ops, the GEM_SVM ioctl entry point, and the GC workqueue.
amdgpu_svm_attr.c The attribute interval tree: validation, gap/overlap
split-merge, SET/GET/RESET, and change-trigger classification that decides whether an attribute change needs PTE invalidation or a remap.
amdgpu_svm_range.c Per-range GPU mapping: PTE-flag computation per GC IP
version, DMA-segment coalescing, MMU-notifier begin/end handling, PTE zapping, and the garbage collector.
amdgpu_svm_fault.c The retry-fault entry point amdgpu_svm_handle_fault()
and the fault_map_range() pipeline.
amdgpu_migrate.c drm_pagemap / ZONE_DEVICE VRAM migration backend.
amdgpu_svm_range_migrate.c Per-range RAM<->VRAM migration helpers.

Fault path (XNACK on):
amdgpu_vm_handle_fault() routes a compute-VM retry fault to amdgpu_svm_handle_fault() when the VM has an SVM context. After PASID lookup and a checkpoint-timestamp filter that drops stale retry faults left over from a recent unmap, it looks up (or synthesizes a default) attribute range and runs fault_map_range(): garbage-collect -> VMA permission check -> find/insert range -> short-circuit if recently validated or already valid -> drm_gpusvm get_pages (HMM) -> program GPU PTEs under the notifier lock with a notifier-sequence re-check.

Locking (patches 13-15):
Following the v9 review, amdgpu_vm's eviction lock is now a selectable read/write semaphore (struct rw_semaphore *eviction_lock) instead of a private mutex. On an SVM VM it is pointed at the drm_gpusvm notifier lock, so page-table updates, MMU-notifier invalidation and TTM eviction all serialize on one lock rather than on separate, unordered ones. Updates made with the root PD reserved take the read side; updates without it, and eviction, take the write side. Because page-table allocation can enter reclaim - and reclaim re-enters the MMU notifier that wants the same lock - the lock is dropped around amdgpu_vm_pt_create() and the range sequence number is rechecked on reacquire, returning -EAGAIN if it moved. Plain graphics VMs keep their own default lock and are unaffected.

Invalidation / GC:
MMU-notifier callbacks zap the affected PTEs (batched, single heavyweight TLB flush) and, for unmap events, queue the range to a high-priority GC workqueue that removes it via drm_gpusvm_range_remove() outside notifier context.

VRAM migration (patches 16-22):
A drm_pagemap is registered over the GPU's VRAM as a ZONE_DEVICE region at device-init / reset-restore time. struct amdgpu_bo_svm (a new BO subtype) backs migrated ranges, with SDMA-based copy_to_devmem / copy_to_ram callbacks using a GART window. TTM eviction of SVM BOs synchronously migrates pages back to system memory, which keeps VRAM overcommit working. The fault and prefetch paths call amdgpu_svm_range_migrate_to_vram() before mapping when migration is requested, with a single -EBUSY retry that evicts conflicting pages first.

Patch 16 ("drm/pagemap: fix page undercount for compound src entries") is a prerequisite fix in the shared drm_pagemap core, found while enabling THP migration on amdgpu. It is independent of this series and can be applied on its own.

Test Results
============

Tested on gfx943 (MI300X) and gfx906 (MI60) with XNACK on:
- KFD test: 95%+ passed.
- ROCR test: all passed.
- HIP catch test: gfx943 (MI300X): 99% passed. gfx906 (MI60): 99% passed.

These numbers come from running the existing KFD and ROCR test suites over the new DRM SVM path, which is enabled by:

https://github.com/ROCm/rocm-systems/pull/13719

IGT test suites covering amdgpu DRM SVM directly will follow.

Changes from Old Version
========================

In previous V8 version, we had consolidated all implementations for the single-GPU XNACK-on mode. This approach followed Christian's suggestion to make the code review process more straightforward.

Previously, the XNACK-on implementation was split into two parts:

- Basic V7
https://lore.kernel.org/amd-gfx/[email protected]/
- Migration V5
https://lore.kernel.org/amd-gfx/[email protected]/

Above two parts are no longer needed to be reviewed separately, please focus on this series.

Changes from V10 to V11:
- Add patch 01 to decouple PTE encoding from buffer objects. The per-IP get_svm_pte_flags callback is removed; SVM reuses get_vm_pte().
- Notifier invalidation zaps the whole range. Surviving ranges with changed attributes drop their cached DMA mappings.
- Remove the IH timestamp checkpoint and the stale retry-fault drain.
- Fix fault filter removal to use the byte address the insert path uses.
- Drop the static VMA precheck from SET_ATTR and GET_ATTR. VMA checks now run only on the fault path.
- Enforce access modes: INACCESSIBLE fails with -EPERM, and only ALLOW_MIGRATE ranges migrate to VRAM. A fault with no VMA fails with -EFAULT.
- Implement SYSMEM prefetch by evicting device pages.
- Validate ioctl VA ranges against the SVM window (-EINVAL).
- Internal cleanups and API adaptations in patches 13-21; other patches keep V10 order.

Changes from V9 to V10:
- Rebased on top of Christian's amdgpu VM rework series (see Dependencies above), which this series now requires. The GEM_SVM ioctl number moved from 0x1B to 0x1C.
- eviction_lock: the V9 limitation is resolved by three new patches (13-15). amdgpu_vm's eviction lock becomes a selectable rwsem aliased to the drm_gpusvm notifier lock on an SVM VM, so page table updates, MMU notifier invalidation and eviction serialize on one lock. It is dropped around amdgpu_vm_pt_create() to avoid the reclaim/notifier recursion, with an -EAGAIN recheck on reacquire.
- Added "drm/pagemap: fix page undercount for compound src entries" as a prerequisite, and made the SDMA copy path folio aware, so THP-backed ranges migrate correctly.
- UAPI: the location enum gained LOCAL/HIVE and UNDEFINED changed from 0xffffffffU to 1, replacing the AMDGPU_SVM_ATTR_HIVE_LOCAL flag. GET_ATTR now returns in @size the length of the range over which the queried attributes are constant, so CRIU can walk the address space.
- Review fixes: the GEM_SVM ioctl no longer creates the SVM context lazily, the missing root BO reservation around context create/destroy was added, the mapping publication moved inside the notifier lock, two range-queueing bugs were fixed, and several error paths now report failure (-EPERM on a write to a read-only range, -EFAULT on a missing VMA, unknown attribute values, TLB flush failures) instead of being silently ignored.
- Cleanups: dropped the private log wrappers in favour of pr_debug() and pr_err_ratelimited(), partition-scoped TLB flushing, kzalloc_obj(), and removed the leftover clean-svm Makefile target.

Changes from V8 to V9:
- This series has been rebased on top of the amdgpu vm fix.
- https://lore.kernel.org/amd-gfx/[email protected]/
- amdgpu_svm.h: dropped the AMDGPU_SVM_KMEM_CACHE_* macros; SVM ranges use plain kzalloc()/kfree().
- amdgpu_svm.h: dropped the flush_tlb callback; amdgpu_svm_flush_tlb() is called directly.
- amdgpu_svm_attr.h: added kerneldoc for the interval tree and list.
- amdgpu_svm_attr.c: dropped the attr slab cache; uses kzalloc()/kfree().
- amdgpu_svm_attr.c: squashed the types header into its implementation patch
- amdgpu_svm_attr.c: renamed the local "flags" to "unsupported_vm_flags".
- amdgpu_svm_attr.c: dropped amdgpu_svm_attr_validate_range_vma() from the fault path; hmm_range_fault() covers it. A lighter sync check is kept only at the set/get attr ioctl entry for fix regression.
- amdgpu_svm_range.h: AMDGPU_SVM_RANGE_DEBUG removed, replaced by a tracepoint.
- amdgpu_svm_range.h: dropped the UNMAP_WORK macro.
- amdgpu_svm_range.c: the fast range valid check is now lock free.
- amdgpu_svm_range.c: zap_ptes always drains the fence regardless of the update return value.
- per IP PTE flags: moved the switch out of the SVM core
into gmc_v9_0.c/gmc_v12_0.c behind a new gmc_funcs->get_svm_pte_flags() callback.
- eviction_lock: drm_gpusvm framwork's limitation blocks using the eviction_lock kept as is.
- SVM/BO overlap: dropped the scan-based amdgpu_svm_attr_check_vm_bo() helper.
- Added drm_pagemap refcount-based deferred destroy for amdgpu_pagemap:
the ZONE_DEVICE mapping is torn down from a destroy worker (amdgpu_pagemap_destroy_work) once the drm_pagemap refcount reaches zero, using drm_dev_enter()/exit() to guard against device teardown
- Added pre_migrate_fence handling in the SDMA copy callbacks: wait for outstanding async VRAM operations (DMA_RESV_USAGE_KERNEL) to complete

Thanks,
Ray/Honglei/Junhua

Honglei Huang (15):
drm/amdgpu: decouple PTE encoding from buffer objects drm/amdgpu: add SVM ioctl UAPI definitions
drm/amdgpu: add SVM core header and VM integration drm/amdgpu: implement SVM attribute tree and helper functions drm/amdgpu: implement SVM attribute set/get/clear operations drm/amdgpu: add SVM range types and work queue interface drm/amdgpu: implement SVM range GPU mapping core drm/amdgpu: implement SVM range notifier and GC helpers drm/amdgpu: add SVM notifier invalidate callback drm/amdgpu: implement SVM initialization and lifecycle drm/amdgpu: add SVM ioctl entry and fault handler module drm/amdgpu: integrate SVM into build system and VM fault path drm/amdgpu: make VM eviction lock read/write to match notifier lock drm/amdgpu: recheck range validity after page table allocation drm/amdgpu: use drm_gpusvm notifier lock for VM eviction

Junhua Shen (7):
drm/pagemap: fix page undercount for compound src entries drm/amdgpu: add VRAM migration infrastructure for drm_pagemap drm/amdgpu: implement drm_pagemap SDMA migration callbacks drm/amdgpu: implement synchronous TTM eviction for SVM BOs drm/amdgpu: hook up ZONE_DEVICE registration in device init and reset drm/amdgpu: add SVM range migration helpers for drm_pagemap drm/amdgpu: integrate VRAM migration into SVM fault and prefetch paths

 drivers/gpu/drm/amd/amdgpu/Kconfig            |  10 +
 drivers/gpu/drm/amd/amdgpu/Makefile           |   4 +
 drivers/gpu/drm/amd/amdgpu/amdgpu.h           |   8 +
 .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c  |   2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c        |   2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c    |   2 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c       |   6 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c       |   2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c       |  34 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.h       |  24 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c   | 900 ++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h   | 107 ++
 drivers/gpu/drm/amd/amdgpu/amdgpu_object.c    |   4 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_reset.c     |   2 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c       | 817 +++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h       | 176 ++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c  | 958 ++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.h  | 180 ++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.c | 433 ++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.h |  38 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c | 708 +++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h | 167 +++
 .../drm/amd/amdgpu/amdgpu_svm_range_migrate.c | 120 +++
 .../drm/amd/amdgpu/amdgpu_svm_range_migrate.h |  35 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_trace.h     |  28 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c       |  20 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_ualink.c    |  36 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c     |   2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c        | 115 ++-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h        |  19 +-
 .../gpu/drm/amd/amdgpu/amdgpu_vm_internal.h   |  31 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c     |  31 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v10_0.c        |   8 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v11_0.c        |   8 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v12_0.c        |   6 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v12_1.c        |  31 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v6_0.c         |   2 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v7_0.c         |   2 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v8_0.c         |   2 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v9_0.c         |  25 +-
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c          |  10 +-
 drivers/gpu/drm/drm_pagemap.c                 |  60 +-
 include/uapi/drm/amdgpu_drm.h                 | 127 +++
 43 files changed, 5162 insertions(+), 140 deletions(-)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.h
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.h
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range_migrate.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range_migrate.h
Signature · 1 line
2.53.0
author
#1 lore raw

PATCH v11 1/22 drm/amdgpu: decouple PTE encoding from buffer objects

From: Honglei Huang <[email protected]>

Describe backing memory with struct amdgpu_gmc_pte_mem instead of a BO pointer. The GMC encoders need the owning device, memory placement, partition and coherence flags, not the BO itself. Populate this description in existing BO callers and update KFD and UALink callers with the common interface.

Provide an optional destination address: convert VRAM offsets using the owning device's VRAM base and leave system DMA/IOVA addresses unchanged. Existing callers without an address output pass NULL.

Keep BO reservation checking in amdgpu_sync_resv(). The NPA debug message no longer reports the TTM resource range. This prerequisite does not introduce SVM UAPI, attribute types or a separate SVM callback.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c    | 34 ++++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.h    | 24 ++++++++++++---
 drivers/gpu/drm/amd/amdgpu/amdgpu_ualink.c | 12 +++++---
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c     |  6 ++--
 drivers/gpu/drm/amd/amdgpu/gmc_v10_0.c     |  8 ++---
 drivers/gpu/drm/amd/amdgpu/gmc_v11_0.c     |  8 ++---
 drivers/gpu/drm/amd/amdgpu/gmc_v12_0.c     |  6 ++--
 drivers/gpu/drm/amd/amdgpu/gmc_v12_1.c     | 31 +++++++++-----------
 drivers/gpu/drm/amd/amdgpu/gmc_v6_0.c      |  2 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v7_0.c      |  2 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v8_0.c      |  2 +-
 drivers/gpu/drm/amd/amdgpu/gmc_v9_0.c      | 25 +++++++---------
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c       |  3 +-
 13 files changed, 106 insertions(+), 57 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c +34 -0
index 08d3ff61edccd..c47d43e1193be 100644
@@ -410,6 +410,40 @@ void amdgpu_gmc_set_agp_default(struct amdgpu_device *adev,
 	mc->agp_size = 0;
 }
 
+/**
+ * amdgpu_gmc_pte_mem_from_bo() - Describe the backing memory of a BO
+ * @bo: BO backing the mapping.
+ * @mem: Output description for amdgpu_gmc_get_vm_pte().
+ */
+void amdgpu_gmc_pte_mem_from_bo(struct amdgpu_bo *bo,
+				struct amdgpu_gmc_pte_mem *mem)
+{
+	mem->adev = amdgpu_ttm_adev(bo->tbo.bdev);
+	mem->flags = bo->flags;
+	mem->mem_type = bo->tbo.resource ? bo->tbo.resource->mem_type :
+					   TTM_PL_SYSTEM;
+	mem->mem_id = KFD_XCP_MEM_ID(mem->adev, bo->xcp_id);
+}
+
+/**
+ * amdgpu_gmc_get_vm_pte() - Encode a GPU mapping's address and flags
+ * @adev: Device receiving the mapping.
+ * @vm: Address space receiving the mapping.
+ * @mem: Backing memory, or NULL if unknown.
+ * @vm_flags: AMDGPU_VM_PAGE_* and AMDGPU_VM_MTYPE_* mapping flags.
+ * @dst: Optional address in @mem; VRAM offsets become GPU addresses.
+ * @pte_flags: Base PTE flags, updated with the hardware specific bits.
+ */
+void amdgpu_gmc_get_vm_pte(struct amdgpu_device *adev, struct amdgpu_vm *vm,
+			   const struct amdgpu_gmc_pte_mem *mem, u32 vm_flags,
+			   u64 *dst, u64 *pte_flags)
+{
+	if (dst && mem && mem->mem_type == TTM_PL_VRAM)
+		*dst += mem->adev->vm_manager.vram_base_offset;
+
+	adev->gmc.gmc_funcs->get_vm_pte(adev, vm, mem, vm_flags, pte_flags);
+}
+
 /**
  * amdgpu_gmc_fault_key - get hask key from vm fault address and pasid
  *
drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.h +20 -4
index 8f0672ed5b67f..37ae9730c802b 100644
@@ -150,6 +150,20 @@ struct amdgpu_vmhub {
 	const struct amdgpu_vmhub_funcs *vmhub_funcs;
 };
 
+/**
+ * struct amdgpu_gmc_pte_mem - Backing memory of a GPU mapping
+ * @adev: Device owning the memory.
+ * @flags: AMDGPU_GEM_CREATE_* coherence and caching flags.
+ * @mem_type: TTM placement of the memory.
+ * @mem_id: Memory partition of the memory, or -1.
+ */
+struct amdgpu_gmc_pte_mem {
+	struct amdgpu_device *adev;
+	u64 flags;
+	u32 mem_type;
+	s8 mem_id;
+};
+
 /*
  * GPU MC structures, functions & helpers
  */
@@ -175,7 +189,7 @@ struct amdgpu_gmc_funcs {
 	/* get the pte flags to use for PTEs */
 	void (*get_vm_pte)(struct amdgpu_device *adev,
 			   struct amdgpu_vm *vm,
-			   struct amdgpu_bo *bo,
+			   const struct amdgpu_gmc_pte_mem *mem,
 			   uint32_t vm_flags,
 			   uint64_t *pte_flags);
 	/* override per-page pte flags */
@@ -375,9 +389,11 @@ struct amdgpu_gmc {
 #define amdgpu_gmc_emit_flush_gpu_tlb(r, vmid, addr) (r)->adev->gmc.gmc_funcs->emit_flush_gpu_tlb((r), (vmid), (addr))
 #define amdgpu_gmc_emit_pasid_mapping(r, vmid, pasid) (r)->adev->gmc.gmc_funcs->emit_pasid_mapping((r), (vmid), (pasid))
 #define amdgpu_gmc_get_vm_pde(adev, level, dst, flags) (adev)->gmc.gmc_funcs->get_vm_pde((adev), (level), (dst), (flags))
-#define amdgpu_gmc_get_vm_pte(adev, vm, bo, vm_flags, pte_flags) \
-	((adev)->gmc.gmc_funcs->get_vm_pte((adev), (vm), (bo), (vm_flags), \
-					   (pte_flags)))
+void amdgpu_gmc_pte_mem_from_bo(struct amdgpu_bo *bo,
+				struct amdgpu_gmc_pte_mem *mem);
+void amdgpu_gmc_get_vm_pte(struct amdgpu_device *adev, struct amdgpu_vm *vm,
+			   const struct amdgpu_gmc_pte_mem *mem, u32 vm_flags,
+			   u64 *dst, u64 *pte_flags);
 #define amdgpu_gmc_override_vm_pte_flags(adev, vm, addr, pte_flags)	\
 	(adev)->gmc.gmc_funcs->override_vm_pte_flags			\
 		((adev), (vm), (addr), (pte_flags))
drivers/gpu/drm/amd/amdgpu/amdgpu_ualink.c +8 -4
index dd0653e6194b7..45654d9561abf 100644
@@ -2032,13 +2032,15 @@ static u64 amdgpu_ualink_get_export_pte_flags(struct amdgpu_device *adev,
 				       u64 mapping_flags)
 {
 	u64 pte_flags = adev->gmc.init_pte_flags;
+	struct amdgpu_gmc_pte_mem mem;
 
 	pte_flags |= (AMDGPU_PTE_VALID | AMDGPU_PTE_READABLE |
 		      AMDGPU_PTE_WRITEABLE);
 	mapping_flags |= AMDGPU_VM_MTYPE_DEFAULT;
 
-	amdgpu_gmc_get_vm_pte(adev, &adev->ualink.npa_vm, bo, mapping_flags,
-			      &pte_flags);
+	amdgpu_gmc_pte_mem_from_bo(bo, &mem);
+	amdgpu_gmc_get_vm_pte(adev, &adev->ualink.npa_vm, &mem, mapping_flags,
+			      NULL, &pte_flags);
 
 	return pte_flags;
 }
@@ -4951,6 +4953,7 @@ static int amdgpu_ualink_metadata_npa_mapping(struct amdgpu_device *adev)
 	struct amdgpu_ualink_remote *remote = to_remote(adev);
 	u32 dst_accel_id = ualink_accel_id(adev);
 	u64 timeout = msecs_to_jiffies(2000);
+	struct amdgpu_gmc_pte_mem mem;
 	struct amdgpu_bo *bos[2];
 	u32 n_bos;
 	struct dma_fence *fence;
@@ -4977,8 +4980,9 @@ static int amdgpu_ualink_metadata_npa_mapping(struct amdgpu_device *adev)
 					    remote->ring_bo->tbo.resource);
 	dev_dbg(adev->dev, "init pte_flags 0x%llx\n", pte_flags);
 
-	amdgpu_gmc_get_vm_pte(adev, &adev->ualink.npa_vm, remote->ring_bo,
-			      AMDGPU_VM_MTYPE_DEFAULT, &pte_flags);
+	amdgpu_gmc_pte_mem_from_bo(remote->ring_bo, &mem);
+	amdgpu_gmc_get_vm_pte(adev, &adev->ualink.npa_vm, &mem,
+			      AMDGPU_VM_MTYPE_DEFAULT, NULL, &pte_flags);
 	dev_dbg(adev->dev, "after get coherent pte_flags 0x%llx\n", pte_flags);
 
 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS) {
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +4 -2
index 792b87ee2fc3c..9fcafed0b598c 100644
@@ -1400,6 +1400,7 @@ int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va,
 	struct amdgpu_bo *bo = bo_va->base.bo;
 	struct amdgpu_vm *vm = bo_va->base.vm;
 	struct amdgpu_bo_va_mapping *mapping;
+	struct amdgpu_gmc_pte_mem pte_mem;
 	struct dma_fence **last_update;
 	dma_addr_t *pages_addr = NULL;
 	struct ttm_resource *mem;
@@ -1466,6 +1467,7 @@ int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va,
 		bo_adev = amdgpu_ttm_adev(bo->tbo.bdev);
 		vram_base = bo_adev->vm_manager.vram_base_offset;
 		uncached = (bo->flags & AMDGPU_GEM_CREATE_UNCACHED) != 0;
+		amdgpu_gmc_pte_mem_from_bo(bo, &pte_mem);
 	} else {
 		flags = 0x0;
 		vram_base = 0;
@@ -1497,8 +1499,8 @@ int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va,
 			update_flags &= ~AMDGPU_PTE_WRITEABLE;
 
 		/* Apply ASIC specific mapping flags */
-		amdgpu_gmc_get_vm_pte(adev, vm, bo, mapping->flags,
-				      &update_flags);
+		amdgpu_gmc_get_vm_pte(adev, vm, bo ? &pte_mem : NULL,
+				      mapping->flags, NULL, &update_flags);
 
 		trace_amdgpu_vm_bo_update(mapping);
 
drivers/gpu/drm/amd/amdgpu/gmc_v10_0.c +4 -4
index 49f593fe2a876..62ce278bc9ea6 100644
@@ -477,7 +477,7 @@ static void gmc_v10_0_get_vm_pde(struct amdgpu_device *adev, int level,
 
 static void gmc_v10_0_get_vm_pte(struct amdgpu_device *adev,
 				 struct amdgpu_vm *vm,
-				 struct amdgpu_bo *bo,
+				 const struct amdgpu_gmc_pte_mem *mem,
 				 uint32_t vm_flags,
 				 uint64_t *flags)
 {
@@ -516,9 +516,9 @@ static void gmc_v10_0_get_vm_pte(struct amdgpu_device *adev,
 		*flags &= ~AMDGPU_PTE_VALID;
 	}
 
-	if (bo && bo->flags & (AMDGPU_GEM_CREATE_COHERENT |
-			       AMDGPU_GEM_CREATE_EXT_COHERENT |
-			       AMDGPU_GEM_CREATE_UNCACHED))
+	if (mem && mem->flags & (AMDGPU_GEM_CREATE_COHERENT |
+				 AMDGPU_GEM_CREATE_EXT_COHERENT |
+				 AMDGPU_GEM_CREATE_UNCACHED))
 		*flags = AMDGPU_PTE_MTYPE_NV10(*flags, MTYPE_UC);
 }
 
drivers/gpu/drm/amd/amdgpu/gmc_v11_0.c +4 -4
index bc3b1ffb54886..36fa9927023a7 100644
@@ -483,7 +483,7 @@ static void gmc_v11_0_get_vm_pde(struct amdgpu_device *adev, int level,
 
 static void gmc_v11_0_get_vm_pte(struct amdgpu_device *adev,
 				 struct amdgpu_vm *vm,
-				 struct amdgpu_bo *bo,
+				 const struct amdgpu_gmc_pte_mem *mem,
 				 uint32_t vm_flags,
 				 uint64_t *flags)
 {
@@ -522,9 +522,9 @@ static void gmc_v11_0_get_vm_pte(struct amdgpu_device *adev,
 		*flags &= ~AMDGPU_PTE_VALID;
 	}
 
-	if (bo && bo->flags & (AMDGPU_GEM_CREATE_COHERENT |
-			       AMDGPU_GEM_CREATE_EXT_COHERENT |
-			       AMDGPU_GEM_CREATE_UNCACHED))
+	if (mem && mem->flags & (AMDGPU_GEM_CREATE_COHERENT |
+				 AMDGPU_GEM_CREATE_EXT_COHERENT |
+				 AMDGPU_GEM_CREATE_UNCACHED))
 		*flags = AMDGPU_PTE_MTYPE_NV10(*flags, MTYPE_UC);
 }
 
drivers/gpu/drm/amd/amdgpu/gmc_v12_0.c +3 -3
index 3bb13cfed92fe..180543b0bbbb4 100644
@@ -510,7 +510,7 @@ static void gmc_v12_0_get_vm_pde(struct amdgpu_device *adev, int level,
 
 static void gmc_v12_0_get_vm_pte(struct amdgpu_device *adev,
 				 struct amdgpu_vm *vm,
-				 struct amdgpu_bo *bo,
+				 const struct amdgpu_gmc_pte_mem *mem,
 				 uint32_t vm_flags,
 				 uint64_t *flags)
 {
@@ -545,10 +545,10 @@ static void gmc_v12_0_get_vm_pte(struct amdgpu_device *adev,
 		*flags &= ~AMDGPU_PTE_VALID;
 	}
 
-	if (bo && bo->flags & AMDGPU_GEM_CREATE_GFX12_DCC)
+	if (mem && mem->flags & AMDGPU_GEM_CREATE_GFX12_DCC)
 		*flags |= AMDGPU_PTE_DCC;
 
-	if (bo && bo->flags & AMDGPU_GEM_CREATE_UNCACHED)
+	if (mem && mem->flags & AMDGPU_GEM_CREATE_UNCACHED)
 		*flags = AMDGPU_PTE_MTYPE_GFX12(*flags, MTYPE_UC);
 }
 
drivers/gpu/drm/amd/amdgpu/gmc_v12_1.c +13 -18
index b676830120026..ef839d6e5cb45 100644
@@ -672,17 +672,15 @@ u32 gmc_v12_1_get_coherent_aql_mtype(struct amdgpu_device *adev)
 }
 
 static void gmc_v12_1_get_coherence_flags(struct amdgpu_device *adev,
-					  struct amdgpu_bo *bo,
+					  const struct amdgpu_gmc_pte_mem *mem,
 					  uint64_t *flags)
 {
-	struct amdgpu_device *bo_adev = amdgpu_ttm_adev(bo->tbo.bdev);
-	bool is_vram = bo->tbo.resource &&
-		       bo->tbo.resource->mem_type == TTM_PL_VRAM;
-	bool coherent = bo->flags & (AMDGPU_GEM_CREATE_COHERENT |
-				     AMDGPU_GEM_CREATE_EXT_COHERENT);
-	bool ext_coherent = bo->flags & AMDGPU_GEM_CREATE_EXT_COHERENT;
+	bool is_vram = mem->mem_type == TTM_PL_VRAM;
+	bool coherent = mem->flags & (AMDGPU_GEM_CREATE_COHERENT |
+				      AMDGPU_GEM_CREATE_EXT_COHERENT);
+	bool ext_coherent = mem->flags & AMDGPU_GEM_CREATE_EXT_COHERENT;
 	uint32_t gc_ip_version = amdgpu_ip_version(adev, GC_HWIP, 0);
-	bool uncached = bo->flags & AMDGPU_GEM_CREATE_UNCACHED;
+	bool uncached = mem->flags & AMDGPU_GEM_CREATE_UNCACHED;
 	unsigned int mtype, mtype_local, mtype_remote;
 	bool snoop = false;
 	bool is_local = false;
@@ -692,7 +690,7 @@ static void gmc_v12_1_get_coherence_flags(struct amdgpu_device *adev,
 	case IP_VERSION(12, 1, 0):
 		gmc_v12_1_get_mtypes(adev, &mtype_local, &mtype_remote);
 
-		is_local = (is_vram && adev == bo_adev);
+		is_local = (is_vram && adev == mem->adev);
 		snoop = true;
 		if (uncached) {
 			mtype = MTYPE_UC;
@@ -730,12 +728,10 @@ static void gmc_v12_1_get_coherence_flags(struct amdgpu_device *adev,
 
 static void gmc_v12_1_get_vm_pte(struct amdgpu_device *adev,
 				 struct amdgpu_vm *vm,
-				 struct amdgpu_bo *bo,
+				 const struct amdgpu_gmc_pte_mem *mem,
 				 uint32_t vm_flags,
 				 uint64_t *flags)
 {
-	struct ttm_resource *mem;
-
 	if (vm_flags & AMDGPU_VM_PAGE_EXECUTABLE)
 		*flags |= AMDGPU_PTE_EXECUTABLE;
 	else
@@ -757,15 +753,14 @@ static void gmc_v12_1_get_vm_pte(struct amdgpu_device *adev,
 		break;
 	}
 
-	if (bo) {
-		mem = bo->tbo.resource;
-		if (mem && mem->mem_type == AMDGPU_PL_NPA) {
+	if (mem) {
+		if (mem->mem_type == AMDGPU_PL_NPA) {
 			dev_dbg(adev->dev,
-				"Setting PTE for NPA BO, mem->type: %d, mem->start: %lx, mem->size: %u, cur_flags: %llx\n",
-				mem->mem_type, mem->start, (u32)mem->size, *flags);
+				"Setting PTE for NPA BO, cur_flags: %llx\n",
+				*flags);
 			gmc_v12_1_get_npa_flags(adev, flags);
 		} else if (*flags & AMDGPU_PTE_VALID) {
-			gmc_v12_1_get_coherence_flags(adev, bo, flags);
+			gmc_v12_1_get_coherence_flags(adev, mem, flags);
 		}
 	}
 }
drivers/gpu/drm/amd/amdgpu/gmc_v6_0.c +1 -1
index a7c353d1ac09d..e0b5c668a4430 100644
@@ -338,7 +338,7 @@ static void gmc_v6_0_get_vm_pde(struct amdgpu_device *adev, int level,
 
 static void gmc_v6_0_get_vm_pte(struct amdgpu_device *adev,
 				struct amdgpu_vm *vm,
-				struct amdgpu_bo *bo,
+				const struct amdgpu_gmc_pte_mem *mem,
 				uint32_t vm_flags,
 				uint64_t *flags)
 {
drivers/gpu/drm/amd/amdgpu/gmc_v7_0.c +1 -1
index c09f5153679ea..e946a6ee69628 100644
@@ -461,7 +461,7 @@ static void gmc_v7_0_get_vm_pde(struct amdgpu_device *adev, int level,
 
 static void gmc_v7_0_get_vm_pte(struct amdgpu_device *adev,
 				struct amdgpu_vm *vm,
-				struct amdgpu_bo *bo,
+				const struct amdgpu_gmc_pte_mem *mem,
 				uint32_t vm_flags,
 				uint64_t *flags)
 {
drivers/gpu/drm/amd/amdgpu/gmc_v8_0.c +1 -1
index 15592027e7c0c..b6d01aeda2b01 100644
@@ -673,7 +673,7 @@ static void gmc_v8_0_get_vm_pde(struct amdgpu_device *adev, int level,
 
 static void gmc_v8_0_get_vm_pte(struct amdgpu_device *adev,
 				struct amdgpu_vm *vm,
-				struct amdgpu_bo *bo,
+				const struct amdgpu_gmc_pte_mem *mem,
 				uint32_t vm_flags,
 				uint64_t *flags)
 {
drivers/gpu/drm/amd/amdgpu/gmc_v9_0.c +11 -14
index a705830ef436c..32ad64313cde7 100644
@@ -1046,24 +1046,21 @@ static void gmc_v9_0_get_vm_pde(struct amdgpu_device *adev, int level,
 
 static void gmc_v9_0_get_coherence_flags(struct amdgpu_device *adev,
 					 struct amdgpu_vm *vm,
-					 struct amdgpu_bo *bo,
+					 const struct amdgpu_gmc_pte_mem *mem,
 					 uint32_t vm_flags,
 					 uint64_t *flags)
 {
-	struct amdgpu_device *bo_adev = amdgpu_ttm_adev(bo->tbo.bdev);
-	bool is_vram = bo->tbo.resource &&
-		bo->tbo.resource->mem_type == TTM_PL_VRAM;
-	bool coherent = bo->flags & (AMDGPU_GEM_CREATE_COHERENT |
-				     AMDGPU_GEM_CREATE_EXT_COHERENT);
-	bool ext_coherent = bo->flags & AMDGPU_GEM_CREATE_EXT_COHERENT;
-	bool uncached = bo->flags & AMDGPU_GEM_CREATE_UNCACHED;
+	struct amdgpu_device *bo_adev = mem->adev;
+	bool is_vram = mem->mem_type == TTM_PL_VRAM;
+	bool coherent = mem->flags & (AMDGPU_GEM_CREATE_COHERENT |
+				      AMDGPU_GEM_CREATE_EXT_COHERENT);
+	bool ext_coherent = mem->flags & AMDGPU_GEM_CREATE_EXT_COHERENT;
+	bool uncached = mem->flags & AMDGPU_GEM_CREATE_UNCACHED;
 	unsigned int mtype_local, mtype;
 	uint32_t gc_ip_version = amdgpu_ip_version(adev, GC_HWIP, 0);
 	bool snoop = false;
 	bool is_local;
 
-	dma_resv_assert_held(bo->tbo.base.resv);
-
 	switch (gc_ip_version) {
 	case IP_VERSION(9, 4, 1):
 	case IP_VERSION(9, 4, 2):
@@ -1122,7 +1119,7 @@ static void gmc_v9_0_get_coherence_flags(struct amdgpu_device *adev,
 		is_local = (!is_vram && (adev->flags & AMD_IS_APU) &&
 			    num_possible_nodes() <= 1) ||
 			   (is_vram && adev == bo_adev &&
-			    KFD_XCP_MEM_ID(adev, bo->xcp_id) == vm->mem_id);
+			    mem->mem_id == vm->mem_id);
 		snoop = true;
 		if (uncached) {
 			mtype = MTYPE_UC;
@@ -1162,7 +1159,7 @@ static void gmc_v9_0_get_coherence_flags(struct amdgpu_device *adev,
 
 static void gmc_v9_0_get_vm_pte(struct amdgpu_device *adev,
 				struct amdgpu_vm *vm,
-				struct amdgpu_bo *bo,
+				const struct amdgpu_gmc_pte_mem *mem,
 				uint32_t vm_flags,
 				uint64_t *flags)
 {
@@ -1196,8 +1193,8 @@ static void gmc_v9_0_get_vm_pte(struct amdgpu_device *adev,
 		*flags &= ~AMDGPU_PTE_VALID;
 	}
 
-	if ((*flags & AMDGPU_PTE_VALID) && bo)
-		gmc_v9_0_get_coherence_flags(adev, vm, bo, vm_flags, flags);
+	if ((*flags & AMDGPU_PTE_VALID) && mem)
+		gmc_v9_0_get_coherence_flags(adev, vm, mem, vm_flags, flags);
 }
 
 static void gmc_v9_0_override_vm_pte_flags(struct amdgpu_device *adev,
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +2 -1
index b2d49876a7800..0d419268d8adf 100644
@@ -1409,7 +1409,8 @@ svm_range_get_pte_flags(struct kfd_node *node, struct amdgpu_vm *vm,
 	if (gc_ip_version >= IP_VERSION(12, 0, 0))
 		pte_flags |= AMDGPU_PTE_IS_PTE;
 
-	amdgpu_gmc_get_vm_pte(node->adev, vm, NULL, mapping_flags, &pte_flags);
+	amdgpu_gmc_get_vm_pte(node->adev, vm, NULL, mapping_flags,
+			      NULL, &pte_flags);
 	pte_flags |= AMDGPU_PTE_READABLE;
 	if (!(flags & KFD_IOCTL_SVM_FLAG_GPU_RO))
 		pte_flags |= AMDGPU_PTE_WRITEABLE;
Signature · 1 line
2.53.0
author
#2 lore raw

PATCH v11 2/22 drm/amdgpu: add SVM ioctl UAPI definitions

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Define the following ioctl structures and enums:
- DRM_AMDGPU_GEM_SVM ioctl command and DRM_IOCTL_AMDGPU_GEM_SVM macro
- enum amdgpu_ioctl_svm_op: SET_ATTR, GET_ATTR, RESET_ATTR operations
- enum amdgpu_ioctl_svm_access: INACCESSIBLE, IN_PLACE, ALLOW_MIGRATE
- enum amdgpu_ioctl_svm_location: SYSMEM, UNDEFINED, LOCAL, HIVE
- enum amdgpu_ioctl_svm_attr_type: PREFERRED_LOC, PREFETCH_LOC, ACCESS, GRANULARITY, HOST_ACCESS, COHERENT, EXT_COHERENT, GPU_RO, GPU_EXEC, GPU_READ_MOSTLY
- struct drm_amdgpu_svm_attribute: type and value pair
- struct drm_amdgpu_gem_svm: ioctl payload with start_addr, size, operation, nattr, and attrs_ptr

---
 include/uapi/drm/amdgpu_drm.h | 127 ++++++++++++++++++++++++++++++++++
 1 file changed, 127 insertions(+)
include/uapi/drm/amdgpu_drm.h +127 -0
index 29009f6aabde9..a3adcb49469b6 100644
@@ -60,6 +60,7 @@ extern "C" {
 #define DRM_AMDGPU_GEM_LIST_HANDLES	0x19
 #define DRM_AMDGPU_PROC_OPTIONS		0x1A
 #define DRM_AMDGPU_UALINK_HANDLE	0x1B
+#define DRM_AMDGPU_GEM_SVM		0x1C
 
 #define DRM_IOCTL_AMDGPU_GEM_CREATE	DRM_IOWR(DRM_COMMAND_BASE + DRM_AMDGPU_GEM_CREATE, union drm_amdgpu_gem_create)
 #define DRM_IOCTL_AMDGPU_GEM_MMAP	DRM_IOWR(DRM_COMMAND_BASE + DRM_AMDGPU_GEM_MMAP, union drm_amdgpu_gem_mmap)
@@ -83,6 +84,9 @@ extern "C" {
 #define DRM_IOCTL_AMDGPU_GEM_LIST_HANDLES DRM_IOWR(DRM_COMMAND_BASE + DRM_AMDGPU_GEM_LIST_HANDLES, struct drm_amdgpu_gem_list_handles)
 #define DRM_IOCTL_AMDGPU_PROC_OPTIONS	DRM_IOWR(DRM_COMMAND_BASE + DRM_AMDGPU_PROC_OPTIONS, struct drm_amdgpu_proc_options)
 #define DRM_IOCTL_AMDGPU_UALINK_HANDLE DRM_IOWR(DRM_COMMAND_BASE + DRM_AMDGPU_UALINK_HANDLE, union drm_amdgpu_ualink_handle)
+#define DRM_IOCTL_AMDGPU_GEM_SVM	\
+	DRM_IOWR(DRM_COMMAND_BASE + DRM_AMDGPU_GEM_SVM, \
+		  struct drm_amdgpu_gem_svm)
 
 /**
  * DOC: memory domains
@@ -1737,6 +1741,129 @@ union drm_amdgpu_ualink_handle {
 	union drm_amdgpu_ualink_handle_out out;
 };
 
+/**
+ * enum amdgpu_ioctl_svm_op - operation selector for DRM_IOCTL_AMDGPU_GEM_SVM.
+ * @AMDGPU_SVM_OP_SET_ATTR: apply the attributes in @attrs_ptr to the VA range
+ *                          [@start_addr, @start_addr + @size).
+ * @AMDGPU_SVM_OP_GET_ATTR: query the attributes at @start_addr. The caller
+ *                          lists the attribute types it is interested in via
+ *                          @attrs_ptr; the kernel fills in their current
+ *                          values and updates @size to the length of the
+ *                          contiguous range starting at @start_addr over
+ *                          which those values are constant. Input @size is an
+ *                          upper bound. This lets user space (e.g. CRIU) walk
+ *                          the address space and read back all attributes
+ *                          without knowing the range boundaries in advance.
+ * @AMDGPU_SVM_OP_RESET_ATTR: reset all attributes for the VA range to their
+ *                            default values. @attrs_ptr and @nattr are ignored.
+ */
+enum amdgpu_ioctl_svm_op {
+	AMDGPU_SVM_OP_SET_ATTR = 0,
+	AMDGPU_SVM_OP_GET_ATTR = 1,
+	AMDGPU_SVM_OP_RESET_ATTR = 2,
+};
+
+/**
+ * enum amdgpu_ioctl_svm_access - values for AMDGPU_SVM_ATTR_ACCESS.
+ * @AMDGPU_SVM_ACCESS_INACCESSIBLE: GPU must not access the range; any access
+ *                                  is a fault.
+ * @AMDGPU_SVM_ACCESS_IN_PLACE:     GPU may access the range only at its
+ *                                  current backing store; the driver will
+ *                                  never migrate pages to local VRAM.
+ * @AMDGPU_SVM_ACCESS_ALLOW_MIGRATE: GPU may access the range and the driver
+ *                                  is allowed (but not required) to migrate
+ *                                  pages between system memory and local
+ *                                  VRAM to satisfy the preferred/prefetch
+ *                                  location.
+ */
+enum amdgpu_ioctl_svm_access {
+	AMDGPU_SVM_ACCESS_INACCESSIBLE		= 0,
+	AMDGPU_SVM_ACCESS_IN_PLACE			= 1,
+	AMDGPU_SVM_ACCESS_ALLOW_MIGRATE		= 2,
+};
+
+/**
+ * enum amdgpu_ioctl_svm_location - values for AMDGPU_SVM_ATTR_PREFERRED_LOC /
+ *                            AMDGPU_SVM_ATTR_PREFETCH_LOC.
+ * @AMDGPU_SVM_LOCATION_SYSMEM:    back the range with system memory.
+ * @AMDGPU_SVM_LOCATION_UNDEFINED: no preference; the driver chooses.
+ * @AMDGPU_SVM_LOCATION_LOCAL:     back the range with the local VRAM of the
+ *                                 device the SVM context belongs to.
+ * @AMDGPU_SVM_LOCATION_HIVE:      back the range with the VRAM of any device
+ *                                 in the same XGMI hive as the local device.
+ *
+ * The location is expressed as a fixed enum rather than a device file
+ * descriptor on purpose: a descriptor has no stable meaning across a
+ * checkpoint/restore (CRIU) cycle.
+ */
+enum amdgpu_ioctl_svm_location {
+	AMDGPU_SVM_LOCATION_SYSMEM	= 0,
+	AMDGPU_SVM_LOCATION_UNDEFINED	= 1,
+	AMDGPU_SVM_LOCATION_LOCAL	= 2,
+	AMDGPU_SVM_LOCATION_HIVE	= 3,
+};
+
+/**
+ * enum amdgpu_ioctl_svm_attr_type - attribute selector for
+ *                                   &drm_amdgpu_svm_attribute.type.
+ *
+ * @AMDGPU_SVM_ATTR_PREFERRED_LOC: Preferred backing location for the range.
+ *	Value is one of &enum amdgpu_ioctl_svm_location.
+ * @AMDGPU_SVM_ATTR_PREFETCH_LOC: Prefetch target for the range. Value is
+ *	one of &enum amdgpu_ioctl_svm_location.
+ * @AMDGPU_SVM_ATTR_ACCESS: GPU access policy for the range. Value is one
+ *	of &enum amdgpu_ioctl_svm_access.
+ * @AMDGPU_SVM_ATTR_GRANULARITY: log2 of the migration granularity in pages.
+ * @AMDGPU_SVM_ATTR_HOST_ACCESS: Guarantee host access to memory.
+ * @AMDGPU_SVM_ATTR_COHERENT: Fine-grained coherency between all devices
+ *	with access.
+ * @AMDGPU_SVM_ATTR_EXT_COHERENT: Fine-grained coherency between all devices
+ *	using device-scope atomics.
+ * @AMDGPU_SVM_ATTR_GPU_RO: GPUs only read the range, allowing replication.
+ * @AMDGPU_SVM_ATTR_GPU_EXEC: Allow execution on GPU.
+ * @AMDGPU_SVM_ATTR_GPU_READ_MOSTLY: GPUs mostly read the range; may allow
+ *	optimizations similar to GPU_RO, but writes still fault.
+ */
+enum amdgpu_ioctl_svm_attr_type {
+	AMDGPU_SVM_ATTR_PREFERRED_LOC		= 0,
+	AMDGPU_SVM_ATTR_PREFETCH_LOC		= 1,
+	AMDGPU_SVM_ATTR_ACCESS				= 2,
+	AMDGPU_SVM_ATTR_GRANULARITY			= 3,
+	/* Boolean attributes below: value must be 0 or 1. */
+	AMDGPU_SVM_ATTR_HOST_ACCESS			= 4,
+	AMDGPU_SVM_ATTR_COHERENT			= 5,
+	AMDGPU_SVM_ATTR_EXT_COHERENT		= 6,
+	AMDGPU_SVM_ATTR_GPU_RO				= 7,
+	AMDGPU_SVM_ATTR_GPU_EXEC			= 8,
+	AMDGPU_SVM_ATTR_GPU_READ_MOSTLY		= 9,
+};
+
+/* One (type, value) pair carried by DRM_IOCTL_AMDGPU_GEM_SVM. */
+struct drm_amdgpu_svm_attribute {
+	/** AMDGPU_SVM_ATTR_* */
+	__u32 type;
+	/** Attribute value; interpretation depends on @type */
+	__u32 value;
+};
+
+/* Argument for DRM_IOCTL_AMDGPU_GEM_SVM. */
+struct drm_amdgpu_gem_svm {
+	/** Start of the virtual address range */
+	__u64 start_addr;
+	/**
+	 * Size of the range in bytes. For AMDGPU_SVM_OP_GET_ATTR this is an
+	 * input upper bound and is updated on return to the length of the
+	 * contiguous range starting at @start_addr with constant attributes.
+	 */
+	__u64 size;
+	/** AMDGPU_SVM_OP_* */
+	__u32 operation;
+	/** Number of struct drm_amdgpu_svm_attribute entries in @attrs_ptr */
+	__u32 nattr;
+	/** User pointer to an array of @nattr struct drm_amdgpu_svm_attribute */
+	__u64 attrs_ptr;
+};
+
 #if defined(__cplusplus)
 }
 #endif
Signature · 1 line
2.53.0
author
#3 lore raw

PATCH v11 3/22 drm/amdgpu: add SVM core header and VM integration

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Add amdgpu_svm.h with SVM data structures and public API:
- enum amdgpu_svm_xnack_mode: OFF, ON and DEFAULT mode
- struct amdgpu_svm: core context with drm_gpusvm, kref lifecycle, attribute tree, rw_semaphore, GC workqueue, xnack state.
- struct amdgpu_svm_gc: garbage collector with workqueue and work_struct
- Kmem cache helpers: AMDGPU_SVM_KMEM_CACHE_CREATE/DESTROY
- Locking helpers: amdgpu_svm_lock/unlock/assert_locked
- Public API declarations (including clean_queue, sync_work)

Expose TLB flush errors so invalidation can stop before releasing DMA mappings when the compute flush fails.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h | 175 ++++++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h  |   4 +
 2 files changed, 179 insertions(+)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h
drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h new file +175 -0
new file mode 100644
index 0000000000000..c21690c2d2117
@@ -0,0 +1,175 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/*
+ * Copyright 2026 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#ifndef __AMDGPU_SVM_H__
+#define __AMDGPU_SVM_H__
+
+#include <drm/amdgpu_drm.h>
+#include <drm/drm_gpusvm.h>
+#include <linux/atomic.h>
+#include <linux/kref.h>
+#include <linux/list.h>
+#include <linux/printk.h>
+#include <linux/rwsem.h>
+#include <linux/slab.h>
+#include <linux/spinlock.h>
+#include <linux/types.h>
+#include <linux/workqueue.h>
+
+struct amdgpu_device;
+struct amdgpu_vm;
+struct amdgpu_svm_attr_tree;
+struct amdgpu_svm_attrs;
+struct drm_device;
+struct drm_file;
+
+enum amdgpu_svm_xnack_mode {
+	AMDGPU_SVM_XNACK_OFF,
+	AMDGPU_SVM_XNACK_ON,
+	AMDGPU_SVM_XNACK_DEFAULT,
+};
+
+#define amdgpu_svm_assert_in_notifier(svm__) \
+	lockdep_assert_held_write(&(svm__)->gpusvm.notifier_lock)
+
+/**
+ * struct amdgpu_svm_gc - SVM range garbage collector used for unmapping
+ * SVM ranges in response to mmu_notifier events.
+ * @wq: Workqueue where @work runs on.
+ * @list: Ranges list in garbage collector. Protected by amdgpu_svm.work_lock.
+ * @work: Drains @list under amdgpu_svm.svm_lock.
+ */
+struct amdgpu_svm_gc {
+	struct workqueue_struct *wq;
+	struct list_head list;
+	struct work_struct work;
+};
+
+/**
+ * struct amdgpu_svm - shared virtual memory context
+ * @gpusvm: Embedded drm_gpusvm base, manages the range/notifier trees.
+ * @refcount: Reference count guarding the lifetime of this instance.
+ * @adev: The amdgpu device this SVM context belongs to.
+ * @vm: Back pointer to the owning amdgpu_vm.
+ * @attr_tree: Interval tree of SVM attributes.
+ * @svm_lock: The driver_svm_lock described in the GPU SVM locking section.
+ *            registered by drm_gpusvm_driver_set_lock().
+ * @work_lock: Protects the deferred work queues such as @gc.list.
+ * @gc: garbage collector for ranges queued for destruction.
+ * @exiting: Set once when the context starts tearing down.
+ * @default_granularity: Default range granularity.
+ * @xnack_enabled: Whether retry (XNACK) faults are enabled.
+ */
+struct amdgpu_svm {
+	struct drm_gpusvm gpusvm;
+	struct kref refcount;
+	struct amdgpu_device *adev;
+	struct amdgpu_vm *vm;
+	struct amdgpu_svm_attr_tree *attr_tree;
+	struct rw_semaphore svm_lock;
+	spinlock_t work_lock; /* Protects GC queue state and pending work. */
+	struct amdgpu_svm_gc gc;
+	atomic_t exiting;
+	u8 default_granularity;
+	bool xnack_enabled;
+};
+
+static inline struct amdgpu_svm *to_amdgpu_svm(struct drm_gpusvm *gpusvm)
+{
+	return container_of(gpusvm, struct amdgpu_svm, gpusvm);
+}
+
+/*
+ * Helpers for amdgpu_svm.svm_lock, the driver_svm_lock registered with GPU SVM.
+ * Hold it in write mode around structural GPU SVM updates, including
+ * drm_gpusvm_range_find_or_insert() and drm_gpusvm_range_remove().
+ */
+static inline void amdgpu_svm_lock(struct amdgpu_svm *svm)
+{
+	down_write(&svm->svm_lock);
+}
+
+static inline void amdgpu_svm_unlock(struct amdgpu_svm *svm)
+{
+	up_write(&svm->svm_lock);
+}
+
+static inline void amdgpu_svm_assert_locked(struct amdgpu_svm *svm)
+{
+	lockdep_assert_held_write(&svm->svm_lock);
+}
+
+#if IS_ENABLED(CONFIG_DRM_AMDGPU_SVM)
+int amdgpu_svm_flush_tlb(struct amdgpu_svm *svm);
+
+int amdgpu_svm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm);
+void amdgpu_svm_close(struct amdgpu_vm *vm);
+void amdgpu_svm_fini(struct amdgpu_vm *vm);
+
+void amdgpu_svm_put(struct amdgpu_svm *svm);
+struct amdgpu_svm *amdgpu_svm_lookup_by_pasid(struct amdgpu_device *adev, u32 pasid);
+int amdgpu_svm_handle_fault(struct amdgpu_device *adev, u32 pasid, u64 fault_page,
+			    bool write_fault);
+bool amdgpu_svm_is_enabled(struct amdgpu_vm *vm);
+
+int amdgpu_gem_svm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp);
+void amdgpu_svm_clean_queue(struct amdgpu_svm *svm, struct list_head *work_list);
+void amdgpu_svm_sync_work(struct amdgpu_svm *svm);
+int amdgpu_svm_garbage_collector(struct amdgpu_svm *svm);
+int amdgpu_svm_apply_attr_change(struct amdgpu_svm *svm, const struct amdgpu_svm_attrs *old_attrs,
+				 const struct amdgpu_svm_attrs *new_attrs, unsigned long start_page,
+				 unsigned long last_page);
+bool amdgpu_svm_devmem_possible(struct amdgpu_svm *svm);
+#else
+static inline int amdgpu_svm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
+{
+	return 0;
+}
+
+static inline void amdgpu_svm_close(struct amdgpu_vm *vm)
+{
+}
+
+static inline void amdgpu_svm_fini(struct amdgpu_vm *vm)
+{
+}
+
+static inline int
+amdgpu_svm_handle_fault(struct amdgpu_device *adev, u32 pasid, u64 fault_page, bool write_fault)
+{
+	return -EOPNOTSUPP;
+}
+
+static inline bool amdgpu_svm_is_enabled(struct amdgpu_vm *vm)
+{
+	return false;
+}
+
+static inline int amdgpu_gem_svm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
+{
+	return -EOPNOTSUPP;
+}
+#endif /* CONFIG_DRM_AMDGPU_SVM */
+
+#endif /* __AMDGPU_SVM_H__ */
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h +4 -0
index ee07982b0a141..bf752c6959b5c 100644
@@ -43,6 +43,7 @@ struct amdgpu_bo_va;
 struct amdgpu_job;
 struct amdgpu_bo_list_entry;
 struct amdgpu_bo_vm;
+struct amdgpu_svm;
 
 /*
  * GPUVM handling
@@ -382,6 +383,9 @@ struct amdgpu_vm {
 
 	/* cached fault info */
 	struct amdgpu_vm_fault_info fault_info;
+
+	/* SVM experimental implementation */
+	struct amdgpu_svm *svm;
 };
 
 struct amdgpu_vm_manager {
Signature · 1 line
2.53.0
author
#4 lore raw

PATCH v11 4/22 drm/amdgpu: implement SVM attribute tree and helper functions

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Implement the per-SVM interval tree that stores attributes independently of CPU VMA lifetime. Provide default attributes, interval lookup and update helpers, and the attribute types shared with mapping and fault handling. Runtime VMA lookup validates the backing memory when needed.

Recognize explicit SYSMEM prefetch separately from a preferred location. Only ALLOW_MIGRATE permits active eviction to system memory; IN_PLACE retains its existing access policy.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c | 262 +++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.h | 172 ++++++++++++
 2 files changed, 434 insertions(+)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.h
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c new file +262 -0
new file mode 100644
index 0000000000000..5b083aad24c01
@@ -0,0 +1,262 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+/*
+ * Copyright 2026 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#include "amdgpu_svm.h"
+#include "amdgpu_svm_attr.h"
+
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/gfp.h>
+#include <linux/lockdep.h>
+#include <linux/minmax.h>
+#include <linux/mm.h>
+#include <linux/slab.h>
+
+struct attr_set_ctx {
+	struct amdgpu_svm_attrs old_attrs;
+	struct amdgpu_svm_attrs new_attrs;
+	unsigned long start_page;
+	unsigned long last_page;
+};
+
+struct attr_get_ctx {
+	s32 preferred_loc;
+	s32 prefetch_loc;
+	enum amdgpu_ioctl_svm_access access;
+	u32 granularity;
+	u32 flags_and;
+	bool has_range;
+};
+
+/**
+ * amdgpu_svm_attr_prefer_vram() - Check a stable attribute snapshot for VRAM
+ * @attrs: Attribute snapshot supplied by the caller.
+ *
+ * Return: True if either location requests device memory.
+ */
+bool amdgpu_svm_attr_prefer_vram(const struct amdgpu_svm_attrs *attrs)
+{
+	if (attrs->preferred_loc != AMDGPU_SVM_LOCATION_UNDEFINED &&
+	    attrs->preferred_loc != AMDGPU_SVM_LOCATION_SYSMEM)
+		return true;
+
+	if (attrs->prefetch_loc != AMDGPU_SVM_LOCATION_UNDEFINED &&
+	    attrs->prefetch_loc != AMDGPU_SVM_LOCATION_SYSMEM)
+		return true;
+
+	return false;
+}
+
+/**
+ * amdgpu_svm_check_vma() - Look up supported CPU backing for a fault
+ * @mm: Address space to inspect.
+ * @addr: Faulting byte address.
+ *
+ * Context: Caller holds mmap_lock; the returned VMA requires that lock.
+ * Return: The VMA, or an error pointer for missing or unsupported backing.
+ */
+struct vm_area_struct *amdgpu_svm_check_vma(struct mm_struct *mm, unsigned long addr)
+{
+	const unsigned long unsupported_vm_flags = VM_IO | VM_PFNMAP | VM_MIXEDMAP;
+	struct vm_area_struct *vma = vma_lookup(mm, addr);
+
+	if (!vma)
+		return ERR_PTR(-EFAULT);
+
+	if (vma->vm_flags & unsupported_vm_flags)
+		return ERR_PTR(-EOPNOTSUPP);
+
+	return vma;
+}
+
+static void attr_set_interval(struct amdgpu_svm_attr_range *range, unsigned long start_page,
+			      unsigned long last_page)
+{
+	range->it_node.start = start_page;
+	range->it_node.last = last_page;
+}
+
+/**
+ * amdgpu_svm_attr_set_default() - Fill the default attributes
+ * @svm: Initialized SVM context with immutable default policy.
+ * @attrs: Caller-owned output snapshot.
+ */
+void amdgpu_svm_attr_set_default(struct amdgpu_svm *svm, struct amdgpu_svm_attrs *attrs)
+{
+	attrs->preferred_loc = AMDGPU_SVM_LOCATION_UNDEFINED;
+	attrs->prefetch_loc = AMDGPU_SVM_LOCATION_UNDEFINED;
+	attrs->granularity = svm->default_granularity;
+	attrs->flags = AMDGPU_SVM_ATTR_BIT_HOST_ACCESS | AMDGPU_SVM_ATTR_BIT_COHERENT;
+	attrs->access = svm->xnack_enabled ? AMDGPU_SVM_ACCESS_ALLOW_MIGRATE :
+					     AMDGPU_SVM_ACCESS_INACCESSIBLE;
+}
+
+static struct amdgpu_svm_attr_range *
+amdgpu_svm_attr_find_locked(struct amdgpu_svm_attr_tree *attr_tree, unsigned long page)
+{
+	struct interval_tree_node *node;
+
+	lockdep_assert_held(&attr_tree->lock);
+
+	node = interval_tree_iter_first(&attr_tree->tree, page, page);
+	if (node)
+		return container_of(node, struct amdgpu_svm_attr_range, it_node);
+
+	return NULL;
+}
+
+/**
+ * amdgpu_svm_attr_get_bounds_locked() - Find attributes  or surrounding bounds
+ * @attr_tree: attribute tree to search.
+ * @page: page index to look up.
+ * @start_page: out, first page of the returned range or gap.
+ * @last_page: out, last page of the returned range or gap.
+ *
+ * If @page is covered by an attribute range, return that range and report its
+ * bounds. Otherwise return NULL and fill @start_page/@last_page with the bounds
+ * of the default attribute gap around @page, clamped by neighboring explicit
+ * ranges or [0, ULONG_MAX] when none.
+ *
+ * Context: Caller holds attr_tree->lock; the returned range requires that lock.
+ * Return: the covering range, or NULL if @page falls in a gap.
+ */
+struct amdgpu_svm_attr_range *
+amdgpu_svm_attr_get_bounds_locked(struct amdgpu_svm_attr_tree *attr_tree, unsigned long page,
+				  unsigned long *start_page, unsigned long *last_page)
+{
+	struct amdgpu_svm_attr_range *attr_range;
+	struct interval_tree_node *node;
+	struct rb_node *rb;
+
+	attr_range = amdgpu_svm_attr_find_locked(attr_tree, page);
+	if (attr_range) {
+		*start_page = amdgpu_svm_attr_start_page(attr_range);
+		*last_page = amdgpu_svm_attr_last_page(attr_range);
+		return attr_range;
+	}
+
+	*start_page = 0;
+	*last_page = ULONG_MAX;
+
+	if (page == ULONG_MAX)
+		return NULL;
+
+	node = interval_tree_iter_first(&attr_tree->tree, page + 1, ULONG_MAX);
+	if (node) {
+		if (node->start > page)
+			*last_page = node->start - 1;
+
+		rb = rb_prev(&node->rb);
+		if (rb) {
+			node = container_of(rb, struct interval_tree_node, rb);
+			if (node->last < page)
+				*start_page = node->last + 1;
+		}
+	} else {
+		rb = rb_last(&attr_tree->tree.rb_root);
+
+		if (rb) {
+			node = container_of(rb, struct interval_tree_node, rb);
+			if (node->last < page)
+				*start_page = node->last + 1;
+		}
+	}
+
+	return NULL;
+}
+
+static bool attr_equal(const struct amdgpu_svm_attrs *a, const struct amdgpu_svm_attrs *b)
+{
+	return a->flags == b->flags && a->preferred_loc == b->preferred_loc &&
+	       a->prefetch_loc == b->prefetch_loc && a->granularity == b->granularity &&
+	       a->access == b->access;
+}
+
+/**
+ * amdgpu_svm_attr_range_alloc() - Allocate an unlinked attribute range
+ * @start_page: First CPU page, inclusive.
+ * @last_page: Last CPU page, inclusive.
+ * @attrs: Stable attributes to copy into the allocation.
+ *
+ * The caller owns the range until insertion into the tree.
+ *
+ * Return: An allocated range, or NULL on allocation failure.
+ */
+struct amdgpu_svm_attr_range *
+amdgpu_svm_attr_range_alloc(unsigned long start_page, unsigned long last_page,
+			    const struct amdgpu_svm_attrs *attrs)
+{
+	struct amdgpu_svm_attr_range *range;
+
+	range = kzalloc_obj(*range, GFP_KERNEL);
+	if (!range)
+		return NULL;
+
+	INIT_LIST_HEAD(&range->list);
+	attr_set_interval(range, start_page, last_page);
+	range->attrs = *attrs;
+	return range;
+}
+
+/**
+ * amdgpu_svm_attr_range_insert_locked() - Transfer a range to the attribute tree
+ * @attr_tree: Destination tree.
+ * @range: Unlinked range that does not overlap existing entries.
+ *
+ * Context: Caller holds attr_tree->lock and serializes SVM attribute updates.
+ */
+void amdgpu_svm_attr_range_insert_locked(struct amdgpu_svm_attr_tree *attr_tree,
+					 struct amdgpu_svm_attr_range *range)
+{
+	struct interval_tree_node *node;
+	struct amdgpu_svm_attr_range *next;
+
+	lockdep_assert_held(&attr_tree->lock);
+
+	/*
+	 * Keep @range_list ordered by start page: insert before the first range
+	 * starting at or after @range, then add to the interval tree.
+	 */
+	node = interval_tree_iter_first(&attr_tree->tree, amdgpu_svm_attr_start_page(range),
+					ULONG_MAX);
+	if (node) {
+		next = container_of(node, struct amdgpu_svm_attr_range, it_node);
+		list_add_tail(&range->list, &next->list);
+	} else {
+		list_add_tail(&range->list, &attr_tree->range_list);
+	}
+
+	interval_tree_insert(&range->it_node, &attr_tree->tree);
+}
+
+static void attr_remove_range_locked(struct amdgpu_svm_attr_tree *attr_tree,
+				     struct amdgpu_svm_attr_range *range, bool free_range)
+{
+	lockdep_assert_held(&attr_tree->lock);
+
+	interval_tree_remove(&range->it_node, &attr_tree->tree);
+	list_del_init(&range->list);
+	if (free_range)
+		kfree(range);
+}
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.h new file +172 -0

172 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#5 lore raw

PATCH v11 5/22 drm/amdgpu: implement SVM attribute set/get/clear operations

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Complete the attribute subsystem with per-type validation, interval updates, default attributes and public SET, GET and RESET operations.

Split attribute ranges as needed when applying updates. GET reports the uniform prefix of the requested interval and its length. Keep interval removal private to the RESET implementation. Document the public helpers' arguments, locking requirements and return values.

Do not preflight attribute ioctls against transient CPU VMAs. Fault and mapping paths validate current backing pages, while the ioctl entry validates numeric address-space bounds.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c | 690 +++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.h |   8 +
 2 files changed, 698 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c +690 -0
index 5b083aad24c01..0db96a4700666 100644
@@ -260,3 +260,693 @@ static void attr_remove_range_locked(struct amdgpu_svm_attr_tree *attr_tree,
 	if (free_range)
 		kfree(range);
 }
+
+static void
+attr_change_ctx_set(struct attr_set_ctx *change, const struct amdgpu_svm_attrs *old_attrs,
+		    const struct amdgpu_svm_attrs *new_attrs, unsigned long start_page,
+		    unsigned long last_page)
+{
+	change->old_attrs = *old_attrs;
+	change->new_attrs = *new_attrs;
+	change->start_page = start_page;
+	change->last_page = last_page;
+}
+
+static inline int attr_check_preferred_loc(u32 value)
+{
+	/*
+	 * SYSMEM and UNDEFINED are always valid; LOCAL/HIVE select device
+	 * VRAM (see enum amdgpu_ioctl_svm_location).
+	 */
+	switch (value) {
+	case AMDGPU_SVM_LOCATION_SYSMEM:
+	case AMDGPU_SVM_LOCATION_UNDEFINED:
+	case AMDGPU_SVM_LOCATION_LOCAL:
+	case AMDGPU_SVM_LOCATION_HIVE:
+		return 0;
+	default:
+		return -EINVAL;
+	}
+}
+
+static inline int attr_check_prefetch_loc(u32 value)
+{
+	/*
+	 * Prefetch accepts the same values as the preferred location (see
+	 * enum amdgpu_ioctl_svm_location); UNDEFINED means no prefetch and is
+	 * what GET_ATTR reports for default or mixed ranges, so it must round
+	 * trip through SET for CRIU restore.
+	 */
+	switch (value) {
+	case AMDGPU_SVM_LOCATION_SYSMEM:
+	case AMDGPU_SVM_LOCATION_UNDEFINED:
+	case AMDGPU_SVM_LOCATION_LOCAL:
+	case AMDGPU_SVM_LOCATION_HIVE:
+		return 0;
+	default:
+		return -EINVAL;
+	}
+}
+
+static inline int attr_check_access(u32 value)
+{
+	switch (value) {
+	case AMDGPU_SVM_ACCESS_INACCESSIBLE:
+	case AMDGPU_SVM_ACCESS_IN_PLACE:
+	case AMDGPU_SVM_ACCESS_ALLOW_MIGRATE:
+		return 0;
+	default:
+		return -EINVAL;
+	}
+}
+
+static bool attr_flag_type_to_bit(u32 type, u32 *flag_bit)
+{
+	if (type < AMDGPU_SVM_ATTR_HOST_ACCESS || type > AMDGPU_SVM_ATTR_GPU_READ_MOSTLY)
+		return false;
+
+	*flag_bit = 1u << (type - AMDGPU_SVM_ATTR_HOST_ACCESS);
+	return true;
+}
+
+static inline int attr_check_flag_value(u32 value)
+{
+	if (value > 1)
+		return -EINVAL;
+
+	return 0;
+}
+
+static inline int attr_check_flag_attr(u32 type, u32 value)
+{
+	u32 flag_bit;
+	int ret;
+
+	if (!attr_flag_type_to_bit(type, &flag_bit))
+		return -EINVAL;
+
+	ret = attr_check_flag_value(value);
+	if (ret)
+		return ret;
+
+	return 0;
+}
+
+static inline int attr_check_granularity(u32 value)
+{
+	return 0;
+}
+
+static int attr_set_validate(const struct drm_amdgpu_svm_attribute *attr)
+{
+	switch (attr->type) {
+	case AMDGPU_SVM_ATTR_PREFERRED_LOC:
+		return attr_check_preferred_loc(attr->value);
+	case AMDGPU_SVM_ATTR_PREFETCH_LOC:
+		return attr_check_prefetch_loc(attr->value);
+	case AMDGPU_SVM_ATTR_ACCESS:
+		return attr_check_access(attr->value);
+	case AMDGPU_SVM_ATTR_GRANULARITY:
+		return attr_check_granularity(attr->value);
+	case AMDGPU_SVM_ATTR_HOST_ACCESS:
+	case AMDGPU_SVM_ATTR_COHERENT:
+	case AMDGPU_SVM_ATTR_GPU_RO:
+	case AMDGPU_SVM_ATTR_GPU_EXEC:
+	case AMDGPU_SVM_ATTR_GPU_READ_MOSTLY:
+	case AMDGPU_SVM_ATTR_EXT_COHERENT:
+		return attr_check_flag_attr(attr->type, attr->value);
+	default:
+		return -EINVAL;
+	}
+}
+
+static void attr_apply_flag(struct amdgpu_svm_attrs *attrs, u32 type, u32 value)
+{
+	u32 flag_bit;
+
+	if (!attr_flag_type_to_bit(type, &flag_bit))
+		return;
+
+	if (value)
+		attrs->flags |= flag_bit;
+	else
+		attrs->flags &= ~flag_bit;
+}
+
+static void
+attr_apply(struct amdgpu_svm_attrs *attrs, u32 nattr, const struct drm_amdgpu_svm_attribute *pattrs)
+{
+	const struct drm_amdgpu_svm_attribute *attr;
+
+	for (attr = pattrs; nattr--; attr++) {
+		switch (attr->type) {
+		case AMDGPU_SVM_ATTR_PREFERRED_LOC:
+			attrs->preferred_loc = (s32)attr->value;
+			break;
+		case AMDGPU_SVM_ATTR_PREFETCH_LOC:
+			attrs->prefetch_loc = (s32)attr->value;
+			break;
+		case AMDGPU_SVM_ATTR_ACCESS:
+			attrs->access = (enum amdgpu_ioctl_svm_access)attr->value;
+			break;
+		case AMDGPU_SVM_ATTR_HOST_ACCESS:
+		case AMDGPU_SVM_ATTR_COHERENT:
+		case AMDGPU_SVM_ATTR_GPU_RO:
+		case AMDGPU_SVM_ATTR_GPU_EXEC:
+		case AMDGPU_SVM_ATTR_GPU_READ_MOSTLY:
+		case AMDGPU_SVM_ATTR_EXT_COHERENT:
+			attr_apply_flag(attrs, attr->type, attr->value);
+			break;
+		case AMDGPU_SVM_ATTR_GRANULARITY:
+			attrs->granularity = min_t(u32, attr->value, 0x3f);
+			break;
+		default:
+			break;
+		}
+	}
+}
+
+static bool attr_same_attrs(const struct amdgpu_svm_attr_range *range, u32 nattr,
+			    const struct drm_amdgpu_svm_attribute *attrs)
+{
+	struct amdgpu_svm_attrs target;
+
+	target = range->attrs;
+	attr_apply(&target, nattr, attrs);
+	return attr_equal(&range->attrs, &target);
+}
+
+static int
+amdgpu_svm_attr_set_hole(struct amdgpu_svm_attr_tree *attr_tree,
+			 const struct amdgpu_svm_attrs *default_attrs, unsigned long start_page,
+			 unsigned long last_page, u32 nattr,
+			 const struct drm_amdgpu_svm_attribute *attrs, struct attr_set_ctx *change)
+{
+	struct amdgpu_svm_attrs new_attrs;
+	struct amdgpu_svm_attr_range *range;
+
+	lockdep_assert_held(&attr_tree->lock);
+
+	if (start_page > last_page)
+		return 0;
+
+	new_attrs = *default_attrs;
+	attr_apply(&new_attrs, nattr, attrs);
+
+	/* Always create a range entry even when attrs equal defaults */
+	range = amdgpu_svm_attr_range_alloc(start_page, last_page, &new_attrs);
+	if (!range)
+		return -ENOMEM;
+
+	amdgpu_svm_attr_range_insert_locked(attr_tree, range);
+
+	attr_change_ctx_set(change, default_attrs, &new_attrs, start_page, last_page);
+	return 0;
+}
+
+/*
+ * amdgpu_svm_attr_set_existing() - Apply attrs to part of an existing range
+ *
+ * Update @range over [@start_page, @last_page]. If the request fully covers
+ * @range the attrs are updated in place, otherwise the range is split into the
+ * head/tail, carrying the old attrs, and the covered middle, carrying
+ * the new attrs. The resulting change is reported by @change.
+ */
+static int amdgpu_svm_attr_set_existing(struct amdgpu_svm_attr_tree *attr_tree,
+					struct amdgpu_svm_attr_range *range,
+					unsigned long start_page, unsigned long last_page,
+					u32 nattr, const struct drm_amdgpu_svm_attribute *attrs,
+					struct attr_set_ctx *change)
+{
+	unsigned long range_start = amdgpu_svm_attr_start_page(range);
+	unsigned long range_last = amdgpu_svm_attr_last_page(range);
+	struct amdgpu_svm_attr_range *left = NULL;
+	struct amdgpu_svm_attr_range *right = NULL;
+	struct amdgpu_svm_attrs old_attrs;
+	struct amdgpu_svm_attrs new_attrs;
+
+	lockdep_assert_held(&attr_tree->lock);
+
+	old_attrs = range->attrs;
+
+	if (attr_same_attrs(range, nattr, attrs)) {
+		/* Report old==new so apply_attr_change can decide */
+		attr_change_ctx_set(change, &old_attrs, &old_attrs, start_page, last_page);
+		return 0;
+	}
+
+	new_attrs = old_attrs;
+	attr_apply(&new_attrs, nattr, attrs);
+
+	/* only need to update attr */
+	if (start_page == range_start && last_page == range_last) {
+		range->attrs = new_attrs;
+		attr_change_ctx_set(change, &old_attrs, &new_attrs, start_page, last_page);
+		return 0;
+	}
+
+	/* split head */
+	if (start_page > range_start) {
+		left = amdgpu_svm_attr_range_alloc(range_start, start_page - 1, &old_attrs);
+		if (!left)
+			return -ENOMEM;
+	}
+
+	/* split tail */
+	if (last_page < range_last) {
+		right = amdgpu_svm_attr_range_alloc(last_page + 1, range_last, &old_attrs);
+		if (!right) {
+			kfree(left);
+			return -ENOMEM;
+		}
+	}
+
+	attr_remove_range_locked(attr_tree, range, false);
+	if (left)
+		amdgpu_svm_attr_range_insert_locked(attr_tree, left);
+	attr_set_interval(range, start_page, last_page);
+	range->attrs = new_attrs;
+	amdgpu_svm_attr_range_insert_locked(attr_tree, range);
+	if (right)
+		amdgpu_svm_attr_range_insert_locked(attr_tree, right);
+
+	attr_change_ctx_set(change, &old_attrs, &new_attrs, start_page, last_page);
+	return 0;
+}
+
+/*
+ * amdgpu_svm_attr_set_range() - Apply attr changes across [@start_page, @last_page]
+ *
+ * Walk the interval in segments, each segment being either an existing range
+ * or a hole.
+ */
+static int amdgpu_svm_attr_set_range(struct amdgpu_svm_attr_tree *attr_tree,
+				     const struct amdgpu_svm_attrs *default_attrs,
+				     unsigned long start_page, unsigned long last_page, u32 nattr,
+				     const struct drm_amdgpu_svm_attribute *attrs)
+{
+	struct amdgpu_svm *svm = attr_tree->svm;
+	unsigned long cursor = start_page;
+	bool need_retry = false;
+
+	while (cursor <= last_page) {
+		struct interval_tree_node *node;
+		unsigned long seg_last;
+		struct attr_set_ctx change = { 0 };
+		int ret;
+
+		amdgpu_svm_lock(svm);
+		mutex_lock(&attr_tree->lock);
+		node = interval_tree_iter_first(&attr_tree->tree, cursor, cursor);
+		if (node) {
+			struct amdgpu_svm_attr_range *range;
+
+			range = container_of(node, struct amdgpu_svm_attr_range, it_node);
+			seg_last = min(last_page, amdgpu_svm_attr_last_page(range));
+			ret = amdgpu_svm_attr_set_existing(attr_tree, range, cursor, seg_last,
+							   nattr, attrs, &change);
+		} else {
+			struct interval_tree_node *next;
+
+			seg_last = last_page;
+			if (cursor != ULONG_MAX) {
+				next = interval_tree_iter_first(&attr_tree->tree, cursor + 1,
+								ULONG_MAX);
+				if (next) {
+					struct amdgpu_svm_attr_range *next_range;
+
+					next_range = container_of(next,
+								  struct amdgpu_svm_attr_range,
+								  it_node);
+					seg_last = min(last_page,
+						       amdgpu_svm_attr_start_page(next_range) - 1);
+				}
+			}
+			ret = amdgpu_svm_attr_set_hole(attr_tree, default_attrs, cursor, seg_last,
+						       nattr, attrs, &change);
+		}
+		mutex_unlock(&attr_tree->lock);
+
+		if (ret) {
+			amdgpu_svm_unlock(svm);
+			return ret;
+		}
+
+		ret = amdgpu_svm_apply_attr_change(svm, &change.old_attrs, &change.new_attrs,
+						   change.start_page, change.last_page);
+		amdgpu_svm_unlock(svm);
+
+		if (ret == -EAGAIN) {
+			need_retry = true;
+			ret = 0;
+		}
+
+		if (ret)
+			return ret;
+
+		if (seg_last == ULONG_MAX || seg_last == last_page)
+			break;
+
+		cursor = seg_last + 1;
+	}
+
+	return need_retry ? -EAGAIN : 0;
+}
+
+/**
+ * amdgpu_svm_attr_tree_create() - Allocate an empty attribute tree
+ * @svm: Owning SVM context.
+ *
+ * Call before publishing the SVM context.
+ *
+ * Return: The tree, or NULL on allocation failure.
+ */
+struct amdgpu_svm_attr_tree *amdgpu_svm_attr_tree_create(struct amdgpu_svm *svm)
+{
+	struct amdgpu_svm_attr_tree *attr_tree;
+
+	attr_tree = kzalloc_obj(*attr_tree, GFP_KERNEL);
+	if (!attr_tree)
+		return NULL;
+
+	mutex_init(&attr_tree->lock);
+	attr_tree->tree = RB_ROOT_CACHED;
+	INIT_LIST_HEAD(&attr_tree->range_list);
+	attr_tree->svm = svm;
+	return attr_tree;
+}
+
+/**
+ * amdgpu_svm_attr_tree_destroy() - Free the attribute tree and its ranges
+ * @attr_tree: Tree to destroy, or NULL.
+ *
+ * All external users must have been quiesced before calling this.
+ */
+void amdgpu_svm_attr_tree_destroy(struct amdgpu_svm_attr_tree *attr_tree)
+{
+	struct amdgpu_svm_attr_range *range, *tmp;
+
+	if (!attr_tree)
+		return;
+
+	mutex_lock(&attr_tree->lock);
+	list_for_each_entry_safe(range, tmp, &attr_tree->range_list, list) {
+		interval_tree_remove(&range->it_node, &attr_tree->tree);
+		list_del_init(&range->list);
+		kfree(range);
+	}
+	mutex_unlock(&attr_tree->lock);
+
+	mutex_destroy(&attr_tree->lock);
+	kfree(attr_tree);
+}
+
+/**
+ * amdgpu_svm_attr_set() - Apply SET_ATTR attributes to a VA interval
+ * @attr_tree: Attribute tree of the SVM context.
+ * @start: Page aligned start address.
+ * @size: Page aligned interval size.
+ * @nattr: Number of entries in @attrs.
+ * @attrs: UAPI attributes to apply.
+ *
+ * Context: Takes the SVM lock and @attr_tree->lock; caller must hold neither.
+ * Return: 0 on success or a negative error code.
+ */
+int amdgpu_svm_attr_set(struct amdgpu_svm_attr_tree *attr_tree, u64 start, u64 size, u32 nattr,
+			const struct drm_amdgpu_svm_attribute *attrs)
+{
+	struct amdgpu_svm *svm = attr_tree->svm;
+	struct amdgpu_svm_attrs default_attrs;
+	unsigned long start_page, last_page;
+	u32 i;
+	int r;
+
+	start_page = start >> PAGE_SHIFT;
+	last_page = (start + size - 1) >> PAGE_SHIFT;
+
+	for (i = 0; i < nattr; i++) {
+		pr_debug("set attr type %u value 0x%08x range [0x%lx-0x%lx] xnack:%d",
+			 attrs[i].type, attrs[i].value, start_page, last_page,
+			 svm->xnack_enabled ? 1 : 0);
+		r = attr_set_validate(&attrs[i]);
+		if (r) {
+			pr_debug("invalid attribute %u value 0x%08x", attrs[i].type,
+				 attrs[i].value);
+			return r;
+		}
+	}
+
+	amdgpu_svm_attr_set_default(attr_tree->svm, &default_attrs);
+
+retry:
+	r = amdgpu_svm_attr_set_range(attr_tree, &default_attrs, start_page, last_page, nattr,
+				      attrs);
+	if (r == -EAGAIN) {
+		pr_debug("attr_set retry [0x%lx-0x%lx]\n", start_page, last_page);
+		amdgpu_svm_sync_work(svm);
+		cond_resched();
+		goto retry;
+	}
+
+	return r;
+}
+
+static int amdgpu_svm_attr_clear(struct amdgpu_svm_attr_tree *attr_tree, unsigned long start_page,
+				 unsigned long last_page)
+{
+	struct interval_tree_node *node;
+	int r = 0;
+
+	if (start_page > last_page)
+		return -EINVAL;
+
+	mutex_lock(&attr_tree->lock);
+
+	node = interval_tree_iter_first(&attr_tree->tree, start_page, last_page);
+	while (node) {
+		struct interval_tree_node *next;
+		struct amdgpu_svm_attr_range *range;
+		unsigned long range_start;
+		unsigned long range_last;
+
+		range = container_of(node, struct amdgpu_svm_attr_range, it_node);
+		next = interval_tree_iter_next(node, start_page, last_page);
+		range_start = amdgpu_svm_attr_start_page(range);
+		range_last = amdgpu_svm_attr_last_page(range);
+
+		if (range_start < start_page && range_last > last_page) {
+			struct amdgpu_svm_attr_range *tail;
+
+			tail = amdgpu_svm_attr_range_alloc(last_page + 1, range_last,
+							   &range->attrs);
+			if (!tail) {
+				r = -ENOMEM;
+				break;
+			}
+
+			attr_remove_range_locked(attr_tree, range, false);
+			attr_set_interval(range, range_start, start_page - 1);
+			amdgpu_svm_attr_range_insert_locked(attr_tree, range);
+			amdgpu_svm_attr_range_insert_locked(attr_tree, tail);
+		} else if (range_start < start_page) {
+			attr_remove_range_locked(attr_tree, range, false);
+			attr_set_interval(range, range_start, start_page - 1);
+			amdgpu_svm_attr_range_insert_locked(attr_tree, range);
+		} else if (range_last > last_page) {
+			attr_remove_range_locked(attr_tree, range, false);
+			attr_set_interval(range, last_page + 1, range_last);
+			amdgpu_svm_attr_range_insert_locked(attr_tree, range);
+		} else {
+			attr_remove_range_locked(attr_tree, range, true);
+		}
+
+		node = next;
+	}
+
+	mutex_unlock(&attr_tree->lock);
+	return r;
+}
+
+/**
+ * amdgpu_svm_attr_reset() - Return a page interval to default attributes
+ * @attr_tree: Attribute tree of the SVM context.
+ * @start_page: First page of the interval.
+ * @last_page: Last page of the interval.
+ *
+ * Context: Takes @attr_tree->lock.
+ * Return: 0 on success, -EINVAL for an empty interval or -ENOMEM.
+ */
+int amdgpu_svm_attr_reset(struct amdgpu_svm_attr_tree *attr_tree, unsigned long start_page,
+			  unsigned long last_page)
+{
+	/*
+	 * Range with no attr node in this implementation is treated the
+	 * same as one that explicitly stores default attrs. So clear
+	 * the attribute ranges when user wants to reset the attrs.
+	 *
+	 * - GET_ATTR: return default_attrs to userspace when there is no attr
+	 *   range.
+	 * - SET_ATTR: holes are treated as having default_attrs when
+	 *   computing the change trigger.
+	 * - Fault: attr lookup falls back to defaults when no attr range exists,
+	 *   so migration and PTE flag decisions are unchanged.
+	 *
+	 * This approach simplifies the implementation and avoids redundant
+	 * attribute maintenance. This ioctl operation is for attribute only,
+	 * so do not invalidate the GPU mapping here.
+	 */
+	return amdgpu_svm_attr_clear(attr_tree, start_page, last_page);
+}
+
+static void attr_get_ctx_add(struct attr_get_ctx *ctx, const struct amdgpu_svm_attrs *attrs)
+{
+	if (!ctx->has_range) {
+		ctx->preferred_loc = attrs->preferred_loc;
+		ctx->prefetch_loc = attrs->prefetch_loc;
+		ctx->granularity = attrs->granularity;
+		ctx->access = attrs->access;
+		ctx->flags_and = attrs->flags;
+		ctx->has_range = true;
+		return;
+	}
+
+	if (ctx->preferred_loc != attrs->preferred_loc)
+		ctx->preferred_loc = AMDGPU_SVM_LOCATION_UNDEFINED;
+	if (ctx->prefetch_loc != attrs->prefetch_loc)
+		ctx->prefetch_loc = AMDGPU_SVM_LOCATION_UNDEFINED;
+	if (attrs->granularity < ctx->granularity)
+		ctx->granularity = attrs->granularity;
+	if (ctx->access != attrs->access)
+		ctx->access = AMDGPU_SVM_ACCESS_INACCESSIBLE;
+	ctx->flags_and &= attrs->flags;
+}
+
+static int attr_get_ctx_to_result(const struct attr_get_ctx *ctx, u32 nattr,
+				  struct drm_amdgpu_svm_attribute *attrs)
+{
+	u32 i;
+
+	for (i = 0; i < nattr; i++) {
+		switch (attrs[i].type) {
+		case AMDGPU_SVM_ATTR_PREFERRED_LOC:
+			attrs[i].value = ctx->preferred_loc;
+			break;
+		case AMDGPU_SVM_ATTR_PREFETCH_LOC:
+			attrs[i].value = ctx->prefetch_loc;
+			break;
+		case AMDGPU_SVM_ATTR_ACCESS:
+			attrs[i].value = (u32)ctx->access;
+			break;
+		case AMDGPU_SVM_ATTR_HOST_ACCESS:
+		case AMDGPU_SVM_ATTR_COHERENT:
+		case AMDGPU_SVM_ATTR_GPU_RO:
+		case AMDGPU_SVM_ATTR_GPU_EXEC:
+		case AMDGPU_SVM_ATTR_GPU_READ_MOSTLY:
+		case AMDGPU_SVM_ATTR_EXT_COHERENT: {
+			u32 flag_bit;
+
+			if (!attr_flag_type_to_bit(attrs[i].type, &flag_bit))
+				return -EINVAL;
+
+			attrs[i].value = (ctx->flags_and & flag_bit) ? 1 : 0;
+			break;
+		}
+		case AMDGPU_SVM_ATTR_GRANULARITY:
+			attrs[i].value = ctx->granularity;
+			break;
+		default:
+			return -EINVAL;
+		}
+	}
+
+	return 0;
+}
+
+/**
+ * amdgpu_svm_attr_get() - Get attributes for the uniform prefix of an interval
+ * @attr_tree: Attribute tree of the SVM context.
+ * @start: Page aligned start address.
+ * @size: Page aligned interval size.
+ * @nattr: Number of entries in @attrs.
+ * @attrs: UAPI attributes, filled in on return.
+ * @out_size: Optional output length of the uniform prefix, in bytes.
+ *
+ * Context: Takes @attr_tree->lock.
+ * Return: 0 on success or -EINVAL for an unknown attribute type.
+ */
+int amdgpu_svm_attr_get(struct amdgpu_svm_attr_tree *attr_tree, u64 start, u64 size, u32 nattr,
+			struct drm_amdgpu_svm_attribute *attrs, u64 *out_size)
+{
+	struct amdgpu_svm_attrs default_attrs;
+	struct amdgpu_svm_attrs ref_attrs;
+	struct attr_get_ctx ctx = { 0 };
+	struct interval_tree_node *node;
+	unsigned long start_page, last_page, cursor, homog_last;
+	bool have_ref = false;
+	int r;
+
+	start_page = start >> PAGE_SHIFT;
+	last_page = (start + size - 1) >> PAGE_SHIFT;
+
+	mutex_lock(&attr_tree->lock);
+	amdgpu_svm_attr_set_default(attr_tree->svm, &default_attrs);
+
+	homog_last = start_page;
+	cursor = start_page;
+	node = interval_tree_iter_first(&attr_tree->tree, start_page, last_page);
+
+	while (cursor <= last_page) {
+		const struct amdgpu_svm_attrs *range_attrs;
+		unsigned long range_last = last_page;
+		struct amdgpu_svm_attr_range *range = NULL;
+		unsigned long next;
+
+		if (node) {
+			range = container_of(node, struct amdgpu_svm_attr_range, it_node);
+
+			if (amdgpu_svm_attr_last_page(range) < cursor) {
+				node = interval_tree_iter_next(node, start_page, last_page);
+				continue;
+			}
+
+			if (amdgpu_svm_attr_start_page(range) <= cursor) {
+				range_last = min(last_page, amdgpu_svm_attr_last_page(range));
+				node = interval_tree_iter_next(node, start_page, last_page);
+			} else {
+				range_last = min(last_page, amdgpu_svm_attr_start_page(range) - 1);
+				range = NULL;
+			}
+		}
+
+		range_attrs = range ? &range->attrs : &default_attrs;
+
+		if (!have_ref) {
+			ref_attrs = *range_attrs;
+			have_ref = true;
+		} else if (!attr_equal(range_attrs, &ref_attrs)) {
+			break;
+		}
+
+		homog_last = range_last;
+
+		if (range_last == ULONG_MAX)
+			break;
+
+		next = range_last + 1;
+		if (next <= cursor)
+			break;
+		cursor = next;
+	}
+
+	if (!have_ref)
+		ref_attrs = default_attrs;
+
+	attr_get_ctx_add(&ctx, &ref_attrs);
+	r = attr_get_ctx_to_result(&ctx, nattr, attrs);
+	mutex_unlock(&attr_tree->lock);
+
+	if (!r && out_size)
+		*out_size = ((u64)(homog_last - start_page) + 1) << PAGE_SHIFT;
+
+	return r;
+}
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.h +8 -0
index 3880ffaf46ffb..94371118cbdc5 100644
@@ -156,11 +156,19 @@ enum amdgpu_svm_attr_change_trigger {
 	(AMDGPU_SVM_ATTR_TRIGGER_ACCESS_CHANGE | AMDGPU_SVM_ATTR_TRIGGER_PTE_FLAG_CHANGE | \
 	 AMDGPU_SVM_ATTR_TRIGGER_MAPPING_FLAG_CHANGE | AMDGPU_SVM_ATTR_TRIGGER_LOCATION_CHANGE)
 
+struct amdgpu_svm_attr_tree *amdgpu_svm_attr_tree_create(struct amdgpu_svm *svm);
+void amdgpu_svm_attr_tree_destroy(struct amdgpu_svm_attr_tree *attr_tree);
 struct amdgpu_svm_attr_range *
 amdgpu_svm_attr_get_bounds_locked(struct amdgpu_svm_attr_tree *attr_tree, unsigned long page,
 				  unsigned long *start_page, unsigned long *last_page);
 void amdgpu_svm_attr_set_default(struct amdgpu_svm *svm, struct amdgpu_svm_attrs *attrs);
 
+int amdgpu_svm_attr_set(struct amdgpu_svm_attr_tree *attr_tree, u64 start, u64 size, u32 nattr,
+			const struct drm_amdgpu_svm_attribute *attrs);
+int amdgpu_svm_attr_get(struct amdgpu_svm_attr_tree *attr_tree, u64 start, u64 size, u32 nattr,
+			struct drm_amdgpu_svm_attribute *attrs, u64 *out_size);
+int amdgpu_svm_attr_reset(struct amdgpu_svm_attr_tree *attr_tree, unsigned long start_page,
+			  unsigned long last_page);
 struct amdgpu_svm_attr_range *
 amdgpu_svm_attr_range_alloc(unsigned long start_page, unsigned long last_page,
 			    const struct amdgpu_svm_attrs *attrs);
Signature · 1 line
2.53.0
author
#6 lore raw

PATCH v11 6/22 drm/amdgpu: add SVM range types and work queue interface

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Add amdgpu_svm_range.h with GPU mapped range types and interfaces:
- enum amdgpu_svm_range_queue_state: NOT_QUEUED, IN_GC, PROCESSING states for queue work
- struct amdgpu_svm_range: extends drm_gpusvm_range with gpu_mapped state, queue_state, attribute flags, work queue node, pending ops/pages, and validation timestamp
- enum amdgpu_svm_range_op: NONE, UNMAP operation types
- struct amdgpu_svm_range_op_ctx: dequeue context for GC processing
- Inline helper: amdgpu_svm_range_invalidate_gpu_mapping
- Range operations API declarations: find_or_insert, get_pages, update_mapping, update_gpu_range, invalidate

Embed the device-owned drm_gpusvm_pages cache in each AMDGPU range and use its notifier sequence for range tracing.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h | 133 ++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_trace.h     |  28 ++++
 2 files changed, 161 insertions(+)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h new file +133 -0
new file mode 100644
index 0000000000000..ad2df5924ebc8
@@ -0,0 +1,133 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/*
+ * Copyright 2026 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#ifndef __AMDGPU_SVM_RANGE_H__
+#define __AMDGPU_SVM_RANGE_H__
+
+#include <drm/drm_gpusvm.h>
+#include <drm/drm_pagemap.h>
+
+#include "amdgpu_svm.h"
+#include "amdgpu_vm.h"
+
+#include <linux/ktime.h>
+#include <linux/list.h>
+#include <linux/types.h>
+
+struct amdgpu_svm;
+struct amdgpu_svm_attr_range;
+struct amdgpu_svm_attrs;
+struct dma_fence;
+struct drm_exec;
+struct drm_gpusvm_notifier;
+struct drm_gpusvm_range;
+struct mmu_notifier_range;
+
+/**
+ * enum amdgpu_svm_range_queue_state - Work queue state of an SVM range
+ * @AMDGPU_SVM_RANGE_NOT_QUEUED: Not on any work list.
+ * @AMDGPU_SVM_RANGE_IN_GC: Queued on the GC list.
+ * @AMDGPU_SVM_RANGE_PROCESSING: Being processed in workqueue.
+ */
+enum amdgpu_svm_range_queue_state {
+	AMDGPU_SVM_RANGE_NOT_QUEUED = 0,
+	AMDGPU_SVM_RANGE_IN_GC,
+	AMDGPU_SVM_RANGE_PROCESSING,
+};
+
+/**
+ * struct amdgpu_svm_range - amdgpu GPU mapped SVM range
+ * @base: Embedded drm_gpusvm_range base.
+ * @pages: Device-owned page and DMA mapping cache.
+ * @work_node: Links the range into the work list. Protected by amdgpu_svm.work_lock.
+ * @gpu_mapped: True while the range has a live GPU mapping. Accessed with
+ *              READ_ONCE/WRITE_ONCE.
+ * @queue_state: Current work queue state @amdgpu_svm_range_queue_state.
+ *               Protected by amdgpu_svm.work_lock.
+ * @pending_ops: Pending amdgpu_svm_range_op bitmask. Protected by work_lock.
+ * @pending_start_page: First page of the accumulated pending interval.
+ * @pending_last_page: Last page of the accumulated pending interval.
+ * @attr_flags: Attribute flags last applied to the GPU mapping.
+ * @validate_timestamp: Time of the last successful mapping validation.
+ */
+struct amdgpu_svm_range {
+	struct drm_gpusvm_range base;
+	struct drm_gpusvm_pages pages;
+	struct list_head work_node;
+	bool gpu_mapped;
+	u8 queue_state;
+	u8 pending_ops;
+	unsigned long pending_start_page;
+	unsigned long pending_last_page;
+	u32 attr_flags;
+	ktime_t validate_timestamp;
+};
+
+static inline struct amdgpu_svm_range *to_amdgpu_svm_range(struct drm_gpusvm_range *range)
+{
+	return container_of(range, struct amdgpu_svm_range, base);
+}
+
+static inline void amdgpu_svm_range_invalidate_gpu_mapping(struct amdgpu_svm_range *range)
+{
+	WRITE_ONCE(range->gpu_mapped, false);
+}
+
+#define AMDGPU_SVM_RANGE_TRACE(r__, op__)                                                          \
+	do {                                                                                       \
+		struct amdgpu_svm_range *trace_range = (r__);                                      \
+	\
+		trace_amdgpu_svm_range((op__), to_amdgpu_svm(trace_range->base.gpusvm)->vm->pasid, \
+				       trace_range->base.gpusvm,                                   \
+				       READ_ONCE(trace_range->gpu_mapped),                         \
+				       trace_range->pages.notifier_seq,                            \
+				       drm_gpusvm_range_start(&trace_range->base) >> PAGE_SHIFT,   \
+				       drm_gpusvm_range_end(&trace_range->base) >> PAGE_SHIFT);    \
+	} while (0)
+
+/**
+ * enum amdgpu_svm_range_op - Pending operation bits for an SVM range
+ * @AMDGPU_SVM_RANGE_OP_NONE: No pending operation.
+ * @AMDGPU_SVM_RANGE_OP_UNMAP: Range needs to be unmapped/removed by the GC.
+ */
+enum amdgpu_svm_range_op {
+	AMDGPU_SVM_RANGE_OP_NONE = 0,
+	AMDGPU_SVM_RANGE_OP_UNMAP = BIT(0),
+};
+
+/**
+ * struct amdgpu_svm_range_op_ctx - context of a range workqueue operation
+ * @range: The dequeued range to process.
+ * @start_page: First page for workqueue operation.
+ * @last_page: Last page for workqueue operation.
+ * @pending_ops: amdgpu_svm_range_op bitmask.
+ */
+struct amdgpu_svm_range_op_ctx {
+	struct amdgpu_svm_range *range;
+	unsigned long start_page;
+	unsigned long last_page;
+	u8 pending_ops;
+};
+
+#endif /* __AMDGPU_SVM_RANGE_H__ */
drivers/gpu/drm/amd/amdgpu/amdgpu_trace.h +28 -0
index 1373a11f50d86..d5c7c983c04d7 100644
@@ -116,6 +116,34 @@ TRACE_EVENT(amdgpu_iv,
 		      __entry->src_data[2], __entry->src_data[3])
 );
 
+TRACE_EVENT(amdgpu_svm_range,
+	    TP_PROTO(const char *op, u32 pasid, void *gpusvm, bool mapped,
+		     unsigned long seqno, unsigned long start_page,
+		     unsigned long end_page),
+	    TP_ARGS(op, pasid, gpusvm, mapped, seqno, start_page, end_page),
+	    TP_STRUCT__entry(__string(op, op)
+			     __field(u32, pasid)
+			     __field(void *, gpusvm)
+			     __field(bool, mapped)
+			     __field(unsigned long, seqno)
+			     __field(unsigned long, start_page)
+			     __field(unsigned long, end_page)
+			    ),
+	    TP_fast_assign(__assign_str(op);
+			   __entry->pasid = pasid;
+			   __entry->gpusvm = gpusvm;
+			   __entry->mapped = mapped;
+			   __entry->seqno = seqno;
+			   __entry->start_page = start_page;
+			   __entry->end_page = end_page;
+			   ),
+	    TP_printk("%s: pasid=%u gpusvm=%p mapped=%d seqno=%lu range=[0x%lx-0x%lx]-0x%lx",
+		      __get_str(op), __entry->pasid, __entry->gpusvm,
+		      __entry->mapped, __entry->seqno,
+		      __entry->start_page, __entry->end_page,
+		      __entry->end_page - __entry->start_page)
+);
+
 
 TRACE_EVENT(amdgpu_bo_create,
 	    TP_PROTO(struct amdgpu_bo *bo),
Signature · 1 line
2.53.0
author
#7 lore raw

PATCH v11 7/22 drm/amdgpu: implement SVM range GPU mapping core

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Map system-memory SVM ranges through the common get_vm_pte interface. Describe backing pages as TTM_PL_TT, translate coherence attributes to GEM flags and set base permissions before hardware encoding. Preserve system DMA/IOVA addresses and reject unsupported interconnect types.

Provide range lookup, page collection, mapping validity and attribute mapping helpers. Keep drm_exec reservation loops at their call sites and enforce SVM access and write-fault permissions. VRAM migration is not part of this implementation.

Collect and validate pages through the generic drm_gpusvm pages APIs. Use the AMDGPU-owned DMA cache and reject ranges with unmapped or partially unmapped state before validating the page sequence.

Return reported compute TLB flush errors to prefetch callers instead of reporting a successful mapping update when the flush fails.

Execute explicit SYSMEM prefetch through the existing GPUSVM eviction helper before collecting pages and updating GPU mappings. Do not skip the request for an already valid mapping or let a LOCAL preference override its target. Return eviction errors without continuing to map. This does not enable the AMDGPU VRAM migration backend.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h       |   4 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c | 338 ++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h |  21 ++
 3 files changed, 363 insertions(+)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c
drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h +4 -0
index c21690c2d2117..e8a9df974988e 100644
@@ -27,6 +27,7 @@
 
 #include <drm/amdgpu_drm.h>
 #include <drm/drm_gpusvm.h>
+#include <drm/drm_pagemap.h>
 #include <linux/atomic.h>
 #include <linux/kref.h>
 #include <linux/list.h>
@@ -44,6 +45,9 @@ struct amdgpu_svm_attrs;
 struct drm_device;
 struct drm_file;
 
+#define AMDGPU_INTERCONNECT_VRAM DRM_INTERCONNECT_DRIVER
+#define AMDGPU_INTERCONNECT_P2P (AMDGPU_INTERCONNECT_VRAM + 1)
+
 enum amdgpu_svm_xnack_mode {
 	AMDGPU_SVM_XNACK_OFF,
 	AMDGPU_SVM_XNACK_ON,
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c new file +338 -0

338 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h +21 -0
index ad2df5924ebc8..641e1dee9e500 100644
@@ -130,4 +130,25 @@ struct amdgpu_svm_range_op_ctx {
 	u8 pending_ops;
 };
 
+bool amdgpu_svm_range_pages_valid(struct amdgpu_svm *svm, struct amdgpu_svm_range *range);
+bool amdgpu_svm_range_is_valid(struct amdgpu_svm_range *range,
+			       const struct amdgpu_svm_attrs *attrs);
+int amdgpu_svm_range_update_gpu_range(struct amdgpu_svm *svm, struct amdgpu_svm_range *range,
+				      const struct amdgpu_svm_attrs *attrs, bool read_only,
+				      bool flush_tlb, bool wait, struct dma_fence **fence);
+int amdgpu_svm_range_update_mapping(struct amdgpu_svm *svm, struct amdgpu_svm_range *range,
+				    const struct amdgpu_svm_attrs *attrs, bool read_only, bool intr,
+				    bool wait, bool flush_tlb);
+int amdgpu_svm_range_map_attrs(struct amdgpu_svm *svm, const struct amdgpu_svm_attrs *attrs,
+			       unsigned long start, unsigned long end);
+int amdgpu_svm_range_zap_ptes(struct amdgpu_svm *svm, struct amdgpu_svm_range *range,
+			      unsigned long start_page, unsigned long last_page);
+void amdgpu_svm_range_evict(struct amdgpu_svm *svm, struct drm_gpusvm_range *range);
+struct amdgpu_svm_range *
+amdgpu_svm_range_find_or_insert(struct amdgpu_svm *svm, unsigned long addr,
+				unsigned long gpuva_start, unsigned long gpuva_end,
+				struct drm_gpusvm_ctx *ctx);
+int amdgpu_svm_range_get_pages(struct amdgpu_svm *svm, struct drm_gpusvm_range *range,
+			       struct drm_gpusvm_ctx *ctx);
+
 #endif /* __AMDGPU_SVM_RANGE_H__ */
Signature · 1 line
2.53.0
author
#8 lore raw

PATCH v11 8/22 drm/amdgpu: implement SVM range notifier and GC helpers

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Add MMU notifier event handling and garbage collection infrastructure:
- remove invalidated ranges from gpusvm
- zap complete ranges before invalidating their DMA mappings
- queue unmapped ranges for deferred garbage collection
- serialize GC queue state and range references
- drain queued GC before changing each attribute segment
- reject ranges already marked unmapped during lookup

The last two steps prevent attribute updates and prefetch mapping from reusing a stale range that has been marked unmapped but has not yet been removed from the gpusvm tree.

The notifier releases DMA mappings for the complete GPUSVM range. Zapping only the notifier intersection would leave valid GPU PTEs referencing unmapped DMA addresses, so invalidate the complete GPU mapping first.

On attribute changes, discard cached DMA mappings even when the range survives. Complete the compute TLB flush before releasing mappings, and propagate failures. Clearing GPU_RO must obtain write-qualified pages for COW rather than reuse a read-only cache.

Invalidate the AMDGPU-owned page cache with the generic pages API. Keep unmap state on the GPUSVM range and pass its device-owned cache to drm_gpusvm_range_set_unmapped().

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c  |   6 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c | 323 ++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h |  10 +
 3 files changed, 339 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_attr.c +6 -0
index 0db96a4700666..70a3db7c830cc 100644
@@ -556,6 +556,12 @@ static int amdgpu_svm_attr_set_range(struct amdgpu_svm_attr_tree *attr_tree,
 		int ret;
 
 		amdgpu_svm_lock(svm);
+		ret = amdgpu_svm_garbage_collector(svm);
+		if (ret) {
+			amdgpu_svm_unlock(svm);
+			return ret;
+		}
+
 		mutex_lock(&attr_tree->lock);
 		node = interval_tree_iter_first(&attr_tree->tree, cursor, cursor);
 		if (node) {
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c +323 -0

344 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h +10 -0
index 641e1dee9e500..82ec0c769d25b 100644
@@ -139,6 +139,12 @@ int amdgpu_svm_range_update_gpu_range(struct amdgpu_svm *svm, struct amdgpu_svm_
 int amdgpu_svm_range_update_mapping(struct amdgpu_svm *svm, struct amdgpu_svm_range *range,
 				    const struct amdgpu_svm_attrs *attrs, bool read_only, bool intr,
 				    bool wait, bool flush_tlb);
+bool amdgpu_svm_range_dequeue_locked(struct amdgpu_svm *svm, struct list_head *work_list,
+				     struct amdgpu_svm_range_op_ctx *op_ctx);
+void amdgpu_svm_range_put_if_dequeued(struct amdgpu_svm *svm, struct amdgpu_svm_range *range);
+void amdgpu_svm_range_unqueue(struct amdgpu_svm *svm, struct amdgpu_svm_range *range);
+void amdgpu_svm_range_remove(struct amdgpu_svm *svm, struct amdgpu_svm_range *range,
+			     struct drm_gpusvm_ctx *ctx);
 int amdgpu_svm_range_map_attrs(struct amdgpu_svm *svm, const struct amdgpu_svm_attrs *attrs,
 			       unsigned long start, unsigned long end);
 int amdgpu_svm_range_zap_ptes(struct amdgpu_svm *svm, struct amdgpu_svm_range *range,
@@ -150,5 +156,9 @@ amdgpu_svm_range_find_or_insert(struct amdgpu_svm *svm, unsigned long addr,
 				struct drm_gpusvm_ctx *ctx);
 int amdgpu_svm_range_get_pages(struct amdgpu_svm *svm, struct drm_gpusvm_range *range,
 			       struct drm_gpusvm_ctx *ctx);
+bool amdgpu_svm_range_notifier_event_begin(struct amdgpu_svm *svm, struct drm_gpusvm_range *range,
+					   const struct mmu_notifier_range *mmu_range);
+int amdgpu_svm_range_invalidate_interval(struct amdgpu_svm *svm, unsigned long start_page,
+					 unsigned long last_page);
 
 #endif /* __AMDGPU_SVM_RANGE_H__ */
Signature · 1 line
2.53.0
author
#9 lore raw

PATCH v11 9/22 drm/amdgpu: add SVM notifier invalidate callback

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Handle invalidation in two phases: zap affected GPU mappings and flush translations before releasing their DMA mappings and queuing garbage collection. Do not use an IH timestamp checkpoint to classify retry
faults: hardware timestamps can reset with GFXOFF and differ by engine.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c | 31 +++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h |  3 ++
 2 files changed, 34 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c +31 -0
index 3b6db15bae680..f201105e94c53 100644
@@ -659,3 +659,34 @@ void amdgpu_svm_range_unqueue(struct amdgpu_svm *svm, struct amdgpu_svm_range *r
 	if (put)
 		drm_gpusvm_range_put(&range->base);
 }
+
+/**
+ * amdgpu_svm_range_invalidate() - MMU notifier invalidate_ranges callback
+ * @svm: The SVM context.
+ * @notifier: The GPU SVM notifier covering the invalidated ranges.
+ * @mmu_range: The MMU notifier range describing the event.
+ * @first: First GPU SVM range in the affected interval.
+ * @adj_start: Adjusted start address of the affected interval.
+ * @adj_end: Adjusted end address of the affected interval.
+ *
+ * Dispatch the two phase notifier handling across every range in
+ * [@adj_start, @adj_end): run the begin phase for all ranges, then
+ * the end phase.
+ */
+void amdgpu_svm_range_invalidate(struct amdgpu_svm *svm, struct drm_gpusvm_notifier *notifier,
+				 const struct mmu_notifier_range *mmu_range,
+				 struct drm_gpusvm_range *first, u64 adj_start, u64 adj_end)
+{
+	struct drm_gpusvm_range *r;
+	bool needs_flush = false;
+
+	r = first;
+	drm_gpusvm_for_each_range(r, notifier, adj_start, adj_end)
+		needs_flush |= amdgpu_svm_range_notifier_event_begin(svm, r, mmu_range);
+	if (needs_flush)
+		amdgpu_svm_flush_tlb(svm);
+
+	r = first;
+	drm_gpusvm_for_each_range(r, notifier, adj_start, adj_end)
+		amdgpu_svm_range_notifier_event_end(svm, r, mmu_range);
+}
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.h +3 -0
index 82ec0c769d25b..3de80ffe88e80 100644
@@ -156,6 +156,9 @@ amdgpu_svm_range_find_or_insert(struct amdgpu_svm *svm, unsigned long addr,
 				struct drm_gpusvm_ctx *ctx);
 int amdgpu_svm_range_get_pages(struct amdgpu_svm *svm, struct drm_gpusvm_range *range,
 			       struct drm_gpusvm_ctx *ctx);
+void amdgpu_svm_range_invalidate(struct amdgpu_svm *svm, struct drm_gpusvm_notifier *notifier,
+				 const struct mmu_notifier_range *mmu_range,
+				 struct drm_gpusvm_range *first, u64 adj_start, u64 adj_end);
 bool amdgpu_svm_range_notifier_event_begin(struct amdgpu_svm *svm, struct drm_gpusvm_range *range,
 					   const struct mmu_notifier_range *mmu_range);
 int amdgpu_svm_range_invalidate_interval(struct amdgpu_svm *svm, unsigned long start_page,
Signature · 1 line
2.53.0
author
#10 lore raw

PATCH v11 10/22 drm/amdgpu: implement SVM initialization and lifecycle

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Initialize the SVM context, attribute tree, work queues and embedded GPUSVM state. Register the driver's structural lock and range/notifier operations, and manage the context lifetime with kref references.

Initialize each range's device-owned pages cache and release it from the range destructor. Select the XNACK mode from device capabilities and reject unsupported modes. Closing the context marks it exiting, flushes GC work and drains retry faults before final teardown.

Dispatch attribute changes to invalidation or mapping, preserving access checks and returning compute TLB flush errors. Treat SYSMEM as an active prefetch target, including repeated requests with unchanged attributes. Revoking access must not restore a mapping because a prefetch attribute remains set.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c | 600 ++++++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c  |   2 +-
 2 files changed, 601 insertions(+), 1 deletion(-)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c
drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c new file +600 -0
new file mode 100644
index 0000000000000..24d9f90941f06
@@ -0,0 +1,600 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+/*
+ * Copyright 2026 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#include <linux/sched/mm.h>
+#include <linux/uaccess.h>
+#include <linux/xarray.h>
+
+#include <drm/drm_file.h>
+
+#include "amdgpu.h"
+#include "amdgpu_ih.h"
+#include "amdgpu_reset.h"
+#include "amdgpu_svm.h"
+#include "amdgpu_svm_attr.h"
+#include "amdgpu_svm_fault.h"
+#include "amdgpu_svm_range.h"
+#include "amdgpu_vm.h"
+
+#if IS_ENABLED(CONFIG_DRM_AMDGPU_SVM)
+
+#define AMDGPU_SVM_MAX_ATTRS 64
+#define AMDGPU_SVM_DEFAULT_SVM_NOTIFIER_SIZE 512
+
+static const unsigned long amdgpu_svm_chunk_sizes[] = {
+	SZ_2M,
+	SZ_64K,
+	SZ_4K,
+};
+
+#define AMDGPU_SVM_GC_WQ_NAME "amdgpu_svm_gc"
+#define XNACK_OFF(svm) (!(svm)->xnack_enabled)
+#define XNACK_ON(svm) ((svm)->xnack_enabled)
+
+/**
+ * amdgpu_svm_invalidate() - drm_gpusvm invalidate callback
+ * @gpusvm: The drm_gpusvm instance.
+ * @notifier: The GPU SVM notifier reporting the event.
+ * @mmu_range: The MMU notifier range describing the invalidation.
+ *
+ * Clamp the event to the notifier window, find the first affected range and
+ * invalidate the affected GPU mappings.
+ */
+static void amdgpu_svm_invalidate(struct drm_gpusvm *gpusvm, struct drm_gpusvm_notifier *notifier,
+				  const struct mmu_notifier_range *mmu_range)
+{
+	struct amdgpu_svm *svm = to_amdgpu_svm(gpusvm);
+	struct drm_gpusvm_range *first;
+	u64 adj_start = mmu_range->start, adj_end = mmu_range->end;
+
+	amdgpu_svm_assert_in_notifier(svm);
+
+	pr_debug("INVALIDATE: pasid=%u, gpusvm=%p, seqno=%lu, [0x%016lx-0x%016lx]-0x%lx, ev=%d\n",
+		 svm->vm->pasid, &svm->gpusvm, notifier->notifier.invalidate_seq, mmu_range->start,
+		 mmu_range->end, mmu_range->end - mmu_range->start, mmu_range->event);
+
+	if (mmu_range->event == MMU_NOTIFY_RELEASE)
+		return;
+	if (atomic_read(&svm->exiting))
+		return;
+
+	adj_start = max(drm_gpusvm_notifier_start(notifier), adj_start);
+	adj_end = min(drm_gpusvm_notifier_end(notifier), adj_end);
+
+	first = drm_gpusvm_range_find(notifier, adj_start, adj_end);
+	if (!first)
+		return;
+
+	amdgpu_svm_range_invalidate(svm, notifier, mmu_range, first, adj_start, adj_end);
+}
+
+static struct drm_gpusvm_range *amdgpu_svm_range_alloc(struct drm_gpusvm *gpusvm)
+{
+	struct amdgpu_svm_range *range;
+
+	range = kzalloc_obj(*range, GFP_KERNEL);
+	if (!range)
+		return NULL;
+
+	drm_gpusvm_init_pages(&range->pages, adev_to_drm(to_amdgpu_svm(gpusvm)->adev));
+	INIT_LIST_HEAD(&range->work_node);
+	range->pending_start_page = ULONG_MAX;
+	return &range->base;
+}
+
+static void amdgpu_svm_range_free(struct drm_gpusvm_range *range)
+{
+	struct amdgpu_svm_range *svm_range = to_amdgpu_svm_range(range);
+	unsigned long npages = (drm_gpusvm_range_end(range) - drm_gpusvm_range_start(range)) >>
+			       PAGE_SHIFT;
+
+	drm_gpusvm_free_pages(range->gpusvm, &svm_range->pages, npages);
+	kfree(svm_range);
+}
+
+static const struct drm_gpusvm_ops amdgpu_gpusvm_ops = {
+	.range_alloc = amdgpu_svm_range_alloc,
+	.range_free = amdgpu_svm_range_free,
+	.invalidate = amdgpu_svm_invalidate,
+};
+
+static void amdgpu_svm_release(struct kref *ref)
+{
+	kfree(container_of(ref, struct amdgpu_svm, refcount));
+}
+
+/**
+ * amdgpu_svm_put() - Drop a reference on an SVM context
+ * @svm: The SVM context.
+ *
+ * Release a reference taken on @svm and free it once the last reference is
+ * dropped.
+ */
+void amdgpu_svm_put(struct amdgpu_svm *svm)
+{
+	if (svm)
+		kref_put(&svm->refcount, amdgpu_svm_release);
+}
+
+/**
+ * amdgpu_svm_lookup_by_pasid() - Find the SVM context for a PASID
+ * @adev: The amdgpu device.
+ * @pasid: The PASID to look up.
+ *
+ * Look up the VM bound to @pasid and return its SVM context with a reference
+ * taken. The caller must drop it with amdgpu_svm_put().
+ *
+ * Return: The referenced SVM context, or %NULL if none is bound.
+ */
+struct amdgpu_svm *amdgpu_svm_lookup_by_pasid(struct amdgpu_device *adev, u32 pasid)
+{
+	struct amdgpu_svm *svm = NULL;
+	struct amdgpu_fpriv *fpriv;
+	struct amdgpu_vm *vm;
+	unsigned long irqflags;
+
+	amdgpu_pasid_lock(&irqflags);
+	fpriv = amdgpu_pasid_get_fpriv_locked(pasid);
+	vm = fpriv ? &fpriv->vm : NULL;
+	if (vm && vm->svm) {
+		svm = vm->svm;
+		kref_get(&svm->refcount);
+	}
+	amdgpu_pasid_unlock(irqflags);
+
+	return svm;
+}
+
+static int amdgpu_svm_op_set_attr(struct amdgpu_vm *vm, u64 start, u64 size, u32 nattr,
+				  const struct drm_amdgpu_svm_attribute *attrs)
+{
+	struct amdgpu_svm *svm = vm->svm;
+
+	amdgpu_svm_sync_work(svm);
+
+	return amdgpu_svm_attr_set(svm->attr_tree, start, size, nattr, attrs);
+}
+
+static int amdgpu_svm_op_get_attr(struct amdgpu_vm *vm, u64 start, u64 size, u32 nattr,
+				  struct drm_amdgpu_svm_attribute *attrs, u64 *out_size)
+{
+	amdgpu_svm_sync_work(vm->svm);
+
+	return amdgpu_svm_attr_get(vm->svm->attr_tree, start, size, nattr, attrs, out_size);
+}
+
+static int amdgpu_svm_op_reset_attr(struct amdgpu_vm *vm, u64 start, u64 size)
+{
+	struct amdgpu_svm *svm = vm->svm;
+	unsigned long start_page = start >> PAGE_SHIFT;
+	unsigned long last_page = (start + size - 1) >> PAGE_SHIFT;
+
+	amdgpu_svm_sync_work(svm);
+
+	return amdgpu_svm_attr_reset(svm->attr_tree, start_page, last_page);
+}
+
+/**
+ * attr_change_trigger() - Classify what an attribute update changed
+ * @old_attrs: Attributes before the update.
+ * @new_attrs: Attributes after the update.
+ *
+ * Compare the two attribute sets and return an
+ * amdgpu_svm_attr_change_trigger bitmask describing which aspects changed:
+ * access, PTE flags, mapping flags, location, granularity, prefetch.
+ *
+ * Return: The trigger bitmask.
+ */
+static u32 attr_change_trigger(const struct amdgpu_svm_attrs *old_attrs,
+			       const struct amdgpu_svm_attrs *new_attrs)
+{
+	u32 trigger = 0;
+	u32 changed_flags = old_attrs->flags ^ new_attrs->flags;
+
+	if (old_attrs->access != new_attrs->access)
+		trigger |= AMDGPU_SVM_ATTR_TRIGGER_ACCESS_CHANGE;
+	if (changed_flags & AMDGPU_SVM_PTE_FLAG_MASK)
+		trigger |= AMDGPU_SVM_ATTR_TRIGGER_PTE_FLAG_CHANGE;
+	if (changed_flags & AMDGPU_SVM_MAPPING_FLAG_MASK)
+		trigger |= AMDGPU_SVM_ATTR_TRIGGER_MAPPING_FLAG_CHANGE;
+	if (old_attrs->preferred_loc != new_attrs->preferred_loc ||
+	    old_attrs->prefetch_loc != new_attrs->prefetch_loc)
+		trigger |= AMDGPU_SVM_ATTR_TRIGGER_LOCATION_CHANGE;
+	if (old_attrs->granularity != new_attrs->granularity)
+		trigger |= AMDGPU_SVM_ATTR_TRIGGER_GRANULARITY_CHANGE;
+	if (new_attrs->prefetch_loc != AMDGPU_SVM_LOCATION_UNDEFINED)
+		trigger |= AMDGPU_SVM_ATTR_TRIGGER_PREFETCH;
+
+	return trigger;
+}
+
+/**
+ * amdgpu_svm_apply_attr_change() - React to an attribute change on a range
+ * @svm: The SVM context.
+ * @old_attrs: Attributes before the change.
+ * @new_attrs: Attributes after the change.
+ * @start_page: First page of the affected interval.
+ * @last_page: Last page of the affected interval.
+ *
+ * Classify the change and act on it: when XNACK is on and the change affects
+ * existing GPU mappings, invalidate the interval; when the new attributes
+ * request a prefetch, map / remap the interval with the new attributes.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int amdgpu_svm_apply_attr_change(struct amdgpu_svm *svm, const struct amdgpu_svm_attrs *old_attrs,
+				 const struct amdgpu_svm_attrs *new_attrs, unsigned long start_page,
+				 unsigned long last_page)
+{
+	bool old_access, new_access;
+	bool needs_invalidate = false;
+	bool needs_mapping = false;
+	u32 trigger;
+	int ret;
+
+	amdgpu_svm_assert_locked(svm);
+
+	if (!start_page && !last_page)
+		return 0;
+
+	trigger = attr_change_trigger(old_attrs, new_attrs);
+	old_access = amdgpu_svm_attr_has_access(old_attrs->access);
+	new_access = amdgpu_svm_attr_has_access(new_attrs->access);
+	if (XNACK_ON(svm) && (trigger & AMDGPU_SVM_ATTR_TRIGGER_NEED_INVALIDATE))
+		needs_invalidate = true;
+
+	if (trigger & AMDGPU_SVM_ATTR_TRIGGER_PREFETCH)
+		needs_mapping = true;
+
+	if (!trigger && !needs_mapping)
+		return 0;
+
+	pr_debug("attr change trigger=0x%x old=%d new=%d [0x%lx-0x%lx]-0x%lx, xnack=%d\n", trigger,
+		 old_access, new_access, start_page, last_page, last_page - start_page + 1,
+		 svm->xnack_enabled ? 1 : 0);
+
+	if (needs_invalidate) {
+		pr_debug("attr change invalidate [0x%lx-0x%lx]-0x%lx trigger=0x%x\n", start_page,
+			 last_page, last_page - start_page + 1, trigger);
+		ret = amdgpu_svm_range_invalidate_interval(svm, start_page, last_page);
+		if (ret) {
+			pr_err_ratelimited("failed to invalidate range for attr change: [0x%lx-0x%lx], ret=%d\n",
+					   start_page, last_page, ret);
+			return ret;
+		}
+	}
+
+	if (!new_access || !needs_mapping)
+		return 0;
+
+	return amdgpu_svm_range_map_attrs(svm, new_attrs, start_page << PAGE_SHIFT,
+					  (last_page + 1) << PAGE_SHIFT);
+}
+
+bool amdgpu_svm_devmem_possible(struct amdgpu_svm *svm)
+{
+	if (svm->adev->apu_prefer_gtt)
+		return false;
+
+	/* TODO: add amdgpu_pagemap_capable() */
+
+	return false;
+}
+
+/**
+ * amdgpu_svm_default_xnack_enabled() - Whether XNACK defaults to on for the HW
+ * @adev: The amdgpu device.
+ *
+ * Decide the default retry fault (XNACK) policy from the GC IP version and
+ * platform constraints.
+ *
+ * Return: true if XNACK should default to enabled.
+ */
+static bool amdgpu_svm_default_xnack_enabled(struct amdgpu_device *adev)
+{
+	u32 gc_ver = amdgpu_ip_version(adev, GC_HWIP, 0);
+
+	if (gc_ver < IP_VERSION(9, 0, 1))
+		return false;
+	if (!amdgpu_sriov_xnack_support(adev))
+		return false;
+
+	if (adev->gmc.noretry)
+		return false;
+
+	switch (gc_ver) {
+	case IP_VERSION(9, 4, 2):
+	case IP_VERSION(9, 4, 3):
+	case IP_VERSION(9, 4, 4):
+	case IP_VERSION(9, 5, 0):
+		return true;
+	default:
+		break;
+	}
+	if (gc_ver >= IP_VERSION(10, 1, 1))
+		return false;
+
+	return true;
+}
+
+int amdgpu_svm_flush_tlb(struct amdgpu_svm *svm)
+{
+	struct amdgpu_fpriv *fpriv = container_of(svm->vm, struct amdgpu_fpriv, vm);
+	struct amdgpu_device *adev = svm->adev;
+	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
+	u32 xcc_mask;
+	int r;
+
+	if (!xcp_mgr || fpriv->xcp_id >= xcp_mgr->num_xcps ||
+	    amdgpu_xcp_get_inst_details(&xcp_mgr->xcp[fpriv->xcp_id], AMDGPU_XCP_GFX, &xcc_mask))
+		xcc_mask = (1U << NUM_XCC(adev->gfx.xcc_mask)) - 1;
+
+	r = amdgpu_vm_flush_compute_tlb(adev, svm->vm, TLB_FLUSH_HEAVYWEIGHT, xcc_mask);
+	if (r)
+		dev_err(adev->dev, "SVM TLB flush failed (%d), GPU may use stale translations\n",
+			r);
+	return r;
+}
+
+static int amdgpu_svm_work_init(struct amdgpu_svm *svm, void (*gc_work_func)(struct work_struct *));
+static void amdgpu_svm_work_fini(struct amdgpu_svm *svm);
+
+/**
+ * amdgpu_svm_init_xnack_mode() - Resolve the requested XNACK mode
+ * @adev: The amdgpu device.
+ * @mode: The requested XNACK mode.
+ * @xnack_enabled: Output, set to the resolved enable state.
+ *
+ * Validate @mode against the hardware default: DEFAULT follows the HW policy,
+ * ON is rejected if the HW does not support it, OFF always disables.
+ *
+ * Return: 0 on success, -EOPNOTSUPP if ON is unavailable, -EINVAL on a bad
+ * mode.
+ */
+static int amdgpu_svm_init_xnack_mode(struct amdgpu_device *adev, enum amdgpu_svm_xnack_mode mode,
+				      bool *xnack_enabled)
+{
+	bool xnack_default = amdgpu_svm_default_xnack_enabled(adev);
+
+	switch (mode) {
+	case AMDGPU_SVM_XNACK_DEFAULT:
+		*xnack_enabled = xnack_default;
+		break;
+	case AMDGPU_SVM_XNACK_ON:
+		if (!xnack_default) {
+			pr_err("xnack on not available (mode=%d)\n", mode);
+			*xnack_enabled = xnack_default;
+			return -EOPNOTSUPP;
+		}
+		*xnack_enabled = true;
+		break;
+	case AMDGPU_SVM_XNACK_OFF:
+		*xnack_enabled = false;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+/**
+ * amdgpu_svm_init_with_ops() - Initialize the SVM core with driver callbacks
+ * @svm: The SVM context to initialize.
+ * @gc_work_func: Work function draining the garbage collector.
+ *
+ * Set up the work queues, attribute tree and the embedded drm_gpusvm (with
+ * the 2M/64K/4K chunk sizes and the driver lock), wiring the supplied
+ * callbacks.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+static int
+amdgpu_svm_init_with_ops(struct amdgpu_svm *svm, void (*gc_work_func)(struct work_struct *))
+{
+	struct amdgpu_device *adev = svm->adev;
+	int ret;
+
+	ret = amdgpu_svm_work_init(svm, gc_work_func);
+	if (ret)
+		return ret;
+
+	svm->attr_tree = amdgpu_svm_attr_tree_create(svm);
+	if (!svm->attr_tree) {
+		ret = -ENOMEM;
+		goto err_work_fini;
+	}
+
+	ret = drm_gpusvm_init(&svm->gpusvm, "AMDGPU SVM", current->mm, 0,
+			      adev->vm_manager.max_pfn << AMDGPU_GPU_PAGE_SHIFT,
+			      AMDGPU_SVM_DEFAULT_SVM_NOTIFIER_SIZE * SZ_1M, &amdgpu_gpusvm_ops,
+			      amdgpu_svm_chunk_sizes, ARRAY_SIZE(amdgpu_svm_chunk_sizes));
+
+	if (ret)
+		goto err_attr_tree_destroy;
+
+	drm_gpusvm_driver_set_lock(&svm->gpusvm, &svm->svm_lock);
+
+	return 0;
+
+err_attr_tree_destroy:
+	amdgpu_svm_attr_tree_destroy(svm->attr_tree);
+err_work_fini:
+	amdgpu_svm_work_fini(svm);
+	return ret;
+}
+
+static void amdgpu_svm_gc_work_func(struct work_struct *w);
+
+/**
+ * amdgpu_svm_init_compute() - Create the SVM context for a compute VM
+ * @adev: The amdgpu device.
+ * @vm: The VM to attach the SVM context to.
+ * @xnack_mode: The requested XNACK mode.
+ *
+ * Allocate and initialize an SVM context for @vm (idempotent if one already
+ * exists), resolving the XNACK mode and wiring the compute callbacks. XNACK
+ * off is not supported yet.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+static int amdgpu_svm_init_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm,
+				   enum amdgpu_svm_xnack_mode xnack_mode)
+{
+	struct amdgpu_svm *svm;
+	int ret;
+
+	if (vm->svm)
+		return 0;
+
+	svm = kzalloc_obj(*svm, GFP_KERNEL);
+	if (!svm)
+		return -ENOMEM;
+
+	kref_init(&svm->refcount);
+	svm->adev = adev;
+	svm->vm = vm;
+	svm->default_granularity = min_t(u8, amdgpu_svm_default_granularity, 0x1B);
+	atomic_set(&svm->exiting, 0);
+
+	ret = amdgpu_svm_init_xnack_mode(adev, xnack_mode, &svm->xnack_enabled);
+	if (ret)
+		goto err_free;
+
+	if (svm->xnack_enabled) {
+		ret = amdgpu_svm_init_with_ops(svm, amdgpu_svm_gc_work_func);
+	} else {
+		pr_err("xnack off is not supported yet\n");
+		ret = -EOPNOTSUPP;
+	}
+
+	if (ret)
+		goto err_free;
+
+	pr_debug("AMDGPU SVM initialized: default granularity 0x%lx bytes, xnack: %s\n",
+		 1UL << (svm->default_granularity + PAGE_SHIFT),
+		 svm->xnack_enabled ? "enabled" : "disabled");
+
+	vm->svm = svm;
+	return 0;
+
+err_free:
+	kfree(svm);
+	return ret;
+}
+
+/**
+ * amdgpu_svm_init() - Initialize SVM for a VM
+ * @adev: The amdgpu device.
+ * @vm: The VM to enable SVM on.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int amdgpu_svm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
+{
+	/* graphics svm init maybe different */
+
+	return amdgpu_svm_init_compute(adev, vm, AMDGPU_SVM_XNACK_DEFAULT);
+}
+
+/**
+ * amdgpu_svm_drain_retry_fault() - Wait for retry faults to drain
+ * @adev: The amdgpu device.
+ *
+ * Wait until the interrupt handler has processed up to the current checkpoint
+ * on the relevant IH rings, so no stale retry faults remain in flight. Skips
+ * draining during a GPU reset or if the reset domain cannot be entered.
+ */
+static void amdgpu_svm_drain_retry_fault(struct amdgpu_device *adev)
+{
+	if (!adev)
+		return;
+
+	if (amdgpu_in_reset(adev))
+		return;
+
+	if (!down_read_trylock(&adev->reset_domain->sem))
+		return;
+
+	amdgpu_ih_wait_on_checkpoint_process_ts(adev, adev->irq.retry_cam_enabled ? &adev->irq.ih :
+										    &adev->irq.ih1);
+	if (adev->irq.retry_cam_enabled)
+		amdgpu_ih_wait_on_checkpoint_process_ts(adev, &adev->irq.ih_soft);
+
+	up_read(&adev->reset_domain->sem);
+}
+
+/**
+ * amdgpu_svm_close() - Begin SVM teardown for a VM
+ * @vm: The VM whose SVM context is closing.
+ *
+ * Mark the context as exiting (once), flush pending GC work and drain
+ * in-flight retry faults. Safe to call on a VM without an SVM context.
+ */
+void amdgpu_svm_close(struct amdgpu_vm *vm)
+{
+	struct amdgpu_svm *svm = vm->svm;
+
+	if (!svm)
+		return;
+
+	if (atomic_xchg(&svm->exiting, 1))
+		return;
+
+	amdgpu_svm_sync_work(svm);
+	amdgpu_svm_drain_retry_fault(svm->adev);
+}
+
+/**
+ * amdgpu_svm_fini() - Finalize and release a VM's SVM context
+ * @vm: The VM whose SVM context is being torn down.
+ *
+ * Close the context, tear down the embedded drm_gpusvm under the SVM lock,
+ * destroy the attribute tree and work queues, and drop the context
+ * reference. Safe to call on a VM without an SVM context.
+ */
+void amdgpu_svm_fini(struct amdgpu_vm *vm)
+{
+	struct amdgpu_svm *svm = vm->svm;
+
+	if (!svm)
+		return;
+
+	amdgpu_svm_close(vm);
+	amdgpu_svm_lock(svm);
+	drm_gpusvm_fini(&svm->gpusvm);
+	amdgpu_svm_unlock(svm);
+
+	amdgpu_svm_attr_tree_destroy(svm->attr_tree);
+	amdgpu_svm_work_fini(svm);
+	vm->svm = NULL;
+	amdgpu_svm_put(svm);
+}
+
+bool amdgpu_svm_is_enabled(struct amdgpu_vm *vm)
+{
+	return vm->svm;
+}
+
+#endif /* CONFIG_DRM_AMDGPU_SVM */
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +1 -1
index 9fcafed0b598c..7b77577aa5621 100644
@@ -1821,7 +1821,7 @@ int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
  * @adev: amdgpu_device pointer
  * @vm: requested vm
  * @flush_type: flush type
- * @xcc_mask: mask of XCCs that belong to the compute partition in need of a TLB flush.
+ * @xcc_mask: mask of logical XCC indices to flush
  *
  * Flush TLB if needed for a compute VM.
  *
Signature · 1 line
2.53.0
author
#11 lore raw

PATCH v11 11/22 drm/amdgpu: add SVM ioctl entry and fault handler module

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Add ioctl entry point and fault handling:

amdgpu_svm.c additions:
- amdgpu_svm_copy_attrs: memdup_user for attribute array
- amdgpu_svm_garbage_collector: dequeue and remove unmapped ranges
- amdgpu_svm_clean_queue: drain work list releasing refs
- amdgpu_svm_gc_work_func: static GC work handler
- amdgpu_svm_gc_init/fini/flush: static workqueue lifecycle
- amdgpu_svm_work_init/work_fini: wrappers for GC lifecycle
- amdgpu_svm_sync_work: wrapper for GC flush
- amdgpu_gem_svm_ioctl: validate args, dispatch SET_ATTR/GET_ATTR/RESET_ATTR with copy_to_user for GET

amdgpu_svm_fault.c (new):
- fault_check_allowed: VMA permission check for fault address
- fault_get_unregistered_attrs: create default attr range for faulting address not covered by explicit attributes, bounded by VMA and granularity alignment
- fault_map_range: fault mapping pipeline with retry, GC, permission check, find/insert range, timestamp dedup, validity check, get_pages, update_mapping.
- amdgpu_svm_handle_fault: top level entry point from VM fault path

The VM fault path treats zero as a successfully serviced or benignly dropped fault. Return an error for faults which cannot be serviced so the caller installs AMDGPU_VM_NORETRY_FLAGS and terminates the faulting wave.

Validate ioctl address-space bounds without overflow and enforce per-GPU access policy during fault recovery. Missing VMAs are errors, and a write fault must still have writable pages after get-pages fallback. Only ALLOW_MIGRATE permits VRAM migration.

On terminal GC removal, clear pending UNMAP work under work_lock before releasing the processing reference. An invalidation can add work between dequeue and removal; after removal that work is covered and must not cause the range to be queued for a second deletion.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c       | 196 ++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.c | 424 ++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.h |  38 ++
 3 files changed, 658 insertions(+)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.h
drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c +196 -0
index 24d9f90941f06..cf9c27cb0080f 100644
@@ -597,4 +597,200 @@ bool amdgpu_svm_is_enabled(struct amdgpu_vm *vm)
 	return vm->svm;
 }
 
+static int amdgpu_svm_copy_attrs(const struct drm_amdgpu_gem_svm *args,
+				 struct drm_amdgpu_svm_attribute **attrs, size_t *size)
+{
+	if (!args->nattr || args->nattr > AMDGPU_SVM_MAX_ATTRS)
+		return -EINVAL;
+	if (!args->attrs_ptr)
+		return -EINVAL;
+
+	*size = args->nattr * sizeof(**attrs);
+	*attrs = memdup_user(u64_to_user_ptr(args->attrs_ptr), *size);
+
+	return PTR_ERR_OR_ZERO(*attrs);
+}
+
+/**
+ * amdgpu_svm_garbage_collector() - Remove ranges queued for unmapping
+ * @svm: The SVM context.
+ *
+ * Drain the GC list: for each queued range, remove it from the gpusvm trees
+ * and drop the reference held while queued. Caller must hold the SVM lock.
+ *
+ * Return: 0 on success.
+ */
+int amdgpu_svm_garbage_collector(struct amdgpu_svm *svm)
+{
+	struct amdgpu_svm_range_op_ctx op_ctx;
+
+	amdgpu_svm_assert_locked(svm);
+
+	spin_lock(&svm->work_lock);
+	while (amdgpu_svm_range_dequeue_locked(svm, &svm->gc.list, &op_ctx)) {
+		spin_unlock(&svm->work_lock);
+
+		WARN_ON(!(op_ctx.pending_ops & AMDGPU_SVM_RANGE_OP_UNMAP));
+
+		drm_gpusvm_range_remove(&svm->gpusvm, &op_ctx.range->base);
+
+		spin_lock(&svm->work_lock);
+		op_ctx.range->pending_ops = AMDGPU_SVM_RANGE_OP_NONE;
+		spin_unlock(&svm->work_lock);
+
+		amdgpu_svm_range_put_if_dequeued(svm, op_ctx.range);
+		spin_lock(&svm->work_lock);
+	}
+	spin_unlock(&svm->work_lock);
+	return 0;
+}
+
+/**
+ * amdgpu_svm_clean_queue() - Drain a work list, releasing range references
+ * @svm: The SVM context.
+ * @work_list: The work list to drain.
+ *
+ * Dequeue every range on @work_list and drop the reference held while it was
+ * queued, without performing any unmapping. Used during teardown.
+ */
+void amdgpu_svm_clean_queue(struct amdgpu_svm *svm, struct list_head *work_list)
+{
+	struct amdgpu_svm_range_op_ctx op_ctx;
+
+	spin_lock(&svm->work_lock);
+	while (amdgpu_svm_range_dequeue_locked(svm, work_list, &op_ctx)) {
+		spin_unlock(&svm->work_lock);
+		amdgpu_svm_range_put_if_dequeued(svm, op_ctx.range);
+		spin_lock(&svm->work_lock);
+	}
+	spin_unlock(&svm->work_lock);
+}
+
+static void amdgpu_svm_gc_work_func(struct work_struct *w)
+{
+	struct amdgpu_svm_gc *gc = container_of(w, struct amdgpu_svm_gc, work);
+	struct amdgpu_svm *svm = container_of(gc, struct amdgpu_svm, gc);
+
+	amdgpu_svm_lock(svm);
+	amdgpu_svm_garbage_collector(svm);
+	amdgpu_svm_unlock(svm);
+}
+
+static int amdgpu_svm_gc_init(struct amdgpu_svm *svm, void (*gc_work_func)(struct work_struct *))
+{
+	svm->gc.wq =
+		alloc_workqueue(AMDGPU_SVM_GC_WQ_NAME, WQ_UNBOUND | WQ_HIGHPRI | WQ_MEM_RECLAIM, 0);
+	if (!svm->gc.wq)
+		return -ENOMEM;
+
+	INIT_LIST_HEAD(&svm->gc.list);
+	INIT_WORK(&svm->gc.work, gc_work_func);
+
+	return 0;
+}
+
+static void amdgpu_svm_gc_fini(struct amdgpu_svm *svm)
+{
+	flush_work(&svm->gc.work);
+	amdgpu_svm_clean_queue(svm, &svm->gc.list);
+	destroy_workqueue(svm->gc.wq);
+	svm->gc.wq = NULL;
+}
+
+static void amdgpu_svm_gc_flush(struct amdgpu_svm *svm)
+{
+	flush_work(&svm->gc.work);
+}
+
+static int amdgpu_svm_work_init(struct amdgpu_svm *svm, void (*gc_work_func)(struct work_struct *))
+{
+	int ret;
+
+	init_rwsem(&svm->svm_lock);
+	spin_lock_init(&svm->work_lock);
+
+	ret = amdgpu_svm_gc_init(svm, gc_work_func);
+	if (ret)
+		return ret;
+
+	return 0;
+}
+
+static void amdgpu_svm_work_fini(struct amdgpu_svm *svm)
+{
+	amdgpu_svm_gc_fini(svm);
+}
+
+void amdgpu_svm_sync_work(struct amdgpu_svm *svm)
+{
+	amdgpu_svm_gc_flush(svm);
+}
+
+/**
+ * amdgpu_gem_svm_ioctl() - SVM GEM ioctl entry point
+ * @dev: The DRM device.
+ * @data: The ioctl argument (struct drm_amdgpu_gem_svm).
+ * @filp: The DRM file.
+ *
+ * Validate the arguments and dispatch to the SET_ATTR / GET_ATTR /
+ * RESET_ATTR operation, copying results back to user space for GET.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int amdgpu_gem_svm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
+{
+	struct amdgpu_fpriv *fpriv = filp->driver_priv;
+	struct drm_amdgpu_gem_svm *args = data;
+	struct drm_amdgpu_svm_attribute *attrs = NULL;
+	struct amdgpu_vm *vm;
+	struct drm_gpusvm *gpusvm;
+	size_t attrs_size = 0;
+	int ret = 0;
+
+	pr_debug("ioctl op=%u va:[0x%llx-0x%llx)-0x%llx nattr=%u\n", args->operation,
+		 args->start_addr, args->start_addr + args->size, args->size, args->nattr);
+
+	vm = &fpriv->vm;
+	if (!amdgpu_svm_is_enabled(vm))
+		return -EOPNOTSUPP;
+
+	if ((args->start_addr & ~PAGE_MASK) || (args->size & ~PAGE_MASK))
+		return -EINVAL;
+
+	if (!args->start_addr || !args->size)
+		return -EINVAL;
+
+	gpusvm = &vm->svm->gpusvm;
+	if (args->start_addr < gpusvm->mm_start || args->size > gpusvm->mm_range ||
+	    args->start_addr - gpusvm->mm_start > gpusvm->mm_range - args->size)
+		return -EINVAL;
+
+	if (args->operation != AMDGPU_SVM_OP_RESET_ATTR) {
+		ret = amdgpu_svm_copy_attrs(args, &attrs, &attrs_size);
+		if (ret)
+			return ret;
+	}
+
+	switch (args->operation) {
+	case AMDGPU_SVM_OP_SET_ATTR:
+		ret = amdgpu_svm_op_set_attr(vm, args->start_addr, args->size, args->nattr, attrs);
+		break;
+	case AMDGPU_SVM_OP_GET_ATTR:
+		ret = amdgpu_svm_op_get_attr(vm, args->start_addr, args->size, args->nattr, attrs,
+					     &args->size);
+		if (!ret && copy_to_user(u64_to_user_ptr(args->attrs_ptr), attrs, attrs_size))
+			ret = -EFAULT;
+		break;
+	case AMDGPU_SVM_OP_RESET_ATTR:
+		ret = amdgpu_svm_op_reset_attr(vm, args->start_addr, args->size);
+		break;
+	default:
+		ret = -EINVAL;
+		break;
+	}
+
+	kvfree(attrs);
+	return ret;
+}
+
 #endif /* CONFIG_DRM_AMDGPU_SVM */
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.c new file +424 -0

424 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.h new file +38 -0
new file mode 100644
index 0000000000000..0e60c7ba179f8
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/*
+ * Copyright 2026 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#ifndef __AMDGPU_SVM_FAULT_H__
+#define __AMDGPU_SVM_FAULT_H__
+
+#include <linux/types.h>
+
+struct amdgpu_device;
+struct amdgpu_svm;
+struct amdgpu_svm_attr_range;
+struct amdgpu_svm_attrs;
+
+int amdgpu_svm_handle_fault(struct amdgpu_device *adev, u32 pasid, u64 fault_page,
+			    bool write_fault);
+
+#endif /* __AMDGPU_SVM_FAULT_H__ */
Signature · 1 line
2.53.0
author
#12 lore raw

PATCH v11 12/22 drm/amdgpu: integrate SVM into build system and VM fault path

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Add the default-disabled AMDGPU SVM configuration option and build its core, attribute, range and fault-handling objects when enabled. Register the SVM ioctl and connect context initialization and teardown to the compute VM lifecycle.

Route faults through the SVM handler when the VM has an SVM context; otherwise retain the existing KFD fault path. Keep disabled-build stubs so ordinary AMDGPU builds do not depend on SVM implementation objects.

---
 drivers/gpu/drm/amd/amdgpu/Kconfig      | 10 ++++++++++
 drivers/gpu/drm/amd/amdgpu/Makefile     |  4 ++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c |  6 +++++-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c  | 23 +++++++++++++++++++++--
 4 files changed, 40 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdgpu/Kconfig +10 -0
index 12e4a41bf1f04..68f519b3479db 100644
@@ -81,6 +81,16 @@ config DRM_AMDGPU_USERPTR
 	  This option selects CONFIG_HMM and CONFIG_HMM_MIRROR if it
 	  isn't already selected to enabled full userptr support.
 
+config DRM_AMDGPU_SVM
+	bool "Enable AMDGPU SVM support (experimental)"
+	depends on DRM_AMDGPU
+	depends on DEVICE_PRIVATE
+	select DRM_GPUSVM
+	select HMM_MIRROR
+	select MMU_NOTIFIER
+	help
+	  Experimental SVM support based on DRM GPUSVM.
+
 config DRM_AMD_ISP
 	bool "Enable AMD Image Signal Processor IP support"
 	depends on DRM_AMDGPU && ACPI
drivers/gpu/drm/amd/amdgpu/Makefile +4 -0
index 8687afc00c24c..ad84e57115428 100644
@@ -330,6 +330,10 @@ amdgpu-$(CONFIG_VGA_SWITCHEROO) += amdgpu_atpx_handler.o
 amdgpu-$(CONFIG_ACPI) += amdgpu_acpi.o
 amdgpu-$(CONFIG_HMM_MIRROR) += amdgpu_hmm.o
 
+# svm support
+amdgpu-$(CONFIG_DRM_AMDGPU_SVM) += amdgpu_svm.o amdgpu_svm_attr.o \
+	amdgpu_svm_fault.o amdgpu_svm_range.o
+
 include $(FULL_AMD_PATH)/pm/Makefile
 
 amdgpu-y += $(AMD_POWERPLAY_FILES)
drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +5 -1
index 541f02ab4d420..97059d12eb0a6 100644
@@ -50,6 +50,7 @@
 #include "amdgpu_ras.h"
 #include "amdgpu_reset.h"
 #include "amdgpu_sched.h"
+#include "amdgpu_svm.h"
 #include "amdgpu_xgmi.h"
 #include "amdgpu_userq.h"
 #include "amdgpu_userq_fence.h"
@@ -3124,7 +3125,10 @@ const struct drm_ioctl_desc amdgpu_ioctls_kms[] = {
 	DRM_IOCTL_DEF_DRV(AMDGPU_USERQ_WAIT, amdgpu_userq_wait_ioctl, DRM_AUTH|DRM_RENDER_ALLOW),
 	DRM_IOCTL_DEF_DRV(AMDGPU_GEM_LIST_HANDLES, amdgpu_gem_list_handles_ioctl, DRM_AUTH|DRM_RENDER_ALLOW),
 	DRM_IOCTL_DEF_DRV(AMDGPU_PROC_OPTIONS, amdgpu_proc_options_ioctl, DRM_AUTH|DRM_RENDER_ALLOW),
-	DRM_IOCTL_DEF_DRV(AMDGPU_UALINK_HANDLE, amdgpu_gem_ualink_handle_ioctl, DRM_AUTH|DRM_RENDER_ALLOW)
+	DRM_IOCTL_DEF_DRV(AMDGPU_UALINK_HANDLE, amdgpu_gem_ualink_handle_ioctl,
+			  DRM_AUTH | DRM_RENDER_ALLOW),
+	DRM_IOCTL_DEF_DRV(AMDGPU_GEM_SVM, amdgpu_gem_svm_ioctl,
+			  DRM_AUTH | DRM_RENDER_ALLOW),
 };
 
 static const struct drm_driver amdgpu_kms_driver = {
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +21 -2
index 7b77577aa5621..8831eb7c7cbc7 100644
@@ -45,6 +45,7 @@
 #include "amdgpu_xgmi.h"
 #include "amdgpu_dma_buf.h"
 #include "amdgpu_res_cursor.h"
+#include "amdgpu_svm.h"
 #include "kfd_svm.h"
 
 /**
@@ -2725,6 +2726,7 @@ int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 	int r, i;
 
 	vm->va = RB_ROOT_CACHED;
+	vm->svm = NULL;
 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
 		vm->reserved_vmid[i] = NULL;
 
@@ -2869,6 +2871,10 @@ int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
 	vm->is_compute_context = true;
 	vm->need_tlb_fence = true;
 
+	r = amdgpu_svm_init(adev, vm);
+	if (r)
+		goto unreserve_bo;
+
 unreserve_bo:
 	amdgpu_bo_unreserve(vm->root.bo);
 	return r;
@@ -2942,6 +2948,9 @@ void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
 	unsigned long flags;
 	int i;
 
+	amdgpu_svm_close(vm);
+	amdgpu_svm_fini(vm);
+
 	amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
 
 	root = amdgpu_bo_ref(vm->root.bo);
@@ -3211,6 +3220,7 @@ bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid,
 {
 	struct amdgpu_vm_update_params params;
 	bool is_compute_context = false;
+	bool use_amdgpu_svm = false;
 	uint64_t *dst, flags[AMDGPU_VM_MAX_LEVEL];
 	struct amdgpu_vm *vm;
 	struct drm_exec exec;
@@ -3230,6 +3240,7 @@ bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid,
 	}
 
 	is_compute_context = vm->is_compute_context;
+	use_amdgpu_svm = !!vm->svm;
 
 	if (is_compute_context) {
 		__label__ drm_exec_retry;
@@ -3241,8 +3252,16 @@ bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid,
 		 */
 		drm_exec_fini(&exec);
 
-		if (!svm_range_restore_pages(adev, pasid, vmid,
-					     node_id, addr >> PAGE_SHIFT, ts, write_fault))
+		if (use_amdgpu_svm)
+			r = amdgpu_svm_handle_fault(adev, pasid,
+						    addr >> PAGE_SHIFT,
+						    write_fault);
+		else
+			r = svm_range_restore_pages(adev, pasid, vmid, node_id,
+						    addr >> PAGE_SHIFT, ts,
+						    write_fault);
+
+		if (!r)
 			return true;
 
 		/* Re-acquire the VM lock, could be that the VM was freed in between. */
Signature · 1 line
2.53.0
author
#13 lore raw

PATCH v11 13/22 drm/amdgpu: make VM eviction lock read/write to match notifier lock

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Make the VM eviction lock read/write to match the drm_gpusvm notifier lock. This allows VM updates, MMU notifier invalidation and eviction to share the same rwsem.

Replace the VM eviction mutex with a selectable rwsem. Updates made with the root BO reserved take the read side. Updates without the root BO reservation take the write side, as does eviction. A VM using drm_gpusvm can use the notifier lock as its eviction lock.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c          |  9 +++++----
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h          |  8 ++++----
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm_internal.h | 12 ++++++++++--
 3 files changed, 19 insertions(+), 10 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +5 -4
index 8831eb7c7cbc7..6f7043bdd2020 100644
@@ -673,7 +673,7 @@ int amdgpu_vm_validate(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 	 * As soon as all page tables are in place we can start updating them
 	 * again.
 	 */
-	scoped_guard(mutex, &vm->eviction_lock)
+	scoped_guard(rwsem_write, vm->eviction_lock)
 		vm->evicting = false;
 
 	list_for_each_entry_safe(bo_base, tmp, &vm->always_valid.evicted,
@@ -734,7 +734,7 @@ bool amdgpu_vm_ready(struct amdgpu_vm *vm)
 
 	amdgpu_vm_assert_locked(vm);
 
-	scoped_guard(mutex, &vm->eviction_lock)
+	scoped_guard(rwsem_read, vm->eviction_lock)
 		ret = !vm->evicting;
 
 	ret &= list_empty(&vm->kernel.evicted);
@@ -2392,7 +2392,7 @@ bool amdgpu_vm_evictable(struct amdgpu_bo *bo)
 
 	/* Try to block ongoing updates */
 	vm = bo_base->vm;
-	scoped_cond_guard(mutex_try, return false, &vm->eviction_lock) {
+	scoped_cond_guard(rwsem_write_try, return false, vm->eviction_lock) {
 
 		/* Don't evict VM page tables while they are updated */
 		if (!dma_fence_is_signaled(vm->last_unlocked))
@@ -2767,7 +2767,8 @@ int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 	vm->last_tlb_inv = dma_fence_get_stub();
 	vm->generation = amdgpu_vm_generation(adev, NULL);
 
-	mutex_init(&vm->eviction_lock);
+	init_rwsem(&vm->default_eviction_lock);
+	vm->eviction_lock = &vm->default_eviction_lock;
 	vm->evicting = false;
 	vm->tlb_fence_context = dma_fence_context_alloc(1);
 
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h +4 -4
index bf752c6959b5c..05e332c1e01f6 100644
@@ -27,6 +27,7 @@
 #include <linux/idr.h>
 #include <linux/kfifo.h>
 #include <linux/rbtree.h>
+#include <linux/rwsem.h>
 #include <drm/gpu_scheduler.h>
 #include <drm/drm_file.h>
 #include <drm/ttm/ttm_bo.h>
@@ -288,10 +289,9 @@ struct amdgpu_vm {
 	/* tree of virtual addresses mapped */
 	struct rb_root_cached	va;
 
-	/* Lock to prevent eviction while we are updating page tables
-	 * use vm_eviction_lock/unlock(vm)
-	 */
-	struct mutex		eviction_lock;
+	/* SVM can replace this pointer with its notifier lock. */
+	struct rw_semaphore	default_eviction_lock;
+	struct rw_semaphore	*eviction_lock;
 	bool			evicting;
 
 	/* Memory statistics for this vm, protected by stats_lock */
drivers/gpu/drm/amd/amdgpu/amdgpu_vm_internal.h +10 -2
index 8a0e5fcbd55ba..920d0b3935807 100644
@@ -160,7 +160,12 @@ void amdgpu_vm_pt_free_dummies(struct amdgpu_device *adev);
  */
 static inline int amdgpu_vm_begin_critical(struct amdgpu_vm_update_params *p)
 {
-	mutex_lock(&p->vm->eviction_lock);
+	/* Use the write lock to serialize updates when the root BO is unlocked. */
+	if (p->unlocked)
+		down_write(p->vm->eviction_lock);
+	else
+		down_read(p->vm->eviction_lock);
+
 	p->saved_flags = memalloc_noreclaim_save();
 	if (p->vm->evicting)
 		return -EBUSY;
@@ -178,7 +183,10 @@ static inline int amdgpu_vm_begin_critical(struct amdgpu_vm_update_params *p)
 static inline void amdgpu_vm_end_critical(struct amdgpu_vm_update_params *p)
 {
 	memalloc_noreclaim_restore(p->saved_flags);
-	mutex_unlock(&p->vm->eviction_lock);
+	if (p->unlocked)
+		up_write(p->vm->eviction_lock);
+	else
+		up_read(p->vm->eviction_lock);
 }
 
 #endif
Signature · 1 line
2.53.0
author
#14 lore raw

PATCH v11 14/22 drm/amdgpu: recheck range validity after page table allocation

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Page-table allocation can enter reclaim and invoke an MMU notifier that needs the same lock as VM eviction. Release the selected lock around allocation and reacquire it before continuing the update.

Revalidate HMM or GPU SVM backing after reacquiring the lock, returning -EAGAIN when invalidation changed it. For SVM, also reject range-level unmap state before checking the device-owned page sequence. Guard the SVM-specific check when that feature is disabled.

Allow callers to supply an eviction lock that they already hold. Other callers pass NULL and retain internal locking. Update the VM, KFD, command submission, GEM, user queue and UALink callers to match the helper interfaces, and remove the obsolete allocation error label.

---
 .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c  |  2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c        |  2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c       |  2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c |  8 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_ualink.c    | 24 +++---
 drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c     |  2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c        | 77 ++++++++++++-------
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h        |  9 ++-
 .../gpu/drm/amd/amdgpu/amdgpu_vm_internal.h   | 29 +++++--
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c     | 31 ++++++--
 drivers/gpu/drm/amd/amdkfd/kfd_svm.c          |  7 +-
 11 files changed, 132 insertions(+), 61 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +1 -1
index 6f9a2f1cde1e4..4507c3ae78621 100644
@@ -514,7 +514,7 @@ static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync)
 	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
 	int ret;
 
-	ret = amdgpu_vm_update_pdes(adev, vm);
+	ret = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (ret)
 		return ret;
 
drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c +1 -1
index 38b454a3e8fc1..273e968ea1323 100644
@@ -1210,7 +1210,7 @@ static int amdgpu_cs_vm_handling(struct amdgpu_cs_parser *p)
 	if (r)
 		return r;
 
-	r = amdgpu_vm_update_pdes(adev, vm);
+	r = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (r)
 		return r;
 
drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c +1 -1
index 87022cdb79aff..496eccfa9f1c6 100644
@@ -851,7 +851,7 @@ amdgpu_gem_va_update_vm(struct amdgpu_device *adev,
 	}
 
 	/* Always update PDEs after we touched the mappings. */
-	r = amdgpu_vm_update_pdes(adev, vm);
+	r = amdgpu_vm_update_pdes(adev, vm, NULL);
 
 error:
 	if (r && r != -ERESTARTSYS)
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c +5 -3
index f201105e94c53..6cc491cdc3ca5 100644
@@ -73,7 +73,8 @@ int amdgpu_svm_range_zap_ptes(struct amdgpu_svm *svm, struct amdgpu_svm_range *r
 		return 0;
 
 	flags = memalloc_noreclaim_save();
-	ret = amdgpu_vm_unmap_range(svm->adev, svm->vm, true, NULL, start_page, last_page, &fence);
+	ret = amdgpu_vm_unmap_range(svm->adev, svm->vm, true, NULL, start_page, last_page, NULL,
+				    &fence);
 	memalloc_noreclaim_restore(flags);
 
 	if (fence) {
@@ -148,7 +149,8 @@ int amdgpu_svm_range_update_gpu_range(struct amdgpu_svm *svm, struct amdgpu_svm_
 		 */
 		ret = amdgpu_vm_map_range(svm->adev, svm->vm, flush_tlb && is_last_seg, true, NULL,
 					  start_page, last_page, pte_flags, 0, dst, NULL, NULL,
-					  NULL, wait_fence && is_last_seg ? fence : NULL);
+					  NULL, NULL, NULL,
+					  wait_fence && is_last_seg ? fence : NULL);
 		if (ret)
 			return ret;
 	}
@@ -263,7 +265,7 @@ int amdgpu_svm_range_update_mapping(struct amdgpu_svm *svm, struct amdgpu_svm_ra
 	dma_fence_put(fence);
 
 	if (!ret)
-		ret = amdgpu_vm_update_pdes(svm->adev, svm->vm);
+		ret = amdgpu_vm_update_pdes(svm->adev, svm->vm, NULL);
 
 	if (!ret) {
 		if (flush_tlb)
drivers/gpu/drm/amd/amdgpu/amdgpu_ualink.c +12 -12
index 45654d9561abf..e8a00c0b59e53 100644
@@ -2064,14 +2064,14 @@ static int amdgpu_ualink_unmap_npa_addr(struct amdgpu_device *adev,
 
 	r = amdgpu_vm_map_range(adev, vm, true, false, NULL, npa_addr,
 				npa_addr + size - 1, pte_value, 0, 0, NULL,
-				NULL, NULL, &vm->last_update);
+				NULL, NULL, NULL, NULL, &vm->last_update);
 	if (r) {
 		dev_err(adev->dev,
 			"Failed to unmap NPA addr (%llx) from NPA VM\n", npa_addr);
 		goto out;
 	}
 
-	r = amdgpu_vm_update_pdes(adev, vm);
+	r = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (r) {
 		dev_err(adev->dev,
 			"Failed %d to update page directories during unmapping NPA: 0x%llx\n",
@@ -2117,7 +2117,7 @@ static int amdgpu_ualink_map_npa_addr(struct amdgpu_device *adev, u64 npa_addr,
 	r = amdgpu_vm_map_range(adev, vm, true, false, NULL, npa_addr,
 				npa_addr + size - 1, pte_flags, offset,
 				adev->vm_manager.vram_base_offset,
-				bo->tbo.resource, NULL, NULL, &vm->last_update);
+				bo->tbo.resource, NULL, NULL, NULL, NULL, &vm->last_update);
 	if (r) {
 		dev_warn(adev->dev,
 			"Failed to map NPA addr (%llx) into NPA VM\n", npa_addr);
@@ -2125,7 +2125,7 @@ static int amdgpu_ualink_map_npa_addr(struct amdgpu_device *adev, u64 npa_addr,
 		goto out;
 	}
 
-	r = amdgpu_vm_update_pdes(adev, vm);
+	r = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (r) {
 		dev_err(adev->dev,
 			"failed %d to update page directories for NPA: 0x%llx\n",
@@ -2656,7 +2656,7 @@ static void amdgpu_ualink_force_retry_rpcs(struct amdgpu_device *adev,
 					pte_flags, 0,
 					adev->vm_manager.vram_base_offset,
 					bo->tbo.resource, NULL, NULL,
-					&vm->last_update);
+					NULL, NULL, &vm->last_update);
 
 		if (r)
 			dev_warn(adev->dev,
@@ -2667,7 +2667,7 @@ static void amdgpu_ualink_force_retry_rpcs(struct amdgpu_device *adev,
 			break;
 	}
 
-	r = amdgpu_vm_update_pdes(adev, vm);
+	r = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (r) {
 		dev_err(adev->dev,
 			"Failed %d to update page directories during force retry rpcs\n",
@@ -2792,7 +2792,7 @@ static void amdgpu_ualink_unmap_all_npa_addr(struct amdgpu_device *adev,
 		r = amdgpu_vm_map_range(adev, vm, true, false, NULL,
 					npa_addr, npa_addr + size - 1,
 					pte_value, 0, 0, NULL, NULL, NULL,
-					&vm->last_update);
+					NULL, NULL, &vm->last_update);
 
 		if (r)
 			dev_err(adev->dev,
@@ -2804,7 +2804,7 @@ static void amdgpu_ualink_unmap_all_npa_addr(struct amdgpu_device *adev,
 			break;
 	}
 
-	r = amdgpu_vm_update_pdes(adev, vm);
+	r = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (r) {
 		dev_err(adev->dev,
 			"Failed %d to update page directories during all NPA addresses unmapping\n",
@@ -4622,7 +4622,7 @@ static int amdgpu_ualink_npa_vm_map_range(struct amdgpu_device *adev, struct amd
 				npa_in_pages, npa_in_pages + size_in_pages - 1,
 				pte_flags, offset, adev->vm_manager.vram_base_offset,
 				bo->tbo.resource, NULL, NULL,
-				&npa_vm->last_update);
+				NULL, NULL, &npa_vm->last_update);
 	if (r)
 		dev_dbg(adev->dev, "failed %d to map npa 0x%llx to NPA VM\n", r,
 			npa_in_pages << AMDGPU_GPU_PAGE_SHIFT);
@@ -4656,7 +4656,7 @@ static int amdgpu_ualink_npa_vm_unmap_range(struct amdgpu_device *adev, struct a
 	r = amdgpu_vm_map_range(adev, npa_vm, true, false, NULL,
 				npa_in_pages, npa_in_pages + size_in_pages - 1,
 				pte_flags, offset, 0, bo->tbo.resource, NULL,
-				NULL, &npa_vm->last_update);
+				NULL, NULL, NULL, &npa_vm->last_update);
 	if (r)
 		dev_dbg(adev->dev, "failed %d to unmap npa 0x%llx from NPA VM\n", r,
 			npa_in_pages << AMDGPU_GPU_PAGE_SHIFT);
@@ -4920,7 +4920,7 @@ static void amdgpu_ualink_metadata_npa_unmapping(struct amdgpu_device *adev)
 		}
 	}
 
-	r = amdgpu_vm_update_pdes(adev, &adev->ualink.npa_vm);
+	r = amdgpu_vm_update_pdes(adev, &adev->ualink.npa_vm, NULL);
 	if (r) {
 		dev_dbg(adev->dev, "failed %d to update directories\n", r);
 		goto out_unreserve;
@@ -5065,7 +5065,7 @@ static int amdgpu_ualink_metadata_npa_mapping(struct amdgpu_device *adev)
 		}
 	}
 
-	r = amdgpu_vm_update_pdes(adev, &adev->ualink.npa_vm);
+	r = amdgpu_vm_update_pdes(adev, &adev->ualink.npa_vm, NULL);
 	if (r) {
 		dev_dbg(adev->dev, "failed %d to update directories\n", r);
 		goto error_npa_mapping;
drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c +1 -1
index 93b088d2ea0aa..2fbc2b2c1aa14 100644
@@ -1190,7 +1190,7 @@ amdgpu_userq_vm_validate_and_restore_queue(struct amdgpu_userq_mgr *uq_mgr)
 		goto retry_lock;
 	}
 
-	ret = amdgpu_vm_update_pdes(adev, vm);
+	ret = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (ret)
 		goto unlock_all;
 
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +51 -26

185 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_vm.h +7 -2
index 05e332c1e01f6..f0d9025f6ef72 100644
@@ -39,6 +39,7 @@
 #include "amdgpu_ttm.h"
 
 struct drm_exec;
+struct drm_gpusvm_range;
 
 struct amdgpu_bo_va;
 struct amdgpu_job;
@@ -289,7 +290,7 @@ struct amdgpu_vm {
 	/* tree of virtual addresses mapped */
 	struct rb_root_cached	va;
 
-	/* SVM can replace this pointer with its notifier lock. */
+	/* SVM uses gpusvm.notifier_lock, other VMs use default_eviction_lock. */
 	struct rw_semaphore	default_eviction_lock;
 	struct rw_semaphore	*eviction_lock;
 	bool			evicting;
@@ -461,7 +462,8 @@ int amdgpu_vm_validate(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 		       void *param);
 void amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job,
 		     bool *need_pipe_sync, bool *emit_gds_needed);
-int amdgpu_vm_update_pdes(struct amdgpu_device *adev, struct amdgpu_vm *vm);
+int amdgpu_vm_update_pdes(struct amdgpu_device *adev, struct amdgpu_vm *vm,
+			  struct rw_semaphore *eviction_lock);
 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
 			  struct amdgpu_vm *vm,
 			  struct dma_fence **fence);
@@ -481,10 +483,13 @@ int amdgpu_vm_map_range(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 			uint64_t vram_base, struct ttm_resource *res,
 			dma_addr_t *pages_addr,
 			struct amdgpu_hmm_range *hmm_range,
+			struct rw_semaphore *eviction_lock,
+			struct drm_gpusvm_range *gpusvm_range,
 			struct dma_fence **fence);
 int amdgpu_vm_unmap_range(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 			  bool unlocked, struct amdgpu_sync *sync,
 			  uint64_t start, uint64_t last,
+			  struct rw_semaphore *eviction_lock,
 			  struct dma_fence **fence);
 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
 			struct amdgpu_bo_va *bo_va,
drivers/gpu/drm/amd/amdgpu/amdgpu_vm_internal.h +23 -6
index 920d0b3935807..2344a56169558 100644
@@ -24,9 +24,11 @@
 #ifndef __AMDGPU_VM_INTERNAL_H__
 #define __AMDGPU_VM_INTERNAL_H__
 
+#include <drm/drm_gpusvm.h>
 #include <linux/types.h>
 #include <linux/list.h>
 #include "amdgpu_hmm.h"
+#include "amdgpu_svm_range.h"
 #include "amdgpu_vm.h"
 
 struct amdgpu_device;
@@ -80,6 +82,12 @@ struct amdgpu_vm_update_params {
 	 */
 	struct amdgpu_hmm_range *hmm_range;
 
+	/** @eviction_lock: Optional caller-held eviction lock. */
+	struct rw_semaphore *eviction_lock;
+
+	/** @gpusvm_range: Optional SVM range to revalidate after taking the lock. */
+	struct drm_gpusvm_range *gpusvm_range;
+
 	/**
 	 * @job: job to used for hw submission
 	 */
@@ -152,6 +160,7 @@ void amdgpu_vm_pt_free_dummies(struct amdgpu_device *adev);
  *
  * Serialize all updates, check parameters and make sure that memory allocations
  * don't enter the reclaim path so that we don't deadlock with MMU notifiers.
+ * A non-NULL eviction_lock means the caller already holds the selected lock.
  *
  * Returns:
  *
@@ -161,7 +170,9 @@ void amdgpu_vm_pt_free_dummies(struct amdgpu_device *adev);
 static inline int amdgpu_vm_begin_critical(struct amdgpu_vm_update_params *p)
 {
 	/* Use the write lock to serialize updates when the root BO is unlocked. */
-	if (p->unlocked)
+	if (p->eviction_lock)
+		lockdep_assert_held(p->eviction_lock);
+	else if (p->unlocked)
 		down_write(p->vm->eviction_lock);
 	else
 		down_read(p->vm->eviction_lock);
@@ -171,6 +182,10 @@ static inline int amdgpu_vm_begin_critical(struct amdgpu_vm_update_params *p)
 		return -EBUSY;
 	if (p->hmm_range && !amdgpu_hmm_range_valid(p->hmm_range))
 		return -EAGAIN;
+	if (IS_ENABLED(CONFIG_DRM_AMDGPU_SVM) && p->gpusvm_range &&
+	    !amdgpu_svm_range_pages_valid(to_amdgpu_svm(p->gpusvm_range->gpusvm),
+					 to_amdgpu_svm_range(p->gpusvm_range)))
+		return -EAGAIN;
 	return 0;
 }
 
@@ -178,15 +193,17 @@ static inline int amdgpu_vm_begin_critical(struct amdgpu_vm_update_params *p)
  * amdgpu_vm_end_critical - end the critical section of the update
  * @p: The update parameters
  *
- * Restore the GFP flags and drop the lock.
+ * Restore the GFP flags.
  */
 static inline void amdgpu_vm_end_critical(struct amdgpu_vm_update_params *p)
 {
 	memalloc_noreclaim_restore(p->saved_flags);
-	if (p->unlocked)
-		up_write(p->vm->eviction_lock);
-	else
-		up_read(p->vm->eviction_lock);
+	if (!p->eviction_lock) {
+		if (p->unlocked)
+			up_write(p->vm->eviction_lock);
+		else
+			up_read(p->vm->eviction_lock);
+	}
 }
 
 #endif
drivers/gpu/drm/amd/amdgpu/amdgpu_vm_pt.c +26 -5
index 8c941476495db..57ea3eb17e31a 100644
@@ -505,6 +505,23 @@ int amdgpu_vm_pt_create(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 	return 0;
 }
 
+static void amdgpu_vm_update_unlock(struct amdgpu_vm_update_params *p)
+{
+	amdgpu_vm_end_critical(p);
+	if (p->eviction_lock) {
+		lockdep_assert_held_read(p->eviction_lock);
+		up_read(p->eviction_lock);
+	}
+}
+
+static int amdgpu_vm_update_relock(struct amdgpu_vm_update_params *p)
+{
+	if (p->eviction_lock)
+		down_read(p->eviction_lock);
+
+	return amdgpu_vm_begin_critical(p);
+}
+
 /**
  * amdgpu_vm_pt_alloc - Allocate a specific page table
  *
@@ -528,14 +545,19 @@ static int amdgpu_vm_pt_alloc(struct amdgpu_vm_update_params *p,
 	if (entry->bo)
 		return 0;
 
-	amdgpu_vm_end_critical(p);
+	amdgpu_vm_update_unlock(p);
 	r = amdgpu_vm_pt_create(p->adev, p->vm, cursor->level,
 				&pt, p->vm->root.bo->xcp_id);
-	r2 = amdgpu_vm_begin_critical(p);
+	r2 = amdgpu_vm_update_relock(p);
 	if (r)
 		return r;
-	if (r2)
-		goto error_free_pt;
+	pt_bo = &pt->bo;
+	if (r2) {
+		amdgpu_vm_update_unlock(p);
+		amdgpu_bo_unref(&pt_bo);
+		(void)amdgpu_vm_update_relock(p);
+		return r2;
+	}
 
 	pt_bo = &pt->bo;
 	if (r2) {
@@ -557,7 +579,6 @@ static int amdgpu_vm_pt_alloc(struct amdgpu_vm_update_params *p,
 error_unpin:
 	if (p->vm->is_npa)
 		amdgpu_bo_unpin(pt_bo);
-error_free_pt:
 	amdgpu_bo_unref(&pt_bo);
 	return r;
 }
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +4 -3
index 0d419268d8adf..343d405eb11c9 100644
@@ -1438,7 +1438,7 @@ svm_range_unmap_from_gpu(struct amdgpu_device *adev, struct amdgpu_vm *vm,
 		gpu_start, gpu_end);
 
 	ret = amdgpu_vm_unmap_range(adev, vm, true, NULL, gpu_start, gpu_end,
-				   fence);
+				   NULL, fence);
 	/* EBUSY here means "vm not ready for updates because it in the process of evicting."
 	 * If that is true, it's safe to not update the range now since the vm is not in use.
 	 */
@@ -1557,7 +1557,8 @@ svm_range_map_to_gpu(struct kfd_process_device *pdd, struct svm_range *prange,
 					gpu_start, gpu_end, pte_flags,
 					(last_start - prange->start) << PAGE_SHIFT,
 					bo_adev ? bo_adev->vm_manager.vram_base_offset : 0,
-					NULL, dma_addr, hmm_range, &vm->last_update);
+					NULL, dma_addr, hmm_range,
+					NULL, NULL, &vm->last_update);
 
 		for (j = last_start - prange->start; j <= i; j++)
 			dma_addr[j] |= last_domain;
@@ -1569,7 +1570,7 @@ svm_range_map_to_gpu(struct kfd_process_device *pdd, struct svm_range *prange,
 		last_start = prange->start + i + 1;
 	}
 
-	r = amdgpu_vm_update_pdes(adev, vm);
+	r = amdgpu_vm_update_pdes(adev, vm, NULL);
 	if (r) {
 		pr_debug("failed %d to update directories 0x%lx\n", r,
 			 prange->start);
Signature · 1 line
2.53.0
author
#15 lore raw

PATCH v11 15/22 drm/amdgpu: use drm_gpusvm notifier lock for VM eviction

In reply to Huang Rui

From: Honglei Huang <[email protected]>

Use the GPUSVM notifier semaphore as the eviction lock for an SVM compute VM, so page-table updates, MMU invalidation and BO eviction share one serialization mechanism.

Pass the caller-held lock to the VM update helpers. Keep range validation, PTE/PDE updates and mapping-state publication under the notifier lock; wait for update fences and perform the compute TLB flush after releasing it. Publish the lock alias before the SVM context, and restore the default lock before unpublishing the context during teardown.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c       | 37 ++++++++++++----
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c | 42 +++++++------------
 2 files changed, 44 insertions(+), 35 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c +28 -9
index cf9c27cb0080f..8036ee189269f 100644
@@ -157,10 +157,13 @@ struct amdgpu_svm *amdgpu_svm_lookup_by_pasid(struct amdgpu_device *adev, u32 pa
 	amdgpu_pasid_lock(&irqflags);
 	fpriv = amdgpu_pasid_get_fpriv_locked(pasid);
 	vm = fpriv ? &fpriv->vm : NULL;
-	if (vm && vm->svm) {
-		svm = vm->svm;
+	/*
+	 * eviction_lock changes when SVM is enabled, so acquire vm->svm
+	 * after the new lock alias is published.
+	 */
+	svm = vm ? smp_load_acquire(&vm->svm) : NULL;
+	if (svm)
 		kref_get(&svm->refcount);
-	}
 	amdgpu_pasid_unlock(irqflags);
 
 	return svm;
@@ -465,6 +468,8 @@ static int amdgpu_svm_init_compute(struct amdgpu_device *adev, struct amdgpu_vm
 	struct amdgpu_svm *svm;
 	int ret;
 
+	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
+
 	if (vm->svm)
 		return 0;
 
@@ -496,7 +501,9 @@ static int amdgpu_svm_init_compute(struct amdgpu_device *adev, struct amdgpu_vm
 		 1UL << (svm->default_granularity + PAGE_SHIFT),
 		 svm->xnack_enabled ? "enabled" : "disabled");
 
-	vm->svm = svm;
+	vm->eviction_lock = &svm->gpusvm.notifier_lock;
+	/* Publish the context after its notifier lock alias. */
+	smp_store_release(&vm->svm, svm);
 	return 0;
 
 err_free:
@@ -570,31 +577,43 @@ void amdgpu_svm_close(struct amdgpu_vm *vm)
  * amdgpu_svm_fini() - Finalize and release a VM's SVM context
  * @vm: The VM whose SVM context is being torn down.
  *
- * Close the context, tear down the embedded drm_gpusvm under the SVM lock,
- * destroy the attribute tree and work queues, and drop the context
- * reference. Safe to call on a VM without an SVM context.
+ * Tear down the embedded drm_gpusvm, attribute tree and work queues, and drop
+ * the context reference.
  */
 void amdgpu_svm_fini(struct amdgpu_vm *vm)
 {
 	struct amdgpu_svm *svm = vm->svm;
+	struct amdgpu_bo *root;
 
 	if (!svm)
 		return;
 
 	amdgpu_svm_close(vm);
 	amdgpu_svm_lock(svm);
+
+	root = amdgpu_bo_ref(vm->root.bo);
+	amdgpu_bo_reserve(root, true);
+
 	drm_gpusvm_fini(&svm->gpusvm);
+
+	vm->eviction_lock = &vm->default_eviction_lock;
+	/* Publish the lock reset before making SVM unavailable. */
+	smp_store_release(&vm->svm, NULL);
+
 	amdgpu_svm_unlock(svm);
 
 	amdgpu_svm_attr_tree_destroy(svm->attr_tree);
 	amdgpu_svm_work_fini(svm);
-	vm->svm = NULL;
 	amdgpu_svm_put(svm);
+
+	amdgpu_bo_unreserve(root);
+	amdgpu_bo_unref(&root);
 }
 
 bool amdgpu_svm_is_enabled(struct amdgpu_vm *vm)
 {
-	return vm->svm;
+	/* Pairs with publishing vm->svm after its lock alias is initialized. */
+	return smp_load_acquire(&vm->svm);
 }
 
 static int amdgpu_svm_copy_attrs(const struct drm_amdgpu_gem_svm *args,
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c +16 -26

99 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#16 lore raw

PATCH v11 16/22 drm/pagemap: fix page undercount for compound src entries

In reply to Huang Rui

From: Junhua Shen <[email protected]>

A migrate.src[] entry with MIGRATE_PFN_VALID=0 && MIGRATE_PFN_COMPOUND=1 represents a compound (THP) source page, but migrate_pfn_to_page() returns NULL for it. Both accounting loops in drm_pagemap_migrate_to_devmem() derive the count from that NULL page and fall back to nr_pages = 1 instead of HPAGE_PMD_NR, undercounting migrated_pages and risking a spurious -EBUSY in the final migration race check. drm_pagemap_cpages() already handles this case, so the open-coded sites disagree.

Factor the decoding out into drm_pagemap_src_pfn_nr_pages() and use it in drm_pagemap_cpages() and both accounting loops of drm_pagemap_migrate_to_devmem(), so a COMPOUND-only entry is consistently counted as HPAGE_PMD_NR base pages.

Fixes 192cb1f5cb16 ("drm/pagemap: Enable THP support for GPU memory migration")
---
 drivers/gpu/drm/drm_pagemap.c | 60 +++++++++++++++++++++++++----------
 1 file changed, 43 insertions(+), 17 deletions(-)
drivers/gpu/drm/drm_pagemap.c +43 -17
index 892b325fa99b8..a31cc4f0af68c 100644
@@ -554,6 +554,37 @@ static int drm_pagemap_migrate_range(struct drm_pagemap_devmem *devmem,
 	return ret;
 }
 
+/**
+ * drm_pagemap_src_pfn_nr_pages() - Decode src entry and return base-page count
+ * @src_pfn: Source migrate entry
+ * @src_page: Optional decoded source page when MIGRATE_PFN_VALID is set
+ *
+ * Decode @src_pfn to compute how many base pages it represents: use folio
+ * page count for valid entries, HPAGE_PMD_NR for COMPOUND-only entries,
+ * otherwise 1.
+ *
+ * Return: Number of base pages represented by @src_pfn.
+ */
+static unsigned long drm_pagemap_src_pfn_nr_pages(unsigned long src_pfn,
+						   struct page **src_page)
+{
+	struct page *page = NULL;
+	unsigned long nr_pages = 1;
+
+	if (src_pfn & MIGRATE_PFN_VALID) {
+		page = migrate_pfn_to_page(src_pfn);
+		if (page)
+			nr_pages = NR_PAGES(folio_order(page_folio(page)));
+	} else if (src_pfn & MIGRATE_PFN_COMPOUND) {
+		nr_pages = HPAGE_PMD_NR;
+	}
+
+	if (src_page)
+		*src_page = page;
+
+	return nr_pages;
+}
+
 /**
  * drm_pagemap_cpages() - Count collected pages
  * @migrate_pfn: Array of migrate_pfn entries to account
@@ -570,20 +601,14 @@ static int drm_pagemap_cpages(unsigned long *migrate_pfn, unsigned long npages)
 	unsigned long i, cpages = 0;
 
 	for (i = 0; i < npages;) {
-		struct page *page = migrate_pfn_to_page(migrate_pfn[i]);
-		struct folio *folio;
-		unsigned int order = 0;
+		unsigned long src_pfn = migrate_pfn[i];
+		struct page *page;
+		unsigned long nr_pages = drm_pagemap_src_pfn_nr_pages(src_pfn, &page);
 
-		if (page) {
-			folio = page_folio(page);
-			order = folio_order(folio);
-			cpages += NR_PAGES(order);
-		} else if (migrate_pfn[i] & MIGRATE_PFN_COMPOUND) {
-			order = HPAGE_PMD_ORDER;
-			cpages += NR_PAGES(order);
-		}
+		if (page || (src_pfn & MIGRATE_PFN_COMPOUND))
+			cpages += nr_pages;
 
-		i += NR_PAGES(order);
+		i += nr_pages;
 	}
 
 	return cpages;
@@ -703,8 +728,9 @@ int drm_pagemap_migrate_to_devmem(struct drm_pagemap_devmem *devmem_allocation,
 
 	/* Count device-private pages to migrate */
 	for (i = 0; i < npages;) {
-		struct page *src_page = migrate_pfn_to_page(migrate.src[i]);
-		unsigned long nr_pages = src_page ? NR_PAGES(folio_order(page_folio(src_page))) : 1;
+		unsigned long src_pfn = migrate.src[i];
+		struct page *src_page;
+		unsigned long nr_pages = drm_pagemap_src_pfn_nr_pages(src_pfn, &src_page);
 
 		if (src_page && is_zone_device_page(src_page)) {
 			if (page_pgmap(src_page) == pagemap)
@@ -818,10 +844,10 @@ int drm_pagemap_migrate_to_devmem(struct drm_pagemap_devmem *devmem_allocation,
 	migrate_vma_pages(&migrate);
 
 	for (i = 0; !err && i < npages;) {
-		struct page *page = migrate_pfn_to_page(migrate.src[i]);
-		unsigned long nr_pages = page ? NR_PAGES(folio_order(page_folio(page))) : 1;
+		unsigned long src_pfn = migrate.src[i];
+		unsigned long nr_pages = drm_pagemap_src_pfn_nr_pages(src_pfn, NULL);
 
-		if (migrate.src[i] & MIGRATE_PFN_MIGRATE)
+		if (src_pfn & MIGRATE_PFN_MIGRATE)
 			migrated_pages += nr_pages;
 
 		i += nr_pages;
Signature · 1 line
2.53.0
author
#17 lore raw

PATCH v11 17/22 drm/amdgpu: add VRAM migration infrastructure for drm_pagemap

In reply to Huang Rui

From: Junhua Shen <[email protected]>

Add the drm_pagemap-based VRAM migration infrastructure:

- Define struct amdgpu_pagemap wrapping dev_pagemap + drm_pagemap
- Define AMDGPU_PGMAP_OWNER() and AMDGPU_INTERCONNECT_VRAM macros
- Implement amdgpu_svm_migration_init() to register ZONE_DEVICE via devm_memremap_pages() and initialize the drm_pagemap
- Add amdgpu_pagemap pointer (apagemap) to struct amdgpu_device

---
 drivers/gpu/drm/amd/amdgpu/Makefile         |   2 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu.h         |   8 +
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c | 252 ++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h |  92 +++++++
 4 files changed, 353 insertions(+), 1 deletion(-)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h
drivers/gpu/drm/amd/amdgpu/Makefile +1 -1
index ad84e57115428..66f4a4d2d451e 100644
@@ -332,7 +332,7 @@ amdgpu-$(CONFIG_HMM_MIRROR) += amdgpu_hmm.o
 
 # svm support
 amdgpu-$(CONFIG_DRM_AMDGPU_SVM) += amdgpu_svm.o amdgpu_svm_attr.o \
-	amdgpu_svm_fault.o amdgpu_svm_range.o
+	amdgpu_svm_fault.o amdgpu_svm_range.o amdgpu_migrate.o
 
 include $(FULL_AMD_PATH)/pm/Makefile
 
drivers/gpu/drm/amd/amdgpu/amdgpu.h +8 -0
index 4f53d87a00b4a..ff6ec97645d4b 100644
@@ -327,6 +327,7 @@ struct amdgpu_fpriv;
 struct amdgpu_bo_va_mapping;
 struct kfd_vm_fault_info;
 struct amdgpu_hive_info;
+struct amdgpu_pagemap;
 struct amdgpu_reset_context;
 struct amdgpu_reset_control;
 struct amdgpu_coredump_info;
@@ -982,6 +983,13 @@ struct amdgpu_device {
 
 	struct amdgpu_uma_carveout_info uma_info;
 
+#if IS_ENABLED(CONFIG_DRM_AMDGPU_SVM)
+	/* SVM VRAM migration via drm_pagemap (drm_gpusvm path).
+	 * Allocated in amdgpu_svm_migration_init(), NULL if SVM disabled.
+	 */
+	struct amdgpu_pagemap		*apagemap;
+#endif
+
 	/* KFD
 	 * Must be last --ends in a flexible-array member.
 	 */
drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c new file +252 -0

252 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h new file +92 -0

92 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#18 lore raw

PATCH v11 18/22 drm/amdgpu: implement drm_pagemap SDMA migration callbacks

In reply to Huang Rui

From: Junhua Shen <[email protected]>

Implement the drm_pagemap_devmem_ops and drm_pagemap_ops callbacks that the DRM GPUSVM migration framework requires.

Introduce struct amdgpu_bo_svm as a BO subtype (following the amdgpu_bo_user/amdgpu_bo_vm pattern) that embeds struct amdgpu_bo and carries a drm_pagemap_devmem allocation.

drm_pagemap_ops (top-level entry points):
- device_map: convert ZONE_DEVICE page to GPU PTE address
- populate_mm: allocate amdgpu_bo_svm and trigger migration

drm_pagemap_devmem_ops (per-BO migration mechanics):
- populate_devmem_pfn: walk BO buddy blocks to build PFN array

  - copy_to_devmem:      SDMA copy system RAM -> VRAM via GART window
  - copy_to_ram:         SDMA copy VRAM -> system RAM via GART window
  - devmem_release:      drop BO ref (triggers destroy to free amdgpu_bo_svm)
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c | 602 ++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h |   3 +
 2 files changed, 605 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c +602 -0
index 054520d3ff1f7..e7d2c6167adb1 100644
@@ -67,6 +67,15 @@
 
 #include "amdgpu_migrate.h"
 #include "amdgpu.h"
+#include "amdgpu_ttm.h"
+#include "amdgpu_sdma.h"
+#include "amdgpu_res_cursor.h"
+
+/* SDMA copy direction */
+#define FROM_RAM_TO_VRAM	0
+#define FROM_VRAM_TO_RAM	1
+
+static const struct drm_pagemap_devmem_ops amdgpu_pagemap_ops;
 
 static inline struct amdgpu_pagemap *
 dpagemap_to_apagemap(struct drm_pagemap *dpagemap)
@@ -94,6 +103,597 @@ amdgpu_svm_page_to_apagemap(struct page *page)
 	return container_of(pgmap, struct amdgpu_pagemap, pgmap);
 }
 
+/**
+ * struct amdgpu_bo_svm - SVM BO subtype with drm_pagemap devmem allocation
+ *
+ * @bo: Embedded base amdgpu_bo
+ * @devmem: drm_pagemap device memory allocation (passed to framework)
+ *
+ * Lifecycle is managed by the drm_pagemap framework's internal zdd refcount:
+ *   - zdd->devmem_allocation points to &svm_bo->devmem
+ *   - When zdd refcount drops to zero, framework calls devmem_release()
+ *   - devmem_release() drops the BO reference (triggering destroy callback)
+ */
+struct amdgpu_bo_svm {
+	struct amdgpu_bo bo;
+	struct drm_pagemap_devmem devmem;
+};
+
+#define to_amdgpu_bo_svm(abo) container_of((abo), struct amdgpu_bo_svm, bo)
+
+static inline struct amdgpu_bo_svm *
+devmem_to_amdgpu_bo_svm(struct drm_pagemap_devmem *devmem_allocation)
+{
+	return container_of(devmem_allocation, struct amdgpu_bo_svm, devmem);
+}
+
+/**
+ * amdgpu_bo_svm_destroy - TTM destroy callback for SVM BO
+ *
+ * Called when the last reference to the BO is dropped.
+ * Follows amdgpu_bo_user_destroy pattern: delegates to amdgpu_bo_base_destroy.
+ */
+static void amdgpu_bo_svm_destroy(struct ttm_buffer_object *tbo)
+{
+	struct amdgpu_bo *bo = ttm_to_amdgpu_bo(tbo);
+	struct amdgpu_bo_svm *svm_bo = to_amdgpu_bo_svm(bo);
+
+	amdgpu_bo_kunmap(bo);
+	drm_gem_object_release(&bo->tbo.base);
+	amdgpu_bo_unref(&bo->parent);
+	kvfree(svm_bo);
+}
+
+/**
+ * amdgpu_bo_svm_alloc - Allocate an amdgpu_bo_svm with VRAM backing
+ * @adev: AMDGPU device
+ * @dpagemap: The drm_pagemap for this device
+ * @mm: mm_struct of the owning process
+ * @size: Allocation size in bytes
+ *
+ * Uses bp->bo_ptr_size = sizeof(struct amdgpu_bo_svm) so that
+ * amdgpu_bo_create() allocates the full amdgpu_bo_svm structure,
+ * with the embedded amdgpu_bo as the base.
+ *
+ * Return: Pointer to allocated amdgpu_bo_svm on success, ERR_PTR on failure
+ */
+static struct amdgpu_bo_svm *
+amdgpu_bo_svm_alloc(struct amdgpu_device *adev,
+		     struct drm_pagemap *dpagemap,
+		     struct mm_struct *mm, unsigned long size)
+{
+	struct dma_fence *pre_migrate_fence = NULL;
+	struct amdgpu_bo_param bp = {};
+	struct amdgpu_bo_svm *svm_bo;
+	struct amdgpu_bo *bo;
+	int ret;
+
+	bp.size = size;
+	bp.bo_ptr_size = sizeof(struct amdgpu_bo_svm);
+	bp.destroy = &amdgpu_bo_svm_destroy;
+	bp.domain = AMDGPU_GEM_DOMAIN_VRAM;
+	bp.type = ttm_bo_type_device;
+	bp.flags = AMDGPU_GEM_CREATE_NO_CPU_ACCESS |
+		   AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS |
+		   AMDGPU_GEM_CREATE_VRAM_CLEARED;
+
+	ret = amdgpu_bo_create(adev, &bp, &bo);
+	if (ret) {
+		pr_debug("Failed to create SVM BO\n");
+		return ERR_PTR(ret);
+	}
+
+	svm_bo = to_amdgpu_bo_svm(bo);
+
+	/* Ensure any async VRAM operations complete before migration copy */
+	if (!dma_resv_test_signaled(bo->tbo.base.resv,
+					 DMA_RESV_USAGE_KERNEL)) {
+		ret = dma_resv_get_singleton(bo->tbo.base.resv,
+					      DMA_RESV_USAGE_KERNEL,
+					      &pre_migrate_fence);
+		if (ret) {
+			amdgpu_bo_unref(&bo);
+			return ERR_PTR(ret);
+		}
+	}
+
+	drm_pagemap_devmem_init(&svm_bo->devmem, adev->dev, mm,
+				&amdgpu_pagemap_ops, dpagemap, size,
+				pre_migrate_fence);
+
+	return svm_bo;
+}
+
+/**
+ * amdgpu_svm_devmem_release - Release BO when all device pages migrate back
+ *
+ * Called by the drm_pagemap framework (via drm_pagemap_zdd_destroy) when the
+ * last device-private page backed by this allocation has been migrated back
+ * to system memory (or the owning process exits).
+ *
+ * Drops the BO reference, which triggers the destroy callback to free
+ * the amdgpu_bo_svm structure.
+ */
+static void
+amdgpu_svm_devmem_release(struct drm_pagemap_devmem *devmem_allocation)
+{
+	struct amdgpu_bo_svm *svm_bo = devmem_to_amdgpu_bo_svm(devmem_allocation);
+	struct amdgpu_bo *bo = &svm_bo->bo;
+
+	pr_debug("Release svm_bo=%px bo=%px\n", svm_bo, bo);
+	dma_fence_put(devmem_allocation->pre_migrate_fence);
+	devmem_allocation->pre_migrate_fence = NULL;
+	amdgpu_bo_unref(&bo);
+}
+
+/**
+ * amdgpu_svm_populate_devmem_pfn - Convert BO VRAM allocation to PFN array
+ * @devmem_allocation: The devmem allocation in the amdgpu_bo_svm wrapper
+ * @npages: Number of PFN entries to fill
+ * @pfn: Output PFN array
+ *
+ * Iterates over the BO's TTM vram_mgr buddy blocks and converts each
+ * block's VRAM offset to ZONE_DEVICE PFNs:
+ *
+ *   PFN = PHYS_PFN(block_offset + apagemap.hpa_base) + page_index
+ *
+ * This is called by drm_pagemap_migrate_to_devmem() to build the
+ * destination PFN array for migrate_vma_pages().
+ *
+ * Return: 0 on success
+ */
+static int
+amdgpu_svm_populate_devmem_pfn(struct drm_pagemap_devmem *devmem_allocation,
+				unsigned long npages, unsigned long *pfn)
+{
+	struct amdgpu_pagemap *svm_dm = dpagemap_to_apagemap(devmem_allocation->dpagemap);
+	struct amdgpu_bo_svm *svm_bo = devmem_to_amdgpu_bo_svm(devmem_allocation);
+	struct amdgpu_bo *bo = &svm_bo->bo;
+	struct amdgpu_res_cursor cursor;
+	unsigned long i = 0;
+
+	dma_resv_assert_held(bo->tbo.base.resv);
+
+	amdgpu_res_first(bo->tbo.resource, 0, npages << PAGE_SHIFT, &cursor);
+	while (cursor.remaining && i < npages) {
+		u64 pfn_base = PHYS_PFN(cursor.start + svm_dm->hpa_base);
+		u64 pages = cursor.size >> PAGE_SHIFT;
+		unsigned long j;
+
+		for (j = 0; j < pages && i < npages; j++, i++)
+			pfn[i] = pfn_base + j;
+
+		amdgpu_res_next(&cursor, cursor.size);
+	}
+
+	pr_debug("populate_devmem_pfn: npages=%lu first_pfn=0x%lx\n",
+		 npages, npages > 0 ? pfn[0] : 0);
+
+	return 0;
+}
+
+/* SDMA copy helpers — GART window based data transfer */
+
+/**
+ * amdgpu_svm_direct_mapping_addr - Convert VRAM offset to MC address
+ * @adev: AMDGPU device
+ * @vram_offset: Byte offset within VRAM
+ *
+ * Return: MC address suitable for SDMA src/dst
+ */
+static u64
+amdgpu_svm_direct_mapping_addr(struct amdgpu_device *adev, u64 vram_offset)
+{
+	return vram_offset + amdgpu_ttm_domain_start(adev, TTM_PL_VRAM);
+}
+
+/**
+ * amdgpu_svm_gart_map - Map system DMA addresses into GART window
+ * @ring: SDMA ring for the GART update job
+ * @npages: Number of pages to map
+ * @addr: Array of system memory DMA addresses
+ * @gart_addr: Output — GART base address to use in SDMA copy
+ * @flags: PTE flags (e.g. writeable for RAM-to-VRAM src)
+ *
+ * Builds GART PTEs pointing at the given DMA addresses, submits an
+ * SDMA job to update the GART entries, and returns the GART address
+ * that can be used as src or dst in a subsequent amdgpu_copy_buffer().
+ *
+ * Uses GART window 0, protected by gtt_window_lock.
+ *
+ * Return: 0 on success, negative error code on failure
+ */
+static int
+amdgpu_svm_gart_map(struct amdgpu_ring *ring,
+		     struct amdgpu_ttm_buffer_entity *entity,
+		     u64 npages,
+		     dma_addr_t *addr, u64 *gart_addr, u64 flags)
+{
+	struct amdgpu_device *adev = ring->adev;
+	struct amdgpu_job *job;
+	unsigned int num_dw, num_bytes;
+	struct dma_fence *fence;
+	u64 src_addr, dst_addr;
+	u64 pte_flags;
+	void *cpu_addr;
+	int r;
+
+	/* Use entity's GART window 0 */
+	*gart_addr = amdgpu_compute_gart_address(&adev->gmc, entity, 0);
+
+	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
+	num_bytes = npages * 8 * AMDGPU_GPU_PAGES_IN_CPU_PAGE;
+
+	r = amdgpu_job_alloc_with_ib(adev, &entity->base,
+				     AMDGPU_FENCE_OWNER_UNDEFINED,
+				     num_dw * 4 + num_bytes,
+				     AMDGPU_IB_POOL_DELAYED,
+				     AMDGPU_KERNEL_JOB_ID_KFD_GART_MAP,
+				     &job);
+	if (r)
+		return r;
+
+	src_addr = num_dw * 4;
+	src_addr += job->ibs[0].gpu_addr;
+
+	dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
+	dst_addr += (entity->gart_window_offs[0] >> AMDGPU_GPU_PAGE_SHIFT) * 8;
+	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
+				dst_addr, num_bytes, 0);
+
+	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
+	WARN_ON(job->ibs[0].length_dw > num_dw);
+
+	pte_flags = AMDGPU_PTE_VALID | AMDGPU_PTE_READABLE;
+	pte_flags |= AMDGPU_PTE_SYSTEM | AMDGPU_PTE_SNOOPED;
+	if (flags & AMDGPU_PTE_WRITEABLE)
+		pte_flags |= AMDGPU_PTE_WRITEABLE;
+	pte_flags |= adev->gart.gart_pte_flags;
+
+	cpu_addr = &job->ibs[0].ptr[num_dw];
+
+	amdgpu_gart_map(adev, 0, npages, addr, pte_flags, cpu_addr);
+	fence = amdgpu_job_submit(job);
+	dma_fence_put(fence);
+
+	return 0;
+}
+
+/**
+ * amdgpu_svm_copy_memory_gart - SDMA copy between system RAM and VRAM
+ * @adev: AMDGPU device
+ * @sys: Array of DMA addresses for system memory pages
+ * @vram: Array of VRAM byte offsets (relative to start of VRAM)
+ * @npages: Number of pages to copy
+ * @direction: FROM_RAM_TO_VRAM or FROM_VRAM_TO_RAM
+ * @mfence: In/out — carries the last SDMA fence for serialization
+ *
+ * Maps system memory pages into the GART window and uses SDMA to copy
+ * data to/from VRAM. Handles splitting into AMDGPU_GTT_MAX_TRANSFER_SIZE
+ * chunks. Acquires entity->lock internally to protect the GART window,
+ * matching the KFD svm_migrate_copy_memory_gart() pattern.
+ *
+ * Return: 0 on success, negative error code on failure
+ */
+static int
+amdgpu_svm_copy_memory_gart(struct amdgpu_device *adev, dma_addr_t *sys,
+			    u64 *vram, u64 npages, int direction,
+			    struct dma_fence **mfence)
+{
+	const u64 max_pages = AMDGPU_GTT_MAX_TRANSFER_SIZE >> PAGE_SHIFT;
+	struct amdgpu_ring *ring = to_amdgpu_ring(adev->mman.buffer_funcs_scheds[0]);
+	struct amdgpu_ttm_buffer_entity *entity = &adev->mman.move_entities[0];
+	u64 gart_s, gart_d;
+	struct dma_fence *next;
+	u64 size;
+	int r;
+
+	mutex_lock(&entity->lock);
+
+	while (npages) {
+		size = min(max_pages, npages);
+
+		if (direction == FROM_VRAM_TO_RAM) {
+			gart_s = amdgpu_svm_direct_mapping_addr(adev, *vram);
+			r = amdgpu_svm_gart_map(ring, entity, size, sys,
+						&gart_d, AMDGPU_PTE_WRITEABLE);
+		} else {
+			r = amdgpu_svm_gart_map(ring, entity, size, sys,
+						&gart_s, 0);
+			gart_d = amdgpu_svm_direct_mapping_addr(adev, *vram);
+		}
+		if (r) {
+			dev_err(adev->dev, "failed %d to map GART for SDMA\n", r);
+			goto out_unlock;
+		}
+
+		pr_debug("SDMA_COPY: %s npages=%llu vram_off=0x%llx\n",
+			 direction == FROM_RAM_TO_VRAM ? "RAM->VRAM" : "VRAM->RAM",
+			 size, (u64)*vram);
+
+		r = amdgpu_copy_buffer(adev, entity, gart_s, gart_d,
+				       size * PAGE_SIZE,
+				       NULL, &next, true, 0);
+		if (r) {
+			dev_err(adev->dev, "failed %d to copy buffer\n", r);
+			goto out_unlock;
+		}
+
+		dma_fence_put(*mfence);
+		*mfence = next;
+		npages -= size;
+		if (npages) {
+			sys += size;
+			vram += size;
+		}
+	}
+
+out_unlock:
+	mutex_unlock(&entity->lock);
+
+	return r;
+}
+
+/**
+ * amdgpu_svm_copy_pages - SDMA copy between system memory and VRAM
+ * @pages: ZONE_DEVICE pages — destination when direction=FROM_RAM_TO_VRAM,
+ *         source when direction=FROM_VRAM_TO_RAM
+ * @pagemap_addr: DMA addresses — source when direction=FROM_RAM_TO_VRAM,
+ *                destination when direction=FROM_VRAM_TO_RAM
+ * @npages: Number of framework slots in the arrays
+ * @pre_migrate_fence: Optional fence to wait before the first SDMA submission
+ * @direction: FROM_RAM_TO_VRAM or FROM_VRAM_TO_RAM
+ *
+ * Builds parallel sys[] (DMA addresses) and vram[] (VRAM byte offsets) arrays
+ * from the framework-provided inputs, then submits batched SDMA copies via
+ * the GART window.  Contiguous VRAM runs are coalesced into a single
+ * amdgpu_svm_copy_memory_gart() call; discontiguity flushes the current batch
+ * and starts a new one.  The pre_migrate_fence wait is deferred until the
+ * first actual SDMA submission.
+ *
+ * Return: 0 on success, negative error code on failure
+ */
+static int
+amdgpu_svm_copy_pages(struct page **pages,
+		       struct drm_pagemap_addr *pagemap_addr,
+		       unsigned long npages,
+		       struct dma_fence *pre_migrate_fence,
+		       int direction)
+{
+	struct amdgpu_device *adev;
+	struct amdgpu_pagemap *svm_dm;
+	struct dma_fence *mfence = NULL;
+	dma_addr_t *sys = NULL;
+	u64 *vram = NULL;
+	unsigned long i, j;
+	bool waited = false;
+	int ret = 0;
+
+	if (!npages)
+		return 0;
+
+	for (i = 0; i < npages; i++) {
+		if (pages[i] && pagemap_addr[i].addr)
+			break;
+	}
+	if (i == npages) {
+		/*
+		 * No data to copy (e.g. anonymous zero-hole migration to
+		 * device).  We still must wait for the pre_migrate_fence (the
+		 * async VRAM clear) before the freshly populated device pages
+		 * become user-visible, otherwise a late clear could overwrite
+		 * subsequent user writes.
+		 */
+		if (pre_migrate_fence)
+			dma_fence_wait(pre_migrate_fence, false);
+		return 0;
+	}
+
+	svm_dm = amdgpu_svm_page_to_apagemap(pages[i]);
+	adev = svm_dm->adev;
+
+	sys = kvcalloc(npages, sizeof(*sys), GFP_KERNEL);
+	vram = kvcalloc(npages, sizeof(*vram), GFP_KERNEL);
+	if (!sys || !vram) {
+		ret = -ENOMEM;
+		goto out_free;
+	}
+
+	for (i = 0, j = 0; i < npages; i++) {
+		unsigned long nr_pages;
+		dma_addr_t sys_base;
+		u64 vram_base;
+		unsigned long k;
+
+		if (!pagemap_addr[i].addr || !pages[i])
+			goto flush;
+
+		nr_pages = folio_nr_pages(page_folio(pages[i]));
+		sys_base = pagemap_addr[i].addr;
+		vram_base = ((u64)page_to_pfn(pages[i]) << PAGE_SHIFT) -
+			    svm_dm->hpa_base;
+
+		if (j > 0 && vram_base != vram[j - 1] + PAGE_SIZE)
+			goto flush;
+
+		for (k = 0; k < nr_pages; k++) {
+			sys[j] = sys_base + k * PAGE_SIZE;
+			vram[j] = vram_base + k * PAGE_SIZE;
+			j++;
+		}
+		continue;
+flush:
+		if (j) {
+			if (pre_migrate_fence && !waited) {
+				dma_fence_wait(pre_migrate_fence, false);
+				waited = true;
+			}
+			ret = amdgpu_svm_copy_memory_gart(adev, sys, vram, j,
+							  direction, &mfence);
+			if (ret)
+				goto out_fence;
+			j = 0;
+		}
+		/* Re-process current page if it was valid but broke contiguity */
+		if (pagemap_addr[i].addr && pages[i]) {
+			nr_pages = folio_nr_pages(page_folio(pages[i]));
+			sys_base = pagemap_addr[i].addr;
+			vram_base = ((u64)page_to_pfn(pages[i]) << PAGE_SHIFT) -
+				    svm_dm->hpa_base;
+			for (k = 0; k < nr_pages; k++) {
+				sys[k] = sys_base + k * PAGE_SIZE;
+				vram[k] = vram_base + k * PAGE_SIZE;
+			}
+			j = nr_pages;
+		}
+	}
+
+	/* Flush remaining batch */
+	if (j) {
+		if (pre_migrate_fence && !waited)
+			dma_fence_wait(pre_migrate_fence, false);
+		ret = amdgpu_svm_copy_memory_gart(adev, sys, vram, j,
+						  direction, &mfence);
+	}
+
+out_fence:
+	if (mfence) {
+		dma_fence_wait(mfence, false);
+		dma_fence_put(mfence);
+	}
+
+out_free:
+	kvfree(vram);
+	kvfree(sys);
+
+	pr_debug("copy_pages done: npages=%ld direction=%d ret=%d\n",
+		 npages, direction, ret);
+	return ret;
+}
+
+static int
+amdgpu_svm_copy_to_devmem(struct page **pages,
+			   struct drm_pagemap_addr *pagemap_addr,
+			   unsigned long npages,
+			   struct dma_fence *pre_migrate_fence)
+{
+	return amdgpu_svm_copy_pages(pages, pagemap_addr, npages,
+				     pre_migrate_fence, FROM_RAM_TO_VRAM);
+}
+
+static int
+amdgpu_svm_copy_to_ram(struct page **pages,
+		        struct drm_pagemap_addr *pagemap_addr,
+		        unsigned long npages,
+		        struct dma_fence *pre_migrate_fence)
+{
+	return amdgpu_svm_copy_pages(pages, pagemap_addr, npages,
+				     pre_migrate_fence, FROM_VRAM_TO_RAM);
+}
+
+static const struct drm_pagemap_devmem_ops amdgpu_pagemap_ops = {
+	.devmem_release      = amdgpu_svm_devmem_release,
+	.populate_devmem_pfn = amdgpu_svm_populate_devmem_pfn,
+	.copy_to_devmem      = amdgpu_svm_copy_to_devmem,
+	.copy_to_ram         = amdgpu_svm_copy_to_ram,
+};
+
+/* drm_pagemap_ops — top-level migration entry points */
+
+/**
+ * amdgpu_svm_device_map - Convert ZONE_DEVICE page to GPU PTE address
+ * @dpagemap: The drm_pagemap for this device
+ * @dev: Requesting device (for P2P check)
+ * @page: ZONE_DEVICE page backed by VRAM
+ * @order: Page order (0 = 4K, 9 = 2M, etc.)
+ * @dir: DMA direction (unused for local VRAM)
+ *
+ * Address conversion chain:
+ *   page -> PFN -> HPA -> VRAM offset -> PTE address
+ *
+ *   HPA = page_to_pfn(page) << PAGE_SHIFT
+ *   VRAM offset = HPA - apagemap.hpa_base
+ *   PTE address = VRAM offset + adev->vm_manager.vram_base_offset
+ *
+ * Return: drm_pagemap_addr with PTE address and AMDGPU_INTERCONNECT_VRAM protocol
+ */
+static struct drm_pagemap_addr
+amdgpu_svm_device_map(struct drm_pagemap *dpagemap,
+		       struct device *dev,
+		       struct page *page,
+		       unsigned int order,
+		       enum dma_data_direction dir)
+{
+	struct amdgpu_pagemap *svm_dm = dpagemap_to_apagemap(dpagemap);
+	struct amdgpu_device *adev = dpagemap_to_adev(dpagemap);
+	dma_addr_t addr;
+
+	if (dpagemap->drm->dev == dev) {
+		/* Same device: return VRAM PTE address */
+		u64 hpa = (u64)page_to_pfn(page) << PAGE_SHIFT;
+		u64 vram_offset = hpa - svm_dm->hpa_base;
+
+		addr = vram_offset + adev->vm_manager.vram_base_offset;
+	} else {
+		/* Cross-device P2P: not yet supported */
+		addr = DMA_MAPPING_ERROR;
+	}
+
+	return drm_pagemap_addr_encode(addr,
+				AMDGPU_INTERCONNECT_VRAM, order, dir);
+}
+
+/**
+ * amdgpu_svm_populate_mm - Allocate VRAM BO and migrate pages
+ * @dpagemap: The drm_pagemap for this device
+ * @start: Start virtual address of the range to migrate
+ * @end: End virtual address (exclusive)
+ * @mm: mm_struct of the owning process
+ * @timeslice_ms: Maximum time to spend migrating (for fairness)
+ *
+ * Core migration entry point called by drm_pagemap_populate_mm().
+ * Allocates an amdgpu_bo_svm via amdgpu_bo_svm_alloc(), then calls
+ * drm_pagemap_migrate_to_devmem() to execute the actual migration.
+ *
+ * Return: 0 on success, negative error code on failure
+ */
+static int
+amdgpu_svm_populate_mm(struct drm_pagemap *dpagemap,
+			unsigned long start, unsigned long end,
+			struct mm_struct *mm,
+			unsigned long timeslice_ms)
+{
+	struct amdgpu_device *adev = dpagemap_to_adev(dpagemap);
+	struct drm_pagemap_migrate_details mdetails = {
+		.timeslice_ms = timeslice_ms,
+	};
+	struct amdgpu_bo_svm *svm_bo;
+	int ret;
+
+	svm_bo = amdgpu_bo_svm_alloc(adev, dpagemap, mm, end - start);
+	if (IS_ERR(svm_bo))
+		return PTR_ERR(svm_bo);
+
+	pr_debug("populate_mm: [0x%lx-0x%lx] size=%lu\n",
+		 start, end, end - start);
+
+	ret = amdgpu_bo_reserve(&svm_bo->bo, true);
+	if (ret) {
+		struct amdgpu_bo *bo = &svm_bo->bo;
+
+		amdgpu_bo_unref(&bo);
+		return ret;
+	}
+
+	ret = drm_pagemap_migrate_to_devmem(&svm_bo->devmem,
+					     mm, start, end,
+					     &mdetails);
+
+	amdgpu_bo_unreserve(&svm_bo->bo);
+
+	return ret;
+}
+
 /**
  * amdgpu_pagemap_destroy_work - Deferred destruction of amdgpu_pagemap
  * @work: work_struct embedded in amdgpu_pagemap
@@ -148,6 +748,8 @@ static void amdgpu_pagemap_destroy(struct drm_pagemap *dpagemap,
 
 const struct drm_pagemap_ops amdgpu_svm_drm_pagemap_ops = {
 	.destroy = amdgpu_pagemap_destroy,
+	.device_map = amdgpu_svm_device_map,
+	.populate_mm = amdgpu_svm_populate_mm,
 };
 
 /**
drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h +3 -0
index f5f726a740469..56c66851f0a47 100644
@@ -31,6 +31,9 @@
 
 struct amdgpu_device;
 
+#define AMDGPU_INTERCONNECT_VRAM	DRM_INTERCONNECT_DRIVER
+#define AMDGPU_INTERCONNECT_P2P		(AMDGPU_INTERCONNECT_VRAM + 1)
+
 /*
  * AMDGPU_PGMAP_OWNER - Unique owner token for dev_pagemap registration.
  *
Signature · 1 line
2.53.0
author
#19 lore raw

PATCH v11 19/22 drm/amdgpu: implement synchronous TTM eviction for SVM BOs

In reply to Huang Rui

From: Junhua Shen <[email protected]>

Implement the TTM eviction path for SVM (Shared Virtual Memory) BOs, enabling VRAM overcommit scenarios where device-private pages must be migrated back to system memory when VRAM is full.

- amdgpu_ttm.c: Add SVM BO detection in amdgpu_evict_flags() to evict directly to SYSTEM domain. Add SVM BO handling in amdgpu_bo_move() to call amdgpu_svm_bo_evict() for VRAM->SYSTEM transitions, which synchronously migrates device-private pages back to RAM via SDMA.

- amdgpu_migrate.c: Add amdgpu_svm_bo_evict() and
amdgpu_svm_bo_is_svm() helpers.

- amdgpu_object.c: Register SVM BO destroy callback in amdgpu_bo_is_amdgpu_bo() so TTM eviction can identify and handle SVM BOs correctly.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c | 46 +++++++++++++++++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h | 12 ++++++
 drivers/gpu/drm/amd/amdgpu/amdgpu_object.c  |  4 +-
 drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c     | 20 +++++++++
 4 files changed, 81 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.c +46 -0
index e7d2c6167adb1..5fbc6d1317743 100644
@@ -64,6 +64,7 @@
 #include <drm/drm_pagemap.h>
 #include <linux/memremap.h>
 #include <linux/migrate.h>
+#include <linux/sched/mm.h>
 
 #include "amdgpu_migrate.h"
 #include "amdgpu.h"
@@ -598,6 +599,51 @@ static const struct drm_pagemap_devmem_ops amdgpu_pagemap_ops = {
 	.copy_to_ram         = amdgpu_svm_copy_to_ram,
 };
 
+/**
+ * amdgpu_svm_bo_evict - Evict SVM BO by migrating device pages back to RAM
+ * @bo: The amdgpu_bo to evict (must be an amdgpu_bo_svm)
+ *
+ * Called from amdgpu_bo_move() when TTM needs to evict a SVM BO from VRAM.
+ * Uses drm_pagemap_evict_to_ram() to synchronously migrate all device-private
+ * pages back to system memory via SDMA.
+ *
+ * Return: 0 on success, negative error code on failure
+ */
+int amdgpu_svm_bo_evict(struct amdgpu_bo *bo)
+{
+	struct amdgpu_bo_svm *sbo = to_amdgpu_bo_svm(bo);
+	struct mm_struct *mm = sbo->devmem.mm;
+	int r;
+
+	/*
+	 * If the owning process is exiting, there is nothing to migrate; return
+	 * -EBUSY so the TTM eviction LRU walk skips this BO instead of aborting
+	 * the whole walk (which would fail the allocation that triggered the
+	 * eviction). Hold an mm reference across the call so the framework's own
+	 * dead-mm path stays unreachable and any -EFAULT it returns is
+	 * unambiguously a real error.
+	 */
+	if (!mmget_not_zero(mm))
+		return -EBUSY;
+
+	r = drm_pagemap_evict_to_ram(&sbo->devmem);
+
+	mmput_async(mm);
+
+	return r;
+}
+
+/**
+ * amdgpu_svm_bo_is_svm - Check if a TTM BO is an SVM BO
+ * @tbo: TTM buffer object
+ *
+ * Return: true if this is an amdgpu_bo_svm (identified by destroy callback)
+ */
+bool amdgpu_svm_bo_is_svm(struct ttm_buffer_object *tbo)
+{
+	return tbo->destroy == &amdgpu_bo_svm_destroy;
+}
+
 /* drm_pagemap_ops — top-level migration entry points */
 
 /**
drivers/gpu/drm/amd/amdgpu/amdgpu_migrate.h +12 -0
index 56c66851f0a47..e9159e8167dd7 100644
@@ -30,6 +30,8 @@
 #include <linux/workqueue.h>
 
 struct amdgpu_device;
+struct amdgpu_bo;
+struct ttm_buffer_object;
 
 #define AMDGPU_INTERCONNECT_VRAM	DRM_INTERCONNECT_DRIVER
 #define AMDGPU_INTERCONNECT_P2P		(AMDGPU_INTERCONNECT_VRAM + 1)
@@ -75,12 +77,22 @@ struct amdgpu_pagemap {
 
 #if IS_ENABLED(CONFIG_DRM_AMDGPU_SVM)
 int amdgpu_svm_migration_init(struct amdgpu_device *adev);
+int amdgpu_svm_bo_evict(struct amdgpu_bo *bo);
+bool amdgpu_svm_bo_is_svm(struct ttm_buffer_object *tbo);
 #else
 static inline
 int amdgpu_svm_migration_init(struct amdgpu_device *adev)
 {
 	return 0;
 }
+static inline int amdgpu_svm_bo_evict(struct amdgpu_bo *bo)
+{
+	return -ENODEV;
+}
+static inline bool amdgpu_svm_bo_is_svm(struct ttm_buffer_object *tbo)
+{
+	return false;
+}
 #endif
 
 /**
drivers/gpu/drm/amd/amdgpu/amdgpu_object.c +3 -1
index 6aa895f63aeaf..1ddba17712ad3 100644
@@ -44,6 +44,7 @@
 #include "amdgpu_vm.h"
 #include "amdgpu_dma_buf.h"
 #include "kfd_svm.h"
+#include "amdgpu_migrate.h"
 
 /**
  * DOC: amdgpu_object
@@ -95,7 +96,8 @@ bool amdgpu_bo_is_amdgpu_bo(struct ttm_buffer_object *bo)
 {
 	if (bo->destroy == &amdgpu_bo_destroy ||
 	    bo->destroy == &amdgpu_bo_user_destroy ||
-	    bo->destroy == &svm_range_bo_destroy)
+	    bo->destroy == &svm_range_bo_destroy ||
+	    amdgpu_svm_bo_is_svm(bo))
 		return true;
 
 	return false;
drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c +20 -0
index 8dfa92967b630..e81bd39ab4ff2 100644
@@ -60,6 +60,7 @@
 #include "amdgpu_hmm.h"
 #include "amdgpu_atomfirmware.h"
 #include "amdgpu_res_cursor.h"
+#include "amdgpu_migrate.h"
 #include "bif/bif_4_1_d.h"
 #include "kfd_svm.h"
 
@@ -123,6 +124,15 @@ static void amdgpu_evict_flags(struct ttm_buffer_object *bo,
 		return;
 	}
 
+	/* SVM BOs must evict directly to system memory for drm_pagemap
+	 * migration back to RAM in amdgpu_bo_move().
+	 */
+	if (amdgpu_svm_bo_is_svm(bo)) {
+		amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
+		*placement = abo->placement;
+		return;
+	}
+
 	switch (bo->resource->mem_type) {
 	case AMDGPU_PL_GDS:
 	case AMDGPU_PL_GWS:
@@ -611,6 +621,16 @@ static int amdgpu_bo_move(struct ttm_buffer_object *bo, bool evict,
 		abo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
 	}
 
+	/* SVM BO eviction: migrate device-private pages back to RAM */
+	if (amdgpu_svm_bo_is_svm(bo) &&
+	    old_mem->mem_type == TTM_PL_VRAM &&
+	    new_mem->mem_type == TTM_PL_SYSTEM) {
+		r = amdgpu_svm_bo_evict(abo);
+		if (!r)
+			ttm_bo_move_null(bo, new_mem);
+		return r;
+	}
+
 	if (adev->mman.buffer_funcs_enabled &&
 	    ((old_mem->mem_type == TTM_PL_SYSTEM &&
 	      new_mem->mem_type == TTM_PL_VRAM) ||
Signature · 1 line
2.53.0
author
#20 lore raw

PATCH v11 20/22 drm/amdgpu: hook up ZONE_DEVICE registration in device init and reset

In reply to Huang Rui

From: Junhua Shen <[email protected]>

Call amdgpu_svm_migration_init() in the device initialization and XGMI reset-restore paths to register the GPU's VRAM as a ZONE_DEVICE region before KFD initialization.

This activates the drm_pagemap migration infrastructure.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 2 ++
 drivers/gpu/drm/amd/amdgpu/amdgpu_reset.c  | 2 ++
 2 files changed, 4 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +2 -0
index b249c169a39e0..01c287d72e58b 100644
@@ -81,6 +81,7 @@
 #include "amdgpu_reset.h"
 #include "amdgpu_virt.h"
 #include "amdgpu_dev_coredump.h"
+#include "amdgpu_migrate.h"
 
 #include <linux/suspend.h>
 #include <drm/task_barrier.h>
@@ -4216,6 +4217,7 @@ int amdgpu_device_init(struct amdgpu_device *adev,
 
 	/* Don't init kfd if whole hive need to be reset during init */
 	if (adev->init_lvl->level != AMDGPU_INIT_LEVEL_MINIMAL_XGMI) {
+		amdgpu_svm_migration_init(adev);
 		kgd2kfd_init_zone_device(adev);
 		kfd_update_svm_support_properties(adev);
 	}
drivers/gpu/drm/amd/amdgpu/amdgpu_reset.c +2 -0
index c8016fa55a92f..571dd062547ce 100644
@@ -26,6 +26,7 @@
 #include "sienna_cichlid.h"
 #include "smu_v13_0_10.h"
 #include "soc_v1_0.h"
+#include "amdgpu_migrate.h"
 
 static int amdgpu_reset_xgmi_reset_on_init_suspend(struct amdgpu_device *adev)
 {
@@ -88,6 +89,7 @@ static int amdgpu_reset_xgmi_reset_on_init_restore_hwctxt(
 		return r;
 	list_for_each_entry(tmp_adev, reset_device_list, reset_list) {
 		if (!tmp_adev->kfd.init_complete) {
+			amdgpu_svm_migration_init(tmp_adev);
 			kgd2kfd_init_zone_device(tmp_adev);
 			amdgpu_amdkfd_device_init(tmp_adev);
 			amdgpu_amdkfd_drm_client_create(tmp_adev);
Signature · 1 line
2.53.0
author
#21 lore raw

PATCH v11 21/22 drm/amdgpu: add SVM range migration helpers for drm_pagemap

In reply to Huang Rui

From: Junhua Shen <[email protected]>

Add amdgpu_svm_range_migrate.c/.h implementing the per-range migration helpers for SVM VRAM migration via drm_pagemap:

- Implement range_needs_migrate_to_vram() checking migrate_devmem capability and current backing location.
- Add amdgpu_svm_range_migrate_to_vram() wrapping drm_pagemap_populate_mm() for RAM-to-VRAM migration. On -EBUSY (partial migration due to races), evict conflicting pages back to system memory via drm_gpusvm_range_evict() and retry once.
- Add amdgpu_pagemap_capable() to check device memory support.

---
 drivers/gpu/drm/amd/amdgpu/Makefile           |   2 +-
 .../drm/amd/amdgpu/amdgpu_svm_range_migrate.c | 120 ++++++++++++++++++
 .../drm/amd/amdgpu/amdgpu_svm_range_migrate.h |  35 +++++
 3 files changed, 156 insertions(+), 1 deletion(-)
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range_migrate.c
 create mode 100644 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range_migrate.h
drivers/gpu/drm/amd/amdgpu/Makefile +1 -1
index 66f4a4d2d451e..a110576ba1b2e 100644
@@ -332,7 +332,7 @@ amdgpu-$(CONFIG_HMM_MIRROR) += amdgpu_hmm.o
 
 # svm support
 amdgpu-$(CONFIG_DRM_AMDGPU_SVM) += amdgpu_svm.o amdgpu_svm_attr.o \
-	amdgpu_svm_fault.o amdgpu_svm_range.o amdgpu_migrate.o
+	amdgpu_svm_fault.o amdgpu_svm_range.o amdgpu_svm_range_migrate.o amdgpu_migrate.o
 
 include $(FULL_AMD_PATH)/pm/Makefile
 
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range_migrate.c new file +120 -0

120 lines not on this page · raw message

drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range_migrate.h new file +35 -0
new file mode 100644
index 0000000000000..6e4b6e45512e7
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-2.0 OR MIT */
+/*
+ * Copyright 2026 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#ifndef __AMDGPU_SVM_RANGE_MIGRATE_H__
+#define __AMDGPU_SVM_RANGE_MIGRATE_H__
+
+struct amdgpu_svm;
+struct drm_gpusvm_range;
+
+bool amdgpu_pagemap_capable(struct amdgpu_svm *svm);
+int amdgpu_svm_range_migrate_to_vram(struct amdgpu_svm *svm,
+				     struct drm_gpusvm_range *range);
+
+#endif /* __AMDGPU_SVM_RANGE_MIGRATE_H__ */
Signature · 1 line
2.53.0
author
#22 lore raw

PATCH v11 22/22 drm/amdgpu: integrate VRAM migration into SVM fault and prefetch paths

In reply to Huang Rui

From: Junhua Shen <[email protected]>

- Call amdgpu_svm_range_migrate_to_vram() before GPU mapping in fault and prefetch paths when VRAM migration is needed
- Set device_private_page_owner in drm_gpusvm_ctx for devmem awareness
- Allow AMDGPU_INTERCONNECT_VRAM entries in update_gpu_range proto check
- Skip valid-mapping fast path in prefetch when VRAM migration is requested, so prefetch can actively move pages to VRAM
- Enable amdgpu_pagemap_capable() check in amdgpu_svm_devmem_possible()
- Move AMDGPU_INTERCONNECT_VRAM/P2P defines to migration header

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c       |  4 ++-
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h       |  3 --
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.c | 11 ++++++-
 drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c | 32 ++++++++++++++++---
 4 files changed, 41 insertions(+), 9 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_svm.c +3 -1
index 8036ee189269f..206a0364b07c0 100644
@@ -35,6 +35,7 @@
 #include "amdgpu_svm_attr.h"
 #include "amdgpu_svm_fault.h"
 #include "amdgpu_svm_range.h"
+#include "amdgpu_svm_range_migrate.h"
 #include "amdgpu_vm.h"
 
 #if IS_ENABLED(CONFIG_DRM_AMDGPU_SVM)
@@ -300,7 +301,8 @@ bool amdgpu_svm_devmem_possible(struct amdgpu_svm *svm)
 	if (svm->adev->apu_prefer_gtt)
 		return false;
 
-	/* TODO: add amdgpu_pagemap_capable() */
+	if (amdgpu_pagemap_capable(svm))
+		return true;
 
 	return false;
 }
drivers/gpu/drm/amd/amdgpu/amdgpu_svm.h +0 -3
index e8a9df974988e..48f0a399d5324 100644
@@ -45,9 +45,6 @@ struct amdgpu_svm_attrs;
 struct drm_device;
 struct drm_file;
 
-#define AMDGPU_INTERCONNECT_VRAM DRM_INTERCONNECT_DRIVER
-#define AMDGPU_INTERCONNECT_P2P (AMDGPU_INTERCONNECT_VRAM + 1)
-
 enum amdgpu_svm_xnack_mode {
 	AMDGPU_SVM_XNACK_OFF,
 	AMDGPU_SVM_XNACK_ON,
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_fault.c +10 -1
index aabe11cf88aed..6ef3f2a5c54e2 100644
@@ -26,6 +26,8 @@
 #include "amdgpu_svm_attr.h"
 #include "amdgpu_svm_fault.h"
 #include "amdgpu_svm_range.h"
+#include "amdgpu_svm_range_migrate.h"
+#include "amdgpu_migrate.h"
 #include "amdgpu.h"
 #include "amdgpu_vm.h"
 #include "amdgpu_gmc.h"
@@ -189,6 +191,8 @@ static int fault_map_range(struct amdgpu_svm *svm, unsigned long fault_addr,
 		.check_pages_threshold = devmem_possible ? SZ_64K : 0,
 		.devmem_only = need_vram_migration,
 		.timeslice_ms = need_vram_migration ? 5 : 0,
+		.device_private_page_owner = devmem_possible ?
+			AMDGPU_PGMAP_OWNER(svm->adev) : NULL,
 	};
 	struct amdgpu_svm_range *range;
 	ktime_t timestamp = ktime_get_boottime();
@@ -251,7 +255,12 @@ static int fault_map_range(struct amdgpu_svm *svm, unsigned long fault_addr,
 	}
 
 	AMDGPU_SVM_RANGE_TRACE(range, "PAGE FAULT");
-	/* TODO: add migration*/
+	if (need_vram_migration) {
+		AMDGPU_SVM_RANGE_TRACE(range, "MIGRATE PAGES");
+		ret = amdgpu_svm_range_migrate_to_vram(svm, &range->base);
+		if (ret)
+			return ret;
+	}
 
 	AMDGPU_SVM_RANGE_TRACE(range, "GET PAGES");
 	ret = amdgpu_svm_range_get_pages(svm, &range->base, &map_ctx);
drivers/gpu/drm/amd/amdgpu/amdgpu_svm_range.c +28 -4
index adb9a0730ebf4..fe2a46f608a95 100644
@@ -26,6 +26,8 @@
 #include "amdgpu_svm_attr.h"
 #include "amdgpu_svm_range.h"
 #include "amdgpu_svm_fault.h"
+#include "amdgpu_svm_range_migrate.h"
+#include "amdgpu_migrate.h"
 #include "amdgpu.h"
 #include "amdgpu_vm.h"
 #include "amdgpu_trace.h"
@@ -125,11 +127,19 @@ int amdgpu_svm_range_update_gpu_range(struct amdgpu_svm *svm, struct amdgpu_svm_
 		unsigned long start_page, last_page;
 		bool is_last_seg;
 
-		if (entry->proto != DRM_INTERCONNECT_SYSTEM)
+		if (entry->proto == DRM_INTERCONNECT_SYSTEM) {
+			pte_mem.mem_type = TTM_PL_TT;
+			pte_flags |= AMDGPU_PTE_SYSTEM | AMDGPU_PTE_SNOOPED;
+		} else if (entry->proto == AMDGPU_INTERCONNECT_VRAM) {
+			pte_mem.mem_type = TTM_PL_VRAM;
+		} else {
 			return -EOPNOTSUPP;
-		pte_flags |= AMDGPU_PTE_SYSTEM | AMDGPU_PTE_SNOOPED;
+		}
 
-		amdgpu_gmc_get_vm_pte(svm->adev, svm->vm, &pte_mem, vm_flags, &dst, &pte_flags);
+		/* VRAM entries already carry vram_base_offset from device_map */
+		amdgpu_gmc_get_vm_pte(svm->adev, svm->vm, &pte_mem, vm_flags,
+				      entry->proto == AMDGPU_INTERCONNECT_VRAM ? NULL : &dst,
+				      &pte_flags);
 
 		start_page = range_start_page + mapped_pages;
 		last_page = start_page + seg_pages - 1;
@@ -280,6 +290,8 @@ int amdgpu_svm_range_map_attrs(struct amdgpu_svm *svm, const struct amdgpu_svm_a
 		.devmem_possible = devmem_possible,
 		.devmem_only = need_vram_migration,
 		.check_pages_threshold = devmem_possible ? SZ_64K : 0,
+		.device_private_page_owner = devmem_possible ?
+			AMDGPU_PGMAP_OWNER(svm->adev) : NULL,
 	};
 
 	if (!amdgpu_svm_attr_has_access(attrs->access))
@@ -302,7 +314,14 @@ int amdgpu_svm_range_map_attrs(struct amdgpu_svm *svm, const struct amdgpu_svm_a
 		if (next_addr <= addr)
 			return -EINVAL;
 
-		if (amdgpu_svm_range_is_valid(range, attrs) && !prefetch_sysmem) {
+		/*
+		 * Prefetch to device memory should still run migration logic even if
+		 * the current GPU mapping is already valid. This allows prefetch
+		 * requests to actively move backing pages to VRAM instead of being
+		 * skipped by the valid-mapping fast path.
+		 */
+		if (amdgpu_svm_range_is_valid(range, attrs) && !prefetch_sysmem &&
+		    !need_vram_migration) {
 			addr = next_addr;
 			continue;
 		}
@@ -311,6 +330,11 @@ int amdgpu_svm_range_map_attrs(struct amdgpu_svm *svm, const struct amdgpu_svm_a
 			ret = drm_gpusvm_range_evict(&svm->gpusvm, &range->base);
 			if (ret)
 				return ret;
+		} else if (need_vram_migration) {
+			AMDGPU_SVM_RANGE_TRACE(range, "MIGRATE PAGES");
+			ret = amdgpu_svm_range_migrate_to_vram(svm, &range->base);
+			if (ret)
+				return ret;
 		}
 
 		AMDGPU_SVM_RANGE_TRACE(range, "GET PAGES");
Signature · 1 line
2.53.0