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>
17 #include <linux/kdb.h>
18 #include <linux/kdbprivate.h>
19 #endif /* CONFIG_KDB */
20 #include <linux/namei.h>
21 #include <linux/shm.h>
22 #include <linux/blkdev.h>
23 #include <linux/writeback.h>
24 #include <linux/proc_fs.h>
25 #include <linux/seq_file.h>
26 #include <linux/init.h>
27 #include <linux/module.h>
28 #include <linux/rmap.h>
29 #include <linux/security.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mutex.h>
32 #include <linux/capability.h>
33 #include <linux/syscalls.h>
34 #include <linux/memcontrol.h>
36 #include <asm/pgtable.h>
37 #include <asm/tlbflush.h>
38 #include <linux/swapops.h>
40 DEFINE_SPINLOCK(swap_lock);
41 unsigned int nr_swapfiles;
42 long total_swap_pages;
43 static int swap_overflow;
45 static const char Bad_file[] = "Bad swap file entry ";
46 static const char Unused_file[] = "Unused swap file entry ";
47 static const char Bad_offset[] = "Bad swap offset entry ";
48 static const char Unused_offset[] = "Unused swap offset entry ";
50 struct swap_list_t swap_list = {-1, -1};
52 static struct swap_info_struct swap_info[MAX_SWAPFILES];
54 static DEFINE_MUTEX(swapon_mutex);
57 * We need this because the bdev->unplug_fn can sleep and we cannot
58 * hold swap_lock while calling the unplug_fn. And swap_lock
59 * cannot be turned into a mutex.
61 static DECLARE_RWSEM(swap_unplug_sem);
63 void swap_unplug_io_fn(struct backing_dev_info *unused_bdi, struct page *page)
67 down_read(&swap_unplug_sem);
68 entry.val = page_private(page);
69 if (PageSwapCache(page)) {
70 struct block_device *bdev = swap_info[swp_type(entry)].bdev;
71 struct backing_dev_info *bdi;
74 * If the page is removed from swapcache from under us (with a
75 * racy try_to_unuse/swapoff) we need an additional reference
76 * count to avoid reading garbage from page_private(page) above.
77 * If the WARN_ON triggers during a swapoff it maybe the race
78 * condition and it's harmless. However if it triggers without
79 * swapoff it signals a problem.
81 WARN_ON(page_count(page) <= 1);
83 bdi = bdev->bd_inode->i_mapping->backing_dev_info;
84 blk_run_backing_dev(bdi, page);
86 up_read(&swap_unplug_sem);
89 #define SWAPFILE_CLUSTER 256
90 #define LATENCY_LIMIT 256
92 static inline unsigned long scan_swap_map(struct swap_info_struct *si)
94 unsigned long offset, last_in_cluster;
95 int latency_ration = LATENCY_LIMIT;
98 * We try to cluster swap pages by allocating them sequentially
99 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
100 * way, however, we resort to first-free allocation, starting
101 * a new cluster. This prevents us from scattering swap pages
102 * all over the entire swap partition, so that we reduce
103 * overall disk seek times between swap pages. -- sct
104 * But we do now try to find an empty cluster. -Andrea
107 si->flags += SWP_SCANNING;
108 if (unlikely(!si->cluster_nr)) {
109 si->cluster_nr = SWAPFILE_CLUSTER - 1;
110 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER)
112 spin_unlock(&swap_lock);
114 offset = si->lowest_bit;
115 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
117 /* Locate the first empty (unaligned) cluster */
118 for (; last_in_cluster <= si->highest_bit; offset++) {
119 if (si->swap_map[offset])
120 last_in_cluster = offset + SWAPFILE_CLUSTER;
121 else if (offset == last_in_cluster) {
122 spin_lock(&swap_lock);
123 si->cluster_next = offset-SWAPFILE_CLUSTER+1;
126 if (unlikely(--latency_ration < 0)) {
128 latency_ration = LATENCY_LIMIT;
131 spin_lock(&swap_lock);
137 offset = si->cluster_next;
138 if (offset > si->highest_bit)
139 lowest: offset = si->lowest_bit;
140 checks: if (!(si->flags & SWP_WRITEOK))
142 if (!si->highest_bit)
144 if (!si->swap_map[offset]) {
145 if (offset == si->lowest_bit)
147 if (offset == si->highest_bit)
150 if (si->inuse_pages == si->pages) {
151 si->lowest_bit = si->max;
154 si->swap_map[offset] = 1;
155 si->cluster_next = offset + 1;
156 si->flags -= SWP_SCANNING;
160 spin_unlock(&swap_lock);
161 while (++offset <= si->highest_bit) {
162 if (!si->swap_map[offset]) {
163 spin_lock(&swap_lock);
166 if (unlikely(--latency_ration < 0)) {
168 latency_ration = LATENCY_LIMIT;
171 spin_lock(&swap_lock);
175 si->flags -= SWP_SCANNING;
179 swp_entry_t get_swap_page(void)
181 struct swap_info_struct *si;
186 spin_lock(&swap_lock);
187 if (nr_swap_pages <= 0)
191 for (type = swap_list.next; type >= 0 && wrapped < 2; type = next) {
192 si = swap_info + type;
195 (!wrapped && si->prio != swap_info[next].prio)) {
196 next = swap_list.head;
200 if (!si->highest_bit)
202 if (!(si->flags & SWP_WRITEOK))
205 swap_list.next = next;
206 offset = scan_swap_map(si);
208 spin_unlock(&swap_lock);
209 return swp_entry(type, offset);
211 next = swap_list.next;
216 spin_unlock(&swap_lock);
217 return (swp_entry_t) {0};
220 swp_entry_t get_swap_page_of_type(int type)
222 struct swap_info_struct *si;
225 spin_lock(&swap_lock);
226 si = swap_info + type;
227 if (si->flags & SWP_WRITEOK) {
229 offset = scan_swap_map(si);
231 spin_unlock(&swap_lock);
232 return swp_entry(type, offset);
236 spin_unlock(&swap_lock);
237 return (swp_entry_t) {0};
240 static struct swap_info_struct * swap_info_get(swp_entry_t entry)
242 struct swap_info_struct * p;
243 unsigned long offset, type;
247 type = swp_type(entry);
248 if (type >= nr_swapfiles)
250 p = & swap_info[type];
251 if (!(p->flags & SWP_USED))
253 offset = swp_offset(entry);
254 if (offset >= p->max)
256 if (!p->swap_map[offset])
258 spin_lock(&swap_lock);
262 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_offset, entry.val);
265 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_offset, entry.val);
268 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_file, entry.val);
271 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_file, entry.val);
276 static int swap_entry_free(struct swap_info_struct *p, unsigned long offset)
278 int count = p->swap_map[offset];
280 if (count < SWAP_MAP_MAX) {
282 p->swap_map[offset] = count;
284 if (offset < p->lowest_bit)
285 p->lowest_bit = offset;
286 if (offset > p->highest_bit)
287 p->highest_bit = offset;
288 if (p->prio > swap_info[swap_list.next].prio)
289 swap_list.next = p - swap_info;
298 * Caller has made sure that the swapdevice corresponding to entry
299 * is still around or has not been recycled.
301 void swap_free(swp_entry_t entry)
303 struct swap_info_struct * p;
305 p = swap_info_get(entry);
307 swap_entry_free(p, swp_offset(entry));
308 spin_unlock(&swap_lock);
313 * How many references to page are currently swapped out?
315 static inline int page_swapcount(struct page *page)
318 struct swap_info_struct *p;
321 entry.val = page_private(page);
322 p = swap_info_get(entry);
324 /* Subtract the 1 for the swap cache itself */
325 count = p->swap_map[swp_offset(entry)] - 1;
326 spin_unlock(&swap_lock);
332 * We can use this swap cache entry directly
333 * if there are no other references to it.
335 int can_share_swap_page(struct page *page)
339 BUG_ON(!PageLocked(page));
340 count = page_mapcount(page);
341 if (count <= 1 && PageSwapCache(page))
342 count += page_swapcount(page);
347 * Work out if there are any other processes sharing this
348 * swap cache page. Free it if you can. Return success.
350 int remove_exclusive_swap_page(struct page *page)
353 struct swap_info_struct * p;
356 BUG_ON(PagePrivate(page));
357 BUG_ON(!PageLocked(page));
359 if (!PageSwapCache(page))
361 if (PageWriteback(page))
363 if (page_count(page) != 2) /* 2: us + cache */
366 entry.val = page_private(page);
367 p = swap_info_get(entry);
371 /* Is the only swap cache user the cache itself? */
373 if (p->swap_map[swp_offset(entry)] == 1) {
374 /* Recheck the page count with the swapcache lock held.. */
375 write_lock_irq(&swapper_space.tree_lock);
376 if ((page_count(page) == 2) && !PageWriteback(page)) {
377 __delete_from_swap_cache(page);
381 write_unlock_irq(&swapper_space.tree_lock);
383 spin_unlock(&swap_lock);
387 page_cache_release(page);
394 * Free the swap entry like above, but also try to
395 * free the page cache entry if it is the last user.
397 void free_swap_and_cache(swp_entry_t entry)
399 struct swap_info_struct * p;
400 struct page *page = NULL;
402 if (is_migration_entry(entry))
405 p = swap_info_get(entry);
407 if (swap_entry_free(p, swp_offset(entry)) == 1) {
408 page = find_get_page(&swapper_space, entry.val);
409 if (page && unlikely(TestSetPageLocked(page))) {
410 page_cache_release(page);
414 spin_unlock(&swap_lock);
419 BUG_ON(PagePrivate(page));
420 one_user = (page_count(page) == 2);
421 /* Only cache user (+us), or swap space full? Free it! */
422 /* Also recheck PageSwapCache after page is locked (above) */
423 if (PageSwapCache(page) && !PageWriteback(page) &&
424 (one_user || vm_swap_full())) {
425 delete_from_swap_cache(page);
429 page_cache_release(page);
433 #ifdef CONFIG_HIBERNATION
435 * Find the swap type that corresponds to given device (if any).
437 * @offset - number of the PAGE_SIZE-sized block of the device, starting
438 * from 0, in which the swap header is expected to be located.
440 * This is needed for the suspend to disk (aka swsusp).
442 int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
444 struct block_device *bdev = NULL;
448 bdev = bdget(device);
450 spin_lock(&swap_lock);
451 for (i = 0; i < nr_swapfiles; i++) {
452 struct swap_info_struct *sis = swap_info + i;
454 if (!(sis->flags & SWP_WRITEOK))
461 spin_unlock(&swap_lock);
464 if (bdev == sis->bdev) {
465 struct swap_extent *se;
467 se = list_entry(sis->extent_list.next,
468 struct swap_extent, list);
469 if (se->start_block == offset) {
473 spin_unlock(&swap_lock);
479 spin_unlock(&swap_lock);
487 * Return either the total number of swap pages of given type, or the number
488 * of free pages of that type (depending on @free)
490 * This is needed for software suspend
492 unsigned int count_swap_pages(int type, int free)
496 if (type < nr_swapfiles) {
497 spin_lock(&swap_lock);
498 if (swap_info[type].flags & SWP_WRITEOK) {
499 n = swap_info[type].pages;
501 n -= swap_info[type].inuse_pages;
503 spin_unlock(&swap_lock);
510 * No need to decide whether this PTE shares the swap entry with others,
511 * just let do_wp_page work it out if a write is requested later - to
512 * force COW, vm_page_prot omits write permission from any private vma.
514 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
515 unsigned long addr, swp_entry_t entry, struct page *page)
521 if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
524 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
525 if (unlikely(!pte_same(*pte, swp_entry_to_pte(entry)))) {
527 mem_cgroup_uncharge_page(page);
532 inc_mm_counter(vma->vm_mm, anon_rss);
534 set_pte_at(vma->vm_mm, addr, pte,
535 pte_mkold(mk_pte(page, vma->vm_page_prot)));
536 page_add_anon_rmap(page, vma, addr);
539 * Move the page to the active list so it is not
540 * immediately swapped out again after swapon.
544 pte_unmap_unlock(pte, ptl);
548 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
549 unsigned long addr, unsigned long end,
550 swp_entry_t entry, struct page *page)
552 pte_t swp_pte = swp_entry_to_pte(entry);
557 * We don't actually need pte lock while scanning for swp_pte: since
558 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
559 * page table while we're scanning; though it could get zapped, and on
560 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
561 * of unmatched parts which look like swp_pte, so unuse_pte must
562 * recheck under pte lock. Scanning without pte lock lets it be
563 * preemptible whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
565 pte = pte_offset_map(pmd, addr);
568 * swapoff spends a _lot_ of time in this loop!
569 * Test inline before going to call unuse_pte.
571 if (unlikely(pte_same(*pte, swp_pte))) {
573 ret = unuse_pte(vma, pmd, addr, entry, page);
576 pte = pte_offset_map(pmd, addr);
578 } while (pte++, addr += PAGE_SIZE, addr != end);
584 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
585 unsigned long addr, unsigned long end,
586 swp_entry_t entry, struct page *page)
592 pmd = pmd_offset(pud, addr);
594 next = pmd_addr_end(addr, end);
595 if (pmd_none_or_clear_bad(pmd))
597 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
600 } while (pmd++, addr = next, addr != end);
604 static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
605 unsigned long addr, unsigned long end,
606 swp_entry_t entry, struct page *page)
612 pud = pud_offset(pgd, addr);
614 next = pud_addr_end(addr, end);
615 if (pud_none_or_clear_bad(pud))
617 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
620 } while (pud++, addr = next, addr != end);
624 static int unuse_vma(struct vm_area_struct *vma,
625 swp_entry_t entry, struct page *page)
628 unsigned long addr, end, next;
632 addr = page_address_in_vma(page, vma);
636 end = addr + PAGE_SIZE;
638 addr = vma->vm_start;
642 pgd = pgd_offset(vma->vm_mm, addr);
644 next = pgd_addr_end(addr, end);
645 if (pgd_none_or_clear_bad(pgd))
647 ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
650 } while (pgd++, addr = next, addr != end);
654 static int unuse_mm(struct mm_struct *mm,
655 swp_entry_t entry, struct page *page)
657 struct vm_area_struct *vma;
660 if (!down_read_trylock(&mm->mmap_sem)) {
662 * Activate page so shrink_cache is unlikely to unmap its
663 * ptes while lock is dropped, so swapoff can make progress.
667 down_read(&mm->mmap_sem);
670 for (vma = mm->mmap; vma; vma = vma->vm_next) {
671 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
674 up_read(&mm->mmap_sem);
675 return (ret < 0)? ret: 0;
679 * Scan swap_map from current position to next entry still in use.
680 * Recycle to start on reaching the end, returning 0 when empty.
682 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
685 unsigned int max = si->max;
686 unsigned int i = prev;
690 * No need for swap_lock here: we're just looking
691 * for whether an entry is in use, not modifying it; false
692 * hits are okay, and sys_swapoff() has already prevented new
693 * allocations from this area (while holding swap_lock).
702 * No entries in use at top of swap_map,
703 * loop back to start and recheck there.
709 count = si->swap_map[i];
710 if (count && count != SWAP_MAP_BAD)
717 * We completely avoid races by reading each swap page in advance,
718 * and then search for the process using it. All the necessary
719 * page table adjustments can then be made atomically.
721 static int try_to_unuse(unsigned int type)
723 struct swap_info_struct * si = &swap_info[type];
724 struct mm_struct *start_mm;
725 unsigned short *swap_map;
726 unsigned short swcount;
731 int reset_overflow = 0;
735 * When searching mms for an entry, a good strategy is to
736 * start at the first mm we freed the previous entry from
737 * (though actually we don't notice whether we or coincidence
738 * freed the entry). Initialize this start_mm with a hold.
740 * A simpler strategy would be to start at the last mm we
741 * freed the previous entry from; but that would take less
742 * advantage of mmlist ordering, which clusters forked mms
743 * together, child after parent. If we race with dup_mmap(), we
744 * prefer to resolve parent before child, lest we miss entries
745 * duplicated after we scanned child: using last mm would invert
746 * that. Though it's only a serious concern when an overflowed
747 * swap count is reset from SWAP_MAP_MAX, preventing a rescan.
750 atomic_inc(&init_mm.mm_users);
753 * Keep on scanning until all entries have gone. Usually,
754 * one pass through swap_map is enough, but not necessarily:
755 * there are races when an instance of an entry might be missed.
757 while ((i = find_next_to_unuse(si, i)) != 0) {
758 if (signal_pending(current)) {
764 * Get a page for the entry, using the existing swap
765 * cache page if there is one. Otherwise, get a clean
766 * page and read the swap into it.
768 swap_map = &si->swap_map[i];
769 entry = swp_entry(type, i);
770 page = read_swap_cache_async(entry,
771 GFP_HIGHUSER_MOVABLE, NULL, 0);
774 * Either swap_duplicate() failed because entry
775 * has been freed independently, and will not be
776 * reused since sys_swapoff() already disabled
777 * allocation from here, or alloc_page() failed.
786 * Don't hold on to start_mm if it looks like exiting.
788 if (atomic_read(&start_mm->mm_users) == 1) {
791 atomic_inc(&init_mm.mm_users);
795 * Wait for and lock page. When do_swap_page races with
796 * try_to_unuse, do_swap_page can handle the fault much
797 * faster than try_to_unuse can locate the entry. This
798 * apparently redundant "wait_on_page_locked" lets try_to_unuse
799 * defer to do_swap_page in such a case - in some tests,
800 * do_swap_page and try_to_unuse repeatedly compete.
802 wait_on_page_locked(page);
803 wait_on_page_writeback(page);
805 wait_on_page_writeback(page);
808 * Remove all references to entry.
809 * Whenever we reach init_mm, there's no address space
810 * to search, but use it as a reminder to search shmem.
815 if (start_mm == &init_mm)
816 shmem = shmem_unuse(entry, page);
818 retval = unuse_mm(start_mm, entry, page);
821 int set_start_mm = (*swap_map >= swcount);
822 struct list_head *p = &start_mm->mmlist;
823 struct mm_struct *new_start_mm = start_mm;
824 struct mm_struct *prev_mm = start_mm;
825 struct mm_struct *mm;
827 atomic_inc(&new_start_mm->mm_users);
828 atomic_inc(&prev_mm->mm_users);
829 spin_lock(&mmlist_lock);
830 while (*swap_map > 1 && !retval && !shmem &&
831 (p = p->next) != &start_mm->mmlist) {
832 mm = list_entry(p, struct mm_struct, mmlist);
833 if (!atomic_inc_not_zero(&mm->mm_users))
835 spin_unlock(&mmlist_lock);
844 else if (mm == &init_mm) {
846 shmem = shmem_unuse(entry, page);
848 retval = unuse_mm(mm, entry, page);
849 if (set_start_mm && *swap_map < swcount) {
851 atomic_inc(&mm->mm_users);
855 spin_lock(&mmlist_lock);
857 spin_unlock(&mmlist_lock);
860 start_mm = new_start_mm;
863 /* page has already been unlocked and released */
871 page_cache_release(page);
876 * How could swap count reach 0x7fff when the maximum
877 * pid is 0x7fff, and there's no way to repeat a swap
878 * page within an mm (except in shmem, where it's the
879 * shared object which takes the reference count)?
880 * We believe SWAP_MAP_MAX cannot occur in Linux 2.4.
882 * If that's wrong, then we should worry more about
883 * exit_mmap() and do_munmap() cases described above:
884 * we might be resetting SWAP_MAP_MAX too early here.
885 * We know "Undead"s can happen, they're okay, so don't
886 * report them; but do report if we reset SWAP_MAP_MAX.
888 if (*swap_map == SWAP_MAP_MAX) {
889 spin_lock(&swap_lock);
891 spin_unlock(&swap_lock);
896 * If a reference remains (rare), we would like to leave
897 * the page in the swap cache; but try_to_unmap could
898 * then re-duplicate the entry once we drop page lock,
899 * so we might loop indefinitely; also, that page could
900 * not be swapped out to other storage meanwhile. So:
901 * delete from cache even if there's another reference,
902 * after ensuring that the data has been saved to disk -
903 * since if the reference remains (rarer), it will be
904 * read from disk into another page. Splitting into two
905 * pages would be incorrect if swap supported "shared
906 * private" pages, but they are handled by tmpfs files.
908 if ((*swap_map > 1) && PageDirty(page) && PageSwapCache(page)) {
909 struct writeback_control wbc = {
910 .sync_mode = WB_SYNC_NONE,
913 swap_writepage(page, &wbc);
915 wait_on_page_writeback(page);
917 if (PageSwapCache(page))
918 delete_from_swap_cache(page);
921 * So we could skip searching mms once swap count went
922 * to 1, we did not mark any present ptes as dirty: must
923 * mark page dirty so shrink_page_list will preserve it.
927 page_cache_release(page);
930 * Make sure that we aren't completely killing
931 * interactive performance.
937 if (reset_overflow) {
938 printk(KERN_WARNING "swapoff: cleared swap entry overflow\n");
945 * After a successful try_to_unuse, if no swap is now in use, we know
946 * we can empty the mmlist. swap_lock must be held on entry and exit.
947 * Note that mmlist_lock nests inside swap_lock, and an mm must be
948 * added to the mmlist just after page_duplicate - before would be racy.
950 static void drain_mmlist(void)
952 struct list_head *p, *next;
955 for (i = 0; i < nr_swapfiles; i++)
956 if (swap_info[i].inuse_pages)
958 spin_lock(&mmlist_lock);
959 list_for_each_safe(p, next, &init_mm.mmlist)
961 spin_unlock(&mmlist_lock);
965 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
966 * corresponds to page offset `offset'.
968 sector_t map_swap_page(struct swap_info_struct *sis, pgoff_t offset)
970 struct swap_extent *se = sis->curr_swap_extent;
971 struct swap_extent *start_se = se;
974 struct list_head *lh;
976 if (se->start_page <= offset &&
977 offset < (se->start_page + se->nr_pages)) {
978 return se->start_block + (offset - se->start_page);
981 if (lh == &sis->extent_list)
983 se = list_entry(lh, struct swap_extent, list);
984 sis->curr_swap_extent = se;
985 BUG_ON(se == start_se); /* It *must* be present */
989 #ifdef CONFIG_HIBERNATION
991 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
992 * corresponding to given index in swap_info (swap type).
994 sector_t swapdev_block(int swap_type, pgoff_t offset)
996 struct swap_info_struct *sis;
998 if (swap_type >= nr_swapfiles)
1001 sis = swap_info + swap_type;
1002 return (sis->flags & SWP_WRITEOK) ? map_swap_page(sis, offset) : 0;
1004 #endif /* CONFIG_HIBERNATION */
1007 * Free all of a swapdev's extent information
1009 static void destroy_swap_extents(struct swap_info_struct *sis)
1011 while (!list_empty(&sis->extent_list)) {
1012 struct swap_extent *se;
1014 se = list_entry(sis->extent_list.next,
1015 struct swap_extent, list);
1016 list_del(&se->list);
1022 * Add a block range (and the corresponding page range) into this swapdev's
1023 * extent list. The extent list is kept sorted in page order.
1025 * This function rather assumes that it is called in ascending page order.
1028 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
1029 unsigned long nr_pages, sector_t start_block)
1031 struct swap_extent *se;
1032 struct swap_extent *new_se;
1033 struct list_head *lh;
1035 lh = sis->extent_list.prev; /* The highest page extent */
1036 if (lh != &sis->extent_list) {
1037 se = list_entry(lh, struct swap_extent, list);
1038 BUG_ON(se->start_page + se->nr_pages != start_page);
1039 if (se->start_block + se->nr_pages == start_block) {
1041 se->nr_pages += nr_pages;
1047 * No merge. Insert a new extent, preserving ordering.
1049 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
1052 new_se->start_page = start_page;
1053 new_se->nr_pages = nr_pages;
1054 new_se->start_block = start_block;
1056 list_add_tail(&new_se->list, &sis->extent_list);
1061 * A `swap extent' is a simple thing which maps a contiguous range of pages
1062 * onto a contiguous range of disk blocks. An ordered list of swap extents
1063 * is built at swapon time and is then used at swap_writepage/swap_readpage
1064 * time for locating where on disk a page belongs.
1066 * If the swapfile is an S_ISBLK block device, a single extent is installed.
1067 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1068 * swap files identically.
1070 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1071 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
1072 * swapfiles are handled *identically* after swapon time.
1074 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1075 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
1076 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1077 * requirements, they are simply tossed out - we will never use those blocks
1080 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1081 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1082 * which will scribble on the fs.
1084 * The amount of disk space which a single swap extent represents varies.
1085 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
1086 * extents in the list. To avoid much list walking, we cache the previous
1087 * search location in `curr_swap_extent', and start new searches from there.
1088 * This is extremely effective. The average number of iterations in
1089 * map_swap_page() has been measured at about 0.3 per page. - akpm.
1091 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1093 struct inode *inode;
1094 unsigned blocks_per_page;
1095 unsigned long page_no;
1097 sector_t probe_block;
1098 sector_t last_block;
1099 sector_t lowest_block = -1;
1100 sector_t highest_block = 0;
1104 inode = sis->swap_file->f_mapping->host;
1105 if (S_ISBLK(inode->i_mode)) {
1106 ret = add_swap_extent(sis, 0, sis->max, 0);
1111 blkbits = inode->i_blkbits;
1112 blocks_per_page = PAGE_SIZE >> blkbits;
1115 * Map all the blocks into the extent list. This code doesn't try
1120 last_block = i_size_read(inode) >> blkbits;
1121 while ((probe_block + blocks_per_page) <= last_block &&
1122 page_no < sis->max) {
1123 unsigned block_in_page;
1124 sector_t first_block;
1126 first_block = bmap(inode, probe_block);
1127 if (first_block == 0)
1131 * It must be PAGE_SIZE aligned on-disk
1133 if (first_block & (blocks_per_page - 1)) {
1138 for (block_in_page = 1; block_in_page < blocks_per_page;
1142 block = bmap(inode, probe_block + block_in_page);
1145 if (block != first_block + block_in_page) {
1152 first_block >>= (PAGE_SHIFT - blkbits);
1153 if (page_no) { /* exclude the header page */
1154 if (first_block < lowest_block)
1155 lowest_block = first_block;
1156 if (first_block > highest_block)
1157 highest_block = first_block;
1161 * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
1163 ret = add_swap_extent(sis, page_no, 1, first_block);
1168 probe_block += blocks_per_page;
1173 *span = 1 + highest_block - lowest_block;
1175 page_no = 1; /* force Empty message */
1177 sis->pages = page_no - 1;
1178 sis->highest_bit = page_no - 1;
1180 sis->curr_swap_extent = list_entry(sis->extent_list.prev,
1181 struct swap_extent, list);
1184 printk(KERN_ERR "swapon: swapfile has holes\n");
1190 #if 0 /* We don't need this yet */
1191 #include <linux/backing-dev.h>
1192 int page_queue_congested(struct page *page)
1194 struct backing_dev_info *bdi;
1196 BUG_ON(!PageLocked(page)); /* It pins the swap_info_struct */
1198 if (PageSwapCache(page)) {
1199 swp_entry_t entry = { .val = page_private(page) };
1200 struct swap_info_struct *sis;
1202 sis = get_swap_info_struct(swp_type(entry));
1203 bdi = sis->bdev->bd_inode->i_mapping->backing_dev_info;
1205 bdi = page->mapping->backing_dev_info;
1206 return bdi_write_congested(bdi);
1210 asmlinkage long sys_swapoff(const char __user * specialfile)
1212 struct swap_info_struct * p = NULL;
1213 unsigned short *swap_map;
1214 struct file *swap_file, *victim;
1215 struct address_space *mapping;
1216 struct inode *inode;
1221 if (!capable(CAP_SYS_ADMIN))
1224 pathname = getname(specialfile);
1225 err = PTR_ERR(pathname);
1226 if (IS_ERR(pathname))
1229 victim = filp_open(pathname, O_RDWR|O_LARGEFILE, 0);
1231 err = PTR_ERR(victim);
1235 mapping = victim->f_mapping;
1237 spin_lock(&swap_lock);
1238 for (type = swap_list.head; type >= 0; type = swap_info[type].next) {
1239 p = swap_info + type;
1240 if ((p->flags & SWP_ACTIVE) == SWP_ACTIVE) {
1241 if (p->swap_file->f_mapping == mapping)
1248 spin_unlock(&swap_lock);
1251 if (!security_vm_enough_memory(p->pages))
1252 vm_unacct_memory(p->pages);
1255 spin_unlock(&swap_lock);
1259 swap_list.head = p->next;
1261 swap_info[prev].next = p->next;
1263 if (type == swap_list.next) {
1264 /* just pick something that's safe... */
1265 swap_list.next = swap_list.head;
1267 nr_swap_pages -= p->pages;
1268 total_swap_pages -= p->pages;
1269 p->flags &= ~SWP_WRITEOK;
1270 spin_unlock(&swap_lock);
1272 current->flags |= PF_SWAPOFF;
1273 err = try_to_unuse(type);
1274 current->flags &= ~PF_SWAPOFF;
1277 /* re-insert swap space back into swap_list */
1278 spin_lock(&swap_lock);
1279 for (prev = -1, i = swap_list.head; i >= 0; prev = i, i = swap_info[i].next)
1280 if (p->prio >= swap_info[i].prio)
1284 swap_list.head = swap_list.next = p - swap_info;
1286 swap_info[prev].next = p - swap_info;
1287 nr_swap_pages += p->pages;
1288 total_swap_pages += p->pages;
1289 p->flags |= SWP_WRITEOK;
1290 spin_unlock(&swap_lock);
1294 /* wait for any unplug function to finish */
1295 down_write(&swap_unplug_sem);
1296 up_write(&swap_unplug_sem);
1298 destroy_swap_extents(p);
1299 mutex_lock(&swapon_mutex);
1300 spin_lock(&swap_lock);
1303 /* wait for anyone still in scan_swap_map */
1304 p->highest_bit = 0; /* cuts scans short */
1305 while (p->flags >= SWP_SCANNING) {
1306 spin_unlock(&swap_lock);
1307 schedule_timeout_uninterruptible(1);
1308 spin_lock(&swap_lock);
1311 swap_file = p->swap_file;
1312 p->swap_file = NULL;
1314 swap_map = p->swap_map;
1317 spin_unlock(&swap_lock);
1318 mutex_unlock(&swapon_mutex);
1320 inode = mapping->host;
1321 if (S_ISBLK(inode->i_mode)) {
1322 struct block_device *bdev = I_BDEV(inode);
1323 set_blocksize(bdev, p->old_block_size);
1326 mutex_lock(&inode->i_mutex);
1327 inode->i_flags &= ~S_SWAPFILE;
1328 mutex_unlock(&inode->i_mutex);
1330 filp_close(swap_file, NULL);
1334 filp_close(victim, NULL);
1339 #ifdef CONFIG_PROC_FS
1341 static void *swap_start(struct seq_file *swap, loff_t *pos)
1343 struct swap_info_struct *ptr = swap_info;
1347 mutex_lock(&swapon_mutex);
1350 return SEQ_START_TOKEN;
1352 for (i = 0; i < nr_swapfiles; i++, ptr++) {
1353 if (!(ptr->flags & SWP_USED) || !ptr->swap_map)
1362 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
1364 struct swap_info_struct *ptr;
1365 struct swap_info_struct *endptr = swap_info + nr_swapfiles;
1367 if (v == SEQ_START_TOKEN)
1374 for (; ptr < endptr; ptr++) {
1375 if (!(ptr->flags & SWP_USED) || !ptr->swap_map)
1384 static void swap_stop(struct seq_file *swap, void *v)
1386 mutex_unlock(&swapon_mutex);
1389 static int swap_show(struct seq_file *swap, void *v)
1391 struct swap_info_struct *ptr = v;
1395 if (ptr == SEQ_START_TOKEN) {
1396 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
1400 file = ptr->swap_file;
1401 len = seq_path(swap, &file->f_path, " \t\n\\");
1402 seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
1403 len < 40 ? 40 - len : 1, " ",
1404 S_ISBLK(file->f_path.dentry->d_inode->i_mode) ?
1405 "partition" : "file\t",
1406 ptr->pages << (PAGE_SHIFT - 10),
1407 ptr->inuse_pages << (PAGE_SHIFT - 10),
1412 static const struct seq_operations swaps_op = {
1413 .start = swap_start,
1419 static int swaps_open(struct inode *inode, struct file *file)
1421 return seq_open(file, &swaps_op);
1424 static const struct file_operations proc_swaps_operations = {
1427 .llseek = seq_lseek,
1428 .release = seq_release,
1431 static int __init procswaps_init(void)
1433 struct proc_dir_entry *entry;
1435 entry = create_proc_entry("swaps", 0, NULL);
1437 entry->proc_fops = &proc_swaps_operations;
1440 __initcall(procswaps_init);
1441 #endif /* CONFIG_PROC_FS */
1444 * Written 01/25/92 by Simmule Turner, heavily changed by Linus.
1446 * The swapon system call
1448 asmlinkage long sys_swapon(const char __user * specialfile, int swap_flags)
1450 struct swap_info_struct * p;
1452 struct block_device *bdev = NULL;
1453 struct file *swap_file = NULL;
1454 struct address_space *mapping;
1458 static int least_priority;
1459 union swap_header *swap_header = NULL;
1460 int swap_header_version;
1461 unsigned int nr_good_pages = 0;
1464 unsigned long maxpages = 1;
1466 unsigned short *swap_map;
1467 struct page *page = NULL;
1468 struct inode *inode = NULL;
1471 if (!capable(CAP_SYS_ADMIN))
1473 spin_lock(&swap_lock);
1475 for (type = 0 ; type < nr_swapfiles ; type++,p++)
1476 if (!(p->flags & SWP_USED))
1479 if (type >= MAX_SWAPFILES) {
1480 spin_unlock(&swap_lock);
1483 if (type >= nr_swapfiles)
1484 nr_swapfiles = type+1;
1485 INIT_LIST_HEAD(&p->extent_list);
1486 p->flags = SWP_USED;
1487 p->swap_file = NULL;
1488 p->old_block_size = 0;
1495 if (swap_flags & SWAP_FLAG_PREFER) {
1497 (swap_flags & SWAP_FLAG_PRIO_MASK)>>SWAP_FLAG_PRIO_SHIFT;
1499 p->prio = --least_priority;
1501 spin_unlock(&swap_lock);
1502 name = getname(specialfile);
1503 error = PTR_ERR(name);
1508 swap_file = filp_open(name, O_RDWR|O_LARGEFILE, 0);
1509 error = PTR_ERR(swap_file);
1510 if (IS_ERR(swap_file)) {
1515 p->swap_file = swap_file;
1516 mapping = swap_file->f_mapping;
1517 inode = mapping->host;
1520 for (i = 0; i < nr_swapfiles; i++) {
1521 struct swap_info_struct *q = &swap_info[i];
1523 if (i == type || !q->swap_file)
1525 if (mapping == q->swap_file->f_mapping)
1530 if (S_ISBLK(inode->i_mode)) {
1531 bdev = I_BDEV(inode);
1532 error = bd_claim(bdev, sys_swapon);
1538 p->old_block_size = block_size(bdev);
1539 error = set_blocksize(bdev, PAGE_SIZE);
1543 } else if (S_ISREG(inode->i_mode)) {
1544 p->bdev = inode->i_sb->s_bdev;
1545 mutex_lock(&inode->i_mutex);
1547 if (IS_SWAPFILE(inode)) {
1555 swapfilesize = i_size_read(inode) >> PAGE_SHIFT;
1558 * Read the swap header.
1560 if (!mapping->a_ops->readpage) {
1564 page = read_mapping_page(mapping, 0, swap_file);
1566 error = PTR_ERR(page);
1570 swap_header = page_address(page);
1572 if (!memcmp("SWAP-SPACE",swap_header->magic.magic,10))
1573 swap_header_version = 1;
1574 else if (!memcmp("SWAPSPACE2",swap_header->magic.magic,10))
1575 swap_header_version = 2;
1577 printk(KERN_ERR "Unable to find swap-space signature\n");
1582 switch (swap_header_version) {
1584 printk(KERN_ERR "version 0 swap is no longer supported. "
1585 "Use mkswap -v1 %s\n", name);
1589 /* Check the swap header's sub-version and the size of
1590 the swap file and bad block lists */
1591 if (swap_header->info.version != 1) {
1593 "Unable to handle swap header version %d\n",
1594 swap_header->info.version);
1600 p->cluster_next = 1;
1603 * Find out how many pages are allowed for a single swap
1604 * device. There are two limiting factors: 1) the number of
1605 * bits for the swap offset in the swp_entry_t type and
1606 * 2) the number of bits in the a swap pte as defined by
1607 * the different architectures. In order to find the
1608 * largest possible bit mask a swap entry with swap type 0
1609 * and swap offset ~0UL is created, encoded to a swap pte,
1610 * decoded to a swp_entry_t again and finally the swap
1611 * offset is extracted. This will mask all the bits from
1612 * the initial ~0UL mask that can't be encoded in either
1613 * the swp_entry_t or the architecture definition of a
1616 maxpages = swp_offset(pte_to_swp_entry(swp_entry_to_pte(swp_entry(0,~0UL)))) - 1;
1617 if (maxpages > swap_header->info.last_page)
1618 maxpages = swap_header->info.last_page;
1619 p->highest_bit = maxpages - 1;
1624 if (swapfilesize && maxpages > swapfilesize) {
1626 "Swap area shorter than signature indicates\n");
1629 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
1631 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
1634 /* OK, set up the swap map and apply the bad block list */
1635 if (!(p->swap_map = vmalloc(maxpages * sizeof(short)))) {
1641 memset(p->swap_map, 0, maxpages * sizeof(short));
1642 for (i = 0; i < swap_header->info.nr_badpages; i++) {
1643 int page_nr = swap_header->info.badpages[i];
1644 if (page_nr <= 0 || page_nr >= swap_header->info.last_page)
1647 p->swap_map[page_nr] = SWAP_MAP_BAD;
1649 nr_good_pages = swap_header->info.last_page -
1650 swap_header->info.nr_badpages -
1651 1 /* header page */;
1656 if (nr_good_pages) {
1657 p->swap_map[0] = SWAP_MAP_BAD;
1659 p->pages = nr_good_pages;
1660 nr_extents = setup_swap_extents(p, &span);
1661 if (nr_extents < 0) {
1665 nr_good_pages = p->pages;
1667 if (!nr_good_pages) {
1668 printk(KERN_WARNING "Empty swap-file\n");
1673 mutex_lock(&swapon_mutex);
1674 spin_lock(&swap_lock);
1675 p->flags = SWP_ACTIVE;
1676 nr_swap_pages += nr_good_pages;
1677 total_swap_pages += nr_good_pages;
1679 printk(KERN_INFO "Adding %uk swap on %s. "
1680 "Priority:%d extents:%d across:%lluk\n",
1681 nr_good_pages<<(PAGE_SHIFT-10), name, p->prio,
1682 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10));
1684 /* insert swap space into swap_list: */
1686 for (i = swap_list.head; i >= 0; i = swap_info[i].next) {
1687 if (p->prio >= swap_info[i].prio) {
1694 swap_list.head = swap_list.next = p - swap_info;
1696 swap_info[prev].next = p - swap_info;
1698 spin_unlock(&swap_lock);
1699 mutex_unlock(&swapon_mutex);
1704 set_blocksize(bdev, p->old_block_size);
1707 destroy_swap_extents(p);
1709 spin_lock(&swap_lock);
1710 swap_map = p->swap_map;
1711 p->swap_file = NULL;
1714 if (!(swap_flags & SWAP_FLAG_PREFER))
1716 spin_unlock(&swap_lock);
1719 filp_close(swap_file, NULL);
1721 if (page && !IS_ERR(page)) {
1723 page_cache_release(page);
1729 inode->i_flags |= S_SWAPFILE;
1730 mutex_unlock(&inode->i_mutex);
1735 void si_swapinfo(struct sysinfo *val)
1738 unsigned long nr_to_be_unused = 0;
1740 spin_lock(&swap_lock);
1741 for (i = 0; i < nr_swapfiles; i++) {
1742 if (!(swap_info[i].flags & SWP_USED) ||
1743 (swap_info[i].flags & SWP_WRITEOK))
1745 nr_to_be_unused += swap_info[i].inuse_pages;
1747 val->freeswap = nr_swap_pages + nr_to_be_unused;
1748 val->totalswap = total_swap_pages + nr_to_be_unused;
1749 spin_unlock(&swap_lock);
1753 /* Like si_swapinfo() but without the locks */
1754 void kdb_si_swapinfo(struct sysinfo *val)
1757 unsigned long nr_to_be_unused = 0;
1759 for (i = 0; i < nr_swapfiles; i++) {
1760 if (!(swap_info[i].flags & SWP_USED) ||
1761 (swap_info[i].flags & SWP_WRITEOK))
1763 nr_to_be_unused += swap_info[i].inuse_pages;
1765 val->freeswap = nr_swap_pages + nr_to_be_unused;
1766 val->totalswap = total_swap_pages + nr_to_be_unused;
1768 #endif /* CONFIG_KDB */
1771 * Verify that a swap entry is valid and increment its swap map count.
1773 * Note: if swap_map[] reaches SWAP_MAP_MAX the entries are treated as
1774 * "permanent", but will be reclaimed by the next swapoff.
1776 int swap_duplicate(swp_entry_t entry)
1778 struct swap_info_struct * p;
1779 unsigned long offset, type;
1782 if (is_migration_entry(entry))
1785 type = swp_type(entry);
1786 if (type >= nr_swapfiles)
1788 p = type + swap_info;
1789 offset = swp_offset(entry);
1791 spin_lock(&swap_lock);
1792 if (offset < p->max && p->swap_map[offset]) {
1793 if (p->swap_map[offset] < SWAP_MAP_MAX - 1) {
1794 p->swap_map[offset]++;
1796 } else if (p->swap_map[offset] <= SWAP_MAP_MAX) {
1797 if (swap_overflow++ < 5)
1798 printk(KERN_WARNING "swap_dup: swap entry overflow\n");
1799 p->swap_map[offset] = SWAP_MAP_MAX;
1803 spin_unlock(&swap_lock);
1808 printk(KERN_ERR "swap_dup: %s%08lx\n", Bad_file, entry.val);
1812 struct swap_info_struct *
1813 get_swap_info_struct(unsigned type)
1815 return &swap_info[type];
1819 * swap_lock prevents swap_map being freed. Don't grab an extra
1820 * reference on the swaphandle, it doesn't matter if it becomes unused.
1822 int valid_swaphandles(swp_entry_t entry, unsigned long *offset)
1824 struct swap_info_struct *si;
1825 int our_page_cluster = page_cluster;
1826 pgoff_t target, toff;
1830 if (!our_page_cluster) /* no readahead */
1833 si = &swap_info[swp_type(entry)];
1834 target = swp_offset(entry);
1835 base = (target >> our_page_cluster) << our_page_cluster;
1836 end = base + (1 << our_page_cluster);
1837 if (!base) /* first page is swap header */
1840 spin_lock(&swap_lock);
1841 if (end > si->max) /* don't go beyond end of map */
1844 /* Count contiguous allocated slots above our target */
1845 for (toff = target; ++toff < end; nr_pages++) {
1846 /* Don't read in free or bad pages */
1847 if (!si->swap_map[toff])
1849 if (si->swap_map[toff] == SWAP_MAP_BAD)
1852 /* Count contiguous allocated slots below our target */
1853 for (toff = target; --toff >= base; nr_pages++) {
1854 /* Don't read in free or bad pages */
1855 if (!si->swap_map[toff])
1857 if (si->swap_map[toff] == SWAP_MAP_BAD)
1860 spin_unlock(&swap_lock);
1863 * Indicate starting offset, and return number of pages to get:
1864 * if only 1, say 0, since there's then no readahead to be done.
1867 return nr_pages? ++nr_pages: 0;