xref: /linux/mm/swapfile.c (revision 190936e7a5da594ffcc3bee75eabb586a3866443)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/swapfile.c
4  *
5  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
6  *  Swap reorganised 29.12.95, Stephen Tweedie
7  */
8 
9 #include <linux/blkdev.h>
10 #include <linux/mm.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/task.h>
13 #include <linux/hugetlb.h>
14 #include <linux/mman.h>
15 #include <linux/slab.h>
16 #include <linux/kernel_stat.h>
17 #include <linux/swap.h>
18 #include <linux/vmalloc.h>
19 #include <linux/pagemap.h>
20 #include <linux/namei.h>
21 #include <linux/shmem_fs.h>
22 #include <linux/blk-cgroup.h>
23 #include <linux/random.h>
24 #include <linux/writeback.h>
25 #include <linux/proc_fs.h>
26 #include <linux/seq_file.h>
27 #include <linux/init.h>
28 #include <linux/ksm.h>
29 #include <linux/rmap.h>
30 #include <linux/security.h>
31 #include <linux/backing-dev.h>
32 #include <linux/mutex.h>
33 #include <linux/capability.h>
34 #include <linux/syscalls.h>
35 #include <linux/memcontrol.h>
36 #include <linux/poll.h>
37 #include <linux/oom.h>
38 #include <linux/swapfile.h>
39 #include <linux/export.h>
40 #include <linux/sort.h>
41 #include <linux/completion.h>
42 #include <linux/suspend.h>
43 #include <linux/zswap.h>
44 #include <linux/plist.h>
45 
46 #include <asm/tlbflush.h>
47 #include <linux/leafops.h>
48 #include "swap_table.h"
49 #include "internal.h"
50 #include "swap.h"
51 
52 static void swap_range_alloc(struct swap_info_struct *si,
53 			     unsigned int nr_entries);
54 static bool folio_swapcache_freeable(struct folio *folio);
55 static void move_cluster(struct swap_info_struct *si,
56 			 struct swap_cluster_info *ci, struct list_head *list,
57 			 enum swap_cluster_flags new_flags);
58 
59 /*
60  * Protects the swap_info array, and the SWP_USED flag. swap_info contains
61  * lazily allocated & freed swap device info struts, and SWP_USED indicates
62  * which device is used, ~SWP_USED devices and can be reused.
63  *
64  * Also protects swap_active_head total_swap_pages, and the SWP_WRITEOK flag.
65  */
66 static DEFINE_SPINLOCK(swap_lock);
67 static unsigned int nr_swapfiles;
68 atomic_long_t nr_swap_pages;
69 /*
70  * Some modules use swappable objects and may try to swap them out under
71  * memory pressure (via the shrinker). Before doing so, they may wish to
72  * check to see if any swap space is available.
73  */
74 EXPORT_SYMBOL_GPL(nr_swap_pages);
75 /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
76 long total_swap_pages;
77 #define DEF_SWAP_PRIO  -1
78 unsigned long swapfile_maximum_size;
79 #ifdef CONFIG_MIGRATION
80 bool swap_migration_ad_supported;
81 #endif	/* CONFIG_MIGRATION */
82 
83 static const char Bad_file[] = "Bad swap file entry ";
84 static const char Bad_offset[] = "Bad swap offset entry ";
85 
86 /*
87  * all active swap_info_structs
88  * protected with swap_lock, and ordered by priority.
89  */
90 static PLIST_HEAD(swap_active_head);
91 
92 /*
93  * all available (active, not full) swap_info_structs
94  * protected with swap_avail_lock, ordered by priority.
95  * This is used by folio_alloc_swap() instead of swap_active_head
96  * because swap_active_head includes all swap_info_structs,
97  * but folio_alloc_swap() doesn't need to look at full ones.
98  * This uses its own lock instead of swap_lock because when a
99  * swap_info_struct changes between not-full/full, it needs to
100  * add/remove itself to/from this list, but the swap_info_struct->lock
101  * is held and the locking order requires swap_lock to be taken
102  * before any swap_info_struct->lock.
103  */
104 static PLIST_HEAD(swap_avail_head);
105 static DEFINE_SPINLOCK(swap_avail_lock);
106 
107 struct swap_info_struct *swap_info[MAX_SWAPFILES];
108 
109 static struct kmem_cache *swap_table_cachep;
110 
111 /* Protects si->swap_file for /proc/swaps usage */
112 static DEFINE_MUTEX(swapon_mutex);
113 
114 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
115 /* Activity counter to indicate that a swapon or swapoff has occurred */
116 static atomic_t proc_poll_event = ATOMIC_INIT(0);
117 
118 atomic_t nr_rotate_swap = ATOMIC_INIT(0);
119 
120 struct percpu_swap_cluster {
121 	struct swap_info_struct *si[SWAP_NR_ORDERS];
122 	unsigned long offset[SWAP_NR_ORDERS];
123 	local_lock_t lock;
124 };
125 
126 static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) = {
127 	.si = { NULL },
128 	.offset = { SWAP_ENTRY_INVALID },
129 	.lock = INIT_LOCAL_LOCK(),
130 };
131 
132 /* May return NULL on invalid type, caller must check for NULL return */
133 static struct swap_info_struct *swap_type_to_info(int type)
134 {
135 	if (type < 0 || type >= MAX_SWAPFILES)
136 		return NULL;
137 	return READ_ONCE(swap_info[type]); /* rcu_dereference() */
138 }
139 
140 /* May return NULL on invalid entry, caller must check for NULL return */
141 static struct swap_info_struct *swap_entry_to_info(swp_entry_t entry)
142 {
143 	return swap_type_to_info(swp_type(entry));
144 }
145 
146 /*
147  * Use the second highest bit of inuse_pages counter as the indicator
148  * if one swap device is on the available plist, so the atomic can
149  * still be updated arithmetically while having special data embedded.
150  *
151  * inuse_pages counter is the only thing indicating if a device should
152  * be on avail_lists or not (except swapon / swapoff). By embedding the
153  * off-list bit in the atomic counter, updates no longer need any lock
154  * to check the list status.
155  *
156  * This bit will be set if the device is not on the plist and not
157  * usable, will be cleared if the device is on the plist.
158  */
159 #define SWAP_USAGE_OFFLIST_BIT (1UL << (BITS_PER_TYPE(atomic_long_t) - 2))
160 #define SWAP_USAGE_COUNTER_MASK (~SWAP_USAGE_OFFLIST_BIT)
161 static long swap_usage_in_pages(struct swap_info_struct *si)
162 {
163 	return atomic_long_read(&si->inuse_pages) & SWAP_USAGE_COUNTER_MASK;
164 }
165 
166 /* Reclaim the swap entry anyway if possible */
167 #define TTRS_ANYWAY		0x1
168 /*
169  * Reclaim the swap entry if there are no more mappings of the
170  * corresponding page
171  */
172 #define TTRS_UNMAPPED		0x2
173 /* Reclaim the swap entry if swap is getting full */
174 #define TTRS_FULL		0x4
175 
176 static bool swap_only_has_cache(struct swap_cluster_info *ci,
177 				unsigned long offset, int nr_pages)
178 {
179 	unsigned int ci_off = offset % SWAPFILE_CLUSTER;
180 	unsigned int ci_end = ci_off + nr_pages;
181 	unsigned long swp_tb;
182 
183 	do {
184 		swp_tb = __swap_table_get(ci, ci_off);
185 		VM_WARN_ON_ONCE(!swp_tb_is_folio(swp_tb));
186 		if (swp_tb_get_count(swp_tb))
187 			return false;
188 	} while (++ci_off < ci_end);
189 
190 	return true;
191 }
192 
193 /*
194  * returns number of pages in the folio that backs the swap entry. If positive,
195  * the folio was reclaimed. If negative, the folio was not reclaimed. If 0, no
196  * folio was associated with the swap entry.
197  */
198 static int __try_to_reclaim_swap(struct swap_info_struct *si,
199 				 unsigned long offset, unsigned long flags)
200 {
201 	const swp_entry_t entry = swp_entry(si->type, offset);
202 	struct swap_cluster_info *ci;
203 	struct folio *folio;
204 	int ret, nr_pages;
205 	bool need_reclaim;
206 
207 again:
208 	folio = swap_cache_get_folio(entry);
209 	if (!folio)
210 		return 0;
211 
212 	nr_pages = folio_nr_pages(folio);
213 	ret = -nr_pages;
214 
215 	/*
216 	 * We hold a folio lock here. We have to use trylock for
217 	 * avoiding deadlock. This is a special case and you should
218 	 * use folio_free_swap() with explicit folio_lock() in usual
219 	 * operations.
220 	 */
221 	if (!folio_trylock(folio))
222 		goto out;
223 
224 	/*
225 	 * Offset could point to the middle of a large folio, or folio
226 	 * may no longer point to the expected offset before it's locked.
227 	 */
228 	if (!folio_matches_swap_entry(folio, entry)) {
229 		folio_unlock(folio);
230 		folio_put(folio);
231 		goto again;
232 	}
233 	offset = swp_offset(folio->swap);
234 
235 	need_reclaim = ((flags & TTRS_ANYWAY) ||
236 			((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) ||
237 			((flags & TTRS_FULL) && mem_cgroup_swap_full(folio)));
238 	if (!need_reclaim || !folio_swapcache_freeable(folio))
239 		goto out_unlock;
240 
241 	/*
242 	 * It's safe to delete the folio from swap cache only if the folio
243 	 * is in swap cache with swap count == 0. The slots have no page table
244 	 * reference or pending writeback, and can't be allocated to others.
245 	 */
246 	ci = swap_cluster_lock(si, offset);
247 	need_reclaim = swap_only_has_cache(ci, offset, nr_pages);
248 	swap_cluster_unlock(ci);
249 	if (!need_reclaim)
250 		goto out_unlock;
251 
252 	swap_cache_del_folio(folio);
253 	folio_set_dirty(folio);
254 	ret = nr_pages;
255 out_unlock:
256 	folio_unlock(folio);
257 out:
258 	folio_put(folio);
259 	return ret;
260 }
261 
262 static inline struct swap_extent *first_se(struct swap_info_struct *sis)
263 {
264 	struct rb_node *rb = rb_first(&sis->swap_extent_root);
265 	return rb_entry(rb, struct swap_extent, rb_node);
266 }
267 
268 static inline struct swap_extent *next_se(struct swap_extent *se)
269 {
270 	struct rb_node *rb = rb_next(&se->rb_node);
271 	return rb ? rb_entry(rb, struct swap_extent, rb_node) : NULL;
272 }
273 
274 /*
275  * swapon tell device that all the old swap contents can be discarded,
276  * to allow the swap device to optimize its wear-levelling.
277  */
278 static int discard_swap(struct swap_info_struct *si)
279 {
280 	struct swap_extent *se;
281 	sector_t start_block;
282 	sector_t nr_blocks;
283 	int err = 0;
284 
285 	/* Do not discard the swap header page! */
286 	se = first_se(si);
287 	start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
288 	nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
289 	if (nr_blocks) {
290 		err = blkdev_issue_discard(si->bdev, start_block,
291 				nr_blocks, GFP_KERNEL);
292 		if (err)
293 			return err;
294 		cond_resched();
295 	}
296 
297 	for (se = next_se(se); se; se = next_se(se)) {
298 		start_block = se->start_block << (PAGE_SHIFT - 9);
299 		nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
300 
301 		err = blkdev_issue_discard(si->bdev, start_block,
302 				nr_blocks, GFP_KERNEL);
303 		if (err)
304 			break;
305 
306 		cond_resched();
307 	}
308 	return err;		/* That will often be -EOPNOTSUPP */
309 }
310 
311 static struct swap_extent *
312 offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
313 {
314 	struct swap_extent *se;
315 	struct rb_node *rb;
316 
317 	rb = sis->swap_extent_root.rb_node;
318 	while (rb) {
319 		se = rb_entry(rb, struct swap_extent, rb_node);
320 		if (offset < se->start_page)
321 			rb = rb->rb_left;
322 		else if (offset >= se->start_page + se->nr_pages)
323 			rb = rb->rb_right;
324 		else
325 			return se;
326 	}
327 	/* It *must* be present */
328 	BUG();
329 }
330 
331 sector_t swap_folio_sector(struct folio *folio)
332 {
333 	struct swap_info_struct *sis = __swap_entry_to_info(folio->swap);
334 	struct swap_extent *se;
335 	sector_t sector;
336 	pgoff_t offset;
337 
338 	offset = swp_offset(folio->swap);
339 	se = offset_to_swap_extent(sis, offset);
340 	sector = se->start_block + (offset - se->start_page);
341 	return sector << (PAGE_SHIFT - 9);
342 }
343 
344 /*
345  * swap allocation tell device that a cluster of swap can now be discarded,
346  * to allow the swap device to optimize its wear-levelling.
347  */
348 static void discard_swap_cluster(struct swap_info_struct *si,
349 				 pgoff_t start_page, pgoff_t nr_pages)
350 {
351 	struct swap_extent *se = offset_to_swap_extent(si, start_page);
352 
353 	while (nr_pages) {
354 		pgoff_t offset = start_page - se->start_page;
355 		sector_t start_block = se->start_block + offset;
356 		sector_t nr_blocks = se->nr_pages - offset;
357 
358 		if (nr_blocks > nr_pages)
359 			nr_blocks = nr_pages;
360 		start_page += nr_blocks;
361 		nr_pages -= nr_blocks;
362 
363 		start_block <<= PAGE_SHIFT - 9;
364 		nr_blocks <<= PAGE_SHIFT - 9;
365 		if (blkdev_issue_discard(si->bdev, start_block,
366 					nr_blocks, GFP_NOIO))
367 			break;
368 
369 		se = next_se(se);
370 	}
371 }
372 
373 static inline bool cluster_is_empty(struct swap_cluster_info *info)
374 {
375 	return info->count == 0;
376 }
377 
378 static inline bool cluster_is_discard(struct swap_cluster_info *info)
379 {
380 	return info->flags == CLUSTER_FLAG_DISCARD;
381 }
382 
383 static inline bool cluster_table_is_alloced(struct swap_cluster_info *ci)
384 {
385 	return rcu_dereference_protected(ci->table, lockdep_is_held(&ci->lock));
386 }
387 
388 static inline bool cluster_is_usable(struct swap_cluster_info *ci, int order)
389 {
390 	if (unlikely(ci->flags > CLUSTER_FLAG_USABLE))
391 		return false;
392 	if (!cluster_table_is_alloced(ci))
393 		return false;
394 	if (!order)
395 		return true;
396 	return cluster_is_empty(ci) || order == ci->order;
397 }
398 
399 static inline unsigned int cluster_index(struct swap_info_struct *si,
400 					 struct swap_cluster_info *ci)
401 {
402 	return ci - si->cluster_info;
403 }
404 
405 static inline unsigned int cluster_offset(struct swap_info_struct *si,
406 					  struct swap_cluster_info *ci)
407 {
408 	return cluster_index(si, ci) * SWAPFILE_CLUSTER;
409 }
410 
411 static void swap_cluster_free_table_folio_rcu_cb(struct rcu_head *head)
412 {
413 	struct folio *folio;
414 
415 	folio = page_folio(container_of(head, struct page, rcu_head));
416 	folio_put(folio);
417 }
418 
419 static void swap_cluster_free_count_table(struct swap_table *table)
420 {
421 	if (!SWP_TABLE_USE_PAGE) {
422 		kmem_cache_free(swap_table_cachep, table);
423 		return;
424 	}
425 
426 	call_rcu(&(folio_page(virt_to_folio(table), 0)->rcu_head),
427 		 swap_cluster_free_table_folio_rcu_cb);
428 }
429 
430 static void swap_cluster_free_table(struct swap_cluster_info *ci)
431 {
432 	struct swap_table *table;
433 
434 #ifdef CONFIG_MEMCG
435 	kfree(ci->memcg_table);
436 	ci->memcg_table = NULL;
437 #endif
438 
439 #if !SWAP_TABLE_HAS_ZEROFLAG
440 	kfree(ci->zero_bitmap);
441 	ci->zero_bitmap = NULL;
442 #endif
443 
444 	table = (struct swap_table *)rcu_access_pointer(ci->table);
445 	if (!table)
446 		return;
447 
448 	rcu_assign_pointer(ci->table, NULL);
449 	swap_cluster_free_count_table(table);
450 }
451 
452 /*
453  * Return with ci locked. An unlocked allocator also needs si's outer locks;
454  * initial bad-slot setup passes NULL because the device is not published.
455  */
456 static int swap_cluster_alloc_table(struct swap_info_struct *si,
457 				    struct swap_cluster_info *ci,
458 				    gfp_t gfp, bool locked)
459 {
460 	struct swap_table *table = NULL;
461 #ifdef CONFIG_MEMCG
462 	struct swap_memcg_table *memcg_table = NULL;
463 #endif
464 #if !SWAP_TABLE_HAS_ZEROFLAG
465 	unsigned long *zero_bitmap = NULL;
466 #endif
467 	struct folio *folio;
468 	int ret = -ENOMEM;
469 
470 	if (SWP_TABLE_USE_PAGE) {
471 		folio = folio_alloc(gfp | __GFP_ZERO, 0);
472 		if (folio)
473 			table = folio_address(folio);
474 	} else {
475 		table = kmem_cache_zalloc(swap_table_cachep, gfp);
476 	}
477 	if (!table)
478 		goto lock;
479 
480 #ifdef CONFIG_MEMCG
481 	if (!mem_cgroup_disabled()) {
482 		memcg_table = kzalloc_obj(*ci->memcg_table, gfp);
483 		if (!memcg_table)
484 			goto lock;
485 	}
486 #endif
487 
488 #if !SWAP_TABLE_HAS_ZEROFLAG
489 	zero_bitmap = bitmap_zalloc(SWAPFILE_CLUSTER, gfp);
490 	if (!zero_bitmap)
491 		goto lock;
492 #endif
493 	ret = 0;
494 
495 lock:
496 	if (!locked) {
497 		if (si) {
498 			local_lock(&percpu_swap_cluster.lock);
499 			if (!(si->flags & SWP_SOLIDSTATE))
500 				spin_lock(&si->global_cluster_lock);
501 		}
502 		spin_lock(&ci->lock);
503 	}
504 	lockdep_assert_held(&ci->lock);
505 
506 	/* A stale reclaimer may have returned the cluster to the free list. */
507 	if (ci->flags != CLUSTER_FLAG_NONE || cluster_table_is_alloced(ci))
508 		ret = -EAGAIN;
509 	if (ret)
510 		goto free;
511 
512 	/* The cluster must be empty and not on any list during allocation. */
513 	VM_WARN_ON_ONCE(!cluster_is_empty(ci));
514 #ifdef CONFIG_MEMCG
515 	VM_WARN_ON_ONCE(ci->memcg_table);
516 	ci->memcg_table = memcg_table;
517 #endif
518 #if !SWAP_TABLE_HAS_ZEROFLAG
519 	VM_WARN_ON_ONCE(ci->zero_bitmap);
520 	ci->zero_bitmap = zero_bitmap;
521 #endif
522 
523 	/*
524 	 * Make tables visible to cluster_is_usable() after everything is
525 	 * ready.
526 	 */
527 	rcu_assign_pointer(ci->table, table);
528 	return 0;
529 
530 free:
531 #ifdef CONFIG_MEMCG
532 	kfree(memcg_table);
533 #endif
534 #if !SWAP_TABLE_HAS_ZEROFLAG
535 	bitmap_free(zero_bitmap);
536 #endif
537 	if (table)
538 		swap_cluster_free_count_table(table);
539 	return ret;
540 }
541 
542 /*
543  * Sanity check to ensure nothing leaked, and the specified range is empty.
544  * One special case is that bad slots can't be freed, so check the number of
545  * bad slots for swapoff, and non-swapoff path must never free bad slots.
546  */
547 static void swap_cluster_assert_empty(struct swap_cluster_info *ci,
548 				      unsigned int ci_off, unsigned int nr,
549 				      bool swapoff)
550 {
551 	unsigned int ci_end = ci_off + nr;
552 	unsigned long swp_tb;
553 	int bad_slots = 0;
554 
555 	if (!IS_ENABLED(CONFIG_DEBUG_VM) && !swapoff)
556 		return;
557 
558 	do {
559 		swp_tb = __swap_table_get(ci, ci_off);
560 		if (swp_tb_is_bad(swp_tb))
561 			bad_slots++;
562 		else
563 			WARN_ON_ONCE(!swp_tb_is_null(swp_tb));
564 		WARN_ON_ONCE(__swap_cgroup_get(ci, ci_off));
565 	} while (++ci_off < ci_end);
566 
567 	WARN_ON_ONCE(bad_slots != (swapoff ? ci->count : 0));
568 	WARN_ON_ONCE(nr == SWAPFILE_CLUSTER && ci->extend_table);
569 }
570 
571 /*
572  * Allocate swap table for one cluster. Attempt an atomic allocation first,
573  * then fallback to sleeping allocation.
574  */
575 static struct swap_cluster_info *
576 swap_cluster_populate(struct swap_info_struct *si,
577 			 struct swap_cluster_info *ci)
578 {
579 	int ret;
580 
581 	/*
582 	 * Only cluster isolation from the allocator does table allocation.
583 	 * Swap allocator uses percpu clusters and holds the local lock.
584 	 */
585 	lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock);
586 	if (!(si->flags & SWP_SOLIDSTATE))
587 		lockdep_assert_held(&si->global_cluster_lock);
588 	lockdep_assert_held(&ci->lock);
589 
590 	if (!swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
591 					      __GFP_NOWARN, true))
592 		return ci;
593 
594 	/*
595 	 * Try a sleep allocation. Each isolated free cluster may cause
596 	 * a sleep allocation, but there is a limited number of them, so
597 	 * the potential recursive allocation is limited.
598 	 */
599 	spin_unlock(&ci->lock);
600 	if (!(si->flags & SWP_SOLIDSTATE))
601 		spin_unlock(&si->global_cluster_lock);
602 	local_unlock(&percpu_swap_cluster.lock);
603 
604 	ret = swap_cluster_alloc_table(si, ci, __GFP_HIGH | __GFP_NOMEMALLOC |
605 					     GFP_KERNEL, false);
606 
607 	/*
608 	 * Back to atomic context. We might have migrated to a new CPU with a
609 	 * usable percpu cluster. But just keep using the isolated cluster to
610 	 * make things easier. Migration indicates a slight change of workload
611 	 * so using a new free cluster might not be a bad idea, and the worst
612 	 * could happen with ignoring the percpu cluster is fragmentation,
613 	 * which is acceptable since this fallback and race is rare.
614 	 */
615 	if (ret) {
616 		if (ret != -EAGAIN)
617 			move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
618 		spin_unlock(&ci->lock);
619 		return NULL;
620 	}
621 	return ci;
622 }
623 
624 static void move_cluster(struct swap_info_struct *si,
625 			 struct swap_cluster_info *ci, struct list_head *list,
626 			 enum swap_cluster_flags new_flags)
627 {
628 	VM_WARN_ON(ci->flags == new_flags);
629 
630 	BUILD_BUG_ON(1 << sizeof(ci->flags) * BITS_PER_BYTE < CLUSTER_FLAG_MAX);
631 	lockdep_assert_held(&ci->lock);
632 
633 	spin_lock(&si->lock);
634 	if (ci->flags == CLUSTER_FLAG_NONE)
635 		list_add_tail(&ci->list, list);
636 	else
637 		list_move_tail(&ci->list, list);
638 	spin_unlock(&si->lock);
639 	ci->flags = new_flags;
640 }
641 
642 /* Add a cluster to discard list and schedule it to do discard */
643 static void swap_cluster_schedule_discard(struct swap_info_struct *si,
644 		struct swap_cluster_info *ci)
645 {
646 	VM_BUG_ON(ci->flags == CLUSTER_FLAG_FREE);
647 	move_cluster(si, ci, &si->discard_clusters, CLUSTER_FLAG_DISCARD);
648 	schedule_work(&si->discard_work);
649 }
650 
651 static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci)
652 {
653 	swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, false);
654 	swap_cluster_free_table(ci);
655 	move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
656 	ci->order = 0;
657 }
658 
659 /*
660  * Isolate and lock the first cluster that is not contented on a list,
661  * clean its flag before taken off-list. Cluster flag must be in sync
662  * with list status, so cluster updaters can always know the cluster
663  * list status without touching si lock.
664  *
665  * Note it's possible that all clusters on a list are contented so
666  * this returns NULL for an non-empty list.
667  */
668 static struct swap_cluster_info *isolate_lock_cluster(
669 		struct swap_info_struct *si, struct list_head *list)
670 {
671 	struct swap_cluster_info *ci, *found = NULL;
672 	u8 flags = CLUSTER_FLAG_NONE;
673 
674 	spin_lock(&si->lock);
675 
676 	if (unlikely(!(si->flags & SWP_WRITEOK)))
677 		goto out;
678 
679 	list_for_each_entry(ci, list, list) {
680 		if (!spin_trylock(&ci->lock))
681 			continue;
682 
683 		/* We may only isolate and clear flags of following lists */
684 		VM_BUG_ON(!ci->flags);
685 		VM_BUG_ON(ci->flags > CLUSTER_FLAG_USABLE &&
686 			  ci->flags != CLUSTER_FLAG_FULL);
687 
688 		list_del(&ci->list);
689 		flags = ci->flags;
690 		ci->flags = CLUSTER_FLAG_NONE;
691 		found = ci;
692 		break;
693 	}
694 out:
695 	spin_unlock(&si->lock);
696 
697 	/* Cluster's table is freed when and only when it's on the free list. */
698 	if (found && flags == CLUSTER_FLAG_FREE) {
699 		VM_WARN_ON_ONCE(list != &si->free_clusters);
700 		VM_WARN_ON_ONCE(cluster_table_is_alloced(found));
701 		return swap_cluster_populate(si, found);
702 	}
703 
704 	return found;
705 }
706 
707 /*
708  * Doing discard actually. After a cluster discard is finished, the cluster
709  * will be added to free cluster list. Discard cluster is a bit special as
710  * they don't participate in allocation or reclaim, so clusters marked as
711  * CLUSTER_FLAG_DISCARD must remain off-list or on discard list.
712  */
713 static bool swap_do_scheduled_discard(struct swap_info_struct *si)
714 {
715 	struct swap_cluster_info *ci;
716 	bool ret = false;
717 	unsigned int idx;
718 
719 	spin_lock(&si->lock);
720 	while (!list_empty(&si->discard_clusters)) {
721 		ci = list_first_entry(&si->discard_clusters, struct swap_cluster_info, list);
722 		/*
723 		 * Delete the cluster from list to prepare for discard, but keep
724 		 * the CLUSTER_FLAG_DISCARD flag, percpu_swap_cluster could be
725 		 * pointing to it, or ran into by relocate_cluster.
726 		 */
727 		list_del(&ci->list);
728 		idx = cluster_index(si, ci);
729 		spin_unlock(&si->lock);
730 		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
731 				SWAPFILE_CLUSTER);
732 
733 		spin_lock(&ci->lock);
734 		/*
735 		 * Discard is done, clear its flags as it's off-list, then
736 		 * return the cluster to allocation list.
737 		 */
738 		ci->flags = CLUSTER_FLAG_NONE;
739 		__free_cluster(si, ci);
740 		spin_unlock(&ci->lock);
741 		ret = true;
742 		spin_lock(&si->lock);
743 	}
744 	spin_unlock(&si->lock);
745 	return ret;
746 }
747 
748 static void swap_discard_work(struct work_struct *work)
749 {
750 	struct swap_info_struct *si;
751 
752 	si = container_of(work, struct swap_info_struct, discard_work);
753 
754 	swap_do_scheduled_discard(si);
755 }
756 
757 static void swap_users_ref_free(struct percpu_ref *ref)
758 {
759 	struct swap_info_struct *si;
760 
761 	si = container_of(ref, struct swap_info_struct, users);
762 	complete(&si->comp);
763 }
764 
765 /*
766  * Must be called after freeing if ci->count == 0, moves the cluster to free
767  * or discard list.
768  */
769 static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci)
770 {
771 	VM_BUG_ON(ci->count != 0);
772 	VM_BUG_ON(ci->flags == CLUSTER_FLAG_FREE);
773 	lockdep_assert_held(&ci->lock);
774 
775 	/*
776 	 * If the swap is discardable, prepare discard the cluster
777 	 * instead of free it immediately. The cluster will be freed
778 	 * after discard.
779 	 */
780 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
781 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
782 		swap_cluster_schedule_discard(si, ci);
783 		return;
784 	}
785 
786 	__free_cluster(si, ci);
787 }
788 
789 /*
790  * Must be called after freeing if ci->count != 0, moves the cluster to
791  * nonfull list.
792  */
793 static void partial_free_cluster(struct swap_info_struct *si,
794 				 struct swap_cluster_info *ci)
795 {
796 	VM_BUG_ON(!ci->count || ci->count == SWAPFILE_CLUSTER);
797 	lockdep_assert_held(&ci->lock);
798 
799 	if (ci->flags != CLUSTER_FLAG_NONFULL)
800 		move_cluster(si, ci, &si->nonfull_clusters[ci->order],
801 			     CLUSTER_FLAG_NONFULL);
802 }
803 
804 /*
805  * Must be called after allocation, moves the cluster to full or frag list.
806  * Note: allocation doesn't acquire si lock, and may drop the ci lock for
807  * reclaim, so the cluster could be any where when called.
808  */
809 static void relocate_cluster(struct swap_info_struct *si,
810 			     struct swap_cluster_info *ci)
811 {
812 	lockdep_assert_held(&ci->lock);
813 
814 	/* Discard cluster must remain off-list or on discard list */
815 	if (cluster_is_discard(ci))
816 		return;
817 
818 	/*
819 	 * An allocator may still be preparing the table.
820 	 * Leave the cluster to it.
821 	 */
822 	if (!cluster_table_is_alloced(ci))
823 		return;
824 
825 	if (!ci->count) {
826 		if (ci->flags != CLUSTER_FLAG_FREE)
827 			free_cluster(si, ci);
828 	} else if (ci->count != SWAPFILE_CLUSTER) {
829 		if (ci->flags != CLUSTER_FLAG_FRAG)
830 			move_cluster(si, ci, &si->frag_clusters[ci->order],
831 				     CLUSTER_FLAG_FRAG);
832 	} else {
833 		if (ci->flags != CLUSTER_FLAG_FULL)
834 			move_cluster(si, ci, &si->full_clusters,
835 				     CLUSTER_FLAG_FULL);
836 	}
837 }
838 
839 /*
840  * The cluster corresponding to @offset will be accounted as having one bad
841  * slot. The cluster will not be added to the free cluster list, and its
842  * usage counter will be increased by 1. Only used for initialization.
843  */
844 static int swap_cluster_setup_bad_slot(struct swap_info_struct *si,
845 				       struct swap_cluster_info *cluster_info,
846 				       unsigned int offset, bool mask)
847 {
848 	unsigned int ci_off = offset % SWAPFILE_CLUSTER;
849 	unsigned long idx = offset / SWAPFILE_CLUSTER;
850 	struct swap_cluster_info *ci;
851 	int ret = 0;
852 
853 	/* si->max may got shrunk by swap swap_activate() */
854 	if (offset >= si->max && !mask) {
855 		pr_debug("Ignoring bad slot %u (max: %u)\n", offset, si->max);
856 		return 0;
857 	}
858 	/*
859 	 * Account it, skip header slot: si->pages is initiated as
860 	 * si->max - 1. Also skip the masking of last cluster,
861 	 * si->pages doesn't include that part.
862 	 */
863 	if (offset && !mask)
864 		si->pages -= 1;
865 	if (!si->pages) {
866 		pr_warn("Empty swap-file\n");
867 		return -EINVAL;
868 	}
869 
870 	ci = cluster_info + idx;
871 	/* Need to allocate swap table first for initial bad slot marking. */
872 	if (!ci->count) {
873 		ret = swap_cluster_alloc_table(NULL, ci, GFP_KERNEL, false);
874 		if (ret)
875 			goto out;
876 	} else {
877 		spin_lock(&ci->lock);
878 	}
879 	/* Check for duplicated bad swap slots. */
880 	if (__swap_table_xchg(ci, ci_off, SWP_TB_BAD) != SWP_TB_NULL) {
881 		pr_warn("Duplicated bad slot offset %d\n", offset);
882 		ret = -EINVAL;
883 	} else {
884 		ci->count++;
885 	}
886 out:
887 	spin_unlock(&ci->lock);
888 
889 	WARN_ON(ci->count > SWAPFILE_CLUSTER);
890 	WARN_ON(ci->flags);
891 
892 	return ret;
893 }
894 
895 /*
896  * Reclaim drops the ci lock, so the cluster may become unusable (freed or
897  * stolen by a lower order). @usable will be set to false if that happens.
898  */
899 static bool cluster_reclaim_range(struct swap_info_struct *si,
900 				  struct swap_cluster_info *ci,
901 				  unsigned long start, unsigned int order,
902 				  bool *usable)
903 {
904 	unsigned int nr_pages = 1 << order;
905 	unsigned long offset = start, end = start + nr_pages;
906 	unsigned long swp_tb;
907 
908 	spin_unlock(&ci->lock);
909 	do {
910 		swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
911 		if (swp_tb_get_count(swp_tb))
912 			break;
913 		if (swp_tb_is_folio(swp_tb))
914 			if (__try_to_reclaim_swap(si, offset, TTRS_ANYWAY) < 0)
915 				break;
916 	} while (++offset < end);
917 	spin_lock(&ci->lock);
918 
919 	/*
920 	 * We just dropped ci->lock so cluster could be used by another
921 	 * order or got freed, check if it's still usable or empty.
922 	 */
923 	if (!cluster_is_usable(ci, order)) {
924 		*usable = false;
925 		return false;
926 	}
927 	*usable = true;
928 
929 	/* Fast path, no need to scan if the whole cluster is empty */
930 	if (cluster_is_empty(ci))
931 		return true;
932 
933 	/*
934 	 * Recheck the range no matter reclaim succeeded or not, the slot
935 	 * could have been be freed while we are not holding the lock.
936 	 */
937 	for (offset = start; offset < end; offset++) {
938 		swp_tb = __swap_table_get(ci, offset % SWAPFILE_CLUSTER);
939 		if (!swp_tb_is_null(swp_tb))
940 			return false;
941 	}
942 
943 	return true;
944 }
945 
946 static bool cluster_scan_range(struct swap_info_struct *si,
947 			       struct swap_cluster_info *ci,
948 			       unsigned long offset, unsigned int nr_pages,
949 			       bool *need_reclaim)
950 {
951 	unsigned int ci_off = offset % SWAPFILE_CLUSTER;
952 	unsigned int ci_end = ci_off + nr_pages;
953 	unsigned long swp_tb;
954 
955 	do {
956 		swp_tb = __swap_table_get(ci, ci_off);
957 		if (swp_tb_is_null(swp_tb))
958 			continue;
959 		if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb)) {
960 			if (!vm_swap_full())
961 				return false;
962 			*need_reclaim = true;
963 			continue;
964 		}
965 		/* Slot with zero count can only be NULL or folio */
966 		VM_WARN_ON(!swp_tb_get_count(swp_tb));
967 		return false;
968 	} while (++ci_off < ci_end);
969 
970 	return true;
971 }
972 
973 static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
974 					 struct swap_cluster_info *ci,
975 					 struct folio *folio,
976 					 unsigned int ci_off)
977 {
978 	unsigned int order;
979 	unsigned long nr_pages;
980 
981 	lockdep_assert_held(&ci->lock);
982 
983 	if (!(si->flags & SWP_WRITEOK))
984 		return false;
985 
986 	/*
987 	 * All mm swap allocation starts with a folio (folio_alloc_swap),
988 	 * it's also the only allocation path for large orders allocation.
989 	 * Such swap slots starts with count == 0 and will be increased
990 	 * upon folio unmap.
991 	 *
992 	 * Else, it's a exclusive order 0 allocation for hibernation.
993 	 * The slot starts with count == 1 and never increases.
994 	 */
995 	if (likely(folio)) {
996 		order = folio_order(folio);
997 		nr_pages = 1 << order;
998 		swap_cluster_assert_empty(ci, ci_off, nr_pages, false);
999 		__swap_cache_add_folio(ci, folio, swp_entry(si->type,
1000 							    ci_off + cluster_offset(si, ci)));
1001 	} else if (IS_ENABLED(CONFIG_HIBERNATION)) {
1002 		order = 0;
1003 		nr_pages = 1;
1004 		swap_cluster_assert_empty(ci, ci_off, 1, false);
1005 		/* Fake shadow placeholder with no flag, hibernation does not use the zeromap */
1006 		__swap_table_set(ci, ci_off, __swp_tb_mk_count(shadow_to_swp_tb(NULL, 0), 1));
1007 	} else {
1008 		/* Allocation without folio is only possible with hibernation */
1009 		WARN_ON_ONCE(1);
1010 		return false;
1011 	}
1012 
1013 	/*
1014 	 * The first allocation in a cluster makes the
1015 	 * cluster exclusive to this order
1016 	 */
1017 	if (cluster_is_empty(ci))
1018 		ci->order = order;
1019 	ci->count += nr_pages;
1020 	swap_range_alloc(si, nr_pages);
1021 
1022 	return true;
1023 }
1024 
1025 /*
1026  * Prefer a new cluster over a nonfull one if the device needs discard, to
1027  * spread out the writes, or if it is not synchronous, to keep the slots
1028  * of a swapout batch contiguous so that its writes can be merged.
1029  */
1030 static bool swap_prefer_free_cluster(struct swap_info_struct *si)
1031 {
1032 	return (si->flags & SWP_PAGE_DISCARD) ||
1033 	       !(si->flags & SWP_SYNCHRONOUS_IO);
1034 }
1035 
1036 /* Try use a new cluster for current CPU and allocate from it. */
1037 static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
1038 					    struct swap_cluster_info *ci,
1039 					    struct folio *folio, unsigned long offset)
1040 {
1041 	unsigned int next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
1042 	unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);
1043 	unsigned int order = likely(folio) ? folio_order(folio) : 0;
1044 	unsigned long end = start + SWAPFILE_CLUSTER;
1045 	unsigned int nr_pages = 1 << order;
1046 	bool need_reclaim, ret, usable;
1047 
1048 	lockdep_assert_held(&ci->lock);
1049 	VM_WARN_ON(!cluster_is_usable(ci, order));
1050 
1051 	if (end < nr_pages || ci->count + nr_pages > SWAPFILE_CLUSTER)
1052 		goto out;
1053 
1054 	for (end -= nr_pages; offset <= end; offset += nr_pages) {
1055 		need_reclaim = false;
1056 		if (!cluster_scan_range(si, ci, offset, nr_pages, &need_reclaim))
1057 			continue;
1058 		if (need_reclaim) {
1059 			ret = cluster_reclaim_range(si, ci, offset, order, &usable);
1060 			if (!usable)
1061 				goto out;
1062 			if (cluster_is_empty(ci))
1063 				offset = start;
1064 			/* Reclaim failed but cluster is usable, try next */
1065 			if (!ret)
1066 				continue;
1067 		}
1068 		if (!__swap_cluster_alloc_entries(si, ci, folio, offset % SWAPFILE_CLUSTER))
1069 			break;
1070 		found = offset;
1071 		offset += nr_pages;
1072 		if (ci->count < SWAPFILE_CLUSTER && offset <= end)
1073 			next = offset;
1074 		break;
1075 	}
1076 out:
1077 	relocate_cluster(si, ci);
1078 	swap_cluster_unlock(ci);
1079 	if (si->flags & SWP_SOLIDSTATE) {
1080 		this_cpu_write(percpu_swap_cluster.offset[order], next);
1081 		this_cpu_write(percpu_swap_cluster.si[order], si);
1082 	} else {
1083 		si->global_cluster->next[order] = next;
1084 	}
1085 	return found;
1086 }
1087 
1088 static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,
1089 					 struct list_head *list,
1090 					 struct folio *folio,
1091 					 bool scan_all)
1092 {
1093 	unsigned int found = SWAP_ENTRY_INVALID;
1094 
1095 	do {
1096 		struct swap_cluster_info *ci = isolate_lock_cluster(si, list);
1097 		unsigned long offset;
1098 
1099 		if (!ci)
1100 			break;
1101 		offset = cluster_offset(si, ci);
1102 		found = alloc_swap_scan_cluster(si, ci, folio, offset);
1103 		if (found)
1104 			break;
1105 	} while (scan_all);
1106 
1107 	return found;
1108 }
1109 
1110 static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
1111 {
1112 	long to_scan = 1;
1113 	unsigned long offset, end;
1114 	struct swap_cluster_info *ci;
1115 	unsigned long swp_tb;
1116 	int nr_reclaim;
1117 
1118 	if (force)
1119 		to_scan = swap_usage_in_pages(si) / SWAPFILE_CLUSTER;
1120 
1121 	while ((ci = isolate_lock_cluster(si, &si->full_clusters))) {
1122 		offset = cluster_offset(si, ci);
1123 		end = min(si->max, offset + SWAPFILE_CLUSTER);
1124 		to_scan--;
1125 
1126 		while (offset < end) {
1127 			swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
1128 			if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb)) {
1129 				spin_unlock(&ci->lock);
1130 				nr_reclaim = __try_to_reclaim_swap(si, offset,
1131 								   TTRS_ANYWAY);
1132 				spin_lock(&ci->lock);
1133 				if (nr_reclaim) {
1134 					offset += abs(nr_reclaim);
1135 					continue;
1136 				}
1137 			}
1138 			offset++;
1139 		}
1140 
1141 		/* in case no swap cache is reclaimed */
1142 		if (ci->flags == CLUSTER_FLAG_NONE)
1143 			relocate_cluster(si, ci);
1144 
1145 		swap_cluster_unlock(ci);
1146 		if (to_scan <= 0)
1147 			break;
1148 
1149 		/*
1150 		 * When 'force' is false, 'to_scan' is initialized to 1.
1151 		 * The loop breaks above, making this cond_resched() unreachable
1152 		 * in atomic contexts.
1153 		 */
1154 		cond_resched();
1155 	}
1156 }
1157 
1158 static void swap_reclaim_work(struct work_struct *work)
1159 {
1160 	struct swap_info_struct *si;
1161 
1162 	si = container_of(work, struct swap_info_struct, reclaim_work);
1163 
1164 	swap_reclaim_full_clusters(si, true);
1165 }
1166 
1167 /*
1168  * Try to allocate swap entries with specified order and try set a new
1169  * cluster for current CPU too.
1170  */
1171 static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
1172 					      struct folio *folio)
1173 {
1174 	struct swap_cluster_info *ci;
1175 	unsigned int order = likely(folio) ? folio_order(folio) : 0;
1176 	unsigned int offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
1177 
1178 	/*
1179 	 * Swapfile is not block device so unable
1180 	 * to allocate large entries.
1181 	 */
1182 	if (order && !(si->flags & SWP_BLKDEV))
1183 		return 0;
1184 
1185 	if (!(si->flags & SWP_SOLIDSTATE)) {
1186 		/* Serialize HDD SWAP allocation for each device. */
1187 		spin_lock(&si->global_cluster_lock);
1188 		offset = si->global_cluster->next[order];
1189 		if (offset == SWAP_ENTRY_INVALID)
1190 			goto new_cluster;
1191 
1192 		ci = swap_cluster_lock(si, offset);
1193 		/* Cluster could have been used by another order */
1194 		if (cluster_is_usable(ci, order)) {
1195 			if (cluster_is_empty(ci))
1196 				offset = cluster_offset(si, ci);
1197 			found = alloc_swap_scan_cluster(si, ci, folio, offset);
1198 		} else {
1199 			swap_cluster_unlock(ci);
1200 		}
1201 		if (found)
1202 			goto done;
1203 	}
1204 
1205 new_cluster:
1206 	if (swap_prefer_free_cluster(si)) {
1207 		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
1208 		if (found)
1209 			goto done;
1210 	}
1211 
1212 	if (order < PMD_ORDER) {
1213 		found = alloc_swap_scan_list(si, &si->nonfull_clusters[order], folio, true);
1214 		if (found)
1215 			goto done;
1216 	}
1217 
1218 	if (!swap_prefer_free_cluster(si)) {
1219 		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
1220 		if (found)
1221 			goto done;
1222 	}
1223 
1224 	/* Try reclaim full clusters if free and nonfull lists are drained */
1225 	if (vm_swap_full())
1226 		swap_reclaim_full_clusters(si, false);
1227 
1228 	if (order < PMD_ORDER) {
1229 		/*
1230 		 * Scan only one fragment cluster is good enough. Order 0
1231 		 * allocation will surely success, and large allocation
1232 		 * failure is not critical. Scanning one cluster still
1233 		 * keeps the list rotated and reclaimed (for clean swap cache).
1234 		 */
1235 		found = alloc_swap_scan_list(si, &si->frag_clusters[order], folio, false);
1236 		if (found)
1237 			goto done;
1238 	}
1239 
1240 	if (order)
1241 		goto done;
1242 
1243 	/* Order 0 stealing from higher order */
1244 	for (int o = 1; o < SWAP_NR_ORDERS; o++) {
1245 		/*
1246 		 * Clusters here have at least one usable slots and can't fail order 0
1247 		 * allocation, but reclaim may drop si->lock and race with another user.
1248 		 */
1249 		found = alloc_swap_scan_list(si, &si->frag_clusters[o], folio, true);
1250 		if (found)
1251 			goto done;
1252 
1253 		found = alloc_swap_scan_list(si, &si->nonfull_clusters[o], folio, true);
1254 		if (found)
1255 			goto done;
1256 	}
1257 done:
1258 	if (!(si->flags & SWP_SOLIDSTATE))
1259 		spin_unlock(&si->global_cluster_lock);
1260 
1261 	return found;
1262 }
1263 
1264 /* SWAP_USAGE_OFFLIST_BIT can only be set by this helper. */
1265 static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)
1266 {
1267 	unsigned long pages;
1268 
1269 	spin_lock(&swap_avail_lock);
1270 
1271 	if (swapoff) {
1272 		/*
1273 		 * Forcefully remove it. Clear the SWP_WRITEOK flags for
1274 		 * swapoff here so it's synchronized by both si->lock and
1275 		 * swap_avail_lock, to ensure the result can be seen by
1276 		 * add_to_avail_list.
1277 		 */
1278 		lockdep_assert_held(&si->lock);
1279 		si->flags &= ~SWP_WRITEOK;
1280 		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
1281 	} else {
1282 		/*
1283 		 * If not called by swapoff, take it off-list only if it's
1284 		 * full and SWAP_USAGE_OFFLIST_BIT is not set (strictly
1285 		 * si->inuse_pages == pages), any concurrent slot freeing,
1286 		 * or device already removed from plist by someone else
1287 		 * will make this return false.
1288 		 */
1289 		pages = si->pages;
1290 		if (!atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
1291 					     pages | SWAP_USAGE_OFFLIST_BIT))
1292 			goto skip;
1293 	}
1294 
1295 	plist_del(&si->avail_list, &swap_avail_head);
1296 
1297 skip:
1298 	spin_unlock(&swap_avail_lock);
1299 }
1300 
1301 /* SWAP_USAGE_OFFLIST_BIT can only be cleared by this helper. */
1302 static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
1303 {
1304 	long val;
1305 	unsigned long pages;
1306 
1307 	spin_lock(&swap_avail_lock);
1308 
1309 	/* Corresponding to SWP_WRITEOK clearing in del_from_avail_list */
1310 	if (swapon) {
1311 		lockdep_assert_held(&si->lock);
1312 		si->flags |= SWP_WRITEOK;
1313 	} else {
1314 		if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
1315 			goto skip;
1316 	}
1317 
1318 	if (!(atomic_long_read(&si->inuse_pages) & SWAP_USAGE_OFFLIST_BIT))
1319 		goto skip;
1320 
1321 	val = atomic_long_fetch_and_relaxed(~SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
1322 
1323 	/*
1324 	 * When device is full and device is on the plist, only one updater will
1325 	 * see (inuse_pages == si->pages) and will call del_from_avail_list. If
1326 	 * that updater happen to be here, just skip adding.
1327 	 */
1328 	pages = si->pages;
1329 	if (val == pages) {
1330 		/* Just like the cmpxchg in del_from_avail_list */
1331 		if (atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
1332 					    pages | SWAP_USAGE_OFFLIST_BIT))
1333 			goto skip;
1334 	}
1335 
1336 	plist_add(&si->avail_list, &swap_avail_head);
1337 
1338 skip:
1339 	spin_unlock(&swap_avail_lock);
1340 }
1341 
1342 /*
1343  * swap_usage_add / swap_usage_sub of each slot are serialized by ci->lock
1344  * within each cluster, so the total contribution to the global counter should
1345  * always be positive and cannot exceed the total number of usable slots.
1346  */
1347 static bool swap_usage_add(struct swap_info_struct *si, unsigned int nr_entries)
1348 {
1349 	long val = atomic_long_add_return_relaxed(nr_entries, &si->inuse_pages);
1350 
1351 	/*
1352 	 * If device is full, and SWAP_USAGE_OFFLIST_BIT is not set,
1353 	 * remove it from the plist.
1354 	 */
1355 	if (unlikely(val == si->pages)) {
1356 		del_from_avail_list(si, false);
1357 		return true;
1358 	}
1359 
1360 	return false;
1361 }
1362 
1363 static void swap_usage_sub(struct swap_info_struct *si, unsigned int nr_entries)
1364 {
1365 	long val = atomic_long_sub_return_relaxed(nr_entries, &si->inuse_pages);
1366 
1367 	/*
1368 	 * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set,
1369 	 * add it to the plist.
1370 	 */
1371 	if (unlikely(val & SWAP_USAGE_OFFLIST_BIT))
1372 		add_to_avail_list(si, false);
1373 }
1374 
1375 static void swap_range_alloc(struct swap_info_struct *si,
1376 			     unsigned int nr_entries)
1377 {
1378 	if (swap_usage_add(si, nr_entries)) {
1379 		if (vm_swap_full())
1380 			schedule_work(&si->reclaim_work);
1381 	}
1382 	atomic_long_sub(nr_entries, &nr_swap_pages);
1383 }
1384 
1385 static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
1386 			    unsigned int nr_entries)
1387 {
1388 	unsigned long end = offset + nr_entries - 1;
1389 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
1390 
1391 	zswap_invalidate(si->type, offset, nr_entries);
1392 
1393 	if (si->flags & SWP_BLKDEV)
1394 		swap_slot_free_notify =
1395 			si->bdev->bd_disk->fops->swap_slot_free_notify;
1396 	else
1397 		swap_slot_free_notify = NULL;
1398 	while (offset <= end) {
1399 		arch_swap_invalidate_page(si->type, offset);
1400 		if (swap_slot_free_notify)
1401 			swap_slot_free_notify(si->bdev, offset);
1402 		offset++;
1403 	}
1404 
1405 	/*
1406 	 * Make sure that try_to_unuse() observes si->inuse_pages reaching 0
1407 	 * only after the above cleanups are done.
1408 	 */
1409 	smp_wmb();
1410 	atomic_long_add(nr_entries, &nr_swap_pages);
1411 	swap_usage_sub(si, nr_entries);
1412 }
1413 
1414 static bool get_swap_device_info(struct swap_info_struct *si)
1415 {
1416 	if (!percpu_ref_tryget_live(&si->users))
1417 		return false;
1418 	/*
1419 	 * Guarantee the si->users are checked before accessing other
1420 	 * fields of swap_info_struct, and si->flags (SWP_WRITEOK) is
1421 	 * up to dated.
1422 	 *
1423 	 * Paired with the spin_unlock() after setup_swap_info() in
1424 	 * enable_swap_info(), and smp_wmb() in swapoff.
1425 	 */
1426 	smp_rmb();
1427 	return true;
1428 }
1429 
1430 /*
1431  * Fast path try to get swap entries with specified order from current
1432  * CPU's swap entry pool (a cluster).
1433  */
1434 static bool swap_alloc_fast(struct folio *folio)
1435 {
1436 	unsigned int order = folio_order(folio);
1437 	struct swap_cluster_info *ci;
1438 	struct swap_info_struct *si;
1439 	unsigned int offset;
1440 
1441 	/*
1442 	 * Once allocated, swap_info_struct will never be completely freed,
1443 	 * so checking it's liveness by get_swap_device_info is enough.
1444 	 */
1445 	si = this_cpu_read(percpu_swap_cluster.si[order]);
1446 	offset = this_cpu_read(percpu_swap_cluster.offset[order]);
1447 	if (!si || !offset || !get_swap_device_info(si))
1448 		return false;
1449 
1450 	ci = swap_cluster_lock(si, offset);
1451 	if (cluster_is_usable(ci, order)) {
1452 		if (cluster_is_empty(ci))
1453 			offset = cluster_offset(si, ci);
1454 		alloc_swap_scan_cluster(si, ci, folio, offset);
1455 	} else {
1456 		swap_cluster_unlock(ci);
1457 	}
1458 
1459 	put_swap_device(si);
1460 	return folio_test_swapcache(folio);
1461 }
1462 
1463 /* Rotate the device and switch to a new cluster */
1464 static void swap_alloc_slow(struct folio *folio)
1465 {
1466 	struct swap_info_struct *si, *next;
1467 
1468 	spin_lock(&swap_avail_lock);
1469 start_over:
1470 	plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
1471 		/* Rotate the device and switch to a new cluster */
1472 		plist_requeue(&si->avail_list, &swap_avail_head);
1473 		spin_unlock(&swap_avail_lock);
1474 		if (get_swap_device_info(si)) {
1475 			cluster_alloc_swap_entry(si, folio);
1476 			put_swap_device(si);
1477 			if (folio_test_swapcache(folio))
1478 				return;
1479 			if (folio_test_large(folio))
1480 				return;
1481 		}
1482 
1483 		spin_lock(&swap_avail_lock);
1484 		/*
1485 		 * if we got here, it's likely that si was almost full before,
1486 		 * multiple callers probably all tried to get a page from the
1487 		 * same si and it filled up before we could get one; or, the si
1488 		 * filled up between us dropping swap_avail_lock.
1489 		 * Since we dropped the swap_avail_lock, the swap_avail_list
1490 		 * may have been modified; so if next is still in the
1491 		 * swap_avail_head list then try it, otherwise start over if we
1492 		 * have not gotten any slots.
1493 		 */
1494 		if (plist_node_empty(&next->avail_list))
1495 			goto start_over;
1496 	}
1497 	spin_unlock(&swap_avail_lock);
1498 }
1499 
1500 /*
1501  * Discard pending clusters in a synchronized way when under high pressure.
1502  * Return: true if any cluster is discarded.
1503  */
1504 static bool swap_sync_discard(void)
1505 {
1506 	bool ret = false;
1507 	struct swap_info_struct *si, *next;
1508 
1509 	spin_lock(&swap_lock);
1510 start_over:
1511 	plist_for_each_entry_safe(si, next, &swap_active_head, list) {
1512 		spin_unlock(&swap_lock);
1513 		if (get_swap_device_info(si)) {
1514 			if (si->flags & SWP_PAGE_DISCARD)
1515 				ret = swap_do_scheduled_discard(si);
1516 			put_swap_device(si);
1517 		}
1518 		if (ret)
1519 			return true;
1520 
1521 		spin_lock(&swap_lock);
1522 		if (plist_node_empty(&next->list))
1523 			goto start_over;
1524 	}
1525 	spin_unlock(&swap_lock);
1526 
1527 	return false;
1528 }
1529 
1530 static int swap_extend_table_alloc(struct swap_info_struct *si,
1531 				   struct swap_cluster_info *ci,
1532 				   unsigned int ci_off, gfp_t gfp)
1533 {
1534 	int count;
1535 	void *table;
1536 
1537 	table = kzalloc(sizeof(ci->extend_table[0]) * SWAPFILE_CLUSTER, gfp);
1538 	if (!table)
1539 		return -ENOMEM;
1540 
1541 	spin_lock(&ci->lock);
1542 	/*
1543 	 * Extend table allocation requires releasing ci lock first so it's
1544 	 * possible that the slot has been freed, no longer overflowed, or
1545 	 * a concurrent extend table allocation has already succeeded, so
1546 	 * the allocation is no longer needed.
1547 	 */
1548 	if (!cluster_table_is_alloced(ci))
1549 		goto out_free;
1550 	count = swp_tb_get_count(__swap_table_get(ci, ci_off));
1551 	if (count < (SWP_TB_COUNT_MAX - 1))
1552 		goto out_free;
1553 	if (ci->extend_table)
1554 		goto out_free;
1555 
1556 	ci->extend_table = table;
1557 	spin_unlock(&ci->lock);
1558 	return 0;
1559 
1560 out_free:
1561 	spin_unlock(&ci->lock);
1562 	kfree(table);
1563 	return 0;
1564 }
1565 
1566 int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp)
1567 {
1568 	int ret;
1569 	struct swap_info_struct *si;
1570 	struct swap_cluster_info *ci;
1571 	unsigned long offset = swp_offset(entry);
1572 
1573 	si = get_swap_device(entry);
1574 	if (IS_ERR_OR_NULL(si))
1575 		return 0;
1576 
1577 	ci = __swap_offset_to_cluster(si, offset);
1578 	ret = swap_extend_table_alloc(si, ci, swp_cluster_offset(entry), gfp);
1579 
1580 	put_swap_device(si);
1581 	return ret;
1582 }
1583 
1584 static void swap_extend_table_try_free(struct swap_cluster_info *ci)
1585 {
1586 	unsigned long i;
1587 
1588 	if (!ci->extend_table)
1589 		return;
1590 
1591 	for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1592 		if (ci->extend_table[i])
1593 			return;
1594 	}
1595 
1596 	kfree(ci->extend_table);
1597 	ci->extend_table = NULL;
1598 }
1599 
1600 /* Decrease the swap count of one slot, without freeing it */
1601 static void __swap_cluster_put_entry(struct swap_cluster_info *ci,
1602 				    unsigned int ci_off)
1603 {
1604 	int count;
1605 	unsigned long swp_tb;
1606 
1607 	lockdep_assert_held(&ci->lock);
1608 	swp_tb = __swap_table_get(ci, ci_off);
1609 	count = __swp_tb_get_count(swp_tb);
1610 
1611 	VM_WARN_ON_ONCE(count <= 0);
1612 	VM_WARN_ON_ONCE(count > SWP_TB_COUNT_MAX);
1613 
1614 	if (count == SWP_TB_COUNT_MAX) {
1615 		count = ci->extend_table[ci_off];
1616 		/* Overflow starts with SWP_TB_COUNT_MAX */
1617 		VM_WARN_ON_ONCE(count < SWP_TB_COUNT_MAX);
1618 		count--;
1619 		if (count == (SWP_TB_COUNT_MAX - 1)) {
1620 			ci->extend_table[ci_off] = 0;
1621 			__swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, count));
1622 		} else {
1623 			ci->extend_table[ci_off] = count;
1624 		}
1625 	} else {
1626 		__swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, --count));
1627 	}
1628 
1629 	/*
1630 	 * `SWP_TB_COUNT_MAX - 1` triggers extend table allocation. If the
1631 	 * count was above that, then the extend table is no longer needed,
1632 	 * so free it. And if we just put the count value from MAX - 1, it's
1633 	 * also possible that a pending dup just attached an extend table.
1634 	 */
1635 	if (unlikely(count == SWP_TB_COUNT_MAX - 2 || count == SWP_TB_COUNT_MAX - 1))
1636 		swap_extend_table_try_free(ci);
1637 }
1638 
1639 /**
1640  * swap_put_entries_cluster - Decrease the swap count of slots within one cluster
1641  * @si: The swap device.
1642  * @offset: start offset of slots.
1643  * @nr: number of slots.
1644  * @reclaim_cache: if true, also reclaim the swap cache if slots are freed.
1645  *
1646  * This helper decreases the swap count of a set of slots and tries to
1647  * batch free them. Also reclaims the swap cache if @reclaim_cache is true.
1648  *
1649  * Context: The specified slots must be pinned by existing swap count or swap
1650  * cache reference, so they won't be released until this helper returns.
1651  */
1652 static void swap_put_entries_cluster(struct swap_info_struct *si,
1653 				     pgoff_t offset, int nr,
1654 				     bool reclaim_cache)
1655 {
1656 	struct swap_cluster_info *ci;
1657 	unsigned int ci_off, ci_end;
1658 	pgoff_t end = offset + nr;
1659 	bool need_reclaim = false;
1660 	unsigned int nr_reclaimed;
1661 	unsigned long swp_tb;
1662 	int ci_batch = -1;
1663 
1664 	ci = swap_cluster_lock(si, offset);
1665 	ci_off = offset % SWAPFILE_CLUSTER;
1666 	ci_end = ci_off + nr;
1667 	do {
1668 		swp_tb = __swap_table_get(ci, ci_off);
1669 		if (swp_tb_get_count(swp_tb) == 1) {
1670 			/* count == 1 and non-cached slots will be batch freed. */
1671 			if (!swp_tb_is_folio(swp_tb)) {
1672 				if (ci_batch == -1)
1673 					ci_batch = ci_off;
1674 				continue;
1675 			}
1676 			/* count will be 0 after put, slot can be reclaimed */
1677 			need_reclaim = true;
1678 		}
1679 		/*
1680 		 * A count != 1 or cached slot can't be freed. Put its swap
1681 		 * count and then free the interrupted pending batch. Cached
1682 		 * slots will be freed when folio is removed from swap cache
1683 		 * (__swap_cache_del_folio).
1684 		 */
1685 		__swap_cluster_put_entry(ci, ci_off);
1686 		if (ci_batch != -1) {
1687 			__swap_cluster_free_entries(si, ci, ci_batch, ci_off - ci_batch);
1688 			ci_batch = -1;
1689 		}
1690 	} while (++ci_off < ci_end);
1691 
1692 	if (ci_batch != -1)
1693 		__swap_cluster_free_entries(si, ci, ci_batch, ci_off - ci_batch);
1694 	swap_cluster_unlock(ci);
1695 
1696 	if (!need_reclaim || !reclaim_cache)
1697 		return;
1698 
1699 	do {
1700 		nr_reclaimed = __try_to_reclaim_swap(si, offset,
1701 						     TTRS_UNMAPPED | TTRS_FULL);
1702 		offset++;
1703 		if (nr_reclaimed)
1704 			offset = round_up(offset, abs(nr_reclaimed));
1705 	} while (offset < end);
1706 }
1707 
1708 /* Increase the swap count of one slot. */
1709 static int __swap_cluster_dup_entry(struct swap_cluster_info *ci,
1710 				    unsigned int ci_off)
1711 {
1712 	int count;
1713 	unsigned long swp_tb;
1714 
1715 	lockdep_assert_held(&ci->lock);
1716 	swp_tb = __swap_table_get(ci, ci_off);
1717 	/* Bad or special slots can't be handled */
1718 	if (WARN_ON_ONCE(swp_tb_is_bad(swp_tb)))
1719 		return -EINVAL;
1720 	count = __swp_tb_get_count(swp_tb);
1721 	/* Must be either cached or have a count already */
1722 	if (WARN_ON_ONCE(!count && !swp_tb_is_folio(swp_tb)))
1723 		return -ENOENT;
1724 
1725 	if (likely(count < (SWP_TB_COUNT_MAX - 1))) {
1726 		__swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, count + 1));
1727 		VM_WARN_ON_ONCE(ci->extend_table && ci->extend_table[ci_off]);
1728 	} else if (count == (SWP_TB_COUNT_MAX - 1)) {
1729 		if (ci->extend_table) {
1730 			VM_WARN_ON_ONCE(ci->extend_table[ci_off]);
1731 			ci->extend_table[ci_off] = SWP_TB_COUNT_MAX;
1732 			__swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, SWP_TB_COUNT_MAX));
1733 		} else {
1734 			return -ENOMEM;
1735 		}
1736 	} else if (count == SWP_TB_COUNT_MAX) {
1737 		VM_WARN_ON_ONCE(ci->extend_table[ci_off] >=
1738                                type_max(typeof(ci->extend_table[0])));
1739 		++ci->extend_table[ci_off];
1740 	} else {
1741 		/* Never happens unless counting went wrong */
1742 		WARN_ON_ONCE(1);
1743 	}
1744 
1745 	return 0;
1746 }
1747 
1748 /**
1749  * swap_dup_entries_cluster: Increase the swap count of slots within one cluster.
1750  * @si: The swap device.
1751  * @offset: start offset of slots.
1752  * @nr: number of slots.
1753  *
1754  * Context: The specified slots must be pinned by existing swap count or swap
1755  * cache reference, so they won't be released until this helper returns.
1756  * Return: 0 on success. -ENOMEM if the swap count maxed out (SWP_TB_COUNT_MAX)
1757  * and failed to allocate an extended table, -EINVAL if any entry is bad entry.
1758  */
1759 static int swap_dup_entries_cluster(struct swap_info_struct *si,
1760 				    pgoff_t offset, int nr)
1761 {
1762 	int err;
1763 	struct swap_cluster_info *ci;
1764 	unsigned int ci_start, ci_off, ci_end;
1765 
1766 	ci_start = offset % SWAPFILE_CLUSTER;
1767 	ci_end = ci_start + nr;
1768 	ci_off = ci_start;
1769 	ci = swap_cluster_lock(si, offset);
1770 restart:
1771 	do {
1772 		err = __swap_cluster_dup_entry(ci, ci_off);
1773 		if (unlikely(err)) {
1774 			if (err == -ENOMEM) {
1775 				spin_unlock(&ci->lock);
1776 				err = swap_extend_table_alloc(si, ci, ci_off, GFP_ATOMIC);
1777 				spin_lock(&ci->lock);
1778 				if (!err)
1779 					goto restart;
1780 			}
1781 			goto failed;
1782 		}
1783 	} while (++ci_off < ci_end);
1784 	swap_cluster_unlock(ci);
1785 	return 0;
1786 failed:
1787 	while (ci_off-- > ci_start)
1788 		__swap_cluster_put_entry(ci, ci_off);
1789 	swap_cluster_unlock(ci);
1790 	return err;
1791 }
1792 
1793 /**
1794  * folio_alloc_swap - allocate swap space for a folio
1795  * @folio: folio we want to move to swap
1796  *
1797  * Allocate swap space for the folio and add the folio to the
1798  * swap cache.
1799  *
1800  * Context: Caller needs to hold the folio lock.
1801  * Return: %0 on success, %-E2BIG if splitting the folio might allow swapout,
1802  * %-ENOSPC if no global swap space is available, or %-ENOMEM if splitting
1803  * would not help.
1804  */
1805 int folio_alloc_swap(struct folio *folio)
1806 {
1807 	unsigned int order = folio_order(folio);
1808 	unsigned int size = 1 << order;
1809 
1810 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1811 	VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio);
1812 
1813 	if (order) {
1814 		/*
1815 		 * Reject large allocation when THP_SWAP is disabled. Check below
1816 		 * whether splitting and retrying can make progress.
1817 		 */
1818 		if (!IS_ENABLED(CONFIG_THP_SWAP))
1819 			goto failed;
1820 
1821 		/*
1822 		 * Allocation size should never exceed cluster size
1823 		 * (HPAGE_PMD_SIZE).
1824 		 */
1825 		if (size > SWAPFILE_CLUSTER) {
1826 			VM_WARN_ON_ONCE(1);
1827 			goto failed;
1828 		}
1829 	}
1830 
1831 again:
1832 	local_lock(&percpu_swap_cluster.lock);
1833 	if (!swap_alloc_fast(folio))
1834 		swap_alloc_slow(folio);
1835 	local_unlock(&percpu_swap_cluster.lock);
1836 
1837 	if (!order && unlikely(!folio_test_swapcache(folio))) {
1838 		if (swap_sync_discard())
1839 			goto again;
1840 	}
1841 
1842 	/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */
1843 	if (unlikely(mem_cgroup_try_charge_swap(folio))) {
1844 		swap_cache_del_folio(folio);
1845 		goto failed;
1846 	}
1847 
1848 	if (unlikely(!folio_test_swapcache(folio)))
1849 		goto failed;
1850 
1851 	return 0;
1852 
1853 failed:
1854 	if (get_nr_swap_pages() <= 0)
1855 		return -ENOSPC;
1856 	if (mem_cgroup_get_folio_swap_margin(folio) <= 0)
1857 		return -ENOMEM;
1858 
1859 	return order ? -E2BIG : -ENOMEM;
1860 }
1861 
1862 /**
1863  * folio_dup_swap() - Increase swap count of swap entries of a folio.
1864  * @folio: folio with swap entries bounded.
1865  * @page: if not NULL, only increase the swap count of this page.
1866  *
1867  * Typically called when the folio is unmapped and have its swap entry to
1868  * take its place: Swap entries allocated to a folio has count == 0 and pinned
1869  * by swap cache. The swap cache pin doesn't increase the swap count. This
1870  * helper sets the initial count == 1 and increases the count as the folio is
1871  * unmapped and swap entries referencing the slots are generated to replace
1872  * the folio.
1873  *
1874  * Context: Caller must ensure the folio is locked and in the swap cache.
1875  * NOTE: The caller also has to ensure there is no raced call to
1876  * swap_put_entries_direct on its swap entry before this helper returns, or
1877  * the swap count may underflow.
1878  */
1879 int folio_dup_swap(struct folio *folio, struct page *page)
1880 {
1881 	swp_entry_t entry = folio->swap;
1882 	unsigned long nr_pages = folio_nr_pages(folio);
1883 
1884 	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
1885 	VM_WARN_ON_FOLIO(!folio_test_swapcache(folio), folio);
1886 
1887 	if (page) {
1888 		entry = folio_page_swap_entry(folio, page);
1889 		nr_pages = 1;
1890 	}
1891 
1892 	return swap_dup_entries_cluster(swap_entry_to_info(entry),
1893 					swp_offset(entry), nr_pages);
1894 }
1895 
1896 /**
1897  * folio_put_swap() - Decrease swap count of swap entries of a folio.
1898  * @folio: folio with swap entries bounded, must be in swap cache and locked.
1899  * @page: if not NULL, only decrease the swap count of this page.
1900  *
1901  * This won't free the swap slots even if swap count drops to zero, they are
1902  * still pinned by the swap cache. User may call folio_free_swap to free them.
1903  * Context: Caller must ensure the folio is locked and in the swap cache.
1904  */
1905 void folio_put_swap(struct folio *folio, struct page *page)
1906 {
1907 	swp_entry_t entry = folio->swap;
1908 	unsigned long nr_pages = folio_nr_pages(folio);
1909 	struct swap_info_struct *si = __swap_entry_to_info(entry);
1910 
1911 	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
1912 	VM_WARN_ON_FOLIO(!folio_test_swapcache(folio), folio);
1913 
1914 	if (page) {
1915 		entry = folio_page_swap_entry(folio, page);
1916 		nr_pages = 1;
1917 	}
1918 
1919 	swap_put_entries_cluster(si, swp_offset(entry), nr_pages, false);
1920 }
1921 
1922 /*
1923  * When we get a swap entry, if there aren't some other ways to
1924  * prevent swapoff, such as the folio in swap cache is locked, RCU
1925  * reader side is locked, etc., the swap entry may become invalid
1926  * because of swapoff.  Then, we need to enclose all swap related
1927  * functions with get_swap_device() and put_swap_device(), unless the
1928  * swap functions call get/put_swap_device() by themselves.
1929  *
1930  * RCU reader side lock (including any spinlock) is sufficient to
1931  * prevent swapoff, because synchronize_rcu() is called in swapoff()
1932  * before freeing data structures.
1933  *
1934  * Check whether swap entry is valid in the swap device.  If so,
1935  * return pointer to swap_info_struct, and keep the swap entry valid
1936  * via preventing the swap device from being swapoff, until
1937  * put_swap_device() is called.  Return NULL for an empty entry or a
1938  * device that is going away, and ERR_PTR(-EIO) if the entry's type
1939  * names no swap device or its offset is past the end of one. These EIOs
1940  * are preceded by pr_err().
1941  *
1942  * Notice that swapoff or swapoff+swapon can still happen before the
1943  * percpu_ref_tryget_live() in get_swap_device() or after the
1944  * percpu_ref_put() in put_swap_device() if there isn't any other way
1945  * to prevent swapoff.  The caller must be prepared for that.  For
1946  * example, the following situation is possible.
1947  *
1948  *   CPU1				CPU2
1949  *   do_swap_page()
1950  *     ...				swapoff+swapon
1951  *     __swap_cache_alloc_folio()
1952  *       // check swap_map
1953  *     // verify PTE not changed
1954  *
1955  * In __swap_duplicate(), the swap_map need to be checked before
1956  * changing partly because the specified swap entry may be for another
1957  * swap device which has been swapoff.  And in do_swap_page(), after
1958  * the page is read from the swap device, the PTE is verified not
1959  * changed with the page table locked to check whether the swap device
1960  * has been swapoff or swapoff+swapon.
1961  */
1962 struct swap_info_struct *get_swap_device(swp_entry_t entry)
1963 {
1964 	struct swap_info_struct *si;
1965 	unsigned long offset;
1966 
1967 	if (!entry.val)
1968 		goto out;
1969 	si = swap_entry_to_info(entry);
1970 	if (!si)
1971 		goto bad_nofile;
1972 	if (!get_swap_device_info(si))
1973 		goto out;
1974 	offset = swp_offset(entry);
1975 	if (offset >= si->max)
1976 		goto put_out;
1977 
1978 	return si;
1979 bad_nofile:
1980 	pr_err_ratelimited("%s: %s%08lx\n", __func__, Bad_file, entry.val);
1981 	return ERR_PTR(-EIO);
1982 
1983 out:
1984 	return NULL;
1985 put_out:
1986 	pr_err_ratelimited("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
1987 	percpu_ref_put(&si->users);
1988 	return ERR_PTR(-EIO);
1989 }
1990 
1991 /*
1992  * Free a set of swap slots after their swap count dropped to zero, or will be
1993  * zero after putting the last ref (saves one __swap_cluster_put_entry call).
1994  */
1995 void __swap_cluster_free_entries(struct swap_info_struct *si,
1996 				 struct swap_cluster_info *ci,
1997 				 unsigned int ci_start, unsigned int nr_pages)
1998 {
1999 	unsigned long old_tb;
2000 	unsigned short batch_id = 0, id_cur;
2001 	unsigned int ci_off = ci_start, ci_end = ci_start + nr_pages;
2002 	unsigned long ci_head = cluster_offset(si, ci);
2003 	unsigned int batch_off = ci_off;
2004 
2005 	VM_WARN_ON(ci->count < nr_pages);
2006 
2007 	ci->count -= nr_pages;
2008 	do {
2009 		old_tb = __swap_table_get(ci, ci_off);
2010 		/*
2011 		 * Freeing is done after release of the last swap count
2012 		 * ref, or after swap cache is dropped
2013 		 */
2014 		VM_WARN_ON(!swp_tb_is_shadow(old_tb) || __swp_tb_get_count(old_tb) > 1);
2015 
2016 		/* Resetting the slot to NULL also clears the inline flags. */
2017 		__swap_table_set(ci, ci_off, null_to_swp_tb());
2018 		if (!SWAP_TABLE_HAS_ZEROFLAG)
2019 			__swap_table_clear_zero(ci, ci_off);
2020 
2021 		/*
2022 		 * Uncharge swap slots by memcg in batches. Consecutive
2023 		 * slots with the same cgroup id are uncharged together.
2024 		 */
2025 		id_cur = __swap_cgroup_clear(ci, ci_off, 1);
2026 		if (batch_id != id_cur) {
2027 			if (batch_id)
2028 				mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
2029 			batch_id = id_cur;
2030 			batch_off = ci_off;
2031 		}
2032 	} while (++ci_off < ci_end);
2033 
2034 	if (batch_id)
2035 		mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off);
2036 
2037 	swap_range_free(si, ci_head + ci_start, nr_pages);
2038 	swap_cluster_assert_empty(ci, ci_start, nr_pages, false);
2039 
2040 	if (!ci->count)
2041 		free_cluster(si, ci);
2042 	else
2043 		partial_free_cluster(si, ci);
2044 }
2045 
2046 int __swap_count(swp_entry_t entry)
2047 {
2048 	struct swap_cluster_info *ci = __swap_entry_to_cluster(entry);
2049 	unsigned int ci_off = swp_cluster_offset(entry);
2050 
2051 	return swp_tb_get_count(__swap_table_get(ci, ci_off));
2052 }
2053 
2054 /**
2055  * swap_entry_swapped - Check if the swap entry is swapped.
2056  * @si: the swap device.
2057  * @entry: the swap entry.
2058  */
2059 bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry)
2060 {
2061 	pgoff_t offset = swp_offset(entry);
2062 	struct swap_cluster_info *ci;
2063 	unsigned long swp_tb;
2064 
2065 	ci = swap_cluster_lock(si, offset);
2066 	swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
2067 	swap_cluster_unlock(ci);
2068 
2069 	return swp_tb_get_count(swp_tb) > 0;
2070 }
2071 
2072 /*
2073  * How many references to @entry are currently swapped out?
2074  * This returns exact answer.
2075  */
2076 int swp_swapcount(swp_entry_t entry)
2077 {
2078 	struct swap_info_struct *si;
2079 	struct swap_cluster_info *ci;
2080 	unsigned long swp_tb;
2081 	int count;
2082 
2083 	si = get_swap_device(entry);
2084 	if (IS_ERR_OR_NULL(si))
2085 		return 0;
2086 
2087 	ci = swap_cluster_lock(si, swp_offset(entry));
2088 	swp_tb = __swap_table_get(ci, swp_cluster_offset(entry));
2089 	count = swp_tb_get_count(swp_tb);
2090 	if (count == SWP_TB_COUNT_MAX)
2091 		count = ci->extend_table[swp_cluster_offset(entry)];
2092 	swap_cluster_unlock(ci);
2093 	put_swap_device(si);
2094 
2095 	return count < 0 ? 0 : count;
2096 }
2097 
2098 /*
2099  * folio_maybe_swapped - Test if a folio covers any swap slot with count > 0.
2100  *
2101  * Check if a folio is swapped. Holding the folio lock ensures the folio won't
2102  * go from not-swapped to swapped because the initial swap count increment can
2103  * only be done by folio_dup_swap, which also locks the folio. But a concurrent
2104  * decrease of swap count is possible through swap_put_entries_direct, so this
2105  * may return a false positive.
2106  *
2107  * Context: Caller must ensure the folio is locked and in the swap cache.
2108  */
2109 static bool folio_maybe_swapped(struct folio *folio)
2110 {
2111 	swp_entry_t entry = folio->swap;
2112 	struct swap_cluster_info *ci;
2113 	unsigned int ci_off, ci_end;
2114 	bool ret = false;
2115 
2116 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
2117 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
2118 
2119 	ci = __swap_entry_to_cluster(entry);
2120 	ci_off = swp_cluster_offset(entry);
2121 	ci_end = ci_off + folio_nr_pages(folio);
2122 	/*
2123 	 * Extra locking not needed, folio lock ensures its swap entries
2124 	 * won't be released, the backing data won't be gone either.
2125 	 */
2126 	rcu_read_lock();
2127 	do {
2128 		if (__swp_tb_get_count(__swap_table_get(ci, ci_off))) {
2129 			ret = true;
2130 			break;
2131 		}
2132 	} while (++ci_off < ci_end);
2133 	rcu_read_unlock();
2134 
2135 	return ret;
2136 }
2137 
2138 static bool folio_swapcache_freeable(struct folio *folio)
2139 {
2140 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
2141 
2142 	if (!folio_test_swapcache(folio))
2143 		return false;
2144 	if (folio_test_writeback(folio))
2145 		return false;
2146 
2147 	/*
2148 	 * Once hibernation has begun to create its image of memory,
2149 	 * there's a danger that one of the calls to folio_free_swap()
2150 	 * - most probably a call from __try_to_reclaim_swap() while
2151 	 * hibernation is allocating its own swap pages for the image,
2152 	 * but conceivably even a call from memory reclaim - will free
2153 	 * the swap from a folio which has already been recorded in the
2154 	 * image as a clean swapcache folio, and then reuse its swap for
2155 	 * another page of the image.  On waking from hibernation, the
2156 	 * original folio might be freed under memory pressure, then
2157 	 * later read back in from swap, now with the wrong data.
2158 	 *
2159 	 * Hibernation suspends storage while it is writing the image
2160 	 * to disk so check that here.
2161 	 */
2162 	if (pm_suspended_storage())
2163 		return false;
2164 
2165 	return true;
2166 }
2167 
2168 /**
2169  * folio_free_swap() - Free the swap space used for this folio.
2170  * @folio: The folio to remove.
2171  *
2172  * If swap is getting full, or if there are no more mappings of this folio,
2173  * then call folio_free_swap to free its swap space.
2174  *
2175  * Return: true if we were able to release the swap space.
2176  */
2177 bool folio_free_swap(struct folio *folio)
2178 {
2179 	if (!folio_swapcache_freeable(folio))
2180 		return false;
2181 	if (folio_maybe_swapped(folio))
2182 		return false;
2183 
2184 	swap_cache_del_folio(folio);
2185 	folio_set_dirty(folio);
2186 	return true;
2187 }
2188 
2189 /**
2190  * swap_put_entries_direct() - Release reference on range of swap entries and
2191  *                             reclaim their cache if no more references remain.
2192  * @entry: First entry of range.
2193  * @nr: Number of entries in range.
2194  *
2195  * For each swap entry in the contiguous range, release a reference. If any swap
2196  * entries become free, try to reclaim their underlying folios, if present. The
2197  * offset range is defined by [entry.offset, entry.offset + nr).
2198  *
2199  * Context: Caller must ensure there is no race condition on the reference
2200  * owner. e.g., locking the PTL of a PTE containing the entry being released.
2201  */
2202 void swap_put_entries_direct(swp_entry_t entry, int nr)
2203 {
2204 	const unsigned long start_offset = swp_offset(entry);
2205 	const unsigned long end_offset = start_offset + nr;
2206 	unsigned long offset, cluster_end;
2207 	struct swap_info_struct *si;
2208 
2209 	si = get_swap_device(entry);
2210 	if (WARN_ON_ONCE(IS_ERR_OR_NULL(si)))
2211 		return;
2212 	if (WARN_ON_ONCE(end_offset > si->max))
2213 		goto out;
2214 
2215 	/* Put entries and reclaim cache in each cluster */
2216 	offset = start_offset;
2217 	do {
2218 		cluster_end = min(round_up(offset + 1, SWAPFILE_CLUSTER), end_offset);
2219 		swap_put_entries_cluster(si, offset, cluster_end - offset, true);
2220 		offset = cluster_end;
2221 	} while (offset < end_offset);
2222 out:
2223 	put_swap_device(si);
2224 }
2225 
2226 #ifdef CONFIG_HIBERNATION
2227 /**
2228  * swap_alloc_hibernation_slot() - Allocate a swap slot for hibernation.
2229  * @type: swap device type index to allocate from.
2230  *
2231  * The caller must ensure the swap device is stable, either by pinning
2232  * it (SWP_HIBERNATION) or by freezing user-space.
2233  *
2234  * Return: a valid swp_entry_t on success, or an empty entry (val == 0)
2235  * on failure.
2236  */
2237 swp_entry_t swap_alloc_hibernation_slot(int type)
2238 {
2239 	struct swap_info_struct *pcp_si, *si = swap_type_to_info(type);
2240 	unsigned long pcp_offset, offset = SWAP_ENTRY_INVALID;
2241 	struct swap_cluster_info *ci;
2242 	swp_entry_t entry = {0};
2243 
2244 	if (!si)
2245 		goto fail;
2246 
2247 	/*
2248 	 * Try the local cluster first if it matches the device. If
2249 	 * not, try grab a new cluster and override local cluster.
2250 	 */
2251 	local_lock(&percpu_swap_cluster.lock);
2252 	pcp_si = this_cpu_read(percpu_swap_cluster.si[0]);
2253 	pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);
2254 	if (pcp_si == si && pcp_offset) {
2255 		ci = swap_cluster_lock(si, pcp_offset);
2256 		if (cluster_is_usable(ci, 0))
2257 			offset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset);
2258 		else
2259 			swap_cluster_unlock(ci);
2260 	}
2261 	if (!offset)
2262 		offset = cluster_alloc_swap_entry(si, NULL);
2263 	local_unlock(&percpu_swap_cluster.lock);
2264 	if (offset)
2265 		entry = swp_entry(si->type, offset);
2266 
2267 fail:
2268 	return entry;
2269 }
2270 
2271 /**
2272  * swap_free_hibernation_slot() - Free a swap slot allocated for hibernation.
2273  * @entry: swap entry to free.
2274  *
2275  * The caller must ensure the swap device is stable.
2276  */
2277 void swap_free_hibernation_slot(swp_entry_t entry)
2278 {
2279 	struct swap_info_struct *si = __swap_entry_to_info(entry);
2280 	struct swap_cluster_info *ci;
2281 	pgoff_t offset = swp_offset(entry);
2282 
2283 	ci = swap_cluster_lock(si, offset);
2284 	__swap_cluster_put_entry(ci, offset % SWAPFILE_CLUSTER);
2285 	/*
2286 	 * A slot with a folio in the swap cache is freed when the folio
2287 	 * leaves the cache, the same rule swap_put_entries_cluster() follows.
2288 	 * Readahead can put a folio here, and freeing the slot now would
2289 	 * leave that folio with no entry behind it.
2290 	 */
2291 	if (!swp_tb_is_folio(__swap_table_get(ci, offset % SWAPFILE_CLUSTER)))
2292 		__swap_cluster_free_entries(si, ci, offset % SWAPFILE_CLUSTER, 1);
2293 	swap_cluster_unlock(ci);
2294 
2295 	/* In theory readahead might add it to the swap cache by accident */
2296 	__try_to_reclaim_swap(si, offset, TTRS_ANYWAY);
2297 }
2298 
2299 static int __find_hibernation_swap_type(dev_t device, sector_t offset)
2300 {
2301 	int type;
2302 
2303 	lockdep_assert_held(&swap_lock);
2304 
2305 	if (!device)
2306 		return -EINVAL;
2307 
2308 	for (type = 0; type < nr_swapfiles; type++) {
2309 		struct swap_info_struct *sis = swap_info[type];
2310 
2311 		if (!(sis->flags & SWP_WRITEOK))
2312 			continue;
2313 
2314 		if (device == sis->bdev->bd_dev) {
2315 			struct swap_extent *se = first_se(sis);
2316 
2317 			if (se->start_block == offset)
2318 				return type;
2319 		}
2320 	}
2321 	return -ENODEV;
2322 }
2323 
2324 /**
2325  * pin_hibernation_swap_type - Pin the swap device for hibernation
2326  * @device: Block device containing the resume image
2327  * @offset: Offset identifying the swap area
2328  *
2329  * Locate the swap device for @device/@offset and mark it as pinned
2330  * for hibernation. While pinned, swapoff() is prevented.
2331  *
2332  * Only one uswsusp context may pin a swap device at a time.
2333  * If already pinned, this function returns -EBUSY.
2334  *
2335  * Return:
2336  * >= 0 on success (swap type).
2337  * -EINVAL if @device is invalid.
2338  * -ENODEV if the swap device is not found.
2339  * -EBUSY if the device is already pinned for hibernation.
2340  */
2341 int pin_hibernation_swap_type(dev_t device, sector_t offset)
2342 {
2343 	int type;
2344 	struct swap_info_struct *si;
2345 
2346 	spin_lock(&swap_lock);
2347 
2348 	type = __find_hibernation_swap_type(device, offset);
2349 	if (type < 0) {
2350 		spin_unlock(&swap_lock);
2351 		return type;
2352 	}
2353 
2354 	si = swap_type_to_info(type);
2355 	if (WARN_ON_ONCE(!si)) {
2356 		spin_unlock(&swap_lock);
2357 		return -ENODEV;
2358 	}
2359 
2360 	/*
2361 	 * hibernate_acquire() prevents concurrent hibernation sessions.
2362 	 * This check additionally guards against double-pinning within
2363 	 * the same session.
2364 	 */
2365 	if (WARN_ON_ONCE(si->flags & SWP_HIBERNATION)) {
2366 		spin_unlock(&swap_lock);
2367 		return -EBUSY;
2368 	}
2369 
2370 	si->flags |= SWP_HIBERNATION;
2371 
2372 	spin_unlock(&swap_lock);
2373 	return type;
2374 }
2375 
2376 /**
2377  * repin_hibernation_swap_type - Atomically replace the hibernation pin
2378  * @old_type: Swap type currently pinned (or < 0 if none).
2379  * @device:   Block device of the new resume image.
2380  * @offset:   Offset identifying the new swap area.
2381  *
2382  * Look up the swap device for @device/@offset and atomically transfer
2383  * the SWP_HIBERNATION pin from @old_type (if valid) to the new device,
2384  * all under a single swap_lock critical section. This closes the
2385  * swapoff() window that exists when callers unpin and re-pin in two
2386  * separate operations.
2387  *
2388  * If the new device cannot be located, the existing pin on @old_type
2389  * is preserved and an error is returned. If @old_type already refers
2390  * to the same swap_info_struct as the new lookup, no flag changes are
2391  * made and @old_type is returned.
2392  *
2393  * Return:
2394  * >= 0 on success (new swap type).
2395  * -EINVAL if @device is invalid.
2396  * -ENODEV if the swap device is not found.
2397  * -EBUSY  if the new device is already pinned by another context.
2398  */
2399 int repin_hibernation_swap_type(int old_type, dev_t device, sector_t offset)
2400 {
2401 	struct swap_info_struct *old_si, *new_si;
2402 	int new_type;
2403 
2404 	spin_lock(&swap_lock);
2405 
2406 	new_type = __find_hibernation_swap_type(device, offset);
2407 	if (new_type < 0) {
2408 		spin_unlock(&swap_lock);
2409 		return new_type;
2410 	}
2411 
2412 	new_si = swap_type_to_info(new_type);
2413 	if (WARN_ON_ONCE(!new_si)) {
2414 		spin_unlock(&swap_lock);
2415 		return -ENODEV;
2416 	}
2417 
2418 	old_si = swap_type_to_info(old_type);
2419 	if (new_si == old_si) {
2420 		spin_unlock(&swap_lock);
2421 		return new_type;
2422 	}
2423 
2424 	if (WARN_ON_ONCE(new_si->flags & SWP_HIBERNATION)) {
2425 		spin_unlock(&swap_lock);
2426 		return -EBUSY;
2427 	}
2428 
2429 	if (old_si)
2430 		old_si->flags &= ~SWP_HIBERNATION;
2431 	new_si->flags |= SWP_HIBERNATION;
2432 
2433 	spin_unlock(&swap_lock);
2434 	return new_type;
2435 }
2436 
2437 /**
2438  * unpin_hibernation_swap_type - Unpin the swap device for hibernation
2439  * @type: Swap type previously returned by pin_hibernation_swap_type()
2440  *
2441  * Clear the hibernation pin on the given swap device, allowing
2442  * swapoff() to proceed normally.
2443  *
2444  * If @type does not refer to a valid swap device, this function
2445  * does nothing.
2446  */
2447 void unpin_hibernation_swap_type(int type)
2448 {
2449 	struct swap_info_struct *si;
2450 
2451 	spin_lock(&swap_lock);
2452 	si = swap_type_to_info(type);
2453 	if (!si) {
2454 		spin_unlock(&swap_lock);
2455 		return;
2456 	}
2457 	si->flags &= ~SWP_HIBERNATION;
2458 	spin_unlock(&swap_lock);
2459 }
2460 
2461 /**
2462  * find_hibernation_swap_type - Find swap type for hibernation
2463  * @device: Block device containing the resume image
2464  * @offset: Offset within the device identifying the swap area
2465  *
2466  * Locate the swap device corresponding to @device and @offset.
2467  *
2468  * Unlike pin_hibernation_swap_type(), this function only performs a
2469  * lookup and does not mark the swap device as pinned for hibernation.
2470  *
2471  * This is safe in the sysfs-based hibernation path where user space
2472  * is already frozen and swapoff() cannot run concurrently.
2473  *
2474  * Return:
2475  * A non-negative swap type on success.
2476  * -EINVAL if @device is invalid.
2477  * -ENODEV if no matching swap device is found.
2478  */
2479 int find_hibernation_swap_type(dev_t device, sector_t offset)
2480 {
2481 	int type;
2482 
2483 	spin_lock(&swap_lock);
2484 	type = __find_hibernation_swap_type(device, offset);
2485 	spin_unlock(&swap_lock);
2486 
2487 	return type;
2488 }
2489 
2490 int find_first_swap(dev_t *device)
2491 {
2492 	int type;
2493 
2494 	spin_lock(&swap_lock);
2495 	for (type = 0; type < nr_swapfiles; type++) {
2496 		struct swap_info_struct *sis = swap_info[type];
2497 
2498 		if (!(sis->flags & SWP_WRITEOK))
2499 			continue;
2500 		*device = sis->bdev->bd_dev;
2501 		spin_unlock(&swap_lock);
2502 		return type;
2503 	}
2504 	spin_unlock(&swap_lock);
2505 	return -ENODEV;
2506 }
2507 
2508 /*
2509  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
2510  * corresponding to given index in swap_info (swap type).
2511  */
2512 sector_t swapdev_block(int type, pgoff_t offset)
2513 {
2514 	struct swap_info_struct *si = swap_type_to_info(type);
2515 	struct swap_extent *se;
2516 
2517 	if (!si || !(si->flags & SWP_WRITEOK))
2518 		return 0;
2519 	se = offset_to_swap_extent(si, offset);
2520 	return se->start_block + (offset - se->start_page);
2521 }
2522 
2523 /*
2524  * Return either the total number of swap pages of given type, or the number
2525  * of free pages of that type (depending on @free)
2526  *
2527  * This is needed for software suspend
2528  */
2529 unsigned int count_swap_pages(int type, int free)
2530 {
2531 	unsigned int n = 0;
2532 
2533 	spin_lock(&swap_lock);
2534 	if ((unsigned int)type < nr_swapfiles) {
2535 		struct swap_info_struct *sis = swap_info[type];
2536 
2537 		spin_lock(&sis->lock);
2538 		if (sis->flags & SWP_WRITEOK) {
2539 			n = sis->pages;
2540 			if (free)
2541 				n -= swap_usage_in_pages(sis);
2542 		}
2543 		spin_unlock(&sis->lock);
2544 	}
2545 	spin_unlock(&swap_lock);
2546 	return n;
2547 }
2548 #endif /* CONFIG_HIBERNATION */
2549 
2550 static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
2551 {
2552 	return pte_same(pte_swp_clear_flags(pte), swp_pte);
2553 }
2554 
2555 /*
2556  * No need to decide whether this PTE shares the swap entry with others,
2557  * just let do_wp_page work it out if a write is requested later - to
2558  * force COW, vm_page_prot omits write permission from any private vma.
2559  */
2560 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
2561 		unsigned long addr, swp_entry_t entry, struct folio *folio)
2562 {
2563 	struct page *page;
2564 	struct folio *swapcache;
2565 	spinlock_t *ptl;
2566 	pte_t *pte, new_pte, old_pte;
2567 	bool hwpoisoned = false;
2568 	int ret = 1;
2569 
2570 	/*
2571 	 * If the folio is removed from swap cache by others, continue to
2572 	 * unuse other PTEs. try_to_unuse may try again if we missed this one.
2573 	 */
2574 	if (!folio_matches_swap_entry(folio, entry))
2575 		return 0;
2576 
2577 	swapcache = folio;
2578 	folio = ksm_might_need_to_copy(folio,
2579 				       folio_file_page(folio, swp_offset(entry)), vma, addr);
2580 	if (unlikely(!folio))
2581 		return -ENOMEM;
2582 	else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
2583 		hwpoisoned = true;
2584 		folio = swapcache;
2585 	}
2586 
2587 	page = folio_file_page(folio, swp_offset(entry));
2588 	if (PageHWPoison(page))
2589 		hwpoisoned = true;
2590 
2591 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
2592 	if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte),
2593 						swp_entry_to_pte(entry)))) {
2594 		ret = 0;
2595 		goto out;
2596 	}
2597 
2598 	old_pte = ptep_get(pte);
2599 
2600 	if (unlikely(hwpoisoned || !folio_test_uptodate(folio))) {
2601 		swp_entry_t swp_entry;
2602 
2603 		dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
2604 		if (hwpoisoned) {
2605 			swp_entry = make_hwpoison_entry(page);
2606 		} else {
2607 			swp_entry = make_poisoned_swp_entry();
2608 		}
2609 		new_pte = swp_entry_to_pte(swp_entry);
2610 		ret = 0;
2611 		goto setpte;
2612 	}
2613 
2614 	/*
2615 	 * Some architectures may have to restore extra metadata to the page
2616 	 * when reading from swap. This metadata may be indexed by swap entry
2617 	 * so this must be called before folio_put_swap().
2618 	 */
2619 	arch_swap_restore(folio_swap(entry, folio), folio);
2620 
2621 	dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
2622 	inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
2623 	folio_get(folio);
2624 	if (folio == swapcache) {
2625 		rmap_t rmap_flags = RMAP_NONE;
2626 
2627 		/*
2628 		 * See do_swap_page(): writeback would be problematic.
2629 		 * However, we do a folio_wait_writeback() just before this
2630 		 * call and have the folio locked.
2631 		 */
2632 		VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio);
2633 		if (pte_swp_exclusive(old_pte))
2634 			rmap_flags |= RMAP_EXCLUSIVE;
2635 		/*
2636 		 * We currently only expect small !anon folios, which are either
2637 		 * fully exclusive or fully shared. If we ever get large folios
2638 		 * here, we have to be careful.
2639 		 */
2640 		if (!folio_test_anon(folio)) {
2641 			VM_WARN_ON_ONCE(folio_test_large(folio));
2642 			VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
2643 			folio_add_new_anon_rmap(folio, vma, addr, rmap_flags);
2644 		} else {
2645 			folio_add_anon_rmap_pte(folio, page, vma, addr, rmap_flags);
2646 		}
2647 	} else { /* ksm created a completely new copy */
2648 		folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
2649 		folio_add_lru_vma(folio, vma);
2650 	}
2651 	new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot));
2652 	if (pte_swp_soft_dirty(old_pte))
2653 		new_pte = pte_mksoft_dirty(new_pte);
2654 	if (pte_swp_uffd(old_pte))
2655 		new_pte = pte_mkuffd(new_pte);
2656 
2657 	/* See do_swap_page(): restore PAGE_NONE for RWP */
2658 	if (pte_swp_uffd(old_pte) && userfaultfd_rwp(vma))
2659 		new_pte = pte_modify(new_pte, PAGE_NONE);
2660 
2661 setpte:
2662 	set_pte_at(vma->vm_mm, addr, pte, new_pte);
2663 	folio_put_swap(swapcache, folio_file_page(swapcache, swp_offset(entry)));
2664 out:
2665 	if (pte)
2666 		pte_unmap_unlock(pte, ptl);
2667 	if (folio != swapcache) {
2668 		folio_unlock(folio);
2669 		folio_put(folio);
2670 	}
2671 	return ret;
2672 }
2673 
2674 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
2675 			unsigned long addr, unsigned long end,
2676 			unsigned int type)
2677 {
2678 	pte_t *pte = NULL;
2679 
2680 	do {
2681 		struct folio *folio;
2682 		unsigned long swp_tb;
2683 		softleaf_t entry;
2684 		int ret;
2685 		pte_t ptent;
2686 
2687 		if (!pte++) {
2688 			pte = pte_offset_map(pmd, addr);
2689 			if (!pte)
2690 				break;
2691 		}
2692 
2693 		ptent = ptep_get_lockless(pte);
2694 		entry = softleaf_from_pte(ptent);
2695 
2696 		if (!softleaf_is_swap(entry))
2697 			continue;
2698 		if (swp_type(entry) != type)
2699 			continue;
2700 
2701 		pte_unmap(pte);
2702 		pte = NULL;
2703 
2704 		folio = swap_cache_get_folio(entry);
2705 		if (!folio) {
2706 			struct vm_fault vmf = {
2707 				.vma = vma,
2708 				.address = addr,
2709 				.real_address = addr,
2710 				.pmd = pmd,
2711 			};
2712 
2713 			folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
2714 						&vmf);
2715 		}
2716 		if (!folio) {
2717 			swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
2718 						swp_cluster_offset(entry));
2719 			if (swp_tb_get_count(swp_tb) <= 0)
2720 				continue;
2721 			return -ENOMEM;
2722 		}
2723 
2724 		folio_lock(folio);
2725 		folio_wait_writeback(folio);
2726 		ret = unuse_pte(vma, pmd, addr, entry, folio);
2727 		if (ret < 0) {
2728 			folio_unlock(folio);
2729 			folio_put(folio);
2730 			return ret;
2731 		}
2732 
2733 		folio_free_swap(folio);
2734 		folio_unlock(folio);
2735 		folio_put(folio);
2736 	} while (addr += PAGE_SIZE, addr != end);
2737 
2738 	if (pte)
2739 		pte_unmap(pte);
2740 	return 0;
2741 }
2742 
2743 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
2744 				unsigned long addr, unsigned long end,
2745 				unsigned int type)
2746 {
2747 	pmd_t *pmd;
2748 	unsigned long next;
2749 	int ret;
2750 
2751 	pmd = pmd_offset(pud, addr);
2752 	do {
2753 		cond_resched();
2754 		if (signal_pending(current))
2755 			return -ERESTARTSYS;
2756 		next = pmd_addr_end(addr, end);
2757 		ret = unuse_pte_range(vma, pmd, addr, next, type);
2758 		if (ret)
2759 			return ret;
2760 	} while (pmd++, addr = next, addr != end);
2761 	return 0;
2762 }
2763 
2764 static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
2765 				unsigned long addr, unsigned long end,
2766 				unsigned int type)
2767 {
2768 	pud_t *pud;
2769 	unsigned long next;
2770 	int ret;
2771 
2772 	pud = pud_offset(p4d, addr);
2773 	do {
2774 		next = pud_addr_end(addr, end);
2775 		if (pud_none_or_clear_bad(pud))
2776 			continue;
2777 		ret = unuse_pmd_range(vma, pud, addr, next, type);
2778 		if (ret)
2779 			return ret;
2780 	} while (pud++, addr = next, addr != end);
2781 	return 0;
2782 }
2783 
2784 static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
2785 				unsigned long addr, unsigned long end,
2786 				unsigned int type)
2787 {
2788 	p4d_t *p4d;
2789 	unsigned long next;
2790 	int ret;
2791 
2792 	p4d = p4d_offset(pgd, addr);
2793 	do {
2794 		next = p4d_addr_end(addr, end);
2795 		if (p4d_none_or_clear_bad(p4d))
2796 			continue;
2797 		ret = unuse_pud_range(vma, p4d, addr, next, type);
2798 		if (ret)
2799 			return ret;
2800 	} while (p4d++, addr = next, addr != end);
2801 	return 0;
2802 }
2803 
2804 static int unuse_vma(struct vm_area_struct *vma, unsigned int type)
2805 {
2806 	pgd_t *pgd;
2807 	unsigned long addr, end, next;
2808 	int ret;
2809 
2810 	addr = vma->vm_start;
2811 	end = vma->vm_end;
2812 
2813 	pgd = pgd_offset(vma->vm_mm, addr);
2814 	do {
2815 		next = pgd_addr_end(addr, end);
2816 		if (pgd_none_or_clear_bad(pgd))
2817 			continue;
2818 		ret = unuse_p4d_range(vma, pgd, addr, next, type);
2819 		if (ret)
2820 			return ret;
2821 	} while (pgd++, addr = next, addr != end);
2822 	return 0;
2823 }
2824 
2825 static int unuse_mm(struct mm_struct *mm, unsigned int type)
2826 {
2827 	struct vm_area_struct *vma;
2828 	int ret = 0;
2829 	VMA_ITERATOR(vmi, mm, 0);
2830 
2831 	mmap_read_lock(mm);
2832 	if (check_stable_address_space(mm))
2833 		goto unlock;
2834 	for_each_vma(vmi, vma) {
2835 		if (vma_has_anon_rmap(vma) && !vma_is_hugetlb(vma)) {
2836 			ret = unuse_vma(vma, type);
2837 			if (ret)
2838 				break;
2839 		}
2840 
2841 		cond_resched();
2842 	}
2843 unlock:
2844 	mmap_read_unlock(mm);
2845 	return ret;
2846 }
2847 
2848 /*
2849  * Scan swap table from current position to next entry still in use.
2850  * Return 0 if there are no inuse entries after prev till end of
2851  * the map.
2852  */
2853 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
2854 					unsigned int prev)
2855 {
2856 	struct swap_cluster_info *ci;
2857 	unsigned long i, end;
2858 	unsigned int ci_off;
2859 	unsigned long swp_tb;
2860 
2861 	/*
2862 	 * No need for swap_lock here: we're just looking
2863 	 * for whether an entry is in use, not modifying it; false
2864 	 * hits are okay, and sys_swapoff() has already prevented new
2865 	 * allocations from this area (while holding swap_lock).
2866 	 */
2867 	i = prev + 1;
2868 	while (i < si->max) {
2869 		ci = __swap_offset_to_cluster(si, i);
2870 		end = min_t(unsigned long,
2871 			    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,
2872 			    si->max);
2873 
2874 		/*
2875 		 * An empty cluster has no slot in use, so skip it whole.
2876 		 * A slot is uncounted only after its folio left the swap
2877 		 * cache, so there is nothing here for try_to_unuse() to act on.
2878 		 * Count only drops here, so a READ_ONCE() without ci->lock is
2879 		 * enough, unlike in every other cluster_is_empty() caller.
2880 		 */
2881 		if (!READ_ONCE(ci->count)) {
2882 			i = end;
2883 			cond_resched();
2884 			continue;
2885 		}
2886 
2887 		ci_off = i % SWAPFILE_CLUSTER;
2888 		for (; i < end; ci_off++, i++) {
2889 			swp_tb = swap_table_get(ci, ci_off);
2890 			if (!swp_tb_is_null(swp_tb) && !swp_tb_is_bad(swp_tb))
2891 				return i;
2892 		}
2893 		cond_resched();
2894 	}
2895 
2896 	return 0;
2897 }
2898 
2899 static int try_to_unuse(unsigned int type)
2900 {
2901 	struct mm_struct *prev_mm;
2902 	struct mm_struct *mm;
2903 	struct list_head *p;
2904 	int retval = 0;
2905 	struct swap_info_struct *si = swap_info[type];
2906 	struct folio *folio;
2907 	swp_entry_t entry;
2908 	unsigned int i;
2909 
2910 	if (!swap_usage_in_pages(si))
2911 		goto success;
2912 
2913 retry:
2914 	retval = shmem_unuse(type);
2915 	if (retval)
2916 		return retval;
2917 
2918 	prev_mm = &init_mm;
2919 	mmget(prev_mm);
2920 
2921 	spin_lock(&mmlist_lock);
2922 	p = &init_mm.mmlist;
2923 	while (swap_usage_in_pages(si) &&
2924 	       !signal_pending(current) &&
2925 	       (p = p->next) != &init_mm.mmlist) {
2926 
2927 		mm = list_entry(p, struct mm_struct, mmlist);
2928 		if (!mmget_not_zero(mm))
2929 			continue;
2930 		spin_unlock(&mmlist_lock);
2931 		mmput(prev_mm);
2932 		prev_mm = mm;
2933 		retval = unuse_mm(mm, type);
2934 		if (retval) {
2935 			mmput(prev_mm);
2936 			return retval;
2937 		}
2938 
2939 		/*
2940 		 * Make sure that we aren't completely killing
2941 		 * interactive performance.
2942 		 */
2943 		cond_resched();
2944 		spin_lock(&mmlist_lock);
2945 	}
2946 	spin_unlock(&mmlist_lock);
2947 
2948 	mmput(prev_mm);
2949 
2950 	i = 0;
2951 	while (swap_usage_in_pages(si) &&
2952 	       !signal_pending(current) &&
2953 	       (i = find_next_to_unuse(si, i)) != 0) {
2954 
2955 		entry = swp_entry(type, i);
2956 		folio = swap_cache_get_folio(entry);
2957 		if (!folio)
2958 			continue;
2959 
2960 		/*
2961 		 * It is conceivable that a racing task removed this folio from
2962 		 * swap cache just before we acquired the page lock. The folio
2963 		 * might even be back in swap cache on another swap area. But
2964 		 * that is okay, folio_free_swap() only removes stale folios.
2965 		 */
2966 		folio_lock(folio);
2967 		folio_wait_writeback(folio);
2968 		folio_free_swap(folio);
2969 		folio_unlock(folio);
2970 		folio_put(folio);
2971 	}
2972 
2973 	/*
2974 	 * Lets check again to see if there are still swap entries in the map.
2975 	 * If yes, we would need to do retry the unuse logic again.
2976 	 * Under global memory pressure, swap entries can be reinserted back
2977 	 * into process space after the mmlist loop above passes over them.
2978 	 *
2979 	 * Limit the number of retries? No: when mmget_not_zero()
2980 	 * above fails, that mm is likely to be freeing swap from
2981 	 * exit_mmap(), which proceeds at its own independent pace;
2982 	 * and even shmem_writeout() could have been preempted after
2983 	 * folio_alloc_swap(), temporarily hiding that swap.  It's easy
2984 	 * and robust (though cpu-intensive) just to keep retrying.
2985 	 */
2986 	if (swap_usage_in_pages(si)) {
2987 		if (!signal_pending(current))
2988 			goto retry;
2989 		return -ERESTARTSYS;
2990 	}
2991 
2992 success:
2993 	/*
2994 	 * Make sure that further cleanups after try_to_unuse() returns happen
2995 	 * after swap_range_free() reduces si->inuse_pages to 0.
2996 	 */
2997 	smp_mb();
2998 	return 0;
2999 }
3000 
3001 /*
3002  * After a successful try_to_unuse, if no swap is now in use, we know
3003  * we can empty the mmlist.  swap_lock must be held on entry and exit.
3004  * Note that mmlist_lock nests inside swap_lock, and an mm must be
3005  * added to the mmlist just after page_duplicate - before would be racy.
3006  */
3007 static void drain_mmlist(void)
3008 {
3009 	struct list_head *p, *next;
3010 	unsigned int type;
3011 
3012 	for (type = 0; type < nr_swapfiles; type++)
3013 		if (swap_usage_in_pages(swap_info[type]))
3014 			return;
3015 	spin_lock(&mmlist_lock);
3016 	list_for_each_safe(p, next, &init_mm.mmlist)
3017 		list_del_init(p);
3018 	spin_unlock(&mmlist_lock);
3019 }
3020 
3021 /*
3022  * Free all of a swapdev's extent information
3023  */
3024 static void destroy_swap_extents(struct swap_info_struct *sis,
3025 				 struct file *swap_file)
3026 {
3027 	while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
3028 		struct rb_node *rb = sis->swap_extent_root.rb_node;
3029 		struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
3030 
3031 		rb_erase(rb, &sis->swap_extent_root);
3032 		kfree(se);
3033 	}
3034 
3035 	if (sis->flags & SWP_ACTIVATED) {
3036 		struct address_space *mapping = swap_file->f_mapping;
3037 
3038 		sis->flags &= ~SWP_ACTIVATED;
3039 		if (mapping->a_ops->swap_deactivate)
3040 			mapping->a_ops->swap_deactivate(swap_file);
3041 	}
3042 }
3043 
3044 /*
3045  * Add a block range (and the corresponding page range) into this swapdev's
3046  * extent tree.
3047  *
3048  * This function rather assumes that it is called in ascending page order.
3049  */
3050 int
3051 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
3052 		unsigned long nr_pages, sector_t start_block)
3053 {
3054 	struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
3055 	struct swap_extent *se;
3056 	struct swap_extent *new_se;
3057 
3058 	/*
3059 	 * place the new node at the right most since the
3060 	 * function is called in ascending page order.
3061 	 */
3062 	while (*link) {
3063 		parent = *link;
3064 		link = &parent->rb_right;
3065 	}
3066 
3067 	if (parent) {
3068 		se = rb_entry(parent, struct swap_extent, rb_node);
3069 		BUG_ON(se->start_page + se->nr_pages != start_page);
3070 		if (se->start_block + se->nr_pages == start_block) {
3071 			/* Merge it */
3072 			se->nr_pages += nr_pages;
3073 			return 0;
3074 		}
3075 	}
3076 
3077 	/* No merge, insert a new extent. */
3078 	new_se = kmalloc_obj(*se);
3079 	if (new_se == NULL)
3080 		return -ENOMEM;
3081 	new_se->start_page = start_page;
3082 	new_se->nr_pages = nr_pages;
3083 	new_se->start_block = start_block;
3084 
3085 	rb_link_node(&new_se->rb_node, parent, link);
3086 	rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
3087 	return 1;
3088 }
3089 EXPORT_SYMBOL_GPL(add_swap_extent);
3090 
3091 /*
3092  * A `swap extent' is a simple thing which maps a contiguous range of pages
3093  * onto a contiguous range of disk blocks.  A rbtree of swap extents is
3094  * built at swapon time and is then used at swap_writeout/swap_read_folio
3095  * time for locating where on disk a page belongs.
3096  *
3097  * If the swapfile is an S_ISBLK block device, a single extent is installed.
3098  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
3099  * swap files identically.
3100  *
3101  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
3102  * extent rbtree operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
3103  * swapfiles are handled *identically* after swapon time.
3104  *
3105  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
3106  * and will parse them into a rbtree, in PAGE_SIZE chunks.  If some stray
3107  * blocks are found which do not fall within the PAGE_SIZE alignment
3108  * requirements, they are simply tossed out - we will never use those blocks
3109  * for swapping.
3110  *
3111  * For all swap devices we set S_SWAPFILE across the life of the swapon.  This
3112  * prevents users from writing to the swap device, which will corrupt memory.
3113  *
3114  * The amount of disk space which a single swap extent represents varies.
3115  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
3116  * extents in the rbtree. - akpm.
3117  */
3118 static int setup_swap_extents(struct swap_info_struct *sis,
3119 			      struct file *swap_file, sector_t *span)
3120 {
3121 	struct address_space *mapping = swap_file->f_mapping;
3122 	struct inode *inode = mapping->host;
3123 	int ret;
3124 
3125 	ret = sio_pool_init();
3126 	if (ret)
3127 		return ret;
3128 
3129 	sis->ops = &swap_bdev_ops;
3130 
3131 	if (S_ISBLK(inode->i_mode)) {
3132 		ret = add_swap_extent(sis, 0, sis->max, 0);
3133 		*span = sis->pages;
3134 		return ret;
3135 	}
3136 
3137 	if (mapping->a_ops->swap_activate) {
3138 		ret = mapping->a_ops->swap_activate(sis, swap_file, span);
3139 		if (ret < 0)
3140 			return ret;
3141 		sis->flags |= SWP_ACTIVATED;
3142 		return ret;
3143 	}
3144 
3145 	return generic_swapfile_activate(sis, swap_file, span);
3146 }
3147 
3148 static void _enable_swap_info(struct swap_info_struct *si)
3149 {
3150 	atomic_long_add(si->pages, &nr_swap_pages);
3151 	total_swap_pages += si->pages;
3152 
3153 	assert_spin_locked(&swap_lock);
3154 
3155 	plist_add(&si->list, &swap_active_head);
3156 
3157 	/* Add back to available list */
3158 	add_to_avail_list(si, true);
3159 }
3160 
3161 /*
3162  * Called after the swap device is ready, resurrect its percpu ref, it's now
3163  * safe to reference it. Add it to the list to expose it to the allocator.
3164  */
3165 static void enable_swap_info(struct swap_info_struct *si)
3166 {
3167 	percpu_ref_resurrect(&si->users);
3168 	spin_lock(&swap_lock);
3169 	spin_lock(&si->lock);
3170 	_enable_swap_info(si);
3171 	spin_unlock(&si->lock);
3172 	spin_unlock(&swap_lock);
3173 }
3174 
3175 static void reinsert_swap_info(struct swap_info_struct *si)
3176 {
3177 	spin_lock(&swap_lock);
3178 	spin_lock(&si->lock);
3179 	_enable_swap_info(si);
3180 	spin_unlock(&si->lock);
3181 	spin_unlock(&swap_lock);
3182 }
3183 
3184 /*
3185  * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range
3186  * see the updated flags, so there will be no more allocations.
3187  */
3188 static void wait_for_allocation(struct swap_info_struct *si)
3189 {
3190 	unsigned long offset;
3191 	unsigned long end = ALIGN(si->max, SWAPFILE_CLUSTER);
3192 	struct swap_cluster_info *ci;
3193 
3194 	BUG_ON(si->flags & SWP_WRITEOK);
3195 
3196 	for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) {
3197 		ci = swap_cluster_lock(si, offset);
3198 		swap_cluster_unlock(ci);
3199 	}
3200 }
3201 
3202 static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
3203 				   unsigned long maxpages)
3204 {
3205 	struct swap_cluster_info *ci;
3206 	int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3207 
3208 	if (!cluster_info)
3209 		return;
3210 	for (i = 0; i < nr_clusters; i++) {
3211 		ci = cluster_info + i;
3212 		/* Cluster with bad marks count will have a remaining table */
3213 		spin_lock(&ci->lock);
3214 		if (cluster_table_is_alloced(ci)) {
3215 			swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);
3216 			swap_cluster_free_table(ci);
3217 		}
3218 		spin_unlock(&ci->lock);
3219 	}
3220 	kvfree(cluster_info);
3221 }
3222 
3223 /*
3224  * Called after swap device's reference count is dead, so
3225  * neither scan nor allocation will use it.
3226  */
3227 static void flush_percpu_swap_cluster(struct swap_info_struct *si)
3228 {
3229 	int cpu, i;
3230 	struct swap_info_struct **pcp_si;
3231 
3232 	for_each_possible_cpu(cpu) {
3233 		pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);
3234 		/*
3235 		 * Invalidate the percpu swap cluster cache, si->users
3236 		 * is dead, so no new user will point to it, just flush
3237 		 * any existing user.
3238 		 */
3239 		for (i = 0; i < SWAP_NR_ORDERS; i++)
3240 			cmpxchg(&pcp_si[i], si, NULL);
3241 	}
3242 }
3243 
3244 
3245 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
3246 {
3247 	struct swap_info_struct *p = NULL;
3248 	struct swap_cluster_info *cluster_info;
3249 	struct file *swap_file, *victim;
3250 	struct address_space *mapping;
3251 	struct inode *inode;
3252 	unsigned int maxpages;
3253 	int err, found = 0;
3254 
3255 	if (!capable(CAP_SYS_ADMIN))
3256 		return -EPERM;
3257 
3258 	BUG_ON(!current->mm);
3259 
3260 	CLASS(filename, pathname)(specialfile);
3261 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
3262 	if (IS_ERR(victim))
3263 		return PTR_ERR(victim);
3264 
3265 	mapping = victim->f_mapping;
3266 	spin_lock(&swap_lock);
3267 	plist_for_each_entry(p, &swap_active_head, list) {
3268 		if (p->flags & SWP_WRITEOK) {
3269 			if (p->swap_file->f_mapping == mapping) {
3270 				found = 1;
3271 				break;
3272 			}
3273 		}
3274 	}
3275 	if (!found) {
3276 		err = -EINVAL;
3277 		spin_unlock(&swap_lock);
3278 		goto out_dput;
3279 	}
3280 
3281 	/* Refuse swapoff while the device is pinned for hibernation */
3282 	if (p->flags & SWP_HIBERNATION) {
3283 		err = -EBUSY;
3284 		spin_unlock(&swap_lock);
3285 		goto out_dput;
3286 	}
3287 
3288 	if (!security_vm_enough_memory_mm(current->mm, p->pages))
3289 		vm_unacct_memory(p->pages);
3290 	else {
3291 		err = -ENOMEM;
3292 		spin_unlock(&swap_lock);
3293 		goto out_dput;
3294 	}
3295 	spin_lock(&p->lock);
3296 	del_from_avail_list(p, true);
3297 	plist_del(&p->list, &swap_active_head);
3298 	atomic_long_sub(p->pages, &nr_swap_pages);
3299 	total_swap_pages -= p->pages;
3300 	spin_unlock(&p->lock);
3301 	spin_unlock(&swap_lock);
3302 
3303 	wait_for_allocation(p);
3304 
3305 	set_current_oom_origin();
3306 	err = try_to_unuse(p->type);
3307 	clear_current_oom_origin();
3308 
3309 	if (err) {
3310 		/* re-insert swap space back into swap_list */
3311 		reinsert_swap_info(p);
3312 		goto out_dput;
3313 	}
3314 
3315 	/*
3316 	 * Wait for swap operations protected by get/put_swap_device()
3317 	 * to complete.  Because of synchronize_rcu() here, all swap
3318 	 * operations protected by RCU reader side lock (including any
3319 	 * spinlock) will be waited too.  This makes it easy to
3320 	 * prevent folio_test_swapcache() and the following swap cache
3321 	 * operations from racing with swapoff.
3322 	 */
3323 	percpu_ref_kill(&p->users);
3324 	synchronize_rcu();
3325 	wait_for_completion(&p->comp);
3326 
3327 	flush_work(&p->discard_work);
3328 	flush_work(&p->reclaim_work);
3329 	flush_percpu_swap_cluster(p);
3330 
3331 	destroy_swap_extents(p, p->swap_file);
3332 
3333 	if (!(p->flags & SWP_SOLIDSTATE))
3334 		atomic_dec(&nr_rotate_swap);
3335 
3336 	mutex_lock(&swapon_mutex);
3337 	spin_lock(&swap_lock);
3338 	spin_lock(&p->lock);
3339 	drain_mmlist();
3340 
3341 	swap_file = p->swap_file;
3342 	p->swap_file = NULL;
3343 	maxpages = p->max;
3344 	cluster_info = p->cluster_info;
3345 	p->max = 0;
3346 	p->cluster_info = NULL;
3347 	spin_unlock(&p->lock);
3348 	spin_unlock(&swap_lock);
3349 	arch_swap_invalidate_area(p->type);
3350 	zswap_swapoff(p->type);
3351 	mutex_unlock(&swapon_mutex);
3352 	kfree(p->global_cluster);
3353 	p->global_cluster = NULL;
3354 	free_swap_cluster_info(cluster_info, maxpages);
3355 
3356 	inode = mapping->host;
3357 
3358 	inode_lock(inode);
3359 	inode->i_flags &= ~S_SWAPFILE;
3360 	inode_unlock(inode);
3361 	filp_close(swap_file, NULL);
3362 
3363 	/*
3364 	 * Clear the SWP_USED flag after all resources are freed so that swapon
3365 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
3366 	 * not hold p->lock after we cleared its SWP_WRITEOK.
3367 	 */
3368 	spin_lock(&swap_lock);
3369 	p->flags = 0;
3370 	spin_unlock(&swap_lock);
3371 
3372 	err = 0;
3373 	atomic_inc(&proc_poll_event);
3374 	wake_up_interruptible(&proc_poll_wait);
3375 
3376 out_dput:
3377 	filp_close(victim, NULL);
3378 	return err;
3379 }
3380 
3381 #ifdef CONFIG_PROC_FS
3382 static __poll_t swaps_poll(struct file *file, poll_table *wait)
3383 {
3384 	struct seq_file *seq = file->private_data;
3385 
3386 	poll_wait(file, &proc_poll_wait, wait);
3387 
3388 	if (seq->poll_event != atomic_read(&proc_poll_event)) {
3389 		seq->poll_event = atomic_read(&proc_poll_event);
3390 		return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
3391 	}
3392 
3393 	return EPOLLIN | EPOLLRDNORM;
3394 }
3395 
3396 /* iterator */
3397 static void *swap_start(struct seq_file *swap, loff_t *pos)
3398 {
3399 	struct swap_info_struct *si;
3400 	int type;
3401 	loff_t l = *pos;
3402 
3403 	mutex_lock(&swapon_mutex);
3404 
3405 	if (!l)
3406 		return SEQ_START_TOKEN;
3407 
3408 	for (type = 0; (si = swap_type_to_info(type)); type++) {
3409 		if (!(si->swap_file))
3410 			continue;
3411 		if (!--l)
3412 			return si;
3413 	}
3414 
3415 	return NULL;
3416 }
3417 
3418 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
3419 {
3420 	struct swap_info_struct *si = v;
3421 	int type;
3422 
3423 	if (v == SEQ_START_TOKEN)
3424 		type = 0;
3425 	else
3426 		type = si->type + 1;
3427 
3428 	++(*pos);
3429 	for (; (si = swap_type_to_info(type)); type++) {
3430 		if (!(si->swap_file))
3431 			continue;
3432 		return si;
3433 	}
3434 
3435 	return NULL;
3436 }
3437 
3438 static void swap_stop(struct seq_file *swap, void *v)
3439 {
3440 	mutex_unlock(&swapon_mutex);
3441 }
3442 
3443 static int swap_show(struct seq_file *swap, void *v)
3444 {
3445 	struct swap_info_struct *si = v;
3446 	struct file *file;
3447 	int len;
3448 	unsigned long bytes, inuse;
3449 
3450 	if (si == SEQ_START_TOKEN) {
3451 		seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
3452 		return 0;
3453 	}
3454 
3455 	bytes = K((unsigned long)si->pages);
3456 	inuse = K(swap_usage_in_pages(si));
3457 
3458 	file = si->swap_file;
3459 	len = seq_file_path(swap, file, " \t\n\\");
3460 	seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
3461 			len < 40 ? 40 - len : 1, " ",
3462 			S_ISBLK(file_inode(file)->i_mode) ?
3463 				"partition" : "file\t",
3464 			bytes, bytes < 10000000 ? "\t" : "",
3465 			inuse, inuse < 10000000 ? "\t" : "",
3466 			si->prio);
3467 	return 0;
3468 }
3469 
3470 static const struct seq_operations swaps_op = {
3471 	.start =	swap_start,
3472 	.next =		swap_next,
3473 	.stop =		swap_stop,
3474 	.show =		swap_show
3475 };
3476 
3477 static int swaps_open(struct inode *inode, struct file *file)
3478 {
3479 	struct seq_file *seq;
3480 	int ret;
3481 
3482 	ret = seq_open(file, &swaps_op);
3483 	if (ret)
3484 		return ret;
3485 
3486 	seq = file->private_data;
3487 	seq->poll_event = atomic_read(&proc_poll_event);
3488 	return 0;
3489 }
3490 
3491 static const struct proc_ops swaps_proc_ops = {
3492 	.proc_flags	= PROC_ENTRY_PERMANENT,
3493 	.proc_open	= swaps_open,
3494 	.proc_read	= seq_read,
3495 	.proc_lseek	= seq_lseek,
3496 	.proc_release	= seq_release,
3497 	.proc_poll	= swaps_poll,
3498 };
3499 
3500 static int __init procswaps_init(void)
3501 {
3502 	proc_create("swaps", 0, NULL, &swaps_proc_ops);
3503 	return 0;
3504 }
3505 __initcall(procswaps_init);
3506 #endif /* CONFIG_PROC_FS */
3507 
3508 #ifdef MAX_SWAPFILES_CHECK
3509 static int __init max_swapfiles_check(void)
3510 {
3511 	MAX_SWAPFILES_CHECK();
3512 	return 0;
3513 }
3514 late_initcall(max_swapfiles_check);
3515 #endif
3516 
3517 static struct swap_info_struct *alloc_swap_info(void)
3518 {
3519 	struct swap_info_struct *p;
3520 	struct swap_info_struct *defer = NULL;
3521 	unsigned int type;
3522 
3523 	p = kvzalloc_obj(struct swap_info_struct);
3524 	if (!p)
3525 		return ERR_PTR(-ENOMEM);
3526 
3527 	if (percpu_ref_init(&p->users, swap_users_ref_free,
3528 			    PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {
3529 		kvfree(p);
3530 		return ERR_PTR(-ENOMEM);
3531 	}
3532 
3533 	spin_lock(&swap_lock);
3534 	for (type = 0; type < nr_swapfiles; type++) {
3535 		if (!(swap_info[type]->flags & SWP_USED))
3536 			break;
3537 	}
3538 	if (type >= MAX_SWAPFILES) {
3539 		spin_unlock(&swap_lock);
3540 		percpu_ref_exit(&p->users);
3541 		kvfree(p);
3542 		return ERR_PTR(-EPERM);
3543 	}
3544 	if (type >= nr_swapfiles) {
3545 		p->type = type;
3546 		/*
3547 		 * Publish the swap_info_struct after initializing it.
3548 		 * Note that kvzalloc() above zeroes all its fields.
3549 		 */
3550 		smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */
3551 		nr_swapfiles++;
3552 	} else {
3553 		defer = p;
3554 		p = swap_info[type];
3555 		/*
3556 		 * Do not memset this entry: a racing procfs swap_next()
3557 		 * would be relying on p->type to remain valid.
3558 		 */
3559 	}
3560 	p->swap_extent_root = RB_ROOT;
3561 	plist_node_init(&p->list, 0);
3562 	plist_node_init(&p->avail_list, 0);
3563 	p->flags = SWP_USED;
3564 	spin_unlock(&swap_lock);
3565 	if (defer) {
3566 		percpu_ref_exit(&defer->users);
3567 		kvfree(defer);
3568 	}
3569 	spin_lock_init(&p->lock);
3570 	atomic_long_set(&p->inuse_pages, SWAP_USAGE_OFFLIST_BIT);
3571 	init_completion(&p->comp);
3572 
3573 	return p;
3574 }
3575 
3576 static int claim_swapfile(struct swap_info_struct *si, struct inode *inode)
3577 {
3578 	if (S_ISBLK(inode->i_mode)) {
3579 		si->bdev = I_BDEV(inode);
3580 		/*
3581 		 * Zoned block devices contain zones that have a sequential
3582 		 * write only restriction.  Hence zoned block devices are not
3583 		 * suitable for swapping.  Disallow them here.
3584 		 */
3585 		if (bdev_is_zoned(si->bdev))
3586 			return -EINVAL;
3587 		si->flags |= SWP_BLKDEV;
3588 	} else if (S_ISREG(inode->i_mode)) {
3589 		si->bdev = inode->i_sb->s_bdev;
3590 	}
3591 
3592 	return 0;
3593 }
3594 
3595 
3596 /*
3597  * Find out how many pages are allowed for a single swap device. There
3598  * are two limiting factors:
3599  * 1) the number of bits for the swap offset in the swp_entry_t type, and
3600  * 2) the number of bits in the swap pte, as defined by the different
3601  * architectures.
3602  *
3603  * In order to find the largest possible bit mask, a swap entry with
3604  * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
3605  * decoded to a swp_entry_t again, and finally the swap offset is
3606  * extracted.
3607  *
3608  * This will mask all the bits from the initial ~0UL mask that can't
3609  * be encoded in either the swp_entry_t or the architecture definition
3610  * of a swap pte.
3611  */
3612 unsigned long generic_max_swapfile_size(void)
3613 {
3614 	swp_entry_t entry = swp_entry(0, ~0UL);
3615 	const pte_t pte = softleaf_to_pte(entry);
3616 
3617 	/*
3618 	 * Since the PTE can be an invalid softleaf entry (e.g. the none PTE),
3619 	 * we need to do this manually.
3620 	 */
3621 	entry = __pte_to_swp_entry(pte);
3622 	entry = swp_entry(__swp_type(entry), __swp_offset(entry));
3623 
3624 	return swp_offset(entry) + 1;
3625 }
3626 
3627 /* Can be overridden by an architecture for additional checks. */
3628 __weak unsigned long arch_max_swapfile_size(void)
3629 {
3630 	return generic_max_swapfile_size();
3631 }
3632 
3633 static unsigned long read_swap_header(struct swap_info_struct *si,
3634 					union swap_header *swap_header,
3635 					struct inode *inode)
3636 {
3637 	int i;
3638 	unsigned long maxpages;
3639 	unsigned long swapfilepages;
3640 	unsigned long last_page;
3641 
3642 	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
3643 		pr_err("Unable to find swap-space signature\n");
3644 		return 0;
3645 	}
3646 
3647 	/* swap partition endianness hack... */
3648 	if (swab32(swap_header->info.version) == 1) {
3649 		swab32s(&swap_header->info.version);
3650 		swab32s(&swap_header->info.last_page);
3651 		swab32s(&swap_header->info.nr_badpages);
3652 		if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3653 			return 0;
3654 		for (i = 0; i < swap_header->info.nr_badpages; i++)
3655 			swab32s(&swap_header->info.badpages[i]);
3656 	}
3657 	/* Check the swap header's sub-version */
3658 	if (swap_header->info.version != 1) {
3659 		pr_warn("Unable to handle swap header version %d\n",
3660 			swap_header->info.version);
3661 		return 0;
3662 	}
3663 
3664 	maxpages = swapfile_maximum_size;
3665 	last_page = swap_header->info.last_page;
3666 	if (!last_page) {
3667 		pr_warn("Empty swap-file\n");
3668 		return 0;
3669 	}
3670 	if (last_page > maxpages) {
3671 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
3672 			K(maxpages), K(last_page));
3673 	}
3674 	if (maxpages > last_page) {
3675 		maxpages = last_page + 1;
3676 		/* p->max is an unsigned int: don't overflow it */
3677 		if ((unsigned int)maxpages == 0)
3678 			maxpages = UINT_MAX;
3679 	}
3680 
3681 	if (!maxpages)
3682 		return 0;
3683 	swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
3684 	if (swapfilepages && maxpages > swapfilepages) {
3685 		pr_warn("Swap area shorter than signature indicates\n");
3686 		return 0;
3687 	}
3688 	if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
3689 		return 0;
3690 	if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3691 		return 0;
3692 
3693 	return maxpages;
3694 }
3695 
3696 static int setup_swap_clusters_info(struct swap_info_struct *si,
3697 				    union swap_header *swap_header,
3698 				    unsigned long maxpages)
3699 {
3700 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3701 	struct swap_cluster_info *cluster_info;
3702 	int err = -ENOMEM;
3703 	unsigned long i;
3704 
3705 	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
3706 	if (!cluster_info)
3707 		goto err;
3708 
3709 	for (i = 0; i < nr_clusters; i++)
3710 		spin_lock_init(&cluster_info[i].lock);
3711 
3712 	if (!(si->flags & SWP_SOLIDSTATE)) {
3713 		si->global_cluster = kmalloc_obj(*si->global_cluster);
3714 		if (!si->global_cluster)
3715 			goto err;
3716 		for (i = 0; i < SWAP_NR_ORDERS; i++)
3717 			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
3718 		spin_lock_init(&si->global_cluster_lock);
3719 	}
3720 
3721 	/*
3722 	 * Mark unusable pages (header page, bad pages, and the EOF part of
3723 	 * the last cluster) as unavailable. The clusters aren't marked free
3724 	 * yet, so no list operations are involved yet.
3725 	 */
3726 	err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false);
3727 	if (err)
3728 		goto err;
3729 	for (i = 0; i < swap_header->info.nr_badpages; i++) {
3730 		unsigned int page_nr = swap_header->info.badpages[i];
3731 
3732 		if (!page_nr || page_nr > swap_header->info.last_page) {
3733 			pr_warn("Bad slot offset is out of border: %d (last_page: %d)\n",
3734 				page_nr, swap_header->info.last_page);
3735 			err = -EINVAL;
3736 			goto err;
3737 		}
3738 		err = swap_cluster_setup_bad_slot(si, cluster_info, page_nr, false);
3739 		if (err)
3740 			goto err;
3741 	}
3742 	for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) {
3743 		err = swap_cluster_setup_bad_slot(si, cluster_info, i, true);
3744 		if (err)
3745 			goto err;
3746 	}
3747 
3748 	INIT_LIST_HEAD(&si->free_clusters);
3749 	INIT_LIST_HEAD(&si->full_clusters);
3750 	INIT_LIST_HEAD(&si->discard_clusters);
3751 
3752 	for (i = 0; i < SWAP_NR_ORDERS; i++) {
3753 		INIT_LIST_HEAD(&si->nonfull_clusters[i]);
3754 		INIT_LIST_HEAD(&si->frag_clusters[i]);
3755 	}
3756 
3757 	for (i = 0; i < nr_clusters; i++) {
3758 		struct swap_cluster_info *ci = &cluster_info[i];
3759 
3760 		if (ci->count) {
3761 			ci->flags = CLUSTER_FLAG_NONFULL;
3762 			list_add_tail(&ci->list, &si->nonfull_clusters[0]);
3763 		} else {
3764 			ci->flags = CLUSTER_FLAG_FREE;
3765 			list_add_tail(&ci->list, &si->free_clusters);
3766 		}
3767 	}
3768 
3769 	si->cluster_info = cluster_info;
3770 	return 0;
3771 err:
3772 	free_swap_cluster_info(cluster_info, maxpages);
3773 	return err;
3774 }
3775 
3776 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
3777 {
3778 	struct swap_info_struct *si;
3779 	struct file *swap_file = NULL;
3780 	struct address_space *mapping;
3781 	struct dentry *dentry;
3782 	int prio;
3783 	int error;
3784 	union swap_header *swap_header;
3785 	int nr_extents;
3786 	sector_t span;
3787 	unsigned long maxpages;
3788 	struct folio *folio = NULL;
3789 	struct inode *inode = NULL;
3790 	bool inced_nr_rotate_swap = false;
3791 
3792 	if (swap_flags & ~SWAP_FLAGS_VALID)
3793 		return -EINVAL;
3794 
3795 	if (!capable(CAP_SYS_ADMIN))
3796 		return -EPERM;
3797 
3798 	/*
3799 	 * Allocate or reuse existing !SWP_USED swap_info. The returned
3800 	 * si will stay in a dying status, so nothing will access its content
3801 	 * until enable_swap_info resurrects its percpu ref and expose it.
3802 	 */
3803 	si = alloc_swap_info();
3804 	if (IS_ERR(si))
3805 		return PTR_ERR(si);
3806 
3807 	INIT_WORK(&si->discard_work, swap_discard_work);
3808 	INIT_WORK(&si->reclaim_work, swap_reclaim_work);
3809 
3810 	CLASS(filename, name)(specialfile);
3811 	swap_file = file_open_name(name, O_RDWR | O_LARGEFILE | O_EXCL, 0);
3812 	if (IS_ERR(swap_file)) {
3813 		error = PTR_ERR(swap_file);
3814 		swap_file = NULL;
3815 		goto bad_swap;
3816 	}
3817 
3818 	mapping = swap_file->f_mapping;
3819 	dentry = swap_file->f_path.dentry;
3820 	inode = mapping->host;
3821 
3822 	error = claim_swapfile(si, inode);
3823 	if (unlikely(error))
3824 		goto bad_swap;
3825 
3826 	inode_lock(inode);
3827 	if (d_unlinked(dentry) || cant_mount(dentry)) {
3828 		error = -ENOENT;
3829 		goto bad_swap_unlock_inode;
3830 	}
3831 	if (IS_SWAPFILE(inode)) {
3832 		error = -EBUSY;
3833 		goto bad_swap_unlock_inode;
3834 	}
3835 	if (IS_ENCRYPTED(inode)) {
3836 		pr_warn_once(
3837 			"Filesystem-level encrypted swapfile '%s' is unsupported. Create a loop device over it, or use dm-crypt\n",
3838 			name->name);
3839 		error = -EINVAL;
3840 		goto bad_swap_unlock_inode;
3841 	}
3842 
3843 	/*
3844 	 * The swap subsystem needs a major overhaul to support this.
3845 	 * It doesn't work yet so just disable it for now.
3846 	 */
3847 	if (mapping_min_folio_order(mapping) > 0) {
3848 		error = -EINVAL;
3849 		goto bad_swap_unlock_inode;
3850 	}
3851 
3852 	/*
3853 	 * Read the swap header.
3854 	 */
3855 	if (!mapping->a_ops->read_folio) {
3856 		error = -EINVAL;
3857 		goto bad_swap_unlock_inode;
3858 	}
3859 	folio = read_mapping_folio(mapping, 0, swap_file);
3860 	if (IS_ERR(folio)) {
3861 		error = PTR_ERR(folio);
3862 		goto bad_swap_unlock_inode;
3863 	}
3864 	swap_header = kmap_local_folio(folio, 0);
3865 
3866 	maxpages = read_swap_header(si, swap_header, inode);
3867 	if (unlikely(!maxpages)) {
3868 		error = -EINVAL;
3869 		goto bad_swap_unlock_inode;
3870 	}
3871 
3872 	si->max = maxpages;
3873 	si->pages = maxpages - 1;
3874 	nr_extents = setup_swap_extents(si, swap_file, &span);
3875 	if (nr_extents < 0) {
3876 		error = nr_extents;
3877 		goto bad_swap_unlock_inode;
3878 	}
3879 	if (si->pages != si->max - 1) {
3880 		pr_err("swap:%u != (max:%u - 1)\n", si->pages, si->max);
3881 		error = -EINVAL;
3882 		goto bad_swap_unlock_inode;
3883 	}
3884 
3885 	maxpages = si->max;
3886 
3887 	if (si->bdev && bdev_stable_writes(si->bdev))
3888 		si->flags |= SWP_STABLE_WRITES;
3889 
3890 	if (si->bdev && bdev_synchronous(si->bdev))
3891 		si->flags |= SWP_SYNCHRONOUS_IO;
3892 
3893 	if (si->bdev && !bdev_rot(si->bdev)) {
3894 		si->flags |= SWP_SOLIDSTATE;
3895 	} else {
3896 		atomic_inc(&nr_rotate_swap);
3897 		inced_nr_rotate_swap = true;
3898 	}
3899 
3900 	/*
3901 	 * Set up the swap cluster info after SWP_ flags handling as
3902 	 * setup_swap_clusters_info() checks SWP_SOLIDSTATE.
3903 	 */
3904 	error = setup_swap_clusters_info(si, swap_header, maxpages);
3905 	if (error)
3906 		goto bad_swap_unlock_inode;
3907 
3908 	if ((swap_flags & SWAP_FLAG_DISCARD) &&
3909 	    si->bdev && bdev_max_discard_sectors(si->bdev)) {
3910 		/*
3911 		 * When discard is enabled for swap with no particular
3912 		 * policy flagged, we set all swap discard flags here in
3913 		 * order to sustain backward compatibility with older
3914 		 * swapon(8) releases.
3915 		 */
3916 		si->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3917 			     SWP_PAGE_DISCARD);
3918 
3919 		/*
3920 		 * By flagging sys_swapon, a sysadmin can tell us to
3921 		 * either do single-time area discards only, or to just
3922 		 * perform discards for released swap page-clusters.
3923 		 * Now it's time to adjust the p->flags accordingly.
3924 		 */
3925 		if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3926 			si->flags &= ~SWP_PAGE_DISCARD;
3927 		else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3928 			si->flags &= ~SWP_AREA_DISCARD;
3929 
3930 		/* issue a swapon-time discard if it's still required */
3931 		if (si->flags & SWP_AREA_DISCARD) {
3932 			int err = discard_swap(si);
3933 			if (unlikely(err))
3934 				pr_err("swapon: discard_swap(%p): %d\n",
3935 					si, err);
3936 		}
3937 	}
3938 
3939 	error = zswap_swapon(si->type, maxpages);
3940 	if (error)
3941 		goto bad_swap_unlock_inode;
3942 
3943 	/*
3944 	 * Flush any pending IO and dirty mappings before we start using this
3945 	 * swap device.
3946 	 */
3947 	inode->i_flags |= S_SWAPFILE;
3948 	error = inode_drain_writes(inode);
3949 	if (error) {
3950 		inode->i_flags &= ~S_SWAPFILE;
3951 		goto free_swap_zswap;
3952 	}
3953 
3954 	mutex_lock(&swapon_mutex);
3955 	prio = DEF_SWAP_PRIO;
3956 	if (swap_flags & SWAP_FLAG_PREFER)
3957 		prio = swap_flags & SWAP_FLAG_PRIO_MASK;
3958 
3959 	/*
3960 	 * The plist prio is negated because plist ordering is
3961 	 * low-to-high, while swap ordering is high-to-low
3962 	 */
3963 	si->prio = prio;
3964 	si->list.prio = -si->prio;
3965 	si->avail_list.prio = -si->prio;
3966 	si->swap_file = swap_file;
3967 
3968 	/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */
3969 	enable_swap_info(si);
3970 
3971 	pr_info("Adding %luk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
3972 		K((unsigned long)si->pages), name->name, si->prio, nr_extents,
3973 		K((unsigned long long)span),
3974 		(si->flags & SWP_SOLIDSTATE) ? "SS" : "",
3975 		(si->flags & SWP_DISCARDABLE) ? "D" : "",
3976 		(si->flags & SWP_AREA_DISCARD) ? "s" : "",
3977 		(si->flags & SWP_PAGE_DISCARD) ? "c" : "");
3978 
3979 	mutex_unlock(&swapon_mutex);
3980 	atomic_inc(&proc_poll_event);
3981 	wake_up_interruptible(&proc_poll_wait);
3982 
3983 	error = 0;
3984 	goto out;
3985 free_swap_zswap:
3986 	zswap_swapoff(si->type);
3987 bad_swap_unlock_inode:
3988 	inode_unlock(inode);
3989 bad_swap:
3990 	kfree(si->global_cluster);
3991 	si->global_cluster = NULL;
3992 	inode = NULL;
3993 	destroy_swap_extents(si, swap_file);
3994 	free_swap_cluster_info(si->cluster_info, si->max);
3995 	si->cluster_info = NULL;
3996 	/*
3997 	 * Clear the SWP_USED flag after all resources are freed so
3998 	 * alloc_swap_info can reuse this si safely.
3999 	 */
4000 	spin_lock(&swap_lock);
4001 	si->flags = 0;
4002 	spin_unlock(&swap_lock);
4003 	if (inced_nr_rotate_swap)
4004 		atomic_dec(&nr_rotate_swap);
4005 	if (swap_file)
4006 		filp_close(swap_file, NULL);
4007 out:
4008 	if (!IS_ERR_OR_NULL(folio))
4009 		folio_release_kmap(folio, swap_header);
4010 	if (inode)
4011 		inode_unlock(inode);
4012 	return error;
4013 }
4014 
4015 void si_swapinfo(struct sysinfo *val)
4016 {
4017 	unsigned int type;
4018 	unsigned long nr_to_be_unused = 0;
4019 
4020 	spin_lock(&swap_lock);
4021 	for (type = 0; type < nr_swapfiles; type++) {
4022 		struct swap_info_struct *si = swap_info[type];
4023 
4024 		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
4025 			nr_to_be_unused += swap_usage_in_pages(si);
4026 	}
4027 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
4028 	val->totalswap = total_swap_pages + nr_to_be_unused;
4029 	spin_unlock(&swap_lock);
4030 }
4031 
4032 /*
4033  * swap_dup_entry_direct() - Increase reference count of a swap entry by one.
4034  * @entry: first swap entry from which we want to increase the refcount.
4035  *
4036  * Returns 0 for success, or -ENOMEM if the extend table is required
4037  * but could not be atomically allocated.  Returns -EINVAL if the swap
4038  * entry is invalid, which might occur if a page table entry has got
4039  * corrupted.
4040  *
4041  * Context: Caller must ensure there is no race condition on the reference
4042  * owner. e.g., locking the PTL of a PTE containing the entry being increased.
4043  * Also the swap entry must have a count >= 1. Otherwise folio_dup_swap should
4044  * be used.
4045  */
4046 int swap_dup_entry_direct(swp_entry_t entry)
4047 {
4048 	struct swap_info_struct *si;
4049 
4050 	si = swap_entry_to_info(entry);
4051 	if (WARN_ON_ONCE(!si)) {
4052 		pr_err_ratelimited("%s%08lx\n", Bad_file, entry.val);
4053 		return -EINVAL;
4054 	}
4055 
4056 	/*
4057 	 * The caller must be increasing the swap count from a direct
4058 	 * reference of the swap slot (e.g. a swap entry in page table).
4059 	 * So the swap count must be >= 1.
4060 	 */
4061 	VM_WARN_ON_ONCE(!swap_entry_swapped(si, entry));
4062 
4063 	return swap_dup_entries_cluster(si, swp_offset(entry), 1);
4064 }
4065 
4066 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
4067 static bool __has_usable_swap(void)
4068 {
4069 	return !plist_head_empty(&swap_active_head);
4070 }
4071 
4072 void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
4073 {
4074 	struct swap_info_struct *si;
4075 
4076 	if (!(gfp & __GFP_IO))
4077 		return;
4078 
4079 	if (!__has_usable_swap())
4080 		return;
4081 
4082 	if (!blk_cgroup_congested())
4083 		return;
4084 
4085 	/*
4086 	 * We've already scheduled a throttle, avoid taking the global swap
4087 	 * lock.
4088 	 */
4089 	if (current->throttle_disk)
4090 		return;
4091 
4092 	spin_lock(&swap_avail_lock);
4093 	plist_for_each_entry(si, &swap_avail_head, avail_list) {
4094 		if (si->bdev) {
4095 			blkcg_schedule_throttle(si->bdev->bd_disk, true);
4096 			break;
4097 		}
4098 	}
4099 	spin_unlock(&swap_avail_lock);
4100 }
4101 #endif
4102 
4103 static int __init swapfile_init(void)
4104 {
4105 	swapfile_maximum_size = arch_max_swapfile_size();
4106 
4107 	/*
4108 	 * Once a cluster is freed, it's swap table content is read
4109 	 * only, and all swap cache readers (swap_cache_*) verifies
4110 	 * the content before use. So it's safe to use RCU slab here.
4111 	 */
4112 	if (!SWP_TABLE_USE_PAGE)
4113 		swap_table_cachep = kmem_cache_create("swap_table",
4114 				    sizeof(struct swap_table),
4115 				    0, SLAB_PANIC | SLAB_TYPESAFE_BY_RCU, NULL);
4116 
4117 #ifdef CONFIG_MIGRATION
4118 	if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS))
4119 		swap_migration_ad_supported = true;
4120 #endif	/* CONFIG_MIGRATION */
4121 
4122 	return 0;
4123 }
4124 subsys_initcall(swapfile_init);
4125