1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
7 * Swap reorganised 29.12.95, Stephen Tweedie.
8 * kswapd added: 7.1.96 sct
9 * Removed kswapd_ctl limits, and swap out as many pages as needed
10 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
11 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
12 * Multiqueue VM started 5.8.00, Rik van Riel.
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 #include <linux/sched/mm.h>
19 #include <linux/module.h>
20 #include <linux/gfp.h>
21 #include <linux/kernel_stat.h>
22 #include <linux/swap.h>
23 #include <linux/pagemap.h>
24 #include <linux/init.h>
25 #include <linux/highmem.h>
26 #include <linux/vmpressure.h>
27 #include <linux/vmstat.h>
28 #include <linux/file.h>
29 #include <linux/writeback.h>
30 #include <linux/blkdev.h>
31 #include <linux/buffer_head.h> /* for try_to_release_page(),
32 buffer_heads_over_limit */
33 #include <linux/mm_inline.h>
34 #include <linux/backing-dev.h>
35 #include <linux/rmap.h>
36 #include <linux/topology.h>
37 #include <linux/cpu.h>
38 #include <linux/cpuset.h>
39 #include <linux/compaction.h>
40 #include <linux/notifier.h>
41 #include <linux/rwsem.h>
42 #include <linux/delay.h>
43 #include <linux/kthread.h>
44 #include <linux/freezer.h>
45 #include <linux/memcontrol.h>
46 #include <linux/delayacct.h>
47 #include <linux/sysctl.h>
48 #include <linux/oom.h>
49 #include <linux/pagevec.h>
50 #include <linux/prefetch.h>
51 #include <linux/printk.h>
52 #include <linux/dax.h>
53 #include <linux/psi.h>
55 #include <asm/tlbflush.h>
56 #include <asm/div64.h>
58 #include <linux/swapops.h>
59 #include <linux/balloon_compaction.h>
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/vmscan.h>
67 /* How many pages shrink_list() should reclaim */
68 unsigned long nr_to_reclaim;
71 * Nodemask of nodes allowed by the caller. If NULL, all nodes
77 * The memory cgroup that hit its limit and as a result is the
78 * primary target of this reclaim invocation.
80 struct mem_cgroup *target_mem_cgroup;
82 /* Can active pages be deactivated as part of reclaim? */
83 #define DEACTIVATE_ANON 1
84 #define DEACTIVATE_FILE 2
85 unsigned int may_deactivate:2;
86 unsigned int force_deactivate:1;
87 unsigned int skipped_deactivate:1;
89 /* Writepage batching in laptop mode; RECLAIM_WRITE */
90 unsigned int may_writepage:1;
92 /* Can mapped pages be reclaimed? */
93 unsigned int may_unmap:1;
95 /* Can pages be swapped as part of reclaim? */
96 unsigned int may_swap:1;
99 * Cgroups are not reclaimed below their configured memory.low,
100 * unless we threaten to OOM. If any cgroups are skipped due to
101 * memory.low and nothing was reclaimed, go back for memory.low.
103 unsigned int memcg_low_reclaim:1;
104 unsigned int memcg_low_skipped:1;
106 unsigned int hibernation_mode:1;
108 /* One of the zones is ready for compaction */
109 unsigned int compaction_ready:1;
111 /* There is easily reclaimable cold cache in the current node */
112 unsigned int cache_trim_mode:1;
114 /* The file pages on the current node are dangerously low */
115 unsigned int file_is_tiny:1;
117 /* Allocation order */
120 /* Scan (total_size >> priority) pages at once */
123 /* The highest zone to isolate pages for reclaim from */
126 /* This context's GFP mask */
129 /* Incremented by the number of inactive pages that were scanned */
130 unsigned long nr_scanned;
132 /* Number of pages freed so far during a call to shrink_zones() */
133 unsigned long nr_reclaimed;
137 unsigned int unqueued_dirty;
138 unsigned int congested;
139 unsigned int writeback;
140 unsigned int immediate;
141 unsigned int file_taken;
145 /* for recording the reclaimed slab by now */
146 struct reclaim_state reclaim_state;
149 #ifdef ARCH_HAS_PREFETCH
150 #define prefetch_prev_lru_page(_page, _base, _field) \
152 if ((_page)->lru.prev != _base) { \
155 prev = lru_to_page(&(_page->lru)); \
156 prefetch(&prev->_field); \
160 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
163 #ifdef ARCH_HAS_PREFETCHW
164 #define prefetchw_prev_lru_page(_page, _base, _field) \
166 if ((_page)->lru.prev != _base) { \
169 prev = lru_to_page(&(_page->lru)); \
170 prefetchw(&prev->_field); \
174 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
178 * From 0 .. 100. Higher means more swappy.
180 int vm_swappiness = 60;
182 * The total number of pages which are beyond the high watermark within all
185 unsigned long vm_total_pages;
187 static void set_task_reclaim_state(struct task_struct *task,
188 struct reclaim_state *rs)
190 /* Check for an overwrite */
191 WARN_ON_ONCE(rs && task->reclaim_state);
193 /* Check for the nulling of an already-nulled member */
194 WARN_ON_ONCE(!rs && !task->reclaim_state);
196 task->reclaim_state = rs;
199 static LIST_HEAD(shrinker_list);
200 static DECLARE_RWSEM(shrinker_rwsem);
204 * We allow subsystems to populate their shrinker-related
205 * LRU lists before register_shrinker_prepared() is called
206 * for the shrinker, since we don't want to impose
207 * restrictions on their internal registration order.
208 * In this case shrink_slab_memcg() may find corresponding
209 * bit is set in the shrinkers map.
211 * This value is used by the function to detect registering
212 * shrinkers and to skip do_shrink_slab() calls for them.
214 #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
216 static DEFINE_IDR(shrinker_idr);
217 static int shrinker_nr_max;
219 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
221 int id, ret = -ENOMEM;
223 down_write(&shrinker_rwsem);
224 /* This may call shrinker, so it must use down_read_trylock() */
225 id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
229 if (id >= shrinker_nr_max) {
230 if (memcg_expand_shrinker_maps(id)) {
231 idr_remove(&shrinker_idr, id);
235 shrinker_nr_max = id + 1;
240 up_write(&shrinker_rwsem);
244 static void unregister_memcg_shrinker(struct shrinker *shrinker)
246 int id = shrinker->id;
250 down_write(&shrinker_rwsem);
251 idr_remove(&shrinker_idr, id);
252 up_write(&shrinker_rwsem);
255 static bool cgroup_reclaim(struct scan_control *sc)
257 return sc->target_mem_cgroup;
261 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
262 * @sc: scan_control in question
264 * The normal page dirty throttling mechanism in balance_dirty_pages() is
265 * completely broken with the legacy memcg and direct stalling in
266 * shrink_page_list() is used for throttling instead, which lacks all the
267 * niceties such as fairness, adaptive pausing, bandwidth proportional
268 * allocation and configurability.
270 * This function tests whether the vmscan currently in progress can assume
271 * that the normal dirty throttling mechanism is operational.
273 static bool writeback_throttling_sane(struct scan_control *sc)
275 if (!cgroup_reclaim(sc))
277 #ifdef CONFIG_CGROUP_WRITEBACK
278 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
284 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
289 static void unregister_memcg_shrinker(struct shrinker *shrinker)
293 static bool cgroup_reclaim(struct scan_control *sc)
298 static bool writeback_throttling_sane(struct scan_control *sc)
305 * This misses isolated pages which are not accounted for to save counters.
306 * As the data only determines if reclaim or compaction continues, it is
307 * not expected that isolated pages will be a dominating factor.
309 unsigned long zone_reclaimable_pages(struct zone *zone)
313 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
314 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
315 if (get_nr_swap_pages() > 0)
316 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
317 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
323 * lruvec_lru_size - Returns the number of pages on the given LRU list.
324 * @lruvec: lru vector
326 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
328 unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
330 unsigned long size = 0;
333 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
334 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
336 if (!managed_zone(zone))
339 if (!mem_cgroup_disabled())
340 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
342 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
348 * Add a shrinker callback to be called from the vm.
350 int prealloc_shrinker(struct shrinker *shrinker)
352 unsigned int size = sizeof(*shrinker->nr_deferred);
354 if (shrinker->flags & SHRINKER_NUMA_AWARE)
357 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
358 if (!shrinker->nr_deferred)
361 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
362 if (prealloc_memcg_shrinker(shrinker))
369 kfree(shrinker->nr_deferred);
370 shrinker->nr_deferred = NULL;
374 void free_prealloced_shrinker(struct shrinker *shrinker)
376 if (!shrinker->nr_deferred)
379 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
380 unregister_memcg_shrinker(shrinker);
382 kfree(shrinker->nr_deferred);
383 shrinker->nr_deferred = NULL;
386 void register_shrinker_prepared(struct shrinker *shrinker)
388 down_write(&shrinker_rwsem);
389 list_add_tail(&shrinker->list, &shrinker_list);
391 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
392 idr_replace(&shrinker_idr, shrinker, shrinker->id);
394 up_write(&shrinker_rwsem);
397 int register_shrinker(struct shrinker *shrinker)
399 int err = prealloc_shrinker(shrinker);
403 register_shrinker_prepared(shrinker);
406 EXPORT_SYMBOL(register_shrinker);
411 void unregister_shrinker(struct shrinker *shrinker)
413 if (!shrinker->nr_deferred)
415 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
416 unregister_memcg_shrinker(shrinker);
417 down_write(&shrinker_rwsem);
418 list_del(&shrinker->list);
419 up_write(&shrinker_rwsem);
420 kfree(shrinker->nr_deferred);
421 shrinker->nr_deferred = NULL;
423 EXPORT_SYMBOL(unregister_shrinker);
425 #define SHRINK_BATCH 128
427 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
428 struct shrinker *shrinker, int priority)
430 unsigned long freed = 0;
431 unsigned long long delta;
436 int nid = shrinkctl->nid;
437 long batch_size = shrinker->batch ? shrinker->batch
439 long scanned = 0, next_deferred;
441 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
444 freeable = shrinker->count_objects(shrinker, shrinkctl);
445 if (freeable == 0 || freeable == SHRINK_EMPTY)
449 * copy the current shrinker scan count into a local variable
450 * and zero it so that other concurrent shrinker invocations
451 * don't also do this scanning work.
453 nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
456 if (shrinker->seeks) {
457 delta = freeable >> priority;
459 do_div(delta, shrinker->seeks);
462 * These objects don't require any IO to create. Trim
463 * them aggressively under memory pressure to keep
464 * them from causing refetches in the IO caches.
466 delta = freeable / 2;
470 if (total_scan < 0) {
471 pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
472 shrinker->scan_objects, total_scan);
473 total_scan = freeable;
476 next_deferred = total_scan;
479 * We need to avoid excessive windup on filesystem shrinkers
480 * due to large numbers of GFP_NOFS allocations causing the
481 * shrinkers to return -1 all the time. This results in a large
482 * nr being built up so when a shrink that can do some work
483 * comes along it empties the entire cache due to nr >>>
484 * freeable. This is bad for sustaining a working set in
487 * Hence only allow the shrinker to scan the entire cache when
488 * a large delta change is calculated directly.
490 if (delta < freeable / 4)
491 total_scan = min(total_scan, freeable / 2);
494 * Avoid risking looping forever due to too large nr value:
495 * never try to free more than twice the estimate number of
498 if (total_scan > freeable * 2)
499 total_scan = freeable * 2;
501 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
502 freeable, delta, total_scan, priority);
505 * Normally, we should not scan less than batch_size objects in one
506 * pass to avoid too frequent shrinker calls, but if the slab has less
507 * than batch_size objects in total and we are really tight on memory,
508 * we will try to reclaim all available objects, otherwise we can end
509 * up failing allocations although there are plenty of reclaimable
510 * objects spread over several slabs with usage less than the
513 * We detect the "tight on memory" situations by looking at the total
514 * number of objects we want to scan (total_scan). If it is greater
515 * than the total number of objects on slab (freeable), we must be
516 * scanning at high prio and therefore should try to reclaim as much as
519 while (total_scan >= batch_size ||
520 total_scan >= freeable) {
522 unsigned long nr_to_scan = min(batch_size, total_scan);
524 shrinkctl->nr_to_scan = nr_to_scan;
525 shrinkctl->nr_scanned = nr_to_scan;
526 ret = shrinker->scan_objects(shrinker, shrinkctl);
527 if (ret == SHRINK_STOP)
531 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
532 total_scan -= shrinkctl->nr_scanned;
533 scanned += shrinkctl->nr_scanned;
538 if (next_deferred >= scanned)
539 next_deferred -= scanned;
543 * move the unused scan count back into the shrinker in a
544 * manner that handles concurrent updates. If we exhausted the
545 * scan, there is no need to do an update.
547 if (next_deferred > 0)
548 new_nr = atomic_long_add_return(next_deferred,
549 &shrinker->nr_deferred[nid]);
551 new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
553 trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
558 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
559 struct mem_cgroup *memcg, int priority)
561 struct memcg_shrinker_map *map;
562 unsigned long ret, freed = 0;
565 if (!mem_cgroup_online(memcg))
568 if (!down_read_trylock(&shrinker_rwsem))
571 map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
576 for_each_set_bit(i, map->map, shrinker_nr_max) {
577 struct shrink_control sc = {
578 .gfp_mask = gfp_mask,
582 struct shrinker *shrinker;
584 shrinker = idr_find(&shrinker_idr, i);
585 if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
587 clear_bit(i, map->map);
591 /* Call non-slab shrinkers even though kmem is disabled */
592 if (!memcg_kmem_enabled() &&
593 !(shrinker->flags & SHRINKER_NONSLAB))
596 ret = do_shrink_slab(&sc, shrinker, priority);
597 if (ret == SHRINK_EMPTY) {
598 clear_bit(i, map->map);
600 * After the shrinker reported that it had no objects to
601 * free, but before we cleared the corresponding bit in
602 * the memcg shrinker map, a new object might have been
603 * added. To make sure, we have the bit set in this
604 * case, we invoke the shrinker one more time and reset
605 * the bit if it reports that it is not empty anymore.
606 * The memory barrier here pairs with the barrier in
607 * memcg_set_shrinker_bit():
609 * list_lru_add() shrink_slab_memcg()
610 * list_add_tail() clear_bit()
612 * set_bit() do_shrink_slab()
614 smp_mb__after_atomic();
615 ret = do_shrink_slab(&sc, shrinker, priority);
616 if (ret == SHRINK_EMPTY)
619 memcg_set_shrinker_bit(memcg, nid, i);
623 if (rwsem_is_contended(&shrinker_rwsem)) {
629 up_read(&shrinker_rwsem);
632 #else /* CONFIG_MEMCG */
633 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
634 struct mem_cgroup *memcg, int priority)
638 #endif /* CONFIG_MEMCG */
641 * shrink_slab - shrink slab caches
642 * @gfp_mask: allocation context
643 * @nid: node whose slab caches to target
644 * @memcg: memory cgroup whose slab caches to target
645 * @priority: the reclaim priority
647 * Call the shrink functions to age shrinkable caches.
649 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
650 * unaware shrinkers will receive a node id of 0 instead.
652 * @memcg specifies the memory cgroup to target. Unaware shrinkers
653 * are called only if it is the root cgroup.
655 * @priority is sc->priority, we take the number of objects and >> by priority
656 * in order to get the scan target.
658 * Returns the number of reclaimed slab objects.
660 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
661 struct mem_cgroup *memcg,
664 unsigned long ret, freed = 0;
665 struct shrinker *shrinker;
668 * The root memcg might be allocated even though memcg is disabled
669 * via "cgroup_disable=memory" boot parameter. This could make
670 * mem_cgroup_is_root() return false, then just run memcg slab
671 * shrink, but skip global shrink. This may result in premature
674 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
675 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
677 if (!down_read_trylock(&shrinker_rwsem))
680 list_for_each_entry(shrinker, &shrinker_list, list) {
681 struct shrink_control sc = {
682 .gfp_mask = gfp_mask,
687 ret = do_shrink_slab(&sc, shrinker, priority);
688 if (ret == SHRINK_EMPTY)
692 * Bail out if someone want to register a new shrinker to
693 * prevent the regsitration from being stalled for long periods
694 * by parallel ongoing shrinking.
696 if (rwsem_is_contended(&shrinker_rwsem)) {
702 up_read(&shrinker_rwsem);
708 void drop_slab_node(int nid)
713 struct mem_cgroup *memcg = NULL;
716 memcg = mem_cgroup_iter(NULL, NULL, NULL);
718 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
719 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
720 } while (freed > 10);
727 for_each_online_node(nid)
731 static inline int is_page_cache_freeable(struct page *page)
734 * A freeable page cache page is referenced only by the caller
735 * that isolated the page, the page cache and optional buffer
736 * heads at page->private.
738 int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
740 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
743 static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
745 if (current->flags & PF_SWAPWRITE)
747 if (!inode_write_congested(inode))
749 if (inode_to_bdi(inode) == current->backing_dev_info)
755 * We detected a synchronous write error writing a page out. Probably
756 * -ENOSPC. We need to propagate that into the address_space for a subsequent
757 * fsync(), msync() or close().
759 * The tricky part is that after writepage we cannot touch the mapping: nothing
760 * prevents it from being freed up. But we have a ref on the page and once
761 * that page is locked, the mapping is pinned.
763 * We're allowed to run sleeping lock_page() here because we know the caller has
766 static void handle_write_error(struct address_space *mapping,
767 struct page *page, int error)
770 if (page_mapping(page) == mapping)
771 mapping_set_error(mapping, error);
775 /* possible outcome of pageout() */
777 /* failed to write page out, page is locked */
779 /* move page to the active list, page is locked */
781 /* page has been sent to the disk successfully, page is unlocked */
783 /* page is clean and locked */
788 * pageout is called by shrink_page_list() for each dirty page.
789 * Calls ->writepage().
791 static pageout_t pageout(struct page *page, struct address_space *mapping,
792 struct scan_control *sc)
795 * If the page is dirty, only perform writeback if that write
796 * will be non-blocking. To prevent this allocation from being
797 * stalled by pagecache activity. But note that there may be
798 * stalls if we need to run get_block(). We could test
799 * PagePrivate for that.
801 * If this process is currently in __generic_file_write_iter() against
802 * this page's queue, we can perform writeback even if that
805 * If the page is swapcache, write it back even if that would
806 * block, for some throttling. This happens by accident, because
807 * swap_backing_dev_info is bust: it doesn't reflect the
808 * congestion state of the swapdevs. Easy to fix, if needed.
810 if (!is_page_cache_freeable(page))
814 * Some data journaling orphaned pages can have
815 * page->mapping == NULL while being dirty with clean buffers.
817 if (page_has_private(page)) {
818 if (try_to_free_buffers(page)) {
819 ClearPageDirty(page);
820 pr_info("%s: orphaned page\n", __func__);
826 if (mapping->a_ops->writepage == NULL)
827 return PAGE_ACTIVATE;
828 if (!may_write_to_inode(mapping->host, sc))
831 if (clear_page_dirty_for_io(page)) {
833 struct writeback_control wbc = {
834 .sync_mode = WB_SYNC_NONE,
835 .nr_to_write = SWAP_CLUSTER_MAX,
837 .range_end = LLONG_MAX,
841 SetPageReclaim(page);
842 res = mapping->a_ops->writepage(page, &wbc);
844 handle_write_error(mapping, page, res);
845 if (res == AOP_WRITEPAGE_ACTIVATE) {
846 ClearPageReclaim(page);
847 return PAGE_ACTIVATE;
850 if (!PageWriteback(page)) {
851 /* synchronous write or broken a_ops? */
852 ClearPageReclaim(page);
854 trace_mm_vmscan_writepage(page);
855 inc_node_page_state(page, NR_VMSCAN_WRITE);
863 * Same as remove_mapping, but if the page is removed from the mapping, it
864 * gets returned with a refcount of 0.
866 static int __remove_mapping(struct address_space *mapping, struct page *page,
867 bool reclaimed, struct mem_cgroup *target_memcg)
872 BUG_ON(!PageLocked(page));
873 BUG_ON(mapping != page_mapping(page));
875 xa_lock_irqsave(&mapping->i_pages, flags);
877 * The non racy check for a busy page.
879 * Must be careful with the order of the tests. When someone has
880 * a ref to the page, it may be possible that they dirty it then
881 * drop the reference. So if PageDirty is tested before page_count
882 * here, then the following race may occur:
884 * get_user_pages(&page);
885 * [user mapping goes away]
887 * !PageDirty(page) [good]
888 * SetPageDirty(page);
890 * !page_count(page) [good, discard it]
892 * [oops, our write_to data is lost]
894 * Reversing the order of the tests ensures such a situation cannot
895 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
896 * load is not satisfied before that of page->_refcount.
898 * Note that if SetPageDirty is always performed via set_page_dirty,
899 * and thus under the i_pages lock, then this ordering is not required.
901 refcount = 1 + compound_nr(page);
902 if (!page_ref_freeze(page, refcount))
904 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
905 if (unlikely(PageDirty(page))) {
906 page_ref_unfreeze(page, refcount);
910 if (PageSwapCache(page)) {
911 swp_entry_t swap = { .val = page_private(page) };
912 mem_cgroup_swapout(page, swap);
913 __delete_from_swap_cache(page, swap);
914 xa_unlock_irqrestore(&mapping->i_pages, flags);
915 put_swap_page(page, swap);
917 void (*freepage)(struct page *);
920 freepage = mapping->a_ops->freepage;
922 * Remember a shadow entry for reclaimed file cache in
923 * order to detect refaults, thus thrashing, later on.
925 * But don't store shadows in an address space that is
926 * already exiting. This is not just an optizimation,
927 * inode reclaim needs to empty out the radix tree or
928 * the nodes are lost. Don't plant shadows behind its
931 * We also don't store shadows for DAX mappings because the
932 * only page cache pages found in these are zero pages
933 * covering holes, and because we don't want to mix DAX
934 * exceptional entries and shadow exceptional entries in the
935 * same address_space.
937 if (reclaimed && page_is_file_cache(page) &&
938 !mapping_exiting(mapping) && !dax_mapping(mapping))
939 shadow = workingset_eviction(page, target_memcg);
940 __delete_from_page_cache(page, shadow);
941 xa_unlock_irqrestore(&mapping->i_pages, flags);
943 if (freepage != NULL)
950 xa_unlock_irqrestore(&mapping->i_pages, flags);
955 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
956 * someone else has a ref on the page, abort and return 0. If it was
957 * successfully detached, return 1. Assumes the caller has a single ref on
960 int remove_mapping(struct address_space *mapping, struct page *page)
962 if (__remove_mapping(mapping, page, false, NULL)) {
964 * Unfreezing the refcount with 1 rather than 2 effectively
965 * drops the pagecache ref for us without requiring another
968 page_ref_unfreeze(page, 1);
975 * putback_lru_page - put previously isolated page onto appropriate LRU list
976 * @page: page to be put back to appropriate lru list
978 * Add previously isolated @page to appropriate LRU list.
979 * Page may still be unevictable for other reasons.
981 * lru_lock must not be held, interrupts must be enabled.
983 void putback_lru_page(struct page *page)
986 put_page(page); /* drop ref from isolate */
989 enum page_references {
991 PAGEREF_RECLAIM_CLEAN,
996 static enum page_references page_check_references(struct page *page,
997 struct scan_control *sc)
999 int referenced_ptes, referenced_page;
1000 unsigned long vm_flags;
1002 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1004 referenced_page = TestClearPageReferenced(page);
1007 * Mlock lost the isolation race with us. Let try_to_unmap()
1008 * move the page to the unevictable list.
1010 if (vm_flags & VM_LOCKED)
1011 return PAGEREF_RECLAIM;
1013 if (referenced_ptes) {
1014 if (PageSwapBacked(page))
1015 return PAGEREF_ACTIVATE;
1017 * All mapped pages start out with page table
1018 * references from the instantiating fault, so we need
1019 * to look twice if a mapped file page is used more
1022 * Mark it and spare it for another trip around the
1023 * inactive list. Another page table reference will
1024 * lead to its activation.
1026 * Note: the mark is set for activated pages as well
1027 * so that recently deactivated but used pages are
1028 * quickly recovered.
1030 SetPageReferenced(page);
1032 if (referenced_page || referenced_ptes > 1)
1033 return PAGEREF_ACTIVATE;
1036 * Activate file-backed executable pages after first usage.
1038 if (vm_flags & VM_EXEC)
1039 return PAGEREF_ACTIVATE;
1041 return PAGEREF_KEEP;
1044 /* Reclaim if clean, defer dirty pages to writeback */
1045 if (referenced_page && !PageSwapBacked(page))
1046 return PAGEREF_RECLAIM_CLEAN;
1048 return PAGEREF_RECLAIM;
1051 /* Check if a page is dirty or under writeback */
1052 static void page_check_dirty_writeback(struct page *page,
1053 bool *dirty, bool *writeback)
1055 struct address_space *mapping;
1058 * Anonymous pages are not handled by flushers and must be written
1059 * from reclaim context. Do not stall reclaim based on them
1061 if (!page_is_file_cache(page) ||
1062 (PageAnon(page) && !PageSwapBacked(page))) {
1068 /* By default assume that the page flags are accurate */
1069 *dirty = PageDirty(page);
1070 *writeback = PageWriteback(page);
1072 /* Verify dirty/writeback state if the filesystem supports it */
1073 if (!page_has_private(page))
1076 mapping = page_mapping(page);
1077 if (mapping && mapping->a_ops->is_dirty_writeback)
1078 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1082 * shrink_page_list() returns the number of reclaimed pages
1084 static unsigned long shrink_page_list(struct list_head *page_list,
1085 struct pglist_data *pgdat,
1086 struct scan_control *sc,
1087 struct reclaim_stat *stat,
1088 bool ignore_references)
1090 LIST_HEAD(ret_pages);
1091 LIST_HEAD(free_pages);
1092 unsigned nr_reclaimed = 0;
1093 unsigned pgactivate = 0;
1095 memset(stat, 0, sizeof(*stat));
1098 while (!list_empty(page_list)) {
1099 struct address_space *mapping;
1102 enum page_references references = PAGEREF_RECLAIM;
1103 bool dirty, writeback;
1104 unsigned int nr_pages;
1108 page = lru_to_page(page_list);
1109 list_del(&page->lru);
1111 if (!trylock_page(page))
1114 VM_BUG_ON_PAGE(PageActive(page), page);
1116 nr_pages = compound_nr(page);
1118 /* Account the number of base pages even though THP */
1119 sc->nr_scanned += nr_pages;
1121 if (unlikely(!page_evictable(page)))
1122 goto activate_locked;
1124 if (!sc->may_unmap && page_mapped(page))
1127 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1128 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1131 * The number of dirty pages determines if a node is marked
1132 * reclaim_congested which affects wait_iff_congested. kswapd
1133 * will stall and start writing pages if the tail of the LRU
1134 * is all dirty unqueued pages.
1136 page_check_dirty_writeback(page, &dirty, &writeback);
1137 if (dirty || writeback)
1140 if (dirty && !writeback)
1141 stat->nr_unqueued_dirty++;
1144 * Treat this page as congested if the underlying BDI is or if
1145 * pages are cycling through the LRU so quickly that the
1146 * pages marked for immediate reclaim are making it to the
1147 * end of the LRU a second time.
1149 mapping = page_mapping(page);
1150 if (((dirty || writeback) && mapping &&
1151 inode_write_congested(mapping->host)) ||
1152 (writeback && PageReclaim(page)))
1153 stat->nr_congested++;
1156 * If a page at the tail of the LRU is under writeback, there
1157 * are three cases to consider.
1159 * 1) If reclaim is encountering an excessive number of pages
1160 * under writeback and this page is both under writeback and
1161 * PageReclaim then it indicates that pages are being queued
1162 * for IO but are being recycled through the LRU before the
1163 * IO can complete. Waiting on the page itself risks an
1164 * indefinite stall if it is impossible to writeback the
1165 * page due to IO error or disconnected storage so instead
1166 * note that the LRU is being scanned too quickly and the
1167 * caller can stall after page list has been processed.
1169 * 2) Global or new memcg reclaim encounters a page that is
1170 * not marked for immediate reclaim, or the caller does not
1171 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1172 * not to fs). In this case mark the page for immediate
1173 * reclaim and continue scanning.
1175 * Require may_enter_fs because we would wait on fs, which
1176 * may not have submitted IO yet. And the loop driver might
1177 * enter reclaim, and deadlock if it waits on a page for
1178 * which it is needed to do the write (loop masks off
1179 * __GFP_IO|__GFP_FS for this reason); but more thought
1180 * would probably show more reasons.
1182 * 3) Legacy memcg encounters a page that is already marked
1183 * PageReclaim. memcg does not have any dirty pages
1184 * throttling so we could easily OOM just because too many
1185 * pages are in writeback and there is nothing else to
1186 * reclaim. Wait for the writeback to complete.
1188 * In cases 1) and 2) we activate the pages to get them out of
1189 * the way while we continue scanning for clean pages on the
1190 * inactive list and refilling from the active list. The
1191 * observation here is that waiting for disk writes is more
1192 * expensive than potentially causing reloads down the line.
1193 * Since they're marked for immediate reclaim, they won't put
1194 * memory pressure on the cache working set any longer than it
1195 * takes to write them to disk.
1197 if (PageWriteback(page)) {
1199 if (current_is_kswapd() &&
1200 PageReclaim(page) &&
1201 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1202 stat->nr_immediate++;
1203 goto activate_locked;
1206 } else if (writeback_throttling_sane(sc) ||
1207 !PageReclaim(page) || !may_enter_fs) {
1209 * This is slightly racy - end_page_writeback()
1210 * might have just cleared PageReclaim, then
1211 * setting PageReclaim here end up interpreted
1212 * as PageReadahead - but that does not matter
1213 * enough to care. What we do want is for this
1214 * page to have PageReclaim set next time memcg
1215 * reclaim reaches the tests above, so it will
1216 * then wait_on_page_writeback() to avoid OOM;
1217 * and it's also appropriate in global reclaim.
1219 SetPageReclaim(page);
1220 stat->nr_writeback++;
1221 goto activate_locked;
1226 wait_on_page_writeback(page);
1227 /* then go back and try same page again */
1228 list_add_tail(&page->lru, page_list);
1233 if (!ignore_references)
1234 references = page_check_references(page, sc);
1236 switch (references) {
1237 case PAGEREF_ACTIVATE:
1238 goto activate_locked;
1240 stat->nr_ref_keep += nr_pages;
1242 case PAGEREF_RECLAIM:
1243 case PAGEREF_RECLAIM_CLEAN:
1244 ; /* try to reclaim the page below */
1248 * Anonymous process memory has backing store?
1249 * Try to allocate it some swap space here.
1250 * Lazyfree page could be freed directly
1252 if (PageAnon(page) && PageSwapBacked(page)) {
1253 if (!PageSwapCache(page)) {
1254 if (!(sc->gfp_mask & __GFP_IO))
1256 if (PageTransHuge(page)) {
1257 /* cannot split THP, skip it */
1258 if (!can_split_huge_page(page, NULL))
1259 goto activate_locked;
1261 * Split pages without a PMD map right
1262 * away. Chances are some or all of the
1263 * tail pages can be freed without IO.
1265 if (!compound_mapcount(page) &&
1266 split_huge_page_to_list(page,
1268 goto activate_locked;
1270 if (!add_to_swap(page)) {
1271 if (!PageTransHuge(page))
1272 goto activate_locked_split;
1273 /* Fallback to swap normal pages */
1274 if (split_huge_page_to_list(page,
1276 goto activate_locked;
1277 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1278 count_vm_event(THP_SWPOUT_FALLBACK);
1280 if (!add_to_swap(page))
1281 goto activate_locked_split;
1286 /* Adding to swap updated mapping */
1287 mapping = page_mapping(page);
1289 } else if (unlikely(PageTransHuge(page))) {
1290 /* Split file THP */
1291 if (split_huge_page_to_list(page, page_list))
1296 * THP may get split above, need minus tail pages and update
1297 * nr_pages to avoid accounting tail pages twice.
1299 * The tail pages that are added into swap cache successfully
1302 if ((nr_pages > 1) && !PageTransHuge(page)) {
1303 sc->nr_scanned -= (nr_pages - 1);
1308 * The page is mapped into the page tables of one or more
1309 * processes. Try to unmap it here.
1311 if (page_mapped(page)) {
1312 enum ttu_flags flags = TTU_BATCH_FLUSH;
1314 if (unlikely(PageTransHuge(page)))
1315 flags |= TTU_SPLIT_HUGE_PMD;
1316 if (!try_to_unmap(page, flags)) {
1317 stat->nr_unmap_fail += nr_pages;
1318 goto activate_locked;
1322 if (PageDirty(page)) {
1324 * Only kswapd can writeback filesystem pages
1325 * to avoid risk of stack overflow. But avoid
1326 * injecting inefficient single-page IO into
1327 * flusher writeback as much as possible: only
1328 * write pages when we've encountered many
1329 * dirty pages, and when we've already scanned
1330 * the rest of the LRU for clean pages and see
1331 * the same dirty pages again (PageReclaim).
1333 if (page_is_file_cache(page) &&
1334 (!current_is_kswapd() || !PageReclaim(page) ||
1335 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1337 * Immediately reclaim when written back.
1338 * Similar in principal to deactivate_page()
1339 * except we already have the page isolated
1340 * and know it's dirty
1342 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
1343 SetPageReclaim(page);
1345 goto activate_locked;
1348 if (references == PAGEREF_RECLAIM_CLEAN)
1352 if (!sc->may_writepage)
1356 * Page is dirty. Flush the TLB if a writable entry
1357 * potentially exists to avoid CPU writes after IO
1358 * starts and then write it out here.
1360 try_to_unmap_flush_dirty();
1361 switch (pageout(page, mapping, sc)) {
1365 goto activate_locked;
1367 if (PageWriteback(page))
1369 if (PageDirty(page))
1373 * A synchronous write - probably a ramdisk. Go
1374 * ahead and try to reclaim the page.
1376 if (!trylock_page(page))
1378 if (PageDirty(page) || PageWriteback(page))
1380 mapping = page_mapping(page);
1382 ; /* try to free the page below */
1387 * If the page has buffers, try to free the buffer mappings
1388 * associated with this page. If we succeed we try to free
1391 * We do this even if the page is PageDirty().
1392 * try_to_release_page() does not perform I/O, but it is
1393 * possible for a page to have PageDirty set, but it is actually
1394 * clean (all its buffers are clean). This happens if the
1395 * buffers were written out directly, with submit_bh(). ext3
1396 * will do this, as well as the blockdev mapping.
1397 * try_to_release_page() will discover that cleanness and will
1398 * drop the buffers and mark the page clean - it can be freed.
1400 * Rarely, pages can have buffers and no ->mapping. These are
1401 * the pages which were not successfully invalidated in
1402 * truncate_complete_page(). We try to drop those buffers here
1403 * and if that worked, and the page is no longer mapped into
1404 * process address space (page_count == 1) it can be freed.
1405 * Otherwise, leave the page on the LRU so it is swappable.
1407 if (page_has_private(page)) {
1408 if (!try_to_release_page(page, sc->gfp_mask))
1409 goto activate_locked;
1410 if (!mapping && page_count(page) == 1) {
1412 if (put_page_testzero(page))
1416 * rare race with speculative reference.
1417 * the speculative reference will free
1418 * this page shortly, so we may
1419 * increment nr_reclaimed here (and
1420 * leave it off the LRU).
1428 if (PageAnon(page) && !PageSwapBacked(page)) {
1429 /* follow __remove_mapping for reference */
1430 if (!page_ref_freeze(page, 1))
1432 if (PageDirty(page)) {
1433 page_ref_unfreeze(page, 1);
1437 count_vm_event(PGLAZYFREED);
1438 count_memcg_page_event(page, PGLAZYFREED);
1439 } else if (!mapping || !__remove_mapping(mapping, page, true,
1440 sc->target_mem_cgroup))
1446 * THP may get swapped out in a whole, need account
1449 nr_reclaimed += nr_pages;
1452 * Is there need to periodically free_page_list? It would
1453 * appear not as the counts should be low
1455 if (unlikely(PageTransHuge(page)))
1456 (*get_compound_page_dtor(page))(page);
1458 list_add(&page->lru, &free_pages);
1461 activate_locked_split:
1463 * The tail pages that are failed to add into swap cache
1464 * reach here. Fixup nr_scanned and nr_pages.
1467 sc->nr_scanned -= (nr_pages - 1);
1471 /* Not a candidate for swapping, so reclaim swap space. */
1472 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1474 try_to_free_swap(page);
1475 VM_BUG_ON_PAGE(PageActive(page), page);
1476 if (!PageMlocked(page)) {
1477 int type = page_is_file_cache(page);
1478 SetPageActive(page);
1479 stat->nr_activate[type] += nr_pages;
1480 count_memcg_page_event(page, PGACTIVATE);
1485 list_add(&page->lru, &ret_pages);
1486 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
1489 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1491 mem_cgroup_uncharge_list(&free_pages);
1492 try_to_unmap_flush();
1493 free_unref_page_list(&free_pages);
1495 list_splice(&ret_pages, page_list);
1496 count_vm_events(PGACTIVATE, pgactivate);
1498 return nr_reclaimed;
1501 unsigned long reclaim_clean_pages_from_list(struct zone *zone,
1502 struct list_head *page_list)
1504 struct scan_control sc = {
1505 .gfp_mask = GFP_KERNEL,
1506 .priority = DEF_PRIORITY,
1509 struct reclaim_stat dummy_stat;
1511 struct page *page, *next;
1512 LIST_HEAD(clean_pages);
1514 list_for_each_entry_safe(page, next, page_list, lru) {
1515 if (page_is_file_cache(page) && !PageDirty(page) &&
1516 !__PageMovable(page) && !PageUnevictable(page)) {
1517 ClearPageActive(page);
1518 list_move(&page->lru, &clean_pages);
1522 ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1524 list_splice(&clean_pages, page_list);
1525 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
1530 * Attempt to remove the specified page from its LRU. Only take this page
1531 * if it is of the appropriate PageActive status. Pages which are being
1532 * freed elsewhere are also ignored.
1534 * page: page to consider
1535 * mode: one of the LRU isolation modes defined above
1537 * returns 0 on success, -ve errno on failure.
1539 int __isolate_lru_page(struct page *page, isolate_mode_t mode)
1543 /* Only take pages on the LRU. */
1547 /* Compaction should not handle unevictable pages but CMA can do so */
1548 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1552 * To minimise LRU disruption, the caller can indicate that it only
1553 * wants to isolate pages it will be able to operate on without
1554 * blocking - clean pages for the most part.
1556 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1557 * that it is possible to migrate without blocking
1559 if (mode & ISOLATE_ASYNC_MIGRATE) {
1560 /* All the caller can do on PageWriteback is block */
1561 if (PageWriteback(page))
1564 if (PageDirty(page)) {
1565 struct address_space *mapping;
1569 * Only pages without mappings or that have a
1570 * ->migratepage callback are possible to migrate
1571 * without blocking. However, we can be racing with
1572 * truncation so it's necessary to lock the page
1573 * to stabilise the mapping as truncation holds
1574 * the page lock until after the page is removed
1575 * from the page cache.
1577 if (!trylock_page(page))
1580 mapping = page_mapping(page);
1581 migrate_dirty = !mapping || mapping->a_ops->migratepage;
1588 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1591 if (likely(get_page_unless_zero(page))) {
1593 * Be careful not to clear PageLRU until after we're
1594 * sure the page is not being freed elsewhere -- the
1595 * page release code relies on it.
1597 if (TestClearPageLRU(page))
1608 * Update LRU sizes after isolating pages. The LRU size updates must
1609 * be complete before mem_cgroup_update_lru_size due to a santity check.
1611 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1612 enum lru_list lru, unsigned long *nr_zone_taken)
1616 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1617 if (!nr_zone_taken[zid])
1620 __update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1622 mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1629 * pgdat->lru_lock is heavily contended. Some of the functions that
1630 * shrink the lists perform better by taking out a batch of pages
1631 * and working on them outside the LRU lock.
1633 * For pagecache intensive workloads, this function is the hottest
1634 * spot in the kernel (apart from copy_*_user functions).
1636 * Appropriate locks must be held before calling this function.
1638 * @nr_to_scan: The number of eligible pages to look through on the list.
1639 * @lruvec: The LRU vector to pull pages from.
1640 * @dst: The temp list to put pages on to.
1641 * @nr_scanned: The number of pages that were scanned.
1642 * @sc: The scan_control struct for this reclaim session
1643 * @mode: One of the LRU isolation modes
1644 * @lru: LRU list id for isolating
1646 * returns how many pages were moved onto *@dst.
1648 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1649 struct lruvec *lruvec, struct list_head *dst,
1650 unsigned long *nr_scanned, struct scan_control *sc,
1653 struct list_head *src = &lruvec->lists[lru];
1654 unsigned long nr_taken = 0;
1655 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1656 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1657 unsigned long skipped = 0;
1658 unsigned long scan, total_scan, nr_pages;
1659 LIST_HEAD(pages_skipped);
1660 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
1664 while (scan < nr_to_scan && !list_empty(src)) {
1667 page = lru_to_page(src);
1668 prefetchw_prev_lru_page(page, src, flags);
1670 nr_pages = compound_nr(page);
1671 total_scan += nr_pages;
1673 if (page_zonenum(page) > sc->reclaim_idx) {
1674 list_move(&page->lru, &pages_skipped);
1675 nr_skipped[page_zonenum(page)] += nr_pages;
1680 * Do not count skipped pages because that makes the function
1681 * return with no isolated pages if the LRU mostly contains
1682 * ineligible pages. This causes the VM to not reclaim any
1683 * pages, triggering a premature OOM.
1685 * Account all tail pages of THP. This would not cause
1686 * premature OOM since __isolate_lru_page() returns -EBUSY
1687 * only when the page is being freed somewhere else.
1690 switch (__isolate_lru_page(page, mode)) {
1692 nr_taken += nr_pages;
1693 nr_zone_taken[page_zonenum(page)] += nr_pages;
1694 list_move(&page->lru, dst);
1698 /* else it is being freed elsewhere */
1699 list_move(&page->lru, src);
1708 * Splice any skipped pages to the start of the LRU list. Note that
1709 * this disrupts the LRU order when reclaiming for lower zones but
1710 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1711 * scanning would soon rescan the same pages to skip and put the
1712 * system at risk of premature OOM.
1714 if (!list_empty(&pages_skipped)) {
1717 list_splice(&pages_skipped, src);
1718 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1719 if (!nr_skipped[zid])
1722 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1723 skipped += nr_skipped[zid];
1726 *nr_scanned = total_scan;
1727 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1728 total_scan, skipped, nr_taken, mode, lru);
1729 update_lru_sizes(lruvec, lru, nr_zone_taken);
1734 * isolate_lru_page - tries to isolate a page from its LRU list
1735 * @page: page to isolate from its LRU list
1737 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1738 * vmstat statistic corresponding to whatever LRU list the page was on.
1740 * Returns 0 if the page was removed from an LRU list.
1741 * Returns -EBUSY if the page was not on an LRU list.
1743 * The returned page will have PageLRU() cleared. If it was found on
1744 * the active list, it will have PageActive set. If it was found on
1745 * the unevictable list, it will have the PageUnevictable bit set. That flag
1746 * may need to be cleared by the caller before letting the page go.
1748 * The vmstat statistic corresponding to the list on which the page was
1749 * found will be decremented.
1753 * (1) Must be called with an elevated refcount on the page. This is a
1754 * fundamentnal difference from isolate_lru_pages (which is called
1755 * without a stable reference).
1756 * (2) the lru_lock must not be held.
1757 * (3) interrupts must be enabled.
1759 int isolate_lru_page(struct page *page)
1763 VM_BUG_ON_PAGE(!page_count(page), page);
1764 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
1766 if (TestClearPageLRU(page)) {
1767 pg_data_t *pgdat = page_pgdat(page);
1768 struct lruvec *lruvec;
1771 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1772 spin_lock_irq(&pgdat->lru_lock);
1773 del_page_from_lru_list(page, lruvec, page_lru(page));
1774 spin_unlock_irq(&pgdat->lru_lock);
1782 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1783 * then get resheduled. When there are massive number of tasks doing page
1784 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1785 * the LRU list will go small and be scanned faster than necessary, leading to
1786 * unnecessary swapping, thrashing and OOM.
1788 static int too_many_isolated(struct pglist_data *pgdat, int file,
1789 struct scan_control *sc)
1791 unsigned long inactive, isolated;
1793 if (current_is_kswapd())
1796 if (!writeback_throttling_sane(sc))
1800 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1801 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1803 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1804 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
1808 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1809 * won't get blocked by normal direct-reclaimers, forming a circular
1812 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
1815 return isolated > inactive;
1819 * This moves pages from @list to corresponding LRU list.
1821 * We move them the other way if the page is referenced by one or more
1822 * processes, from rmap.
1824 * If the pages are mostly unmapped, the processing is fast and it is
1825 * appropriate to hold zone_lru_lock across the whole operation. But if
1826 * the pages are mapped, the processing is slow (page_referenced()) so we
1827 * should drop zone_lru_lock around each page. It's impossible to balance
1828 * this, so instead we remove the pages from the LRU while processing them.
1829 * It is safe to rely on PG_active against the non-LRU pages in here because
1830 * nobody will play with that bit on a non-LRU page.
1832 * The downside is that we have to touch page->_refcount against each page.
1833 * But we had to alter page->flags anyway.
1835 * Returns the number of pages moved to the given lruvec.
1838 static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1839 struct list_head *list)
1841 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1842 int nr_pages, nr_moved = 0;
1843 LIST_HEAD(pages_to_free);
1847 while (!list_empty(list)) {
1848 page = lru_to_page(list);
1849 VM_BUG_ON_PAGE(PageLRU(page), page);
1850 if (unlikely(!page_evictable(page))) {
1851 list_del(&page->lru);
1852 spin_unlock_irq(&pgdat->lru_lock);
1853 putback_lru_page(page);
1854 spin_lock_irq(&pgdat->lru_lock);
1857 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1860 lru = page_lru(page);
1862 nr_pages = hpage_nr_pages(page);
1863 update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1864 list_move(&page->lru, &lruvec->lists[lru]);
1866 if (put_page_testzero(page)) {
1867 __ClearPageLRU(page);
1868 __ClearPageActive(page);
1869 del_page_from_lru_list(page, lruvec, lru);
1871 if (unlikely(PageCompound(page))) {
1872 spin_unlock_irq(&pgdat->lru_lock);
1873 (*get_compound_page_dtor(page))(page);
1874 spin_lock_irq(&pgdat->lru_lock);
1876 list_add(&page->lru, &pages_to_free);
1878 nr_moved += nr_pages;
1883 * To save our caller's stack, now use input list for pages to free.
1885 list_splice(&pages_to_free, list);
1891 * If a kernel thread (such as nfsd for loop-back mounts) services
1892 * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1893 * In that case we should only throttle if the backing device it is
1894 * writing to is congested. In other cases it is safe to throttle.
1896 static int current_may_throttle(void)
1898 return !(current->flags & PF_LESS_THROTTLE) ||
1899 current->backing_dev_info == NULL ||
1900 bdi_write_congested(current->backing_dev_info);
1904 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1905 * of reclaimed pages
1907 static noinline_for_stack unsigned long
1908 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
1909 struct scan_control *sc, enum lru_list lru)
1911 LIST_HEAD(page_list);
1912 unsigned long nr_scanned;
1913 unsigned long nr_reclaimed = 0;
1914 unsigned long nr_taken;
1915 struct reclaim_stat stat;
1916 int file = is_file_lru(lru);
1917 enum vm_event_item item;
1918 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1919 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1920 bool stalled = false;
1922 while (unlikely(too_many_isolated(pgdat, file, sc))) {
1926 /* wait a bit for the reclaimer. */
1930 /* We are about to die and free our memory. Return now. */
1931 if (fatal_signal_pending(current))
1932 return SWAP_CLUSTER_MAX;
1937 spin_lock_irq(&pgdat->lru_lock);
1939 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1940 &nr_scanned, sc, lru);
1942 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1943 reclaim_stat->recent_scanned[file] += nr_taken;
1945 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
1946 if (!cgroup_reclaim(sc))
1947 __count_vm_events(item, nr_scanned);
1948 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1949 spin_unlock_irq(&pgdat->lru_lock);
1954 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
1956 spin_lock_irq(&pgdat->lru_lock);
1958 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
1959 if (!cgroup_reclaim(sc))
1960 __count_vm_events(item, nr_reclaimed);
1961 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1962 reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
1963 reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
1965 move_pages_to_lru(lruvec, &page_list);
1967 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1969 spin_unlock_irq(&pgdat->lru_lock);
1971 mem_cgroup_uncharge_list(&page_list);
1972 free_unref_page_list(&page_list);
1975 * If dirty pages are scanned that are not queued for IO, it
1976 * implies that flushers are not doing their job. This can
1977 * happen when memory pressure pushes dirty pages to the end of
1978 * the LRU before the dirty limits are breached and the dirty
1979 * data has expired. It can also happen when the proportion of
1980 * dirty pages grows not through writes but through memory
1981 * pressure reclaiming all the clean cache. And in some cases,
1982 * the flushers simply cannot keep up with the allocation
1983 * rate. Nudge the flusher threads in case they are asleep.
1985 if (stat.nr_unqueued_dirty == nr_taken)
1986 wakeup_flusher_threads(WB_REASON_VMSCAN);
1988 sc->nr.dirty += stat.nr_dirty;
1989 sc->nr.congested += stat.nr_congested;
1990 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1991 sc->nr.writeback += stat.nr_writeback;
1992 sc->nr.immediate += stat.nr_immediate;
1993 sc->nr.taken += nr_taken;
1995 sc->nr.file_taken += nr_taken;
1997 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1998 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
1999 return nr_reclaimed;
2002 static void shrink_active_list(unsigned long nr_to_scan,
2003 struct lruvec *lruvec,
2004 struct scan_control *sc,
2007 unsigned long nr_taken;
2008 unsigned long nr_scanned;
2009 unsigned long vm_flags;
2010 LIST_HEAD(l_hold); /* The pages which were snipped off */
2011 LIST_HEAD(l_active);
2012 LIST_HEAD(l_inactive);
2014 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
2015 unsigned nr_deactivate, nr_activate;
2016 unsigned nr_rotated = 0;
2017 int file = is_file_lru(lru);
2018 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2022 spin_lock_irq(&pgdat->lru_lock);
2024 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2025 &nr_scanned, sc, lru);
2027 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2028 reclaim_stat->recent_scanned[file] += nr_taken;
2030 __count_vm_events(PGREFILL, nr_scanned);
2031 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2033 spin_unlock_irq(&pgdat->lru_lock);
2035 while (!list_empty(&l_hold)) {
2037 page = lru_to_page(&l_hold);
2038 list_del(&page->lru);
2040 if (unlikely(!page_evictable(page))) {
2041 putback_lru_page(page);
2045 if (unlikely(buffer_heads_over_limit)) {
2046 if (page_has_private(page) && trylock_page(page)) {
2047 if (page_has_private(page))
2048 try_to_release_page(page, 0);
2053 if (page_referenced(page, 0, sc->target_mem_cgroup,
2055 nr_rotated += hpage_nr_pages(page);
2057 * Identify referenced, file-backed active pages and
2058 * give them one more trip around the active list. So
2059 * that executable code get better chances to stay in
2060 * memory under moderate memory pressure. Anon pages
2061 * are not likely to be evicted by use-once streaming
2062 * IO, plus JVM can create lots of anon VM_EXEC pages,
2063 * so we ignore them here.
2065 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
2066 list_add(&page->lru, &l_active);
2071 ClearPageActive(page); /* we are de-activating */
2072 SetPageWorkingset(page);
2073 list_add(&page->lru, &l_inactive);
2077 * Move pages back to the lru list.
2079 spin_lock_irq(&pgdat->lru_lock);
2081 * Count referenced pages from currently used mappings as rotated,
2082 * even though only some of them are actually re-activated. This
2083 * helps balance scan pressure between file and anonymous pages in
2086 reclaim_stat->recent_rotated[file] += nr_rotated;
2088 nr_activate = move_pages_to_lru(lruvec, &l_active);
2089 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2090 /* Keep all free pages in l_active list */
2091 list_splice(&l_inactive, &l_active);
2093 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2094 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2096 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2097 spin_unlock_irq(&pgdat->lru_lock);
2099 mem_cgroup_uncharge_list(&l_active);
2100 free_unref_page_list(&l_active);
2101 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2102 nr_deactivate, nr_rotated, sc->priority, file);
2105 unsigned long reclaim_pages(struct list_head *page_list)
2108 unsigned long nr_reclaimed = 0;
2109 LIST_HEAD(node_page_list);
2110 struct reclaim_stat dummy_stat;
2112 struct scan_control sc = {
2113 .gfp_mask = GFP_KERNEL,
2114 .priority = DEF_PRIORITY,
2120 while (!list_empty(page_list)) {
2121 page = lru_to_page(page_list);
2123 nid = page_to_nid(page);
2124 INIT_LIST_HEAD(&node_page_list);
2127 if (nid == page_to_nid(page)) {
2128 ClearPageActive(page);
2129 list_move(&page->lru, &node_page_list);
2133 nr_reclaimed += shrink_page_list(&node_page_list,
2135 &sc, &dummy_stat, false);
2136 while (!list_empty(&node_page_list)) {
2137 page = lru_to_page(&node_page_list);
2138 list_del(&page->lru);
2139 putback_lru_page(page);
2145 if (!list_empty(&node_page_list)) {
2146 nr_reclaimed += shrink_page_list(&node_page_list,
2148 &sc, &dummy_stat, false);
2149 while (!list_empty(&node_page_list)) {
2150 page = lru_to_page(&node_page_list);
2151 list_del(&page->lru);
2152 putback_lru_page(page);
2156 return nr_reclaimed;
2159 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2160 struct lruvec *lruvec, struct scan_control *sc)
2162 if (is_active_lru(lru)) {
2163 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2164 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2166 sc->skipped_deactivate = 1;
2170 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2174 * The inactive anon list should be small enough that the VM never has
2175 * to do too much work.
2177 * The inactive file list should be small enough to leave most memory
2178 * to the established workingset on the scan-resistant active list,
2179 * but large enough to avoid thrashing the aggregate readahead window.
2181 * Both inactive lists should also be large enough that each inactive
2182 * page has a chance to be referenced again before it is reclaimed.
2184 * If that fails and refaulting is observed, the inactive list grows.
2186 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2187 * on this LRU, maintained by the pageout code. An inactive_ratio
2188 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2191 * memory ratio inactive
2192 * -------------------------------------
2201 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2203 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2204 unsigned long inactive, active;
2205 unsigned long inactive_ratio;
2208 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2209 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2211 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2213 inactive_ratio = int_sqrt(10 * gb);
2217 return inactive * inactive_ratio < active;
2227 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2230 struct lruvec *target_lruvec;
2232 if (lru_gen_enabled())
2235 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2238 * Target desirable inactive:active list ratios for the anon
2239 * and file LRU lists.
2241 if (!sc->force_deactivate) {
2242 unsigned long refaults;
2244 if (inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2245 sc->may_deactivate |= DEACTIVATE_ANON;
2247 sc->may_deactivate &= ~DEACTIVATE_ANON;
2250 * When refaults are being observed, it means a new
2251 * workingset is being established. Deactivate to get
2252 * rid of any stale active pages quickly.
2254 refaults = lruvec_page_state(target_lruvec,
2255 WORKINGSET_ACTIVATE);
2256 if (refaults != target_lruvec->refaults ||
2257 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2258 sc->may_deactivate |= DEACTIVATE_FILE;
2260 sc->may_deactivate &= ~DEACTIVATE_FILE;
2262 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2265 * If we have plenty of inactive file pages that aren't
2266 * thrashing, try to reclaim those first before touching
2269 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2270 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2271 sc->cache_trim_mode = 1;
2273 sc->cache_trim_mode = 0;
2276 * Prevent the reclaimer from falling into the cache trap: as
2277 * cache pages start out inactive, every cache fault will tip
2278 * the scan balance towards the file LRU. And as the file LRU
2279 * shrinks, so does the window for rotation from references.
2280 * This means we have a runaway feedback loop where a tiny
2281 * thrashing file LRU becomes infinitely more attractive than
2282 * anon pages. Try to detect this based on file LRU size.
2284 if (!cgroup_reclaim(sc)) {
2285 unsigned long total_high_wmark = 0;
2286 unsigned long free, anon;
2289 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2290 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2291 node_page_state(pgdat, NR_INACTIVE_FILE);
2293 for (z = 0; z < MAX_NR_ZONES; z++) {
2294 struct zone *zone = &pgdat->node_zones[z];
2296 if (!managed_zone(zone))
2299 total_high_wmark += high_wmark_pages(zone);
2303 * Consider anon: if that's low too, this isn't a
2304 * runaway file reclaim problem, but rather just
2305 * extreme pressure. Reclaim as per usual then.
2307 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2310 file + free <= total_high_wmark &&
2311 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2312 anon >> sc->priority;
2317 * Determine how aggressively the anon and file LRU lists should be
2318 * scanned. The relative value of each set of LRU lists is determined
2319 * by looking at the fraction of the pages scanned we did rotate back
2320 * onto the active list instead of evict.
2322 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2323 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2325 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2328 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2329 int swappiness = mem_cgroup_swappiness(memcg);
2330 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
2331 u64 fraction[ANON_AND_FILE];
2332 u64 denominator = 0; /* gcc */
2333 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2334 unsigned long anon_prio, file_prio;
2335 enum scan_balance scan_balance;
2336 unsigned long anon, file;
2337 unsigned long ap, fp;
2340 /* If we have no swap space, do not bother scanning anon pages. */
2341 if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
2342 scan_balance = SCAN_FILE;
2347 * Global reclaim will swap to prevent OOM even with no
2348 * swappiness, but memcg users want to use this knob to
2349 * disable swapping for individual groups completely when
2350 * using the memory controller's swap limit feature would be
2353 if (cgroup_reclaim(sc) && !swappiness) {
2354 scan_balance = SCAN_FILE;
2359 * Do not apply any pressure balancing cleverness when the
2360 * system is close to OOM, scan both anon and file equally
2361 * (unless the swappiness setting disagrees with swapping).
2363 if (!sc->priority && swappiness) {
2364 scan_balance = SCAN_EQUAL;
2369 * If the system is almost out of file pages, force-scan anon.
2371 if (sc->file_is_tiny) {
2372 scan_balance = SCAN_ANON;
2377 * If there is enough inactive page cache, we do not reclaim
2378 * anything from the anonymous working right now.
2380 if (sc->cache_trim_mode) {
2381 scan_balance = SCAN_FILE;
2385 scan_balance = SCAN_FRACT;
2388 * With swappiness at 100, anonymous and file have the same priority.
2389 * This scanning priority is essentially the inverse of IO cost.
2391 anon_prio = swappiness;
2392 file_prio = 200 - anon_prio;
2395 * OK, so we have swap space and a fair amount of page cache
2396 * pages. We use the recently rotated / recently scanned
2397 * ratios to determine how valuable each cache is.
2399 * Because workloads change over time (and to avoid overflow)
2400 * we keep these statistics as a floating average, which ends
2401 * up weighing recent references more than old ones.
2403 * anon in [0], file in [1]
2406 anon = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2407 lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2408 file = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2409 lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
2411 spin_lock_irq(&pgdat->lru_lock);
2412 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
2413 reclaim_stat->recent_scanned[0] /= 2;
2414 reclaim_stat->recent_rotated[0] /= 2;
2417 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
2418 reclaim_stat->recent_scanned[1] /= 2;
2419 reclaim_stat->recent_rotated[1] /= 2;
2423 * The amount of pressure on anon vs file pages is inversely
2424 * proportional to the fraction of recently scanned pages on
2425 * each list that were recently referenced and in active use.
2427 ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
2428 ap /= reclaim_stat->recent_rotated[0] + 1;
2430 fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
2431 fp /= reclaim_stat->recent_rotated[1] + 1;
2432 spin_unlock_irq(&pgdat->lru_lock);
2436 denominator = ap + fp + 1;
2438 for_each_evictable_lru(lru) {
2439 int file = is_file_lru(lru);
2440 unsigned long lruvec_size;
2442 unsigned long protection;
2444 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2445 protection = mem_cgroup_protection(memcg,
2446 sc->memcg_low_reclaim);
2450 * Scale a cgroup's reclaim pressure by proportioning
2451 * its current usage to its memory.low or memory.min
2454 * This is important, as otherwise scanning aggression
2455 * becomes extremely binary -- from nothing as we
2456 * approach the memory protection threshold, to totally
2457 * nominal as we exceed it. This results in requiring
2458 * setting extremely liberal protection thresholds. It
2459 * also means we simply get no protection at all if we
2460 * set it too low, which is not ideal.
2462 * If there is any protection in place, we reduce scan
2463 * pressure by how much of the total memory used is
2464 * within protection thresholds.
2466 * There is one special case: in the first reclaim pass,
2467 * we skip over all groups that are within their low
2468 * protection. If that fails to reclaim enough pages to
2469 * satisfy the reclaim goal, we come back and override
2470 * the best-effort low protection. However, we still
2471 * ideally want to honor how well-behaved groups are in
2472 * that case instead of simply punishing them all
2473 * equally. As such, we reclaim them based on how much
2474 * memory they are using, reducing the scan pressure
2475 * again by how much of the total memory used is under
2478 unsigned long cgroup_size = mem_cgroup_size(memcg);
2480 /* Avoid TOCTOU with earlier protection check */
2481 cgroup_size = max(cgroup_size, protection);
2483 scan = lruvec_size - lruvec_size * protection /
2487 * Minimally target SWAP_CLUSTER_MAX pages to keep
2488 * reclaim moving forwards, avoiding decremeting
2489 * sc->priority further than desirable.
2491 scan = max(scan, SWAP_CLUSTER_MAX);
2496 scan >>= sc->priority;
2499 * If the cgroup's already been deleted, make sure to
2500 * scrape out the remaining cache.
2502 if (!scan && !mem_cgroup_online(memcg))
2503 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2505 switch (scan_balance) {
2507 /* Scan lists relative to size */
2511 * Scan types proportional to swappiness and
2512 * their relative recent reclaim efficiency.
2513 * Make sure we don't miss the last page on
2514 * the offlined memory cgroups because of a
2517 scan = mem_cgroup_online(memcg) ?
2518 div64_u64(scan * fraction[file], denominator) :
2519 DIV64_U64_ROUND_UP(scan * fraction[file],
2524 /* Scan one type exclusively */
2525 if ((scan_balance == SCAN_FILE) != file)
2529 /* Look ma, no brain */
2537 #ifdef CONFIG_LRU_GEN
2539 /******************************************************************************
2541 ******************************************************************************/
2543 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2545 #define DEFINE_MAX_SEQ(lruvec) \
2546 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2548 #define DEFINE_MIN_SEQ(lruvec) \
2549 unsigned long min_seq[ANON_AND_FILE] = { \
2550 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2551 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2554 #define for_each_gen_type_zone(gen, type, zone) \
2555 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2556 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2557 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2559 static struct lruvec __maybe_unused *get_lruvec(struct mem_cgroup *memcg, int nid)
2561 struct pglist_data *pgdat = NODE_DATA(nid);
2565 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2567 /* for hotadd_new_pgdat() */
2569 lruvec->pgdat = pgdat;
2574 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2576 return pgdat ? &pgdat->__lruvec : NULL;
2579 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2581 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2582 /* struct pglist_data *pgdat = lruvec_pgdat(lruvec); */
2584 /* FIXME: see a2a36488a61c + 26aa2d199d6f */
2585 if (/* !can_demote(pgdat->node_id, sc) && */
2586 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2589 return mem_cgroup_swappiness(memcg);
2592 static int get_nr_gens(struct lruvec *lruvec, int type)
2594 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2597 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2599 /* see the comment on lru_gen_struct */
2600 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2601 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2602 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2605 /******************************************************************************
2606 * refault feedback loop
2607 ******************************************************************************/
2610 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
2612 * The P term is refaulted/(evicted+protected) from a tier in the generation
2613 * currently being evicted; the I term is the exponential moving average of the
2614 * P term over the generations previously evicted, using the smoothing factor
2615 * 1/2; the D term isn't supported.
2617 * The setpoint (SP) is always the first tier of one type; the process variable
2618 * (PV) is either any tier of the other type or any other tier of the same
2621 * The error is the difference between the SP and the PV; the correction is to
2622 * turn off protection when SP>PV or turn on protection when SP<PV.
2624 * For future optimizations:
2625 * 1. The D term may discount the other two terms over time so that long-lived
2626 * generations can resist stale information.
2629 unsigned long refaulted;
2630 unsigned long total;
2634 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
2635 struct ctrl_pos *pos)
2637 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2638 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
2640 pos->refaulted = lrugen->avg_refaulted[type][tier] +
2641 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
2642 pos->total = lrugen->avg_total[type][tier] +
2643 atomic_long_read(&lrugen->evicted[hist][type][tier]);
2645 pos->total += lrugen->protected[hist][type][tier - 1];
2649 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
2652 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2653 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
2654 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
2656 lockdep_assert_held(&lruvec_pgdat(lruvec)->lru_lock);
2658 if (!carryover && !clear)
2661 hist = lru_hist_from_seq(seq);
2663 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
2667 sum = lrugen->avg_refaulted[type][tier] +
2668 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
2669 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
2671 sum = lrugen->avg_total[type][tier] +
2672 atomic_long_read(&lrugen->evicted[hist][type][tier]);
2674 sum += lrugen->protected[hist][type][tier - 1];
2675 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
2679 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
2680 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
2682 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
2687 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
2690 * Return true if the PV has a limited number of refaults or a lower
2691 * refaulted/total than the SP.
2693 return pv->refaulted < MIN_LRU_BATCH ||
2694 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
2695 (sp->refaulted + 1) * pv->total * pv->gain;
2698 /******************************************************************************
2700 ******************************************************************************/
2702 /* protect pages accessed multiple times through file descriptors */
2703 static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
2705 int type = page_is_file_cache(page);
2706 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2707 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
2708 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
2710 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
2713 new_gen = (old_gen + 1) % MAX_NR_GENS;
2715 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
2716 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
2717 /* for end_page_writeback() */
2719 new_flags |= BIT(PG_reclaim);
2720 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
2722 lru_gen_update_size(lruvec, page, old_gen, new_gen);
2727 static void inc_min_seq(struct lruvec *lruvec, int type)
2729 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2731 reset_ctrl_pos(lruvec, type, true);
2732 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
2735 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
2737 int gen, type, zone;
2738 bool success = false;
2739 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2740 DEFINE_MIN_SEQ(lruvec);
2742 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
2744 /* find the oldest populated generation */
2745 for (type = !can_swap; type < ANON_AND_FILE; type++) {
2746 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
2747 gen = lru_gen_from_seq(min_seq[type]);
2749 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
2750 if (!list_empty(&lrugen->lists[gen][type][zone]))
2760 /* see the comment on lru_gen_struct */
2762 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
2763 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
2766 for (type = !can_swap; type < ANON_AND_FILE; type++) {
2767 if (min_seq[type] == lrugen->min_seq[type])
2770 reset_ctrl_pos(lruvec, type, true);
2771 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
2778 static void inc_max_seq(struct lruvec *lruvec, unsigned long max_seq, bool can_swap)
2782 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2784 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
2786 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
2788 if (max_seq != lrugen->max_seq)
2791 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
2792 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
2795 VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap);
2797 inc_min_seq(lruvec, type);
2801 * Update the active/inactive LRU sizes for compatibility. Both sides of
2802 * the current max_seq need to be covered, since max_seq+1 can overlap
2803 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
2804 * overlap, cold/hot inversion happens.
2806 prev = lru_gen_from_seq(lrugen->max_seq - 1);
2807 next = lru_gen_from_seq(lrugen->max_seq + 1);
2809 for (type = 0; type < ANON_AND_FILE; type++) {
2810 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
2811 enum lru_list lru = type * LRU_INACTIVE_FILE;
2812 long delta = lrugen->nr_pages[prev][type][zone] -
2813 lrugen->nr_pages[next][type][zone];
2818 __update_lru_size(lruvec, lru, zone, delta);
2819 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
2823 for (type = 0; type < ANON_AND_FILE; type++)
2824 reset_ctrl_pos(lruvec, type, false);
2826 /* make sure preceding modifications appear */
2827 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
2829 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
2832 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
2833 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
2835 int gen, type, zone;
2836 unsigned long old = 0;
2837 unsigned long young = 0;
2838 unsigned long total = 0;
2839 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2840 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2842 for (type = !can_swap; type < ANON_AND_FILE; type++) {
2845 for (seq = min_seq[type]; seq <= max_seq; seq++) {
2846 unsigned long size = 0;
2848 gen = lru_gen_from_seq(seq);
2850 for (zone = 0; zone < MAX_NR_ZONES; zone++)
2851 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
2856 else if (seq + MIN_NR_GENS == max_seq)
2861 /* try to scrape all its memory if this memcg was deleted */
2862 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
2865 * The aging tries to be lazy to reduce the overhead, while the eviction
2866 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
2867 * ideal number of generations is MIN_NR_GENS+1.
2869 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
2871 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
2875 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
2876 * of the total number of pages for each generation. A reasonable range
2877 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
2878 * aging cares about the upper bound of hot pages, while the eviction
2879 * cares about the lower bound of cold pages.
2881 if (young * MIN_NR_GENS > total)
2883 if (old * (MIN_NR_GENS + 2) < total)
2889 static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
2892 unsigned long nr_to_scan;
2893 int swappiness = get_swappiness(lruvec, sc);
2894 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2895 DEFINE_MAX_SEQ(lruvec);
2896 DEFINE_MIN_SEQ(lruvec);
2898 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
2900 mem_cgroup_calculate_protection(NULL, memcg);
2902 if (mem_cgroup_below_min(memcg))
2905 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
2907 inc_max_seq(lruvec, max_seq, swappiness);
2910 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
2912 struct mem_cgroup *memcg;
2914 VM_WARN_ON_ONCE(!current_is_kswapd());
2916 memcg = mem_cgroup_iter(NULL, NULL, NULL);
2918 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
2920 age_lruvec(lruvec, sc);
2923 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
2926 /******************************************************************************
2928 ******************************************************************************/
2930 static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
2933 int gen = page_lru_gen(page);
2934 int type = page_is_file_cache(page);
2935 int zone = page_zonenum(page);
2936 int delta = hpage_nr_pages(page);
2937 int refs = page_lru_refs(page);
2938 int tier = lru_tier_from_refs(refs);
2939 struct lru_gen_struct *lrugen = &lruvec->lrugen;
2941 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
2944 if (!page_evictable(page)) {
2945 success = lru_gen_del_page(lruvec, page, true);
2946 VM_WARN_ON_ONCE_PAGE(!success, page);
2947 SetPageUnevictable(page);
2948 add_page_to_lru_list(page, lruvec, LRU_UNEVICTABLE);
2949 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
2953 /* dirty lazyfree */
2954 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
2955 enum lru_list lru = page_lru_base_type(page);
2957 success = lru_gen_del_page(lruvec, page, true);
2958 VM_WARN_ON_ONCE_PAGE(!success, page);
2959 SetPageSwapBacked(page);
2960 add_page_to_lru_list_tail(page, lruvec, lru);
2965 if (tier > tier_idx) {
2966 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
2968 gen = page_inc_gen(lruvec, page, false);
2969 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
2971 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
2972 lrugen->protected[hist][type][tier - 1] + delta);
2973 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE, delta);
2977 /* waiting for writeback */
2978 if (PageLocked(page) || PageWriteback(page) ||
2979 (type == LRU_GEN_FILE && PageDirty(page))) {
2980 gen = page_inc_gen(lruvec, page, true);
2981 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
2988 static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
2992 /* unmapping inhibited */
2993 if (!sc->may_unmap && page_mapped(page))
2996 /* swapping inhibited */
2997 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
2999 (PageAnon(page) && !PageSwapCache(page))))
3002 /* raced with release_pages() */
3003 if (!get_page_unless_zero(page))
3006 /* raced with another isolation */
3007 if (!TestClearPageLRU(page)) {
3012 /* see the comment on MAX_NR_TIERS */
3013 if (!PageReferenced(page))
3014 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
3016 /* for shrink_page_list() */
3017 ClearPageReclaim(page);
3018 ClearPageReferenced(page);
3020 success = lru_gen_del_page(lruvec, page, true);
3021 VM_WARN_ON_ONCE_PAGE(!success, page);
3026 static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
3027 int type, int tier, struct list_head *list)
3030 enum vm_event_item item;
3034 int remaining = MAX_LRU_BATCH;
3035 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3036 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3038 VM_WARN_ON_ONCE(!list_empty(list));
3040 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
3043 gen = lru_gen_from_seq(lrugen->min_seq[type]);
3045 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
3048 struct list_head *head = &lrugen->lists[gen][type][zone];
3050 while (!list_empty(head)) {
3051 struct page *page = lru_to_page(head);
3052 int delta = hpage_nr_pages(page);
3054 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
3055 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
3056 VM_WARN_ON_ONCE_PAGE(page_is_file_cache(page) != type, page);
3057 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
3061 if (sort_page(lruvec, page, tier))
3063 else if (isolate_page(lruvec, page, sc)) {
3064 list_add(&page->lru, list);
3067 list_move(&page->lru, &moved);
3071 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
3076 list_splice(&moved, head);
3077 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
3080 if (!remaining || isolated >= MIN_LRU_BATCH)
3084 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
3085 if (!cgroup_reclaim(sc)) {
3086 __count_vm_events(item, isolated);
3087 __count_vm_events(PGREFILL, sorted);
3089 __count_memcg_events(memcg, item, isolated);
3090 __count_memcg_events(memcg, PGREFILL, sorted);
3093 * There might not be eligible pages due to reclaim_idx, may_unmap and
3094 * may_writepage. Check the remaining to prevent livelock if it's not
3097 return isolated || !remaining ? scanned : 0;
3100 static int get_tier_idx(struct lruvec *lruvec, int type)
3103 struct ctrl_pos sp, pv;
3106 * To leave a margin for fluctuations, use a larger gain factor (1:2).
3107 * This value is chosen because any other tier would have at least twice
3108 * as many refaults as the first tier.
3110 read_ctrl_pos(lruvec, type, 0, 1, &sp);
3111 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3112 read_ctrl_pos(lruvec, type, tier, 2, &pv);
3113 if (!positive_ctrl_err(&sp, &pv))
3120 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
3123 struct ctrl_pos sp, pv;
3124 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
3127 * Compare the first tier of anon with that of file to determine which
3128 * type to scan. Also need to compare other tiers of the selected type
3129 * with the first tier of the other type to determine the last tier (of
3130 * the selected type) to evict.
3132 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
3133 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
3134 type = positive_ctrl_err(&sp, &pv);
3136 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
3137 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3138 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
3139 if (!positive_ctrl_err(&sp, &pv))
3143 *tier_idx = tier - 1;
3148 static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
3149 int *type_scanned, struct list_head *list)
3155 DEFINE_MIN_SEQ(lruvec);
3158 * Try to make the obvious choice first. When anon and file are both
3159 * available from the same generation, interpret swappiness 1 as file
3160 * first and 200 as anon first.
3163 type = LRU_GEN_FILE;
3164 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
3165 type = LRU_GEN_ANON;
3166 else if (swappiness == 1)
3167 type = LRU_GEN_FILE;
3168 else if (swappiness == 200)
3169 type = LRU_GEN_ANON;
3171 type = get_type_to_scan(lruvec, swappiness, &tier);
3173 for (i = !swappiness; i < ANON_AND_FILE; i++) {
3175 tier = get_tier_idx(lruvec, type);
3177 scanned = scan_pages(lruvec, sc, type, tier, list);
3185 *type_scanned = type;
3190 static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
3197 enum vm_event_item item;
3198 struct reclaim_stat stat;
3199 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3200 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3202 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3204 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
3206 scanned += try_to_inc_min_seq(lruvec, swappiness);
3208 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
3211 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3213 if (list_empty(&list))
3216 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
3218 list_for_each_entry(page, &list, lru) {
3219 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
3220 if (PageWorkingset(page))
3221 SetPageReferenced(page);
3223 /* don't add rejected pages to the oldest generation */
3224 if (PageReclaim(page) &&
3225 (PageDirty(page) || PageWriteback(page)))
3226 ClearPageActive(page);
3228 SetPageActive(page);
3231 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3233 move_pages_to_lru(lruvec, &list);
3235 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
3236 if (!cgroup_reclaim(sc))
3237 __count_vm_events(item, reclaimed);
3238 __count_memcg_events(memcg, item, reclaimed);
3240 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3242 mem_cgroup_uncharge_list(&list);
3243 free_unref_page_list(&list);
3245 sc->nr_reclaimed += reclaimed;
3250 static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
3254 unsigned long nr_to_scan;
3255 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3256 DEFINE_MAX_SEQ(lruvec);
3257 DEFINE_MIN_SEQ(lruvec);
3259 if (mem_cgroup_below_min(memcg) ||
3260 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
3263 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
3267 /* skip the aging path at the default priority */
3268 if (sc->priority == DEF_PRIORITY)
3271 /* leave the work to lru_gen_age_node() */
3272 if (current_is_kswapd())
3275 inc_max_seq(lruvec, max_seq, can_swap);
3277 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
3280 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3282 struct blk_plug plug;
3283 unsigned long scanned = 0;
3287 blk_start_plug(&plug);
3292 unsigned long nr_to_scan;
3295 swappiness = get_swappiness(lruvec, sc);
3296 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
3301 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
3305 delta = evict_pages(lruvec, sc, swappiness);
3310 if (scanned >= nr_to_scan)
3316 blk_finish_plug(&plug);
3319 /******************************************************************************
3321 ******************************************************************************/
3323 void lru_gen_init_lruvec(struct lruvec *lruvec)
3325 int gen, type, zone;
3326 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3328 lrugen->max_seq = MIN_NR_GENS + 1;
3330 for_each_gen_type_zone(gen, type, zone)
3331 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
3335 void lru_gen_init_memcg(struct mem_cgroup *memcg)
3339 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
3343 for_each_node(nid) {
3344 struct lruvec *lruvec = get_lruvec(memcg, nid);
3346 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
3347 sizeof(lruvec->lrugen.nr_pages)));
3352 static int __init init_lru_gen(void)
3354 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
3355 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
3359 late_initcall(init_lru_gen);
3361 #else /* !CONFIG_LRU_GEN */
3363 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3367 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3371 #endif /* CONFIG_LRU_GEN */
3373 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3375 unsigned long nr[NR_LRU_LISTS];
3376 unsigned long targets[NR_LRU_LISTS];
3377 unsigned long nr_to_scan;
3379 unsigned long nr_reclaimed = 0;
3380 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
3381 struct blk_plug plug;
3384 if (lru_gen_enabled()) {
3385 lru_gen_shrink_lruvec(lruvec, sc);
3389 get_scan_count(lruvec, sc, nr);
3391 /* Record the original scan target for proportional adjustments later */
3392 memcpy(targets, nr, sizeof(nr));
3395 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
3396 * event that can occur when there is little memory pressure e.g.
3397 * multiple streaming readers/writers. Hence, we do not abort scanning
3398 * when the requested number of pages are reclaimed when scanning at
3399 * DEF_PRIORITY on the assumption that the fact we are direct
3400 * reclaiming implies that kswapd is not keeping up and it is best to
3401 * do a batch of work at once. For memcg reclaim one check is made to
3402 * abort proportional reclaim if either the file or anon lru has already
3403 * dropped to zero at the first pass.
3405 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
3406 sc->priority == DEF_PRIORITY);
3408 blk_start_plug(&plug);
3409 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
3410 nr[LRU_INACTIVE_FILE]) {
3411 unsigned long nr_anon, nr_file, percentage;
3412 unsigned long nr_scanned;
3414 for_each_evictable_lru(lru) {
3416 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
3417 nr[lru] -= nr_to_scan;
3419 nr_reclaimed += shrink_list(lru, nr_to_scan,
3426 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
3430 * For kswapd and memcg, reclaim at least the number of pages
3431 * requested. Ensure that the anon and file LRUs are scanned
3432 * proportionally what was requested by get_scan_count(). We
3433 * stop reclaiming one LRU and reduce the amount scanning
3434 * proportional to the original scan target.
3436 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3437 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3440 * It's just vindictive to attack the larger once the smaller
3441 * has gone to zero. And given the way we stop scanning the
3442 * smaller below, this makes sure that we only make one nudge
3443 * towards proportionality once we've got nr_to_reclaim.
3445 if (!nr_file || !nr_anon)
3448 if (nr_file > nr_anon) {
3449 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
3450 targets[LRU_ACTIVE_ANON] + 1;
3452 percentage = nr_anon * 100 / scan_target;
3454 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
3455 targets[LRU_ACTIVE_FILE] + 1;
3457 percentage = nr_file * 100 / scan_target;
3460 /* Stop scanning the smaller of the LRU */
3462 nr[lru + LRU_ACTIVE] = 0;
3465 * Recalculate the other LRU scan count based on its original
3466 * scan target and the percentage scanning already complete
3468 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
3469 nr_scanned = targets[lru] - nr[lru];
3470 nr[lru] = targets[lru] * (100 - percentage) / 100;
3471 nr[lru] -= min(nr[lru], nr_scanned);
3474 nr_scanned = targets[lru] - nr[lru];
3475 nr[lru] = targets[lru] * (100 - percentage) / 100;
3476 nr[lru] -= min(nr[lru], nr_scanned);
3478 scan_adjusted = true;
3480 blk_finish_plug(&plug);
3481 sc->nr_reclaimed += nr_reclaimed;
3484 * Even if we did not try to evict anon pages at all, we want to
3485 * rebalance the anon lru active/inactive ratio.
3487 if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3488 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3489 sc, LRU_ACTIVE_ANON);
3492 /* Use reclaim/compaction for costly allocs or under memory pressure */
3493 static bool in_reclaim_compaction(struct scan_control *sc)
3495 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
3496 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
3497 sc->priority < DEF_PRIORITY - 2))
3504 * Reclaim/compaction is used for high-order allocation requests. It reclaims
3505 * order-0 pages before compacting the zone. should_continue_reclaim() returns
3506 * true if more pages should be reclaimed such that when the page allocator
3507 * calls try_to_compact_zone() that it will have enough free pages to succeed.
3508 * It will give up earlier than that if there is difficulty reclaiming pages.
3510 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
3511 unsigned long nr_reclaimed,
3512 struct scan_control *sc)
3514 unsigned long pages_for_compaction;
3515 unsigned long inactive_lru_pages;
3518 /* If not in reclaim/compaction mode, stop */
3519 if (!in_reclaim_compaction(sc))
3523 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
3524 * number of pages that were scanned. This will return to the caller
3525 * with the risk reclaim/compaction and the resulting allocation attempt
3526 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
3527 * allocations through requiring that the full LRU list has been scanned
3528 * first, by assuming that zero delta of sc->nr_scanned means full LRU
3529 * scan, but that approximation was wrong, and there were corner cases
3530 * where always a non-zero amount of pages were scanned.
3535 /* If compaction would go ahead or the allocation would succeed, stop */
3536 for (z = 0; z <= sc->reclaim_idx; z++) {
3537 struct zone *zone = &pgdat->node_zones[z];
3538 if (!managed_zone(zone))
3541 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
3542 case COMPACT_SUCCESS:
3543 case COMPACT_CONTINUE:
3546 /* check next zone */
3552 * If we have not reclaimed enough pages for compaction and the
3553 * inactive lists are large enough, continue reclaiming
3555 pages_for_compaction = compact_gap(sc->order);
3556 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
3557 if (get_nr_swap_pages() > 0)
3558 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
3560 return inactive_lru_pages > pages_for_compaction;
3563 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
3565 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
3566 struct mem_cgroup *memcg;
3568 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
3570 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3571 unsigned long reclaimed;
3572 unsigned long scanned;
3574 mem_cgroup_calculate_protection(target_memcg, memcg);
3576 if (mem_cgroup_below_min(memcg)) {
3579 * If there is no reclaimable memory, OOM.
3582 } else if (mem_cgroup_below_low(memcg)) {
3585 * Respect the protection only as long as
3586 * there is an unprotected supply
3587 * of reclaimable memory from other cgroups.
3589 if (!sc->memcg_low_reclaim) {
3590 sc->memcg_low_skipped = 1;
3593 memcg_memory_event(memcg, MEMCG_LOW);
3596 reclaimed = sc->nr_reclaimed;
3597 scanned = sc->nr_scanned;
3599 shrink_lruvec(lruvec, sc);
3601 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
3604 /* Record the group's reclaim efficiency */
3605 vmpressure(sc->gfp_mask, memcg, false,
3606 sc->nr_scanned - scanned,
3607 sc->nr_reclaimed - reclaimed);
3609 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
3612 static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
3614 struct reclaim_state *reclaim_state = current->reclaim_state;
3615 unsigned long nr_reclaimed, nr_scanned;
3616 struct lruvec *target_lruvec;
3617 bool reclaimable = false;
3619 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
3622 memset(&sc->nr, 0, sizeof(sc->nr));
3624 nr_reclaimed = sc->nr_reclaimed;
3625 nr_scanned = sc->nr_scanned;
3627 prepare_scan_count(pgdat, sc);
3629 shrink_node_memcgs(pgdat, sc);
3631 if (reclaim_state) {
3632 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
3633 reclaim_state->reclaimed_slab = 0;
3636 /* Record the subtree's reclaim efficiency */
3637 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
3638 sc->nr_scanned - nr_scanned,
3639 sc->nr_reclaimed - nr_reclaimed);
3641 if (sc->nr_reclaimed - nr_reclaimed)
3644 if (current_is_kswapd()) {
3646 * If reclaim is isolating dirty pages under writeback,
3647 * it implies that the long-lived page allocation rate
3648 * is exceeding the page laundering rate. Either the
3649 * global limits are not being effective at throttling
3650 * processes due to the page distribution throughout
3651 * zones or there is heavy usage of a slow backing
3652 * device. The only option is to throttle from reclaim
3653 * context which is not ideal as there is no guarantee
3654 * the dirtying process is throttled in the same way
3655 * balance_dirty_pages() manages.
3657 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3658 * count the number of pages under pages flagged for
3659 * immediate reclaim and stall if any are encountered
3660 * in the nr_immediate check below.
3662 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3663 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3665 /* Allow kswapd to start writing pages during reclaim.*/
3666 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3667 set_bit(PGDAT_DIRTY, &pgdat->flags);
3670 * If kswapd scans pages marked marked for immediate
3671 * reclaim and under writeback (nr_immediate), it
3672 * implies that pages are cycling through the LRU
3673 * faster than they are written so also forcibly stall.
3675 if (sc->nr.immediate)
3676 congestion_wait(BLK_RW_ASYNC, HZ/10);
3680 * Tag a node/memcg as congested if all the dirty pages
3681 * scanned were backed by a congested BDI and
3682 * wait_iff_congested will stall.
3684 * Legacy memcg will stall in page writeback so avoid forcibly
3685 * stalling in wait_iff_congested().
3687 if ((current_is_kswapd() ||
3688 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3689 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
3690 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3693 * Stall direct reclaim for IO completions if underlying BDIs
3694 * and node is congested. Allow kswapd to continue until it
3695 * starts encountering unqueued dirty pages or cycling through
3696 * the LRU too quickly.
3698 if (!current_is_kswapd() && current_may_throttle() &&
3699 !sc->hibernation_mode &&
3700 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
3701 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
3703 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3708 * Kswapd gives up on balancing particular nodes after too
3709 * many failures to reclaim anything from them and goes to
3710 * sleep. On reclaim progress, reset the failure counter. A
3711 * successful direct reclaim run will revive a dormant kswapd.
3714 pgdat->kswapd_failures = 0;
3720 * Returns true if compaction should go ahead for a costly-order request, or
3721 * the allocation would already succeed without compaction. Return false if we
3722 * should reclaim first.
3724 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3726 unsigned long watermark;
3727 enum compact_result suitable;
3729 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3730 if (suitable == COMPACT_SUCCESS)
3731 /* Allocation should succeed already. Don't reclaim. */
3733 if (suitable == COMPACT_SKIPPED)
3734 /* Compaction cannot yet proceed. Do reclaim. */
3738 * Compaction is already possible, but it takes time to run and there
3739 * are potentially other callers using the pages just freed. So proceed
3740 * with reclaim to make a buffer of free pages available to give
3741 * compaction a reasonable chance of completing and allocating the page.
3742 * Note that we won't actually reclaim the whole buffer in one attempt
3743 * as the target watermark in should_continue_reclaim() is lower. But if
3744 * we are already above the high+gap watermark, don't reclaim at all.
3746 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3748 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3752 * This is the direct reclaim path, for page-allocating processes. We only
3753 * try to reclaim pages from zones which will satisfy the caller's allocation
3756 * If a zone is deemed to be full of pinned pages then just give it a light
3757 * scan then give up on it.
3759 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
3763 unsigned long nr_soft_reclaimed;
3764 unsigned long nr_soft_scanned;
3766 pg_data_t *last_pgdat = NULL;
3769 * If the number of buffer_heads in the machine exceeds the maximum
3770 * allowed level, force direct reclaim to scan the highmem zone as
3771 * highmem pages could be pinning lowmem pages storing buffer_heads
3773 orig_mask = sc->gfp_mask;
3774 if (buffer_heads_over_limit) {
3775 sc->gfp_mask |= __GFP_HIGHMEM;
3776 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3779 for_each_zone_zonelist_nodemask(zone, z, zonelist,
3780 sc->reclaim_idx, sc->nodemask) {
3782 * Take care memory controller reclaiming has small influence
3785 if (!cgroup_reclaim(sc)) {
3786 if (!cpuset_zone_allowed(zone,
3787 GFP_KERNEL | __GFP_HARDWALL))
3791 * If we already have plenty of memory free for
3792 * compaction in this zone, don't free any more.
3793 * Even though compaction is invoked for any
3794 * non-zero order, only frequent costly order
3795 * reclamation is disruptive enough to become a
3796 * noticeable problem, like transparent huge
3799 if (IS_ENABLED(CONFIG_COMPACTION) &&
3800 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
3801 compaction_ready(zone, sc)) {
3802 sc->compaction_ready = true;
3807 * Shrink each node in the zonelist once. If the
3808 * zonelist is ordered by zone (not the default) then a
3809 * node may be shrunk multiple times but in that case
3810 * the user prefers lower zones being preserved.
3812 if (zone->zone_pgdat == last_pgdat)
3816 * This steals pages from memory cgroups over softlimit
3817 * and returns the number of reclaimed pages and
3818 * scanned pages. This works for global memory pressure
3819 * and balancing, not for a memcg's limit.
3821 nr_soft_scanned = 0;
3822 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
3823 sc->order, sc->gfp_mask,
3825 sc->nr_reclaimed += nr_soft_reclaimed;
3826 sc->nr_scanned += nr_soft_scanned;
3827 /* need some check for avoid more shrink_zone() */
3830 /* See comment about same check for global reclaim above */
3831 if (zone->zone_pgdat == last_pgdat)
3833 last_pgdat = zone->zone_pgdat;
3834 shrink_node(zone->zone_pgdat, sc);
3838 * Restore to original mask to avoid the impact on the caller if we
3839 * promoted it to __GFP_HIGHMEM.
3841 sc->gfp_mask = orig_mask;
3844 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
3846 struct lruvec *target_lruvec;
3847 unsigned long refaults;
3849 if (lru_gen_enabled())
3852 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3853 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE);
3854 target_lruvec->refaults = refaults;
3858 * This is the main entry point to direct page reclaim.
3860 * If a full scan of the inactive list fails to free enough memory then we
3861 * are "out of memory" and something needs to be killed.
3863 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3864 * high - the zone may be full of dirty or under-writeback pages, which this
3865 * caller can't do much about. We kick the writeback threads and take explicit
3866 * naps in the hope that some of these pages can be written. But if the
3867 * allocating task holds filesystem locks which prevent writeout this might not
3868 * work, and the allocation attempt will fail.
3870 * returns: 0, if no pages reclaimed
3871 * else, the number of pages reclaimed
3873 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3874 struct scan_control *sc)
3876 int initial_priority = sc->priority;
3877 pg_data_t *last_pgdat;
3881 delayacct_freepages_start();
3883 if (!cgroup_reclaim(sc))
3884 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
3887 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
3890 shrink_zones(zonelist, sc);
3892 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
3895 if (sc->compaction_ready)
3899 * If we're getting trouble reclaiming, start doing
3900 * writepage even in laptop mode.
3902 if (sc->priority < DEF_PRIORITY - 2)
3903 sc->may_writepage = 1;
3904 } while (--sc->priority >= 0);
3907 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
3909 if (zone->zone_pgdat == last_pgdat)
3911 last_pgdat = zone->zone_pgdat;
3913 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3915 if (cgroup_reclaim(sc)) {
3916 struct lruvec *lruvec;
3918 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
3920 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3924 delayacct_freepages_end();
3926 if (sc->nr_reclaimed)
3927 return sc->nr_reclaimed;
3929 /* Aborted reclaim to try compaction? don't OOM, then */
3930 if (sc->compaction_ready)
3934 * We make inactive:active ratio decisions based on the node's
3935 * composition of memory, but a restrictive reclaim_idx or a
3936 * memory.low cgroup setting can exempt large amounts of
3937 * memory from reclaim. Neither of which are very common, so
3938 * instead of doing costly eligibility calculations of the
3939 * entire cgroup subtree up front, we assume the estimates are
3940 * good, and retry with forcible deactivation if that fails.
3942 if (sc->skipped_deactivate) {
3943 sc->priority = initial_priority;
3944 sc->force_deactivate = 1;
3945 sc->skipped_deactivate = 0;
3949 /* Untapped cgroup reserves? Don't OOM, retry. */
3950 if (sc->memcg_low_skipped) {
3951 sc->priority = initial_priority;
3952 sc->force_deactivate = 0;
3953 sc->skipped_deactivate = 0;
3954 sc->memcg_low_reclaim = 1;
3955 sc->memcg_low_skipped = 0;
3962 static bool allow_direct_reclaim(pg_data_t *pgdat)
3965 unsigned long pfmemalloc_reserve = 0;
3966 unsigned long free_pages = 0;
3970 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3973 for (i = 0; i <= ZONE_NORMAL; i++) {
3974 zone = &pgdat->node_zones[i];
3975 if (!managed_zone(zone))
3978 if (!zone_reclaimable_pages(zone))
3981 pfmemalloc_reserve += min_wmark_pages(zone);
3982 free_pages += zone_page_state(zone, NR_FREE_PAGES);
3985 /* If there are no reserves (unexpected config) then do not throttle */
3986 if (!pfmemalloc_reserve)
3989 wmark_ok = free_pages > pfmemalloc_reserve / 2;
3991 /* kswapd must be awake if processes are being throttled */
3992 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
3993 pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
3994 (enum zone_type)ZONE_NORMAL);
3995 wake_up_interruptible(&pgdat->kswapd_wait);
4002 * Throttle direct reclaimers if backing storage is backed by the network
4003 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
4004 * depleted. kswapd will continue to make progress and wake the processes
4005 * when the low watermark is reached.
4007 * Returns true if a fatal signal was delivered during throttling. If this
4008 * happens, the page allocator should not consider triggering the OOM killer.
4010 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
4011 nodemask_t *nodemask)
4015 pg_data_t *pgdat = NULL;
4018 * Kernel threads should not be throttled as they may be indirectly
4019 * responsible for cleaning pages necessary for reclaim to make forward
4020 * progress. kjournald for example may enter direct reclaim while
4021 * committing a transaction where throttling it could forcing other
4022 * processes to block on log_wait_commit().
4024 if (current->flags & PF_KTHREAD)
4028 * If a fatal signal is pending, this process should not throttle.
4029 * It should return quickly so it can exit and free its memory
4031 if (fatal_signal_pending(current))
4035 * Check if the pfmemalloc reserves are ok by finding the first node
4036 * with a usable ZONE_NORMAL or lower zone. The expectation is that
4037 * GFP_KERNEL will be required for allocating network buffers when
4038 * swapping over the network so ZONE_HIGHMEM is unusable.
4040 * Throttling is based on the first usable node and throttled processes
4041 * wait on a queue until kswapd makes progress and wakes them. There
4042 * is an affinity then between processes waking up and where reclaim
4043 * progress has been made assuming the process wakes on the same node.
4044 * More importantly, processes running on remote nodes will not compete
4045 * for remote pfmemalloc reserves and processes on different nodes
4046 * should make reasonable progress.
4048 for_each_zone_zonelist_nodemask(zone, z, zonelist,
4049 gfp_zone(gfp_mask), nodemask) {
4050 if (zone_idx(zone) > ZONE_NORMAL)
4053 /* Throttle based on the first usable node */
4054 pgdat = zone->zone_pgdat;
4055 if (allow_direct_reclaim(pgdat))
4060 /* If no zone was usable by the allocation flags then do not throttle */
4064 /* Account for the throttling */
4065 count_vm_event(PGSCAN_DIRECT_THROTTLE);
4068 * If the caller cannot enter the filesystem, it's possible that it
4069 * is due to the caller holding an FS lock or performing a journal
4070 * transaction in the case of a filesystem like ext[3|4]. In this case,
4071 * it is not safe to block on pfmemalloc_wait as kswapd could be
4072 * blocked waiting on the same lock. Instead, throttle for up to a
4073 * second before continuing.
4075 if (!(gfp_mask & __GFP_FS)) {
4076 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
4077 allow_direct_reclaim(pgdat), HZ);
4082 /* Throttle until kswapd wakes the process */
4083 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
4084 allow_direct_reclaim(pgdat));
4087 if (fatal_signal_pending(current))
4094 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
4095 gfp_t gfp_mask, nodemask_t *nodemask)
4097 unsigned long nr_reclaimed;
4098 struct scan_control sc = {
4099 .nr_to_reclaim = SWAP_CLUSTER_MAX,
4100 .gfp_mask = current_gfp_context(gfp_mask),
4101 .reclaim_idx = gfp_zone(gfp_mask),
4103 .nodemask = nodemask,
4104 .priority = DEF_PRIORITY,
4105 .may_writepage = !laptop_mode,
4111 * scan_control uses s8 fields for order, priority, and reclaim_idx.
4112 * Confirm they are large enough for max values.
4114 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
4115 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
4116 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
4119 * Do not enter reclaim if fatal signal was delivered while throttled.
4120 * 1 is returned so that the page allocator does not OOM kill at this
4123 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
4126 set_task_reclaim_state(current, &sc.reclaim_state);
4127 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
4129 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4131 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
4132 set_task_reclaim_state(current, NULL);
4134 return nr_reclaimed;
4139 /* Only used by soft limit reclaim. Do not reuse for anything else. */
4140 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
4141 gfp_t gfp_mask, bool noswap,
4143 unsigned long *nr_scanned)
4145 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4146 struct scan_control sc = {
4147 .nr_to_reclaim = SWAP_CLUSTER_MAX,
4148 .target_mem_cgroup = memcg,
4149 .may_writepage = !laptop_mode,
4151 .reclaim_idx = MAX_NR_ZONES - 1,
4152 .may_swap = !noswap,
4155 WARN_ON_ONCE(!current->reclaim_state);
4157 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
4158 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
4160 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
4164 * NOTE: Although we can get the priority field, using it
4165 * here is not a good idea, since it limits the pages we can scan.
4166 * if we don't reclaim here, the shrink_node from balance_pgdat
4167 * will pick up pages from other mem cgroup's as well. We hack
4168 * the priority and make it zero.
4170 shrink_lruvec(lruvec, &sc);
4172 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
4174 *nr_scanned = sc.nr_scanned;
4176 return sc.nr_reclaimed;
4179 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
4180 unsigned long nr_pages,
4184 struct zonelist *zonelist;
4185 unsigned long nr_reclaimed;
4186 unsigned long pflags;
4188 unsigned int noreclaim_flag;
4189 struct scan_control sc = {
4190 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4191 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
4192 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
4193 .reclaim_idx = MAX_NR_ZONES - 1,
4194 .target_mem_cgroup = memcg,
4195 .priority = DEF_PRIORITY,
4196 .may_writepage = !laptop_mode,
4198 .may_swap = may_swap,
4201 set_task_reclaim_state(current, &sc.reclaim_state);
4203 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
4204 * take care of from where we get pages. So the node where we start the
4205 * scan does not need to be the current node.
4207 nid = mem_cgroup_select_victim_node(memcg);
4209 zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
4211 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
4213 psi_memstall_enter(&pflags);
4214 noreclaim_flag = memalloc_noreclaim_save();
4216 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4218 memalloc_noreclaim_restore(noreclaim_flag);
4219 psi_memstall_leave(&pflags);
4221 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
4222 set_task_reclaim_state(current, NULL);
4224 return nr_reclaimed;
4228 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4230 struct mem_cgroup *memcg;
4231 struct lruvec *lruvec;
4233 if (lru_gen_enabled()) {
4234 lru_gen_age_node(pgdat, sc);
4239 if (!total_swap_pages)
4242 lruvec = mem_cgroup_lruvec(NULL, pgdat);
4243 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
4246 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4248 lruvec = mem_cgroup_lruvec(memcg, pgdat);
4249 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4250 sc, LRU_ACTIVE_ANON);
4251 memcg = mem_cgroup_iter(NULL, memcg, NULL);
4255 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
4261 * Check for watermark boosts top-down as the higher zones
4262 * are more likely to be boosted. Both watermarks and boosts
4263 * should not be checked at the time time as reclaim would
4264 * start prematurely when there is no boosting and a lower
4267 for (i = classzone_idx; i >= 0; i--) {
4268 zone = pgdat->node_zones + i;
4269 if (!managed_zone(zone))
4272 if (zone->watermark_boost)
4280 * Returns true if there is an eligible zone balanced for the request order
4283 static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
4286 unsigned long mark = -1;
4290 * Check watermarks bottom-up as lower zones are more likely to
4293 for (i = 0; i <= classzone_idx; i++) {
4294 zone = pgdat->node_zones + i;
4296 if (!managed_zone(zone))
4299 mark = high_wmark_pages(zone);
4300 if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
4305 * If a node has no populated zone within classzone_idx, it does not
4306 * need balancing by definition. This can happen if a zone-restricted
4307 * allocation tries to wake a remote kswapd.
4315 /* Clear pgdat state for congested, dirty or under writeback. */
4316 static void clear_pgdat_congested(pg_data_t *pgdat)
4318 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
4320 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
4321 clear_bit(PGDAT_DIRTY, &pgdat->flags);
4322 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4326 * Prepare kswapd for sleeping. This verifies that there are no processes
4327 * waiting in throttle_direct_reclaim() and that watermarks have been met.
4329 * Returns true if kswapd is ready to sleep
4331 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
4334 * The throttled processes are normally woken up in balance_pgdat() as
4335 * soon as allow_direct_reclaim() is true. But there is a potential
4336 * race between when kswapd checks the watermarks and a process gets
4337 * throttled. There is also a potential race if processes get
4338 * throttled, kswapd wakes, a large process exits thereby balancing the
4339 * zones, which causes kswapd to exit balance_pgdat() before reaching
4340 * the wake up checks. If kswapd is going to sleep, no process should
4341 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
4342 * the wake up is premature, processes will wake kswapd and get
4343 * throttled again. The difference from wake ups in balance_pgdat() is
4344 * that here we are under prepare_to_wait().
4346 if (waitqueue_active(&pgdat->pfmemalloc_wait))
4347 wake_up_all(&pgdat->pfmemalloc_wait);
4349 /* Hopeless node, leave it to direct reclaim */
4350 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4353 if (pgdat_balanced(pgdat, order, classzone_idx)) {
4354 clear_pgdat_congested(pgdat);
4362 * kswapd shrinks a node of pages that are at or below the highest usable
4363 * zone that is currently unbalanced.
4365 * Returns true if kswapd scanned at least the requested number of pages to
4366 * reclaim or if the lack of progress was due to pages under writeback.
4367 * This is used to determine if the scanning priority needs to be raised.
4369 static bool kswapd_shrink_node(pg_data_t *pgdat,
4370 struct scan_control *sc)
4375 /* Reclaim a number of pages proportional to the number of zones */
4376 sc->nr_to_reclaim = 0;
4377 for (z = 0; z <= sc->reclaim_idx; z++) {
4378 zone = pgdat->node_zones + z;
4379 if (!managed_zone(zone))
4382 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
4386 * Historically care was taken to put equal pressure on all zones but
4387 * now pressure is applied based on node LRU order.
4389 shrink_node(pgdat, sc);
4392 * Fragmentation may mean that the system cannot be rebalanced for
4393 * high-order allocations. If twice the allocation size has been
4394 * reclaimed then recheck watermarks only at order-0 to prevent
4395 * excessive reclaim. Assume that a process requested a high-order
4396 * can direct reclaim/compact.
4398 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
4401 return sc->nr_scanned >= sc->nr_to_reclaim;
4405 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
4406 * that are eligible for use by the caller until at least one zone is
4409 * Returns the order kswapd finished reclaiming at.
4411 * kswapd scans the zones in the highmem->normal->dma direction. It skips
4412 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
4413 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
4414 * or lower is eligible for reclaim until at least one usable zone is
4417 static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
4420 unsigned long nr_soft_reclaimed;
4421 unsigned long nr_soft_scanned;
4422 unsigned long pflags;
4423 unsigned long nr_boost_reclaim;
4424 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
4427 struct scan_control sc = {
4428 .gfp_mask = GFP_KERNEL,
4433 set_task_reclaim_state(current, &sc.reclaim_state);
4434 psi_memstall_enter(&pflags);
4435 __fs_reclaim_acquire();
4437 count_vm_event(PAGEOUTRUN);
4440 * Account for the reclaim boost. Note that the zone boost is left in
4441 * place so that parallel allocations that are near the watermark will
4442 * stall or direct reclaim until kswapd is finished.
4444 nr_boost_reclaim = 0;
4445 for (i = 0; i <= classzone_idx; i++) {
4446 zone = pgdat->node_zones + i;
4447 if (!managed_zone(zone))
4450 nr_boost_reclaim += zone->watermark_boost;
4451 zone_boosts[i] = zone->watermark_boost;
4453 boosted = nr_boost_reclaim;
4456 sc.priority = DEF_PRIORITY;
4458 unsigned long nr_reclaimed = sc.nr_reclaimed;
4459 bool raise_priority = true;
4463 sc.reclaim_idx = classzone_idx;
4466 * If the number of buffer_heads exceeds the maximum allowed
4467 * then consider reclaiming from all zones. This has a dual
4468 * purpose -- on 64-bit systems it is expected that
4469 * buffer_heads are stripped during active rotation. On 32-bit
4470 * systems, highmem pages can pin lowmem memory and shrinking
4471 * buffers can relieve lowmem pressure. Reclaim may still not
4472 * go ahead if all eligible zones for the original allocation
4473 * request are balanced to avoid excessive reclaim from kswapd.
4475 if (buffer_heads_over_limit) {
4476 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
4477 zone = pgdat->node_zones + i;
4478 if (!managed_zone(zone))
4487 * If the pgdat is imbalanced then ignore boosting and preserve
4488 * the watermarks for a later time and restart. Note that the
4489 * zone watermarks will be still reset at the end of balancing
4490 * on the grounds that the normal reclaim should be enough to
4491 * re-evaluate if boosting is required when kswapd next wakes.
4493 balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
4494 if (!balanced && nr_boost_reclaim) {
4495 nr_boost_reclaim = 0;
4500 * If boosting is not active then only reclaim if there are no
4501 * eligible zones. Note that sc.reclaim_idx is not used as
4502 * buffer_heads_over_limit may have adjusted it.
4504 if (!nr_boost_reclaim && balanced)
4507 /* Limit the priority of boosting to avoid reclaim writeback */
4508 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
4509 raise_priority = false;
4512 * Do not writeback or swap pages for boosted reclaim. The
4513 * intent is to relieve pressure not issue sub-optimal IO
4514 * from reclaim context. If no pages are reclaimed, the
4515 * reclaim will be aborted.
4517 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
4518 sc.may_swap = !nr_boost_reclaim;
4521 * Do some background aging, to give pages a chance to be
4522 * referenced before reclaiming. All pages are rotated
4523 * regardless of classzone as this is about consistent aging.
4525 kswapd_age_node(pgdat, &sc);
4528 * If we're getting trouble reclaiming, start doing writepage
4529 * even in laptop mode.
4531 if (sc.priority < DEF_PRIORITY - 2)
4532 sc.may_writepage = 1;
4534 /* Call soft limit reclaim before calling shrink_node. */
4536 nr_soft_scanned = 0;
4537 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
4538 sc.gfp_mask, &nr_soft_scanned);
4539 sc.nr_reclaimed += nr_soft_reclaimed;
4542 * There should be no need to raise the scanning priority if
4543 * enough pages are already being scanned that that high
4544 * watermark would be met at 100% efficiency.
4546 if (kswapd_shrink_node(pgdat, &sc))
4547 raise_priority = false;
4550 * If the low watermark is met there is no need for processes
4551 * to be throttled on pfmemalloc_wait as they should not be
4552 * able to safely make forward progress. Wake them
4554 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
4555 allow_direct_reclaim(pgdat))
4556 wake_up_all(&pgdat->pfmemalloc_wait);
4558 /* Check if kswapd should be suspending */
4559 __fs_reclaim_release();
4560 ret = try_to_freeze();
4561 __fs_reclaim_acquire();
4562 if (ret || kthread_should_stop())
4566 * Raise priority if scanning rate is too low or there was no
4567 * progress in reclaiming pages
4569 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
4570 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
4573 * If reclaim made no progress for a boost, stop reclaim as
4574 * IO cannot be queued and it could be an infinite loop in
4575 * extreme circumstances.
4577 if (nr_boost_reclaim && !nr_reclaimed)
4580 if (raise_priority || !nr_reclaimed)
4582 } while (sc.priority >= 1);
4584 if (!sc.nr_reclaimed)
4585 pgdat->kswapd_failures++;
4588 /* If reclaim was boosted, account for the reclaim done in this pass */
4590 unsigned long flags;
4592 for (i = 0; i <= classzone_idx; i++) {
4593 if (!zone_boosts[i])
4596 /* Increments are under the zone lock */
4597 zone = pgdat->node_zones + i;
4598 spin_lock_irqsave(&zone->lock, flags);
4599 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
4600 spin_unlock_irqrestore(&zone->lock, flags);
4604 * As there is now likely space, wakeup kcompact to defragment
4607 wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
4610 snapshot_refaults(NULL, pgdat);
4611 __fs_reclaim_release();
4612 psi_memstall_leave(&pflags);
4613 set_task_reclaim_state(current, NULL);
4616 * Return the order kswapd stopped reclaiming at as
4617 * prepare_kswapd_sleep() takes it into account. If another caller
4618 * entered the allocator slow path while kswapd was awake, order will
4619 * remain at the higher level.
4625 * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
4626 * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
4627 * a valid index then either kswapd runs for first time or kswapd couldn't sleep
4628 * after previous reclaim attempt (node is still unbalanced). In that case
4629 * return the zone index of the previous kswapd reclaim cycle.
4631 static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
4632 enum zone_type prev_classzone_idx)
4634 if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
4635 return prev_classzone_idx;
4636 return pgdat->kswapd_classzone_idx;
4639 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
4640 unsigned int classzone_idx)
4645 if (freezing(current) || kthread_should_stop())
4648 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4651 * Try to sleep for a short interval. Note that kcompactd will only be
4652 * woken if it is possible to sleep for a short interval. This is
4653 * deliberate on the assumption that if reclaim cannot keep an
4654 * eligible zone balanced that it's also unlikely that compaction will
4657 if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
4659 * Compaction records what page blocks it recently failed to
4660 * isolate pages from and skips them in the future scanning.
4661 * When kswapd is going to sleep, it is reasonable to assume
4662 * that pages and compaction may succeed so reset the cache.
4664 reset_isolation_suitable(pgdat);
4667 * We have freed the memory, now we should compact it to make
4668 * allocation of the requested order possible.
4670 wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
4672 remaining = schedule_timeout(HZ/10);
4675 * If woken prematurely then reset kswapd_classzone_idx and
4676 * order. The values will either be from a wakeup request or
4677 * the previous request that slept prematurely.
4680 pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
4681 pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
4684 finish_wait(&pgdat->kswapd_wait, &wait);
4685 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4689 * After a short sleep, check if it was a premature sleep. If not, then
4690 * go fully to sleep until explicitly woken up.
4693 prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
4694 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4697 * vmstat counters are not perfectly accurate and the estimated
4698 * value for counters such as NR_FREE_PAGES can deviate from the
4699 * true value by nr_online_cpus * threshold. To avoid the zone
4700 * watermarks being breached while under pressure, we reduce the
4701 * per-cpu vmstat threshold while kswapd is awake and restore
4702 * them before going back to sleep.
4704 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
4706 if (!kthread_should_stop())
4709 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4712 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4714 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4716 finish_wait(&pgdat->kswapd_wait, &wait);
4720 * The background pageout daemon, started as a kernel thread
4721 * from the init process.
4723 * This basically trickles out pages so that we have _some_
4724 * free memory available even if there is no other activity
4725 * that frees anything up. This is needed for things like routing
4726 * etc, where we otherwise might have all activity going on in
4727 * asynchronous contexts that cannot page things out.
4729 * If there are applications that are active memory-allocators
4730 * (most normal use), this basically shouldn't matter.
4732 static int kswapd(void *p)
4734 unsigned int alloc_order, reclaim_order;
4735 unsigned int classzone_idx = MAX_NR_ZONES - 1;
4736 pg_data_t *pgdat = (pg_data_t*)p;
4737 struct task_struct *tsk = current;
4738 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
4740 if (!cpumask_empty(cpumask))
4741 set_cpus_allowed_ptr(tsk, cpumask);
4744 * Tell the memory management that we're a "memory allocator",
4745 * and that if we need more memory we should get access to it
4746 * regardless (see "__alloc_pages()"). "kswapd" should
4747 * never get caught in the normal page freeing logic.
4749 * (Kswapd normally doesn't need memory anyway, but sometimes
4750 * you need a small amount of memory in order to be able to
4751 * page out something else, and this flag essentially protects
4752 * us from recursively trying to free more memory as we're
4753 * trying to free the first piece of memory in the first place).
4755 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
4758 pgdat->kswapd_order = 0;
4759 pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
4763 alloc_order = reclaim_order = pgdat->kswapd_order;
4764 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
4767 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
4770 /* Read the new order and classzone_idx */
4771 alloc_order = reclaim_order = pgdat->kswapd_order;
4772 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
4773 pgdat->kswapd_order = 0;
4774 pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
4776 ret = try_to_freeze();
4777 if (kthread_should_stop())
4781 * We can speed up thawing tasks if we don't call balance_pgdat
4782 * after returning from the refrigerator
4788 * Reclaim begins at the requested order but if a high-order
4789 * reclaim fails then kswapd falls back to reclaiming for
4790 * order-0. If that happens, kswapd will consider sleeping
4791 * for the order it finished reclaiming at (reclaim_order)
4792 * but kcompactd is woken to compact for the original
4793 * request (alloc_order).
4795 trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
4797 reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
4798 if (reclaim_order < alloc_order)
4799 goto kswapd_try_sleep;
4802 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
4808 * A zone is low on free memory or too fragmented for high-order memory. If
4809 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
4810 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
4811 * has failed or is not needed, still wake up kcompactd if only compaction is
4814 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
4815 enum zone_type classzone_idx)
4819 if (!managed_zone(zone))
4822 if (!cpuset_zone_allowed(zone, gfp_flags))
4824 pgdat = zone->zone_pgdat;
4826 if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
4827 pgdat->kswapd_classzone_idx = classzone_idx;
4829 pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
4831 pgdat->kswapd_order = max(pgdat->kswapd_order, order);
4832 if (!waitqueue_active(&pgdat->kswapd_wait))
4835 /* Hopeless node, leave it to direct reclaim if possible */
4836 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
4837 (pgdat_balanced(pgdat, order, classzone_idx) &&
4838 !pgdat_watermark_boosted(pgdat, classzone_idx))) {
4840 * There may be plenty of free memory available, but it's too
4841 * fragmented for high-order allocations. Wake up kcompactd
4842 * and rely on compaction_suitable() to determine if it's
4843 * needed. If it fails, it will defer subsequent attempts to
4844 * ratelimit its work.
4846 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
4847 wakeup_kcompactd(pgdat, order, classzone_idx);
4851 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
4853 wake_up_interruptible(&pgdat->kswapd_wait);
4856 #ifdef CONFIG_HIBERNATION
4858 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4861 * Rather than trying to age LRUs the aim is to preserve the overall
4862 * LRU order by reclaiming preferentially
4863 * inactive > active > active referenced > active mapped
4865 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
4867 struct scan_control sc = {
4868 .nr_to_reclaim = nr_to_reclaim,
4869 .gfp_mask = GFP_HIGHUSER_MOVABLE,
4870 .reclaim_idx = MAX_NR_ZONES - 1,
4871 .priority = DEF_PRIORITY,
4875 .hibernation_mode = 1,
4877 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
4878 unsigned long nr_reclaimed;
4879 unsigned int noreclaim_flag;
4881 fs_reclaim_acquire(sc.gfp_mask);
4882 noreclaim_flag = memalloc_noreclaim_save();
4883 set_task_reclaim_state(current, &sc.reclaim_state);
4885 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4887 set_task_reclaim_state(current, NULL);
4888 memalloc_noreclaim_restore(noreclaim_flag);
4889 fs_reclaim_release(sc.gfp_mask);
4891 return nr_reclaimed;
4893 #endif /* CONFIG_HIBERNATION */
4895 /* It's optimal to keep kswapds on the same CPUs as their memory, but
4896 not required for correctness. So if the last cpu in a node goes
4897 away, we get changed to run anywhere: as the first one comes back,
4898 restore their cpu bindings. */
4899 static int kswapd_cpu_online(unsigned int cpu)
4903 for_each_node_state(nid, N_MEMORY) {
4904 pg_data_t *pgdat = NODE_DATA(nid);
4905 const struct cpumask *mask;
4907 mask = cpumask_of_node(pgdat->node_id);
4909 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
4910 /* One of our CPUs online: restore mask */
4911 set_cpus_allowed_ptr(pgdat->kswapd, mask);
4917 * This kswapd start function will be called by init and node-hot-add.
4918 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
4920 int kswapd_run(int nid)
4922 pg_data_t *pgdat = NODE_DATA(nid);
4928 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
4929 if (IS_ERR(pgdat->kswapd)) {
4930 /* failure at boot is fatal */
4931 BUG_ON(system_state < SYSTEM_RUNNING);
4932 pr_err("Failed to start kswapd on node %d\n", nid);
4933 ret = PTR_ERR(pgdat->kswapd);
4934 pgdat->kswapd = NULL;
4940 * Called by memory hotplug when all memory in a node is offlined. Caller must
4941 * hold mem_hotplug_begin/end().
4943 void kswapd_stop(int nid)
4945 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
4948 kthread_stop(kswapd);
4949 NODE_DATA(nid)->kswapd = NULL;
4953 static int __init kswapd_init(void)
4958 for_each_node_state(nid, N_MEMORY)
4960 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
4961 "mm/vmscan:online", kswapd_cpu_online,
4967 module_init(kswapd_init)
4973 * If non-zero call node_reclaim when the number of free pages falls below
4976 int node_reclaim_mode __read_mostly;
4978 #define RECLAIM_OFF 0
4979 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
4980 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
4981 #define RECLAIM_UNMAP (1<<2) /* Unmap pages during reclaim */
4984 * Priority for NODE_RECLAIM. This determines the fraction of pages
4985 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4988 #define NODE_RECLAIM_PRIORITY 4
4991 * Percentage of pages in a zone that must be unmapped for node_reclaim to
4994 int sysctl_min_unmapped_ratio = 1;
4997 * If the number of slab pages in a zone grows beyond this percentage then
4998 * slab reclaim needs to occur.
5000 int sysctl_min_slab_ratio = 5;
5002 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
5004 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
5005 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
5006 node_page_state(pgdat, NR_ACTIVE_FILE);
5009 * It's possible for there to be more file mapped pages than
5010 * accounted for by the pages on the file LRU lists because
5011 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
5013 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
5016 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
5017 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
5019 unsigned long nr_pagecache_reclaimable;
5020 unsigned long delta = 0;
5023 * If RECLAIM_UNMAP is set, then all file pages are considered
5024 * potentially reclaimable. Otherwise, we have to worry about
5025 * pages like swapcache and node_unmapped_file_pages() provides
5028 if (node_reclaim_mode & RECLAIM_UNMAP)
5029 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
5031 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
5033 /* If we can't clean pages, remove dirty pages from consideration */
5034 if (!(node_reclaim_mode & RECLAIM_WRITE))
5035 delta += node_page_state(pgdat, NR_FILE_DIRTY);
5037 /* Watch for any possible underflows due to delta */
5038 if (unlikely(delta > nr_pagecache_reclaimable))
5039 delta = nr_pagecache_reclaimable;
5041 return nr_pagecache_reclaimable - delta;
5045 * Try to free up some pages from this node through reclaim.
5047 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
5049 /* Minimum pages needed in order to stay on node */
5050 const unsigned long nr_pages = 1 << order;
5051 struct task_struct *p = current;
5052 unsigned int noreclaim_flag;
5053 struct scan_control sc = {
5054 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
5055 .gfp_mask = current_gfp_context(gfp_mask),
5057 .priority = NODE_RECLAIM_PRIORITY,
5058 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
5059 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
5061 .reclaim_idx = gfp_zone(gfp_mask),
5064 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
5068 fs_reclaim_acquire(sc.gfp_mask);
5070 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
5071 * and we also need to be able to write out pages for RECLAIM_WRITE
5072 * and RECLAIM_UNMAP.
5074 noreclaim_flag = memalloc_noreclaim_save();
5075 p->flags |= PF_SWAPWRITE;
5076 set_task_reclaim_state(p, &sc.reclaim_state);
5078 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
5080 * Free memory by calling shrink node with increasing
5081 * priorities until we have enough memory freed.
5084 shrink_node(pgdat, &sc);
5085 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
5088 set_task_reclaim_state(p, NULL);
5089 current->flags &= ~PF_SWAPWRITE;
5090 memalloc_noreclaim_restore(noreclaim_flag);
5091 fs_reclaim_release(sc.gfp_mask);
5093 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
5095 return sc.nr_reclaimed >= nr_pages;
5098 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
5103 * Node reclaim reclaims unmapped file backed pages and
5104 * slab pages if we are over the defined limits.
5106 * A small portion of unmapped file backed pages is needed for
5107 * file I/O otherwise pages read by file I/O will be immediately
5108 * thrown out if the node is overallocated. So we do not reclaim
5109 * if less than a specified percentage of the node is used by
5110 * unmapped file backed pages.
5112 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
5113 node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
5114 return NODE_RECLAIM_FULL;
5117 * Do not scan if the allocation should not be delayed.
5119 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
5120 return NODE_RECLAIM_NOSCAN;
5123 * Only run node reclaim on the local node or on nodes that do not
5124 * have associated processors. This will favor the local processor
5125 * over remote processors and spread off node memory allocations
5126 * as wide as possible.
5128 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
5129 return NODE_RECLAIM_NOSCAN;
5131 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
5132 return NODE_RECLAIM_NOSCAN;
5134 ret = __node_reclaim(pgdat, gfp_mask, order);
5135 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
5138 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
5145 * page_evictable - test whether a page is evictable
5146 * @page: the page to test
5148 * Test whether page is evictable--i.e., should be placed on active/inactive
5149 * lists vs unevictable list.
5151 * Reasons page might not be evictable:
5152 * (1) page's mapping marked unevictable
5153 * (2) page is part of an mlocked VMA
5156 int page_evictable(struct page *page)
5160 /* Prevent address_space of inode and swap cache from being freed */
5162 ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
5168 * check_move_unevictable_pages - check pages for evictability and move to
5169 * appropriate zone lru list
5170 * @pvec: pagevec with lru pages to check
5172 * Checks pages for evictability, if an evictable page is in the unevictable
5173 * lru list, moves it to the appropriate evictable lru list. This function
5174 * should be only used for lru pages.
5176 void check_move_unevictable_pages(struct pagevec *pvec)
5178 struct lruvec *lruvec;
5179 struct pglist_data *pgdat = NULL;
5184 for (i = 0; i < pvec->nr; i++) {
5185 struct page *page = pvec->pages[i];
5186 struct pglist_data *pagepgdat = page_pgdat(page);
5190 if (!TestClearPageLRU(page))
5193 if (pagepgdat != pgdat) {
5195 spin_unlock_irq(&pgdat->lru_lock);
5197 spin_lock_irq(&pgdat->lru_lock);
5199 lruvec = mem_cgroup_page_lruvec(page, pgdat);
5201 if (page_evictable(page) && PageUnevictable(page)) {
5202 enum lru_list lru = page_lru_base_type(page);
5204 VM_BUG_ON_PAGE(PageActive(page), page);
5205 ClearPageUnevictable(page);
5206 del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
5207 add_page_to_lru_list(page, lruvec, lru);
5214 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
5215 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
5216 spin_unlock_irq(&pgdat->lru_lock);
5217 } else if (pgscanned) {
5218 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
5221 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);