Linux-mm Archive on lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v18 00/14] migrate on fault for device pages
@ 2026-12-01  4:55 mpenttil
  2026-12-01  4:55 ` [PATCH v18 01/14] mm/Kconfig: changes for " mpenttil
                   ` (13 more replies)
  0 siblings, 14 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

Currently, the way device page faulting and migration works is not
optimal, if you want to do both fault handling and migration at once.

Being able to migrate not present pages (or pages mapped with incorrect
permissions, eg. COW) to the GPU requires doing either of the following
sequences:

1. hmm_range_fault() - fault in non-present pages with correct
   permissions, etc.
2. migrate_vma_*() - migrate the pages

Or:

1. migrate_vma_*() - migrate present pages
2. If non-present pages detected by migrate_vma_*():
   a) call hmm_range_fault() to fault pages in
   b) call migrate_vma_*() again to migrate now present pages

The problem with the first sequence is that you always have to do two
page walks even when most of the time the pages are present or zero page
mappings so the common case takes a performance hit.

The second sequence is better for the common case, but far worse if
pages aren't present because now you have to walk the page tables three
times (once to find the page is not present, once so hmm_range_fault()
can find a non-present page to fault in and once again to setup
the migration).

It is also tricky to code correctly. Today, drivers such as Xe implement
migrate-on-fault through multiple HMM page-table walks and migrate_vma
calls. This requires additional presence checks, range-size adjustments,
and retries to handle non-present pages, partial migration collection,
and concurrent page-table changes. The resulting complexity and repeated
walks are consequences of the missing MM primitive.
This series allows faults to be resolved and pages collected for
migration in a single walk, simplifying the implementation and reducing
the race windows between separate operations.
One page table walk could cost over 1000 cpu cycles on x86-64, which is
a significant hit.

We should be able to walk the page table once, faulting pages in as
required and replacing them with migration entries if requested. The
current collector can't fault-in, so add a HMM based collector that can
do the same as current one, and additionally fault in if asked.

Add a new flag to HMM APIs, HMM_PFN_REQ_MIGRATE, which asks
hmm_range_fault() to prepare the pages for migration during fault
handling. For the migrate_vma_setup() call paths, new flags,
MIGRATE_VMA_FAULT and MIGRATE_VMA_WRITE, add fault handling to
migration.

This series also avoids a problem in the current collector, where
a racing MADV_DONTNEED could make the collecting arrays overflow.
Collecting into an address-indexed hmm_pfns array, with stale entries
rolled back on revisit, removes that class of append overruns. Fixes
like "mm/migrate_device: don't collect a range twice", now in rc5,
address it case by case in the old collector (that patch prevents the
crash, but entries collected before the lock was dropped are not checked
again - that would need rollback and re-collect). The new collector
covers the cases fixed in rc5 as well, and the series has been checked
with AI review (sashiko) for both the existing non-faulting flows and
the new faulting ones.

An extra benefit of migrating with hmm_range_fault() path is the
migrate_vma.vma gets populated by the flow, so no need to retrieve
that separately.

Tested in x86-64 VM with HMM test device, passing the selftests,
and verified not to have regressions for current migrate_vma_setup()
callers.

For nouveau migrate-on-fault the test harness was: Fedora 44, Mesa
Rusticl, and a fine-grained-system-SVM OpenCL program.
Nouveau SVM is opt-in via Mesa. The OpenCL program passes a plain
malloc pointer (64 pages, array of integers) to the GPU, increments each
element on the GPU, and verifies the result on the CPU.
So it drives both directions of migration. With svm_migrate_on_fault=1,
no migration at bind happens. The GPU used in testing was Pascal
generation GP102.

LLM tools were used to identify some of the pre existing problems in
current nouveau SVM implementation. This series comes with two patches,
"drm/nouveau/dmem: serialize the copy channel users" and
"drm/nouveau/dmem: commit migrate_to_ram() only after the copy is confirmed",
which directly impacted nouveau SVM working in testing.
Quite a comprehensive HW testing was done, and with the series nouveau
SVM was usable. A follow-up series will fix further pre-existing issues.
Also, a follow-up fix on test_hmm.c will fix its pre existing races wrt
invalidations with multiple fds, as noted by Andrew and Aveline also.

Changes in v18:
  - Cover letter changes
  - rebased on v7.4-rc5 (drm-tip)
  - addressed all sashiko's concerns
  - improved selftest robustness (patch 10)
  - KSM folios are not collected (patch 06)
  - added uffd checks for collect
  - added guard for shadow stack areas
  - split two independent nouveau dmem fixes into their own patches
    (12, 13)

Sashiko's concerns in v17
https://sashiko.dev/#/patchset/20261103061629.972669-1-mpenttil%40redhat.com

Answers to sashiko's concerns:

patch 03
  Q "Will this break the build when CONFIG_HMM_MIRROR=y and
  CONFIG_MIGRATION=n?"
  A fixed in v18
  Q "Can unconditionally calling memset() on range->hmm_pfns"
  A fixed in v18

patch 04
  Q "Question about failed split and continuation after it.."
  A When migrating, the caller only uses the entries collected for
  migration, so faulting is best effort there. Since v17 the pfns are
  cleared on entry, so entries skipped after a failed split are reliably
  0 rather than stale. v18 documents that, with HMM_PFN_REQ_MIGRATE,
  hmm_range_fault() may return 0 with such entries left unpopulated,
  and that callers check HMM_PFN_VALID/HMM_PFN_MIGRATE per entry. This
  mirrors migrate_vma_collect_skip().

patch 05
  Q "Should the anon check happen before splitting?"
  A Yes. In v18 the check moves ahead of the split at pte level.
  Q "Should we also reject folio_test_ksm()?"
  A Yes. In v18 KSM folios are not collected, as in Chris Mason's
  pending fix for migrate_vma_collect_pmd(): rmap_walk_ksm() may miss a
  fresh KSM mapping when restoring the migration entry. When faulting,
  KSM pages weren't collected anyway (never PageAnonExclusive).
  The second mapping's stale pfn in hmm_pfns is covered by the notifier:
  try_to_migrate() unmaps it with an MMU_NOTIFY_CLEAR invalidation, so
  the caller's mmu_interval_read_retry() fails before it maps the device
  from that pfn.
  Q "Again question about failed split..."
  A A failed split skips the rest of that pmd range, as
  migrate_vma_collect_skip() does today, and the walk continues with the
  next pmd. v18 documents that with HMM_PFN_REQ_MIGRATE faulting is best
  effort and that such entries are left 0 even with HMM_PFN_REQ_FAULT,
  so callers check HMM_PFN_VALID/HMM_PFN_MIGRATE per entry. Since
  the pfns are cleared on entry, the skipped entries are reliably 0
  rather than stale.

patch 06
  Q "Can calling folio_lock(folio) in migrate_vma_split_folio() cause an
  ABBA deadlock when another folio is already held locked in the walk?"
  A The blocking lock came from the existing migrate_vma_split_folio(),
  which has the same exposure. In v18 the split path only trylocks,
  like collection; a busy folio is not migrated and is handled like
  a failed split.
  Q "How are PMD-mapped MEMORY_DEVICE_COHERENT folios handled here?"
  A v18 applies the pte-level checks at the pmd level too: a
  device-coherent THP needs MIGRATE_VMA_SELECT_DEVICE_COHERENT and a
  matching pgmap owner, and SELECT_SYSTEM no longer picks it up.
  Q "Should hmm_vma_handle_migrate_prepare_pmd() check
  folio_test_anon(folio) before collecting or splitting a PMD-mapped
  folio?"
  A Fixed together with the pte level fix.
  Q "Could hmm_vma_walk_pmd() similarly loop locally to the again label
  when hmm_vma_handle_migrate_prepare_pmd() splits the PMD?"
  A It could, as the pte level does, but returning -EBUSY is deliberate.
  The split sends an MMU_NOTIFY_CLEAR invalidation, so with a notifier
  the walk ends with -EBUSY, and the caller aborts and retries the range
  under its own retry policy, including its timeout. That costs one
  extra pass per huge pmd split, which is rare. Without a notifier, the
  retry loop in hmm_range_fault_locked() walks the range again as PTEs.

patch 08
  Q "When hmm_range_fault_locked() aborts with -EBUSY.."
  A Same as the patch 03 comment, fixed in v18.
  Q "If the migration PTEs or PTE page table covering
  [range->start, addr) were zapped...can those earlier collected entries
  in range->hmm_pfns ever be revisited or rolled back, or will they leak
  folio locks and references?"
  A No leak: entries collected below last stay marked in
  range->hmm_pfns, and the caller completes or aborts them
  through migrate_hmm_range_setup(), migrate_vma_pages() and
  migrate_vma_finalize(), which unlocks and puts every collected folio.
  If a migration pte was zapped in the meantime, remove_migration_ptes()
  just finds nothing, the same as when that happens between
  migrate_vma_setup() and migrate_vma_finalize() today. The zap also
  invalidates the range, so the caller's mmu_interval_read_retry() keeps
  it from mapping the stale entry. Rollback on revisit is only needed
  for entries the walk visits again.

  Q "if migration PTEs or the PTE table in [start, end) vanished during
  that window, won't returning 0 without re-walking [start, end) skip
  rolling back those collected folios,..."
  A In v18 the split path only trylocks, taken before the PTE lock
  is dropped, so there's no sleep there any more. Entries collected
  in [start, addr) that aren't revisited stay marked and are released
  by the caller's migrate_vma_pages()/migrate_vma_finalize(), even
  if their migration ptes vanished; rollback is only needed for
  entries the walk visits again. Leaving the rest of the pmd range 0
  after a failed split is the documented best effort behaviour, as in
  migrate_vma_collect_skip().

patch 09
  Q "Are MIGRATE_VMA_FAULT and MIGRATE_VMA_WRITE in enum
  migrate_vma_info and their handling in migrate_vma_setup() needed when
  there are no in-tree callers?"
  A They're kept on purpose: they are the migrate-on-fault entry point
  for existing migrate_vma_setup() users. Without them, pages that
  aren't present (swapped out, or another device's private pages) are
  skipped, and shared pages are migrated as they are, read-only for
  every process mapping them. With the flags, migrate_vma_setup() faults
  the missing pages in (and MIGRATE_VMA_WRITE breaks the sharing first)
  in the same walk, instead of needing a separate hmm_range_fault() or
  GUP pass first. It's two flag checks on top of the hmm_range_fault()
  path that test_hmm and nouveau use directly. The v18 commit log
  explains this.
  Q "Question about possible build break.."
  A The build issue with CONFIG_MIGRATION=n is fixed in v18
  (the pgmap_owner check goes through a migrate.h helper
  with a !CONFIG_MIGRATION stub). With CONFIG_MIGRATION=y
  and CONFIG_DEVICE_MIGRATION=n it builds and is harmless:
  the collection functions in mm/hmm.c are stubs then, and
  migrate_hmm_range_setup()/migrate_vma_*() aren't built, so there
  can be no migrating caller. The helpers follow the existing
  migrate.h convention, where the migrate_vma API is declared under
  CONFIG_MIGRATION and built with CONFIG_DEVICE_MIGRATION.
  Q This is the memset/-EBUSY issue a third time.
  A Fixed in v18 (same as patch 03 comment).

  Q "while hmm_do_fault() runs, a concurrent MADV_DONTNEED can zap
  migration ptes we already collected below last. The walk doesn't
  re-check them, so finalize finds no pte to restore and frees dst. Is
  that a use-after-free if the device has already mapped dst?"
  A No. The same window exists in mainline between migrate_vma_setup()
  and migrate_vma_finalize(). The zap sends an invalidation, so a
  driver's mmu notifier sequence check fails before it maps device
  memory. nouveau and test_hmm do that check. Collected entries stay
  collected and finalize releases them, so no rollback is needed.

  Q.1 "migrate_vma_split_folio()-> folio_lock() possible deadlock?"
  Q.2 "when HMM_PFN_REQ_FAULT is set, a migrating walk can meet another
  thread's migration entry and wait on it in hmm_do_fault(), while still
  holding the folios it has already collected. Can that deadlock?"
  A.1 migrate_vma_split_folio() now takes folio_trylock.
  A.2 Fixed in v18: a migrating walk never waits for another migration.
  Such entries are left uncollected (best effort).

  Q "the pmd level has no folio_test_anon() check, so could a file or
  shmem THP be collected or split?"
  A That's already fixed in v18 (from previous comments).
  hmm_vma_handle_migrate_prepare_pmd() now skips non-anonymous THPs
  before locking, collecting or splitting them, as the pte level does.

  Q "a failed split returns 0, which leaves the rest of the pmd
  unwalked. After a restart, it also leaves entries collected above addr
  in the earlier pass unchecked and not rolled back."
  A Skipping the rest is the documented best-effort behaviour. Entries
  collected earlier, above or below addr, stay collected and are
  released by the caller's finalize, so no rollback is needed for
  entries that aren't revisited.

  Q "a writable protnone pte or pmd is collected without HMM_PFN_WRITE,
  so MIGRATE_PFN_WRITE is lost.."
  A Valid. v18 sets HMM_PFN_WRITE from the pte or pmd write bit when
  collecting, as mainline did.

patch 10
  Q "test_hmm retries inside dmirror_range_fault() without aborting the
  collected entries. Does the memset then hide our own entries, causing
  a self-deadlock and leaks? And does a timeout leave stale state from
  the previous chunk?"
  A Both are fixed in v18. The migrate case returns straight to
  do_fault_and_migrate(), which aborts before retrying. The timeout
  can't fire before that single hmm_range_fault() call.
  Q "if read_retry trips after migrate_vma_pages(), the dmirror mapping
  is skipped. The retry doesn't remap pages already committed, so the
  read-back in the ioctl fails with -ENOENT."
  A Valid for the test. The read-back now faults in unmapped pages, as
  dmirror_read() does and as a real device would.
  Q "can two 64-entry pfn arrays on the stack exceed
  -Wframe-larger-than, as happened before in test_hmm?"
  A v18 allocates src_pfns/dst_pfns with kvzalloc_objs(), as
  dmirror_migrate_to_device() does.

patch 11
  Q "Could this wording be clarified regarding what needs to be called
  when hmm_range_fault() returns an error?.."
  A Documentation changes in v18.

patch 12
  Q "dmem and TTM share ttm.chan, but dmem takes only migrate.lock
  while TTM takes only cli->mutex, so can they interleave pushes and
  corrupt fences?"
  A That's pre-existing in mainline, where dmem had no lock at all. This
  series serializes the dmem users. Using cli->mutex would ABBA with
  svmm->mutex through reclaim and the mmu notifier.
  The proper fix is a separate dmem channel, outside this series.
  Q "fence_done() now returns int, but nobody uses the result, and the
  commit log leaves out migrate.lock and the migrate_to_ram() rework."
  A Agreed on both. v18 restores the void fence_done() and describes
  both changes in the logs (now split into their own patches,
  12 and 13).
  Q "a pending replayable GPU fault stalls the copy engine. In
  migrate_to_ram() nobody replays, because the fault worker is blocked
  on our migration entry. In migrate on fault, the GPU can refault after
  the early replay. Does the fence poll then stall 30 s?"
  A Case 1 is the same dependency as mainline, which then commits the
  unfinished copy, whereas we abort safely after the deadline. Case 2
  follows the order that worked on HW: replay before the wait, and map
  only after the copy is confirmed.
  A timeout there aborts and falls back to mapping in place.
  Q "the abort clears MIGRATE_PFN_MIGRATE but leaves dst[i] set,
  and __migrate_device_pages() doesn't check MIGRATE when both pages
  exist. Doesn't that still move the mapping, flags and memcg to the
  destination, corrupting the source that finalize restores?"
  A Yes, fixed. v18's abort clears dst[i] (unlocking the destination and
  keeping its reference, so it's still leaked), so migrate_vma_pages()
  leaves the source alone.
  Q "in the fault path, the abort keeps the VRAM dst but lets finalize
  release the DMA-mapped system src, so isn't it pinning the wrong
  folio? And doesn't a leaked VRAM page hang driver teardown?"
  A It's the right folio. The copy engine only writes dst, and src
  is restored as the live page, where a stale read can't corrupt
  anything. The teardown point is true: it's the cost of not freeing
  memory a wedged engine might write, and a wedged engine needs a
  GPU reset anyway.
  Q "a GPU write fault on a read-only device-private VRAM page owned
  by nouveau is reported without WRITE. Is it then mapped read-only and
  replayed, refaulting forever?"
  A That's pre-existing. Mainline hmm_range_fault() doesn't fault
  the caller's own device-private pages for write, and mainline
  nouveau_range_fault() maps them read-only in the same way. The fix
  belongs in hmm_range_fault(), as a separate change.
  Q "should nouveau.svm_migrate_on_fault be documented in
  kernel-parameters.txt?"
  A No. No nouveau module parameter is listed there. They're documented
  through MODULE_PARM_DESC, which this one has, and it depends on the
  experimental SVM option.
  Q "why does bind skip the migration when svm_migrate_on_fault is on?
  It makes an explicit bind a no-op: pages already mapped in system
  memory never migrate, and THPs are split."
  A It's intentional. The parameter selects a simple, fully lazy policy
  where everything migrates on demand at GPU fault. Pages mapped in
  place and compound migration are things for the better policy the
  commit log already mentions.

Link to v17:
https://lore.kernel.org/linux-mm/20261103061629.972669-1-mpenttil@redhat.com/

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Lorenzo Stoakes <ljs@kernel.org>
Cc: "Liam R. Howlett" <liam@infradead.org>
Cc: Vlastimil Babka <vbabka@kernel.org>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Lyude Paul <lyude@redhat.com>
Cc: Danilo Krummrich <dakr@kernel.org>
Cc: Jonathan Corbet <corbet@lwn.net>
Cc: Shuah Khan <shuah@kernel.org>
Cc: Madhavan Srinivasan <maddy@linux.ibm.com>

Mika Penttilä (14):
  mm/Kconfig: changes for migrate on fault for device pages
  mm: add helper to convert HMM pfn to migrate pfn
  mm/hmm: preparations for HMM to participate in migration
  mm/hmm: do the plumbing for HMM to participate in migration
  mm/hmm: implement rollback for device page migration in HMM pagewalk
  mm/hmm: migrate collection in HMM pagewalk - pte level
  mm/hmm: migrate collection in HMM pagewalk - pmd level
  mm/hmm: add lazy MMU mode support for migration in HMM pagewalk
  mm: enable device page migration from HMM pagewalk
  lib/test_hmm: add a new testcase for the migrate on fault
  Documentation/mm/hmm: document migration through hmm_range_fault()
  drm/nouveau/dmem: serialize the copy channel users
  drm/nouveau/dmem: commit migrate_to_ram() only after the copy is
    confirmed
  drm/nouveau/svm: add support for migrate on fault

 Documentation/mm/hmm.rst                     |  123 +-
 arch/powerpc/include/asm/book3s/64/pgtable.h |    2 +-
 drivers/gpu/drm/drm_pagemap.c                |    2 +-
 drivers/gpu/drm/nouveau/nouveau_dmem.c       |  467 ++++++-
 drivers/gpu/drm/nouveau/nouveau_dmem.h       |   12 +
 drivers/gpu/drm/nouveau/nouveau_svm.c        |  164 ++-
 drivers/gpu/drm/nouveau/nouveau_svm.h        |    5 +
 include/linux/hmm.h                          |   32 +-
 include/linux/migrate.h                      |   75 +-
 include/linux/mmu_notifier.h                 |    3 +-
 lib/test_hmm.c                               |  217 +++-
 lib/test_hmm_uapi.h                          |   21 +-
 mm/Kconfig                                   |    1 +
 mm/hmm.c                                     | 1222 +++++++++++++++++-
 mm/migrate_device.c                          |  648 ++--------
 tools/testing/selftests/mm/hmm-tests.c       |   73 ++
 16 files changed, 2380 insertions(+), 687 deletions(-)

drm-tip
base-commit: 87312a33227c3d67b5dd786d81e093ca7a0cba56
--
2.55.0



^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v18 01/14] mm/Kconfig: changes for migrate on fault for device pages
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 02/14] mm: add helper to convert HMM pfn to migrate pfn mpenttil
                   ` (12 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan, Vlastimil Babka,
	Suren Baghdasaryan

From: Mika Penttilä <mpenttil@redhat.com>

HMM depends on MMU notifiers. With the unified HMM/migrate_device
page table walk migrate_device needs HMM enabled.
Enable them explicitly to avoid breaking random configs.

Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: David Hildenbrand <david@kernel.org>
Cc: Lorenzo Stoakes <ljs@kernel.org>
Cc: "Liam R. Howlett" <liam@infradead.org>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
Acked-by: David Hildenbrand (Arm) <david@kernel.org>
Acked-by: Balbir Singh <balbirs@nvidia.com>
---
 mm/Kconfig | 1 +
 1 file changed, 1 insertion(+)

diff --git a/mm/Kconfig b/mm/Kconfig
index afff1b25b543..6fa03655b575 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -682,6 +682,7 @@ config MIGRATION
 
 config DEVICE_MIGRATION
 	def_bool MIGRATION && ZONE_DEVICE
+	select HMM_MIRROR
 
 config ARCH_ENABLE_HUGEPAGE_MIGRATION
 	bool
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 02/14] mm: add helper to convert HMM pfn to migrate pfn
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
  2026-12-01  4:55 ` [PATCH v18 01/14] mm/Kconfig: changes for " mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 03/14] mm/hmm: preparations for HMM to participate in migration mpenttil
                   ` (11 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

The unified HMM/migrate_device pagewalk does the "collecting"
on the HMM side, so we need a helper to transfer pfns to the
migrate_vma world.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 include/linux/hmm.h     | 29 +++++++++++++++++-----
 include/linux/migrate.h |  3 ++-
 mm/migrate_device.c     | 55 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 80 insertions(+), 7 deletions(-)

diff --git a/include/linux/hmm.h b/include/linux/hmm.h
index 6f04e3932f5b..4f56f3419cb4 100644
--- a/include/linux/hmm.h
+++ b/include/linux/hmm.h
@@ -13,6 +13,8 @@
 
 struct mmu_interval_notifier;
 
+struct migrate_vma;
+
 /*
  * On output:
  * 0             - The page is faultable and a future call with 
@@ -27,13 +29,22 @@ struct mmu_interval_notifier;
  * HMM_PFN_P2PDMA_BUS - Bus mapped P2P transfer
  * HMM_PFN_DMA_MAPPED - Flag preserved on input-to-output transformation
  *                      to mark that page is already DMA mapped
+ * HMM_PFN_MIGRATE    - The entry is to be migrated. Note, HMM_PFN_MIGRATE
+ *                      alone without HMM_PFN_VALID denotes the
+ *                      empty page.
+ *                      This flag optionally together with HMM_PFN_COMPOUND
+ *                      are indicators for migrate_hmm_range_setup() to
+ *                      setup the migrate pfns.
+ * HMM_PFN_COMPOUND   - The entry represents a > 0 order page
  *
  * On input:
- * 0                 - Return the current state of the page, do not fault it.
- * HMM_PFN_REQ_FAULT - The output must have HMM_PFN_VALID or hmm_range_fault()
- *                     will fail
- * HMM_PFN_REQ_WRITE - The output must have HMM_PFN_WRITE or hmm_range_fault()
- *                     will fail. Must be combined with HMM_PFN_REQ_FAULT.
+ * 0                   - Return the current state of the page, do not fault it.
+ * HMM_PFN_REQ_FAULT   - The output must have HMM_PFN_VALID or hmm_range_fault()
+ *                       will fail
+ * HMM_PFN_REQ_WRITE   - The output must have HMM_PFN_WRITE or hmm_range_fault()
+ *                       will fail. Must be combined with HMM_PFN_REQ_FAULT.
+ * HMM_PFN_REQ_MIGRATE - For default_flags only, request to migrate the range,
+ *                       according to hmm_range.migrate.flags
  */
 enum hmm_pfn_flags {
 	/* Output fields and flags */
@@ -48,11 +59,15 @@ enum hmm_pfn_flags {
 	HMM_PFN_P2PDMA     = 1UL << (BITS_PER_LONG - 5),
 	HMM_PFN_P2PDMA_BUS = 1UL << (BITS_PER_LONG - 6),
 
-	HMM_PFN_ORDER_SHIFT = (BITS_PER_LONG - 11),
+	/* Migrate request */
+	HMM_PFN_MIGRATE    = 1UL << (BITS_PER_LONG - 7),
+	HMM_PFN_COMPOUND   = 1UL << (BITS_PER_LONG - 8),
+	HMM_PFN_ORDER_SHIFT = (BITS_PER_LONG - 13),
 
 	/* Input flags */
 	HMM_PFN_REQ_FAULT = HMM_PFN_VALID,
 	HMM_PFN_REQ_WRITE = HMM_PFN_WRITE,
+	HMM_PFN_REQ_MIGRATE = HMM_PFN_MIGRATE,
 
 	HMM_PFN_FLAGS = ~((1UL << HMM_PFN_ORDER_SHIFT) - 1),
 };
@@ -107,6 +122,7 @@ static inline unsigned int hmm_pfn_to_map_order(unsigned long hmm_pfn)
  * @default_flags: default flags for the range (write, read, ... see hmm doc)
  * @pfn_flags_mask: allows to mask pfn flags so that only default_flags matter
  * @dev_private_owner: owner of device private pages
+ * @migrate: structure for migrating a range of a VMA
  */
 struct hmm_range {
 	struct mmu_interval_notifier *notifier;
@@ -117,6 +133,7 @@ struct hmm_range {
 	unsigned long		default_flags;
 	unsigned long		pfn_flags_mask;
 	void			*dev_private_owner;
+	struct migrate_vma      *migrate;
 };
 
 /*
diff --git a/include/linux/migrate.h b/include/linux/migrate.h
index c6cce7925b9b..b778f8bba5a3 100644
--- a/include/linux/migrate.h
+++ b/include/linux/migrate.h
@@ -3,6 +3,7 @@
 #define _LINUX_MIGRATE_H
 
 #include <linux/mm.h>
+#include <linux/hmm.h>
 #include <linux/mempolicy.h>
 #include <linux/migrate_mode.h>
 #include <linux/hugetlb.h>
@@ -203,7 +204,7 @@ void migrate_device_pages(unsigned long *src_pfns, unsigned long *dst_pfns,
 			unsigned long npages);
 void migrate_device_finalize(unsigned long *src_pfns,
 			unsigned long *dst_pfns, unsigned long npages);
-
+void migrate_hmm_range_setup(struct hmm_range *range);
 #endif /* CONFIG_MIGRATION */
 
 #endif /* _LINUX_MIGRATE_H */
diff --git a/mm/migrate_device.c b/mm/migrate_device.c
index b4660eeb975a..5db01a728fce 100644
--- a/mm/migrate_device.c
+++ b/mm/migrate_device.c
@@ -1567,3 +1567,58 @@ int migrate_device_coherent_folio(struct folio *folio)
 		return 0;
 	return -EBUSY;
 }
+
+/**
+ * migrate_hmm_range_setup() - prepare to migrate a range of memory
+ * @range: contains pointer to struct migrate_vma to be set up.
+ *
+ * When collecting has been done with hmm_range_fault(), this
+ * should be called next, and completes range->migrate by
+ * populating migrate->src[] and migrate->dst[]
+ * using range->hmm_pfns[].
+ * Also, migrate->cpages and migrate->npages get initialized.
+ * After migrate_hmm_range_setup(), range->migrate is good
+ * for the rest of the migrate_vma_* flow.
+ */
+void migrate_hmm_range_setup(struct hmm_range *range)
+{
+	struct migrate_vma *migrate = range->migrate;
+
+	if (!migrate)
+		return;
+
+	migrate->npages = (migrate->end - migrate->start) >> PAGE_SHIFT;
+	migrate->cpages = 0;
+
+	for (unsigned long i = 0; i < migrate->npages; i++) {
+		unsigned long pfn = range->hmm_pfns[i];
+
+		/*
+		 * We are only interested in entries to be
+		 * migrated.
+		 */
+		if (!(pfn & HMM_PFN_MIGRATE)) {
+			migrate->src[i] = 0;
+			migrate->dst[i] = 0;
+			continue;
+		}
+
+		migrate->cpages++;
+
+		/* HMM_PFN_MIGRATE without HMM_PFN_VALID denotes the special zero page */
+		if (pfn & HMM_PFN_VALID)
+			migrate->src[i] = migrate_pfn(page_to_pfn(hmm_pfn_to_page(pfn)));
+		else
+			migrate->src[i] = 0;
+
+		migrate->src[i] |= MIGRATE_PFN_MIGRATE;
+		migrate->src[i] |= (pfn & HMM_PFN_WRITE) ? MIGRATE_PFN_WRITE : 0;
+		migrate->src[i] |= (pfn & HMM_PFN_COMPOUND) ? MIGRATE_PFN_COMPOUND : 0;
+		migrate->dst[i] = 0;
+	}
+
+	if (migrate->cpages)
+		migrate_vma_unmap(migrate);
+
+}
+EXPORT_SYMBOL(migrate_hmm_range_setup);
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 03/14] mm/hmm: preparations for HMM to participate in migration
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
  2026-12-01  4:55 ` [PATCH v18 01/14] mm/Kconfig: changes for " mpenttil
  2026-12-01  4:55 ` [PATCH v18 02/14] mm: add helper to convert HMM pfn to migrate pfn mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 04/14] mm/hmm: do the plumbing " mpenttil
                   ` (10 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

For migration to happen after hmm_range_fault(), the vma has to be
retrieved. Luckily, pagewalk already resolves that for us, so
just have to save it for further use. For migration, mmap_lock
has to be held for the whole operation, so vma stays stable.
In case lock-drop behavior is requested, return an error while
migrating. Also, rename some struct hmm_vma_walk fields to solve
namespace collisions, and we are later introducing more
xxlocked fields so be unambiguous.

Take care also of firing the mmu_notifier when migrating, and don't wait
for another migration's entries while migrating. A migrating walk
re-walks while holding collected folios and may have no notifier to end
it (migrate_vma_setup()), so a fatal signal pending after a fault ends
it with -EINTR. The vma restrictions match migrate_vma_setup(), and
shadow stack vmas are refused as well, as in the pending
"mm/migrate_device: refuse to migrate shadow stacks".

When migrating, requests come only from range->default_flags
(pfn_flags_mask must be 0), so the input range->hmm_pfns carry
nothing and are cleared at the start of hmm_range_fault(). Collected
entries (HMM_PFN_VALID | HMM_PFN_MIGRATE) can then be told apart
reliably during the walk and on rollback. This also means that
HMM_PFN_INOUT_FLAGS such as HMM_PFN_DMA_MAPPED are not preserved
across a migrating call, which is intended since the pages are being
replaced.

Also, prepare for differences of how mm_struct * is retrieved
in fault and migrate_vma paths.

Migration is still stubbed off here: hmm_select_migrate() returns
MIGRATE_VMA_SELECT_NONE until a later patch enables it, so none of this
takes effect yet. The enum migrate_vma_direction becomes
migrate_vma_info, as it also carries the fault flags added later, and
gets MIGRATE_VMA_SELECT_NONE. The small helpers hmm_select_migrate(),
hmm_fill_migrate_vma() and hmm_range_fault_mm() live in migrate.h next
to struct migrate_vma, which they use, with stubs for !CONFIG_MIGRATION.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 include/linux/hmm.h     |   7 +-
 include/linux/migrate.h |  66 ++++++++++++-
 lib/test_hmm.c          |   2 +-
 mm/hmm.c                | 208 +++++++++++++++++++++++++++++++++++-----
 4 files changed, 257 insertions(+), 26 deletions(-)

diff --git a/include/linux/hmm.h b/include/linux/hmm.h
index 4f56f3419cb4..e4cd255da1a2 100644
--- a/include/linux/hmm.h
+++ b/include/linux/hmm.h
@@ -40,11 +40,14 @@ struct migrate_vma;
  * On input:
  * 0                   - Return the current state of the page, do not fault it.
  * HMM_PFN_REQ_FAULT   - The output must have HMM_PFN_VALID or hmm_range_fault()
- *                       will fail
+ *                       will fail, except when migrating, which is best
+ *                       effort (see HMM_PFN_REQ_MIGRATE)
  * HMM_PFN_REQ_WRITE   - The output must have HMM_PFN_WRITE or hmm_range_fault()
  *                       will fail. Must be combined with HMM_PFN_REQ_FAULT.
  * HMM_PFN_REQ_MIGRATE - For default_flags only, request to migrate the range,
- *                       according to hmm_range.migrate.flags
+ *                       according to hmm_range.migrate.flags. Collection,
+ *                       and faulting with it, is best effort, see
+ *                       hmm_range_fault().
  */
 enum hmm_pfn_flags {
 	/* Output fields and flags */
diff --git a/include/linux/migrate.h b/include/linux/migrate.h
index b778f8bba5a3..9513d1697232 100644
--- a/include/linux/migrate.h
+++ b/include/linux/migrate.h
@@ -5,6 +5,7 @@
 #include <linux/mm.h>
 #include <linux/hmm.h>
 #include <linux/mempolicy.h>
+#include <linux/mmu_notifier.h>
 #include <linux/migrate_mode.h>
 #include <linux/hugetlb.h>
 
@@ -108,6 +109,35 @@ static inline void softleaf_entry_wait_on_locked(softleaf_t entry, spinlock_t *p
 	spin_unlock(ptl);
 }
 
+enum migrate_vma_info {
+	MIGRATE_VMA_SELECT_NONE = 0,
+	/* No migration, so no compound migration either */
+	MIGRATE_VMA_SELECT_COMPOUND = MIGRATE_VMA_SELECT_NONE,
+};
+
+static inline enum migrate_vma_info hmm_select_migrate(struct hmm_range *range)
+{
+	return MIGRATE_VMA_SELECT_NONE;
+}
+
+static inline void *hmm_migrate_pgmap_owner(struct hmm_range *range)
+{
+	return NULL;
+}
+
+static inline void hmm_fill_migrate_vma(struct hmm_range *range,
+					struct vm_area_struct *vma,
+					unsigned long start,
+					unsigned long end)
+{
+}
+
+#ifdef CONFIG_MMU_NOTIFIER
+static inline struct mm_struct *hmm_range_fault_mm(struct hmm_range *range)
+{
+	return range->notifier->mm;
+}
+#endif
 #endif /* CONFIG_MIGRATION */
 
 #ifdef CONFIG_NUMA_BALANCING
@@ -152,7 +182,8 @@ static inline unsigned long migrate_pfn(unsigned long pfn)
 	return (pfn << MIGRATE_PFN_SHIFT) | MIGRATE_PFN_VALID;
 }
 
-enum migrate_vma_direction {
+enum migrate_vma_info {
+	MIGRATE_VMA_SELECT_NONE = 0,
 	MIGRATE_VMA_SELECT_SYSTEM = 1 << 0,
 	MIGRATE_VMA_SELECT_DEVICE_PRIVATE = 1 << 1,
 	MIGRATE_VMA_SELECT_DEVICE_COHERENT = 1 << 2,
@@ -194,6 +225,39 @@ struct migrate_vma {
 	struct page		*fault_page;
 };
 
+/*
+ * Helpers for the migration path of hmm_range_fault() in mm/hmm.c. They live
+ * here next to struct migrate_vma, which they use, and the !CONFIG_MIGRATION
+ * stubs above let mm/hmm.c build without #ifdefs.
+ */
+/* Migration collection in hmm_range_fault() is enabled later in the series */
+static inline enum migrate_vma_info hmm_select_migrate(struct hmm_range *range)
+{
+	return MIGRATE_VMA_SELECT_NONE;
+}
+
+static inline void *hmm_migrate_pgmap_owner(struct hmm_range *range)
+{
+	return range->migrate->pgmap_owner;
+}
+
+#ifdef CONFIG_MMU_NOTIFIER
+static inline struct mm_struct *hmm_range_fault_mm(struct hmm_range *range)
+{
+	return range->notifier ? range->notifier->mm : range->migrate->vma->vm_mm;
+}
+#endif
+
+static inline void hmm_fill_migrate_vma(struct hmm_range *range,
+					struct vm_area_struct *vma,
+					unsigned long start,
+					unsigned long end)
+{
+	range->migrate->vma   = vma;
+	range->migrate->start = start;
+	range->migrate->end   = end;
+}
+
 int migrate_vma_setup(struct migrate_vma *args);
 void migrate_vma_pages(struct migrate_vma *migrate);
 void migrate_vma_finalize(struct migrate_vma *migrate);
diff --git a/lib/test_hmm.c b/lib/test_hmm.c
index a09a766b15b0..63226caea5da 100644
--- a/lib/test_hmm.c
+++ b/lib/test_hmm.c
@@ -145,7 +145,7 @@ static bool dmirror_is_private_zone(struct dmirror_device *mdevice)
 		HMM_DMIRROR_MEMORY_DEVICE_PRIVATE);
 }
 
-static enum migrate_vma_direction
+static enum migrate_vma_info
 dmirror_select_device(struct dmirror *dmirror)
 {
 	return (dmirror->mdevice->zone_device_type ==
diff --git a/mm/hmm.c b/mm/hmm.c
index 9871d3c3cd07..35bbae71e19c 100644
--- a/mm/hmm.c
+++ b/mm/hmm.c
@@ -21,6 +21,7 @@
 #include <linux/pagemap.h>
 #include <linux/leafops.h>
 #include <linux/hugetlb.h>
+#include <linux/migrate.h>
 #include <linux/memremap.h>
 #include <linux/sched/mm.h>
 #include <linux/jump_label.h>
@@ -32,11 +33,18 @@
 #include "internal.h"
 
 struct hmm_vma_walk {
-	struct hmm_range	*range;
-	bool			*locked;
-	unsigned long		last;
-	unsigned long		end;
-	unsigned int		required_fault;
+	struct mmu_notifier_range	mmu_range;
+	/* Set once mmu_range is armed with mmu_notifier_invalidate_range_start() */
+	bool				mmu_armed;
+	struct vm_area_struct		*vma;
+	struct hmm_range		*range;
+	/* End of the range armed for migration, set when the vma is captured */
+	unsigned long			end;
+	unsigned long			last;
+	/* fault and lock drop related fields */
+	bool				*mmlocked;
+	unsigned long			fault_end;
+	unsigned int			required_fault;
 };
 
 /*
@@ -95,7 +103,7 @@ static int hmm_record_fault(unsigned long addr, unsigned long end,
 
 	WARN_ON_ONCE(!required_fault);
 	hmm_vma_walk->last = addr;
-	hmm_vma_walk->end = end;
+	hmm_vma_walk->fault_end = end;
 	hmm_vma_walk->required_fault = required_fault;
 	return HMM_FAULT_PENDING;
 }
@@ -176,7 +184,7 @@ static int hmm_vma_walk_hole(unsigned long addr, unsigned long end,
 	required_fault =
 		hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0);
 	if (!walk->vma) {
-		if (required_fault)
+		if (required_fault || hmm_select_migrate(range))
 			return -EFAULT;
 		return hmm_pfns_fill(addr, end, range, HMM_PFN_ERROR);
 	}
@@ -296,6 +304,13 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 			goto fault;
 
 		if (softleaf_is_migration(entry)) {
+			/*
+			 * Someone else's migration. When migrating, don't wait
+			 * for it: we may hold collected folios it waits for.
+			 * Leave the entry uncollected (best effort).
+			 */
+			if (hmm_select_migrate(range))
+				goto out;
 			pte_unmap(ptep);
 			hmm_vma_walk->last = addr;
 			migration_entry_wait(walk->mm, pmdp, addr);
@@ -400,6 +415,79 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 }
 #endif  /* CONFIG_ARCH_HAS_PMD_SOFTLEAVES */
 
+static int hmm_vma_capture_migrate_range(unsigned long start,
+					 unsigned long end,
+					 struct mm_walk *walk)
+{
+	struct hmm_vma_walk *hmm_vma_walk = walk->private;
+	struct hmm_range *range = hmm_vma_walk->range;
+	struct vm_area_struct *vma = walk->vma;
+
+	if (!hmm_select_migrate(range))
+		return 0;
+
+	if (!hmm_vma_walk->vma) {
+		/*
+		 * Only vmas migrate_vma_setup() handles: mm backed, not
+		 * hugetlb or DAX. Shadow stacks are refused too, so that no
+		 * device gets a writable copy of one.
+		 */
+		if (!vma_is_mm_backed(vma) || vma_is_hugetlb(vma) ||
+		    vma_is_dax(vma) ||
+		    vma_test_single_mask(vma, VMA_SHADOW_STACK))
+			return -EINVAL;
+		/*
+		 * migrate_vma covers the whole range and indexes src[] from
+		 * range->start, so a single vma must cover the whole range.
+		 */
+		if (vma->vm_start > range->start ||
+		    vma->vm_end < range->end)
+			return -ERANGE;
+		hmm_vma_walk->vma = vma;
+		hmm_vma_walk->end = end;
+	}
+
+	/*
+	 * The invalidation is closed before faulting, see
+	 * hmm_range_fault_locked(), so (re)open it for each walk. Only over
+	 * what is still to be walked: an earlier walk handled the range below
+	 * start, and its entries are not changed again.
+	 */
+	if (!hmm_vma_walk->mmu_armed) {
+		mmu_notifier_range_init_owner(&hmm_vma_walk->mmu_range, MMU_NOTIFY_MIGRATE, 0,
+					      walk->vma->vm_mm, start,
+					      hmm_vma_walk->end, range->dev_private_owner);
+		mmu_notifier_invalidate_range_start(&hmm_vma_walk->mmu_range);
+		hmm_vma_walk->mmu_armed = true;
+	}
+
+	return 0;
+}
+
+static void hmm_vma_migrate_disarm(struct hmm_vma_walk *hmm_vma_walk)
+{
+	if (hmm_vma_walk->mmu_armed) {
+		mmu_notifier_invalidate_range_end(&hmm_vma_walk->mmu_range);
+		hmm_vma_walk->mmu_armed = false;
+	}
+}
+
+static void hmm_vma_post_range_fault(struct hmm_vma_walk *hmm_vma_walk)
+{
+	struct hmm_range *range = hmm_vma_walk->range;
+
+	/*
+	 * The migrate_vma path has the following initialized. For the fault
+	 * path fill them in, also when the walk failed before capturing the
+	 * vma, so migrate_hmm_range_setup() always sees the range.
+	 */
+	if (hmm_select_migrate(range) && range->notifier)
+		hmm_fill_migrate_vma(range,
+				     hmm_vma_walk->vma,
+				     range->start, range->end);
+	hmm_vma_migrate_disarm(hmm_vma_walk);
+}
+
 static int hmm_vma_walk_pmd(pmd_t *pmdp,
 			    unsigned long start,
 			    unsigned long end,
@@ -420,7 +508,9 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 		return hmm_vma_walk_hole(start, end, -1, walk);
 
 	if (thp_migration_supported() && pmd_is_migration_entry(pmd)) {
-		if (hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0)) {
+		/* Someone else's migration: when migrating, don't wait (see pte level) */
+		if (!hmm_select_migrate(range) &&
+		    hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0)) {
 			hmm_vma_walk->last = addr;
 			pmd_migration_entry_wait(walk->mm, pmdp);
 			return -EBUSY;
@@ -594,10 +684,13 @@ static int hmm_vma_walk_test(unsigned long start, unsigned long end,
 	struct hmm_vma_walk *hmm_vma_walk = walk->private;
 	struct hmm_range *range = hmm_vma_walk->range;
 	struct vm_area_struct *vma = walk->vma;
+	/* Migration without faulting moves pages regardless of VM_READ */
+	bool migrate_only = hmm_select_migrate(range) &&
+			    !(range->default_flags & HMM_PFN_REQ_FAULT);
 
 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)) &&
-	    vma->vm_flags & VM_READ)
-		return 0;
+	    (vma->vm_flags & VM_READ || migrate_only))
+		return hmm_vma_capture_migrate_range(start, end, walk);
 
 	/*
 	 * vma ranges that don't have struct page backing them or map I/O
@@ -607,10 +700,11 @@ static int hmm_vma_walk_test(unsigned long start, unsigned long end,
 	 * allow write access either. HMM does not support architectures that
 	 * allow write without read.
 	 *
-	 * If a fault is requested for an unsupported range then it is a hard
-	 * failure.
+	 * If a fault or migration is requested for an unsupported range then
+	 * it is a hard failure.
 	 */
-	if (hmm_range_need_fault(hmm_vma_walk,
+	if (hmm_select_migrate(range) ||
+	    hmm_range_need_fault(hmm_vma_walk,
 				 range->hmm_pfns +
 					 ((start - range->start) >> PAGE_SHIFT),
 				 (end - start) >> PAGE_SHIFT, 0))
@@ -646,12 +740,12 @@ static int hmm_do_fault(struct mm_struct *mm,
 			struct hmm_vma_walk *hmm_vma_walk)
 {
 	unsigned long addr = hmm_vma_walk->last;
-	unsigned long end = hmm_vma_walk->end;
+	unsigned long end = hmm_vma_walk->fault_end;
 	unsigned int required_fault = hmm_vma_walk->required_fault;
 	unsigned int fault_flags = FAULT_FLAG_REMOTE;
 	struct vm_area_struct *vma;
 
-	if (hmm_vma_walk->locked)
+	if (hmm_vma_walk->mmlocked)
 		fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
 
 	vma = vma_lookup(mm, addr);
@@ -670,8 +764,8 @@ static int hmm_do_fault(struct mm_struct *mm,
 		ret = handle_mm_fault(vma, addr, fault_flags, NULL);
 
 		if (ret & (VM_FAULT_COMPLETED | VM_FAULT_RETRY)) {
-			if (hmm_vma_walk->locked)    /* needed by sparse */
-				*hmm_vma_walk->locked = false;
+			if (hmm_vma_walk->mmlocked)    /* needed by sparse */
+				*hmm_vma_walk->mmlocked = false;
 			else
 				WARN_ON_ONCE(1);    /* broken fault handler */
 			return HMM_FAULT_UNLOCKED;
@@ -694,19 +788,54 @@ static int hmm_range_fault_locked(struct hmm_range *range, bool *locked)
 {
 	struct hmm_vma_walk hmm_vma_walk = {
 		.range = range,
-		.locked = locked,
+		.mmlocked = locked,
 		.last = range->start,
 	};
-	struct mm_struct *mm = range->notifier->mm;
+	/*
+	 *  Could be serving a device fault or come from migrate
+	 *  entry point. For the former we have not resolved the vma
+	 *  yet, and the latter we don't have a notifier (but have a vma).
+	 *
+	 */
+	struct mm_struct *mm;
 	int ret;
 
+	/* Checked once here, so the migration helpers can rely on it */
+	if ((range->default_flags & HMM_PFN_REQ_MIGRATE) &&
+	    WARN_ON_ONCE(!range->migrate))
+		return -EINVAL;
+	mm = hmm_range_fault_mm(range);
+
+	/* Migration is incompatible with mmap lock drop */
+	if (locked && hmm_select_migrate(range))
+		return -EINVAL;
+
+	/*
+	 * Migration takes its requests only from default_flags, so the input
+	 * pfns carry nothing. Clear them so that collected entries can be
+	 * told apart reliably during the walk and on rollback.
+	 * A migrating call doesn't resume a previous one: the caller must
+	 * finish the previous attempt with migrate_vma_pages() and
+	 * migrate_vma_finalize() before calling again.
+	 */
+	if (hmm_select_migrate(range)) {
+		WARN_ON_ONCE(range->pfn_flags_mask);
+		WARN_ON_ONCE(range->dev_private_owner !=
+			     hmm_migrate_pgmap_owner(range));
+		memset(range->hmm_pfns, 0,
+		       ((range->end - range->start) >> PAGE_SHIFT) *
+		       sizeof(*range->hmm_pfns));
+	}
+
 	mmap_assert_locked(mm);
 
 	do {
 		/* If range is no longer valid force retry. */
-		if (mmu_interval_check_retry(range->notifier,
-					     range->notifier_seq))
-			return -EBUSY;
+		if (range->notifier && mmu_interval_check_retry(range->notifier,
+								range->notifier_seq)) {
+			ret =  -EBUSY;
+			break;
+		}
 		ret = walk_page_range(mm, hmm_vma_walk.last, range->end,
 				      &hmm_walk_ops, &hmm_vma_walk);
 		/*
@@ -718,12 +847,38 @@ static int hmm_range_fault_locked(struct hmm_range *range, bool *locked)
 		 * now-present entries.
 		 */
 		if (ret == HMM_FAULT_PENDING) {
+			/*
+			 * Don't hold the migrate invalidation across a
+			 * possibly sleeping fault. Already collected entries
+			 * stay locked and referenced, and the next walk
+			 * reopens the invalidation. Entries below last are not
+			 * revisited; if their migration ptes vanish meanwhile,
+			 * the caller's migrate_vma_finalize() still releases
+			 * them, as after migrate_vma_setup(). Whatever removed
+			 * them also invalidated the range, so the caller's
+			 * mmu_interval_read_retry() keeps it from mapping the
+			 * unused destination on the device.
+			 */
+			hmm_vma_migrate_disarm(&hmm_vma_walk);
 			ret = hmm_do_fault(mm, &hmm_vma_walk);
 			if (ret == HMM_FAULT_UNLOCKED) {
 				if (fatal_signal_pending(current))
 					return -EINTR;
 				return -EBUSY;
 			}
+			/*
+			 * A fault can return without making the entry present
+			 * (e.g. a migrate_to_ram() that didn't migrate), so the
+			 * next walk faults it again. A migrating walk keeps
+			 * collected folios locked across these re-walks, and
+			 * migrate_vma_setup() has no notifier to end them: let
+			 * a fatal signal end it.
+			 */
+			if (ret == -EBUSY && hmm_select_migrate(range) &&
+			    fatal_signal_pending(current)) {
+				ret = -EINTR;
+				break;
+			}
 		}
 		/*
 		 * When -EBUSY is returned the loop restarts with
@@ -732,6 +887,8 @@ static int hmm_range_fault_locked(struct hmm_range *range, bool *locked)
 		 * output, and all >= are still at their input values.
 		 */
 	} while (ret == -EBUSY);
+
+	hmm_vma_post_range_fault(&hmm_vma_walk);
 	return ret;
 }
 
@@ -750,6 +907,13 @@ static int hmm_range_fault_locked(struct hmm_range *range, bool *locked)
  *		the invalidation to finish.
  * -EFAULT:     A page was requested to be valid and could not be made valid
  *              ie it has no backing VMA or it is illegal to access
+ * -ERANGE:     When migrating, the range is not covered by a single VMA
+ *              (a range starting in a hole gets -EFAULT instead).
+ * -EINTR:      When migrating, a fatal signal is pending after a fault.
+ *
+ * When migrating (HMM_PFN_REQ_MIGRATE), collection and faulting are best
+ * effort: the call can succeed with entries left without HMM_PFN_VALID, even
+ * with HMM_PFN_REQ_FAULT, so callers check each entry.
  *
  * This is similar to get_user_pages(), except that it can read the page tables
  * without mutating them (ie causing faults).
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 04/14] mm/hmm: do the plumbing for HMM to participate in migration
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (2 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 03/14] mm/hmm: preparations for HMM to participate in migration mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 05/14] mm/hmm: implement rollback for device page migration in HMM pagewalk mpenttil
                   ` (9 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

Do the preparations in hmm_range_fault() and pagewalk callbacks to
do the "collecting" part of migration, needed for migration.

These steps include locking for pmd/pte if migrating, and calling the
still dummy hmm_vma_handle_migrate_prepare_pmd() and
hmm_vma_handle_migrate_prepare()  functions in the pagewalk.

When doing migration, have to have pmd/pte table locked for the
duration of both hmm_vma_handle*() and hmm_vma_handle_migrate_prepare*()
walks, and unlock when handling the faults.

Besides the locking and the stub calls, when migrating hmm_pfns_fill()
marks holes in anonymous vmas with HMM_PFN_MIGRATE (and
HMM_PFN_COMPOUND for a pmd sized hole with MIGRATE_VMA_SELECT_COMPOUND),
as migrate_vma_collect_hole() does, and a fault is recorded by the walk
callback and handled outside the walk with the page table locks
dropped. The HMM_FAULT_UNLOCKED path now leaves the loop instead of
returning, so every exit goes through hmm_vma_post_range_fault(). It
does nothing there: that path doesn't migrate, since migration refuses
mmap lock drop.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 mm/hmm.c | 302 ++++++++++++++++++++++++++++++++++++++++++++++---------
 1 file changed, 255 insertions(+), 47 deletions(-)

diff --git a/mm/hmm.c b/mm/hmm.c
index 35bbae71e19c..747319b4ae81 100644
--- a/mm/hmm.c
+++ b/mm/hmm.c
@@ -29,6 +29,7 @@
 #include <linux/pci-p2pdma.h>
 #include <linux/mmu_notifier.h>
 #include <linux/memory_hotplug.h>
+#include <asm/tlbflush.h>
 
 #include "internal.h"
 
@@ -41,6 +42,16 @@ struct hmm_vma_walk {
 	/* End of the range armed for migration, set when the vma is captured */
 	unsigned long			end;
 	unsigned long			last;
+	/*
+	 * For migration we need pte/pmd locked for the handle_* and
+	 * prepare_* regions. While faulting we have to drop the locks
+	 * and start again. ptelocked and pmdlocked hold the state
+	 * and tell  if need to drop locks before faulting.
+	 * ptl is the lock held for pte or pmd.
+	 */
+	bool				ptelocked;
+	bool				pmdlocked;
+	spinlock_t			*ptl;
 	/* fault and lock drop related fields */
 	bool				*mmlocked;
 	unsigned long			fault_end;
@@ -62,6 +73,10 @@ struct hmm_vma_walk {
  */
 #define HMM_FAULT_UNLOCKED	-ENOLCK
 
+#define HMM_ASSERT_UNLOCKED(hmm_vma_walk)			\
+	WARN_ON_ONCE((hmm_vma_walk)->ptelocked ||		\
+		     (hmm_vma_walk)->pmdlocked)
+
 enum {
 	HMM_NEED_FAULT = 1 << 0,
 	HMM_NEED_WRITE_FAULT = 1 << 1,
@@ -75,14 +90,38 @@ enum {
 };
 
 static int hmm_pfns_fill(unsigned long addr, unsigned long end,
-			 struct hmm_range *range, unsigned long cpu_flags)
+			 struct hmm_vma_walk *hmm_vma_walk, unsigned long cpu_flags)
 {
+	struct hmm_range *range = hmm_vma_walk->range;
 	unsigned long i = (addr - range->start) >> PAGE_SHIFT;
+	enum migrate_vma_info minfo;
+	bool migrate = false;
+
+	minfo = hmm_select_migrate(range);
+	if (cpu_flags != HMM_PFN_ERROR) {
+		if (minfo && (vma_is_anonymous(hmm_vma_walk->vma))) {
+			cpu_flags |= HMM_PFN_MIGRATE;
+			migrate = true;
+		}
+	}
+
+	if (migrate && thp_migration_supported() &&
+	    (minfo & MIGRATE_VMA_SELECT_COMPOUND) &&
+	    IS_ALIGNED(addr, HPAGE_PMD_SIZE) &&
+	    IS_ALIGNED(end, HPAGE_PMD_SIZE) &&
+		end-addr == HPAGE_PMD_SIZE) {
+		range->hmm_pfns[i] &= HMM_PFN_INOUT_FLAGS;
+		range->hmm_pfns[i] |= cpu_flags | HMM_PFN_COMPOUND;
+		addr += PAGE_SIZE;
+		i++;
+		cpu_flags = 0;
+	}
 
 	for (; addr < end; addr += PAGE_SIZE, i++) {
 		range->hmm_pfns[i] &= HMM_PFN_INOUT_FLAGS;
 		range->hmm_pfns[i] |= cpu_flags;
 	}
+
 	return 0;
 }
 
@@ -102,6 +141,7 @@ static int hmm_record_fault(unsigned long addr, unsigned long end,
 	struct hmm_vma_walk *hmm_vma_walk = walk->private;
 
 	WARN_ON_ONCE(!required_fault);
+	HMM_ASSERT_UNLOCKED(hmm_vma_walk);
 	hmm_vma_walk->last = addr;
 	hmm_vma_walk->fault_end = end;
 	hmm_vma_walk->required_fault = required_fault;
@@ -186,11 +226,16 @@ static int hmm_vma_walk_hole(unsigned long addr, unsigned long end,
 	if (!walk->vma) {
 		if (required_fault || hmm_select_migrate(range))
 			return -EFAULT;
-		return hmm_pfns_fill(addr, end, range, HMM_PFN_ERROR);
+		return hmm_pfns_fill(addr, end, hmm_vma_walk, HMM_PFN_ERROR);
 	}
-	if (required_fault)
+	if (required_fault) {
+		if (hmm_vma_walk->pmdlocked) {
+			spin_unlock(hmm_vma_walk->ptl);
+			hmm_vma_walk->pmdlocked = false;
+		}
 		return hmm_record_fault(addr, end, required_fault, walk);
-	return hmm_pfns_fill(addr, end, range, 0);
+	}
+	return hmm_pfns_fill(addr, end, hmm_vma_walk, 0);
 }
 
 static inline unsigned long hmm_pfn_flags_order(unsigned long order)
@@ -223,8 +268,13 @@ static int hmm_vma_handle_pmd(struct mm_walk *walk, unsigned long addr,
 	cpu_flags = pmd_to_hmm_pfn_flags(range, pmd);
 	required_fault =
 		hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, cpu_flags);
-	if (required_fault)
+	if (required_fault) {
+		if (hmm_vma_walk->pmdlocked) {
+			spin_unlock(hmm_vma_walk->ptl);
+			hmm_vma_walk->pmdlocked = false;
+		}
 		return hmm_record_fault(addr, end, required_fault, walk);
+	}
 
 	pfn = pmd_pfn(pmd) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
 	for (i = 0; addr < end; addr += PAGE_SIZE, i++, pfn++) {
@@ -311,6 +361,7 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 			 */
 			if (hmm_select_migrate(range))
 				goto out;
+			HMM_ASSERT_UNLOCKED(hmm_vma_walk);
 			pte_unmap(ptep);
 			hmm_vma_walk->last = addr;
 			migration_entry_wait(walk->mm, pmdp, addr);
@@ -318,7 +369,14 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 		}
 
 		/* Report error for everything else */
-		pte_unmap(ptep);
+
+		if (hmm_vma_walk->ptelocked) {
+			pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
+			hmm_vma_walk->ptelocked = false;
+		} else {
+			pte_unmap(ptep);
+		}
+
 		return -EFAULT;
 	}
 
@@ -335,7 +393,13 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 	if (!vm_normal_page(walk->vma, addr, pte) &&
 	    !is_zero_pfn(pte_pfn(pte))) {
 		if (hmm_pte_need_fault(hmm_vma_walk, pfn_req_flags, 0)) {
-			pte_unmap(ptep);
+			if (hmm_vma_walk->ptelocked) {
+				pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
+				hmm_vma_walk->ptelocked = false;
+			} else {
+				pte_unmap(ptep);
+			}
+
 			return -EFAULT;
 		}
 		new_pfn_flags = HMM_PFN_ERROR;
@@ -348,7 +412,12 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 	return 0;
 
 fault:
-	pte_unmap(ptep);
+	if (hmm_vma_walk->ptelocked) {
+		pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
+		hmm_vma_walk->ptelocked = false;
+	} else {
+		pte_unmap(ptep);
+	}
 	/* Fault any virtual address we were asked to fault */
 	return hmm_record_fault(addr, end, required_fault, walk);
 }
@@ -392,13 +461,18 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 	required_fault = hmm_range_need_fault(hmm_vma_walk, hmm_pfns,
 					      npages, 0);
 	if (required_fault) {
-		if (softleaf_is_device_private(entry))
+		if (softleaf_is_device_private(entry)) {
+			if (hmm_vma_walk->pmdlocked) {
+				spin_unlock(hmm_vma_walk->ptl);
+				hmm_vma_walk->pmdlocked = false;
+			}
 			return hmm_record_fault(addr, end, required_fault, walk);
+		}
 		else
 			return -EFAULT;
 	}
 
-	return hmm_pfns_fill(start, end, range, HMM_PFN_ERROR);
+	return hmm_pfns_fill(start, end, hmm_vma_walk, HMM_PFN_ERROR);
 }
 #else
 static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
@@ -406,15 +480,58 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 				     pmd_t pmd)
 {
 	struct hmm_vma_walk *hmm_vma_walk = walk->private;
-	struct hmm_range *range = hmm_vma_walk->range;
 	unsigned long npages = (end - start) >> PAGE_SHIFT;
 
 	if (hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0))
 		return -EFAULT;
-	return hmm_pfns_fill(start, end, range, HMM_PFN_ERROR);
+	return hmm_pfns_fill(start, end, hmm_vma_walk, HMM_PFN_ERROR);
 }
 #endif  /* CONFIG_ARCH_HAS_PMD_SOFTLEAVES */
 
+#ifdef CONFIG_DEVICE_MIGRATION
+static int hmm_vma_handle_migrate_prepare_pmd(const struct mm_walk *walk,
+					      pmd_t *pmdp,
+					      unsigned long start,
+					      unsigned long end,
+					      unsigned long *hmm_pfn)
+{
+	/* Collection is implemented by later patches */
+	return 0;
+}
+
+static int hmm_vma_handle_migrate_prepare(const struct mm_walk *walk,
+					  pmd_t *pmdp,
+					  pte_t *ptep,
+					  unsigned long addr,
+					  unsigned long *hmm_pfn,
+					  bool *unmapped)
+{
+	/* Collection is implemented by later patches */
+	return 0;
+}
+
+#else
+static int hmm_vma_handle_migrate_prepare_pmd(const struct mm_walk *walk,
+					      pmd_t *pmdp,
+					      unsigned long start,
+					      unsigned long end,
+					      unsigned long *hmm_pfn)
+{
+	return 0;
+}
+
+static int hmm_vma_handle_migrate_prepare(const struct mm_walk *walk,
+					  pmd_t *pmdp,
+					  pte_t *ptep,
+					  unsigned long addr,
+					  unsigned long *hmm_pfn,
+					  bool *unmapped)
+{
+	return 0;
+}
+
+#endif
+
 static int hmm_vma_capture_migrate_range(unsigned long start,
 					 unsigned long end,
 					 struct mm_walk *walk)
@@ -495,48 +612,118 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 {
 	struct hmm_vma_walk *hmm_vma_walk = walk->private;
 	struct hmm_range *range = hmm_vma_walk->range;
-	unsigned long *hmm_pfns =
-		&range->hmm_pfns[(start - range->start) >> PAGE_SHIFT];
 	unsigned long npages = (end - start) >> PAGE_SHIFT;
+	struct mm_struct *mm = walk->vma->vm_mm;
+	unsigned long *hmm_pfns, *hmm_pfns_start;
+	enum migrate_vma_info minfo;
 	unsigned long addr = start;
+	bool unmapped = false;
+	unsigned long i;
 	pte_t *ptep;
 	pmd_t pmd;
+	int r = 0;
 
+	minfo = hmm_select_migrate(range);
+	hmm_pfns_start = &range->hmm_pfns[(start - range->start) >> PAGE_SHIFT];
 again:
-	pmd = pmdp_get_lockless(pmdp);
-	if (pmd_none(pmd))
-		return hmm_vma_walk_hole(start, end, -1, walk);
+	hmm_pfns = &range->hmm_pfns[(addr - range->start) >> PAGE_SHIFT];
+	hmm_vma_walk->ptelocked = false;
+	hmm_vma_walk->pmdlocked = false;
+
+	if (minfo) {
+		hmm_vma_walk->ptl = pmd_lock(mm, pmdp);
+		hmm_vma_walk->pmdlocked = true;
+		pmd = pmdp_get(pmdp);
+	} else
+		pmd = pmdp_get_lockless(pmdp);
+
+	if (pmd_none(pmd)) {
+		r = hmm_vma_walk_hole(start, end, -1, walk);
+
+		if (hmm_vma_walk->pmdlocked) {
+			spin_unlock(hmm_vma_walk->ptl);
+			hmm_vma_walk->pmdlocked = false;
+		}
+		return r;
+	}
 
 	if (thp_migration_supported() && pmd_is_migration_entry(pmd)) {
+		unsigned int required_fault =
+			hmm_range_need_fault(hmm_vma_walk, hmm_pfns_start, npages, 0);
+
+		if (hmm_vma_walk->pmdlocked) {
+			spin_unlock(hmm_vma_walk->ptl);
+			hmm_vma_walk->pmdlocked = false;
+		}
+
 		/* Someone else's migration: when migrating, don't wait (see pte level) */
-		if (!hmm_select_migrate(range) &&
-		    hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0)) {
+		if (required_fault && !minfo) {
 			hmm_vma_walk->last = addr;
 			pmd_migration_entry_wait(walk->mm, pmdp);
 			return -EBUSY;
 		}
-		return hmm_pfns_fill(start, end, range, 0);
+		for (i = 0; start < end; start += PAGE_SIZE, i++)
+			hmm_pfns_start[i] &= HMM_PFN_INOUT_FLAGS;
+
+		return 0;
 	}
 
-	if (!pmd_present(pmd))
-		return hmm_vma_handle_absent_pmd(walk, start, end, hmm_pfns,
-						 pmd);
+	if (pmd_trans_huge(pmd) || !pmd_present(pmd)) {
+		if (!pmd_present(pmd)) {
+			r = hmm_vma_handle_absent_pmd(walk, start, end, hmm_pfns_start,
+						      pmd);
+			/* If not migrating we are done */
+			if (r || !minfo) {
+				if (hmm_vma_walk->pmdlocked) {
+					spin_unlock(hmm_vma_walk->ptl);
+					hmm_vma_walk->pmdlocked = false;
+				}
+				return r;
+			}
+		}
 
-	if (pmd_trans_huge(pmd)) {
-		/*
-		 * No need to take pmd_lock here, even if some other thread
-		 * is splitting the huge pmd we will get that event through
-		 * mmu_notifier callback.
-		 *
-		 * So just read pmd value and check again it's a transparent
-		 * huge or device mapping one and compute corresponding pfn
-		 * values.
-		 */
-		pmd = pmdp_get_lockless(pmdp);
-		if (!pmd_trans_huge(pmd))
-			goto again;
+		if (pmd_trans_huge(pmd)) {
+			/*
+			 * No need to take pmd_lock here if not migrating,
+			 * even if some other thread is splitting the huge
+			 * pmd we will get that event through mmu_notifier callback.
+			 *
+			 * So just read pmd value and check again it's a transparent
+			 * huge or device mapping one and compute corresponding pfn
+			 * values.
+			 */
+
+			if (!minfo) {
+				pmd = pmdp_get_lockless(pmdp);
+				if (!pmd_trans_huge(pmd))
+					goto again;
+			}
+
+			r = hmm_vma_handle_pmd(walk, start, end, hmm_pfns_start, pmd);
+
+			/* If not migrating we are done */
+			if (r || !minfo) {
+				if (hmm_vma_walk->pmdlocked) {
+					spin_unlock(hmm_vma_walk->ptl);
+					hmm_vma_walk->pmdlocked = false;
+				}
+				return r;
+			}
+		}
+
+		r = hmm_vma_handle_migrate_prepare_pmd(walk, pmdp, start, end, hmm_pfns_start);
 
-		return hmm_vma_handle_pmd(walk, addr, end, hmm_pfns, pmd);
+		if (hmm_vma_walk->pmdlocked) {
+			spin_unlock(hmm_vma_walk->ptl);
+			hmm_vma_walk->pmdlocked = false;
+		}
+
+		return r;
+	}
+
+	if (hmm_vma_walk->pmdlocked) {
+		spin_unlock(hmm_vma_walk->ptl);
+		hmm_vma_walk->pmdlocked = false;
 	}
 
 	/*
@@ -546,24 +733,45 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 	 * recover.
 	 */
 	if (pmd_bad(pmd)) {
-		if (hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0))
+		if (hmm_range_need_fault(hmm_vma_walk, hmm_pfns_start, npages, 0))
 			return -EFAULT;
-		return hmm_pfns_fill(start, end, range, HMM_PFN_ERROR);
+		return hmm_pfns_fill(start, end, hmm_vma_walk, HMM_PFN_ERROR);
 	}
 
-	ptep = pte_offset_map(pmdp, addr);
+	if (minfo) {
+		ptep = pte_offset_map_lock(mm, pmdp, addr, &hmm_vma_walk->ptl);
+		if (ptep)
+			hmm_vma_walk->ptelocked = true;
+	} else {
+		ptep = pte_offset_map(pmdp, addr);
+	}
 	if (!ptep)
 		goto again;
+
 	for (; addr < end; addr += PAGE_SIZE, ptep++, hmm_pfns++) {
-		int r;
 
 		r = hmm_vma_handle_pte(walk, addr, end, pmdp, ptep, hmm_pfns);
 		if (r) {
-			/* hmm_vma_handle_pte() did pte_unmap() */
+			/* hmm_vma_handle_pte() did pte_unmap() / pte_unmap_unlock */
+			if (unmapped)
+				flush_tlb_range(walk->vma, start, addr);
 			return r;
 		}
+
+		/* Collection is added by later patches: a no-op until then */
+		hmm_vma_handle_migrate_prepare(walk, pmdp, ptep, addr, hmm_pfns, &unmapped);
 	}
-	pte_unmap(ptep - 1);
+
+	if (unmapped)
+		flush_tlb_range(walk->vma, start, addr);
+
+	if (hmm_vma_walk->ptelocked) {
+		pte_unmap_unlock(ptep - 1, hmm_vma_walk->ptl);
+		hmm_vma_walk->ptelocked = false;
+	} else {
+		pte_unmap(ptep - 1);
+	}
+
 	return 0;
 }
 
@@ -710,7 +918,7 @@ static int hmm_vma_walk_test(unsigned long start, unsigned long end,
 				 (end - start) >> PAGE_SHIFT, 0))
 		return -EFAULT;
 
-	hmm_pfns_fill(start, end, range, HMM_PFN_ERROR);
+	hmm_pfns_fill(start, end, hmm_vma_walk, HMM_PFN_ERROR);
 
 	/* Skip this vma and continue processing the next vma. */
 	return 1;
@@ -862,9 +1070,9 @@ static int hmm_range_fault_locked(struct hmm_range *range, bool *locked)
 			hmm_vma_migrate_disarm(&hmm_vma_walk);
 			ret = hmm_do_fault(mm, &hmm_vma_walk);
 			if (ret == HMM_FAULT_UNLOCKED) {
-				if (fatal_signal_pending(current))
-					return -EINTR;
-				return -EBUSY;
+				ret = fatal_signal_pending(current) ? -EINTR :
+					-EBUSY;
+				break;
 			}
 			/*
 			 * A fault can return without making the entry present
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 05/14] mm/hmm: implement rollback for device page migration in HMM pagewalk
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (3 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 04/14] mm/hmm: do the plumbing " mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 06/14] mm/hmm: migrate collection in HMM pagewalk - pte level mpenttil
                   ` (8 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

During the migration pagewalk, the PTE table could be cleared and/or
changed into PMD leaf or even another PTE table while dropped locks.

In these cases the possibly inserted migration ptes are gone. We have
to however undo the collecting done so far, so unlock the folios and
drop reference taken.

During the pagewalk we notice such scenarios if going to recollect a pfn
but have already committed to migrate the entry with HMM_PFN_MIGRATE, in
which case do rollback. Rollback clears HMM_PFN_VALID, HMM_PFN_MIGRATE
and HMM_PFN_COMPOUND, which is safe, as migration is entirely driven by
default_flags. The marker helpers are private to mm/hmm.c.

For the revisit to happen, our own migration entries are recognized at
pte and pmd level (marker plus the same page) and kept. When migrating,
a fault covers only the faulting page, so that our own migration entries
and caller owned device private pages later in the range are never
faulted; the walk then restarts at that page. Collected entries the walk
doesn't visit again stay collected and are released by finalize.

This comes before the collection itself, which the next patches add, so
that collection always has rollback in place. Until then it is a no-op.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 mm/hmm.c | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 136 insertions(+), 1 deletion(-)

diff --git a/mm/hmm.c b/mm/hmm.c
index 747319b4ae81..273d0e364fd7 100644
--- a/mm/hmm.c
+++ b/mm/hmm.c
@@ -89,6 +89,33 @@ enum {
 			      HMM_PFN_P2PDMA_BUS,
 };
 
+/*
+ * hmm_pfn_collected() - is this pfn entry prepared for migration ?
+ * If collected the folio's refcount is increased and the folio
+ * is locked.
+ */
+static inline bool hmm_pfn_collected(unsigned long hmm_pfn)
+{
+	return (hmm_pfn & (HMM_PFN_VALID | HMM_PFN_MIGRATE)) ==
+		(HMM_PFN_VALID | HMM_PFN_MIGRATE);
+}
+
+/*
+ * hmm_pfn_rollback_collected() - undoes the collection of hmm_pfn
+ *
+ * Note for total rollback the folio's refcount has to be put
+ * and folio has to be unlocked.
+ */
+static inline unsigned long hmm_pfn_rollback_collected(unsigned long hmm_pfn)
+{
+	return hmm_pfn & ~(HMM_PFN_VALID | HMM_PFN_MIGRATE | HMM_PFN_COMPOUND);
+}
+
+static void hmm_vma_handle_migrate_prepare_rollback(const struct hmm_vma_walk *hmm_vma_walk,
+						    unsigned long start,
+						    unsigned long end,
+						    unsigned long *hmm_pfn);
+
 static int hmm_pfns_fill(unsigned long addr, unsigned long end,
 			 struct hmm_vma_walk *hmm_vma_walk, unsigned long cpu_flags)
 {
@@ -105,6 +132,8 @@ static int hmm_pfns_fill(unsigned long addr, unsigned long end,
 		}
 	}
 
+	hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk, addr, end, &range->hmm_pfns[i]);
+
 	if (migrate && thp_migration_supported() &&
 	    (minfo & MIGRATE_VMA_SELECT_COMPOUND) &&
 	    IS_ALIGNED(addr, HPAGE_PMD_SIZE) &&
@@ -233,6 +262,9 @@ static int hmm_vma_walk_hole(unsigned long addr, unsigned long end,
 			spin_unlock(hmm_vma_walk->ptl);
 			hmm_vma_walk->pmdlocked = false;
 		}
+		/* Entries collected from a vanished page table are gone */
+		hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk, addr, end,
+							hmm_pfns);
 		return hmm_record_fault(addr, end, required_fault, walk);
 	}
 	return hmm_pfns_fill(addr, end, hmm_vma_walk, 0);
@@ -268,6 +300,9 @@ static int hmm_vma_handle_pmd(struct mm_walk *walk, unsigned long addr,
 	cpu_flags = pmd_to_hmm_pfn_flags(range, pmd);
 	required_fault =
 		hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, cpu_flags);
+	/* Entries collected from a vanished page table are gone */
+	hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk, addr,
+						end, hmm_pfns);
 	if (required_fault) {
 		if (hmm_vma_walk->pmdlocked) {
 			spin_unlock(hmm_vma_walk->ptl);
@@ -325,6 +360,15 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 	if (!pte_present(pte)) {
 		const softleaf_t entry = softleaf_from_pte(pte);
 
+		/*
+		 * Our own migration entry, collected earlier in this walk:
+		 * keep the collected pfn, don't fault or roll it back.
+		 */
+		if (softleaf_is_migration(entry) && hmm_select_migrate(range) &&
+		    hmm_pfn_collected(*hmm_pfn) &&
+		    hmm_pfn_to_page(*hmm_pfn) == softleaf_to_page(entry))
+			return 0;
+
 		/*
 		 * Don't fault in device private pages owned by the caller,
 		 * just report the PFN.
@@ -408,6 +452,9 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 
 	new_pfn_flags = pte_pfn(pte) | cpu_flags;
 out:
+	hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk, addr,
+						addr + PAGE_SIZE,
+						hmm_pfn);
 	*hmm_pfn = (*hmm_pfn & HMM_PFN_INOUT_FLAGS) | new_pfn_flags;
 	return 0;
 
@@ -418,7 +465,19 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 	} else {
 		pte_unmap(ptep);
 	}
-	/* Fault any virtual address we were asked to fault */
+	/*
+	 * This pte needs a fault, so it is not our migration entry: a pfn
+	 * collected here earlier is gone, roll it back before faulting.
+	 */
+	hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk, addr,
+						addr + PAGE_SIZE, hmm_pfn);
+	/*
+	 * Fault any virtual address we were asked to fault. When migrating,
+	 * only this page: later ptes may be our own migration entries or
+	 * caller owned device private pages, which must not be faulted.
+	 */
+	if (hmm_select_migrate(range))
+		end = addr + PAGE_SIZE;
 	return hmm_record_fault(addr, end, required_fault, walk);
 }
 
@@ -445,6 +504,9 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 		if (softleaf_is_device_private_write(entry))
 			cpu_flags |= HMM_PFN_WRITE;
 
+		hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk,
+							start, end,
+							hmm_pfns);
 		/*
 		 * Fully populate the PFN list though subsequent PFNs could be
 		 * inferred, because drivers which are not yet aware of large
@@ -466,6 +528,10 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 				spin_unlock(hmm_vma_walk->ptl);
 				hmm_vma_walk->pmdlocked = false;
 			}
+			/* Entries collected from a vanished page table are gone */
+			hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk,
+								addr, end,
+								hmm_pfns);
 			return hmm_record_fault(addr, end, required_fault, walk);
 		}
 		else
@@ -489,6 +555,54 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 #endif  /* CONFIG_ARCH_HAS_PMD_SOFTLEAVES */
 
 #ifdef CONFIG_DEVICE_MIGRATION
+/*
+ * Due to dropping ptl locks for splitting for instance, would we
+ * overwrite already collected pfns? This could happen when pmd
+ * pointing to a page table has vanished and been replaced with
+ * a leaf pmd, or another page table. In that case unref and unlock
+ * the folios, the pfns of which were collected from the disappeared
+ * page tables.
+ *
+ * Migrate mode drives fault/migration requests only via range->default_flags.
+ * (HMM_PFN_VALID | HMM_PFN_MIGRATE) denotes a collected entry and can safely
+ * be cleared from hmm_pfn[].
+ *
+ * Rollback is only needed for entries the walk visits again, where a stale
+ * marker would be mistaken for our own migration entry. Collected entries
+ * that are not revisited stay marked, and the caller's migrate_vma_pages()
+ * and migrate_vma_finalize() release them even if their migration ptes
+ * vanished meanwhile.
+ */
+static void hmm_vma_handle_migrate_prepare_rollback(const struct hmm_vma_walk *hmm_vma_walk,
+						    unsigned long start,
+						    unsigned long end,
+						    unsigned long *hmm_pfn)
+{
+	struct hmm_range *range = hmm_vma_walk->range;
+	struct migrate_vma *migrate = range->migrate;
+	struct folio *fault_folio;
+	enum migrate_vma_info minfo;
+	struct folio *folio;
+	unsigned long i;
+
+	minfo = hmm_select_migrate(range);
+	if (!minfo)
+		return;
+
+	fault_folio = migrate->fault_page ?
+		page_folio(migrate->fault_page) : NULL;
+
+	for (i = 0; start < end; start += PAGE_SIZE, i++) {
+		if (hmm_pfn_collected(hmm_pfn[i])) {
+			folio = page_folio(hmm_pfn_to_page(hmm_pfn[i]));
+			if (folio != fault_folio)
+				folio_unlock(folio);
+			folio_put(folio);
+			hmm_pfn[i] = hmm_pfn_rollback_collected(hmm_pfn[i]);
+		}
+	}
+}
+
 static int hmm_vma_handle_migrate_prepare_pmd(const struct mm_walk *walk,
 					      pmd_t *pmdp,
 					      unsigned long start,
@@ -511,6 +625,13 @@ static int hmm_vma_handle_migrate_prepare(const struct mm_walk *walk,
 }
 
 #else
+static void hmm_vma_handle_migrate_prepare_rollback(const struct hmm_vma_walk *hmm_vma_walk,
+						    unsigned long start,
+						    unsigned long end,
+						    unsigned long *hmm_pfn)
+{
+}
+
 static int hmm_vma_handle_migrate_prepare_pmd(const struct mm_walk *walk,
 					      pmd_t *pmdp,
 					      unsigned long start,
@@ -650,12 +771,26 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 	if (thp_migration_supported() && pmd_is_migration_entry(pmd)) {
 		unsigned int required_fault =
 			hmm_range_need_fault(hmm_vma_walk, hmm_pfns_start, npages, 0);
+		/*
+		 * Our own migration entry, collected earlier in this walk.
+		 * Decided while the pmd lock (taken when migrating) still holds.
+		 */
+		bool own = minfo && hmm_pfn_collected(hmm_pfns_start[0]) &&
+			   hmm_pfn_to_page(hmm_pfns_start[0]) ==
+			   softleaf_to_page(softleaf_from_pmd(pmd));
 
 		if (hmm_vma_walk->pmdlocked) {
 			spin_unlock(hmm_vma_walk->ptl);
 			hmm_vma_walk->pmdlocked = false;
 		}
 
+		if (own)
+			return 0;
+
+		/* Not ours: entries collected from a vanished page table are gone */
+		hmm_vma_handle_migrate_prepare_rollback(hmm_vma_walk, start, end,
+							hmm_pfns_start);
+
 		/* Someone else's migration: when migrating, don't wait (see pte level) */
 		if (required_fault && !minfo) {
 			hmm_vma_walk->last = addr;
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 06/14] mm/hmm: migrate collection in HMM pagewalk - pte level
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (4 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 05/14] mm/hmm: implement rollback for device page migration in HMM pagewalk mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 07/14] mm/hmm: migrate collection in HMM pagewalk - pmd level mpenttil
                   ` (7 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

Implement the needed hmm_vma_handle_migrate_prepare() function
which is mostly carried over from migrate_device.c's
migrate_vma_collect_pmd() function.

Also implement hmm_migrate_split_folio(), for splitting pte mapped large
folios. Compared with migrate_vma_split_folio() in migrate_device.c it
takes the folio reference before dropping the page table lock, only
trylocks the folio, and splits the fault folio at the fault page with
split_huge_page(), so the caller's lock and reference stay on the folio
holding the fault page. The old migrate_vma_collect*() code is removed
once migration switches over to the HMM pagewalk, later in the series.

As in the pending "mm/migrate_device: do not migrate a uffd-protected
zero page", a zero page whose uffd state would be lost is not collected.
As in Chris Mason's pending fix for migrate_vma_collect_pmd(), a KSM
folio is not collected: KSM maps a KSM folio before rmap walks can find
the mapping, so rmap_walk_ksm() may miss the pte when restoring the
migration entry, leaving a stale one behind.

With HMM pagewalk based migration, the idea is that
hmm_vma_handle_*() are responsible for faulting,
and the pfn collecting part. hmm_vma_handle_migrate_prepare*()
do the migration decisions (with HMM_PFN_MIGRATE), possibly split
folios, and insert migration ptes/pmds.

Collected folios stay locked while hmm_range_fault() may still fault
other pages of the range. This cannot deadlock: only anonymous folios
are collected, so no page cache or invalidate_lock ordering is involved,
and when the walk faults it collects only folios mapped by this process
alone (PageAnonExclusive), besides the fault folio. A folio shared with
another process (e.g. after fork) could be reached through that mapping
by another faulting walk, which would sleep on our folio lock while we
may sleep on its, so it is left as reported. A write fault breaks the
sharing first, so only read faults leave shared folios in place; that is
the price of faulting in the same walk. An exclusive folio is reachable
only through our migration entry, and walks waiting on each other's
migration entries can't form a cycle: a walk stops when it records a
fault, so it holds only what it collected before the check that led to
the fault, and a walk that finds another walk's migration entry leaves
it without waiting, so every wait goes to a walk that checked later (see
hmm_migrate_collectable()). Only the faulting pte is faulted, never our
own entries, and when faulting a swapcache folio still referenced by
other swap entries is not collected. The walk itself only trylocks folio
locks, also before splitting a folio. Reclaim and direct compaction
under the fault only trylock folio locks too.

When the pte lock has to be dropped to split a folio, the pmd may change
under us, so the walk re-reads it and continues at the current address,
as migrate_vma_setup() has always done: a changed pmd is handled for the
whole range, and entries collected before that address stay collected
and are released by finalize if their migration ptes are gone. When
locking or splitting a folio fails, the rest of the pmd is not walked
further, also as before.

HMM pagewalk based migration is enabled in later commit, for
now hmm_select_migrate() returns MIGRATE_VMA_SELECT_NONE.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 mm/hmm.c | 380 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 377 insertions(+), 3 deletions(-)

diff --git a/mm/hmm.c b/mm/hmm.c
index 273d0e364fd7..359ed7c16f29 100644
--- a/mm/hmm.c
+++ b/mm/hmm.c
@@ -73,6 +73,19 @@ struct hmm_vma_walk {
  */
 #define HMM_FAULT_UNLOCKED	-ENOLCK
 
+/*
+ * Internal results of hmm_vma_handle_migrate_prepare(), consumed by
+ * hmm_vma_walk_pmd() and never propagated. Both mean the pte lock was
+ * dropped: HMM_MIGRATE_REWALK after splitting a large folio, so the pmd
+ * range is walked again; HMM_MIGRATE_SKIP when a large folio can't be
+ * locked or split, so the rest of the pmd range is skipped (best effort).
+ */
+#define HMM_MIGRATE_REWALK	1
+#define HMM_MIGRATE_SKIP	2
+
+#define HMM_ASSERT_PTE_LOCKED(hmm_vma_walk, locked)		\
+	WARN_ON_ONCE((hmm_vma_walk)->ptelocked != (locked))
+
 #define HMM_ASSERT_UNLOCKED(hmm_vma_walk)			\
 	WARN_ON_ONCE((hmm_vma_walk)->ptelocked ||		\
 		     (hmm_vma_walk)->pmdlocked)
@@ -555,6 +568,75 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 #endif  /* CONFIG_ARCH_HAS_PMD_SOFTLEAVES */
 
 #ifdef CONFIG_DEVICE_MIGRATION
+/**
+ * __hmm_migrate_split_folio() - split a locked folio for migration
+ * @folio: the folio to split, locked and referenced by the caller
+ * @fault_page: fault page if any
+ *
+ * The fault folio is split at @fault_page, so the caller's lock and reference
+ * stay on the folio containing @fault_page. For any other folio our lock and
+ * reference are dropped, whether or not the split succeeds.
+ *
+ * Return: 0 on success, or the split_huge_page() / split_folio() error.
+ */
+static int __hmm_migrate_split_folio(struct folio *folio,
+				     struct page *fault_page)
+{
+	int ret;
+
+	if (fault_page && folio == page_folio(fault_page))
+		return split_huge_page(fault_page);
+
+	/* Found large under the page table lock and locked since: still large */
+	ret = folio_test_large(folio) ? split_folio(folio) : 0;
+	folio_unlock(folio);
+	folio_put(folio);
+	return ret;
+}
+
+/**
+ * hmm_migrate_split_folio() - drop the pte lock and split a THP folio
+ * @folio: the folio to split
+ * @fault_page: struct page associated with the fault if any
+ * @hmm_vma_walk: walk in progress
+ * @ptep: pte_t * for unmap and unlock ptl
+ *
+ * Always drops the pte lock associated with @ptep.
+ *
+ * Return: 0 on success, -EBUSY if the folio is locked by someone else, or the
+ * split_huge_page() / split_folio() error.
+ */
+static int hmm_migrate_split_folio(struct folio *folio,
+				   struct page *fault_page,
+				   struct hmm_vma_walk *hmm_vma_walk,
+				   pte_t *ptep)
+{
+	struct folio *fault_folio = fault_page ? page_folio(fault_page) : NULL;
+	bool locked = true;
+
+	/*
+	 * Take the reference while still holding the PTE lock, so the folio
+	 * cannot be freed once the lock is dropped. As at collection, only
+	 * trylock: other collected folios may be held locked, so sleeping
+	 * here could deadlock. A busy folio is just not migrated. The fault
+	 * folio is already referenced and locked by do_swap_page().
+	 */
+	if (folio != fault_folio) {
+		folio_get(folio);
+		locked = folio_trylock(folio);
+	}
+
+	pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
+	hmm_vma_walk->ptelocked = false;
+
+	if (!locked) {
+		folio_put(folio);
+		return -EBUSY;
+	}
+
+	return __hmm_migrate_split_folio(folio, fault_page);
+}
+
 /*
  * Due to dropping ptl locks for splitting for instance, would we
  * overwrite already collected pfns? This could happen when pmd
@@ -603,6 +685,29 @@ static void hmm_vma_handle_migrate_prepare_rollback(const struct hmm_vma_walk *h
 	}
 }
 
+/*
+ * Collected folios stay locked while hmm_range_fault() faults other pages
+ * of the range. When faulting, collect only the fault folio and folios
+ * mapped by this process alone (PageAnonExclusive): a shared folio can be
+ * reached by another faulting walk, which would sleep on our lock while we
+ * sleep on its. A write fault breaks the sharing first, so only read faults
+ * on still shared pages (after fork, or KSM) leave them in place: a rare,
+ * deliberate trade-off.
+ *
+ * An exclusive folio is reachable only through our migration entry, and
+ * waits on those can't form a cycle: a walk stops when it records a fault
+ * and leaves other walks' entries alone, so every wait goes to a walk that
+ * checked later.
+ */
+static bool hmm_migrate_collectable(const struct hmm_range *range,
+				    struct page *page,
+				    struct folio *fault_folio)
+{
+	if (!(range->default_flags & HMM_PFN_REQ_FAULT))
+		return true;
+	return page_folio(page) == fault_folio || PageAnonExclusive(page);
+}
+
 static int hmm_vma_handle_migrate_prepare_pmd(const struct mm_walk *walk,
 					      pmd_t *pmdp,
 					      unsigned long start,
@@ -613,6 +718,10 @@ static int hmm_vma_handle_migrate_prepare_pmd(const struct mm_walk *walk,
 	return 0;
 }
 
+/*
+ * Install migration entries if migration requested, either from fault
+ * or migrate paths.
+ */
 static int hmm_vma_handle_migrate_prepare(const struct mm_walk *walk,
 					  pmd_t *pmdp,
 					  pte_t *ptep,
@@ -620,8 +729,240 @@ static int hmm_vma_handle_migrate_prepare(const struct mm_walk *walk,
 					  unsigned long *hmm_pfn,
 					  bool *unmapped)
 {
-	/* Collection is implemented by later patches */
+	struct hmm_vma_walk *hmm_vma_walk = walk->private;
+	struct hmm_range *range = hmm_vma_walk->range;
+	struct migrate_vma *migrate = range->migrate;
+	struct mm_struct *mm = walk->vma->vm_mm;
+	struct folio *fault_folio = NULL;
+	enum migrate_vma_info minfo;
+	struct dev_pagemap *pgmap;
+	bool anon_exclusive;
+	struct folio *folio;
+	unsigned long pfn;
+	struct page *page;
+	softleaf_t entry;
+	pte_t pte, swp_pte;
+	bool writable = false;
+
+	/* Do we want to migrate at all? */
+	minfo = hmm_select_migrate(range);
+	if (!minfo)
+		return 0;
+
+	HMM_ASSERT_PTE_LOCKED(hmm_vma_walk, true);
+
+	fault_folio = migrate->fault_page ?
+		page_folio(migrate->fault_page) : NULL;
+
+	pte = ptep_get(ptep);
+
+	if (pte_none(pte)) {
+		if (vma_is_anonymous(walk->vma)) {
+			*hmm_pfn &= HMM_PFN_INOUT_FLAGS;
+			*hmm_pfn |= HMM_PFN_MIGRATE;
+			goto out;
+		}
+	}
+
+	/*
+	 * NUMA hinting (protnone) entries are not reported valid, but the
+	 * page can still be migrated as is.
+	 */
+	if (!(hmm_pfn[0] & HMM_PFN_VALID) &&
+	    !(pte_present(pte) && pte_protnone(pte)))
+		goto out;
+
+	if (!pte_present(pte)) {
+		/*
+		 * Only care about unaddressable device page special
+		 * page table entry. Other special swap entries are not
+		 * migratable, and we ignore regular swapped page.
+		 */
+		entry = softleaf_from_pte(pte);
+		if (!softleaf_is_device_private(entry))
+			goto out;
+
+		if (!(minfo & MIGRATE_VMA_SELECT_DEVICE_PRIVATE))
+			goto out;
+
+		page = softleaf_to_page(entry);
+		folio = page_folio(page);
+		if (folio->pgmap->owner != migrate->pgmap_owner)
+			goto out;
+
+		pfn = page_to_pfn(page);
+		if (softleaf_is_device_private_write(entry))
+			writable = true;
+	} else {
+		pfn = pte_pfn(pte);
+		if (is_zero_pfn(pfn) &&
+		    (minfo & MIGRATE_VMA_SELECT_SYSTEM)) {
+			/* Like pte_none(): only anonymous memory can be populated */
+			if (!vma_is_anonymous(walk->vma))
+				goto out;
+			/* Nothing carries the uffd state of the zero page over */
+			if (userfaultfd_protected(walk->vma) && pte_uffd(pte))
+				goto out;
+			*hmm_pfn &= HMM_PFN_INOUT_FLAGS;
+			*hmm_pfn |= HMM_PFN_MIGRATE;
+			goto out;
+		}
+		page = vm_normal_page(walk->vma, addr, pte);
+		if (page && !is_zone_device_page(page) &&
+		    !(minfo & MIGRATE_VMA_SELECT_SYSTEM)) {
+			goto out;
+		} else if (page && is_device_coherent_page(page)) {
+			pgmap = page_pgmap(page);
+
+			if (!(minfo &
+			      MIGRATE_VMA_SELECT_DEVICE_COHERENT) ||
+			    pgmap->owner != migrate->pgmap_owner)
+				goto out;
+		}
+
+		folio = page ? page_folio(page) : NULL;
+		/*
+		 * Only anonymous memory can be migrated to device memory.
+		 * Check before splitting.
+		 */
+		if (!folio || !folio_test_anon(folio))
+			goto out;
+
+		writable = pte_write(pte);
+	}
+
+	if (!hmm_migrate_collectable(range, page, fault_folio))
+		goto out;
+	if (folio_test_large(folio)) {
+		int ret;
+
+		ret = hmm_migrate_split_folio(folio, migrate->fault_page,
+					      hmm_vma_walk, ptep);
+		if (ret)
+			goto out_skip;
+		return HMM_MIGRATE_REWALK;
+	}
+
+	/*
+	 * By getting a reference on the folio we pin it and that blocks
+	 * any kind of migration. Side effect is that it "freezes" the
+	 * pte.
+	 *
+	 * We drop this reference after isolating the folio from the lru
+	 * for non device folio (device folio are not on the lru and thus
+	 * can't be dropped from it).
+	 */
+	folio = page_folio(page);
+	folio_get(folio);
+
+	/*
+	 * We rely on folio_trylock() to avoid deadlock between
+	 * concurrent migrations where each is waiting on the others
+	 * folio lock. If we can't immediately lock the folio we fail this
+	 * migration as it is only best effort anyway.
+	 *
+	 * If we can lock the folio it's safe to set up a migration entry
+	 * now. In the common case where the folio is mapped once in a
+	 * single process setting up the migration entry now is an
+	 * optimisation to avoid walking the rmap later with
+	 * try_to_migrate().
+	 */
+
+	if (fault_folio == folio || folio_trylock(folio)) {
+		/*
+		 * When faulting, a swapcache folio still referenced by other
+		 * swap entries isn't collected: faulting one of those entries
+		 * later in the walk, with no retry allowed, would block on the
+		 * lock we hold. It couldn't be migrated anyway (see
+		 * __migrate_device_pages()). Without faulting the swap cache is
+		 * left alone here and freed only when the folio is migrated.
+		 */
+		if ((range->default_flags & HMM_PFN_REQ_FAULT) &&
+		    folio_test_swapcache(folio) && !folio_free_swap(folio)) {
+			if (fault_folio != folio)
+				folio_unlock(folio);
+			folio_put(folio);
+			goto out;
+		}
+
+		/*
+		 * rmap_walk_ksm() may not find this pte to restore the
+		 * migration entry later.
+		 */
+		if (folio_test_ksm(folio)) {
+			if (fault_folio != folio)
+				folio_unlock(folio);
+			folio_put(folio);
+			goto out;
+		}
+
+		anon_exclusive = folio_test_anon(folio) &&
+			PageAnonExclusive(page);
+
+		if (pte_present(pte))
+			flush_cache_page(walk->vma, addr, pfn);
+
+		if (anon_exclusive) {
+			pte = ptep_clear_flush(walk->vma, addr, ptep);
+
+			if (folio_try_share_anon_rmap_pte(folio, page)) {
+				set_pte_at(mm, addr, ptep, pte);
+				if (fault_folio != folio)
+					folio_unlock(folio);
+				folio_put(folio);
+				goto out;
+			}
+		} else {
+			pte = ptep_get_and_clear(mm, addr, ptep);
+		}
+
+		if (pte_present(pte) && pte_dirty(pte))
+			folio_mark_dirty(folio);
+
+		/* Setup special migration page table entry */
+		if (writable)
+			entry = make_writable_migration_entry(pfn);
+		else if (anon_exclusive)
+			entry = make_readable_exclusive_migration_entry(pfn);
+		else
+			entry = make_readable_migration_entry(pfn);
+
+		if (pte_present(pte)) {
+			if (pte_young(pte))
+				entry = make_migration_entry_young(entry);
+			if (pte_dirty(pte))
+				entry = make_migration_entry_dirty(entry);
+		}
+
+		swp_pte = swp_entry_to_pte(entry);
+		if (pte_present(pte)) {
+			if (pte_soft_dirty(pte))
+				swp_pte = pte_swp_mksoft_dirty(swp_pte);
+			if (pte_uffd(pte))
+				swp_pte = pte_swp_mkuffd(swp_pte);
+		} else {
+			if (pte_swp_soft_dirty(pte))
+				swp_pte = pte_swp_mksoft_dirty(swp_pte);
+			if (pte_swp_uffd(pte))
+				swp_pte = pte_swp_mkuffd(swp_pte);
+		}
+
+		set_pte_at(mm, addr, ptep, swp_pte);
+		folio_remove_rmap_pte(folio, page, walk->vma);
+		folio_put(folio);
+		*hmm_pfn |= HMM_PFN_VALID | HMM_PFN_MIGRATE;
+		if (writable)
+			*hmm_pfn |= HMM_PFN_WRITE;
+		if (pte_present(pte))
+			*unmapped = true;
+	} else {
+		folio_put(folio);
+	}
+out:
 	return 0;
+out_skip:
+	/* Lock or split failed: the caller skips the rest of the pmd (best effort) */
+	return HMM_MIGRATE_SKIP;
 }
 
 #else
@@ -880,6 +1221,7 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 	} else {
 		ptep = pte_offset_map(pmdp, addr);
 	}
+	/* The pte table is gone: re-read the pmd and continue at addr */
 	if (!ptep)
 		goto again;
 
@@ -893,8 +1235,40 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 			return r;
 		}
 
-		/* Collection is added by later patches: a no-op until then */
-		hmm_vma_handle_migrate_prepare(walk, pmdp, ptep, addr, hmm_pfns, &unmapped);
+		r = hmm_vma_handle_migrate_prepare(walk, pmdp, ptep, addr, hmm_pfns, &unmapped);
+		if (r == HMM_MIGRATE_REWALK) {
+			HMM_ASSERT_UNLOCKED(hmm_vma_walk);
+			if (unmapped) {
+				flush_tlb_range(walk->vma, start, addr);
+				unmapped = false;
+			}
+			/*
+			 * The pte lock was dropped and the pmd may have changed:
+			 * re-read it and continue at addr, as migrate_vma_setup()
+			 * has always done. A changed pmd is handled for the whole
+			 * range. Entries collected before addr are not revisited:
+			 * if their migration ptes are gone meanwhile, finalize
+			 * releases them (see
+			 * hmm_vma_handle_migrate_prepare_rollback()).
+			 */
+			goto again;
+		}
+		if (r == HMM_MIGRATE_SKIP) {
+			/*
+			 * Locking or splitting the folio failed, and the split
+			 * helper already dropped the PTE lock. addr keeps its
+			 * valid pfn. The rest of the pmd range is not walked
+			 * further, as migrate_vma_setup() has always done:
+			 * entries there keep what an earlier pass wrote, and
+			 * entries already collected stay collected. When
+			 * migrating, collection and faulting are best effort
+			 * (see hmm_range_fault()).
+			 */
+			HMM_ASSERT_UNLOCKED(hmm_vma_walk);
+			if (unmapped)
+				flush_tlb_range(walk->vma, start, addr);
+			return 0;
+		}
 	}
 
 	if (unmapped)
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 07/14] mm/hmm: migrate collection in HMM pagewalk - pmd level
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (5 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 06/14] mm/hmm: migrate collection in HMM pagewalk - pte level mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 08/14] mm/hmm: add lazy MMU mode support for migration in HMM pagewalk mpenttil
                   ` (6 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

Implement the needed hmm_vma_handle_migrate_prepare_pmd() function
which is mostly carried over from migrate_device.c's
migrate_vma_collect_huge_pmd() function.

With HMM pagewalk based migration, the idea is that
hmm_vma_handle_*() are responsible for faulting, and the pfn
collecting part. hmm_vma_handle_migrate_prepare*() do the
migration decisions (with HMM_PFN_MIGRATE), possibly split
folios, and insert migration ptes/pmds.

Locking follows the same rules as at the pte level (see the previous
commit): only anonymous THPs are collected, and when faulting only ones
mapped by this process alone; the folio is only trylocked, a PMD-mapped
THP is collected whole behind its pmd migration entry, and when faulting
a swapcache folio still referenced by other swap entries is not
collected. On a trylock or split failure the valid pfns are kept and
nothing is migrated.

HMM pagewalk based migration is enabled in later commit, for now
hmm_select_migrate() returns MIGRATE_VMA_SELECT_NONE. The old
migrate_vma_collect_huge_pmd() is removed then. A uffd-protected huge
zero pmd is not collected, as at the pte level.

Also avoid the problems present in the migrate_vma_collect_huge_pmd()
split fallback path this HMM path supersedes:

      - extra refcount for fault_folio makes split_folio() fail
      - wrong folio unlocked after split_folio()

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 mm/hmm.c | 162 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 161 insertions(+), 1 deletion(-)

diff --git a/mm/hmm.c b/mm/hmm.c
index 359ed7c16f29..8a2197a4db5a 100644
--- a/mm/hmm.c
+++ b/mm/hmm.c
@@ -86,6 +86,9 @@ struct hmm_vma_walk {
 #define HMM_ASSERT_PTE_LOCKED(hmm_vma_walk, locked)		\
 	WARN_ON_ONCE((hmm_vma_walk)->ptelocked != (locked))
 
+#define HMM_ASSERT_PMD_LOCKED(hmm_vma_walk, locked)		\
+	WARN_ON_ONCE((hmm_vma_walk)->pmdlocked != (locked))
+
 #define HMM_ASSERT_UNLOCKED(hmm_vma_walk)			\
 	WARN_ON_ONCE((hmm_vma_walk)->ptelocked ||		\
 		     (hmm_vma_walk)->pmdlocked)
@@ -714,8 +717,154 @@ static int hmm_vma_handle_migrate_prepare_pmd(const struct mm_walk *walk,
 					      unsigned long end,
 					      unsigned long *hmm_pfn)
 {
-	/* Collection is implemented by later patches */
+	struct hmm_vma_walk *hmm_vma_walk = walk->private;
+	struct hmm_range *range = hmm_vma_walk->range;
+	struct migrate_vma *migrate = range->migrate;
+	struct folio *fault_folio = NULL;
+	enum migrate_vma_info minfo;
+	struct folio *folio;
+	unsigned long i;
+	pmd_t pmd;
+	int r;
+
+	/* Do we want to migrate at all? */
+	minfo = hmm_select_migrate(range);
+	if (!minfo)
+		return 0;
+
+	HMM_ASSERT_PMD_LOCKED(hmm_vma_walk, true);
+
+	fault_folio = migrate->fault_page ?
+		page_folio(migrate->fault_page) : NULL;
+
+	/*
+	 * The caller holds the pmd lock and found a huge or device private
+	 * pmd; none and migration entries it handles itself.
+	 */
+	pmd = pmdp_get(pmdp);
+
+	/* Like at the pte level, NUMA hinting (protnone) pmds are migrated */
+	if (!(hmm_pfn[0] & HMM_PFN_VALID) &&
+	    !(pmd_trans_huge(pmd) && pmd_protnone(pmd)))
+		goto out;
+
+	if (pmd_trans_huge(pmd)) {
+		folio = pmd_folio(pmd);
+		/* Like at the pte level */
+		if (folio_is_device_coherent(folio)) {
+			if (!(minfo & MIGRATE_VMA_SELECT_DEVICE_COHERENT) ||
+			    folio->pgmap->owner != migrate->pgmap_owner)
+				goto out;
+		} else {
+			if (!(minfo & MIGRATE_VMA_SELECT_SYSTEM))
+				goto out;
+			if (is_huge_zero_folio(folio)) {
+				/* See the pte level: keep a uffd-protected zero page */
+				if (userfaultfd_protected(walk->vma) &&
+				    pmd_uffd(pmd))
+					goto out;
+				return hmm_pfns_fill(start, end, hmm_vma_walk, 0);
+			}
+		}
+		/* Only anonymous memory, as at the pte level */
+		if (!folio_test_anon(folio))
+			goto out;
+		if (!hmm_migrate_collectable(range, folio_page(folio, 0),
+					     fault_folio))
+			goto out;
+
+	} else if (!pmd_present(pmd)) {
+		const softleaf_t entry = softleaf_from_pmd(pmd);
+
+		if (!softleaf_is_device_private(entry))
+			goto out;
+
+		if (!(minfo & MIGRATE_VMA_SELECT_DEVICE_PRIVATE))
+			goto out;
+
+		folio = softleaf_to_folio(entry);
+		if (folio->pgmap->owner != migrate->pgmap_owner)
+			goto out;
+		if (!hmm_migrate_collectable(range, folio_page(folio, 0),
+					     fault_folio))
+			goto out;
+	} else {
+		VM_WARN_ON_ONCE(1);
+		goto out;
+	}
+
+	folio_get(folio);
+
+	/* Can't lock it: not migrated, the valid pfns stay as reported */
+	if (folio != fault_folio && unlikely(!folio_trylock(folio))) {
+		folio_put(folio);
+		return 0;
+	}
+
+	/* Swapcache folio still referenced elsewhere: see the pte level */
+	if ((range->default_flags & HMM_PFN_REQ_FAULT) &&
+	    folio_test_swapcache(folio) && !folio_free_swap(folio)) {
+		if (folio != fault_folio)
+			folio_unlock(folio);
+		folio_put(folio);
+		return 0;
+	}
+
+	if (thp_migration_supported() &&
+	    (minfo & MIGRATE_VMA_SELECT_COMPOUND) &&
+	    (IS_ALIGNED(start, HPAGE_PMD_SIZE) &&
+	     IS_ALIGNED(end, HPAGE_PMD_SIZE))) {
+		struct page_vma_mapped_walk pvmw = {
+			.ptl = hmm_vma_walk->ptl,
+			.address = start,
+			.pmd = pmdp,
+			.vma = walk->vma,
+		};
+		bool writable = pmd_trans_huge(pmd) && pmd_write(pmd);
+
+		hmm_pfn[0] |= HMM_PFN_MIGRATE | HMM_PFN_COMPOUND;
+
+		r = set_pmd_migration_entry(&pvmw, folio_page(folio, 0));
+		if (r) {
+			hmm_pfn[0] &= ~(HMM_PFN_MIGRATE | HMM_PFN_COMPOUND);
+			goto split;	/* fall back to splitting the pmd */
+		}
+		/* Collected; a protnone pmd was not reported valid before */
+		hmm_pfn[0] |= HMM_PFN_VALID;
+		if (writable)
+			hmm_pfn[0] |= HMM_PFN_WRITE;
+		for (i = 1, start += PAGE_SIZE; start < end; start += PAGE_SIZE, i++)
+			hmm_pfn[i] &= HMM_PFN_INOUT_FLAGS;
+
+	} else {
+		goto split;		/* fall back to splitting the pmd */
+	}
+
+out:
 	return 0;
+
+split:
+	spin_unlock(hmm_vma_walk->ptl);
+	hmm_vma_walk->pmdlocked = false;
+
+	/*
+	 * folio_get() above took an extra reference. For the fault folio the
+	 * caller still holds a reference and the lock, which is the
+	 * precondition of __hmm_migrate_split_folio(), so drop the extra one.
+	 */
+	if (folio == fault_folio)
+		folio_put(folio);
+
+	/* Split failed: not migrated, the valid pfns stay as reported */
+	if (__hmm_migrate_split_folio(folio, migrate->fault_page))
+		return 0;
+
+	/* Re-walked as PTEs from start: drop the pmd-level output */
+	for (i = 0; i < (end - start) >> PAGE_SHIFT; i++)
+		hmm_pfn[i] &= HMM_PFN_INOUT_FLAGS;
+
+	hmm_vma_walk->last = start;
+	return -EBUSY;
 }
 
 /*
@@ -1194,6 +1343,17 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 			hmm_vma_walk->pmdlocked = false;
 		}
 
+		/*
+		 * hmm_vma_handle_migrate_prepare_pmd() splits the huge pmd in
+		 * place when needed and returns -EBUSY to walk the range again
+		 * as PTEs. Without a notifier that happens in the retry loop of
+		 * hmm_range_fault_locked(). With a notifier, the split's
+		 * MMU_NOTIFY_CLEAR invalidation ends the walk with -EBUSY: the
+		 * caller aborts and retries the range under its own retry policy
+		 * (timeout), at the cost of one extra pass per huge pmd split.
+		 * That is every collected THP not migrated whole with
+		 * MIGRATE_VMA_SELECT_COMPOUND.
+		 */
 		return r;
 	}
 
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 08/14] mm/hmm: add lazy MMU mode support for migration in HMM pagewalk
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (6 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 07/14] mm/hmm: migrate collection in HMM pagewalk - pmd level mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 09/14] mm: enable device page migration from " mpenttil
                   ` (5 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

Add calls to lazy_mmu_mode_enable() and lazy_mmu_mode_disable()
while doing migration.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 mm/hmm.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/mm/hmm.c b/mm/hmm.c
index 8a2197a4db5a..d2f5909940d3 100644
--- a/mm/hmm.c
+++ b/mm/hmm.c
@@ -431,6 +431,7 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 		/* Report error for everything else */
 
 		if (hmm_vma_walk->ptelocked) {
+			lazy_mmu_mode_disable();
 			pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
 			hmm_vma_walk->ptelocked = false;
 		} else {
@@ -454,6 +455,7 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 	    !is_zero_pfn(pte_pfn(pte))) {
 		if (hmm_pte_need_fault(hmm_vma_walk, pfn_req_flags, 0)) {
 			if (hmm_vma_walk->ptelocked) {
+				lazy_mmu_mode_disable();
 				pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
 				hmm_vma_walk->ptelocked = false;
 			} else {
@@ -476,6 +478,7 @@ static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
 
 fault:
 	if (hmm_vma_walk->ptelocked) {
+		lazy_mmu_mode_disable();
 		pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
 		hmm_vma_walk->ptelocked = false;
 	} else {
@@ -629,6 +632,7 @@ static int hmm_migrate_split_folio(struct folio *folio,
 		locked = folio_trylock(folio);
 	}
 
+	lazy_mmu_mode_disable();
 	pte_unmap_unlock(ptep, hmm_vma_walk->ptl);
 	hmm_vma_walk->ptelocked = false;
 
@@ -1376,8 +1380,10 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 
 	if (minfo) {
 		ptep = pte_offset_map_lock(mm, pmdp, addr, &hmm_vma_walk->ptl);
-		if (ptep)
+		if (ptep) {
+			lazy_mmu_mode_enable();
 			hmm_vma_walk->ptelocked = true;
+		}
 	} else {
 		ptep = pte_offset_map(pmdp, addr);
 	}
@@ -1435,6 +1441,7 @@ static int hmm_vma_walk_pmd(pmd_t *pmdp,
 		flush_tlb_range(walk->vma, start, addr);
 
 	if (hmm_vma_walk->ptelocked) {
+		lazy_mmu_mode_disable();
 		pte_unmap_unlock(ptep - 1, hmm_vma_walk->ptl);
 		hmm_vma_walk->ptelocked = false;
 	} else {
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 09/14] mm: enable device page migration from HMM pagewalk
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (7 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 08/14] mm/hmm: add lazy MMU mode support for migration in HMM pagewalk mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 10/14] lib/test_hmm: add a new testcase for the migrate on fault mpenttil
                   ` (4 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

HMM pagewalk has now the machinery to do the first phase of
device page migration, collecting the pfns and installing
migration ptes.

Enable migration in hmm_range_fault(), and change migrate_vma_setup() to
use HMM pagewalk path. Two new flags, MIGRATE_VMA_FAULT and
MIGRATE_VMA_WRITE, let migrate_vma_setup() callers fault in missing
pages, for read or for write, in the same walk. Without them, pages that
aren't present (swapped out, or another device's private pages) are
skipped, and shared pages after fork are migrated as they are, for every
process mapping them and read-only. MIGRATE_VMA_FAULT faults the missing
pages in, and MIGRATE_VMA_WRITE also breaks the sharing first, so the
device gets an exclusive writable copy, without a separate
hmm_range_fault() or GUP pass. When faulting, shared pages are collected
only after such a write fault: with MIGRATE_VMA_FAULT alone they stay in
place, as the walk can't hold a folio another process can fault on while
it sleeps in a fault itself (see the pte level collection commit). If a
fault fails, the partial collection is undone and migrate_vma_setup()
returns the error. Drivers that migrate on device fault use
hmm_range_fault() with HMM_PFN_REQ_MIGRATE directly, as the test_hmm and
nouveau changes later in this series do.

Only anonymous folios are collected now. The old collector also took
file folios, which could only move to system memory; no in-tree user
migrates those.

migrate_vma_setup() refuses shadow stack vmas up front, as in the
pending "mm/migrate_device: refuse to migrate shadow stacks". It also
refuses the fault flags together with a fault page: from
migrate_to_ram() the fault page is locked by do_swap_page(), and nested
faults must not start under it.

Without the fault flags, migrate_vma_setup() still fails only on invalid
arguments or an unsupported vma. nouveau's migrate_to_ram() leaks its
src/dst arrays when migrate_vma_setup() fails or collects nothing; that
is pre-existing (since c32287471077) and fixed by a later patch in this
series.

Also, the migrate_vma_collect*() based paths are now unused,
so delete them.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Suggested-by: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 arch/powerpc/include/asm/book3s/64/pgtable.h |   2 +-
 drivers/gpu/drm/drm_pagemap.c                |   2 +-
 include/linux/migrate.h                      |  10 +-
 include/linux/mmu_notifier.h                 |   3 +-
 mm/hmm.c                                     |  42 +-
 mm/migrate_device.c                          | 593 +++----------------
 6 files changed, 129 insertions(+), 523 deletions(-)

diff --git a/arch/powerpc/include/asm/book3s/64/pgtable.h b/arch/powerpc/include/asm/book3s/64/pgtable.h
index dff8790a047d..c821d305aefc 100644
--- a/arch/powerpc/include/asm/book3s/64/pgtable.h
+++ b/arch/powerpc/include/asm/book3s/64/pgtable.h
@@ -1334,7 +1334,7 @@ static inline pmd_t pmdp_huge_get_and_clear(struct mm_struct *mm,
 	 * entries. This can happen at 2 places:
 	 * - When the address space is being unmapped zap_huge_pmd(), and we
 	 *   encounter non-present pmds.
-	 * - migrate_vma_collect_huge_pmd() could calls this during migration
+	 * - hmm_vma_handle_migrate_prepare_pmd() could call this during migration
 	 *   of device-private pmd entries.
 	 */
 	if (!pmd_present(*pmdp)) {
diff --git a/drivers/gpu/drm/drm_pagemap.c b/drivers/gpu/drm/drm_pagemap.c
index bbef0c225b7e..1d1785f349cf 100644
--- a/drivers/gpu/drm/drm_pagemap.c
+++ b/drivers/gpu/drm/drm_pagemap.c
@@ -948,7 +948,7 @@ static int drm_pagemap_migrate_populate_ram_pfn(struct vm_area_struct *vas,
 		 * A large source folio is always collected whole, at its head
 		 * page, PMD aligned and flagged MIGRATE_PFN_COMPOUND: anything
 		 * else is split before it reaches us, either by
-		 * migrate_vma_collect_pmd() or, for the eviction path, by
+		 * the migration collection in mm/hmm.c or, for the eviction path, by
 		 * migrate_device_pfns(). Both the order-0 fallback below and
 		 * drm_pagemap_migrate_populate_src_pages() rely on that, as
 		 * they index the folio from @i.
diff --git a/include/linux/migrate.h b/include/linux/migrate.h
index 9513d1697232..b13600876083 100644
--- a/include/linux/migrate.h
+++ b/include/linux/migrate.h
@@ -188,6 +188,8 @@ enum migrate_vma_info {
 	MIGRATE_VMA_SELECT_DEVICE_PRIVATE = 1 << 1,
 	MIGRATE_VMA_SELECT_DEVICE_COHERENT = 1 << 2,
 	MIGRATE_VMA_SELECT_COMPOUND = 1 << 3,
+	MIGRATE_VMA_FAULT = 1 << 4,
+	MIGRATE_VMA_WRITE = 1 << 5,
 };
 
 struct migrate_vma {
@@ -230,10 +232,14 @@ struct migrate_vma {
  * here next to struct migrate_vma, which they use, and the !CONFIG_MIGRATION
  * stubs above let mm/hmm.c build without #ifdefs.
  */
-/* Migration collection in hmm_range_fault() is enabled later in the series */
 static inline enum migrate_vma_info hmm_select_migrate(struct hmm_range *range)
 {
-	return MIGRATE_VMA_SELECT_NONE;
+	enum migrate_vma_info minfo;
+
+	minfo = (range->default_flags & HMM_PFN_REQ_MIGRATE) ?
+		range->migrate->flags : 0;
+
+	return minfo;
 }
 
 static inline void *hmm_migrate_pgmap_owner(struct hmm_range *range)
diff --git a/include/linux/mmu_notifier.h b/include/linux/mmu_notifier.h
index 5db78e5761c5..1d5115df2bbc 100644
--- a/include/linux/mmu_notifier.h
+++ b/include/linux/mmu_notifier.h
@@ -39,7 +39,8 @@ struct mmu_interval_notifier;
  * @MMU_NOTIFY_RELEASE: used during mmu_interval_notifier invalidate to signal
  * that the mm refcount is zero and the range is no longer accessible.
  *
- * @MMU_NOTIFY_MIGRATE: used during migrate_vma_collect() invalidate to signal
+ * @MMU_NOTIFY_MIGRATE: used during migration collection (migrate_vma_setup(),
+ * or hmm_range_fault() with HMM_PFN_REQ_MIGRATE) invalidate to signal
  * a device driver to possibly ignore the invalidation if the
  * owner field matches the driver's device private pgmap owner.
  *
diff --git a/mm/hmm.c b/mm/hmm.c
index d2f5909940d3..c97ab0e4271e 100644
--- a/mm/hmm.c
+++ b/mm/hmm.c
@@ -1804,8 +1804,46 @@ static int hmm_range_fault_locked(struct hmm_range *range, bool *locked)
  *
  * The mmap lock must be held by the caller and will remain held on return.
  * New users should prefer hmm_range_fault_unlocked_timeout() unless they
- * specifically need to keep the mmap lock held across the call. This helper
- * cannot support VMAs whose fault handlers need to drop the mmap lock.
+ * specifically need to keep the mmap lock held across the call like while
+ * migrating. This helper cannot support VMAs whose fault handlers need to
+ * drop the mmap lock.
+ *
+ * If want to do migration after faulting, call hmm_range_fault() with
+ * range.default_flags of HMM_PFN_REQ_MIGRATE, and optionally
+ * HMM_PFN_REQ_FAULT|HMM_PFN_REQ_WRITE, and initialize range->migrate field.
+ * range->migrate->vma will be populated during the call,
+ * and must be stable across the whole migrate process, which is
+ * why mmap_lock must be held around this call.
+ *
+ * When HMM_PFN_REQ_MIGRATE is set, migration collection may be partial on
+ * return and the caller takes responsibility for completing or aborting it.
+ * Collection is then best effort: a folio that can't be locked is left as
+ * reported, and if a large folio can't be locked for splitting or can't be
+ * split, the rest of its pmd range is not walked further (not faulted or
+ * collected), even with HMM_PFN_REQ_FAULT. Entries under another migration
+ * are not waited for, as that could deadlock: they are reported as 0 (not
+ * valid) and not collected. When faulting, a folio shared with other
+ * processes (after fork, or KSM) is not collected but left as reported (see
+ * hmm_migrate_collectable()); a write fault gives this process its own copy
+ * first. Callers check HMM_PFN_VALID and HMM_PFN_MIGRATE per entry.
+ *
+ * Other tasks' faults on collected pages wait until the migration is
+ * finalized, so the caller must not hold locks across the call that it
+ * takes again before migrate_vma_finalize().
+ *
+ * On success, the caller calls migrate_hmm_range_setup() and then either
+ * completes the migration (prepare destination pages, migrate_vma_pages(),
+ * update device mappings as needed, migrate_vma_finalize()) or aborts it as
+ * below. Either way migrate_vma_finalize() must be called.
+ *
+ * On any error, including -EBUSY, the caller must call
+ * migrate_hmm_range_setup(), migrate_vma_pages() with no valid destination
+ * entries, and migrate_vma_finalize() to abort the partial migration before
+ * retrying. A migrating call clears range->hmm_pfns on entry and does not
+ * resume a previous attempt.
+ *
+ * The mmap read lock must remain held until the migration has either been
+ * completed or aborted.
  */
 int hmm_range_fault(struct hmm_range *range)
 {
diff --git a/mm/migrate_device.c b/mm/migrate_device.c
index 5db01a728fce..81fa96e92b94 100644
--- a/mm/migrate_device.c
+++ b/mm/migrate_device.c
@@ -18,507 +18,6 @@
 #include <asm/tlbflush.h>
 #include "internal.h"
 
-static int migrate_vma_collect_skip(unsigned long start,
-				    unsigned long end,
-				    struct mm_walk *walk)
-{
-	struct migrate_vma *migrate = walk->private;
-	unsigned long addr;
-
-	for (addr = start; addr < end; addr += PAGE_SIZE) {
-		migrate->dst[migrate->npages] = 0;
-		migrate->src[migrate->npages++] = 0;
-	}
-
-	return 0;
-}
-
-static int migrate_vma_collect_hole(unsigned long start,
-				    unsigned long end,
-				    __always_unused int depth,
-				    struct mm_walk *walk)
-{
-	struct migrate_vma *migrate = walk->private;
-	unsigned long addr;
-
-	/* Only allow populating anonymous memory. */
-	if (!vma_is_anonymous(walk->vma))
-		return migrate_vma_collect_skip(start, end, walk);
-
-	if (thp_migration_supported() &&
-		(migrate->flags & MIGRATE_VMA_SELECT_COMPOUND) &&
-		(IS_ALIGNED(start, HPAGE_PMD_SIZE) &&
-		 IS_ALIGNED(end, HPAGE_PMD_SIZE))) {
-		migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE |
-						MIGRATE_PFN_COMPOUND;
-		migrate->dst[migrate->npages] = 0;
-		migrate->npages++;
-		migrate->cpages++;
-
-		/*
-		 * Collect the remaining entries as holes, in case we
-		 * need to split later
-		 */
-		return migrate_vma_collect_skip(start + PAGE_SIZE, end, walk);
-	}
-
-	for (addr = start; addr < end; addr += PAGE_SIZE) {
-		migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
-		migrate->dst[migrate->npages] = 0;
-		migrate->npages++;
-		migrate->cpages++;
-	}
-
-	return 0;
-}
-
-/**
- * migrate_vma_split_folio() - Helper function to split a THP folio
- * @folio: the folio to split
- * @fault_page: struct page associated with the fault if any
- *
- * If @folio is not the folio containing @fault_page, the caller must hold a
- * reference on @folio. The helper consumes that reference.
- *
- * Returns 0 on success
- */
-static int migrate_vma_split_folio(struct folio *folio,
-				   struct page *fault_page)
-{
-	int ret;
-	struct folio *fault_folio = fault_page ? page_folio(fault_page) : NULL;
-
-	/*
-	 * The lock and the reference of the fault handler stay with the
-	 * folio which holds the fault page after the split.
-	 */
-	if (folio == fault_folio)
-		return split_huge_page(fault_page);
-
-	folio_lock(folio);
-	ret = split_folio(folio);
-	folio_unlock(folio);
-	folio_put(folio);
-
-	return ret;
-}
-
-/** migrate_vma_collect_huge_pmd - collect THP pages without splitting the
- * folio for device private pages.
- * @pmdp: pointer to pmd entry
- * @start: start address of the range for migration
- * @end: end address of the range for migration
- * @walk: mm_walk callback structure
- * @fault_folio: folio associated with the fault if any
- *
- * Collect the huge pmd entry at @pmdp for migration and set the
- * MIGRATE_PFN_COMPOUND flag in the migrate src entry to indicate that
- * migration will occur at HPAGE_PMD granularity
- */
-static int migrate_vma_collect_huge_pmd(pmd_t *pmdp, unsigned long start,
-					unsigned long end, struct mm_walk *walk,
-					struct folio *fault_folio)
-{
-	struct mm_struct *mm = walk->mm;
-	struct folio *folio;
-	struct migrate_vma *migrate = walk->private;
-	spinlock_t *ptl;
-	int ret;
-	unsigned long write = 0;
-
-	ptl = pmd_lock(mm, pmdp);
-	if (pmd_none(*pmdp)) {
-		spin_unlock(ptl);
-		return migrate_vma_collect_hole(start, end, -1, walk);
-	}
-
-	if (pmd_trans_huge(*pmdp)) {
-		if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM)) {
-			spin_unlock(ptl);
-			return migrate_vma_collect_skip(start, end, walk);
-		}
-
-		folio = pmd_folio(*pmdp);
-		if (is_huge_zero_folio(folio)) {
-			spin_unlock(ptl);
-			return migrate_vma_collect_hole(start, end, -1, walk);
-		}
-		if (pmd_write(*pmdp))
-			write = MIGRATE_PFN_WRITE;
-	} else if (!pmd_present(*pmdp)) {
-		const softleaf_t entry = softleaf_from_pmd(*pmdp);
-
-		if (!softleaf_is_device_private(entry) ||
-		    !(migrate->flags & MIGRATE_VMA_SELECT_DEVICE_PRIVATE)) {
-			spin_unlock(ptl);
-			return migrate_vma_collect_skip(start, end, walk);
-		}
-
-		folio = softleaf_to_folio(entry);
-		if (folio->pgmap->owner != migrate->pgmap_owner) {
-			spin_unlock(ptl);
-			return migrate_vma_collect_skip(start, end, walk);
-		}
-
-		if (softleaf_is_device_private_write(entry))
-			write = MIGRATE_PFN_WRITE;
-	} else {
-		spin_unlock(ptl);
-		return -EAGAIN;
-	}
-
-	folio_get(folio);
-	if (folio != fault_folio && unlikely(!folio_trylock(folio))) {
-		spin_unlock(ptl);
-		folio_put(folio);
-		return migrate_vma_collect_skip(start, end, walk);
-	}
-
-	if (thp_migration_supported() &&
-		(migrate->flags & MIGRATE_VMA_SELECT_COMPOUND) &&
-		(IS_ALIGNED(start, HPAGE_PMD_SIZE) &&
-		 IS_ALIGNED(end, HPAGE_PMD_SIZE))) {
-
-		struct page_vma_mapped_walk pvmw = {
-			.ptl = ptl,
-			.address = start,
-			.pmd = pmdp,
-			.vma = walk->vma,
-		};
-
-		unsigned long pfn = page_to_pfn(folio_page(folio, 0));
-
-		migrate->src[migrate->npages] = migrate_pfn(pfn) | write
-						| MIGRATE_PFN_MIGRATE
-						| MIGRATE_PFN_COMPOUND;
-		migrate->dst[migrate->npages++] = 0;
-		migrate->cpages++;
-		ret = set_pmd_migration_entry(&pvmw, folio_page(folio, 0));
-		if (ret) {
-			migrate->npages--;
-			migrate->cpages--;
-			migrate->src[migrate->npages] = 0;
-			migrate->dst[migrate->npages] = 0;
-			goto fallback;
-		}
-		migrate_vma_collect_skip(start + PAGE_SIZE, end, walk);
-		spin_unlock(ptl);
-		return 0;
-	}
-
-fallback:
-	spin_unlock(ptl);
-	if (!folio_test_large(folio))
-		goto done;
-	ret = split_folio(folio);
-	if (fault_folio != folio)
-		folio_unlock(folio);
-	folio_put(folio);
-	if (ret)
-		return migrate_vma_collect_skip(start, end, walk);
-	if (pmd_none(pmdp_get_lockless(pmdp)))
-		return migrate_vma_collect_hole(start, end, -1, walk);
-
-done:
-	return -ENOENT;
-}
-
-static int migrate_vma_collect_pmd(pmd_t *pmdp,
-				   unsigned long start,
-				   unsigned long end,
-				   struct mm_walk *walk)
-{
-	struct migrate_vma *migrate = walk->private;
-	struct vm_area_struct *vma = walk->vma;
-	struct mm_struct *mm = vma->vm_mm;
-	unsigned long addr = start, unmapped = 0;
-	spinlock_t *ptl;
-	struct folio *fault_folio;
-	pte_t *ptep;
-
-again:
-	/* The fault page is in another folio once its folio has been split */
-	fault_folio = migrate->fault_page ?
-		page_folio(migrate->fault_page) : NULL;
-
-	/* [start, addr) is collected if we get here after splitting a folio */
-	if (pmd_trans_huge(*pmdp) || !pmd_present(*pmdp)) {
-		int ret = migrate_vma_collect_huge_pmd(pmdp, addr, end, walk, fault_folio);
-
-		if (ret == -EAGAIN)
-			goto again;
-		if (ret == 0) {
-			if (unmapped)
-				flush_tlb_range(walk->vma, start, end);
-			return 0;
-		}
-	}
-
-	ptep = pte_offset_map_lock(mm, pmdp, start, &ptl);
-	if (!ptep)
-		goto again;
-	lazy_mmu_mode_enable();
-	ptep += (addr - start) / PAGE_SIZE;
-
-	for (; addr < end; addr += PAGE_SIZE, ptep++) {
-		struct dev_pagemap *pgmap;
-		unsigned long mpfn = 0, pfn;
-		struct folio *folio;
-		struct page *page;
-		softleaf_t entry;
-		pte_t pte;
-
-		pte = ptep_get(ptep);
-
-		if (pte_none(pte)) {
-			if (vma_is_anonymous(vma)) {
-				mpfn = MIGRATE_PFN_MIGRATE;
-				migrate->cpages++;
-			}
-			goto next;
-		}
-
-		if (!pte_present(pte)) {
-			/*
-			 * Only care about unaddressable device page special
-			 * page table entry. Other special swap entries are not
-			 * migratable, and we ignore regular swapped page.
-			 */
-			entry = softleaf_from_pte(pte);
-			if (!softleaf_is_device_private(entry))
-				goto next;
-
-			page = softleaf_to_page(entry);
-			pgmap = page_pgmap(page);
-			if (!(migrate->flags &
-				MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
-			    pgmap->owner != migrate->pgmap_owner)
-				goto next;
-
-			folio = page_folio(page);
-			if (folio_test_large(folio)) {
-				int ret;
-
-				/* migrate_vma_split_folio() consumes this reference */
-				if (folio != fault_folio)
-					folio_get(folio);
-				lazy_mmu_mode_disable();
-				pte_unmap_unlock(ptep, ptl);
-				ret = migrate_vma_split_folio(folio,
-							  migrate->fault_page);
-
-				if (ret) {
-					if (unmapped)
-						flush_tlb_range(walk->vma, start, end);
-
-					return migrate_vma_collect_skip(addr, end, walk);
-				}
-
-				goto again;
-			}
-
-			mpfn = migrate_pfn(page_to_pfn(page)) |
-					MIGRATE_PFN_MIGRATE;
-			if (softleaf_is_device_private_write(entry))
-				mpfn |= MIGRATE_PFN_WRITE;
-		} else {
-			pfn = pte_pfn(pte);
-			if (is_zero_pfn(pfn) &&
-			    (migrate->flags & MIGRATE_VMA_SELECT_SYSTEM)) {
-				mpfn = MIGRATE_PFN_MIGRATE;
-				migrate->cpages++;
-				goto next;
-			}
-			page = vm_normal_page(migrate->vma, addr, pte);
-			if (page && !is_zone_device_page(page) &&
-			    !(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM)) {
-				goto next;
-			} else if (page && is_device_coherent_page(page)) {
-				pgmap = page_pgmap(page);
-
-				if (!(migrate->flags &
-					MIGRATE_VMA_SELECT_DEVICE_COHERENT) ||
-					pgmap->owner != migrate->pgmap_owner)
-					goto next;
-			}
-			folio = page ? page_folio(page) : NULL;
-			if (folio && folio_test_large(folio)) {
-				int ret;
-
-				/* migrate_vma_split_folio() consumes this reference */
-				if (folio != fault_folio)
-					folio_get(folio);
-				lazy_mmu_mode_disable();
-				pte_unmap_unlock(ptep, ptl);
-				ret = migrate_vma_split_folio(folio,
-							  migrate->fault_page);
-
-				if (ret) {
-					if (unmapped)
-						flush_tlb_range(walk->vma, start, end);
-
-					return migrate_vma_collect_skip(addr, end, walk);
-				}
-
-				goto again;
-			}
-			mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
-			mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
-		}
-
-		if (!page || !page->mapping) {
-			mpfn = 0;
-			goto next;
-		}
-
-		/*
-		 * By getting a reference on the folio we pin it and that blocks
-		 * any kind of migration. Side effect is that it "freezes" the
-		 * pte.
-		 *
-		 * We drop this reference after isolating the folio from the lru
-		 * for non device folio (device folio are not on the lru and thus
-		 * can't be dropped from it).
-		 */
-		folio = page_folio(page);
-		folio_get(folio);
-
-		/*
-		 * We rely on folio_trylock() to avoid deadlock between
-		 * concurrent migrations where each is waiting on the others
-		 * folio lock. If we can't immediately lock the folio we fail this
-		 * migration as it is only best effort anyway.
-		 *
-		 * If we can lock the folio it's safe to set up a migration entry
-		 * now. In the common case where the folio is mapped once in a
-		 * single process setting up the migration entry now is an
-		 * optimisation to avoid walking the rmap later with
-		 * try_to_migrate().
-		 */
-		if (fault_folio == folio || folio_trylock(folio)) {
-			bool anon_exclusive;
-			pte_t swp_pte;
-
-			if (pte_present(pte))
-				flush_cache_page(vma, addr, pte_pfn(pte));
-			anon_exclusive = folio_test_anon(folio) &&
-					  PageAnonExclusive(page);
-			if (anon_exclusive) {
-				pte = ptep_clear_flush(vma, addr, ptep);
-
-				if (folio_try_share_anon_rmap_pte(folio, page)) {
-					set_pte_at(mm, addr, ptep, pte);
-					if (fault_folio != folio)
-						folio_unlock(folio);
-					folio_put(folio);
-					mpfn = 0;
-					goto next;
-				}
-			} else {
-				pte = ptep_get_and_clear(mm, addr, ptep);
-			}
-
-			migrate->cpages++;
-
-			/* Set the dirty flag on the folio now the pte is gone. */
-			if (pte_present(pte) && pte_dirty(pte))
-				folio_mark_dirty(folio);
-
-			/* Setup special migration page table entry */
-			if (mpfn & MIGRATE_PFN_WRITE)
-				entry = make_writable_migration_entry(
-							page_to_pfn(page));
-			else if (anon_exclusive)
-				entry = make_readable_exclusive_migration_entry(
-							page_to_pfn(page));
-			else
-				entry = make_readable_migration_entry(
-							page_to_pfn(page));
-			if (pte_present(pte)) {
-				if (pte_young(pte))
-					entry = make_migration_entry_young(entry);
-				if (pte_dirty(pte))
-					entry = make_migration_entry_dirty(entry);
-			}
-			swp_pte = swp_entry_to_pte(entry);
-			if (pte_present(pte)) {
-				if (pte_soft_dirty(pte))
-					swp_pte = pte_swp_mksoft_dirty(swp_pte);
-				if (pte_uffd(pte))
-					swp_pte = pte_swp_mkuffd(swp_pte);
-			} else {
-				if (pte_swp_soft_dirty(pte))
-					swp_pte = pte_swp_mksoft_dirty(swp_pte);
-				if (pte_swp_uffd(pte))
-					swp_pte = pte_swp_mkuffd(swp_pte);
-			}
-			set_pte_at(mm, addr, ptep, swp_pte);
-
-			/*
-			 * This is like regular unmap: we remove the rmap and
-			 * drop the folio refcount. The folio won't be freed, as
-			 * we took a reference just above.
-			 */
-			folio_remove_rmap_pte(folio, page, vma);
-			folio_put(folio);
-
-			if (pte_present(pte))
-				unmapped++;
-		} else {
-			folio_put(folio);
-			mpfn = 0;
-		}
-
-next:
-		migrate->dst[migrate->npages] = 0;
-		migrate->src[migrate->npages++] = mpfn;
-	}
-
-	/* Only flush the TLB if we actually modified any entries */
-	if (unmapped)
-		flush_tlb_range(walk->vma, start, end);
-
-	lazy_mmu_mode_disable();
-	pte_unmap_unlock(ptep - 1, ptl);
-
-	return 0;
-}
-
-static const struct mm_walk_ops migrate_vma_walk_ops = {
-	.pmd_entry		= migrate_vma_collect_pmd,
-	.pte_hole		= migrate_vma_collect_hole,
-	.walk_lock		= PGWALK_RDLOCK,
-};
-
-/*
- * migrate_vma_collect() - collect pages over a range of virtual addresses
- * @migrate: migrate struct containing all migration information
- *
- * This will walk the CPU page table. For each virtual address backed by a
- * valid page, it updates the src array and takes a reference on the page, in
- * order to pin the page until we lock it and unmap it.
- */
-static void migrate_vma_collect(struct migrate_vma *migrate)
-{
-	struct mmu_notifier_range range;
-
-	/*
-	 * Note that the pgmap_owner is passed to the mmu notifier callback so
-	 * that the registered device driver can skip invalidating device
-	 * private page mappings that won't be migrated.
-	 */
-	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
-		migrate->vma->vm_mm, migrate->start, migrate->end,
-		migrate->pgmap_owner);
-	mmu_notifier_invalidate_range_start(&range);
-
-	walk_page_range_vma(migrate->vma, migrate->start, migrate->end,
-			&migrate_vma_walk_ops, migrate);
-
-	mmu_notifier_invalidate_range_end(&range);
-	migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
-}
-
 /*
  * migrate_vma_check_page() - check if page is pinned or not
  * @page: struct page to check
@@ -533,8 +32,8 @@ static bool migrate_vma_check_page(struct page *page, struct page *fault_page)
 
 	/*
 	 * One extra ref because caller holds an extra reference, either from
-	 * folio_isolate_lru() for a regular folio, or migrate_vma_collect() for
-	 * a device folio.
+	 * folio_isolate_lru() for a regular folio, or the migration collection
+	 * in mm/hmm.c for a device folio.
 	 */
 	int extra = 1 + (page == fault_page);
 
@@ -687,8 +186,12 @@ static void migrate_vma_unmap(struct migrate_vma *migrate)
  * migrate_vma_setup() - prepare to migrate a range of memory
  * @args: contains the vma, start, and pfns arrays for the migration
  *
- * Returns: negative errno on failures, 0 when 0 or more pages were migrated
- * without an error.
+ * Returns: -EINVAL on invalid arguments, -EFAULT for a VM_IO or VM_PFNMAP
+ * vma; with MIGRATE_VMA_FAULT or MIGRATE_VMA_WRITE, the hmm_range_fault()
+ * error (e.g. -EFAULT, -EPERM, -ENOMEM) if a fault fails, or -EINTR if a
+ * fatal signal is pending after a fault; 0 otherwise. A 0 return does not
+ * imply anything was collected; on return @args->cpages holds the number of
+ * pages prepared for migration (possibly 0). See the note on faulting below.
  *
  * Prepare to migrate a range of memory virtual address range by collecting all
  * the pages backing each virtual address in the range, saving them inside the
@@ -698,6 +201,29 @@ static void migrate_vma_unmap(struct migrate_vma *migrate)
  * corresponding src array entry.  Then restores any pages that are pinned, by
  * remapping and unlocking those pages.
  *
+ * By default migrate_vma_setup() is best-effort: virtual addresses that cannot
+ * be collected are left with an empty src[] entry and the rest of the range
+ * still proceeds. Only anonymous memory is collected.
+ *
+ * The optional flags MIGRATE_VMA_FAULT and MIGRATE_VMA_WRITE in @args->flags
+ * additionally fault in missing pages before collecting them, for read and for
+ * write respectively. If such a fault fails, the whole range is aborted: the
+ * partial collection is rolled back, @args->src is cleared, @args->cpages and
+ * @args->npages are reset to 0, and migrate_vma_setup() returns the error.
+ * Pages that just can't be collected (a folio that can't be locked or split,
+ * an entry under another migration) don't abort the range; their src[]
+ * entries stay empty, as without the flags. When faulting,
+ * pages shared with other processes (e.g. after fork) are only collected once
+ * a write fault has given this process its own copy: with MIGRATE_VMA_FAULT
+ * alone they stay in place.
+ *
+ * The faults are those the CPU would take: empty entries of anonymous memory
+ * get system pages, which are then collected and copied, rather than being
+ * left empty for device memory as below. In a vma that isn't anonymous a fault
+ * can have side effects, such as dirtying page cache, while only anonymous
+ * folios are collected. The fault flags can't be combined with
+ * @args->fault_page.
+ *
  * The caller should then allocate destination memory and copy source memory to
  * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
  * flag set).  Once these are allocated and copied, the caller must update each
@@ -712,14 +238,14 @@ static void migrate_vma_unmap(struct migrate_vma *migrate)
  * consequences for the userspace process, so it must be avoided if at all
  * possible.
  *
- * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
- * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
- * allowing the caller to allocate device memory for those unbacked virtual
- * addresses.  For this the caller simply has to allocate device memory and
- * properly set the destination entry like for regular migration.  Note that
- * this can still fail, and thus inside the device driver you must check if the
- * migration was successful for those entries after calling migrate_vma_pages(),
- * just like for regular migration.
+ * For empty entries inside CPU page table (pte_none() or pmd_none() is true),
+ * unless the fault flags fault them in, we do set MIGRATE_PFN_MIGRATE flag
+ * inside the corresponding source array thus allowing the caller to allocate
+ * device memory for those unbacked virtual addresses.  For this the caller
+ * simply has to allocate device memory and properly set the destination entry
+ * like for regular migration.  Note that this can still fail, and thus inside
+ * the device driver you must check if the migration was successful for those
+ * entries after calling migrate_vma_pages(), just like for regular migration.
  *
  * After that, the callers must call migrate_vma_pages() to go over each entry
  * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
@@ -751,14 +277,27 @@ int migrate_vma_setup(struct migrate_vma *args)
 {
 	const struct vm_area_struct *vma = args->vma;
 	long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
+	struct hmm_range range = {
+		.notifier = NULL,
+		.hmm_pfns = args->src,
+		.dev_private_owner = args->pgmap_owner,
+		.migrate = args,
+		.default_flags = HMM_PFN_REQ_MIGRATE
+	};
+	int ret;
 
 	args->start &= PAGE_MASK;
 	args->end &= PAGE_MASK;
+	range.start = args->start;
+	range.end = args->end;
+
 	if (!vma)
 		return -EINVAL;
 	/* The migrate_vma page walk has no hugetlb support. */
 	if (!vma_is_mm_backed(vma) || vma_is_hugetlb(vma) || vma_is_dax(vma))
 		return -EINVAL;
+	if (vma_test_single_mask(vma, VMA_SHADOW_STACK))
+		return -EINVAL;
 	if (nr_pages <= 0)
 		return -EINVAL;
 	if (args->start < vma->vm_start || args->start >= vma->vm_end)
@@ -771,15 +310,37 @@ int migrate_vma_setup(struct migrate_vma *args)
 		return -EINVAL;
 	if (args->fault_page && !PageLocked(args->fault_page))
 		return -EINVAL;
+	/*
+	 * From migrate_to_ram() the fault page is locked by do_swap_page():
+	 * don't start nested faults under it.
+	 */
+	if (args->fault_page &&
+	    (args->flags & (MIGRATE_VMA_FAULT | MIGRATE_VMA_WRITE)))
+		return -EINVAL;
 
 	memset(args->src, 0, sizeof(*args->src) * nr_pages);
 	args->cpages = 0;
 	args->npages = 0;
 
-	migrate_vma_collect(args);
+	if (args->flags & MIGRATE_VMA_FAULT)
+		range.default_flags |= HMM_PFN_REQ_FAULT;
 
-	if (args->cpages)
-		migrate_vma_unmap(args);
+	if (args->flags & MIGRATE_VMA_WRITE)
+		range.default_flags |= HMM_PFN_REQ_FAULT | HMM_PFN_REQ_WRITE;
+
+	ret = hmm_range_fault(&range);
+
+	migrate_hmm_range_setup(&range);
+
+	/* Remove migration PTEs */
+	if (ret) {
+		migrate_vma_pages(args);
+		migrate_vma_finalize(args);
+		memset(args->src, 0, sizeof(*args->src) * nr_pages);
+		args->cpages = 0;
+		args->npages = 0;
+		return ret;
+	}
 
 	/*
 	 * At this point pages are locked and unmapped, and thus they have
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 10/14] lib/test_hmm: add a new testcase for the migrate on fault
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (8 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 09/14] mm: enable device page migration from " mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 11/14] Documentation/mm/hmm: document migration through hmm_range_fault() mpenttil
                   ` (3 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan, Marco Pagani

From: Mika Penttilä <mpenttil@redhat.com>

Enhance the hmm test driver (lib/test_hmm) with a migrate on fault
case: a single hmm_range_fault() walk with HMM_PFN_REQ_FAULT |
HMM_PFN_REQ_MIGRATE faults in and collects the range, which is then
migrated to device private memory and mapped into the dmirror page
table. The selftest leaves the first two pages unwritten, so page 0
has to be faulted in and page 1 maps the zero page.

If mmu_interval_read_retry() trips after migrate_vma_pages(), the
dmirror mapping is skipped and the -EBUSY retry re-walks. Normally the
trip comes from an unmap or zap: the migration ptes are gone,
migrate_vma_finalize() releases the destination pages and the retry
migrates again. Pages committed to device memory without a dmirror
mapping (e.g. after a huge zero pmd split in migrate_vma_insert_page())
are still consistent: that path drops the dmirror page table entries of
the range, which our own MIGRATE invalidation doesn't clear, so no entry
an earlier read stored can point at a freed source page, and a real
device would map them on its next fault. The selftest doesn't hit that
case: the unwritten pages share a pmd with written ones, so there is no
huge zero pmd.

The verification read faults such pages in, as dmirror_read() does. For
that, dmirror_do_fault() now maps the backing page of the device's own
device private pages, as __dmirror_migrate_map_locked() does. It used to
store the device private page itself, which has no memory behind it, so
dmirror_do_read() and dmirror_do_write() would access a pfn without RAM.
Like the rest of the dmirror page table handling this relies on the
dmirror's own invalidations, which skip this device's MIGRATE
invalidations, so a concurrent CPU fault migrating the page back, or a
second dmirror of the range, can leave a stale entry, as
HMM_DMIRROR_MIGRATE_TO_SYS already can; the selftests do neither.

Cc: David Hildenbrand <david@kernel.org>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Leon Romanovsky <leonro@nvidia.com>
Cc: Alistair Popple <apopple@nvidia.com>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Zi Yan <ziy@nvidia.com>
Cc: Matthew Brost <matthew.brost@intel.com>
Co-developed-by: Marco Pagani <marpagan@redhat.com>
Signed-off-by: Marco Pagani <marpagan@redhat.com>
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 lib/test_hmm.c                         | 215 +++++++++++++++++++++++--
 lib/test_hmm_uapi.h                    |  21 +--
 tools/testing/selftests/mm/hmm-tests.c |  73 +++++++++
 3 files changed, 289 insertions(+), 20 deletions(-)

diff --git a/lib/test_hmm.c b/lib/test_hmm.c
index 63226caea5da..7b07f595273f 100644
--- a/lib/test_hmm.c
+++ b/lib/test_hmm.c
@@ -36,6 +36,7 @@
 #define DMIRROR_RANGE_FAULT_TIMEOUT	1000
 #define DEVMEM_CHUNK_SIZE		(256 * 1024 * 1024U)
 #define DEVMEM_CHUNKS_RESERVE		16
+#define PFNS_ARRAY_SIZE			64
 
 /*
  * For device_private pages, dpage is just a dummy struct page
@@ -290,6 +291,23 @@ static int dmirror_do_fault(struct dmirror *dmirror, struct hmm_range *range)
 		page = hmm_pfn_to_page(*pfns);
 		WARN_ON(!page);
 
+		/*
+		 * Device private pages are backed by system pages: map those.
+		 * Like the rest of the dmirror page table handling, this relies
+		 * on the dmirror's own invalidations, and MIGRATE invalidations
+		 * of this device are skipped. A CPU fault migrating the page
+		 * back concurrently, or a second dmirror of the same range, can
+		 * therefore leave a stale entry, as HMM_DMIRROR_MIGRATE_TO_SYS
+		 * already can. The selftests do neither.
+		 */
+		if (is_device_private_page(page)) {
+			struct folio *folio = page_folio(page);
+			struct page *rpage = BACKING_PAGE(folio_page(folio, 0));
+
+			page = folio_page(page_folio(rpage),
+					  folio_page_idx(folio, page));
+		}
+
 		entry = page;
 		if (*pfns & HMM_PFN_WRITE)
 			entry = xa_tag_pointer(entry, DPT_XA_TAG_WRITE);
@@ -355,15 +373,29 @@ static int dmirror_range_fault(struct dmirror *dmirror,
 	struct mm_struct *mm = dmirror->notifier.mm;
 	unsigned long timeout =
 		jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
+	bool migrate = range->default_flags & HMM_PFN_REQ_MIGRATE;
 	int ret;
 
 	while (true) {
-		if (time_after(jiffies, timeout)) {
+		/*
+		 * A migrating call returns below after one walk; its caller,
+		 * do_fault_and_migrate(), has its own retry loop and timeout.
+		 */
+		if (!migrate && time_after(jiffies, timeout)) {
 			ret = -EBUSY;
 			goto out;
 		}
 
 		range->notifier_seq = mmu_interval_read_begin(range->notifier);
+
+		/*
+		 * mmap lock held for whole migrate on fault operation. A
+		 * migrating call isn't retried here: the caller aborts the
+		 * partial migration first.
+		 */
+		if (migrate)
+			return hmm_range_fault(range);
+
 		mmap_read_lock(mm);
 		ret = hmm_range_fault(range);
 		mmap_read_unlock(mm);
@@ -994,8 +1026,12 @@ static int dmirror_atomic_map(unsigned long addr, struct page *page,
 	return 0;
 }
 
-static int dmirror_migrate_finalize_and_map(struct migrate_vma *args,
-					    struct dmirror *dmirror)
+/*
+ * Map the migrated pages into the device's page table. Caller must hold
+ * dmirror->mutex.
+ */
+static int __dmirror_migrate_map_locked(struct migrate_vma *args,
+					struct dmirror *dmirror)
 {
 	unsigned long start = args->start;
 	unsigned long end = args->end;
@@ -1005,9 +1041,6 @@ static int dmirror_migrate_finalize_and_map(struct migrate_vma *args,
 	const unsigned long start_pfn = start >> PAGE_SHIFT;
 	const unsigned long end_pfn = end >> PAGE_SHIFT;
 
-	/* Map the migrated pages into the device's page tables. */
-	mutex_lock(&dmirror->mutex);
-
 	for (pfn = start_pfn; pfn < end_pfn; pfn++, src++, dst++) {
 		struct page *dpage;
 		void *entry;
@@ -1036,17 +1069,27 @@ static int dmirror_migrate_finalize_and_map(struct migrate_vma *args,
 			if (*dst & MIGRATE_PFN_WRITE)
 				entry = xa_tag_pointer(entry, DPT_XA_TAG_WRITE);
 			entry = xa_store(&dmirror->pt, pfn + i, entry, GFP_ATOMIC);
-			if (xa_is_err(entry)) {
-				mutex_unlock(&dmirror->mutex);
+			if (xa_is_err(entry))
 				return xa_err(entry);
-			}
 		}
 	}
 
-	mutex_unlock(&dmirror->mutex);
 	return 0;
 }
 
+static int dmirror_migrate_finalize_and_map(struct migrate_vma *args,
+					    struct dmirror *dmirror)
+{
+	int ret;
+
+	/* Map the migrated pages into the device's page tables. */
+	mutex_lock(&dmirror->mutex);
+	ret = __dmirror_migrate_map_locked(args, dmirror);
+	mutex_unlock(&dmirror->mutex);
+
+	return ret;
+}
+
 static int dmirror_exclusive(struct dmirror *dmirror,
 			     struct hmm_dmirror_cmd *cmd)
 {
@@ -1379,6 +1422,154 @@ static int dmirror_migrate_to_device(struct dmirror *dmirror,
 	return ret;
 }
 
+static int do_fault_and_migrate(struct dmirror *dmirror, struct hmm_range *range)
+{
+	struct migrate_vma *migrate = range->migrate;
+	unsigned long timeout =
+		jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
+	int ret;
+
+	do {
+		mmap_read_lock(dmirror->notifier.mm);
+
+		/* Fault-in pages for migration */
+		ret = dmirror_range_fault(dmirror, range);
+		/*
+		 * Set this up even on error: hmm_range_fault() may have collected
+		 * part of the range before failing.
+		 */
+		migrate_hmm_range_setup(range);
+		if (ret) {
+			/*
+			 * dst[] entries are empty, so this marks every collected
+			 * migration as failed. finalize then restores the source
+			 * mappings and drops the associated locks/references.
+			 */
+			migrate_vma_pages(migrate);
+			migrate_vma_finalize(migrate);
+			goto unlock;
+		}
+
+		pr_debug("Migrating from sys mem to device mem\n");
+
+		dmirror_migrate_alloc_and_copy(migrate, dmirror);
+		migrate_vma_pages(migrate);
+
+		mutex_lock(&dmirror->mutex);
+		if (mmu_interval_read_retry(&dmirror->notifier,
+					    range->notifier_seq)) {
+			/*
+			 * The migration may already be committed, and our own
+			 * MIGRATE invalidation didn't clear the dmirror page
+			 * table: drop entries an earlier read left pointing at
+			 * the source pages that finalize may free.
+			 */
+			dmirror_do_update(dmirror, range->start, range->end);
+			ret = -EBUSY;
+		} else {
+			ret = __dmirror_migrate_map_locked(migrate, dmirror);
+		}
+		mutex_unlock(&dmirror->mutex);
+
+		migrate_vma_finalize(migrate);
+unlock:
+		mmap_read_unlock(dmirror->notifier.mm);
+	} while (ret == -EBUSY && !time_after(jiffies, timeout));
+
+	return ret;
+}
+
+static int dmirror_fault_and_migrate_to_device(struct dmirror *dmirror,
+					       struct hmm_dmirror_cmd *cmd)
+{
+	unsigned long start, size, end, next;
+	unsigned long *src_pfns, *dst_pfns;
+	struct migrate_vma migrate = { 0 };
+	struct hmm_range range = { 0 };
+	struct dmirror_bounce bounce;
+	int ret = 0;
+
+	/* Whole range */
+	start = cmd->addr;
+	size = cmd->npages << PAGE_SHIFT;
+	end = start + size;
+	if (end < start)
+		return -EINVAL;
+
+	if (!mmget_not_zero(dmirror->notifier.mm)) {
+		ret = -EINVAL;
+		goto out;
+	}
+
+	src_pfns = kvzalloc_objs(*src_pfns, PFNS_ARRAY_SIZE,
+				 GFP_KERNEL | __GFP_NOFAIL);
+	dst_pfns = kvzalloc_objs(*dst_pfns, PFNS_ARRAY_SIZE,
+				 GFP_KERNEL | __GFP_NOFAIL);
+
+	migrate.pgmap_owner = dmirror->mdevice;
+	migrate.src = src_pfns;
+	migrate.dst = dst_pfns;
+	migrate.flags = MIGRATE_VMA_SELECT_SYSTEM;
+
+	range.migrate = &migrate;
+	range.hmm_pfns = src_pfns;
+	range.pfn_flags_mask = 0;
+	range.default_flags = HMM_PFN_REQ_FAULT | HMM_PFN_REQ_MIGRATE;
+	range.dev_private_owner = dmirror->mdevice;
+	range.notifier = &dmirror->notifier;
+
+	for (next = start; next < end; next = range.end) {
+		range.start = next;
+		range.end = min(end, next + (PFNS_ARRAY_SIZE << PAGE_SHIFT));
+
+		pr_debug("Fault and migrate range start:%#lx end:%#lx\n",
+			 range.start, range.end);
+
+		ret = do_fault_and_migrate(dmirror, &range);
+		if (ret)
+			goto out_mmput;
+	}
+
+	/*
+	 * Return the migrated data for verification.
+	 * Only for pages in device zone
+	 */
+	ret = dmirror_bounce_init(&bounce, start, size);
+	if (ret)
+		goto out_mmput;
+
+	next = start;
+	while (1) {
+		mutex_lock(&dmirror->mutex);
+		ret = dmirror_do_read(dmirror, next, end, &bounce);
+		mutex_unlock(&dmirror->mutex);
+		if (ret != -ENOENT)
+			break;
+
+		/*
+		 * Committed to device memory but not mapped after a read_retry
+		 * trip in do_fault_and_migrate(): fault it in, as a device would.
+		 */
+		next = start + (bounce.cpages << PAGE_SHIFT);
+		ret = dmirror_fault(dmirror, next, end, false);
+		if (ret)
+			break;
+	}
+	if (ret == 0 &&
+	    copy_to_user(u64_to_user_ptr(cmd->ptr), bounce.ptr, bounce.size))
+		ret = -EFAULT;
+
+	cmd->cpages = bounce.cpages;
+	dmirror_bounce_fini(&bounce);
+
+out_mmput:
+	kvfree(src_pfns);
+	kvfree(dst_pfns);
+	mmput(dmirror->notifier.mm);
+out:
+	return ret;
+}
+
 static void dmirror_mkentry(struct dmirror *dmirror, struct hmm_range *range,
 			    unsigned char *perm, unsigned long entry)
 {
@@ -1647,6 +1838,10 @@ static long dmirror_fops_unlocked_ioctl(struct file *filp,
 		ret = dmirror_migrate_to_device(dmirror, &cmd);
 		break;
 
+	case HMM_DMIRROR_MIGRATE_ON_FAULT_TO_DEV:
+		ret = dmirror_fault_and_migrate_to_device(dmirror, &cmd);
+		break;
+
 	case HMM_DMIRROR_MIGRATE_TO_SYS:
 		ret = dmirror_migrate_to_system(dmirror, &cmd);
 		break;
diff --git a/lib/test_hmm_uapi.h b/lib/test_hmm_uapi.h
index ea9b0ec404fb..67d267a3b999 100644
--- a/lib/test_hmm_uapi.h
+++ b/lib/test_hmm_uapi.h
@@ -29,16 +29,17 @@ struct hmm_dmirror_cmd {
 };
 
 /* Expose the address space of the calling process through hmm device file */
-#define HMM_DMIRROR_READ		_IOWR('H', 0x00, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_WRITE		_IOWR('H', 0x01, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_MIGRATE_TO_DEV	_IOWR('H', 0x02, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_MIGRATE_TO_SYS	_IOWR('H', 0x03, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_SNAPSHOT		_IOWR('H', 0x04, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_EXCLUSIVE		_IOWR('H', 0x05, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_CHECK_EXCLUSIVE	_IOWR('H', 0x06, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_RELEASE		_IOWR('H', 0x07, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_FLAGS		_IOWR('H', 0x08, struct hmm_dmirror_cmd)
-#define HMM_DMIRROR_READ_UNLOCKED	_IOWR('H', 0x09, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_READ			_IOWR('H', 0x00, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_WRITE			_IOWR('H', 0x01, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_MIGRATE_TO_DEV		_IOWR('H', 0x02, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_MIGRATE_TO_SYS		_IOWR('H', 0x03, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_SNAPSHOT			_IOWR('H', 0x04, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_EXCLUSIVE			_IOWR('H', 0x05, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_CHECK_EXCLUSIVE		_IOWR('H', 0x06, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_RELEASE			_IOWR('H', 0x07, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_FLAGS			_IOWR('H', 0x08, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_READ_UNLOCKED		_IOWR('H', 0x09, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_MIGRATE_ON_FAULT_TO_DEV	_IOWR('H', 0x0a, struct hmm_dmirror_cmd)
 
 #define HMM_DMIRROR_FLAG_FAIL_ALLOC	(1ULL << 0)
 
diff --git a/tools/testing/selftests/mm/hmm-tests.c b/tools/testing/selftests/mm/hmm-tests.c
index e5f273ca84c1..1d7a51bb55cd 100644
--- a/tools/testing/selftests/mm/hmm-tests.c
+++ b/tools/testing/selftests/mm/hmm-tests.c
@@ -333,6 +333,13 @@ static int hmm_migrate_sys_to_dev(int fd,
 	return hmm_dmirror_cmd(fd, HMM_DMIRROR_MIGRATE_TO_DEV, buffer, npages);
 }
 
+static int hmm_migrate_on_fault_sys_to_dev(int fd,
+					   struct hmm_buffer *buffer,
+					   unsigned long npages)
+{
+	return hmm_dmirror_cmd(fd, HMM_DMIRROR_MIGRATE_ON_FAULT_TO_DEV, buffer, npages);
+}
+
 static int hmm_migrate_dev_to_sys(int fd,
 				   struct hmm_buffer *buffer,
 				   unsigned long npages)
@@ -937,6 +944,72 @@ TEST_F(hmm, migrate)
 	hmm_buffer_free(buffer);
 }
 
+
+/*
+ * Fault and migrate anonymous memory to device private memory.
+ */
+TEST_F(hmm, migrate_on_fault)
+{
+	struct hmm_buffer *buffer;
+	unsigned long npages;
+	unsigned long size;
+	unsigned long i;
+	unsigned char *m;
+	unsigned char prot;
+	int *ptr;
+	int ret;
+	int val;
+
+	npages = ALIGN(HMM_BUFFER_SIZE, self->page_size) >> self->page_shift;
+	ASSERT_NE(npages, 0);
+	size = npages << self->page_shift;
+
+	buffer = hmm_buffer_alloc(size, size,
+				  PROT_READ | PROT_WRITE,
+				  MAP_PRIVATE | MAP_ANONYMOUS, -1);
+	ASSERT_NE(buffer, NULL);
+
+	/* No THP, which would populate the first two pages too */
+	ret = madvise(buffer->ptr, size, MADV_NOHUGEPAGE);
+	ASSERT_EQ(ret, 0);
+
+	/*
+	 * Initialize buffer in system memory but leave the first two pages
+	 * zero: page 0 stays pte_none so that hmm_range_fault() has to fault
+	 * it in, page 1 is mapped to the zero page.
+	 */
+	i = 2 * self->page_size / sizeof(*ptr);
+	for (ptr = buffer->ptr; i < size / sizeof(*ptr); ++i)
+		ptr[i] = i;
+
+	val = *(int *)(buffer->ptr + self->page_size);
+	ASSERT_EQ(val, 0);
+
+	/* Fault and migrate memory to device. */
+	ret = hmm_migrate_on_fault_sys_to_dev(self->fd, buffer, npages);
+	ASSERT_EQ(ret, 0);
+	ASSERT_EQ(buffer->cpages, npages);
+
+	/* Check what the device read. */
+	for (i = 0, ptr = buffer->mirror; i < 2 * self->page_size / sizeof(*ptr); ++i)
+		ASSERT_EQ(ptr[i], 0);
+	for (; i < size / sizeof(*ptr); ++i)
+		ASSERT_EQ(ptr[i], i);
+
+	/* Check the pages were migrated to this device, not just read. */
+	ret = hmm_dmirror_cmd(self->fd, HMM_DMIRROR_SNAPSHOT, buffer, npages);
+	ASSERT_EQ(ret, 0);
+	ASSERT_EQ(buffer->cpages, npages);
+	prot = hmm_is_coherent_type(variant->device_number) ?
+	       HMM_DMIRROR_PROT_DEV_COHERENT_LOCAL :
+	       HMM_DMIRROR_PROT_DEV_PRIVATE_LOCAL;
+	m = buffer->mirror;
+	for (i = 0; i < npages; ++i)
+		ASSERT_EQ(m[i] & 0xF0, prot);
+
+	hmm_buffer_free(buffer);
+}
+
 /*
  * Migrate private file memory to device private memory.
  */
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 11/14] Documentation/mm/hmm: document migration through hmm_range_fault()
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (9 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 10/14] lib/test_hmm: add a new testcase for the migrate on fault mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 12/14] drm/nouveau/dmem: serialize the copy channel users mpenttil
                   ` (2 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

With this series migrate_vma_setup() collects through the
hmm_range_fault() page table walk, and drivers can collect directly
from hmm_range_fault() for migrate on fault. Update hmm.rst to match:

Describe the two new MIGRATE_VMA_FAULT / MIGRATE_VMA_WRITE flags of
migrate_vma_setup(), what is collected without them, and that a failed
fault aborts the whole range.

Correct the lock_page() wording: collection only trylocks the pages,
and a page that can't be locked is not migrated. Note that
migrate_vma_setup() now uses the hmm_range_fault() walk.

Add a section on driving the migration collection phase directly from
hmm_range_fault() via HMM_PFN_REQ_MIGRATE and migrate_hmm_range_setup():
the range and notifier requirements, how collected entries and holes are
marked, rollback, the mmu_interval_read_retry() duty, best effort
collection (shared pages aren't collected when faulting), the rule not
to hold locks across the call that the driver takes again before
finalizing, and the abort contract.

Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 Documentation/mm/hmm.rst | 123 ++++++++++++++++++++++++++++++++++++++-
 1 file changed, 121 insertions(+), 2 deletions(-)

diff --git a/Documentation/mm/hmm.rst b/Documentation/mm/hmm.rst
index fc1b8dc19825..1ba7086ca888 100644
--- a/Documentation/mm/hmm.rst
+++ b/Documentation/mm/hmm.rst
@@ -348,6 +348,33 @@ between device driver specific code and shared common code:
    Currently only anonymous private VMA ranges can be migrated to or from
    system memory and device private memory.
 
+   By default nothing is faulted in: present pages are collected, empty
+   entries of anonymous vmas are collected as holes to be filled with new
+   pages, and pages that are not present (swapped out, or another device's
+   private pages) are skipped. Two additional flags ask migrate_vma_setup()
+   to fault in such pages first:
+
+   * ``MIGRATE_VMA_FAULT`` faults in missing pages with read access.
+   * ``MIGRATE_VMA_WRITE`` faults in missing pages with write access
+     (implies faulting), breaking any sharing first, so the device gets an
+     exclusive writable copy.
+
+   When faulting, pages shared with other processes (e.g. after fork) are
+   only collected once a write fault has given this process its own copy:
+   with ``MIGRATE_VMA_FAULT`` alone they stay in place. Device private pages
+   owned by ``args->pgmap_owner`` are never faulted, so a write fault doesn't
+   unshare them either. The faults are those the CPU would take, so empty
+   anonymous entries get system pages that are then copied, instead of being
+   collected as holes.
+
+   With either flag, a fault that fails aborts the whole range: the partial
+   collection is undone, ``args->src`` is cleared, ``args->cpages`` and
+   ``args->npages`` are zero, and migrate_vma_setup() returns the error
+   (for example ``-EFAULT`` or ``-ENOMEM``). Pages that just can't be
+   collected don't abort the range. The ``MMU_NOTIFY_MIGRATE`` invalidation
+   described below is then ended around each fault and reopened over the
+   rest of the range.
+
    One of the first steps migrate_vma_setup() does is to invalidate other
    device's MMUs with the ``mmu_notifier_invalidate_range_start()`` and
    ``mmu_notifier_invalidate_range_end()`` calls around the page table
@@ -364,11 +391,14 @@ between device driver specific code and shared common code:
    entry results in a valid "zero" PFN stored in the ``args->src`` array.
    This lets the driver allocate device private memory and clear it instead
    of copying a page of zeros. Valid PTE entries to system memory or
-   device private struct pages will be locked with ``lock_page()``, isolated
+   device private struct pages will be locked (only trylocked: a page that
+   can't be locked is not migrated), isolated
    from the LRU (if system memory since device private pages are not on
    the LRU), unmapped from the process, and a special migration PTE is
    inserted in place of the original PTE.
-   migrate_vma_setup() also clears the ``args->dst`` array.
+   migrate_vma_setup() also clears the ``args->dst`` array. It does all of
+   this through the hmm_range_fault() page table walk, see "Migration
+   collection through hmm_range_fault()" below.
 
 3. The device driver allocates destination pages and copies source pages to
    destination pages.
@@ -427,6 +457,95 @@ between device driver specific code and shared common code:
 
    The lock can now be released.
 
+Migration collection through hmm_range_fault()
+==============================================
+
+The collection phase of migration (steps 1 and 2 above) can also be driven by
+hmm_range_fault() directly, sharing its page table walk. This lets a driver
+fault in and collect a range for migration in one walk, which is useful for
+migrate on fault.
+
+To do so, the driver sets ``HMM_PFN_REQ_MIGRATE`` in ``range->default_flags``
+and points ``range->migrate`` at a ``struct migrate_vma`` it has filled in
+(``flags``, ``src``, ``dst``, ``pgmap_owner``; ``src``, ``dst`` and
+``range->hmm_pfns`` have one entry per page of the range). ``range->notifier``
+must be set and ``range->notifier_seq`` must come from
+mmu_interval_read_begin(); hmm_range_fault() fills in ``migrate->vma``,
+``start`` and ``end``. ``migrate->flags`` needs at least one
+``MIGRATE_VMA_SELECT_*`` bit. The range must lie within a single vma, otherwise
+``-ERANGE`` is returned (``-EFAULT`` if it starts in a hole); vmas
+migrate_vma_setup() doesn't handle (not mm backed, hugetlb, DAX, shadow stack)
+get ``-EINVAL``.
+
+The mmap_read_lock() has to be held for the whole migration, since the vma
+must stay stable. hmm_range_fault_unlocked_timeout() can't be used: it fails
+without collecting anything (don't call migrate_hmm_range_setup() after it).
+
+Usually ``HMM_PFN_REQ_FAULT`` (and ``HMM_PFN_REQ_WRITE``) is set as well, so
+missing pages are faulted in before being collected. ``MIGRATE_VMA_FAULT`` and
+``MIGRATE_VMA_WRITE`` in ``migrate->flags`` have no effect here: only
+migrate_vma_setup() reads them.
+
+Migration requests come only from ``range->default_flags``:
+``range->pfn_flags_mask`` must be 0 and ``range->dev_private_owner`` must
+equal ``migrate->pgmap_owner``. ``range->hmm_pfns`` is cleared at the start of
+hmm_range_fault(), so per-pfn input, including ``HMM_PFN_INOUT_FLAGS`` such as
+``HMM_PFN_DMA_MAPPED``, is not preserved across a migrating call.
+
+hmm_range_fault() collects the entries the same way migrate_vma_setup() does,
+taking a folio reference, locking it and installing a migration PTE. Collected
+pages are marked with ``HMM_PFN_VALID | HMM_PFN_MIGRATE`` in
+``range->hmm_pfns``. When a large folio is collected whole, only its first
+entry is marked, with ``HMM_PFN_COMPOUND`` added, and the following entries are
+0, as with ``MIGRATE_PFN_COMPOUND`` in ``migrate->src``. An entry with
+``HMM_PFN_MIGRATE`` but without ``HMM_PFN_VALID`` is a collected hole (empty or
+zero page) that the driver may fill with a new page. If the page tables change
+while locks are dropped, entries collected earlier are rolled back when the
+walk visits them again; entries it doesn't revisit stay collected and are
+released by migrate_vma_pages() and migrate_vma_finalize().
+
+The ``MMU_NOTIFY_MIGRATE`` invalidation covering the collected range is ended
+while hmm_range_fault() faults pages in. As with any hmm_range_fault() use, the
+driver must check mmu_interval_read_retry() under its own lock before mapping
+the destination pages on the device, and abort the migration if it reports a
+change.
+
+Collection is best effort when migrating: a folio that can't be locked is left
+as reported, and if a large folio can't be locked for splitting or can't be
+split, the rest of its pmd range is not walked further (not faulted or
+collected), as migrate_vma_setup() does, even with ``HMM_PFN_REQ_FAULT``.
+Entries under another migration are left 0, since waiting for them while
+holding collected folios could deadlock. For the same reason, when faulting,
+only pages mapped by this process alone are collected: a page shared with other
+processes (after fork, or KSM) is left as reported. A write fault gives this
+process its own copy first, so this only leaves shared pages in place for read
+faults. That is the price of faulting in the same walk. Drivers check
+``HMM_PFN_MIGRATE`` (and ``HMM_PFN_VALID``, see above) per entry.
+
+Faults by other tasks on collected pages wait until the migration is finalized.
+The driver must therefore not hold locks across a migrating hmm_range_fault()
+call that it takes again before migrate_vma_finalize().
+
+After hmm_range_fault() returns, the driver calls::
+
+    void migrate_hmm_range_setup(struct hmm_range *range);
+
+to translate ``range->hmm_pfns`` into ``migrate->src[]`` (``migrate->dst[]`` is
+zeroed), initialize ``migrate->cpages`` and ``migrate->npages``, and unmap the
+collected pages as migrate_vma_setup() does (migrate_vma_unmap()). From here on
+the ``range->migrate`` struct is ready for the rest of the flow (steps 3
+onwards): the driver either completes the migration or aborts it as below,
+and either way calls migrate_vma_pages() and migrate_vma_finalize().
+
+migrate_hmm_range_setup() must be called even when hmm_range_fault() fails,
+since it may have collected part of the range before failing. On any error,
+including ``-EBUSY``, the driver then aborts the partial migration: it skips
+step 3, so ``migrate->dst[]`` stays zeroed, and calls migrate_vma_pages() and
+migrate_vma_finalize(), which restore the original PTEs and release the
+collected folios. A migrating call does not resume a previous attempt, so
+the previous one, completed or aborted, must be finished before calling
+hmm_range_fault() again.
+
 Exclusive access memory
 =======================
 
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 12/14] drm/nouveau/dmem: serialize the copy channel users
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (10 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 11/14] Documentation/mm/hmm: document migration through hmm_range_fault() mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 13/14] drm/nouveau/dmem: commit migrate_to_ram() only after the copy is confirmed mpenttil
  2026-12-01  4:55 ` [PATCH v18 14/14] drm/nouveau/svm: add support for migrate on fault mpenttil
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

The dmem users of the migration copy channel (CPU faults in
migrate_to_ram(), bulk migration and chunk eviction) write copy and
clear commands to its push buffer and emit fences without any
serialization, so concurrent users can interleave their pushes.

Add drm->dmem->migrate.lock and the wrappers nouveau_dmem_copy(),
nouveau_dmem_clear() and nouveau_dmem_fence_new(), which take it only
around the pushes and the fence emit. It is never held across memory
allocation: migrate_to_ram() copies under svmm->mutex, and reclaim can
take svmm->mutex through the mmu notifier, so the fence is allocated
before taking the lock.

The channel is shared with TTM, which serializes its own use with
cli->mutex. dmem and TTM stay unserialized against each other, as
before: dmem can't take cli->mutex, since TTM allocates memory under it.

Fixes: 5be73b690875 ("drm/nouveau/dmem: device memory helpers for SVM")
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 drivers/gpu/drm/nouveau/nouveau_dmem.c | 81 ++++++++++++++++++++++----
 1 file changed, 71 insertions(+), 10 deletions(-)

diff --git a/drivers/gpu/drm/nouveau/nouveau_dmem.c b/drivers/gpu/drm/nouveau/nouveau_dmem.c
index eacac8055834..6824f5401d00 100644
--- a/drivers/gpu/drm/nouveau/nouveau_dmem.c
+++ b/drivers/gpu/drm/nouveau/nouveau_dmem.c
@@ -76,6 +76,22 @@ struct nouveau_dmem_migrate {
 	nouveau_migrate_copy_t copy_func;
 	nouveau_clear_page_t clear_func;
 	struct nouveau_channel *chan;
+	/*
+	 * Serializes the dmem users of chan (CPU faults in migrate_to_ram(),
+	 * bulk migration, eviction): the copy and clear
+	 * commands they write to its push buffer and the fences they emit.
+	 * Held only around those writes, never across memory allocation
+	 * (fences are allocated before taking it).
+	 *
+	 * chan is shared with TTM (drm->ttm.chan), which serializes its own
+	 * use with cli->mutex instead. dmem and TTM are therefore not
+	 * serialized against each other, as before this lock was added.
+	 * dmem can't take cli->mutex: dmem copies run under svmm->mutex,
+	 * while TTM may allocate memory under cli->mutex, and an allocation
+	 * can enter reclaim, whose mmu notifier invalidation takes
+	 * svmm->mutex.
+	 */
+	struct mutex lock;
 };
 
 struct nouveau_dmem {
@@ -93,6 +109,51 @@ struct nouveau_dmem_dma_info {
 	size_t size;
 };
 
+static int nouveau_dmem_copy(struct nouveau_drm *drm, u64 npages,
+			     enum nouveau_aper dst_aper, u64 dst_addr,
+			     enum nouveau_aper src_aper, u64 src_addr)
+{
+	int ret;
+
+	mutex_lock(&drm->dmem->migrate.lock);
+	ret = drm->dmem->migrate.copy_func(drm, npages, dst_aper, dst_addr,
+					   src_aper, src_addr);
+	mutex_unlock(&drm->dmem->migrate.lock);
+	return ret;
+}
+
+static int nouveau_dmem_clear(struct nouveau_drm *drm, u32 length,
+			      enum nouveau_aper dst_aper, u64 dst_addr)
+{
+	int ret;
+
+	mutex_lock(&drm->dmem->migrate.lock);
+	ret = drm->dmem->migrate.clear_func(drm, length, dst_aper, dst_addr);
+	mutex_unlock(&drm->dmem->migrate.lock);
+	return ret;
+}
+
+static int nouveau_dmem_fence_new(struct nouveau_drm *drm,
+				  struct nouveau_fence **fence)
+{
+	int ret;
+
+	/*
+	 * nouveau_fence_new() without the allocation under migrate.lock:
+	 * the fence is allocated first, the lock only covers the emit.
+	 */
+	ret = nouveau_fence_create(fence, drm->dmem->migrate.chan);
+	if (ret)
+		return ret;
+
+	mutex_lock(&drm->dmem->migrate.lock);
+	ret = nouveau_fence_emit(*fence);
+	mutex_unlock(&drm->dmem->migrate.lock);
+	if (ret)
+		nouveau_fence_unref(fence);
+	return ret;
+}
+
 static struct nouveau_dmem_chunk *nouveau_page_to_chunk(struct page *page)
 {
 	return container_of(page_pgmap(page), struct nouveau_dmem_chunk,
@@ -168,10 +229,10 @@ static int nouveau_dmem_copy_folio(struct nouveau_drm *drm,
 	if (dma_mapping_error(dev, dma_info->dma_addr))
 		return -EIO;
 
-	if (drm->dmem->migrate.copy_func(drm, folio_nr_pages(sfolio),
-					 NOUVEAU_APER_HOST, dma_info->dma_addr,
-					 NOUVEAU_APER_VRAM,
-					 nouveau_dmem_page_addr(spage))) {
+	if (nouveau_dmem_copy(drm, folio_nr_pages(sfolio),
+			      NOUVEAU_APER_HOST, dma_info->dma_addr,
+			      NOUVEAU_APER_VRAM,
+			      nouveau_dmem_page_addr(spage))) {
 		dma_unmap_page(dev, dma_info->dma_addr, page_size(dpage),
 					DMA_BIDIRECTIONAL);
 		return -EIO;
@@ -183,7 +244,6 @@ static int nouveau_dmem_copy_folio(struct nouveau_drm *drm,
 static vm_fault_t nouveau_dmem_migrate_to_ram(struct vm_fault *vmf)
 {
 	struct nouveau_drm *drm = page_to_drm(vmf->page);
-	struct nouveau_dmem *dmem = drm->dmem;
 	struct nouveau_fence *fence;
 	struct nouveau_svmm *svmm;
 	struct page *dpage;
@@ -264,7 +324,7 @@ static vm_fault_t nouveau_dmem_migrate_to_ram(struct vm_fault *vmf)
 		goto done;
 	}
 
-	nouveau_fence_new(&fence, dmem->migrate.chan);
+	nouveau_dmem_fence_new(drm, &fence);
 	migrate_vma_pages(&args);
 	nouveau_dmem_fence_done(&fence);
 	dma_unmap_page(drm->dev->dev, dma_info.dma_addr, dma_info.size,
@@ -528,7 +588,7 @@ nouveau_dmem_evict_chunk(struct nouveau_dmem_chunk *chunk)
 		}
 	}
 
-	nouveau_fence_new(&fence, chunk->drm->dmem->migrate.chan);
+	nouveau_dmem_fence_new(chunk->drm, &fence);
 	migrate_device_pages(src_pfns, dst_pfns, npages);
 	nouveau_dmem_fence_done(&fence);
 	migrate_device_finalize(src_pfns, dst_pfns, npages);
@@ -729,6 +789,7 @@ nouveau_dmem_init(struct nouveau_drm *drm)
 	INIT_LIST_HEAD(&drm->dmem->chunks);
 	mutex_init(&drm->dmem->mutex);
 	spin_lock_init(&drm->dmem->lock);
+	mutex_init(&drm->dmem->migrate.lock);
 
 	/* Initialize migration dma helpers before registering memory */
 	ret = nouveau_dmem_migrate_init(drm);
@@ -764,13 +825,13 @@ static unsigned long nouveau_dmem_migrate_copy_one(struct nouveau_drm *drm,
 		dma_info->size = page_size(spage);
 		if (dma_mapping_error(dev, dma_info->dma_addr))
 			goto out_free_page;
-		if (drm->dmem->migrate.copy_func(drm, folio_nr_pages(page_folio(spage)),
+		if (nouveau_dmem_copy(drm, folio_nr_pages(page_folio(spage)),
 			NOUVEAU_APER_VRAM, paddr, NOUVEAU_APER_HOST,
 			dma_info->dma_addr))
 			goto out_dma_unmap;
 	} else {
 		dma_info->dma_addr = DMA_MAPPING_ERROR;
-		if (drm->dmem->migrate.clear_func(drm, page_size(dpage),
+		if (nouveau_dmem_clear(drm, page_size(dpage),
 			NOUVEAU_APER_VRAM, paddr))
 			goto out_free_page;
 	}
@@ -820,7 +881,7 @@ static void nouveau_dmem_migrate_chunk(struct nouveau_drm *drm,
 		addr += (1 << order) * PAGE_SIZE;
 	}
 
-	nouveau_fence_new(&fence, drm->dmem->migrate.chan);
+	nouveau_dmem_fence_new(drm, &fence);
 	migrate_vma_pages(args);
 	nouveau_dmem_fence_done(&fence);
 	nouveau_pfns_map(svmm, args->vma->vm_mm, args->start, pfns, i, order);
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 13/14] drm/nouveau/dmem: commit migrate_to_ram() only after the copy is confirmed
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (11 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 12/14] drm/nouveau/dmem: serialize the copy channel users mpenttil
@ 2026-12-01  4:55 ` mpenttil
  2026-12-01  4:55 ` [PATCH v18 14/14] drm/nouveau/svm: add support for migrate on fault mpenttil
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

nouveau_dmem_migrate_to_ram() ignores the nouveau_fence_new() result,
commits the migration with migrate_vma_pages() before the copy has
completed, and then uses the lazy, interrupt driven fence wait, whose
completion interrupt can be missed. A failed fence allocation leaves the
fence uninitialized, and a copy that doesn't complete in time leaves the
process with a page that wasn't fully copied.

Check the fence, poll it a jiffy at a time with a deadline (a tighter
interval was found to regress to the timeout on hardware), and commit
the migration only once the copy is confirmed: a fence signaled with an
error, as a channel kill does, doesn't count. Otherwise abort it:
finalize restores the device private pte with the data intact, and the
fault returns SIGBUS (VM_FAULT_OOM if the fence couldn't be allocated).
Letting the CPU fault again instead would, with a wedged copy engine,
queue another copy and leak another page on every retry. The destination
page and its DMA mapping may still be in use by the copy engine, so they
are leaked rather than freed. That is rare, as the copy didn't complete
within the deadline. The early returns after allocating the src/dst
arrays now free them too.

A GPU access to the page while the copy runs faults, and the GPU fault
worker waits for this migration before it can replay that fault. A copy
was seen on hardware not to progress until the faulting channel was
replayed, so this can hold up the copy. The deadline covers that case as
well.

Fixes: c32287471077 ("gpu/drm/nouveau: enable THP support for GPU memory migration")
Fixes: bfe69ef94aee ("nouveau: simplify nouveau_dmem_migrate_to_ram")
Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 drivers/gpu/drm/nouveau/nouveau_dmem.c | 109 +++++++++++++++++++++++--
 1 file changed, 100 insertions(+), 9 deletions(-)

diff --git a/drivers/gpu/drm/nouveau/nouveau_dmem.c b/drivers/gpu/drm/nouveau/nouveau_dmem.c
index 6824f5401d00..36c44d3a3c8f 100644
--- a/drivers/gpu/drm/nouveau/nouveau_dmem.c
+++ b/drivers/gpu/drm/nouveau/nouveau_dmem.c
@@ -40,6 +40,7 @@
 #include <linux/hmm.h>
 #include <linux/memremap.h>
 #include <linux/migrate.h>
+#include <linux/jiffies.h>
 
 /*
  * FIXME: this is ugly right now we are using TTM to allocate vram and we pin
@@ -213,6 +214,70 @@ static void nouveau_dmem_fence_done(struct nouveau_fence **fence)
 	}
 }
 
+/*
+ * Poll the copy fence instead of the lazy (interrupt-driven) wait since
+ * completion IRQ is randomly missed, hitting the timeout. Poll gently, a
+ * jiffy at a time: a tighter interval (usleep_range()) polls the fence far
+ * more often and was found on hardware to regress to the timeout. A CPU
+ * fault on device memory thus takes at least a jiffy. The deadline is
+ * well beyond any copy time and only catches a copy that won't complete.
+ *
+ * A fence signaled with an error, as a channel kill does to its pending
+ * fences, doesn't confirm the copy.
+ *
+ * Returns 0 on completion, -EBUSY on timeout, -EIO if the fence signaled
+ * with an error. Consumes the fence reference.
+ */
+static int nouveau_dmem_fence_poll(struct nouveau_fence **fence)
+{
+	unsigned long deadline = jiffies + 30 * HZ;
+	int ret = 0;
+
+	while (!nouveau_fence_done(*fence)) {
+		if (time_after(jiffies, deadline)) {
+			ret = -EBUSY;
+			break;
+		}
+		schedule_timeout_uninterruptible(msecs_to_jiffies(1));
+	}
+	if (!ret && dma_fence_get_status(&(*fence)->base) < 0)
+		ret = -EIO;
+	nouveau_fence_unref(fence);
+
+	return ret;
+}
+
+/*
+ * The copy could not be confirmed (no fence, timeout, or a fence signaled with
+ * an error): don't migrate, so finalize restores the original ptes and the
+ * source stays valid. The copy engine may still be writing the destination,
+ * and there is no telling when it stops, so keep the destination folios: take
+ * them out of dst[], so that migrate_vma_pages() doesn't migrate those entries
+ * and finalize doesn't free them, and keep their allocation reference. The
+ * caller skips the DMA unmap. Only the destination is written by the copy;
+ * the source is restored and stays in use.
+ *
+ * This is rare: the copy didn't complete within the deadline, because the
+ * engine is wedged or held up. Leaking is the safe choice then. The leaked
+ * destination stays allocated with its DMA mapping; a VRAM destination keeps
+ * its chunk in use, so device teardown can't complete afterwards.
+ */
+static void nouveau_dmem_migrate_abort(struct nouveau_drm *drm,
+				       struct migrate_vma *args)
+{
+	unsigned long i;
+
+	for (i = 0; i < args->npages; i++) {
+		struct page *dpage = migrate_pfn_to_page(args->dst[i]);
+
+		if (dpage) {
+			folio_unlock(page_folio(dpage));
+			args->dst[i] = 0;
+		}
+	}
+	NV_ERROR(drm, "svm: copy not confirmed, migration aborted, pages leaked\n");
+}
+
 static int nouveau_dmem_copy_folio(struct nouveau_drm *drm,
 				   struct folio *sfolio, struct folio *dfolio,
 				   struct nouveau_dmem_dma_info *dma_info)
@@ -244,11 +309,11 @@ static int nouveau_dmem_copy_folio(struct nouveau_drm *drm,
 static vm_fault_t nouveau_dmem_migrate_to_ram(struct vm_fault *vmf)
 {
 	struct nouveau_drm *drm = page_to_drm(vmf->page);
-	struct nouveau_fence *fence;
+	struct nouveau_fence *fence = NULL;
 	struct nouveau_svmm *svmm;
 	struct page *dpage;
 	vm_fault_t ret = 0;
-	int err;
+	int err, fret = 0;
 	struct migrate_vma args = {
 		.vma		= vmf->vma,
 		.pgmap_owner	= drm->dev,
@@ -293,10 +358,12 @@ static vm_fault_t nouveau_dmem_migrate_to_ram(struct vm_fault *vmf)
 	 * than just one page on CPU fault. When such fault happens it is very
 	 * likely that more surrounding page will CPU fault too.
 	 */
-	if (migrate_vma_setup(&args) < 0)
-		return VM_FAULT_SIGBUS;
+	if (migrate_vma_setup(&args) < 0) {
+		ret = VM_FAULT_SIGBUS;
+		goto err;
+	}
 	if (!args.cpages)
-		return 0;
+		goto done;
 
 	if (order)
 		dpage = folio_page(vma_alloc_folio(GFP_HIGHUSER | __GFP_ZERO,
@@ -324,11 +391,35 @@ static vm_fault_t nouveau_dmem_migrate_to_ram(struct vm_fault *vmf)
 		goto done;
 	}
 
-	nouveau_dmem_fence_new(drm, &fence);
+	/*
+	 * Commit the migration only once the copy is confirmed. Without a
+	 * fence the copy can't be confirmed: treat it as failed.
+	 */
+	fret = nouveau_dmem_fence_new(drm, &fence);
+	/*
+	 * A GPU access to this page while the copy runs faults, and the GPU
+	 * fault worker waits for this migration before it can replay that
+	 * fault. A copy was seen on hardware not to progress until the
+	 * faulting channel was replayed, so this can hold up the copy. The
+	 * deadline then aborts the migration instead of committing an
+	 * unconfirmed copy.
+	 */
+	if (!fret)
+		fret = nouveau_dmem_fence_poll(&fence);
+	if (fret) {
+		nouveau_dmem_migrate_abort(drm, &args);
+		/*
+		 * finalize restores the device private pte and the data is
+		 * intact, but don't let the CPU fault again: with the copy
+		 * engine wedged, every refault would queue another copy and
+		 * leak another destination page.
+		 */
+		ret = fret == -ENOMEM ? VM_FAULT_OOM : VM_FAULT_SIGBUS;
+	} else {
+		dma_unmap_page(drm->dev->dev, dma_info.dma_addr, dma_info.size,
+			       DMA_BIDIRECTIONAL);
+	}
 	migrate_vma_pages(&args);
-	nouveau_dmem_fence_done(&fence);
-	dma_unmap_page(drm->dev->dev, dma_info.dma_addr, dma_info.size,
-				DMA_BIDIRECTIONAL);
 done:
 	migrate_vma_finalize(&args);
 err:
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v18 14/14] drm/nouveau/svm: add support for migrate on fault
  2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
                   ` (12 preceding siblings ...)
  2026-12-01  4:55 ` [PATCH v18 13/14] drm/nouveau/dmem: commit migrate_to_ram() only after the copy is confirmed mpenttil
@ 2026-12-01  4:55 ` mpenttil
  13 siblings, 0 replies; 15+ messages in thread
From: mpenttil @ 2026-12-01  4:55 UTC (permalink / raw)
  To: linux-mm
  Cc: dri-devel, intel-xe, linux-kernel, Mika Penttilä,
	David Hildenbrand, Jason Gunthorpe, Leon Romanovsky,
	Alistair Popple, Balbir Singh, Zi Yan, Matthew Brost,
	Andrew Morton, Lorenzo Stoakes, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lyude Paul, Danilo Krummrich,
	Jonathan Corbet, Shuah Khan, Madhavan Srinivasan

From: Mika Penttilä <mpenttil@redhat.com>

Add a direct user for the new HMM_PFN_REQ_MIGRATE flag and
implement migrate on fault for nouveau driver. It is gated
by the svm_migrate_on_fault module parameter, default off.
When enabled, the policy is fully lazy: pages are migrated to
VRAM on GPU fault, and SVM_BIND no longer migrates the bound
range up front.

Added nouveau_dmem_migrate_fault() that faults a range in and
does migrate collecting in a single hmm_range_fault() walk.

It uses the copy channel lock, the fence poll and the abort handling
added by the previous two patches.

The migrate on fault path faults a single page and doesn't use
MIGRATE_VMA_SELECT_COMPOUND, so a THP covering it is split first and
stays split if the migration fails. Faulting in whole THPs is left for
later.

As an optimization, a migration policy - deciding which faulting
ranges are worth migrating to VRAM and which are better left
mirrored in system memory - would be useful. This patch
establishes the migrate-on-fault mechanism as a basis for later
refinement.

A GPU write fault on a read-only device private page owned by nouveau
is mapped read-only and refaults, because hmm_range_fault() reports the
caller's own device private pages without faulting them. This is
pre-existing (nouveau_range_fault() behaves the same) and needs a fix
in hmm_range_fault().

Signed-off-by: Mika Penttilä <mpenttil@redhat.com>
---
 drivers/gpu/drm/nouveau/nouveau_dmem.c | 281 ++++++++++++++++++++++++-
 drivers/gpu/drm/nouveau/nouveau_dmem.h |  12 ++
 drivers/gpu/drm/nouveau/nouveau_svm.c  | 164 ++++++++++-----
 drivers/gpu/drm/nouveau/nouveau_svm.h  |   5 +
 4 files changed, 410 insertions(+), 52 deletions(-)

diff --git a/drivers/gpu/drm/nouveau/nouveau_dmem.c b/drivers/gpu/drm/nouveau/nouveau_dmem.c
index 36c44d3a3c8f..ecb8397951c1 100644
--- a/drivers/gpu/drm/nouveau/nouveau_dmem.c
+++ b/drivers/gpu/drm/nouveau/nouveau_dmem.c
@@ -41,6 +41,7 @@
 #include <linux/memremap.h>
 #include <linux/migrate.h>
 #include <linux/jiffies.h>
+#include <linux/mmu_notifier.h>
 
 /*
  * FIXME: this is ugly right now we are using TTM to allocate vram and we pin
@@ -79,7 +80,7 @@ struct nouveau_dmem_migrate {
 	struct nouveau_channel *chan;
 	/*
 	 * Serializes the dmem users of chan (CPU faults in migrate_to_ram(),
-	 * bulk migration, eviction): the copy and clear
+	 * migrate on fault, bulk migration, eviction): the copy and clear
 	 * commands they write to its push buffer and the fences they emit.
 	 * Held only around those writes, never across memory allocation
 	 * (fences are allocated before taking it).
@@ -946,11 +947,12 @@ static unsigned long nouveau_dmem_migrate_copy_one(struct nouveau_drm *drm,
 	return 0;
 }
 
-static void nouveau_dmem_migrate_chunk(struct nouveau_drm *drm,
+static unsigned long
+nouveau_dmem_migrate_alloc_and_copy(struct nouveau_drm *drm,
 		struct nouveau_svmm *svmm, struct migrate_vma *args,
-		struct nouveau_dmem_dma_info *dma_info, u64 *pfns)
+		struct nouveau_dmem_dma_info *dma_info, u64 *pfns,
+		unsigned long *nr_dma_out, unsigned long *order_out)
 {
-	struct nouveau_fence *fence;
 	unsigned long addr = args->start, nr_dma = 0, i;
 	unsigned long order = 0;
 
@@ -972,6 +974,21 @@ static void nouveau_dmem_migrate_chunk(struct nouveau_drm *drm,
 		addr += (1 << order) * PAGE_SIZE;
 	}
 
+	*nr_dma_out = nr_dma;
+	*order_out = order;
+	return i;
+}
+
+static void nouveau_dmem_migrate_chunk(struct nouveau_drm *drm,
+		struct nouveau_svmm *svmm, struct migrate_vma *args,
+		struct nouveau_dmem_dma_info *dma_info, u64 *pfns)
+{
+	struct nouveau_fence *fence;
+	unsigned long nr_dma, order, i;
+
+	i = nouveau_dmem_migrate_alloc_and_copy(drm, svmm, args, dma_info, pfns,
+						&nr_dma, &order);
+
 	nouveau_dmem_fence_new(drm, &fence);
 	migrate_vma_pages(args);
 	nouveau_dmem_fence_done(&fence);
@@ -984,6 +1001,262 @@ static void nouveau_dmem_migrate_chunk(struct nouveau_drm *drm,
 	migrate_vma_finalize(args);
 }
 
+/*
+ * Encode an hmm_range_fault() pfn for @start into the nouveau PFNMAP format,
+ * shared by nouveau_hmm_convert_pfn() and the in-place map in
+ * nouveau_dmem_migrate_fault().
+ */
+u64 nouveau_dmem_hmm_pfn_to_map(unsigned long hmm_pfn, unsigned long start,
+				unsigned long *map_addr, unsigned int *page_shift)
+{
+	unsigned long order;
+	struct page *page;
+	u64 pfn;
+
+	*map_addr = start;
+	*page_shift = PAGE_SHIFT;
+
+	if (!(hmm_pfn & HMM_PFN_VALID))
+		return NVIF_VMM_PFNMAP_V0_NONE;
+
+	page = hmm_pfn_to_page(hmm_pfn);
+
+	order = hmm_pfn_to_map_order(hmm_pfn);
+	if (order) {
+		*page_shift = order + PAGE_SHIFT;
+		*map_addr = start & ~((1UL << *page_shift) - 1);
+		page -= (start - *map_addr) >> PAGE_SHIFT;
+	}
+
+	if (is_device_private_page(page))
+		pfn = nouveau_dmem_page_addr(page) |
+			NVIF_VMM_PFNMAP_V0_V | NVIF_VMM_PFNMAP_V0_VRAM;
+	else
+		pfn = page_to_phys(page) |
+			NVIF_VMM_PFNMAP_V0_V | NVIF_VMM_PFNMAP_V0_HOST;
+	if (hmm_pfn & HMM_PFN_WRITE)
+		pfn |= NVIF_VMM_PFNMAP_V0_W;
+
+	return pfn;
+}
+
+/*
+ * Fault a range in and migrate it to VRAM.
+ * Returns 0 on success, or an error (so the caller
+ * falls back to nouveau_range_fault()) if nothing could be mapped.
+ */
+int
+nouveau_dmem_migrate_fault(struct nouveau_drm *drm, struct nouveau_svmm *svmm,
+			   struct mmu_interval_notifier *notifier,
+			   unsigned long start, unsigned long end,
+			   unsigned long hmm_flags,
+			   u64 *out_pfn0, unsigned long *out_addr,
+			   unsigned int *out_shift)
+{
+	unsigned long timeout =
+		jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
+	unsigned long npages = (end - start) >> PAGE_SHIFT;
+	struct mm_struct *mm = notifier->mm;
+	struct nouveau_dmem_dma_info *dma_info;
+	struct nouveau_fence *fence = NULL;
+	struct migrate_vma migrate = {
+		.start		= start,
+		.end		= end,
+		.pgmap_owner	= drm->dev,
+		/*
+		 * No MIGRATE_VMA_SELECT_COMPOUND: the fault range is a single
+		 * page, so a THP covering it is split before migrating, and
+		 * stays split if the migration then fails. Faulting in whole
+		 * THPs is left for later.
+		 */
+		.flags		= MIGRATE_VMA_SELECT_SYSTEM,
+	};
+	struct hmm_range range = {
+		.notifier		= notifier,
+		.start			= start,
+		.end			= end,
+		.dev_private_owner	= drm->dev,
+		.migrate		= &migrate,
+		.default_flags		= hmm_flags | HMM_PFN_REQ_MIGRATE,
+	};
+	unsigned long nr_dma, order, n, i;
+	unsigned long hmm_pfn0 = 0;
+	bool migrated;
+	u64 *pfns;
+	int ret, fret = 0;
+
+	if (!drm->dmem)
+		return -ENODEV;
+
+	migrate.src = kcalloc(npages, sizeof(*migrate.src), GFP_KERNEL);
+	if (!migrate.src)
+		return -ENOMEM;
+	migrate.dst = kcalloc(npages, sizeof(*migrate.dst), GFP_KERNEL);
+	if (!migrate.dst) {
+		ret = -ENOMEM;
+		goto out_free_src;
+	}
+	dma_info = kmalloc_objs(*dma_info, npages);
+	if (!dma_info) {
+		ret = -ENOMEM;
+		goto out_free_dst;
+	}
+	pfns = nouveau_pfns_alloc(npages);
+	if (!pfns) {
+		ret = -ENOMEM;
+		goto out_free_dma;
+	}
+
+	/* hmm_range_fault() shares the source pfn array with migrate_vma. */
+	range.hmm_pfns = migrate.src;
+
+	do {
+		mmap_read_lock(mm);
+		range.notifier_seq = mmu_interval_read_begin(notifier);
+
+		ret = hmm_range_fault(&range);
+		/*
+		 * Snapshot the pfn before migrate_hmm_range_setup() overwrites the
+		 * shared array; used to map in place if nothing migrates.
+		 */
+		if (!ret)
+			hmm_pfn0 = range.hmm_pfns[0];
+		migrate_hmm_range_setup(&range);
+		if (ret) {
+			migrate_vma_pages(&migrate);
+			migrate_vma_finalize(&migrate);
+			goto unlock;
+		}
+
+		n = nouveau_dmem_migrate_alloc_and_copy(drm, svmm, &migrate,
+							dma_info, pfns,
+							&nr_dma, &order);
+
+		/* Only a migrated page has an in-flight CE copy to unblock below. */
+		for (i = 0, migrated = false; i < npages; i++) {
+			if (migrate.dst[i]) {
+				migrated = true;
+				break;
+			}
+		}
+
+		/*
+		 * Track a copy fence only when a copy was enqueued; waiting on an
+		 * empty fence would block until the fault's CTXSW_TIMEOUT.
+		 */
+		if (migrated)
+			fret = nouveau_dmem_fence_new(drm, &fence);
+
+		/*
+		 * The fault-in path must replay the faulting channel before waiting on
+		 * the copy fence: with the fault still unreplayed the copy does not
+		 * make progress. GPU has no mapping so it might refault, until it
+		 * gets the migrated or mirrored mapping; it is mapped only once the
+		 * copy is confirmed. In practice such a refault doesn't hold up the
+		 * copy; as a safety net, if the copy doesn't complete by the
+		 * deadline, the migration is aborted and the fault is mapped in place.
+		 */
+		if (drm->svm && migrated)
+			nouveau_svm_fault_replay(drm->svm);
+
+		/* Without a fence (fret set) the copy can't be confirmed. */
+		if (migrated && !fret)
+			fret = nouveau_dmem_fence_poll(&fence);
+
+		/* Commit the migration only once the copy is confirmed. */
+		if (fret)
+			nouveau_dmem_migrate_abort(drm, &migrate);
+		migrate_vma_pages(&migrate);
+
+		/*
+		 * Don't map destination pages that migrate_vma_pages() didn't
+		 * migrate: finalize frees them and restores the source.
+		 */
+		for (i = 0; i < npages; i++)
+			if (!(migrate.src[i] & MIGRATE_PFN_MIGRATE))
+				pfns[i] = NVIF_VMM_PFNMAP_V0_NONE;
+
+		mutex_lock(&svmm->mutex);
+		if (fret) {
+			/* Copy did not complete; don't map a half-copied page. */
+			ret = -EIO;
+		} else if (mmu_interval_read_retry(notifier, range.notifier_seq)) {
+			ret = -EBUSY;
+		} else {
+			unsigned long map_addr = migrate.start;
+			unsigned int page_shift = PAGE_SHIFT + order;
+
+			/*
+			 * If nothing migrated might still be able to mirror.
+			 * In that case use the snapshot hmm_pfn.
+			 * npages == 1 always today.
+			 *
+			 * A read-only device private page of ours is reported
+			 * without HMM_PFN_WRITE even for a write fault, because
+			 * hmm_range_fault() doesn't fault the caller's own device
+			 * private pages. It is then mapped read-only and the GPU
+			 * faults again, as with nouveau_range_fault(). That is
+			 * pre-existing and needs a fix in hmm_range_fault().
+			 */
+			if (npages == 1 && !(pfns[0] & NVIF_VMM_PFNMAP_V0_V))
+				pfns[0] = nouveau_dmem_hmm_pfn_to_map(hmm_pfn0,
+						start, &map_addr, &page_shift);
+
+			/*
+			 * Nothing to map: leave the GPU mapping alone, the
+			 * caller falls back to nouveau_range_fault().
+			 */
+			if (pfns[0] & NVIF_VMM_PFNMAP_V0_V) {
+				/* On failure the caller falls back, then cancels */
+				ret = __nouveau_pfns_map_locked(svmm, map_addr,
+								pfns, n,
+								page_shift);
+				if (!ret) {
+					*out_pfn0 = pfns[0];
+					*out_addr = map_addr;
+					*out_shift = page_shift;
+				}
+			}
+		}
+		/*
+		 * The migration may be committed without being mapped, and our
+		 * own MIGRATE invalidation didn't clear the GPU page table: drop
+		 * a mapping an earlier fault left to a source page that finalize
+		 * may free.
+		 */
+		if (ret && !fret)
+			nouveau_svmm_invalidate(svmm, migrate.start, migrate.end);
+		mutex_unlock(&svmm->mutex);
+
+		if (fret)
+			NV_ERROR(drm,
+				 "svm: migrate copy did not complete (%d) for %lx-%lx\n",
+				 fret, start, end);
+
+		/* After an aborted copy the engine may still use the mappings */
+		while (!fret && nr_dma--) {
+			dma_unmap_page(drm->dev->dev, dma_info[nr_dma].dma_addr,
+				       dma_info[nr_dma].size, DMA_BIDIRECTIONAL);
+		}
+		migrate_vma_finalize(&migrate);
+unlock:
+		mmap_read_unlock(mm);
+	} while (ret == -EBUSY && !time_after(jiffies, timeout));
+
+	/* Nothing migrated or mappable in place, fallback to nouveau_range_fault(). */
+	if (!ret && !(pfns[0] & NVIF_VMM_PFNMAP_V0_V))
+		ret = -ENOENT;
+
+	nouveau_pfns_free(pfns);
+out_free_dma:
+	kfree(dma_info);
+out_free_dst:
+	kfree(migrate.dst);
+out_free_src:
+	kfree(migrate.src);
+	return ret;
+}
+
 int
 nouveau_dmem_migrate_vma(struct nouveau_drm *drm,
 			 struct nouveau_svmm *svmm,
diff --git a/drivers/gpu/drm/nouveau/nouveau_dmem.h b/drivers/gpu/drm/nouveau/nouveau_dmem.h
index 64da5d3635c8..91e8910cadbf 100644
--- a/drivers/gpu/drm/nouveau/nouveau_dmem.h
+++ b/drivers/gpu/drm/nouveau/nouveau_dmem.h
@@ -27,6 +27,7 @@ struct drm_file;
 struct nouveau_drm;
 struct nouveau_svmm;
 struct hmm_range;
+struct mmu_interval_notifier;
 
 #if IS_ENABLED(CONFIG_DRM_NOUVEAU_SVM)
 void nouveau_dmem_init(struct nouveau_drm *);
@@ -39,7 +40,18 @@ int nouveau_dmem_migrate_vma(struct nouveau_drm *drm,
 			     struct vm_area_struct *vma,
 			     unsigned long start,
 			     unsigned long end);
+int nouveau_dmem_migrate_fault(struct nouveau_drm *drm,
+			       struct nouveau_svmm *svmm,
+			       struct mmu_interval_notifier *notifier,
+			       unsigned long start,
+			       unsigned long end,
+			       unsigned long hmm_flags,
+			       u64 *out_pfn0,
+			       unsigned long *out_addr,
+			       unsigned int *out_shift);
 unsigned long nouveau_dmem_page_addr(struct page *page);
+u64 nouveau_dmem_hmm_pfn_to_map(unsigned long hmm_pfn, unsigned long start,
+				unsigned long *map_addr, unsigned int *page_shift);
 
 #else /* IS_ENABLED(CONFIG_DRM_NOUVEAU_SVM) */
 static inline void nouveau_dmem_init(struct nouveau_drm *drm) {}
diff --git a/drivers/gpu/drm/nouveau/nouveau_svm.c b/drivers/gpu/drm/nouveau/nouveau_svm.c
index c519c28164fa..a67395207032 100644
--- a/drivers/gpu/drm/nouveau/nouveau_svm.c
+++ b/drivers/gpu/drm/nouveau/nouveau_svm.c
@@ -37,6 +37,7 @@
 #include <linux/hmm.h>
 #include <linux/memremap.h>
 #include <linux/rmap.h>
+#include <linux/moduleparam.h>
 
 struct nouveau_svm {
 	struct nouveau_drm *drm;
@@ -78,6 +79,17 @@ struct nouveau_svm {
 #define SVM_DBG(s,f,a...) NV_DEBUG((s)->drm, "svm: "f"\n", ##a)
 #define SVM_ERR(s,f,a...) NV_WARN((s)->drm, "svm: "f"\n", ##a)
 
+/*
+ * When set, migrate the faulting range to VRAM on GPU fault (default off).
+ * Like the other nouveau parameters, it is documented by MODULE_PARM_DESC
+ * only, and it matters only with the experimental SVM support.
+ */
+static bool nouveau_svm_migrate_on_fault;
+module_param_named(svm_migrate_on_fault, nouveau_svm_migrate_on_fault, bool,
+		   0644);
+MODULE_PARM_DESC(svm_migrate_on_fault,
+		 "migrate system memory to VRAM on GPU fault (default off)");
+
 struct nouveau_pfnmap_args {
 	struct nvif_ioctl_v0_hdr i;
 	struct nvif_ioctl_mthd_v0_hdr m;
@@ -182,9 +194,15 @@ nouveau_svmm_bind(struct drm_device *dev, void *data,
 
 		addr = max(addr, vma->vm_start);
 		next = min(vma->vm_end, end);
-		/* This is a best effort so we ignore errors */
-		nouveau_dmem_migrate_vma(cli->drm, cli->svm.svmm, vma, addr,
-					 next);
+		/*
+		 * Best effort. With svm_migrate_on_fault the policy is lazy:
+		 * pages migrate to VRAM on GPU fault, not up front here. Pages
+		 * the GPU already maps in system memory don't fault again, so
+		 * they stay there; that is part of the opt-in policy.
+		 */
+		if (!nouveau_svm_migrate_on_fault)
+			nouveau_dmem_migrate_vma(cli->drm, cli->svm.svmm, vma,
+						 addr, next);
 		addr = next;
 	}
 
@@ -390,7 +408,7 @@ nouveau_svmm_init(struct drm_device *dev, void *data,
 }
 
 /* Issue fault replay for GPU to retry accesses that faulted previously. */
-static void
+void
 nouveau_svm_fault_replay(struct nouveau_svm *svm)
 {
 	SVM_DBG(svm, "replay");
@@ -514,6 +532,8 @@ nouveau_svm_fault_cache(struct nouveau_svm *svm,
 struct svm_notifier {
 	struct mmu_interval_notifier notifier;
 	struct nouveau_svmm *svmm;
+	/* Task running this fault's migrate-on-fault walk, or NULL */
+	struct task_struct *migrating;
 };
 
 static bool nouveau_svm_range_invalidate(struct mmu_interval_notifier *mni,
@@ -527,6 +547,17 @@ static bool nouveau_svm_range_invalidate(struct mmu_interval_notifier *mni,
 	    range->owner == sn->svmm->vmm->cli->drm->dev)
 		return true;
 
+	/*
+	 * Ignore the invalidation of this fault's own migrate-on-fault walk,
+	 * which runs in the walking task; otherwise its MMU_NOTIFY_MIGRATE
+	 * bumps the seq and read_retry() spins to timeout. Other migrations
+	 * on the device (CPU faults, bind) must still invalidate.
+	 */
+	if (range->event == MMU_NOTIFY_MIGRATE &&
+	    range->owner == sn->svmm->vmm->cli->drm->dev &&
+	    READ_ONCE(sn->migrating) == current)
+		return true;
+
 	/*
 	 * serializes the update to mni->invalidate_seq done by caller and
 	 * prevents invalidation of the PTE from progressing while HW is being
@@ -551,48 +582,25 @@ static void nouveau_hmm_convert_pfn(struct nouveau_drm *drm,
 				    struct hmm_range *range,
 				    struct nouveau_pfnmap_args *args)
 {
-	struct page *page;
+	unsigned long map_addr;
+	unsigned int page_shift;
 
 	/*
 	 * The address prepared here is passed through nvif_object_ioctl()
 	 * to an eventual DMA map in something like gp100_vmm_pgt_pfn()
 	 *
 	 * This is all just encoding the internal hmm representation into a
-	 * different nouveau internal representation.
+	 * different nouveau internal representation; see the shared encoder
+	 * nouveau_dmem_hmm_pfn_to_map() (also widens to the CPU folio order).
 	 */
-	if (!(range->hmm_pfns[0] & HMM_PFN_VALID)) {
-		args->p.phys[0] = 0;
-		return;
+	args->p.phys[0] = nouveau_dmem_hmm_pfn_to_map(range->hmm_pfns[0],
+						      args->p.addr, &map_addr,
+						      &page_shift);
+	if (page_shift != PAGE_SHIFT) {
+		args->p.addr = map_addr;
+		args->p.page = page_shift;
+		args->p.size = 1UL << page_shift;
 	}
-
-	page = hmm_pfn_to_page(range->hmm_pfns[0]);
-	/*
-	 * Only map compound pages to the GPU if the CPU is also mapping the
-	 * page as a compound page. Otherwise, the PTE protections might not be
-	 * consistent (e.g., CPU only maps part of a compound page).
-	 * Note that the underlying page might still be larger than the
-	 * CPU mapping (e.g., a PUD sized compound page partially mapped with
-	 * a PMD sized page table entry).
-	 */
-	if (hmm_pfn_to_map_order(range->hmm_pfns[0])) {
-		unsigned long addr = args->p.addr;
-
-		args->p.page = hmm_pfn_to_map_order(range->hmm_pfns[0]) +
-				PAGE_SHIFT;
-		args->p.size = 1UL << args->p.page;
-		args->p.addr &= ~(args->p.size - 1);
-		page -= (addr - args->p.addr) >> PAGE_SHIFT;
-	}
-	if (is_device_private_page(page))
-		args->p.phys[0] = nouveau_dmem_page_addr(page) |
-				NVIF_VMM_PFNMAP_V0_V |
-				NVIF_VMM_PFNMAP_V0_VRAM;
-	else
-		args->p.phys[0] = page_to_phys(page) |
-				NVIF_VMM_PFNMAP_V0_V |
-				NVIF_VMM_PFNMAP_V0_HOST;
-	if (range->hmm_pfns[0] & HMM_PFN_WRITE)
-		args->p.phys[0] |= NVIF_VMM_PFNMAP_V0_W;
 }
 
 static int nouveau_atomic_range_fault(struct nouveau_svmm *svmm,
@@ -728,6 +736,46 @@ static int nouveau_range_fault(struct nouveau_svmm *svmm,
 	return ret;
 }
 
+static int nouveau_range_fault_and_migrate(struct nouveau_svmm *svmm,
+					   struct nouveau_drm *drm,
+					   struct nouveau_pfnmap_args *args,
+					   unsigned long hmm_flags,
+					   struct svm_notifier *notifier)
+{
+	struct mm_struct *mm = svmm->notifier.mm;
+	unsigned long start = args->p.addr;
+	unsigned long end = start + args->p.size;
+	unsigned long map_addr;
+	unsigned int page_shift;
+	u64 pfn0;
+	int ret;
+
+	ret = mmu_interval_notifier_insert(&notifier->notifier, mm,
+					   start, args->p.size,
+					   &nouveau_svm_mni_ops);
+	if (ret)
+		return ret;
+
+	WRITE_ONCE(notifier->migrating, current);
+	ret = nouveau_dmem_migrate_fault(drm, svmm, &notifier->notifier,
+					 start, end, hmm_flags,
+					 &pfn0, &map_addr, &page_shift);
+	WRITE_ONCE(notifier->migrating, NULL);
+
+	if (!ret) {
+		args->p.phys[0] = pfn0;
+		if (page_shift != PAGE_SHIFT) {
+			args->p.addr = map_addr;
+			args->p.page = page_shift;
+			args->p.size = 1UL << page_shift;
+		}
+	}
+
+	mmu_interval_notifier_remove(&notifier->notifier);
+
+	return ret;
+}
+
 static void
 nouveau_svm_fault(struct work_struct *work)
 {
@@ -843,14 +891,26 @@ nouveau_svm_fault(struct work_struct *work)
 		}
 
 		notifier.svmm = svmm;
-		if (atomic)
+		notifier.migrating = NULL;
+		if (atomic) {
 			ret = nouveau_atomic_range_fault(svmm, svm->drm, args,
 							 __struct_size(args),
 							 &notifier);
-		else
+		} else if (nouveau_svm_migrate_on_fault &&
+			   buffer->fault[fi]->access != FAULT_ACCESS_PREFETCH) {
+			/* Fault+migrate in one walk; fall back if nothing migrated. */
+			ret = nouveau_range_fault_and_migrate(svmm, svm->drm,
+							      args, hmm_flags,
+							      &notifier);
+			if (ret)
+				ret = nouveau_range_fault(svmm, svm->drm, args,
+							  __struct_size(args),
+							  hmm_flags, &notifier);
+		} else {
 			ret = nouveau_range_fault(svmm, svm->drm, args,
 						  __struct_size(args),
 						  hmm_flags, &notifier);
+		}
 		mmput(mm);
 
 		limit = args->p.addr + args->p.size;
@@ -934,22 +994,30 @@ nouveau_pfns_free(u64 *pfns)
 	kfree(args);
 }
 
-void
-nouveau_pfns_map(struct nouveau_svmm *svmm, struct mm_struct *mm,
-		 unsigned long addr, u64 *pfns, unsigned long npages,
-		 unsigned int page_shift)
+int
+__nouveau_pfns_map_locked(struct nouveau_svmm *svmm, unsigned long addr,
+			  u64 *pfns, unsigned long npages,
+			  unsigned int page_shift)
 {
 	struct nouveau_pfnmap_args *args = nouveau_pfns_to_args(pfns);
 
+	lockdep_assert_held(&svmm->mutex);
+
 	args->p.addr = addr;
 	args->p.size = npages << page_shift;
 	args->p.page = page_shift;
 
-	mutex_lock(&svmm->mutex);
-
-	nvif_object_ioctl(&svmm->vmm->vmm.object, args,
-			  struct_size(args, p.phys, npages), NULL);
+	return nvif_object_ioctl(&svmm->vmm->vmm.object, args,
+				 struct_size(args, p.phys, npages), NULL);
+}
 
+void
+nouveau_pfns_map(struct nouveau_svmm *svmm, struct mm_struct *mm,
+		 unsigned long addr, u64 *pfns, unsigned long npages,
+		 unsigned int page_shift)
+{
+	mutex_lock(&svmm->mutex);
+	__nouveau_pfns_map_locked(svmm, addr, pfns, npages, page_shift);
 	mutex_unlock(&svmm->mutex);
 }
 
diff --git a/drivers/gpu/drm/nouveau/nouveau_svm.h b/drivers/gpu/drm/nouveau/nouveau_svm.h
index 3fd78662f17e..c24b717819a5 100644
--- a/drivers/gpu/drm/nouveau/nouveau_svm.h
+++ b/drivers/gpu/drm/nouveau/nouveau_svm.h
@@ -5,6 +5,7 @@
 struct drm_device;
 struct drm_file;
 struct nouveau_drm;
+struct nouveau_svm;
 
 struct nouveau_svmm {
 	struct mmu_notifier notifier;
@@ -35,6 +36,10 @@ void nouveau_pfns_free(u64 *pfns);
 void nouveau_pfns_map(struct nouveau_svmm *svmm, struct mm_struct *mm,
 		      unsigned long addr, u64 *pfns, unsigned long npages,
 		      unsigned int page_shift);
+int __nouveau_pfns_map_locked(struct nouveau_svmm *svmm, unsigned long addr,
+			      u64 *pfns, unsigned long npages,
+			      unsigned int page_shift);
+void nouveau_svm_fault_replay(struct nouveau_svm *svm);
 #else /* IS_ENABLED(CONFIG_DRM_NOUVEAU_SVM) */
 static inline void nouveau_svm_init(struct nouveau_drm *drm) {}
 static inline void nouveau_svm_fini(struct nouveau_drm *drm) {}
-- 
2.55.0



^ permalink raw reply related	[flat|nested] 15+ messages in thread

end of thread, other threads:[~2026-12-01  4:57 UTC | newest]

Thread overview: 15+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01  4:55 [PATCH v18 00/14] migrate on fault for device pages mpenttil
2026-12-01  4:55 ` [PATCH v18 01/14] mm/Kconfig: changes for " mpenttil
2026-12-01  4:55 ` [PATCH v18 02/14] mm: add helper to convert HMM pfn to migrate pfn mpenttil
2026-12-01  4:55 ` [PATCH v18 03/14] mm/hmm: preparations for HMM to participate in migration mpenttil
2026-12-01  4:55 ` [PATCH v18 04/14] mm/hmm: do the plumbing " mpenttil
2026-12-01  4:55 ` [PATCH v18 05/14] mm/hmm: implement rollback for device page migration in HMM pagewalk mpenttil
2026-12-01  4:55 ` [PATCH v18 06/14] mm/hmm: migrate collection in HMM pagewalk - pte level mpenttil
2026-12-01  4:55 ` [PATCH v18 07/14] mm/hmm: migrate collection in HMM pagewalk - pmd level mpenttil
2026-12-01  4:55 ` [PATCH v18 08/14] mm/hmm: add lazy MMU mode support for migration in HMM pagewalk mpenttil
2026-12-01  4:55 ` [PATCH v18 09/14] mm: enable device page migration from " mpenttil
2026-12-01  4:55 ` [PATCH v18 10/14] lib/test_hmm: add a new testcase for the migrate on fault mpenttil
2026-12-01  4:55 ` [PATCH v18 11/14] Documentation/mm/hmm: document migration through hmm_range_fault() mpenttil
2026-12-01  4:55 ` [PATCH v18 12/14] drm/nouveau/dmem: serialize the copy channel users mpenttil
2026-12-01  4:55 ` [PATCH v18 13/14] drm/nouveau/dmem: commit migrate_to_ram() only after the copy is confirmed mpenttil
2026-12-01  4:55 ` [PATCH v18 14/14] drm/nouveau/svm: add support for migrate on fault mpenttil

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox