mm/swap: introduce priority queues for swap device allocation
Subsystems (3)
v5 cover mm/swap: introduce priority queues for swap device allocation
Hi all,
This is v5 of Kairui Song's swap priority queue series. Today, choosing among swap devices of equal priority means rotating a shared plist. With this series, each CPU advances its own position in a ring of equal-priority devices. The allocator selects a device before looking for slots on it. This keeps the existing global swap priorities and does not add a tier ABI or a per-memcg device-selection policy. Memcg swap accounting and limits are unchanged.
Thanks to Kairui and Kunwu Chan for reviewing v4. I'm dropping the RFC tag and submitting the series for review.
Changes since v4:
- Rebased onto mm-unstable at 7d1a16abe4cc (7.4-rc3), retaining the upstream swap size reporting fix in swap_show() and swapon().
- Following Kairui's review, renamed swap_ring_iterator to swap_queue_reader_head and ring_only to no_fallback. A large folio can still try other devices of the same priority after an allocation failure, but not a lower priority.
- Following Kunwu's review, retained READ_ONCE() in the availability check, removed a misleading comment about slot reuse, and made both /proc/swaps iterators check the published swap_file under the read lock.
- Split the off-list bit fix into patch 10, before the queue conversion. The plist allocator also needs to mask that bit when checking whether a swap device is full.
- Revised patch 04 to distinguish all allocated descriptors from writable devices. drain_mmlist() needs only the usage count and no longer reads the flags. si_swapinfo() takes one flags snapshot when accounting for devices being taken offline. I have not carried the previous Reviewed-by on that patch.
Testing:
I ran Kairui's benchmarks on the 7.4-rc3 base (7d1a16abe4cc) before and after applying the then-current v5 patches.
On one x86-64 host, both kernels built the same source (4dbe24720eb3) with make -j96 and eight 8-GiB ZRAM devices. Each build used a fresh output directory. The BRD test used twelve 8-GiB RAM disks, a 24-GiB memcg limit and one invocation per kernel:
usemem --init-time -O -y -x -n 32 1536M
Times are in seconds (means for kbuild).
Workload Runs/kernel SYS: Before -> After Wall: Before -> After kbuild, 2 GiB 12 4193.23 -> 4271.06 167.80 -> 168.80 kbuild, 3 GiB 12 2257.60 -> 2299.63 136.29 -> 136.77
12-BRD 1 141.16 -> 131.44 6.61 -> 6.32
Both kbuild cases used 1.86% more system CPU time; elapsed time rose by 0.60% and 0.35%, respectively. In the single BRD run, throughput (48 GiB mapped divided by elapsed time) rose from 7436 to 7777 MiB/s (+4.59%). There was one boot per kernel and the baseline ran first. The BRD result alone does not establish a repeatable speedup.
v4:
https://lore.kernel.org/all/[email protected]/
v1 and original test method:
https://lore.kernel.org/all/[email protected]/
Related swap tier work:
https://lore.kernel.org/all/[email protected]/
Best regards,
Lian Wang
---
Kairui Song (12):
mm/swap: remove unused parameter for reading swap header mm/swap: clean up hibernation error handling
mm/swap: cleanup and document swap device availability flag usage mm/swap: introduce swap device iteration helper mm/swap: change the swapon lock into a percpu rwsem mm/swap: serialize swap publication before removing swapon mutex mm/swap: consolidate swap inuse accounting helpers mm/swap: add priority queue for swap device allocation mm/swap: remove available list
mm/swap: bound synchronous discard outside the allocation reader mm/swap: drop swap active plist
lib/plist.c: remove requeue function
Lian Wang (6):
mm/swap: avoid direct reclaim when populating swap cluster metadata mm/swap: mask the off-list bit when checking whether swap is full mm/swap: reuse per-CPU queue readers across priority changes mm/swap: advance the global queue cursor directly between priority
rings
mm/swap: skip reader rotation for single-device priority rings mm/swap: redistribute queue readers after membership changes
Youngjun Park (1):
mm/swap: change back to use each swap device's percpu cluster
include/linux/plist.h | 2 - include/linux/swap.h | 45 +- lib/plist.c | 71 -- mm/swap.h | 12 +- mm/swapfile.c | 1446 ++++++++++++++++++++++++++--------------- 5 files changed, 963 insertions(+), 613 deletions(-)
base-commit: 7d1a16abe4cc5dccd21e3d6262e44433a5885d27
PATCH v5 1/19 mm/swap: remove unused parameter for reading swap header
From: Kairui Song <[email protected]>
The swap_info_struct argument to read_swap_header() is unused. Remove it and update the swapon() call site.
No functional change.
--- mm/swapfile.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
mm/swapfile.c +3 -4
@@ -3630,9 +3630,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;
@@ -3863,7 +3862,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;
PATCH v5 2/19 mm/swap: clean up hibernation error handling
In reply to Lian WangFrom: Kairui Song <[email protected]>
Restructure the error paths in pin_hibernation_swap_type() using a goto out pattern to avoid repeated spin_unlock() calls and simplify the return flow. Also simplify unpin_hibernation_swap_type() by making the si NULL check inline, and clean up find_first_swap() to avoid an early return inside the loop.
--- mm/swapfile.c | 39 +++++++++++++++++---------------------- 1 file changed, 17 insertions(+), 22 deletions(-)
mm/swapfile.c +17 -22
@@ -2331,21 +2331,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); + ret =__find_hibernation_swap_type (device, offset); +if (ret <0 ) + goto out; - type =__find_hibernation_swap_type (device, offset); -if (type <0 ) { -spin_unlock (&swap_lock); -return type; - } - - 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 +2351,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 ; +out:spin_unlock (&swap_lock); -return type; +return ret; }/**
@@ -2441,11 +2439,8 @@ void unpin_hibernation_swap_type(int type)spin_lock (&swap_lock); si =swap_type_to_info (type); -if (!si) { -spin_unlock (&swap_lock); -return ; - } - si->flags &= ~SWP_HIBERNATION ; +if (si) + si->flags &= ~SWP_HIBERNATION ;spin_unlock (&swap_lock); }
@@ -2480,7 +2475,7 @@ int find_hibernation_swap_type(dev_t device, sector_t offset)int find_first_swap (dev_t *device) { -int type; +int type, ret = -ENODEV ;spin_lock (&swap_lock);for (type =0 ; type < nr_swapfiles; type++) {
@@ -2489,11 +2484,11 @@ int find_first_swap(dev_t *device)if (!(sis->flags &SWP_WRITEOK ))continue ; *device = sis->bdev->bd_dev; -spin_unlock (&swap_lock); -return type; + ret = type; +break ; }spin_unlock (&swap_lock); -return -ENODEV ; +return ret; }/*
PATCH v5 3/19 mm/swap: cleanup and document swap device availability flag usage
In reply to Lian WangFrom: Kairui Song <[email protected]>
Rework swap device flag and metadata handling to make the writable publication and disable boundaries explicit.
Introduce swap_device_enable() and swap_device_disable(). Move SWP_WRITEOK updates into these boundaries. Clear the writable flag, set the off-list state and remove the available entry in one swap_avail_lock critical section, before releasing swap_lock.
Preserve the existing swap_lock critical section across mapping lookup, hibernation checks and the disable transition. Drain cluster allocators after dropping swap_lock, retaining the device-identity protection without holding swap_lock over all cluster locks.
Document the flag lifetime and locking rules.
--- include/linux/swap.h | 29 ++++-- mm/swapfile.c | 205 ++++++++++++++++++++----------------------- 2 files changed, 118 insertions(+), 116 deletions(-)
include/linux/swap.h +21 -8
@@ -188,6 +188,24 @@ 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: +* - SWP_USED: Protected by swap_lock. 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 swap_lock, si->lock and swap_avail_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 swap_lock. 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? */
@@ -256,14 +274,9 @@ struct swap_info_struct {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 swap_lock. */ struct work_struct discard_work;/* discard worker */ struct work_struct reclaim_work;/* reclaim worker */
mm/swapfile.c +97 -108
311 lines not on this page · raw message
PATCH v5 4/19 mm/swap: introduce swap device iteration helper
In reply to Lian WangFrom: Kairui Song <[email protected]>
Separate iteration over allocated swap_info descriptors from iteration over writable devices. Hibernation lookups require SWP_USED and SWP_WRITEOK under swap_lock. Take a single snapshot for each flag test, since unrelated bits in the same word can change during setup.
drain_mmlist() only needs the atomic usage count; walk every descriptor without loading flags there. In si_swapinfo(), count usage only for descriptors that are in use but no longer writable.
Move the live-reference warning from __swap_type_to_info() into __swap_entry_to_info(). The iterator must inspect descriptors before applying its flag filter, including descriptors whose device reference is dead; entry-based lookup retains the warning.
--- mm/swap.h | 12 ++++---- mm/swapfile.c | 77 ++++++++++++++++++++++++++++++++------------------- 2 files changed, 54 insertions(+), 35 deletions(-)
mm/swap.h +6 -6
@@ -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(
mm/swapfile.c +48 -29
122 lines not on this page · raw message
PATCH v5 5/19 mm/swap: change the swapon lock into a percpu rwsem
In reply to Lian WangFrom: Kairui Song <[email protected]>
Reading swap metadata is a common hot path, while swapon and swapoff are costly and rare. Convert swap_lock from a spinlock to the swapon_rwsem percpu rwsem so metadata readers can run concurrently. Writers still serialize topology changes and exclude readers.
Preserve the atomic writable/off-list/available-list transition under swap_avail_lock. The device-selection and cluster-allocation paths do not yet hold swapon_rwsem; the priority queue patch adds that allocation reader protocol.
Also update the comments in swap_info_struct to reflect the lock name change.
--- include/linux/swap.h | 10 ++-- mm/swapfile.c | 126 ++++++++++++++++++++++--------------------- 2 files changed, 69 insertions(+), 67 deletions(-)
include/linux/swap.h +5 -5
@@ -192,18 +192,18 @@ struct swap_extent {* 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: -* - SWP_USED: Protected by swap_lock. Indicates the device is inuse. Once +* 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 swap_lock, si->lock and swap_avail_lock. +* - SWP_WRITEOK: Protected by swapon_rwsem, si->lock and swap_avail_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 swap_lock. Indicates if the device +* - SWP_HIBERNATION: Protected by swapon_rwsem. Indicates if the device * is pinned for hibernation. */ enum {
@@ -276,7 +276,7 @@ struct swap_info_struct {spinlock_t lock;/* * Protect cluster lists. Other fields * are only changed at swapon/swapoff, -* so are protected by swap_lock. +* so are protected by swapon_rwsem. */ struct work_struct discard_work;/* discard worker */ struct work_struct reclaim_work;/* reclaim worker */
mm/swapfile.c +64 -62
380 lines not on this page · raw message
PATCH v5 6/19 mm/swap: serialize swap publication before removing swapon mutex
In reply to Lian WangFrom: Kairui Song <[email protected]>
Move publication of swap_file, resurrection of the device reference and the writable transition into one swapon_rwsem writer section. Split out a writer-held enable helper so initial publication can share this section, while failed swapoff can use the locking wrapper.
With file publication and teardown serialized by the writer, remove swapon_mutex and use a topology reader across /proc/swaps iteration. Only expose entries with a published swap_file. Other bits in flags can already change during device setup, before publication.
The publication boundary excludes proc readers from partially published state and gives the lockless live-reference users initialized device metadata before the device becomes an allocation candidate.
--- mm/swapfile.c | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-)
mm/swapfile.c +19 -20
@@ -139,9 +139,6 @@ static inline struct swap_info_struct *__swap_iter(int *i, unsigned long flag)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 );
@@ -3161,9 +3158,9 @@ static int setup_swap_extents(struct swap_info_struct *sis,* Mark a fully initialized swap device writable and expose it to the * allocator. The caller must have resurrected its percpu ref first. */ -static void swap_device_enable (struct swap_info_struct *si) +static void __swap_device_enable (struct swap_info_struct *si) { -percpu_down_write (&swapon_rwsem); +lockdep_assert_held_write (&swapon_rwsem);spin_lock (&si->lock);spin_lock (&swap_avail_lock); si->flags |=SWP_WRITEOK ;
@@ -3173,11 +3170,16 @@ static void swap_device_enable(struct swap_info_struct *si)atomic_long_add (si->pages, &nr_swap_pages); total_swap_pages += si->pages;plist_add (&si->list, &swap_active_head); -percpu_up_write (&swapon_rwsem); -add_to_avail_list (si); } +static void swap_device_enable (struct swap_info_struct *si) +{ +percpu_down_write (&swapon_rwsem); +__swap_device_enable (si); +percpu_up_write (&swapon_rwsem); +} +static int swap_device_disable (struct address_space *mapping,struct swap_info_struct **swap_info) {
@@ -3340,7 +3342,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)if (!(p->flags &SWP_SOLIDSTATE ))atomic_dec (&nr_rotate_swap); -mutex_lock (&swapon_mutex);percpu_down_write (&swapon_rwsem);spin_lock (&p->lock);drain_mmlist ();
@@ -3355,7 +3356,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)percpu_up_write (&swapon_rwsem);arch_swap_invalidate_area (p->type);zswap_swapoff (p->type); -mutex_unlock (&swapon_mutex);kfree (p->global_cluster); p->global_cluster =NULL ;free_swap_cluster_info (cluster_info, maxpages);
@@ -3397,20 +3397,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_info (si) { +if (!si->swap_file)continue ;if (!--l)return si;
@@ -3431,7 +3429,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->swap_file)continue ;return si; }
@@ -3441,7 +3439,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)
@@ -3954,7 +3952,6 @@ 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 ;
@@ -3966,11 +3963,14 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) si->prio = prio; si->list.prio = -si->prio; si->avail_list.prio = -si->prio; +/* Publish the file, live reference and writable state together. */ +percpu_down_write (&swapon_rwsem); si->swap_file = swap_file; -/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */ +/* Make the reference live before exposing the writable device. */ percpu_ref_resurrect (&si->users); -swap_device_enable (si); +__swap_device_enable (si); +percpu_up_write (&swapon_rwsem); pr_info("Adding %luk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", K((unsigned long)si->pages), name->name, si->prio, nr_extents,
@@ -3980,7 +3980,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);
PATCH v5 7/19 mm/swap: consolidate swap inuse accounting helpers
In reply to Lian WangFrom: Kairui Song <[email protected]>
Inline the swap_usage_add/sub helpers into their only callers and rename the callers to better reflect what they actually do: track per-device inuse page counts.
Keep the existing accounting and allocation policy. In the inlined full-device path, reclaim work is scheduled before availability removal rather than afterwards. Slot-free notifications and zswap invalidation retain their existing order.
--- mm/swapfile.c | 64 ++++++++++++++++++++++----------------------------- 1 file changed, 27 insertions(+), 37 deletions(-)
mm/swapfile.c +27 -37
@@ -49,8 +49,8 @@#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,
@@ -1045,7 +1045,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; }
@@ -1363,53 +1363,36 @@ static void add_to_avail_list(struct swap_info_struct *si) }/* -* 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. */ -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); -} - -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);
@@ -1431,7 +1414,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 plist. +*/ + 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)
@@ -2059,7 +2049,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)
@@ -2999,7 +2989,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 ;
PATCH v5 8/19 mm/swap: change back to use each swap device's percpu cluster
In reply to Lian WangFrom: Youngjun Park <[email protected]>
This reverts commit 1b7e90020eb7 ("mm, swap: use percpu cluster as allocation fast path").
The global percpu cluster causes several issues:
1) It prevents efficient swap allocation for users that do not want the default swap device policy. Because the cluster cache sits above device selection, users that need a different policy must bypass or replace the cache. This complicates incoming ideas like swap tiering.
2) It can bypass a caller's preferred device policy. Consider a future policy with per-memcg device restrictions: memcg1 can access devices A and B, where A has higher priority; memcg2 can only access B. Memcg2 can write the global percpu cluster with device B, then memcg1 takes B in the fast path even though higher-priority device A is not exhausted.
3) The fast-path / slow-path design bundled with the global per-CPU cache is problematic: only the fast path uses the global cache, and the slow path is forced to rotate the allocation list. This complicates consumers like discard.
Revert to per-device percpu clusters first. A later patch will introduce new infrastructure for a high-performance global allocation path.
--- include/linux/swap.h | 13 +++- mm/swapfile.c | 170 ++++++++++++++----------------------------- 2 files changed, 63 insertions(+), 120 deletions(-)
include/linux/swap.h +10 -3
@@ -241,10 +241,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 */ };
@@ -267,8 +274,8 @@ 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 */
mm/swapfile.c +53 -117
293 lines not on this page · raw message
PATCH v5 9/19 mm/swap: avoid direct reclaim when populating swap cluster metadata
In reply to Lian WangSwap cluster population is entered from swap allocation and may itself need memory for slot metadata. Its fallback drops the device and cluster locks before allocating with GFP_KERNEL, which can reenter swap allocation through direct reclaim.
Make this allocation boundary explicitly non-reclaiming so callers can retain outer synchronization without a recursive swap allocation. Clear __GFP_DIRECT_RECLAIM from the fallback request while retaining __GFP_HIGH and __GFP_NOMEMALLOC. The retry can still wake kswapd, but fails without direct reclaim when memory is unavailable.
This can make metadata allocation fail earlier under memory pressure. Keep the existing isolated-cluster rollback and restrict this request without adding a task-wide PF_MEMALLOC scope.
--- mm/swapfile.c | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-)
mm/swapfile.c +13 -10
@@ -586,13 +586,14 @@ 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;/*
@@ -610,9 +611,11 @@ 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. +* Drop the device and cluster locks before retrying. Metadata allocation +* must not recurse into swap allocation through direct reclaim: callers +* can retain outer synchronization across cluster population. 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 )
@@ -620,8 +623,9 @@ swap_cluster_populate(struct swap_info_struct *si,else spin_unlock (&si->global_cluster->lock); - 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
@@ -3160,9 +3164,8 @@ static int swap_device_disable(struct address_space *mapping,return err;/* -* The swap allocator doesn't take swapon_rwsem. Looping through every -* cluster lock after clearing SWP_WRITEOK ensures that allocators see -* the updated flag and that no allocation remains in flight. +* 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);
PATCH v5 10/19 mm/swap: mask the off-list bit when checking whether swap is full
In reply to Lian Wangadd_to_avail_list() clears SWAP_USAGE_OFFLIST_BIT with an atomic fetch-and. The returned value is the old count, including the bit. If a freed slot has already been allocated again, comparing that value directly with si->pages misses a full device.
Mask the state bit for the comparison. Keep the cmpxchg on the live counter so that a concurrent free can still make the device available. This also applies to the existing plist allocator.
--- mm/swapfile.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/swapfile.c +1 -1
@@ -1347,7 +1347,7 @@ static void add_to_avail_list(struct swap_info_struct *si)* that updater happen to be here, just skip adding. */ 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 ))
PATCH v5 11/19 mm/swap: add priority queue for swap device allocation
In reply to Lian WangFrom: Kairui Song <[email protected]>
Swap device selection rotates swap_avail_head with plist_requeue(), serializing cluster transitions on swap_avail_lock. Separate selection from device-local cluster allocation with same-priority device rings ordered from highest priority to lowest.
Keep membership and sizes stable under swapon_rwsem during each allocation walk. Full or disabled devices remain as masked pointers. Serialize tag writers with swap_queue_update_lock and use READ_ONCE() and WRITE_ONCE() for complete tagged-pointer accesses.
Each per-CPU reader holds one head per ring: a starting offset and a
base-page quota. A task-local cursor snapshots that offset so retries
visit every peer once even if another task advances the shared head.
Disable migration across the sleepable walk. Large folios retry same-priority peers before asking the caller to split instead of falling through after one fragmented
device.
Prepare reader storage with GFP_NOIO outside the topology writer, then recheck priority and required length before publication. Transfer the prepared storage only on successful installation; otherwise free it after unlocking. Keep per-CPU backing allocation outside the writer's noreclaim scope because it filters caller GFP flags. Constrain small queue/ring allocations with a scoped noreclaim context and __GFP_NOMEMALLOC, restoring context before cleanup. Deletion keeps reader storage until replacement or an empty queue, avoiding shrinking backing allocations beneath the writer.
These boundaries prevent queue updates from reclaiming into a swap allocation that would acquire a reader behind the same writer. The cluster metadata fallback also avoids direct reclaim while the walk retains its outer reader. These recursive paths were identified by source inspection rather than reproduced hangs.
Publish swap_file, the live reference, queue membership and SWP_WRITEOK under the same writer. Complete the disable flag and queue mask transition before releasing that writer, so a new allocation reader cannot select a device that is no longer writable.
Keep the old available plist in parallel while migrating its remaining consumers.
--- include/linux/swap.h | 3 +- mm/swapfile.c | 576 ++++++++++++++++++++++++++++++++++++++----- 2 files changed, 515 insertions(+), 64 deletions(-)
include/linux/swap.h +2 -1
@@ -196,7 +196,8 @@ struct swap_extent {* - 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_avail_lock. +* - 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
mm/swapfile.c +513 -63
705 lines not on this page · raw message
PATCH v5 12/19 mm/swap: remove available list
In reply to Lian WangFrom: Kairui Song <[email protected]>
The allocator now selects devices from the priority queue. Move the remaining block-cgroup throttle traversal from swap_avail_head to swap_active_head under swapon_rwsem. Check SWP_WRITEOK, the off-list state and the backing block device to retain priority-ordered target selection.
Remove swap_avail_head, swap_avail_lock, the per-device avail_list field and their maintenance now that no consumer needs the available plist. Queue masking and the embedded availability state remain serialized by swap_queue_update_lock.
--- include/linux/swap.h | 1 - mm/swapfile.c | 33 ++++++--------------------------- 2 files changed, 6 insertions(+), 28 deletions(-)
include/linux/swap.h +0 -1
@@ -289,7 +289,6 @@ struct swap_info_struct {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; };
mm/swapfile.c +6 -27
@@ -96,21 +96,6 @@ static const char Bad_offset[] = "Bad swap offset entry ";*/ static PLIST_HEAD (swap_active_head); -/* -* 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 swapon_rwsem 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 swapon_rwsem to be taken -* before any swap_info_struct->lock. -*/ -static PLIST_HEAD (swap_avail_head); -static DEFINE_SPINLOCK (swap_avail_lock); -static inline struct swap_info_struct *__swap_iter (int *i,unsigned long flag) {lockdep_assert_held (&swapon_rwsem);
@@ -1711,7 +1696,6 @@ 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);/*
@@ -1734,10 +1718,8 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff) }swap_queue_mask (si); -plist_del (&si->avail_list, &swap_avail_head); skip:spin_unlock (&swap_queue_update_lock); -spin_unlock (&swap_avail_lock); }/* SWAP_USAGE_OFFLIST_BIT can only be cleared by this helper. */
@@ -1746,7 +1728,6 @@ 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);/*
@@ -1777,10 +1758,8 @@ static void add_to_avail_list(struct swap_info_struct *si) }swap_queue_unmask (si); -plist_add (&si->avail_list, &swap_avail_head); skip:spin_unlock (&swap_queue_update_lock); -spin_unlock (&swap_avail_lock); }/*
@@ -3904,7 +3883,6 @@ 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 ;percpu_up_write (&swapon_rwsem);if (defer) {
@@ -4320,7 +4298,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)*/ si->prio = prio; si->list.prio = -si->prio; - si->avail_list.prio = -si->prio;/* * Publish swap_file before making the percpu ref live, then add the device
@@ -4471,14 +4448,16 @@ 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) { +percpu_down_read (&swapon_rwsem); +plist_for_each_entry (si, &swap_active_head, list) { +if ((si->flags &SWP_WRITEOK ) && + !(atomic_long_read (&si->inuse_pages) & +SWAP_USAGE_OFFLIST_BIT ) && si->bdev) {blkcg_schedule_throttle (si->bdev->bd_disk, true);break ; } } - spin_unlock(&swap_avail_lock); + percpu_up_read(&swapon_rwsem); }#endif
PATCH v5 13/19 mm/swap: bound synchronous discard outside the allocation reader
In reply to Lian WangFrom: Kairui Song <[email protected]>
The synchronous discard fallback drains a list that freeing paths can keep replenishing. Limit each foreground step to one cluster, retaining CLUSTER_FLAG_DISCARD while I/O is in flight and returning the cluster to the free list only after completion. The background worker continues to process the remaining list.
Keep synchronous discard outside the topology reader. Enter this fallback only after a complete normal order-0 allocation walk fails. A higher- priority device with only pending discard work does not force synchronous I/O if a lower-priority device satisfies that walk.
Find a writable discard-capable device under the reader and take its live reference, then release the reader before issuing I/O. Drop the reference after completion and restart allocation with a fresh cursor, so a concurrent topology change cannot leave stale ring state. This also sees discard work produced by the preceding reclaim scans.
Track the swap types already processed during this folio allocation and check each candidate at most once per fallback search. An empty check does not consume the I/O budget. Each swap type can complete at most one synchronous cluster discard, bounding successful retries by MAX_SWAPFILES even if membership changes. Do not keep discarding until this task wins a free cluster from a peer.
Large folios retain the existing same-priority retry and split boundary; their reader-held cluster walk does not issue synchronous discard. The budget bounds work count, not device I/O completion latency.
--- mm/swapfile.c | 175 ++++++++++++++++++++++++++++---------------------- 1 file changed, 100 insertions(+), 75 deletions(-)
mm/swapfile.c +100 -75
@@ -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>
@@ -583,6 +584,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/*
@@ -914,12 +935,8 @@ static int swap_cluster_alloc_table(struct swap_info_struct *si, lock:if (!locked) { -if (si) { -if (si->flags &SWP_SOLIDSTATE ) -local_lock (&si->percpu_cluster->lock); -else -spin_lock (&si->global_cluster->lock); - } +if (si) +swap_alloc_lock_device (si);spin_lock (&ci->lock); }lockdep_assert_held (&ci->lock);
@@ -1022,10 +1039,7 @@ swap_cluster_populate(struct swap_info_struct *si,* which could give allocator hooks and failure cleanup reserve access. */ spin_unlock (&ci->lock); -if (si->flags &SWP_SOLIDSTATE ) -local_unlock (&si->percpu_cluster->lock); -else -spin_unlock (&si->global_cluster->lock); +swap_alloc_unlock_device (si); gfp = (GFP_KERNEL | __GFP_HIGH | __GFP_NOMEMALLOC) & ~__GFP_DIRECT_RECLAIM;
@@ -1132,44 +1146,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, there could be percpu_cluster -* 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)
@@ -1178,7 +1188,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)
@@ -1607,15 +1618,11 @@ 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 ) { -/* Fast path using per CPU cluster */ -local_lock (&si->percpu_cluster->lock); +swap_alloc_lock_device (si); +if (si->flags &SWP_SOLIDSTATE ) offset =__this_cpu_read (si->percpu_cluster->next[order]); - }else { -/* Serialize HDD SWAP allocation for each device. */ -spin_lock (&si->global_cluster->lock); +else offset = si->global_cluster->next[order]; - }if (offset !=SWAP_ENTRY_INVALID ) { ci =swap_cluster_lock (si, offset);
@@ -1683,10 +1690,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, goto done; } done: -if (si->flags &SWP_SOLIDSTATE ) -local_unlock (&si->percpu_cluster->lock); -else -spin_unlock (&si->global_cluster->lock); +swap_alloc_unlock_device (si);return found; }
@@ -1881,33 +1885,50 @@ static int swap_alloc_entry(struct folio *folio) }/* -* 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; + DECLARE_BITMAP(checked, MAX_SWAPFILES) = {}; +struct swap_info_struct *si, *candidate; +unsigned int i, j; +bool done; +int type; -percpu_down_read (&swapon_rwsem); -start_over: -plist_for_each_entry_safe (si, next, &swap_active_head, list) { -percpu_up_read (&swapon_rwsem); -if (get_swap_device_info (si)) { -if (si->flags &SWP_PAGE_DISCARD ) - ret =swap_do_scheduled_discard (si); -put_swap_device (si); +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; -percpu_down_read (&swapon_rwsem); -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; } -percpu_up_read (&swapon_rwsem); - -return false; } static int swap_extend_table_alloc(struct swap_info_struct *si,
@@ -2211,12 +2232,16 @@ int folio_alloc_swap(struct folio *folio) } } -again: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. */
PATCH v5 14/19 mm/swap: drop swap active plist
In reply to Lian WangFrom: Kairui Song <[email protected]>
Remove swap_active_head and the associated plist_node. Device identity lookups can use the writable swap_info iterator without ordering.
Keep priority ordering for the block-cgroup swap throttle target by walking the priority queue under the topology reader. Choose the first unmasked, writable, non-offlist device with a backing block device. Check OFFLIST as well as the pointer tag because full transitions can temporarily leave an unmasked entry, and keep the explicit WRITEOK check. The disable transition already publishes its mask before releasing the topology writer.
This read-only lookup does not consume per-CPU allocation quotas or change retry cursors. It avoids making the throttle disk depend on swapon's swap-type assignment order when devices have different priorities.
--- include/linux/swap.h | 1 - mm/swapfile.c | 60 +++++++++++++++++++++++--------------------- 2 files changed, 32 insertions(+), 29 deletions(-)
include/linux/swap.h +0 -1
@@ -263,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 */
mm/swapfile.c +32 -28
115 lines not on this page · raw message
PATCH v5 15/19 lib/plist.c: remove requeue function
In reply to Lian WangFrom: Kairui Song <[email protected]>
Now the last user of plist requeue is gone, this function can be removed.
--- include/linux/plist.h | 2 -- lib/plist.c | 71 ------------------------------------------- 2 files changed, 73 deletions(-)
include/linux/plist.h +0 -2
@@ -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
lib/plist.c +0 -71
89 lines not on this page · raw message
PATCH v5 16/19 mm/swap: reuse per-CPU queue readers across priority changes
In reply to Lian WangInserting a new priority allocates a replacement per-CPU reader array even when earlier ring removal left enough storage. An unnecessary allocation can add swapon work or fail despite sufficient capacity.
Track the installed reader capacity and retain its high-water mark until the queue becomes empty. Reuse existing storage when the new ring fits, initializing every valid ring index for the new topology. Prepare larger storage outside the writer only when growth is required and recheck capacity under the writer before publishing.
Preserve the existing prepare/install ownership and failure rollback protocol. Device removal continues to avoid per-CPU shrinking allocation under the writer.
--- mm/swapfile.c | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-)
mm/swapfile.c +18 -10
@@ -201,6 +201,8 @@ struct swap_queue_cursor { };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) {
@@ -240,7 +242,7 @@ static bool swap_queue_needs_readers(int prio)return false; } -return true; +return swap_queue_len >= swap_queue_readers_capacity; }/*
@@ -288,13 +290,15 @@ static void swap_queue_reset_readers(void) } } -static void swap_queue_install_readers (struct swap_queue_reader __percpu *readers) +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 ;
@@ -430,7 +434,8 @@ static int swap_queue_add(struct swap_info_struct *si, }/* No ring at this priority: insert a new one at pos. */ -if (!*readers || nr_readers <= swap_queue_len) +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)
@@ -458,8 +463,12 @@ static int swap_queue_add(struct swap_info_struct *si,memalloc_noreclaim_restore (noreclaim_flag);kfree (old_queue); -swap_queue_install_readers (*readers); - *readers =NULL ; +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:
@@ -502,10 +511,9 @@ static void swap_queue_del(struct swap_info_struct *si) }/* -* Shrinking the small topology arrays is optional. Keep reader storage -* until a new priority is inserted or the queue is empty: per-CPU -* allocation must not run under this writer's noreclaim scope, which -* can grant backing pages reserve access. +* 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 ();
@@ -548,7 +556,7 @@ static void swap_queue_del(struct swap_info_struct *si) swap_queue =NULL ; }if (!swap_queue_len) -swap_queue_install_readers (NULL ); +swap_queue_install_readers (NULL ,0 ); }spin_unlock (&swap_queue_update_lock);
PATCH v5 17/19 mm/swap: advance the global queue cursor directly between priority rings
In reply to Lian WangThe allocation walk previously passed a total retry index to the selector. Each retry translated it back to a priority ring by scanning from the beginning of swap_queue. Keep the ring index and the number of attempted peers in the task-local cursor instead.
Snapshot the starting device only on the first visit to each ring and advance each peer exactly once, including masked entries. Preserve the large-folio same-ring boundary and the stale reader-offset correction. The selector's complete walk is linear in the devices and priority groups; device cluster scanning and availability updates have their own costs.
Keep the topology read lock and CPU migration protection across the walk. The global selector uses only existing priorities and adds no per-memcg device-selection state or ABI. Existing swap charging and limits remain in folio_alloc_swap(), whose failure path classifies allocation errors.
The walk no longer returns an ignored internal error to that caller.
--- mm/swapfile.c | 51 ++++++++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 27 deletions(-)
mm/swapfile.c +24 -27
@@ -194,10 +194,10 @@ struct swap_queue_reader { };struct swap_queue_cursor { -bool valid;bool no_fallback;/* Do not descend to a lower priority ring. */ unsigned int ring_idx;unsigned int offset; +unsigned int nr_iter; };static __percpu struct swap_queue_reader *swap_queue_readers;
@@ -307,37 +307,39 @@ static void swap_queue_install_readers(struct swap_queue_reader __percpu *readerswap_queue_reset_readers (); } -static struct swap_info_struct *swap_queue_get_device (long nr_alloc,int nr_iter, -struct swap_queue_cursor *cursor) +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_queue_reader_head *head;struct swap_prio_ring *ring; -unsigned int dev_idx, queue_idx; +unsigned int dev_idx, queue_idx, nr_iter; -if (!swap_queue_len) + queue_idx = cursor->ring_idx; +if (queue_idx >= swap_queue_len)return ERR_PTR (-ENOENT ); - queue_idx =0 ; -while (nr_iter >= swap_queue[queue_idx]->size) { - nr_iter -= swap_queue[queue_idx]->size; -if (++queue_idx >= swap_queue_len) -return ERR_PTR (cursor->no_fallback ? -E2BIG : -ENOENT ); - } -if (cursor->no_fallback && cursor->ring_idx != queue_idx) -return ERR_PTR (-E2BIG ); - ring = swap_queue[queue_idx]; +if (cursor->nr_iter >= ring->size) { +if (cursor->no_fallback) +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++;local_lock (&swap_queue_readers->lock); head =this_cpu_ptr (&swap_queue_readers->heads[queue_idx]);/* * Snapshot the starting offset for this walk. Other allocations on * this CPU can move the shared head between retries. */ -if (!cursor->valid || cursor->ring_idx != queue_idx) { - cursor->valid = true; - cursor->ring_idx = queue_idx; +if (!nr_iter) {if (head->rr_counter < nr_alloc) rotate = true;else if (head->offset >= ring->size)
@@ -1845,29 +1847,25 @@ static bool get_swap_device_info(struct swap_info_struct *si)return true; } -static int swap_alloc_entry (struct folio *folio) +static void swap_alloc_entry (struct folio *folio) {struct swap_queue_cursor cursor = {};long nr_pages =folio_nr_pages (folio);struct swap_info_struct *si; -int nr_iter, ret;percpu_down_read (&swapon_rwsem);migrate_disable (); -for (nr_iter =0 ;; nr_iter++) { - si =swap_queue_get_device (nr_pages, nr_iter, &cursor); +for (;;) { + si =swap_queue_get_device (nr_pages, &cursor);if (IS_ERR (si)) { - ret =PTR_ERR (si); -if (ret == -EBUSY ) +if (PTR_ERR (si) == -EBUSY )continue ;break ; }cluster_alloc_swap_entry (si, folio); -if (folio_test_swapcache (folio)) { - ret =0 ; +if (folio_test_swapcache (folio))break ; - }/* * For large allocations, try every device at the same priority,
@@ -1882,7 +1880,6 @@ static int swap_alloc_entry(struct folio *folio)migrate_enable ();percpu_up_read (&swapon_rwsem); -return ret; }/*
PATCH v5 18/19 mm/swap: skip reader rotation for single-device priority rings
In reply to Lian WangA priority ring with one device cannot benefit from rotating its starting offset or maintaining a quota. Read its only entry directly while the caller continues to hold the topology read lock and migration protection.
Consume the cursor attempt and check the full/disabled pointer tag through the common path. A masked singleton therefore terminates or falls through with the same bounded behavior as a multi-device ring. Keep the existing large-folio same-priority failure boundary.
This removes reader-local state updates for the common single-device case without bypassing device lifetime or availability checks.
--- mm/swapfile.c | 6 ++++++ 1 file changed, 6 insertions(+)
mm/swapfile.c +6 -0
@@ -333,6 +333,11 @@ swap_queue_get_device(long nr_alloc, struct swap_queue_cursor *cursor)/* 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); head =this_cpu_ptr (&swap_queue_readers->heads[queue_idx]);/*
@@ -361,6 +366,7 @@ swap_queue_get_device(long nr_alloc, struct swap_queue_cursor *cursor) si =READ_ONCE (ring->dev[dev_idx]);local_unlock (&swap_queue_readers->lock); +check_device:if (swap_device_masked (si))return ERR_PTR (-EBUSY );
PATCH v5 19/19 mm/swap: redistribute queue readers after membership changes
In reply to Lian WangAdding a device to an existing priority ring reuses the per-CPU reader storage. A ring that previously contained one device can therefore keep every CPU at the old common starting offset after peers are added. Deleting devices or rings can likewise leave offsets and quotas that describe the previous membership.
Reset the valid per-CPU ring offsets and quotas after peer insertion and every nonempty deletion. Run the initialization helper under the topology writer, which excludes allocation walks, without allocating new reader storage or adding selector hot-path work.
Use cpu-id modulo placement for a fresh best-effort rotation across all valid rings. This does not move existing slots or guarantee strict balance for every active CPU subset. Mask and availability transitions do not trigger the topology reset.
--- mm/swapfile.c | 3 +++ 1 file changed, 3 insertions(+)
mm/swapfile.c +3 -0
@@ -495,6 +495,7 @@ static int swap_queue_add(struct swap_info_struct *si,spin_unlock (&swap_queue_update_lock);memalloc_noreclaim_restore (noreclaim_flag);kfree (old_ring); +swap_queue_reset_readers ();return 0 ; failed:
@@ -567,6 +568,8 @@ static void swap_queue_del(struct swap_info_struct *si)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);