mm/migrate_device: avoid out-of-bounds writes for compound folios

migrate_device_range() and migrate_device_pfns() clear the entries
following a compound folio so that the PFN arrays retain their
page-granular representation.

If a compound folio extends beyond the end of the caller-provided range,
the loops clear all following folio entries without limiting them to the
number of slots remaining in the npages-sized array, causing an
out-of-bounds write.

Do not proceed with a compound folio if its page-granular representation
does not fit entirely in the remaining PFN array.  If this happens, drop
any reference and lock acquired for the folio, clear the remaining
entries, and stop collecting.

Observed with a KASAN x86 QEMU kernel using the HMM migrate_anon_huge_zero
selftest.  Closing /dev/hmm_dmirror0 after migrating an anonymous huge
page to device memory exercises:

  dmirror_fops_release()
    -> dmirror_device_evict_chunk()
      -> migrate_device_range()

Link: https://lore.kernel.org/[email protected]
Fixes: a30b48bf1b ("mm/migrate_device: implement THP migration of zone device pages")
Signed-off-by: Hui Su <[email protected]>
Cc: Alistair Popple <[email protected]>
Cc: Balbir Singh <[email protected]>
Cc: Byungchul Park <[email protected]>
Cc: David Hildenbrand <[email protected]>
Cc: Gregory Price <[email protected]>
Cc: "Huang, Ying" <[email protected]>
Cc: Joshua Hahn <[email protected]>
Cc: Matthew Brost <[email protected]>
Cc: Rakie Kim <[email protected]>
Cc: Zi Yan <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
This commit is contained in:
Hui Su authored and Andrew Morton committed 2026-09-01 20:26:20 -07:00
1 parent eedc8474d4
commit dc41e961a2
1 file changed
+18
+18
View File
@@ -1423,6 +1423,15 @@ int migrate_device_range(unsigned long *src_pfns, unsigned long start,
src_pfns[i] = migrate_device_pfn_lock(pfn);
nr = folio_nr_pages(folio);
if (nr > npages - i) {
if (src_pfns[i] & MIGRATE_PFN_MIGRATE) {
folio_unlock(folio);
folio_put(folio);
}
memset(&src_pfns[i], 0,
(npages - i) * sizeof(*src_pfns));
break;
}
if (nr > 1) {
src_pfns[i] |= MIGRATE_PFN_COMPOUND;
for (j = 1; j < nr; j++)
@@ -1457,6 +1466,15 @@ int migrate_device_pfns(unsigned long *src_pfns, unsigned long npages)
src_pfns[i] = migrate_device_pfn_lock(src_pfns[i]);
nr = folio_nr_pages(folio);
if (nr > npages - i) {
if (src_pfns[i] & MIGRATE_PFN_MIGRATE) {
folio_unlock(folio);
folio_put(folio);
}
memset(&src_pfns[i], 0,
(npages - i) * sizeof(*src_pfns));
break;
}
if (nr > 1) {
src_pfns[i] |= MIGRATE_PFN_COMPOUND;
for (j = 1; j < nr; j++)