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