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/page_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 #if !defined(__e2k__) || !defined(CONFIG_RECOVERY)
52 unsigned int nr_swapfiles
;
53 atomic_long_t nr_swap_pages
;
54 /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
55 long total_swap_pages
;
56 static int least_priority
;
58 static const char Bad_file
[] = "Bad swap file entry ";
59 static const char Unused_file
[] = "Unused swap file entry ";
60 static const char Bad_offset
[] = "Bad swap offset entry ";
61 static const char Unused_offset
[] = "Unused swap offset entry ";
64 * all active swap_info_structs
65 * protected with swap_lock, and ordered by priority.
67 PLIST_HEAD(swap_active_head
);
70 * all available (active, not full) swap_info_structs
71 * protected with swap_avail_lock, ordered by priority.
72 * This is used by get_swap_page() instead of swap_active_head
73 * because swap_active_head includes all swap_info_structs,
74 * but get_swap_page() doesn't need to look at full ones.
75 * This uses its own lock instead of swap_lock because when a
76 * swap_info_struct changes between not-full/full, it needs to
77 * add/remove itself to/from this list, but the swap_info_struct->lock
78 * is held and the locking order requires swap_lock to be taken
79 * before any swap_info_struct->lock.
81 static PLIST_HEAD(swap_avail_head
);
82 static DEFINE_SPINLOCK(swap_avail_lock
);
84 struct swap_info_struct
*swap_info
[MAX_SWAPFILES
];
86 static DEFINE_MUTEX(swapon_mutex
);
88 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait
);
89 /* Activity counter to indicate that a swapon or swapoff has occurred */
90 static atomic_t proc_poll_event
= ATOMIC_INIT(0);
92 static inline unsigned char swap_count(unsigned char ent
)
94 return ent
& ~SWAP_HAS_CACHE
; /* may include SWAP_HAS_CONT flag */
97 /* returns 1 if swap entry is freed */
99 __try_to_reclaim_swap(struct swap_info_struct
*si
, unsigned long offset
)
101 swp_entry_t entry
= swp_entry(si
->type
, offset
);
105 page
= find_get_page(swap_address_space(entry
), entry
.val
);
109 * This function is called from scan_swap_map() and it's called
110 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
111 * We have to use trylock for avoiding deadlock. This is a special
112 * case and you should use try_to_free_swap() with explicit lock_page()
113 * in usual operations.
115 if (trylock_page(page
)) {
116 ret
= try_to_free_swap(page
);
119 page_cache_release(page
);
124 * swapon tell device that all the old swap contents can be discarded,
125 * to allow the swap device to optimize its wear-levelling.
127 static int discard_swap(struct swap_info_struct
*si
)
129 struct swap_extent
*se
;
130 sector_t start_block
;
134 /* Do not discard the swap header page! */
135 se
= &si
->first_swap_extent
;
136 start_block
= (se
->start_block
+ 1) << (PAGE_SHIFT
- 9);
137 nr_blocks
= ((sector_t
)se
->nr_pages
- 1) << (PAGE_SHIFT
- 9);
139 err
= blkdev_issue_discard(si
->bdev
, start_block
,
140 nr_blocks
, GFP_KERNEL
, 0);
146 list_for_each_entry(se
, &si
->first_swap_extent
.list
, list
) {
147 start_block
= se
->start_block
<< (PAGE_SHIFT
- 9);
148 nr_blocks
= (sector_t
)se
->nr_pages
<< (PAGE_SHIFT
- 9);
150 err
= blkdev_issue_discard(si
->bdev
, start_block
,
151 nr_blocks
, GFP_KERNEL
, 0);
157 return err
; /* That will often be -EOPNOTSUPP */
161 * swap allocation tell device that a cluster of swap can now be discarded,
162 * to allow the swap device to optimize its wear-levelling.
164 static void discard_swap_cluster(struct swap_info_struct
*si
,
165 pgoff_t start_page
, pgoff_t nr_pages
)
167 struct swap_extent
*se
= si
->curr_swap_extent
;
168 int found_extent
= 0;
171 struct list_head
*lh
;
173 if (se
->start_page
<= start_page
&&
174 start_page
< se
->start_page
+ se
->nr_pages
) {
175 pgoff_t offset
= start_page
- se
->start_page
;
176 sector_t start_block
= se
->start_block
+ offset
;
177 sector_t nr_blocks
= se
->nr_pages
- offset
;
179 if (nr_blocks
> nr_pages
)
180 nr_blocks
= nr_pages
;
181 start_page
+= nr_blocks
;
182 nr_pages
-= nr_blocks
;
185 si
->curr_swap_extent
= se
;
187 start_block
<<= PAGE_SHIFT
- 9;
188 nr_blocks
<<= PAGE_SHIFT
- 9;
189 if (blkdev_issue_discard(si
->bdev
, start_block
,
190 nr_blocks
, GFP_NOIO
, 0))
195 se
= list_entry(lh
, struct swap_extent
, list
);
199 #define SWAPFILE_CLUSTER 256
200 #define LATENCY_LIMIT 256
202 static inline void cluster_set_flag(struct swap_cluster_info
*info
,
208 static inline unsigned int cluster_count(struct swap_cluster_info
*info
)
213 static inline void cluster_set_count(struct swap_cluster_info
*info
,
219 static inline void cluster_set_count_flag(struct swap_cluster_info
*info
,
220 unsigned int c
, unsigned int f
)
226 static inline unsigned int cluster_next(struct swap_cluster_info
*info
)
231 static inline void cluster_set_next(struct swap_cluster_info
*info
,
237 static inline void cluster_set_next_flag(struct swap_cluster_info
*info
,
238 unsigned int n
, unsigned int f
)
244 static inline bool cluster_is_free(struct swap_cluster_info
*info
)
246 return info
->flags
& CLUSTER_FLAG_FREE
;
249 static inline bool cluster_is_null(struct swap_cluster_info
*info
)
251 return info
->flags
& CLUSTER_FLAG_NEXT_NULL
;
254 static inline void cluster_set_null(struct swap_cluster_info
*info
)
256 info
->flags
= CLUSTER_FLAG_NEXT_NULL
;
260 /* Add a cluster to discard list and schedule it to do discard */
261 static void swap_cluster_schedule_discard(struct swap_info_struct
*si
,
265 * If scan_swap_map() can't find a free cluster, it will check
266 * si->swap_map directly. To make sure the discarding cluster isn't
267 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
268 * will be cleared after discard
270 memset(si
->swap_map
+ idx
* SWAPFILE_CLUSTER
,
271 SWAP_MAP_BAD
, SWAPFILE_CLUSTER
);
273 if (cluster_is_null(&si
->discard_cluster_head
)) {
274 cluster_set_next_flag(&si
->discard_cluster_head
,
276 cluster_set_next_flag(&si
->discard_cluster_tail
,
279 unsigned int tail
= cluster_next(&si
->discard_cluster_tail
);
280 cluster_set_next(&si
->cluster_info
[tail
], idx
);
281 cluster_set_next_flag(&si
->discard_cluster_tail
,
285 schedule_work(&si
->discard_work
);
289 * Doing discard actually. After a cluster discard is finished, the cluster
290 * will be added to free cluster list. caller should hold si->lock.
292 static void swap_do_scheduled_discard(struct swap_info_struct
*si
)
294 struct swap_cluster_info
*info
;
297 info
= si
->cluster_info
;
299 while (!cluster_is_null(&si
->discard_cluster_head
)) {
300 idx
= cluster_next(&si
->discard_cluster_head
);
302 cluster_set_next_flag(&si
->discard_cluster_head
,
303 cluster_next(&info
[idx
]), 0);
304 if (cluster_next(&si
->discard_cluster_tail
) == idx
) {
305 cluster_set_null(&si
->discard_cluster_head
);
306 cluster_set_null(&si
->discard_cluster_tail
);
308 spin_unlock(&si
->lock
);
310 discard_swap_cluster(si
, idx
* SWAPFILE_CLUSTER
,
313 spin_lock(&si
->lock
);
314 cluster_set_flag(&info
[idx
], CLUSTER_FLAG_FREE
);
315 if (cluster_is_null(&si
->free_cluster_head
)) {
316 cluster_set_next_flag(&si
->free_cluster_head
,
318 cluster_set_next_flag(&si
->free_cluster_tail
,
323 tail
= cluster_next(&si
->free_cluster_tail
);
324 cluster_set_next(&info
[tail
], idx
);
325 cluster_set_next_flag(&si
->free_cluster_tail
,
328 memset(si
->swap_map
+ idx
* SWAPFILE_CLUSTER
,
329 0, SWAPFILE_CLUSTER
);
333 static void swap_discard_work(struct work_struct
*work
)
335 struct swap_info_struct
*si
;
337 si
= container_of(work
, struct swap_info_struct
, discard_work
);
339 spin_lock(&si
->lock
);
340 swap_do_scheduled_discard(si
);
341 spin_unlock(&si
->lock
);
345 * The cluster corresponding to page_nr will be used. The cluster will be
346 * removed from free cluster list and its usage counter will be increased.
348 static void inc_cluster_info_page(struct swap_info_struct
*p
,
349 struct swap_cluster_info
*cluster_info
, unsigned long page_nr
)
351 unsigned long idx
= page_nr
/ SWAPFILE_CLUSTER
;
355 if (cluster_is_free(&cluster_info
[idx
])) {
356 VM_BUG_ON(cluster_next(&p
->free_cluster_head
) != idx
);
357 cluster_set_next_flag(&p
->free_cluster_head
,
358 cluster_next(&cluster_info
[idx
]), 0);
359 if (cluster_next(&p
->free_cluster_tail
) == idx
) {
360 cluster_set_null(&p
->free_cluster_tail
);
361 cluster_set_null(&p
->free_cluster_head
);
363 cluster_set_count_flag(&cluster_info
[idx
], 0, 0);
366 VM_BUG_ON(cluster_count(&cluster_info
[idx
]) >= SWAPFILE_CLUSTER
);
367 cluster_set_count(&cluster_info
[idx
],
368 cluster_count(&cluster_info
[idx
]) + 1);
372 * The cluster corresponding to page_nr decreases one usage. If the usage
373 * counter becomes 0, which means no page in the cluster is in using, we can
374 * optionally discard the cluster and add it to free cluster list.
376 static void dec_cluster_info_page(struct swap_info_struct
*p
,
377 struct swap_cluster_info
*cluster_info
, unsigned long page_nr
)
379 unsigned long idx
= page_nr
/ SWAPFILE_CLUSTER
;
384 VM_BUG_ON(cluster_count(&cluster_info
[idx
]) == 0);
385 cluster_set_count(&cluster_info
[idx
],
386 cluster_count(&cluster_info
[idx
]) - 1);
388 if (cluster_count(&cluster_info
[idx
]) == 0) {
390 * If the swap is discardable, prepare discard the cluster
391 * instead of free it immediately. The cluster will be freed
394 if ((p
->flags
& (SWP_WRITEOK
| SWP_PAGE_DISCARD
)) ==
395 (SWP_WRITEOK
| SWP_PAGE_DISCARD
)) {
396 swap_cluster_schedule_discard(p
, idx
);
400 cluster_set_flag(&cluster_info
[idx
], CLUSTER_FLAG_FREE
);
401 if (cluster_is_null(&p
->free_cluster_head
)) {
402 cluster_set_next_flag(&p
->free_cluster_head
, idx
, 0);
403 cluster_set_next_flag(&p
->free_cluster_tail
, idx
, 0);
405 unsigned int tail
= cluster_next(&p
->free_cluster_tail
);
406 cluster_set_next(&cluster_info
[tail
], idx
);
407 cluster_set_next_flag(&p
->free_cluster_tail
, idx
, 0);
413 * It's possible scan_swap_map() uses a free cluster in the middle of free
414 * cluster list. Avoiding such abuse to avoid list corruption.
417 scan_swap_map_ssd_cluster_conflict(struct swap_info_struct
*si
,
418 unsigned long offset
)
420 struct percpu_cluster
*percpu_cluster
;
423 offset
/= SWAPFILE_CLUSTER
;
424 conflict
= !cluster_is_null(&si
->free_cluster_head
) &&
425 offset
!= cluster_next(&si
->free_cluster_head
) &&
426 cluster_is_free(&si
->cluster_info
[offset
]);
431 percpu_cluster
= this_cpu_ptr(si
->percpu_cluster
);
432 cluster_set_null(&percpu_cluster
->index
);
437 * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
438 * might involve allocating a new cluster for current CPU too.
440 static void scan_swap_map_try_ssd_cluster(struct swap_info_struct
*si
,
441 unsigned long *offset
, unsigned long *scan_base
)
443 struct percpu_cluster
*cluster
;
448 cluster
= this_cpu_ptr(si
->percpu_cluster
);
449 if (cluster_is_null(&cluster
->index
)) {
450 if (!cluster_is_null(&si
->free_cluster_head
)) {
451 cluster
->index
= si
->free_cluster_head
;
452 cluster
->next
= cluster_next(&cluster
->index
) *
454 } else if (!cluster_is_null(&si
->discard_cluster_head
)) {
456 * we don't have free cluster but have some clusters in
457 * discarding, do discard now and reclaim them
459 swap_do_scheduled_discard(si
);
460 *scan_base
= *offset
= si
->cluster_next
;
469 * Other CPUs can use our cluster if they can't find a free cluster,
470 * check if there is still free entry in the cluster
473 while (tmp
< si
->max
&& tmp
< (cluster_next(&cluster
->index
) + 1) *
475 if (!si
->swap_map
[tmp
]) {
482 cluster_set_null(&cluster
->index
);
485 cluster
->next
= tmp
+ 1;
490 static unsigned long scan_swap_map(struct swap_info_struct
*si
,
493 unsigned long offset
;
494 unsigned long scan_base
;
495 unsigned long last_in_cluster
= 0;
496 int latency_ration
= LATENCY_LIMIT
;
499 * We try to cluster swap pages by allocating them sequentially
500 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
501 * way, however, we resort to first-free allocation, starting
502 * a new cluster. This prevents us from scattering swap pages
503 * all over the entire swap partition, so that we reduce
504 * overall disk seek times between swap pages. -- sct
505 * But we do now try to find an empty cluster. -Andrea
506 * And we let swap pages go all over an SSD partition. Hugh
509 si
->flags
+= SWP_SCANNING
;
510 scan_base
= offset
= si
->cluster_next
;
513 if (si
->cluster_info
) {
514 scan_swap_map_try_ssd_cluster(si
, &offset
, &scan_base
);
518 if (unlikely(!si
->cluster_nr
--)) {
519 if (si
->pages
- si
->inuse_pages
< SWAPFILE_CLUSTER
) {
520 si
->cluster_nr
= SWAPFILE_CLUSTER
- 1;
524 spin_unlock(&si
->lock
);
527 * If seek is expensive, start searching for new cluster from
528 * start of partition, to minimize the span of allocated swap.
529 * But if seek is cheap, search from our current position, so
530 * that swap is allocated from all over the partition: if the
531 * Flash Translation Layer only remaps within limited zones,
532 * we don't want to wear out the first zone too quickly.
534 if (!(si
->flags
& SWP_SOLIDSTATE
))
535 scan_base
= offset
= si
->lowest_bit
;
536 last_in_cluster
= offset
+ SWAPFILE_CLUSTER
- 1;
538 /* Locate the first empty (unaligned) cluster */
539 for (; last_in_cluster
<= si
->highest_bit
; offset
++) {
540 if (si
->swap_map
[offset
])
541 last_in_cluster
= offset
+ SWAPFILE_CLUSTER
;
542 else if (offset
== last_in_cluster
) {
543 spin_lock(&si
->lock
);
544 offset
-= SWAPFILE_CLUSTER
- 1;
545 si
->cluster_next
= offset
;
546 si
->cluster_nr
= SWAPFILE_CLUSTER
- 1;
549 if (unlikely(--latency_ration
< 0)) {
551 latency_ration
= LATENCY_LIMIT
;
555 offset
= si
->lowest_bit
;
556 last_in_cluster
= offset
+ SWAPFILE_CLUSTER
- 1;
558 /* Locate the first empty (unaligned) cluster */
559 for (; last_in_cluster
< scan_base
; offset
++) {
560 if (si
->swap_map
[offset
])
561 last_in_cluster
= offset
+ SWAPFILE_CLUSTER
;
562 else if (offset
== last_in_cluster
) {
563 spin_lock(&si
->lock
);
564 offset
-= SWAPFILE_CLUSTER
- 1;
565 si
->cluster_next
= offset
;
566 si
->cluster_nr
= SWAPFILE_CLUSTER
- 1;
569 if (unlikely(--latency_ration
< 0)) {
571 latency_ration
= LATENCY_LIMIT
;
576 spin_lock(&si
->lock
);
577 si
->cluster_nr
= SWAPFILE_CLUSTER
- 1;
581 if (si
->cluster_info
) {
582 while (scan_swap_map_ssd_cluster_conflict(si
, offset
))
583 scan_swap_map_try_ssd_cluster(si
, &offset
, &scan_base
);
585 if (!(si
->flags
& SWP_WRITEOK
))
587 if (!si
->highest_bit
)
589 if (offset
> si
->highest_bit
)
590 scan_base
= offset
= si
->lowest_bit
;
592 /* reuse swap entry of cache-only swap if not busy. */
593 if (vm_swap_full() && si
->swap_map
[offset
] == SWAP_HAS_CACHE
) {
595 spin_unlock(&si
->lock
);
596 swap_was_freed
= __try_to_reclaim_swap(si
, offset
);
597 spin_lock(&si
->lock
);
598 /* entry was freed successfully, try to use this again */
601 goto scan
; /* check next one */
604 if (si
->swap_map
[offset
])
607 if (offset
== si
->lowest_bit
)
609 if (offset
== si
->highest_bit
)
612 if (si
->inuse_pages
== si
->pages
) {
613 si
->lowest_bit
= si
->max
;
615 spin_lock(&swap_avail_lock
);
616 plist_del(&si
->avail_list
, &swap_avail_head
);
617 spin_unlock(&swap_avail_lock
);
619 si
->swap_map
[offset
] = usage
;
620 inc_cluster_info_page(si
, si
->cluster_info
, offset
);
621 si
->cluster_next
= offset
+ 1;
622 si
->flags
-= SWP_SCANNING
;
627 spin_unlock(&si
->lock
);
628 while (++offset
<= si
->highest_bit
) {
629 if (!si
->swap_map
[offset
]) {
630 spin_lock(&si
->lock
);
633 if (vm_swap_full() && si
->swap_map
[offset
] == SWAP_HAS_CACHE
) {
634 spin_lock(&si
->lock
);
637 if (unlikely(--latency_ration
< 0)) {
639 latency_ration
= LATENCY_LIMIT
;
642 offset
= si
->lowest_bit
;
643 while (offset
< scan_base
) {
644 if (!si
->swap_map
[offset
]) {
645 spin_lock(&si
->lock
);
648 if (vm_swap_full() && si
->swap_map
[offset
] == SWAP_HAS_CACHE
) {
649 spin_lock(&si
->lock
);
652 if (unlikely(--latency_ration
< 0)) {
654 latency_ration
= LATENCY_LIMIT
;
658 spin_lock(&si
->lock
);
661 si
->flags
-= SWP_SCANNING
;
665 swp_entry_t
get_swap_page(void)
667 struct swap_info_struct
*si
, *next
;
670 if (atomic_long_read(&nr_swap_pages
) <= 0)
672 atomic_long_dec(&nr_swap_pages
);
674 spin_lock(&swap_avail_lock
);
677 plist_for_each_entry_safe(si
, next
, &swap_avail_head
, avail_list
) {
678 /* requeue si to after same-priority siblings */
679 plist_requeue(&si
->avail_list
, &swap_avail_head
);
680 spin_unlock(&swap_avail_lock
);
681 spin_lock(&si
->lock
);
682 if (!si
->highest_bit
|| !(si
->flags
& SWP_WRITEOK
)) {
683 spin_lock(&swap_avail_lock
);
684 if (plist_node_empty(&si
->avail_list
)) {
685 spin_unlock(&si
->lock
);
688 WARN(!si
->highest_bit
,
689 "swap_info %d in list but !highest_bit\n",
691 WARN(!(si
->flags
& SWP_WRITEOK
),
692 "swap_info %d in list but !SWP_WRITEOK\n",
694 plist_del(&si
->avail_list
, &swap_avail_head
);
695 spin_unlock(&si
->lock
);
699 /* This is called for allocating swap entry for cache */
700 offset
= scan_swap_map(si
, SWAP_HAS_CACHE
);
701 spin_unlock(&si
->lock
);
703 return swp_entry(si
->type
, offset
);
704 pr_debug("scan_swap_map of si %d failed to find offset\n",
706 spin_lock(&swap_avail_lock
);
709 * if we got here, it's likely that si was almost full before,
710 * and since scan_swap_map() can drop the si->lock, multiple
711 * callers probably all tried to get a page from the same si
712 * and it filled up before we could get one; or, the si filled
713 * up between us dropping swap_avail_lock and taking si->lock.
714 * Since we dropped the swap_avail_lock, the swap_avail_head
715 * list may have been modified; so if next is still in the
716 * swap_avail_head list then try it, otherwise start over.
718 if (plist_node_empty(&next
->avail_list
))
722 spin_unlock(&swap_avail_lock
);
724 atomic_long_inc(&nr_swap_pages
);
726 return (swp_entry_t
) {0};
729 /* The only caller of this function is now suspend routine */
730 swp_entry_t
get_swap_page_of_type(int type
)
732 struct swap_info_struct
*si
;
735 si
= swap_info
[type
];
736 spin_lock(&si
->lock
);
737 if (si
&& (si
->flags
& SWP_WRITEOK
)) {
738 atomic_long_dec(&nr_swap_pages
);
739 /* This is called for allocating swap entry, not cache */
740 offset
= scan_swap_map(si
, 1);
742 spin_unlock(&si
->lock
);
743 return swp_entry(type
, offset
);
745 atomic_long_inc(&nr_swap_pages
);
747 spin_unlock(&si
->lock
);
748 return (swp_entry_t
) {0};
751 static struct swap_info_struct
*swap_info_get(swp_entry_t entry
)
753 struct swap_info_struct
*p
;
754 unsigned long offset
, type
;
758 type
= swp_type(entry
);
759 if (type
>= nr_swapfiles
)
762 if (!(p
->flags
& SWP_USED
))
764 offset
= swp_offset(entry
);
765 if (offset
>= p
->max
)
767 if (!p
->swap_map
[offset
])
773 pr_err("swap_free: %s%08lx\n", Unused_offset
, entry
.val
);
776 pr_err("swap_free: %s%08lx\n", Bad_offset
, entry
.val
);
779 pr_err("swap_free: %s%08lx\n", Unused_file
, entry
.val
);
782 pr_err("swap_free: %s%08lx\n", Bad_file
, entry
.val
);
787 static unsigned char swap_entry_free(struct swap_info_struct
*p
,
788 swp_entry_t entry
, unsigned char usage
)
790 unsigned long offset
= swp_offset(entry
);
792 unsigned char has_cache
;
794 count
= p
->swap_map
[offset
];
795 has_cache
= count
& SWAP_HAS_CACHE
;
796 count
&= ~SWAP_HAS_CACHE
;
798 if (usage
== SWAP_HAS_CACHE
) {
799 VM_BUG_ON(!has_cache
);
801 } else if (count
== SWAP_MAP_SHMEM
) {
803 * Or we could insist on shmem.c using a special
804 * swap_shmem_free() and free_shmem_swap_and_cache()...
807 } else if ((count
& ~COUNT_CONTINUED
) <= SWAP_MAP_MAX
) {
808 if (count
== COUNT_CONTINUED
) {
809 if (swap_count_continued(p
, offset
, count
))
810 count
= SWAP_MAP_MAX
| COUNT_CONTINUED
;
812 count
= SWAP_MAP_MAX
;
818 mem_cgroup_uncharge_swap(entry
);
820 usage
= count
| has_cache
;
821 p
->swap_map
[offset
] = usage
;
823 /* free if no reference */
825 dec_cluster_info_page(p
, p
->cluster_info
, offset
);
826 if (offset
< p
->lowest_bit
)
827 p
->lowest_bit
= offset
;
828 if (offset
> p
->highest_bit
) {
829 bool was_full
= !p
->highest_bit
;
830 p
->highest_bit
= offset
;
831 if (was_full
&& (p
->flags
& SWP_WRITEOK
)) {
832 spin_lock(&swap_avail_lock
);
833 WARN_ON(!plist_node_empty(&p
->avail_list
));
834 if (plist_node_empty(&p
->avail_list
))
835 plist_add(&p
->avail_list
,
837 spin_unlock(&swap_avail_lock
);
840 atomic_long_inc(&nr_swap_pages
);
842 frontswap_invalidate_page(p
->type
, offset
);
843 if (p
->flags
& SWP_BLKDEV
) {
844 struct gendisk
*disk
= p
->bdev
->bd_disk
;
845 if (disk
->fops
->swap_slot_free_notify
)
846 disk
->fops
->swap_slot_free_notify(p
->bdev
,
855 * Caller has made sure that the swap device corresponding to entry
856 * is still around or has not been recycled.
858 void swap_free(swp_entry_t entry
)
860 struct swap_info_struct
*p
;
862 p
= swap_info_get(entry
);
864 swap_entry_free(p
, entry
, 1);
865 spin_unlock(&p
->lock
);
870 * Called after dropping swapcache to decrease refcnt to swap entries.
872 void swapcache_free(swp_entry_t entry
, struct page
*page
)
874 struct swap_info_struct
*p
;
877 p
= swap_info_get(entry
);
879 count
= swap_entry_free(p
, entry
, SWAP_HAS_CACHE
);
881 mem_cgroup_uncharge_swapcache(page
, entry
, count
!= 0);
882 spin_unlock(&p
->lock
);
887 * How many references to page are currently swapped out?
888 * This does not give an exact answer when swap count is continued,
889 * but does include the high COUNT_CONTINUED flag to allow for that.
891 int page_swapcount(struct page
*page
)
894 struct swap_info_struct
*p
;
897 entry
.val
= page_private(page
);
898 p
= swap_info_get(entry
);
900 count
= swap_count(p
->swap_map
[swp_offset(entry
)]);
901 spin_unlock(&p
->lock
);
907 * We can write to an anon page without COW if there are no other references
908 * to it. And as a side-effect, free up its swap: because the old content
909 * on disk will never be read, and seeking back there to write new content
910 * later would only waste time away from clustering.
912 int reuse_swap_page(struct page
*page
)
916 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
917 if (unlikely(PageKsm(page
)))
919 count
= page_mapcount(page
);
920 if (count
<= 1 && PageSwapCache(page
)) {
921 count
+= page_swapcount(page
);
922 if (count
== 1 && !PageWriteback(page
)) {
923 delete_from_swap_cache(page
);
931 * If swap is getting full, or if there are no more mappings of this page,
932 * then try_to_free_swap is called to free its swap space.
934 int try_to_free_swap(struct page
*page
)
936 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
938 if (!PageSwapCache(page
))
940 if (PageWriteback(page
))
942 if (page_swapcount(page
))
946 * Once hibernation has begun to create its image of memory,
947 * there's a danger that one of the calls to try_to_free_swap()
948 * - most probably a call from __try_to_reclaim_swap() while
949 * hibernation is allocating its own swap pages for the image,
950 * but conceivably even a call from memory reclaim - will free
951 * the swap from a page which has already been recorded in the
952 * image as a clean swapcache page, and then reuse its swap for
953 * another page of the image. On waking from hibernation, the
954 * original page might be freed under memory pressure, then
955 * later read back in from swap, now with the wrong data.
957 * Hibernation suspends storage while it is writing the image
958 * to disk so check that here.
960 if (pm_suspended_storage())
963 delete_from_swap_cache(page
);
969 * Free the swap entry like above, but also try to
970 * free the page cache entry if it is the last user.
972 int free_swap_and_cache(swp_entry_t entry
)
974 struct swap_info_struct
*p
;
975 struct page
*page
= NULL
;
977 if (non_swap_entry(entry
))
980 p
= swap_info_get(entry
);
982 if (swap_entry_free(p
, entry
, 1) == SWAP_HAS_CACHE
) {
983 page
= find_get_page(swap_address_space(entry
),
985 if (page
&& !trylock_page(page
)) {
986 page_cache_release(page
);
990 spin_unlock(&p
->lock
);
994 * Not mapped elsewhere, or swap space full? Free it!
995 * Also recheck PageSwapCache now page is locked (above).
997 if (PageSwapCache(page
) && !PageWriteback(page
) &&
998 (!page_mapped(page
) || vm_swap_full())) {
999 delete_from_swap_cache(page
);
1003 page_cache_release(page
);
1008 #ifdef CONFIG_HIBERNATION
1010 * Find the swap type that corresponds to given device (if any).
1012 * @offset - number of the PAGE_SIZE-sized block of the device, starting
1013 * from 0, in which the swap header is expected to be located.
1015 * This is needed for the suspend to disk (aka swsusp).
1017 int swap_type_of(dev_t device
, sector_t offset
, struct block_device
**bdev_p
)
1019 struct block_device
*bdev
= NULL
;
1023 bdev
= bdget(device
);
1025 spin_lock(&swap_lock
);
1026 for (type
= 0; type
< nr_swapfiles
; type
++) {
1027 struct swap_info_struct
*sis
= swap_info
[type
];
1029 if (!(sis
->flags
& SWP_WRITEOK
))
1034 *bdev_p
= bdgrab(sis
->bdev
);
1036 spin_unlock(&swap_lock
);
1039 if (bdev
== sis
->bdev
) {
1040 struct swap_extent
*se
= &sis
->first_swap_extent
;
1042 if (se
->start_block
== offset
) {
1044 *bdev_p
= bdgrab(sis
->bdev
);
1046 spin_unlock(&swap_lock
);
1052 spin_unlock(&swap_lock
);
1060 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1061 * corresponding to given index in swap_info (swap type).
1063 sector_t
swapdev_block(int type
, pgoff_t offset
)
1065 struct block_device
*bdev
;
1067 if ((unsigned int)type
>= nr_swapfiles
)
1069 if (!(swap_info
[type
]->flags
& SWP_WRITEOK
))
1071 return map_swap_entry(swp_entry(type
, offset
), &bdev
);
1075 * Return either the total number of swap pages of given type, or the number
1076 * of free pages of that type (depending on @free)
1078 * This is needed for software suspend
1080 unsigned int count_swap_pages(int type
, int free
)
1084 spin_lock(&swap_lock
);
1085 if ((unsigned int)type
< nr_swapfiles
) {
1086 struct swap_info_struct
*sis
= swap_info
[type
];
1088 spin_lock(&sis
->lock
);
1089 if (sis
->flags
& SWP_WRITEOK
) {
1092 n
-= sis
->inuse_pages
;
1094 spin_unlock(&sis
->lock
);
1096 spin_unlock(&swap_lock
);
1099 #endif /* CONFIG_HIBERNATION */
1101 static inline int maybe_same_pte(pte_t pte
, pte_t swp_pte
)
1103 #ifdef CONFIG_MEM_SOFT_DIRTY
1105 * When pte keeps soft dirty bit the pte generated
1106 * from swap entry does not has it, still it's same
1107 * pte from logical point of view.
1109 pte_t swp_pte_dirty
= pte_swp_mksoft_dirty(swp_pte
);
1110 return pte_same(pte
, swp_pte
) || pte_same(pte
, swp_pte_dirty
);
1112 return pte_same(pte
, swp_pte
);
1117 * No need to decide whether this PTE shares the swap entry with others,
1118 * just let do_wp_page work it out if a write is requested later - to
1119 * force COW, vm_page_prot omits write permission from any private vma.
1121 static int unuse_pte(struct vm_area_struct
*vma
, pmd_t
*pmd
,
1122 unsigned long addr
, swp_entry_t entry
, struct page
*page
)
1124 struct page
*swapcache
;
1125 struct mem_cgroup
*memcg
;
1131 page
= ksm_might_need_to_copy(page
, vma
, addr
);
1132 if (unlikely(!page
))
1135 if (mem_cgroup_try_charge_swapin(vma
->vm_mm
, page
,
1136 GFP_KERNEL
, &memcg
)) {
1141 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
1142 if (unlikely(!maybe_same_pte(*pte
, swp_entry_to_pte(entry
)))) {
1143 mem_cgroup_cancel_charge_swapin(memcg
);
1148 dec_mm_counter(vma
->vm_mm
, MM_SWAPENTS
);
1149 inc_mm_counter(vma
->vm_mm
, MM_ANONPAGES
);
1151 set_pte_at(vma
->vm_mm
, addr
, pte
,
1152 pte_mkold(mk_pte(page
, vma
->vm_page_prot
)));
1153 if (page
== swapcache
)
1154 page_add_anon_rmap(page
, vma
, addr
);
1155 else /* ksm created a completely new copy */
1156 page_add_new_anon_rmap(page
, vma
, addr
);
1157 mem_cgroup_commit_charge_swapin(page
, memcg
);
1160 * Move the page to the active list so it is not
1161 * immediately swapped out again after swapon.
1163 activate_page(page
);
1165 pte_unmap_unlock(pte
, ptl
);
1167 if (page
!= swapcache
) {
1174 static int unuse_pte_range(struct vm_area_struct
*vma
, pmd_t
*pmd
,
1175 unsigned long addr
, unsigned long end
,
1176 swp_entry_t entry
, struct page
*page
)
1178 pte_t swp_pte
= swp_entry_to_pte(entry
);
1183 * We don't actually need pte lock while scanning for swp_pte: since
1184 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
1185 * page table while we're scanning; though it could get zapped, and on
1186 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
1187 * of unmatched parts which look like swp_pte, so unuse_pte must
1188 * recheck under pte lock. Scanning without pte lock lets it be
1189 * preemptable whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
1191 pte
= pte_offset_map(pmd
, addr
);
1194 * swapoff spends a _lot_ of time in this loop!
1195 * Test inline before going to call unuse_pte.
1197 if (unlikely(maybe_same_pte(*pte
, swp_pte
))) {
1199 ret
= unuse_pte(vma
, pmd
, addr
, entry
, page
);
1202 pte
= pte_offset_map(pmd
, addr
);
1204 } while (pte
++, addr
+= PAGE_SIZE
, addr
!= end
);
1210 static inline int unuse_pmd_range(struct vm_area_struct
*vma
, pud_t
*pud
,
1211 unsigned long addr
, unsigned long end
,
1212 swp_entry_t entry
, struct page
*page
)
1218 pmd
= pmd_offset(pud
, addr
);
1220 next
= pmd_addr_end(addr
, end
);
1221 if (pmd_none_or_trans_huge_or_clear_bad(pmd
))
1223 ret
= unuse_pte_range(vma
, pmd
, addr
, next
, entry
, page
);
1226 } while (pmd
++, addr
= next
, addr
!= end
);
1230 static inline int unuse_pud_range(struct vm_area_struct
*vma
, pgd_t
*pgd
,
1231 unsigned long addr
, unsigned long end
,
1232 swp_entry_t entry
, struct page
*page
)
1238 pud
= pud_offset(pgd
, addr
);
1240 next
= pud_addr_end(addr
, end
);
1241 if (pud_none_or_clear_bad(pud
))
1243 ret
= unuse_pmd_range(vma
, pud
, addr
, next
, entry
, page
);
1246 } while (pud
++, addr
= next
, addr
!= end
);
1250 static int unuse_vma(struct vm_area_struct
*vma
,
1251 swp_entry_t entry
, struct page
*page
)
1254 unsigned long addr
, end
, next
;
1257 if (page_anon_vma(page
)) {
1258 addr
= page_address_in_vma(page
, vma
);
1259 if (addr
== -EFAULT
)
1262 end
= addr
+ PAGE_SIZE
;
1264 addr
= vma
->vm_start
;
1268 pgd
= pgd_offset(vma
->vm_mm
, addr
);
1270 next
= pgd_addr_end(addr
, end
);
1271 if (pgd_none_or_clear_bad(pgd
))
1273 ret
= unuse_pud_range(vma
, pgd
, addr
, next
, entry
, page
);
1276 } while (pgd
++, addr
= next
, addr
!= end
);
1280 static int unuse_mm(struct mm_struct
*mm
,
1281 swp_entry_t entry
, struct page
*page
)
1283 struct vm_area_struct
*vma
;
1286 if (!down_read_trylock(&mm
->mmap_sem
)) {
1288 * Activate page so shrink_inactive_list is unlikely to unmap
1289 * its ptes while lock is dropped, so swapoff can make progress.
1291 activate_page(page
);
1293 down_read(&mm
->mmap_sem
);
1296 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
1297 if (vma
->anon_vma
&& (ret
= unuse_vma(vma
, entry
, page
)))
1300 up_read(&mm
->mmap_sem
);
1301 return (ret
< 0)? ret
: 0;
1305 * Scan swap_map (or frontswap_map if frontswap parameter is true)
1306 * from current position to next entry still in use.
1307 * Recycle to start on reaching the end, returning 0 when empty.
1309 static unsigned int find_next_to_unuse(struct swap_info_struct
*si
,
1310 unsigned int prev
, bool frontswap
)
1312 unsigned int max
= si
->max
;
1313 unsigned int i
= prev
;
1314 unsigned char count
;
1317 * No need for swap_lock here: we're just looking
1318 * for whether an entry is in use, not modifying it; false
1319 * hits are okay, and sys_swapoff() has already prevented new
1320 * allocations from this area (while holding swap_lock).
1329 * No entries in use at top of swap_map,
1330 * loop back to start and recheck there.
1337 if (frontswap_test(si
, i
))
1342 count
= ACCESS_ONCE(si
->swap_map
[i
]);
1343 if (count
&& swap_count(count
) != SWAP_MAP_BAD
)
1350 * We completely avoid races by reading each swap page in advance,
1351 * and then search for the process using it. All the necessary
1352 * page table adjustments can then be made atomically.
1354 * if the boolean frontswap is true, only unuse pages_to_unuse pages;
1355 * pages_to_unuse==0 means all pages; ignored if frontswap is false
1357 int try_to_unuse(unsigned int type
, bool frontswap
,
1358 unsigned long pages_to_unuse
)
1360 struct swap_info_struct
*si
= swap_info
[type
];
1361 struct mm_struct
*start_mm
;
1362 volatile unsigned char *swap_map
; /* swap_map is accessed without
1363 * locking. Mark it as volatile
1364 * to prevent compiler doing
1367 unsigned char swcount
;
1374 * When searching mms for an entry, a good strategy is to
1375 * start at the first mm we freed the previous entry from
1376 * (though actually we don't notice whether we or coincidence
1377 * freed the entry). Initialize this start_mm with a hold.
1379 * A simpler strategy would be to start at the last mm we
1380 * freed the previous entry from; but that would take less
1381 * advantage of mmlist ordering, which clusters forked mms
1382 * together, child after parent. If we race with dup_mmap(), we
1383 * prefer to resolve parent before child, lest we miss entries
1384 * duplicated after we scanned child: using last mm would invert
1387 start_mm
= &init_mm
;
1388 atomic_inc(&init_mm
.mm_users
);
1391 * Keep on scanning until all entries have gone. Usually,
1392 * one pass through swap_map is enough, but not necessarily:
1393 * there are races when an instance of an entry might be missed.
1395 while ((i
= find_next_to_unuse(si
, i
, frontswap
)) != 0) {
1396 if (signal_pending(current
)) {
1402 * Get a page for the entry, using the existing swap
1403 * cache page if there is one. Otherwise, get a clean
1404 * page and read the swap into it.
1406 swap_map
= &si
->swap_map
[i
];
1407 entry
= swp_entry(type
, i
);
1408 page
= read_swap_cache_async(entry
,
1409 GFP_HIGHUSER_MOVABLE
, NULL
, 0);
1412 * Either swap_duplicate() failed because entry
1413 * has been freed independently, and will not be
1414 * reused since sys_swapoff() already disabled
1415 * allocation from here, or alloc_page() failed.
1417 swcount
= *swap_map
;
1419 * We don't hold lock here, so the swap entry could be
1420 * SWAP_MAP_BAD (when the cluster is discarding).
1421 * Instead of fail out, We can just skip the swap
1422 * entry because swapoff will wait for discarding
1425 if (!swcount
|| swcount
== SWAP_MAP_BAD
)
1432 * Don't hold on to start_mm if it looks like exiting.
1434 if (atomic_read(&start_mm
->mm_users
) == 1) {
1436 start_mm
= &init_mm
;
1437 atomic_inc(&init_mm
.mm_users
);
1441 * Wait for and lock page. When do_swap_page races with
1442 * try_to_unuse, do_swap_page can handle the fault much
1443 * faster than try_to_unuse can locate the entry. This
1444 * apparently redundant "wait_on_page_locked" lets try_to_unuse
1445 * defer to do_swap_page in such a case - in some tests,
1446 * do_swap_page and try_to_unuse repeatedly compete.
1448 wait_on_page_locked(page
);
1449 wait_on_page_writeback(page
);
1451 wait_on_page_writeback(page
);
1454 * Remove all references to entry.
1456 swcount
= *swap_map
;
1457 if (swap_count(swcount
) == SWAP_MAP_SHMEM
) {
1458 retval
= shmem_unuse(entry
, page
);
1459 /* page has already been unlocked and released */
1464 if (swap_count(swcount
) && start_mm
!= &init_mm
)
1465 retval
= unuse_mm(start_mm
, entry
, page
);
1467 if (swap_count(*swap_map
)) {
1468 int set_start_mm
= (*swap_map
>= swcount
);
1469 struct list_head
*p
= &start_mm
->mmlist
;
1470 struct mm_struct
*new_start_mm
= start_mm
;
1471 struct mm_struct
*prev_mm
= start_mm
;
1472 struct mm_struct
*mm
;
1474 atomic_inc(&new_start_mm
->mm_users
);
1475 atomic_inc(&prev_mm
->mm_users
);
1476 spin_lock(&mmlist_lock
);
1477 while (swap_count(*swap_map
) && !retval
&&
1478 (p
= p
->next
) != &start_mm
->mmlist
) {
1479 mm
= list_entry(p
, struct mm_struct
, mmlist
);
1480 if (!atomic_inc_not_zero(&mm
->mm_users
))
1482 spin_unlock(&mmlist_lock
);
1488 swcount
= *swap_map
;
1489 if (!swap_count(swcount
)) /* any usage ? */
1491 else if (mm
== &init_mm
)
1494 retval
= unuse_mm(mm
, entry
, page
);
1496 if (set_start_mm
&& *swap_map
< swcount
) {
1497 mmput(new_start_mm
);
1498 atomic_inc(&mm
->mm_users
);
1502 spin_lock(&mmlist_lock
);
1504 spin_unlock(&mmlist_lock
);
1507 start_mm
= new_start_mm
;
1511 page_cache_release(page
);
1516 * If a reference remains (rare), we would like to leave
1517 * the page in the swap cache; but try_to_unmap could
1518 * then re-duplicate the entry once we drop page lock,
1519 * so we might loop indefinitely; also, that page could
1520 * not be swapped out to other storage meanwhile. So:
1521 * delete from cache even if there's another reference,
1522 * after ensuring that the data has been saved to disk -
1523 * since if the reference remains (rarer), it will be
1524 * read from disk into another page. Splitting into two
1525 * pages would be incorrect if swap supported "shared
1526 * private" pages, but they are handled by tmpfs files.
1528 * Given how unuse_vma() targets one particular offset
1529 * in an anon_vma, once the anon_vma has been determined,
1530 * this splitting happens to be just what is needed to
1531 * handle where KSM pages have been swapped out: re-reading
1532 * is unnecessarily slow, but we can fix that later on.
1534 if (swap_count(*swap_map
) &&
1535 PageDirty(page
) && PageSwapCache(page
)) {
1536 struct writeback_control wbc
= {
1537 .sync_mode
= WB_SYNC_NONE
,
1540 swap_writepage(page
, &wbc
);
1542 wait_on_page_writeback(page
);
1546 * It is conceivable that a racing task removed this page from
1547 * swap cache just before we acquired the page lock at the top,
1548 * or while we dropped it in unuse_mm(). The page might even
1549 * be back in swap cache on another swap area: that we must not
1550 * delete, since it may not have been written out to swap yet.
1552 if (PageSwapCache(page
) &&
1553 likely(page_private(page
) == entry
.val
))
1554 delete_from_swap_cache(page
);
1557 * So we could skip searching mms once swap count went
1558 * to 1, we did not mark any present ptes as dirty: must
1559 * mark page dirty so shrink_page_list will preserve it.
1563 page_cache_release(page
);
1566 * Make sure that we aren't completely killing
1567 * interactive performance.
1570 if (frontswap
&& pages_to_unuse
> 0) {
1571 if (!--pages_to_unuse
)
1581 * After a successful try_to_unuse, if no swap is now in use, we know
1582 * we can empty the mmlist. swap_lock must be held on entry and exit.
1583 * Note that mmlist_lock nests inside swap_lock, and an mm must be
1584 * added to the mmlist just after page_duplicate - before would be racy.
1586 static void drain_mmlist(void)
1588 struct list_head
*p
, *next
;
1591 for (type
= 0; type
< nr_swapfiles
; type
++)
1592 if (swap_info
[type
]->inuse_pages
)
1594 spin_lock(&mmlist_lock
);
1595 list_for_each_safe(p
, next
, &init_mm
.mmlist
)
1597 spin_unlock(&mmlist_lock
);
1601 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
1602 * corresponds to page offset for the specified swap entry.
1603 * Note that the type of this function is sector_t, but it returns page offset
1604 * into the bdev, not sector offset.
1606 static sector_t
map_swap_entry(swp_entry_t entry
, struct block_device
**bdev
)
1608 struct swap_info_struct
*sis
;
1609 struct swap_extent
*start_se
;
1610 struct swap_extent
*se
;
1613 sis
= swap_info
[swp_type(entry
)];
1616 offset
= swp_offset(entry
);
1617 start_se
= sis
->curr_swap_extent
;
1621 struct list_head
*lh
;
1623 if (se
->start_page
<= offset
&&
1624 offset
< (se
->start_page
+ se
->nr_pages
)) {
1625 return se
->start_block
+ (offset
- se
->start_page
);
1628 se
= list_entry(lh
, struct swap_extent
, list
);
1629 sis
->curr_swap_extent
= se
;
1630 BUG_ON(se
== start_se
); /* It *must* be present */
1635 * Returns the page offset into bdev for the specified page's swap entry.
1637 sector_t
map_swap_page(struct page
*page
, struct block_device
**bdev
)
1640 entry
.val
= page_private(page
);
1641 return map_swap_entry(entry
, bdev
);
1645 * Free all of a swapdev's extent information
1647 static void destroy_swap_extents(struct swap_info_struct
*sis
)
1649 while (!list_empty(&sis
->first_swap_extent
.list
)) {
1650 struct swap_extent
*se
;
1652 se
= list_entry(sis
->first_swap_extent
.list
.next
,
1653 struct swap_extent
, list
);
1654 list_del(&se
->list
);
1658 if (sis
->flags
& SWP_FILE
) {
1659 struct file
*swap_file
= sis
->swap_file
;
1660 struct address_space
*mapping
= swap_file
->f_mapping
;
1662 sis
->flags
&= ~SWP_FILE
;
1663 mapping
->a_ops
->swap_deactivate(swap_file
);
1668 * Add a block range (and the corresponding page range) into this swapdev's
1669 * extent list. The extent list is kept sorted in page order.
1671 * This function rather assumes that it is called in ascending page order.
1674 add_swap_extent(struct swap_info_struct
*sis
, unsigned long start_page
,
1675 unsigned long nr_pages
, sector_t start_block
)
1677 struct swap_extent
*se
;
1678 struct swap_extent
*new_se
;
1679 struct list_head
*lh
;
1681 if (start_page
== 0) {
1682 se
= &sis
->first_swap_extent
;
1683 sis
->curr_swap_extent
= se
;
1685 se
->nr_pages
= nr_pages
;
1686 se
->start_block
= start_block
;
1689 lh
= sis
->first_swap_extent
.list
.prev
; /* Highest extent */
1690 se
= list_entry(lh
, struct swap_extent
, list
);
1691 BUG_ON(se
->start_page
+ se
->nr_pages
!= start_page
);
1692 if (se
->start_block
+ se
->nr_pages
== start_block
) {
1694 se
->nr_pages
+= nr_pages
;
1700 * No merge. Insert a new extent, preserving ordering.
1702 new_se
= kmalloc(sizeof(*se
), GFP_KERNEL
);
1705 new_se
->start_page
= start_page
;
1706 new_se
->nr_pages
= nr_pages
;
1707 new_se
->start_block
= start_block
;
1709 list_add_tail(&new_se
->list
, &sis
->first_swap_extent
.list
);
1714 * A `swap extent' is a simple thing which maps a contiguous range of pages
1715 * onto a contiguous range of disk blocks. An ordered list of swap extents
1716 * is built at swapon time and is then used at swap_writepage/swap_readpage
1717 * time for locating where on disk a page belongs.
1719 * If the swapfile is an S_ISBLK block device, a single extent is installed.
1720 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1721 * swap files identically.
1723 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1724 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
1725 * swapfiles are handled *identically* after swapon time.
1727 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1728 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
1729 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1730 * requirements, they are simply tossed out - we will never use those blocks
1733 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1734 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1735 * which will scribble on the fs.
1737 * The amount of disk space which a single swap extent represents varies.
1738 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
1739 * extents in the list. To avoid much list walking, we cache the previous
1740 * search location in `curr_swap_extent', and start new searches from there.
1741 * This is extremely effective. The average number of iterations in
1742 * map_swap_page() has been measured at about 0.3 per page. - akpm.
1744 static int setup_swap_extents(struct swap_info_struct
*sis
, sector_t
*span
)
1746 struct file
*swap_file
= sis
->swap_file
;
1747 struct address_space
*mapping
= swap_file
->f_mapping
;
1748 struct inode
*inode
= mapping
->host
;
1751 if (S_ISBLK(inode
->i_mode
)) {
1752 ret
= add_swap_extent(sis
, 0, sis
->max
, 0);
1757 if (mapping
->a_ops
->swap_activate
) {
1758 ret
= mapping
->a_ops
->swap_activate(sis
, swap_file
, span
);
1760 sis
->flags
|= SWP_FILE
;
1761 ret
= add_swap_extent(sis
, 0, sis
->max
, 0);
1767 return generic_swapfile_activate(sis
, swap_file
, span
);
1770 static void _enable_swap_info(struct swap_info_struct
*p
, int prio
,
1771 unsigned char *swap_map
,
1772 struct swap_cluster_info
*cluster_info
)
1777 p
->prio
= --least_priority
;
1779 * the plist prio is negated because plist ordering is
1780 * low-to-high, while swap ordering is high-to-low
1782 p
->list
.prio
= -p
->prio
;
1783 p
->avail_list
.prio
= -p
->prio
;
1784 p
->swap_map
= swap_map
;
1785 p
->cluster_info
= cluster_info
;
1786 p
->flags
|= SWP_WRITEOK
;
1787 atomic_long_add(p
->pages
, &nr_swap_pages
);
1788 total_swap_pages
+= p
->pages
;
1790 assert_spin_locked(&swap_lock
);
1792 * both lists are plists, and thus priority ordered.
1793 * swap_active_head needs to be priority ordered for swapoff(),
1794 * which on removal of any swap_info_struct with an auto-assigned
1795 * (i.e. negative) priority increments the auto-assigned priority
1796 * of any lower-priority swap_info_structs.
1797 * swap_avail_head needs to be priority ordered for get_swap_page(),
1798 * which allocates swap pages from the highest available priority
1801 plist_add(&p
->list
, &swap_active_head
);
1802 spin_lock(&swap_avail_lock
);
1803 plist_add(&p
->avail_list
, &swap_avail_head
);
1804 spin_unlock(&swap_avail_lock
);
1807 static void enable_swap_info(struct swap_info_struct
*p
, int prio
,
1808 unsigned char *swap_map
,
1809 struct swap_cluster_info
*cluster_info
,
1810 unsigned long *frontswap_map
)
1812 frontswap_init(p
->type
, frontswap_map
);
1813 spin_lock(&swap_lock
);
1814 spin_lock(&p
->lock
);
1815 _enable_swap_info(p
, prio
, swap_map
, cluster_info
);
1816 spin_unlock(&p
->lock
);
1817 spin_unlock(&swap_lock
);
1820 static void reinsert_swap_info(struct swap_info_struct
*p
)
1822 spin_lock(&swap_lock
);
1823 spin_lock(&p
->lock
);
1824 _enable_swap_info(p
, p
->prio
, p
->swap_map
, p
->cluster_info
);
1825 spin_unlock(&p
->lock
);
1826 spin_unlock(&swap_lock
);
1829 SYSCALL_DEFINE1(swapoff
, const char __user
*, specialfile
)
1831 struct swap_info_struct
*p
= NULL
;
1832 unsigned char *swap_map
;
1833 struct swap_cluster_info
*cluster_info
;
1834 unsigned long *frontswap_map
;
1835 struct file
*swap_file
, *victim
;
1836 struct address_space
*mapping
;
1837 struct inode
*inode
;
1838 struct filename
*pathname
;
1840 unsigned int old_block_size
;
1842 if (!capable(CAP_SYS_ADMIN
))
1845 BUG_ON(!current
->mm
);
1847 pathname
= getname(specialfile
);
1848 if (IS_ERR(pathname
))
1849 return PTR_ERR(pathname
);
1851 victim
= file_open_name(pathname
, O_RDWR
|O_LARGEFILE
, 0);
1852 err
= PTR_ERR(victim
);
1856 mapping
= victim
->f_mapping
;
1857 spin_lock(&swap_lock
);
1858 plist_for_each_entry(p
, &swap_active_head
, list
) {
1859 if (p
->flags
& SWP_WRITEOK
) {
1860 if (p
->swap_file
->f_mapping
== mapping
) {
1868 spin_unlock(&swap_lock
);
1871 if (!security_vm_enough_memory_mm(current
->mm
, p
->pages
))
1872 vm_unacct_memory(p
->pages
);
1875 spin_unlock(&swap_lock
);
1878 spin_lock(&swap_avail_lock
);
1879 plist_del(&p
->avail_list
, &swap_avail_head
);
1880 spin_unlock(&swap_avail_lock
);
1881 spin_lock(&p
->lock
);
1883 struct swap_info_struct
*si
= p
;
1885 plist_for_each_entry_continue(si
, &swap_active_head
, list
) {
1888 si
->avail_list
.prio
--;
1892 plist_del(&p
->list
, &swap_active_head
);
1893 atomic_long_sub(p
->pages
, &nr_swap_pages
);
1894 total_swap_pages
-= p
->pages
;
1895 p
->flags
&= ~SWP_WRITEOK
;
1896 spin_unlock(&p
->lock
);
1897 spin_unlock(&swap_lock
);
1899 set_current_oom_origin();
1900 err
= try_to_unuse(p
->type
, false, 0); /* force unuse all pages */
1901 clear_current_oom_origin();
1904 /* re-insert swap space back into swap_list */
1905 reinsert_swap_info(p
);
1909 flush_work(&p
->discard_work
);
1911 destroy_swap_extents(p
);
1912 if (p
->flags
& SWP_CONTINUED
)
1913 free_swap_count_continuations(p
);
1915 mutex_lock(&swapon_mutex
);
1916 spin_lock(&swap_lock
);
1917 spin_lock(&p
->lock
);
1920 /* wait for anyone still in scan_swap_map */
1921 p
->highest_bit
= 0; /* cuts scans short */
1922 while (p
->flags
>= SWP_SCANNING
) {
1923 spin_unlock(&p
->lock
);
1924 spin_unlock(&swap_lock
);
1925 schedule_timeout_uninterruptible(1);
1926 spin_lock(&swap_lock
);
1927 spin_lock(&p
->lock
);
1930 swap_file
= p
->swap_file
;
1931 old_block_size
= p
->old_block_size
;
1932 p
->swap_file
= NULL
;
1934 swap_map
= p
->swap_map
;
1936 cluster_info
= p
->cluster_info
;
1937 p
->cluster_info
= NULL
;
1938 frontswap_map
= frontswap_map_get(p
);
1939 spin_unlock(&p
->lock
);
1940 spin_unlock(&swap_lock
);
1941 frontswap_invalidate_area(p
->type
);
1942 frontswap_map_set(p
, NULL
);
1943 mutex_unlock(&swapon_mutex
);
1944 free_percpu(p
->percpu_cluster
);
1945 p
->percpu_cluster
= NULL
;
1947 vfree(cluster_info
);
1948 vfree(frontswap_map
);
1949 /* Destroy swap account information */
1950 swap_cgroup_swapoff(p
->type
);
1952 inode
= mapping
->host
;
1953 if (S_ISBLK(inode
->i_mode
)) {
1954 struct block_device
*bdev
= I_BDEV(inode
);
1955 set_blocksize(bdev
, old_block_size
);
1956 blkdev_put(bdev
, FMODE_READ
| FMODE_WRITE
| FMODE_EXCL
);
1958 mutex_lock(&inode
->i_mutex
);
1959 inode
->i_flags
&= ~S_SWAPFILE
;
1960 mutex_unlock(&inode
->i_mutex
);
1962 filp_close(swap_file
, NULL
);
1965 * Clear the SWP_USED flag after all resources are freed so that swapon
1966 * can reuse this swap_info in alloc_swap_info() safely. It is ok to
1967 * not hold p->lock after we cleared its SWP_WRITEOK.
1969 spin_lock(&swap_lock
);
1971 spin_unlock(&swap_lock
);
1974 atomic_inc(&proc_poll_event
);
1975 wake_up_interruptible(&proc_poll_wait
);
1978 filp_close(victim
, NULL
);
1984 #ifdef CONFIG_PROC_FS
1985 static unsigned swaps_poll(struct file
*file
, poll_table
*wait
)
1987 struct seq_file
*seq
= file
->private_data
;
1989 poll_wait(file
, &proc_poll_wait
, wait
);
1991 if (seq
->poll_event
!= atomic_read(&proc_poll_event
)) {
1992 seq
->poll_event
= atomic_read(&proc_poll_event
);
1993 return POLLIN
| POLLRDNORM
| POLLERR
| POLLPRI
;
1996 return POLLIN
| POLLRDNORM
;
2000 static void *swap_start(struct seq_file
*swap
, loff_t
*pos
)
2002 struct swap_info_struct
*si
;
2006 mutex_lock(&swapon_mutex
);
2009 return SEQ_START_TOKEN
;
2011 for (type
= 0; type
< nr_swapfiles
; type
++) {
2012 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
2013 si
= swap_info
[type
];
2014 if (!(si
->flags
& SWP_USED
) || !si
->swap_map
)
2023 static void *swap_next(struct seq_file
*swap
, void *v
, loff_t
*pos
)
2025 struct swap_info_struct
*si
= v
;
2028 if (v
== SEQ_START_TOKEN
)
2031 type
= si
->type
+ 1;
2033 for (; type
< nr_swapfiles
; type
++) {
2034 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
2035 si
= swap_info
[type
];
2036 if (!(si
->flags
& SWP_USED
) || !si
->swap_map
)
2045 static void swap_stop(struct seq_file
*swap
, void *v
)
2047 mutex_unlock(&swapon_mutex
);
2050 static int swap_show(struct seq_file
*swap
, void *v
)
2052 struct swap_info_struct
*si
= v
;
2056 if (si
== SEQ_START_TOKEN
) {
2057 seq_puts(swap
,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
2061 file
= si
->swap_file
;
2062 len
= seq_path(swap
, &file
->f_path
, " \t\n\\");
2063 seq_printf(swap
, "%*s%s\t%u\t%u\t%d\n",
2064 len
< 40 ? 40 - len
: 1, " ",
2065 S_ISBLK(file_inode(file
)->i_mode
) ?
2066 "partition" : "file\t",
2067 si
->pages
<< (PAGE_SHIFT
- 10),
2068 si
->inuse_pages
<< (PAGE_SHIFT
- 10),
2073 static const struct seq_operations swaps_op
= {
2074 .start
= swap_start
,
2080 static int swaps_open(struct inode
*inode
, struct file
*file
)
2082 struct seq_file
*seq
;
2085 ret
= seq_open(file
, &swaps_op
);
2089 seq
= file
->private_data
;
2090 seq
->poll_event
= atomic_read(&proc_poll_event
);
2094 static const struct file_operations proc_swaps_operations
= {
2097 .llseek
= seq_lseek
,
2098 .release
= seq_release
,
2102 static int __init
procswaps_init(void)
2104 proc_create("swaps", 0, NULL
, &proc_swaps_operations
);
2107 __initcall(procswaps_init
);
2108 #endif /* CONFIG_PROC_FS */
2110 #ifdef MAX_SWAPFILES_CHECK
2111 static int __init
max_swapfiles_check(void)
2113 MAX_SWAPFILES_CHECK();
2116 late_initcall(max_swapfiles_check
);
2119 static struct swap_info_struct
*alloc_swap_info(void)
2121 struct swap_info_struct
*p
;
2124 p
= kzalloc(sizeof(*p
), GFP_KERNEL
);
2126 return ERR_PTR(-ENOMEM
);
2128 spin_lock(&swap_lock
);
2129 for (type
= 0; type
< nr_swapfiles
; type
++) {
2130 if (!(swap_info
[type
]->flags
& SWP_USED
))
2133 if (type
>= MAX_SWAPFILES
) {
2134 spin_unlock(&swap_lock
);
2136 return ERR_PTR(-EPERM
);
2138 if (type
>= nr_swapfiles
) {
2140 swap_info
[type
] = p
;
2142 * Write swap_info[type] before nr_swapfiles, in case a
2143 * racing procfs swap_start() or swap_next() is reading them.
2144 * (We never shrink nr_swapfiles, we never free this entry.)
2150 p
= swap_info
[type
];
2152 * Do not memset this entry: a racing procfs swap_next()
2153 * would be relying on p->type to remain valid.
2156 INIT_LIST_HEAD(&p
->first_swap_extent
.list
);
2157 plist_node_init(&p
->list
, 0);
2158 plist_node_init(&p
->avail_list
, 0);
2159 p
->flags
= SWP_USED
;
2160 spin_unlock(&swap_lock
);
2161 spin_lock_init(&p
->lock
);
2166 static int claim_swapfile(struct swap_info_struct
*p
, struct inode
*inode
)
2170 if (S_ISBLK(inode
->i_mode
)) {
2171 p
->bdev
= bdgrab(I_BDEV(inode
));
2172 error
= blkdev_get(p
->bdev
,
2173 FMODE_READ
| FMODE_WRITE
| FMODE_EXCL
,
2179 p
->old_block_size
= block_size(p
->bdev
);
2180 error
= set_blocksize(p
->bdev
, PAGE_SIZE
);
2183 p
->flags
|= SWP_BLKDEV
;
2184 } else if (S_ISREG(inode
->i_mode
)) {
2185 p
->bdev
= inode
->i_sb
->s_bdev
;
2186 mutex_lock(&inode
->i_mutex
);
2187 if (IS_SWAPFILE(inode
))
2195 static unsigned long read_swap_header(struct swap_info_struct
*p
,
2196 union swap_header
*swap_header
,
2197 struct inode
*inode
)
2200 unsigned long maxpages
;
2201 unsigned long swapfilepages
;
2202 unsigned long last_page
;
2204 if (memcmp("SWAPSPACE2", swap_header
->magic
.magic
, 10)) {
2205 pr_err("Unable to find swap-space signature\n");
2209 /* swap partition endianess hack... */
2210 if (swab32(swap_header
->info
.version
) == 1) {
2211 swab32s(&swap_header
->info
.version
);
2212 swab32s(&swap_header
->info
.last_page
);
2213 swab32s(&swap_header
->info
.nr_badpages
);
2214 for (i
= 0; i
< swap_header
->info
.nr_badpages
; i
++)
2215 swab32s(&swap_header
->info
.badpages
[i
]);
2217 /* Check the swap header's sub-version */
2218 if (swap_header
->info
.version
!= 1) {
2219 pr_warn("Unable to handle swap header version %d\n",
2220 swap_header
->info
.version
);
2225 p
->cluster_next
= 1;
2229 * Find out how many pages are allowed for a single swap
2230 * device. There are two limiting factors: 1) the number
2231 * of bits for the swap offset in the swp_entry_t type, and
2232 * 2) the number of bits in the swap pte as defined by the
2233 * different architectures. In order to find the
2234 * largest possible bit mask, a swap entry with swap type 0
2235 * and swap offset ~0UL is created, encoded to a swap pte,
2236 * decoded to a swp_entry_t again, and finally the swap
2237 * offset is extracted. This will mask all the bits from
2238 * the initial ~0UL mask that can't be encoded in either
2239 * the swp_entry_t or the architecture definition of a
2242 maxpages
= swp_offset(pte_to_swp_entry(
2243 swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2244 last_page
= swap_header
->info
.last_page
;
2245 if (last_page
> maxpages
) {
2246 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
2247 maxpages
<< (PAGE_SHIFT
- 10),
2248 last_page
<< (PAGE_SHIFT
- 10));
2250 if (maxpages
> last_page
) {
2251 maxpages
= last_page
+ 1;
2252 /* p->max is an unsigned int: don't overflow it */
2253 if ((unsigned int)maxpages
== 0)
2254 maxpages
= UINT_MAX
;
2256 p
->highest_bit
= maxpages
- 1;
2260 swapfilepages
= i_size_read(inode
) >> PAGE_SHIFT
;
2261 if (swapfilepages
&& maxpages
> swapfilepages
) {
2262 pr_warn("Swap area shorter than signature indicates\n");
2265 if (swap_header
->info
.nr_badpages
&& S_ISREG(inode
->i_mode
))
2267 if (swap_header
->info
.nr_badpages
> MAX_SWAP_BADPAGES
)
2273 static int setup_swap_map_and_extents(struct swap_info_struct
*p
,
2274 union swap_header
*swap_header
,
2275 unsigned char *swap_map
,
2276 struct swap_cluster_info
*cluster_info
,
2277 unsigned long maxpages
,
2281 unsigned int nr_good_pages
;
2283 unsigned long nr_clusters
= DIV_ROUND_UP(maxpages
, SWAPFILE_CLUSTER
);
2284 unsigned long idx
= p
->cluster_next
/ SWAPFILE_CLUSTER
;
2286 nr_good_pages
= maxpages
- 1; /* omit header page */
2288 cluster_set_null(&p
->free_cluster_head
);
2289 cluster_set_null(&p
->free_cluster_tail
);
2290 cluster_set_null(&p
->discard_cluster_head
);
2291 cluster_set_null(&p
->discard_cluster_tail
);
2293 for (i
= 0; i
< swap_header
->info
.nr_badpages
; i
++) {
2294 unsigned int page_nr
= swap_header
->info
.badpages
[i
];
2295 if (page_nr
== 0 || page_nr
> swap_header
->info
.last_page
)
2297 if (page_nr
< maxpages
) {
2298 swap_map
[page_nr
] = SWAP_MAP_BAD
;
2301 * Haven't marked the cluster free yet, no list
2302 * operation involved
2304 inc_cluster_info_page(p
, cluster_info
, page_nr
);
2308 /* Haven't marked the cluster free yet, no list operation involved */
2309 for (i
= maxpages
; i
< round_up(maxpages
, SWAPFILE_CLUSTER
); i
++)
2310 inc_cluster_info_page(p
, cluster_info
, i
);
2312 if (nr_good_pages
) {
2313 swap_map
[0] = SWAP_MAP_BAD
;
2315 * Not mark the cluster free yet, no list
2316 * operation involved
2318 inc_cluster_info_page(p
, cluster_info
, 0);
2320 p
->pages
= nr_good_pages
;
2321 nr_extents
= setup_swap_extents(p
, span
);
2324 nr_good_pages
= p
->pages
;
2326 if (!nr_good_pages
) {
2327 pr_warn("Empty swap-file\n");
2334 for (i
= 0; i
< nr_clusters
; i
++) {
2335 if (!cluster_count(&cluster_info
[idx
])) {
2336 cluster_set_flag(&cluster_info
[idx
], CLUSTER_FLAG_FREE
);
2337 if (cluster_is_null(&p
->free_cluster_head
)) {
2338 cluster_set_next_flag(&p
->free_cluster_head
,
2340 cluster_set_next_flag(&p
->free_cluster_tail
,
2345 tail
= cluster_next(&p
->free_cluster_tail
);
2346 cluster_set_next(&cluster_info
[tail
], idx
);
2347 cluster_set_next_flag(&p
->free_cluster_tail
,
2352 if (idx
== nr_clusters
)
2359 * Helper to sys_swapon determining if a given swap
2360 * backing device queue supports DISCARD operations.
2362 static bool swap_discardable(struct swap_info_struct
*si
)
2364 struct request_queue
*q
= bdev_get_queue(si
->bdev
);
2366 if (!q
|| !blk_queue_discard(q
))
2372 SYSCALL_DEFINE2(swapon
, const char __user
*, specialfile
, int, swap_flags
)
2374 struct swap_info_struct
*p
;
2375 struct filename
*name
;
2376 struct file
*swap_file
= NULL
;
2377 struct address_space
*mapping
;
2381 union swap_header
*swap_header
;
2384 unsigned long maxpages
;
2385 unsigned char *swap_map
= NULL
;
2386 struct swap_cluster_info
*cluster_info
= NULL
;
2387 unsigned long *frontswap_map
= NULL
;
2388 struct page
*page
= NULL
;
2389 struct inode
*inode
= NULL
;
2391 if (swap_flags
& ~SWAP_FLAGS_VALID
)
2394 if (!capable(CAP_SYS_ADMIN
))
2397 p
= alloc_swap_info();
2401 INIT_WORK(&p
->discard_work
, swap_discard_work
);
2403 name
= getname(specialfile
);
2405 error
= PTR_ERR(name
);
2409 swap_file
= file_open_name(name
, O_RDWR
|O_LARGEFILE
, 0);
2410 if (IS_ERR(swap_file
)) {
2411 error
= PTR_ERR(swap_file
);
2416 p
->swap_file
= swap_file
;
2417 mapping
= swap_file
->f_mapping
;
2419 for (i
= 0; i
< nr_swapfiles
; i
++) {
2420 struct swap_info_struct
*q
= swap_info
[i
];
2422 if (q
== p
|| !q
->swap_file
)
2424 if (mapping
== q
->swap_file
->f_mapping
) {
2430 inode
= mapping
->host
;
2431 /* If S_ISREG(inode->i_mode) will do mutex_lock(&inode->i_mutex); */
2432 error
= claim_swapfile(p
, inode
);
2433 if (unlikely(error
))
2437 * Read the swap header.
2439 if (!mapping
->a_ops
->readpage
) {
2443 page
= read_mapping_page(mapping
, 0, swap_file
);
2445 error
= PTR_ERR(page
);
2448 swap_header
= kmap(page
);
2450 maxpages
= read_swap_header(p
, swap_header
, inode
);
2451 if (unlikely(!maxpages
)) {
2456 /* OK, set up the swap map and apply the bad block list */
2457 swap_map
= vzalloc(maxpages
);
2462 if (p
->bdev
&& blk_queue_nonrot(bdev_get_queue(p
->bdev
))) {
2463 p
->flags
|= SWP_SOLIDSTATE
;
2465 * select a random position to start with to help wear leveling
2468 p
->cluster_next
= 1 + (prandom_u32() % p
->highest_bit
);
2470 cluster_info
= vzalloc(DIV_ROUND_UP(maxpages
,
2471 SWAPFILE_CLUSTER
) * sizeof(*cluster_info
));
2472 if (!cluster_info
) {
2476 p
->percpu_cluster
= alloc_percpu(struct percpu_cluster
);
2477 if (!p
->percpu_cluster
) {
2481 for_each_possible_cpu(i
) {
2482 struct percpu_cluster
*cluster
;
2483 cluster
= per_cpu_ptr(p
->percpu_cluster
, i
);
2484 cluster_set_null(&cluster
->index
);
2488 error
= swap_cgroup_swapon(p
->type
, maxpages
);
2492 nr_extents
= setup_swap_map_and_extents(p
, swap_header
, swap_map
,
2493 cluster_info
, maxpages
, &span
);
2494 if (unlikely(nr_extents
< 0)) {
2498 /* frontswap enabled? set up bit-per-page map for frontswap */
2499 if (frontswap_enabled
)
2500 frontswap_map
= vzalloc(BITS_TO_LONGS(maxpages
) * sizeof(long));
2502 if (p
->bdev
&&(swap_flags
& SWAP_FLAG_DISCARD
) && swap_discardable(p
)) {
2504 * When discard is enabled for swap with no particular
2505 * policy flagged, we set all swap discard flags here in
2506 * order to sustain backward compatibility with older
2507 * swapon(8) releases.
2509 p
->flags
|= (SWP_DISCARDABLE
| SWP_AREA_DISCARD
|
2513 * By flagging sys_swapon, a sysadmin can tell us to
2514 * either do single-time area discards only, or to just
2515 * perform discards for released swap page-clusters.
2516 * Now it's time to adjust the p->flags accordingly.
2518 if (swap_flags
& SWAP_FLAG_DISCARD_ONCE
)
2519 p
->flags
&= ~SWP_PAGE_DISCARD
;
2520 else if (swap_flags
& SWAP_FLAG_DISCARD_PAGES
)
2521 p
->flags
&= ~SWP_AREA_DISCARD
;
2523 /* issue a swapon-time discard if it's still required */
2524 if (p
->flags
& SWP_AREA_DISCARD
) {
2525 int err
= discard_swap(p
);
2527 pr_err("swapon: discard_swap(%p): %d\n",
2532 mutex_lock(&swapon_mutex
);
2534 if (swap_flags
& SWAP_FLAG_PREFER
)
2536 (swap_flags
& SWAP_FLAG_PRIO_MASK
) >> SWAP_FLAG_PRIO_SHIFT
;
2537 enable_swap_info(p
, prio
, swap_map
, cluster_info
, frontswap_map
);
2539 pr_info("Adding %uk swap on %s. "
2540 "Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
2541 p
->pages
<<(PAGE_SHIFT
-10), name
->name
, p
->prio
,
2542 nr_extents
, (unsigned long long)span
<<(PAGE_SHIFT
-10),
2543 (p
->flags
& SWP_SOLIDSTATE
) ? "SS" : "",
2544 (p
->flags
& SWP_DISCARDABLE
) ? "D" : "",
2545 (p
->flags
& SWP_AREA_DISCARD
) ? "s" : "",
2546 (p
->flags
& SWP_PAGE_DISCARD
) ? "c" : "",
2547 (frontswap_map
) ? "FS" : "");
2549 mutex_unlock(&swapon_mutex
);
2550 atomic_inc(&proc_poll_event
);
2551 wake_up_interruptible(&proc_poll_wait
);
2553 if (S_ISREG(inode
->i_mode
))
2554 inode
->i_flags
|= S_SWAPFILE
;
2558 free_percpu(p
->percpu_cluster
);
2559 p
->percpu_cluster
= NULL
;
2560 if (inode
&& S_ISBLK(inode
->i_mode
) && p
->bdev
) {
2561 set_blocksize(p
->bdev
, p
->old_block_size
);
2562 blkdev_put(p
->bdev
, FMODE_READ
| FMODE_WRITE
| FMODE_EXCL
);
2564 destroy_swap_extents(p
);
2565 swap_cgroup_swapoff(p
->type
);
2566 spin_lock(&swap_lock
);
2567 p
->swap_file
= NULL
;
2569 spin_unlock(&swap_lock
);
2571 vfree(cluster_info
);
2573 if (inode
&& S_ISREG(inode
->i_mode
)) {
2574 mutex_unlock(&inode
->i_mutex
);
2577 filp_close(swap_file
, NULL
);
2580 if (page
&& !IS_ERR(page
)) {
2582 page_cache_release(page
);
2586 if (inode
&& S_ISREG(inode
->i_mode
))
2587 mutex_unlock(&inode
->i_mutex
);
2591 void si_swapinfo(struct sysinfo
*val
)
2594 unsigned long nr_to_be_unused
= 0;
2596 spin_lock(&swap_lock
);
2597 for (type
= 0; type
< nr_swapfiles
; type
++) {
2598 struct swap_info_struct
*si
= swap_info
[type
];
2600 if ((si
->flags
& SWP_USED
) && !(si
->flags
& SWP_WRITEOK
))
2601 nr_to_be_unused
+= si
->inuse_pages
;
2603 val
->freeswap
= atomic_long_read(&nr_swap_pages
) + nr_to_be_unused
;
2604 val
->totalswap
= total_swap_pages
+ nr_to_be_unused
;
2605 spin_unlock(&swap_lock
);
2609 * Verify that a swap entry is valid and increment its swap map count.
2611 * Returns error code in following case.
2613 * - swp_entry is invalid -> EINVAL
2614 * - swp_entry is migration entry -> EINVAL
2615 * - swap-cache reference is requested but there is already one. -> EEXIST
2616 * - swap-cache reference is requested but the entry is not used. -> ENOENT
2617 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
2619 static int __swap_duplicate(swp_entry_t entry
, unsigned char usage
)
2621 struct swap_info_struct
*p
;
2622 unsigned long offset
, type
;
2623 unsigned char count
;
2624 unsigned char has_cache
;
2627 if (non_swap_entry(entry
))
2630 type
= swp_type(entry
);
2631 if (type
>= nr_swapfiles
)
2633 p
= swap_info
[type
];
2634 offset
= swp_offset(entry
);
2636 spin_lock(&p
->lock
);
2637 if (unlikely(offset
>= p
->max
))
2640 count
= p
->swap_map
[offset
];
2643 * swapin_readahead() doesn't check if a swap entry is valid, so the
2644 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
2646 if (unlikely(swap_count(count
) == SWAP_MAP_BAD
)) {
2651 has_cache
= count
& SWAP_HAS_CACHE
;
2652 count
&= ~SWAP_HAS_CACHE
;
2655 if (usage
== SWAP_HAS_CACHE
) {
2657 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
2658 if (!has_cache
&& count
)
2659 has_cache
= SWAP_HAS_CACHE
;
2660 else if (has_cache
) /* someone else added cache */
2662 else /* no users remaining */
2665 } else if (count
|| has_cache
) {
2667 if ((count
& ~COUNT_CONTINUED
) < SWAP_MAP_MAX
)
2669 else if ((count
& ~COUNT_CONTINUED
) > SWAP_MAP_MAX
)
2671 else if (swap_count_continued(p
, offset
, count
))
2672 count
= COUNT_CONTINUED
;
2676 err
= -ENOENT
; /* unused swap entry */
2678 p
->swap_map
[offset
] = count
| has_cache
;
2681 spin_unlock(&p
->lock
);
2686 pr_err("swap_dup: %s%08lx\n", Bad_file
, entry
.val
);
2691 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
2692 * (in which case its reference count is never incremented).
2694 void swap_shmem_alloc(swp_entry_t entry
)
2696 __swap_duplicate(entry
, SWAP_MAP_SHMEM
);
2700 * Increase reference count of swap entry by 1.
2701 * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
2702 * but could not be atomically allocated. Returns 0, just as if it succeeded,
2703 * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
2704 * might occur if a page table entry has got corrupted.
2706 int swap_duplicate(swp_entry_t entry
)
2710 while (!err
&& __swap_duplicate(entry
, 1) == -ENOMEM
)
2711 err
= add_swap_count_continuation(entry
, GFP_ATOMIC
);
2716 * @entry: swap entry for which we allocate swap cache.
2718 * Called when allocating swap cache for existing swap entry,
2719 * This can return error codes. Returns 0 at success.
2720 * -EBUSY means there is a swap cache.
2721 * Note: return code is different from swap_duplicate().
2723 int swapcache_prepare(swp_entry_t entry
)
2725 return __swap_duplicate(entry
, SWAP_HAS_CACHE
);
2728 struct swap_info_struct
*page_swap_info(struct page
*page
)
2730 swp_entry_t swap
= { .val
= page_private(page
) };
2731 BUG_ON(!PageSwapCache(page
));
2732 return swap_info
[swp_type(swap
)];
2736 * out-of-line __page_file_ methods to avoid include hell.
2738 struct address_space
*__page_file_mapping(struct page
*page
)
2740 VM_BUG_ON_PAGE(!PageSwapCache(page
), page
);
2741 return page_swap_info(page
)->swap_file
->f_mapping
;
2743 EXPORT_SYMBOL_GPL(__page_file_mapping
);
2745 pgoff_t
__page_file_index(struct page
*page
)
2747 swp_entry_t swap
= { .val
= page_private(page
) };
2748 VM_BUG_ON_PAGE(!PageSwapCache(page
), page
);
2749 return swp_offset(swap
);
2751 EXPORT_SYMBOL_GPL(__page_file_index
);
2754 * add_swap_count_continuation - called when a swap count is duplicated
2755 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
2756 * page of the original vmalloc'ed swap_map, to hold the continuation count
2757 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
2758 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
2760 * These continuation pages are seldom referenced: the common paths all work
2761 * on the original swap_map, only referring to a continuation page when the
2762 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
2764 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
2765 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
2766 * can be called after dropping locks.
2768 int add_swap_count_continuation(swp_entry_t entry
, gfp_t gfp_mask
)
2770 struct swap_info_struct
*si
;
2773 struct page
*list_page
;
2775 unsigned char count
;
2778 * When debugging, it's easier to use __GFP_ZERO here; but it's better
2779 * for latency not to zero a page while GFP_ATOMIC and holding locks.
2781 page
= alloc_page(gfp_mask
| __GFP_HIGHMEM
);
2783 si
= swap_info_get(entry
);
2786 * An acceptable race has occurred since the failing
2787 * __swap_duplicate(): the swap entry has been freed,
2788 * perhaps even the whole swap_map cleared for swapoff.
2793 offset
= swp_offset(entry
);
2794 count
= si
->swap_map
[offset
] & ~SWAP_HAS_CACHE
;
2796 if ((count
& ~COUNT_CONTINUED
) != SWAP_MAP_MAX
) {
2798 * The higher the swap count, the more likely it is that tasks
2799 * will race to add swap count continuation: we need to avoid
2800 * over-provisioning.
2806 spin_unlock(&si
->lock
);
2811 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
2812 * no architecture is using highmem pages for kernel page tables: so it
2813 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
2815 head
= vmalloc_to_page(si
->swap_map
+ offset
);
2816 offset
&= ~PAGE_MASK
;
2819 * Page allocation does not initialize the page's lru field,
2820 * but it does always reset its private field.
2822 if (!page_private(head
)) {
2823 BUG_ON(count
& COUNT_CONTINUED
);
2824 INIT_LIST_HEAD(&head
->lru
);
2825 set_page_private(head
, SWP_CONTINUED
);
2826 si
->flags
|= SWP_CONTINUED
;
2829 list_for_each_entry(list_page
, &head
->lru
, lru
) {
2833 * If the previous map said no continuation, but we've found
2834 * a continuation page, free our allocation and use this one.
2836 if (!(count
& COUNT_CONTINUED
))
2839 map
= kmap_atomic(list_page
) + offset
;
2844 * If this continuation count now has some space in it,
2845 * free our allocation and use this one.
2847 if ((count
& ~COUNT_CONTINUED
) != SWAP_CONT_MAX
)
2851 list_add_tail(&page
->lru
, &head
->lru
);
2852 page
= NULL
; /* now it's attached, don't free it */
2854 spin_unlock(&si
->lock
);
2862 * swap_count_continued - when the original swap_map count is incremented
2863 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
2864 * into, carry if so, or else fail until a new continuation page is allocated;
2865 * when the original swap_map count is decremented from 0 with continuation,
2866 * borrow from the continuation and report whether it still holds more.
2867 * Called while __swap_duplicate() or swap_entry_free() holds swap_lock.
2869 static bool swap_count_continued(struct swap_info_struct
*si
,
2870 pgoff_t offset
, unsigned char count
)
2876 head
= vmalloc_to_page(si
->swap_map
+ offset
);
2877 if (page_private(head
) != SWP_CONTINUED
) {
2878 BUG_ON(count
& COUNT_CONTINUED
);
2879 return false; /* need to add count continuation */
2882 offset
&= ~PAGE_MASK
;
2883 page
= list_entry(head
->lru
.next
, struct page
, lru
);
2884 map
= kmap_atomic(page
) + offset
;
2886 if (count
== SWAP_MAP_MAX
) /* initial increment from swap_map */
2887 goto init_map
; /* jump over SWAP_CONT_MAX checks */
2889 if (count
== (SWAP_MAP_MAX
| COUNT_CONTINUED
)) { /* incrementing */
2891 * Think of how you add 1 to 999
2893 while (*map
== (SWAP_CONT_MAX
| COUNT_CONTINUED
)) {
2895 page
= list_entry(page
->lru
.next
, struct page
, lru
);
2896 BUG_ON(page
== head
);
2897 map
= kmap_atomic(page
) + offset
;
2899 if (*map
== SWAP_CONT_MAX
) {
2901 page
= list_entry(page
->lru
.next
, struct page
, lru
);
2903 return false; /* add count continuation */
2904 map
= kmap_atomic(page
) + offset
;
2905 init_map
: *map
= 0; /* we didn't zero the page */
2909 page
= list_entry(page
->lru
.prev
, struct page
, lru
);
2910 while (page
!= head
) {
2911 map
= kmap_atomic(page
) + offset
;
2912 *map
= COUNT_CONTINUED
;
2914 page
= list_entry(page
->lru
.prev
, struct page
, lru
);
2916 return true; /* incremented */
2918 } else { /* decrementing */
2920 * Think of how you subtract 1 from 1000
2922 BUG_ON(count
!= COUNT_CONTINUED
);
2923 while (*map
== COUNT_CONTINUED
) {
2925 page
= list_entry(page
->lru
.next
, struct page
, lru
);
2926 BUG_ON(page
== head
);
2927 map
= kmap_atomic(page
) + offset
;
2934 page
= list_entry(page
->lru
.prev
, struct page
, lru
);
2935 while (page
!= head
) {
2936 map
= kmap_atomic(page
) + offset
;
2937 *map
= SWAP_CONT_MAX
| count
;
2938 count
= COUNT_CONTINUED
;
2940 page
= list_entry(page
->lru
.prev
, struct page
, lru
);
2942 return count
== COUNT_CONTINUED
;
2947 * free_swap_count_continuations - swapoff free all the continuation pages
2948 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
2950 static void free_swap_count_continuations(struct swap_info_struct
*si
)
2954 for (offset
= 0; offset
< si
->max
; offset
+= PAGE_SIZE
) {
2956 head
= vmalloc_to_page(si
->swap_map
+ offset
);
2957 if (page_private(head
)) {
2958 struct list_head
*this, *next
;
2959 list_for_each_safe(this, next
, &head
->lru
) {
2961 page
= list_entry(this, struct page
, lru
);