1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
6 * Swap reorganised 29.12.95, Stephen Tweedie
10 #include <linux/sched/mm.h>
11 #include <linux/sched/task.h>
12 #include <linux/hugetlb.h>
13 #include <linux/mman.h>
14 #include <linux/slab.h>
15 #include <linux/kernel_stat.h>
16 #include <linux/swap.h>
17 #include <linux/vmalloc.h>
18 #include <linux/pagemap.h>
19 #include <linux/namei.h>
20 #include <linux/shmem_fs.h>
21 #include <linux/blkdev.h>
22 #include <linux/random.h>
23 #include <linux/writeback.h>
24 #include <linux/proc_fs.h>
25 #include <linux/seq_file.h>
26 #include <linux/init.h>
27 #include <linux/ksm.h>
28 #include <linux/rmap.h>
29 #include <linux/security.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mutex.h>
32 #include <linux/capability.h>
33 #include <linux/syscalls.h>
34 #include <linux/memcontrol.h>
35 #include <linux/poll.h>
36 #include <linux/oom.h>
37 #include <linux/frontswap.h>
38 #include <linux/swapfile.h>
39 #include <linux/export.h>
40 #include <linux/swap_slots.h>
41 #include <linux/sort.h>
43 #include <asm/tlbflush.h>
44 #include <linux/swapops.h>
45 #include <linux/swap_cgroup.h>
47 static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
49 static void free_swap_count_continuations(struct swap_info_struct *);
50 static sector_t map_swap_entry(swp_entry_t, struct block_device**);
52 DEFINE_SPINLOCK(swap_lock);
53 static unsigned int nr_swapfiles;
54 atomic_long_t nr_swap_pages;
56 * Some modules use swappable objects and may try to swap them out under
57 * memory pressure (via the shrinker). Before doing so, they may wish to
58 * check to see if any swap space is available.
60 EXPORT_SYMBOL_GPL(nr_swap_pages);
61 /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
62 long total_swap_pages;
63 static int least_priority = -1;
65 static const char Bad_file[] = "Bad swap file entry ";
66 static const char Unused_file[] = "Unused swap file entry ";
67 static const char Bad_offset[] = "Bad swap offset entry ";
68 static const char Unused_offset[] = "Unused swap offset entry ";
71 * all active swap_info_structs
72 * protected with swap_lock, and ordered by priority.
74 PLIST_HEAD(swap_active_head);
77 * all available (active, not full) swap_info_structs
78 * protected with swap_avail_lock, ordered by priority.
79 * This is used by get_swap_page() instead of swap_active_head
80 * because swap_active_head includes all swap_info_structs,
81 * but get_swap_page() doesn't need to look at full ones.
82 * This uses its own lock instead of swap_lock because when a
83 * swap_info_struct changes between not-full/full, it needs to
84 * add/remove itself to/from this list, but the swap_info_struct->lock
85 * is held and the locking order requires swap_lock to be taken
86 * before any swap_info_struct->lock.
88 static struct plist_head *swap_avail_heads;
89 static DEFINE_SPINLOCK(swap_avail_lock);
91 struct swap_info_struct *swap_info[MAX_SWAPFILES];
93 static DEFINE_MUTEX(swapon_mutex);
95 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
96 /* Activity counter to indicate that a swapon or swapoff has occurred */
97 static atomic_t proc_poll_event = ATOMIC_INIT(0);
99 atomic_t nr_rotate_swap = ATOMIC_INIT(0);
101 static struct swap_info_struct *swap_type_to_swap_info(int type)
103 if (type >= READ_ONCE(nr_swapfiles))
106 smp_rmb(); /* Pairs with smp_wmb in alloc_swap_info. */
107 return READ_ONCE(swap_info[type]);
110 static inline unsigned char swap_count(unsigned char ent)
112 return ent & ~SWAP_HAS_CACHE; /* may include COUNT_CONTINUED flag */
115 /* Reclaim the swap entry anyway if possible */
116 #define TTRS_ANYWAY 0x1
118 * Reclaim the swap entry if there are no more mappings of the
121 #define TTRS_UNMAPPED 0x2
122 /* Reclaim the swap entry if swap is getting full*/
123 #define TTRS_FULL 0x4
125 /* returns 1 if swap entry is freed */
126 static int __try_to_reclaim_swap(struct swap_info_struct *si,
127 unsigned long offset, unsigned long flags)
129 swp_entry_t entry = swp_entry(si->type, offset);
133 page = find_get_page(swap_address_space(entry), offset);
137 * When this function is called from scan_swap_map_slots() and it's
138 * called by vmscan.c at reclaiming pages. So, we hold a lock on a page,
139 * here. We have to use trylock for avoiding deadlock. This is a special
140 * case and you should use try_to_free_swap() with explicit lock_page()
141 * in usual operations.
143 if (trylock_page(page)) {
144 if ((flags & TTRS_ANYWAY) ||
145 ((flags & TTRS_UNMAPPED) && !page_mapped(page)) ||
146 ((flags & TTRS_FULL) && mem_cgroup_swap_full(page)))
147 ret = try_to_free_swap(page);
154 static inline struct swap_extent *first_se(struct swap_info_struct *sis)
156 struct rb_node *rb = rb_first(&sis->swap_extent_root);
157 return rb_entry(rb, struct swap_extent, rb_node);
160 static inline struct swap_extent *next_se(struct swap_extent *se)
162 struct rb_node *rb = rb_next(&se->rb_node);
163 return rb ? rb_entry(rb, struct swap_extent, rb_node) : NULL;
167 * swapon tell device that all the old swap contents can be discarded,
168 * to allow the swap device to optimize its wear-levelling.
170 static int discard_swap(struct swap_info_struct *si)
172 struct swap_extent *se;
173 sector_t start_block;
177 /* Do not discard the swap header page! */
179 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
180 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
182 err = blkdev_issue_discard(si->bdev, start_block,
183 nr_blocks, GFP_KERNEL, 0);
189 for (se = next_se(se); se; se = next_se(se)) {
190 start_block = se->start_block << (PAGE_SHIFT - 9);
191 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
193 err = blkdev_issue_discard(si->bdev, start_block,
194 nr_blocks, GFP_KERNEL, 0);
200 return err; /* That will often be -EOPNOTSUPP */
203 static struct swap_extent *
204 offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
206 struct swap_extent *se;
209 rb = sis->swap_extent_root.rb_node;
211 se = rb_entry(rb, struct swap_extent, rb_node);
212 if (offset < se->start_page)
214 else if (offset >= se->start_page + se->nr_pages)
219 /* It *must* be present */
223 sector_t swap_page_sector(struct page *page)
225 struct swap_info_struct *sis = page_swap_info(page);
226 struct swap_extent *se;
230 offset = __page_file_index(page);
231 se = offset_to_swap_extent(sis, offset);
232 sector = se->start_block + (offset - se->start_page);
233 return sector << (PAGE_SHIFT - 9);
237 * swap allocation tell device that a cluster of swap can now be discarded,
238 * to allow the swap device to optimize its wear-levelling.
240 static void discard_swap_cluster(struct swap_info_struct *si,
241 pgoff_t start_page, pgoff_t nr_pages)
243 struct swap_extent *se = offset_to_swap_extent(si, start_page);
246 pgoff_t offset = start_page - se->start_page;
247 sector_t start_block = se->start_block + offset;
248 sector_t nr_blocks = se->nr_pages - offset;
250 if (nr_blocks > nr_pages)
251 nr_blocks = nr_pages;
252 start_page += nr_blocks;
253 nr_pages -= nr_blocks;
255 start_block <<= PAGE_SHIFT - 9;
256 nr_blocks <<= PAGE_SHIFT - 9;
257 if (blkdev_issue_discard(si->bdev, start_block,
258 nr_blocks, GFP_NOIO, 0))
265 #ifdef CONFIG_THP_SWAP
266 #define SWAPFILE_CLUSTER HPAGE_PMD_NR
268 #define swap_entry_size(size) (size)
270 #define SWAPFILE_CLUSTER 256
273 * Define swap_entry_size() as constant to let compiler to optimize
274 * out some code if !CONFIG_THP_SWAP
276 #define swap_entry_size(size) 1
278 #define LATENCY_LIMIT 256
280 static inline void cluster_set_flag(struct swap_cluster_info *info,
286 static inline unsigned int cluster_count(struct swap_cluster_info *info)
291 static inline void cluster_set_count(struct swap_cluster_info *info,
297 static inline void cluster_set_count_flag(struct swap_cluster_info *info,
298 unsigned int c, unsigned int f)
304 static inline unsigned int cluster_next(struct swap_cluster_info *info)
309 static inline void cluster_set_next(struct swap_cluster_info *info,
315 static inline void cluster_set_next_flag(struct swap_cluster_info *info,
316 unsigned int n, unsigned int f)
322 static inline bool cluster_is_free(struct swap_cluster_info *info)
324 return info->flags & CLUSTER_FLAG_FREE;
327 static inline bool cluster_is_null(struct swap_cluster_info *info)
329 return info->flags & CLUSTER_FLAG_NEXT_NULL;
332 static inline void cluster_set_null(struct swap_cluster_info *info)
334 info->flags = CLUSTER_FLAG_NEXT_NULL;
338 static inline bool cluster_is_huge(struct swap_cluster_info *info)
340 if (IS_ENABLED(CONFIG_THP_SWAP))
341 return info->flags & CLUSTER_FLAG_HUGE;
345 static inline void cluster_clear_huge(struct swap_cluster_info *info)
347 info->flags &= ~CLUSTER_FLAG_HUGE;
350 static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
351 unsigned long offset)
353 struct swap_cluster_info *ci;
355 ci = si->cluster_info;
357 ci += offset / SWAPFILE_CLUSTER;
358 spin_lock(&ci->lock);
363 static inline void unlock_cluster(struct swap_cluster_info *ci)
366 spin_unlock(&ci->lock);
370 * Determine the locking method in use for this device. Return
371 * swap_cluster_info if SSD-style cluster-based locking is in place.
373 static inline struct swap_cluster_info *lock_cluster_or_swap_info(
374 struct swap_info_struct *si, unsigned long offset)
376 struct swap_cluster_info *ci;
378 /* Try to use fine-grained SSD-style locking if available: */
379 ci = lock_cluster(si, offset);
380 /* Otherwise, fall back to traditional, coarse locking: */
382 spin_lock(&si->lock);
387 static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
388 struct swap_cluster_info *ci)
393 spin_unlock(&si->lock);
396 static inline bool cluster_list_empty(struct swap_cluster_list *list)
398 return cluster_is_null(&list->head);
401 static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
403 return cluster_next(&list->head);
406 static void cluster_list_init(struct swap_cluster_list *list)
408 cluster_set_null(&list->head);
409 cluster_set_null(&list->tail);
412 static void cluster_list_add_tail(struct swap_cluster_list *list,
413 struct swap_cluster_info *ci,
416 if (cluster_list_empty(list)) {
417 cluster_set_next_flag(&list->head, idx, 0);
418 cluster_set_next_flag(&list->tail, idx, 0);
420 struct swap_cluster_info *ci_tail;
421 unsigned int tail = cluster_next(&list->tail);
424 * Nested cluster lock, but both cluster locks are
425 * only acquired when we held swap_info_struct->lock
428 spin_lock_nested(&ci_tail->lock, SINGLE_DEPTH_NESTING);
429 cluster_set_next(ci_tail, idx);
430 spin_unlock(&ci_tail->lock);
431 cluster_set_next_flag(&list->tail, idx, 0);
435 static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
436 struct swap_cluster_info *ci)
440 idx = cluster_next(&list->head);
441 if (cluster_next(&list->tail) == idx) {
442 cluster_set_null(&list->head);
443 cluster_set_null(&list->tail);
445 cluster_set_next_flag(&list->head,
446 cluster_next(&ci[idx]), 0);
451 /* Add a cluster to discard list and schedule it to do discard */
452 static void swap_cluster_schedule_discard(struct swap_info_struct *si,
456 * If scan_swap_map() can't find a free cluster, it will check
457 * si->swap_map directly. To make sure the discarding cluster isn't
458 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
459 * will be cleared after discard
461 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
462 SWAP_MAP_BAD, SWAPFILE_CLUSTER);
464 cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
466 schedule_work(&si->discard_work);
469 static void __free_cluster(struct swap_info_struct *si, unsigned long idx)
471 struct swap_cluster_info *ci = si->cluster_info;
473 cluster_set_flag(ci + idx, CLUSTER_FLAG_FREE);
474 cluster_list_add_tail(&si->free_clusters, ci, idx);
478 * Doing discard actually. After a cluster discard is finished, the cluster
479 * will be added to free cluster list. caller should hold si->lock.
481 static void swap_do_scheduled_discard(struct swap_info_struct *si)
483 struct swap_cluster_info *info, *ci;
486 info = si->cluster_info;
488 while (!cluster_list_empty(&si->discard_clusters)) {
489 idx = cluster_list_del_first(&si->discard_clusters, info);
490 spin_unlock(&si->lock);
492 discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
495 spin_lock(&si->lock);
496 ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
497 __free_cluster(si, idx);
498 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
499 0, SWAPFILE_CLUSTER);
504 static void swap_discard_work(struct work_struct *work)
506 struct swap_info_struct *si;
508 si = container_of(work, struct swap_info_struct, discard_work);
510 spin_lock(&si->lock);
511 swap_do_scheduled_discard(si);
512 spin_unlock(&si->lock);
515 static void alloc_cluster(struct swap_info_struct *si, unsigned long idx)
517 struct swap_cluster_info *ci = si->cluster_info;
519 VM_BUG_ON(cluster_list_first(&si->free_clusters) != idx);
520 cluster_list_del_first(&si->free_clusters, ci);
521 cluster_set_count_flag(ci + idx, 0, 0);
524 static void free_cluster(struct swap_info_struct *si, unsigned long idx)
526 struct swap_cluster_info *ci = si->cluster_info + idx;
528 VM_BUG_ON(cluster_count(ci) != 0);
530 * If the swap is discardable, prepare discard the cluster
531 * instead of free it immediately. The cluster will be freed
534 if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
535 (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
536 swap_cluster_schedule_discard(si, idx);
540 __free_cluster(si, idx);
544 * The cluster corresponding to page_nr will be used. The cluster will be
545 * removed from free cluster list and its usage counter will be increased.
547 static void inc_cluster_info_page(struct swap_info_struct *p,
548 struct swap_cluster_info *cluster_info, unsigned long page_nr)
550 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
554 if (cluster_is_free(&cluster_info[idx]))
555 alloc_cluster(p, idx);
557 VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
558 cluster_set_count(&cluster_info[idx],
559 cluster_count(&cluster_info[idx]) + 1);
563 * The cluster corresponding to page_nr decreases one usage. If the usage
564 * counter becomes 0, which means no page in the cluster is in using, we can
565 * optionally discard the cluster and add it to free cluster list.
567 static void dec_cluster_info_page(struct swap_info_struct *p,
568 struct swap_cluster_info *cluster_info, unsigned long page_nr)
570 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
575 VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
576 cluster_set_count(&cluster_info[idx],
577 cluster_count(&cluster_info[idx]) - 1);
579 if (cluster_count(&cluster_info[idx]) == 0)
580 free_cluster(p, idx);
584 * It's possible scan_swap_map() uses a free cluster in the middle of free
585 * cluster list. Avoiding such abuse to avoid list corruption.
588 scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
589 unsigned long offset)
591 struct percpu_cluster *percpu_cluster;
594 offset /= SWAPFILE_CLUSTER;
595 conflict = !cluster_list_empty(&si->free_clusters) &&
596 offset != cluster_list_first(&si->free_clusters) &&
597 cluster_is_free(&si->cluster_info[offset]);
602 percpu_cluster = this_cpu_ptr(si->percpu_cluster);
603 cluster_set_null(&percpu_cluster->index);
608 * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
609 * might involve allocating a new cluster for current CPU too.
611 static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
612 unsigned long *offset, unsigned long *scan_base)
614 struct percpu_cluster *cluster;
615 struct swap_cluster_info *ci;
616 unsigned long tmp, max;
619 cluster = this_cpu_ptr(si->percpu_cluster);
620 if (cluster_is_null(&cluster->index)) {
621 if (!cluster_list_empty(&si->free_clusters)) {
622 cluster->index = si->free_clusters.head;
623 cluster->next = cluster_next(&cluster->index) *
625 } else if (!cluster_list_empty(&si->discard_clusters)) {
627 * we don't have free cluster but have some clusters in
628 * discarding, do discard now and reclaim them, then
629 * reread cluster_next_cpu since we dropped si->lock
631 swap_do_scheduled_discard(si);
632 *scan_base = this_cpu_read(*si->cluster_next_cpu);
633 *offset = *scan_base;
640 * Other CPUs can use our cluster if they can't find a free cluster,
641 * check if there is still free entry in the cluster
644 max = min_t(unsigned long, si->max,
645 (cluster_next(&cluster->index) + 1) * SWAPFILE_CLUSTER);
647 ci = lock_cluster(si, tmp);
649 if (!si->swap_map[tmp])
656 cluster_set_null(&cluster->index);
659 cluster->next = tmp + 1;
665 static void __del_from_avail_list(struct swap_info_struct *p)
670 plist_del(&p->avail_lists[nid], &swap_avail_heads[nid]);
673 static void del_from_avail_list(struct swap_info_struct *p)
675 spin_lock(&swap_avail_lock);
676 __del_from_avail_list(p);
677 spin_unlock(&swap_avail_lock);
680 static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
681 unsigned int nr_entries)
683 unsigned int end = offset + nr_entries - 1;
685 if (offset == si->lowest_bit)
686 si->lowest_bit += nr_entries;
687 if (end == si->highest_bit)
688 WRITE_ONCE(si->highest_bit, si->highest_bit - nr_entries);
689 si->inuse_pages += nr_entries;
690 if (si->inuse_pages == si->pages) {
691 si->lowest_bit = si->max;
693 del_from_avail_list(si);
697 static void add_to_avail_list(struct swap_info_struct *p)
701 spin_lock(&swap_avail_lock);
703 WARN_ON(!plist_node_empty(&p->avail_lists[nid]));
704 plist_add(&p->avail_lists[nid], &swap_avail_heads[nid]);
706 spin_unlock(&swap_avail_lock);
709 static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
710 unsigned int nr_entries)
712 unsigned long begin = offset;
713 unsigned long end = offset + nr_entries - 1;
714 void (*swap_slot_free_notify)(struct block_device *, unsigned long);
716 if (offset < si->lowest_bit)
717 si->lowest_bit = offset;
718 if (end > si->highest_bit) {
719 bool was_full = !si->highest_bit;
721 WRITE_ONCE(si->highest_bit, end);
722 if (was_full && (si->flags & SWP_WRITEOK))
723 add_to_avail_list(si);
725 atomic_long_add(nr_entries, &nr_swap_pages);
726 si->inuse_pages -= nr_entries;
727 if (si->flags & SWP_BLKDEV)
728 swap_slot_free_notify =
729 si->bdev->bd_disk->fops->swap_slot_free_notify;
731 swap_slot_free_notify = NULL;
732 while (offset <= end) {
733 arch_swap_invalidate_page(si->type, offset);
734 frontswap_invalidate_page(si->type, offset);
735 if (swap_slot_free_notify)
736 swap_slot_free_notify(si->bdev, offset);
739 clear_shadow_from_swap_cache(si->type, begin, end);
742 static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
746 if (!(si->flags & SWP_SOLIDSTATE)) {
747 si->cluster_next = next;
751 prev = this_cpu_read(*si->cluster_next_cpu);
753 * Cross the swap address space size aligned trunk, choose
754 * another trunk randomly to avoid lock contention on swap
755 * address space if possible.
757 if ((prev >> SWAP_ADDRESS_SPACE_SHIFT) !=
758 (next >> SWAP_ADDRESS_SPACE_SHIFT)) {
759 /* No free swap slots available */
760 if (si->highest_bit <= si->lowest_bit)
762 next = si->lowest_bit +
763 prandom_u32_max(si->highest_bit - si->lowest_bit + 1);
764 next = ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES);
765 next = max_t(unsigned int, next, si->lowest_bit);
767 this_cpu_write(*si->cluster_next_cpu, next);
770 static int scan_swap_map_slots(struct swap_info_struct *si,
771 unsigned char usage, int nr,
774 struct swap_cluster_info *ci;
775 unsigned long offset;
776 unsigned long scan_base;
777 unsigned long last_in_cluster = 0;
778 int latency_ration = LATENCY_LIMIT;
780 bool scanned_many = false;
783 * We try to cluster swap pages by allocating them sequentially
784 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
785 * way, however, we resort to first-free allocation, starting
786 * a new cluster. This prevents us from scattering swap pages
787 * all over the entire swap partition, so that we reduce
788 * overall disk seek times between swap pages. -- sct
789 * But we do now try to find an empty cluster. -Andrea
790 * And we let swap pages go all over an SSD partition. Hugh
793 si->flags += SWP_SCANNING;
795 * Use percpu scan base for SSD to reduce lock contention on
796 * cluster and swap cache. For HDD, sequential access is more
799 if (si->flags & SWP_SOLIDSTATE)
800 scan_base = this_cpu_read(*si->cluster_next_cpu);
802 scan_base = si->cluster_next;
806 if (si->cluster_info) {
807 if (!scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
809 } else if (unlikely(!si->cluster_nr--)) {
810 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
811 si->cluster_nr = SWAPFILE_CLUSTER - 1;
815 spin_unlock(&si->lock);
818 * If seek is expensive, start searching for new cluster from
819 * start of partition, to minimize the span of allocated swap.
820 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
821 * case, just handled by scan_swap_map_try_ssd_cluster() above.
823 scan_base = offset = si->lowest_bit;
824 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
826 /* Locate the first empty (unaligned) cluster */
827 for (; last_in_cluster <= si->highest_bit; offset++) {
828 if (si->swap_map[offset])
829 last_in_cluster = offset + SWAPFILE_CLUSTER;
830 else if (offset == last_in_cluster) {
831 spin_lock(&si->lock);
832 offset -= SWAPFILE_CLUSTER - 1;
833 si->cluster_next = offset;
834 si->cluster_nr = SWAPFILE_CLUSTER - 1;
837 if (unlikely(--latency_ration < 0)) {
839 latency_ration = LATENCY_LIMIT;
844 spin_lock(&si->lock);
845 si->cluster_nr = SWAPFILE_CLUSTER - 1;
849 if (si->cluster_info) {
850 while (scan_swap_map_ssd_cluster_conflict(si, offset)) {
851 /* take a break if we already got some slots */
854 if (!scan_swap_map_try_ssd_cluster(si, &offset,
859 if (!(si->flags & SWP_WRITEOK))
861 if (!si->highest_bit)
863 if (offset > si->highest_bit)
864 scan_base = offset = si->lowest_bit;
866 ci = lock_cluster(si, offset);
867 /* reuse swap entry of cache-only swap if not busy. */
868 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
871 spin_unlock(&si->lock);
872 swap_was_freed = __try_to_reclaim_swap(si, offset, TTRS_ANYWAY);
873 spin_lock(&si->lock);
874 /* entry was freed successfully, try to use this again */
877 goto scan; /* check next one */
880 if (si->swap_map[offset]) {
887 WRITE_ONCE(si->swap_map[offset], usage);
888 inc_cluster_info_page(si, si->cluster_info, offset);
891 swap_range_alloc(si, offset, 1);
892 slots[n_ret++] = swp_entry(si->type, offset);
894 /* got enough slots or reach max slots? */
895 if ((n_ret == nr) || (offset >= si->highest_bit))
898 /* search for next available slot */
900 /* time to take a break? */
901 if (unlikely(--latency_ration < 0)) {
904 spin_unlock(&si->lock);
906 spin_lock(&si->lock);
907 latency_ration = LATENCY_LIMIT;
910 /* try to get more slots in cluster */
911 if (si->cluster_info) {
912 if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
914 } else if (si->cluster_nr && !si->swap_map[++offset]) {
915 /* non-ssd case, still more slots in cluster? */
921 * Even if there's no free clusters available (fragmented),
922 * try to scan a little more quickly with lock held unless we
923 * have scanned too many slots already.
926 unsigned long scan_limit;
928 if (offset < scan_base)
929 scan_limit = scan_base;
931 scan_limit = si->highest_bit;
932 for (; offset <= scan_limit && --latency_ration > 0;
934 if (!si->swap_map[offset])
940 set_cluster_next(si, offset + 1);
941 si->flags -= SWP_SCANNING;
945 spin_unlock(&si->lock);
946 while (++offset <= READ_ONCE(si->highest_bit)) {
947 if (data_race(!si->swap_map[offset])) {
948 spin_lock(&si->lock);
951 if (vm_swap_full() &&
952 READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
953 spin_lock(&si->lock);
956 if (unlikely(--latency_ration < 0)) {
958 latency_ration = LATENCY_LIMIT;
962 offset = si->lowest_bit;
963 while (offset < scan_base) {
964 if (data_race(!si->swap_map[offset])) {
965 spin_lock(&si->lock);
968 if (vm_swap_full() &&
969 READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
970 spin_lock(&si->lock);
973 if (unlikely(--latency_ration < 0)) {
975 latency_ration = LATENCY_LIMIT;
980 spin_lock(&si->lock);
983 si->flags -= SWP_SCANNING;
987 static int swap_alloc_cluster(struct swap_info_struct *si, swp_entry_t *slot)
990 struct swap_cluster_info *ci;
991 unsigned long offset, i;
995 * Should not even be attempting cluster allocations when huge
996 * page swap is disabled. Warn and fail the allocation.
998 if (!IS_ENABLED(CONFIG_THP_SWAP)) {
1003 if (cluster_list_empty(&si->free_clusters))
1006 idx = cluster_list_first(&si->free_clusters);
1007 offset = idx * SWAPFILE_CLUSTER;
1008 ci = lock_cluster(si, offset);
1009 alloc_cluster(si, idx);
1010 cluster_set_count_flag(ci, SWAPFILE_CLUSTER, CLUSTER_FLAG_HUGE);
1012 map = si->swap_map + offset;
1013 for (i = 0; i < SWAPFILE_CLUSTER; i++)
1014 map[i] = SWAP_HAS_CACHE;
1016 swap_range_alloc(si, offset, SWAPFILE_CLUSTER);
1017 *slot = swp_entry(si->type, offset);
1022 static void swap_free_cluster(struct swap_info_struct *si, unsigned long idx)
1024 unsigned long offset = idx * SWAPFILE_CLUSTER;
1025 struct swap_cluster_info *ci;
1027 ci = lock_cluster(si, offset);
1028 memset(si->swap_map + offset, 0, SWAPFILE_CLUSTER);
1029 cluster_set_count_flag(ci, 0, 0);
1030 free_cluster(si, idx);
1032 swap_range_free(si, offset, SWAPFILE_CLUSTER);
1035 static unsigned long scan_swap_map(struct swap_info_struct *si,
1036 unsigned char usage)
1041 n_ret = scan_swap_map_slots(si, usage, 1, &entry);
1044 return swp_offset(entry);
1050 int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_size)
1052 unsigned long size = swap_entry_size(entry_size);
1053 struct swap_info_struct *si, *next;
1058 /* Only single cluster request supported */
1059 WARN_ON_ONCE(n_goal > 1 && size == SWAPFILE_CLUSTER);
1061 spin_lock(&swap_avail_lock);
1063 avail_pgs = atomic_long_read(&nr_swap_pages) / size;
1064 if (avail_pgs <= 0) {
1065 spin_unlock(&swap_avail_lock);
1069 n_goal = min3((long)n_goal, (long)SWAP_BATCH, avail_pgs);
1071 atomic_long_sub(n_goal * size, &nr_swap_pages);
1074 node = numa_node_id();
1075 plist_for_each_entry_safe(si, next, &swap_avail_heads[node], avail_lists[node]) {
1076 /* requeue si to after same-priority siblings */
1077 plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]);
1078 spin_unlock(&swap_avail_lock);
1079 spin_lock(&si->lock);
1080 if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
1081 spin_lock(&swap_avail_lock);
1082 if (plist_node_empty(&si->avail_lists[node])) {
1083 spin_unlock(&si->lock);
1086 WARN(!si->highest_bit,
1087 "swap_info %d in list but !highest_bit\n",
1089 WARN(!(si->flags & SWP_WRITEOK),
1090 "swap_info %d in list but !SWP_WRITEOK\n",
1092 __del_from_avail_list(si);
1093 spin_unlock(&si->lock);
1096 if (size == SWAPFILE_CLUSTER) {
1097 if (si->flags & SWP_BLKDEV)
1098 n_ret = swap_alloc_cluster(si, swp_entries);
1100 n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
1101 n_goal, swp_entries);
1102 spin_unlock(&si->lock);
1103 if (n_ret || size == SWAPFILE_CLUSTER)
1105 pr_debug("scan_swap_map of si %d failed to find offset\n",
1108 spin_lock(&swap_avail_lock);
1111 * if we got here, it's likely that si was almost full before,
1112 * and since scan_swap_map() can drop the si->lock, multiple
1113 * callers probably all tried to get a page from the same si
1114 * and it filled up before we could get one; or, the si filled
1115 * up between us dropping swap_avail_lock and taking si->lock.
1116 * Since we dropped the swap_avail_lock, the swap_avail_head
1117 * list may have been modified; so if next is still in the
1118 * swap_avail_head list then try it, otherwise start over
1119 * if we have not gotten any slots.
1121 if (plist_node_empty(&next->avail_lists[node]))
1125 spin_unlock(&swap_avail_lock);
1129 atomic_long_add((long)(n_goal - n_ret) * size,
1135 /* The only caller of this function is now suspend routine */
1136 swp_entry_t get_swap_page_of_type(int type)
1138 struct swap_info_struct *si = swap_type_to_swap_info(type);
1144 spin_lock(&si->lock);
1145 if (si->flags & SWP_WRITEOK) {
1146 /* This is called for allocating swap entry, not cache */
1147 offset = scan_swap_map(si, 1);
1149 atomic_long_dec(&nr_swap_pages);
1150 spin_unlock(&si->lock);
1151 return swp_entry(type, offset);
1154 spin_unlock(&si->lock);
1156 return (swp_entry_t) {0};
1159 static struct swap_info_struct *__swap_info_get(swp_entry_t entry)
1161 struct swap_info_struct *p;
1162 unsigned long offset;
1166 p = swp_swap_info(entry);
1169 if (data_race(!(p->flags & SWP_USED)))
1171 offset = swp_offset(entry);
1172 if (offset >= p->max)
1177 pr_err("swap_info_get: %s%08lx\n", Bad_offset, entry.val);
1180 pr_err("swap_info_get: %s%08lx\n", Unused_file, entry.val);
1183 pr_err("swap_info_get: %s%08lx\n", Bad_file, entry.val);
1188 static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
1190 struct swap_info_struct *p;
1192 p = __swap_info_get(entry);
1195 if (data_race(!p->swap_map[swp_offset(entry)]))
1200 pr_err("swap_info_get: %s%08lx\n", Unused_offset, entry.val);
1205 static struct swap_info_struct *swap_info_get(swp_entry_t entry)
1207 struct swap_info_struct *p;
1209 p = _swap_info_get(entry);
1211 spin_lock(&p->lock);
1215 static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
1216 struct swap_info_struct *q)
1218 struct swap_info_struct *p;
1220 p = _swap_info_get(entry);
1224 spin_unlock(&q->lock);
1226 spin_lock(&p->lock);
1231 static unsigned char __swap_entry_free_locked(struct swap_info_struct *p,
1232 unsigned long offset,
1233 unsigned char usage)
1235 unsigned char count;
1236 unsigned char has_cache;
1238 count = p->swap_map[offset];
1240 has_cache = count & SWAP_HAS_CACHE;
1241 count &= ~SWAP_HAS_CACHE;
1243 if (usage == SWAP_HAS_CACHE) {
1244 VM_BUG_ON(!has_cache);
1246 } else if (count == SWAP_MAP_SHMEM) {
1248 * Or we could insist on shmem.c using a special
1249 * swap_shmem_free() and free_shmem_swap_and_cache()...
1252 } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
1253 if (count == COUNT_CONTINUED) {
1254 if (swap_count_continued(p, offset, count))
1255 count = SWAP_MAP_MAX | COUNT_CONTINUED;
1257 count = SWAP_MAP_MAX;
1262 usage = count | has_cache;
1264 WRITE_ONCE(p->swap_map[offset], usage);
1266 WRITE_ONCE(p->swap_map[offset], SWAP_HAS_CACHE);
1272 * Check whether swap entry is valid in the swap device. If so,
1273 * return pointer to swap_info_struct, and keep the swap entry valid
1274 * via preventing the swap device from being swapoff, until
1275 * put_swap_device() is called. Otherwise return NULL.
1277 * The entirety of the RCU read critical section must come before the
1278 * return from or after the call to synchronize_rcu() in
1279 * enable_swap_info() or swapoff(). So if "si->flags & SWP_VALID" is
1280 * true, the si->map, si->cluster_info, etc. must be valid in the
1283 * Notice that swapoff or swapoff+swapon can still happen before the
1284 * rcu_read_lock() in get_swap_device() or after the rcu_read_unlock()
1285 * in put_swap_device() if there isn't any other way to prevent
1286 * swapoff, such as page lock, page table lock, etc. The caller must
1287 * be prepared for that. For example, the following situation is
1292 * ... swapoff+swapon
1293 * __read_swap_cache_async()
1294 * swapcache_prepare()
1295 * __swap_duplicate()
1297 * // verify PTE not changed
1299 * In __swap_duplicate(), the swap_map need to be checked before
1300 * changing partly because the specified swap entry may be for another
1301 * swap device which has been swapoff. And in do_swap_page(), after
1302 * the page is read from the swap device, the PTE is verified not
1303 * changed with the page table locked to check whether the swap device
1304 * has been swapoff or swapoff+swapon.
1306 struct swap_info_struct *get_swap_device(swp_entry_t entry)
1308 struct swap_info_struct *si;
1309 unsigned long offset;
1313 si = swp_swap_info(entry);
1318 if (data_race(!(si->flags & SWP_VALID)))
1320 offset = swp_offset(entry);
1321 if (offset >= si->max)
1326 pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
1334 static unsigned char __swap_entry_free(struct swap_info_struct *p,
1337 struct swap_cluster_info *ci;
1338 unsigned long offset = swp_offset(entry);
1339 unsigned char usage;
1341 ci = lock_cluster_or_swap_info(p, offset);
1342 usage = __swap_entry_free_locked(p, offset, 1);
1343 unlock_cluster_or_swap_info(p, ci);
1345 free_swap_slot(entry);
1350 static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
1352 struct swap_cluster_info *ci;
1353 unsigned long offset = swp_offset(entry);
1354 unsigned char count;
1356 ci = lock_cluster(p, offset);
1357 count = p->swap_map[offset];
1358 VM_BUG_ON(count != SWAP_HAS_CACHE);
1359 p->swap_map[offset] = 0;
1360 dec_cluster_info_page(p, p->cluster_info, offset);
1363 mem_cgroup_uncharge_swap(entry, 1);
1364 swap_range_free(p, offset, 1);
1368 * Caller has made sure that the swap device corresponding to entry
1369 * is still around or has not been recycled.
1371 void swap_free(swp_entry_t entry)
1373 struct swap_info_struct *p;
1375 p = _swap_info_get(entry);
1377 __swap_entry_free(p, entry);
1381 * Called after dropping swapcache to decrease refcnt to swap entries.
1383 void put_swap_page(struct page *page, swp_entry_t entry)
1385 unsigned long offset = swp_offset(entry);
1386 unsigned long idx = offset / SWAPFILE_CLUSTER;
1387 struct swap_cluster_info *ci;
1388 struct swap_info_struct *si;
1390 unsigned int i, free_entries = 0;
1392 int size = swap_entry_size(thp_nr_pages(page));
1394 si = _swap_info_get(entry);
1398 ci = lock_cluster_or_swap_info(si, offset);
1399 if (size == SWAPFILE_CLUSTER) {
1400 VM_BUG_ON(!cluster_is_huge(ci));
1401 map = si->swap_map + offset;
1402 for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1404 VM_BUG_ON(!(val & SWAP_HAS_CACHE));
1405 if (val == SWAP_HAS_CACHE)
1408 cluster_clear_huge(ci);
1409 if (free_entries == SWAPFILE_CLUSTER) {
1410 unlock_cluster_or_swap_info(si, ci);
1411 spin_lock(&si->lock);
1412 mem_cgroup_uncharge_swap(entry, SWAPFILE_CLUSTER);
1413 swap_free_cluster(si, idx);
1414 spin_unlock(&si->lock);
1418 for (i = 0; i < size; i++, entry.val++) {
1419 if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) {
1420 unlock_cluster_or_swap_info(si, ci);
1421 free_swap_slot(entry);
1424 lock_cluster_or_swap_info(si, offset);
1427 unlock_cluster_or_swap_info(si, ci);
1430 #ifdef CONFIG_THP_SWAP
1431 int split_swap_cluster(swp_entry_t entry)
1433 struct swap_info_struct *si;
1434 struct swap_cluster_info *ci;
1435 unsigned long offset = swp_offset(entry);
1437 si = _swap_info_get(entry);
1440 ci = lock_cluster(si, offset);
1441 cluster_clear_huge(ci);
1447 static int swp_entry_cmp(const void *ent1, const void *ent2)
1449 const swp_entry_t *e1 = ent1, *e2 = ent2;
1451 return (int)swp_type(*e1) - (int)swp_type(*e2);
1454 void swapcache_free_entries(swp_entry_t *entries, int n)
1456 struct swap_info_struct *p, *prev;
1466 * Sort swap entries by swap device, so each lock is only taken once.
1467 * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
1468 * so low that it isn't necessary to optimize further.
1470 if (nr_swapfiles > 1)
1471 sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
1472 for (i = 0; i < n; ++i) {
1473 p = swap_info_get_cont(entries[i], prev);
1475 swap_entry_free(p, entries[i]);
1479 spin_unlock(&p->lock);
1483 * How many references to page are currently swapped out?
1484 * This does not give an exact answer when swap count is continued,
1485 * but does include the high COUNT_CONTINUED flag to allow for that.
1487 int page_swapcount(struct page *page)
1490 struct swap_info_struct *p;
1491 struct swap_cluster_info *ci;
1493 unsigned long offset;
1495 entry.val = page_private(page);
1496 p = _swap_info_get(entry);
1498 offset = swp_offset(entry);
1499 ci = lock_cluster_or_swap_info(p, offset);
1500 count = swap_count(p->swap_map[offset]);
1501 unlock_cluster_or_swap_info(p, ci);
1506 int __swap_count(swp_entry_t entry)
1508 struct swap_info_struct *si;
1509 pgoff_t offset = swp_offset(entry);
1512 si = get_swap_device(entry);
1514 count = swap_count(si->swap_map[offset]);
1515 put_swap_device(si);
1520 static int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
1523 pgoff_t offset = swp_offset(entry);
1524 struct swap_cluster_info *ci;
1526 ci = lock_cluster_or_swap_info(si, offset);
1527 count = swap_count(si->swap_map[offset]);
1528 unlock_cluster_or_swap_info(si, ci);
1533 * How many references to @entry are currently swapped out?
1534 * This does not give an exact answer when swap count is continued,
1535 * but does include the high COUNT_CONTINUED flag to allow for that.
1537 int __swp_swapcount(swp_entry_t entry)
1540 struct swap_info_struct *si;
1542 si = get_swap_device(entry);
1544 count = swap_swapcount(si, entry);
1545 put_swap_device(si);
1551 * How many references to @entry are currently swapped out?
1552 * This considers COUNT_CONTINUED so it returns exact answer.
1554 int swp_swapcount(swp_entry_t entry)
1556 int count, tmp_count, n;
1557 struct swap_info_struct *p;
1558 struct swap_cluster_info *ci;
1563 p = _swap_info_get(entry);
1567 offset = swp_offset(entry);
1569 ci = lock_cluster_or_swap_info(p, offset);
1571 count = swap_count(p->swap_map[offset]);
1572 if (!(count & COUNT_CONTINUED))
1575 count &= ~COUNT_CONTINUED;
1576 n = SWAP_MAP_MAX + 1;
1578 page = vmalloc_to_page(p->swap_map + offset);
1579 offset &= ~PAGE_MASK;
1580 VM_BUG_ON(page_private(page) != SWP_CONTINUED);
1583 page = list_next_entry(page, lru);
1584 map = kmap_atomic(page);
1585 tmp_count = map[offset];
1588 count += (tmp_count & ~COUNT_CONTINUED) * n;
1589 n *= (SWAP_CONT_MAX + 1);
1590 } while (tmp_count & COUNT_CONTINUED);
1592 unlock_cluster_or_swap_info(p, ci);
1596 static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
1599 struct swap_cluster_info *ci;
1600 unsigned char *map = si->swap_map;
1601 unsigned long roffset = swp_offset(entry);
1602 unsigned long offset = round_down(roffset, SWAPFILE_CLUSTER);
1606 ci = lock_cluster_or_swap_info(si, offset);
1607 if (!ci || !cluster_is_huge(ci)) {
1608 if (swap_count(map[roffset]))
1612 for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1613 if (swap_count(map[offset + i])) {
1619 unlock_cluster_or_swap_info(si, ci);
1623 static bool page_swapped(struct page *page)
1626 struct swap_info_struct *si;
1628 if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!PageTransCompound(page)))
1629 return page_swapcount(page) != 0;
1631 page = compound_head(page);
1632 entry.val = page_private(page);
1633 si = _swap_info_get(entry);
1635 return swap_page_trans_huge_swapped(si, entry);
1639 static int page_trans_huge_map_swapcount(struct page *page, int *total_mapcount,
1640 int *total_swapcount)
1642 int i, map_swapcount, _total_mapcount, _total_swapcount;
1643 unsigned long offset = 0;
1644 struct swap_info_struct *si;
1645 struct swap_cluster_info *ci = NULL;
1646 unsigned char *map = NULL;
1647 int mapcount, swapcount = 0;
1649 /* hugetlbfs shouldn't call it */
1650 VM_BUG_ON_PAGE(PageHuge(page), page);
1652 if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!PageTransCompound(page))) {
1653 mapcount = page_trans_huge_mapcount(page, total_mapcount);
1654 if (PageSwapCache(page))
1655 swapcount = page_swapcount(page);
1656 if (total_swapcount)
1657 *total_swapcount = swapcount;
1658 return mapcount + swapcount;
1661 page = compound_head(page);
1663 _total_mapcount = _total_swapcount = map_swapcount = 0;
1664 if (PageSwapCache(page)) {
1667 entry.val = page_private(page);
1668 si = _swap_info_get(entry);
1671 offset = swp_offset(entry);
1675 ci = lock_cluster(si, offset);
1676 for (i = 0; i < HPAGE_PMD_NR; i++) {
1677 mapcount = atomic_read(&page[i]._mapcount) + 1;
1678 _total_mapcount += mapcount;
1680 swapcount = swap_count(map[offset + i]);
1681 _total_swapcount += swapcount;
1683 map_swapcount = max(map_swapcount, mapcount + swapcount);
1686 if (PageDoubleMap(page)) {
1688 _total_mapcount -= HPAGE_PMD_NR;
1690 mapcount = compound_mapcount(page);
1691 map_swapcount += mapcount;
1692 _total_mapcount += mapcount;
1694 *total_mapcount = _total_mapcount;
1695 if (total_swapcount)
1696 *total_swapcount = _total_swapcount;
1698 return map_swapcount;
1702 * We can write to an anon page without COW if there are no other references
1703 * to it. And as a side-effect, free up its swap: because the old content
1704 * on disk will never be read, and seeking back there to write new content
1705 * later would only waste time away from clustering.
1707 * NOTE: total_map_swapcount should not be relied upon by the caller if
1708 * reuse_swap_page() returns false, but it may be always overwritten
1709 * (see the other implementation for CONFIG_SWAP=n).
1711 bool reuse_swap_page(struct page *page, int *total_map_swapcount)
1713 int count, total_mapcount, total_swapcount;
1715 VM_BUG_ON_PAGE(!PageLocked(page), page);
1716 if (unlikely(PageKsm(page)))
1718 count = page_trans_huge_map_swapcount(page, &total_mapcount,
1720 if (total_map_swapcount)
1721 *total_map_swapcount = total_mapcount + total_swapcount;
1722 if (count == 1 && PageSwapCache(page) &&
1723 (likely(!PageTransCompound(page)) ||
1724 /* The remaining swap count will be freed soon */
1725 total_swapcount == page_swapcount(page))) {
1726 if (!PageWriteback(page)) {
1727 page = compound_head(page);
1728 delete_from_swap_cache(page);
1732 struct swap_info_struct *p;
1734 entry.val = page_private(page);
1735 p = swap_info_get(entry);
1736 if (p->flags & SWP_STABLE_WRITES) {
1737 spin_unlock(&p->lock);
1740 spin_unlock(&p->lock);
1748 * If swap is getting full, or if there are no more mappings of this page,
1749 * then try_to_free_swap is called to free its swap space.
1751 int try_to_free_swap(struct page *page)
1753 VM_BUG_ON_PAGE(!PageLocked(page), page);
1755 if (!PageSwapCache(page))
1757 if (PageWriteback(page))
1759 if (page_swapped(page))
1763 * Once hibernation has begun to create its image of memory,
1764 * there's a danger that one of the calls to try_to_free_swap()
1765 * - most probably a call from __try_to_reclaim_swap() while
1766 * hibernation is allocating its own swap pages for the image,
1767 * but conceivably even a call from memory reclaim - will free
1768 * the swap from a page which has already been recorded in the
1769 * image as a clean swapcache page, and then reuse its swap for
1770 * another page of the image. On waking from hibernation, the
1771 * original page might be freed under memory pressure, then
1772 * later read back in from swap, now with the wrong data.
1774 * Hibernation suspends storage while it is writing the image
1775 * to disk so check that here.
1777 if (pm_suspended_storage())
1780 page = compound_head(page);
1781 delete_from_swap_cache(page);
1787 * Free the swap entry like above, but also try to
1788 * free the page cache entry if it is the last user.
1790 int free_swap_and_cache(swp_entry_t entry)
1792 struct swap_info_struct *p;
1793 unsigned char count;
1795 if (non_swap_entry(entry))
1798 p = _swap_info_get(entry);
1800 count = __swap_entry_free(p, entry);
1801 if (count == SWAP_HAS_CACHE &&
1802 !swap_page_trans_huge_swapped(p, entry))
1803 __try_to_reclaim_swap(p, swp_offset(entry),
1804 TTRS_UNMAPPED | TTRS_FULL);
1809 #ifdef CONFIG_HIBERNATION
1811 * Find the swap type that corresponds to given device (if any).
1813 * @offset - number of the PAGE_SIZE-sized block of the device, starting
1814 * from 0, in which the swap header is expected to be located.
1816 * This is needed for the suspend to disk (aka swsusp).
1818 int swap_type_of(dev_t device, sector_t offset)
1825 spin_lock(&swap_lock);
1826 for (type = 0; type < nr_swapfiles; type++) {
1827 struct swap_info_struct *sis = swap_info[type];
1829 if (!(sis->flags & SWP_WRITEOK))
1832 if (device == sis->bdev->bd_dev) {
1833 struct swap_extent *se = first_se(sis);
1835 if (se->start_block == offset) {
1836 spin_unlock(&swap_lock);
1841 spin_unlock(&swap_lock);
1845 int find_first_swap(dev_t *device)
1849 spin_lock(&swap_lock);
1850 for (type = 0; type < nr_swapfiles; type++) {
1851 struct swap_info_struct *sis = swap_info[type];
1853 if (!(sis->flags & SWP_WRITEOK))
1855 *device = sis->bdev->bd_dev;
1856 spin_unlock(&swap_lock);
1859 spin_unlock(&swap_lock);
1864 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1865 * corresponding to given index in swap_info (swap type).
1867 sector_t swapdev_block(int type, pgoff_t offset)
1869 struct block_device *bdev;
1870 struct swap_info_struct *si = swap_type_to_swap_info(type);
1872 if (!si || !(si->flags & SWP_WRITEOK))
1874 return map_swap_entry(swp_entry(type, offset), &bdev);
1878 * Return either the total number of swap pages of given type, or the number
1879 * of free pages of that type (depending on @free)
1881 * This is needed for software suspend
1883 unsigned int count_swap_pages(int type, int free)
1887 spin_lock(&swap_lock);
1888 if ((unsigned int)type < nr_swapfiles) {
1889 struct swap_info_struct *sis = swap_info[type];
1891 spin_lock(&sis->lock);
1892 if (sis->flags & SWP_WRITEOK) {
1895 n -= sis->inuse_pages;
1897 spin_unlock(&sis->lock);
1899 spin_unlock(&swap_lock);
1902 #endif /* CONFIG_HIBERNATION */
1904 static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1906 return pte_same(pte_swp_clear_flags(pte), swp_pte);
1910 * No need to decide whether this PTE shares the swap entry with others,
1911 * just let do_wp_page work it out if a write is requested later - to
1912 * force COW, vm_page_prot omits write permission from any private vma.
1914 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1915 unsigned long addr, swp_entry_t entry, struct page *page)
1917 struct page *swapcache;
1923 page = ksm_might_need_to_copy(page, vma, addr);
1924 if (unlikely(!page))
1927 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1928 if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
1933 dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1934 inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
1936 set_pte_at(vma->vm_mm, addr, pte,
1937 pte_mkold(mk_pte(page, vma->vm_page_prot)));
1938 if (page == swapcache) {
1939 page_add_anon_rmap(page, vma, addr, false);
1940 } else { /* ksm created a completely new copy */
1941 page_add_new_anon_rmap(page, vma, addr, false);
1942 lru_cache_add_inactive_or_unevictable(page, vma);
1946 pte_unmap_unlock(pte, ptl);
1947 if (page != swapcache) {
1954 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
1955 unsigned long addr, unsigned long end,
1956 unsigned int type, bool frontswap,
1957 unsigned long *fs_pages_to_unuse)
1962 struct swap_info_struct *si;
1963 unsigned long offset;
1965 volatile unsigned char *swap_map;
1967 si = swap_info[type];
1968 pte = pte_offset_map(pmd, addr);
1970 struct vm_fault vmf;
1972 if (!is_swap_pte(*pte))
1975 entry = pte_to_swp_entry(*pte);
1976 if (swp_type(entry) != type)
1979 offset = swp_offset(entry);
1980 if (frontswap && !frontswap_test(si, offset))
1984 swap_map = &si->swap_map[offset];
1985 page = lookup_swap_cache(entry, vma, addr);
1990 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
1994 if (*swap_map == 0 || *swap_map == SWAP_MAP_BAD)
2000 wait_on_page_writeback(page);
2001 ret = unuse_pte(vma, pmd, addr, entry, page);
2008 try_to_free_swap(page);
2012 if (*fs_pages_to_unuse && !--(*fs_pages_to_unuse)) {
2013 ret = FRONTSWAP_PAGES_UNUSED;
2017 pte = pte_offset_map(pmd, addr);
2018 } while (pte++, addr += PAGE_SIZE, addr != end);
2026 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
2027 unsigned long addr, unsigned long end,
2028 unsigned int type, bool frontswap,
2029 unsigned long *fs_pages_to_unuse)
2035 pmd = pmd_offset(pud, addr);
2038 next = pmd_addr_end(addr, end);
2039 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
2041 ret = unuse_pte_range(vma, pmd, addr, next, type,
2042 frontswap, fs_pages_to_unuse);
2045 } while (pmd++, addr = next, addr != end);
2049 static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
2050 unsigned long addr, unsigned long end,
2051 unsigned int type, bool frontswap,
2052 unsigned long *fs_pages_to_unuse)
2058 pud = pud_offset(p4d, addr);
2060 next = pud_addr_end(addr, end);
2061 if (pud_none_or_clear_bad(pud))
2063 ret = unuse_pmd_range(vma, pud, addr, next, type,
2064 frontswap, fs_pages_to_unuse);
2067 } while (pud++, addr = next, addr != end);
2071 static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
2072 unsigned long addr, unsigned long end,
2073 unsigned int type, bool frontswap,
2074 unsigned long *fs_pages_to_unuse)
2080 p4d = p4d_offset(pgd, addr);
2082 next = p4d_addr_end(addr, end);
2083 if (p4d_none_or_clear_bad(p4d))
2085 ret = unuse_pud_range(vma, p4d, addr, next, type,
2086 frontswap, fs_pages_to_unuse);
2089 } while (p4d++, addr = next, addr != end);
2093 static int unuse_vma(struct vm_area_struct *vma, unsigned int type,
2094 bool frontswap, unsigned long *fs_pages_to_unuse)
2097 unsigned long addr, end, next;
2100 addr = vma->vm_start;
2103 pgd = pgd_offset(vma->vm_mm, addr);
2105 next = pgd_addr_end(addr, end);
2106 if (pgd_none_or_clear_bad(pgd))
2108 ret = unuse_p4d_range(vma, pgd, addr, next, type,
2109 frontswap, fs_pages_to_unuse);
2112 } while (pgd++, addr = next, addr != end);
2116 static int unuse_mm(struct mm_struct *mm, unsigned int type,
2117 bool frontswap, unsigned long *fs_pages_to_unuse)
2119 struct vm_area_struct *vma;
2123 for (vma = mm->mmap; vma; vma = vma->vm_next) {
2124 if (vma->anon_vma) {
2125 ret = unuse_vma(vma, type, frontswap,
2132 mmap_read_unlock(mm);
2137 * Scan swap_map (or frontswap_map if frontswap parameter is true)
2138 * from current position to next entry still in use. Return 0
2139 * if there are no inuse entries after prev till end of the map.
2141 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
2142 unsigned int prev, bool frontswap)
2145 unsigned char count;
2148 * No need for swap_lock here: we're just looking
2149 * for whether an entry is in use, not modifying it; false
2150 * hits are okay, and sys_swapoff() has already prevented new
2151 * allocations from this area (while holding swap_lock).
2153 for (i = prev + 1; i < si->max; i++) {
2154 count = READ_ONCE(si->swap_map[i]);
2155 if (count && swap_count(count) != SWAP_MAP_BAD)
2156 if (!frontswap || frontswap_test(si, i))
2158 if ((i % LATENCY_LIMIT) == 0)
2169 * If the boolean frontswap is true, only unuse pages_to_unuse pages;
2170 * pages_to_unuse==0 means all pages; ignored if frontswap is false
2172 int try_to_unuse(unsigned int type, bool frontswap,
2173 unsigned long pages_to_unuse)
2175 struct mm_struct *prev_mm;
2176 struct mm_struct *mm;
2177 struct list_head *p;
2179 struct swap_info_struct *si = swap_info[type];
2184 if (!READ_ONCE(si->inuse_pages))
2191 retval = shmem_unuse(type, frontswap, &pages_to_unuse);
2198 spin_lock(&mmlist_lock);
2199 p = &init_mm.mmlist;
2200 while (READ_ONCE(si->inuse_pages) &&
2201 !signal_pending(current) &&
2202 (p = p->next) != &init_mm.mmlist) {
2204 mm = list_entry(p, struct mm_struct, mmlist);
2205 if (!mmget_not_zero(mm))
2207 spin_unlock(&mmlist_lock);
2210 retval = unuse_mm(mm, type, frontswap, &pages_to_unuse);
2218 * Make sure that we aren't completely killing
2219 * interactive performance.
2222 spin_lock(&mmlist_lock);
2224 spin_unlock(&mmlist_lock);
2229 while (READ_ONCE(si->inuse_pages) &&
2230 !signal_pending(current) &&
2231 (i = find_next_to_unuse(si, i, frontswap)) != 0) {
2233 entry = swp_entry(type, i);
2234 page = find_get_page(swap_address_space(entry), i);
2239 * It is conceivable that a racing task removed this page from
2240 * swap cache just before we acquired the page lock. The page
2241 * might even be back in swap cache on another swap area. But
2242 * that is okay, try_to_free_swap() only removes stale pages.
2245 wait_on_page_writeback(page);
2246 try_to_free_swap(page);
2251 * For frontswap, we just need to unuse pages_to_unuse, if
2252 * it was specified. Need not check frontswap again here as
2253 * we already zeroed out pages_to_unuse if not frontswap.
2255 if (pages_to_unuse && --pages_to_unuse == 0)
2260 * Lets check again to see if there are still swap entries in the map.
2261 * If yes, we would need to do retry the unuse logic again.
2262 * Under global memory pressure, swap entries can be reinserted back
2263 * into process space after the mmlist loop above passes over them.
2265 * Limit the number of retries? No: when mmget_not_zero() above fails,
2266 * that mm is likely to be freeing swap from exit_mmap(), which proceeds
2267 * at its own independent pace; and even shmem_writepage() could have
2268 * been preempted after get_swap_page(), temporarily hiding that swap.
2269 * It's easy and robust (though cpu-intensive) just to keep retrying.
2271 if (READ_ONCE(si->inuse_pages)) {
2272 if (!signal_pending(current))
2277 return (retval == FRONTSWAP_PAGES_UNUSED) ? 0 : retval;
2281 * After a successful try_to_unuse, if no swap is now in use, we know
2282 * we can empty the mmlist. swap_lock must be held on entry and exit.
2283 * Note that mmlist_lock nests inside swap_lock, and an mm must be
2284 * added to the mmlist just after page_duplicate - before would be racy.
2286 static void drain_mmlist(void)
2288 struct list_head *p, *next;
2291 for (type = 0; type < nr_swapfiles; type++)
2292 if (swap_info[type]->inuse_pages)
2294 spin_lock(&mmlist_lock);
2295 list_for_each_safe(p, next, &init_mm.mmlist)
2297 spin_unlock(&mmlist_lock);
2301 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
2302 * corresponds to page offset for the specified swap entry.
2303 * Note that the type of this function is sector_t, but it returns page offset
2304 * into the bdev, not sector offset.
2306 static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
2308 struct swap_info_struct *sis;
2309 struct swap_extent *se;
2312 sis = swp_swap_info(entry);
2315 offset = swp_offset(entry);
2316 se = offset_to_swap_extent(sis, offset);
2317 return se->start_block + (offset - se->start_page);
2321 * Returns the page offset into bdev for the specified page's swap entry.
2323 sector_t map_swap_page(struct page *page, struct block_device **bdev)
2326 entry.val = page_private(page);
2327 return map_swap_entry(entry, bdev);
2331 * Free all of a swapdev's extent information
2333 static void destroy_swap_extents(struct swap_info_struct *sis)
2335 while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
2336 struct rb_node *rb = sis->swap_extent_root.rb_node;
2337 struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
2339 rb_erase(rb, &sis->swap_extent_root);
2343 if (sis->flags & SWP_ACTIVATED) {
2344 struct file *swap_file = sis->swap_file;
2345 struct address_space *mapping = swap_file->f_mapping;
2347 sis->flags &= ~SWP_ACTIVATED;
2348 if (mapping->a_ops->swap_deactivate)
2349 mapping->a_ops->swap_deactivate(swap_file);
2354 * Add a block range (and the corresponding page range) into this swapdev's
2357 * This function rather assumes that it is called in ascending page order.
2360 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
2361 unsigned long nr_pages, sector_t start_block)
2363 struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
2364 struct swap_extent *se;
2365 struct swap_extent *new_se;
2368 * place the new node at the right most since the
2369 * function is called in ascending page order.
2373 link = &parent->rb_right;
2377 se = rb_entry(parent, struct swap_extent, rb_node);
2378 BUG_ON(se->start_page + se->nr_pages != start_page);
2379 if (se->start_block + se->nr_pages == start_block) {
2381 se->nr_pages += nr_pages;
2386 /* No merge, insert a new extent. */
2387 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
2390 new_se->start_page = start_page;
2391 new_se->nr_pages = nr_pages;
2392 new_se->start_block = start_block;
2394 rb_link_node(&new_se->rb_node, parent, link);
2395 rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
2398 EXPORT_SYMBOL_GPL(add_swap_extent);
2401 * A `swap extent' is a simple thing which maps a contiguous range of pages
2402 * onto a contiguous range of disk blocks. An ordered list of swap extents
2403 * is built at swapon time and is then used at swap_writepage/swap_readpage
2404 * time for locating where on disk a page belongs.
2406 * If the swapfile is an S_ISBLK block device, a single extent is installed.
2407 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
2408 * swap files identically.
2410 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
2411 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
2412 * swapfiles are handled *identically* after swapon time.
2414 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
2415 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
2416 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
2417 * requirements, they are simply tossed out - we will never use those blocks
2420 * For all swap devices we set S_SWAPFILE across the life of the swapon. This
2421 * prevents users from writing to the swap device, which will corrupt memory.
2423 * The amount of disk space which a single swap extent represents varies.
2424 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
2425 * extents in the list. To avoid much list walking, we cache the previous
2426 * search location in `curr_swap_extent', and start new searches from there.
2427 * This is extremely effective. The average number of iterations in
2428 * map_swap_page() has been measured at about 0.3 per page. - akpm.
2430 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
2432 struct file *swap_file = sis->swap_file;
2433 struct address_space *mapping = swap_file->f_mapping;
2434 struct inode *inode = mapping->host;
2437 if (S_ISBLK(inode->i_mode)) {
2438 ret = add_swap_extent(sis, 0, sis->max, 0);
2443 if (mapping->a_ops->swap_activate) {
2444 ret = mapping->a_ops->swap_activate(sis, swap_file, span);
2446 sis->flags |= SWP_ACTIVATED;
2448 sis->flags |= SWP_FS_OPS;
2449 ret = add_swap_extent(sis, 0, sis->max, 0);
2455 return generic_swapfile_activate(sis, swap_file, span);
2458 static int swap_node(struct swap_info_struct *p)
2460 struct block_device *bdev;
2465 bdev = p->swap_file->f_inode->i_sb->s_bdev;
2467 return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
2470 static void setup_swap_info(struct swap_info_struct *p, int prio,
2471 unsigned char *swap_map,
2472 struct swap_cluster_info *cluster_info)
2479 p->prio = --least_priority;
2481 * the plist prio is negated because plist ordering is
2482 * low-to-high, while swap ordering is high-to-low
2484 p->list.prio = -p->prio;
2487 p->avail_lists[i].prio = -p->prio;
2489 if (swap_node(p) == i)
2490 p->avail_lists[i].prio = 1;
2492 p->avail_lists[i].prio = -p->prio;
2495 p->swap_map = swap_map;
2496 p->cluster_info = cluster_info;
2499 static void _enable_swap_info(struct swap_info_struct *p)
2501 p->flags |= SWP_WRITEOK | SWP_VALID;
2502 atomic_long_add(p->pages, &nr_swap_pages);
2503 total_swap_pages += p->pages;
2505 assert_spin_locked(&swap_lock);
2507 * both lists are plists, and thus priority ordered.
2508 * swap_active_head needs to be priority ordered for swapoff(),
2509 * which on removal of any swap_info_struct with an auto-assigned
2510 * (i.e. negative) priority increments the auto-assigned priority
2511 * of any lower-priority swap_info_structs.
2512 * swap_avail_head needs to be priority ordered for get_swap_page(),
2513 * which allocates swap pages from the highest available priority
2516 plist_add(&p->list, &swap_active_head);
2517 add_to_avail_list(p);
2520 static void enable_swap_info(struct swap_info_struct *p, int prio,
2521 unsigned char *swap_map,
2522 struct swap_cluster_info *cluster_info,
2523 unsigned long *frontswap_map)
2525 frontswap_init(p->type, frontswap_map);
2526 spin_lock(&swap_lock);
2527 spin_lock(&p->lock);
2528 setup_swap_info(p, prio, swap_map, cluster_info);
2529 spin_unlock(&p->lock);
2530 spin_unlock(&swap_lock);
2532 * Guarantee swap_map, cluster_info, etc. fields are valid
2533 * between get/put_swap_device() if SWP_VALID bit is set
2536 spin_lock(&swap_lock);
2537 spin_lock(&p->lock);
2538 _enable_swap_info(p);
2539 spin_unlock(&p->lock);
2540 spin_unlock(&swap_lock);
2543 static void reinsert_swap_info(struct swap_info_struct *p)
2545 spin_lock(&swap_lock);
2546 spin_lock(&p->lock);
2547 setup_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2548 _enable_swap_info(p);
2549 spin_unlock(&p->lock);
2550 spin_unlock(&swap_lock);
2553 bool has_usable_swap(void)
2557 spin_lock(&swap_lock);
2558 if (plist_head_empty(&swap_active_head))
2560 spin_unlock(&swap_lock);
2564 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
2566 struct swap_info_struct *p = NULL;
2567 unsigned char *swap_map;
2568 struct swap_cluster_info *cluster_info;
2569 unsigned long *frontswap_map;
2570 struct file *swap_file, *victim;
2571 struct address_space *mapping;
2572 struct inode *inode;
2573 struct filename *pathname;
2575 unsigned int old_block_size;
2577 if (!capable(CAP_SYS_ADMIN))
2580 BUG_ON(!current->mm);
2582 pathname = getname(specialfile);
2583 if (IS_ERR(pathname))
2584 return PTR_ERR(pathname);
2586 victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
2587 err = PTR_ERR(victim);
2591 mapping = victim->f_mapping;
2592 spin_lock(&swap_lock);
2593 plist_for_each_entry(p, &swap_active_head, list) {
2594 if (p->flags & SWP_WRITEOK) {
2595 if (p->swap_file->f_mapping == mapping) {
2603 spin_unlock(&swap_lock);
2606 if (!security_vm_enough_memory_mm(current->mm, p->pages))
2607 vm_unacct_memory(p->pages);
2610 spin_unlock(&swap_lock);
2613 del_from_avail_list(p);
2614 spin_lock(&p->lock);
2616 struct swap_info_struct *si = p;
2619 plist_for_each_entry_continue(si, &swap_active_head, list) {
2622 for_each_node(nid) {
2623 if (si->avail_lists[nid].prio != 1)
2624 si->avail_lists[nid].prio--;
2629 plist_del(&p->list, &swap_active_head);
2630 atomic_long_sub(p->pages, &nr_swap_pages);
2631 total_swap_pages -= p->pages;
2632 p->flags &= ~SWP_WRITEOK;
2633 spin_unlock(&p->lock);
2634 spin_unlock(&swap_lock);
2636 disable_swap_slots_cache_lock();
2638 set_current_oom_origin();
2639 err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
2640 clear_current_oom_origin();
2643 /* re-insert swap space back into swap_list */
2644 reinsert_swap_info(p);
2645 reenable_swap_slots_cache_unlock();
2649 reenable_swap_slots_cache_unlock();
2651 spin_lock(&swap_lock);
2652 spin_lock(&p->lock);
2653 p->flags &= ~SWP_VALID; /* mark swap device as invalid */
2654 spin_unlock(&p->lock);
2655 spin_unlock(&swap_lock);
2657 * wait for swap operations protected by get/put_swap_device()
2662 flush_work(&p->discard_work);
2664 destroy_swap_extents(p);
2665 if (p->flags & SWP_CONTINUED)
2666 free_swap_count_continuations(p);
2668 if (!p->bdev || !blk_queue_nonrot(bdev_get_queue(p->bdev)))
2669 atomic_dec(&nr_rotate_swap);
2671 mutex_lock(&swapon_mutex);
2672 spin_lock(&swap_lock);
2673 spin_lock(&p->lock);
2676 /* wait for anyone still in scan_swap_map */
2677 p->highest_bit = 0; /* cuts scans short */
2678 while (p->flags >= SWP_SCANNING) {
2679 spin_unlock(&p->lock);
2680 spin_unlock(&swap_lock);
2681 schedule_timeout_uninterruptible(1);
2682 spin_lock(&swap_lock);
2683 spin_lock(&p->lock);
2686 swap_file = p->swap_file;
2687 old_block_size = p->old_block_size;
2688 p->swap_file = NULL;
2690 swap_map = p->swap_map;
2692 cluster_info = p->cluster_info;
2693 p->cluster_info = NULL;
2694 frontswap_map = frontswap_map_get(p);
2695 spin_unlock(&p->lock);
2696 spin_unlock(&swap_lock);
2697 arch_swap_invalidate_area(p->type);
2698 frontswap_invalidate_area(p->type);
2699 frontswap_map_set(p, NULL);
2700 mutex_unlock(&swapon_mutex);
2701 free_percpu(p->percpu_cluster);
2702 p->percpu_cluster = NULL;
2703 free_percpu(p->cluster_next_cpu);
2704 p->cluster_next_cpu = NULL;
2706 kvfree(cluster_info);
2707 kvfree(frontswap_map);
2708 /* Destroy swap account information */
2709 swap_cgroup_swapoff(p->type);
2710 exit_swap_address_space(p->type);
2712 inode = mapping->host;
2713 if (S_ISBLK(inode->i_mode)) {
2714 struct block_device *bdev = I_BDEV(inode);
2716 set_blocksize(bdev, old_block_size);
2717 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2721 inode->i_flags &= ~S_SWAPFILE;
2722 inode_unlock(inode);
2723 filp_close(swap_file, NULL);
2726 * Clear the SWP_USED flag after all resources are freed so that swapon
2727 * can reuse this swap_info in alloc_swap_info() safely. It is ok to
2728 * not hold p->lock after we cleared its SWP_WRITEOK.
2730 spin_lock(&swap_lock);
2732 spin_unlock(&swap_lock);
2735 atomic_inc(&proc_poll_event);
2736 wake_up_interruptible(&proc_poll_wait);
2739 filp_close(victim, NULL);
2745 #ifdef CONFIG_PROC_FS
2746 static __poll_t swaps_poll(struct file *file, poll_table *wait)
2748 struct seq_file *seq = file->private_data;
2750 poll_wait(file, &proc_poll_wait, wait);
2752 if (seq->poll_event != atomic_read(&proc_poll_event)) {
2753 seq->poll_event = atomic_read(&proc_poll_event);
2754 return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
2757 return EPOLLIN | EPOLLRDNORM;
2761 static void *swap_start(struct seq_file *swap, loff_t *pos)
2763 struct swap_info_struct *si;
2767 mutex_lock(&swapon_mutex);
2770 return SEQ_START_TOKEN;
2772 for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
2773 if (!(si->flags & SWP_USED) || !si->swap_map)
2782 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
2784 struct swap_info_struct *si = v;
2787 if (v == SEQ_START_TOKEN)
2790 type = si->type + 1;
2793 for (; (si = swap_type_to_swap_info(type)); type++) {
2794 if (!(si->flags & SWP_USED) || !si->swap_map)
2802 static void swap_stop(struct seq_file *swap, void *v)
2804 mutex_unlock(&swapon_mutex);
2807 static int swap_show(struct seq_file *swap, void *v)
2809 struct swap_info_struct *si = v;
2812 unsigned int bytes, inuse;
2814 if (si == SEQ_START_TOKEN) {
2815 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
2819 bytes = si->pages << (PAGE_SHIFT - 10);
2820 inuse = si->inuse_pages << (PAGE_SHIFT - 10);
2822 file = si->swap_file;
2823 len = seq_file_path(swap, file, " \t\n\\");
2824 seq_printf(swap, "%*s%s\t%u\t%s%u\t%s%d\n",
2825 len < 40 ? 40 - len : 1, " ",
2826 S_ISBLK(file_inode(file)->i_mode) ?
2827 "partition" : "file\t",
2828 bytes, bytes < 10000000 ? "\t" : "",
2829 inuse, inuse < 10000000 ? "\t" : "",
2834 static const struct seq_operations swaps_op = {
2835 .start = swap_start,
2841 static int swaps_open(struct inode *inode, struct file *file)
2843 struct seq_file *seq;
2846 ret = seq_open(file, &swaps_op);
2850 seq = file->private_data;
2851 seq->poll_event = atomic_read(&proc_poll_event);
2855 static const struct proc_ops swaps_proc_ops = {
2856 .proc_flags = PROC_ENTRY_PERMANENT,
2857 .proc_open = swaps_open,
2858 .proc_read = seq_read,
2859 .proc_lseek = seq_lseek,
2860 .proc_release = seq_release,
2861 .proc_poll = swaps_poll,
2864 static int __init procswaps_init(void)
2866 proc_create("swaps", 0, NULL, &swaps_proc_ops);
2869 __initcall(procswaps_init);
2870 #endif /* CONFIG_PROC_FS */
2872 #ifdef MAX_SWAPFILES_CHECK
2873 static int __init max_swapfiles_check(void)
2875 MAX_SWAPFILES_CHECK();
2878 late_initcall(max_swapfiles_check);
2881 static struct swap_info_struct *alloc_swap_info(void)
2883 struct swap_info_struct *p;
2884 struct swap_info_struct *defer = NULL;
2888 p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
2890 return ERR_PTR(-ENOMEM);
2892 spin_lock(&swap_lock);
2893 for (type = 0; type < nr_swapfiles; type++) {
2894 if (!(swap_info[type]->flags & SWP_USED))
2897 if (type >= MAX_SWAPFILES) {
2898 spin_unlock(&swap_lock);
2900 return ERR_PTR(-EPERM);
2902 if (type >= nr_swapfiles) {
2904 WRITE_ONCE(swap_info[type], p);
2906 * Write swap_info[type] before nr_swapfiles, in case a
2907 * racing procfs swap_start() or swap_next() is reading them.
2908 * (We never shrink nr_swapfiles, we never free this entry.)
2911 WRITE_ONCE(nr_swapfiles, nr_swapfiles + 1);
2914 p = swap_info[type];
2916 * Do not memset this entry: a racing procfs swap_next()
2917 * would be relying on p->type to remain valid.
2920 p->swap_extent_root = RB_ROOT;
2921 plist_node_init(&p->list, 0);
2923 plist_node_init(&p->avail_lists[i], 0);
2924 p->flags = SWP_USED;
2925 spin_unlock(&swap_lock);
2927 spin_lock_init(&p->lock);
2928 spin_lock_init(&p->cont_lock);
2933 static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
2937 if (S_ISBLK(inode->i_mode)) {
2938 p->bdev = blkdev_get_by_dev(inode->i_rdev,
2939 FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
2940 if (IS_ERR(p->bdev)) {
2941 error = PTR_ERR(p->bdev);
2945 p->old_block_size = block_size(p->bdev);
2946 error = set_blocksize(p->bdev, PAGE_SIZE);
2950 * Zoned block devices contain zones that have a sequential
2951 * write only restriction. Hence zoned block devices are not
2952 * suitable for swapping. Disallow them here.
2954 if (blk_queue_is_zoned(p->bdev->bd_disk->queue))
2956 p->flags |= SWP_BLKDEV;
2957 } else if (S_ISREG(inode->i_mode)) {
2958 p->bdev = inode->i_sb->s_bdev;
2966 * Find out how many pages are allowed for a single swap device. There
2967 * are two limiting factors:
2968 * 1) the number of bits for the swap offset in the swp_entry_t type, and
2969 * 2) the number of bits in the swap pte, as defined by the different
2972 * In order to find the largest possible bit mask, a swap entry with
2973 * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2974 * decoded to a swp_entry_t again, and finally the swap offset is
2977 * This will mask all the bits from the initial ~0UL mask that can't
2978 * be encoded in either the swp_entry_t or the architecture definition
2981 unsigned long generic_max_swapfile_size(void)
2983 return swp_offset(pte_to_swp_entry(
2984 swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2987 /* Can be overridden by an architecture for additional checks. */
2988 __weak unsigned long max_swapfile_size(void)
2990 return generic_max_swapfile_size();
2993 static unsigned long read_swap_header(struct swap_info_struct *p,
2994 union swap_header *swap_header,
2995 struct inode *inode)
2998 unsigned long maxpages;
2999 unsigned long swapfilepages;
3000 unsigned long last_page;
3002 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
3003 pr_err("Unable to find swap-space signature\n");
3007 /* swap partition endianess hack... */
3008 if (swab32(swap_header->info.version) == 1) {
3009 swab32s(&swap_header->info.version);
3010 swab32s(&swap_header->info.last_page);
3011 swab32s(&swap_header->info.nr_badpages);
3012 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3014 for (i = 0; i < swap_header->info.nr_badpages; i++)
3015 swab32s(&swap_header->info.badpages[i]);
3017 /* Check the swap header's sub-version */
3018 if (swap_header->info.version != 1) {
3019 pr_warn("Unable to handle swap header version %d\n",
3020 swap_header->info.version);
3025 p->cluster_next = 1;
3028 maxpages = max_swapfile_size();
3029 last_page = swap_header->info.last_page;
3031 pr_warn("Empty swap-file\n");
3034 if (last_page > maxpages) {
3035 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
3036 maxpages << (PAGE_SHIFT - 10),
3037 last_page << (PAGE_SHIFT - 10));
3039 if (maxpages > last_page) {
3040 maxpages = last_page + 1;
3041 /* p->max is an unsigned int: don't overflow it */
3042 if ((unsigned int)maxpages == 0)
3043 maxpages = UINT_MAX;
3045 p->highest_bit = maxpages - 1;
3049 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
3050 if (swapfilepages && maxpages > swapfilepages) {
3051 pr_warn("Swap area shorter than signature indicates\n");
3054 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
3056 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3062 #define SWAP_CLUSTER_INFO_COLS \
3063 DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
3064 #define SWAP_CLUSTER_SPACE_COLS \
3065 DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
3066 #define SWAP_CLUSTER_COLS \
3067 max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
3069 static int setup_swap_map_and_extents(struct swap_info_struct *p,
3070 union swap_header *swap_header,
3071 unsigned char *swap_map,
3072 struct swap_cluster_info *cluster_info,
3073 unsigned long maxpages,
3077 unsigned int nr_good_pages;
3079 unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3080 unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
3081 unsigned long i, idx;
3083 nr_good_pages = maxpages - 1; /* omit header page */
3085 cluster_list_init(&p->free_clusters);
3086 cluster_list_init(&p->discard_clusters);
3088 for (i = 0; i < swap_header->info.nr_badpages; i++) {
3089 unsigned int page_nr = swap_header->info.badpages[i];
3090 if (page_nr == 0 || page_nr > swap_header->info.last_page)
3092 if (page_nr < maxpages) {
3093 swap_map[page_nr] = SWAP_MAP_BAD;
3096 * Haven't marked the cluster free yet, no list
3097 * operation involved
3099 inc_cluster_info_page(p, cluster_info, page_nr);
3103 /* Haven't marked the cluster free yet, no list operation involved */
3104 for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
3105 inc_cluster_info_page(p, cluster_info, i);
3107 if (nr_good_pages) {
3108 swap_map[0] = SWAP_MAP_BAD;
3110 * Not mark the cluster free yet, no list
3111 * operation involved
3113 inc_cluster_info_page(p, cluster_info, 0);
3115 p->pages = nr_good_pages;
3116 nr_extents = setup_swap_extents(p, span);
3119 nr_good_pages = p->pages;
3121 if (!nr_good_pages) {
3122 pr_warn("Empty swap-file\n");
3131 * Reduce false cache line sharing between cluster_info and
3132 * sharing same address space.
3134 for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
3135 j = (k + col) % SWAP_CLUSTER_COLS;
3136 for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
3137 idx = i * SWAP_CLUSTER_COLS + j;
3138 if (idx >= nr_clusters)
3140 if (cluster_count(&cluster_info[idx]))
3142 cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
3143 cluster_list_add_tail(&p->free_clusters, cluster_info,
3151 * Helper to sys_swapon determining if a given swap
3152 * backing device queue supports DISCARD operations.
3154 static bool swap_discardable(struct swap_info_struct *si)
3156 struct request_queue *q = bdev_get_queue(si->bdev);
3158 if (!q || !blk_queue_discard(q))
3164 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
3166 struct swap_info_struct *p;
3167 struct filename *name;
3168 struct file *swap_file = NULL;
3169 struct address_space *mapping;
3172 union swap_header *swap_header;
3175 unsigned long maxpages;
3176 unsigned char *swap_map = NULL;
3177 struct swap_cluster_info *cluster_info = NULL;
3178 unsigned long *frontswap_map = NULL;
3179 struct page *page = NULL;
3180 struct inode *inode = NULL;
3181 bool inced_nr_rotate_swap = false;
3183 if (swap_flags & ~SWAP_FLAGS_VALID)
3186 if (!capable(CAP_SYS_ADMIN))
3189 if (!swap_avail_heads)
3192 p = alloc_swap_info();
3196 INIT_WORK(&p->discard_work, swap_discard_work);
3198 name = getname(specialfile);
3200 error = PTR_ERR(name);
3204 swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
3205 if (IS_ERR(swap_file)) {
3206 error = PTR_ERR(swap_file);
3211 p->swap_file = swap_file;
3212 mapping = swap_file->f_mapping;
3213 inode = mapping->host;
3215 error = claim_swapfile(p, inode);
3216 if (unlikely(error))
3220 if (IS_SWAPFILE(inode)) {
3222 goto bad_swap_unlock_inode;
3226 * Read the swap header.
3228 if (!mapping->a_ops->readpage) {
3230 goto bad_swap_unlock_inode;
3232 page = read_mapping_page(mapping, 0, swap_file);
3234 error = PTR_ERR(page);
3235 goto bad_swap_unlock_inode;
3237 swap_header = kmap(page);
3239 maxpages = read_swap_header(p, swap_header, inode);
3240 if (unlikely(!maxpages)) {
3242 goto bad_swap_unlock_inode;
3245 /* OK, set up the swap map and apply the bad block list */
3246 swap_map = vzalloc(maxpages);
3249 goto bad_swap_unlock_inode;
3252 if (p->bdev && blk_queue_stable_writes(p->bdev->bd_disk->queue))
3253 p->flags |= SWP_STABLE_WRITES;
3255 if (p->bdev && p->bdev->bd_disk->fops->rw_page)
3256 p->flags |= SWP_SYNCHRONOUS_IO;
3258 if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
3260 unsigned long ci, nr_cluster;
3262 p->flags |= SWP_SOLIDSTATE;
3263 p->cluster_next_cpu = alloc_percpu(unsigned int);
3264 if (!p->cluster_next_cpu) {
3266 goto bad_swap_unlock_inode;
3269 * select a random position to start with to help wear leveling
3272 for_each_possible_cpu(cpu) {
3273 per_cpu(*p->cluster_next_cpu, cpu) =
3274 1 + prandom_u32_max(p->highest_bit);
3276 nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3278 cluster_info = kvcalloc(nr_cluster, sizeof(*cluster_info),
3280 if (!cluster_info) {
3282 goto bad_swap_unlock_inode;
3285 for (ci = 0; ci < nr_cluster; ci++)
3286 spin_lock_init(&((cluster_info + ci)->lock));
3288 p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3289 if (!p->percpu_cluster) {
3291 goto bad_swap_unlock_inode;
3293 for_each_possible_cpu(cpu) {
3294 struct percpu_cluster *cluster;
3295 cluster = per_cpu_ptr(p->percpu_cluster, cpu);
3296 cluster_set_null(&cluster->index);
3299 atomic_inc(&nr_rotate_swap);
3300 inced_nr_rotate_swap = true;
3303 error = swap_cgroup_swapon(p->type, maxpages);
3305 goto bad_swap_unlock_inode;
3307 nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
3308 cluster_info, maxpages, &span);
3309 if (unlikely(nr_extents < 0)) {
3311 goto bad_swap_unlock_inode;
3313 /* frontswap enabled? set up bit-per-page map for frontswap */
3314 if (IS_ENABLED(CONFIG_FRONTSWAP))
3315 frontswap_map = kvcalloc(BITS_TO_LONGS(maxpages),
3319 if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
3321 * When discard is enabled for swap with no particular
3322 * policy flagged, we set all swap discard flags here in
3323 * order to sustain backward compatibility with older
3324 * swapon(8) releases.
3326 p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3330 * By flagging sys_swapon, a sysadmin can tell us to
3331 * either do single-time area discards only, or to just
3332 * perform discards for released swap page-clusters.
3333 * Now it's time to adjust the p->flags accordingly.
3335 if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3336 p->flags &= ~SWP_PAGE_DISCARD;
3337 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3338 p->flags &= ~SWP_AREA_DISCARD;
3340 /* issue a swapon-time discard if it's still required */
3341 if (p->flags & SWP_AREA_DISCARD) {
3342 int err = discard_swap(p);
3344 pr_err("swapon: discard_swap(%p): %d\n",
3349 error = init_swap_address_space(p->type, maxpages);
3351 goto bad_swap_unlock_inode;
3354 * Flush any pending IO and dirty mappings before we start using this
3357 inode->i_flags |= S_SWAPFILE;
3358 error = inode_drain_writes(inode);
3360 inode->i_flags &= ~S_SWAPFILE;
3361 goto free_swap_address_space;
3364 mutex_lock(&swapon_mutex);
3366 if (swap_flags & SWAP_FLAG_PREFER)
3368 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
3369 enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
3371 pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
3372 p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
3373 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
3374 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
3375 (p->flags & SWP_DISCARDABLE) ? "D" : "",
3376 (p->flags & SWP_AREA_DISCARD) ? "s" : "",
3377 (p->flags & SWP_PAGE_DISCARD) ? "c" : "",
3378 (frontswap_map) ? "FS" : "");
3380 mutex_unlock(&swapon_mutex);
3381 atomic_inc(&proc_poll_event);
3382 wake_up_interruptible(&proc_poll_wait);
3386 free_swap_address_space:
3387 exit_swap_address_space(p->type);
3388 bad_swap_unlock_inode:
3389 inode_unlock(inode);
3391 free_percpu(p->percpu_cluster);
3392 p->percpu_cluster = NULL;
3393 free_percpu(p->cluster_next_cpu);
3394 p->cluster_next_cpu = NULL;
3395 if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
3396 set_blocksize(p->bdev, p->old_block_size);
3397 blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
3400 destroy_swap_extents(p);
3401 swap_cgroup_swapoff(p->type);
3402 spin_lock(&swap_lock);
3403 p->swap_file = NULL;
3405 spin_unlock(&swap_lock);
3407 kvfree(cluster_info);
3408 kvfree(frontswap_map);
3409 if (inced_nr_rotate_swap)
3410 atomic_dec(&nr_rotate_swap);
3412 filp_close(swap_file, NULL);
3414 if (page && !IS_ERR(page)) {
3421 inode_unlock(inode);
3423 enable_swap_slots_cache();
3427 void si_swapinfo(struct sysinfo *val)
3430 unsigned long nr_to_be_unused = 0;
3432 spin_lock(&swap_lock);
3433 for (type = 0; type < nr_swapfiles; type++) {
3434 struct swap_info_struct *si = swap_info[type];
3436 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3437 nr_to_be_unused += si->inuse_pages;
3439 val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
3440 val->totalswap = total_swap_pages + nr_to_be_unused;
3441 spin_unlock(&swap_lock);
3445 * Verify that a swap entry is valid and increment its swap map count.
3447 * Returns error code in following case.
3449 * - swp_entry is invalid -> EINVAL
3450 * - swp_entry is migration entry -> EINVAL
3451 * - swap-cache reference is requested but there is already one. -> EEXIST
3452 * - swap-cache reference is requested but the entry is not used. -> ENOENT
3453 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
3455 static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
3457 struct swap_info_struct *p;
3458 struct swap_cluster_info *ci;
3459 unsigned long offset;
3460 unsigned char count;
3461 unsigned char has_cache;
3464 p = get_swap_device(entry);
3468 offset = swp_offset(entry);
3469 ci = lock_cluster_or_swap_info(p, offset);
3471 count = p->swap_map[offset];
3474 * swapin_readahead() doesn't check if a swap entry is valid, so the
3475 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3477 if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3482 has_cache = count & SWAP_HAS_CACHE;
3483 count &= ~SWAP_HAS_CACHE;
3486 if (usage == SWAP_HAS_CACHE) {
3488 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
3489 if (!has_cache && count)
3490 has_cache = SWAP_HAS_CACHE;
3491 else if (has_cache) /* someone else added cache */
3493 else /* no users remaining */
3496 } else if (count || has_cache) {
3498 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3500 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
3502 else if (swap_count_continued(p, offset, count))
3503 count = COUNT_CONTINUED;
3507 err = -ENOENT; /* unused swap entry */
3509 WRITE_ONCE(p->swap_map[offset], count | has_cache);
3512 unlock_cluster_or_swap_info(p, ci);
3520 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3521 * (in which case its reference count is never incremented).
3523 void swap_shmem_alloc(swp_entry_t entry)
3525 __swap_duplicate(entry, SWAP_MAP_SHMEM);
3529 * Increase reference count of swap entry by 1.
3530 * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
3531 * but could not be atomically allocated. Returns 0, just as if it succeeded,
3532 * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
3533 * might occur if a page table entry has got corrupted.
3535 int swap_duplicate(swp_entry_t entry)
3539 while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3540 err = add_swap_count_continuation(entry, GFP_ATOMIC);
3545 * @entry: swap entry for which we allocate swap cache.
3547 * Called when allocating swap cache for existing swap entry,
3548 * This can return error codes. Returns 0 at success.
3549 * -EEXIST means there is a swap cache.
3550 * Note: return code is different from swap_duplicate().
3552 int swapcache_prepare(swp_entry_t entry)
3554 return __swap_duplicate(entry, SWAP_HAS_CACHE);
3557 struct swap_info_struct *swp_swap_info(swp_entry_t entry)
3559 return swap_type_to_swap_info(swp_type(entry));
3562 struct swap_info_struct *page_swap_info(struct page *page)
3564 swp_entry_t entry = { .val = page_private(page) };
3565 return swp_swap_info(entry);
3569 * out-of-line __page_file_ methods to avoid include hell.
3571 struct address_space *__page_file_mapping(struct page *page)
3573 return page_swap_info(page)->swap_file->f_mapping;
3575 EXPORT_SYMBOL_GPL(__page_file_mapping);
3577 pgoff_t __page_file_index(struct page *page)
3579 swp_entry_t swap = { .val = page_private(page) };
3580 return swp_offset(swap);
3582 EXPORT_SYMBOL_GPL(__page_file_index);
3585 * add_swap_count_continuation - called when a swap count is duplicated
3586 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3587 * page of the original vmalloc'ed swap_map, to hold the continuation count
3588 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
3589 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3591 * These continuation pages are seldom referenced: the common paths all work
3592 * on the original swap_map, only referring to a continuation page when the
3593 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3595 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3596 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3597 * can be called after dropping locks.
3599 int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3601 struct swap_info_struct *si;
3602 struct swap_cluster_info *ci;
3605 struct page *list_page;
3607 unsigned char count;
3611 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3612 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3614 page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3616 si = get_swap_device(entry);
3619 * An acceptable race has occurred since the failing
3620 * __swap_duplicate(): the swap device may be swapoff
3624 spin_lock(&si->lock);
3626 offset = swp_offset(entry);
3628 ci = lock_cluster(si, offset);
3630 count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
3632 if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3634 * The higher the swap count, the more likely it is that tasks
3635 * will race to add swap count continuation: we need to avoid
3636 * over-provisioning.
3647 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
3648 * no architecture is using highmem pages for kernel page tables: so it
3649 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
3651 head = vmalloc_to_page(si->swap_map + offset);
3652 offset &= ~PAGE_MASK;
3654 spin_lock(&si->cont_lock);
3656 * Page allocation does not initialize the page's lru field,
3657 * but it does always reset its private field.
3659 if (!page_private(head)) {
3660 BUG_ON(count & COUNT_CONTINUED);
3661 INIT_LIST_HEAD(&head->lru);
3662 set_page_private(head, SWP_CONTINUED);
3663 si->flags |= SWP_CONTINUED;
3666 list_for_each_entry(list_page, &head->lru, lru) {
3670 * If the previous map said no continuation, but we've found
3671 * a continuation page, free our allocation and use this one.
3673 if (!(count & COUNT_CONTINUED))
3674 goto out_unlock_cont;
3676 map = kmap_atomic(list_page) + offset;
3681 * If this continuation count now has some space in it,
3682 * free our allocation and use this one.
3684 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
3685 goto out_unlock_cont;
3688 list_add_tail(&page->lru, &head->lru);
3689 page = NULL; /* now it's attached, don't free it */
3691 spin_unlock(&si->cont_lock);
3694 spin_unlock(&si->lock);
3695 put_swap_device(si);
3703 * swap_count_continued - when the original swap_map count is incremented
3704 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3705 * into, carry if so, or else fail until a new continuation page is allocated;
3706 * when the original swap_map count is decremented from 0 with continuation,
3707 * borrow from the continuation and report whether it still holds more.
3708 * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3711 static bool swap_count_continued(struct swap_info_struct *si,
3712 pgoff_t offset, unsigned char count)
3719 head = vmalloc_to_page(si->swap_map + offset);
3720 if (page_private(head) != SWP_CONTINUED) {
3721 BUG_ON(count & COUNT_CONTINUED);
3722 return false; /* need to add count continuation */
3725 spin_lock(&si->cont_lock);
3726 offset &= ~PAGE_MASK;
3727 page = list_next_entry(head, lru);
3728 map = kmap_atomic(page) + offset;
3730 if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
3731 goto init_map; /* jump over SWAP_CONT_MAX checks */
3733 if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3735 * Think of how you add 1 to 999
3737 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
3739 page = list_next_entry(page, lru);
3740 BUG_ON(page == head);
3741 map = kmap_atomic(page) + offset;
3743 if (*map == SWAP_CONT_MAX) {
3745 page = list_next_entry(page, lru);
3747 ret = false; /* add count continuation */
3750 map = kmap_atomic(page) + offset;
3751 init_map: *map = 0; /* we didn't zero the page */
3755 while ((page = list_prev_entry(page, lru)) != head) {
3756 map = kmap_atomic(page) + offset;
3757 *map = COUNT_CONTINUED;
3760 ret = true; /* incremented */
3762 } else { /* decrementing */
3764 * Think of how you subtract 1 from 1000
3766 BUG_ON(count != COUNT_CONTINUED);
3767 while (*map == COUNT_CONTINUED) {
3769 page = list_next_entry(page, lru);
3770 BUG_ON(page == head);
3771 map = kmap_atomic(page) + offset;
3778 while ((page = list_prev_entry(page, lru)) != head) {
3779 map = kmap_atomic(page) + offset;
3780 *map = SWAP_CONT_MAX | count;
3781 count = COUNT_CONTINUED;
3784 ret = count == COUNT_CONTINUED;
3787 spin_unlock(&si->cont_lock);
3792 * free_swap_count_continuations - swapoff free all the continuation pages
3793 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3795 static void free_swap_count_continuations(struct swap_info_struct *si)
3799 for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3801 head = vmalloc_to_page(si->swap_map + offset);
3802 if (page_private(head)) {
3803 struct page *page, *next;
3805 list_for_each_entry_safe(page, next, &head->lru, lru) {
3806 list_del(&page->lru);
3813 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
3814 void cgroup_throttle_swaprate(struct page *page, gfp_t gfp_mask)
3816 struct swap_info_struct *si, *next;
3817 int nid = page_to_nid(page);
3819 if (!(gfp_mask & __GFP_IO))
3822 if (!blk_cgroup_congested())
3826 * We've already scheduled a throttle, avoid taking the global swap
3829 if (current->throttle_queue)
3832 spin_lock(&swap_avail_lock);
3833 plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
3836 blkcg_schedule_throttle(bdev_get_queue(si->bdev), true);
3840 spin_unlock(&swap_avail_lock);
3844 static int __init swapfile_init(void)
3848 swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3850 if (!swap_avail_heads) {
3851 pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3856 plist_head_init(&swap_avail_heads[nid]);
3860 subsys_initcall(swapfile_init);