Back to home page

LXR

 
 

    


0001 /*
0002  *  linux/mm/swap_state.c
0003  *
0004  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
0005  *  Swap reorganised 29.12.95, Stephen Tweedie
0006  *
0007  *  Rewritten to use page cache, (C) 1998 Stephen Tweedie
0008  */
0009 #include <linux/mm.h>
0010 #include <linux/gfp.h>
0011 #include <linux/kernel_stat.h>
0012 #include <linux/swap.h>
0013 #include <linux/swapops.h>
0014 #include <linux/init.h>
0015 #include <linux/pagemap.h>
0016 #include <linux/backing-dev.h>
0017 #include <linux/blkdev.h>
0018 #include <linux/pagevec.h>
0019 #include <linux/migrate.h>
0020 
0021 #include <asm/pgtable.h>
0022 
0023 /*
0024  * swapper_space is a fiction, retained to simplify the path through
0025  * vmscan's shrink_page_list.
0026  */
0027 static const struct address_space_operations swap_aops = {
0028     .writepage  = swap_writepage,
0029     .set_page_dirty = swap_set_page_dirty,
0030 #ifdef CONFIG_MIGRATION
0031     .migratepage    = migrate_page,
0032 #endif
0033 };
0034 
0035 struct address_space swapper_spaces[MAX_SWAPFILES] = {
0036     [0 ... MAX_SWAPFILES - 1] = {
0037         .page_tree  = RADIX_TREE_INIT(GFP_ATOMIC|__GFP_NOWARN),
0038         .i_mmap_writable = ATOMIC_INIT(0),
0039         .a_ops      = &swap_aops,
0040         /* swap cache doesn't use writeback related tags */
0041         .flags      = 1 << AS_NO_WRITEBACK_TAGS,
0042     }
0043 };
0044 
0045 #define INC_CACHE_INFO(x)   do { swap_cache_info.x++; } while (0)
0046 
0047 static struct {
0048     unsigned long add_total;
0049     unsigned long del_total;
0050     unsigned long find_success;
0051     unsigned long find_total;
0052 } swap_cache_info;
0053 
0054 unsigned long total_swapcache_pages(void)
0055 {
0056     int i;
0057     unsigned long ret = 0;
0058 
0059     for (i = 0; i < MAX_SWAPFILES; i++)
0060         ret += swapper_spaces[i].nrpages;
0061     return ret;
0062 }
0063 
0064 static atomic_t swapin_readahead_hits = ATOMIC_INIT(4);
0065 
0066 void show_swap_cache_info(void)
0067 {
0068     printk("%lu pages in swap cache\n", total_swapcache_pages());
0069     printk("Swap cache stats: add %lu, delete %lu, find %lu/%lu\n",
0070         swap_cache_info.add_total, swap_cache_info.del_total,
0071         swap_cache_info.find_success, swap_cache_info.find_total);
0072     printk("Free swap  = %ldkB\n",
0073         get_nr_swap_pages() << (PAGE_SHIFT - 10));
0074     printk("Total swap = %lukB\n", total_swap_pages << (PAGE_SHIFT - 10));
0075 }
0076 
0077 /*
0078  * __add_to_swap_cache resembles add_to_page_cache_locked on swapper_space,
0079  * but sets SwapCache flag and private instead of mapping and index.
0080  */
0081 int __add_to_swap_cache(struct page *page, swp_entry_t entry)
0082 {
0083     int error;
0084     struct address_space *address_space;
0085 
0086     VM_BUG_ON_PAGE(!PageLocked(page), page);
0087     VM_BUG_ON_PAGE(PageSwapCache(page), page);
0088     VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
0089 
0090     get_page(page);
0091     SetPageSwapCache(page);
0092     set_page_private(page, entry.val);
0093 
0094     address_space = swap_address_space(entry);
0095     spin_lock_irq(&address_space->tree_lock);
0096     error = radix_tree_insert(&address_space->page_tree,
0097                   swp_offset(entry), page);
0098     if (likely(!error)) {
0099         address_space->nrpages++;
0100         __inc_node_page_state(page, NR_FILE_PAGES);
0101         INC_CACHE_INFO(add_total);
0102     }
0103     spin_unlock_irq(&address_space->tree_lock);
0104 
0105     if (unlikely(error)) {
0106         /*
0107          * Only the context which have set SWAP_HAS_CACHE flag
0108          * would call add_to_swap_cache().
0109          * So add_to_swap_cache() doesn't returns -EEXIST.
0110          */
0111         VM_BUG_ON(error == -EEXIST);
0112         set_page_private(page, 0UL);
0113         ClearPageSwapCache(page);
0114         put_page(page);
0115     }
0116 
0117     return error;
0118 }
0119 
0120 
0121 int add_to_swap_cache(struct page *page, swp_entry_t entry, gfp_t gfp_mask)
0122 {
0123     int error;
0124 
0125     error = radix_tree_maybe_preload(gfp_mask);
0126     if (!error) {
0127         error = __add_to_swap_cache(page, entry);
0128         radix_tree_preload_end();
0129     }
0130     return error;
0131 }
0132 
0133 /*
0134  * This must be called only on pages that have
0135  * been verified to be in the swap cache.
0136  */
0137 void __delete_from_swap_cache(struct page *page)
0138 {
0139     swp_entry_t entry;
0140     struct address_space *address_space;
0141 
0142     VM_BUG_ON_PAGE(!PageLocked(page), page);
0143     VM_BUG_ON_PAGE(!PageSwapCache(page), page);
0144     VM_BUG_ON_PAGE(PageWriteback(page), page);
0145 
0146     entry.val = page_private(page);
0147     address_space = swap_address_space(entry);
0148     radix_tree_delete(&address_space->page_tree, swp_offset(entry));
0149     set_page_private(page, 0);
0150     ClearPageSwapCache(page);
0151     address_space->nrpages--;
0152     __dec_node_page_state(page, NR_FILE_PAGES);
0153     INC_CACHE_INFO(del_total);
0154 }
0155 
0156 /**
0157  * add_to_swap - allocate swap space for a page
0158  * @page: page we want to move to swap
0159  *
0160  * Allocate swap space for the page and add the page to the
0161  * swap cache.  Caller needs to hold the page lock. 
0162  */
0163 int add_to_swap(struct page *page, struct list_head *list)
0164 {
0165     swp_entry_t entry;
0166     int err;
0167 
0168     VM_BUG_ON_PAGE(!PageLocked(page), page);
0169     VM_BUG_ON_PAGE(!PageUptodate(page), page);
0170 
0171     entry = get_swap_page();
0172     if (!entry.val)
0173         return 0;
0174 
0175     if (mem_cgroup_try_charge_swap(page, entry)) {
0176         swapcache_free(entry);
0177         return 0;
0178     }
0179 
0180     if (unlikely(PageTransHuge(page)))
0181         if (unlikely(split_huge_page_to_list(page, list))) {
0182             swapcache_free(entry);
0183             return 0;
0184         }
0185 
0186     /*
0187      * Radix-tree node allocations from PF_MEMALLOC contexts could
0188      * completely exhaust the page allocator. __GFP_NOMEMALLOC
0189      * stops emergency reserves from being allocated.
0190      *
0191      * TODO: this could cause a theoretical memory reclaim
0192      * deadlock in the swap out path.
0193      */
0194     /*
0195      * Add it to the swap cache.
0196      */
0197     err = add_to_swap_cache(page, entry,
0198             __GFP_HIGH|__GFP_NOMEMALLOC|__GFP_NOWARN);
0199 
0200     if (!err) {
0201         return 1;
0202     } else {    /* -ENOMEM radix-tree allocation failure */
0203         /*
0204          * add_to_swap_cache() doesn't return -EEXIST, so we can safely
0205          * clear SWAP_HAS_CACHE flag.
0206          */
0207         swapcache_free(entry);
0208         return 0;
0209     }
0210 }
0211 
0212 /*
0213  * This must be called only on pages that have
0214  * been verified to be in the swap cache and locked.
0215  * It will never put the page into the free list,
0216  * the caller has a reference on the page.
0217  */
0218 void delete_from_swap_cache(struct page *page)
0219 {
0220     swp_entry_t entry;
0221     struct address_space *address_space;
0222 
0223     entry.val = page_private(page);
0224 
0225     address_space = swap_address_space(entry);
0226     spin_lock_irq(&address_space->tree_lock);
0227     __delete_from_swap_cache(page);
0228     spin_unlock_irq(&address_space->tree_lock);
0229 
0230     swapcache_free(entry);
0231     put_page(page);
0232 }
0233 
0234 /* 
0235  * If we are the only user, then try to free up the swap cache. 
0236  * 
0237  * Its ok to check for PageSwapCache without the page lock
0238  * here because we are going to recheck again inside
0239  * try_to_free_swap() _with_ the lock.
0240  *                  - Marcelo
0241  */
0242 static inline void free_swap_cache(struct page *page)
0243 {
0244     if (PageSwapCache(page) && !page_mapped(page) && trylock_page(page)) {
0245         try_to_free_swap(page);
0246         unlock_page(page);
0247     }
0248 }
0249 
0250 /* 
0251  * Perform a free_page(), also freeing any swap cache associated with
0252  * this page if it is the last user of the page.
0253  */
0254 void free_page_and_swap_cache(struct page *page)
0255 {
0256     free_swap_cache(page);
0257     if (!is_huge_zero_page(page))
0258         put_page(page);
0259 }
0260 
0261 /*
0262  * Passed an array of pages, drop them all from swapcache and then release
0263  * them.  They are removed from the LRU and freed if this is their last use.
0264  */
0265 void free_pages_and_swap_cache(struct page **pages, int nr)
0266 {
0267     struct page **pagep = pages;
0268     int i;
0269 
0270     lru_add_drain();
0271     for (i = 0; i < nr; i++)
0272         free_swap_cache(pagep[i]);
0273     release_pages(pagep, nr, false);
0274 }
0275 
0276 /*
0277  * Lookup a swap entry in the swap cache. A found page will be returned
0278  * unlocked and with its refcount incremented - we rely on the kernel
0279  * lock getting page table operations atomic even if we drop the page
0280  * lock before returning.
0281  */
0282 struct page * lookup_swap_cache(swp_entry_t entry)
0283 {
0284     struct page *page;
0285 
0286     page = find_get_page(swap_address_space(entry), swp_offset(entry));
0287 
0288     if (page) {
0289         INC_CACHE_INFO(find_success);
0290         if (TestClearPageReadahead(page))
0291             atomic_inc(&swapin_readahead_hits);
0292     }
0293 
0294     INC_CACHE_INFO(find_total);
0295     return page;
0296 }
0297 
0298 struct page *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
0299             struct vm_area_struct *vma, unsigned long addr,
0300             bool *new_page_allocated)
0301 {
0302     struct page *found_page, *new_page = NULL;
0303     struct address_space *swapper_space = swap_address_space(entry);
0304     int err;
0305     *new_page_allocated = false;
0306 
0307     do {
0308         /*
0309          * First check the swap cache.  Since this is normally
0310          * called after lookup_swap_cache() failed, re-calling
0311          * that would confuse statistics.
0312          */
0313         found_page = find_get_page(swapper_space, swp_offset(entry));
0314         if (found_page)
0315             break;
0316 
0317         /*
0318          * Get a new page to read into from swap.
0319          */
0320         if (!new_page) {
0321             new_page = alloc_page_vma(gfp_mask, vma, addr);
0322             if (!new_page)
0323                 break;      /* Out of memory */
0324         }
0325 
0326         /*
0327          * call radix_tree_preload() while we can wait.
0328          */
0329         err = radix_tree_maybe_preload(gfp_mask & GFP_KERNEL);
0330         if (err)
0331             break;
0332 
0333         /*
0334          * Swap entry may have been freed since our caller observed it.
0335          */
0336         err = swapcache_prepare(entry);
0337         if (err == -EEXIST) {
0338             radix_tree_preload_end();
0339             /*
0340              * We might race against get_swap_page() and stumble
0341              * across a SWAP_HAS_CACHE swap_map entry whose page
0342              * has not been brought into the swapcache yet, while
0343              * the other end is scheduled away waiting on discard
0344              * I/O completion at scan_swap_map().
0345              *
0346              * In order to avoid turning this transitory state
0347              * into a permanent loop around this -EEXIST case
0348              * if !CONFIG_PREEMPT and the I/O completion happens
0349              * to be waiting on the CPU waitqueue where we are now
0350              * busy looping, we just conditionally invoke the
0351              * scheduler here, if there are some more important
0352              * tasks to run.
0353              */
0354             cond_resched();
0355             continue;
0356         }
0357         if (err) {      /* swp entry is obsolete ? */
0358             radix_tree_preload_end();
0359             break;
0360         }
0361 
0362         /* May fail (-ENOMEM) if radix-tree node allocation failed. */
0363         __SetPageLocked(new_page);
0364         __SetPageSwapBacked(new_page);
0365         err = __add_to_swap_cache(new_page, entry);
0366         if (likely(!err)) {
0367             radix_tree_preload_end();
0368             /*
0369              * Initiate read into locked page and return.
0370              */
0371             lru_cache_add_anon(new_page);
0372             *new_page_allocated = true;
0373             return new_page;
0374         }
0375         radix_tree_preload_end();
0376         __ClearPageLocked(new_page);
0377         /*
0378          * add_to_swap_cache() doesn't return -EEXIST, so we can safely
0379          * clear SWAP_HAS_CACHE flag.
0380          */
0381         swapcache_free(entry);
0382     } while (err != -ENOMEM);
0383 
0384     if (new_page)
0385         put_page(new_page);
0386     return found_page;
0387 }
0388 
0389 /*
0390  * Locate a page of swap in physical memory, reserving swap cache space
0391  * and reading the disk if it is not already cached.
0392  * A failure return means that either the page allocation failed or that
0393  * the swap entry is no longer in use.
0394  */
0395 struct page *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
0396             struct vm_area_struct *vma, unsigned long addr)
0397 {
0398     bool page_was_allocated;
0399     struct page *retpage = __read_swap_cache_async(entry, gfp_mask,
0400             vma, addr, &page_was_allocated);
0401 
0402     if (page_was_allocated)
0403         swap_readpage(retpage);
0404 
0405     return retpage;
0406 }
0407 
0408 static unsigned long swapin_nr_pages(unsigned long offset)
0409 {
0410     static unsigned long prev_offset;
0411     unsigned int pages, max_pages, last_ra;
0412     static atomic_t last_readahead_pages;
0413 
0414     max_pages = 1 << READ_ONCE(page_cluster);
0415     if (max_pages <= 1)
0416         return 1;
0417 
0418     /*
0419      * This heuristic has been found to work well on both sequential and
0420      * random loads, swapping to hard disk or to SSD: please don't ask
0421      * what the "+ 2" means, it just happens to work well, that's all.
0422      */
0423     pages = atomic_xchg(&swapin_readahead_hits, 0) + 2;
0424     if (pages == 2) {
0425         /*
0426          * We can have no readahead hits to judge by: but must not get
0427          * stuck here forever, so check for an adjacent offset instead
0428          * (and don't even bother to check whether swap type is same).
0429          */
0430         if (offset != prev_offset + 1 && offset != prev_offset - 1)
0431             pages = 1;
0432         prev_offset = offset;
0433     } else {
0434         unsigned int roundup = 4;
0435         while (roundup < pages)
0436             roundup <<= 1;
0437         pages = roundup;
0438     }
0439 
0440     if (pages > max_pages)
0441         pages = max_pages;
0442 
0443     /* Don't shrink readahead too fast */
0444     last_ra = atomic_read(&last_readahead_pages) / 2;
0445     if (pages < last_ra)
0446         pages = last_ra;
0447     atomic_set(&last_readahead_pages, pages);
0448 
0449     return pages;
0450 }
0451 
0452 /**
0453  * swapin_readahead - swap in pages in hope we need them soon
0454  * @entry: swap entry of this memory
0455  * @gfp_mask: memory allocation flags
0456  * @vma: user vma this address belongs to
0457  * @addr: target address for mempolicy
0458  *
0459  * Returns the struct page for entry and addr, after queueing swapin.
0460  *
0461  * Primitive swap readahead code. We simply read an aligned block of
0462  * (1 << page_cluster) entries in the swap area. This method is chosen
0463  * because it doesn't cost us any seek time.  We also make sure to queue
0464  * the 'original' request together with the readahead ones...
0465  *
0466  * This has been extended to use the NUMA policies from the mm triggering
0467  * the readahead.
0468  *
0469  * Caller must hold down_read on the vma->vm_mm if vma is not NULL.
0470  */
0471 struct page *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
0472             struct vm_area_struct *vma, unsigned long addr)
0473 {
0474     struct page *page;
0475     unsigned long entry_offset = swp_offset(entry);
0476     unsigned long offset = entry_offset;
0477     unsigned long start_offset, end_offset;
0478     unsigned long mask;
0479     struct blk_plug plug;
0480 
0481     mask = swapin_nr_pages(offset) - 1;
0482     if (!mask)
0483         goto skip;
0484 
0485     /* Read a page_cluster sized and aligned cluster around offset. */
0486     start_offset = offset & ~mask;
0487     end_offset = offset | mask;
0488     if (!start_offset)  /* First page is swap header. */
0489         start_offset++;
0490 
0491     blk_start_plug(&plug);
0492     for (offset = start_offset; offset <= end_offset ; offset++) {
0493         /* Ok, do the async read-ahead now */
0494         page = read_swap_cache_async(swp_entry(swp_type(entry), offset),
0495                         gfp_mask, vma, addr);
0496         if (!page)
0497             continue;
0498         if (offset != entry_offset)
0499             SetPageReadahead(page);
0500         put_page(page);
0501     }
0502     blk_finish_plug(&plug);
0503 
0504     lru_add_drain();    /* Push any new pages onto the LRU now */
0505 skip:
0506     return read_swap_cache_async(entry, gfp_mask, vma, addr);
0507 }