4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie
8 #include <linux/config.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/shm.h>
18 #include <linux/blkdev.h>
19 #include <linux/writeback.h>
20 #include <linux/proc_fs.h>
21 #include <linux/seq_file.h>
22 #include <linux/init.h>
23 #include <linux/module.h>
24 #include <linux/rmap.h>
25 #include <linux/security.h>
26 #include <linux/backing-dev.h>
28 #include <asm/pgtable.h>
29 #include <asm/tlbflush.h>
30 #include <linux/swapops.h>
32 spinlock_t swaplock = SPIN_LOCK_UNLOCKED;
33 unsigned int nr_swapfiles;
35 static int swap_overflow;
37 EXPORT_SYMBOL(total_swap_pages);
39 static const char Bad_file[] = "Bad swap file entry ";
40 static const char Unused_file[] = "Unused swap file entry ";
41 static const char Bad_offset[] = "Bad swap offset entry ";
42 static const char Unused_offset[] = "Unused swap offset entry ";
44 struct swap_list_t swap_list = {-1, -1};
46 struct swap_info_struct swap_info[MAX_SWAPFILES];
48 static DECLARE_MUTEX(swapon_sem);
51 * Array of backing blockdevs, for swap_unplug_fn. We need this because the
52 * bdev->unplug_fn can sleep and we cannot hold swap_list_lock while calling
53 * the unplug_fn. And swap_list_lock cannot be turned into a semaphore.
55 static DECLARE_MUTEX(swap_bdevs_sem);
56 static struct block_device *swap_bdevs[MAX_SWAPFILES];
58 #define SWAPFILE_CLUSTER 256
61 * Caller holds swap_bdevs_sem
63 static void install_swap_bdev(struct block_device *bdev)
67 for (i = 0; i < MAX_SWAPFILES; i++) {
68 if (swap_bdevs[i] == NULL) {
76 static void remove_swap_bdev(struct block_device *bdev)
80 for (i = 0; i < MAX_SWAPFILES; i++) {
81 if (swap_bdevs[i] == bdev) {
82 memcpy(&swap_bdevs[i], &swap_bdevs[i + 1],
83 (MAX_SWAPFILES - i - 1) * sizeof(*swap_bdevs));
84 swap_bdevs[MAX_SWAPFILES - 1] = NULL;
92 * Unlike a standard unplug_io_fn, swap_unplug_io_fn is never called
93 * through swap's backing_dev_info (which is only used by shrink_list),
94 * but directly from sync_page when PageSwapCache: and takes the page
95 * as argument, so that it can find the right device from swp_entry_t.
97 void swap_unplug_io_fn(struct page *page)
101 down(&swap_bdevs_sem);
102 entry.val = page->private;
103 if (PageSwapCache(page)) {
104 struct block_device *bdev = swap_bdevs[swp_type(entry)];
105 struct backing_dev_info *bdi;
108 bdi = bdev->bd_inode->i_mapping->backing_dev_info;
109 (*bdi->unplug_io_fn)(bdi);
115 static inline int scan_swap_map(struct swap_info_struct *si)
117 unsigned long offset;
119 * We try to cluster swap pages by allocating them
120 * sequentially in swap. Once we've allocated
121 * SWAPFILE_CLUSTER pages this way, however, we resort to
122 * first-free allocation, starting a new cluster. This
123 * prevents us from scattering swap pages all over the entire
124 * swap partition, so that we reduce overall disk seek times
125 * between swap pages. -- sct */
126 if (si->cluster_nr) {
127 while (si->cluster_next <= si->highest_bit) {
128 offset = si->cluster_next++;
129 if (si->swap_map[offset])
135 si->cluster_nr = SWAPFILE_CLUSTER;
137 /* try to find an empty (even not aligned) cluster. */
138 offset = si->lowest_bit;
140 if (offset+SWAPFILE_CLUSTER-1 <= si->highest_bit)
143 for (nr = offset; nr < offset+SWAPFILE_CLUSTER; nr++)
144 if (si->swap_map[nr])
147 goto check_next_cluster;
149 /* We found a completly empty cluster, so start
154 /* No luck, so now go finegrined as usual. -Andrea */
155 for (offset = si->lowest_bit; offset <= si->highest_bit ; offset++) {
156 if (si->swap_map[offset])
158 si->lowest_bit = offset+1;
160 if (offset == si->lowest_bit)
162 if (offset == si->highest_bit)
164 if (si->lowest_bit > si->highest_bit) {
165 si->lowest_bit = si->max;
168 si->swap_map[offset] = 1;
171 si->cluster_next = offset+1;
174 si->lowest_bit = si->max;
179 swp_entry_t get_swap_page(void)
181 struct swap_info_struct * p;
182 unsigned long offset;
184 int type, wrapped = 0;
186 entry.val = 0; /* Out of memory */
188 type = swap_list.next;
191 if (nr_swap_pages <= 0)
195 p = &swap_info[type];
196 if ((p->flags & SWP_ACTIVE) == SWP_ACTIVE) {
198 offset = scan_swap_map(p);
199 swap_device_unlock(p);
201 entry = swp_entry(type,offset);
202 type = swap_info[type].next;
204 p->prio != swap_info[type].prio) {
205 swap_list.next = swap_list.head;
207 swap_list.next = type;
214 if (type < 0 || p->prio != swap_info[type].prio) {
215 type = swap_list.head;
220 goto out; /* out of swap space */
227 static struct swap_info_struct * swap_info_get(swp_entry_t entry)
229 struct swap_info_struct * p;
230 unsigned long offset, type;
234 type = swp_type(entry);
235 if (type >= nr_swapfiles)
237 p = & swap_info[type];
238 if (!(p->flags & SWP_USED))
240 offset = swp_offset(entry);
241 if (offset >= p->max)
243 if (!p->swap_map[offset])
246 if (p->prio > swap_info[swap_list.next].prio)
247 swap_list.next = type;
252 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_offset, entry.val);
255 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_offset, entry.val);
258 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_file, entry.val);
261 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_file, entry.val);
266 static void swap_info_put(struct swap_info_struct * p)
268 swap_device_unlock(p);
272 static int swap_entry_free(struct swap_info_struct *p, unsigned long offset)
274 int count = p->swap_map[offset];
276 if (count < SWAP_MAP_MAX) {
278 p->swap_map[offset] = count;
280 if (offset < p->lowest_bit)
281 p->lowest_bit = offset;
282 if (offset > p->highest_bit)
283 p->highest_bit = offset;
292 * Caller has made sure that the swapdevice corresponding to entry
293 * is still around or has not been recycled.
295 void swap_free(swp_entry_t entry)
297 struct swap_info_struct * p;
299 p = swap_info_get(entry);
301 swap_entry_free(p, swp_offset(entry));
307 * Check if we're the only user of a swap page,
308 * when the page is locked.
310 static int exclusive_swap_page(struct page *page)
313 struct swap_info_struct * p;
316 entry.val = page->private;
317 p = swap_info_get(entry);
319 /* Is the only swap cache user the cache itself? */
320 if (p->swap_map[swp_offset(entry)] == 1) {
321 /* Recheck the page count with the swapcache lock held.. */
322 spin_lock(&swapper_space.tree_lock);
323 if (page_count(page) == 2)
325 spin_unlock(&swapper_space.tree_lock);
333 * We can use this swap cache entry directly
334 * if there are no other references to it.
336 * Here "exclusive_swap_page()" does the real
337 * work, but we opportunistically check whether
338 * we need to get all the locks first..
340 int can_share_swap_page(struct page *page)
344 if (!PageLocked(page))
346 switch (page_count(page)) {
348 if (!PagePrivate(page))
352 if (!PageSwapCache(page))
354 retval = exclusive_swap_page(page);
357 if (PageReserved(page))
365 * Work out if there are any other processes sharing this
366 * swap cache page. Free it if you can. Return success.
368 int remove_exclusive_swap_page(struct page *page)
371 struct swap_info_struct * p;
374 BUG_ON(PagePrivate(page));
375 BUG_ON(!PageLocked(page));
377 if (!PageSwapCache(page))
379 if (PageWriteback(page))
381 if (page_count(page) != 2) /* 2: us + cache */
384 entry.val = page->private;
385 p = swap_info_get(entry);
389 /* Is the only swap cache user the cache itself? */
391 if (p->swap_map[swp_offset(entry)] == 1) {
392 /* Recheck the page count with the swapcache lock held.. */
393 spin_lock(&swapper_space.tree_lock);
394 if ((page_count(page) == 2) && !PageWriteback(page)) {
395 __delete_from_swap_cache(page);
399 spin_unlock(&swapper_space.tree_lock);
405 page_cache_release(page);
412 * Free the swap entry like above, but also try to
413 * free the page cache entry if it is the last user.
415 void free_swap_and_cache(swp_entry_t entry)
417 struct swap_info_struct * p;
418 struct page *page = NULL;
420 p = swap_info_get(entry);
422 if (swap_entry_free(p, swp_offset(entry)) == 1) {
423 spin_lock(&swapper_space.tree_lock);
424 page = radix_tree_lookup(&swapper_space.page_tree,
426 if (page && TestSetPageLocked(page))
428 spin_unlock(&swapper_space.tree_lock);
435 BUG_ON(PagePrivate(page));
436 page_cache_get(page);
437 one_user = (page_count(page) == 2);
438 /* Only cache user (+us), or swap space full? Free it! */
439 if (!PageWriteback(page) && (one_user || vm_swap_full())) {
440 delete_from_swap_cache(page);
444 page_cache_release(page);
449 * The swap entry has been read in advance, and we return 1 to indicate
450 * that the page has been used or is no longer needed.
452 * Always set the resulting pte to be nowrite (the same as COW pages
453 * after one process has exited). We don't know just how many PTEs will
454 * share this swap entry, so be cautious and let do_wp_page work out
455 * what to do if a write is requested later.
457 /* vma->vm_mm->page_table_lock is held */
459 unuse_pte(struct vm_area_struct *vma, unsigned long address, pte_t *dir,
460 swp_entry_t entry, struct page *page, struct pte_chain **pte_chainp)
464 set_pte(dir, pte_mkold(mk_pte(page, vma->vm_page_prot)));
465 *pte_chainp = page_add_rmap(page, dir, *pte_chainp);
469 /* vma->vm_mm->page_table_lock is held */
470 static int unuse_pmd(struct vm_area_struct * vma, pmd_t *dir,
471 unsigned long address, unsigned long size, unsigned long offset,
472 swp_entry_t entry, struct page *page, struct pte_chain **pte_chainp)
476 pte_t swp_pte = swp_entry_to_pte(entry);
485 pte = pte_offset_map(dir, address);
486 offset += address & PMD_MASK;
487 address &= ~PMD_MASK;
488 end = address + size;
493 * swapoff spends a _lot_ of time in this loop!
494 * Test inline before going to call unuse_pte.
496 if (unlikely(pte_same(*pte, swp_pte))) {
497 unuse_pte(vma, offset + address, pte,
498 entry, page, pte_chainp);
502 address += PAGE_SIZE;
504 } while (address && (address < end));
509 /* vma->vm_mm->page_table_lock is held */
510 static int unuse_pgd(struct vm_area_struct * vma, pgd_t *dir,
511 unsigned long address, unsigned long size,
512 swp_entry_t entry, struct page *page, struct pte_chain **pte_chainp)
515 unsigned long offset, end;
524 pmd = pmd_offset(dir, address);
525 offset = address & PGDIR_MASK;
526 address &= ~PGDIR_MASK;
527 end = address + size;
528 if (end > PGDIR_SIZE)
533 if (unuse_pmd(vma, pmd, address, end - address,
534 offset, entry, page, pte_chainp))
536 address = (address + PMD_SIZE) & PMD_MASK;
538 } while (address && (address < end));
542 /* vma->vm_mm->page_table_lock is held */
543 static int unuse_vma(struct vm_area_struct * vma, pgd_t *pgdir,
544 swp_entry_t entry, struct page *page, struct pte_chain **pte_chainp)
546 unsigned long start = vma->vm_start, end = vma->vm_end;
551 if (unuse_pgd(vma, pgdir, start, end - start,
552 entry, page, pte_chainp))
554 start = (start + PGDIR_SIZE) & PGDIR_MASK;
556 } while (start && (start < end));
560 static int unuse_process(struct mm_struct * mm,
561 swp_entry_t entry, struct page* page)
563 struct vm_area_struct* vma;
564 struct pte_chain *pte_chain;
566 pte_chain = pte_chain_alloc(GFP_KERNEL);
571 * Go through process' page directory.
573 spin_lock(&mm->page_table_lock);
574 for (vma = mm->mmap; vma; vma = vma->vm_next) {
575 pgd_t * pgd = pgd_offset(mm, vma->vm_start);
576 if (unuse_vma(vma, pgd, entry, page, &pte_chain))
579 spin_unlock(&mm->page_table_lock);
580 pte_chain_free(pte_chain);
585 * Scan swap_map from current position to next entry still in use.
586 * Recycle to start on reaching the end, returning 0 when empty.
588 static int find_next_to_unuse(struct swap_info_struct *si, int prev)
595 * No need for swap_device_lock(si) here: we're just looking
596 * for whether an entry is in use, not modifying it; false
597 * hits are okay, and sys_swapoff() has already prevented new
598 * allocations from this area (while holding swap_list_lock()).
607 * No entries in use at top of swap_map,
608 * loop back to start and recheck there.
614 count = si->swap_map[i];
615 if (count && count != SWAP_MAP_BAD)
622 * We completely avoid races by reading each swap page in advance,
623 * and then search for the process using it. All the necessary
624 * page table adjustments can then be made atomically.
626 static int try_to_unuse(unsigned int type)
628 struct swap_info_struct * si = &swap_info[type];
629 struct mm_struct *start_mm;
630 unsigned short *swap_map;
631 unsigned short swcount;
636 int reset_overflow = 0;
640 * When searching mms for an entry, a good strategy is to
641 * start at the first mm we freed the previous entry from
642 * (though actually we don't notice whether we or coincidence
643 * freed the entry). Initialize this start_mm with a hold.
645 * A simpler strategy would be to start at the last mm we
646 * freed the previous entry from; but that would take less
647 * advantage of mmlist ordering (now preserved by swap_out()),
648 * which clusters forked address spaces together, most recent
649 * child immediately after parent. If we race with dup_mmap(),
650 * we very much want to resolve parent before child, otherwise
651 * we may miss some entries: using last mm would invert that.
654 atomic_inc(&init_mm.mm_users);
657 * Keep on scanning until all entries have gone. Usually,
658 * one pass through swap_map is enough, but not necessarily:
659 * mmput() removes mm from mmlist before exit_mmap() and its
660 * zap_page_range(). That's not too bad, those entries are
661 * on their way out, and handled faster there than here.
662 * do_munmap() behaves similarly, taking the range out of mm's
663 * vma list before zap_page_range(). But unfortunately, when
664 * unmapping a part of a vma, it takes the whole out first,
665 * then reinserts what's left after (might even reschedule if
666 * open() method called) - so swap entries may be invisible
667 * to swapoff for a while, then reappear - but that is rare.
669 while ((i = find_next_to_unuse(si, i))) {
670 if (signal_pending(current)) {
676 * Get a page for the entry, using the existing swap
677 * cache page if there is one. Otherwise, get a clean
678 * page and read the swap into it.
680 swap_map = &si->swap_map[i];
681 entry = swp_entry(type, i);
682 page = read_swap_cache_async(entry);
685 * Either swap_duplicate() failed because entry
686 * has been freed independently, and will not be
687 * reused since sys_swapoff() already disabled
688 * allocation from here, or alloc_page() failed.
697 * Don't hold on to start_mm if it looks like exiting.
699 if (atomic_read(&start_mm->mm_users) == 1) {
702 atomic_inc(&init_mm.mm_users);
706 * Wait for and lock page. When do_swap_page races with
707 * try_to_unuse, do_swap_page can handle the fault much
708 * faster than try_to_unuse can locate the entry. This
709 * apparently redundant "wait_on_page_locked" lets try_to_unuse
710 * defer to do_swap_page in such a case - in some tests,
711 * do_swap_page and try_to_unuse repeatedly compete.
713 wait_on_page_locked(page);
714 wait_on_page_writeback(page);
716 wait_on_page_writeback(page);
719 * Remove all references to entry, without blocking.
720 * Whenever we reach init_mm, there's no address space
721 * to search, but use it as a reminder to search shmem.
726 if (start_mm == &init_mm)
727 shmem = shmem_unuse(entry, page);
729 retval = unuse_process(start_mm, entry, page);
732 int set_start_mm = (*swap_map >= swcount);
733 struct list_head *p = &start_mm->mmlist;
734 struct mm_struct *new_start_mm = start_mm;
735 struct mm_struct *prev_mm = start_mm;
736 struct mm_struct *mm;
738 atomic_inc(&new_start_mm->mm_users);
739 atomic_inc(&prev_mm->mm_users);
740 spin_lock(&mmlist_lock);
741 while (*swap_map > 1 && !retval &&
742 (p = p->next) != &start_mm->mmlist) {
743 mm = list_entry(p, struct mm_struct, mmlist);
744 atomic_inc(&mm->mm_users);
745 spin_unlock(&mmlist_lock);
754 else if (mm == &init_mm) {
756 shmem = shmem_unuse(entry, page);
758 retval = unuse_process(mm, entry, page);
759 if (set_start_mm && *swap_map < swcount) {
761 atomic_inc(&mm->mm_users);
765 spin_lock(&mmlist_lock);
767 spin_unlock(&mmlist_lock);
770 start_mm = new_start_mm;
774 page_cache_release(page);
779 * How could swap count reach 0x7fff when the maximum
780 * pid is 0x7fff, and there's no way to repeat a swap
781 * page within an mm (except in shmem, where it's the
782 * shared object which takes the reference count)?
783 * We believe SWAP_MAP_MAX cannot occur in Linux 2.4.
785 * If that's wrong, then we should worry more about
786 * exit_mmap() and do_munmap() cases described above:
787 * we might be resetting SWAP_MAP_MAX too early here.
788 * We know "Undead"s can happen, they're okay, so don't
789 * report them; but do report if we reset SWAP_MAP_MAX.
791 if (*swap_map == SWAP_MAP_MAX) {
792 swap_device_lock(si);
794 swap_device_unlock(si);
799 * If a reference remains (rare), we would like to leave
800 * the page in the swap cache; but try_to_unmap could
801 * then re-duplicate the entry once we drop page lock,
802 * so we might loop indefinitely; also, that page could
803 * not be swapped out to other storage meanwhile. So:
804 * delete from cache even if there's another reference,
805 * after ensuring that the data has been saved to disk -
806 * since if the reference remains (rarer), it will be
807 * read from disk into another page. Splitting into two
808 * pages would be incorrect if swap supported "shared
809 * private" pages, but they are handled by tmpfs files.
811 * Note shmem_unuse already deleted a swappage from
812 * the swap cache, unless the move to filepage failed:
813 * in which case it left swappage in cache, lowered its
814 * swap count to pass quickly through the loops above,
815 * and now we must reincrement count to try again later.
817 if ((*swap_map > 1) && PageDirty(page) && PageSwapCache(page)) {
818 struct writeback_control wbc = {
819 .sync_mode = WB_SYNC_NONE,
822 swap_writepage(page, &wbc);
824 wait_on_page_writeback(page);
826 if (PageSwapCache(page)) {
828 swap_duplicate(entry);
830 delete_from_swap_cache(page);
834 * So we could skip searching mms once swap count went
835 * to 1, we did not mark any present ptes as dirty: must
836 * mark page dirty so shrink_list will preserve it.
840 page_cache_release(page);
843 * Make sure that we aren't completely killing
844 * interactive performance.
850 if (reset_overflow) {
851 printk(KERN_WARNING "swapoff: cleared swap entry overflow\n");
858 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
859 * corresponds to page offset `offset'.
861 sector_t map_swap_page(struct swap_info_struct *sis, pgoff_t offset)
863 struct swap_extent *se = sis->curr_swap_extent;
864 struct swap_extent *start_se = se;
867 struct list_head *lh;
869 if (se->start_page <= offset &&
870 offset < (se->start_page + se->nr_pages)) {
871 return se->start_block + (offset - se->start_page);
874 if (lh == &sis->extent_list)
876 se = list_entry(lh, struct swap_extent, list);
877 sis->curr_swap_extent = se;
878 BUG_ON(se == start_se); /* It *must* be present */
883 * Free all of a swapdev's extent information
885 static void destroy_swap_extents(struct swap_info_struct *sis)
887 while (!list_empty(&sis->extent_list)) {
888 struct swap_extent *se;
890 se = list_entry(sis->extent_list.next,
891 struct swap_extent, list);
899 * Add a block range (and the corresponding page range) into this swapdev's
900 * extent list. The extent list is kept sorted in block order.
902 * This function rather assumes that it is called in ascending sector_t order.
903 * It doesn't look for extent coalescing opportunities.
906 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
907 unsigned long nr_pages, sector_t start_block)
909 struct swap_extent *se;
910 struct swap_extent *new_se;
911 struct list_head *lh;
913 lh = sis->extent_list.next; /* The highest-addressed block */
914 while (lh != &sis->extent_list) {
915 se = list_entry(lh, struct swap_extent, list);
916 if (se->start_block + se->nr_pages == start_block &&
917 se->start_page + se->nr_pages == start_page) {
919 se->nr_pages += nr_pages;
926 * No merge. Insert a new extent, preserving ordering.
928 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
931 new_se->start_page = start_page;
932 new_se->nr_pages = nr_pages;
933 new_se->start_block = start_block;
935 lh = sis->extent_list.prev; /* The lowest block */
936 while (lh != &sis->extent_list) {
937 se = list_entry(lh, struct swap_extent, list);
938 if (se->start_block > start_block)
942 list_add_tail(&new_se->list, lh);
948 * A `swap extent' is a simple thing which maps a contiguous range of pages
949 * onto a contiguous range of disk blocks. An ordered list of swap extents
950 * is built at swapon time and is then used at swap_writepage/swap_readpage
951 * time for locating where on disk a page belongs.
953 * If the swapfile is an S_ISBLK block device, a single extent is installed.
954 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
955 * swap files identically.
957 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
958 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
959 * swapfiles are handled *identically* after swapon time.
961 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
962 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
963 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
964 * requirements, they are simply tossed out - we will never use those blocks
967 * For S_ISREG swapfiles we hold i_sem across the life of the swapon. This
968 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
969 * which will scribble on the fs.
971 * The amount of disk space which a single swap extent represents varies.
972 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
973 * extents in the list. To avoid much list walking, we cache the previous
974 * search location in `curr_swap_extent', and start new searches from there.
975 * This is extremely effective. The average number of iterations in
976 * map_swap_page() has been measured at about 0.3 per page. - akpm.
978 static int setup_swap_extents(struct swap_info_struct *sis)
981 unsigned blocks_per_page;
982 unsigned long page_no;
984 sector_t probe_block;
988 inode = sis->swap_file->f_mapping->host;
989 if (S_ISBLK(inode->i_mode)) {
990 ret = add_swap_extent(sis, 0, sis->max, 0);
994 blkbits = inode->i_blkbits;
995 blocks_per_page = PAGE_SIZE >> blkbits;
998 * Map all the blocks into the extent list. This code doesn't try
1003 last_block = i_size_read(inode) >> blkbits;
1004 while ((probe_block + blocks_per_page) <= last_block &&
1005 page_no < sis->max) {
1006 unsigned block_in_page;
1007 sector_t first_block;
1009 first_block = bmap(inode, probe_block);
1010 if (first_block == 0)
1014 * It must be PAGE_SIZE aligned on-disk
1016 if (first_block & (blocks_per_page - 1)) {
1021 for (block_in_page = 1; block_in_page < blocks_per_page;
1025 block = bmap(inode, probe_block + block_in_page);
1028 if (block != first_block + block_in_page) {
1036 * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
1038 ret = add_swap_extent(sis, page_no, 1,
1039 first_block >> (PAGE_SHIFT - blkbits));
1043 probe_block += blocks_per_page;
1051 sis->highest_bit = page_no - 1;
1053 sis->curr_swap_extent = list_entry(sis->extent_list.prev,
1054 struct swap_extent, list);
1057 printk(KERN_ERR "swapon: swapfile has holes\n");
1063 #if 0 /* We don't need this yet */
1064 #include <linux/backing-dev.h>
1065 int page_queue_congested(struct page *page)
1067 struct backing_dev_info *bdi;
1069 BUG_ON(!PageLocked(page)); /* It pins the swap_info_struct */
1071 if (PageSwapCache(page)) {
1072 swp_entry_t entry = { .val = page->private };
1073 struct swap_info_struct *sis;
1075 sis = get_swap_info_struct(swp_type(entry));
1076 bdi = sis->bdev->bd_inode->i_mapping->backing_dev_info;
1078 bdi = page->mapping->backing_dev_info;
1079 return bdi_write_congested(bdi);
1083 asmlinkage long sys_swapoff(const char __user * specialfile)
1085 struct swap_info_struct * p = NULL;
1086 unsigned short *swap_map;
1087 struct file *swap_file, *victim;
1088 struct address_space *mapping;
1093 if (!capable(CAP_SYS_ADMIN))
1096 pathname = getname(specialfile);
1097 err = PTR_ERR(pathname);
1098 if (IS_ERR(pathname))
1101 victim = filp_open(pathname, O_RDWR, 0);
1103 err = PTR_ERR(victim);
1107 mapping = victim->f_mapping;
1110 for (type = swap_list.head; type >= 0; type = swap_info[type].next) {
1111 p = swap_info + type;
1112 if ((p->flags & SWP_ACTIVE) == SWP_ACTIVE) {
1113 if (p->swap_file->f_mapping == mapping)
1123 if (!security_vm_enough_memory(p->pages))
1124 vm_unacct_memory(p->pages);
1131 swap_list.head = p->next;
1133 swap_info[prev].next = p->next;
1135 if (type == swap_list.next) {
1136 /* just pick something that's safe... */
1137 swap_list.next = swap_list.head;
1139 nr_swap_pages -= p->pages;
1140 total_swap_pages -= p->pages;
1141 p->flags &= ~SWP_WRITEOK;
1143 current->flags |= PF_SWAPOFF;
1144 err = try_to_unuse(type);
1145 current->flags &= ~PF_SWAPOFF;
1147 /* re-insert swap space back into swap_list */
1149 for (prev = -1, i = swap_list.head; i >= 0; prev = i, i = swap_info[i].next)
1150 if (p->prio >= swap_info[i].prio)
1154 swap_list.head = swap_list.next = p - swap_info;
1156 swap_info[prev].next = p - swap_info;
1157 nr_swap_pages += p->pages;
1158 total_swap_pages += p->pages;
1159 p->flags |= SWP_WRITEOK;
1164 down(&swap_bdevs_sem);
1166 swap_device_lock(p);
1167 swap_file = p->swap_file;
1168 p->swap_file = NULL;
1170 swap_map = p->swap_map;
1173 destroy_swap_extents(p);
1174 swap_device_unlock(p);
1176 remove_swap_bdev(p->bdev);
1177 up(&swap_bdevs_sem);
1180 if (S_ISBLK(mapping->host->i_mode)) {
1181 struct block_device *bdev = I_BDEV(mapping->host);
1182 set_blocksize(bdev, p->old_block_size);
1185 up(&mapping->host->i_sem);
1187 filp_close(swap_file, NULL);
1191 filp_close(victim, NULL);
1196 #ifdef CONFIG_PROC_FS
1198 static void *swap_start(struct seq_file *swap, loff_t *pos)
1200 struct swap_info_struct *ptr = swap_info;
1206 for (i = 0; i < nr_swapfiles; i++, ptr++) {
1207 if (!(ptr->flags & SWP_USED) || !ptr->swap_map)
1216 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
1218 struct swap_info_struct *ptr = v;
1219 struct swap_info_struct *endptr = swap_info + nr_swapfiles;
1221 for (++ptr; ptr < endptr; ptr++) {
1222 if (!(ptr->flags & SWP_USED) || !ptr->swap_map)
1231 static void swap_stop(struct seq_file *swap, void *v)
1236 static int swap_show(struct seq_file *swap, void *v)
1238 struct swap_info_struct *ptr = v;
1243 seq_puts(swap, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
1245 file = ptr->swap_file;
1246 len = seq_path(swap, file->f_vfsmnt, file->f_dentry, " \t\n\\");
1247 seq_printf(swap, "%*s%s\t%d\t%ld\t%d\n",
1248 len < 40 ? 40 - len : 1, " ",
1249 S_ISBLK(file->f_dentry->d_inode->i_mode) ?
1250 "partition" : "file\t",
1251 ptr->pages << (PAGE_SHIFT - 10),
1252 ptr->inuse_pages << (PAGE_SHIFT - 10),
1257 static struct seq_operations swaps_op = {
1258 .start = swap_start,
1264 static int swaps_open(struct inode *inode, struct file *file)
1266 return seq_open(file, &swaps_op);
1269 static struct file_operations proc_swaps_operations = {
1272 .llseek = seq_lseek,
1273 .release = seq_release,
1276 static int __init procswaps_init(void)
1278 struct proc_dir_entry *entry;
1280 entry = create_proc_entry("swaps", 0, NULL);
1282 entry->proc_fops = &proc_swaps_operations;
1285 __initcall(procswaps_init);
1286 #endif /* CONFIG_PROC_FS */
1289 * Written 01/25/92 by Simmule Turner, heavily changed by Linus.
1291 * The swapon system call
1293 asmlinkage long sys_swapon(const char __user * specialfile, int swap_flags)
1295 struct swap_info_struct * p;
1297 struct block_device *bdev = NULL;
1298 struct file *swap_file = NULL;
1299 struct address_space *mapping;
1303 static int least_priority;
1304 union swap_header *swap_header = 0;
1305 int swap_header_version;
1306 int nr_good_pages = 0;
1307 unsigned long maxpages = 1;
1309 unsigned short *swap_map;
1310 struct page *page = NULL;
1311 struct inode *inode = NULL;
1314 if (!capable(CAP_SYS_ADMIN))
1318 for (type = 0 ; type < nr_swapfiles ; type++,p++)
1319 if (!(p->flags & SWP_USED))
1323 * Test if adding another swap device is possible. There are
1324 * two limiting factors: 1) the number of bits for the swap
1325 * type swp_entry_t definition and 2) the number of bits for
1326 * the swap type in the swap ptes as defined by the different
1327 * architectures. To honor both limitations a swap entry
1328 * with swap offset 0 and swap type ~0UL is created, encoded
1329 * to a swap pte, decoded to a swp_entry_t again and finally
1330 * the swap type part is extracted. This will mask all bits
1331 * from the initial ~0UL that can't be encoded in either the
1332 * swp_entry_t or the architecture definition of a swap pte.
1334 if (type > swp_type(pte_to_swp_entry(swp_entry_to_pte(swp_entry(~0UL,0))))) {
1338 if (type >= nr_swapfiles)
1339 nr_swapfiles = type+1;
1340 INIT_LIST_HEAD(&p->extent_list);
1341 p->flags = SWP_USED;
1343 p->swap_file = NULL;
1344 p->old_block_size = 0;
1350 p->sdev_lock = SPIN_LOCK_UNLOCKED;
1352 if (swap_flags & SWAP_FLAG_PREFER) {
1354 (swap_flags & SWAP_FLAG_PRIO_MASK)>>SWAP_FLAG_PRIO_SHIFT;
1356 p->prio = --least_priority;
1359 name = getname(specialfile);
1360 error = PTR_ERR(name);
1365 swap_file = filp_open(name, O_RDWR, 0);
1366 error = PTR_ERR(swap_file);
1367 if (IS_ERR(swap_file)) {
1372 p->swap_file = swap_file;
1373 mapping = swap_file->f_mapping;
1374 inode = mapping->host;
1377 for (i = 0; i < nr_swapfiles; i++) {
1378 struct swap_info_struct *q = &swap_info[i];
1380 if (i == type || !q->swap_file)
1382 if (mapping == q->swap_file->f_mapping)
1387 if (S_ISBLK(inode->i_mode)) {
1388 bdev = I_BDEV(inode);
1389 error = bd_claim(bdev, sys_swapon);
1394 p->old_block_size = block_size(bdev);
1395 error = set_blocksize(bdev, PAGE_SIZE);
1399 } else if (S_ISREG(inode->i_mode)) {
1400 p->bdev = inode->i_sb->s_bdev;
1401 down(&inode->i_sem);
1407 swapfilesize = i_size_read(inode) >> PAGE_SHIFT;
1410 * Read the swap header.
1412 if (!mapping->a_ops->readpage) {
1416 page = read_cache_page(mapping, 0,
1417 (filler_t *)mapping->a_ops->readpage, swap_file);
1419 error = PTR_ERR(page);
1422 wait_on_page_locked(page);
1423 if (!PageUptodate(page))
1426 swap_header = page_address(page);
1428 if (!memcmp("SWAP-SPACE",swap_header->magic.magic,10))
1429 swap_header_version = 1;
1430 else if (!memcmp("SWAPSPACE2",swap_header->magic.magic,10))
1431 swap_header_version = 2;
1433 printk("Unable to find swap-space signature\n");
1438 switch (swap_header_version) {
1440 printk(KERN_ERR "version 0 swap is no longer supported. "
1441 "Use mkswap -v1 %s\n", name);
1445 /* Check the swap header's sub-version and the size of
1446 the swap file and bad block lists */
1447 if (swap_header->info.version != 1) {
1449 "Unable to handle swap header version %d\n",
1450 swap_header->info.version);
1457 * Find out how many pages are allowed for a single swap
1458 * device. There are two limiting factors: 1) the number of
1459 * bits for the swap offset in the swp_entry_t type and
1460 * 2) the number of bits in the a swap pte as defined by
1461 * the different architectures. In order to find the
1462 * largest possible bit mask a swap entry with swap type 0
1463 * and swap offset ~0UL is created, encoded to a swap pte,
1464 * decoded to a swp_entry_t again and finally the swap
1465 * offset is extracted. This will mask all the bits from
1466 * the initial ~0UL mask that can't be encoded in either
1467 * the swp_entry_t or the architecture definition of a
1470 maxpages = swp_offset(pte_to_swp_entry(swp_entry_to_pte(swp_entry(0,~0UL)))) - 1;
1471 if (maxpages > swap_header->info.last_page)
1472 maxpages = swap_header->info.last_page;
1473 p->highest_bit = maxpages - 1;
1476 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
1479 /* OK, set up the swap map and apply the bad block list */
1480 if (!(p->swap_map = vmalloc(maxpages * sizeof(short)))) {
1486 memset(p->swap_map, 0, maxpages * sizeof(short));
1487 for (i=0; i<swap_header->info.nr_badpages; i++) {
1488 int page = swap_header->info.badpages[i];
1489 if (page <= 0 || page >= swap_header->info.last_page)
1492 p->swap_map[page] = SWAP_MAP_BAD;
1494 nr_good_pages = swap_header->info.last_page -
1495 swap_header->info.nr_badpages -
1496 1 /* header page */;
1501 if (swapfilesize && maxpages > swapfilesize) {
1503 "Swap area shorter than signature indicates\n");
1507 if (!nr_good_pages) {
1508 printk(KERN_WARNING "Empty swap-file\n");
1512 p->swap_map[0] = SWAP_MAP_BAD;
1514 p->pages = nr_good_pages;
1516 error = setup_swap_extents(p);
1521 down(&swap_bdevs_sem);
1523 swap_device_lock(p);
1524 p->flags = SWP_ACTIVE;
1525 nr_swap_pages += nr_good_pages;
1526 total_swap_pages += nr_good_pages;
1527 printk(KERN_INFO "Adding %dk swap on %s. Priority:%d extents:%d\n",
1528 nr_good_pages<<(PAGE_SHIFT-10), name,
1529 p->prio, p->nr_extents);
1531 /* insert swap space into swap_list: */
1533 for (i = swap_list.head; i >= 0; i = swap_info[i].next) {
1534 if (p->prio >= swap_info[i].prio) {
1541 swap_list.head = swap_list.next = p - swap_info;
1543 swap_info[prev].next = p - swap_info;
1545 swap_device_unlock(p);
1547 install_swap_bdev(p->bdev);
1548 up(&swap_bdevs_sem);
1554 set_blocksize(bdev, p->old_block_size);
1559 swap_map = p->swap_map;
1560 p->swap_file = NULL;
1563 if (!(swap_flags & SWAP_FLAG_PREFER))
1566 destroy_swap_extents(p);
1570 filp_close(swap_file, NULL);
1572 if (page && !IS_ERR(page)) {
1574 page_cache_release(page);
1578 if (error && did_down)
1583 void si_swapinfo(struct sysinfo *val)
1586 unsigned long nr_to_be_unused = 0;
1589 for (i = 0; i < nr_swapfiles; i++) {
1590 if (!(swap_info[i].flags & SWP_USED) ||
1591 (swap_info[i].flags & SWP_WRITEOK))
1593 nr_to_be_unused += swap_info[i].inuse_pages;
1595 val->freeswap = nr_swap_pages + nr_to_be_unused;
1596 val->totalswap = total_swap_pages + nr_to_be_unused;
1601 * Verify that a swap entry is valid and increment its swap map count.
1603 * Note: if swap_map[] reaches SWAP_MAP_MAX the entries are treated as
1604 * "permanent", but will be reclaimed by the next swapoff.
1606 int swap_duplicate(swp_entry_t entry)
1608 struct swap_info_struct * p;
1609 unsigned long offset, type;
1612 type = swp_type(entry);
1613 if (type >= nr_swapfiles)
1615 p = type + swap_info;
1616 offset = swp_offset(entry);
1618 swap_device_lock(p);
1619 if (offset < p->max && p->swap_map[offset]) {
1620 if (p->swap_map[offset] < SWAP_MAP_MAX - 1) {
1621 p->swap_map[offset]++;
1623 } else if (p->swap_map[offset] <= SWAP_MAP_MAX) {
1624 if (swap_overflow++ < 5)
1625 printk(KERN_WARNING "swap_dup: swap entry overflow\n");
1626 p->swap_map[offset] = SWAP_MAP_MAX;
1630 swap_device_unlock(p);
1635 printk(KERN_ERR "swap_dup: %s%08lx\n", Bad_file, entry.val);
1639 struct swap_info_struct *
1640 get_swap_info_struct(unsigned type)
1642 return &swap_info[type];
1646 * swap_device_lock prevents swap_map being freed. Don't grab an extra
1647 * reference on the swaphandle, it doesn't matter if it becomes unused.
1649 int valid_swaphandles(swp_entry_t entry, unsigned long *offset)
1651 int ret = 0, i = 1 << page_cluster;
1653 struct swap_info_struct *swapdev = swp_type(entry) + swap_info;
1655 if (!page_cluster) /* no readahead */
1657 toff = (swp_offset(entry) >> page_cluster) << page_cluster;
1658 if (!toff) /* first page is swap header */
1662 swap_device_lock(swapdev);
1664 /* Don't read-ahead past the end of the swap area */
1665 if (toff >= swapdev->max)
1667 /* Don't read in free or bad pages */
1668 if (!swapdev->swap_map[toff])
1670 if (swapdev->swap_map[toff] == SWAP_MAP_BAD)
1675 swap_device_unlock(swapdev);