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

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