xref: /linux/mm/swapfile.c (revision 65f208e1e60850d6cb812661289d67ac12da37cd)
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 	/*
2578 	 * A large folio that a fault didn't map can't be mapped one PTE at a
2579 	 * time here, so drop it and swap in small folios instead.
2580 	 */
2581 	if (unlikely(!swap_cache_folio_mappable(folio, 1))) {
2582 		swap_cache_del_folio(folio);
2583 		return 0;
2584 	}
2585 
2586 	swapcache = folio;
2587 	folio = ksm_might_need_to_copy(folio,
2588 				       folio_file_page(folio, swp_offset(entry)), vma, addr);
2589 	if (unlikely(!folio))
2590 		return -ENOMEM;
2591 	else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
2592 		hwpoisoned = true;
2593 		folio = swapcache;
2594 	}
2595 
2596 	page = folio_file_page(folio, swp_offset(entry));
2597 	if (PageHWPoison(page))
2598 		hwpoisoned = true;
2599 
2600 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
2601 	if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte),
2602 						swp_entry_to_pte(entry)))) {
2603 		ret = 0;
2604 		goto out;
2605 	}
2606 
2607 	old_pte = ptep_get(pte);
2608 
2609 	if (unlikely(hwpoisoned || !folio_test_uptodate(folio))) {
2610 		swp_entry_t swp_entry;
2611 
2612 		dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
2613 		if (hwpoisoned) {
2614 			swp_entry = make_hwpoison_entry(page);
2615 		} else {
2616 			swp_entry = make_poisoned_swp_entry();
2617 		}
2618 		new_pte = swp_entry_to_pte(swp_entry);
2619 		ret = 0;
2620 		goto setpte;
2621 	}
2622 
2623 	/*
2624 	 * Some architectures may have to restore extra metadata to the page
2625 	 * when reading from swap. This metadata may be indexed by swap entry
2626 	 * so this must be called before folio_put_swap().
2627 	 */
2628 	arch_swap_restore(folio_swap(entry, folio), folio);
2629 
2630 	dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
2631 	inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
2632 	folio_get(folio);
2633 	if (folio == swapcache) {
2634 		rmap_t rmap_flags = RMAP_NONE;
2635 
2636 		/*
2637 		 * See do_swap_page(): writeback would be problematic.
2638 		 * However, we do a folio_wait_writeback() just before this
2639 		 * call and have the folio locked.
2640 		 */
2641 		VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio);
2642 		if (pte_swp_exclusive(old_pte))
2643 			rmap_flags |= RMAP_EXCLUSIVE;
2644 		/*
2645 		 * We currently only expect small !anon folios, which are either
2646 		 * fully exclusive or fully shared. If we ever get large folios
2647 		 * here, we have to be careful.
2648 		 */
2649 		if (!folio_test_anon(folio)) {
2650 			VM_WARN_ON_ONCE(folio_test_large(folio));
2651 			VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
2652 			folio_add_new_anon_rmap(folio, vma, addr, rmap_flags);
2653 		} else {
2654 			folio_add_anon_rmap_pte(folio, page, vma, addr, rmap_flags);
2655 		}
2656 	} else { /* ksm created a completely new copy */
2657 		folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
2658 		folio_add_lru_vma(folio, vma);
2659 	}
2660 	new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot));
2661 	if (pte_swp_soft_dirty(old_pte))
2662 		new_pte = pte_mksoft_dirty(new_pte);
2663 	if (pte_swp_uffd(old_pte))
2664 		new_pte = pte_mkuffd(new_pte);
2665 
2666 	/* See do_swap_page(): restore PAGE_NONE for RWP */
2667 	if (pte_swp_uffd(old_pte) && userfaultfd_rwp(vma))
2668 		new_pte = pte_modify(new_pte, PAGE_NONE);
2669 
2670 setpte:
2671 	set_pte_at(vma->vm_mm, addr, pte, new_pte);
2672 	folio_put_swap(swapcache, folio_file_page(swapcache, swp_offset(entry)));
2673 out:
2674 	if (pte)
2675 		pte_unmap_unlock(pte, ptl);
2676 	if (folio != swapcache) {
2677 		folio_unlock(folio);
2678 		folio_put(folio);
2679 	}
2680 	return ret;
2681 }
2682 
2683 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
2684 			unsigned long addr, unsigned long end,
2685 			unsigned int type)
2686 {
2687 	pte_t *pte = NULL;
2688 
2689 	do {
2690 		struct folio *folio;
2691 		unsigned long swp_tb;
2692 		softleaf_t entry;
2693 		int ret;
2694 		pte_t ptent;
2695 
2696 		if (!pte++) {
2697 			pte = pte_offset_map(pmd, addr);
2698 			if (!pte)
2699 				break;
2700 		}
2701 
2702 		ptent = ptep_get_lockless(pte);
2703 		entry = softleaf_from_pte(ptent);
2704 
2705 		if (!softleaf_is_swap(entry))
2706 			continue;
2707 		if (swp_type(entry) != type)
2708 			continue;
2709 
2710 		pte_unmap(pte);
2711 		pte = NULL;
2712 
2713 		folio = swap_cache_get_folio(entry);
2714 		if (!folio) {
2715 			struct vm_fault vmf = {
2716 				.vma = vma,
2717 				.address = addr,
2718 				.real_address = addr,
2719 				.pmd = pmd,
2720 			};
2721 
2722 			folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
2723 						&vmf);
2724 		}
2725 		if (!folio) {
2726 			swp_tb = swap_table_get(__swap_entry_to_cluster(entry),
2727 						swp_cluster_offset(entry));
2728 			if (swp_tb_get_count(swp_tb) <= 0)
2729 				continue;
2730 			return -ENOMEM;
2731 		}
2732 
2733 		folio_lock(folio);
2734 		folio_wait_writeback(folio);
2735 		ret = unuse_pte(vma, pmd, addr, entry, folio);
2736 		if (ret < 0) {
2737 			folio_unlock(folio);
2738 			folio_put(folio);
2739 			return ret;
2740 		}
2741 
2742 		folio_free_swap(folio);
2743 		folio_unlock(folio);
2744 		folio_put(folio);
2745 	} while (addr += PAGE_SIZE, addr != end);
2746 
2747 	if (pte)
2748 		pte_unmap(pte);
2749 	return 0;
2750 }
2751 
2752 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
2753 				unsigned long addr, unsigned long end,
2754 				unsigned int type)
2755 {
2756 	pmd_t *pmd;
2757 	unsigned long next;
2758 	int ret;
2759 
2760 	pmd = pmd_offset(pud, addr);
2761 	do {
2762 		cond_resched();
2763 		if (signal_pending(current))
2764 			return -ERESTARTSYS;
2765 		next = pmd_addr_end(addr, end);
2766 		ret = unuse_pte_range(vma, pmd, addr, next, type);
2767 		if (ret)
2768 			return ret;
2769 	} while (pmd++, addr = next, addr != end);
2770 	return 0;
2771 }
2772 
2773 static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
2774 				unsigned long addr, unsigned long end,
2775 				unsigned int type)
2776 {
2777 	pud_t *pud;
2778 	unsigned long next;
2779 	int ret;
2780 
2781 	pud = pud_offset(p4d, addr);
2782 	do {
2783 		next = pud_addr_end(addr, end);
2784 		if (pud_none_or_clear_bad(pud))
2785 			continue;
2786 		ret = unuse_pmd_range(vma, pud, addr, next, type);
2787 		if (ret)
2788 			return ret;
2789 	} while (pud++, addr = next, addr != end);
2790 	return 0;
2791 }
2792 
2793 static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
2794 				unsigned long addr, unsigned long end,
2795 				unsigned int type)
2796 {
2797 	p4d_t *p4d;
2798 	unsigned long next;
2799 	int ret;
2800 
2801 	p4d = p4d_offset(pgd, addr);
2802 	do {
2803 		next = p4d_addr_end(addr, end);
2804 		if (p4d_none_or_clear_bad(p4d))
2805 			continue;
2806 		ret = unuse_pud_range(vma, p4d, addr, next, type);
2807 		if (ret)
2808 			return ret;
2809 	} while (p4d++, addr = next, addr != end);
2810 	return 0;
2811 }
2812 
2813 static int unuse_vma(struct vm_area_struct *vma, unsigned int type)
2814 {
2815 	pgd_t *pgd;
2816 	unsigned long addr, end, next;
2817 	int ret;
2818 
2819 	addr = vma->vm_start;
2820 	end = vma->vm_end;
2821 
2822 	pgd = pgd_offset(vma->vm_mm, addr);
2823 	do {
2824 		next = pgd_addr_end(addr, end);
2825 		if (pgd_none_or_clear_bad(pgd))
2826 			continue;
2827 		ret = unuse_p4d_range(vma, pgd, addr, next, type);
2828 		if (ret)
2829 			return ret;
2830 	} while (pgd++, addr = next, addr != end);
2831 	return 0;
2832 }
2833 
2834 static int unuse_mm(struct mm_struct *mm, unsigned int type)
2835 {
2836 	struct vm_area_struct *vma;
2837 	int ret = 0;
2838 	VMA_ITERATOR(vmi, mm, 0);
2839 
2840 	mmap_read_lock(mm);
2841 	if (check_stable_address_space(mm))
2842 		goto unlock;
2843 	for_each_vma(vmi, vma) {
2844 		if (vma_has_anon_rmap(vma) && !vma_is_hugetlb(vma)) {
2845 			ret = unuse_vma(vma, type);
2846 			if (ret)
2847 				break;
2848 		}
2849 
2850 		cond_resched();
2851 	}
2852 unlock:
2853 	mmap_read_unlock(mm);
2854 	return ret;
2855 }
2856 
2857 /*
2858  * Scan swap table from current position to next entry still in use.
2859  * Return 0 if there are no inuse entries after prev till end of
2860  * the map.
2861  */
2862 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
2863 					unsigned int prev)
2864 {
2865 	struct swap_cluster_info *ci;
2866 	unsigned long i, end;
2867 	unsigned int ci_off;
2868 	unsigned long swp_tb;
2869 
2870 	/*
2871 	 * No need for swap_lock here: we're just looking
2872 	 * for whether an entry is in use, not modifying it; false
2873 	 * hits are okay, and sys_swapoff() has already prevented new
2874 	 * allocations from this area (while holding swap_lock).
2875 	 */
2876 	i = prev + 1;
2877 	while (i < si->max) {
2878 		ci = __swap_offset_to_cluster(si, i);
2879 		end = min_t(unsigned long,
2880 			    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,
2881 			    si->max);
2882 
2883 		/*
2884 		 * An empty cluster has no slot in use, so skip it whole.
2885 		 * A slot is uncounted only after its folio left the swap
2886 		 * cache, so there is nothing here for try_to_unuse() to act on.
2887 		 * Count only drops here, so a READ_ONCE() without ci->lock is
2888 		 * enough, unlike in every other cluster_is_empty() caller.
2889 		 */
2890 		if (!READ_ONCE(ci->count)) {
2891 			i = end;
2892 			cond_resched();
2893 			continue;
2894 		}
2895 
2896 		ci_off = i % SWAPFILE_CLUSTER;
2897 		for (; i < end; ci_off++, i++) {
2898 			swp_tb = swap_table_get(ci, ci_off);
2899 			if (!swp_tb_is_null(swp_tb) && !swp_tb_is_bad(swp_tb))
2900 				return i;
2901 		}
2902 		cond_resched();
2903 	}
2904 
2905 	return 0;
2906 }
2907 
2908 static int try_to_unuse(unsigned int type)
2909 {
2910 	struct mm_struct *prev_mm;
2911 	struct mm_struct *mm;
2912 	struct list_head *p;
2913 	int retval = 0;
2914 	struct swap_info_struct *si = swap_info[type];
2915 	struct folio *folio;
2916 	swp_entry_t entry;
2917 	unsigned int i;
2918 
2919 	if (!swap_usage_in_pages(si))
2920 		goto success;
2921 
2922 retry:
2923 	retval = shmem_unuse(type);
2924 	if (retval)
2925 		return retval;
2926 
2927 	prev_mm = &init_mm;
2928 	mmget(prev_mm);
2929 
2930 	spin_lock(&mmlist_lock);
2931 	p = &init_mm.mmlist;
2932 	while (swap_usage_in_pages(si) &&
2933 	       !signal_pending(current) &&
2934 	       (p = p->next) != &init_mm.mmlist) {
2935 
2936 		mm = list_entry(p, struct mm_struct, mmlist);
2937 		if (!mmget_not_zero(mm))
2938 			continue;
2939 		spin_unlock(&mmlist_lock);
2940 		mmput(prev_mm);
2941 		prev_mm = mm;
2942 		retval = unuse_mm(mm, type);
2943 		if (retval) {
2944 			mmput(prev_mm);
2945 			return retval;
2946 		}
2947 
2948 		/*
2949 		 * Make sure that we aren't completely killing
2950 		 * interactive performance.
2951 		 */
2952 		cond_resched();
2953 		spin_lock(&mmlist_lock);
2954 	}
2955 	spin_unlock(&mmlist_lock);
2956 
2957 	mmput(prev_mm);
2958 
2959 	i = 0;
2960 	while (swap_usage_in_pages(si) &&
2961 	       !signal_pending(current) &&
2962 	       (i = find_next_to_unuse(si, i)) != 0) {
2963 
2964 		entry = swp_entry(type, i);
2965 		folio = swap_cache_get_folio(entry);
2966 		if (!folio)
2967 			continue;
2968 
2969 		/*
2970 		 * It is conceivable that a racing task removed this folio from
2971 		 * swap cache just before we acquired the page lock. The folio
2972 		 * might even be back in swap cache on another swap area. But
2973 		 * that is okay, folio_free_swap() only removes stale folios.
2974 		 */
2975 		folio_lock(folio);
2976 		folio_wait_writeback(folio);
2977 		folio_free_swap(folio);
2978 		folio_unlock(folio);
2979 		folio_put(folio);
2980 	}
2981 
2982 	/*
2983 	 * Lets check again to see if there are still swap entries in the map.
2984 	 * If yes, we would need to do retry the unuse logic again.
2985 	 * Under global memory pressure, swap entries can be reinserted back
2986 	 * into process space after the mmlist loop above passes over them.
2987 	 *
2988 	 * Limit the number of retries? No: when mmget_not_zero()
2989 	 * above fails, that mm is likely to be freeing swap from
2990 	 * exit_mmap(), which proceeds at its own independent pace;
2991 	 * and even shmem_writeout() could have been preempted after
2992 	 * folio_alloc_swap(), temporarily hiding that swap.  It's easy
2993 	 * and robust (though cpu-intensive) just to keep retrying.
2994 	 */
2995 	if (swap_usage_in_pages(si)) {
2996 		if (!signal_pending(current))
2997 			goto retry;
2998 		return -ERESTARTSYS;
2999 	}
3000 
3001 success:
3002 	/*
3003 	 * Make sure that further cleanups after try_to_unuse() returns happen
3004 	 * after swap_range_free() reduces si->inuse_pages to 0.
3005 	 */
3006 	smp_mb();
3007 	return 0;
3008 }
3009 
3010 /*
3011  * After a successful try_to_unuse, if no swap is now in use, we know
3012  * we can empty the mmlist.  swap_lock must be held on entry and exit.
3013  * Note that mmlist_lock nests inside swap_lock, and an mm must be
3014  * added to the mmlist just after page_duplicate - before would be racy.
3015  */
3016 static void drain_mmlist(void)
3017 {
3018 	struct list_head *p, *next;
3019 	unsigned int type;
3020 
3021 	for (type = 0; type < nr_swapfiles; type++)
3022 		if (swap_usage_in_pages(swap_info[type]))
3023 			return;
3024 	spin_lock(&mmlist_lock);
3025 	list_for_each_safe(p, next, &init_mm.mmlist)
3026 		list_del_init(p);
3027 	spin_unlock(&mmlist_lock);
3028 }
3029 
3030 /*
3031  * Free all of a swapdev's extent information
3032  */
3033 static void destroy_swap_extents(struct swap_info_struct *sis,
3034 				 struct file *swap_file)
3035 {
3036 	while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
3037 		struct rb_node *rb = sis->swap_extent_root.rb_node;
3038 		struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
3039 
3040 		rb_erase(rb, &sis->swap_extent_root);
3041 		kfree(se);
3042 	}
3043 
3044 	if (sis->flags & SWP_ACTIVATED) {
3045 		struct address_space *mapping = swap_file->f_mapping;
3046 
3047 		sis->flags &= ~SWP_ACTIVATED;
3048 		if (mapping->a_ops->swap_deactivate)
3049 			mapping->a_ops->swap_deactivate(swap_file);
3050 	}
3051 }
3052 
3053 /*
3054  * Add a block range (and the corresponding page range) into this swapdev's
3055  * extent tree.
3056  *
3057  * This function rather assumes that it is called in ascending page order.
3058  */
3059 int
3060 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
3061 		unsigned long nr_pages, sector_t start_block)
3062 {
3063 	struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
3064 	struct swap_extent *se;
3065 	struct swap_extent *new_se;
3066 
3067 	/*
3068 	 * place the new node at the right most since the
3069 	 * function is called in ascending page order.
3070 	 */
3071 	while (*link) {
3072 		parent = *link;
3073 		link = &parent->rb_right;
3074 	}
3075 
3076 	if (parent) {
3077 		se = rb_entry(parent, struct swap_extent, rb_node);
3078 		BUG_ON(se->start_page + se->nr_pages != start_page);
3079 		if (se->start_block + se->nr_pages == start_block) {
3080 			/* Merge it */
3081 			se->nr_pages += nr_pages;
3082 			return 0;
3083 		}
3084 	}
3085 
3086 	/* No merge, insert a new extent. */
3087 	new_se = kmalloc_obj(*se);
3088 	if (new_se == NULL)
3089 		return -ENOMEM;
3090 	new_se->start_page = start_page;
3091 	new_se->nr_pages = nr_pages;
3092 	new_se->start_block = start_block;
3093 
3094 	rb_link_node(&new_se->rb_node, parent, link);
3095 	rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
3096 	return 1;
3097 }
3098 EXPORT_SYMBOL_GPL(add_swap_extent);
3099 
3100 /*
3101  * A `swap extent' is a simple thing which maps a contiguous range of pages
3102  * onto a contiguous range of disk blocks.  A rbtree of swap extents is
3103  * built at swapon time and is then used at swap_writeout/swap_read_folio
3104  * time for locating where on disk a page belongs.
3105  *
3106  * If the swapfile is an S_ISBLK block device, a single extent is installed.
3107  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
3108  * swap files identically.
3109  *
3110  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
3111  * extent rbtree operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
3112  * swapfiles are handled *identically* after swapon time.
3113  *
3114  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
3115  * and will parse them into a rbtree, in PAGE_SIZE chunks.  If some stray
3116  * blocks are found which do not fall within the PAGE_SIZE alignment
3117  * requirements, they are simply tossed out - we will never use those blocks
3118  * for swapping.
3119  *
3120  * For all swap devices we set S_SWAPFILE across the life of the swapon.  This
3121  * prevents users from writing to the swap device, which will corrupt memory.
3122  *
3123  * The amount of disk space which a single swap extent represents varies.
3124  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
3125  * extents in the rbtree. - akpm.
3126  */
3127 static int setup_swap_extents(struct swap_info_struct *sis,
3128 			      struct file *swap_file, sector_t *span)
3129 {
3130 	struct address_space *mapping = swap_file->f_mapping;
3131 	struct inode *inode = mapping->host;
3132 	int ret;
3133 
3134 	ret = sio_pool_init();
3135 	if (ret)
3136 		return ret;
3137 
3138 	sis->ops = &swap_bdev_ops;
3139 
3140 	if (S_ISBLK(inode->i_mode)) {
3141 		ret = add_swap_extent(sis, 0, sis->max, 0);
3142 		*span = sis->pages;
3143 		return ret;
3144 	}
3145 
3146 	if (mapping->a_ops->swap_activate) {
3147 		ret = mapping->a_ops->swap_activate(sis, swap_file, span);
3148 		if (ret < 0)
3149 			return ret;
3150 		sis->flags |= SWP_ACTIVATED;
3151 		return ret;
3152 	}
3153 
3154 	return generic_swapfile_activate(sis, swap_file, span);
3155 }
3156 
3157 static void _enable_swap_info(struct swap_info_struct *si)
3158 {
3159 	atomic_long_add(si->pages, &nr_swap_pages);
3160 	total_swap_pages += si->pages;
3161 
3162 	assert_spin_locked(&swap_lock);
3163 
3164 	plist_add(&si->list, &swap_active_head);
3165 
3166 	/* Add back to available list */
3167 	add_to_avail_list(si, true);
3168 }
3169 
3170 /*
3171  * Called after the swap device is ready, resurrect its percpu ref, it's now
3172  * safe to reference it. Add it to the list to expose it to the allocator.
3173  */
3174 static void enable_swap_info(struct swap_info_struct *si)
3175 {
3176 	percpu_ref_resurrect(&si->users);
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 static void reinsert_swap_info(struct swap_info_struct *si)
3185 {
3186 	spin_lock(&swap_lock);
3187 	spin_lock(&si->lock);
3188 	_enable_swap_info(si);
3189 	spin_unlock(&si->lock);
3190 	spin_unlock(&swap_lock);
3191 }
3192 
3193 /*
3194  * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range
3195  * see the updated flags, so there will be no more allocations.
3196  */
3197 static void wait_for_allocation(struct swap_info_struct *si)
3198 {
3199 	unsigned long offset;
3200 	unsigned long end = ALIGN(si->max, SWAPFILE_CLUSTER);
3201 	struct swap_cluster_info *ci;
3202 
3203 	BUG_ON(si->flags & SWP_WRITEOK);
3204 
3205 	for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) {
3206 		ci = swap_cluster_lock(si, offset);
3207 		swap_cluster_unlock(ci);
3208 	}
3209 }
3210 
3211 static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
3212 				   unsigned long maxpages)
3213 {
3214 	struct swap_cluster_info *ci;
3215 	int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3216 
3217 	if (!cluster_info)
3218 		return;
3219 	for (i = 0; i < nr_clusters; i++) {
3220 		ci = cluster_info + i;
3221 		/* Cluster with bad marks count will have a remaining table */
3222 		spin_lock(&ci->lock);
3223 		if (cluster_table_is_alloced(ci)) {
3224 			swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);
3225 			swap_cluster_free_table(ci);
3226 		}
3227 		spin_unlock(&ci->lock);
3228 	}
3229 	kvfree(cluster_info);
3230 }
3231 
3232 /*
3233  * Called after swap device's reference count is dead, so
3234  * neither scan nor allocation will use it.
3235  */
3236 static void flush_percpu_swap_cluster(struct swap_info_struct *si)
3237 {
3238 	int cpu, i;
3239 	struct swap_info_struct **pcp_si;
3240 
3241 	for_each_possible_cpu(cpu) {
3242 		pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);
3243 		/*
3244 		 * Invalidate the percpu swap cluster cache, si->users
3245 		 * is dead, so no new user will point to it, just flush
3246 		 * any existing user.
3247 		 */
3248 		for (i = 0; i < SWAP_NR_ORDERS; i++)
3249 			cmpxchg(&pcp_si[i], si, NULL);
3250 	}
3251 }
3252 
3253 
3254 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
3255 {
3256 	struct swap_info_struct *p = NULL;
3257 	struct swap_cluster_info *cluster_info;
3258 	struct file *swap_file, *victim;
3259 	struct address_space *mapping;
3260 	struct inode *inode;
3261 	unsigned int maxpages;
3262 	int err, found = 0;
3263 
3264 	if (!capable(CAP_SYS_ADMIN))
3265 		return -EPERM;
3266 
3267 	BUG_ON(!current->mm);
3268 
3269 	CLASS(filename, pathname)(specialfile);
3270 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
3271 	if (IS_ERR(victim))
3272 		return PTR_ERR(victim);
3273 
3274 	mapping = victim->f_mapping;
3275 	spin_lock(&swap_lock);
3276 	plist_for_each_entry(p, &swap_active_head, list) {
3277 		if (p->flags & SWP_WRITEOK) {
3278 			if (p->swap_file->f_mapping == mapping) {
3279 				found = 1;
3280 				break;
3281 			}
3282 		}
3283 	}
3284 	if (!found) {
3285 		err = -EINVAL;
3286 		spin_unlock(&swap_lock);
3287 		goto out_dput;
3288 	}
3289 
3290 	/* Refuse swapoff while the device is pinned for hibernation */
3291 	if (p->flags & SWP_HIBERNATION) {
3292 		err = -EBUSY;
3293 		spin_unlock(&swap_lock);
3294 		goto out_dput;
3295 	}
3296 
3297 	if (!security_vm_enough_memory_mm(current->mm, p->pages))
3298 		vm_unacct_memory(p->pages);
3299 	else {
3300 		err = -ENOMEM;
3301 		spin_unlock(&swap_lock);
3302 		goto out_dput;
3303 	}
3304 	spin_lock(&p->lock);
3305 	del_from_avail_list(p, true);
3306 	plist_del(&p->list, &swap_active_head);
3307 	atomic_long_sub(p->pages, &nr_swap_pages);
3308 	total_swap_pages -= p->pages;
3309 	spin_unlock(&p->lock);
3310 	spin_unlock(&swap_lock);
3311 
3312 	wait_for_allocation(p);
3313 
3314 	set_current_oom_origin();
3315 	err = try_to_unuse(p->type);
3316 	clear_current_oom_origin();
3317 
3318 	if (err) {
3319 		/* re-insert swap space back into swap_list */
3320 		reinsert_swap_info(p);
3321 		goto out_dput;
3322 	}
3323 
3324 	/*
3325 	 * Wait for swap operations protected by get/put_swap_device()
3326 	 * to complete.  Because of synchronize_rcu() here, all swap
3327 	 * operations protected by RCU reader side lock (including any
3328 	 * spinlock) will be waited too.  This makes it easy to
3329 	 * prevent folio_test_swapcache() and the following swap cache
3330 	 * operations from racing with swapoff.
3331 	 */
3332 	percpu_ref_kill(&p->users);
3333 	synchronize_rcu();
3334 	wait_for_completion(&p->comp);
3335 
3336 	flush_work(&p->discard_work);
3337 	flush_work(&p->reclaim_work);
3338 	flush_percpu_swap_cluster(p);
3339 
3340 	destroy_swap_extents(p, p->swap_file);
3341 
3342 	if (!(p->flags & SWP_SOLIDSTATE))
3343 		atomic_dec(&nr_rotate_swap);
3344 
3345 	mutex_lock(&swapon_mutex);
3346 	spin_lock(&swap_lock);
3347 	spin_lock(&p->lock);
3348 	drain_mmlist();
3349 
3350 	swap_file = p->swap_file;
3351 	p->swap_file = NULL;
3352 	maxpages = p->max;
3353 	cluster_info = p->cluster_info;
3354 	p->max = 0;
3355 	p->cluster_info = NULL;
3356 	spin_unlock(&p->lock);
3357 	spin_unlock(&swap_lock);
3358 	arch_swap_invalidate_area(p->type);
3359 	zswap_swapoff(p->type);
3360 	mutex_unlock(&swapon_mutex);
3361 	kfree(p->global_cluster);
3362 	p->global_cluster = NULL;
3363 	free_swap_cluster_info(cluster_info, maxpages);
3364 
3365 	inode = mapping->host;
3366 
3367 	inode_lock(inode);
3368 	inode->i_flags &= ~S_SWAPFILE;
3369 	inode_unlock(inode);
3370 	filp_close(swap_file, NULL);
3371 
3372 	/*
3373 	 * Clear the SWP_USED flag after all resources are freed so that swapon
3374 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
3375 	 * not hold p->lock after we cleared its SWP_WRITEOK.
3376 	 */
3377 	spin_lock(&swap_lock);
3378 	p->flags = 0;
3379 	spin_unlock(&swap_lock);
3380 
3381 	err = 0;
3382 	atomic_inc(&proc_poll_event);
3383 	wake_up_interruptible(&proc_poll_wait);
3384 
3385 out_dput:
3386 	filp_close(victim, NULL);
3387 	return err;
3388 }
3389 
3390 #ifdef CONFIG_PROC_FS
3391 static __poll_t swaps_poll(struct file *file, poll_table *wait)
3392 {
3393 	struct seq_file *seq = file->private_data;
3394 
3395 	poll_wait(file, &proc_poll_wait, wait);
3396 
3397 	if (seq->poll_event != atomic_read(&proc_poll_event)) {
3398 		seq->poll_event = atomic_read(&proc_poll_event);
3399 		return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
3400 	}
3401 
3402 	return EPOLLIN | EPOLLRDNORM;
3403 }
3404 
3405 /* iterator */
3406 static void *swap_start(struct seq_file *swap, loff_t *pos)
3407 {
3408 	struct swap_info_struct *si;
3409 	int type;
3410 	loff_t l = *pos;
3411 
3412 	mutex_lock(&swapon_mutex);
3413 
3414 	if (!l)
3415 		return SEQ_START_TOKEN;
3416 
3417 	for (type = 0; (si = swap_type_to_info(type)); type++) {
3418 		if (!(si->swap_file))
3419 			continue;
3420 		if (!--l)
3421 			return si;
3422 	}
3423 
3424 	return NULL;
3425 }
3426 
3427 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
3428 {
3429 	struct swap_info_struct *si = v;
3430 	int type;
3431 
3432 	if (v == SEQ_START_TOKEN)
3433 		type = 0;
3434 	else
3435 		type = si->type + 1;
3436 
3437 	++(*pos);
3438 	for (; (si = swap_type_to_info(type)); type++) {
3439 		if (!(si->swap_file))
3440 			continue;
3441 		return si;
3442 	}
3443 
3444 	return NULL;
3445 }
3446 
3447 static void swap_stop(struct seq_file *swap, void *v)
3448 {
3449 	mutex_unlock(&swapon_mutex);
3450 }
3451 
3452 static int swap_show(struct seq_file *swap, void *v)
3453 {
3454 	struct swap_info_struct *si = v;
3455 	struct file *file;
3456 	int len;
3457 	unsigned long bytes, inuse;
3458 
3459 	if (si == SEQ_START_TOKEN) {
3460 		seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
3461 		return 0;
3462 	}
3463 
3464 	bytes = K((unsigned long)si->pages);
3465 	inuse = K(swap_usage_in_pages(si));
3466 
3467 	file = si->swap_file;
3468 	len = seq_file_path(swap, file, " \t\n\\");
3469 	seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
3470 			len < 40 ? 40 - len : 1, " ",
3471 			S_ISBLK(file_inode(file)->i_mode) ?
3472 				"partition" : "file\t",
3473 			bytes, bytes < 10000000 ? "\t" : "",
3474 			inuse, inuse < 10000000 ? "\t" : "",
3475 			si->prio);
3476 	return 0;
3477 }
3478 
3479 static const struct seq_operations swaps_op = {
3480 	.start =	swap_start,
3481 	.next =		swap_next,
3482 	.stop =		swap_stop,
3483 	.show =		swap_show
3484 };
3485 
3486 static int swaps_open(struct inode *inode, struct file *file)
3487 {
3488 	struct seq_file *seq;
3489 	int ret;
3490 
3491 	ret = seq_open(file, &swaps_op);
3492 	if (ret)
3493 		return ret;
3494 
3495 	seq = file->private_data;
3496 	seq->poll_event = atomic_read(&proc_poll_event);
3497 	return 0;
3498 }
3499 
3500 static const struct proc_ops swaps_proc_ops = {
3501 	.proc_flags	= PROC_ENTRY_PERMANENT,
3502 	.proc_open	= swaps_open,
3503 	.proc_read	= seq_read,
3504 	.proc_lseek	= seq_lseek,
3505 	.proc_release	= seq_release,
3506 	.proc_poll	= swaps_poll,
3507 };
3508 
3509 static int __init procswaps_init(void)
3510 {
3511 	proc_create("swaps", 0, NULL, &swaps_proc_ops);
3512 	return 0;
3513 }
3514 __initcall(procswaps_init);
3515 #endif /* CONFIG_PROC_FS */
3516 
3517 #ifdef MAX_SWAPFILES_CHECK
3518 static int __init max_swapfiles_check(void)
3519 {
3520 	MAX_SWAPFILES_CHECK();
3521 	return 0;
3522 }
3523 late_initcall(max_swapfiles_check);
3524 #endif
3525 
3526 static struct swap_info_struct *alloc_swap_info(void)
3527 {
3528 	struct swap_info_struct *p;
3529 	struct swap_info_struct *defer = NULL;
3530 	unsigned int type;
3531 
3532 	p = kvzalloc_obj(struct swap_info_struct);
3533 	if (!p)
3534 		return ERR_PTR(-ENOMEM);
3535 
3536 	if (percpu_ref_init(&p->users, swap_users_ref_free,
3537 			    PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {
3538 		kvfree(p);
3539 		return ERR_PTR(-ENOMEM);
3540 	}
3541 
3542 	spin_lock(&swap_lock);
3543 	for (type = 0; type < nr_swapfiles; type++) {
3544 		if (!(swap_info[type]->flags & SWP_USED))
3545 			break;
3546 	}
3547 	if (type >= MAX_SWAPFILES) {
3548 		spin_unlock(&swap_lock);
3549 		percpu_ref_exit(&p->users);
3550 		kvfree(p);
3551 		return ERR_PTR(-EPERM);
3552 	}
3553 	if (type >= nr_swapfiles) {
3554 		p->type = type;
3555 		/*
3556 		 * Publish the swap_info_struct after initializing it.
3557 		 * Note that kvzalloc() above zeroes all its fields.
3558 		 */
3559 		smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */
3560 		nr_swapfiles++;
3561 	} else {
3562 		defer = p;
3563 		p = swap_info[type];
3564 		/*
3565 		 * Do not memset this entry: a racing procfs swap_next()
3566 		 * would be relying on p->type to remain valid.
3567 		 */
3568 	}
3569 	p->swap_extent_root = RB_ROOT;
3570 	plist_node_init(&p->list, 0);
3571 	plist_node_init(&p->avail_list, 0);
3572 	p->flags = SWP_USED;
3573 	spin_unlock(&swap_lock);
3574 	if (defer) {
3575 		percpu_ref_exit(&defer->users);
3576 		kvfree(defer);
3577 	}
3578 	spin_lock_init(&p->lock);
3579 	atomic_long_set(&p->inuse_pages, SWAP_USAGE_OFFLIST_BIT);
3580 	init_completion(&p->comp);
3581 
3582 	return p;
3583 }
3584 
3585 static int claim_swapfile(struct swap_info_struct *si, struct inode *inode)
3586 {
3587 	if (S_ISBLK(inode->i_mode)) {
3588 		si->bdev = I_BDEV(inode);
3589 		/*
3590 		 * Zoned block devices contain zones that have a sequential
3591 		 * write only restriction.  Hence zoned block devices are not
3592 		 * suitable for swapping.  Disallow them here.
3593 		 */
3594 		if (bdev_is_zoned(si->bdev))
3595 			return -EINVAL;
3596 		si->flags |= SWP_BLKDEV;
3597 	} else if (S_ISREG(inode->i_mode)) {
3598 		si->bdev = inode->i_sb->s_bdev;
3599 	}
3600 
3601 	return 0;
3602 }
3603 
3604 
3605 /*
3606  * Find out how many pages are allowed for a single swap device. There
3607  * are two limiting factors:
3608  * 1) the number of bits for the swap offset in the swp_entry_t type, and
3609  * 2) the number of bits in the swap pte, as defined by the different
3610  * architectures.
3611  *
3612  * In order to find the largest possible bit mask, a swap entry with
3613  * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
3614  * decoded to a swp_entry_t again, and finally the swap offset is
3615  * extracted.
3616  *
3617  * This will mask all the bits from the initial ~0UL mask that can't
3618  * be encoded in either the swp_entry_t or the architecture definition
3619  * of a swap pte.
3620  */
3621 unsigned long generic_max_swapfile_size(void)
3622 {
3623 	swp_entry_t entry = swp_entry(0, ~0UL);
3624 	const pte_t pte = softleaf_to_pte(entry);
3625 
3626 	/*
3627 	 * Since the PTE can be an invalid softleaf entry (e.g. the none PTE),
3628 	 * we need to do this manually.
3629 	 */
3630 	entry = __pte_to_swp_entry(pte);
3631 	entry = swp_entry(__swp_type(entry), __swp_offset(entry));
3632 
3633 	return swp_offset(entry) + 1;
3634 }
3635 
3636 /* Can be overridden by an architecture for additional checks. */
3637 __weak unsigned long arch_max_swapfile_size(void)
3638 {
3639 	return generic_max_swapfile_size();
3640 }
3641 
3642 static unsigned long read_swap_header(struct swap_info_struct *si,
3643 					union swap_header *swap_header,
3644 					struct inode *inode)
3645 {
3646 	int i;
3647 	unsigned long maxpages;
3648 	unsigned long swapfilepages;
3649 	unsigned long last_page;
3650 
3651 	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
3652 		pr_err("Unable to find swap-space signature\n");
3653 		return 0;
3654 	}
3655 
3656 	/* swap partition endianness hack... */
3657 	if (swab32(swap_header->info.version) == 1) {
3658 		swab32s(&swap_header->info.version);
3659 		swab32s(&swap_header->info.last_page);
3660 		swab32s(&swap_header->info.nr_badpages);
3661 		if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3662 			return 0;
3663 		for (i = 0; i < swap_header->info.nr_badpages; i++)
3664 			swab32s(&swap_header->info.badpages[i]);
3665 	}
3666 	/* Check the swap header's sub-version */
3667 	if (swap_header->info.version != 1) {
3668 		pr_warn("Unable to handle swap header version %d\n",
3669 			swap_header->info.version);
3670 		return 0;
3671 	}
3672 
3673 	maxpages = swapfile_maximum_size;
3674 	last_page = swap_header->info.last_page;
3675 	if (!last_page) {
3676 		pr_warn("Empty swap-file\n");
3677 		return 0;
3678 	}
3679 	if (last_page > maxpages) {
3680 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
3681 			K(maxpages), K(last_page));
3682 	}
3683 	if (maxpages > last_page) {
3684 		maxpages = last_page + 1;
3685 		/* p->max is an unsigned int: don't overflow it */
3686 		if ((unsigned int)maxpages == 0)
3687 			maxpages = UINT_MAX;
3688 	}
3689 
3690 	if (!maxpages)
3691 		return 0;
3692 	swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
3693 	if (swapfilepages && maxpages > swapfilepages) {
3694 		pr_warn("Swap area shorter than signature indicates\n");
3695 		return 0;
3696 	}
3697 	if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
3698 		return 0;
3699 	if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3700 		return 0;
3701 
3702 	return maxpages;
3703 }
3704 
3705 static int setup_swap_clusters_info(struct swap_info_struct *si,
3706 				    union swap_header *swap_header,
3707 				    unsigned long maxpages)
3708 {
3709 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3710 	struct swap_cluster_info *cluster_info;
3711 	int err = -ENOMEM;
3712 	unsigned long i;
3713 
3714 	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
3715 	if (!cluster_info)
3716 		goto err;
3717 
3718 	for (i = 0; i < nr_clusters; i++)
3719 		spin_lock_init(&cluster_info[i].lock);
3720 
3721 	if (!(si->flags & SWP_SOLIDSTATE)) {
3722 		si->global_cluster = kmalloc_obj(*si->global_cluster);
3723 		if (!si->global_cluster)
3724 			goto err;
3725 		for (i = 0; i < SWAP_NR_ORDERS; i++)
3726 			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
3727 		spin_lock_init(&si->global_cluster_lock);
3728 	}
3729 
3730 	/*
3731 	 * Mark unusable pages (header page, bad pages, and the EOF part of
3732 	 * the last cluster) as unavailable. The clusters aren't marked free
3733 	 * yet, so no list operations are involved yet.
3734 	 */
3735 	err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false);
3736 	if (err)
3737 		goto err;
3738 	for (i = 0; i < swap_header->info.nr_badpages; i++) {
3739 		unsigned int page_nr = swap_header->info.badpages[i];
3740 
3741 		if (!page_nr || page_nr > swap_header->info.last_page) {
3742 			pr_warn("Bad slot offset is out of border: %d (last_page: %d)\n",
3743 				page_nr, swap_header->info.last_page);
3744 			err = -EINVAL;
3745 			goto err;
3746 		}
3747 		err = swap_cluster_setup_bad_slot(si, cluster_info, page_nr, false);
3748 		if (err)
3749 			goto err;
3750 	}
3751 	for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) {
3752 		err = swap_cluster_setup_bad_slot(si, cluster_info, i, true);
3753 		if (err)
3754 			goto err;
3755 	}
3756 
3757 	INIT_LIST_HEAD(&si->free_clusters);
3758 	INIT_LIST_HEAD(&si->full_clusters);
3759 	INIT_LIST_HEAD(&si->discard_clusters);
3760 
3761 	for (i = 0; i < SWAP_NR_ORDERS; i++) {
3762 		INIT_LIST_HEAD(&si->nonfull_clusters[i]);
3763 		INIT_LIST_HEAD(&si->frag_clusters[i]);
3764 	}
3765 
3766 	for (i = 0; i < nr_clusters; i++) {
3767 		struct swap_cluster_info *ci = &cluster_info[i];
3768 
3769 		if (ci->count) {
3770 			ci->flags = CLUSTER_FLAG_NONFULL;
3771 			list_add_tail(&ci->list, &si->nonfull_clusters[0]);
3772 		} else {
3773 			ci->flags = CLUSTER_FLAG_FREE;
3774 			list_add_tail(&ci->list, &si->free_clusters);
3775 		}
3776 	}
3777 
3778 	si->cluster_info = cluster_info;
3779 	return 0;
3780 err:
3781 	free_swap_cluster_info(cluster_info, maxpages);
3782 	return err;
3783 }
3784 
3785 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
3786 {
3787 	struct swap_info_struct *si;
3788 	struct file *swap_file = NULL;
3789 	struct address_space *mapping;
3790 	struct dentry *dentry;
3791 	int prio;
3792 	int error;
3793 	union swap_header *swap_header;
3794 	int nr_extents;
3795 	sector_t span;
3796 	unsigned long maxpages;
3797 	struct folio *folio = NULL;
3798 	struct inode *inode = NULL;
3799 	bool inced_nr_rotate_swap = false;
3800 
3801 	if (swap_flags & ~SWAP_FLAGS_VALID)
3802 		return -EINVAL;
3803 
3804 	if (!capable(CAP_SYS_ADMIN))
3805 		return -EPERM;
3806 
3807 	/*
3808 	 * Allocate or reuse existing !SWP_USED swap_info. The returned
3809 	 * si will stay in a dying status, so nothing will access its content
3810 	 * until enable_swap_info resurrects its percpu ref and expose it.
3811 	 */
3812 	si = alloc_swap_info();
3813 	if (IS_ERR(si))
3814 		return PTR_ERR(si);
3815 
3816 	INIT_WORK(&si->discard_work, swap_discard_work);
3817 	INIT_WORK(&si->reclaim_work, swap_reclaim_work);
3818 
3819 	CLASS(filename, name)(specialfile);
3820 	swap_file = file_open_name(name, O_RDWR | O_LARGEFILE | O_EXCL, 0);
3821 	if (IS_ERR(swap_file)) {
3822 		error = PTR_ERR(swap_file);
3823 		swap_file = NULL;
3824 		goto bad_swap;
3825 	}
3826 
3827 	mapping = swap_file->f_mapping;
3828 	dentry = swap_file->f_path.dentry;
3829 	inode = mapping->host;
3830 
3831 	error = claim_swapfile(si, inode);
3832 	if (unlikely(error))
3833 		goto bad_swap;
3834 
3835 	inode_lock(inode);
3836 	if (d_unlinked(dentry) || cant_mount(dentry)) {
3837 		error = -ENOENT;
3838 		goto bad_swap_unlock_inode;
3839 	}
3840 	if (IS_SWAPFILE(inode)) {
3841 		error = -EBUSY;
3842 		goto bad_swap_unlock_inode;
3843 	}
3844 	if (IS_ENCRYPTED(inode)) {
3845 		pr_warn_once(
3846 			"Filesystem-level encrypted swapfile '%s' is unsupported. Create a loop device over it, or use dm-crypt\n",
3847 			name->name);
3848 		error = -EINVAL;
3849 		goto bad_swap_unlock_inode;
3850 	}
3851 
3852 	/*
3853 	 * The swap subsystem needs a major overhaul to support this.
3854 	 * It doesn't work yet so just disable it for now.
3855 	 */
3856 	if (mapping_min_folio_order(mapping) > 0) {
3857 		error = -EINVAL;
3858 		goto bad_swap_unlock_inode;
3859 	}
3860 
3861 	/*
3862 	 * Read the swap header.
3863 	 */
3864 	if (!mapping->a_ops->read_folio) {
3865 		error = -EINVAL;
3866 		goto bad_swap_unlock_inode;
3867 	}
3868 	folio = read_mapping_folio(mapping, 0, swap_file);
3869 	if (IS_ERR(folio)) {
3870 		error = PTR_ERR(folio);
3871 		goto bad_swap_unlock_inode;
3872 	}
3873 	swap_header = kmap_local_folio(folio, 0);
3874 
3875 	maxpages = read_swap_header(si, swap_header, inode);
3876 	if (unlikely(!maxpages)) {
3877 		error = -EINVAL;
3878 		goto bad_swap_unlock_inode;
3879 	}
3880 
3881 	si->max = maxpages;
3882 	si->pages = maxpages - 1;
3883 	nr_extents = setup_swap_extents(si, swap_file, &span);
3884 	if (nr_extents < 0) {
3885 		error = nr_extents;
3886 		goto bad_swap_unlock_inode;
3887 	}
3888 	if (si->pages != si->max - 1) {
3889 		pr_err("swap:%u != (max:%u - 1)\n", si->pages, si->max);
3890 		error = -EINVAL;
3891 		goto bad_swap_unlock_inode;
3892 	}
3893 
3894 	maxpages = si->max;
3895 
3896 	if (si->bdev && bdev_stable_writes(si->bdev))
3897 		si->flags |= SWP_STABLE_WRITES;
3898 
3899 	if (si->bdev && bdev_synchronous(si->bdev))
3900 		si->flags |= SWP_SYNCHRONOUS_IO;
3901 
3902 	if (si->bdev && !bdev_rot(si->bdev)) {
3903 		si->flags |= SWP_SOLIDSTATE;
3904 	} else {
3905 		atomic_inc(&nr_rotate_swap);
3906 		inced_nr_rotate_swap = true;
3907 	}
3908 
3909 	/*
3910 	 * Set up the swap cluster info after SWP_ flags handling as
3911 	 * setup_swap_clusters_info() checks SWP_SOLIDSTATE.
3912 	 */
3913 	error = setup_swap_clusters_info(si, swap_header, maxpages);
3914 	if (error)
3915 		goto bad_swap_unlock_inode;
3916 
3917 	if ((swap_flags & SWAP_FLAG_DISCARD) &&
3918 	    si->bdev && bdev_max_discard_sectors(si->bdev)) {
3919 		/*
3920 		 * When discard is enabled for swap with no particular
3921 		 * policy flagged, we set all swap discard flags here in
3922 		 * order to sustain backward compatibility with older
3923 		 * swapon(8) releases.
3924 		 */
3925 		si->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3926 			     SWP_PAGE_DISCARD);
3927 
3928 		/*
3929 		 * By flagging sys_swapon, a sysadmin can tell us to
3930 		 * either do single-time area discards only, or to just
3931 		 * perform discards for released swap page-clusters.
3932 		 * Now it's time to adjust the p->flags accordingly.
3933 		 */
3934 		if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3935 			si->flags &= ~SWP_PAGE_DISCARD;
3936 		else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3937 			si->flags &= ~SWP_AREA_DISCARD;
3938 
3939 		/* issue a swapon-time discard if it's still required */
3940 		if (si->flags & SWP_AREA_DISCARD) {
3941 			int err = discard_swap(si);
3942 			if (unlikely(err))
3943 				pr_err("swapon: discard_swap(%p): %d\n",
3944 					si, err);
3945 		}
3946 	}
3947 
3948 	error = zswap_swapon(si->type, maxpages);
3949 	if (error)
3950 		goto bad_swap_unlock_inode;
3951 
3952 	/*
3953 	 * Flush any pending IO and dirty mappings before we start using this
3954 	 * swap device.
3955 	 */
3956 	inode->i_flags |= S_SWAPFILE;
3957 	error = inode_drain_writes(inode);
3958 	if (error) {
3959 		inode->i_flags &= ~S_SWAPFILE;
3960 		goto free_swap_zswap;
3961 	}
3962 
3963 	mutex_lock(&swapon_mutex);
3964 	prio = DEF_SWAP_PRIO;
3965 	if (swap_flags & SWAP_FLAG_PREFER)
3966 		prio = swap_flags & SWAP_FLAG_PRIO_MASK;
3967 
3968 	/*
3969 	 * The plist prio is negated because plist ordering is
3970 	 * low-to-high, while swap ordering is high-to-low
3971 	 */
3972 	si->prio = prio;
3973 	si->list.prio = -si->prio;
3974 	si->avail_list.prio = -si->prio;
3975 	si->swap_file = swap_file;
3976 
3977 	/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */
3978 	enable_swap_info(si);
3979 
3980 	pr_info("Adding %luk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
3981 		K((unsigned long)si->pages), name->name, si->prio, nr_extents,
3982 		K((unsigned long long)span),
3983 		(si->flags & SWP_SOLIDSTATE) ? "SS" : "",
3984 		(si->flags & SWP_DISCARDABLE) ? "D" : "",
3985 		(si->flags & SWP_AREA_DISCARD) ? "s" : "",
3986 		(si->flags & SWP_PAGE_DISCARD) ? "c" : "");
3987 
3988 	mutex_unlock(&swapon_mutex);
3989 	atomic_inc(&proc_poll_event);
3990 	wake_up_interruptible(&proc_poll_wait);
3991 
3992 	error = 0;
3993 	goto out;
3994 free_swap_zswap:
3995 	zswap_swapoff(si->type);
3996 bad_swap_unlock_inode:
3997 	inode_unlock(inode);
3998 bad_swap:
3999 	kfree(si->global_cluster);
4000 	si->global_cluster = NULL;
4001 	inode = NULL;
4002 	destroy_swap_extents(si, swap_file);
4003 	free_swap_cluster_info(si->cluster_info, si->max);
4004 	si->cluster_info = NULL;
4005 	/*
4006 	 * Clear the SWP_USED flag after all resources are freed so
4007 	 * alloc_swap_info can reuse this si safely.
4008 	 */
4009 	spin_lock(&swap_lock);
4010 	si->flags = 0;
4011 	spin_unlock(&swap_lock);
4012 	if (inced_nr_rotate_swap)
4013 		atomic_dec(&nr_rotate_swap);
4014 	if (swap_file)
4015 		filp_close(swap_file, NULL);
4016 out:
4017 	if (!IS_ERR_OR_NULL(folio))
4018 		folio_release_kmap(folio, swap_header);
4019 	if (inode)
4020 		inode_unlock(inode);
4021 	return error;
4022 }
4023 
4024 void si_swapinfo(struct sysinfo *val)
4025 {
4026 	unsigned int type;
4027 	unsigned long nr_to_be_unused = 0;
4028 
4029 	spin_lock(&swap_lock);
4030 	for (type = 0; type < nr_swapfiles; type++) {
4031 		struct swap_info_struct *si = swap_info[type];
4032 
4033 		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
4034 			nr_to_be_unused += swap_usage_in_pages(si);
4035 	}
4036 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
4037 	val->totalswap = total_swap_pages + nr_to_be_unused;
4038 	spin_unlock(&swap_lock);
4039 }
4040 
4041 /*
4042  * swap_dup_entry_direct() - Increase reference count of a swap entry by one.
4043  * @entry: first swap entry from which we want to increase the refcount.
4044  *
4045  * Returns 0 for success, or -ENOMEM if the extend table is required
4046  * but could not be atomically allocated.  Returns -EINVAL if the swap
4047  * entry is invalid, which might occur if a page table entry has got
4048  * corrupted.
4049  *
4050  * Context: Caller must ensure there is no race condition on the reference
4051  * owner. e.g., locking the PTL of a PTE containing the entry being increased.
4052  * Also the swap entry must have a count >= 1. Otherwise folio_dup_swap should
4053  * be used.
4054  */
4055 int swap_dup_entry_direct(swp_entry_t entry)
4056 {
4057 	struct swap_info_struct *si;
4058 
4059 	si = swap_entry_to_info(entry);
4060 	if (WARN_ON_ONCE(!si)) {
4061 		pr_err_ratelimited("%s%08lx\n", Bad_file, entry.val);
4062 		return -EINVAL;
4063 	}
4064 
4065 	/*
4066 	 * The caller must be increasing the swap count from a direct
4067 	 * reference of the swap slot (e.g. a swap entry in page table).
4068 	 * So the swap count must be >= 1.
4069 	 */
4070 	VM_WARN_ON_ONCE(!swap_entry_swapped(si, entry));
4071 
4072 	return swap_dup_entries_cluster(si, swp_offset(entry), 1);
4073 }
4074 
4075 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
4076 static bool __has_usable_swap(void)
4077 {
4078 	return !plist_head_empty(&swap_active_head);
4079 }
4080 
4081 void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
4082 {
4083 	struct swap_info_struct *si;
4084 
4085 	if (!(gfp & __GFP_IO))
4086 		return;
4087 
4088 	if (!__has_usable_swap())
4089 		return;
4090 
4091 	if (!blk_cgroup_congested())
4092 		return;
4093 
4094 	/*
4095 	 * We've already scheduled a throttle, avoid taking the global swap
4096 	 * lock.
4097 	 */
4098 	if (current->throttle_disk)
4099 		return;
4100 
4101 	spin_lock(&swap_avail_lock);
4102 	plist_for_each_entry(si, &swap_avail_head, avail_list) {
4103 		if (si->bdev) {
4104 			blkcg_schedule_throttle(si->bdev->bd_disk, true);
4105 			break;
4106 		}
4107 	}
4108 	spin_unlock(&swap_avail_lock);
4109 }
4110 #endif
4111 
4112 static int __init swapfile_init(void)
4113 {
4114 	swapfile_maximum_size = arch_max_swapfile_size();
4115 
4116 	/*
4117 	 * Once a cluster is freed, it's swap table content is read
4118 	 * only, and all swap cache readers (swap_cache_*) verifies
4119 	 * the content before use. So it's safe to use RCU slab here.
4120 	 */
4121 	if (!SWP_TABLE_USE_PAGE)
4122 		swap_table_cachep = kmem_cache_create("swap_table",
4123 				    sizeof(struct swap_table),
4124 				    0, SLAB_PANIC | SLAB_TYPESAFE_BY_RCU, NULL);
4125 
4126 #ifdef CONFIG_MIGRATION
4127 	if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS))
4128 		swap_migration_ad_supported = true;
4129 #endif	/* CONFIG_MIGRATION */
4130 
4131 	return 0;
4132 }
4133 subsys_initcall(swapfile_init);
4134