4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie
9 #include <linux/hugetlb.h>
10 #include <linux/mman.h>
11 #include <linux/slab.h>
12 #include <linux/kernel_stat.h>
13 #include <linux/swap.h>
14 #include <linux/vmalloc.h>
15 #include <linux/pagemap.h>
16 #include <linux/namei.h>
17 #include <linux/shmem_fs.h>
18 #include <linux/blkdev.h>
19 #include <linux/random.h>
20 #include <linux/writeback.h>
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/init.h>
24 #include <linux/ksm.h>
25 #include <linux/rmap.h>
26 #include <linux/security.h>
27 #include <linux/backing-dev.h>
28 #include <linux/mutex.h>
29 #include <linux/capability.h>
30 #include <linux/syscalls.h>
31 #include <linux/memcontrol.h>
32 #include <linux/poll.h>
33 #include <linux/oom.h>
34 #include <linux/frontswap.h>
35 #include <linux/swapfile.h>
36 #include <linux/export.h>
38 #include <asm/pgtable.h>
39 #include <asm/tlbflush.h>
40 #include <linux/swapops.h>
41 #include <linux/swap_cgroup.h>
43 static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
45 static void free_swap_count_continuations(struct swap_info_struct *);
46 static sector_t map_swap_entry(swp_entry_t, struct block_device**);
48 DEFINE_SPINLOCK(swap_lock);
49 static unsigned int nr_swapfiles;
50 atomic_long_t nr_swap_pages;
51 /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
52 long total_swap_pages;
53 static int least_priority;
55 static const char Bad_file[] = "Bad swap file entry ";
56 static const char Unused_file[] = "Unused swap file entry ";
57 static const char Bad_offset[] = "Bad swap offset entry ";
58 static const char Unused_offset[] = "Unused swap offset entry ";
61 * all active swap_info_structs
62 * protected with swap_lock, and ordered by priority.
64 PLIST_HEAD(swap_active_head);
67 * all available (active, not full) swap_info_structs
68 * protected with swap_avail_lock, ordered by priority.
69 * This is used by get_swap_page() instead of swap_active_head
70 * because swap_active_head includes all swap_info_structs,
71 * but get_swap_page() doesn't need to look at full ones.
72 * This uses its own lock instead of swap_lock because when a
73 * swap_info_struct changes between not-full/full, it needs to
74 * add/remove itself to/from this list, but the swap_info_struct->lock
75 * is held and the locking order requires swap_lock to be taken
76 * before any swap_info_struct->lock.
78 PLIST_HEAD(swap_avail_head);
79 DEFINE_SPINLOCK(swap_avail_lock);
81 struct swap_info_struct *swap_info[MAX_SWAPFILES];
83 static DEFINE_MUTEX(swapon_mutex);
85 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
86 /* Activity counter to indicate that a swapon or swapoff has occurred */
87 static atomic_t proc_poll_event = ATOMIC_INIT(0);
89 static inline unsigned char swap_count(unsigned char ent)
91 return ent & ~SWAP_HAS_CACHE; /* may include SWAP_HAS_CONT flag */
94 bool is_swap_fast(swp_entry_t entry)
96 struct swap_info_struct *p;
99 if (non_swap_entry(entry))
102 type = swp_type(entry);
103 if (type >= nr_swapfiles)
108 if (p->flags & SWP_FAST)
114 /* returns 1 if swap entry is freed */
116 __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
118 swp_entry_t entry = swp_entry(si->type, offset);
122 page = find_get_page(swap_address_space(entry), entry.val);
126 * This function is called from scan_swap_map() and it's called
127 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
128 * We have to use trylock for avoiding deadlock. This is a special
129 * case and you should use try_to_free_swap() with explicit lock_page()
130 * in usual operations.
132 if (trylock_page(page)) {
133 ret = try_to_free_swap(page);
136 page_cache_release(page);
141 * swapon tell device that all the old swap contents can be discarded,
142 * to allow the swap device to optimize its wear-levelling.
144 static int discard_swap(struct swap_info_struct *si)
146 struct swap_extent *se;
147 sector_t start_block;
151 /* Do not discard the swap header page! */
152 se = &si->first_swap_extent;
153 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
154 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
156 err = blkdev_issue_discard(si->bdev, start_block,
157 nr_blocks, GFP_KERNEL, 0);
163 list_for_each_entry(se, &si->first_swap_extent.list, list) {
164 start_block = se->start_block << (PAGE_SHIFT - 9);
165 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
167 err = blkdev_issue_discard(si->bdev, start_block,
168 nr_blocks, GFP_KERNEL, 0);
174 return err; /* That will often be -EOPNOTSUPP */
178 * swap allocation tell device that a cluster of swap can now be discarded,
179 * to allow the swap device to optimize its wear-levelling.
181 static void discard_swap_cluster(struct swap_info_struct *si,
182 pgoff_t start_page, pgoff_t nr_pages)
184 struct swap_extent *se = si->curr_swap_extent;
185 int found_extent = 0;
188 struct list_head *lh;
190 if (se->start_page <= start_page &&
191 start_page < se->start_page + se->nr_pages) {
192 pgoff_t offset = start_page - se->start_page;
193 sector_t start_block = se->start_block + offset;
194 sector_t nr_blocks = se->nr_pages - offset;
196 if (nr_blocks > nr_pages)
197 nr_blocks = nr_pages;
198 start_page += nr_blocks;
199 nr_pages -= nr_blocks;
202 si->curr_swap_extent = se;
204 start_block <<= PAGE_SHIFT - 9;
205 nr_blocks <<= PAGE_SHIFT - 9;
206 if (blkdev_issue_discard(si->bdev, start_block,
207 nr_blocks, GFP_NOIO, 0))
212 se = list_entry(lh, struct swap_extent, list);
216 #define LATENCY_LIMIT 256
218 static inline void cluster_set_flag(struct swap_cluster_info *info,
224 static inline unsigned int cluster_count(struct swap_cluster_info *info)
229 static inline void cluster_set_count(struct swap_cluster_info *info,
235 static inline void cluster_set_count_flag(struct swap_cluster_info *info,
236 unsigned int c, unsigned int f)
242 static inline unsigned int cluster_next(struct swap_cluster_info *info)
247 static inline void cluster_set_next(struct swap_cluster_info *info,
253 static inline void cluster_set_next_flag(struct swap_cluster_info *info,
254 unsigned int n, unsigned int f)
260 static inline bool cluster_is_free(struct swap_cluster_info *info)
262 return info->flags & CLUSTER_FLAG_FREE;
265 static inline bool cluster_is_null(struct swap_cluster_info *info)
267 return info->flags & CLUSTER_FLAG_NEXT_NULL;
270 static inline void cluster_set_null(struct swap_cluster_info *info)
272 info->flags = CLUSTER_FLAG_NEXT_NULL;
276 /* Add a cluster to discard list and schedule it to do discard */
277 static void swap_cluster_schedule_discard(struct swap_info_struct *si,
281 * If scan_swap_map() can't find a free cluster, it will check
282 * si->swap_map directly. To make sure the discarding cluster isn't
283 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
284 * will be cleared after discard
286 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
287 SWAP_MAP_BAD, SWAPFILE_CLUSTER);
289 if (cluster_is_null(&si->discard_cluster_head)) {
290 cluster_set_next_flag(&si->discard_cluster_head,
292 cluster_set_next_flag(&si->discard_cluster_tail,
295 unsigned int tail = cluster_next(&si->discard_cluster_tail);
296 cluster_set_next(&si->cluster_info[tail], idx);
297 cluster_set_next_flag(&si->discard_cluster_tail,
301 schedule_work(&si->discard_work);
305 * Doing discard actually. After a cluster discard is finished, the cluster
306 * will be added to free cluster list. caller should hold si->lock.
308 static void swap_do_scheduled_discard(struct swap_info_struct *si)
310 struct swap_cluster_info *info;
313 info = si->cluster_info;
315 while (!cluster_is_null(&si->discard_cluster_head)) {
316 idx = cluster_next(&si->discard_cluster_head);
318 cluster_set_next_flag(&si->discard_cluster_head,
319 cluster_next(&info[idx]), 0);
320 if (cluster_next(&si->discard_cluster_tail) == idx) {
321 cluster_set_null(&si->discard_cluster_head);
322 cluster_set_null(&si->discard_cluster_tail);
324 spin_unlock(&si->lock);
326 discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
329 spin_lock(&si->lock);
330 cluster_set_flag(&info[idx], CLUSTER_FLAG_FREE);
331 if (cluster_is_null(&si->free_cluster_head)) {
332 cluster_set_next_flag(&si->free_cluster_head,
334 cluster_set_next_flag(&si->free_cluster_tail,
339 tail = cluster_next(&si->free_cluster_tail);
340 cluster_set_next(&info[tail], idx);
341 cluster_set_next_flag(&si->free_cluster_tail,
344 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
345 0, SWAPFILE_CLUSTER);
349 static void swap_discard_work(struct work_struct *work)
351 struct swap_info_struct *si;
353 si = container_of(work, struct swap_info_struct, discard_work);
355 spin_lock(&si->lock);
356 swap_do_scheduled_discard(si);
357 spin_unlock(&si->lock);
361 * The cluster corresponding to page_nr will be used. The cluster will be
362 * removed from free cluster list and its usage counter will be increased.
364 static void inc_cluster_info_page(struct swap_info_struct *p,
365 struct swap_cluster_info *cluster_info, unsigned long page_nr)
367 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
371 if (cluster_is_free(&cluster_info[idx])) {
372 VM_BUG_ON(cluster_next(&p->free_cluster_head) != idx);
373 cluster_set_next_flag(&p->free_cluster_head,
374 cluster_next(&cluster_info[idx]), 0);
375 if (cluster_next(&p->free_cluster_tail) == idx) {
376 cluster_set_null(&p->free_cluster_tail);
377 cluster_set_null(&p->free_cluster_head);
379 cluster_set_count_flag(&cluster_info[idx], 0, 0);
382 VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
383 cluster_set_count(&cluster_info[idx],
384 cluster_count(&cluster_info[idx]) + 1);
388 * The cluster corresponding to page_nr decreases one usage. If the usage
389 * counter becomes 0, which means no page in the cluster is in using, we can
390 * optionally discard the cluster and add it to free cluster list.
392 static void dec_cluster_info_page(struct swap_info_struct *p,
393 struct swap_cluster_info *cluster_info, unsigned long page_nr)
395 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
400 VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
401 cluster_set_count(&cluster_info[idx],
402 cluster_count(&cluster_info[idx]) - 1);
404 if (cluster_count(&cluster_info[idx]) == 0) {
406 * If the swap is discardable, prepare discard the cluster
407 * instead of free it immediately. The cluster will be freed
410 if ((p->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
411 (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
412 swap_cluster_schedule_discard(p, idx);
416 cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
417 if (cluster_is_null(&p->free_cluster_head)) {
418 cluster_set_next_flag(&p->free_cluster_head, idx, 0);
419 cluster_set_next_flag(&p->free_cluster_tail, idx, 0);
421 unsigned int tail = cluster_next(&p->free_cluster_tail);
422 cluster_set_next(&cluster_info[tail], idx);
423 cluster_set_next_flag(&p->free_cluster_tail, idx, 0);
429 * It's possible scan_swap_map() uses a free cluster in the middle of free
430 * cluster list. Avoiding such abuse to avoid list corruption.
433 scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
434 unsigned long offset)
436 struct percpu_cluster *percpu_cluster;
439 offset /= SWAPFILE_CLUSTER;
440 conflict = !cluster_is_null(&si->free_cluster_head) &&
441 offset != cluster_next(&si->free_cluster_head) &&
442 cluster_is_free(&si->cluster_info[offset]);
447 percpu_cluster = this_cpu_ptr(si->percpu_cluster);
448 cluster_set_null(&percpu_cluster->index);
453 * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
454 * might involve allocating a new cluster for current CPU too.
456 static void scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
457 unsigned long *offset, unsigned long *scan_base)
459 struct percpu_cluster *cluster;
464 cluster = this_cpu_ptr(si->percpu_cluster);
465 if (cluster_is_null(&cluster->index)) {
466 if (!cluster_is_null(&si->free_cluster_head)) {
467 cluster->index = si->free_cluster_head;
468 cluster->next = cluster_next(&cluster->index) *
470 } else if (!cluster_is_null(&si->discard_cluster_head)) {
472 * we don't have free cluster but have some clusters in
473 * discarding, do discard now and reclaim them
475 swap_do_scheduled_discard(si);
476 *scan_base = *offset = si->cluster_next;
485 * Other CPUs can use our cluster if they can't find a free cluster,
486 * check if there is still free entry in the cluster
489 while (tmp < si->max && tmp < (cluster_next(&cluster->index) + 1) *
491 if (!si->swap_map[tmp]) {
498 cluster_set_null(&cluster->index);
501 cluster->next = tmp + 1;
506 static unsigned long scan_swap_map(struct swap_info_struct *si,
509 unsigned long offset;
510 unsigned long scan_base;
511 unsigned long last_in_cluster = 0;
512 int latency_ration = LATENCY_LIMIT;
515 * We try to cluster swap pages by allocating them sequentially
516 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
517 * way, however, we resort to first-free allocation, starting
518 * a new cluster. This prevents us from scattering swap pages
519 * all over the entire swap partition, so that we reduce
520 * overall disk seek times between swap pages. -- sct
521 * But we do now try to find an empty cluster. -Andrea
522 * And we let swap pages go all over an SSD partition. Hugh
525 si->flags += SWP_SCANNING;
526 scan_base = offset = si->cluster_next;
529 if (si->cluster_info) {
530 scan_swap_map_try_ssd_cluster(si, &offset, &scan_base);
534 if (unlikely(!si->cluster_nr--)) {
535 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
536 si->cluster_nr = SWAPFILE_CLUSTER - 1;
540 spin_unlock(&si->lock);
543 * If seek is expensive, start searching for new cluster from
544 * start of partition, to minimize the span of allocated swap.
545 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
546 * case, just handled by scan_swap_map_try_ssd_cluster() above.
548 scan_base = offset = si->lowest_bit;
549 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
551 /* Locate the first empty (unaligned) cluster */
552 for (; last_in_cluster <= si->highest_bit; offset++) {
553 if (si->swap_map[offset])
554 last_in_cluster = offset + SWAPFILE_CLUSTER;
555 else if (offset == last_in_cluster) {
556 spin_lock(&si->lock);
557 offset -= SWAPFILE_CLUSTER - 1;
558 si->cluster_next = offset;
559 si->cluster_nr = SWAPFILE_CLUSTER - 1;
562 if (unlikely(--latency_ration < 0)) {
564 latency_ration = LATENCY_LIMIT;
569 spin_lock(&si->lock);
570 si->cluster_nr = SWAPFILE_CLUSTER - 1;
574 if (si->cluster_info) {
575 while (scan_swap_map_ssd_cluster_conflict(si, offset))
576 scan_swap_map_try_ssd_cluster(si, &offset, &scan_base);
578 if (!(si->flags & SWP_WRITEOK))
580 if (!si->highest_bit)
582 if (offset > si->highest_bit)
583 scan_base = offset = si->lowest_bit;
585 /* reuse swap entry of cache-only swap if not busy. */
586 if (vm_swap_full(si) && si->swap_map[offset] == SWAP_HAS_CACHE) {
588 spin_unlock(&si->lock);
589 swap_was_freed = __try_to_reclaim_swap(si, offset);
590 spin_lock(&si->lock);
591 /* entry was freed successfully, try to use this again */
594 goto scan; /* check next one */
597 if (si->swap_map[offset])
600 if (offset == si->lowest_bit)
602 if (offset == si->highest_bit)
605 if (si->inuse_pages == si->pages) {
606 si->lowest_bit = si->max;
608 spin_lock(&swap_avail_lock);
609 plist_del(&si->avail_list, &swap_avail_head);
610 spin_unlock(&swap_avail_lock);
612 si->swap_map[offset] = usage;
613 inc_cluster_info_page(si, si->cluster_info, offset);
614 si->cluster_next = offset + 1;
615 si->flags -= SWP_SCANNING;
620 spin_unlock(&si->lock);
621 while (++offset <= si->highest_bit) {
622 if (!si->swap_map[offset]) {
623 spin_lock(&si->lock);
626 if (vm_swap_full(si) &&
627 si->swap_map[offset] == SWAP_HAS_CACHE) {
628 spin_lock(&si->lock);
631 if (unlikely(--latency_ration < 0)) {
633 latency_ration = LATENCY_LIMIT;
636 offset = si->lowest_bit;
637 while (offset < scan_base) {
638 if (!si->swap_map[offset]) {
639 spin_lock(&si->lock);
642 if (vm_swap_full(si) &&
643 si->swap_map[offset] == SWAP_HAS_CACHE) {
644 spin_lock(&si->lock);
647 if (unlikely(--latency_ration < 0)) {
649 latency_ration = LATENCY_LIMIT;
653 spin_lock(&si->lock);
656 si->flags -= SWP_SCANNING;
660 swp_entry_t get_swap_page(void)
662 struct swap_info_struct *si, *next;
664 int swap_ratio_off = 0;
666 if (atomic_long_read(&nr_swap_pages) <= 0)
668 atomic_long_dec(&nr_swap_pages);
671 spin_lock(&swap_avail_lock);
674 plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
676 if (sysctl_swap_ratio && !swap_ratio_off) {
679 spin_unlock(&swap_avail_lock);
680 ret = swap_ratio(&si);
683 * Error. Start again with swap
693 /* requeue si to after same-priority siblings */
694 plist_requeue(&si->avail_list, &swap_avail_head);
695 spin_unlock(&swap_avail_lock);
697 spin_lock(&si->lock);
698 if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
699 spin_lock(&swap_avail_lock);
700 if (plist_node_empty(&si->avail_list)) {
701 spin_unlock(&si->lock);
704 WARN(!si->highest_bit,
705 "swap_info %d in list but !highest_bit\n",
707 WARN(!(si->flags & SWP_WRITEOK),
708 "swap_info %d in list but !SWP_WRITEOK\n",
710 plist_del(&si->avail_list, &swap_avail_head);
711 spin_unlock(&si->lock);
715 /* This is called for allocating swap entry for cache */
716 offset = scan_swap_map(si, SWAP_HAS_CACHE);
717 spin_unlock(&si->lock);
719 return swp_entry(si->type, offset);
720 pr_debug("scan_swap_map of si %d failed to find offset\n",
722 spin_lock(&swap_avail_lock);
725 * if we got here, it's likely that si was almost full before,
726 * and since scan_swap_map() can drop the si->lock, multiple
727 * callers probably all tried to get a page from the same si
728 * and it filled up before we could get one; or, the si filled
729 * up between us dropping swap_avail_lock and taking si->lock.
730 * Since we dropped the swap_avail_lock, the swap_avail_head
731 * list may have been modified; so if next is still in the
732 * swap_avail_head list then try it, otherwise start over.
734 if (plist_node_empty(&next->avail_list))
738 spin_unlock(&swap_avail_lock);
740 atomic_long_inc(&nr_swap_pages);
742 return (swp_entry_t) {0};
745 /* The only caller of this function is now suspend routine */
746 swp_entry_t get_swap_page_of_type(int type)
748 struct swap_info_struct *si;
751 si = swap_info[type];
752 spin_lock(&si->lock);
753 if (si && (si->flags & SWP_WRITEOK)) {
754 atomic_long_dec(&nr_swap_pages);
755 /* This is called for allocating swap entry, not cache */
756 offset = scan_swap_map(si, 1);
758 spin_unlock(&si->lock);
759 return swp_entry(type, offset);
761 atomic_long_inc(&nr_swap_pages);
763 spin_unlock(&si->lock);
764 return (swp_entry_t) {0};
767 static struct swap_info_struct *swap_info_get(swp_entry_t entry)
769 struct swap_info_struct *p;
770 unsigned long offset, type;
774 type = swp_type(entry);
775 if (type >= nr_swapfiles)
778 if (!(p->flags & SWP_USED))
780 offset = swp_offset(entry);
781 if (offset >= p->max)
783 if (!p->swap_map[offset])
789 pr_err("swap_free: %s%08lx\n", Unused_offset, entry.val);
792 pr_err("swap_free: %s%08lx\n", Bad_offset, entry.val);
795 pr_err("swap_free: %s%08lx\n", Unused_file, entry.val);
798 pr_err("swap_free: %s%08lx\n", Bad_file, entry.val);
803 static unsigned char swap_entry_free(struct swap_info_struct *p,
804 swp_entry_t entry, unsigned char usage)
806 unsigned long offset = swp_offset(entry);
808 unsigned char has_cache;
810 count = p->swap_map[offset];
811 has_cache = count & SWAP_HAS_CACHE;
812 count &= ~SWAP_HAS_CACHE;
814 if (usage == SWAP_HAS_CACHE) {
815 VM_BUG_ON(!has_cache);
817 } else if (count == SWAP_MAP_SHMEM) {
819 * Or we could insist on shmem.c using a special
820 * swap_shmem_free() and free_shmem_swap_and_cache()...
823 } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
824 if (count == COUNT_CONTINUED) {
825 if (swap_count_continued(p, offset, count))
826 count = SWAP_MAP_MAX | COUNT_CONTINUED;
828 count = SWAP_MAP_MAX;
834 mem_cgroup_uncharge_swap(entry);
836 usage = count | has_cache;
837 p->swap_map[offset] = usage;
839 /* free if no reference */
841 dec_cluster_info_page(p, p->cluster_info, offset);
842 if (offset < p->lowest_bit)
843 p->lowest_bit = offset;
844 if (offset > p->highest_bit) {
845 bool was_full = !p->highest_bit;
846 p->highest_bit = offset;
847 if (was_full && (p->flags & SWP_WRITEOK)) {
848 spin_lock(&swap_avail_lock);
849 WARN_ON(!plist_node_empty(&p->avail_list));
850 if (plist_node_empty(&p->avail_list))
851 plist_add(&p->avail_list,
853 spin_unlock(&swap_avail_lock);
856 atomic_long_inc(&nr_swap_pages);
858 frontswap_invalidate_page(p->type, offset);
859 if (p->flags & SWP_BLKDEV) {
860 struct gendisk *disk = p->bdev->bd_disk;
861 if (disk->fops->swap_slot_free_notify)
862 disk->fops->swap_slot_free_notify(p->bdev,
871 * Caller has made sure that the swap device corresponding to entry
872 * is still around or has not been recycled.
874 void swap_free(swp_entry_t entry)
876 struct swap_info_struct *p;
878 p = swap_info_get(entry);
880 swap_entry_free(p, entry, 1);
881 spin_unlock(&p->lock);
886 * Called after dropping swapcache to decrease refcnt to swap entries.
888 void swapcache_free(swp_entry_t entry)
890 struct swap_info_struct *p;
892 p = swap_info_get(entry);
894 swap_entry_free(p, entry, SWAP_HAS_CACHE);
895 spin_unlock(&p->lock);
900 * How many references to page are currently swapped out?
901 * This does not give an exact answer when swap count is continued,
902 * but does include the high COUNT_CONTINUED flag to allow for that.
904 int page_swapcount(struct page *page)
907 struct swap_info_struct *p;
910 entry.val = page_private(page);
911 p = swap_info_get(entry);
913 count = swap_count(p->swap_map[swp_offset(entry)]);
914 spin_unlock(&p->lock);
920 * How many references to @entry are currently swapped out?
921 * This considers COUNT_CONTINUED so it returns exact answer.
923 int swp_swapcount(swp_entry_t entry)
925 int count, tmp_count, n;
926 struct swap_info_struct *p;
931 p = swap_info_get(entry);
935 count = swap_count(p->swap_map[swp_offset(entry)]);
936 if (!(count & COUNT_CONTINUED))
939 count &= ~COUNT_CONTINUED;
940 n = SWAP_MAP_MAX + 1;
942 offset = swp_offset(entry);
943 page = vmalloc_to_page(p->swap_map + offset);
944 offset &= ~PAGE_MASK;
945 VM_BUG_ON(page_private(page) != SWP_CONTINUED);
948 page = list_entry(page->lru.next, struct page, lru);
949 map = kmap_atomic(page);
950 tmp_count = map[offset];
953 count += (tmp_count & ~COUNT_CONTINUED) * n;
954 n *= (SWAP_CONT_MAX + 1);
955 } while (tmp_count & COUNT_CONTINUED);
957 spin_unlock(&p->lock);
962 * We can write to an anon page without COW if there are no other references
963 * to it. And as a side-effect, free up its swap: because the old content
964 * on disk will never be read, and seeking back there to write new content
965 * later would only waste time away from clustering.
967 int reuse_swap_page(struct page *page)
971 VM_BUG_ON_PAGE(!PageLocked(page), page);
972 if (unlikely(PageKsm(page)))
974 count = page_mapcount(page);
975 if (count <= 1 && PageSwapCache(page)) {
976 count += page_swapcount(page);
979 if (!PageWriteback(page)) {
980 delete_from_swap_cache(page);
984 struct swap_info_struct *p;
986 entry.val = page_private(page);
987 p = swap_info_get(entry);
988 if (p->flags & SWP_STABLE_WRITES) {
989 spin_unlock(&p->lock);
992 spin_unlock(&p->lock);
1000 * If swap is getting full, or if there are no more mappings of this page,
1001 * then try_to_free_swap is called to free its swap space.
1003 int try_to_free_swap(struct page *page)
1005 VM_BUG_ON_PAGE(!PageLocked(page), page);
1007 if (!PageSwapCache(page))
1009 if (PageWriteback(page))
1011 if (page_swapcount(page))
1015 * Once hibernation has begun to create its image of memory,
1016 * there's a danger that one of the calls to try_to_free_swap()
1017 * - most probably a call from __try_to_reclaim_swap() while
1018 * hibernation is allocating its own swap pages for the image,
1019 * but conceivably even a call from memory reclaim - will free
1020 * the swap from a page which has already been recorded in the
1021 * image as a clean swapcache page, and then reuse its swap for
1022 * another page of the image. On waking from hibernation, the
1023 * original page might be freed under memory pressure, then
1024 * later read back in from swap, now with the wrong data.
1026 * Hibernation suspends storage while it is writing the image
1027 * to disk so check that here.
1029 if (pm_suspended_storage())
1032 delete_from_swap_cache(page);
1038 * Free the swap entry like above, but also try to
1039 * free the page cache entry if it is the last user.
1041 int free_swap_and_cache(swp_entry_t entry)
1043 struct swap_info_struct *p;
1044 struct page *page = NULL;
1046 if (non_swap_entry(entry))
1049 p = swap_info_get(entry);
1051 if (swap_entry_free(p, entry, 1) == SWAP_HAS_CACHE) {
1052 page = find_get_page(swap_address_space(entry),
1054 if (page && !trylock_page(page)) {
1055 page_cache_release(page);
1059 spin_unlock(&p->lock);
1063 * Not mapped elsewhere, or swap space full? Free it!
1064 * Also recheck PageSwapCache now page is locked (above).
1066 if (PageSwapCache(page) && !PageWriteback(page) &&
1067 (!page_mapped(page) ||
1068 vm_swap_full(page_swap_info(page)))) {
1069 delete_from_swap_cache(page);
1073 page_cache_release(page);
1078 #ifdef CONFIG_HIBERNATION
1080 * Find the swap type that corresponds to given device (if any).
1082 * @offset - number of the PAGE_SIZE-sized block of the device, starting
1083 * from 0, in which the swap header is expected to be located.
1085 * This is needed for the suspend to disk (aka swsusp).
1087 int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
1089 struct block_device *bdev = NULL;
1093 bdev = bdget(device);
1095 spin_lock(&swap_lock);
1096 for (type = 0; type < nr_swapfiles; type++) {
1097 struct swap_info_struct *sis = swap_info[type];
1099 if (!(sis->flags & SWP_WRITEOK))
1104 *bdev_p = bdgrab(sis->bdev);
1106 spin_unlock(&swap_lock);
1109 if (bdev == sis->bdev) {
1110 struct swap_extent *se = &sis->first_swap_extent;
1112 if (se->start_block == offset) {
1114 *bdev_p = bdgrab(sis->bdev);
1116 spin_unlock(&swap_lock);
1122 spin_unlock(&swap_lock);
1130 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1131 * corresponding to given index in swap_info (swap type).
1133 sector_t swapdev_block(int type, pgoff_t offset)
1135 struct block_device *bdev;
1137 if ((unsigned int)type >= nr_swapfiles)
1139 if (!(swap_info[type]->flags & SWP_WRITEOK))
1141 return map_swap_entry(swp_entry(type, offset), &bdev);
1145 * Return either the total number of swap pages of given type, or the number
1146 * of free pages of that type (depending on @free)
1148 * This is needed for software suspend
1150 unsigned int count_swap_pages(int type, int free)
1154 spin_lock(&swap_lock);
1155 if ((unsigned int)type < nr_swapfiles) {
1156 struct swap_info_struct *sis = swap_info[type];
1158 spin_lock(&sis->lock);
1159 if (sis->flags & SWP_WRITEOK) {
1162 n -= sis->inuse_pages;
1164 spin_unlock(&sis->lock);
1166 spin_unlock(&swap_lock);
1169 #endif /* CONFIG_HIBERNATION */
1171 static inline int maybe_same_pte(pte_t pte, pte_t swp_pte)
1173 #ifdef CONFIG_MEM_SOFT_DIRTY
1175 * When pte keeps soft dirty bit the pte generated
1176 * from swap entry does not has it, still it's same
1177 * pte from logical point of view.
1179 pte_t swp_pte_dirty = pte_swp_mksoft_dirty(swp_pte);
1180 return pte_same(pte, swp_pte) || pte_same(pte, swp_pte_dirty);
1182 return pte_same(pte, swp_pte);
1187 * No need to decide whether this PTE shares the swap entry with others,
1188 * just let do_wp_page work it out if a write is requested later - to
1189 * force COW, vm_page_prot omits write permission from any private vma.
1191 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1192 unsigned long addr, swp_entry_t entry, struct page *page)
1194 struct page *swapcache;
1195 struct mem_cgroup *memcg;
1201 page = ksm_might_need_to_copy(page, vma, addr);
1202 if (unlikely(!page))
1205 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg)) {
1210 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1211 if (unlikely(!maybe_same_pte(*pte, swp_entry_to_pte(entry)))) {
1212 mem_cgroup_cancel_charge(page, memcg);
1217 dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1218 inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
1220 set_pte_at(vma->vm_mm, addr, pte,
1221 pte_mkold(mk_pte(page, vma->vm_page_prot)));
1222 if (page == swapcache) {
1223 page_add_anon_rmap(page, vma, addr);
1224 mem_cgroup_commit_charge(page, memcg, true);
1225 } else { /* ksm created a completely new copy */
1226 page_add_new_anon_rmap(page, vma, addr);
1227 mem_cgroup_commit_charge(page, memcg, false);
1228 lru_cache_add_active_or_unevictable(page, vma);
1232 * Move the page to the active list so it is not
1233 * immediately swapped out again after swapon.
1235 activate_page(page);
1237 pte_unmap_unlock(pte, ptl);
1239 if (page != swapcache) {
1246 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
1247 unsigned long addr, unsigned long end,
1248 swp_entry_t entry, struct page *page)
1250 pte_t swp_pte = swp_entry_to_pte(entry);
1255 * We don't actually need pte lock while scanning for swp_pte: since
1256 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
1257 * page table while we're scanning; though it could get zapped, and on
1258 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
1259 * of unmatched parts which look like swp_pte, so unuse_pte must
1260 * recheck under pte lock. Scanning without pte lock lets it be
1261 * preemptable whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
1263 pte = pte_offset_map(pmd, addr);
1266 * swapoff spends a _lot_ of time in this loop!
1267 * Test inline before going to call unuse_pte.
1269 if (unlikely(maybe_same_pte(*pte, swp_pte))) {
1271 ret = unuse_pte(vma, pmd, addr, entry, page);
1274 pte = pte_offset_map(pmd, addr);
1276 } while (pte++, addr += PAGE_SIZE, addr != end);
1282 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
1283 unsigned long addr, unsigned long end,
1284 swp_entry_t entry, struct page *page)
1290 pmd = pmd_offset(pud, addr);
1292 next = pmd_addr_end(addr, end);
1293 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1295 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
1298 } while (pmd++, addr = next, addr != end);
1302 static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
1303 unsigned long addr, unsigned long end,
1304 swp_entry_t entry, struct page *page)
1310 pud = pud_offset(pgd, addr);
1312 next = pud_addr_end(addr, end);
1313 if (pud_none_or_clear_bad(pud))
1315 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
1318 } while (pud++, addr = next, addr != end);
1322 static int unuse_vma(struct vm_area_struct *vma,
1323 swp_entry_t entry, struct page *page)
1326 unsigned long addr, end, next;
1329 if (page_anon_vma(page)) {
1330 addr = page_address_in_vma(page, vma);
1331 if (addr == -EFAULT)
1334 end = addr + PAGE_SIZE;
1336 addr = vma->vm_start;
1340 pgd = pgd_offset(vma->vm_mm, addr);
1342 next = pgd_addr_end(addr, end);
1343 if (pgd_none_or_clear_bad(pgd))
1345 ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
1348 } while (pgd++, addr = next, addr != end);
1352 static int unuse_mm(struct mm_struct *mm,
1353 swp_entry_t entry, struct page *page)
1355 struct vm_area_struct *vma;
1358 if (!down_read_trylock(&mm->mmap_sem)) {
1360 * Activate page so shrink_inactive_list is unlikely to unmap
1361 * its ptes while lock is dropped, so swapoff can make progress.
1363 activate_page(page);
1365 down_read(&mm->mmap_sem);
1368 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1369 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
1372 up_read(&mm->mmap_sem);
1373 return (ret < 0)? ret: 0;
1377 * Scan swap_map (or frontswap_map if frontswap parameter is true)
1378 * from current position to next entry still in use.
1379 * Recycle to start on reaching the end, returning 0 when empty.
1381 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
1382 unsigned int prev, bool frontswap)
1384 unsigned int max = si->max;
1385 unsigned int i = prev;
1386 unsigned char count;
1389 * No need for swap_lock here: we're just looking
1390 * for whether an entry is in use, not modifying it; false
1391 * hits are okay, and sys_swapoff() has already prevented new
1392 * allocations from this area (while holding swap_lock).
1401 * No entries in use at top of swap_map,
1402 * loop back to start and recheck there.
1409 if (frontswap_test(si, i))
1414 count = READ_ONCE(si->swap_map[i]);
1415 if (count && swap_count(count) != SWAP_MAP_BAD)
1422 * We completely avoid races by reading each swap page in advance,
1423 * and then search for the process using it. All the necessary
1424 * page table adjustments can then be made atomically.
1426 * if the boolean frontswap is true, only unuse pages_to_unuse pages;
1427 * pages_to_unuse==0 means all pages; ignored if frontswap is false
1429 int try_to_unuse(unsigned int type, bool frontswap,
1430 unsigned long pages_to_unuse)
1432 struct swap_info_struct *si = swap_info[type];
1433 struct mm_struct *start_mm;
1434 volatile unsigned char *swap_map; /* swap_map is accessed without
1435 * locking. Mark it as volatile
1436 * to prevent compiler doing
1439 unsigned char swcount;
1446 * When searching mms for an entry, a good strategy is to
1447 * start at the first mm we freed the previous entry from
1448 * (though actually we don't notice whether we or coincidence
1449 * freed the entry). Initialize this start_mm with a hold.
1451 * A simpler strategy would be to start at the last mm we
1452 * freed the previous entry from; but that would take less
1453 * advantage of mmlist ordering, which clusters forked mms
1454 * together, child after parent. If we race with dup_mmap(), we
1455 * prefer to resolve parent before child, lest we miss entries
1456 * duplicated after we scanned child: using last mm would invert
1459 start_mm = &init_mm;
1460 atomic_inc(&init_mm.mm_users);
1463 * Keep on scanning until all entries have gone. Usually,
1464 * one pass through swap_map is enough, but not necessarily:
1465 * there are races when an instance of an entry might be missed.
1467 while ((i = find_next_to_unuse(si, i, frontswap)) != 0) {
1468 if (signal_pending(current)) {
1474 * Get a page for the entry, using the existing swap
1475 * cache page if there is one. Otherwise, get a clean
1476 * page and read the swap into it.
1478 swap_map = &si->swap_map[i];
1479 entry = swp_entry(type, i);
1480 page = read_swap_cache_async(entry,
1481 GFP_HIGHUSER_MOVABLE, NULL, 0);
1484 * Either swap_duplicate() failed because entry
1485 * has been freed independently, and will not be
1486 * reused since sys_swapoff() already disabled
1487 * allocation from here, or alloc_page() failed.
1489 swcount = *swap_map;
1491 * We don't hold lock here, so the swap entry could be
1492 * SWAP_MAP_BAD (when the cluster is discarding).
1493 * Instead of fail out, We can just skip the swap
1494 * entry because swapoff will wait for discarding
1497 if (!swcount || swcount == SWAP_MAP_BAD)
1504 * Don't hold on to start_mm if it looks like exiting.
1506 if (atomic_read(&start_mm->mm_users) == 1) {
1508 start_mm = &init_mm;
1509 atomic_inc(&init_mm.mm_users);
1513 * Wait for and lock page. When do_swap_page races with
1514 * try_to_unuse, do_swap_page can handle the fault much
1515 * faster than try_to_unuse can locate the entry. This
1516 * apparently redundant "wait_on_page_locked" lets try_to_unuse
1517 * defer to do_swap_page in such a case - in some tests,
1518 * do_swap_page and try_to_unuse repeatedly compete.
1520 wait_on_page_locked(page);
1521 wait_on_page_writeback(page);
1523 wait_on_page_writeback(page);
1526 * Remove all references to entry.
1528 swcount = *swap_map;
1529 if (swap_count(swcount) == SWAP_MAP_SHMEM) {
1530 retval = shmem_unuse(entry, page);
1531 /* page has already been unlocked and released */
1536 if (swap_count(swcount) && start_mm != &init_mm)
1537 retval = unuse_mm(start_mm, entry, page);
1539 if (swap_count(*swap_map)) {
1540 int set_start_mm = (*swap_map >= swcount);
1541 struct list_head *p = &start_mm->mmlist;
1542 struct mm_struct *new_start_mm = start_mm;
1543 struct mm_struct *prev_mm = start_mm;
1544 struct mm_struct *mm;
1546 atomic_inc(&new_start_mm->mm_users);
1547 atomic_inc(&prev_mm->mm_users);
1548 spin_lock(&mmlist_lock);
1549 while (swap_count(*swap_map) && !retval &&
1550 (p = p->next) != &start_mm->mmlist) {
1551 mm = list_entry(p, struct mm_struct, mmlist);
1552 if (!atomic_inc_not_zero(&mm->mm_users))
1554 spin_unlock(&mmlist_lock);
1560 swcount = *swap_map;
1561 if (!swap_count(swcount)) /* any usage ? */
1563 else if (mm == &init_mm)
1566 retval = unuse_mm(mm, entry, page);
1568 if (set_start_mm && *swap_map < swcount) {
1569 mmput(new_start_mm);
1570 atomic_inc(&mm->mm_users);
1574 spin_lock(&mmlist_lock);
1576 spin_unlock(&mmlist_lock);
1579 start_mm = new_start_mm;
1583 page_cache_release(page);
1588 * If a reference remains (rare), we would like to leave
1589 * the page in the swap cache; but try_to_unmap could
1590 * then re-duplicate the entry once we drop page lock,
1591 * so we might loop indefinitely; also, that page could
1592 * not be swapped out to other storage meanwhile. So:
1593 * delete from cache even if there's another reference,
1594 * after ensuring that the data has been saved to disk -
1595 * since if the reference remains (rarer), it will be
1596 * read from disk into another page. Splitting into two
1597 * pages would be incorrect if swap supported "shared
1598 * private" pages, but they are handled by tmpfs files.
1600 * Given how unuse_vma() targets one particular offset
1601 * in an anon_vma, once the anon_vma has been determined,
1602 * this splitting happens to be just what is needed to
1603 * handle where KSM pages have been swapped out: re-reading
1604 * is unnecessarily slow, but we can fix that later on.
1606 if (swap_count(*swap_map) &&
1607 PageDirty(page) && PageSwapCache(page)) {
1608 struct writeback_control wbc = {
1609 .sync_mode = WB_SYNC_NONE,
1612 swap_writepage(page, &wbc);
1614 wait_on_page_writeback(page);
1618 * It is conceivable that a racing task removed this page from
1619 * swap cache just before we acquired the page lock at the top,
1620 * or while we dropped it in unuse_mm(). The page might even
1621 * be back in swap cache on another swap area: that we must not
1622 * delete, since it may not have been written out to swap yet.
1624 if (PageSwapCache(page) &&
1625 likely(page_private(page) == entry.val))
1626 delete_from_swap_cache(page);
1629 * So we could skip searching mms once swap count went
1630 * to 1, we did not mark any present ptes as dirty: must
1631 * mark page dirty so shrink_page_list will preserve it.
1635 page_cache_release(page);
1638 * Make sure that we aren't completely killing
1639 * interactive performance.
1642 if (frontswap && pages_to_unuse > 0) {
1643 if (!--pages_to_unuse)
1653 * After a successful try_to_unuse, if no swap is now in use, we know
1654 * we can empty the mmlist. swap_lock must be held on entry and exit.
1655 * Note that mmlist_lock nests inside swap_lock, and an mm must be
1656 * added to the mmlist just after page_duplicate - before would be racy.
1658 static void drain_mmlist(void)
1660 struct list_head *p, *next;
1663 for (type = 0; type < nr_swapfiles; type++)
1664 if (swap_info[type]->inuse_pages)
1666 spin_lock(&mmlist_lock);
1667 list_for_each_safe(p, next, &init_mm.mmlist)
1669 spin_unlock(&mmlist_lock);
1673 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
1674 * corresponds to page offset for the specified swap entry.
1675 * Note that the type of this function is sector_t, but it returns page offset
1676 * into the bdev, not sector offset.
1678 static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
1680 struct swap_info_struct *sis;
1681 struct swap_extent *start_se;
1682 struct swap_extent *se;
1685 sis = swap_info[swp_type(entry)];
1688 offset = swp_offset(entry);
1689 start_se = sis->curr_swap_extent;
1693 struct list_head *lh;
1695 if (se->start_page <= offset &&
1696 offset < (se->start_page + se->nr_pages)) {
1697 return se->start_block + (offset - se->start_page);
1700 se = list_entry(lh, struct swap_extent, list);
1701 sis->curr_swap_extent = se;
1702 BUG_ON(se == start_se); /* It *must* be present */
1707 * Returns the page offset into bdev for the specified page's swap entry.
1709 sector_t map_swap_page(struct page *page, struct block_device **bdev)
1712 entry.val = page_private(page);
1713 return map_swap_entry(entry, bdev);
1717 * Free all of a swapdev's extent information
1719 static void destroy_swap_extents(struct swap_info_struct *sis)
1721 while (!list_empty(&sis->first_swap_extent.list)) {
1722 struct swap_extent *se;
1724 se = list_entry(sis->first_swap_extent.list.next,
1725 struct swap_extent, list);
1726 list_del(&se->list);
1730 if (sis->flags & SWP_FILE) {
1731 struct file *swap_file = sis->swap_file;
1732 struct address_space *mapping = swap_file->f_mapping;
1734 sis->flags &= ~SWP_FILE;
1735 mapping->a_ops->swap_deactivate(swap_file);
1740 * Add a block range (and the corresponding page range) into this swapdev's
1741 * extent list. The extent list is kept sorted in page order.
1743 * This function rather assumes that it is called in ascending page order.
1746 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
1747 unsigned long nr_pages, sector_t start_block)
1749 struct swap_extent *se;
1750 struct swap_extent *new_se;
1751 struct list_head *lh;
1753 if (start_page == 0) {
1754 se = &sis->first_swap_extent;
1755 sis->curr_swap_extent = se;
1757 se->nr_pages = nr_pages;
1758 se->start_block = start_block;
1761 lh = sis->first_swap_extent.list.prev; /* Highest extent */
1762 se = list_entry(lh, struct swap_extent, list);
1763 BUG_ON(se->start_page + se->nr_pages != start_page);
1764 if (se->start_block + se->nr_pages == start_block) {
1766 se->nr_pages += nr_pages;
1772 * No merge. Insert a new extent, preserving ordering.
1774 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
1777 new_se->start_page = start_page;
1778 new_se->nr_pages = nr_pages;
1779 new_se->start_block = start_block;
1781 list_add_tail(&new_se->list, &sis->first_swap_extent.list);
1786 * A `swap extent' is a simple thing which maps a contiguous range of pages
1787 * onto a contiguous range of disk blocks. An ordered list of swap extents
1788 * is built at swapon time and is then used at swap_writepage/swap_readpage
1789 * time for locating where on disk a page belongs.
1791 * If the swapfile is an S_ISBLK block device, a single extent is installed.
1792 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1793 * swap files identically.
1795 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1796 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
1797 * swapfiles are handled *identically* after swapon time.
1799 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1800 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
1801 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1802 * requirements, they are simply tossed out - we will never use those blocks
1805 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1806 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1807 * which will scribble on the fs.
1809 * The amount of disk space which a single swap extent represents varies.
1810 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
1811 * extents in the list. To avoid much list walking, we cache the previous
1812 * search location in `curr_swap_extent', and start new searches from there.
1813 * This is extremely effective. The average number of iterations in
1814 * map_swap_page() has been measured at about 0.3 per page. - akpm.
1816 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1818 struct file *swap_file = sis->swap_file;
1819 struct address_space *mapping = swap_file->f_mapping;
1820 struct inode *inode = mapping->host;
1823 if (S_ISBLK(inode->i_mode)) {
1824 ret = add_swap_extent(sis, 0, sis->max, 0);
1829 if (mapping->a_ops->swap_activate) {
1830 ret = mapping->a_ops->swap_activate(sis, swap_file, span);
1832 sis->flags |= SWP_FILE;
1833 ret = add_swap_extent(sis, 0, sis->max, 0);
1839 return generic_swapfile_activate(sis, swap_file, span);
1842 static void _enable_swap_info(struct swap_info_struct *p, int prio,
1843 unsigned char *swap_map,
1844 struct swap_cluster_info *cluster_info)
1849 p->prio = --least_priority;
1851 * the plist prio is negated because plist ordering is
1852 * low-to-high, while swap ordering is high-to-low
1854 p->list.prio = -p->prio;
1855 p->avail_list.prio = -p->prio;
1856 p->swap_map = swap_map;
1857 p->cluster_info = cluster_info;
1858 p->flags |= SWP_WRITEOK;
1859 atomic_long_add(p->pages, &nr_swap_pages);
1860 total_swap_pages += p->pages;
1862 assert_spin_locked(&swap_lock);
1864 * both lists are plists, and thus priority ordered.
1865 * swap_active_head needs to be priority ordered for swapoff(),
1866 * which on removal of any swap_info_struct with an auto-assigned
1867 * (i.e. negative) priority increments the auto-assigned priority
1868 * of any lower-priority swap_info_structs.
1869 * swap_avail_head needs to be priority ordered for get_swap_page(),
1870 * which allocates swap pages from the highest available priority
1873 plist_add(&p->list, &swap_active_head);
1874 spin_lock(&swap_avail_lock);
1875 plist_add(&p->avail_list, &swap_avail_head);
1876 spin_unlock(&swap_avail_lock);
1879 static void enable_swap_info(struct swap_info_struct *p, int prio,
1880 unsigned char *swap_map,
1881 struct swap_cluster_info *cluster_info,
1882 unsigned long *frontswap_map)
1884 frontswap_init(p->type, frontswap_map);
1885 spin_lock(&swap_lock);
1886 spin_lock(&p->lock);
1887 _enable_swap_info(p, prio, swap_map, cluster_info);
1888 spin_unlock(&p->lock);
1889 spin_unlock(&swap_lock);
1892 static void reinsert_swap_info(struct swap_info_struct *p)
1894 spin_lock(&swap_lock);
1895 spin_lock(&p->lock);
1896 _enable_swap_info(p, p->prio, p->swap_map, p->cluster_info);
1897 spin_unlock(&p->lock);
1898 spin_unlock(&swap_lock);
1901 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
1903 struct swap_info_struct *p = NULL;
1904 unsigned char *swap_map;
1905 struct swap_cluster_info *cluster_info;
1906 unsigned long *frontswap_map;
1907 struct file *swap_file, *victim;
1908 struct address_space *mapping;
1909 struct inode *inode;
1910 struct filename *pathname;
1912 unsigned int old_block_size;
1914 if (!capable(CAP_SYS_ADMIN))
1917 BUG_ON(!current->mm);
1919 pathname = getname(specialfile);
1920 if (IS_ERR(pathname))
1921 return PTR_ERR(pathname);
1923 victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
1924 err = PTR_ERR(victim);
1928 mapping = victim->f_mapping;
1929 spin_lock(&swap_lock);
1930 plist_for_each_entry(p, &swap_active_head, list) {
1931 if (p->flags & SWP_WRITEOK) {
1932 if (p->swap_file->f_mapping == mapping) {
1940 spin_unlock(&swap_lock);
1943 if (!security_vm_enough_memory_mm(current->mm, p->pages))
1944 vm_unacct_memory(p->pages);
1947 spin_unlock(&swap_lock);
1950 spin_lock(&swap_avail_lock);
1951 plist_del(&p->avail_list, &swap_avail_head);
1952 spin_unlock(&swap_avail_lock);
1953 spin_lock(&p->lock);
1955 struct swap_info_struct *si = p;
1957 plist_for_each_entry_continue(si, &swap_active_head, list) {
1960 si->avail_list.prio--;
1964 plist_del(&p->list, &swap_active_head);
1965 atomic_long_sub(p->pages, &nr_swap_pages);
1966 total_swap_pages -= p->pages;
1967 p->flags &= ~SWP_WRITEOK;
1968 spin_unlock(&p->lock);
1969 spin_unlock(&swap_lock);
1971 set_current_oom_origin();
1972 err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
1973 clear_current_oom_origin();
1976 /* re-insert swap space back into swap_list */
1977 reinsert_swap_info(p);
1981 flush_work(&p->discard_work);
1983 destroy_swap_extents(p);
1984 if (p->flags & SWP_CONTINUED)
1985 free_swap_count_continuations(p);
1987 mutex_lock(&swapon_mutex);
1988 spin_lock(&swap_lock);
1989 spin_lock(&p->lock);
1992 /* wait for anyone still in scan_swap_map */
1993 p->highest_bit = 0; /* cuts scans short */
1994 while (p->flags >= SWP_SCANNING) {
1995 spin_unlock(&p->lock);
1996 spin_unlock(&swap_lock);
1997 schedule_timeout_uninterruptible(1);
1998 spin_lock(&swap_lock);
1999 spin_lock(&p->lock);
2002 swap_file = p->swap_file;
2003 old_block_size = p->old_block_size;
2004 p->swap_file = NULL;
2006 swap_map = p->swap_map;
2008 cluster_info = p->cluster_info;
2009 p->cluster_info = NULL;
2010 frontswap_map = frontswap_map_get(p);
2011 spin_unlock(&p->lock);
2012 spin_unlock(&swap_lock);
2013 frontswap_invalidate_area(p->type);
2014 frontswap_map_set(p, NULL);
2015 mutex_unlock(&swapon_mutex);
2016 free_percpu(p->percpu_cluster);
2017 p->percpu_cluster = NULL;
2019 vfree(cluster_info);
2020 vfree(frontswap_map);
2021 /* Destroy swap account information */
2022 swap_cgroup_swapoff(p->type);
2024 inode = mapping->host;
2025 if (S_ISBLK(inode->i_mode)) {
2026 struct block_device *bdev = I_BDEV(inode);
2027 set_blocksize(bdev, old_block_size);
2028 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2030 mutex_lock(&inode->i_mutex);
2031 inode->i_flags &= ~S_SWAPFILE;
2032 mutex_unlock(&inode->i_mutex);
2034 filp_close(swap_file, NULL);
2037 * Clear the SWP_USED flag after all resources are freed so that swapon
2038 * can reuse this swap_info in alloc_swap_info() safely. It is ok to
2039 * not hold p->lock after we cleared its SWP_WRITEOK.
2041 spin_lock(&swap_lock);
2043 spin_unlock(&swap_lock);
2046 atomic_inc(&proc_poll_event);
2047 wake_up_interruptible(&proc_poll_wait);
2050 filp_close(victim, NULL);
2056 #ifdef CONFIG_PROC_FS
2057 static unsigned swaps_poll(struct file *file, poll_table *wait)
2059 struct seq_file *seq = file->private_data;
2061 poll_wait(file, &proc_poll_wait, wait);
2063 if (seq->poll_event != atomic_read(&proc_poll_event)) {
2064 seq->poll_event = atomic_read(&proc_poll_event);
2065 return POLLIN | POLLRDNORM | POLLERR | POLLPRI;
2068 return POLLIN | POLLRDNORM;
2072 static void *swap_start(struct seq_file *swap, loff_t *pos)
2074 struct swap_info_struct *si;
2078 mutex_lock(&swapon_mutex);
2081 return SEQ_START_TOKEN;
2083 for (type = 0; type < nr_swapfiles; type++) {
2084 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
2085 si = swap_info[type];
2086 if (!(si->flags & SWP_USED) || !si->swap_map)
2095 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
2097 struct swap_info_struct *si = v;
2100 if (v == SEQ_START_TOKEN)
2103 type = si->type + 1;
2105 for (; type < nr_swapfiles; type++) {
2106 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
2107 si = swap_info[type];
2108 if (!(si->flags & SWP_USED) || !si->swap_map)
2117 static void swap_stop(struct seq_file *swap, void *v)
2119 mutex_unlock(&swapon_mutex);
2122 static int swap_show(struct seq_file *swap, void *v)
2124 struct swap_info_struct *si = v;
2128 if (si == SEQ_START_TOKEN) {
2129 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
2133 file = si->swap_file;
2134 len = seq_file_path(swap, file, " \t\n\\");
2135 seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
2136 len < 40 ? 40 - len : 1, " ",
2137 S_ISBLK(file_inode(file)->i_mode) ?
2138 "partition" : "file\t",
2139 si->pages << (PAGE_SHIFT - 10),
2140 si->inuse_pages << (PAGE_SHIFT - 10),
2145 static const struct seq_operations swaps_op = {
2146 .start = swap_start,
2152 static int swaps_open(struct inode *inode, struct file *file)
2154 struct seq_file *seq;
2157 ret = seq_open(file, &swaps_op);
2161 seq = file->private_data;
2162 seq->poll_event = atomic_read(&proc_poll_event);
2166 static const struct file_operations proc_swaps_operations = {
2169 .llseek = seq_lseek,
2170 .release = seq_release,
2174 static int __init procswaps_init(void)
2176 proc_create("swaps", 0, NULL, &proc_swaps_operations);
2179 __initcall(procswaps_init);
2180 #endif /* CONFIG_PROC_FS */
2182 #ifdef MAX_SWAPFILES_CHECK
2183 static int __init max_swapfiles_check(void)
2185 MAX_SWAPFILES_CHECK();
2188 late_initcall(max_swapfiles_check);
2191 static struct swap_info_struct *alloc_swap_info(void)
2193 struct swap_info_struct *p;
2196 p = kzalloc(sizeof(*p), GFP_KERNEL);
2198 return ERR_PTR(-ENOMEM);
2200 spin_lock(&swap_lock);
2201 for (type = 0; type < nr_swapfiles; type++) {
2202 if (!(swap_info[type]->flags & SWP_USED))
2205 if (type >= MAX_SWAPFILES) {
2206 spin_unlock(&swap_lock);
2208 return ERR_PTR(-EPERM);
2210 if (type >= nr_swapfiles) {
2212 swap_info[type] = p;
2214 * Write swap_info[type] before nr_swapfiles, in case a
2215 * racing procfs swap_start() or swap_next() is reading them.
2216 * (We never shrink nr_swapfiles, we never free this entry.)
2222 p = swap_info[type];
2224 * Do not memset this entry: a racing procfs swap_next()
2225 * would be relying on p->type to remain valid.
2228 INIT_LIST_HEAD(&p->first_swap_extent.list);
2229 plist_node_init(&p->list, 0);
2230 plist_node_init(&p->avail_list, 0);
2231 p->flags = SWP_USED;
2232 spin_unlock(&swap_lock);
2233 spin_lock_init(&p->lock);
2238 static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
2242 if (S_ISBLK(inode->i_mode)) {
2243 p->bdev = bdgrab(I_BDEV(inode));
2244 error = blkdev_get(p->bdev,
2245 FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
2250 p->old_block_size = block_size(p->bdev);
2251 error = set_blocksize(p->bdev, PAGE_SIZE);
2254 p->flags |= SWP_BLKDEV;
2255 } else if (S_ISREG(inode->i_mode)) {
2256 p->bdev = inode->i_sb->s_bdev;
2257 mutex_lock(&inode->i_mutex);
2258 if (IS_SWAPFILE(inode))
2268 * Find out how many pages are allowed for a single swap device. There
2269 * are two limiting factors:
2270 * 1) the number of bits for the swap offset in the swp_entry_t type, and
2271 * 2) the number of bits in the swap pte, as defined by the different
2274 * In order to find the largest possible bit mask, a swap entry with
2275 * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2276 * decoded to a swp_entry_t again, and finally the swap offset is
2279 * This will mask all the bits from the initial ~0UL mask that can't
2280 * be encoded in either the swp_entry_t or the architecture definition
2283 unsigned long generic_max_swapfile_size(void)
2285 return swp_offset(pte_to_swp_entry(
2286 swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2289 /* Can be overridden by an architecture for additional checks. */
2290 __weak unsigned long max_swapfile_size(void)
2292 return generic_max_swapfile_size();
2295 static unsigned long read_swap_header(struct swap_info_struct *p,
2296 union swap_header *swap_header,
2297 struct inode *inode)
2300 unsigned long maxpages;
2301 unsigned long swapfilepages;
2302 unsigned long last_page;
2304 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
2305 pr_err("Unable to find swap-space signature\n");
2309 /* swap partition endianess hack... */
2310 if (swab32(swap_header->info.version) == 1) {
2311 swab32s(&swap_header->info.version);
2312 swab32s(&swap_header->info.last_page);
2313 swab32s(&swap_header->info.nr_badpages);
2314 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2316 for (i = 0; i < swap_header->info.nr_badpages; i++)
2317 swab32s(&swap_header->info.badpages[i]);
2319 /* Check the swap header's sub-version */
2320 if (swap_header->info.version != 1) {
2321 pr_warn("Unable to handle swap header version %d\n",
2322 swap_header->info.version);
2327 p->cluster_next = 1;
2330 maxpages = max_swapfile_size();
2331 last_page = swap_header->info.last_page;
2333 pr_warn("Empty swap-file\n");
2336 if (last_page > maxpages) {
2337 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
2338 maxpages << (PAGE_SHIFT - 10),
2339 last_page << (PAGE_SHIFT - 10));
2341 if (maxpages > last_page) {
2342 maxpages = last_page + 1;
2343 /* p->max is an unsigned int: don't overflow it */
2344 if ((unsigned int)maxpages == 0)
2345 maxpages = UINT_MAX;
2347 p->highest_bit = maxpages - 1;
2351 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
2352 if (swapfilepages && maxpages > swapfilepages) {
2353 pr_warn("Swap area shorter than signature indicates\n");
2356 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
2358 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2364 static int setup_swap_map_and_extents(struct swap_info_struct *p,
2365 union swap_header *swap_header,
2366 unsigned char *swap_map,
2367 struct swap_cluster_info *cluster_info,
2368 unsigned long maxpages,
2372 unsigned int nr_good_pages;
2374 unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2375 unsigned long idx = p->cluster_next / SWAPFILE_CLUSTER;
2377 nr_good_pages = maxpages - 1; /* omit header page */
2379 cluster_set_null(&p->free_cluster_head);
2380 cluster_set_null(&p->free_cluster_tail);
2381 cluster_set_null(&p->discard_cluster_head);
2382 cluster_set_null(&p->discard_cluster_tail);
2384 for (i = 0; i < swap_header->info.nr_badpages; i++) {
2385 unsigned int page_nr = swap_header->info.badpages[i];
2386 if (page_nr == 0 || page_nr > swap_header->info.last_page)
2388 if (page_nr < maxpages) {
2389 swap_map[page_nr] = SWAP_MAP_BAD;
2392 * Haven't marked the cluster free yet, no list
2393 * operation involved
2395 inc_cluster_info_page(p, cluster_info, page_nr);
2399 /* Haven't marked the cluster free yet, no list operation involved */
2400 for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
2401 inc_cluster_info_page(p, cluster_info, i);
2403 if (nr_good_pages) {
2404 swap_map[0] = SWAP_MAP_BAD;
2406 * Not mark the cluster free yet, no list
2407 * operation involved
2409 inc_cluster_info_page(p, cluster_info, 0);
2411 p->pages = nr_good_pages;
2412 nr_extents = setup_swap_extents(p, span);
2415 nr_good_pages = p->pages;
2417 if (!nr_good_pages) {
2418 pr_warn("Empty swap-file\n");
2425 for (i = 0; i < nr_clusters; i++) {
2426 if (!cluster_count(&cluster_info[idx])) {
2427 cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
2428 if (cluster_is_null(&p->free_cluster_head)) {
2429 cluster_set_next_flag(&p->free_cluster_head,
2431 cluster_set_next_flag(&p->free_cluster_tail,
2436 tail = cluster_next(&p->free_cluster_tail);
2437 cluster_set_next(&cluster_info[tail], idx);
2438 cluster_set_next_flag(&p->free_cluster_tail,
2443 if (idx == nr_clusters)
2450 * Helper to sys_swapon determining if a given swap
2451 * backing device queue supports DISCARD operations.
2453 static bool swap_discardable(struct swap_info_struct *si)
2455 struct request_queue *q = bdev_get_queue(si->bdev);
2457 if (!q || !blk_queue_discard(q))
2463 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
2465 struct swap_info_struct *p;
2466 struct filename *name;
2467 struct file *swap_file = NULL;
2468 struct address_space *mapping;
2471 union swap_header *swap_header;
2474 unsigned long maxpages;
2475 unsigned char *swap_map = NULL;
2476 struct swap_cluster_info *cluster_info = NULL;
2477 unsigned long *frontswap_map = NULL;
2478 struct page *page = NULL;
2479 struct inode *inode = NULL;
2481 if (swap_flags & ~SWAP_FLAGS_VALID)
2484 if (!capable(CAP_SYS_ADMIN))
2487 p = alloc_swap_info();
2491 INIT_WORK(&p->discard_work, swap_discard_work);
2493 name = getname(specialfile);
2495 error = PTR_ERR(name);
2499 swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
2500 if (IS_ERR(swap_file)) {
2501 error = PTR_ERR(swap_file);
2506 p->swap_file = swap_file;
2507 mapping = swap_file->f_mapping;
2508 inode = mapping->host;
2510 /* If S_ISREG(inode->i_mode) will do mutex_lock(&inode->i_mutex); */
2511 error = claim_swapfile(p, inode);
2512 if (unlikely(error))
2516 * Read the swap header.
2518 if (!mapping->a_ops->readpage) {
2522 page = read_mapping_page(mapping, 0, swap_file);
2524 error = PTR_ERR(page);
2527 swap_header = kmap(page);
2529 maxpages = read_swap_header(p, swap_header, inode);
2530 if (unlikely(!maxpages)) {
2535 /* OK, set up the swap map and apply the bad block list */
2536 swap_map = vzalloc(maxpages);
2542 if (bdi_cap_stable_pages_required(inode_to_bdi(inode)))
2543 p->flags |= SWP_STABLE_WRITES;
2545 if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
2548 p->flags |= SWP_SOLIDSTATE;
2550 * select a random position to start with to help wear leveling
2553 p->cluster_next = 1 + (prandom_u32() % p->highest_bit);
2555 cluster_info = vzalloc(DIV_ROUND_UP(maxpages,
2556 SWAPFILE_CLUSTER) * sizeof(*cluster_info));
2557 if (!cluster_info) {
2561 p->percpu_cluster = alloc_percpu(struct percpu_cluster);
2562 if (!p->percpu_cluster) {
2566 for_each_possible_cpu(cpu) {
2567 struct percpu_cluster *cluster;
2568 cluster = per_cpu_ptr(p->percpu_cluster, cpu);
2569 cluster_set_null(&cluster->index);
2573 error = swap_cgroup_swapon(p->type, maxpages);
2577 nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
2578 cluster_info, maxpages, &span);
2579 if (unlikely(nr_extents < 0)) {
2583 /* frontswap enabled? set up bit-per-page map for frontswap */
2584 if (frontswap_enabled)
2585 frontswap_map = vzalloc(BITS_TO_LONGS(maxpages) * sizeof(long));
2587 if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
2589 * When discard is enabled for swap with no particular
2590 * policy flagged, we set all swap discard flags here in
2591 * order to sustain backward compatibility with older
2592 * swapon(8) releases.
2594 p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
2598 * By flagging sys_swapon, a sysadmin can tell us to
2599 * either do single-time area discards only, or to just
2600 * perform discards for released swap page-clusters.
2601 * Now it's time to adjust the p->flags accordingly.
2603 if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
2604 p->flags &= ~SWP_PAGE_DISCARD;
2605 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
2606 p->flags &= ~SWP_AREA_DISCARD;
2608 /* issue a swapon-time discard if it's still required */
2609 if (p->flags & SWP_AREA_DISCARD) {
2610 int err = discard_swap(p);
2612 pr_err("swapon: discard_swap(%p): %d\n",
2617 if (p->bdev && blk_queue_fast(bdev_get_queue(p->bdev)))
2618 p->flags |= SWP_FAST;
2620 mutex_lock(&swapon_mutex);
2622 if (swap_flags & SWAP_FLAG_PREFER) {
2624 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
2625 setup_swap_ratio(p, prio);
2627 enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
2629 pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
2630 p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
2631 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
2632 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
2633 (p->flags & SWP_DISCARDABLE) ? "D" : "",
2634 (p->flags & SWP_AREA_DISCARD) ? "s" : "",
2635 (p->flags & SWP_PAGE_DISCARD) ? "c" : "",
2636 (frontswap_map) ? "FS" : "");
2638 mutex_unlock(&swapon_mutex);
2639 atomic_inc(&proc_poll_event);
2640 wake_up_interruptible(&proc_poll_wait);
2642 if (S_ISREG(inode->i_mode))
2643 inode->i_flags |= S_SWAPFILE;
2647 free_percpu(p->percpu_cluster);
2648 p->percpu_cluster = NULL;
2649 if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
2650 set_blocksize(p->bdev, p->old_block_size);
2651 blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2653 destroy_swap_extents(p);
2654 swap_cgroup_swapoff(p->type);
2655 spin_lock(&swap_lock);
2656 p->swap_file = NULL;
2658 spin_unlock(&swap_lock);
2660 vfree(cluster_info);
2662 if (inode && S_ISREG(inode->i_mode)) {
2663 mutex_unlock(&inode->i_mutex);
2666 filp_close(swap_file, NULL);
2669 if (page && !IS_ERR(page)) {
2671 page_cache_release(page);
2675 if (inode && S_ISREG(inode->i_mode))
2676 mutex_unlock(&inode->i_mutex);
2680 void si_swapinfo(struct sysinfo *val)
2683 unsigned long nr_to_be_unused = 0;
2685 spin_lock(&swap_lock);
2686 for (type = 0; type < nr_swapfiles; type++) {
2687 struct swap_info_struct *si = swap_info[type];
2689 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
2690 nr_to_be_unused += si->inuse_pages;
2692 val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
2693 val->totalswap = total_swap_pages + nr_to_be_unused;
2694 spin_unlock(&swap_lock);
2698 * Verify that a swap entry is valid and increment its swap map count.
2700 * Returns error code in following case.
2702 * - swp_entry is invalid -> EINVAL
2703 * - swp_entry is migration entry -> EINVAL
2704 * - swap-cache reference is requested but there is already one. -> EEXIST
2705 * - swap-cache reference is requested but the entry is not used. -> ENOENT
2706 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
2708 static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
2710 struct swap_info_struct *p;
2711 unsigned long offset, type;
2712 unsigned char count;
2713 unsigned char has_cache;
2716 if (non_swap_entry(entry))
2719 type = swp_type(entry);
2720 if (type >= nr_swapfiles)
2722 p = swap_info[type];
2723 offset = swp_offset(entry);
2725 spin_lock(&p->lock);
2726 if (unlikely(offset >= p->max))
2729 count = p->swap_map[offset];
2732 * swapin_readahead() doesn't check if a swap entry is valid, so the
2733 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
2735 if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
2740 has_cache = count & SWAP_HAS_CACHE;
2741 count &= ~SWAP_HAS_CACHE;
2744 if (usage == SWAP_HAS_CACHE) {
2746 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
2747 if (!has_cache && count)
2748 has_cache = SWAP_HAS_CACHE;
2749 else if (has_cache) /* someone else added cache */
2751 else /* no users remaining */
2754 } else if (count || has_cache) {
2756 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
2758 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
2760 else if (swap_count_continued(p, offset, count))
2761 count = COUNT_CONTINUED;
2765 err = -ENOENT; /* unused swap entry */
2767 p->swap_map[offset] = count | has_cache;
2770 spin_unlock(&p->lock);
2775 pr_err("swap_dup: %s%08lx\n", Bad_file, entry.val);
2780 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
2781 * (in which case its reference count is never incremented).
2783 void swap_shmem_alloc(swp_entry_t entry)
2785 __swap_duplicate(entry, SWAP_MAP_SHMEM);
2789 * Increase reference count of swap entry by 1.
2790 * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
2791 * but could not be atomically allocated. Returns 0, just as if it succeeded,
2792 * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
2793 * might occur if a page table entry has got corrupted.
2795 int swap_duplicate(swp_entry_t entry)
2799 while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
2800 err = add_swap_count_continuation(entry, GFP_ATOMIC);
2805 * @entry: swap entry for which we allocate swap cache.
2807 * Called when allocating swap cache for existing swap entry,
2808 * This can return error codes. Returns 0 at success.
2809 * -EBUSY means there is a swap cache.
2810 * Note: return code is different from swap_duplicate().
2812 int swapcache_prepare(swp_entry_t entry)
2814 return __swap_duplicate(entry, SWAP_HAS_CACHE);
2817 struct swap_info_struct *page_swap_info(struct page *page)
2819 swp_entry_t swap = { .val = page_private(page) };
2820 BUG_ON(!PageSwapCache(page));
2821 return swap_info[swp_type(swap)];
2825 * out-of-line __page_file_ methods to avoid include hell.
2827 struct address_space *__page_file_mapping(struct page *page)
2829 VM_BUG_ON_PAGE(!PageSwapCache(page), page);
2830 return page_swap_info(page)->swap_file->f_mapping;
2832 EXPORT_SYMBOL_GPL(__page_file_mapping);
2834 pgoff_t __page_file_index(struct page *page)
2836 swp_entry_t swap = { .val = page_private(page) };
2837 VM_BUG_ON_PAGE(!PageSwapCache(page), page);
2838 return swp_offset(swap);
2840 EXPORT_SYMBOL_GPL(__page_file_index);
2843 * add_swap_count_continuation - called when a swap count is duplicated
2844 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
2845 * page of the original vmalloc'ed swap_map, to hold the continuation count
2846 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
2847 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
2849 * These continuation pages are seldom referenced: the common paths all work
2850 * on the original swap_map, only referring to a continuation page when the
2851 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
2853 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
2854 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
2855 * can be called after dropping locks.
2857 int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
2859 struct swap_info_struct *si;
2862 struct page *list_page;
2864 unsigned char count;
2867 * When debugging, it's easier to use __GFP_ZERO here; but it's better
2868 * for latency not to zero a page while GFP_ATOMIC and holding locks.
2870 page = alloc_page(gfp_mask | __GFP_HIGHMEM);
2872 si = swap_info_get(entry);
2875 * An acceptable race has occurred since the failing
2876 * __swap_duplicate(): the swap entry has been freed,
2877 * perhaps even the whole swap_map cleared for swapoff.
2882 offset = swp_offset(entry);
2883 count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
2885 if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
2887 * The higher the swap count, the more likely it is that tasks
2888 * will race to add swap count continuation: we need to avoid
2889 * over-provisioning.
2895 spin_unlock(&si->lock);
2900 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
2901 * no architecture is using highmem pages for kernel page tables: so it
2902 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
2904 head = vmalloc_to_page(si->swap_map + offset);
2905 offset &= ~PAGE_MASK;
2908 * Page allocation does not initialize the page's lru field,
2909 * but it does always reset its private field.
2911 if (!page_private(head)) {
2912 BUG_ON(count & COUNT_CONTINUED);
2913 INIT_LIST_HEAD(&head->lru);
2914 set_page_private(head, SWP_CONTINUED);
2915 si->flags |= SWP_CONTINUED;
2918 list_for_each_entry(list_page, &head->lru, lru) {
2922 * If the previous map said no continuation, but we've found
2923 * a continuation page, free our allocation and use this one.
2925 if (!(count & COUNT_CONTINUED))
2928 map = kmap_atomic(list_page) + offset;
2933 * If this continuation count now has some space in it,
2934 * free our allocation and use this one.
2936 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
2940 list_add_tail(&page->lru, &head->lru);
2941 page = NULL; /* now it's attached, don't free it */
2943 spin_unlock(&si->lock);
2951 * swap_count_continued - when the original swap_map count is incremented
2952 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
2953 * into, carry if so, or else fail until a new continuation page is allocated;
2954 * when the original swap_map count is decremented from 0 with continuation,
2955 * borrow from the continuation and report whether it still holds more.
2956 * Called while __swap_duplicate() or swap_entry_free() holds swap_lock.
2958 static bool swap_count_continued(struct swap_info_struct *si,
2959 pgoff_t offset, unsigned char count)
2965 head = vmalloc_to_page(si->swap_map + offset);
2966 if (page_private(head) != SWP_CONTINUED) {
2967 BUG_ON(count & COUNT_CONTINUED);
2968 return false; /* need to add count continuation */
2971 offset &= ~PAGE_MASK;
2972 page = list_entry(head->lru.next, struct page, lru);
2973 map = kmap_atomic(page) + offset;
2975 if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
2976 goto init_map; /* jump over SWAP_CONT_MAX checks */
2978 if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
2980 * Think of how you add 1 to 999
2982 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
2984 page = list_entry(page->lru.next, struct page, lru);
2985 BUG_ON(page == head);
2986 map = kmap_atomic(page) + offset;
2988 if (*map == SWAP_CONT_MAX) {
2990 page = list_entry(page->lru.next, struct page, lru);
2992 return false; /* add count continuation */
2993 map = kmap_atomic(page) + offset;
2994 init_map: *map = 0; /* we didn't zero the page */
2998 page = list_entry(page->lru.prev, struct page, lru);
2999 while (page != head) {
3000 map = kmap_atomic(page) + offset;
3001 *map = COUNT_CONTINUED;
3003 page = list_entry(page->lru.prev, struct page, lru);
3005 return true; /* incremented */
3007 } else { /* decrementing */
3009 * Think of how you subtract 1 from 1000
3011 BUG_ON(count != COUNT_CONTINUED);
3012 while (*map == COUNT_CONTINUED) {
3014 page = list_entry(page->lru.next, struct page, lru);
3015 BUG_ON(page == head);
3016 map = kmap_atomic(page) + offset;
3023 page = list_entry(page->lru.prev, struct page, lru);
3024 while (page != head) {
3025 map = kmap_atomic(page) + offset;
3026 *map = SWAP_CONT_MAX | count;
3027 count = COUNT_CONTINUED;
3029 page = list_entry(page->lru.prev, struct page, lru);
3031 return count == COUNT_CONTINUED;
3036 * free_swap_count_continuations - swapoff free all the continuation pages
3037 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3039 static void free_swap_count_continuations(struct swap_info_struct *si)
3043 for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3045 head = vmalloc_to_page(si->swap_map + offset);
3046 if (page_private(head)) {
3047 struct list_head *this, *next;
3048 list_for_each_safe(this, next, &head->lru) {
3050 page = list_entry(this, struct page, lru);