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