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