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