Device-private page table entries are weird: they are non-present page table entries, and the device can write to the memory without the CPU noticing or the CPU page tables reflecting it. So there is no dirty bit on the PTE we could sync to the folio. And usually, nobody cares about the dirty bit for these folios, as these folios are not on the LRU. Device-coherent memory has the same problem: it is mapped through present PTEs, but the device writes through its own page tables and does not set the PTE dirty bit. There is one problem, though: when we migrate such a clean folio back to system RAM, the new folio will be clean, and will be mapped through clean PTEs. Consequently, reclaim can discard the data if the folio is lazyfree: (1) MADV_FREE on an ordinary anonymous folio makes the folio lazyfree and clean. (2) We migrate the folio to device memory. The new (device) folio is lazyfree and clean. (3) The device writes to the folio. (4) We migrate the folio back to system RAM. The new folio is still lazyfree, and clean just like the PTE that now maps it. (5) Reclaim discards the folio, and the data the device wrote is lost. Similarly, after fork(), a child that shares such a clean folio can call MADV_FREE, which does not check a clean folio for other mappings. So let's fix it by simply marking folios dirty when migrating them out of device memory. This has low urgency, as it requires MADV_FREE on memory that is migrated to device memory and written by the device. Fixes: a5430dda8a3a ("mm/migrate: support un-addressable ZONE_DEVICE page in migration") Fixes: 8315ada7f095 ("mm/migrate: allow migrate_vma() to alloc new page on empty entry") Fixes: f25cbb7a95a2 ("mm: add zone device coherent type memory support") Fixes: a30b48bf1b24 ("mm/migrate_device: implement THP migration of zone device pages") Cc: stable@vger.kernel.org Reported-by: Chris Mason Tested-by: Gregory Price (Meta) Reviewed-by: Gregory Price (Meta) Reviewed-by: Alistair Popple Reviewed-by: Balbir Singh Signed-off-by: David Hildenbrand (Arm) --- mm/migrate_device.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/mm/migrate_device.c b/mm/migrate_device.c index 578a4419bb083..964549222ed7c 100644 --- a/mm/migrate_device.c +++ b/mm/migrate_device.c @@ -1289,10 +1289,18 @@ static void __migrate_device_pages(unsigned long *src_pfns, mapping = folio_mapping(folio); r = folio_migrate_mapping(mapping, newfolio, folio, extra_cnt); - if (r) + if (r) { src_pfns[i+j] &= ~MIGRATE_PFN_MIGRATE; - else - folio_migrate_flags(newfolio, folio); + continue; + } + folio_migrate_flags(newfolio, folio); + /* + * A device can write to device memory without setting + * any dirty bit, so just consider folios that leave + * device memory dirty. + */ + if (folio_is_zone_device(folio)) + folio_mark_dirty(newfolio); } next: i += nr; -- 2.56.1