From: Baoquan He Preallocate the backend table before allocating the physical slot, and record the owner before installing the reverse map. A slot is then never visible to swapoff without its owner. Signed-off-by: Baoquan He --- mm/swapfile.c | 51 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/mm/swapfile.c b/mm/swapfile.c index e55711300169..adc7f41cd8a3 100644 --- a/mm/swapfile.c +++ b/mm/swapfile.c @@ -4761,8 +4761,8 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry) struct swap_info_struct *si = __swap_entry_to_info(entry); struct swap_cluster_info *ci; unsigned long off = swp_offset(entry); + unsigned long swp_tb; swp_entry_t phys, old; - bool recorded = false; /* * A folio that was written back, redirtied while still in the swap @@ -4777,6 +4777,19 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry) xswap_backend_free(entry, old); } + /* + * Get the xswap side ready before a physical slot exists, so the + * reverse map installed below cannot expose a slot with no owner. + */ + ci = swap_cluster_lock(si, off); + if (!ci) + return (swp_entry_t){}; + if (!xswap_xs_table_locked(ci, GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC)) { + swap_cluster_unlock(ci); + return (swp_entry_t){}; + } + swap_cluster_unlock(ci); + phys = xswap_alloc_phys_slot(); if (!phys.val) return phys; @@ -4785,31 +4798,27 @@ swp_entry_t xswap_backend_alloc(swp_entry_t entry) * The slot is a shadow until the reverse map is installed below. * Physical swapoff can see it and retry; the window is short and * try_to_unuse() reschedules. + * + * Owner first, then the reverse map, under one hold of the lock. */ - xswap_install_rmap(phys, entry); - ci = swap_cluster_lock(si, off); - if (ci) { - unsigned int slot = off % SWAPFILE_CLUSTER; - unsigned long swp_tb; - - recorded = xswap_slot_set_backend(ci, slot, phys); - /* - * The folio can lose its last reference while the owner is - * not recorded yet; that path cannot mark the slot for us. - */ - swp_tb = __swap_table_get(ci, slot); - if (recorded && swp_tb_is_folio(swp_tb) && - !swp_tb_get_count(swp_tb)) - xswap_mark_cache_only(si, ci, slot); - swap_cluster_unlock(ci); - } - - if (!recorded) { - /* The backend is unrecorded, so the data would be unreachable. */ + if (!ci) { xswap_backend_free(entry, phys); return (swp_entry_t){}; } + /* The table is preallocated above, so this cannot fail. */ + if (!xswap_slot_set_backend(ci, off % SWAPFILE_CLUSTER, phys)) + VM_WARN_ON_ONCE(1); + xswap_install_rmap(phys, entry); + + /* + * The folio can lose its last reference while the owner is not + * recorded yet; that path cannot mark the slot for us. + */ + swp_tb = __swap_table_get(ci, off % SWAPFILE_CLUSTER); + if (swp_tb_is_folio(swp_tb) && !swp_tb_get_count(swp_tb)) + xswap_mark_cache_only(si, ci, off % SWAPFILE_CLUSTER); + swap_cluster_unlock(ci); return phys; } -- 2.54.0