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