Back to home page

LXR

 
 

    


0001 /*
0002  * Workingset detection
0003  *
0004  * Copyright (C) 2013 Red Hat, Inc., Johannes Weiner
0005  */
0006 
0007 #include <linux/memcontrol.h>
0008 #include <linux/writeback.h>
0009 #include <linux/pagemap.h>
0010 #include <linux/atomic.h>
0011 #include <linux/module.h>
0012 #include <linux/swap.h>
0013 #include <linux/dax.h>
0014 #include <linux/fs.h>
0015 #include <linux/mm.h>
0016 
0017 /*
0018  *      Double CLOCK lists
0019  *
0020  * Per node, two clock lists are maintained for file pages: the
0021  * inactive and the active list.  Freshly faulted pages start out at
0022  * the head of the inactive list and page reclaim scans pages from the
0023  * tail.  Pages that are accessed multiple times on the inactive list
0024  * are promoted to the active list, to protect them from reclaim,
0025  * whereas active pages are demoted to the inactive list when the
0026  * active list grows too big.
0027  *
0028  *   fault ------------------------+
0029  *                                 |
0030  *              +--------------+   |            +-------------+
0031  *   reclaim <- |   inactive   | <-+-- demotion |    active   | <--+
0032  *              +--------------+                +-------------+    |
0033  *                     |                                           |
0034  *                     +-------------- promotion ------------------+
0035  *
0036  *
0037  *      Access frequency and refault distance
0038  *
0039  * A workload is thrashing when its pages are frequently used but they
0040  * are evicted from the inactive list every time before another access
0041  * would have promoted them to the active list.
0042  *
0043  * In cases where the average access distance between thrashing pages
0044  * is bigger than the size of memory there is nothing that can be
0045  * done - the thrashing set could never fit into memory under any
0046  * circumstance.
0047  *
0048  * However, the average access distance could be bigger than the
0049  * inactive list, yet smaller than the size of memory.  In this case,
0050  * the set could fit into memory if it weren't for the currently
0051  * active pages - which may be used more, hopefully less frequently:
0052  *
0053  *      +-memory available to cache-+
0054  *      |                           |
0055  *      +-inactive------+-active----+
0056  *  a b | c d e f g h i | J K L M N |
0057  *      +---------------+-----------+
0058  *
0059  * It is prohibitively expensive to accurately track access frequency
0060  * of pages.  But a reasonable approximation can be made to measure
0061  * thrashing on the inactive list, after which refaulting pages can be
0062  * activated optimistically to compete with the existing active pages.
0063  *
0064  * Approximating inactive page access frequency - Observations:
0065  *
0066  * 1. When a page is accessed for the first time, it is added to the
0067  *    head of the inactive list, slides every existing inactive page
0068  *    towards the tail by one slot, and pushes the current tail page
0069  *    out of memory.
0070  *
0071  * 2. When a page is accessed for the second time, it is promoted to
0072  *    the active list, shrinking the inactive list by one slot.  This
0073  *    also slides all inactive pages that were faulted into the cache
0074  *    more recently than the activated page towards the tail of the
0075  *    inactive list.
0076  *
0077  * Thus:
0078  *
0079  * 1. The sum of evictions and activations between any two points in
0080  *    time indicate the minimum number of inactive pages accessed in
0081  *    between.
0082  *
0083  * 2. Moving one inactive page N page slots towards the tail of the
0084  *    list requires at least N inactive page accesses.
0085  *
0086  * Combining these:
0087  *
0088  * 1. When a page is finally evicted from memory, the number of
0089  *    inactive pages accessed while the page was in cache is at least
0090  *    the number of page slots on the inactive list.
0091  *
0092  * 2. In addition, measuring the sum of evictions and activations (E)
0093  *    at the time of a page's eviction, and comparing it to another
0094  *    reading (R) at the time the page faults back into memory tells
0095  *    the minimum number of accesses while the page was not cached.
0096  *    This is called the refault distance.
0097  *
0098  * Because the first access of the page was the fault and the second
0099  * access the refault, we combine the in-cache distance with the
0100  * out-of-cache distance to get the complete minimum access distance
0101  * of this page:
0102  *
0103  *      NR_inactive + (R - E)
0104  *
0105  * And knowing the minimum access distance of a page, we can easily
0106  * tell if the page would be able to stay in cache assuming all page
0107  * slots in the cache were available:
0108  *
0109  *   NR_inactive + (R - E) <= NR_inactive + NR_active
0110  *
0111  * which can be further simplified to
0112  *
0113  *   (R - E) <= NR_active
0114  *
0115  * Put into words, the refault distance (out-of-cache) can be seen as
0116  * a deficit in inactive list space (in-cache).  If the inactive list
0117  * had (R - E) more page slots, the page would not have been evicted
0118  * in between accesses, but activated instead.  And on a full system,
0119  * the only thing eating into inactive list space is active pages.
0120  *
0121  *
0122  *      Activating refaulting pages
0123  *
0124  * All that is known about the active list is that the pages have been
0125  * accessed more than once in the past.  This means that at any given
0126  * time there is actually a good chance that pages on the active list
0127  * are no longer in active use.
0128  *
0129  * So when a refault distance of (R - E) is observed and there are at
0130  * least (R - E) active pages, the refaulting page is activated
0131  * optimistically in the hope that (R - E) active pages are actually
0132  * used less frequently than the refaulting page - or even not used at
0133  * all anymore.
0134  *
0135  * If this is wrong and demotion kicks in, the pages which are truly
0136  * used more frequently will be reactivated while the less frequently
0137  * used once will be evicted from memory.
0138  *
0139  * But if this is right, the stale pages will be pushed out of memory
0140  * and the used pages get to stay in cache.
0141  *
0142  *
0143  *      Implementation
0144  *
0145  * For each node's file LRU lists, a counter for inactive evictions
0146  * and activations is maintained (node->inactive_age).
0147  *
0148  * On eviction, a snapshot of this counter (along with some bits to
0149  * identify the node) is stored in the now empty page cache radix tree
0150  * slot of the evicted page.  This is called a shadow entry.
0151  *
0152  * On cache misses for which there are shadow entries, an eligible
0153  * refault distance will immediately activate the refaulting page.
0154  */
0155 
0156 #define EVICTION_SHIFT  (RADIX_TREE_EXCEPTIONAL_ENTRY + \
0157              NODES_SHIFT +  \
0158              MEM_CGROUP_ID_SHIFT)
0159 #define EVICTION_MASK   (~0UL >> EVICTION_SHIFT)
0160 
0161 /*
0162  * Eviction timestamps need to be able to cover the full range of
0163  * actionable refaults. However, bits are tight in the radix tree
0164  * entry, and after storing the identifier for the lruvec there might
0165  * not be enough left to represent every single actionable refault. In
0166  * that case, we have to sacrifice granularity for distance, and group
0167  * evictions into coarser buckets by shaving off lower timestamp bits.
0168  */
0169 static unsigned int bucket_order __read_mostly;
0170 
0171 static void *pack_shadow(int memcgid, pg_data_t *pgdat, unsigned long eviction)
0172 {
0173     eviction >>= bucket_order;
0174     eviction = (eviction << MEM_CGROUP_ID_SHIFT) | memcgid;
0175     eviction = (eviction << NODES_SHIFT) | pgdat->node_id;
0176     eviction = (eviction << RADIX_TREE_EXCEPTIONAL_SHIFT);
0177 
0178     return (void *)(eviction | RADIX_TREE_EXCEPTIONAL_ENTRY);
0179 }
0180 
0181 static void unpack_shadow(void *shadow, int *memcgidp, pg_data_t **pgdat,
0182               unsigned long *evictionp)
0183 {
0184     unsigned long entry = (unsigned long)shadow;
0185     int memcgid, nid;
0186 
0187     entry >>= RADIX_TREE_EXCEPTIONAL_SHIFT;
0188     nid = entry & ((1UL << NODES_SHIFT) - 1);
0189     entry >>= NODES_SHIFT;
0190     memcgid = entry & ((1UL << MEM_CGROUP_ID_SHIFT) - 1);
0191     entry >>= MEM_CGROUP_ID_SHIFT;
0192 
0193     *memcgidp = memcgid;
0194     *pgdat = NODE_DATA(nid);
0195     *evictionp = entry << bucket_order;
0196 }
0197 
0198 /**
0199  * workingset_eviction - note the eviction of a page from memory
0200  * @mapping: address space the page was backing
0201  * @page: the page being evicted
0202  *
0203  * Returns a shadow entry to be stored in @mapping->page_tree in place
0204  * of the evicted @page so that a later refault can be detected.
0205  */
0206 void *workingset_eviction(struct address_space *mapping, struct page *page)
0207 {
0208     struct mem_cgroup *memcg = page_memcg(page);
0209     struct pglist_data *pgdat = page_pgdat(page);
0210     int memcgid = mem_cgroup_id(memcg);
0211     unsigned long eviction;
0212     struct lruvec *lruvec;
0213 
0214     /* Page is fully exclusive and pins page->mem_cgroup */
0215     VM_BUG_ON_PAGE(PageLRU(page), page);
0216     VM_BUG_ON_PAGE(page_count(page), page);
0217     VM_BUG_ON_PAGE(!PageLocked(page), page);
0218 
0219     lruvec = mem_cgroup_lruvec(pgdat, memcg);
0220     eviction = atomic_long_inc_return(&lruvec->inactive_age);
0221     return pack_shadow(memcgid, pgdat, eviction);
0222 }
0223 
0224 /**
0225  * workingset_refault - evaluate the refault of a previously evicted page
0226  * @shadow: shadow entry of the evicted page
0227  *
0228  * Calculates and evaluates the refault distance of the previously
0229  * evicted page in the context of the node it was allocated in.
0230  *
0231  * Returns %true if the page should be activated, %false otherwise.
0232  */
0233 bool workingset_refault(void *shadow)
0234 {
0235     unsigned long refault_distance;
0236     unsigned long active_file;
0237     struct mem_cgroup *memcg;
0238     unsigned long eviction;
0239     struct lruvec *lruvec;
0240     unsigned long refault;
0241     struct pglist_data *pgdat;
0242     int memcgid;
0243 
0244     unpack_shadow(shadow, &memcgid, &pgdat, &eviction);
0245 
0246     rcu_read_lock();
0247     /*
0248      * Look up the memcg associated with the stored ID. It might
0249      * have been deleted since the page's eviction.
0250      *
0251      * Note that in rare events the ID could have been recycled
0252      * for a new cgroup that refaults a shared page. This is
0253      * impossible to tell from the available data. However, this
0254      * should be a rare and limited disturbance, and activations
0255      * are always speculative anyway. Ultimately, it's the aging
0256      * algorithm's job to shake out the minimum access frequency
0257      * for the active cache.
0258      *
0259      * XXX: On !CONFIG_MEMCG, this will always return NULL; it
0260      * would be better if the root_mem_cgroup existed in all
0261      * configurations instead.
0262      */
0263     memcg = mem_cgroup_from_id(memcgid);
0264     if (!mem_cgroup_disabled() && !memcg) {
0265         rcu_read_unlock();
0266         return false;
0267     }
0268     lruvec = mem_cgroup_lruvec(pgdat, memcg);
0269     refault = atomic_long_read(&lruvec->inactive_age);
0270     active_file = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE);
0271     rcu_read_unlock();
0272 
0273     /*
0274      * The unsigned subtraction here gives an accurate distance
0275      * across inactive_age overflows in most cases.
0276      *
0277      * There is a special case: usually, shadow entries have a
0278      * short lifetime and are either refaulted or reclaimed along
0279      * with the inode before they get too old.  But it is not
0280      * impossible for the inactive_age to lap a shadow entry in
0281      * the field, which can then can result in a false small
0282      * refault distance, leading to a false activation should this
0283      * old entry actually refault again.  However, earlier kernels
0284      * used to deactivate unconditionally with *every* reclaim
0285      * invocation for the longest time, so the occasional
0286      * inappropriate activation leading to pressure on the active
0287      * list is not a problem.
0288      */
0289     refault_distance = (refault - eviction) & EVICTION_MASK;
0290 
0291     inc_node_state(pgdat, WORKINGSET_REFAULT);
0292 
0293     if (refault_distance <= active_file) {
0294         inc_node_state(pgdat, WORKINGSET_ACTIVATE);
0295         return true;
0296     }
0297     return false;
0298 }
0299 
0300 /**
0301  * workingset_activation - note a page activation
0302  * @page: page that is being activated
0303  */
0304 void workingset_activation(struct page *page)
0305 {
0306     struct mem_cgroup *memcg;
0307     struct lruvec *lruvec;
0308 
0309     rcu_read_lock();
0310     /*
0311      * Filter non-memcg pages here, e.g. unmap can call
0312      * mark_page_accessed() on VDSO pages.
0313      *
0314      * XXX: See workingset_refault() - this should return
0315      * root_mem_cgroup even for !CONFIG_MEMCG.
0316      */
0317     memcg = page_memcg_rcu(page);
0318     if (!mem_cgroup_disabled() && !memcg)
0319         goto out;
0320     lruvec = mem_cgroup_lruvec(page_pgdat(page), memcg);
0321     atomic_long_inc(&lruvec->inactive_age);
0322 out:
0323     rcu_read_unlock();
0324 }
0325 
0326 /*
0327  * Shadow entries reflect the share of the working set that does not
0328  * fit into memory, so their number depends on the access pattern of
0329  * the workload.  In most cases, they will refault or get reclaimed
0330  * along with the inode, but a (malicious) workload that streams
0331  * through files with a total size several times that of available
0332  * memory, while preventing the inodes from being reclaimed, can
0333  * create excessive amounts of shadow nodes.  To keep a lid on this,
0334  * track shadow nodes and reclaim them when they grow way past the
0335  * point where they would still be useful.
0336  */
0337 
0338 static struct list_lru shadow_nodes;
0339 
0340 void workingset_update_node(struct radix_tree_node *node, void *private)
0341 {
0342     struct address_space *mapping = private;
0343 
0344     /* Only regular page cache has shadow entries */
0345     if (dax_mapping(mapping) || shmem_mapping(mapping))
0346         return;
0347 
0348     /*
0349      * Track non-empty nodes that contain only shadow entries;
0350      * unlink those that contain pages or are being freed.
0351      *
0352      * Avoid acquiring the list_lru lock when the nodes are
0353      * already where they should be. The list_empty() test is safe
0354      * as node->private_list is protected by &mapping->tree_lock.
0355      */
0356     if (node->count && node->count == node->exceptional) {
0357         if (list_empty(&node->private_list)) {
0358             node->private_data = mapping;
0359             list_lru_add(&shadow_nodes, &node->private_list);
0360         }
0361     } else {
0362         if (!list_empty(&node->private_list))
0363             list_lru_del(&shadow_nodes, &node->private_list);
0364     }
0365 }
0366 
0367 static unsigned long count_shadow_nodes(struct shrinker *shrinker,
0368                     struct shrink_control *sc)
0369 {
0370     unsigned long max_nodes;
0371     unsigned long nodes;
0372     unsigned long cache;
0373 
0374     /* list_lru lock nests inside IRQ-safe mapping->tree_lock */
0375     local_irq_disable();
0376     nodes = list_lru_shrink_count(&shadow_nodes, sc);
0377     local_irq_enable();
0378 
0379     /*
0380      * Approximate a reasonable limit for the radix tree nodes
0381      * containing shadow entries. We don't need to keep more
0382      * shadow entries than possible pages on the active list,
0383      * since refault distances bigger than that are dismissed.
0384      *
0385      * The size of the active list converges toward 100% of
0386      * overall page cache as memory grows, with only a tiny
0387      * inactive list. Assume the total cache size for that.
0388      *
0389      * Nodes might be sparsely populated, with only one shadow
0390      * entry in the extreme case. Obviously, we cannot keep one
0391      * node for every eligible shadow entry, so compromise on a
0392      * worst-case density of 1/8th. Below that, not all eligible
0393      * refaults can be detected anymore.
0394      *
0395      * On 64-bit with 7 radix_tree_nodes per page and 64 slots
0396      * each, this will reclaim shadow entries when they consume
0397      * ~1.8% of available memory:
0398      *
0399      * PAGE_SIZE / radix_tree_nodes / node_entries * 8 / PAGE_SIZE
0400      */
0401     if (sc->memcg) {
0402         cache = mem_cgroup_node_nr_lru_pages(sc->memcg, sc->nid,
0403                              LRU_ALL_FILE);
0404     } else {
0405         cache = node_page_state(NODE_DATA(sc->nid), NR_ACTIVE_FILE) +
0406             node_page_state(NODE_DATA(sc->nid), NR_INACTIVE_FILE);
0407     }
0408     max_nodes = cache >> (RADIX_TREE_MAP_SHIFT - 3);
0409 
0410     if (nodes <= max_nodes)
0411         return 0;
0412     return nodes - max_nodes;
0413 }
0414 
0415 static enum lru_status shadow_lru_isolate(struct list_head *item,
0416                       struct list_lru_one *lru,
0417                       spinlock_t *lru_lock,
0418                       void *arg)
0419 {
0420     struct address_space *mapping;
0421     struct radix_tree_node *node;
0422     unsigned int i;
0423     int ret;
0424 
0425     /*
0426      * Page cache insertions and deletions synchroneously maintain
0427      * the shadow node LRU under the mapping->tree_lock and the
0428      * lru_lock.  Because the page cache tree is emptied before
0429      * the inode can be destroyed, holding the lru_lock pins any
0430      * address_space that has radix tree nodes on the LRU.
0431      *
0432      * We can then safely transition to the mapping->tree_lock to
0433      * pin only the address_space of the particular node we want
0434      * to reclaim, take the node off-LRU, and drop the lru_lock.
0435      */
0436 
0437     node = container_of(item, struct radix_tree_node, private_list);
0438     mapping = node->private_data;
0439 
0440     /* Coming from the list, invert the lock order */
0441     if (!spin_trylock(&mapping->tree_lock)) {
0442         spin_unlock(lru_lock);
0443         ret = LRU_RETRY;
0444         goto out;
0445     }
0446 
0447     list_lru_isolate(lru, item);
0448     spin_unlock(lru_lock);
0449 
0450     /*
0451      * The nodes should only contain one or more shadow entries,
0452      * no pages, so we expect to be able to remove them all and
0453      * delete and free the empty node afterwards.
0454      */
0455     if (WARN_ON_ONCE(!node->exceptional))
0456         goto out_invalid;
0457     if (WARN_ON_ONCE(node->count != node->exceptional))
0458         goto out_invalid;
0459     for (i = 0; i < RADIX_TREE_MAP_SIZE; i++) {
0460         if (node->slots[i]) {
0461             if (WARN_ON_ONCE(!radix_tree_exceptional_entry(node->slots[i])))
0462                 goto out_invalid;
0463             if (WARN_ON_ONCE(!node->exceptional))
0464                 goto out_invalid;
0465             if (WARN_ON_ONCE(!mapping->nrexceptional))
0466                 goto out_invalid;
0467             node->slots[i] = NULL;
0468             node->exceptional--;
0469             node->count--;
0470             mapping->nrexceptional--;
0471         }
0472     }
0473     if (WARN_ON_ONCE(node->exceptional))
0474         goto out_invalid;
0475     inc_node_state(page_pgdat(virt_to_page(node)), WORKINGSET_NODERECLAIM);
0476     __radix_tree_delete_node(&mapping->page_tree, node,
0477                  workingset_update_node, mapping);
0478 
0479 out_invalid:
0480     spin_unlock(&mapping->tree_lock);
0481     ret = LRU_REMOVED_RETRY;
0482 out:
0483     local_irq_enable();
0484     cond_resched();
0485     local_irq_disable();
0486     spin_lock(lru_lock);
0487     return ret;
0488 }
0489 
0490 static unsigned long scan_shadow_nodes(struct shrinker *shrinker,
0491                        struct shrink_control *sc)
0492 {
0493     unsigned long ret;
0494 
0495     /* list_lru lock nests inside IRQ-safe mapping->tree_lock */
0496     local_irq_disable();
0497     ret = list_lru_shrink_walk(&shadow_nodes, sc, shadow_lru_isolate, NULL);
0498     local_irq_enable();
0499     return ret;
0500 }
0501 
0502 static struct shrinker workingset_shadow_shrinker = {
0503     .count_objects = count_shadow_nodes,
0504     .scan_objects = scan_shadow_nodes,
0505     .seeks = DEFAULT_SEEKS,
0506     .flags = SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE,
0507 };
0508 
0509 /*
0510  * Our list_lru->lock is IRQ-safe as it nests inside the IRQ-safe
0511  * mapping->tree_lock.
0512  */
0513 static struct lock_class_key shadow_nodes_key;
0514 
0515 static int __init workingset_init(void)
0516 {
0517     unsigned int timestamp_bits;
0518     unsigned int max_order;
0519     int ret;
0520 
0521     BUILD_BUG_ON(BITS_PER_LONG < EVICTION_SHIFT);
0522     /*
0523      * Calculate the eviction bucket size to cover the longest
0524      * actionable refault distance, which is currently half of
0525      * memory (totalram_pages/2). However, memory hotplug may add
0526      * some more pages at runtime, so keep working with up to
0527      * double the initial memory by using totalram_pages as-is.
0528      */
0529     timestamp_bits = BITS_PER_LONG - EVICTION_SHIFT;
0530     max_order = fls_long(totalram_pages - 1);
0531     if (max_order > timestamp_bits)
0532         bucket_order = max_order - timestamp_bits;
0533     pr_info("workingset: timestamp_bits=%d max_order=%d bucket_order=%u\n",
0534            timestamp_bits, max_order, bucket_order);
0535 
0536     ret = list_lru_init_key(&shadow_nodes, &shadow_nodes_key);
0537     if (ret)
0538         goto err;
0539     ret = register_shrinker(&workingset_shadow_shrinker);
0540     if (ret)
0541         goto err_list_lru;
0542     return 0;
0543 err_list_lru:
0544     list_lru_destroy(&shadow_nodes);
0545 err:
0546     return ret;
0547 }
0548 module_init(workingset_init);