AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/18 16:15 flow patch-triage
11m Args:
null

Results:
{
  "EnableConfigs": [
    "SWAP",
    "HIBERNATION",
    "MEMCG",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "folio_alloc_swap",
    "swap_alloc_entry",
    "swap_queue_get_device",
    "swap_queue_add",
    "swap_queue_del",
    "swap_device_enable",
    "swap_device_disable",
    "cluster_alloc_swap_entry",
    "swap_discard_for_alloc",
    "__x64_sys_swapon",
    "__x64_sys_swapoff"
  ],
  "KMSANReasoning": "The patch series reworks the internal swap device management and locking hierarchy in mm/swapfile.c. It replaces the plist-based active and available lists with priority rings (struct swap_prio_ring, swap_queue) protected by a percpu rwsem (swapon_rwsem) and a spinlock (swap_queue_update_lock), alongside per-CPU reader iterators (struct swap_queue_reader) and percpu/global cluster allocation state.\n\nKMSAN vs KASAN Applicability:\n1. Memory Initialization: All newly allocated kernel data structures (percpu_cluster via alloc_percpu, swap_prio_ring via kmalloc with explicit element initialization/memcpy, swap_queue_reader via __alloc_percpu_gfp followed by local_lock_init and swap_queue_reset_readers, and swap_info_struct via kvzalloc) are thoroughly initialized before use. Local stack variables (cursor, bitmap arrays) are explicitly zero-initialized with '= {}'.\n2. Info-Leaks and Userspace Boundaries: No kernel structures or raw kernel buffers are copied or exposed to userspace. /proc/swaps and si_swapinfo only format text and aggregate numeric counters from initialized fields.\n3. Failure Modes: The primary risks introduced by this refactoring are synchronization/locking bugs (deadlocks, lock ordering issues), use-after-free (during queue/ring reallocation and reader replacement), and array indexing or bounds errors. These are comprehensively detected by standard KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory reads or information leak risks that would be caught uniquely by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series refactors the core Linux memory management swap subsystem. It replaces the plist-based swap device tracking (swap_active_head, swap_avail_head) and coarse spinlocks (swap_lock, swap_avail_lock) with a per-CPU priority-ring queue (swap_queue, swap_prio_ring), per-CPU readers, swapon_rwsem, and fine-grained queue update locks. It also rewires per-CPU swap cluster allocation, swap device activation/deactivation during swapon/swapoff, and synchronous cluster discard handling. These changes modify core mm logic and synchronization paths that are fully reachable in virtualized environments via the swapon/swapoff syscalls and anonymous memory paging pressure.",
  "WorthFuzzing": true
}

1/1 2026/11/18 16:15 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 00c4e8cb61a1f01e70050a532c7ceeebefa7e809\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Nov 18 16:15:20 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/include/linux/plist.h b/include/linux/plist.h\nindex 16cf4355b5c131..73d359c1a0536a 100644\n--- a/include/linux/plist.h\n+++ b/include/linux/plist.h\n@@ -132,8 +132,6 @@ static inline void plist_node_init(struct plist_node *node, int prio)\n extern void plist_add(struct plist_node *node, struct plist_head *head);\n extern void plist_del(struct plist_node *node, struct plist_head *head);\n \n-extern void plist_requeue(struct plist_node *node, struct plist_head *head);\n-\n /**\n  * plist_for_each - iterate over the plist\n  * @pos:\tthe type * to use as a loop counter\ndiff --git a/include/linux/swap.h b/include/linux/swap.h\nindex 4f686709d71f00..ce8a800751ca2a 100644\n--- a/include/linux/swap.h\n+++ b/include/linux/swap.h\n@@ -188,6 +188,25 @@ struct swap_extent {\n \t((offsetof(union swap_header, magic.magic) - \\\n \t  offsetof(union swap_header, info.badpages)) / sizeof(int))\n \n+/*\n+ * Swap device flags, except the ones documented below, all are immutable\n+ * after exposed by swap_device_enable, and until the device is freed again\n+ * (SWP_USED unset), except that teardown clears SWP_ACTIVATED after draining\n+ * allocators and live references. The other exceptions use swapon_rwsem:\n+ * - SWP_USED: Protected by swapon_rwsem. Indicates the device is inuse. Once\n+ *   set, won't be cleared unless all reference to this device is freed and\n+ *   swapoff finished.\n+ * - SWP_WRITEOK: Protected by swapon_rwsem, si-\u003elock and\n+ *   swap_queue_update_lock.\n+ *   Clearing this flag is followed by waiting for all current cluster lock\n+ *   users to exit, so\n+ *   checking this flag while holding any of these locks ensures the device\n+ *   is safe to use at the moment. Note: clearing this flag doesn't affect\n+ *   pending IO or async requests, it only prevents further entry allocation\n+ *   or new async request (e.g. discard) from initiating.\n+ * - SWP_HIBERNATION: Protected by swapon_rwsem. Indicates if the device\n+ *   is pinned for hibernation.\n+ */\n enum {\n \tSWP_USED\t= (1 \u003c\u003c 0),\t/* is slot in swap_info[] used? */\n \tSWP_WRITEOK\t= (1 \u003c\u003c 1),\t/* ok to write to this swap?\t*/\n@@ -223,10 +242,17 @@ enum {\n #endif\n \n /*\n- * We keep using same cluster for rotational device so IO will be sequential.\n- * The purpose is to optimize SWAP throughput on these device.\n+ * We assign a cluster to each CPU, so each CPU can allocate swap entry from\n+ * its own cluster and swapout sequentially. The purpose is to optimize swapout\n+ * throughput.\n  */\n+struct percpu_cluster {\n+\tlocal_lock_t lock; /* Protect the percpu_cluster above */\n+\tunsigned int next[SWAP_NR_ORDERS]; /* Likely next allocation offset */\n+};\n+\n struct swap_sequential_cluster {\n+\tspinlock_t lock; /* Serialize usage of global cluster */\n \tunsigned int next[SWAP_NR_ORDERS]; /* Likely next allocation offset */\n };\n \n@@ -237,7 +263,6 @@ struct swap_info_struct {\n \tstruct percpu_ref users;\t/* indicate and keep swap device valid. */\n \tunsigned long\tflags;\t\t/* SWP_USED etc: see above */\n \tsigned short\tprio;\t\t/* swap priority of this type */\n-\tstruct plist_node list;\t\t/* entry in swap_active_head */\n \tsigned char\ttype;\t\t/* strange name for an index */\n \tunsigned int\tmax;\t\t/* size of this swap device */\n \tstruct swap_cluster_info *cluster_info; /* array, one entry per cluster */\n@@ -249,26 +274,20 @@ struct swap_info_struct {\n \t\t\t\t\t/* list of cluster that are fragmented or contented */\n \tunsigned int pages;\t\t/* total of usable pages of swap */\n \tatomic_long_t inuse_pages;\t/* number of those currently in use */\n+\tstruct percpu_cluster\t__percpu *percpu_cluster; /* per cpu's swap location */\n \tstruct swap_sequential_cluster *global_cluster; /* Use one global cluster for rotating device */\n-\tspinlock_t global_cluster_lock;\t/* Serialize usage of global cluster */\n \tstruct rb_root swap_extent_root;/* root of the swap extent rbtree */\n \tstruct block_device *bdev;\t/* swap device or bdev of swap file */\n \tstruct file *swap_file;\t\t/* seldom referenced */\n \tstruct completion comp;\t\t/* seldom referenced */\n \tspinlock_t lock;\t\t/*\n-\t\t\t\t\t * protect map scan related fields like\n-\t\t\t\t\t * inuse_pages and all cluster lists.\n-\t\t\t\t\t * Other fields are only changed\n-\t\t\t\t\t * at swapon/swapoff, so are protected\n-\t\t\t\t\t * by swap_lock. changing flags need\n-\t\t\t\t\t * hold this lock and swap_lock. If\n-\t\t\t\t\t * both locks need hold, hold swap_lock\n-\t\t\t\t\t * first.\n+\t\t\t\t\t * Protect cluster lists. Other fields\n+\t\t\t\t\t * are only changed at swapon/swapoff,\n+\t\t\t\t\t * so are protected by swapon_rwsem.\n \t\t\t\t\t */\n \tstruct work_struct discard_work; /* discard worker */\n \tstruct work_struct reclaim_work; /* reclaim worker */\n \tstruct list_head discard_clusters; /* discard clusters list */\n-\tstruct plist_node avail_list;   /* entry in swap_avail_head */\n \tconst struct swap_ops *ops;\n };\n \ndiff --git a/lib/plist.c b/lib/plist.c\nindex b0273533c04d2a..b05ae7ffea87e8 100644\n--- a/lib/plist.c\n+++ b/lib/plist.c\n@@ -142,65 +142,6 @@ void plist_del(struct plist_node *node, struct plist_head *head)\n \tplist_check_head(head);\n }\n \n-/**\n- * plist_requeue - Requeue @node at end of same-prio entries.\n- *\n- * This is essentially an optimized plist_del() followed by\n- * plist_add().  It moves an entry already in the plist to\n- * after any other same-priority entries.\n- *\n- * @node:\t\u0026struct plist_node pointer - entry to be moved\n- * @head:\t\u0026struct plist_head pointer - list head\n- */\n-void plist_requeue(struct plist_node *node, struct plist_head *head)\n-{\n-\tstruct plist_node *iter;\n-\tstruct list_head *node_next = \u0026head-\u003enode_list;\n-\n-\tplist_check_head(head);\n-\tBUG_ON(plist_head_empty(head));\n-\tBUG_ON(plist_node_empty(node));\n-\n-\tif (node == plist_last(head))\n-\t\treturn;\n-\n-\titer = plist_next(node);\n-\n-\tif (node-\u003eprio != iter-\u003eprio)\n-\t\treturn;\n-\n-\tplist_del(node, head);\n-\n-\t/*\n-\t * After plist_del(), iter is the replacement of the node.  If the node\n-\t * was on prio_list, take shortcut to find node_next instead of looping.\n-\t *\n-\t * prio_list is a headless ring, so from the LAST bucket -\u003enext wraps\n-\t * round to the first one; in that case node_next is the list head.\n-\t */\n-\tif (!list_empty(\u0026iter-\u003eprio_list)) {\n-\t\tstruct plist_node *first = plist_first(head);\n-\n-\t\tif (iter-\u003eprio_list.next == \u0026first-\u003eprio_list)\n-\t\t\tgoto queue;\n-\t\titer = list_entry(iter-\u003eprio_list.next, struct plist_node,\n-\t\t\t\t  prio_list);\n-\t\tnode_next = \u0026iter-\u003enode_list;\n-\t\tgoto queue;\n-\t}\n-\n-\tplist_for_each_continue(iter, head) {\n-\t\tif (node-\u003eprio != iter-\u003eprio) {\n-\t\t\tnode_next = \u0026iter-\u003enode_list;\n-\t\t\tbreak;\n-\t\t}\n-\t}\n-queue:\n-\tlist_add_tail(\u0026node-\u003enode_list, node_next);\n-\n-\tplist_check_head(head);\n-}\n-\n #ifdef CONFIG_DEBUG_PLIST\n #include \u003clinux/sched.h\u003e\n #include \u003clinux/sched/clock.h\u003e\n@@ -238,14 +179,6 @@ static void __init plist_test_check(int nr_expect)\n \tBUG_ON(prio_pos-\u003eprio_list.next != \u0026first-\u003eprio_list);\n }\n \n-static void __init plist_test_requeue(struct plist_node *node)\n-{\n-\tplist_requeue(node, \u0026test_head);\n-\n-\tif (node != plist_last(\u0026test_head))\n-\t\tBUG_ON(node-\u003eprio == plist_next(node)-\u003eprio);\n-}\n-\n static int  __init plist_test(void)\n {\n \tint nr_expect = 0, i, loop;\n@@ -269,10 +202,6 @@ static int  __init plist_test(void)\n \t\t\tnr_expect--;\n \t\t}\n \t\tplist_test_check(nr_expect);\n-\t\tif (!plist_node_empty(test_node + i)) {\n-\t\t\tplist_test_requeue(test_node + i);\n-\t\t\tplist_test_check(nr_expect);\n-\t\t}\n \t}\n \n \tfor (i = 0; i \u003c ARRAY_SIZE(test_node); i++) {\ndiff --git a/mm/swap.h b/mm/swap.h\nindex d488a69c28091c..70fd3ab655ff81 100644\n--- a/mm/swap.h\n+++ b/mm/swap.h\n@@ -108,16 +108,16 @@ static inline unsigned int swp_cluster_offset(swp_entry_t entry)\n  */\n static inline struct swap_info_struct *__swap_type_to_info(int type)\n {\n-\tstruct swap_info_struct *si;\n-\n-\tsi = READ_ONCE(swap_info[type]); /* rcu_dereference() */\n-\tVM_WARN_ON_ONCE(percpu_ref_is_zero(\u0026si-\u003eusers)); /* race with swapoff */\n-\treturn si;\n+\treturn READ_ONCE(swap_info[type]); /* rcu_dereference() */\n }\n \n static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)\n {\n-\treturn __swap_type_to_info(swp_type(entry));\n+\tstruct swap_info_struct *si;\n+\n+\tsi = __swap_type_to_info(swp_type(entry)); /* rcu_dereference() */\n+\tVM_WARN_ON_ONCE(percpu_ref_is_zero(\u0026si-\u003eusers)); /* race with swapoff */\n+\treturn si;\n }\n \n static inline struct swap_cluster_info *__swap_offset_to_cluster(\ndiff --git a/mm/swapfile.c b/mm/swapfile.c\nindex fcda5eba171402..eb212813245598 100644\n--- a/mm/swapfile.c\n+++ b/mm/swapfile.c\n@@ -6,6 +6,7 @@\n  *  Swap reorganised 29.12.95, Stephen Tweedie\n  */\n \n+#include \u003clinux/bitmap.h\u003e\n #include \u003clinux/blkdev.h\u003e\n #include \u003clinux/mm.h\u003e\n #include \u003clinux/sched/mm.h\u003e\n@@ -41,7 +42,6 @@\n #include \u003clinux/completion.h\u003e\n #include \u003clinux/suspend.h\u003e\n #include \u003clinux/zswap.h\u003e\n-#include \u003clinux/plist.h\u003e\n \n #include \u003casm/tlbflush.h\u003e\n #include \u003clinux/leafops.h\u003e\n@@ -49,31 +49,38 @@\n #include \"internal.h\"\n #include \"swap.h\"\n \n-static void swap_range_alloc(struct swap_info_struct *si,\n-\t\t\t     unsigned int nr_entries);\n+static void swap_device_inuse_add(struct swap_info_struct *si,\n+\t\t\t\t  unsigned int nr_entries);\n static bool folio_swapcache_freeable(struct folio *folio);\n static void move_cluster(struct swap_info_struct *si,\n \t\t\t struct swap_cluster_info *ci, struct list_head *list,\n \t\t\t enum swap_cluster_flags new_flags);\n+static bool get_swap_device_info(struct swap_info_struct *si);\n \n /*\n- * Protects the swap_info array, and the SWP_USED flag. swap_info contains\n- * lazily allocated \u0026 freed swap device info struts, and SWP_USED indicates\n- * which device is used, ~SWP_USED devices and can be reused.\n- *\n- * Also protects swap_active_head total_swap_pages, and the SWP_WRITEOK flag.\n+ * Serializes swapon/swapoff (writers) and protects the swap_info\n+ * array, nr_swapfiles, total_swap_pages, and part of swap device\n+ * info content (see comment of swap_info_struct).  Readers\n+ * (allocation, /proc/swaps, etc.) take percpu_down_read() which\n+ * is cheap as the hot path.\n+ */\n+DEFINE_STATIC_PERCPU_RWSEM(swapon_rwsem);\n+/*\n+ * swap_info contains lazily allocated swap device info structs, and\n+ * SWP_USED indicates which device is used, ~SWP_USED devices can be\n+ * reused. Protected by swapon_rwsem, but reading could be lockless.\n  */\n-static DEFINE_SPINLOCK(swap_lock);\n+struct swap_info_struct *swap_info[MAX_SWAPFILES];\n static unsigned int nr_swapfiles;\n-atomic_long_t nr_swap_pages;\n+long total_swap_pages;\n+\n /*\n  * Some modules use swappable objects and may try to swap them out under\n  * memory pressure (via the shrinker). Before doing so, they may wish to\n  * check to see if any swap space is available.\n  */\n+atomic_long_t nr_swap_pages;\n EXPORT_SYMBOL_GPL(nr_swap_pages);\n-/* protected with swap_lock. reading in vm_swap_full() doesn't need lock */\n-long total_swap_pages;\n #define DEF_SWAP_PRIO  -1\n unsigned long swapfile_maximum_size;\n #ifdef CONFIG_MIGRATION\n@@ -83,52 +90,42 @@ bool swap_migration_ad_supported;\n static const char Bad_file[] = \"Bad swap file entry \";\n static const char Bad_offset[] = \"Bad swap offset entry \";\n \n-/*\n- * all active swap_info_structs\n- * protected with swap_lock, and ordered by priority.\n- */\n-static PLIST_HEAD(swap_active_head);\n+static inline struct swap_info_struct *__swap_iter(int *i, unsigned long flag)\n+{\n+\tlockdep_assert_held(\u0026swapon_rwsem);\n+\twhile (*i \u003c nr_swapfiles) {\n+\t\tstruct swap_info_struct *si = __swap_type_to_info(*i);\n+\n+\t\tVM_WARN_ON(!si);\n+\t\t(*i)++;\n+\t\tif (flag \u0026\u0026 !((si-\u003eflags \u0026 flag) == flag))\n+\t\t\tcontinue;\n+\t\treturn si;\n+\t}\n+\treturn NULL;\n+}\n+\n+#define __for_each_swap(si, flag)\t\t\t\\\n+\tfor (int __i = 0; ((si) = __swap_iter(\u0026__i, flag));)\n \n /*\n- * all available (active, not full) swap_info_structs\n- * protected with swap_avail_lock, ordered by priority.\n- * This is used by folio_alloc_swap() instead of swap_active_head\n- * because swap_active_head includes all swap_info_structs,\n- * but folio_alloc_swap() doesn't need to look at full ones.\n- * This uses its own lock instead of swap_lock because when a\n- * swap_info_struct changes between not-full/full, it needs to\n- * add/remove itself to/from this list, but the swap_info_struct-\u003elock\n- * is held and the locking order requires swap_lock to be taken\n- * before any swap_info_struct-\u003elock.\n+ * for_each_swap - iterate through all allocated and inuse swap devices\n+ * @si: the iterator\n+ *\n+ * Context: The caller must hold swapon_rwsem. The lock may be dropped during\n+ * the loop body but must be re-acquired before the next iteration.\n  */\n-static PLIST_HEAD(swap_avail_head);\n-static DEFINE_SPINLOCK(swap_avail_lock);\n-\n-struct swap_info_struct *swap_info[MAX_SWAPFILES];\n+#define for_each_swap(si) __for_each_swap(si, SWP_USED)\n+#define for_each_avail_swap(si) __for_each_swap(si, SWP_USED | SWP_WRITEOK)\n \n static struct kmem_cache *swap_table_cachep;\n \n-/* Protects si-\u003eswap_file for /proc/swaps usage */\n-static DEFINE_MUTEX(swapon_mutex);\n-\n static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);\n /* Activity counter to indicate that a swapon or swapoff has occurred */\n static atomic_t proc_poll_event = ATOMIC_INIT(0);\n \n atomic_t nr_rotate_swap = ATOMIC_INIT(0);\n \n-struct percpu_swap_cluster {\n-\tstruct swap_info_struct *si[SWAP_NR_ORDERS];\n-\tunsigned long offset[SWAP_NR_ORDERS];\n-\tlocal_lock_t lock;\n-};\n-\n-static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) = {\n-\t.si = { NULL },\n-\t.offset = { SWAP_ENTRY_INVALID },\n-\t.lock = INIT_LOCAL_LOCK(),\n-};\n-\n /* May return NULL on invalid type, caller must check for NULL return */\n static struct swap_info_struct *swap_type_to_info(int type)\n {\n@@ -143,18 +140,456 @@ static struct swap_info_struct *swap_entry_to_info(swp_entry_t entry)\n \treturn swap_type_to_info(swp_type(entry));\n }\n \n+/*\n+ * All available swap_info_structs are grouped by priority rings, the rings\n+ * are ordered in a queue by priority (higher prio value = higher priority).\n+ * The allocator iterates and rotates devices within each priority ring.\n+ * When all devices in a ring are iterated, it goes to the next lower\n+ * priority ring.\n+ */\n+struct swap_prio_ring {\n+\tint prio;\n+\tunsigned int size;\n+\tstruct swap_info_struct *dev[] __counted_by(size);\n+};\n+\n+/*\n+ * The ring is protected by swapon_rwsem so updating it is costly. To make\n+ * the allocator and other users skip full devices faster, the lowest bit of\n+ * a device pointer is used to mark it disabled (temporarily unavailable).\n+ * This relies on the natural alignment of struct swap_info_struct.\n+ */\n+#define SWAP_DEVICE_MASKED_SHIFT\t0\n+#define SWAP_DEVICE_MASKED_BIT\t\tBIT(SWAP_DEVICE_MASKED_SHIFT)\n+static_assert(__alignof__(struct swap_info_struct) \u003e= 2);\n+\n+/*\n+ * Serializes queue content mutations and keeps SWAP_USAGE_OFFLIST_BIT\n+ * consistent with the masked state of each device pointer.\n+ */\n+static DEFINE_SPINLOCK(swap_queue_update_lock);\n+\n+/*\n+ * Swap queue is protected by both swap_queue_update_lock and swapon_rwsem.\n+ * Only swapon/swapoff will take the write lock, and modify the queue length\n+ * or any ring's length. swap_queue_update_lock protects the content so\n+ * devices can be masked easily without taking the writelock, which is heavy.\n+ */\n+static struct swap_prio_ring **swap_queue;\n+static unsigned int swap_queue_len;\n+\n+/*\n+ * Each CPU has its read iterator, so the queue itself will remain read\n+ * only and the CPU side reader rotates by iterating the devices\n+ * periodically using the counter.\n+ */\n+#define SWAP_ROUND_ROBIN_QUOTA SWAPFILE_CLUSTER\n+struct swap_ring_iterator {\n+\tint offset;\n+\tlong rr_counter;\n+};\n+\n+struct swap_queue_reader {\n+\tlocal_lock_t lock;\n+\tstruct swap_ring_iterator ri[];\n+};\n+\n+struct swap_queue_cursor {\n+\tbool ring_only;\n+\tunsigned int ring_idx;\n+\tunsigned int offset;\n+\tunsigned int nr_iter;\n+};\n+\n+static __percpu struct swap_queue_reader *swap_queue_readers;\n+/* Keep the high-water capacity until the last priority ring is removed. */\n+static unsigned int swap_queue_readers_capacity;\n+\n+static inline bool swap_device_masked(struct swap_info_struct *si)\n+{\n+\treturn (unsigned long)si \u0026 SWAP_DEVICE_MASKED_BIT;\n+}\n+\n+static inline struct swap_info_struct *swap_device_mask_ptr(struct swap_info_struct *si)\n+{\n+\treturn (struct swap_info_struct *)((unsigned long)si |\n+\t\t\t\t\t   SWAP_DEVICE_MASKED_BIT);\n+}\n+\n+static inline struct swap_info_struct *swap_device_unmask_ptr(struct swap_info_struct *si)\n+{\n+\treturn (struct swap_info_struct *)((unsigned long)si \u0026 ~SWAP_DEVICE_MASKED_BIT);\n+}\n+\n+static struct swap_queue_reader __percpu *swap_queue_prealloc_readers(int nr_rings, gfp_t gfp)\n+{\n+\tstruct swap_queue_reader __percpu *readers;\n+\n+\tif (!nr_rings)\n+\t\treturn NULL;\n+\n+\treaders = __alloc_percpu_gfp(struct_size(readers, ri, nr_rings),\n+\t\t\t\t     __alignof__(*readers), gfp);\n+\treturn readers;\n+}\n+\n+static bool swap_queue_needs_readers(int prio)\n+{\n+\tunsigned int i;\n+\n+\tlockdep_assert_held_write(\u0026swapon_rwsem);\n+\tfor (i = 0; i \u003c swap_queue_len; i++) {\n+\t\tif (swap_queue[i]-\u003eprio == prio)\n+\t\t\treturn false;\n+\t}\n+\n+\treturn swap_queue_len \u003e= swap_queue_readers_capacity;\n+}\n+\n+/*\n+ * Return with swapon_rwsem held for writing, or unlocked on allocation failure.\n+ * Per-CPU backing allocations may reclaim, so prepare them before publishing\n+ * the device and outside the topology lock and our noreclaim scope. Keep NOIO\n+ * because the swapon caller still holds the swapfile's inode lock.\n+ */\n+static int swap_queue_lock_for_add(int prio,\n+\t\t\t\t   struct swap_queue_reader __percpu **readers,\n+\t\t\t\t   unsigned int *nr_readers)\n+{\n+\t*readers = NULL;\n+\t*nr_readers = 0;\n+\tfor (;;) {\n+\t\tpercpu_down_write(\u0026swapon_rwsem);\n+\t\tif (!swap_queue_needs_readers(prio) ||\n+\t\t    *nr_readers \u003e swap_queue_len)\n+\t\t\treturn 0;\n+\n+\t\t*nr_readers = swap_queue_len + 1;\n+\t\tpercpu_up_write(\u0026swapon_rwsem);\n+\t\tfree_percpu(*readers);\n+\t\t*readers = swap_queue_prealloc_readers(*nr_readers, GFP_NOIO);\n+\t\tif (!*readers)\n+\t\t\treturn -ENOMEM;\n+\t}\n+}\n+\n+static void swap_queue_reset_readers(void)\n+{\n+\tint ring_idx, cpu;\n+\tstruct swap_prio_ring *ring;\n+\n+\tlockdep_assert_held_write(\u0026swapon_rwsem);\n+\t/* A new topology starts a fresh, distributed rotation on every CPU. */\n+\tfor_each_possible_cpu(cpu) {\n+\t\tfor (ring_idx = 0; ring_idx \u003c swap_queue_len; ring_idx++) {\n+\t\t\tring = swap_queue[ring_idx];\n+\t\t\tper_cpu_ptr(swap_queue_readers, cpu)-\u003eri[ring_idx].offset =\n+\t\t\t\t    cpu % ring-\u003esize;\n+\t\t\tper_cpu_ptr(swap_queue_readers, cpu)-\u003eri[ring_idx].rr_counter =\n+\t\t\t\t    SWAP_ROUND_ROBIN_QUOTA;\n+\t\t}\n+\t}\n+}\n+\n+static void swap_queue_install_readers(struct swap_queue_reader __percpu *readers,\n+\t\t\t\t       unsigned int capacity)\n+{\n+\tint cpu;\n+\n+\tlockdep_assert_held_write(\u0026swapon_rwsem);\n+\tfree_percpu(swap_queue_readers);\n+\tswap_queue_readers = readers;\n+\tswap_queue_readers_capacity = capacity;\n+\tif (!readers)\n+\t\treturn;\n+\n+\tfor_each_possible_cpu(cpu)\n+\t\tlocal_lock_init(\u0026per_cpu_ptr(readers, cpu)-\u003elock);\n+\tswap_queue_reset_readers();\n+}\n+\n+static struct swap_info_struct *\n+swap_queue_get_device(long nr_alloc, struct swap_queue_cursor *cursor)\n+{\n+\tbool rotate = false;\n+\tstruct swap_info_struct *si;\n+\tstruct swap_ring_iterator *ri;\n+\tstruct swap_prio_ring *ring;\n+\tunsigned int dev_idx, queue_idx, nr_iter;\n+\n+\tqueue_idx = cursor-\u003ering_idx;\n+\tif (queue_idx \u003e= swap_queue_len)\n+\t\treturn ERR_PTR(-ENOENT);\n+\n+\tring = swap_queue[queue_idx];\n+\tif (cursor-\u003enr_iter \u003e= ring-\u003esize) {\n+\t\tif (cursor-\u003ering_only)\n+\t\t\treturn ERR_PTR(-E2BIG);\n+\t\tqueue_idx = ++cursor-\u003ering_idx;\n+\t\tif (queue_idx \u003e= swap_queue_len)\n+\t\t\treturn ERR_PTR(-ENOENT);\n+\t\tcursor-\u003enr_iter = 0;\n+\t\tring = swap_queue[queue_idx];\n+\t}\n+\n+\t/* Consume masked peers too, so every walk remains bounded. */\n+\tnr_iter = cursor-\u003enr_iter++;\n+\tif (ring-\u003esize == 1) {\n+\t\tsi = READ_ONCE(ring-\u003edev[0]);\n+\t\tgoto check_device;\n+\t}\n+\n+\tlocal_lock(\u0026swap_queue_readers-\u003elock);\n+\tri = this_cpu_ptr(\u0026swap_queue_readers-\u003eri[queue_idx]);\n+\t/*\n+\t * Snapshot the starting offset for this allocation's walk. The shared\n+\t * iterator can move between retries, but the cursor must visit every\n+\t * device in the ring exactly once before falling through.\n+\t */\n+\tif (!nr_iter) {\n+\t\tif (ri-\u003err_counter \u003c nr_alloc)\n+\t\t\trotate = true;\n+\t\telse if (ri-\u003eoffset \u003e= ring-\u003esize)\n+\t\t\trotate = true;\n+\t\tif (rotate) {\n+\t\t\tri-\u003eoffset++;\n+\t\t\tri-\u003eoffset %= ring-\u003esize;\n+\t\t\tri-\u003err_counter = SWAP_ROUND_ROBIN_QUOTA;\n+\t\t}\n+\t\tcursor-\u003eoffset = ri-\u003eoffset;\n+\t}\n+\n+\tdev_idx = (cursor-\u003eoffset + nr_iter) % ring-\u003esize;\n+\tif (nr_iter) {\n+\t\tri-\u003eoffset = dev_idx;\n+\t\tri-\u003err_counter = SWAP_ROUND_ROBIN_QUOTA;\n+\t}\n+\tri-\u003err_counter -= nr_alloc;\n+\tsi = READ_ONCE(ring-\u003edev[dev_idx]);\n+\tlocal_unlock(\u0026swap_queue_readers-\u003elock);\n+\n+check_device:\n+\tif (swap_device_masked(si))\n+\t\treturn ERR_PTR(-EBUSY);\n+\n+\tsi = swap_device_unmask_ptr(si);\n+\treturn si;\n+}\n+\n+static bool swap_queue_find(struct swap_info_struct *si,\n+\t\t\t    unsigned int *ring_idx, unsigned int *dev_idx)\n+{\n+\tunsigned int i, j;\n+\tstruct swap_prio_ring *ring;\n+\n+\tlockdep_assert(lockdep_is_held(\u0026swapon_rwsem) ||\n+\t\t       lockdep_is_held(\u0026swap_queue_update_lock));\n+\n+\tfor (i = 0; i \u003c swap_queue_len; i++) {\n+\t\tring = swap_queue[i];\n+\t\tif (ring-\u003eprio != si-\u003eprio)\n+\t\t\tcontinue;\n+\t\tfor (j = 0; j \u003c ring-\u003esize; j++) {\n+\t\t\tif (swap_device_unmask_ptr(READ_ONCE(ring-\u003edev[j])) != si)\n+\t\t\t\tcontinue;\n+\t\t\t*ring_idx = i;\n+\t\t\t*dev_idx = j;\n+\t\t\treturn true;\n+\t\t}\n+\t}\n+\treturn false;\n+}\n+\n+static void swap_queue_mask(struct swap_info_struct *si)\n+{\n+\tunsigned int ring_idx, dev_idx;\n+\n+\tlockdep_assert_held(\u0026swap_queue_update_lock);\n+\tif (swap_queue_find(si, \u0026ring_idx, \u0026dev_idx))\n+\t\tWRITE_ONCE(swap_queue[ring_idx]-\u003edev[dev_idx],\n+\t\t\t   swap_device_mask_ptr(si));\n+}\n+\n+static void swap_queue_unmask(struct swap_info_struct *si)\n+{\n+\tunsigned int ring_idx, dev_idx;\n+\n+\tlockdep_assert_held(\u0026swap_queue_update_lock);\n+\tif (swap_queue_find(si, \u0026ring_idx, \u0026dev_idx))\n+\t\tWRITE_ONCE(swap_queue[ring_idx]-\u003edev[dev_idx], si);\n+}\n+\n+/* Prepared readers remain caller-owned unless installed successfully. */\n+static int swap_queue_add(struct swap_info_struct *si,\n+\t\t\t  struct swap_queue_reader __percpu **readers,\n+\t\t\t  unsigned int nr_readers)\n+{\n+\tstruct swap_prio_ring **new_queue = NULL, **old_queue = NULL;\n+\tstruct swap_prio_ring *ring, *new_ring = NULL, *old_ring = NULL;\n+\tint prio = si-\u003eprio;\n+\tint i, pos, err = -ENOMEM;\n+\tunsigned int noreclaim_flag;\n+\tgfp_t gfp;\n+\n+\t/* A writer must not reclaim into another swap allocation. */\n+\tgfp = GFP_NOIO | __GFP_HIGH | __GFP_NOMEMALLOC;\n+\tlockdep_assert_held_write(\u0026swapon_rwsem);\n+\tnoreclaim_flag = memalloc_noreclaim_save();\n+\n+\tfor (pos = 0; pos \u003c swap_queue_len; pos++) {\n+\t\tif (swap_queue[pos]-\u003eprio == prio)\n+\t\t\tgoto add_to_ring;\n+\t\tif (swap_queue[pos]-\u003eprio \u003c prio)\n+\t\t\tbreak;\n+\t}\n+\n+\t/* No ring at this priority: insert a new one at pos. */\n+\tif (swap_queue_len \u003e= swap_queue_readers_capacity \u0026\u0026\n+\t    (!*readers || nr_readers \u003c= swap_queue_len))\n+\t\tgoto failed;\n+\tnew_queue = kmalloc_array(swap_queue_len + 1, sizeof(*swap_queue), gfp);\n+\tif (!new_queue)\n+\t\tgoto failed;\n+\tnew_ring = kmalloc(struct_size(new_ring, dev, 1), gfp);\n+\tif (!new_ring)\n+\t\tgoto failed;\n+\tif (!get_swap_device_info(si))\n+\t\tgoto failed;\n+\n+\tnew_ring-\u003eprio = prio;\n+\tnew_ring-\u003esize = 1;\n+\tnew_ring-\u003edev[0] = si;\n+\tfor (i = 0; i \u003c pos; i++)\n+\t\tnew_queue[i] = swap_queue[i];\n+\tnew_queue[pos] = new_ring;\n+\tfor (i = pos; i \u003c swap_queue_len; i++)\n+\t\tnew_queue[i + 1] = swap_queue[i];\n+\n+\tspin_lock(\u0026swap_queue_update_lock);\n+\told_queue = swap_queue;\n+\tswap_queue = new_queue;\n+\tswap_queue_len++;\n+\tspin_unlock(\u0026swap_queue_update_lock);\n+\tmemalloc_noreclaim_restore(noreclaim_flag);\n+\tkfree(old_queue);\n+\n+\tif (swap_queue_len \u003e swap_queue_readers_capacity) {\n+\t\tswap_queue_install_readers(*readers, nr_readers);\n+\t\t*readers = NULL;\n+\t} else {\n+\t\tswap_queue_reset_readers();\n+\t}\n+\treturn 0;\n+\n+add_to_ring:\n+\tring = swap_queue[pos];\n+\tnew_ring = kmalloc(struct_size(ring, dev, ring-\u003esize + 1), gfp);\n+\tif (!new_ring)\n+\t\tgoto failed;\n+\tif (!get_swap_device_info(si))\n+\t\tgoto failed;\n+\tspin_lock(\u0026swap_queue_update_lock);\n+\tmemcpy(new_ring, ring, struct_size(ring, dev, ring-\u003esize));\n+\tnew_ring-\u003esize++;\n+\tnew_ring-\u003edev[new_ring-\u003esize - 1] = si;\n+\told_ring = swap_queue[pos];\n+\tswap_queue[pos] = new_ring;\n+\tspin_unlock(\u0026swap_queue_update_lock);\n+\tmemalloc_noreclaim_restore(noreclaim_flag);\n+\tkfree(old_ring);\n+\tswap_queue_reset_readers();\n+\treturn 0;\n+\n+failed:\n+\tmemalloc_noreclaim_restore(noreclaim_flag);\n+\tkfree(new_queue);\n+\tkfree(new_ring);\n+\treturn err;\n+}\n+\n+static void swap_queue_del(struct swap_info_struct *si)\n+{\n+\tgfp_t gfp;\n+\tunsigned int noreclaim_flag;\n+\tunsigned int ring_idx, dev_idx;\n+\tstruct swap_prio_ring *ring, *new_ring = NULL, *old_ring = NULL;\n+\tstruct swap_prio_ring **new_queue = NULL, **old_queue = NULL;\n+\n+\tlockdep_assert_held_write(\u0026swapon_rwsem);\n+\tif (!swap_queue_find(si, \u0026ring_idx, \u0026dev_idx)) {\n+\t\tWARN_ON(1);\n+\t\treturn;\n+\t}\n+\n+\t/*\n+\t * Shrinking the small topology arrays is optional. Keep reader capacity\n+\t * until the queue is empty: per-CPU allocation must not run under this\n+\t * writer's noreclaim scope, which can grant backing pages reserve access.\n+\t */\n+\tgfp = GFP_NOIO | __GFP_HIGH | __GFP_NOMEMALLOC;\n+\tnoreclaim_flag = memalloc_noreclaim_save();\n+\tring = swap_queue[ring_idx];\n+\tif (ring-\u003esize \u003e 1)\n+\t\tnew_ring = kmalloc(struct_size(ring, dev, ring-\u003esize - 1), gfp);\n+\tif (ring-\u003esize == 1 \u0026\u0026 swap_queue_len \u003e 1) {\n+\t\tnew_queue = kmalloc(sizeof(*swap_queue) *\n+\t\t\t\t    (swap_queue_len - 1), gfp);\n+\t}\n+\tmemalloc_noreclaim_restore(noreclaim_flag);\n+\n+\tspin_lock(\u0026swap_queue_update_lock);\n+\tif (ring-\u003esize \u003e 1) {\n+\t\t/* Shift trailing devices left to fill the gap. */\n+\t\twhile (++dev_idx \u003c ring-\u003esize)\n+\t\t\tring-\u003edev[dev_idx - 1] =\n+\t\t\t\tring-\u003edev[dev_idx];\n+\t\tring-\u003esize--;\n+\t\tif (new_ring) {\n+\t\t\tmemcpy(new_ring, ring,\n+\t\t\t       struct_size(ring, dev, ring-\u003esize));\n+\t\t\told_ring = ring;\n+\t\t\tswap_queue[ring_idx] = new_ring;\n+\t\t}\n+\t} else {\n+\t\t/* Last device in this ring: remove the ring. */\n+\t\told_ring = ring;\n+\t\tswap_queue_len--;\n+\t\twhile (++ring_idx \u003c= swap_queue_len)\n+\t\t\tswap_queue[ring_idx - 1] =\n+\t\t\t\tswap_queue[ring_idx];\n+\t\tif (new_queue) {\n+\t\t\tmemcpy(new_queue, swap_queue,\n+\t\t\t       sizeof(*swap_queue) * swap_queue_len);\n+\t\t\told_queue = swap_queue;\n+\t\t\tswap_queue = new_queue;\n+\t\t} else if (!swap_queue_len) {\n+\t\t\told_queue = swap_queue;\n+\t\t\tswap_queue = NULL;\n+\t\t}\n+\t\tif (!swap_queue_len)\n+\t\t\tswap_queue_install_readers(NULL, 0);\n+\t}\n+\tspin_unlock(\u0026swap_queue_update_lock);\n+\tif (swap_queue_len)\n+\t\tswap_queue_reset_readers();\n+\n+\tkfree(old_ring);\n+\tkfree(old_queue);\n+\tput_swap_device(si);\n+}\n+\n /*\n  * Use the second highest bit of inuse_pages counter as the indicator\n- * if one swap device is on the available plist, so the atomic can\n+ * if one swap device is unavailable for allocation, so the atomic can\n  * still be updated arithmetically while having special data embedded.\n  *\n  * inuse_pages counter is the only thing indicating if a device should\n- * be on avail_lists or not (except swapon / swapoff). By embedding the\n- * off-list bit in the atomic counter, updates no longer need any lock\n- * to check the list status.\n+ * be in the available queue or not (except swapon / swapoff). By\n+ * embedding the off-list bit in the atomic counter, updates no longer\n+ * need any lock to check the list status.\n  *\n- * This bit will be set if the device is not on the plist and not\n- * usable, will be cleared if the device is on the plist.\n+ * This bit will be set if the device is not in the available queue\n+ * and not usable, will be cleared if the device is in the queue.\n  */\n #define SWAP_USAGE_OFFLIST_BIT (1UL \u003c\u003c (BITS_PER_TYPE(atomic_long_t) - 2))\n #define SWAP_USAGE_COUNTER_MASK (~SWAP_USAGE_OFFLIST_BIT)\n@@ -163,6 +598,26 @@ static long swap_usage_in_pages(struct swap_info_struct *si)\n \treturn atomic_long_read(\u0026si-\u003einuse_pages) \u0026 SWAP_USAGE_COUNTER_MASK;\n }\n \n+/*\n+ * Serialize the allocation on single CPU or globally to avoid\n+ * fragmentation and make the workflow easier to follow.\n+ */\n+static void swap_alloc_lock_device(struct swap_info_struct *si)\n+{\n+\tif (si-\u003eflags \u0026 SWP_SOLIDSTATE)\n+\t\tlocal_lock(\u0026si-\u003epercpu_cluster-\u003elock);\n+\telse\n+\t\tspin_lock(\u0026si-\u003eglobal_cluster-\u003elock);\n+}\n+\n+static void swap_alloc_unlock_device(struct swap_info_struct *si)\n+{\n+\tif (si-\u003eflags \u0026 SWP_SOLIDSTATE)\n+\t\tlocal_unlock(\u0026si-\u003epercpu_cluster-\u003elock);\n+\telse\n+\t\tspin_unlock(\u0026si-\u003eglobal_cluster-\u003elock);\n+}\n+\n /* Reclaim the swap entry anyway if possible */\n #define TTRS_ANYWAY\t\t0x1\n /*\n@@ -494,11 +949,8 @@ static int swap_cluster_alloc_table(struct swap_info_struct *si,\n \n lock:\n \tif (!locked) {\n-\t\tif (si) {\n-\t\t\tlocal_lock(\u0026percpu_swap_cluster.lock);\n-\t\t\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE))\n-\t\t\t\tspin_lock(\u0026si-\u003eglobal_cluster_lock);\n-\t\t}\n+\t\tif (si)\n+\t\t\tswap_alloc_lock_device(si);\n \t\tspin_lock(\u0026ci-\u003elock);\n \t}\n \tlockdep_assert_held(\u0026ci-\u003elock);\n@@ -569,22 +1021,24 @@ static void swap_cluster_assert_empty(struct swap_cluster_info *ci,\n }\n \n /*\n- * Allocate swap table for one cluster. Attempt an atomic allocation first,\n- * then fallback to sleeping allocation.\n+ * Allocate swap table for one cluster. Attempt allocation under the locks\n+ * first, then retry with the locks dropped without entering direct reclaim.\n  */\n static struct swap_cluster_info *\n swap_cluster_populate(struct swap_info_struct *si,\n \t\t\t struct swap_cluster_info *ci)\n {\n+\tgfp_t gfp;\n \tint ret;\n \n \t/*\n \t * Only cluster isolation from the allocator does table allocation.\n \t * Swap allocator uses percpu clusters and holds the local lock.\n \t */\n-\tlockdep_assert_held(\u0026this_cpu_ptr(\u0026percpu_swap_cluster)-\u003elock);\n-\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE))\n-\t\tlockdep_assert_held(\u0026si-\u003eglobal_cluster_lock);\n+\tif (si-\u003eflags \u0026 SWP_SOLIDSTATE)\n+\t\tlockdep_assert_held(this_cpu_ptr(\u0026si-\u003epercpu_cluster-\u003elock));\n+\telse\n+\t\tlockdep_assert_held(\u0026si-\u003eglobal_cluster-\u003elock);\n \tlockdep_assert_held(\u0026ci-\u003elock);\n \n \tif (!swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |\n@@ -592,17 +1046,18 @@ swap_cluster_populate(struct swap_info_struct *si,\n \t\treturn ci;\n \n \t/*\n-\t * Try a sleep allocation. Each isolated free cluster may cause\n-\t * a sleep allocation, but there is a limited number of them, so\n-\t * the potential recursive allocation is limited.\n+\t * Retry with the local and cluster locks dropped. The allocator can\n+\t * still hold swapon_rwsem for reading: direct reclaim could enter\n+\t * swap allocation again while a writer is waiting for this reader.\n+\t * Restrict this request instead of granting the task PF_MEMALLOC,\n+\t * which could give allocator hooks and failure cleanup reserve access.\n \t */\n \tspin_unlock(\u0026ci-\u003elock);\n-\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE))\n-\t\tspin_unlock(\u0026si-\u003eglobal_cluster_lock);\n-\tlocal_unlock(\u0026percpu_swap_cluster.lock);\n+\tswap_alloc_unlock_device(si);\n \n-\tret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |\n-\t\t\t\t\t     GFP_KERNEL, false);\n+\tgfp = (GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC) \u0026\n+\t\t~__GFP_DIRECT_RECLAIM;\n+\tret = swap_cluster_alloc_table(si, ci, gfp, false);\n \n \t/*\n \t * Back to atomic context. We might have migrated to a new CPU with a\n@@ -705,44 +1160,40 @@ static struct swap_cluster_info *isolate_lock_cluster(\n }\n \n /*\n- * Doing discard actually. After a cluster discard is finished, the cluster\n- * will be added to free cluster list. Discard cluster is a bit special as\n- * they don't participate in allocation or reclaim, so clusters marked as\n- * CLUSTER_FLAG_DISCARD must remain off-list or on discard list.\n+ * Discard one cluster. After the discard is finished, the cluster will be\n+ * added to the free cluster list. Discard clusters are special because they\n+ * don't participate in allocation or reclaim, so CLUSTER_FLAG_DISCARD must\n+ * remain set while a cluster is either queued or being discarded.\n  */\n-static bool swap_do_scheduled_discard(struct swap_info_struct *si)\n+static bool swap_discard_one_cluster(struct swap_info_struct *si)\n {\n \tstruct swap_cluster_info *ci;\n-\tbool ret = false;\n \tunsigned int idx;\n \n \tspin_lock(\u0026si-\u003elock);\n-\twhile (!list_empty(\u0026si-\u003ediscard_clusters)) {\n-\t\tci = list_first_entry(\u0026si-\u003ediscard_clusters, struct swap_cluster_info, list);\n-\t\t/*\n-\t\t * Delete the cluster from list to prepare for discard, but keep\n-\t\t * the CLUSTER_FLAG_DISCARD flag, percpu_swap_cluster could be\n-\t\t * pointing to it, or ran into by relocate_cluster.\n-\t\t */\n-\t\tlist_del(\u0026ci-\u003elist);\n-\t\tidx = cluster_index(si, ci);\n+\tif (list_empty(\u0026si-\u003ediscard_clusters)) {\n \t\tspin_unlock(\u0026si-\u003elock);\n-\t\tdiscard_swap_cluster(si, idx * SWAPFILE_CLUSTER,\n-\t\t\t\tSWAPFILE_CLUSTER);\n-\n-\t\tspin_lock(\u0026ci-\u003elock);\n-\t\t/*\n-\t\t * Discard is done, clear its flags as it's off-list, then\n-\t\t * return the cluster to allocation list.\n-\t\t */\n-\t\tci-\u003eflags = CLUSTER_FLAG_NONE;\n-\t\t__free_cluster(si, ci);\n-\t\tspin_unlock(\u0026ci-\u003elock);\n-\t\tret = true;\n-\t\tspin_lock(\u0026si-\u003elock);\n+\t\treturn false;\n \t}\n+\n+\tci = list_first_entry(\u0026si-\u003ediscard_clusters,\n+\t\t\t      struct swap_cluster_info, list);\n+\t/*\n+\t * Delete the cluster from the list, but keep CLUSTER_FLAG_DISCARD\n+\t * set while the discard is in flight. A percpu cluster may still\n+\t * point to it, or relocate_cluster() may encounter it.\n+\t */\n+\tlist_del(\u0026ci-\u003elist);\n+\tidx = cluster_index(si, ci);\n \tspin_unlock(\u0026si-\u003elock);\n-\treturn ret;\n+\n+\tdiscard_swap_cluster(si, idx * SWAPFILE_CLUSTER, SWAPFILE_CLUSTER);\n+\n+\tspin_lock(\u0026ci-\u003elock);\n+\tci-\u003eflags = CLUSTER_FLAG_NONE;\n+\t__free_cluster(si, ci);\n+\tspin_unlock(\u0026ci-\u003elock);\n+\treturn true;\n }\n \n static void swap_discard_work(struct work_struct *work)\n@@ -751,7 +1202,8 @@ static void swap_discard_work(struct work_struct *work)\n \n \tsi = container_of(work, struct swap_info_struct, discard_work);\n \n-\tswap_do_scheduled_discard(si);\n+\twhile (swap_discard_one_cluster(si))\n+\t\tcond_resched();\n }\n \n static void swap_users_ref_free(struct percpu_ref *ref)\n@@ -1017,7 +1469,7 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,\n \tif (cluster_is_empty(ci))\n \t\tci-\u003eorder = order;\n \tci-\u003ecount += nr_pages;\n-\tswap_range_alloc(si, nr_pages);\n+\tswap_device_inuse_add(si, nr_pages);\n \n \treturn true;\n }\n@@ -1076,12 +1528,10 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,\n out:\n \trelocate_cluster(si, ci);\n \tswap_cluster_unlock(ci);\n-\tif (si-\u003eflags \u0026 SWP_SOLIDSTATE) {\n-\t\tthis_cpu_write(percpu_swap_cluster.offset[order], next);\n-\t\tthis_cpu_write(percpu_swap_cluster.si[order], si);\n-\t} else {\n+\tif (si-\u003eflags \u0026 SWP_SOLIDSTATE)\n+\t\tthis_cpu_write(si-\u003epercpu_cluster-\u003enext[order], next);\n+\telse\n \t\tsi-\u003eglobal_cluster-\u003enext[order] = next;\n-\t}\n \treturn found;\n }\n \n@@ -1182,13 +1632,13 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,\n \tif (order \u0026\u0026 !(si-\u003eflags \u0026 SWP_BLKDEV))\n \t\treturn 0;\n \n-\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE)) {\n-\t\t/* Serialize HDD SWAP allocation for each device. */\n-\t\tspin_lock(\u0026si-\u003eglobal_cluster_lock);\n+\tswap_alloc_lock_device(si);\n+\tif (si-\u003eflags \u0026 SWP_SOLIDSTATE)\n+\t\toffset = __this_cpu_read(si-\u003epercpu_cluster-\u003enext[order]);\n+\telse\n \t\toffset = si-\u003eglobal_cluster-\u003enext[order];\n-\t\tif (offset == SWAP_ENTRY_INVALID)\n-\t\t\tgoto new_cluster;\n \n+\tif (offset != SWAP_ENTRY_INVALID) {\n \t\tci = swap_cluster_lock(si, offset);\n \t\t/* Cluster could have been used by another order */\n \t\tif (cluster_is_usable(ci, order)) {\n@@ -1202,7 +1652,6 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,\n \t\t\tgoto done;\n \t}\n \n-new_cluster:\n \tif (swap_prefer_free_cluster(si)) {\n \t\tfound = alloc_swap_scan_list(si, \u0026si-\u003efree_clusters, folio, false);\n \t\tif (found)\n@@ -1255,8 +1704,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,\n \t\t\tgoto done;\n \t}\n done:\n-\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE))\n-\t\tspin_unlock(\u0026si-\u003eglobal_cluster_lock);\n+\tswap_alloc_unlock_device(si);\n \n \treturn found;\n }\n@@ -1266,54 +1714,47 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)\n {\n \tunsigned long pages;\n \n-\tspin_lock(\u0026swap_avail_lock);\n+\tspin_lock(\u0026swap_queue_update_lock);\n \n-\tif (swapoff) {\n-\t\t/*\n-\t\t * Forcefully remove it. Clear the SWP_WRITEOK flags for\n-\t\t * swapoff here so it's synchronized by both si-\u003elock and\n-\t\t * swap_avail_lock, to ensure the result can be seen by\n-\t\t * add_to_avail_list.\n-\t\t */\n-\t\tlockdep_assert_held(\u0026si-\u003elock);\n-\t\tsi-\u003eflags \u0026= ~SWP_WRITEOK;\n-\t\tatomic_long_or(SWAP_USAGE_OFFLIST_BIT, \u0026si-\u003einuse_pages);\n-\t} else {\n-\t\t/*\n-\t\t * If not called by swapoff, take it off-list only if it's\n-\t\t * full and SWAP_USAGE_OFFLIST_BIT is not set (strictly\n-\t\t * si-\u003einuse_pages == pages), any concurrent slot freeing,\n-\t\t * or device already removed from plist by someone else\n-\t\t * will make this return false.\n-\t\t */\n+\t/*\n+\t * Force remove it only for swapoff. Else, take it off-list only if\n+\t * it's full and SWAP_USAGE_OFFLIST_BIT is not set (strictly\n+\t * si-\u003einuse_pages == pages), so concurrent slot freeing, or\n+\t * concurrent list removal will make the cmpxchg fail and skip\n+\t * the removal.\n+\t */\n+\tif (!swapoff) {\n \t\tpages = si-\u003epages;\n \t\tif (!atomic_long_try_cmpxchg(\u0026si-\u003einuse_pages, \u0026pages,\n \t\t\t\t\t     pages | SWAP_USAGE_OFFLIST_BIT))\n \t\t\tgoto skip;\n+\t} else {\n+\t\tlockdep_assert_held_write(\u0026swapon_rwsem);\n+\t\tlockdep_assert_held(\u0026si-\u003elock);\n+\t\tsi-\u003eflags \u0026= ~SWP_WRITEOK;\n+\t\tatomic_long_or(SWAP_USAGE_OFFLIST_BIT, \u0026si-\u003einuse_pages);\n \t}\n \n-\tplist_del(\u0026si-\u003eavail_list, \u0026swap_avail_head);\n-\n+\tswap_queue_mask(si);\n skip:\n-\tspin_unlock(\u0026swap_avail_lock);\n+\tspin_unlock(\u0026swap_queue_update_lock);\n }\n \n /* SWAP_USAGE_OFFLIST_BIT can only be cleared by this helper. */\n-static void add_to_avail_list(struct swap_info_struct *si, bool swapon)\n+static void add_to_avail_list(struct swap_info_struct *si)\n {\n \tlong val;\n \tunsigned long pages;\n \n-\tspin_lock(\u0026swap_avail_lock);\n+\tspin_lock(\u0026swap_queue_update_lock);\n \n-\t/* Corresponding to SWP_WRITEOK clearing in del_from_avail_list */\n-\tif (swapon) {\n-\t\tlockdep_assert_held(\u0026si-\u003elock);\n-\t\tsi-\u003eflags |= SWP_WRITEOK;\n-\t} else {\n-\t\tif (!(READ_ONCE(si-\u003eflags) \u0026 SWP_WRITEOK))\n-\t\t\tgoto skip;\n-\t}\n+\t/*\n+\t * Mark the device as avail if SWP_WRITEOK is set. Swapoff clears\n+\t * SWP_WRITEOK first, so check that first so the device won't be\n+\t * re-added after swapoff started.\n+\t */\n+\tif (!(si-\u003eflags \u0026 SWP_WRITEOK))\n+\t\tgoto skip;\n \n \tif (!(atomic_long_read(\u0026si-\u003einuse_pages) \u0026 SWAP_USAGE_OFFLIST_BIT))\n \t\tgoto skip;\n@@ -1321,72 +1762,55 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)\n \tval = atomic_long_fetch_and_relaxed(~SWAP_USAGE_OFFLIST_BIT, \u0026si-\u003einuse_pages);\n \n \t/*\n-\t * When device is full and device is on the plist, only one updater will\n-\t * see (inuse_pages == si-\u003epages) and will call del_from_avail_list. If\n-\t * that updater happen to be here, just skip adding.\n+\t * When device is full and marked as available, one reader will see\n+\t * (inuse_pages == si-\u003epages) and should mark it as unavailable and\n+\t * set SWAP_USAGE_OFFLIST_BIT. If that updater happens to be here, just\n+\t * skip the rest.\n \t */\n \tpages = si-\u003epages;\n-\tif (val == pages) {\n+\tif ((val \u0026 SWAP_USAGE_COUNTER_MASK) == pages) {\n \t\t/* Just like the cmpxchg in del_from_avail_list */\n \t\tif (atomic_long_try_cmpxchg(\u0026si-\u003einuse_pages, \u0026pages,\n \t\t\t\t\t    pages | SWAP_USAGE_OFFLIST_BIT))\n \t\t\tgoto skip;\n \t}\n \n-\tplist_add(\u0026si-\u003eavail_list, \u0026swap_avail_head);\n-\n+\tswap_queue_unmask(si);\n skip:\n-\tspin_unlock(\u0026swap_avail_lock);\n+\tspin_unlock(\u0026swap_queue_update_lock);\n }\n \n /*\n- * swap_usage_add / swap_usage_sub of each slot are serialized by ci-\u003elock\n- * within each cluster, so the total contribution to the global counter should\n- * always be positive and cannot exceed the total number of usable slots.\n+ * swap_device_inuse_add / swap_device_inuse_sub are called within cluster\n+ * update critical sections and serialized by ci-\u003elock within each cluster,\n+ * so the total contribution to the global counter should always be positive\n+ * and cannot exceed the total number of usable slots.\n  */\n-static bool swap_usage_add(struct swap_info_struct *si, unsigned int nr_entries)\n+static void swap_device_inuse_add(struct swap_info_struct *si,\n+\t\t\t\t  unsigned int nr_entries)\n {\n-\tlong val = atomic_long_add_return_relaxed(nr_entries, \u0026si-\u003einuse_pages);\n+\tlong inuse_pages;\n \n \t/*\n \t * If device is full, and SWAP_USAGE_OFFLIST_BIT is not set,\n-\t * remove it from the plist.\n+\t * mark it unavailable.\n \t */\n-\tif (unlikely(val == si-\u003epages)) {\n-\t\tdel_from_avail_list(si, false);\n-\t\treturn true;\n-\t}\n-\n-\treturn false;\n-}\n-\n-static void swap_usage_sub(struct swap_info_struct *si, unsigned int nr_entries)\n-{\n-\tlong val = atomic_long_sub_return_relaxed(nr_entries, \u0026si-\u003einuse_pages);\n-\n-\t/*\n-\t * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,\n-\t * add it to the plist.\n-\t */\n-\tif (unlikely(val \u0026 SWAP_USAGE_OFFLIST_BIT))\n-\t\tadd_to_avail_list(si, false);\n-}\n-\n-static void swap_range_alloc(struct swap_info_struct *si,\n-\t\t\t     unsigned int nr_entries)\n-{\n-\tif (swap_usage_add(si, nr_entries)) {\n+\tinuse_pages = atomic_long_add_return_relaxed(nr_entries, \u0026si-\u003einuse_pages);\n+\tif (unlikely(inuse_pages == si-\u003epages)) {\n \t\tif (vm_swap_full())\n \t\t\tschedule_work(\u0026si-\u003ereclaim_work);\n+\t\tdel_from_avail_list(si, false);\n \t}\n+\n \tatomic_long_sub(nr_entries, \u0026nr_swap_pages);\n }\n \n-static void swap_range_free(struct swap_info_struct *si, unsigned long offset,\n-\t\t\t    unsigned int nr_entries)\n+static void swap_device_inuse_sub(struct swap_info_struct *si, unsigned long offset,\n+\t\t\t\t  unsigned int nr_entries)\n {\n \tunsigned long end = offset + nr_entries - 1;\n \tvoid (*swap_slot_free_notify)(struct block_device *, unsigned long);\n+\tlong inuse_pages;\n \n \tzswap_invalidate(si-\u003etype, offset, nr_entries);\n \n@@ -1408,7 +1832,14 @@ static void swap_range_free(struct swap_info_struct *si, unsigned long offset,\n \t */\n \tsmp_wmb();\n \tatomic_long_add(nr_entries, \u0026nr_swap_pages);\n-\tswap_usage_sub(si, nr_entries);\n+\n+\t/*\n+\t * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,\n+\t * add it back to the available queue.\n+\t */\n+\tinuse_pages = atomic_long_sub_return_relaxed(nr_entries, \u0026si-\u003einuse_pages);\n+\tif (unlikely(inuse_pages \u0026 SWAP_USAGE_OFFLIST_BIT))\n+\t\tadd_to_avail_list(si);\n }\n \n static bool get_swap_device_info(struct swap_info_struct *si)\n@@ -1418,113 +1849,95 @@ static bool get_swap_device_info(struct swap_info_struct *si)\n \t/*\n \t * Guarantee the si-\u003eusers are checked before accessing other\n \t * fields of swap_info_struct, and si-\u003eflags (SWP_WRITEOK) is\n-\t * up to dated.\n+\t * up to date.\n \t *\n-\t * Paired with the spin_unlock() after setup_swap_info() in\n-\t * enable_swap_info(), and smp_wmb() in swapoff.\n+\t * Paired with percpu_up_write() in swap_device_enable(), and\n+\t * smp_wmb() after clearing SWP_WRITEOK in swapoff.\n \t */\n \tsmp_rmb();\n \treturn true;\n }\n \n-/*\n- * Fast path try to get swap entries with specified order from current\n- * CPU's swap entry pool (a cluster).\n- */\n-static bool swap_alloc_fast(struct folio *folio)\n+static void swap_alloc_entry(struct folio *folio)\n {\n-\tunsigned int order = folio_order(folio);\n-\tstruct swap_cluster_info *ci;\n+\tstruct swap_queue_cursor cursor = {};\n+\tlong nr_pages = folio_nr_pages(folio);\n \tstruct swap_info_struct *si;\n-\tunsigned int offset;\n \n-\t/*\n-\t * Once allocated, swap_info_struct will never be completely freed,\n-\t * so checking it's liveness by get_swap_device_info is enough.\n-\t */\n-\tsi = this_cpu_read(percpu_swap_cluster.si[order]);\n-\toffset = this_cpu_read(percpu_swap_cluster.offset[order]);\n-\tif (!si || !offset || !get_swap_device_info(si))\n-\t\treturn false;\n-\n-\tci = swap_cluster_lock(si, offset);\n-\tif (cluster_is_usable(ci, order)) {\n-\t\tif (cluster_is_empty(ci))\n-\t\t\toffset = cluster_offset(si, ci);\n-\t\talloc_swap_scan_cluster(si, ci, folio, offset);\n-\t} else {\n-\t\tswap_cluster_unlock(ci);\n-\t}\n-\n-\tput_swap_device(si);\n-\treturn folio_test_swapcache(folio);\n-}\n-\n-/* Rotate the device and switch to a new cluster */\n-static void swap_alloc_slow(struct folio *folio)\n-{\n-\tstruct swap_info_struct *si, *next;\n-\n-\tspin_lock(\u0026swap_avail_lock);\n-start_over:\n-\tplist_for_each_entry_safe(si, next, \u0026swap_avail_head, avail_list) {\n-\t\t/* Rotate the device and switch to a new cluster */\n-\t\tplist_requeue(\u0026si-\u003eavail_list, \u0026swap_avail_head);\n-\t\tspin_unlock(\u0026swap_avail_lock);\n-\t\tif (get_swap_device_info(si)) {\n-\t\t\tcluster_alloc_swap_entry(si, folio);\n-\t\t\tput_swap_device(si);\n-\t\t\tif (folio_test_swapcache(folio))\n-\t\t\t\treturn;\n-\t\t\tif (folio_test_large(folio))\n-\t\t\t\treturn;\n+\tpercpu_down_read(\u0026swapon_rwsem);\n+\tmigrate_disable();\n+\tfor (;;) {\n+\t\tsi = swap_queue_get_device(nr_pages, \u0026cursor);\n+\t\tif (IS_ERR(si)) {\n+\t\t\tif (PTR_ERR(si) == -EBUSY)\n+\t\t\t\tcontinue;\n+\t\t\tbreak;\n \t\t}\n+\t\tcluster_alloc_swap_entry(si, folio);\n+\n+\t\tif (folio_test_swapcache(folio))\n+\t\t\tbreak;\n \n-\t\tspin_lock(\u0026swap_avail_lock);\n \t\t/*\n-\t\t * if we got here, it's likely that si was almost full before,\n-\t\t * multiple callers probably all tried to get a page from the\n-\t\t * same si and it filled up before we could get one; or, the si\n-\t\t * filled up between us dropping swap_avail_lock.\n-\t\t * Since we dropped the swap_avail_lock, the swap_avail_list\n-\t\t * may have been modified; so if next is still in the\n-\t\t * swap_avail_head list then try it, otherwise start over if we\n-\t\t * have not gotten any slots.\n+\t\t * For large allocations, try every device at the same priority,\n+\t\t * but ask the caller to split instead of falling back to a lower\n+\t\t * priority ring.\n \t\t */\n-\t\tif (plist_node_empty(\u0026next-\u003eavail_list))\n-\t\t\tgoto start_over;\n+\t\tif (folio_test_large(folio)) {\n+\t\t\tcursor.ring_only = true;\n+\t\t\tcontinue;\n+\t\t}\n \t}\n-\tspin_unlock(\u0026swap_avail_lock);\n+\n+\tmigrate_enable();\n+\tpercpu_up_read(\u0026swapon_rwsem);\n }\n \n /*\n- * Discard pending clusters in a synchronized way when under high pressure.\n- * Return: true if any cluster is discarded.\n+ * Discard outside the topology reader, holding only the selected device's\n+ * live reference across I/O. Each successful retry starts a fresh queue walk.\n  */\n-static bool swap_sync_discard(void)\n+static bool swap_discard_for_alloc(unsigned long *discarded)\n {\n-\tbool ret = false;\n-\tstruct swap_info_struct *si, *next;\n-\n-\tspin_lock(\u0026swap_lock);\n-start_over:\n-\tplist_for_each_entry_safe(si, next, \u0026swap_active_head, list) {\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\tif (get_swap_device_info(si)) {\n-\t\t\tif (si-\u003eflags \u0026 SWP_PAGE_DISCARD)\n-\t\t\t\tret = swap_do_scheduled_discard(si);\n-\t\t\tput_swap_device(si);\n+\tDECLARE_BITMAP(checked, MAX_SWAPFILES) = {};\n+\tstruct swap_info_struct *si, *candidate;\n+\tunsigned int i, j;\n+\tbool done;\n+\tint type;\n+\n+\tfor (;;) {\n+\t\tcandidate = NULL;\n+\t\tpercpu_down_read(\u0026swapon_rwsem);\n+\t\tfor (i = 0; i \u003c swap_queue_len \u0026\u0026 !candidate; i++) {\n+\t\t\tstruct swap_prio_ring *ring = swap_queue[i];\n+\n+\t\t\tfor (j = 0; j \u003c ring-\u003esize; j++) {\n+\t\t\t\tsi = swap_device_unmask_ptr(READ_ONCE(ring-\u003edev[j]));\n+\t\t\t\ttype = si-\u003etype;\n+\t\t\t\tif (test_bit(type, discarded) || test_bit(type, checked))\n+\t\t\t\t\tcontinue;\n+\t\t\t\t__set_bit(type, checked);\n+\t\t\t\tif ((READ_ONCE(si-\u003eflags) \u0026 (SWP_WRITEOK | SWP_PAGE_DISCARD)) !=\n+\t\t\t\t    (SWP_WRITEOK | SWP_PAGE_DISCARD))\n+\t\t\t\t\tcontinue;\n+\t\t\t\tif (get_swap_device_info(si)) {\n+\t\t\t\t\tcandidate = si;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t}\n \t\t}\n-\t\tif (ret)\n-\t\t\treturn true;\n+\t\tpercpu_up_read(\u0026swapon_rwsem);\n+\t\tif (!candidate)\n+\t\t\treturn false;\n \n-\t\tspin_lock(\u0026swap_lock);\n-\t\tif (plist_node_empty(\u0026next-\u003elist))\n-\t\t\tgoto start_over;\n+\t\ttype = candidate-\u003etype;\n+\t\tdone = swap_discard_one_cluster(candidate);\n+\t\tif (done)\n+\t\t\t__set_bit(type, discarded);\n+\t\tput_swap_device(candidate);\n+\t\tif (done)\n+\t\t\treturn true;\n \t}\n-\tspin_unlock(\u0026swap_lock);\n-\n-\treturn false;\n }\n \n static int swap_extend_table_alloc(struct swap_info_struct *si,\n@@ -1828,15 +2241,16 @@ int folio_alloc_swap(struct folio *folio)\n \t\t}\n \t}\n \n-again:\n-\tlocal_lock(\u0026percpu_swap_cluster.lock);\n-\tif (!swap_alloc_fast(folio))\n-\t\tswap_alloc_slow(folio);\n-\tlocal_unlock(\u0026percpu_swap_cluster.lock);\n+\tswap_alloc_entry(folio);\n \n \tif (!order \u0026\u0026 unlikely(!folio_test_swapcache(folio))) {\n-\t\tif (swap_sync_discard())\n-\t\t\tgoto again;\n+\t\tDECLARE_BITMAP(discarded, MAX_SWAPFILES) = {};\n+\n+\t\twhile (swap_discard_for_alloc(discarded)) {\n+\t\t\tswap_alloc_entry(folio);\n+\t\t\tif (folio_test_swapcache(folio))\n+\t\t\t\tbreak;\n+\t\t}\n \t}\n \n \t/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */\n@@ -2036,7 +2450,7 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,\n \tif (batch_id)\n \t\tmem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);\n \n-\tswap_range_free(si, ci_head + ci_start, nr_pages);\n+\tswap_device_inuse_sub(si, ci_head + ci_start, nr_pages);\n \tswap_cluster_assert_empty(ci, ci_start, nr_pages, false);\n \n \tif (!ci-\u003ecount)\n@@ -2238,31 +2652,14 @@ void swap_put_entries_direct(swp_entry_t entry, int nr)\n  */\n swp_entry_t swap_alloc_hibernation_slot(int type)\n {\n-\tstruct swap_info_struct *pcp_si, *si = swap_type_to_info(type);\n-\tunsigned long pcp_offset, offset = SWAP_ENTRY_INVALID;\n-\tstruct swap_cluster_info *ci;\n+\tstruct swap_info_struct *si = swap_type_to_info(type);\n+\tunsigned long offset = SWAP_ENTRY_INVALID;\n \tswp_entry_t entry = {0};\n \n \tif (!si)\n \t\tgoto fail;\n \n-\t/*\n-\t * Try the local cluster first if it matches the device. If\n-\t * not, try grab a new cluster and override local cluster.\n-\t */\n-\tlocal_lock(\u0026percpu_swap_cluster.lock);\n-\tpcp_si = this_cpu_read(percpu_swap_cluster.si[0]);\n-\tpcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);\n-\tif (pcp_si == si \u0026\u0026 pcp_offset) {\n-\t\tci = swap_cluster_lock(si, pcp_offset);\n-\t\tif (cluster_is_usable(ci, 0))\n-\t\t\toffset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset);\n-\t\telse\n-\t\t\tswap_cluster_unlock(ci);\n-\t}\n-\tif (!offset)\n-\t\toffset = cluster_alloc_swap_entry(si, NULL);\n-\tlocal_unlock(\u0026percpu_swap_cluster.lock);\n+\toffset = cluster_alloc_swap_entry(si, NULL);\n \tif (offset)\n \t\tentry = swp_entry(si-\u003etype, offset);\n \n@@ -2289,26 +2686,18 @@ void swap_free_hibernation_slot(swp_entry_t entry)\n \n static int __find_hibernation_swap_type(dev_t device, sector_t offset)\n {\n-\tint type;\n-\n-\tlockdep_assert_held(\u0026swap_lock);\n+\tstruct swap_info_struct *si;\n \n \tif (!device)\n \t\treturn -EINVAL;\n \n-\tfor (type = 0; type \u003c nr_swapfiles; type++) {\n-\t\tstruct swap_info_struct *sis = swap_info[type];\n-\n-\t\tif (!(sis-\u003eflags \u0026 SWP_WRITEOK))\n-\t\t\tcontinue;\n-\n-\t\tif (device == sis-\u003ebdev-\u003ebd_dev) {\n-\t\t\tstruct swap_extent *se = first_se(sis);\n-\n-\t\t\tif (se-\u003estart_block == offset)\n-\t\t\t\treturn type;\n+\tfor_each_avail_swap(si) {\n+\t\tif (device == si-\u003ebdev-\u003ebd_dev) {\n+\t\t\tif (first_se(si)-\u003estart_block == offset)\n+\t\t\t\treturn si-\u003etype;\n \t\t}\n \t}\n+\n \treturn -ENODEV;\n }\n \n@@ -2331,21 +2720,18 @@ static int __find_hibernation_swap_type(dev_t device, sector_t offset)\n  */\n int pin_hibernation_swap_type(dev_t device, sector_t offset)\n {\n-\tint type;\n+\tint ret;\n \tstruct swap_info_struct *si;\n \n-\tspin_lock(\u0026swap_lock);\n-\n-\ttype = __find_hibernation_swap_type(device, offset);\n-\tif (type \u003c 0) {\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\treturn type;\n-\t}\n+\tpercpu_down_write(\u0026swapon_rwsem);\n+\tret = __find_hibernation_swap_type(device, offset);\n+\tif (ret \u003c 0)\n+\t\tgoto out;\n \n-\tsi = swap_type_to_info(type);\n+\tsi = swap_type_to_info(ret);\n \tif (WARN_ON_ONCE(!si)) {\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\treturn -ENODEV;\n+\t\tret = -ENODEV;\n+\t\tgoto out;\n \t}\n \n \t/*\n@@ -2354,14 +2740,15 @@ int pin_hibernation_swap_type(dev_t device, sector_t offset)\n \t * the same session.\n \t */\n \tif (WARN_ON_ONCE(si-\u003eflags \u0026 SWP_HIBERNATION)) {\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\treturn -EBUSY;\n+\t\tret = -EBUSY;\n+\t\tgoto out;\n \t}\n \n \tsi-\u003eflags |= SWP_HIBERNATION;\n \n-\tspin_unlock(\u0026swap_lock);\n-\treturn type;\n+out:\n+\tpercpu_up_write(\u0026swapon_rwsem);\n+\treturn ret;\n }\n \n /**\n@@ -2372,7 +2759,7 @@ int pin_hibernation_swap_type(dev_t device, sector_t offset)\n  *\n  * Look up the swap device for @device/@offset and atomically transfer\n  * the SWP_HIBERNATION pin from @old_type (if valid) to the new device,\n- * all under a single swap_lock critical section. This closes the\n+ * all under a single swapon_rwsem writer section. This closes the\n  * swapoff() window that exists when callers unpin and re-pin in two\n  * separate operations.\n  *\n@@ -2392,28 +2779,28 @@ int repin_hibernation_swap_type(int old_type, dev_t device, sector_t offset)\n \tstruct swap_info_struct *old_si, *new_si;\n \tint new_type;\n \n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_write(\u0026swapon_rwsem);\n \n \tnew_type = __find_hibernation_swap_type(device, offset);\n \tif (new_type \u003c 0) {\n-\t\tspin_unlock(\u0026swap_lock);\n+\t\tpercpu_up_write(\u0026swapon_rwsem);\n \t\treturn new_type;\n \t}\n \n \tnew_si = swap_type_to_info(new_type);\n \tif (WARN_ON_ONCE(!new_si)) {\n-\t\tspin_unlock(\u0026swap_lock);\n+\t\tpercpu_up_write(\u0026swapon_rwsem);\n \t\treturn -ENODEV;\n \t}\n \n \told_si = swap_type_to_info(old_type);\n \tif (new_si == old_si) {\n-\t\tspin_unlock(\u0026swap_lock);\n+\t\tpercpu_up_write(\u0026swapon_rwsem);\n \t\treturn new_type;\n \t}\n \n \tif (WARN_ON_ONCE(new_si-\u003eflags \u0026 SWP_HIBERNATION)) {\n-\t\tspin_unlock(\u0026swap_lock);\n+\t\tpercpu_up_write(\u0026swapon_rwsem);\n \t\treturn -EBUSY;\n \t}\n \n@@ -2421,7 +2808,7 @@ int repin_hibernation_swap_type(int old_type, dev_t device, sector_t offset)\n \t\told_si-\u003eflags \u0026= ~SWP_HIBERNATION;\n \tnew_si-\u003eflags |= SWP_HIBERNATION;\n \n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_write(\u0026swapon_rwsem);\n \treturn new_type;\n }\n \n@@ -2439,14 +2826,11 @@ void unpin_hibernation_swap_type(int type)\n {\n \tstruct swap_info_struct *si;\n \n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_write(\u0026swapon_rwsem);\n \tsi = swap_type_to_info(type);\n-\tif (!si) {\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\treturn;\n-\t}\n-\tsi-\u003eflags \u0026= ~SWP_HIBERNATION;\n-\tspin_unlock(\u0026swap_lock);\n+\tif (si)\n+\t\tsi-\u003eflags \u0026= ~SWP_HIBERNATION;\n+\tpercpu_up_write(\u0026swapon_rwsem);\n }\n \n /**\n@@ -2471,29 +2855,26 @@ int find_hibernation_swap_type(dev_t device, sector_t offset)\n {\n \tint type;\n \n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_read(\u0026swapon_rwsem);\n \ttype = __find_hibernation_swap_type(device, offset);\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_read(\u0026swapon_rwsem);\n \n \treturn type;\n }\n \n int find_first_swap(dev_t *device)\n {\n-\tint type;\n-\n-\tspin_lock(\u0026swap_lock);\n-\tfor (type = 0; type \u003c nr_swapfiles; type++) {\n-\t\tstruct swap_info_struct *sis = swap_info[type];\n+\tint ret = -ENODEV;\n+\tstruct swap_info_struct *si;\n \n-\t\tif (!(sis-\u003eflags \u0026 SWP_WRITEOK))\n-\t\t\tcontinue;\n-\t\t*device = sis-\u003ebdev-\u003ebd_dev;\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\treturn type;\n+\tpercpu_down_read(\u0026swapon_rwsem);\n+\tfor_each_avail_swap(si) {\n+\t\t*device = si-\u003ebdev-\u003ebd_dev;\n+\t\tret = si-\u003etype;\n+\t\tbreak;\n \t}\n-\tspin_unlock(\u0026swap_lock);\n-\treturn -ENODEV;\n+\tpercpu_up_read(\u0026swapon_rwsem);\n+\treturn ret;\n }\n \n /*\n@@ -2521,7 +2902,7 @@ unsigned int count_swap_pages(int type, int free)\n {\n \tunsigned int n = 0;\n \n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_read(\u0026swapon_rwsem);\n \tif ((unsigned int)type \u003c nr_swapfiles) {\n \t\tstruct swap_info_struct *sis = swap_info[type];\n \n@@ -2533,7 +2914,7 @@ unsigned int count_swap_pages(int type, int free)\n \t\t}\n \t\tspin_unlock(\u0026sis-\u003elock);\n \t}\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_read(\u0026swapon_rwsem);\n \treturn n;\n }\n #endif /* CONFIG_HIBERNATION */\n@@ -2859,10 +3240,10 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,\n \tunsigned long swp_tb;\n \n \t/*\n-\t * No need for swap_lock here: we're just looking\n+\t * No need for swapon_rwsem here: we're just looking\n \t * for whether an entry is in use, not modifying it; false\n \t * hits are okay, and sys_swapoff() has already prevented new\n-\t * allocations from this area (while holding swap_lock).\n+\t * allocations from this area (while holding swapon_rwsem).\n \t */\n \ti = prev + 1;\n \twhile (i \u003c si-\u003emax) {\n@@ -2992,7 +3373,7 @@ static int try_to_unuse(unsigned int type)\n success:\n \t/*\n \t * Make sure that further cleanups after try_to_unuse() returns happen\n-\t * after swap_range_free() reduces si-\u003einuse_pages to 0.\n+\t * after swap_device_inuse_sub() reduces si-\u003einuse_pages to 0.\n \t */\n \tsmp_mb();\n \treturn 0;\n@@ -3000,18 +3381,20 @@ static int try_to_unuse(unsigned int type)\n \n /*\n  * After a successful try_to_unuse, if no swap is now in use, we know\n- * we can empty the mmlist.  swap_lock must be held on entry and exit.\n- * Note that mmlist_lock nests inside swap_lock, and an mm must be\n+ * we can empty the mmlist. swapon_rwsem must be held on entry and exit.\n+ * Note that mmlist_lock nests inside swapon_rwsem, and an mm must be\n  * added to the mmlist just after page_duplicate - before would be racy.\n  */\n static void drain_mmlist(void)\n {\n+\tstruct swap_info_struct *si;\n \tstruct list_head *p, *next;\n-\tunsigned int type;\n \n-\tfor (type = 0; type \u003c nr_swapfiles; type++)\n-\t\tif (swap_usage_in_pages(swap_info[type]))\n+\tfor_each_swap(si) {\n+\t\tif (swap_usage_in_pages(si))\n \t\t\treturn;\n+\t}\n+\n \tspin_lock(\u0026mmlist_lock);\n \tlist_for_each_safe(p, next, \u0026init_mm.mmlist)\n \t\tlist_del_init(p);\n@@ -3145,58 +3528,86 @@ static int setup_swap_extents(struct swap_info_struct *sis,\n \treturn generic_swapfile_activate(sis, swap_file, span);\n }\n \n-static void _enable_swap_info(struct swap_info_struct *si)\n-{\n-\tatomic_long_add(si-\u003epages, \u0026nr_swap_pages);\n-\ttotal_swap_pages += si-\u003epages;\n-\n-\tassert_spin_locked(\u0026swap_lock);\n-\n-\tplist_add(\u0026si-\u003elist, \u0026swap_active_head);\n-\n-\t/* Add back to available list */\n-\tadd_to_avail_list(si, true);\n-}\n-\n /*\n- * Called after the swap device is ready, resurrect its percpu ref, it's now\n- * safe to reference it. Add it to the list to expose it to the allocator.\n+ * Mark a fully initialized swap device writable and expose it to the allocator.\n+ * The caller must have resurrected its percpu ref before entering this helper.\n  */\n-static void enable_swap_info(struct swap_info_struct *si)\n+static void __swap_device_enable(struct swap_info_struct *si)\n {\n-\tpercpu_ref_resurrect(\u0026si-\u003eusers);\n-\tspin_lock(\u0026swap_lock);\n+\tlockdep_assert_held_write(\u0026swapon_rwsem);\n \tspin_lock(\u0026si-\u003elock);\n-\t_enable_swap_info(si);\n+\tspin_lock(\u0026swap_queue_update_lock);\n+\tsi-\u003eflags |= SWP_WRITEOK;\n+\tspin_unlock(\u0026swap_queue_update_lock);\n \tspin_unlock(\u0026si-\u003elock);\n-\tspin_unlock(\u0026swap_lock);\n+\tatomic_long_add(si-\u003epages, \u0026nr_swap_pages);\n+\ttotal_swap_pages += si-\u003epages;\n+\tadd_to_avail_list(si);\n }\n \n-static void reinsert_swap_info(struct swap_info_struct *si)\n+static void swap_device_enable(struct swap_info_struct *si)\n {\n-\tspin_lock(\u0026swap_lock);\n-\tspin_lock(\u0026si-\u003elock);\n-\t_enable_swap_info(si);\n-\tspin_unlock(\u0026si-\u003elock);\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_down_write(\u0026swapon_rwsem);\n+\t__swap_device_enable(si);\n+\tpercpu_up_write(\u0026swapon_rwsem);\n }\n \n-/*\n- * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range\n- * see the updated flags, so there will be no more allocations.\n- */\n-static void wait_for_allocation(struct swap_info_struct *si)\n+static int swap_device_disable(struct address_space *mapping,\n+\t\t\t       struct swap_info_struct **swap_info)\n {\n-\tunsigned long offset;\n-\tunsigned long end = ALIGN(si-\u003emax, SWAPFILE_CLUSTER);\n+\tstruct swap_info_struct *si;\n \tstruct swap_cluster_info *ci;\n+\tunsigned long offset, end;\n+\tint err = -EINVAL;\n+\n+\tpercpu_down_write(\u0026swapon_rwsem);\n+\tfor_each_avail_swap(si) {\n+\t\tif (si-\u003eswap_file-\u003ef_mapping == mapping) {\n+\t\t\terr = 0;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tif (err)\n+\t\tgoto unlock;\n+\n+\t/*\n+\t * Refuse swapoff while the device is pinned for hibernation.\n+\t */\n+\tif (si-\u003eflags \u0026 SWP_HIBERNATION) {\n+\t\terr = -EBUSY;\n+\t\tgoto unlock;\n+\t}\n+\n+\tif (security_vm_enough_memory_mm(current-\u003emm, si-\u003epages)) {\n+\t\terr = -ENOMEM;\n+\t\tgoto unlock;\n+\t}\n+\tvm_unacct_memory(si-\u003epages);\n+\n+\t/* Serialize with the WRITEOK check in isolate_lock_cluster(). */\n+\tspin_lock(\u0026si-\u003elock);\n+\tdel_from_avail_list(si, true);\n+\tspin_unlock(\u0026si-\u003elock);\n+\ttotal_swap_pages -= si-\u003epages;\n+\tatomic_long_sub(si-\u003epages, \u0026nr_swap_pages);\n \n-\tBUG_ON(si-\u003eflags \u0026 SWP_WRITEOK);\n+\tend = ALIGN(si-\u003emax, SWAPFILE_CLUSTER);\n+unlock:\n+\tpercpu_up_write(\u0026swapon_rwsem);\n+\tif (err)\n+\t\treturn err;\n \n+\t/*\n+\t * Drain cluster-lock users after clearing SWP_WRITEOK, so swapoff\n+\t * does not race with operations that started before the transition.\n+\t */\n \tfor (offset = 0; offset \u003c end; offset += SWAPFILE_CLUSTER) {\n \t\tci = swap_cluster_lock(si, offset);\n \t\tswap_cluster_unlock(ci);\n \t}\n+\n+\t*swap_info = si;\n+\treturn 0;\n }\n \n static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,\n@@ -3220,28 +3631,6 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,\n \tkvfree(cluster_info);\n }\n \n-/*\n- * Called after swap device's reference count is dead, so\n- * neither scan nor allocation will use it.\n- */\n-static void flush_percpu_swap_cluster(struct swap_info_struct *si)\n-{\n-\tint cpu, i;\n-\tstruct swap_info_struct **pcp_si;\n-\n-\tfor_each_possible_cpu(cpu) {\n-\t\tpcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);\n-\t\t/*\n-\t\t * Invalidate the percpu swap cluster cache, si-\u003eusers\n-\t\t * is dead, so no new user will point to it, just flush\n-\t\t * any existing user.\n-\t\t */\n-\t\tfor (i = 0; i \u003c SWAP_NR_ORDERS; i++)\n-\t\t\tcmpxchg(\u0026pcp_si[i], si, NULL);\n-\t}\n-}\n-\n-\n SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n {\n \tstruct swap_info_struct *p = NULL;\n@@ -3250,7 +3639,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \tstruct address_space *mapping;\n \tstruct inode *inode;\n \tunsigned int maxpages;\n-\tint err, found = 0;\n+\tint err;\n \n \tif (!capable(CAP_SYS_ADMIN))\n \t\treturn -EPERM;\n@@ -3263,44 +3652,11 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \t\treturn PTR_ERR(victim);\n \n \tmapping = victim-\u003ef_mapping;\n-\tspin_lock(\u0026swap_lock);\n-\tplist_for_each_entry(p, \u0026swap_active_head, list) {\n-\t\tif (p-\u003eflags \u0026 SWP_WRITEOK) {\n-\t\t\tif (p-\u003eswap_file-\u003ef_mapping == mapping) {\n-\t\t\t\tfound = 1;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t}\n-\t}\n-\tif (!found) {\n-\t\terr = -EINVAL;\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\tgoto out_dput;\n-\t}\n-\n-\t/* Refuse swapoff while the device is pinned for hibernation */\n-\tif (p-\u003eflags \u0026 SWP_HIBERNATION) {\n-\t\terr = -EBUSY;\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\tgoto out_dput;\n-\t}\n-\n-\tif (!security_vm_enough_memory_mm(current-\u003emm, p-\u003epages))\n-\t\tvm_unacct_memory(p-\u003epages);\n-\telse {\n-\t\terr = -ENOMEM;\n-\t\tspin_unlock(\u0026swap_lock);\n-\t\tgoto out_dput;\n-\t}\n-\tspin_lock(\u0026p-\u003elock);\n-\tdel_from_avail_list(p, true);\n-\tplist_del(\u0026p-\u003elist, \u0026swap_active_head);\n-\tatomic_long_sub(p-\u003epages, \u0026nr_swap_pages);\n-\ttotal_swap_pages -= p-\u003epages;\n-\tspin_unlock(\u0026p-\u003elock);\n-\tspin_unlock(\u0026swap_lock);\n+\terr = swap_device_disable(mapping, \u0026p);\n+\tfilp_close(victim, NULL);\n \n-\twait_for_allocation(p);\n+\tif (err)\n+\t\treturn err;\n \n \tset_current_oom_origin();\n \terr = try_to_unuse(p-\u003etype);\n@@ -3308,10 +3664,15 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \n \tif (err) {\n \t\t/* re-insert swap space back into swap_list */\n-\t\treinsert_swap_info(p);\n-\t\tgoto out_dput;\n+\t\tswap_device_enable(p);\n+\t\treturn err;\n \t}\n \n+\tpercpu_down_write(\u0026swapon_rwsem);\n+\tswap_queue_del(p);\n+\tpercpu_ref_kill(\u0026p-\u003eusers);\n+\tpercpu_up_write(\u0026swapon_rwsem);\n+\n \t/*\n \t * Wait for swap operations protected by get/put_swap_device()\n \t * to complete.  Because of synchronize_rcu() here, all swap\n@@ -3320,21 +3681,18 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \t * prevent folio_test_swapcache() and the following swap cache\n \t * operations from racing with swapoff.\n \t */\n-\tpercpu_ref_kill(\u0026p-\u003eusers);\n \tsynchronize_rcu();\n \twait_for_completion(\u0026p-\u003ecomp);\n \n \tflush_work(\u0026p-\u003ediscard_work);\n \tflush_work(\u0026p-\u003ereclaim_work);\n-\tflush_percpu_swap_cluster(p);\n \n \tdestroy_swap_extents(p, p-\u003eswap_file);\n \n \tif (!(p-\u003eflags \u0026 SWP_SOLIDSTATE))\n \t\tatomic_dec(\u0026nr_rotate_swap);\n \n-\tmutex_lock(\u0026swapon_mutex);\n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_write(\u0026swapon_rwsem);\n \tspin_lock(\u0026p-\u003elock);\n \tdrain_mmlist();\n \n@@ -3345,10 +3703,11 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \tp-\u003emax = 0;\n \tp-\u003ecluster_info = NULL;\n \tspin_unlock(\u0026p-\u003elock);\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_write(\u0026swapon_rwsem);\n \tarch_swap_invalidate_area(p-\u003etype);\n \tzswap_swapoff(p-\u003etype);\n-\tmutex_unlock(\u0026swapon_mutex);\n+\tfree_percpu(p-\u003epercpu_cluster);\n+\tp-\u003epercpu_cluster = NULL;\n \tkfree(p-\u003eglobal_cluster);\n \tp-\u003eglobal_cluster = NULL;\n \tfree_swap_cluster_info(cluster_info, maxpages);\n@@ -3364,18 +3723,19 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \t * Clear the SWP_USED flag after all resources are freed so that swapon\n \t * can reuse this swap_info in alloc_swap_info() safely.  It is ok to\n \t * not hold p-\u003elock after we cleared its SWP_WRITEOK.\n+\t *\n+\t * The write lock ensures the flag clear is visible to lockless\n+\t * readers of swap_type_to_info() before alloc_swap_info() reuses\n+\t * this slot.\n \t */\n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_write(\u0026swapon_rwsem);\n \tp-\u003eflags = 0;\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_write(\u0026swapon_rwsem);\n \n-\terr = 0;\n \tatomic_inc(\u0026proc_poll_event);\n \twake_up_interruptible(\u0026proc_poll_wait);\n \n-out_dput:\n-\tfilp_close(victim, NULL);\n-\treturn err;\n+\treturn 0;\n }\n \n #ifdef CONFIG_PROC_FS\n@@ -3393,20 +3753,18 @@ static __poll_t swaps_poll(struct file *file, poll_table *wait)\n \treturn EPOLLIN | EPOLLRDNORM;\n }\n \n-/* iterator */\n static void *swap_start(struct seq_file *swap, loff_t *pos)\n {\n \tstruct swap_info_struct *si;\n-\tint type;\n \tloff_t l = *pos;\n \n-\tmutex_lock(\u0026swapon_mutex);\n+\tpercpu_down_read(\u0026swapon_rwsem);\n \n \tif (!l)\n \t\treturn SEQ_START_TOKEN;\n \n-\tfor (type = 0; (si = swap_type_to_info(type)); type++) {\n-\t\tif (!(si-\u003eswap_file))\n+\tfor_each_swap(si) {\n+\t\tif (!si-\u003eswap_file)\n \t\t\tcontinue;\n \t\tif (!--l)\n \t\t\treturn si;\n@@ -3427,7 +3785,7 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)\n \n \t++(*pos);\n \tfor (; (si = swap_type_to_info(type)); type++) {\n-\t\tif (!(si-\u003eswap_file))\n+\t\tif (!(si-\u003eflags \u0026 SWP_USED) || !(si-\u003eswap_file))\n \t\t\tcontinue;\n \t\treturn si;\n \t}\n@@ -3437,7 +3795,7 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)\n \n static void swap_stop(struct seq_file *swap, void *v)\n {\n-\tmutex_unlock(\u0026swapon_mutex);\n+\tpercpu_up_read(\u0026swapon_rwsem);\n }\n \n static int swap_show(struct seq_file *swap, void *v)\n@@ -3530,13 +3888,13 @@ static struct swap_info_struct *alloc_swap_info(void)\n \t\treturn ERR_PTR(-ENOMEM);\n \t}\n \n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_write(\u0026swapon_rwsem);\n \tfor (type = 0; type \u003c nr_swapfiles; type++) {\n \t\tif (!(swap_info[type]-\u003eflags \u0026 SWP_USED))\n \t\t\tbreak;\n \t}\n \tif (type \u003e= MAX_SWAPFILES) {\n-\t\tspin_unlock(\u0026swap_lock);\n+\t\tpercpu_up_write(\u0026swapon_rwsem);\n \t\tpercpu_ref_exit(\u0026p-\u003eusers);\n \t\tkvfree(p);\n \t\treturn ERR_PTR(-EPERM);\n@@ -3558,10 +3916,8 @@ static struct swap_info_struct *alloc_swap_info(void)\n \t\t */\n \t}\n \tp-\u003eswap_extent_root = RB_ROOT;\n-\tplist_node_init(\u0026p-\u003elist, 0);\n-\tplist_node_init(\u0026p-\u003eavail_list, 0);\n \tp-\u003eflags = SWP_USED;\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_write(\u0026swapon_rwsem);\n \tif (defer) {\n \t\tpercpu_ref_exit(\u0026defer-\u003eusers);\n \t\tkvfree(defer);\n@@ -3630,9 +3986,8 @@ __weak unsigned long arch_max_swapfile_size(void)\n \treturn generic_max_swapfile_size();\n }\n \n-static unsigned long read_swap_header(struct swap_info_struct *si,\n-\t\t\t\t\tunion swap_header *swap_header,\n-\t\t\t\t\tstruct inode *inode)\n+static unsigned long read_swap_header(union swap_header *swap_header,\n+\t\t\t\t      struct inode *inode)\n {\n \tint i;\n \tunsigned long maxpages;\n@@ -3699,7 +4054,7 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,\n {\n \tunsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);\n \tstruct swap_cluster_info *cluster_info;\n-\tint err = -ENOMEM;\n+\tint cpu, err = -ENOMEM;\n \tunsigned long i;\n \n \tcluster_info = kvzalloc_objs(*cluster_info, nr_clusters);\n@@ -3709,13 +4064,26 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,\n \tfor (i = 0; i \u003c nr_clusters; i++)\n \t\tspin_lock_init(\u0026cluster_info[i].lock);\n \n-\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE)) {\n+\tif (si-\u003eflags \u0026 SWP_SOLIDSTATE) {\n+\t\tsi-\u003epercpu_cluster = alloc_percpu(struct percpu_cluster);\n+\t\tif (!si-\u003epercpu_cluster)\n+\t\t\tgoto err;\n+\n+\t\tfor_each_possible_cpu(cpu) {\n+\t\t\tstruct percpu_cluster *cluster;\n+\n+\t\t\tcluster = per_cpu_ptr(si-\u003epercpu_cluster, cpu);\n+\t\t\tfor (i = 0; i \u003c SWAP_NR_ORDERS; i++)\n+\t\t\t\tcluster-\u003enext[i] = SWAP_ENTRY_INVALID;\n+\t\t\tlocal_lock_init(\u0026cluster-\u003elock);\n+\t\t}\n+\t} else {\n \t\tsi-\u003eglobal_cluster = kmalloc_obj(*si-\u003eglobal_cluster);\n \t\tif (!si-\u003eglobal_cluster)\n \t\t\tgoto err;\n \t\tfor (i = 0; i \u003c SWAP_NR_ORDERS; i++)\n \t\t\tsi-\u003eglobal_cluster-\u003enext[i] = SWAP_ENTRY_INVALID;\n-\t\tspin_lock_init(\u0026si-\u003eglobal_cluster_lock);\n+\t\tspin_lock_init(\u0026si-\u003eglobal_cluster-\u003elock);\n \t}\n \n \t/*\n@@ -3776,6 +4144,8 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,\n SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n {\n \tstruct swap_info_struct *si;\n+\tstruct swap_queue_reader __percpu *readers;\n+\tunsigned int nr_readers;\n \tstruct file *swap_file = NULL;\n \tstruct address_space *mapping;\n \tstruct dentry *dentry;\n@@ -3798,7 +4168,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \t/*\n \t * Allocate or reuse existing !SWP_USED swap_info. The returned\n \t * si will stay in a dying status, so nothing will access its content\n-\t * until enable_swap_info resurrects its percpu ref and expose it.\n+\t * until swap_device_enable resurrects its percpu ref and expose it.\n \t */\n \tsi = alloc_swap_info();\n \tif (IS_ERR(si))\n@@ -3863,7 +4233,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \t}\n \tswap_header = kmap_local_folio(folio, 0);\n \n-\tmaxpages = read_swap_header(si, swap_header, inode);\n+\tmaxpages = read_swap_header(swap_header, inode);\n \tif (unlikely(!maxpages)) {\n \t\terror = -EINVAL;\n \t\tgoto bad_swap_unlock_inode;\n@@ -3951,22 +4321,38 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \t\tgoto free_swap_zswap;\n \t}\n \n-\tmutex_lock(\u0026swapon_mutex);\n \tprio = DEF_SWAP_PRIO;\n \tif (swap_flags \u0026 SWAP_FLAG_PREFER)\n \t\tprio = swap_flags \u0026 SWAP_FLAG_PRIO_MASK;\n \n+\tsi-\u003eprio = prio;\n+\n \t/*\n-\t * The plist prio is negated because plist ordering is\n-\t * low-to-high, while swap ordering is high-to-low\n+\t * Publish swap_file before making the percpu ref live, then add the device\n+\t * to the queue and make it writable under the same write-side lock. This\n+\t * keeps lockless ref users and /proc/swaps from observing partial state.\n \t */\n-\tsi-\u003eprio = prio;\n-\tsi-\u003elist.prio = -si-\u003eprio;\n-\tsi-\u003eavail_list.prio = -si-\u003eprio;\n+\terror = swap_queue_lock_for_add(prio, \u0026readers, \u0026nr_readers);\n+\tif (error) {\n+\t\tinode-\u003ei_flags \u0026= ~S_SWAPFILE;\n+\t\tgoto free_swap_zswap;\n+\t}\n \tsi-\u003eswap_file = swap_file;\n-\n-\t/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */\n-\tenable_swap_info(si);\n+\tpercpu_ref_resurrect(\u0026si-\u003eusers);\n+\terror = swap_queue_add(si, \u0026readers, nr_readers);\n+\tif (error) {\n+\t\tsi-\u003eswap_file = NULL;\n+\t\tpercpu_ref_kill(\u0026si-\u003eusers);\n+\t} else {\n+\t\t__swap_device_enable(si);\n+\t}\n+\tpercpu_up_write(\u0026swapon_rwsem);\n+\tfree_percpu(readers);\n+\tif (error) {\n+\t\twait_for_completion(\u0026si-\u003ecomp);\n+\t\tinode-\u003ei_flags \u0026= ~S_SWAPFILE;\n+\t\tgoto free_swap_zswap;\n+\t}\n \n \tpr_info(\"Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\\n\",\n \t\tK(si-\u003epages), name-\u003ename, si-\u003eprio, nr_extents,\n@@ -3976,7 +4362,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \t\t(si-\u003eflags \u0026 SWP_AREA_DISCARD) ? \"s\" : \"\",\n \t\t(si-\u003eflags \u0026 SWP_PAGE_DISCARD) ? \"c\" : \"\");\n \n-\tmutex_unlock(\u0026swapon_mutex);\n \tatomic_inc(\u0026proc_poll_event);\n \twake_up_interruptible(\u0026proc_poll_wait);\n \n@@ -3987,6 +4372,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n bad_swap_unlock_inode:\n \tinode_unlock(inode);\n bad_swap:\n+\tfree_percpu(si-\u003epercpu_cluster);\n+\tsi-\u003epercpu_cluster = NULL;\n \tkfree(si-\u003eglobal_cluster);\n \tsi-\u003eglobal_cluster = NULL;\n \tinode = NULL;\n@@ -3997,9 +4384,9 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \t * Clear the SWP_USED flag after all resources are freed so\n \t * alloc_swap_info can reuse this si safely.\n \t */\n-\tspin_lock(\u0026swap_lock);\n+\tpercpu_down_write(\u0026swapon_rwsem);\n \tsi-\u003eflags = 0;\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_write(\u0026swapon_rwsem);\n \tif (inced_nr_rotate_swap)\n \t\tatomic_dec(\u0026nr_rotate_swap);\n \tif (swap_file)\n@@ -4014,19 +4401,17 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \n void si_swapinfo(struct sysinfo *val)\n {\n-\tunsigned int type;\n+\tstruct swap_info_struct *si;\n \tunsigned long nr_to_be_unused = 0;\n \n-\tspin_lock(\u0026swap_lock);\n-\tfor (type = 0; type \u003c nr_swapfiles; type++) {\n-\t\tstruct swap_info_struct *si = swap_info[type];\n-\n-\t\tif ((si-\u003eflags \u0026 SWP_USED) \u0026\u0026 !(si-\u003eflags \u0026 SWP_WRITEOK))\n+\tpercpu_down_read(\u0026swapon_rwsem);\n+\tfor_each_swap(si) {\n+\t\tif (!(si-\u003eflags \u0026 SWP_WRITEOK))\n \t\t\tnr_to_be_unused += swap_usage_in_pages(si);\n \t}\n \tval-\u003efreeswap = atomic_long_read(\u0026nr_swap_pages) + nr_to_be_unused;\n \tval-\u003etotalswap = total_swap_pages + nr_to_be_unused;\n-\tspin_unlock(\u0026swap_lock);\n+\tpercpu_up_read(\u0026swapon_rwsem);\n }\n \n /*\n@@ -4066,7 +4451,33 @@ int swap_dup_entry_direct(swp_entry_t entry)\n #if defined(CONFIG_MEMCG) \u0026\u0026 defined(CONFIG_BLK_CGROUP)\n static bool __has_usable_swap(void)\n {\n-\treturn !plist_head_empty(\u0026swap_active_head);\n+\treturn READ_ONCE(total_swap_pages) \u003e 0;\n+}\n+\n+static struct swap_info_struct *swap_queue_first_usable_bdev(void)\n+{\n+\tstruct swap_prio_ring *ring;\n+\tstruct swap_info_struct *si;\n+\tunsigned int ring_idx, dev_idx;\n+\n+\tlockdep_assert_held(\u0026swapon_rwsem);\n+\tfor (ring_idx = 0; ring_idx \u003c swap_queue_len; ring_idx++) {\n+\t\tring = swap_queue[ring_idx];\n+\t\tfor (dev_idx = 0; dev_idx \u003c ring-\u003esize; dev_idx++) {\n+\t\t\tsi = READ_ONCE(ring-\u003edev[dev_idx]);\n+\t\t\tif (swap_device_masked(si))\n+\t\t\t\tcontinue;\n+\t\t\tsi = swap_device_unmask_ptr(si);\n+\t\t\tif (!(READ_ONCE(si-\u003eflags) \u0026 SWP_WRITEOK))\n+\t\t\t\tcontinue;\n+\t\t\tif (atomic_long_read(\u0026si-\u003einuse_pages) \u0026\n+\t\t\t    SWAP_USAGE_OFFLIST_BIT)\n+\t\t\t\tcontinue;\n+\t\t\tif (si-\u003ebdev)\n+\t\t\t\treturn si;\n+\t\t}\n+\t}\n+\treturn NULL;\n }\n \n void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)\n@@ -4089,14 +4500,11 @@ void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)\n \tif (current-\u003ethrottle_disk)\n \t\treturn;\n \n-\tspin_lock(\u0026swap_avail_lock);\n-\tplist_for_each_entry(si, \u0026swap_avail_head, avail_list) {\n-\t\tif (si-\u003ebdev) {\n-\t\t\tblkcg_schedule_throttle(si-\u003ebdev-\u003ebd_disk, true);\n-\t\t\tbreak;\n-\t\t}\n-\t}\n-\tspin_unlock(\u0026swap_avail_lock);\n+\tpercpu_down_read(\u0026swapon_rwsem);\n+\tsi = swap_queue_first_usable_bdev();\n+\tif (si)\n+\t\tblkcg_schedule_throttle(si-\u003ebdev-\u003ebd_disk, true);\n+\tpercpu_up_read(\u0026swapon_rwsem);\n }\n #endif\n \n"
}

2/1 2026/11/18 16:15 agent patch-evaluator
7m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "SWAP",
    "HIBERNATION",
    "MEMCG",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "folio_alloc_swap",
    "swap_alloc_entry",
    "swap_queue_get_device",
    "swap_queue_add",
    "swap_queue_del",
    "swap_device_enable",
    "swap_device_disable",
    "cluster_alloc_swap_entry",
    "swap_discard_for_alloc",
    "__x64_sys_swapon",
    "__x64_sys_swapoff"
  ],
  "Reasoning": "The patch series refactors the core Linux memory management swap subsystem. It replaces the plist-based swap device tracking (swap_active_head, swap_avail_head) and coarse spinlocks (swap_lock, swap_avail_lock) with a per-CPU priority-ring queue (swap_queue, swap_prio_ring), per-CPU readers, swapon_rwsem, and fine-grained queue update locks. It also rewires per-CPU swap cluster allocation, swap device activation/deactivation during swapon/swapoff, and synchronous cluster discard handling. These changes modify core mm logic and synchronization paths that are fully reachable in virtualized environments via the swapon/swapoff syscalls and anonymous memory paging pressure.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 00c4e8cb61a1f01e70050a532c7ceeebefa7e809
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 18 16:15:20 2026 +0000

    syz-cluster: applied patch under review

diff --git a/include/linux/plist.h b/include/linux/plist.h
index 16cf4355b5c131..73d359c1a0536a 100644
--- a/include/linux/plist.h
+++ b/include/linux/plist.h
@@ -132,8 +132,6 @@ static inline void plist_node_init(struct plist_node *node, int prio)
 extern void plist_add(struct plist_node *node, struct plist_head *head);
 extern void plist_del(struct plist_node *node, struct plist_head *head);
 
-extern void plist_requeue(struct plist_node *node, struct plist_head *head);
-
 /**
  * plist_for_each - iterate over the plist
  * @pos:	the type * to use as a loop counter
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 4f686709d71f00..ce8a800751ca2a 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -188,6 +188,25 @@ struct swap_extent {
 	((offsetof(union swap_header, magic.magic) - \
 	  offsetof(union swap_header, info.badpages)) / sizeof(int))
 
+/*
+ * Swap device flags, except the ones documented below, all are immutable
+ * after exposed by swap_device_enable, and until the device is freed again
+ * (SWP_USED unset), except that teardown clears SWP_ACTIVATED after draining
+ * allocators and live references. The other exceptions use swapon_rwsem:
+ * - SWP_USED: Protected by swapon_rwsem. Indicates the device is inuse. Once
+ *   set, won't be cleared unless all reference to this device is freed and
+ *   swapoff finished.
+ * - SWP_WRITEOK: Protected by swapon_rwsem, si->lock and
+ *   swap_queue_update_lock.
+ *   Clearing this flag is followed by waiting for all current cluster lock
+ *   users to exit, so
+ *   checking this flag while holding any of these locks ensures the device
+ *   is safe to use at the moment. Note: clearing this flag doesn't affect
+ *   pending IO or async requests, it only prevents further entry allocation
+ *   or new async request (e.g. discard) from initiating.
+ * - SWP_HIBERNATION: Protected by swapon_rwsem. Indicates if the device
+ *   is pinned for hibernation.
+ */
 enum {
 	SWP_USED	= (1 << 0),	/* is slot in swap_info[] used? */
 	SWP_WRITEOK	= (1 << 1),	/* ok to write to this swap?	*/
@@ -223,10 +242,17 @@ enum {
 #endif
 
 /*
- * We keep using same cluster for rotational device so IO will be sequential.
- * The purpose is to optimize SWAP throughput on these device.
+ * We assign a cluster to each CPU, so each CPU can allocate swap entry from
+ * its own cluster and swapout sequentially. The purpose is to optimize swapout
+ * throughput.
  */
+struct percpu_cluster {
+	local_lock_t lock; /* Protect the percpu_cluster above */
+	unsigned int next[SWAP_NR_ORDERS]; /* Likely next allocation offset */
+};
+
 struct swap_sequential_cluster {
+	spinlock_t lock; /* Serialize usage of global cluster */
 	unsigned int next[SWAP_NR_ORDERS]; /* Likely next allocation offset */
 };
 
@@ -237,7 +263,6 @@ struct swap_info_struct {
 	struct percpu_ref users;	/* indicate and keep swap device valid. */
 	unsigned long	flags;		/* SWP_USED etc: see above */
 	signed short	prio;		/* swap priority of this type */
-	struct plist_node list;		/* entry in swap_active_head */
 	signed char	type;		/* strange name for an index */
 	unsigned int	max;		/* size of this swap device */
 	struct swap_cluster_info *cluster_info; /* array, one entry per cluster */
@@ -249,26 +274,20 @@ struct swap_info_struct {
 					/* list of cluster that are fragmented or contented */
 	unsigned int pages;		/* total of usable pages of swap */
 	atomic_long_t inuse_pages;	/* number of those currently in use */
+	struct percpu_cluster	__percpu *percpu_cluster; /* per cpu's swap location */
 	struct swap_sequential_cluster *global_cluster; /* Use one global cluster for rotating device */
-	spinlock_t global_cluster_lock;	/* Serialize usage of global cluster */
 	struct rb_root swap_extent_root;/* root of the swap extent rbtree */
 	struct block_device *bdev;	/* swap device or bdev of swap file */
 	struct file *swap_file;		/* seldom referenced */
 	struct completion comp;		/* seldom referenced */
 	spinlock_t lock;		/*
-					 * protect map scan related fields like
-					 * inuse_pages and all cluster lists.
-					 * Other fields are only changed
-					 * at swapon/swapoff, so are protected
-					 * by swap_lock. changing flags need
-					 * hold this lock and swap_lock. If
-					 * both locks need hold, hold swap_lock
-					 * first.
+					 * Protect cluster lists. Other fields
+					 * are only changed at swapon/swapoff,
+					 * so are protected by swapon_rwsem.
 					 */
 	struct work_struct discard_work; /* discard worker */
 	struct work_struct reclaim_work; /* reclaim worker */
 	struct list_head discard_clusters; /* discard clusters list */
-	struct plist_node avail_list;   /* entry in swap_avail_head */
 	const struct swap_ops *ops;
 };
 
diff --git a/lib/plist.c b/lib/plist.c
index b0273533c04d2a..b05ae7ffea87e8 100644
--- a/lib/plist.c
+++ b/lib/plist.c
@@ -142,65 +142,6 @@ void plist_del(struct plist_node *node, struct plist_head *head)
 	plist_check_head(head);
 }
 
-/**
- * plist_requeue - Requeue @node at end of same-prio entries.
- *
- * This is essentially an optimized plist_del() followed by
- * plist_add().  It moves an entry already in the plist to
- * after any other same-priority entries.
- *
- * @node:	&struct plist_node pointer - entry to be moved
- * @head:	&struct plist_head pointer - list head
- */
-void plist_requeue(struct plist_node *node, struct plist_head *head)
-{
-	struct plist_node *iter;
-	struct list_head *node_next = &head->node_list;
-
-	plist_check_head(head);
-	BUG_ON(plist_head_empty(head));
-	BUG_ON(plist_node_empty(node));
-
-	if (node == plist_last(head))
-		return;
-
-	iter = plist_next(node);
-
-	if (node->prio != iter->prio)
-		return;
-
-	plist_del(node, head);
-
-	/*
-	 * After plist_del(), iter is the replacement of the node.  If the node
-	 * was on prio_list, take shortcut to find node_next instead of looping.
-	 *
-	 * prio_list is a headless ring, so from the LAST bucket ->next wraps
-	 * round to the first one; in that case node_next is the list head.
-	 */
-	if (!list_empty(&iter->prio_list)) {
-		struct plist_node *first = plist_first(head);
-
-		if (iter->prio_list.next == &first->prio_list)
-			goto queue;
-		iter = list_entry(iter->prio_list.next, struct plist_node,
-				  prio_list);
-		node_next = &iter->node_list;
-		goto queue;
-	}
-
-	plist_for_each_continue(iter, head) {
-		if (node->prio != iter->prio) {
-			node_next = &iter->node_list;
-			break;
-		}
-	}
-queue:
-	list_add_tail(&node->node_list, node_next);
-
-	plist_check_head(head);
-}
-
 #ifdef CONFIG_DEBUG_PLIST
 #include <linux/sched.h>
 #include <linux/sched/clock.h>
@@ -238,14 +179,6 @@ static void __init plist_test_check(int nr_expect)
 	BUG_ON(prio_pos->prio_list.next != &first->prio_list);
 }
 
-static void __init plist_test_requeue(struct plist_node *node)
-{
-	plist_requeue(node, &test_head);
-
-	if (node != plist_last(&test_head))
-		BUG_ON(node->prio == plist_next(node)->prio);
-}
-
 static int  __init plist_test(void)
 {
 	int nr_expect = 0, i, loop;
@@ -269,10 +202,6 @@ static int  __init plist_test(void)
 			nr_expect--;
 		}
 		plist_test_check(nr_expect);
-		if (!plist_node_empty(test_node + i)) {
-			plist_test_requeue(test_node + i);
-			plist_test_check(nr_expect);
-		}
 	}
 
 	for (i = 0; i < ARRAY_SIZE(test_node); i++) {
diff --git a/mm/swap.h b/mm/swap.h
index d488a69c28091c..70fd3ab655ff81 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -108,16 +108,16 @@ static inline unsigned int swp_cluster_offset(swp_entry_t entry)
  */
 static inline struct swap_info_struct *__swap_type_to_info(int type)
 {
-	struct swap_info_struct *si;
-
-	si = READ_ONCE(swap_info[type]); /* rcu_dereference() */
-	VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */
-	return si;
+	return READ_ONCE(swap_info[type]); /* rcu_dereference() */
 }
 
 static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)
 {
-	return __swap_type_to_info(swp_type(entry));
+	struct swap_info_struct *si;
+
+	si = __swap_type_to_info(swp_type(entry)); /* rcu_dereference() */
+	VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */
+	return si;
 }
 
 static inline struct swap_cluster_info *__swap_offset_to_cluster(
diff --git a/mm/swapfile.c b/mm/swapfile.c
index fcda5eba171402..eb212813245598 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -6,6 +6,7 @@
  *  Swap reorganised 29.12.95, Stephen Tweedie
  */
 
+#include <linux/bitmap.h>
 #include <linux/blkdev.h>
 #include <linux/mm.h>
 #include <linux/sched/mm.h>
@@ -41,7 +42,6 @@
 #include <linux/completion.h>
 #include <linux/suspend.h>
 #include <linux/zswap.h>
-#include <linux/plist.h>
 
 #include <asm/tlbflush.h>
 #include <linux/leafops.h>
@@ -49,31 +49,38 @@
 #include "internal.h"
 #include "swap.h"
 
-static void swap_range_alloc(struct swap_info_struct *si,
-			     unsigned int nr_entries);
+static void swap_device_inuse_add(struct swap_info_struct *si,
+				  unsigned int nr_entries);
 static bool folio_swapcache_freeable(struct folio *folio);
 static void move_cluster(struct swap_info_struct *si,
 			 struct swap_cluster_info *ci, struct list_head *list,
 			 enum swap_cluster_flags new_flags);
+static bool get_swap_device_info(struct swap_info_struct *si);
 
 /*
- * Protects the swap_info array, and the SWP_USED flag. swap_info contains
- * lazily allocated & freed swap device info struts, and SWP_USED indicates
- * which device is used, ~SWP_USED devices and can be reused.
- *
- * Also protects swap_active_head total_swap_pages, and the SWP_WRITEOK flag.
+ * Serializes swapon/swapoff (writers) and protects the swap_info
+ * array, nr_swapfiles, total_swap_pages, and part of swap device
+ * info content (see comment of swap_info_struct).  Readers
+ * (allocation, /proc/swaps, etc.) take percpu_down_read() which
+ * is cheap as the hot path.
+ */
+DEFINE_STATIC_PERCPU_RWSEM(swapon_rwsem);
+/*
+ * swap_info contains lazily allocated swap device info structs, and
+ * SWP_USED indicates which device is used, ~SWP_USED devices can be
+ * reused. Protected by swapon_rwsem, but reading could be lockless.
  */
-static DEFINE_SPINLOCK(swap_lock);
+struct swap_info_struct *swap_info[MAX_SWAPFILES];
 static unsigned int nr_swapfiles;
-atomic_long_t nr_swap_pages;
+long total_swap_pages;
+
 /*
  * Some modules use swappable objects and may try to swap them out under
  * memory pressure (via the shrinker). Before doing so, they may wish to
  * check to see if any swap space is available.
  */
+atomic_long_t nr_swap_pages;
 EXPORT_SYMBOL_GPL(nr_swap_pages);
-/* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
-long total_swap_pages;
 #define DEF_SWAP_PRIO  -1
 unsigned long swapfile_maximum_size;
 #ifdef CONFIG_MIGRATION
@@ -83,52 +90,42 @@ bool swap_migration_ad_supported;
 static const char Bad_file[] = "Bad swap file entry ";
 static const char Bad_offset[] = "Bad swap offset entry ";
 
-/*
- * all active swap_info_structs
- * protected with swap_lock, and ordered by priority.
- */
-static PLIST_HEAD(swap_active_head);
+static inline struct swap_info_struct *__swap_iter(int *i, unsigned long flag)
+{
+	lockdep_assert_held(&swapon_rwsem);
+	while (*i < nr_swapfiles) {
+		struct swap_info_struct *si = __swap_type_to_info(*i);
+
+		VM_WARN_ON(!si);
+		(*i)++;
+		if (flag && !((si->flags & flag) == flag))
+			continue;
+		return si;
+	}
+	return NULL;
+}
+
+#define __for_each_swap(si, flag)			\
+	for (int __i = 0; ((si) = __swap_iter(&__i, flag));)
 
 /*
- * all available (active, not full) swap_info_structs
- * protected with swap_avail_lock, ordered by priority.
- * This is used by folio_alloc_swap() instead of swap_active_head
- * because swap_active_head includes all swap_info_structs,
- * but folio_alloc_swap() doesn't need to look at full ones.
- * This uses its own lock instead of swap_lock because when a
- * swap_info_struct changes between not-full/full, it needs to
- * add/remove itself to/from this list, but the swap_info_struct->lock
- * is held and the locking order requires swap_lock to be taken
- * before any swap_info_struct->lock.
+ * for_each_swap - iterate through all allocated and inuse swap devices
+ * @si: the iterator
+ *
+ * Context: The caller must hold swapon_rwsem. The lock may be dropped during
+ * the loop body but must be re-acquired before the next iteration.
  */
-static PLIST_HEAD(swap_avail_head);
-static DEFINE_SPINLOCK(swap_avail_lock);
-
-struct swap_info_struct *swap_info[MAX_SWAPFILES];
+#define for_each_swap(si) __for_each_swap(si, SWP_USED)
+#define for_each_avail_swap(si) __for_each_swap(si, SWP_USED | SWP_WRITEOK)
 
 static struct kmem_cache *swap_table_cachep;
 
-/* Protects si->swap_file for /proc/swaps usage */
-static DEFINE_MUTEX(swapon_mutex);
-
 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
 /* Activity counter to indicate that a swapon or swapoff has occurred */
 static atomic_t proc_poll_event = ATOMIC_INIT(0);
 
 atomic_t nr_rotate_swap = ATOMIC_INIT(0);
 
-struct percpu_swap_cluster {
-	struct swap_info_struct *si[SWAP_NR_ORDERS];
-	unsigned long offset[SWAP_NR_ORDERS];
-	local_lock_t lock;
-};
-
-static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) = {
-	.si = { NULL },
-	.offset = { SWAP_ENTRY_INVALID },
-	.lock = INIT_LOCAL_LOCK(),
-};
-
 /* May return NULL on invalid type, caller must check for NULL return */
 static struct swap_info_struct *swap_type_to_info(int type)
 {
@@ -143,18 +140,456 @@ static struct swap_info_struct *swap_entry_to_info(swp_entry_t entry)
 	return swap_type_to_info(swp_type(entry));
 }
 
+/*
+ * All available swap_info_structs are grouped by priority rings, the rings
+ * are ordered in a queue by priority (higher prio value = higher priority).
+ * The allocator iterates and rotates devices within each priority ring.
+ * When all devices in a ring are iterated, it goes to the next lower
+ * priority ring.
+ */
+struct swap_prio_ring {
+	int prio;
+	unsigned int size;
+	struct swap_info_struct *dev[] __counted_by(size);
+};
+
+/*
+ * The ring is protected by swapon_rwsem so updating it is costly. To make
+ * the allocator and other users skip full devices faster, the lowest bit of
+ * a device pointer is used to mark it disabled (temporarily unavailable).
+ * This relies on the natural alignment of struct swap_info_struct.
+ */
+#define SWAP_DEVICE_MASKED_SHIFT	0
+#define SWAP_DEVICE_MASKED_BIT		BIT(SWAP_DEVICE_MASKED_SHIFT)
+static_assert(__alignof__(struct swap_info_struct) >= 2);
+
+/*
+ * Serializes queue content mutations and keeps SWAP_USAGE_OFFLIST_BIT
+ * consistent with the masked state of each device pointer.
+ */
+static DEFINE_SPINLOCK(swap_queue_update_lock);
+
+/*
+ * Swap queue is protected by both swap_queue_update_lock and swapon_rwsem.
+ * Only swapon/swapoff will take the write lock, and modify the queue length
+ * or any ring's length. swap_queue_update_lock protects the content so
+ * devices can be masked easily without taking the writelock, which is heavy.
+ */
+static struct swap_prio_ring **swap_queue;
+static unsigned int swap_queue_len;
+
+/*
+ * Each CPU has its read iterator, so the queue itself will remain read
+ * only and the CPU side reader rotates by iterating the devices
+ * periodically using the counter.
+ */
+#define SWAP_ROUND_ROBIN_QUOTA SWAPFILE_CLUSTER
+struct swap_ring_iterator {
+	int offset;
+	long rr_counter;
+};
+
+struct swap_queue_reader {
+	local_lock_t lock;
+	struct swap_ring_iterator ri[];
+};
+
+struct swap_queue_cursor {
+	bool ring_only;
+	unsigned int ring_idx;
+	unsigned int offset;
+	unsigned int nr_iter;
+};
+
+static __percpu struct swap_queue_reader *swap_queue_readers;
+/* Keep the high-water capacity until the last priority ring is removed. */
+static unsigned int swap_queue_readers_capacity;
+
+static inline bool swap_device_masked(struct swap_info_struct *si)
+{
+	return (unsigned long)si & SWAP_DEVICE_MASKED_BIT;
+}
+
+static inline struct swap_info_struct *swap_device_mask_ptr(struct swap_info_struct *si)
+{
+	return (struct swap_info_struct *)((unsigned long)si |
+					   SWAP_DEVICE_MASKED_BIT);
+}
+
+static inline struct swap_info_struct *swap_device_unmask_ptr(struct swap_info_struct *si)
+{
+	return (struct swap_info_struct *)((unsigned long)si & ~SWAP_DEVICE_MASKED_BIT);
+}
+
+static struct swap_queue_reader __percpu *swap_queue_prealloc_readers(int nr_rings, gfp_t gfp)
+{
+	struct swap_queue_reader __percpu *readers;
+
+	if (!nr_rings)
+		return NULL;
+
+	readers = __alloc_percpu_gfp(struct_size(readers, ri, nr_rings),
+				     __alignof__(*readers), gfp);
+	return readers;
+}
+
+static bool swap_queue_needs_readers(int prio)
+{
+	unsigned int i;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	for (i = 0; i < swap_queue_len; i++) {
+		if (swap_queue[i]->prio == prio)
+			return false;
+	}
+
+	return swap_queue_len >= swap_queue_readers_capacity;
+}
+
+/*
+ * Return with swapon_rwsem held for writing, or unlocked on allocation failure.
+ * Per-CPU backing allocations may reclaim, so prepare them before publishing
+ * the device and outside the topology lock and our noreclaim scope. Keep NOIO
+ * because the swapon caller still holds the swapfile's inode lock.
+ */
+static int swap_queue_lock_for_add(int prio,
+				   struct swap_queue_reader __percpu **readers,
+				   unsigned int *nr_readers)
+{
+	*readers = NULL;
+	*nr_readers = 0;
+	for (;;) {
+		percpu_down_write(&swapon_rwsem);
+		if (!swap_queue_needs_readers(prio) ||
+		    *nr_readers > swap_queue_len)
+			return 0;
+
+		*nr_readers = swap_queue_len + 1;
+		percpu_up_write(&swapon_rwsem);
+		free_percpu(*readers);
+		*readers = swap_queue_prealloc_readers(*nr_readers, GFP_NOIO);
+		if (!*readers)
+			return -ENOMEM;
+	}
+}
+
+static void swap_queue_reset_readers(void)
+{
+	int ring_idx, cpu;
+	struct swap_prio_ring *ring;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	/* A new topology starts a fresh, distributed rotation on every CPU. */
+	for_each_possible_cpu(cpu) {
+		for (ring_idx = 0; ring_idx < swap_queue_len; ring_idx++) {
+			ring = swap_queue[ring_idx];
+			per_cpu_ptr(swap_queue_readers, cpu)->ri[ring_idx].offset =
+				    cpu % ring->size;
+			per_cpu_ptr(swap_queue_readers, cpu)->ri[ring_idx].rr_counter =
+				    SWAP_ROUND_ROBIN_QUOTA;
+		}
+	}
+}
+
+static void swap_queue_install_readers(struct swap_queue_reader __percpu *readers,
+				       unsigned int capacity)
+{
+	int cpu;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	free_percpu(swap_queue_readers);
+	swap_queue_readers = readers;
+	swap_queue_readers_capacity = capacity;
+	if (!readers)
+		return;
+
+	for_each_possible_cpu(cpu)
+		local_lock_init(&per_cpu_ptr(readers, cpu)->lock);
+	swap_queue_reset_readers();
+}
+
+static struct swap_info_struct *
+swap_queue_get_device(long nr_alloc, struct swap_queue_cursor *cursor)
+{
+	bool rotate = false;
+	struct swap_info_struct *si;
+	struct swap_ring_iterator *ri;
+	struct swap_prio_ring *ring;
+	unsigned int dev_idx, queue_idx, nr_iter;
+
+	queue_idx = cursor->ring_idx;
+	if (queue_idx >= swap_queue_len)
+		return ERR_PTR(-ENOENT);
+
+	ring = swap_queue[queue_idx];
+	if (cursor->nr_iter >= ring->size) {
+		if (cursor->ring_only)
+			return ERR_PTR(-E2BIG);
+		queue_idx = ++cursor->ring_idx;
+		if (queue_idx >= swap_queue_len)
+			return ERR_PTR(-ENOENT);
+		cursor->nr_iter = 0;
+		ring = swap_queue[queue_idx];
+	}
+
+	/* Consume masked peers too, so every walk remains bounded. */
+	nr_iter = cursor->nr_iter++;
+	if (ring->size == 1) {
+		si = READ_ONCE(ring->dev[0]);
+		goto check_device;
+	}
+
+	local_lock(&swap_queue_readers->lock);
+	ri = this_cpu_ptr(&swap_queue_readers->ri[queue_idx]);
+	/*
+	 * Snapshot the starting offset for this allocation's walk. The shared
+	 * iterator can move between retries, but the cursor must visit every
+	 * device in the ring exactly once before falling through.
+	 */
+	if (!nr_iter) {
+		if (ri->rr_counter < nr_alloc)
+			rotate = true;
+		else if (ri->offset >= ring->size)
+			rotate = true;
+		if (rotate) {
+			ri->offset++;
+			ri->offset %= ring->size;
+			ri->rr_counter = SWAP_ROUND_ROBIN_QUOTA;
+		}
+		cursor->offset = ri->offset;
+	}
+
+	dev_idx = (cursor->offset + nr_iter) % ring->size;
+	if (nr_iter) {
+		ri->offset = dev_idx;
+		ri->rr_counter = SWAP_ROUND_ROBIN_QUOTA;
+	}
+	ri->rr_counter -= nr_alloc;
+	si = READ_ONCE(ring->dev[dev_idx]);
+	local_unlock(&swap_queue_readers->lock);
+
+check_device:
+	if (swap_device_masked(si))
+		return ERR_PTR(-EBUSY);
+
+	si = swap_device_unmask_ptr(si);
+	return si;
+}
+
+static bool swap_queue_find(struct swap_info_struct *si,
+			    unsigned int *ring_idx, unsigned int *dev_idx)
+{
+	unsigned int i, j;
+	struct swap_prio_ring *ring;
+
+	lockdep_assert(lockdep_is_held(&swapon_rwsem) ||
+		       lockdep_is_held(&swap_queue_update_lock));
+
+	for (i = 0; i < swap_queue_len; i++) {
+		ring = swap_queue[i];
+		if (ring->prio != si->prio)
+			continue;
+		for (j = 0; j < ring->size; j++) {
+			if (swap_device_unmask_ptr(READ_ONCE(ring->dev[j])) != si)
+				continue;
+			*ring_idx = i;
+			*dev_idx = j;
+			return true;
+		}
+	}
+	return false;
+}
+
+static void swap_queue_mask(struct swap_info_struct *si)
+{
+	unsigned int ring_idx, dev_idx;
+
+	lockdep_assert_held(&swap_queue_update_lock);
+	if (swap_queue_find(si, &ring_idx, &dev_idx))
+		WRITE_ONCE(swap_queue[ring_idx]->dev[dev_idx],
+			   swap_device_mask_ptr(si));
+}
+
+static void swap_queue_unmask(struct swap_info_struct *si)
+{
+	unsigned int ring_idx, dev_idx;
+
+	lockdep_assert_held(&swap_queue_update_lock);
+	if (swap_queue_find(si, &ring_idx, &dev_idx))
+		WRITE_ONCE(swap_queue[ring_idx]->dev[dev_idx], si);
+}
+
+/* Prepared readers remain caller-owned unless installed successfully. */
+static int swap_queue_add(struct swap_info_struct *si,
+			  struct swap_queue_reader __percpu **readers,
+			  unsigned int nr_readers)
+{
+	struct swap_prio_ring **new_queue = NULL, **old_queue = NULL;
+	struct swap_prio_ring *ring, *new_ring = NULL, *old_ring = NULL;
+	int prio = si->prio;
+	int i, pos, err = -ENOMEM;
+	unsigned int noreclaim_flag;
+	gfp_t gfp;
+
+	/* A writer must not reclaim into another swap allocation. */
+	gfp = GFP_NOIO | __GFP_HIGH | __GFP_NOMEMALLOC;
+	lockdep_assert_held_write(&swapon_rwsem);
+	noreclaim_flag = memalloc_noreclaim_save();
+
+	for (pos = 0; pos < swap_queue_len; pos++) {
+		if (swap_queue[pos]->prio == prio)
+			goto add_to_ring;
+		if (swap_queue[pos]->prio < prio)
+			break;
+	}
+
+	/* No ring at this priority: insert a new one at pos. */
+	if (swap_queue_len >= swap_queue_readers_capacity &&
+	    (!*readers || nr_readers <= swap_queue_len))
+		goto failed;
+	new_queue = kmalloc_array(swap_queue_len + 1, sizeof(*swap_queue), gfp);
+	if (!new_queue)
+		goto failed;
+	new_ring = kmalloc(struct_size(new_ring, dev, 1), gfp);
+	if (!new_ring)
+		goto failed;
+	if (!get_swap_device_info(si))
+		goto failed;
+
+	new_ring->prio = prio;
+	new_ring->size = 1;
+	new_ring->dev[0] = si;
+	for (i = 0; i < pos; i++)
+		new_queue[i] = swap_queue[i];
+	new_queue[pos] = new_ring;
+	for (i = pos; i < swap_queue_len; i++)
+		new_queue[i + 1] = swap_queue[i];
+
+	spin_lock(&swap_queue_update_lock);
+	old_queue = swap_queue;
+	swap_queue = new_queue;
+	swap_queue_len++;
+	spin_unlock(&swap_queue_update_lock);
+	memalloc_noreclaim_restore(noreclaim_flag);
+	kfree(old_queue);
+
+	if (swap_queue_len > swap_queue_readers_capacity) {
+		swap_queue_install_readers(*readers, nr_readers);
+		*readers = NULL;
+	} else {
+		swap_queue_reset_readers();
+	}
+	return 0;
+
+add_to_ring:
+	ring = swap_queue[pos];
+	new_ring = kmalloc(struct_size(ring, dev, ring->size + 1), gfp);
+	if (!new_ring)
+		goto failed;
+	if (!get_swap_device_info(si))
+		goto failed;
+	spin_lock(&swap_queue_update_lock);
+	memcpy(new_ring, ring, struct_size(ring, dev, ring->size));
+	new_ring->size++;
+	new_ring->dev[new_ring->size - 1] = si;
+	old_ring = swap_queue[pos];
+	swap_queue[pos] = new_ring;
+	spin_unlock(&swap_queue_update_lock);
+	memalloc_noreclaim_restore(noreclaim_flag);
+	kfree(old_ring);
+	swap_queue_reset_readers();
+	return 0;
+
+failed:
+	memalloc_noreclaim_restore(noreclaim_flag);
+	kfree(new_queue);
+	kfree(new_ring);
+	return err;
+}
+
+static void swap_queue_del(struct swap_info_struct *si)
+{
+	gfp_t gfp;
+	unsigned int noreclaim_flag;
+	unsigned int ring_idx, dev_idx;
+	struct swap_prio_ring *ring, *new_ring = NULL, *old_ring = NULL;
+	struct swap_prio_ring **new_queue = NULL, **old_queue = NULL;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	if (!swap_queue_find(si, &ring_idx, &dev_idx)) {
+		WARN_ON(1);
+		return;
+	}
+
+	/*
+	 * Shrinking the small topology arrays is optional. Keep reader capacity
+	 * until the queue is empty: per-CPU allocation must not run under this
+	 * writer's noreclaim scope, which can grant backing pages reserve access.
+	 */
+	gfp = GFP_NOIO | __GFP_HIGH | __GFP_NOMEMALLOC;
+	noreclaim_flag = memalloc_noreclaim_save();
+	ring = swap_queue[ring_idx];
+	if (ring->size > 1)
+		new_ring = kmalloc(struct_size(ring, dev, ring->size - 1), gfp);
+	if (ring->size == 1 && swap_queue_len > 1) {
+		new_queue = kmalloc(sizeof(*swap_queue) *
+				    (swap_queue_len - 1), gfp);
+	}
+	memalloc_noreclaim_restore(noreclaim_flag);
+
+	spin_lock(&swap_queue_update_lock);
+	if (ring->size > 1) {
+		/* Shift trailing devices left to fill the gap. */
+		while (++dev_idx < ring->size)
+			ring->dev[dev_idx - 1] =
+				ring->dev[dev_idx];
+		ring->size--;
+		if (new_ring) {
+			memcpy(new_ring, ring,
+			       struct_size(ring, dev, ring->size));
+			old_ring = ring;
+			swap_queue[ring_idx] = new_ring;
+		}
+	} else {
+		/* Last device in this ring: remove the ring. */
+		old_ring = ring;
+		swap_queue_len--;
+		while (++ring_idx <= swap_queue_len)
+			swap_queue[ring_idx - 1] =
+				swap_queue[ring_idx];
+		if (new_queue) {
+			memcpy(new_queue, swap_queue,
+			       sizeof(*swap_queue) * swap_queue_len);
+			old_queue = swap_queue;
+			swap_queue = new_queue;
+		} else if (!swap_queue_len) {
+			old_queue = swap_queue;
+			swap_queue = NULL;
+		}
+		if (!swap_queue_len)
+			swap_queue_install_readers(NULL, 0);
+	}
+	spin_unlock(&swap_queue_update_lock);
+	if (swap_queue_len)
+		swap_queue_reset_readers();
+
+	kfree(old_ring);
+	kfree(old_queue);
+	put_swap_device(si);
+}
+
 /*
  * Use the second highest bit of inuse_pages counter as the indicator
- * if one swap device is on the available plist, so the atomic can
+ * if one swap device is unavailable for allocation, so the atomic can
  * still be updated arithmetically while having special data embedded.
  *
  * inuse_pages counter is the only thing indicating if a device should
- * be on avail_lists or not (except swapon / swapoff). By embedding the
- * off-list bit in the atomic counter, updates no longer need any lock
- * to check the list status.
+ * be in the available queue or not (except swapon / swapoff). By
+ * embedding the off-list bit in the atomic counter, updates no longer
+ * need any lock to check the list status.
  *
- * This bit will be set if the device is not on the plist and not
- * usable, will be cleared if the device is on the plist.
+ * This bit will be set if the device is not in the available queue
+ * and not usable, will be cleared if the device is in the queue.
  */
 #define SWAP_USAGE_OFFLIST_BIT (1UL << (BITS_PER_TYPE(atomic_long_t) - 2))
 #define SWAP_USAGE_COUNTER_MASK (~SWAP_USAGE_OFFLIST_BIT)
@@ -163,6 +598,26 @@ static long swap_usage_in_pages(struct swap_info_struct *si)
 	return atomic_long_read(&si->inuse_pages) & SWAP_USAGE_COUNTER_MASK;
 }
 
+/*
+ * Serialize the allocation on single CPU or globally to avoid
+ * fragmentation and make the workflow easier to follow.
+ */
+static void swap_alloc_lock_device(struct swap_info_struct *si)
+{
+	if (si->flags & SWP_SOLIDSTATE)
+		local_lock(&si->percpu_cluster->lock);
+	else
+		spin_lock(&si->global_cluster->lock);
+}
+
+static void swap_alloc_unlock_device(struct swap_info_struct *si)
+{
+	if (si->flags & SWP_SOLIDSTATE)
+		local_unlock(&si->percpu_cluster->lock);
+	else
+		spin_unlock(&si->global_cluster->lock);
+}
+
 /* Reclaim the swap entry anyway if possible */
 #define TTRS_ANYWAY		0x1
 /*
@@ -494,11 +949,8 @@ static int swap_cluster_alloc_table(struct swap_info_struct *si,
 
 lock:
 	if (!locked) {
-		if (si) {
-			local_lock(&percpu_swap_cluster.lock);
-			if (!(si->flags & SWP_SOLIDSTATE))
-				spin_lock(&si->global_cluster_lock);
-		}
+		if (si)
+			swap_alloc_lock_device(si);
 		spin_lock(&ci->lock);
 	}
 	lockdep_assert_held(&ci->lock);
@@ -569,22 +1021,24 @@ static void swap_cluster_assert_empty(struct swap_cluster_info *ci,
 }
 
 /*
- * Allocate swap table for one cluster. Attempt an atomic allocation first,
- * then fallback to sleeping allocation.
+ * Allocate swap table for one cluster. Attempt allocation under the locks
+ * first, then retry with the locks dropped without entering direct reclaim.
  */
 static struct swap_cluster_info *
 swap_cluster_populate(struct swap_info_struct *si,
 			 struct swap_cluster_info *ci)
 {
+	gfp_t gfp;
 	int ret;
 
 	/*
 	 * Only cluster isolation from the allocator does table allocation.
 	 * Swap allocator uses percpu clusters and holds the local lock.
 	 */
-	lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock);
-	if (!(si->flags & SWP_SOLIDSTATE))
-		lockdep_assert_held(&si->global_cluster_lock);
+	if (si->flags & SWP_SOLIDSTATE)
+		lockdep_assert_held(this_cpu_ptr(&si->percpu_cluster->lock));
+	else
+		lockdep_assert_held(&si->global_cluster->lock);
 	lockdep_assert_held(&ci->lock);
 
 	if (!swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
@@ -592,17 +1046,18 @@ swap_cluster_populate(struct swap_info_struct *si,
 		return ci;
 
 	/*
-	 * Try a sleep allocation. Each isolated free cluster may cause
-	 * a sleep allocation, but there is a limited number of them, so
-	 * the potential recursive allocation is limited.
+	 * Retry with the local and cluster locks dropped. The allocator can
+	 * still hold swapon_rwsem for reading: direct reclaim could enter
+	 * swap allocation again while a writer is waiting for this reader.
+	 * Restrict this request instead of granting the task PF_MEMALLOC,
+	 * which could give allocator hooks and failure cleanup reserve access.
 	 */
 	spin_unlock(&ci->lock);
-	if (!(si->flags & SWP_SOLIDSTATE))
-		spin_unlock(&si->global_cluster_lock);
-	local_unlock(&percpu_swap_cluster.lock);
+	swap_alloc_unlock_device(si);
 
-	ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
-					     GFP_KERNEL, false);
+	gfp = (GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC) &
+		~__GFP_DIRECT_RECLAIM;
+	ret = swap_cluster_alloc_table(si, ci, gfp, false);
 
 	/*
 	 * Back to atomic context. We might have migrated to a new CPU with a
@@ -705,44 +1160,40 @@ static struct swap_cluster_info *isolate_lock_cluster(
 }
 
 /*
- * Doing discard actually. After a cluster discard is finished, the cluster
- * will be added to free cluster list. Discard cluster is a bit special as
- * they don't participate in allocation or reclaim, so clusters marked as
- * CLUSTER_FLAG_DISCARD must remain off-list or on discard list.
+ * Discard one cluster. After the discard is finished, the cluster will be
+ * added to the free cluster list. Discard clusters are special because they
+ * don't participate in allocation or reclaim, so CLUSTER_FLAG_DISCARD must
+ * remain set while a cluster is either queued or being discarded.
  */
-static bool swap_do_scheduled_discard(struct swap_info_struct *si)
+static bool swap_discard_one_cluster(struct swap_info_struct *si)
 {
 	struct swap_cluster_info *ci;
-	bool ret = false;
 	unsigned int idx;
 
 	spin_lock(&si->lock);
-	while (!list_empty(&si->discard_clusters)) {
-		ci = list_first_entry(&si->discard_clusters, struct swap_cluster_info, list);
-		/*
-		 * Delete the cluster from list to prepare for discard, but keep
-		 * the CLUSTER_FLAG_DISCARD flag, percpu_swap_cluster could be
-		 * pointing to it, or ran into by relocate_cluster.
-		 */
-		list_del(&ci->list);
-		idx = cluster_index(si, ci);
+	if (list_empty(&si->discard_clusters)) {
 		spin_unlock(&si->lock);
-		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
-				SWAPFILE_CLUSTER);
-
-		spin_lock(&ci->lock);
-		/*
-		 * Discard is done, clear its flags as it's off-list, then
-		 * return the cluster to allocation list.
-		 */
-		ci->flags = CLUSTER_FLAG_NONE;
-		__free_cluster(si, ci);
-		spin_unlock(&ci->lock);
-		ret = true;
-		spin_lock(&si->lock);
+		return false;
 	}
+
+	ci = list_first_entry(&si->discard_clusters,
+			      struct swap_cluster_info, list);
+	/*
+	 * Delete the cluster from the list, but keep CLUSTER_FLAG_DISCARD
+	 * set while the discard is in flight. A percpu cluster may still
+	 * point to it, or relocate_cluster() may encounter it.
+	 */
+	list_del(&ci->list);
+	idx = cluster_index(si, ci);
 	spin_unlock(&si->lock);
-	return ret;
+
+	discard_swap_cluster(si, idx * SWAPFILE_CLUSTER, SWAPFILE_CLUSTER);
+
+	spin_lock(&ci->lock);
+	ci->flags = CLUSTER_FLAG_NONE;
+	__free_cluster(si, ci);
+	spin_unlock(&ci->lock);
+	return true;
 }
 
 static void swap_discard_work(struct work_struct *work)
@@ -751,7 +1202,8 @@ static void swap_discard_work(struct work_struct *work)
 
 	si = container_of(work, struct swap_info_struct, discard_work);
 
-	swap_do_scheduled_discard(si);
+	while (swap_discard_one_cluster(si))
+		cond_resched();
 }
 
 static void swap_users_ref_free(struct percpu_ref *ref)
@@ -1017,7 +1469,7 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 	if (cluster_is_empty(ci))
 		ci->order = order;
 	ci->count += nr_pages;
-	swap_range_alloc(si, nr_pages);
+	swap_device_inuse_add(si, nr_pages);
 
 	return true;
 }
@@ -1076,12 +1528,10 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 out:
 	relocate_cluster(si, ci);
 	swap_cluster_unlock(ci);
-	if (si->flags & SWP_SOLIDSTATE) {
-		this_cpu_write(percpu_swap_cluster.offset[order], next);
-		this_cpu_write(percpu_swap_cluster.si[order], si);
-	} else {
+	if (si->flags & SWP_SOLIDSTATE)
+		this_cpu_write(si->percpu_cluster->next[order], next);
+	else
 		si->global_cluster->next[order] = next;
-	}
 	return found;
 }
 
@@ -1182,13 +1632,13 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	if (order && !(si->flags & SWP_BLKDEV))
 		return 0;
 
-	if (!(si->flags & SWP_SOLIDSTATE)) {
-		/* Serialize HDD SWAP allocation for each device. */
-		spin_lock(&si->global_cluster_lock);
+	swap_alloc_lock_device(si);
+	if (si->flags & SWP_SOLIDSTATE)
+		offset = __this_cpu_read(si->percpu_cluster->next[order]);
+	else
 		offset = si->global_cluster->next[order];
-		if (offset == SWAP_ENTRY_INVALID)
-			goto new_cluster;
 
+	if (offset != SWAP_ENTRY_INVALID) {
 		ci = swap_cluster_lock(si, offset);
 		/* Cluster could have been used by another order */
 		if (cluster_is_usable(ci, order)) {
@@ -1202,7 +1652,6 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 			goto done;
 	}
 
-new_cluster:
 	if (swap_prefer_free_cluster(si)) {
 		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
 		if (found)
@@ -1255,8 +1704,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 			goto done;
 	}
 done:
-	if (!(si->flags & SWP_SOLIDSTATE))
-		spin_unlock(&si->global_cluster_lock);
+	swap_alloc_unlock_device(si);
 
 	return found;
 }
@@ -1266,54 +1714,47 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)
 {
 	unsigned long pages;
 
-	spin_lock(&swap_avail_lock);
+	spin_lock(&swap_queue_update_lock);
 
-	if (swapoff) {
-		/*
-		 * Forcefully remove it. Clear the SWP_WRITEOK flags for
-		 * swapoff here so it's synchronized by both si->lock and
-		 * swap_avail_lock, to ensure the result can be seen by
-		 * add_to_avail_list.
-		 */
-		lockdep_assert_held(&si->lock);
-		si->flags &= ~SWP_WRITEOK;
-		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
-	} else {
-		/*
-		 * If not called by swapoff, take it off-list only if it's
-		 * full and SWAP_USAGE_OFFLIST_BIT is not set (strictly
-		 * si->inuse_pages == pages), any concurrent slot freeing,
-		 * or device already removed from plist by someone else
-		 * will make this return false.
-		 */
+	/*
+	 * Force remove it only for swapoff. Else, take it off-list only if
+	 * it's full and SWAP_USAGE_OFFLIST_BIT is not set (strictly
+	 * si->inuse_pages == pages), so concurrent slot freeing, or
+	 * concurrent list removal will make the cmpxchg fail and skip
+	 * the removal.
+	 */
+	if (!swapoff) {
 		pages = si->pages;
 		if (!atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
 					     pages | SWAP_USAGE_OFFLIST_BIT))
 			goto skip;
+	} else {
+		lockdep_assert_held_write(&swapon_rwsem);
+		lockdep_assert_held(&si->lock);
+		si->flags &= ~SWP_WRITEOK;
+		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 	}
 
-	plist_del(&si->avail_list, &swap_avail_head);
-
+	swap_queue_mask(si);
 skip:
-	spin_unlock(&swap_avail_lock);
+	spin_unlock(&swap_queue_update_lock);
 }
 
 /* SWAP_USAGE_OFFLIST_BIT can only be cleared by this helper. */
-static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
+static void add_to_avail_list(struct swap_info_struct *si)
 {
 	long val;
 	unsigned long pages;
 
-	spin_lock(&swap_avail_lock);
+	spin_lock(&swap_queue_update_lock);
 
-	/* Corresponding to SWP_WRITEOK clearing in del_from_avail_list */
-	if (swapon) {
-		lockdep_assert_held(&si->lock);
-		si->flags |= SWP_WRITEOK;
-	} else {
-		if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
-			goto skip;
-	}
+	/*
+	 * Mark the device as avail if SWP_WRITEOK is set. Swapoff clears
+	 * SWP_WRITEOK first, so check that first so the device won't be
+	 * re-added after swapoff started.
+	 */
+	if (!(si->flags & SWP_WRITEOK))
+		goto skip;
 
 	if (!(atomic_long_read(&si->inuse_pages) & SWAP_USAGE_OFFLIST_BIT))
 		goto skip;
@@ -1321,72 +1762,55 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	val = atomic_long_fetch_and_relaxed(~SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 
 	/*
-	 * When device is full and device is on the plist, only one updater will
-	 * see (inuse_pages == si->pages) and will call del_from_avail_list. If
-	 * that updater happen to be here, just skip adding.
+	 * When device is full and marked as available, one reader will see
+	 * (inuse_pages == si->pages) and should mark it as unavailable and
+	 * set SWAP_USAGE_OFFLIST_BIT. If that updater happens to be here, just
+	 * skip the rest.
 	 */
 	pages = si->pages;
-	if (val == pages) {
+	if ((val & SWAP_USAGE_COUNTER_MASK) == pages) {
 		/* Just like the cmpxchg in del_from_avail_list */
 		if (atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
 					    pages | SWAP_USAGE_OFFLIST_BIT))
 			goto skip;
 	}
 
-	plist_add(&si->avail_list, &swap_avail_head);
-
+	swap_queue_unmask(si);
 skip:
-	spin_unlock(&swap_avail_lock);
+	spin_unlock(&swap_queue_update_lock);
 }
 
 /*
- * swap_usage_add / swap_usage_sub of each slot are serialized by ci->lock
- * within each cluster, so the total contribution to the global counter should
- * always be positive and cannot exceed the total number of usable slots.
+ * swap_device_inuse_add / swap_device_inuse_sub are called within cluster
+ * update critical sections and serialized by ci->lock within each cluster,
+ * so the total contribution to the global counter should always be positive
+ * and cannot exceed the total number of usable slots.
  */
-static bool swap_usage_add(struct swap_info_struct *si, unsigned int nr_entries)
+static void swap_device_inuse_add(struct swap_info_struct *si,
+				  unsigned int nr_entries)
 {
-	long val = atomic_long_add_return_relaxed(nr_entries, &si->inuse_pages);
+	long inuse_pages;
 
 	/*
 	 * If device is full, and SWAP_USAGE_OFFLIST_BIT is not set,
-	 * remove it from the plist.
+	 * mark it unavailable.
 	 */
-	if (unlikely(val == si->pages)) {
-		del_from_avail_list(si, false);
-		return true;
-	}
-
-	return false;
-}
-
-static void swap_usage_sub(struct swap_info_struct *si, unsigned int nr_entries)
-{
-	long val = atomic_long_sub_return_relaxed(nr_entries, &si->inuse_pages);
-
-	/*
-	 * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,
-	 * add it to the plist.
-	 */
-	if (unlikely(val & SWAP_USAGE_OFFLIST_BIT))
-		add_to_avail_list(si, false);
-}
-
-static void swap_range_alloc(struct swap_info_struct *si,
-			     unsigned int nr_entries)
-{
-	if (swap_usage_add(si, nr_entries)) {
+	inuse_pages = atomic_long_add_return_relaxed(nr_entries, &si->inuse_pages);
+	if (unlikely(inuse_pages == si->pages)) {
 		if (vm_swap_full())
 			schedule_work(&si->reclaim_work);
+		del_from_avail_list(si, false);
 	}
+
 	atomic_long_sub(nr_entries, &nr_swap_pages);
 }
 
-static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
-			    unsigned int nr_entries)
+static void swap_device_inuse_sub(struct swap_info_struct *si, unsigned long offset,
+				  unsigned int nr_entries)
 {
 	unsigned long end = offset + nr_entries - 1;
 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
+	long inuse_pages;
 
 	zswap_invalidate(si->type, offset, nr_entries);
 
@@ -1408,7 +1832,14 @@ static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
 	 */
 	smp_wmb();
 	atomic_long_add(nr_entries, &nr_swap_pages);
-	swap_usage_sub(si, nr_entries);
+
+	/*
+	 * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,
+	 * add it back to the available queue.
+	 */
+	inuse_pages = atomic_long_sub_return_relaxed(nr_entries, &si->inuse_pages);
+	if (unlikely(inuse_pages & SWAP_USAGE_OFFLIST_BIT))
+		add_to_avail_list(si);
 }
 
 static bool get_swap_device_info(struct swap_info_struct *si)
@@ -1418,113 +1849,95 @@ static bool get_swap_device_info(struct swap_info_struct *si)
 	/*
 	 * Guarantee the si->users are checked before accessing other
 	 * fields of swap_info_struct, and si->flags (SWP_WRITEOK) is
-	 * up to dated.
+	 * up to date.
 	 *
-	 * Paired with the spin_unlock() after setup_swap_info() in
-	 * enable_swap_info(), and smp_wmb() in swapoff.
+	 * Paired with percpu_up_write() in swap_device_enable(), and
+	 * smp_wmb() after clearing SWP_WRITEOK in swapoff.
 	 */
 	smp_rmb();
 	return true;
 }
 
-/*
- * Fast path try to get swap entries with specified order from current
- * CPU's swap entry pool (a cluster).
- */
-static bool swap_alloc_fast(struct folio *folio)
+static void swap_alloc_entry(struct folio *folio)
 {
-	unsigned int order = folio_order(folio);
-	struct swap_cluster_info *ci;
+	struct swap_queue_cursor cursor = {};
+	long nr_pages = folio_nr_pages(folio);
 	struct swap_info_struct *si;
-	unsigned int offset;
 
-	/*
-	 * Once allocated, swap_info_struct will never be completely freed,
-	 * so checking it's liveness by get_swap_device_info is enough.
-	 */
-	si = this_cpu_read(percpu_swap_cluster.si[order]);
-	offset = this_cpu_read(percpu_swap_cluster.offset[order]);
-	if (!si || !offset || !get_swap_device_info(si))
-		return false;
-
-	ci = swap_cluster_lock(si, offset);
-	if (cluster_is_usable(ci, order)) {
-		if (cluster_is_empty(ci))
-			offset = cluster_offset(si, ci);
-		alloc_swap_scan_cluster(si, ci, folio, offset);
-	} else {
-		swap_cluster_unlock(ci);
-	}
-
-	put_swap_device(si);
-	return folio_test_swapcache(folio);
-}
-
-/* Rotate the device and switch to a new cluster */
-static void swap_alloc_slow(struct folio *folio)
-{
-	struct swap_info_struct *si, *next;
-
-	spin_lock(&swap_avail_lock);
-start_over:
-	plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
-		/* Rotate the device and switch to a new cluster */
-		plist_requeue(&si->avail_list, &swap_avail_head);
-		spin_unlock(&swap_avail_lock);
-		if (get_swap_device_info(si)) {
-			cluster_alloc_swap_entry(si, folio);
-			put_swap_device(si);
-			if (folio_test_swapcache(folio))
-				return;
-			if (folio_test_large(folio))
-				return;
+	percpu_down_read(&swapon_rwsem);
+	migrate_disable();
+	for (;;) {
+		si = swap_queue_get_device(nr_pages, &cursor);
+		if (IS_ERR(si)) {
+			if (PTR_ERR(si) == -EBUSY)
+				continue;
+			break;
 		}
+		cluster_alloc_swap_entry(si, folio);
+
+		if (folio_test_swapcache(folio))
+			break;
 
-		spin_lock(&swap_avail_lock);
 		/*
-		 * if we got here, it's likely that si was almost full before,
-		 * multiple callers probably all tried to get a page from the
-		 * same si and it filled up before we could get one; or, the si
-		 * filled up between us dropping swap_avail_lock.
-		 * Since we dropped the swap_avail_lock, the swap_avail_list
-		 * may have been modified; so if next is still in the
-		 * swap_avail_head list then try it, otherwise start over if we
-		 * have not gotten any slots.
+		 * For large allocations, try every device at the same priority,
+		 * but ask the caller to split instead of falling back to a lower
+		 * priority ring.
 		 */
-		if (plist_node_empty(&next->avail_list))
-			goto start_over;
+		if (folio_test_large(folio)) {
+			cursor.ring_only = true;
+			continue;
+		}
 	}
-	spin_unlock(&swap_avail_lock);
+
+	migrate_enable();
+	percpu_up_read(&swapon_rwsem);
 }
 
 /*
- * Discard pending clusters in a synchronized way when under high pressure.
- * Return: true if any cluster is discarded.
+ * Discard outside the topology reader, holding only the selected device's
+ * live reference across I/O. Each successful retry starts a fresh queue walk.
  */
-static bool swap_sync_discard(void)
+static bool swap_discard_for_alloc(unsigned long *discarded)
 {
-	bool ret = false;
-	struct swap_info_struct *si, *next;
-
-	spin_lock(&swap_lock);
-start_over:
-	plist_for_each_entry_safe(si, next, &swap_active_head, list) {
-		spin_unlock(&swap_lock);
-		if (get_swap_device_info(si)) {
-			if (si->flags & SWP_PAGE_DISCARD)
-				ret = swap_do_scheduled_discard(si);
-			put_swap_device(si);
+	DECLARE_BITMAP(checked, MAX_SWAPFILES) = {};
+	struct swap_info_struct *si, *candidate;
+	unsigned int i, j;
+	bool done;
+	int type;
+
+	for (;;) {
+		candidate = NULL;
+		percpu_down_read(&swapon_rwsem);
+		for (i = 0; i < swap_queue_len && !candidate; i++) {
+			struct swap_prio_ring *ring = swap_queue[i];
+
+			for (j = 0; j < ring->size; j++) {
+				si = swap_device_unmask_ptr(READ_ONCE(ring->dev[j]));
+				type = si->type;
+				if (test_bit(type, discarded) || test_bit(type, checked))
+					continue;
+				__set_bit(type, checked);
+				if ((READ_ONCE(si->flags) & (SWP_WRITEOK | SWP_PAGE_DISCARD)) !=
+				    (SWP_WRITEOK | SWP_PAGE_DISCARD))
+					continue;
+				if (get_swap_device_info(si)) {
+					candidate = si;
+					break;
+				}
+			}
 		}
-		if (ret)
-			return true;
+		percpu_up_read(&swapon_rwsem);
+		if (!candidate)
+			return false;
 
-		spin_lock(&swap_lock);
-		if (plist_node_empty(&next->list))
-			goto start_over;
+		type = candidate->type;
+		done = swap_discard_one_cluster(candidate);
+		if (done)
+			__set_bit(type, discarded);
+		put_swap_device(candidate);
+		if (done)
+			return true;
 	}
-	spin_unlock(&swap_lock);
-
-	return false;
 }
 
 static int swap_extend_table_alloc(struct swap_info_struct *si,
@@ -1828,15 +2241,16 @@ int folio_alloc_swap(struct folio *folio)
 		}
 	}
 
-again:
-	local_lock(&percpu_swap_cluster.lock);
-	if (!swap_alloc_fast(folio))
-		swap_alloc_slow(folio);
-	local_unlock(&percpu_swap_cluster.lock);
+	swap_alloc_entry(folio);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
-		if (swap_sync_discard())
-			goto again;
+		DECLARE_BITMAP(discarded, MAX_SWAPFILES) = {};
+
+		while (swap_discard_for_alloc(discarded)) {
+			swap_alloc_entry(folio);
+			if (folio_test_swapcache(folio))
+				break;
+		}
 	}
 
 	/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */
@@ -2036,7 +2450,7 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 	if (batch_id)
 		mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
 
-	swap_range_free(si, ci_head + ci_start, nr_pages);
+	swap_device_inuse_sub(si, ci_head + ci_start, nr_pages);
 	swap_cluster_assert_empty(ci, ci_start, nr_pages, false);
 
 	if (!ci->count)
@@ -2238,31 +2652,14 @@ void swap_put_entries_direct(swp_entry_t entry, int nr)
  */
 swp_entry_t swap_alloc_hibernation_slot(int type)
 {
-	struct swap_info_struct *pcp_si, *si = swap_type_to_info(type);
-	unsigned long pcp_offset, offset = SWAP_ENTRY_INVALID;
-	struct swap_cluster_info *ci;
+	struct swap_info_struct *si = swap_type_to_info(type);
+	unsigned long offset = SWAP_ENTRY_INVALID;
 	swp_entry_t entry = {0};
 
 	if (!si)
 		goto fail;
 
-	/*
-	 * Try the local cluster first if it matches the device. If
-	 * not, try grab a new cluster and override local cluster.
-	 */
-	local_lock(&percpu_swap_cluster.lock);
-	pcp_si = this_cpu_read(percpu_swap_cluster.si[0]);
-	pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);
-	if (pcp_si == si && pcp_offset) {
-		ci = swap_cluster_lock(si, pcp_offset);
-		if (cluster_is_usable(ci, 0))
-			offset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset);
-		else
-			swap_cluster_unlock(ci);
-	}
-	if (!offset)
-		offset = cluster_alloc_swap_entry(si, NULL);
-	local_unlock(&percpu_swap_cluster.lock);
+	offset = cluster_alloc_swap_entry(si, NULL);
 	if (offset)
 		entry = swp_entry(si->type, offset);
 
@@ -2289,26 +2686,18 @@ void swap_free_hibernation_slot(swp_entry_t entry)
 
 static int __find_hibernation_swap_type(dev_t device, sector_t offset)
 {
-	int type;
-
-	lockdep_assert_held(&swap_lock);
+	struct swap_info_struct *si;
 
 	if (!device)
 		return -EINVAL;
 
-	for (type = 0; type < nr_swapfiles; type++) {
-		struct swap_info_struct *sis = swap_info[type];
-
-		if (!(sis->flags & SWP_WRITEOK))
-			continue;
-
-		if (device == sis->bdev->bd_dev) {
-			struct swap_extent *se = first_se(sis);
-
-			if (se->start_block == offset)
-				return type;
+	for_each_avail_swap(si) {
+		if (device == si->bdev->bd_dev) {
+			if (first_se(si)->start_block == offset)
+				return si->type;
 		}
 	}
+
 	return -ENODEV;
 }
 
@@ -2331,21 +2720,18 @@ static int __find_hibernation_swap_type(dev_t device, sector_t offset)
  */
 int pin_hibernation_swap_type(dev_t device, sector_t offset)
 {
-	int type;
+	int ret;
 	struct swap_info_struct *si;
 
-	spin_lock(&swap_lock);
-
-	type = __find_hibernation_swap_type(device, offset);
-	if (type < 0) {
-		spin_unlock(&swap_lock);
-		return type;
-	}
+	percpu_down_write(&swapon_rwsem);
+	ret = __find_hibernation_swap_type(device, offset);
+	if (ret < 0)
+		goto out;
 
-	si = swap_type_to_info(type);
+	si = swap_type_to_info(ret);
 	if (WARN_ON_ONCE(!si)) {
-		spin_unlock(&swap_lock);
-		return -ENODEV;
+		ret = -ENODEV;
+		goto out;
 	}
 
 	/*
@@ -2354,14 +2740,15 @@ int pin_hibernation_swap_type(dev_t device, sector_t offset)
 	 * the same session.
 	 */
 	if (WARN_ON_ONCE(si->flags & SWP_HIBERNATION)) {
-		spin_unlock(&swap_lock);
-		return -EBUSY;
+		ret = -EBUSY;
+		goto out;
 	}
 
 	si->flags |= SWP_HIBERNATION;
 
-	spin_unlock(&swap_lock);
-	return type;
+out:
+	percpu_up_write(&swapon_rwsem);
+	return ret;
 }
 
 /**
@@ -2372,7 +2759,7 @@ int pin_hibernation_swap_type(dev_t device, sector_t offset)
  *
  * Look up the swap device for @device/@offset and atomically transfer
  * the SWP_HIBERNATION pin from @old_type (if valid) to the new device,
- * all under a single swap_lock critical section. This closes the
+ * all under a single swapon_rwsem writer section. This closes the
  * swapoff() window that exists when callers unpin and re-pin in two
  * separate operations.
  *
@@ -2392,28 +2779,28 @@ int repin_hibernation_swap_type(int old_type, dev_t device, sector_t offset)
 	struct swap_info_struct *old_si, *new_si;
 	int new_type;
 
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 
 	new_type = __find_hibernation_swap_type(device, offset);
 	if (new_type < 0) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return new_type;
 	}
 
 	new_si = swap_type_to_info(new_type);
 	if (WARN_ON_ONCE(!new_si)) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return -ENODEV;
 	}
 
 	old_si = swap_type_to_info(old_type);
 	if (new_si == old_si) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return new_type;
 	}
 
 	if (WARN_ON_ONCE(new_si->flags & SWP_HIBERNATION)) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return -EBUSY;
 	}
 
@@ -2421,7 +2808,7 @@ int repin_hibernation_swap_type(int old_type, dev_t device, sector_t offset)
 		old_si->flags &= ~SWP_HIBERNATION;
 	new_si->flags |= SWP_HIBERNATION;
 
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	return new_type;
 }
 
@@ -2439,14 +2826,11 @@ void unpin_hibernation_swap_type(int type)
 {
 	struct swap_info_struct *si;
 
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	si = swap_type_to_info(type);
-	if (!si) {
-		spin_unlock(&swap_lock);
-		return;
-	}
-	si->flags &= ~SWP_HIBERNATION;
-	spin_unlock(&swap_lock);
+	if (si)
+		si->flags &= ~SWP_HIBERNATION;
+	percpu_up_write(&swapon_rwsem);
 }
 
 /**
@@ -2471,29 +2855,26 @@ int find_hibernation_swap_type(dev_t device, sector_t offset)
 {
 	int type;
 
-	spin_lock(&swap_lock);
+	percpu_down_read(&swapon_rwsem);
 	type = __find_hibernation_swap_type(device, offset);
-	spin_unlock(&swap_lock);
+	percpu_up_read(&swapon_rwsem);
 
 	return type;
 }
 
 int find_first_swap(dev_t *device)
 {
-	int type;
-
-	spin_lock(&swap_lock);
-	for (type = 0; type < nr_swapfiles; type++) {
-		struct swap_info_struct *sis = swap_info[type];
+	int ret = -ENODEV;
+	struct swap_info_struct *si;
 
-		if (!(sis->flags & SWP_WRITEOK))
-			continue;
-		*device = sis->bdev->bd_dev;
-		spin_unlock(&swap_lock);
-		return type;
+	percpu_down_read(&swapon_rwsem);
+	for_each_avail_swap(si) {
+		*device = si->bdev->bd_dev;
+		ret = si->type;
+		break;
 	}
-	spin_unlock(&swap_lock);
-	return -ENODEV;
+	percpu_up_read(&swapon_rwsem);
+	return ret;
 }
 
 /*
@@ -2521,7 +2902,7 @@ unsigned int count_swap_pages(int type, int free)
 {
 	unsigned int n = 0;
 
-	spin_lock(&swap_lock);
+	percpu_down_read(&swapon_rwsem);
 	if ((unsigned int)type < nr_swapfiles) {
 		struct swap_info_struct *sis = swap_info[type];
 
@@ -2533,7 +2914,7 @@ unsigned int count_swap_pages(int type, int free)
 		}
 		spin_unlock(&sis->lock);
 	}
-	spin_unlock(&swap_lock);
+	percpu_up_read(&swapon_rwsem);
 	return n;
 }
 #endif /* CONFIG_HIBERNATION */
@@ -2859,10 +3240,10 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 	unsigned long swp_tb;
 
 	/*
-	 * No need for swap_lock here: we're just looking
+	 * No need for swapon_rwsem here: we're just looking
 	 * for whether an entry is in use, not modifying it; false
 	 * hits are okay, and sys_swapoff() has already prevented new
-	 * allocations from this area (while holding swap_lock).
+	 * allocations from this area (while holding swapon_rwsem).
 	 */
 	i = prev + 1;
 	while (i < si->max) {
@@ -2992,7 +3373,7 @@ static int try_to_unuse(unsigned int type)
 success:
 	/*
 	 * Make sure that further cleanups after try_to_unuse() returns happen
-	 * after swap_range_free() reduces si->inuse_pages to 0.
+	 * after swap_device_inuse_sub() reduces si->inuse_pages to 0.
 	 */
 	smp_mb();
 	return 0;
@@ -3000,18 +3381,20 @@ static int try_to_unuse(unsigned int type)
 
 /*
  * After a successful try_to_unuse, if no swap is now in use, we know
- * we can empty the mmlist.  swap_lock must be held on entry and exit.
- * Note that mmlist_lock nests inside swap_lock, and an mm must be
+ * we can empty the mmlist. swapon_rwsem must be held on entry and exit.
+ * Note that mmlist_lock nests inside swapon_rwsem, and an mm must be
  * added to the mmlist just after page_duplicate - before would be racy.
  */
 static void drain_mmlist(void)
 {
+	struct swap_info_struct *si;
 	struct list_head *p, *next;
-	unsigned int type;
 
-	for (type = 0; type < nr_swapfiles; type++)
-		if (swap_usage_in_pages(swap_info[type]))
+	for_each_swap(si) {
+		if (swap_usage_in_pages(si))
 			return;
+	}
+
 	spin_lock(&mmlist_lock);
 	list_for_each_safe(p, next, &init_mm.mmlist)
 		list_del_init(p);
@@ -3145,58 +3528,86 @@ static int setup_swap_extents(struct swap_info_struct *sis,
 	return generic_swapfile_activate(sis, swap_file, span);
 }
 
-static void _enable_swap_info(struct swap_info_struct *si)
-{
-	atomic_long_add(si->pages, &nr_swap_pages);
-	total_swap_pages += si->pages;
-
-	assert_spin_locked(&swap_lock);
-
-	plist_add(&si->list, &swap_active_head);
-
-	/* Add back to available list */
-	add_to_avail_list(si, true);
-}
-
 /*
- * Called after the swap device is ready, resurrect its percpu ref, it's now
- * safe to reference it. Add it to the list to expose it to the allocator.
+ * Mark a fully initialized swap device writable and expose it to the allocator.
+ * The caller must have resurrected its percpu ref before entering this helper.
  */
-static void enable_swap_info(struct swap_info_struct *si)
+static void __swap_device_enable(struct swap_info_struct *si)
 {
-	percpu_ref_resurrect(&si->users);
-	spin_lock(&swap_lock);
+	lockdep_assert_held_write(&swapon_rwsem);
 	spin_lock(&si->lock);
-	_enable_swap_info(si);
+	spin_lock(&swap_queue_update_lock);
+	si->flags |= SWP_WRITEOK;
+	spin_unlock(&swap_queue_update_lock);
 	spin_unlock(&si->lock);
-	spin_unlock(&swap_lock);
+	atomic_long_add(si->pages, &nr_swap_pages);
+	total_swap_pages += si->pages;
+	add_to_avail_list(si);
 }
 
-static void reinsert_swap_info(struct swap_info_struct *si)
+static void swap_device_enable(struct swap_info_struct *si)
 {
-	spin_lock(&swap_lock);
-	spin_lock(&si->lock);
-	_enable_swap_info(si);
-	spin_unlock(&si->lock);
-	spin_unlock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
+	__swap_device_enable(si);
+	percpu_up_write(&swapon_rwsem);
 }
 
-/*
- * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range
- * see the updated flags, so there will be no more allocations.
- */
-static void wait_for_allocation(struct swap_info_struct *si)
+static int swap_device_disable(struct address_space *mapping,
+			       struct swap_info_struct **swap_info)
 {
-	unsigned long offset;
-	unsigned long end = ALIGN(si->max, SWAPFILE_CLUSTER);
+	struct swap_info_struct *si;
 	struct swap_cluster_info *ci;
+	unsigned long offset, end;
+	int err = -EINVAL;
+
+	percpu_down_write(&swapon_rwsem);
+	for_each_avail_swap(si) {
+		if (si->swap_file->f_mapping == mapping) {
+			err = 0;
+			break;
+		}
+	}
+	if (err)
+		goto unlock;
+
+	/*
+	 * Refuse swapoff while the device is pinned for hibernation.
+	 */
+	if (si->flags & SWP_HIBERNATION) {
+		err = -EBUSY;
+		goto unlock;
+	}
+
+	if (security_vm_enough_memory_mm(current->mm, si->pages)) {
+		err = -ENOMEM;
+		goto unlock;
+	}
+	vm_unacct_memory(si->pages);
+
+	/* Serialize with the WRITEOK check in isolate_lock_cluster(). */
+	spin_lock(&si->lock);
+	del_from_avail_list(si, true);
+	spin_unlock(&si->lock);
+	total_swap_pages -= si->pages;
+	atomic_long_sub(si->pages, &nr_swap_pages);
 
-	BUG_ON(si->flags & SWP_WRITEOK);
+	end = ALIGN(si->max, SWAPFILE_CLUSTER);
+unlock:
+	percpu_up_write(&swapon_rwsem);
+	if (err)
+		return err;
 
+	/*
+	 * Drain cluster-lock users after clearing SWP_WRITEOK, so swapoff
+	 * does not race with operations that started before the transition.
+	 */
 	for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) {
 		ci = swap_cluster_lock(si, offset);
 		swap_cluster_unlock(ci);
 	}
+
+	*swap_info = si;
+	return 0;
 }
 
 static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
@@ -3220,28 +3631,6 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
 	kvfree(cluster_info);
 }
 
-/*
- * Called after swap device's reference count is dead, so
- * neither scan nor allocation will use it.
- */
-static void flush_percpu_swap_cluster(struct swap_info_struct *si)
-{
-	int cpu, i;
-	struct swap_info_struct **pcp_si;
-
-	for_each_possible_cpu(cpu) {
-		pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);
-		/*
-		 * Invalidate the percpu swap cluster cache, si->users
-		 * is dead, so no new user will point to it, just flush
-		 * any existing user.
-		 */
-		for (i = 0; i < SWAP_NR_ORDERS; i++)
-			cmpxchg(&pcp_si[i], si, NULL);
-	}
-}
-
-
 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 {
 	struct swap_info_struct *p = NULL;
@@ -3250,7 +3639,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	struct address_space *mapping;
 	struct inode *inode;
 	unsigned int maxpages;
-	int err, found = 0;
+	int err;
 
 	if (!capable(CAP_SYS_ADMIN))
 		return -EPERM;
@@ -3263,44 +3652,11 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 		return PTR_ERR(victim);
 
 	mapping = victim->f_mapping;
-	spin_lock(&swap_lock);
-	plist_for_each_entry(p, &swap_active_head, list) {
-		if (p->flags & SWP_WRITEOK) {
-			if (p->swap_file->f_mapping == mapping) {
-				found = 1;
-				break;
-			}
-		}
-	}
-	if (!found) {
-		err = -EINVAL;
-		spin_unlock(&swap_lock);
-		goto out_dput;
-	}
-
-	/* Refuse swapoff while the device is pinned for hibernation */
-	if (p->flags & SWP_HIBERNATION) {
-		err = -EBUSY;
-		spin_unlock(&swap_lock);
-		goto out_dput;
-	}
-
-	if (!security_vm_enough_memory_mm(current->mm, p->pages))
-		vm_unacct_memory(p->pages);
-	else {
-		err = -ENOMEM;
-		spin_unlock(&swap_lock);
-		goto out_dput;
-	}
-	spin_lock(&p->lock);
-	del_from_avail_list(p, true);
-	plist_del(&p->list, &swap_active_head);
-	atomic_long_sub(p->pages, &nr_swap_pages);
-	total_swap_pages -= p->pages;
-	spin_unlock(&p->lock);
-	spin_unlock(&swap_lock);
+	err = swap_device_disable(mapping, &p);
+	filp_close(victim, NULL);
 
-	wait_for_allocation(p);
+	if (err)
+		return err;
 
 	set_current_oom_origin();
 	err = try_to_unuse(p->type);
@@ -3308,10 +3664,15 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	if (err) {
 		/* re-insert swap space back into swap_list */
-		reinsert_swap_info(p);
-		goto out_dput;
+		swap_device_enable(p);
+		return err;
 	}
 
+	percpu_down_write(&swapon_rwsem);
+	swap_queue_del(p);
+	percpu_ref_kill(&p->users);
+	percpu_up_write(&swapon_rwsem);
+
 	/*
 	 * Wait for swap operations protected by get/put_swap_device()
 	 * to complete.  Because of synchronize_rcu() here, all swap
@@ -3320,21 +3681,18 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	 * prevent folio_test_swapcache() and the following swap cache
 	 * operations from racing with swapoff.
 	 */
-	percpu_ref_kill(&p->users);
 	synchronize_rcu();
 	wait_for_completion(&p->comp);
 
 	flush_work(&p->discard_work);
 	flush_work(&p->reclaim_work);
-	flush_percpu_swap_cluster(p);
 
 	destroy_swap_extents(p, p->swap_file);
 
 	if (!(p->flags & SWP_SOLIDSTATE))
 		atomic_dec(&nr_rotate_swap);
 
-	mutex_lock(&swapon_mutex);
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	spin_lock(&p->lock);
 	drain_mmlist();
 
@@ -3345,10 +3703,11 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	p->max = 0;
 	p->cluster_info = NULL;
 	spin_unlock(&p->lock);
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	arch_swap_invalidate_area(p->type);
 	zswap_swapoff(p->type);
-	mutex_unlock(&swapon_mutex);
+	free_percpu(p->percpu_cluster);
+	p->percpu_cluster = NULL;
 	kfree(p->global_cluster);
 	p->global_cluster = NULL;
 	free_swap_cluster_info(cluster_info, maxpages);
@@ -3364,18 +3723,19 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	 * Clear the SWP_USED flag after all resources are freed so that swapon
 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
 	 * not hold p->lock after we cleared its SWP_WRITEOK.
+	 *
+	 * The write lock ensures the flag clear is visible to lockless
+	 * readers of swap_type_to_info() before alloc_swap_info() reuses
+	 * this slot.
 	 */
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	p->flags = 0;
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 
-	err = 0;
 	atomic_inc(&proc_poll_event);
 	wake_up_interruptible(&proc_poll_wait);
 
-out_dput:
-	filp_close(victim, NULL);
-	return err;
+	return 0;
 }
 
 #ifdef CONFIG_PROC_FS
@@ -3393,20 +3753,18 @@ static __poll_t swaps_poll(struct file *file, poll_table *wait)
 	return EPOLLIN | EPOLLRDNORM;
 }
 
-/* iterator */
 static void *swap_start(struct seq_file *swap, loff_t *pos)
 {
 	struct swap_info_struct *si;
-	int type;
 	loff_t l = *pos;
 
-	mutex_lock(&swapon_mutex);
+	percpu_down_read(&swapon_rwsem);
 
 	if (!l)
 		return SEQ_START_TOKEN;
 
-	for (type = 0; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+	for_each_swap(si) {
+		if (!si->swap_file)
 			continue;
 		if (!--l)
 			return si;
@@ -3427,7 +3785,7 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
 
 	++(*pos);
 	for (; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+		if (!(si->flags & SWP_USED) || !(si->swap_file))
 			continue;
 		return si;
 	}
@@ -3437,7 +3795,7 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
 
 static void swap_stop(struct seq_file *swap, void *v)
 {
-	mutex_unlock(&swapon_mutex);
+	percpu_up_read(&swapon_rwsem);
 }
 
 static int swap_show(struct seq_file *swap, void *v)
@@ -3530,13 +3888,13 @@ static struct swap_info_struct *alloc_swap_info(void)
 		return ERR_PTR(-ENOMEM);
 	}
 
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	for (type = 0; type < nr_swapfiles; type++) {
 		if (!(swap_info[type]->flags & SWP_USED))
 			break;
 	}
 	if (type >= MAX_SWAPFILES) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		percpu_ref_exit(&p->users);
 		kvfree(p);
 		return ERR_PTR(-EPERM);
@@ -3558,10 +3916,8 @@ static struct swap_info_struct *alloc_swap_info(void)
 		 */
 	}
 	p->swap_extent_root = RB_ROOT;
-	plist_node_init(&p->list, 0);
-	plist_node_init(&p->avail_list, 0);
 	p->flags = SWP_USED;
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	if (defer) {
 		percpu_ref_exit(&defer->users);
 		kvfree(defer);
@@ -3630,9 +3986,8 @@ __weak unsigned long arch_max_swapfile_size(void)
 	return generic_max_swapfile_size();
 }
 
-static unsigned long read_swap_header(struct swap_info_struct *si,
-					union swap_header *swap_header,
-					struct inode *inode)
+static unsigned long read_swap_header(union swap_header *swap_header,
+				      struct inode *inode)
 {
 	int i;
 	unsigned long maxpages;
@@ -3699,7 +4054,7 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 {
 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 	struct swap_cluster_info *cluster_info;
-	int err = -ENOMEM;
+	int cpu, err = -ENOMEM;
 	unsigned long i;
 
 	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
@@ -3709,13 +4064,26 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	for (i = 0; i < nr_clusters; i++)
 		spin_lock_init(&cluster_info[i].lock);
 
-	if (!(si->flags & SWP_SOLIDSTATE)) {
+	if (si->flags & SWP_SOLIDSTATE) {
+		si->percpu_cluster = alloc_percpu(struct percpu_cluster);
+		if (!si->percpu_cluster)
+			goto err;
+
+		for_each_possible_cpu(cpu) {
+			struct percpu_cluster *cluster;
+
+			cluster = per_cpu_ptr(si->percpu_cluster, cpu);
+			for (i = 0; i < SWAP_NR_ORDERS; i++)
+				cluster->next[i] = SWAP_ENTRY_INVALID;
+			local_lock_init(&cluster->lock);
+		}
+	} else {
 		si->global_cluster = kmalloc_obj(*si->global_cluster);
 		if (!si->global_cluster)
 			goto err;
 		for (i = 0; i < SWAP_NR_ORDERS; i++)
 			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
-		spin_lock_init(&si->global_cluster_lock);
+		spin_lock_init(&si->global_cluster->lock);
 	}
 
 	/*
@@ -3776,6 +4144,8 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 {
 	struct swap_info_struct *si;
+	struct swap_queue_reader __percpu *readers;
+	unsigned int nr_readers;
 	struct file *swap_file = NULL;
 	struct address_space *mapping;
 	struct dentry *dentry;
@@ -3798,7 +4168,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	/*
 	 * Allocate or reuse existing !SWP_USED swap_info. The returned
 	 * si will stay in a dying status, so nothing will access its content
-	 * until enable_swap_info resurrects its percpu ref and expose it.
+	 * until swap_device_enable resurrects its percpu ref and expose it.
 	 */
 	si = alloc_swap_info();
 	if (IS_ERR(si))
@@ -3863,7 +4233,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	}
 	swap_header = kmap_local_folio(folio, 0);
 
-	maxpages = read_swap_header(si, swap_header, inode);
+	maxpages = read_swap_header(swap_header, inode);
 	if (unlikely(!maxpages)) {
 		error = -EINVAL;
 		goto bad_swap_unlock_inode;
@@ -3951,22 +4321,38 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		goto free_swap_zswap;
 	}
 
-	mutex_lock(&swapon_mutex);
 	prio = DEF_SWAP_PRIO;
 	if (swap_flags & SWAP_FLAG_PREFER)
 		prio = swap_flags & SWAP_FLAG_PRIO_MASK;
 
+	si->prio = prio;
+
 	/*
-	 * The plist prio is negated because plist ordering is
-	 * low-to-high, while swap ordering is high-to-low
+	 * Publish swap_file before making the percpu ref live, then add the device
+	 * to the queue and make it writable under the same write-side lock. This
+	 * keeps lockless ref users and /proc/swaps from observing partial state.
 	 */
-	si->prio = prio;
-	si->list.prio = -si->prio;
-	si->avail_list.prio = -si->prio;
+	error = swap_queue_lock_for_add(prio, &readers, &nr_readers);
+	if (error) {
+		inode->i_flags &= ~S_SWAPFILE;
+		goto free_swap_zswap;
+	}
 	si->swap_file = swap_file;
-
-	/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */
-	enable_swap_info(si);
+	percpu_ref_resurrect(&si->users);
+	error = swap_queue_add(si, &readers, nr_readers);
+	if (error) {
+		si->swap_file = NULL;
+		percpu_ref_kill(&si->users);
+	} else {
+		__swap_device_enable(si);
+	}
+	percpu_up_write(&swapon_rwsem);
+	free_percpu(readers);
+	if (error) {
+		wait_for_completion(&si->comp);
+		inode->i_flags &= ~S_SWAPFILE;
+		goto free_swap_zswap;
+	}
 
 	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
 		K(si->pages), name->name, si->prio, nr_extents,
@@ -3976,7 +4362,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		(si->flags & SWP_AREA_DISCARD) ? "s" : "",
 		(si->flags & SWP_PAGE_DISCARD) ? "c" : "");
 
-	mutex_unlock(&swapon_mutex);
 	atomic_inc(&proc_poll_event);
 	wake_up_interruptible(&proc_poll_wait);
 
@@ -3987,6 +4372,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 bad_swap_unlock_inode:
 	inode_unlock(inode);
 bad_swap:
+	free_percpu(si->percpu_cluster);
+	si->percpu_cluster = NULL;
 	kfree(si->global_cluster);
 	si->global_cluster = NULL;
 	inode = NULL;
@@ -3997,9 +4384,9 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	 * Clear the SWP_USED flag after all resources are freed so
 	 * alloc_swap_info can reuse this si safely.
 	 */
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	si->flags = 0;
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	if (inced_nr_rotate_swap)
 		atomic_dec(&nr_rotate_swap);
 	if (swap_file)
@@ -4014,19 +4401,17 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 
 void si_swapinfo(struct sysinfo *val)
 {
-	unsigned int type;
+	struct swap_info_struct *si;
 	unsigned long nr_to_be_unused = 0;
 
-	spin_lock(&swap_lock);
-	for (type = 0; type < nr_swapfiles; type++) {
-		struct swap_info_struct *si = swap_info[type];
-
-		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
+	percpu_down_read(&swapon_rwsem);
+	for_each_swap(si) {
+		if (!(si->flags & SWP_WRITEOK))
 			nr_to_be_unused += swap_usage_in_pages(si);
 	}
 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
 	val->totalswap = total_swap_pages + nr_to_be_unused;
-	spin_unlock(&swap_lock);
+	percpu_up_read(&swapon_rwsem);
 }
 
 /*
@@ -4066,7 +4451,33 @@ int swap_dup_entry_direct(swp_entry_t entry)
 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
 static bool __has_usable_swap(void)
 {
-	return !plist_head_empty(&swap_active_head);
+	return READ_ONCE(total_swap_pages) > 0;
+}
+
+static struct swap_info_struct *swap_queue_first_usable_bdev(void)
+{
+	struct swap_prio_ring *ring;
+	struct swap_info_struct *si;
+	unsigned int ring_idx, dev_idx;
+
+	lockdep_assert_held(&swapon_rwsem);
+	for (ring_idx = 0; ring_idx < swap_queue_len; ring_idx++) {
+		ring = swap_queue[ring_idx];
+		for (dev_idx = 0; dev_idx < ring->size; dev_idx++) {
+			si = READ_ONCE(ring->dev[dev_idx]);
+			if (swap_device_masked(si))
+				continue;
+			si = swap_device_unmask_ptr(si);
+			if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
+				continue;
+			if (atomic_long_read(&si->inuse_pages) &
+			    SWAP_USAGE_OFFLIST_BIT)
+				continue;
+			if (si->bdev)
+				return si;
+		}
+	}
+	return NULL;
 }
 
 void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
@@ -4089,14 +4500,11 @@ void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
 	if (current->throttle_disk)
 		return;
 
-	spin_lock(&swap_avail_lock);
-	plist_for_each_entry(si, &swap_avail_head, avail_list) {
-		if (si->bdev) {
-			blkcg_schedule_throttle(si->bdev->bd_disk, true);
-			break;
-		}
-	}
-	spin_unlock(&swap_avail_lock);
+	percpu_down_read(&swapon_rwsem);
+	si = swap_queue_first_usable_bdev();
+	if (si)
+		blkcg_schedule_throttle(si->bdev->bd_disk, true);
+	percpu_up_read(&swapon_rwsem);
 }
 #endif
 

3/2 2026/11/18 16:15 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31004
							output: 27
							thoughts: 671
						

Thoughts:
**Fuzzing Decision for a Major Swap Refactor**

Okay, let's break this down. We have a substantial patch here, a deep dive into swap management, and my initial gut feeling is that this *screams* for fuzzing. This isn't some minor tweak; we're talking about a significant redesign, a wholesale refactoring of core memory management (`mm/`) code, specifically involving swap device handling and allocation. The patch touches numerous files: `plist.h`, `swap.h`, `plist.c`, `swapfile.c` -- all the bread-and-butter of swap management. It’s making changes to key data structures: `swap_info_struct`, `percpu_cluster`, `swap_prio_ring`, `swapon_rwsem`, and the fundamental swap allocation process. The overhaul includes the `swapon` and `swapoff` syscalls, hibernation swap, `/proc/swaps`, etc. This is a big deal!

The kernel's documentation, specifically Section 3, clearly designates memory management (`mm/`) as a core subsystem that *always* merits fuzzing when modified. Furthermore, this patch checks all the boxes: it's a refactoring, it involves restructuring of reachable data structures (swap management is clearly a reachable data structure), and it's likely to impact algorithm flows. The refactoring aspect is probably the biggest red flag.

The question then becomes: Is this code reachable? Absolutely! `swapon`, `swapoff`, memory pressure causing swap allocation (`folio_alloc_swap`), reading `/proc/swaps`, and system information like `sysinfo` are standard targets for fuzzing and frequently exercised by syzkaller.

Therefore, WorthFuzzing = True. Now, let's dig into the details to figure out which configurations are needed to compile and reach this code. Time to start looking at Kconfig for `mm/swapfile.c`...



4/2 2026/11/18 16:16 tool grepper
0m Args:
{
  "Expression": "swapfile\\.o",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/Makefile=78=endif\nmm/Makefile-79-\nmm/Makefile:80:obj-$(CONFIG_SWAP)\t+= page_io.o swap_state.o swapfile.o\nmm/Makefile-81-obj-$(CONFIG_ZSWAP)\t+= zswap.o\n"
}

5/2 2026/11/18 16:16 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32195
							output: 19
							thoughts: 32
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Investigating a CONFIG_SWAP Dependency**

Right, so `CONFIG_SWAP` is clearly a requirement here. The immediate question is where is that configuration option defined, and potentially, what are its dependencies? Given the typical structure of the kernel source, my first instinct is to check `init/Kconfig` or `mm/Kconfig`. Those are the usual suspects for memory management related features, and swap is, of course, a core memory management concept. I'll need to confirm its location to understand its inclusion conditions and any potential interactions with other kernel components. Time to dive into those Kconfig files...



6/2 2026/11/18 16:16 tool grepper
0m Args:
{
  "Expression": "config SWAP\\b"
}

Results:
{
  "Output": "mm/Kconfig=9=config ARCH_NO_SWAP\n--\nmm/Kconfig-11-\nmm/Kconfig:12:menuconfig SWAP\nmm/Kconfig-13-\tbool \"Support for paging of anonymous memory (swap)\"\n"
}

7/2 2026/11/18 16:16 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32465
							output: 31
							thoughts: 102
						

Thoughts:
**Examining Swapfile Configuration Dependencies**

Okay, let's dive in. I need to make sure I haven't missed any relevant configurations in `swapfile.c`. First, I'm thinking about `CONFIG_MEMCG` and `CONFIG_BLK_CGROUP` – are they used for `__folio_throttle_swaprate`, that's an important consideration. Then, there's `CONFIG_HIBERNATION` - that one obviously brings in hibernation-specific swap functions. Ultimately, `CONFIG_SWAP` seems to be the core, the big one that drives the compilation of `mm/swapfile.c`. Now, let me just go and quickly read the surrounding lines in `mm/Kconfig` to get a better grasp of its dependencies and implications in the broader context.



8/2 2026/11/18 16:17 tool read-file
0m Args:
{
  "File": "mm/Kconfig",
  "FirstLine": 10,
  "LineCount": 30
}

Results:
{
  "Contents": "  10:\t\tbool\n  11:\t\n  12:\tmenuconfig SWAP\n  13:\t\tbool \"Support for paging of anonymous memory (swap)\"\n  14:\t\tdepends on MMU \u0026\u0026 BLOCK \u0026\u0026 !ARCH_NO_SWAP\n  15:\t\tdefault y\n  16:\t\thelp\n  17:\t\t  This option allows you to choose whether you want to have support\n  18:\t\t  for so called swap devices or swap files in your kernel that are\n  19:\t\t  used to provide more virtual memory than the actual RAM present\n  20:\t\t  in your computer.  If unsure say Y.\n  21:\t\n  22:\tconfig ZSWAP\n  23:\t\tbool \"Compressed cache for swap pages\"\n  24:\t\tdepends on SWAP\n  25:\t\tselect CRYPTO\n  26:\t\tselect ZSMALLOC\n  27:\t\thelp\n  28:\t\t  A lightweight compressed cache for swap pages.  It takes\n  29:\t\t  pages that are in the process of being swapped out and attempts to\n  30:\t\t  compress them into a dynamically allocated RAM-based memory pool.\n  31:\t\t  This can result in a significant I/O reduction on swap device and,\n  32:\t\t  in the case where decompressing from RAM is faster than swap device\n  33:\t\t  reads, can also improve workload performance.\n  34:\t\n  35:\tconfig ZSWAP_DEFAULT_ON\n  36:\t\tbool \"Enable the compressed cache for swap pages by default\"\n  37:\t\tdepends on ZSWAP\n  38:\t\thelp\n  39:\t\t  If selected, the compressed cache for swap pages will be enabled\n"
}

9/2 2026/11/18 16:17 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33186
							output: 28
							thoughts: 824
						

Thoughts:
**Focusing on Swap Functionality for Fuzzing**

Okay, so `CONFIG_SWAP` hinges on `MMU` and `BLOCK`, that much is clear. Now, let's figure out the optimal `FocusSymbols` for effective fuzzing. We need to avoid dilution and guide the fuzzer towards specific feature logic. According to the instructions, we *must* avoid ubiquitous lifecycle functions – things like memory allocators, page fault handlers, and core synchronization primitives. Listing those will just cause the fuzzer to waste time. Instead, we need to focus on functions that *specifically* implement the added or altered logic, or API entry points. Also, a key point: dealing with static inline functions can be tricky. Since they lack distinct symbol addresses, we must identify non-static, feature-specific caller functions that *exercise* those inlines.

Right, so let's zero in on `mm/swapfile.c` and identify the key functions that are either new, modified, or act as entry points. Looking at the list, we have: the system call entry points `__do_sys_swapon`, `sys_swapon`, `swapon`, `__do_sys_swapoff`, `sys_swapoff`, `swapoff`; the core allocation entry point `folio_alloc_swap` (and importantly, its static caller `swap_alloc_entry`); and then a bunch of queue management, device enable/disable, cluster allocation/population, discard, and list manipulation functions: `swap_queue_add`, `swap_queue_del`, `swap_queue_get_device`, `swap_device_enable`, `swap_device_disable`, `cluster_alloc_swap_entry`, `alloc_swap_scan_cluster`, `swap_cluster_populate`, `swap_discard_for_alloc`, `swap_discard_one_cluster`, `del_from_avail_list`, `add_to_avail_list`. Also, `si_swapinfo` and hibernation-related functions: `pin_hibernation_swap_type`, `repin_hibernation_swap_type`, `unpin_hibernation_swap_type`, `find_hibernation_swap_type`, and `find_first_swap`.

Wait a minute, how are these system calls named in the vmlinux symbols on amd64/x86_64? I need to check the actual naming convention. I'll use either `grepper`, `nm`, or `objdump` if they're available, or just go with standard naming conventions. I recall that `SYSCALL_DEFINE1` and `SYSCALL_DEFINE2` are used, but the exact symbol can be different. It could be `__do_sys_swapon`, `__se_sys_swapon`, `__x64_sys_swapon` or `__do_sys_swapon`. I need to be precise.

Also, `folio_alloc_swap` is exported or used throughout mm? That's a good candidate to see how it's actually used. Let's trace all callers of `folio_alloc_swap` to understand the bigger picture of this swap functionality.



10/2 2026/11/18 16:18 tool grepper
0m Args:
{
  "Expression": "folio_alloc_swap",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/shmem.c=1845=int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,\n--\nmm/shmem.c-1933-\nmm/shmem.c:1934:\tret = folio_alloc_swap(folio);\nmm/shmem.c-1935-\tif (!ret) {\n--\nmm/swap.h=226=extern int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp);\n--\nmm/swap.h-234- *\nmm/swap.h:235: * folio_alloc_swap(): the entry point for a folio to be swapped\nmm/swap.h-236- * out. It allocates swap slots and pins the slots with swap cache.\n--\nmm/swap.h-246- */\nmm/swap.h:247:int folio_alloc_swap(struct folio *folio);\nmm/swap.h-248-int folio_dup_swap(struct folio *folio, struct page *page);\n--\nmm/swap.h=380=static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)\n--\nmm/swap.h-384-\nmm/swap.h:385:static inline int folio_alloc_swap(struct folio *folio)\nmm/swap.h-386-{\n--\nmm/swapfile.c=1425=static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,\n--\nmm/swapfile.c-1438-\t/*\nmm/swapfile.c:1439:\t * All mm swap allocation starts with a folio (folio_alloc_swap),\nmm/swapfile.c-1440-\t * it's also the only allocation path for large orders allocation.\n--\nmm/swapfile.c=2172=static int swap_dup_entries_cluster(struct swap_info_struct *si,\n--\nmm/swapfile.c-2206-/**\nmm/swapfile.c:2207: * folio_alloc_swap - allocate swap space for a folio\nmm/swapfile.c-2208- * @folio: folio we want to move to swap\n--\nmm/swapfile.c-2217- */\nmm/swapfile.c:2218:int folio_alloc_swap(struct folio *folio)\nmm/swapfile.c-2219-{\n--\nmm/swapfile.c=3280=static int try_to_unuse(unsigned int type)\n--\nmm/swapfile.c-3363-\t * and even shmem_writeout() could have been preempted after\nmm/swapfile.c:3364:\t * folio_alloc_swap(), temporarily hiding that swap.  It's easy\nmm/swapfile.c-3365-\t * and robust (though cpu-intensive) just to keep retrying.\n--\nmm/vmscan.c=1048=static unsigned int shrink_folio_list(struct list_head *folio_list,\n--\nmm/vmscan.c-1271-\t\t\t}\nmm/vmscan.c:1272:\t\t\tret = folio_alloc_swap(folio);\nmm/vmscan.c-1273-\t\t\tif (ret) {\n--\nmm/vmscan.c-1290-\t\t\t\tcount_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);\nmm/vmscan.c:1291:\t\t\t\tif (folio_alloc_swap(folio))\nmm/vmscan.c-1292-\t\t\t\t\tgoto activate_locked_split;\n"
}

11/2 2026/11/18 16:18 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35644
							output: 34
							thoughts: 464
						

Thoughts:
**Analyzing Swap Allocation Entry Points**

Okay, so `folio_alloc_swap` is the key entry point for swap allocation. But is it *the* only one? No, of course not. It's not universally hit, only when memory reclaim actively swaps out anonymous or shmem pages. In the context of syzkaller, programs that are designed to trigger swap or stress memory will hit it, which is ideal for testing.

Now, let's dive deeper. I need to examine the static functions within `mm/swapfile.c` that have been modified or newly introduced. This is where the core logic likely resides. The following functions look important: `swap_queue_add`, `swap_queue_del`, `swap_queue_get_device`, `swap_alloc_entry`, `swap_device_enable`, `swap_device_disable`, `cluster_alloc_swap_entry`, `alloc_swap_scan_cluster`, `swap_cluster_populate`, `del_from_avail_list`, `add_to_avail_list`, `swap_discard_for_alloc`, `swap_discard_one_cluster`, and `setup_swap_clusters_info`.

Wait, are static functions even exposed as symbols in the `vmlinux` image? In a standard kernel build, and especially with debug info and kallsyms, static functions *are* symbols in `kallsyms` and `vmlinux`, unless aggressively inlined by the compiler, which is unlikely for all of these. So, to be thorough, I should include both the main entry point and these relevant static functions that implement core logic and are unlikely to be fully inlined. This should ensure effective coverage.

Hold on, what about `swapon` and `swapoff` system calls? I need to consider these as well. Let me check how syzkaller or the kernel's symbol tables represent the `SYSCALL_DEFINE` macros that define those system calls. It's usually something like `__do_sys_swapon`, `__do_sys_swapoff`, or perhaps `__x64_sys_swapon`, `__x64_sys_swapoff`, `sys_swapon`, or `sys_swapoff`. I need to confirm whether `grepper` (or another tool) can directly show the other `SYSCALL_DEFINE` symbols, or if there's a good way to determine this programmatically. I should also check how the `SYSCALL_DEFINE` macro itself generates function names. This might reveal a pattern.



12/2 2026/11/18 16:19 tool grepper
0m Args:
{
  "Expression": "__do_sys_",
  "PathPrefixes": [
    "include/linux/syscalls.h"
  ]
}

Results:
{
  "Output": "include/linux/syscalls.h=212=static inline int is_syscall_trace_event(struct trace_event_call *tp_event)\n--\ninclude/linux/syscalls.h-243- * sign-extends 32-bit ints to longs whenever needed. The actual work is\ninclude/linux/syscalls.h:244: * done within __do_sys_*().\ninclude/linux/syscalls.h-245- */\n"
}

13/2 2026/11/18 16:19 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36810
							output: 36
							thoughts: 75
						

Thoughts:
Okay, let me think this through.

**Investigating Swapon System Call Implementations**

Right, so I'm seeing that, on x86_64, the system call `swapon` has a few incarnations: `__do_sys_swapon`, `__se_sys_swapon`, and `__x64_sys_swapon`. Interesting. I need to understand the relationship and implementation details. Where is the common definition?

Let me step back and think, the macros must be defined somewhere. To understand the relationship between those, let's explore how `SYSCALL_DEFINE` is actually implemented, since that's what's likely behind these variations. Time to check `include/linux/syscalls.h`. That's where I expect to find the magic.



14/2 2026/11/18 16:19 tool grepper
0m Args:
{
  "Expression": "__do_sys_##name",
  "PathPrefixes": [
    "include/linux/syscalls.h"
  ]
}

Results:
{
  "Output": "no matches"
}

15/2 2026/11/18 16:19 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37107
							output: 36
							thoughts: 21
						

Thoughts:
Here's a first-person summary, tailored for an expert audience, based on the prompt:

**Diving into `syscalls.h`**

Alright, let's get down to brass tacks. Based on the initial context, I think it's time to dig into `include/linux/syscalls.h`. Knowing the kernel's architecture, I immediately zero in on line 240. I expect to find a declaration or definition related to a system call, probably a macro or a function prototype. My expertise tells me that this file holds the critical glue between user space and kernel space, and this specific line is likely a piece of that puzzle. It's time to get a good look at the system call table, arguments, and return types. From here, I can examine its implementation.



16/2 2026/11/18 16:20 tool read-file
0m Args:
{
  "File": "include/linux/syscalls.h",
  "FirstLine": 235,
  "LineCount": 40
}

Results:
{
  "Contents": " 235:\t#define SYSCALL_DEFINEx(x, sname, ...)\t\t\t\t\\\n 236:\t\tSYSCALL_METADATA(sname, x, __VA_ARGS__)\t\t\t\\\n 237:\t\t__SYSCALL_DEFINEx(x, sname, __VA_ARGS__)\n 238:\t\n 239:\t#define __PROTECT(...) asmlinkage_protect(__VA_ARGS__)\n 240:\t\n 241:\t/*\n 242:\t * The asmlinkage stub is aliased to a function named __se_sys_*() which\n 243:\t * sign-extends 32-bit ints to longs whenever needed. The actual work is\n 244:\t * done within __do_sys_*().\n 245:\t */\n 246:\t#ifndef __SYSCALL_DEFINEx\n 247:\t#define __SYSCALL_DEFINEx(x, name, ...)\t\t\t\t\t\\\n 248:\t\t__diag_push();\t\t\t\t\t\t\t\\\n 249:\t\t__diag_ignore(GCC, 8, \"-Wattribute-alias\",\t\t\t\\\n 250:\t\t\t      \"Type aliasing is used to sanitize syscall arguments\");\\\n 251:\t\t__diag_ignore(clang, 23, \"-Wunknown-warning-option\",\t\t\\\n 252:\t\t\t      \"Avoid breaking versions without -Wattribute-alias\");\\\n 253:\t\t__diag_ignore(clang, 23, \"-Wattribute-alias\",\t\t\t\\\n 254:\t\t\t      \"Type aliasing is used to sanitize syscall arguments\");\\\n 255:\t\tasmlinkage long sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))\t\\\n 256:\t\t\t__attribute__((alias(__stringify(__se_sys##name))));\t\\\n 257:\t\tALLOW_ERROR_INJECTION(sys##name, ERRNO);\t\t\t\\\n 258:\t\tstatic inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\\\n 259:\t\tasmlinkage long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__));\t\\\n 260:\t\tasmlinkage long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__))\t\\\n 261:\t\t{\t\t\t\t\t\t\t\t\\\n 262:\t\t\tlong ret = __do_sys##name(__MAP(x,__SC_CAST,__VA_ARGS__));\\\n 263:\t\t\t__MAP(x,__SC_TEST,__VA_ARGS__);\t\t\t\t\\\n 264:\t\t\t__PROTECT(x, ret,__MAP(x,__SC_ARGS,__VA_ARGS__));\t\\\n 265:\t\t\treturn ret;\t\t\t\t\t\t\\\n 266:\t\t}\t\t\t\t\t\t\t\t\\\n 267:\t\t__diag_pop();\t\t\t\t\t\t\t\\\n 268:\t\tstatic inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))\n 269:\t#endif /* __SYSCALL_DEFINEx */\n 270:\t\n 271:\t/* For split 64-bit arguments on 32-bit architectures */\n 272:\t#ifdef __LITTLE_ENDIAN\n 273:\t#define SC_ARG64(name) u32, name##_lo, u32, name##_hi\n 274:\t#else\n"
}

17/2 2026/11/18 16:20 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38180
							output: 33
							thoughts: 50
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Examining x86-64 System Call Wrappers**

Alright, let's dive into this. Thinking about system calls on x86-64, I know the architecture uses specific wrappers. My immediate thought is, let's get right to the source. I need to refresh my memory on how they're handled at the assembly level. The file I want is `arch/x86/include/asm/syscall_wrapper.h`. I'll use it to understand the exact mechanics of these wrappers, focusing on how they're defined and implemented within the kernel. I need to see how the system call interface is structured in this specific architecture and how it differs from others. What I'm most interested in is how it handles argument passing, register usage, and the transition into kernel mode. The nuances are always the devil in the details, so let's get into the specifics.



18/2 2026/11/18 16:21 tool grepper
0m Args:
{
  "Expression": "__x64_sys",
  "PathPrefixes": [
    "arch/x86/"
  ]
}

Results:
{
  "Output": "arch/x86/entry/syscall_64.c=37=static noinline long x64_sys_call(const struct pt_regs *regs, unsigned int nr)\n--\narch/x86/entry/syscall_64.c-40-\t#include \u003casm/syscalls_64.h\u003e\narch/x86/entry/syscall_64.c:41:\tdefault: return __x64_sys_ni_syscall(regs);\narch/x86/entry/syscall_64.c-42-\t}\n--\narch/x86/entry/syscall_64.c=45=static noinline long x32_sys_call(const struct pt_regs *regs, unsigned int nr)\n--\narch/x86/entry/syscall_64.c-49-\t#include \u003casm/syscalls_x32.h\u003e\narch/x86/entry/syscall_64.c:50:\tdefault: return __x64_sys_ni_syscall(regs);\narch/x86/entry/syscall_64.c-51-\t}\n--\narch/x86/entry/syscalls/syscall_64.tbl-7-#\narch/x86/entry/syscalls/syscall_64.tbl:8:# The __x64_sys_*() stubs are created on-the-fly for sys_*() system calls\narch/x86/entry/syscalls/syscall_64.tbl-9-#\n--\narch/x86/entry/vsyscall/vsyscall_64.c=119=static bool __emulate_vsyscall(struct pt_regs *regs, unsigned long address)\n--\narch/x86/entry/vsyscall/vsyscall_64.c-217-\t\t/* this decodes regs-\u003edi and regs-\u003esi on its own */\narch/x86/entry/vsyscall/vsyscall_64.c:218:\t\tret = __x64_sys_gettimeofday(regs);\narch/x86/entry/vsyscall/vsyscall_64.c-219-\t\tbreak;\n--\narch/x86/entry/vsyscall/vsyscall_64.c-222-\t\t/* this decodes regs-\u003edi on its own */\narch/x86/entry/vsyscall/vsyscall_64.c:223:\t\tret = __x64_sys_time(regs);\narch/x86/entry/vsyscall/vsyscall_64.c-224-\t\tbreak;\n--\narch/x86/entry/vsyscall/vsyscall_64.c-230-\t\t/* this decodes regs-\u003edi, regs-\u003esi and regs-\u003edx on its own */\narch/x86/entry/vsyscall/vsyscall_64.c:231:\t\tret = __x64_sys_getcpu(regs);\narch/x86/entry/vsyscall/vsyscall_64.c-232-\t\tregs-\u003edx = orig_dx;\n--\narch/x86/include/asm/ftrace.h=130=static inline bool arch_syscall_match_sym_name(const char *sym, const char *name)\n--\narch/x86/include/asm/ftrace.h-133-\t * Compare the symbol name with the system call name. Skip the\narch/x86/include/asm/ftrace.h:134:\t * \"__x64_sys\", \"__ia32_sys\", \"__do_sys\" or simple \"sys\" prefix.\narch/x86/include/asm/ftrace.h-135-\t */\n--\narch/x86/include/asm/syscall_wrapper.h-10-\narch/x86/include/asm/syscall_wrapper.h:11:extern long __x64_sys_ni_syscall(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h-12-extern long __ia32_sys_ni_syscall(const struct pt_regs *regs);\n--\narch/x86/include/asm/syscall_wrapper.h-16- * struct pt_regs *regs as the only argument of the syscall stub(s) named as:\narch/x86/include/asm/syscall_wrapper.h:17: * __x64_sys_*()         - 64-bit native syscall\narch/x86/include/asm/syscall_wrapper.h-18- * __ia32_sys_*()        - 32-bit native syscall or common compat syscall\n--\narch/x86/include/asm/syscall_wrapper.h-33- *\narch/x86/include/asm/syscall_wrapper.h:34: * \u003c__x64_sys_recv\u003e:\t\t\u003c-- syscall with 4 parameters\narch/x86/include/asm/syscall_wrapper.h-35- *\tcallq\t\u003c__fentry__\u003e\n--\narch/x86/include/asm/syscall_wrapper.h-259- */\narch/x86/include/asm/syscall_wrapper.h:260:long __x64_sys_getcpu(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h:261:long __x64_sys_gettimeofday(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h:262:long __x64_sys_time(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h-263-\n"
}

19/2 2026/11/18 16:21 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39859
							output: 43
							thoughts: 35
						

Thoughts:
Here's a summary of my mental process:

**Diving into the System Call Wrapper**

Okay, let's get down to brass tacks. I need to understand how these system calls are being handled at a fundamental level in the x86 architecture. Time to crack open `arch/x86/include/asm/syscall_wrapper.h`. I'm particularly interested in lines 200 through 240, as that's likely where the core of the wrapping mechanism, whatever it may be, is implemented or at least defined in this file. Let's see what gems we can find there. This is where the magic happens, or at least, this is one of the places where the magic happens.



20/2 2026/11/18 16:22 tool read-file
0m Args:
{
  "File": "arch/x86/include/asm/syscall_wrapper.h",
  "FirstLine": 200,
  "LineCount": 45
}

Results:
{
  "Contents": " 200:\t\t__do_compat_sys_##name(const struct pt_regs *__unused)\n 201:\t\n 202:\t#define COMPAT_SYSCALL_DEFINEx(x, name, ...)\t\t\t\t\t\\\n 203:\t\tstatic long __se_compat_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__));\t\\\n 204:\t\tstatic inline long __do_compat_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\\\n 205:\t\t__IA32_COMPAT_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 206:\t\t__X32_COMPAT_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 207:\t\tstatic long __se_compat_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__))\t\\\n 208:\t\t{\t\t\t\t\t\t\t\t\t\\\n 209:\t\t\treturn __do_compat_sys##name(__MAP(x,__SC_DELOUSE,__VA_ARGS__));\\\n 210:\t\t}\t\t\t\t\t\t\t\t\t\\\n 211:\t\tstatic inline long __do_compat_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))\n 212:\t\n 213:\t/*\n 214:\t * As some compat syscalls may not be implemented, we need to expand\n 215:\t * COND_SYSCALL_COMPAT in kernel/sys_ni.c to cover this case as well.\n 216:\t */\n 217:\t#define COND_SYSCALL_COMPAT(name) \t\t\t\t\t\\\n 218:\t\t__IA32_COMPAT_COND_SYSCALL(name)\t\t\t\t\\\n 219:\t\t__X32_COMPAT_COND_SYSCALL(name)\n 220:\t\n 221:\t#endif /* CONFIG_COMPAT */\n 222:\t\n 223:\t#define __SYSCALL_DEFINEx(x, name, ...)\t\t\t\t\t\\\n 224:\t\tstatic long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__));\t\\\n 225:\t\tstatic inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\\\n 226:\t\t__X64_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 227:\t\t__IA32_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 228:\t\tstatic long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__))\t\\\n 229:\t\t{\t\t\t\t\t\t\t\t\\\n 230:\t\t\tlong ret = __do_sys##name(__MAP(x,__SC_CAST,__VA_ARGS__));\\\n 231:\t\t\t__MAP(x,__SC_TEST,__VA_ARGS__);\t\t\t\t\\\n 232:\t\t\t__PROTECT(x, ret,__MAP(x,__SC_ARGS,__VA_ARGS__));\t\\\n 233:\t\t\treturn ret;\t\t\t\t\t\t\\\n 234:\t\t}\t\t\t\t\t\t\t\t\\\n 235:\t\tstatic inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))\n 236:\t\n 237:\t/*\n 238:\t * As the generic SYSCALL_DEFINE0() macro does not decode any parameters for\n 239:\t * obvious reasons, and passing struct pt_regs *regs to it in %rdi does not\n 240:\t * hurt, we only need to re-define it here to keep the naming congruent to\n 241:\t * SYSCALL_DEFINEx() -- which is essential for the COND_SYSCALL() macro\n 242:\t * to work correctly.\n 243:\t */\n 244:\t#define SYSCALL_DEFINE0(sname)\t\t\t\t\t\t\\\n"
}

21/2 2026/11/18 16:22 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41064
							output: 307
							thoughts: 2037
						

Thoughts:
**Reasoning for Fuzzing Swapfile.c Changes**

Okay, so the initial thought is, `__do_sys_##name` is *inline*, meaning the actual syscall symbols are `__x64_sys_##name` and `__se_sys_##name`.  I need to be mindful of inlining during symbol analysis, especially in a context like syzkaller and kallsyms.  Specifically, `__do_sys_swapon` might be inlined directly into `__se_sys_swapon` or `__x64_sys_swapon`.  Let's make sure we track what functions are *actually* modified within `swapfile.c`.

Alright, a quick audit of modified and introduced functions in `mm/swapfile.c` is in order:

*   Syscall Entrypoints: `__do_sys_swapon`, `__x64_sys_swapon`, `__se_sys_swapon`, `__do_sys_swapoff`, `__x64_sys_swapoff`, `__se_sys_swapoff`
*   Queue Management: `swap_queue_add`, `swap_queue_del`, `swap_queue_get_device`
*   Device Control: `swap_device_enable`, `swap_device_disable`
*   Allocation: `swap_alloc_entry`, `cluster_alloc_swap_entry`, `alloc_swap_scan_cluster`, `swap_cluster_populate`
*   Availability List: `del_from_avail_list`, `add_to_avail_list`
*   In-Use Tracking: `swap_device_inuse_add`, `swap_device_inuse_sub`
*   Discard Operations: `swap_discard_for_alloc`, `swap_discard_one_cluster`
*   Other: `folio_alloc_swap`, `si_swapinfo`, `swap_alloc_hibernation_slot`, `pin_hibernation_swap_type`, `repin_hibernation_swap_type`, `unpin_hibernation_swap_type`, `find_first_swap`, `setup_swap_clusters_info`

Now, let's filter: are any of these ubiquitous, in that they'd be called all over the place anyway?  `folio_alloc_swap` is *not* ubiquitous; it's specific to memory pressure/reclaim during swap-out.  `swap_alloc_entry` is static and called by `folio_alloc_swap`, so not broadly used either. The swap queue functions: `swap_queue_get_device`, `swap_queue_add`, `swap_queue_del`; `swap_device_enable`, `swap_device_disable`, `swap_discard_for_alloc`, `swap_discard_one_cluster`, `cluster_alloc_swap_entry` seems like good targets. The syscalls, of course are always good targets.

Okay, let's think about the syzkaller context.  What symbols do we *typically* use for `FocusSymbols`? We're looking for functions that specifically implement the *logic being added or altered*, or direct API entrypoints for the subsystem. And of course we need to handle static inlines.  Since the changes are primarily in static inline helpers, we need to identify non-static, feature-specific caller functions.

So, let's review the candidates:  `__x64_sys_swapon`, `__x64_sys_swapoff` (syscalls). We'll want to include `folio_alloc_swap`, `swap_alloc_entry`, `swap_queue_get_device`, `swap_queue_add`, `swap_queue_del`, `swap_device_enable`, `swap_device_disable`, `cluster_alloc_swap_entry`, and `swap_discard_for_alloc`.

Now, regarding the static inlines, is `__do_sys_swapon` inlined?  Yes, in x86_64, `__do_sys_swapon` is a `static inline long __do_sys...`, so it becomes part of the `__se_sys_swapon` and `__x64_sys_swapon` functions.  kallsyms will most likely have `__x64_sys_swapon` and `__x64_sys_swapoff` as the relevant symbols.  We can, and should, include those.

To be thorough, let's verify all options and ensure the approach is comprehensive.

Now, checking configs: `CONFIG_SWAP` is obviously required.


22/2 2026/11/18 16:22 tool set-results
0m Args:
{
  "EnableConfigs": [
    "SWAP",
    "HIBERNATION",
    "MEMCG",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "folio_alloc_swap",
    "swap_alloc_entry",
    "swap_queue_get_device",
    "swap_queue_add",
    "swap_queue_del",
    "swap_device_enable",
    "swap_device_disable",
    "cluster_alloc_swap_entry",
    "swap_discard_for_alloc",
    "__x64_sys_swapon",
    "__x64_sys_swapoff"
  ],
  "Reasoning": "The patch series refactors the core Linux memory management swap subsystem. It replaces the plist-based swap device tracking (swap_active_head, swap_avail_head) and coarse spinlocks (swap_lock, swap_avail_lock) with a per-CPU priority-ring queue (swap_queue, swap_prio_ring), per-CPU readers, swapon_rwsem, and fine-grained queue update locks. It also rewires per-CPU swap cluster allocation, swap device activation/deactivation during swapon/swapoff, and synchronous cluster discard handling. These changes modify core mm logic and synchronization paths that are fully reachable in virtualized environments via the swapon/swapoff syscalls and anonymous memory paging pressure.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "SWAP",
    "HIBERNATION",
    "MEMCG",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "folio_alloc_swap",
    "swap_alloc_entry",
    "swap_queue_get_device",
    "swap_queue_add",
    "swap_queue_del",
    "swap_device_enable",
    "swap_device_disable",
    "cluster_alloc_swap_entry",
    "swap_discard_for_alloc",
    "__x64_sys_swapon",
    "__x64_sys_swapoff"
  ],
  "Reasoning": "The patch series refactors the core Linux memory management swap subsystem. It replaces the plist-based swap device tracking (swap_active_head, swap_avail_head) and coarse spinlocks (swap_lock, swap_avail_lock) with a per-CPU priority-ring queue (swap_queue, swap_prio_ring), per-CPU readers, swapon_rwsem, and fine-grained queue update locks. It also rewires per-CPU swap cluster allocation, swap device activation/deactivation during swapon/swapoff, and synchronous cluster discard handling. These changes modify core mm logic and synchronization paths that are fully reachable in virtualized environments via the swapon/swapoff syscalls and anonymous memory paging pressure.",
  "WorthFuzzing": true
}

23/1 2026/11/18 16:22 action If
3m Args:
{
  "WorthFuzzing": true
}

Results:
null

24/2 2026/11/18 16:22 agent kmsan-evaluator
3m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series reworks the internal swap device management and locking hierarchy in mm/swapfile.c. It replaces the plist-based active and available lists with priority rings (struct swap_prio_ring, swap_queue) protected by a percpu rwsem (swapon_rwsem) and a spinlock (swap_queue_update_lock), alongside per-CPU reader iterators (struct swap_queue_reader) and percpu/global cluster allocation state.\n\nKMSAN vs KASAN Applicability:\n1. Memory Initialization: All newly allocated kernel data structures (percpu_cluster via alloc_percpu, swap_prio_ring via kmalloc with explicit element initialization/memcpy, swap_queue_reader via __alloc_percpu_gfp followed by local_lock_init and swap_queue_reset_readers, and swap_info_struct via kvzalloc) are thoroughly initialized before use. Local stack variables (cursor, bitmap arrays) are explicitly zero-initialized with '= {}'.\n2. Info-Leaks and Userspace Boundaries: No kernel structures or raw kernel buffers are copied or exposed to userspace. /proc/swaps and si_swapinfo only format text and aggregate numeric counters from initialized fields.\n3. Failure Modes: The primary risks introduced by this refactoring are synchronization/locking bugs (deadlocks, lock ordering issues), use-after-free (during queue/ring reallocation and reader replacement), and array indexing or bounds errors. These are comprehensively detected by standard KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory reads or information leak risks that would be caught uniquely by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 00c4e8cb61a1f01e70050a532c7ceeebefa7e809
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 18 16:15:20 2026 +0000

    syz-cluster: applied patch under review

diff --git a/include/linux/plist.h b/include/linux/plist.h
index 16cf4355b5c131..73d359c1a0536a 100644
--- a/include/linux/plist.h
+++ b/include/linux/plist.h
@@ -132,8 +132,6 @@ static inline void plist_node_init(struct plist_node *node, int prio)
 extern void plist_add(struct plist_node *node, struct plist_head *head);
 extern void plist_del(struct plist_node *node, struct plist_head *head);
 
-extern void plist_requeue(struct plist_node *node, struct plist_head *head);
-
 /**
  * plist_for_each - iterate over the plist
  * @pos:	the type * to use as a loop counter
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 4f686709d71f00..ce8a800751ca2a 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -188,6 +188,25 @@ struct swap_extent {
 	((offsetof(union swap_header, magic.magic) - \
 	  offsetof(union swap_header, info.badpages)) / sizeof(int))
 
+/*
+ * Swap device flags, except the ones documented below, all are immutable
+ * after exposed by swap_device_enable, and until the device is freed again
+ * (SWP_USED unset), except that teardown clears SWP_ACTIVATED after draining
+ * allocators and live references. The other exceptions use swapon_rwsem:
+ * - SWP_USED: Protected by swapon_rwsem. Indicates the device is inuse. Once
+ *   set, won't be cleared unless all reference to this device is freed and
+ *   swapoff finished.
+ * - SWP_WRITEOK: Protected by swapon_rwsem, si->lock and
+ *   swap_queue_update_lock.
+ *   Clearing this flag is followed by waiting for all current cluster lock
+ *   users to exit, so
+ *   checking this flag while holding any of these locks ensures the device
+ *   is safe to use at the moment. Note: clearing this flag doesn't affect
+ *   pending IO or async requests, it only prevents further entry allocation
+ *   or new async request (e.g. discard) from initiating.
+ * - SWP_HIBERNATION: Protected by swapon_rwsem. Indicates if the device
+ *   is pinned for hibernation.
+ */
 enum {
 	SWP_USED	= (1 << 0),	/* is slot in swap_info[] used? */
 	SWP_WRITEOK	= (1 << 1),	/* ok to write to this swap?	*/
@@ -223,10 +242,17 @@ enum {
 #endif
 
 /*
- * We keep using same cluster for rotational device so IO will be sequential.
- * The purpose is to optimize SWAP throughput on these device.
+ * We assign a cluster to each CPU, so each CPU can allocate swap entry from
+ * its own cluster and swapout sequentially. The purpose is to optimize swapout
+ * throughput.
  */
+struct percpu_cluster {
+	local_lock_t lock; /* Protect the percpu_cluster above */
+	unsigned int next[SWAP_NR_ORDERS]; /* Likely next allocation offset */
+};
+
 struct swap_sequential_cluster {
+	spinlock_t lock; /* Serialize usage of global cluster */
 	unsigned int next[SWAP_NR_ORDERS]; /* Likely next allocation offset */
 };
 
@@ -237,7 +263,6 @@ struct swap_info_struct {
 	struct percpu_ref users;	/* indicate and keep swap device valid. */
 	unsigned long	flags;		/* SWP_USED etc: see above */
 	signed short	prio;		/* swap priority of this type */
-	struct plist_node list;		/* entry in swap_active_head */
 	signed char	type;		/* strange name for an index */
 	unsigned int	max;		/* size of this swap device */
 	struct swap_cluster_info *cluster_info; /* array, one entry per cluster */
@@ -249,26 +274,20 @@ struct swap_info_struct {
 					/* list of cluster that are fragmented or contented */
 	unsigned int pages;		/* total of usable pages of swap */
 	atomic_long_t inuse_pages;	/* number of those currently in use */
+	struct percpu_cluster	__percpu *percpu_cluster; /* per cpu's swap location */
 	struct swap_sequential_cluster *global_cluster; /* Use one global cluster for rotating device */
-	spinlock_t global_cluster_lock;	/* Serialize usage of global cluster */
 	struct rb_root swap_extent_root;/* root of the swap extent rbtree */
 	struct block_device *bdev;	/* swap device or bdev of swap file */
 	struct file *swap_file;		/* seldom referenced */
 	struct completion comp;		/* seldom referenced */
 	spinlock_t lock;		/*
-					 * protect map scan related fields like
-					 * inuse_pages and all cluster lists.
-					 * Other fields are only changed
-					 * at swapon/swapoff, so are protected
-					 * by swap_lock. changing flags need
-					 * hold this lock and swap_lock. If
-					 * both locks need hold, hold swap_lock
-					 * first.
+					 * Protect cluster lists. Other fields
+					 * are only changed at swapon/swapoff,
+					 * so are protected by swapon_rwsem.
 					 */
 	struct work_struct discard_work; /* discard worker */
 	struct work_struct reclaim_work; /* reclaim worker */
 	struct list_head discard_clusters; /* discard clusters list */
-	struct plist_node avail_list;   /* entry in swap_avail_head */
 	const struct swap_ops *ops;
 };
 
diff --git a/lib/plist.c b/lib/plist.c
index b0273533c04d2a..b05ae7ffea87e8 100644
--- a/lib/plist.c
+++ b/lib/plist.c
@@ -142,65 +142,6 @@ void plist_del(struct plist_node *node, struct plist_head *head)
 	plist_check_head(head);
 }
 
-/**
- * plist_requeue - Requeue @node at end of same-prio entries.
- *
- * This is essentially an optimized plist_del() followed by
- * plist_add().  It moves an entry already in the plist to
- * after any other same-priority entries.
- *
- * @node:	&struct plist_node pointer - entry to be moved
- * @head:	&struct plist_head pointer - list head
- */
-void plist_requeue(struct plist_node *node, struct plist_head *head)
-{
-	struct plist_node *iter;
-	struct list_head *node_next = &head->node_list;
-
-	plist_check_head(head);
-	BUG_ON(plist_head_empty(head));
-	BUG_ON(plist_node_empty(node));
-
-	if (node == plist_last(head))
-		return;
-
-	iter = plist_next(node);
-
-	if (node->prio != iter->prio)
-		return;
-
-	plist_del(node, head);
-
-	/*
-	 * After plist_del(), iter is the replacement of the node.  If the node
-	 * was on prio_list, take shortcut to find node_next instead of looping.
-	 *
-	 * prio_list is a headless ring, so from the LAST bucket ->next wraps
-	 * round to the first one; in that case node_next is the list head.
-	 */
-	if (!list_empty(&iter->prio_list)) {
-		struct plist_node *first = plist_first(head);
-
-		if (iter->prio_list.next == &first->prio_list)
-			goto queue;
-		iter = list_entry(iter->prio_list.next, struct plist_node,
-				  prio_list);
-		node_next = &iter->node_list;
-		goto queue;
-	}
-
-	plist_for_each_continue(iter, head) {
-		if (node->prio != iter->prio) {
-			node_next = &iter->node_list;
-			break;
-		}
-	}
-queue:
-	list_add_tail(&node->node_list, node_next);
-
-	plist_check_head(head);
-}
-
 #ifdef CONFIG_DEBUG_PLIST
 #include <linux/sched.h>
 #include <linux/sched/clock.h>
@@ -238,14 +179,6 @@ static void __init plist_test_check(int nr_expect)
 	BUG_ON(prio_pos->prio_list.next != &first->prio_list);
 }
 
-static void __init plist_test_requeue(struct plist_node *node)
-{
-	plist_requeue(node, &test_head);
-
-	if (node != plist_last(&test_head))
-		BUG_ON(node->prio == plist_next(node)->prio);
-}
-
 static int  __init plist_test(void)
 {
 	int nr_expect = 0, i, loop;
@@ -269,10 +202,6 @@ static int  __init plist_test(void)
 			nr_expect--;
 		}
 		plist_test_check(nr_expect);
-		if (!plist_node_empty(test_node + i)) {
-			plist_test_requeue(test_node + i);
-			plist_test_check(nr_expect);
-		}
 	}
 
 	for (i = 0; i < ARRAY_SIZE(test_node); i++) {
diff --git a/mm/swap.h b/mm/swap.h
index d488a69c28091c..70fd3ab655ff81 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -108,16 +108,16 @@ static inline unsigned int swp_cluster_offset(swp_entry_t entry)
  */
 static inline struct swap_info_struct *__swap_type_to_info(int type)
 {
-	struct swap_info_struct *si;
-
-	si = READ_ONCE(swap_info[type]); /* rcu_dereference() */
-	VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */
-	return si;
+	return READ_ONCE(swap_info[type]); /* rcu_dereference() */
 }
 
 static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)
 {
-	return __swap_type_to_info(swp_type(entry));
+	struct swap_info_struct *si;
+
+	si = __swap_type_to_info(swp_type(entry)); /* rcu_dereference() */
+	VM_WARN_ON_ONCE(percpu_ref_is_zero(&si->users)); /* race with swapoff */
+	return si;
 }
 
 static inline struct swap_cluster_info *__swap_offset_to_cluster(
diff --git a/mm/swapfile.c b/mm/swapfile.c
index fcda5eba171402..eb212813245598 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -6,6 +6,7 @@
  *  Swap reorganised 29.12.95, Stephen Tweedie
  */
 
+#include <linux/bitmap.h>
 #include <linux/blkdev.h>
 #include <linux/mm.h>
 #include <linux/sched/mm.h>
@@ -41,7 +42,6 @@
 #include <linux/completion.h>
 #include <linux/suspend.h>
 #include <linux/zswap.h>
-#include <linux/plist.h>
 
 #include <asm/tlbflush.h>
 #include <linux/leafops.h>
@@ -49,31 +49,38 @@
 #include "internal.h"
 #include "swap.h"
 
-static void swap_range_alloc(struct swap_info_struct *si,
-			     unsigned int nr_entries);
+static void swap_device_inuse_add(struct swap_info_struct *si,
+				  unsigned int nr_entries);
 static bool folio_swapcache_freeable(struct folio *folio);
 static void move_cluster(struct swap_info_struct *si,
 			 struct swap_cluster_info *ci, struct list_head *list,
 			 enum swap_cluster_flags new_flags);
+static bool get_swap_device_info(struct swap_info_struct *si);
 
 /*
- * Protects the swap_info array, and the SWP_USED flag. swap_info contains
- * lazily allocated & freed swap device info struts, and SWP_USED indicates
- * which device is used, ~SWP_USED devices and can be reused.
- *
- * Also protects swap_active_head total_swap_pages, and the SWP_WRITEOK flag.
+ * Serializes swapon/swapoff (writers) and protects the swap_info
+ * array, nr_swapfiles, total_swap_pages, and part of swap device
+ * info content (see comment of swap_info_struct).  Readers
+ * (allocation, /proc/swaps, etc.) take percpu_down_read() which
+ * is cheap as the hot path.
+ */
+DEFINE_STATIC_PERCPU_RWSEM(swapon_rwsem);
+/*
+ * swap_info contains lazily allocated swap device info structs, and
+ * SWP_USED indicates which device is used, ~SWP_USED devices can be
+ * reused. Protected by swapon_rwsem, but reading could be lockless.
  */
-static DEFINE_SPINLOCK(swap_lock);
+struct swap_info_struct *swap_info[MAX_SWAPFILES];
 static unsigned int nr_swapfiles;
-atomic_long_t nr_swap_pages;
+long total_swap_pages;
+
 /*
  * Some modules use swappable objects and may try to swap them out under
  * memory pressure (via the shrinker). Before doing so, they may wish to
  * check to see if any swap space is available.
  */
+atomic_long_t nr_swap_pages;
 EXPORT_SYMBOL_GPL(nr_swap_pages);
-/* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
-long total_swap_pages;
 #define DEF_SWAP_PRIO  -1
 unsigned long swapfile_maximum_size;
 #ifdef CONFIG_MIGRATION
@@ -83,52 +90,42 @@ bool swap_migration_ad_supported;
 static const char Bad_file[] = "Bad swap file entry ";
 static const char Bad_offset[] = "Bad swap offset entry ";
 
-/*
- * all active swap_info_structs
- * protected with swap_lock, and ordered by priority.
- */
-static PLIST_HEAD(swap_active_head);
+static inline struct swap_info_struct *__swap_iter(int *i, unsigned long flag)
+{
+	lockdep_assert_held(&swapon_rwsem);
+	while (*i < nr_swapfiles) {
+		struct swap_info_struct *si = __swap_type_to_info(*i);
+
+		VM_WARN_ON(!si);
+		(*i)++;
+		if (flag && !((si->flags & flag) == flag))
+			continue;
+		return si;
+	}
+	return NULL;
+}
+
+#define __for_each_swap(si, flag)			\
+	for (int __i = 0; ((si) = __swap_iter(&__i, flag));)
 
 /*
- * all available (active, not full) swap_info_structs
- * protected with swap_avail_lock, ordered by priority.
- * This is used by folio_alloc_swap() instead of swap_active_head
- * because swap_active_head includes all swap_info_structs,
- * but folio_alloc_swap() doesn't need to look at full ones.
- * This uses its own lock instead of swap_lock because when a
- * swap_info_struct changes between not-full/full, it needs to
- * add/remove itself to/from this list, but the swap_info_struct->lock
- * is held and the locking order requires swap_lock to be taken
- * before any swap_info_struct->lock.
+ * for_each_swap - iterate through all allocated and inuse swap devices
+ * @si: the iterator
+ *
+ * Context: The caller must hold swapon_rwsem. The lock may be dropped during
+ * the loop body but must be re-acquired before the next iteration.
  */
-static PLIST_HEAD(swap_avail_head);
-static DEFINE_SPINLOCK(swap_avail_lock);
-
-struct swap_info_struct *swap_info[MAX_SWAPFILES];
+#define for_each_swap(si) __for_each_swap(si, SWP_USED)
+#define for_each_avail_swap(si) __for_each_swap(si, SWP_USED | SWP_WRITEOK)
 
 static struct kmem_cache *swap_table_cachep;
 
-/* Protects si->swap_file for /proc/swaps usage */
-static DEFINE_MUTEX(swapon_mutex);
-
 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
 /* Activity counter to indicate that a swapon or swapoff has occurred */
 static atomic_t proc_poll_event = ATOMIC_INIT(0);
 
 atomic_t nr_rotate_swap = ATOMIC_INIT(0);
 
-struct percpu_swap_cluster {
-	struct swap_info_struct *si[SWAP_NR_ORDERS];
-	unsigned long offset[SWAP_NR_ORDERS];
-	local_lock_t lock;
-};
-
-static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) = {
-	.si = { NULL },
-	.offset = { SWAP_ENTRY_INVALID },
-	.lock = INIT_LOCAL_LOCK(),
-};
-
 /* May return NULL on invalid type, caller must check for NULL return */
 static struct swap_info_struct *swap_type_to_info(int type)
 {
@@ -143,18 +140,456 @@ static struct swap_info_struct *swap_entry_to_info(swp_entry_t entry)
 	return swap_type_to_info(swp_type(entry));
 }
 
+/*
+ * All available swap_info_structs are grouped by priority rings, the rings
+ * are ordered in a queue by priority (higher prio value = higher priority).
+ * The allocator iterates and rotates devices within each priority ring.
+ * When all devices in a ring are iterated, it goes to the next lower
+ * priority ring.
+ */
+struct swap_prio_ring {
+	int prio;
+	unsigned int size;
+	struct swap_info_struct *dev[] __counted_by(size);
+};
+
+/*
+ * The ring is protected by swapon_rwsem so updating it is costly. To make
+ * the allocator and other users skip full devices faster, the lowest bit of
+ * a device pointer is used to mark it disabled (temporarily unavailable).
+ * This relies on the natural alignment of struct swap_info_struct.
+ */
+#define SWAP_DEVICE_MASKED_SHIFT	0
+#define SWAP_DEVICE_MASKED_BIT		BIT(SWAP_DEVICE_MASKED_SHIFT)
+static_assert(__alignof__(struct swap_info_struct) >= 2);
+
+/*
+ * Serializes queue content mutations and keeps SWAP_USAGE_OFFLIST_BIT
+ * consistent with the masked state of each device pointer.
+ */
+static DEFINE_SPINLOCK(swap_queue_update_lock);
+
+/*
+ * Swap queue is protected by both swap_queue_update_lock and swapon_rwsem.
+ * Only swapon/swapoff will take the write lock, and modify the queue length
+ * or any ring's length. swap_queue_update_lock protects the content so
+ * devices can be masked easily without taking the writelock, which is heavy.
+ */
+static struct swap_prio_ring **swap_queue;
+static unsigned int swap_queue_len;
+
+/*
+ * Each CPU has its read iterator, so the queue itself will remain read
+ * only and the CPU side reader rotates by iterating the devices
+ * periodically using the counter.
+ */
+#define SWAP_ROUND_ROBIN_QUOTA SWAPFILE_CLUSTER
+struct swap_ring_iterator {
+	int offset;
+	long rr_counter;
+};
+
+struct swap_queue_reader {
+	local_lock_t lock;
+	struct swap_ring_iterator ri[];
+};
+
+struct swap_queue_cursor {
+	bool ring_only;
+	unsigned int ring_idx;
+	unsigned int offset;
+	unsigned int nr_iter;
+};
+
+static __percpu struct swap_queue_reader *swap_queue_readers;
+/* Keep the high-water capacity until the last priority ring is removed. */
+static unsigned int swap_queue_readers_capacity;
+
+static inline bool swap_device_masked(struct swap_info_struct *si)
+{
+	return (unsigned long)si & SWAP_DEVICE_MASKED_BIT;
+}
+
+static inline struct swap_info_struct *swap_device_mask_ptr(struct swap_info_struct *si)
+{
+	return (struct swap_info_struct *)((unsigned long)si |
+					   SWAP_DEVICE_MASKED_BIT);
+}
+
+static inline struct swap_info_struct *swap_device_unmask_ptr(struct swap_info_struct *si)
+{
+	return (struct swap_info_struct *)((unsigned long)si & ~SWAP_DEVICE_MASKED_BIT);
+}
+
+static struct swap_queue_reader __percpu *swap_queue_prealloc_readers(int nr_rings, gfp_t gfp)
+{
+	struct swap_queue_reader __percpu *readers;
+
+	if (!nr_rings)
+		return NULL;
+
+	readers = __alloc_percpu_gfp(struct_size(readers, ri, nr_rings),
+				     __alignof__(*readers), gfp);
+	return readers;
+}
+
+static bool swap_queue_needs_readers(int prio)
+{
+	unsigned int i;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	for (i = 0; i < swap_queue_len; i++) {
+		if (swap_queue[i]->prio == prio)
+			return false;
+	}
+
+	return swap_queue_len >= swap_queue_readers_capacity;
+}
+
+/*
+ * Return with swapon_rwsem held for writing, or unlocked on allocation failure.
+ * Per-CPU backing allocations may reclaim, so prepare them before publishing
+ * the device and outside the topology lock and our noreclaim scope. Keep NOIO
+ * because the swapon caller still holds the swapfile's inode lock.
+ */
+static int swap_queue_lock_for_add(int prio,
+				   struct swap_queue_reader __percpu **readers,
+				   unsigned int *nr_readers)
+{
+	*readers = NULL;
+	*nr_readers = 0;
+	for (;;) {
+		percpu_down_write(&swapon_rwsem);
+		if (!swap_queue_needs_readers(prio) ||
+		    *nr_readers > swap_queue_len)
+			return 0;
+
+		*nr_readers = swap_queue_len + 1;
+		percpu_up_write(&swapon_rwsem);
+		free_percpu(*readers);
+		*readers = swap_queue_prealloc_readers(*nr_readers, GFP_NOIO);
+		if (!*readers)
+			return -ENOMEM;
+	}
+}
+
+static void swap_queue_reset_readers(void)
+{
+	int ring_idx, cpu;
+	struct swap_prio_ring *ring;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	/* A new topology starts a fresh, distributed rotation on every CPU. */
+	for_each_possible_cpu(cpu) {
+		for (ring_idx = 0; ring_idx < swap_queue_len; ring_idx++) {
+			ring = swap_queue[ring_idx];
+			per_cpu_ptr(swap_queue_readers, cpu)->ri[ring_idx].offset =
+				    cpu % ring->size;
+			per_cpu_ptr(swap_queue_readers, cpu)->ri[ring_idx].rr_counter =
+				    SWAP_ROUND_ROBIN_QUOTA;
+		}
+	}
+}
+
+static void swap_queue_install_readers(struct swap_queue_reader __percpu *readers,
+				       unsigned int capacity)
+{
+	int cpu;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	free_percpu(swap_queue_readers);
+	swap_queue_readers = readers;
+	swap_queue_readers_capacity = capacity;
+	if (!readers)
+		return;
+
+	for_each_possible_cpu(cpu)
+		local_lock_init(&per_cpu_ptr(readers, cpu)->lock);
+	swap_queue_reset_readers();
+}
+
+static struct swap_info_struct *
+swap_queue_get_device(long nr_alloc, struct swap_queue_cursor *cursor)
+{
+	bool rotate = false;
+	struct swap_info_struct *si;
+	struct swap_ring_iterator *ri;
+	struct swap_prio_ring *ring;
+	unsigned int dev_idx, queue_idx, nr_iter;
+
+	queue_idx = cursor->ring_idx;
+	if (queue_idx >= swap_queue_len)
+		return ERR_PTR(-ENOENT);
+
+	ring = swap_queue[queue_idx];
+	if (cursor->nr_iter >= ring->size) {
+		if (cursor->ring_only)
+			return ERR_PTR(-E2BIG);
+		queue_idx = ++cursor->ring_idx;
+		if (queue_idx >= swap_queue_len)
+			return ERR_PTR(-ENOENT);
+		cursor->nr_iter = 0;
+		ring = swap_queue[queue_idx];
+	}
+
+	/* Consume masked peers too, so every walk remains bounded. */
+	nr_iter = cursor->nr_iter++;
+	if (ring->size == 1) {
+		si = READ_ONCE(ring->dev[0]);
+		goto check_device;
+	}
+
+	local_lock(&swap_queue_readers->lock);
+	ri = this_cpu_ptr(&swap_queue_readers->ri[queue_idx]);
+	/*
+	 * Snapshot the starting offset for this allocation's walk. The shared
+	 * iterator can move between retries, but the cursor must visit every
+	 * device in the ring exactly once before falling through.
+	 */
+	if (!nr_iter) {
+		if (ri->rr_counter < nr_alloc)
+			rotate = true;
+		else if (ri->offset >= ring->size)
+			rotate = true;
+		if (rotate) {
+			ri->offset++;
+			ri->offset %= ring->size;
+			ri->rr_counter = SWAP_ROUND_ROBIN_QUOTA;
+		}
+		cursor->offset = ri->offset;
+	}
+
+	dev_idx = (cursor->offset + nr_iter) % ring->size;
+	if (nr_iter) {
+		ri->offset = dev_idx;
+		ri->rr_counter = SWAP_ROUND_ROBIN_QUOTA;
+	}
+	ri->rr_counter -= nr_alloc;
+	si = READ_ONCE(ring->dev[dev_idx]);
+	local_unlock(&swap_queue_readers->lock);
+
+check_device:
+	if (swap_device_masked(si))
+		return ERR_PTR(-EBUSY);
+
+	si = swap_device_unmask_ptr(si);
+	return si;
+}
+
+static bool swap_queue_find(struct swap_info_struct *si,
+			    unsigned int *ring_idx, unsigned int *dev_idx)
+{
+	unsigned int i, j;
+	struct swap_prio_ring *ring;
+
+	lockdep_assert(lockdep_is_held(&swapon_rwsem) ||
+		       lockdep_is_held(&swap_queue_update_lock));
+
+	for (i = 0; i < swap_queue_len; i++) {
+		ring = swap_queue[i];
+		if (ring->prio != si->prio)
+			continue;
+		for (j = 0; j < ring->size; j++) {
+			if (swap_device_unmask_ptr(READ_ONCE(ring->dev[j])) != si)
+				continue;
+			*ring_idx = i;
+			*dev_idx = j;
+			return true;
+		}
+	}
+	return false;
+}
+
+static void swap_queue_mask(struct swap_info_struct *si)
+{
+	unsigned int ring_idx, dev_idx;
+
+	lockdep_assert_held(&swap_queue_update_lock);
+	if (swap_queue_find(si, &ring_idx, &dev_idx))
+		WRITE_ONCE(swap_queue[ring_idx]->dev[dev_idx],
+			   swap_device_mask_ptr(si));
+}
+
+static void swap_queue_unmask(struct swap_info_struct *si)
+{
+	unsigned int ring_idx, dev_idx;
+
+	lockdep_assert_held(&swap_queue_update_lock);
+	if (swap_queue_find(si, &ring_idx, &dev_idx))
+		WRITE_ONCE(swap_queue[ring_idx]->dev[dev_idx], si);
+}
+
+/* Prepared readers remain caller-owned unless installed successfully. */
+static int swap_queue_add(struct swap_info_struct *si,
+			  struct swap_queue_reader __percpu **readers,
+			  unsigned int nr_readers)
+{
+	struct swap_prio_ring **new_queue = NULL, **old_queue = NULL;
+	struct swap_prio_ring *ring, *new_ring = NULL, *old_ring = NULL;
+	int prio = si->prio;
+	int i, pos, err = -ENOMEM;
+	unsigned int noreclaim_flag;
+	gfp_t gfp;
+
+	/* A writer must not reclaim into another swap allocation. */
+	gfp = GFP_NOIO | __GFP_HIGH | __GFP_NOMEMALLOC;
+	lockdep_assert_held_write(&swapon_rwsem);
+	noreclaim_flag = memalloc_noreclaim_save();
+
+	for (pos = 0; pos < swap_queue_len; pos++) {
+		if (swap_queue[pos]->prio == prio)
+			goto add_to_ring;
+		if (swap_queue[pos]->prio < prio)
+			break;
+	}
+
+	/* No ring at this priority: insert a new one at pos. */
+	if (swap_queue_len >= swap_queue_readers_capacity &&
+	    (!*readers || nr_readers <= swap_queue_len))
+		goto failed;
+	new_queue = kmalloc_array(swap_queue_len + 1, sizeof(*swap_queue), gfp);
+	if (!new_queue)
+		goto failed;
+	new_ring = kmalloc(struct_size(new_ring, dev, 1), gfp);
+	if (!new_ring)
+		goto failed;
+	if (!get_swap_device_info(si))
+		goto failed;
+
+	new_ring->prio = prio;
+	new_ring->size = 1;
+	new_ring->dev[0] = si;
+	for (i = 0; i < pos; i++)
+		new_queue[i] = swap_queue[i];
+	new_queue[pos] = new_ring;
+	for (i = pos; i < swap_queue_len; i++)
+		new_queue[i + 1] = swap_queue[i];
+
+	spin_lock(&swap_queue_update_lock);
+	old_queue = swap_queue;
+	swap_queue = new_queue;
+	swap_queue_len++;
+	spin_unlock(&swap_queue_update_lock);
+	memalloc_noreclaim_restore(noreclaim_flag);
+	kfree(old_queue);
+
+	if (swap_queue_len > swap_queue_readers_capacity) {
+		swap_queue_install_readers(*readers, nr_readers);
+		*readers = NULL;
+	} else {
+		swap_queue_reset_readers();
+	}
+	return 0;
+
+add_to_ring:
+	ring = swap_queue[pos];
+	new_ring = kmalloc(struct_size(ring, dev, ring->size + 1), gfp);
+	if (!new_ring)
+		goto failed;
+	if (!get_swap_device_info(si))
+		goto failed;
+	spin_lock(&swap_queue_update_lock);
+	memcpy(new_ring, ring, struct_size(ring, dev, ring->size));
+	new_ring->size++;
+	new_ring->dev[new_ring->size - 1] = si;
+	old_ring = swap_queue[pos];
+	swap_queue[pos] = new_ring;
+	spin_unlock(&swap_queue_update_lock);
+	memalloc_noreclaim_restore(noreclaim_flag);
+	kfree(old_ring);
+	swap_queue_reset_readers();
+	return 0;
+
+failed:
+	memalloc_noreclaim_restore(noreclaim_flag);
+	kfree(new_queue);
+	kfree(new_ring);
+	return err;
+}
+
+static void swap_queue_del(struct swap_info_struct *si)
+{
+	gfp_t gfp;
+	unsigned int noreclaim_flag;
+	unsigned int ring_idx, dev_idx;
+	struct swap_prio_ring *ring, *new_ring = NULL, *old_ring = NULL;
+	struct swap_prio_ring **new_queue = NULL, **old_queue = NULL;
+
+	lockdep_assert_held_write(&swapon_rwsem);
+	if (!swap_queue_find(si, &ring_idx, &dev_idx)) {
+		WARN_ON(1);
+		return;
+	}
+
+	/*
+	 * Shrinking the small topology arrays is optional. Keep reader capacity
+	 * until the queue is empty: per-CPU allocation must not run under this
+	 * writer's noreclaim scope, which can grant backing pages reserve access.
+	 */
+	gfp = GFP_NOIO | __GFP_HIGH | __GFP_NOMEMALLOC;
+	noreclaim_flag = memalloc_noreclaim_save();
+	ring = swap_queue[ring_idx];
+	if (ring->size > 1)
+		new_ring = kmalloc(struct_size(ring, dev, ring->size - 1), gfp);
+	if (ring->size == 1 && swap_queue_len > 1) {
+		new_queue = kmalloc(sizeof(*swap_queue) *
+				    (swap_queue_len - 1), gfp);
+	}
+	memalloc_noreclaim_restore(noreclaim_flag);
+
+	spin_lock(&swap_queue_update_lock);
+	if (ring->size > 1) {
+		/* Shift trailing devices left to fill the gap. */
+		while (++dev_idx < ring->size)
+			ring->dev[dev_idx - 1] =
+				ring->dev[dev_idx];
+		ring->size--;
+		if (new_ring) {
+			memcpy(new_ring, ring,
+			       struct_size(ring, dev, ring->size));
+			old_ring = ring;
+			swap_queue[ring_idx] = new_ring;
+		}
+	} else {
+		/* Last device in this ring: remove the ring. */
+		old_ring = ring;
+		swap_queue_len--;
+		while (++ring_idx <= swap_queue_len)
+			swap_queue[ring_idx - 1] =
+				swap_queue[ring_idx];
+		if (new_queue) {
+			memcpy(new_queue, swap_queue,
+			       sizeof(*swap_queue) * swap_queue_len);
+			old_queue = swap_queue;
+			swap_queue = new_queue;
+		} else if (!swap_queue_len) {
+			old_queue = swap_queue;
+			swap_queue = NULL;
+		}
+		if (!swap_queue_len)
+			swap_queue_install_readers(NULL, 0);
+	}
+	spin_unlock(&swap_queue_update_lock);
+	if (swap_queue_len)
+		swap_queue_reset_readers();
+
+	kfree(old_ring);
+	kfree(old_queue);
+	put_swap_device(si);
+}
+
 /*
  * Use the second highest bit of inuse_pages counter as the indicator
- * if one swap device is on the available plist, so the atomic can
+ * if one swap device is unavailable for allocation, so the atomic can
  * still be updated arithmetically while having special data embedded.
  *
  * inuse_pages counter is the only thing indicating if a device should
- * be on avail_lists or not (except swapon / swapoff). By embedding the
- * off-list bit in the atomic counter, updates no longer need any lock
- * to check the list status.
+ * be in the available queue or not (except swapon / swapoff). By
+ * embedding the off-list bit in the atomic counter, updates no longer
+ * need any lock to check the list status.
  *
- * This bit will be set if the device is not on the plist and not
- * usable, will be cleared if the device is on the plist.
+ * This bit will be set if the device is not in the available queue
+ * and not usable, will be cleared if the device is in the queue.
  */
 #define SWAP_USAGE_OFFLIST_BIT (1UL << (BITS_PER_TYPE(atomic_long_t) - 2))
 #define SWAP_USAGE_COUNTER_MASK (~SWAP_USAGE_OFFLIST_BIT)
@@ -163,6 +598,26 @@ static long swap_usage_in_pages(struct swap_info_struct *si)
 	return atomic_long_read(&si->inuse_pages) & SWAP_USAGE_COUNTER_MASK;
 }
 
+/*
+ * Serialize the allocation on single CPU or globally to avoid
+ * fragmentation and make the workflow easier to follow.
+ */
+static void swap_alloc_lock_device(struct swap_info_struct *si)
+{
+	if (si->flags & SWP_SOLIDSTATE)
+		local_lock(&si->percpu_cluster->lock);
+	else
+		spin_lock(&si->global_cluster->lock);
+}
+
+static void swap_alloc_unlock_device(struct swap_info_struct *si)
+{
+	if (si->flags & SWP_SOLIDSTATE)
+		local_unlock(&si->percpu_cluster->lock);
+	else
+		spin_unlock(&si->global_cluster->lock);
+}
+
 /* Reclaim the swap entry anyway if possible */
 #define TTRS_ANYWAY		0x1
 /*
@@ -494,11 +949,8 @@ static int swap_cluster_alloc_table(struct swap_info_struct *si,
 
 lock:
 	if (!locked) {
-		if (si) {
-			local_lock(&percpu_swap_cluster.lock);
-			if (!(si->flags & SWP_SOLIDSTATE))
-				spin_lock(&si->global_cluster_lock);
-		}
+		if (si)
+			swap_alloc_lock_device(si);
 		spin_lock(&ci->lock);
 	}
 	lockdep_assert_held(&ci->lock);
@@ -569,22 +1021,24 @@ static void swap_cluster_assert_empty(struct swap_cluster_info *ci,
 }
 
 /*
- * Allocate swap table for one cluster. Attempt an atomic allocation first,
- * then fallback to sleeping allocation.
+ * Allocate swap table for one cluster. Attempt allocation under the locks
+ * first, then retry with the locks dropped without entering direct reclaim.
  */
 static struct swap_cluster_info *
 swap_cluster_populate(struct swap_info_struct *si,
 			 struct swap_cluster_info *ci)
 {
+	gfp_t gfp;
 	int ret;
 
 	/*
 	 * Only cluster isolation from the allocator does table allocation.
 	 * Swap allocator uses percpu clusters and holds the local lock.
 	 */
-	lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock);
-	if (!(si->flags & SWP_SOLIDSTATE))
-		lockdep_assert_held(&si->global_cluster_lock);
+	if (si->flags & SWP_SOLIDSTATE)
+		lockdep_assert_held(this_cpu_ptr(&si->percpu_cluster->lock));
+	else
+		lockdep_assert_held(&si->global_cluster->lock);
 	lockdep_assert_held(&ci->lock);
 
 	if (!swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
@@ -592,17 +1046,18 @@ swap_cluster_populate(struct swap_info_struct *si,
 		return ci;
 
 	/*
-	 * Try a sleep allocation. Each isolated free cluster may cause
-	 * a sleep allocation, but there is a limited number of them, so
-	 * the potential recursive allocation is limited.
+	 * Retry with the local and cluster locks dropped. The allocator can
+	 * still hold swapon_rwsem for reading: direct reclaim could enter
+	 * swap allocation again while a writer is waiting for this reader.
+	 * Restrict this request instead of granting the task PF_MEMALLOC,
+	 * which could give allocator hooks and failure cleanup reserve access.
 	 */
 	spin_unlock(&ci->lock);
-	if (!(si->flags & SWP_SOLIDSTATE))
-		spin_unlock(&si->global_cluster_lock);
-	local_unlock(&percpu_swap_cluster.lock);
+	swap_alloc_unlock_device(si);
 
-	ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
-					     GFP_KERNEL, false);
+	gfp = (GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC) &
+		~__GFP_DIRECT_RECLAIM;
+	ret = swap_cluster_alloc_table(si, ci, gfp, false);
 
 	/*
 	 * Back to atomic context. We might have migrated to a new CPU with a
@@ -705,44 +1160,40 @@ static struct swap_cluster_info *isolate_lock_cluster(
 }
 
 /*
- * Doing discard actually. After a cluster discard is finished, the cluster
- * will be added to free cluster list. Discard cluster is a bit special as
- * they don't participate in allocation or reclaim, so clusters marked as
- * CLUSTER_FLAG_DISCARD must remain off-list or on discard list.
+ * Discard one cluster. After the discard is finished, the cluster will be
+ * added to the free cluster list. Discard clusters are special because they
+ * don't participate in allocation or reclaim, so CLUSTER_FLAG_DISCARD must
+ * remain set while a cluster is either queued or being discarded.
  */
-static bool swap_do_scheduled_discard(struct swap_info_struct *si)
+static bool swap_discard_one_cluster(struct swap_info_struct *si)
 {
 	struct swap_cluster_info *ci;
-	bool ret = false;
 	unsigned int idx;
 
 	spin_lock(&si->lock);
-	while (!list_empty(&si->discard_clusters)) {
-		ci = list_first_entry(&si->discard_clusters, struct swap_cluster_info, list);
-		/*
-		 * Delete the cluster from list to prepare for discard, but keep
-		 * the CLUSTER_FLAG_DISCARD flag, percpu_swap_cluster could be
-		 * pointing to it, or ran into by relocate_cluster.
-		 */
-		list_del(&ci->list);
-		idx = cluster_index(si, ci);
+	if (list_empty(&si->discard_clusters)) {
 		spin_unlock(&si->lock);
-		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
-				SWAPFILE_CLUSTER);
-
-		spin_lock(&ci->lock);
-		/*
-		 * Discard is done, clear its flags as it's off-list, then
-		 * return the cluster to allocation list.
-		 */
-		ci->flags = CLUSTER_FLAG_NONE;
-		__free_cluster(si, ci);
-		spin_unlock(&ci->lock);
-		ret = true;
-		spin_lock(&si->lock);
+		return false;
 	}
+
+	ci = list_first_entry(&si->discard_clusters,
+			      struct swap_cluster_info, list);
+	/*
+	 * Delete the cluster from the list, but keep CLUSTER_FLAG_DISCARD
+	 * set while the discard is in flight. A percpu cluster may still
+	 * point to it, or relocate_cluster() may encounter it.
+	 */
+	list_del(&ci->list);
+	idx = cluster_index(si, ci);
 	spin_unlock(&si->lock);
-	return ret;
+
+	discard_swap_cluster(si, idx * SWAPFILE_CLUSTER, SWAPFILE_CLUSTER);
+
+	spin_lock(&ci->lock);
+	ci->flags = CLUSTER_FLAG_NONE;
+	__free_cluster(si, ci);
+	spin_unlock(&ci->lock);
+	return true;
 }
 
 static void swap_discard_work(struct work_struct *work)
@@ -751,7 +1202,8 @@ static void swap_discard_work(struct work_struct *work)
 
 	si = container_of(work, struct swap_info_struct, discard_work);
 
-	swap_do_scheduled_discard(si);
+	while (swap_discard_one_cluster(si))
+		cond_resched();
 }
 
 static void swap_users_ref_free(struct percpu_ref *ref)
@@ -1017,7 +1469,7 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 	if (cluster_is_empty(ci))
 		ci->order = order;
 	ci->count += nr_pages;
-	swap_range_alloc(si, nr_pages);
+	swap_device_inuse_add(si, nr_pages);
 
 	return true;
 }
@@ -1076,12 +1528,10 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 out:
 	relocate_cluster(si, ci);
 	swap_cluster_unlock(ci);
-	if (si->flags & SWP_SOLIDSTATE) {
-		this_cpu_write(percpu_swap_cluster.offset[order], next);
-		this_cpu_write(percpu_swap_cluster.si[order], si);
-	} else {
+	if (si->flags & SWP_SOLIDSTATE)
+		this_cpu_write(si->percpu_cluster->next[order], next);
+	else
 		si->global_cluster->next[order] = next;
-	}
 	return found;
 }
 
@@ -1182,13 +1632,13 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	if (order && !(si->flags & SWP_BLKDEV))
 		return 0;
 
-	if (!(si->flags & SWP_SOLIDSTATE)) {
-		/* Serialize HDD SWAP allocation for each device. */
-		spin_lock(&si->global_cluster_lock);
+	swap_alloc_lock_device(si);
+	if (si->flags & SWP_SOLIDSTATE)
+		offset = __this_cpu_read(si->percpu_cluster->next[order]);
+	else
 		offset = si->global_cluster->next[order];
-		if (offset == SWAP_ENTRY_INVALID)
-			goto new_cluster;
 
+	if (offset != SWAP_ENTRY_INVALID) {
 		ci = swap_cluster_lock(si, offset);
 		/* Cluster could have been used by another order */
 		if (cluster_is_usable(ci, order)) {
@@ -1202,7 +1652,6 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 			goto done;
 	}
 
-new_cluster:
 	if (swap_prefer_free_cluster(si)) {
 		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
 		if (found)
@@ -1255,8 +1704,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 			goto done;
 	}
 done:
-	if (!(si->flags & SWP_SOLIDSTATE))
-		spin_unlock(&si->global_cluster_lock);
+	swap_alloc_unlock_device(si);
 
 	return found;
 }
@@ -1266,54 +1714,47 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)
 {
 	unsigned long pages;
 
-	spin_lock(&swap_avail_lock);
+	spin_lock(&swap_queue_update_lock);
 
-	if (swapoff) {
-		/*
-		 * Forcefully remove it. Clear the SWP_WRITEOK flags for
-		 * swapoff here so it's synchronized by both si->lock and
-		 * swap_avail_lock, to ensure the result can be seen by
-		 * add_to_avail_list.
-		 */
-		lockdep_assert_held(&si->lock);
-		si->flags &= ~SWP_WRITEOK;
-		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
-	} else {
-		/*
-		 * If not called by swapoff, take it off-list only if it's
-		 * full and SWAP_USAGE_OFFLIST_BIT is not set (strictly
-		 * si->inuse_pages == pages), any concurrent slot freeing,
-		 * or device already removed from plist by someone else
-		 * will make this return false.
-		 */
+	/*
+	 * Force remove it only for swapoff. Else, take it off-list only if
+	 * it's full and SWAP_USAGE_OFFLIST_BIT is not set (strictly
+	 * si->inuse_pages == pages), so concurrent slot freeing, or
+	 * concurrent list removal will make the cmpxchg fail and skip
+	 * the removal.
+	 */
+	if (!swapoff) {
 		pages = si->pages;
 		if (!atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
 					     pages | SWAP_USAGE_OFFLIST_BIT))
 			goto skip;
+	} else {
+		lockdep_assert_held_write(&swapon_rwsem);
+		lockdep_assert_held(&si->lock);
+		si->flags &= ~SWP_WRITEOK;
+		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 	}
 
-	plist_del(&si->avail_list, &swap_avail_head);
-
+	swap_queue_mask(si);
 skip:
-	spin_unlock(&swap_avail_lock);
+	spin_unlock(&swap_queue_update_lock);
 }
 
 /* SWAP_USAGE_OFFLIST_BIT can only be cleared by this helper. */
-static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
+static void add_to_avail_list(struct swap_info_struct *si)
 {
 	long val;
 	unsigned long pages;
 
-	spin_lock(&swap_avail_lock);
+	spin_lock(&swap_queue_update_lock);
 
-	/* Corresponding to SWP_WRITEOK clearing in del_from_avail_list */
-	if (swapon) {
-		lockdep_assert_held(&si->lock);
-		si->flags |= SWP_WRITEOK;
-	} else {
-		if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
-			goto skip;
-	}
+	/*
+	 * Mark the device as avail if SWP_WRITEOK is set. Swapoff clears
+	 * SWP_WRITEOK first, so check that first so the device won't be
+	 * re-added after swapoff started.
+	 */
+	if (!(si->flags & SWP_WRITEOK))
+		goto skip;
 
 	if (!(atomic_long_read(&si->inuse_pages) & SWAP_USAGE_OFFLIST_BIT))
 		goto skip;
@@ -1321,72 +1762,55 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	val = atomic_long_fetch_and_relaxed(~SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 
 	/*
-	 * When device is full and device is on the plist, only one updater will
-	 * see (inuse_pages == si->pages) and will call del_from_avail_list. If
-	 * that updater happen to be here, just skip adding.
+	 * When device is full and marked as available, one reader will see
+	 * (inuse_pages == si->pages) and should mark it as unavailable and
+	 * set SWAP_USAGE_OFFLIST_BIT. If that updater happens to be here, just
+	 * skip the rest.
 	 */
 	pages = si->pages;
-	if (val == pages) {
+	if ((val & SWAP_USAGE_COUNTER_MASK) == pages) {
 		/* Just like the cmpxchg in del_from_avail_list */
 		if (atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
 					    pages | SWAP_USAGE_OFFLIST_BIT))
 			goto skip;
 	}
 
-	plist_add(&si->avail_list, &swap_avail_head);
-
+	swap_queue_unmask(si);
 skip:
-	spin_unlock(&swap_avail_lock);
+	spin_unlock(&swap_queue_update_lock);
 }
 
 /*
- * swap_usage_add / swap_usage_sub of each slot are serialized by ci->lock
- * within each cluster, so the total contribution to the global counter should
- * always be positive and cannot exceed the total number of usable slots.
+ * swap_device_inuse_add / swap_device_inuse_sub are called within cluster
+ * update critical sections and serialized by ci->lock within each cluster,
+ * so the total contribution to the global counter should always be positive
+ * and cannot exceed the total number of usable slots.
  */
-static bool swap_usage_add(struct swap_info_struct *si, unsigned int nr_entries)
+static void swap_device_inuse_add(struct swap_info_struct *si,
+				  unsigned int nr_entries)
 {
-	long val = atomic_long_add_return_relaxed(nr_entries, &si->inuse_pages);
+	long inuse_pages;
 
 	/*
 	 * If device is full, and SWAP_USAGE_OFFLIST_BIT is not set,
-	 * remove it from the plist.
+	 * mark it unavailable.
 	 */
-	if (unlikely(val == si->pages)) {
-		del_from_avail_list(si, false);
-		return true;
-	}
-
-	return false;
-}
-
-static void swap_usage_sub(struct swap_info_struct *si, unsigned int nr_entries)
-{
-	long val = atomic_long_sub_return_relaxed(nr_entries, &si->inuse_pages);
-
-	/*
-	 * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,
-	 * add it to the plist.
-	 */
-	if (unlikely(val & SWAP_USAGE_OFFLIST_BIT))
-		add_to_avail_list(si, false);
-}
-
-static void swap_range_alloc(struct swap_info_struct *si,
-			     unsigned int nr_entries)
-{
-	if (swap_usage_add(si, nr_entries)) {
+	inuse_pages = atomic_long_add_return_relaxed(nr_entries, &si->inuse_pages);
+	if (unlikely(inuse_pages == si->pages)) {
 		if (vm_swap_full())
 			schedule_work(&si->reclaim_work);
+		del_from_avail_list(si, false);
 	}
+
 	atomic_long_sub(nr_entries, &nr_swap_pages);
 }
 
-static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
-			    unsigned int nr_entries)
+static void swap_device_inuse_sub(struct swap_info_struct *si, unsigned long offset,
+				  unsigned int nr_entries)
 {
 	unsigned long end = offset + nr_entries - 1;
 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
+	long inuse_pages;
 
 	zswap_invalidate(si->type, offset, nr_entries);
 
@@ -1408,7 +1832,14 @@ static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
 	 */
 	smp_wmb();
 	atomic_long_add(nr_entries, &nr_swap_pages);
-	swap_usage_sub(si, nr_entries);
+
+	/*
+	 * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,
+	 * add it back to the available queue.
+	 */
+	inuse_pages = atomic_long_sub_return_relaxed(nr_entries, &si->inuse_pages);
+	if (unlikely(inuse_pages & SWAP_USAGE_OFFLIST_BIT))
+		add_to_avail_list(si);
 }
 
 static bool get_swap_device_info(struct swap_info_struct *si)
@@ -1418,113 +1849,95 @@ static bool get_swap_device_info(struct swap_info_struct *si)
 	/*
 	 * Guarantee the si->users are checked before accessing other
 	 * fields of swap_info_struct, and si->flags (SWP_WRITEOK) is
-	 * up to dated.
+	 * up to date.
 	 *
-	 * Paired with the spin_unlock() after setup_swap_info() in
-	 * enable_swap_info(), and smp_wmb() in swapoff.
+	 * Paired with percpu_up_write() in swap_device_enable(), and
+	 * smp_wmb() after clearing SWP_WRITEOK in swapoff.
 	 */
 	smp_rmb();
 	return true;
 }
 
-/*
- * Fast path try to get swap entries with specified order from current
- * CPU's swap entry pool (a cluster).
- */
-static bool swap_alloc_fast(struct folio *folio)
+static void swap_alloc_entry(struct folio *folio)
 {
-	unsigned int order = folio_order(folio);
-	struct swap_cluster_info *ci;
+	struct swap_queue_cursor cursor = {};
+	long nr_pages = folio_nr_pages(folio);
 	struct swap_info_struct *si;
-	unsigned int offset;
 
-	/*
-	 * Once allocated, swap_info_struct will never be completely freed,
-	 * so checking it's liveness by get_swap_device_info is enough.
-	 */
-	si = this_cpu_read(percpu_swap_cluster.si[order]);
-	offset = this_cpu_read(percpu_swap_cluster.offset[order]);
-	if (!si || !offset || !get_swap_device_info(si))
-		return false;
-
-	ci = swap_cluster_lock(si, offset);
-	if (cluster_is_usable(ci, order)) {
-		if (cluster_is_empty(ci))
-			offset = cluster_offset(si, ci);
-		alloc_swap_scan_cluster(si, ci, folio, offset);
-	} else {
-		swap_cluster_unlock(ci);
-	}
-
-	put_swap_device(si);
-	return folio_test_swapcache(folio);
-}
-
-/* Rotate the device and switch to a new cluster */
-static void swap_alloc_slow(struct folio *folio)
-{
-	struct swap_info_struct *si, *next;
-
-	spin_lock(&swap_avail_lock);
-start_over:
-	plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
-		/* Rotate the device and switch to a new cluster */
-		plist_requeue(&si->avail_list, &swap_avail_head);
-		spin_unlock(&swap_avail_lock);
-		if (get_swap_device_info(si)) {
-			cluster_alloc_swap_entry(si, folio);
-			put_swap_device(si);
-			if (folio_test_swapcache(folio))
-				return;
-			if (folio_test_large(folio))
-				return;
+	percpu_down_read(&swapon_rwsem);
+	migrate_disable();
+	for (;;) {
+		si = swap_queue_get_device(nr_pages, &cursor);
+		if (IS_ERR(si)) {
+			if (PTR_ERR(si) == -EBUSY)
+				continue;
+			break;
 		}
+		cluster_alloc_swap_entry(si, folio);
+
+		if (folio_test_swapcache(folio))
+			break;
 
-		spin_lock(&swap_avail_lock);
 		/*
-		 * if we got here, it's likely that si was almost full before,
-		 * multiple callers probably all tried to get a page from the
-		 * same si and it filled up before we could get one; or, the si
-		 * filled up between us dropping swap_avail_lock.
-		 * Since we dropped the swap_avail_lock, the swap_avail_list
-		 * may have been modified; so if next is still in the
-		 * swap_avail_head list then try it, otherwise start over if we
-		 * have not gotten any slots.
+		 * For large allocations, try every device at the same priority,
+		 * but ask the caller to split instead of falling back to a lower
+		 * priority ring.
 		 */
-		if (plist_node_empty(&next->avail_list))
-			goto start_over;
+		if (folio_test_large(folio)) {
+			cursor.ring_only = true;
+			continue;
+		}
 	}
-	spin_unlock(&swap_avail_lock);
+
+	migrate_enable();
+	percpu_up_read(&swapon_rwsem);
 }
 
 /*
- * Discard pending clusters in a synchronized way when under high pressure.
- * Return: true if any cluster is discarded.
+ * Discard outside the topology reader, holding only the selected device's
+ * live reference across I/O. Each successful retry starts a fresh queue walk.
  */
-static bool swap_sync_discard(void)
+static bool swap_discard_for_alloc(unsigned long *discarded)
 {
-	bool ret = false;
-	struct swap_info_struct *si, *next;
-
-	spin_lock(&swap_lock);
-start_over:
-	plist_for_each_entry_safe(si, next, &swap_active_head, list) {
-		spin_unlock(&swap_lock);
-		if (get_swap_device_info(si)) {
-			if (si->flags & SWP_PAGE_DISCARD)
-				ret = swap_do_scheduled_discard(si);
-			put_swap_device(si);
+	DECLARE_BITMAP(checked, MAX_SWAPFILES) = {};
+	struct swap_info_struct *si, *candidate;
+	unsigned int i, j;
+	bool done;
+	int type;
+
+	for (;;) {
+		candidate = NULL;
+		percpu_down_read(&swapon_rwsem);
+		for (i = 0; i < swap_queue_len && !candidate; i++) {
+			struct swap_prio_ring *ring = swap_queue[i];
+
+			for (j = 0; j < ring->size; j++) {
+				si = swap_device_unmask_ptr(READ_ONCE(ring->dev[j]));
+				type = si->type;
+				if (test_bit(type, discarded) || test_bit(type, checked))
+					continue;
+				__set_bit(type, checked);
+				if ((READ_ONCE(si->flags) & (SWP_WRITEOK | SWP_PAGE_DISCARD)) !=
+				    (SWP_WRITEOK | SWP_PAGE_DISCARD))
+					continue;
+				if (get_swap_device_info(si)) {
+					candidate = si;
+					break;
+				}
+			}
 		}
-		if (ret)
-			return true;
+		percpu_up_read(&swapon_rwsem);
+		if (!candidate)
+			return false;
 
-		spin_lock(&swap_lock);
-		if (plist_node_empty(&next->list))
-			goto start_over;
+		type = candidate->type;
+		done = swap_discard_one_cluster(candidate);
+		if (done)
+			__set_bit(type, discarded);
+		put_swap_device(candidate);
+		if (done)
+			return true;
 	}
-	spin_unlock(&swap_lock);
-
-	return false;
 }
 
 static int swap_extend_table_alloc(struct swap_info_struct *si,
@@ -1828,15 +2241,16 @@ int folio_alloc_swap(struct folio *folio)
 		}
 	}
 
-again:
-	local_lock(&percpu_swap_cluster.lock);
-	if (!swap_alloc_fast(folio))
-		swap_alloc_slow(folio);
-	local_unlock(&percpu_swap_cluster.lock);
+	swap_alloc_entry(folio);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
-		if (swap_sync_discard())
-			goto again;
+		DECLARE_BITMAP(discarded, MAX_SWAPFILES) = {};
+
+		while (swap_discard_for_alloc(discarded)) {
+			swap_alloc_entry(folio);
+			if (folio_test_swapcache(folio))
+				break;
+		}
 	}
 
 	/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */
@@ -2036,7 +2450,7 @@ void __swap_cluster_free_entries(struct swap_info_struct *si,
 	if (batch_id)
 		mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
 
-	swap_range_free(si, ci_head + ci_start, nr_pages);
+	swap_device_inuse_sub(si, ci_head + ci_start, nr_pages);
 	swap_cluster_assert_empty(ci, ci_start, nr_pages, false);
 
 	if (!ci->count)
@@ -2238,31 +2652,14 @@ void swap_put_entries_direct(swp_entry_t entry, int nr)
  */
 swp_entry_t swap_alloc_hibernation_slot(int type)
 {
-	struct swap_info_struct *pcp_si, *si = swap_type_to_info(type);
-	unsigned long pcp_offset, offset = SWAP_ENTRY_INVALID;
-	struct swap_cluster_info *ci;
+	struct swap_info_struct *si = swap_type_to_info(type);
+	unsigned long offset = SWAP_ENTRY_INVALID;
 	swp_entry_t entry = {0};
 
 	if (!si)
 		goto fail;
 
-	/*
-	 * Try the local cluster first if it matches the device. If
-	 * not, try grab a new cluster and override local cluster.
-	 */
-	local_lock(&percpu_swap_cluster.lock);
-	pcp_si = this_cpu_read(percpu_swap_cluster.si[0]);
-	pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);
-	if (pcp_si == si && pcp_offset) {
-		ci = swap_cluster_lock(si, pcp_offset);
-		if (cluster_is_usable(ci, 0))
-			offset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset);
-		else
-			swap_cluster_unlock(ci);
-	}
-	if (!offset)
-		offset = cluster_alloc_swap_entry(si, NULL);
-	local_unlock(&percpu_swap_cluster.lock);
+	offset = cluster_alloc_swap_entry(si, NULL);
 	if (offset)
 		entry = swp_entry(si->type, offset);
 
@@ -2289,26 +2686,18 @@ void swap_free_hibernation_slot(swp_entry_t entry)
 
 static int __find_hibernation_swap_type(dev_t device, sector_t offset)
 {
-	int type;
-
-	lockdep_assert_held(&swap_lock);
+	struct swap_info_struct *si;
 
 	if (!device)
 		return -EINVAL;
 
-	for (type = 0; type < nr_swapfiles; type++) {
-		struct swap_info_struct *sis = swap_info[type];
-
-		if (!(sis->flags & SWP_WRITEOK))
-			continue;
-
-		if (device == sis->bdev->bd_dev) {
-			struct swap_extent *se = first_se(sis);
-
-			if (se->start_block == offset)
-				return type;
+	for_each_avail_swap(si) {
+		if (device == si->bdev->bd_dev) {
+			if (first_se(si)->start_block == offset)
+				return si->type;
 		}
 	}
+
 	return -ENODEV;
 }
 
@@ -2331,21 +2720,18 @@ static int __find_hibernation_swap_type(dev_t device, sector_t offset)
  */
 int pin_hibernation_swap_type(dev_t device, sector_t offset)
 {
-	int type;
+	int ret;
 	struct swap_info_struct *si;
 
-	spin_lock(&swap_lock);
-
-	type = __find_hibernation_swap_type(device, offset);
-	if (type < 0) {
-		spin_unlock(&swap_lock);
-		return type;
-	}
+	percpu_down_write(&swapon_rwsem);
+	ret = __find_hibernation_swap_type(device, offset);
+	if (ret < 0)
+		goto out;
 
-	si = swap_type_to_info(type);
+	si = swap_type_to_info(ret);
 	if (WARN_ON_ONCE(!si)) {
-		spin_unlock(&swap_lock);
-		return -ENODEV;
+		ret = -ENODEV;
+		goto out;
 	}
 
 	/*
@@ -2354,14 +2740,15 @@ int pin_hibernation_swap_type(dev_t device, sector_t offset)
 	 * the same session.
 	 */
 	if (WARN_ON_ONCE(si->flags & SWP_HIBERNATION)) {
-		spin_unlock(&swap_lock);
-		return -EBUSY;
+		ret = -EBUSY;
+		goto out;
 	}
 
 	si->flags |= SWP_HIBERNATION;
 
-	spin_unlock(&swap_lock);
-	return type;
+out:
+	percpu_up_write(&swapon_rwsem);
+	return ret;
 }
 
 /**
@@ -2372,7 +2759,7 @@ int pin_hibernation_swap_type(dev_t device, sector_t offset)
  *
  * Look up the swap device for @device/@offset and atomically transfer
  * the SWP_HIBERNATION pin from @old_type (if valid) to the new device,
- * all under a single swap_lock critical section. This closes the
+ * all under a single swapon_rwsem writer section. This closes the
  * swapoff() window that exists when callers unpin and re-pin in two
  * separate operations.
  *
@@ -2392,28 +2779,28 @@ int repin_hibernation_swap_type(int old_type, dev_t device, sector_t offset)
 	struct swap_info_struct *old_si, *new_si;
 	int new_type;
 
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 
 	new_type = __find_hibernation_swap_type(device, offset);
 	if (new_type < 0) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return new_type;
 	}
 
 	new_si = swap_type_to_info(new_type);
 	if (WARN_ON_ONCE(!new_si)) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return -ENODEV;
 	}
 
 	old_si = swap_type_to_info(old_type);
 	if (new_si == old_si) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return new_type;
 	}
 
 	if (WARN_ON_ONCE(new_si->flags & SWP_HIBERNATION)) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		return -EBUSY;
 	}
 
@@ -2421,7 +2808,7 @@ int repin_hibernation_swap_type(int old_type, dev_t device, sector_t offset)
 		old_si->flags &= ~SWP_HIBERNATION;
 	new_si->flags |= SWP_HIBERNATION;
 
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	return new_type;
 }
 
@@ -2439,14 +2826,11 @@ void unpin_hibernation_swap_type(int type)
 {
 	struct swap_info_struct *si;
 
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	si = swap_type_to_info(type);
-	if (!si) {
-		spin_unlock(&swap_lock);
-		return;
-	}
-	si->flags &= ~SWP_HIBERNATION;
-	spin_unlock(&swap_lock);
+	if (si)
+		si->flags &= ~SWP_HIBERNATION;
+	percpu_up_write(&swapon_rwsem);
 }
 
 /**
@@ -2471,29 +2855,26 @@ int find_hibernation_swap_type(dev_t device, sector_t offset)
 {
 	int type;
 
-	spin_lock(&swap_lock);
+	percpu_down_read(&swapon_rwsem);
 	type = __find_hibernation_swap_type(device, offset);
-	spin_unlock(&swap_lock);
+	percpu_up_read(&swapon_rwsem);
 
 	return type;
 }
 
 int find_first_swap(dev_t *device)
 {
-	int type;
-
-	spin_lock(&swap_lock);
-	for (type = 0; type < nr_swapfiles; type++) {
-		struct swap_info_struct *sis = swap_info[type];
+	int ret = -ENODEV;
+	struct swap_info_struct *si;
 
-		if (!(sis->flags & SWP_WRITEOK))
-			continue;
-		*device = sis->bdev->bd_dev;
-		spin_unlock(&swap_lock);
-		return type;
+	percpu_down_read(&swapon_rwsem);
+	for_each_avail_swap(si) {
+		*device = si->bdev->bd_dev;
+		ret = si->type;
+		break;
 	}
-	spin_unlock(&swap_lock);
-	return -ENODEV;
+	percpu_up_read(&swapon_rwsem);
+	return ret;
 }
 
 /*
@@ -2521,7 +2902,7 @@ unsigned int count_swap_pages(int type, int free)
 {
 	unsigned int n = 0;
 
-	spin_lock(&swap_lock);
+	percpu_down_read(&swapon_rwsem);
 	if ((unsigned int)type < nr_swapfiles) {
 		struct swap_info_struct *sis = swap_info[type];
 
@@ -2533,7 +2914,7 @@ unsigned int count_swap_pages(int type, int free)
 		}
 		spin_unlock(&sis->lock);
 	}
-	spin_unlock(&swap_lock);
+	percpu_up_read(&swapon_rwsem);
 	return n;
 }
 #endif /* CONFIG_HIBERNATION */
@@ -2859,10 +3240,10 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 	unsigned long swp_tb;
 
 	/*
-	 * No need for swap_lock here: we're just looking
+	 * No need for swapon_rwsem here: we're just looking
 	 * for whether an entry is in use, not modifying it; false
 	 * hits are okay, and sys_swapoff() has already prevented new
-	 * allocations from this area (while holding swap_lock).
+	 * allocations from this area (while holding swapon_rwsem).
 	 */
 	i = prev + 1;
 	while (i < si->max) {
@@ -2992,7 +3373,7 @@ static int try_to_unuse(unsigned int type)
 success:
 	/*
 	 * Make sure that further cleanups after try_to_unuse() returns happen
-	 * after swap_range_free() reduces si->inuse_pages to 0.
+	 * after swap_device_inuse_sub() reduces si->inuse_pages to 0.
 	 */
 	smp_mb();
 	return 0;
@@ -3000,18 +3381,20 @@ static int try_to_unuse(unsigned int type)
 
 /*
  * After a successful try_to_unuse, if no swap is now in use, we know
- * we can empty the mmlist.  swap_lock must be held on entry and exit.
- * Note that mmlist_lock nests inside swap_lock, and an mm must be
+ * we can empty the mmlist. swapon_rwsem must be held on entry and exit.
+ * Note that mmlist_lock nests inside swapon_rwsem, and an mm must be
  * added to the mmlist just after page_duplicate - before would be racy.
  */
 static void drain_mmlist(void)
 {
+	struct swap_info_struct *si;
 	struct list_head *p, *next;
-	unsigned int type;
 
-	for (type = 0; type < nr_swapfiles; type++)
-		if (swap_usage_in_pages(swap_info[type]))
+	for_each_swap(si) {
+		if (swap_usage_in_pages(si))
 			return;
+	}
+
 	spin_lock(&mmlist_lock);
 	list_for_each_safe(p, next, &init_mm.mmlist)
 		list_del_init(p);
@@ -3145,58 +3528,86 @@ static int setup_swap_extents(struct swap_info_struct *sis,
 	return generic_swapfile_activate(sis, swap_file, span);
 }
 
-static void _enable_swap_info(struct swap_info_struct *si)
-{
-	atomic_long_add(si->pages, &nr_swap_pages);
-	total_swap_pages += si->pages;
-
-	assert_spin_locked(&swap_lock);
-
-	plist_add(&si->list, &swap_active_head);
-
-	/* Add back to available list */
-	add_to_avail_list(si, true);
-}
-
 /*
- * Called after the swap device is ready, resurrect its percpu ref, it's now
- * safe to reference it. Add it to the list to expose it to the allocator.
+ * Mark a fully initialized swap device writable and expose it to the allocator.
+ * The caller must have resurrected its percpu ref before entering this helper.
  */
-static void enable_swap_info(struct swap_info_struct *si)
+static void __swap_device_enable(struct swap_info_struct *si)
 {
-	percpu_ref_resurrect(&si->users);
-	spin_lock(&swap_lock);
+	lockdep_assert_held_write(&swapon_rwsem);
 	spin_lock(&si->lock);
-	_enable_swap_info(si);
+	spin_lock(&swap_queue_update_lock);
+	si->flags |= SWP_WRITEOK;
+	spin_unlock(&swap_queue_update_lock);
 	spin_unlock(&si->lock);
-	spin_unlock(&swap_lock);
+	atomic_long_add(si->pages, &nr_swap_pages);
+	total_swap_pages += si->pages;
+	add_to_avail_list(si);
 }
 
-static void reinsert_swap_info(struct swap_info_struct *si)
+static void swap_device_enable(struct swap_info_struct *si)
 {
-	spin_lock(&swap_lock);
-	spin_lock(&si->lock);
-	_enable_swap_info(si);
-	spin_unlock(&si->lock);
-	spin_unlock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
+	__swap_device_enable(si);
+	percpu_up_write(&swapon_rwsem);
 }
 
-/*
- * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range
- * see the updated flags, so there will be no more allocations.
- */
-static void wait_for_allocation(struct swap_info_struct *si)
+static int swap_device_disable(struct address_space *mapping,
+			       struct swap_info_struct **swap_info)
 {
-	unsigned long offset;
-	unsigned long end = ALIGN(si->max, SWAPFILE_CLUSTER);
+	struct swap_info_struct *si;
 	struct swap_cluster_info *ci;
+	unsigned long offset, end;
+	int err = -EINVAL;
+
+	percpu_down_write(&swapon_rwsem);
+	for_each_avail_swap(si) {
+		if (si->swap_file->f_mapping == mapping) {
+			err = 0;
+			break;
+		}
+	}
+	if (err)
+		goto unlock;
+
+	/*
+	 * Refuse swapoff while the device is pinned for hibernation.
+	 */
+	if (si->flags & SWP_HIBERNATION) {
+		err = -EBUSY;
+		goto unlock;
+	}
+
+	if (security_vm_enough_memory_mm(current->mm, si->pages)) {
+		err = -ENOMEM;
+		goto unlock;
+	}
+	vm_unacct_memory(si->pages);
+
+	/* Serialize with the WRITEOK check in isolate_lock_cluster(). */
+	spin_lock(&si->lock);
+	del_from_avail_list(si, true);
+	spin_unlock(&si->lock);
+	total_swap_pages -= si->pages;
+	atomic_long_sub(si->pages, &nr_swap_pages);
 
-	BUG_ON(si->flags & SWP_WRITEOK);
+	end = ALIGN(si->max, SWAPFILE_CLUSTER);
+unlock:
+	percpu_up_write(&swapon_rwsem);
+	if (err)
+		return err;
 
+	/*
+	 * Drain cluster-lock users after clearing SWP_WRITEOK, so swapoff
+	 * does not race with operations that started before the transition.
+	 */
 	for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) {
 		ci = swap_cluster_lock(si, offset);
 		swap_cluster_unlock(ci);
 	}
+
+	*swap_info = si;
+	return 0;
 }
 
 static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
@@ -3220,28 +3631,6 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
 	kvfree(cluster_info);
 }
 
-/*
- * Called after swap device's reference count is dead, so
- * neither scan nor allocation will use it.
- */
-static void flush_percpu_swap_cluster(struct swap_info_struct *si)
-{
-	int cpu, i;
-	struct swap_info_struct **pcp_si;
-
-	for_each_possible_cpu(cpu) {
-		pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);
-		/*
-		 * Invalidate the percpu swap cluster cache, si->users
-		 * is dead, so no new user will point to it, just flush
-		 * any existing user.
-		 */
-		for (i = 0; i < SWAP_NR_ORDERS; i++)
-			cmpxchg(&pcp_si[i], si, NULL);
-	}
-}
-
-
 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 {
 	struct swap_info_struct *p = NULL;
@@ -3250,7 +3639,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	struct address_space *mapping;
 	struct inode *inode;
 	unsigned int maxpages;
-	int err, found = 0;
+	int err;
 
 	if (!capable(CAP_SYS_ADMIN))
 		return -EPERM;
@@ -3263,44 +3652,11 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 		return PTR_ERR(victim);
 
 	mapping = victim->f_mapping;
-	spin_lock(&swap_lock);
-	plist_for_each_entry(p, &swap_active_head, list) {
-		if (p->flags & SWP_WRITEOK) {
-			if (p->swap_file->f_mapping == mapping) {
-				found = 1;
-				break;
-			}
-		}
-	}
-	if (!found) {
-		err = -EINVAL;
-		spin_unlock(&swap_lock);
-		goto out_dput;
-	}
-
-	/* Refuse swapoff while the device is pinned for hibernation */
-	if (p->flags & SWP_HIBERNATION) {
-		err = -EBUSY;
-		spin_unlock(&swap_lock);
-		goto out_dput;
-	}
-
-	if (!security_vm_enough_memory_mm(current->mm, p->pages))
-		vm_unacct_memory(p->pages);
-	else {
-		err = -ENOMEM;
-		spin_unlock(&swap_lock);
-		goto out_dput;
-	}
-	spin_lock(&p->lock);
-	del_from_avail_list(p, true);
-	plist_del(&p->list, &swap_active_head);
-	atomic_long_sub(p->pages, &nr_swap_pages);
-	total_swap_pages -= p->pages;
-	spin_unlock(&p->lock);
-	spin_unlock(&swap_lock);
+	err = swap_device_disable(mapping, &p);
+	filp_close(victim, NULL);
 
-	wait_for_allocation(p);
+	if (err)
+		return err;
 
 	set_current_oom_origin();
 	err = try_to_unuse(p->type);
@@ -3308,10 +3664,15 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	if (err) {
 		/* re-insert swap space back into swap_list */
-		reinsert_swap_info(p);
-		goto out_dput;
+		swap_device_enable(p);
+		return err;
 	}
 
+	percpu_down_write(&swapon_rwsem);
+	swap_queue_del(p);
+	percpu_ref_kill(&p->users);
+	percpu_up_write(&swapon_rwsem);
+
 	/*
 	 * Wait for swap operations protected by get/put_swap_device()
 	 * to complete.  Because of synchronize_rcu() here, all swap
@@ -3320,21 +3681,18 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	 * prevent folio_test_swapcache() and the following swap cache
 	 * operations from racing with swapoff.
 	 */
-	percpu_ref_kill(&p->users);
 	synchronize_rcu();
 	wait_for_completion(&p->comp);
 
 	flush_work(&p->discard_work);
 	flush_work(&p->reclaim_work);
-	flush_percpu_swap_cluster(p);
 
 	destroy_swap_extents(p, p->swap_file);
 
 	if (!(p->flags & SWP_SOLIDSTATE))
 		atomic_dec(&nr_rotate_swap);
 
-	mutex_lock(&swapon_mutex);
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	spin_lock(&p->lock);
 	drain_mmlist();
 
@@ -3345,10 +3703,11 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	p->max = 0;
 	p->cluster_info = NULL;
 	spin_unlock(&p->lock);
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	arch_swap_invalidate_area(p->type);
 	zswap_swapoff(p->type);
-	mutex_unlock(&swapon_mutex);
+	free_percpu(p->percpu_cluster);
+	p->percpu_cluster = NULL;
 	kfree(p->global_cluster);
 	p->global_cluster = NULL;
 	free_swap_cluster_info(cluster_info, maxpages);
@@ -3364,18 +3723,19 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	 * Clear the SWP_USED flag after all resources are freed so that swapon
 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
 	 * not hold p->lock after we cleared its SWP_WRITEOK.
+	 *
+	 * The write lock ensures the flag clear is visible to lockless
+	 * readers of swap_type_to_info() before alloc_swap_info() reuses
+	 * this slot.
 	 */
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	p->flags = 0;
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 
-	err = 0;
 	atomic_inc(&proc_poll_event);
 	wake_up_interruptible(&proc_poll_wait);
 
-out_dput:
-	filp_close(victim, NULL);
-	return err;
+	return 0;
 }
 
 #ifdef CONFIG_PROC_FS
@@ -3393,20 +3753,18 @@ static __poll_t swaps_poll(struct file *file, poll_table *wait)
 	return EPOLLIN | EPOLLRDNORM;
 }
 
-/* iterator */
 static void *swap_start(struct seq_file *swap, loff_t *pos)
 {
 	struct swap_info_struct *si;
-	int type;
 	loff_t l = *pos;
 
-	mutex_lock(&swapon_mutex);
+	percpu_down_read(&swapon_rwsem);
 
 	if (!l)
 		return SEQ_START_TOKEN;
 
-	for (type = 0; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+	for_each_swap(si) {
+		if (!si->swap_file)
 			continue;
 		if (!--l)
 			return si;
@@ -3427,7 +3785,7 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
 
 	++(*pos);
 	for (; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+		if (!(si->flags & SWP_USED) || !(si->swap_file))
 			continue;
 		return si;
 	}
@@ -3437,7 +3795,7 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
 
 static void swap_stop(struct seq_file *swap, void *v)
 {
-	mutex_unlock(&swapon_mutex);
+	percpu_up_read(&swapon_rwsem);
 }
 
 static int swap_show(struct seq_file *swap, void *v)
@@ -3530,13 +3888,13 @@ static struct swap_info_struct *alloc_swap_info(void)
 		return ERR_PTR(-ENOMEM);
 	}
 
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	for (type = 0; type < nr_swapfiles; type++) {
 		if (!(swap_info[type]->flags & SWP_USED))
 			break;
 	}
 	if (type >= MAX_SWAPFILES) {
-		spin_unlock(&swap_lock);
+		percpu_up_write(&swapon_rwsem);
 		percpu_ref_exit(&p->users);
 		kvfree(p);
 		return ERR_PTR(-EPERM);
@@ -3558,10 +3916,8 @@ static struct swap_info_struct *alloc_swap_info(void)
 		 */
 	}
 	p->swap_extent_root = RB_ROOT;
-	plist_node_init(&p->list, 0);
-	plist_node_init(&p->avail_list, 0);
 	p->flags = SWP_USED;
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	if (defer) {
 		percpu_ref_exit(&defer->users);
 		kvfree(defer);
@@ -3630,9 +3986,8 @@ __weak unsigned long arch_max_swapfile_size(void)
 	return generic_max_swapfile_size();
 }
 
-static unsigned long read_swap_header(struct swap_info_struct *si,
-					union swap_header *swap_header,
-					struct inode *inode)
+static unsigned long read_swap_header(union swap_header *swap_header,
+				      struct inode *inode)
 {
 	int i;
 	unsigned long maxpages;
@@ -3699,7 +4054,7 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 {
 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 	struct swap_cluster_info *cluster_info;
-	int err = -ENOMEM;
+	int cpu, err = -ENOMEM;
 	unsigned long i;
 
 	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
@@ -3709,13 +4064,26 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	for (i = 0; i < nr_clusters; i++)
 		spin_lock_init(&cluster_info[i].lock);
 
-	if (!(si->flags & SWP_SOLIDSTATE)) {
+	if (si->flags & SWP_SOLIDSTATE) {
+		si->percpu_cluster = alloc_percpu(struct percpu_cluster);
+		if (!si->percpu_cluster)
+			goto err;
+
+		for_each_possible_cpu(cpu) {
+			struct percpu_cluster *cluster;
+
+			cluster = per_cpu_ptr(si->percpu_cluster, cpu);
+			for (i = 0; i < SWAP_NR_ORDERS; i++)
+				cluster->next[i] = SWAP_ENTRY_INVALID;
+			local_lock_init(&cluster->lock);
+		}
+	} else {
 		si->global_cluster = kmalloc_obj(*si->global_cluster);
 		if (!si->global_cluster)
 			goto err;
 		for (i = 0; i < SWAP_NR_ORDERS; i++)
 			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
-		spin_lock_init(&si->global_cluster_lock);
+		spin_lock_init(&si->global_cluster->lock);
 	}
 
 	/*
@@ -3776,6 +4144,8 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 {
 	struct swap_info_struct *si;
+	struct swap_queue_reader __percpu *readers;
+	unsigned int nr_readers;
 	struct file *swap_file = NULL;
 	struct address_space *mapping;
 	struct dentry *dentry;
@@ -3798,7 +4168,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	/*
 	 * Allocate or reuse existing !SWP_USED swap_info. The returned
 	 * si will stay in a dying status, so nothing will access its content
-	 * until enable_swap_info resurrects its percpu ref and expose it.
+	 * until swap_device_enable resurrects its percpu ref and expose it.
 	 */
 	si = alloc_swap_info();
 	if (IS_ERR(si))
@@ -3863,7 +4233,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	}
 	swap_header = kmap_local_folio(folio, 0);
 
-	maxpages = read_swap_header(si, swap_header, inode);
+	maxpages = read_swap_header(swap_header, inode);
 	if (unlikely(!maxpages)) {
 		error = -EINVAL;
 		goto bad_swap_unlock_inode;
@@ -3951,22 +4321,38 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		goto free_swap_zswap;
 	}
 
-	mutex_lock(&swapon_mutex);
 	prio = DEF_SWAP_PRIO;
 	if (swap_flags & SWAP_FLAG_PREFER)
 		prio = swap_flags & SWAP_FLAG_PRIO_MASK;
 
+	si->prio = prio;
+
 	/*
-	 * The plist prio is negated because plist ordering is
-	 * low-to-high, while swap ordering is high-to-low
+	 * Publish swap_file before making the percpu ref live, then add the device
+	 * to the queue and make it writable under the same write-side lock. This
+	 * keeps lockless ref users and /proc/swaps from observing partial state.
 	 */
-	si->prio = prio;
-	si->list.prio = -si->prio;
-	si->avail_list.prio = -si->prio;
+	error = swap_queue_lock_for_add(prio, &readers, &nr_readers);
+	if (error) {
+		inode->i_flags &= ~S_SWAPFILE;
+		goto free_swap_zswap;
+	}
 	si->swap_file = swap_file;
-
-	/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */
-	enable_swap_info(si);
+	percpu_ref_resurrect(&si->users);
+	error = swap_queue_add(si, &readers, nr_readers);
+	if (error) {
+		si->swap_file = NULL;
+		percpu_ref_kill(&si->users);
+	} else {
+		__swap_device_enable(si);
+	}
+	percpu_up_write(&swapon_rwsem);
+	free_percpu(readers);
+	if (error) {
+		wait_for_completion(&si->comp);
+		inode->i_flags &= ~S_SWAPFILE;
+		goto free_swap_zswap;
+	}
 
 	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
 		K(si->pages), name->name, si->prio, nr_extents,
@@ -3976,7 +4362,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		(si->flags & SWP_AREA_DISCARD) ? "s" : "",
 		(si->flags & SWP_PAGE_DISCARD) ? "c" : "");
 
-	mutex_unlock(&swapon_mutex);
 	atomic_inc(&proc_poll_event);
 	wake_up_interruptible(&proc_poll_wait);
 
@@ -3987,6 +4372,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 bad_swap_unlock_inode:
 	inode_unlock(inode);
 bad_swap:
+	free_percpu(si->percpu_cluster);
+	si->percpu_cluster = NULL;
 	kfree(si->global_cluster);
 	si->global_cluster = NULL;
 	inode = NULL;
@@ -3997,9 +4384,9 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	 * Clear the SWP_USED flag after all resources are freed so
 	 * alloc_swap_info can reuse this si safely.
 	 */
-	spin_lock(&swap_lock);
+	percpu_down_write(&swapon_rwsem);
 	si->flags = 0;
-	spin_unlock(&swap_lock);
+	percpu_up_write(&swapon_rwsem);
 	if (inced_nr_rotate_swap)
 		atomic_dec(&nr_rotate_swap);
 	if (swap_file)
@@ -4014,19 +4401,17 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 
 void si_swapinfo(struct sysinfo *val)
 {
-	unsigned int type;
+	struct swap_info_struct *si;
 	unsigned long nr_to_be_unused = 0;
 
-	spin_lock(&swap_lock);
-	for (type = 0; type < nr_swapfiles; type++) {
-		struct swap_info_struct *si = swap_info[type];
-
-		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
+	percpu_down_read(&swapon_rwsem);
+	for_each_swap(si) {
+		if (!(si->flags & SWP_WRITEOK))
 			nr_to_be_unused += swap_usage_in_pages(si);
 	}
 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
 	val->totalswap = total_swap_pages + nr_to_be_unused;
-	spin_unlock(&swap_lock);
+	percpu_up_read(&swapon_rwsem);
 }
 
 /*
@@ -4066,7 +4451,33 @@ int swap_dup_entry_direct(swp_entry_t entry)
 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
 static bool __has_usable_swap(void)
 {
-	return !plist_head_empty(&swap_active_head);
+	return READ_ONCE(total_swap_pages) > 0;
+}
+
+static struct swap_info_struct *swap_queue_first_usable_bdev(void)
+{
+	struct swap_prio_ring *ring;
+	struct swap_info_struct *si;
+	unsigned int ring_idx, dev_idx;
+
+	lockdep_assert_held(&swapon_rwsem);
+	for (ring_idx = 0; ring_idx < swap_queue_len; ring_idx++) {
+		ring = swap_queue[ring_idx];
+		for (dev_idx = 0; dev_idx < ring->size; dev_idx++) {
+			si = READ_ONCE(ring->dev[dev_idx]);
+			if (swap_device_masked(si))
+				continue;
+			si = swap_device_unmask_ptr(si);
+			if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
+				continue;
+			if (atomic_long_read(&si->inuse_pages) &
+			    SWAP_USAGE_OFFLIST_BIT)
+				continue;
+			if (si->bdev)
+				return si;
+		}
+	}
+	return NULL;
 }
 
 void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
@@ -4089,14 +4500,11 @@ void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
 	if (current->throttle_disk)
 		return;
 
-	spin_lock(&swap_avail_lock);
-	plist_for_each_entry(si, &swap_avail_head, avail_list) {
-		if (si->bdev) {
-			blkcg_schedule_throttle(si->bdev->bd_disk, true);
-			break;
-		}
-	}
-	spin_unlock(&swap_avail_lock);
+	percpu_down_read(&swapon_rwsem);
+	si = swap_queue_first_usable_bdev();
+	if (si)
+		blkcg_schedule_throttle(si->bdev->bd_disk, true);
+	percpu_up_read(&swapon_rwsem);
 }
 #endif
 

25/3 2026/11/18 16:22 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30216
							output: 18
							thoughts: 2093
						

Thoughts:
**KMSAN Evaluation for this Swap Patch Series**

Okay, let's break this down. My goal is to determine if this kernel patch series warrants a dedicated KMSAN fuzzing session. The guiding principle is clear: if KASAN, LOCKDEP, or standard debuggers are sufficient, then KMSAN is overkill.

So, let's go through the checklist:

*   **Patch Series Analysis**:
    *   This patch focuses on refactoring the swap device management, specifically moving away from `plist` structures and global locks towards priority rings and per-CPU clusters. This includes changes in `plist.h`, `swap.h`, `plist.c`, `swapfile.c`, and `swap.h`

*   **KMSAN Trigger Checklist**:
    *   **User-Space Interaction**: I need to check if any kernel structures are now being sent to user-space in ways that might expose uninitialized memory. This means scrutinizing calls to functions like `copy_to_user`, `put_user`, netlink, ioctl, socket options, or BPF buffers. Importantly, are there now new fields in structures that could be uninitialized? Let's check:
    *   **Conditional Logic**: The checklist says to look for conditional logic that depends on potentially uninitialized variables. This is where uninitialized memory could become a problem.
    *   **Data Structure Initialization**: The series changes allocations and initialization of data structures, potentially where uninitialized fields are read later.
    *   **Bounds Checks/Lengths**: No evidence of this yet.

*   **Deep Dive into `mm/swapfile.c`**:
    *   **Memory Allocation**: The patch introduces new per-CPU data structures (`percpu_cluster`, `swap_queue_readers`). I need to verify that these are initialized correctly, especially when allocated with functions like `__alloc_percpu_gfp` (which by default zeroes the memory).
    *   I see that `__alloc_percpu_gfp` does zero the memory in Linux.
    *   `swap_queue_install_readers`:  This function initializes locks for each CPU, but does not read uninitialized memory.
    *   **Ring Structure**: `swap_queue_add`, `swap_queue_del`, introduce allocation/copying using `kmalloc_array`, `kmalloc`, `memcpy`. I need to ensure there are no uninitialized fields being copied. Looks good so far; they are explicitly initialized with values.
    *   **`setup_swap_clusters_info`**: This function initializes the `percpu_cluster` for SSD or the `global_cluster` for rotational disks. It appears the members are initialized.
    *   **Zero Initialization**: There are several instances of local variables and bitmaps being initialized to zero (`swap_alloc_entry`, `swap_discard_for_alloc`). This is a good sign.
    *   **No Obvious Data Copies to Userspace**: So far I don't see any direct data copies from kernel to user space. But let's verify. I must verify if `si_swapinfo(struct sysinfo *val)` copies to user space. This warrants a quick search for callers of this function.

*   **Action**: I'm going to run a quick grep for calls to `si_swapinfo` to confirm or deny this. If there are no data copies to userspace or any other KMSAN related issue, this patch series does *not* warrant a dedicated KMSAN session.



26/3 2026/11/18 16:23 tool grepper
0m Args:
{
  "Expression": "si_swapinfo"
}

Results:
{
  "Output": "Documentation/livepatch/module-elf-format.rst=267=Examples:\n--\nDocumentation/livepatch/module-elf-format.rst-287-      75: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT OS [0xff20] .klp.sym.vmlinux.find_next_bit,0\nDocumentation/livepatch/module-elf-format.rst:288:      76: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT OS [0xff20] .klp.sym.vmlinux.si_swapinfo,0\nDocumentation/livepatch/module-elf-format.rst-289-    [ snip ]                                               ^\n--\narch/s390/appldata/appldata_base.c=461=EXPORT_SYMBOL_GPL(appldata_diag);\n--\narch/s390/appldata/appldata_base.c-463-#ifdef CONFIG_SWAP\narch/s390/appldata/appldata_base.c:464:EXPORT_SYMBOL_GPL(si_swapinfo);\narch/s390/appldata/appldata_base.c-465-#endif\n--\narch/s390/appldata/appldata_mem.c=72=static void appldata_get_mem_data(void *data)\n--\narch/s390/appldata/appldata_mem.c-104-\narch/s390/appldata/appldata_mem.c:105:\tsi_swapinfo(\u0026val);\narch/s390/appldata/appldata_mem.c-106-\tmem_data-\u003etotalswap = P2K(val.totalswap);\n--\nfs/proc/meminfo.c=34=static int meminfo_proc_show(struct seq_file *m, void *v)\n--\nfs/proc/meminfo.c-44-\tsi_meminfo(\u0026i);\nfs/proc/meminfo.c:45:\tsi_swapinfo(\u0026i);\nfs/proc/meminfo.c-46-\tcommitted = vm_memory_committed();\n--\ninclude/linux/swap.h=409=static inline long get_nr_swap_pages(void)\n--\ninclude/linux/swap.h-413-\ninclude/linux/swap.h:414:extern void si_swapinfo(struct sysinfo *);\ninclude/linux/swap.h-415-extern int pin_hibernation_swap_type(dev_t device, sector_t offset);\n--\ninclude/linux/swap.h=466=static inline void put_swap_device(struct swap_info_struct *si)\n--\ninclude/linux/swap.h-474-\ninclude/linux/swap.h:475:#define si_swapinfo(val) \\\ninclude/linux/swap.h-476-\tdo { (val)-\u003efreeswap = (val)-\u003etotalswap = 0; } while (0)\n--\nkernel/sys.c=2937=static int do_sysinfo(struct sysinfo *info)\n--\nkernel/sys.c-2953-\tsi_meminfo(info);\nkernel/sys.c:2954:\tsi_swapinfo(info);\nkernel/sys.c-2955-\n--\nmm/swapfile.c=4144=SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n--\nmm/swapfile.c-4401-\nmm/swapfile.c:4402:void si_swapinfo(struct sysinfo *val)\nmm/swapfile.c-4403-{\n--\nnet/netfilter/ipvs/ip_vs_ctl.c=93=static void update_defense_level(struct netns_ipvs *ipvs)\n--\nnet/netfilter/ipvs/ip_vs_ctl.c-105-\t   we need adjust it */\nnet/netfilter/ipvs/ip_vs_ctl.c:106:\t/* si_swapinfo(\u0026i); */\nnet/netfilter/ipvs/ip_vs_ctl.c-107-\t/* availmem = availmem - (i.totalswap - i.freeswap); */\n"
}

27/3 2026/11/18 16:23 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34151
							output: 30
							thoughts: 258
						

Thoughts:
**Analyzing Swap Information Retrieval**

Okay, let's break down this `si_swapinfo` function. My initial impression is that it's responsible for populating a `sysinfo` structure with swap space statistics. We're getting the free and total swap pages. The code uses `percpu_down_read` and `percpu_up_read` on `swapon_rwsem` which suggests this is dealing with a read-mostly lock for swap device information, which is good practice.

I see a loop iterating through swap entries using `for_each_swap`.  Within the loop, there's a check for `SWP_WRITEOK` and if the swap is not writable, `swap_usage_in_pages` is summed into `nr_to_be_unused`. The interesting part is how this `nr_to_be_unused` gets added to `atomic_long_read(&nr_swap_pages)` and `total_swap_pages` to calculate `val->freeswap` and `val->totalswap`.  This is clever - it's compensating for swap entries that aren't currently considered "available" for writing, but *are* present and counted. The code is carefully accounting for the pages on these non-writable swap spaces, in order to get an accurate total. This suggests potential issues like read-only mounted swap partitions, or possibly degraded swap devices that are still present in the system, but shouldn't be written to. Good, so we're ensuring there are no uninitialized values in `val->freeswap` and `val->totalswap` which is crucial for reliability.

Now I need to remember, what about `/proc/swaps`? I'm assuming that this function is providing the data that is visible there, or at least a subset of it. The next logical step is to analyze the functions related to `/proc/swaps`: `swap_start`, `swap_next`, `swap_stop`, and `swap_show`. I'm especially keen to look at `swap_show` because it's most likely the code that's responsible for the actual display of swap information.



28/3 2026/11/18 16:24 tool grepper
0m Args:
{
  "Expression": "swap_show",
  "PathPrefixes": [
    "mm/swapfile.c"
  ]
}

Results:
{
  "Output": "mm/swapfile.c=3796=static void swap_stop(struct seq_file *swap, void *v)\n--\nmm/swapfile.c-3800-\nmm/swapfile.c:3801:static int swap_show(struct seq_file *swap, void *v)\nmm/swapfile.c-3802-{\n--\nmm/swapfile.c=3828=static const struct seq_operations swaps_op = {\n--\nmm/swapfile.c-3831-\t.stop =\t\tswap_stop,\nmm/swapfile.c:3832:\t.show =\t\tswap_show\nmm/swapfile.c-3833-};\n"
}

29/3 2026/11/18 16:24 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35084
							output: 35
							thoughts: 9
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and rendered in the first person:

**Analyzing the `swap_show` Function Call**

Alright, let's dive in. I see we're about to read the code related to `swap_show`. My immediate assumption is that this function likely deals with the visual representation of a swap operation. Given the common usage of "swap" in programming contexts, I anticipate this involves the exchange of data or pointers, and "show" probably means displaying the state of the data before, during, or after that exchange.

I'm mentally preparing to scrutinize the implementation for efficiency. Are there any potential bottlenecks? Memory allocation issues? Unnecessary copies? I'll be looking for how it handles different data types, if it's generic, and if it integrates well with the rest of the display framework. I'm especially keen to see how the "show" part is implemented – is it using a standard library, or something custom? Does it visualize the swap itself, or simply the end result?

This is likely a critical area for performance and debugging, so my initial focus will be on the core logic and how it interacts with the underlying data structures. I'll expect good comments and clear variable names to ease the analysis. Let's see if the code meets my expectations!



30/3 2026/11/18 16:25 tool read-file
0m Args:
{
  "File": "mm/swapfile.c",
  "FirstLine": 3800,
  "LineCount": 30
}

Results:
{
  "Contents": "3800:\t\n3801:\tstatic int swap_show(struct seq_file *swap, void *v)\n3802:\t{\n3803:\t\tstruct swap_info_struct *si = v;\n3804:\t\tstruct file *file;\n3805:\t\tint len;\n3806:\t\tunsigned long bytes, inuse;\n3807:\t\n3808:\t\tif (si == SEQ_START_TOKEN) {\n3809:\t\t\tseq_puts(swap, \"Filename\\t\\t\\t\\tType\\t\\tSize\\t\\tUsed\\t\\tPriority\\n\");\n3810:\t\t\treturn 0;\n3811:\t\t}\n3812:\t\n3813:\t\tbytes = K(si-\u003epages);\n3814:\t\tinuse = K(swap_usage_in_pages(si));\n3815:\t\n3816:\t\tfile = si-\u003eswap_file;\n3817:\t\tlen = seq_file_path(swap, file, \" \\t\\n\\\\\");\n3818:\t\tseq_printf(swap, \"%*s%s\\t%lu\\t%s%lu\\t%s%d\\n\",\n3819:\t\t\t\tlen \u003c 40 ? 40 - len : 1, \" \",\n3820:\t\t\t\tS_ISBLK(file_inode(file)-\u003ei_mode) ?\n3821:\t\t\t\t\t\"partition\" : \"file\\t\",\n3822:\t\t\t\tbytes, bytes \u003c 10000000 ? \"\\t\" : \"\",\n3823:\t\t\t\tinuse, inuse \u003c 10000000 ? \"\\t\" : \"\",\n3824:\t\t\t\tsi-\u003eprio);\n3825:\t\treturn 0;\n3826:\t}\n3827:\t\n3828:\tstatic const struct seq_operations swaps_op = {\n3829:\t\t.start =\tswap_start,\n"
}

31/3 2026/11/18 16:25 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35921
							output: 380
							thoughts: 4651
						

Thoughts:
**Analysis of Swap Subsystem Changes and KMSAN Applicability**

Okay, here's the breakdown. I've been diving into this code, specifically around `mm/swapfile.c`, to understand these changes. The core idea is a shift away from the existing lists (`available`, `active`) and towards a priority ring structure using `swap_prio_ring` and `swap_queue`. This also involves introducing a static percpu read-write semaphore (`swapon_rwsem`) and a spinlock (`swap_queue_update_lock`) for synchronization. We've got per-CPU reader state (`swap_queue_reader`) as well as cluster locks per CPU (`percpu_cluster`).

First, I've confirmed that every dynamically allocated structure --  `swap_prio_ring`, `swap_queue`, `swap_queue_reader`, `percpu_cluster`, `swap_sequential_cluster` -- is properly initialized. Either these are initialized by `alloc_percpu` (which zeroes) or `kvzalloc` or the members and flexible array elements are fully initialized by `memcpy` with known valid bounds or explicit assignments (e.g. `swap_queue_reset_readers`, loops). Stack variables like `struct swap_queue_cursor cursor = {}`, bitmaps (`checked`, `discarded`) are initialized by explicit zeroing. This covers all the key data structures.

Second, there is *no* direct exposure of kernel structures to user space.  The `swapon` and `swapoff` syscalls return error codes, simple integers.  /proc/swaps formatting is a simple `seq_printf` function of initialized variables. There are no memory leaks or copies to user space. `si_swapinfo` is computing page counts for `sysinfo` using atomic counters.

Now, considering KMSAN, my assessment is that we're primarily dealing with concurrency issues: potential deadlocks, races between `swapon_rwsem` and `swap_queue_update_lock`, and possible out-of-bounds indexing or use-after-free conditions during queue resizing, reader updates, or cluster operations. The central question is: does KMSAN bring anything to the table here?

My analysis is that the risks are already covered. KASAN is well-equipped to detect out-of-bounds array accesses (e.g., `ring->dev[dev_idx]`, `swap_queue[ring_idx]`, `ri[queue_idx]`) and use-after-free scenarios. LOCKDEP will catch any potential locking issues, deadlocks, and incorrect lock ordering or usage. No uninitialized memory reads or kernel information leaks have been identified, so KMSAN will not find anything useful.

Therefore,  `NeedsKMSAN` is `false`. The reasoning is clear, and the contrasting discussion for `set-results` is ready. We can proceed with confidence.



32/3 2026/11/18 16:26 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series reworks the internal swap device management and locking hierarchy in mm/swapfile.c. It replaces the plist-based active and available lists with priority rings (struct swap_prio_ring, swap_queue) protected by a percpu rwsem (swapon_rwsem) and a spinlock (swap_queue_update_lock), alongside per-CPU reader iterators (struct swap_queue_reader) and percpu/global cluster allocation state.\n\nKMSAN vs KASAN Applicability:\n1. Memory Initialization: All newly allocated kernel data structures (percpu_cluster via alloc_percpu, swap_prio_ring via kmalloc with explicit element initialization/memcpy, swap_queue_reader via __alloc_percpu_gfp followed by local_lock_init and swap_queue_reset_readers, and swap_info_struct via kvzalloc) are thoroughly initialized before use. Local stack variables (cursor, bitmap arrays) are explicitly zero-initialized with '= {}'.\n2. Info-Leaks and Userspace Boundaries: No kernel structures or raw kernel buffers are copied or exposed to userspace. /proc/swaps and si_swapinfo only format text and aggregate numeric counters from initialized fields.\n3. Failure Modes: The primary risks introduced by this refactoring are synchronization/locking bugs (deadlocks, lock ordering issues), use-after-free (during queue/ring reallocation and reader replacement), and array indexing or bounds errors. These are comprehensively detected by standard KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory reads or information leak risks that would be caught uniquely by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series reworks the internal swap device management and locking hierarchy in mm/swapfile.c. It replaces the plist-based active and available lists with priority rings (struct swap_prio_ring, swap_queue) protected by a percpu rwsem (swapon_rwsem) and a spinlock (swap_queue_update_lock), alongside per-CPU reader iterators (struct swap_queue_reader) and percpu/global cluster allocation state.\n\nKMSAN vs KASAN Applicability:\n1. Memory Initialization: All newly allocated kernel data structures (percpu_cluster via alloc_percpu, swap_prio_ring via kmalloc with explicit element initialization/memcpy, swap_queue_reader via __alloc_percpu_gfp followed by local_lock_init and swap_queue_reset_readers, and swap_info_struct via kvzalloc) are thoroughly initialized before use. Local stack variables (cursor, bitmap arrays) are explicitly zero-initialized with '= {}'.\n2. Info-Leaks and Userspace Boundaries: No kernel structures or raw kernel buffers are copied or exposed to userspace. /proc/swaps and si_swapinfo only format text and aggregate numeric counters from initialized fields.\n3. Failure Modes: The primary risks introduced by this refactoring are synchronization/locking bugs (deadlocks, lock ordering issues), use-after-free (during queue/ring reallocation and reader replacement), and array indexing or bounds errors. These are comprehensively detected by standard KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory reads or information leak risks that would be caught uniquely by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)