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