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