1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 #include <linux/sched/mm.h>
17 #include <linux/module.h>
18 #include <linux/gfp.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/swap.h>
21 #include <linux/pagemap.h>
22 #include <linux/init.h>
23 #include <linux/highmem.h>
24 #include <linux/vmpressure.h>
25 #include <linux/vmstat.h>
26 #include <linux/file.h>
27 #include <linux/writeback.h>
28 #include <linux/blkdev.h>
29 #include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31 #include <linux/mm_inline.h>
32 #include <linux/backing-dev.h>
33 #include <linux/rmap.h>
34 #include <linux/topology.h>
35 #include <linux/cpu.h>
36 #include <linux/cpuset.h>
37 #include <linux/compaction.h>
38 #include <linux/notifier.h>
39 #include <linux/rwsem.h>
40 #include <linux/delay.h>
41 #include <linux/kthread.h>
42 #include <linux/freezer.h>
43 #include <linux/memcontrol.h>
44 #include <linux/delayacct.h>
45 #include <linux/sysctl.h>
46 #include <linux/oom.h>
47 #include <linux/pagevec.h>
48 #include <linux/prefetch.h>
49 #include <linux/printk.h>
50 #include <linux/dax.h>
51 #include <linux/psi.h>
53 #include <asm/tlbflush.h>
54 #include <asm/div64.h>
56 #include <linux/swapops.h>
57 #include <linux/balloon_compaction.h>
61 #define CREATE_TRACE_POINTS
62 #include <trace/events/vmscan.h>
65 /* How many pages shrink_list() should reclaim */
66 unsigned long nr_to_reclaim;
69 * Nodemask of nodes allowed by the caller. If NULL, all nodes
75 * The memory cgroup that hit its limit and as a result is the
76 * primary target of this reclaim invocation.
78 struct mem_cgroup *target_mem_cgroup;
81 * Scan pressure balancing between anon and file LRUs
83 unsigned long anon_cost;
84 unsigned long file_cost;
86 /* Can active pages be deactivated as part of reclaim? */
87 #define DEACTIVATE_ANON 1
88 #define DEACTIVATE_FILE 2
89 unsigned int may_deactivate:2;
90 unsigned int force_deactivate:1;
91 unsigned int skipped_deactivate:1;
93 /* Writepage batching in laptop mode; RECLAIM_WRITE */
94 unsigned int may_writepage:1;
96 /* Can mapped pages be reclaimed? */
97 unsigned int may_unmap:1;
99 /* Can pages be swapped as part of reclaim? */
100 unsigned int may_swap:1;
103 * Cgroups are not reclaimed below their configured memory.low,
104 * unless we threaten to OOM. If any cgroups are skipped due to
105 * memory.low and nothing was reclaimed, go back for memory.low.
107 unsigned int memcg_low_reclaim:1;
108 unsigned int memcg_low_skipped:1;
110 unsigned int hibernation_mode:1;
112 /* One of the zones is ready for compaction */
113 unsigned int compaction_ready:1;
115 /* There is easily reclaimable cold cache in the current node */
116 unsigned int cache_trim_mode:1;
118 /* The file pages on the current node are dangerously low */
119 unsigned int file_is_tiny:1;
121 /* Allocation order */
124 /* Scan (total_size >> priority) pages at once */
127 /* The highest zone to isolate pages for reclaim from */
130 /* This context's GFP mask */
133 /* Incremented by the number of inactive pages that were scanned */
134 unsigned long nr_scanned;
136 /* Number of pages freed so far during a call to shrink_zones() */
137 unsigned long nr_reclaimed;
141 unsigned int unqueued_dirty;
142 unsigned int congested;
143 unsigned int writeback;
144 unsigned int immediate;
145 unsigned int file_taken;
149 /* for recording the reclaimed slab by now */
150 struct reclaim_state reclaim_state;
153 #ifdef ARCH_HAS_PREFETCHW
154 #define prefetchw_prev_lru_page(_page, _base, _field) \
156 if ((_page)->lru.prev != _base) { \
159 prev = lru_to_page(&(_page->lru)); \
160 prefetchw(&prev->_field); \
164 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
168 * From 0 .. 200. Higher means more swappy.
170 int vm_swappiness = 60;
172 static void set_task_reclaim_state(struct task_struct *task,
173 struct reclaim_state *rs)
175 /* Check for an overwrite */
176 WARN_ON_ONCE(rs && task->reclaim_state);
178 /* Check for the nulling of an already-nulled member */
179 WARN_ON_ONCE(!rs && !task->reclaim_state);
181 task->reclaim_state = rs;
184 static LIST_HEAD(shrinker_list);
185 static DECLARE_RWSEM(shrinker_rwsem);
189 static int memcg_shrinker_map_size;
191 static void free_shrinker_map_rcu(struct rcu_head *head)
193 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
196 static int expand_one_shrinker_map(struct mem_cgroup *memcg,
197 int size, int old_size)
199 struct memcg_shrinker_map *new, *old;
200 struct mem_cgroup_per_node *pn;
204 pn = memcg->nodeinfo[nid];
205 old = rcu_dereference_protected(pn->shrinker_map, true);
206 /* Not yet online memcg */
210 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
214 /* Set all old bits, clear all new bits */
215 memset(new->map, (int)0xff, old_size);
216 memset((void *)new->map + old_size, 0, size - old_size);
218 rcu_assign_pointer(pn->shrinker_map, new);
219 call_rcu(&old->rcu, free_shrinker_map_rcu);
225 void free_shrinker_maps(struct mem_cgroup *memcg)
227 struct mem_cgroup_per_node *pn;
228 struct memcg_shrinker_map *map;
231 if (mem_cgroup_is_root(memcg))
235 pn = memcg->nodeinfo[nid];
236 map = rcu_dereference_protected(pn->shrinker_map, true);
238 rcu_assign_pointer(pn->shrinker_map, NULL);
242 int alloc_shrinker_maps(struct mem_cgroup *memcg)
244 struct memcg_shrinker_map *map;
245 int nid, size, ret = 0;
247 if (mem_cgroup_is_root(memcg))
250 down_write(&shrinker_rwsem);
251 size = memcg_shrinker_map_size;
253 map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
255 free_shrinker_maps(memcg);
259 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
261 up_write(&shrinker_rwsem);
266 static int expand_shrinker_maps(int new_id)
268 int size, old_size, ret = 0;
269 struct mem_cgroup *memcg;
271 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
272 old_size = memcg_shrinker_map_size;
273 if (size <= old_size)
276 if (!root_mem_cgroup)
279 lockdep_assert_held(&shrinker_rwsem);
281 memcg = mem_cgroup_iter(NULL, NULL, NULL);
283 if (mem_cgroup_is_root(memcg))
285 ret = expand_one_shrinker_map(memcg, size, old_size);
287 mem_cgroup_iter_break(NULL, memcg);
290 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
293 memcg_shrinker_map_size = size;
298 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
300 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
301 struct memcg_shrinker_map *map;
304 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
305 /* Pairs with smp mb in shrink_slab() */
306 smp_mb__before_atomic();
307 set_bit(shrinker_id, map->map);
313 * We allow subsystems to populate their shrinker-related
314 * LRU lists before register_shrinker_prepared() is called
315 * for the shrinker, since we don't want to impose
316 * restrictions on their internal registration order.
317 * In this case shrink_slab_memcg() may find corresponding
318 * bit is set in the shrinkers map.
320 * This value is used by the function to detect registering
321 * shrinkers and to skip do_shrink_slab() calls for them.
323 #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
325 static DEFINE_IDR(shrinker_idr);
326 static int shrinker_nr_max;
328 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
330 int id, ret = -ENOMEM;
332 down_write(&shrinker_rwsem);
333 /* This may call shrinker, so it must use down_read_trylock() */
334 id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
338 if (id >= shrinker_nr_max) {
339 if (expand_shrinker_maps(id)) {
340 idr_remove(&shrinker_idr, id);
344 shrinker_nr_max = id + 1;
349 up_write(&shrinker_rwsem);
353 static void unregister_memcg_shrinker(struct shrinker *shrinker)
355 int id = shrinker->id;
359 down_write(&shrinker_rwsem);
360 idr_remove(&shrinker_idr, id);
361 up_write(&shrinker_rwsem);
364 static bool cgroup_reclaim(struct scan_control *sc)
366 return sc->target_mem_cgroup;
370 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
371 * @sc: scan_control in question
373 * The normal page dirty throttling mechanism in balance_dirty_pages() is
374 * completely broken with the legacy memcg and direct stalling in
375 * shrink_page_list() is used for throttling instead, which lacks all the
376 * niceties such as fairness, adaptive pausing, bandwidth proportional
377 * allocation and configurability.
379 * This function tests whether the vmscan currently in progress can assume
380 * that the normal dirty throttling mechanism is operational.
382 static bool writeback_throttling_sane(struct scan_control *sc)
384 if (!cgroup_reclaim(sc))
386 #ifdef CONFIG_CGROUP_WRITEBACK
387 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
393 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
398 static void unregister_memcg_shrinker(struct shrinker *shrinker)
402 static bool cgroup_reclaim(struct scan_control *sc)
407 static bool writeback_throttling_sane(struct scan_control *sc)
414 * This misses isolated pages which are not accounted for to save counters.
415 * As the data only determines if reclaim or compaction continues, it is
416 * not expected that isolated pages will be a dominating factor.
418 unsigned long zone_reclaimable_pages(struct zone *zone)
422 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
423 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
424 if (get_nr_swap_pages() > 0)
425 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
426 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
432 * lruvec_lru_size - Returns the number of pages on the given LRU list.
433 * @lruvec: lru vector
435 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
437 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
440 unsigned long size = 0;
443 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
444 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
446 if (!managed_zone(zone))
449 if (!mem_cgroup_disabled())
450 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
452 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
458 * Add a shrinker callback to be called from the vm.
460 int prealloc_shrinker(struct shrinker *shrinker)
462 unsigned int size = sizeof(*shrinker->nr_deferred);
464 if (shrinker->flags & SHRINKER_NUMA_AWARE)
467 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
468 if (!shrinker->nr_deferred)
471 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
472 if (prealloc_memcg_shrinker(shrinker))
479 kfree(shrinker->nr_deferred);
480 shrinker->nr_deferred = NULL;
484 void free_prealloced_shrinker(struct shrinker *shrinker)
486 if (!shrinker->nr_deferred)
489 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
490 unregister_memcg_shrinker(shrinker);
492 kfree(shrinker->nr_deferred);
493 shrinker->nr_deferred = NULL;
496 void register_shrinker_prepared(struct shrinker *shrinker)
498 down_write(&shrinker_rwsem);
499 list_add_tail(&shrinker->list, &shrinker_list);
501 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
502 idr_replace(&shrinker_idr, shrinker, shrinker->id);
504 up_write(&shrinker_rwsem);
507 int register_shrinker(struct shrinker *shrinker)
509 int err = prealloc_shrinker(shrinker);
513 register_shrinker_prepared(shrinker);
516 EXPORT_SYMBOL(register_shrinker);
521 void unregister_shrinker(struct shrinker *shrinker)
523 if (!shrinker->nr_deferred)
525 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
526 unregister_memcg_shrinker(shrinker);
527 down_write(&shrinker_rwsem);
528 list_del(&shrinker->list);
529 up_write(&shrinker_rwsem);
530 kfree(shrinker->nr_deferred);
531 shrinker->nr_deferred = NULL;
533 EXPORT_SYMBOL(unregister_shrinker);
535 #define SHRINK_BATCH 128
537 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
538 struct shrinker *shrinker, int priority)
540 unsigned long freed = 0;
541 unsigned long long delta;
546 int nid = shrinkctl->nid;
547 long batch_size = shrinker->batch ? shrinker->batch
549 long scanned = 0, next_deferred;
551 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
554 freeable = shrinker->count_objects(shrinker, shrinkctl);
555 if (freeable == 0 || freeable == SHRINK_EMPTY)
559 * copy the current shrinker scan count into a local variable
560 * and zero it so that other concurrent shrinker invocations
561 * don't also do this scanning work.
563 nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
566 if (shrinker->seeks) {
567 delta = freeable >> priority;
569 do_div(delta, shrinker->seeks);
572 * These objects don't require any IO to create. Trim
573 * them aggressively under memory pressure to keep
574 * them from causing refetches in the IO caches.
576 delta = freeable / 2;
580 if (total_scan < 0) {
581 pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
582 shrinker->scan_objects, total_scan);
583 total_scan = freeable;
586 next_deferred = total_scan;
589 * We need to avoid excessive windup on filesystem shrinkers
590 * due to large numbers of GFP_NOFS allocations causing the
591 * shrinkers to return -1 all the time. This results in a large
592 * nr being built up so when a shrink that can do some work
593 * comes along it empties the entire cache due to nr >>>
594 * freeable. This is bad for sustaining a working set in
597 * Hence only allow the shrinker to scan the entire cache when
598 * a large delta change is calculated directly.
600 if (delta < freeable / 4)
601 total_scan = min(total_scan, freeable / 2);
604 * Avoid risking looping forever due to too large nr value:
605 * never try to free more than twice the estimate number of
608 if (total_scan > freeable * 2)
609 total_scan = freeable * 2;
611 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
612 freeable, delta, total_scan, priority);
615 * Normally, we should not scan less than batch_size objects in one
616 * pass to avoid too frequent shrinker calls, but if the slab has less
617 * than batch_size objects in total and we are really tight on memory,
618 * we will try to reclaim all available objects, otherwise we can end
619 * up failing allocations although there are plenty of reclaimable
620 * objects spread over several slabs with usage less than the
623 * We detect the "tight on memory" situations by looking at the total
624 * number of objects we want to scan (total_scan). If it is greater
625 * than the total number of objects on slab (freeable), we must be
626 * scanning at high prio and therefore should try to reclaim as much as
629 while (total_scan >= batch_size ||
630 total_scan >= freeable) {
632 unsigned long nr_to_scan = min(batch_size, total_scan);
634 shrinkctl->nr_to_scan = nr_to_scan;
635 shrinkctl->nr_scanned = nr_to_scan;
636 ret = shrinker->scan_objects(shrinker, shrinkctl);
637 if (ret == SHRINK_STOP)
641 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
642 total_scan -= shrinkctl->nr_scanned;
643 scanned += shrinkctl->nr_scanned;
648 if (next_deferred >= scanned)
649 next_deferred -= scanned;
653 * move the unused scan count back into the shrinker in a
654 * manner that handles concurrent updates. If we exhausted the
655 * scan, there is no need to do an update.
657 if (next_deferred > 0)
658 new_nr = atomic_long_add_return(next_deferred,
659 &shrinker->nr_deferred[nid]);
661 new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
663 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
668 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
669 struct mem_cgroup *memcg, int priority)
671 struct memcg_shrinker_map *map;
672 unsigned long ret, freed = 0;
675 if (!mem_cgroup_online(memcg))
678 if (!down_read_trylock(&shrinker_rwsem))
681 map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
686 for_each_set_bit(i, map->map, shrinker_nr_max) {
687 struct shrink_control sc = {
688 .gfp_mask = gfp_mask,
692 struct shrinker *shrinker;
694 shrinker = idr_find(&shrinker_idr, i);
695 if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
697 clear_bit(i, map->map);
701 /* Call non-slab shrinkers even though kmem is disabled */
702 if (!memcg_kmem_enabled() &&
703 !(shrinker->flags & SHRINKER_NONSLAB))
706 ret = do_shrink_slab(&sc, shrinker, priority);
707 if (ret == SHRINK_EMPTY) {
708 clear_bit(i, map->map);
710 * After the shrinker reported that it had no objects to
711 * free, but before we cleared the corresponding bit in
712 * the memcg shrinker map, a new object might have been
713 * added. To make sure, we have the bit set in this
714 * case, we invoke the shrinker one more time and reset
715 * the bit if it reports that it is not empty anymore.
716 * The memory barrier here pairs with the barrier in
717 * set_shrinker_bit():
719 * list_lru_add() shrink_slab_memcg()
720 * list_add_tail() clear_bit()
722 * set_bit() do_shrink_slab()
724 smp_mb__after_atomic();
725 ret = do_shrink_slab(&sc, shrinker, priority);
726 if (ret == SHRINK_EMPTY)
729 set_shrinker_bit(memcg, nid, i);
733 if (rwsem_is_contended(&shrinker_rwsem)) {
739 up_read(&shrinker_rwsem);
742 #else /* CONFIG_MEMCG */
743 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
744 struct mem_cgroup *memcg, int priority)
748 #endif /* CONFIG_MEMCG */
751 * shrink_slab - shrink slab caches
752 * @gfp_mask: allocation context
753 * @nid: node whose slab caches to target
754 * @memcg: memory cgroup whose slab caches to target
755 * @priority: the reclaim priority
757 * Call the shrink functions to age shrinkable caches.
759 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
760 * unaware shrinkers will receive a node id of 0 instead.
762 * @memcg specifies the memory cgroup to target. Unaware shrinkers
763 * are called only if it is the root cgroup.
765 * @priority is sc->priority, we take the number of objects and >> by priority
766 * in order to get the scan target.
768 * Returns the number of reclaimed slab objects.
770 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
771 struct mem_cgroup *memcg,
774 unsigned long ret, freed = 0;
775 struct shrinker *shrinker;
778 * The root memcg might be allocated even though memcg is disabled
779 * via "cgroup_disable=memory" boot parameter. This could make
780 * mem_cgroup_is_root() return false, then just run memcg slab
781 * shrink, but skip global shrink. This may result in premature
784 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
785 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
787 if (!down_read_trylock(&shrinker_rwsem))
790 list_for_each_entry(shrinker, &shrinker_list, list) {
791 struct shrink_control sc = {
792 .gfp_mask = gfp_mask,
797 ret = do_shrink_slab(&sc, shrinker, priority);
798 if (ret == SHRINK_EMPTY)
802 * Bail out if someone want to register a new shrinker to
803 * prevent the registration from being stalled for long periods
804 * by parallel ongoing shrinking.
806 if (rwsem_is_contended(&shrinker_rwsem)) {
812 up_read(&shrinker_rwsem);
818 void drop_slab_node(int nid)
823 struct mem_cgroup *memcg = NULL;
825 if (fatal_signal_pending(current))
829 memcg = mem_cgroup_iter(NULL, NULL, NULL);
831 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
832 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
833 } while (freed > 10);
840 for_each_online_node(nid)
844 static inline int is_page_cache_freeable(struct page *page)
847 * A freeable page cache page is referenced only by the caller
848 * that isolated the page, the page cache and optional buffer
849 * heads at page->private.
851 int page_cache_pins = thp_nr_pages(page);
852 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
855 static int may_write_to_inode(struct inode *inode)
857 if (current->flags & PF_SWAPWRITE)
859 if (!inode_write_congested(inode))
861 if (inode_to_bdi(inode) == current->backing_dev_info)
867 * We detected a synchronous write error writing a page out. Probably
868 * -ENOSPC. We need to propagate that into the address_space for a subsequent
869 * fsync(), msync() or close().
871 * The tricky part is that after writepage we cannot touch the mapping: nothing
872 * prevents it from being freed up. But we have a ref on the page and once
873 * that page is locked, the mapping is pinned.
875 * We're allowed to run sleeping lock_page() here because we know the caller has
878 static void handle_write_error(struct address_space *mapping,
879 struct page *page, int error)
882 if (page_mapping(page) == mapping)
883 mapping_set_error(mapping, error);
887 /* possible outcome of pageout() */
889 /* failed to write page out, page is locked */
891 /* move page to the active list, page is locked */
893 /* page has been sent to the disk successfully, page is unlocked */
895 /* page is clean and locked */
900 * pageout is called by shrink_page_list() for each dirty page.
901 * Calls ->writepage().
903 static pageout_t pageout(struct page *page, struct address_space *mapping)
906 * If the page is dirty, only perform writeback if that write
907 * will be non-blocking. To prevent this allocation from being
908 * stalled by pagecache activity. But note that there may be
909 * stalls if we need to run get_block(). We could test
910 * PagePrivate for that.
912 * If this process is currently in __generic_file_write_iter() against
913 * this page's queue, we can perform writeback even if that
916 * If the page is swapcache, write it back even if that would
917 * block, for some throttling. This happens by accident, because
918 * swap_backing_dev_info is bust: it doesn't reflect the
919 * congestion state of the swapdevs. Easy to fix, if needed.
921 if (!is_page_cache_freeable(page))
925 * Some data journaling orphaned pages can have
926 * page->mapping == NULL while being dirty with clean buffers.
928 if (page_has_private(page)) {
929 if (try_to_free_buffers(page)) {
930 ClearPageDirty(page);
931 pr_info("%s: orphaned page\n", __func__);
937 if (mapping->a_ops->writepage == NULL)
938 return PAGE_ACTIVATE;
939 if (!may_write_to_inode(mapping->host))
942 if (clear_page_dirty_for_io(page)) {
944 struct writeback_control wbc = {
945 .sync_mode = WB_SYNC_NONE,
946 .nr_to_write = SWAP_CLUSTER_MAX,
948 .range_end = LLONG_MAX,
952 SetPageReclaim(page);
953 res = mapping->a_ops->writepage(page, &wbc);
955 handle_write_error(mapping, page, res);
956 if (res == AOP_WRITEPAGE_ACTIVATE) {
957 ClearPageReclaim(page);
958 return PAGE_ACTIVATE;
961 if (!PageWriteback(page)) {
962 /* synchronous write or broken a_ops? */
963 ClearPageReclaim(page);
965 trace_mm_vmscan_writepage(page);
966 inc_node_page_state(page, NR_VMSCAN_WRITE);
974 * Same as remove_mapping, but if the page is removed from the mapping, it
975 * gets returned with a refcount of 0.
977 static int __remove_mapping(struct address_space *mapping, struct page *page,
978 bool reclaimed, struct mem_cgroup *target_memcg)
984 BUG_ON(!PageLocked(page));
985 BUG_ON(mapping != page_mapping(page));
987 xa_lock_irqsave(&mapping->i_pages, flags);
989 * The non racy check for a busy page.
991 * Must be careful with the order of the tests. When someone has
992 * a ref to the page, it may be possible that they dirty it then
993 * drop the reference. So if PageDirty is tested before page_count
994 * here, then the following race may occur:
996 * get_user_pages(&page);
997 * [user mapping goes away]
999 * !PageDirty(page) [good]
1000 * SetPageDirty(page);
1002 * !page_count(page) [good, discard it]
1004 * [oops, our write_to data is lost]
1006 * Reversing the order of the tests ensures such a situation cannot
1007 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
1008 * load is not satisfied before that of page->_refcount.
1010 * Note that if SetPageDirty is always performed via set_page_dirty,
1011 * and thus under the i_pages lock, then this ordering is not required.
1013 refcount = 1 + compound_nr(page);
1014 if (!page_ref_freeze(page, refcount))
1016 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1017 if (unlikely(PageDirty(page))) {
1018 page_ref_unfreeze(page, refcount);
1022 if (PageSwapCache(page)) {
1023 swp_entry_t swap = { .val = page_private(page) };
1024 mem_cgroup_swapout(page, swap);
1025 if (reclaimed && !mapping_exiting(mapping))
1026 shadow = workingset_eviction(page, target_memcg);
1027 __delete_from_swap_cache(page, swap, shadow);
1028 xa_unlock_irqrestore(&mapping->i_pages, flags);
1029 put_swap_page(page, swap);
1031 void (*freepage)(struct page *);
1033 freepage = mapping->a_ops->freepage;
1035 * Remember a shadow entry for reclaimed file cache in
1036 * order to detect refaults, thus thrashing, later on.
1038 * But don't store shadows in an address space that is
1039 * already exiting. This is not just an optimization,
1040 * inode reclaim needs to empty out the radix tree or
1041 * the nodes are lost. Don't plant shadows behind its
1044 * We also don't store shadows for DAX mappings because the
1045 * only page cache pages found in these are zero pages
1046 * covering holes, and because we don't want to mix DAX
1047 * exceptional entries and shadow exceptional entries in the
1048 * same address_space.
1050 if (reclaimed && page_is_file_lru(page) &&
1051 !mapping_exiting(mapping) && !dax_mapping(mapping))
1052 shadow = workingset_eviction(page, target_memcg);
1053 __delete_from_page_cache(page, shadow);
1054 xa_unlock_irqrestore(&mapping->i_pages, flags);
1056 if (freepage != NULL)
1063 xa_unlock_irqrestore(&mapping->i_pages, flags);
1068 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1069 * someone else has a ref on the page, abort and return 0. If it was
1070 * successfully detached, return 1. Assumes the caller has a single ref on
1073 int remove_mapping(struct address_space *mapping, struct page *page)
1075 if (__remove_mapping(mapping, page, false, NULL)) {
1077 * Unfreezing the refcount with 1 rather than 2 effectively
1078 * drops the pagecache ref for us without requiring another
1081 page_ref_unfreeze(page, 1);
1088 * putback_lru_page - put previously isolated page onto appropriate LRU list
1089 * @page: page to be put back to appropriate lru list
1091 * Add previously isolated @page to appropriate LRU list.
1092 * Page may still be unevictable for other reasons.
1094 * lru_lock must not be held, interrupts must be enabled.
1096 void putback_lru_page(struct page *page)
1098 lru_cache_add(page);
1099 put_page(page); /* drop ref from isolate */
1102 enum page_references {
1104 PAGEREF_RECLAIM_CLEAN,
1109 static enum page_references page_check_references(struct page *page,
1110 struct scan_control *sc)
1112 int referenced_ptes, referenced_page;
1113 unsigned long vm_flags;
1115 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1117 referenced_page = TestClearPageReferenced(page);
1120 * Mlock lost the isolation race with us. Let try_to_unmap()
1121 * move the page to the unevictable list.
1123 if (vm_flags & VM_LOCKED)
1124 return PAGEREF_RECLAIM;
1126 if (referenced_ptes) {
1128 * All mapped pages start out with page table
1129 * references from the instantiating fault, so we need
1130 * to look twice if a mapped file page is used more
1133 * Mark it and spare it for another trip around the
1134 * inactive list. Another page table reference will
1135 * lead to its activation.
1137 * Note: the mark is set for activated pages as well
1138 * so that recently deactivated but used pages are
1139 * quickly recovered.
1141 SetPageReferenced(page);
1143 if (referenced_page || referenced_ptes > 1)
1144 return PAGEREF_ACTIVATE;
1147 * Activate file-backed executable pages after first usage.
1149 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1150 return PAGEREF_ACTIVATE;
1152 return PAGEREF_KEEP;
1155 /* Reclaim if clean, defer dirty pages to writeback */
1156 if (referenced_page && !PageSwapBacked(page))
1157 return PAGEREF_RECLAIM_CLEAN;
1159 return PAGEREF_RECLAIM;
1162 /* Check if a page is dirty or under writeback */
1163 static void page_check_dirty_writeback(struct page *page,
1164 bool *dirty, bool *writeback)
1166 struct address_space *mapping;
1169 * Anonymous pages are not handled by flushers and must be written
1170 * from reclaim context. Do not stall reclaim based on them
1172 if (!page_is_file_lru(page) ||
1173 (PageAnon(page) && !PageSwapBacked(page))) {
1179 /* By default assume that the page flags are accurate */
1180 *dirty = PageDirty(page);
1181 *writeback = PageWriteback(page);
1183 /* Verify dirty/writeback state if the filesystem supports it */
1184 if (!page_has_private(page))
1187 mapping = page_mapping(page);
1188 if (mapping && mapping->a_ops->is_dirty_writeback)
1189 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1193 * shrink_page_list() returns the number of reclaimed pages
1195 static unsigned int shrink_page_list(struct list_head *page_list,
1196 struct pglist_data *pgdat,
1197 struct scan_control *sc,
1198 struct reclaim_stat *stat,
1199 bool ignore_references)
1201 LIST_HEAD(ret_pages);
1202 LIST_HEAD(free_pages);
1203 unsigned int nr_reclaimed = 0;
1204 unsigned int pgactivate = 0;
1206 memset(stat, 0, sizeof(*stat));
1209 while (!list_empty(page_list)) {
1210 struct address_space *mapping;
1212 enum page_references references = PAGEREF_RECLAIM;
1213 bool dirty, writeback, may_enter_fs;
1214 unsigned int nr_pages;
1218 page = lru_to_page(page_list);
1219 list_del(&page->lru);
1221 if (!trylock_page(page))
1224 VM_BUG_ON_PAGE(PageActive(page), page);
1226 nr_pages = compound_nr(page);
1228 /* Account the number of base pages even though THP */
1229 sc->nr_scanned += nr_pages;
1231 if (unlikely(!page_evictable(page)))
1232 goto activate_locked;
1234 if (!sc->may_unmap && page_mapped(page))
1237 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1238 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1241 * The number of dirty pages determines if a node is marked
1242 * reclaim_congested which affects wait_iff_congested. kswapd
1243 * will stall and start writing pages if the tail of the LRU
1244 * is all dirty unqueued pages.
1246 page_check_dirty_writeback(page, &dirty, &writeback);
1247 if (dirty || writeback)
1250 if (dirty && !writeback)
1251 stat->nr_unqueued_dirty++;
1254 * Treat this page as congested if the underlying BDI is or if
1255 * pages are cycling through the LRU so quickly that the
1256 * pages marked for immediate reclaim are making it to the
1257 * end of the LRU a second time.
1259 mapping = page_mapping(page);
1260 if (((dirty || writeback) && mapping &&
1261 inode_write_congested(mapping->host)) ||
1262 (writeback && PageReclaim(page)))
1263 stat->nr_congested++;
1266 * If a page at the tail of the LRU is under writeback, there
1267 * are three cases to consider.
1269 * 1) If reclaim is encountering an excessive number of pages
1270 * under writeback and this page is both under writeback and
1271 * PageReclaim then it indicates that pages are being queued
1272 * for IO but are being recycled through the LRU before the
1273 * IO can complete. Waiting on the page itself risks an
1274 * indefinite stall if it is impossible to writeback the
1275 * page due to IO error or disconnected storage so instead
1276 * note that the LRU is being scanned too quickly and the
1277 * caller can stall after page list has been processed.
1279 * 2) Global or new memcg reclaim encounters a page that is
1280 * not marked for immediate reclaim, or the caller does not
1281 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1282 * not to fs). In this case mark the page for immediate
1283 * reclaim and continue scanning.
1285 * Require may_enter_fs because we would wait on fs, which
1286 * may not have submitted IO yet. And the loop driver might
1287 * enter reclaim, and deadlock if it waits on a page for
1288 * which it is needed to do the write (loop masks off
1289 * __GFP_IO|__GFP_FS for this reason); but more thought
1290 * would probably show more reasons.
1292 * 3) Legacy memcg encounters a page that is already marked
1293 * PageReclaim. memcg does not have any dirty pages
1294 * throttling so we could easily OOM just because too many
1295 * pages are in writeback and there is nothing else to
1296 * reclaim. Wait for the writeback to complete.
1298 * In cases 1) and 2) we activate the pages to get them out of
1299 * the way while we continue scanning for clean pages on the
1300 * inactive list and refilling from the active list. The
1301 * observation here is that waiting for disk writes is more
1302 * expensive than potentially causing reloads down the line.
1303 * Since they're marked for immediate reclaim, they won't put
1304 * memory pressure on the cache working set any longer than it
1305 * takes to write them to disk.
1307 if (PageWriteback(page)) {
1309 if (current_is_kswapd() &&
1310 PageReclaim(page) &&
1311 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1312 stat->nr_immediate++;
1313 goto activate_locked;
1316 } else if (writeback_throttling_sane(sc) ||
1317 !PageReclaim(page) || !may_enter_fs) {
1319 * This is slightly racy - end_page_writeback()
1320 * might have just cleared PageReclaim, then
1321 * setting PageReclaim here end up interpreted
1322 * as PageReadahead - but that does not matter
1323 * enough to care. What we do want is for this
1324 * page to have PageReclaim set next time memcg
1325 * reclaim reaches the tests above, so it will
1326 * then wait_on_page_writeback() to avoid OOM;
1327 * and it's also appropriate in global reclaim.
1329 SetPageReclaim(page);
1330 stat->nr_writeback++;
1331 goto activate_locked;
1336 wait_on_page_writeback(page);
1337 /* then go back and try same page again */
1338 list_add_tail(&page->lru, page_list);
1343 if (!ignore_references)
1344 references = page_check_references(page, sc);
1346 switch (references) {
1347 case PAGEREF_ACTIVATE:
1348 goto activate_locked;
1350 stat->nr_ref_keep += nr_pages;
1352 case PAGEREF_RECLAIM:
1353 case PAGEREF_RECLAIM_CLEAN:
1354 ; /* try to reclaim the page below */
1358 * Anonymous process memory has backing store?
1359 * Try to allocate it some swap space here.
1360 * Lazyfree page could be freed directly
1362 if (PageAnon(page) && PageSwapBacked(page)) {
1363 if (!PageSwapCache(page)) {
1364 if (!(sc->gfp_mask & __GFP_IO))
1366 if (page_maybe_dma_pinned(page))
1368 if (PageTransHuge(page)) {
1369 /* cannot split THP, skip it */
1370 if (!can_split_huge_page(page, NULL))
1371 goto activate_locked;
1373 * Split pages without a PMD map right
1374 * away. Chances are some or all of the
1375 * tail pages can be freed without IO.
1377 if (!compound_mapcount(page) &&
1378 split_huge_page_to_list(page,
1380 goto activate_locked;
1382 if (!add_to_swap(page)) {
1383 if (!PageTransHuge(page))
1384 goto activate_locked_split;
1385 /* Fallback to swap normal pages */
1386 if (split_huge_page_to_list(page,
1388 goto activate_locked;
1389 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1390 count_vm_event(THP_SWPOUT_FALLBACK);
1392 if (!add_to_swap(page))
1393 goto activate_locked_split;
1396 may_enter_fs = true;
1398 /* Adding to swap updated mapping */
1399 mapping = page_mapping(page);
1401 } else if (unlikely(PageTransHuge(page))) {
1402 /* Split file THP */
1403 if (split_huge_page_to_list(page, page_list))
1408 * THP may get split above, need minus tail pages and update
1409 * nr_pages to avoid accounting tail pages twice.
1411 * The tail pages that are added into swap cache successfully
1414 if ((nr_pages > 1) && !PageTransHuge(page)) {
1415 sc->nr_scanned -= (nr_pages - 1);
1420 * The page is mapped into the page tables of one or more
1421 * processes. Try to unmap it here.
1423 if (page_mapped(page)) {
1424 enum ttu_flags flags = TTU_BATCH_FLUSH;
1425 bool was_swapbacked = PageSwapBacked(page);
1427 if (unlikely(PageTransHuge(page)))
1428 flags |= TTU_SPLIT_HUGE_PMD;
1430 if (!try_to_unmap(page, flags)) {
1431 stat->nr_unmap_fail += nr_pages;
1432 if (!was_swapbacked && PageSwapBacked(page))
1433 stat->nr_lazyfree_fail += nr_pages;
1434 goto activate_locked;
1438 if (PageDirty(page)) {
1440 * Only kswapd can writeback filesystem pages
1441 * to avoid risk of stack overflow. But avoid
1442 * injecting inefficient single-page IO into
1443 * flusher writeback as much as possible: only
1444 * write pages when we've encountered many
1445 * dirty pages, and when we've already scanned
1446 * the rest of the LRU for clean pages and see
1447 * the same dirty pages again (PageReclaim).
1449 if (page_is_file_lru(page) &&
1450 (!current_is_kswapd() || !PageReclaim(page) ||
1451 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1453 * Immediately reclaim when written back.
1454 * Similar in principal to deactivate_page()
1455 * except we already have the page isolated
1456 * and know it's dirty
1458 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
1459 SetPageReclaim(page);
1461 goto activate_locked;
1464 if (references == PAGEREF_RECLAIM_CLEAN)
1468 if (!sc->may_writepage)
1472 * Page is dirty. Flush the TLB if a writable entry
1473 * potentially exists to avoid CPU writes after IO
1474 * starts and then write it out here.
1476 try_to_unmap_flush_dirty();
1477 switch (pageout(page, mapping)) {
1481 goto activate_locked;
1483 stat->nr_pageout += thp_nr_pages(page);
1485 if (PageWriteback(page))
1487 if (PageDirty(page))
1491 * A synchronous write - probably a ramdisk. Go
1492 * ahead and try to reclaim the page.
1494 if (!trylock_page(page))
1496 if (PageDirty(page) || PageWriteback(page))
1498 mapping = page_mapping(page);
1501 ; /* try to free the page below */
1506 * If the page has buffers, try to free the buffer mappings
1507 * associated with this page. If we succeed we try to free
1510 * We do this even if the page is PageDirty().
1511 * try_to_release_page() does not perform I/O, but it is
1512 * possible for a page to have PageDirty set, but it is actually
1513 * clean (all its buffers are clean). This happens if the
1514 * buffers were written out directly, with submit_bh(). ext3
1515 * will do this, as well as the blockdev mapping.
1516 * try_to_release_page() will discover that cleanness and will
1517 * drop the buffers and mark the page clean - it can be freed.
1519 * Rarely, pages can have buffers and no ->mapping. These are
1520 * the pages which were not successfully invalidated in
1521 * truncate_cleanup_page(). We try to drop those buffers here
1522 * and if that worked, and the page is no longer mapped into
1523 * process address space (page_count == 1) it can be freed.
1524 * Otherwise, leave the page on the LRU so it is swappable.
1526 if (page_has_private(page)) {
1527 if (!try_to_release_page(page, sc->gfp_mask))
1528 goto activate_locked;
1529 if (!mapping && page_count(page) == 1) {
1531 if (put_page_testzero(page))
1535 * rare race with speculative reference.
1536 * the speculative reference will free
1537 * this page shortly, so we may
1538 * increment nr_reclaimed here (and
1539 * leave it off the LRU).
1547 if (PageAnon(page) && !PageSwapBacked(page)) {
1548 /* follow __remove_mapping for reference */
1549 if (!page_ref_freeze(page, 1))
1551 if (PageDirty(page)) {
1552 page_ref_unfreeze(page, 1);
1556 count_vm_event(PGLAZYFREED);
1557 count_memcg_page_event(page, PGLAZYFREED);
1558 } else if (!mapping || !__remove_mapping(mapping, page, true,
1559 sc->target_mem_cgroup))
1565 * THP may get swapped out in a whole, need account
1568 nr_reclaimed += nr_pages;
1571 * Is there need to periodically free_page_list? It would
1572 * appear not as the counts should be low
1574 if (unlikely(PageTransHuge(page)))
1575 destroy_compound_page(page);
1577 list_add(&page->lru, &free_pages);
1580 activate_locked_split:
1582 * The tail pages that are failed to add into swap cache
1583 * reach here. Fixup nr_scanned and nr_pages.
1586 sc->nr_scanned -= (nr_pages - 1);
1590 /* Not a candidate for swapping, so reclaim swap space. */
1591 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1593 try_to_free_swap(page);
1594 VM_BUG_ON_PAGE(PageActive(page), page);
1595 if (!PageMlocked(page)) {
1596 int type = page_is_file_lru(page);
1597 SetPageActive(page);
1598 stat->nr_activate[type] += nr_pages;
1599 count_memcg_page_event(page, PGACTIVATE);
1604 list_add(&page->lru, &ret_pages);
1605 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
1608 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1610 mem_cgroup_uncharge_list(&free_pages);
1611 try_to_unmap_flush();
1612 free_unref_page_list(&free_pages);
1614 list_splice(&ret_pages, page_list);
1615 count_vm_events(PGACTIVATE, pgactivate);
1617 return nr_reclaimed;
1620 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1621 struct list_head *page_list)
1623 struct scan_control sc = {
1624 .gfp_mask = GFP_KERNEL,
1625 .priority = DEF_PRIORITY,
1628 struct reclaim_stat stat;
1629 unsigned int nr_reclaimed;
1630 struct page *page, *next;
1631 LIST_HEAD(clean_pages);
1633 list_for_each_entry_safe(page, next, page_list, lru) {
1634 if (!PageHuge(page) && page_is_file_lru(page) &&
1635 !PageDirty(page) && !__PageMovable(page) &&
1636 !PageUnevictable(page)) {
1637 ClearPageActive(page);
1638 list_move(&page->lru, &clean_pages);
1642 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1644 list_splice(&clean_pages, page_list);
1645 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1646 -(long)nr_reclaimed);
1648 * Since lazyfree pages are isolated from file LRU from the beginning,
1649 * they will rotate back to anonymous LRU in the end if it failed to
1650 * discard so isolated count will be mismatched.
1651 * Compensate the isolated count for both LRU lists.
1653 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1654 stat.nr_lazyfree_fail);
1655 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1656 -(long)stat.nr_lazyfree_fail);
1657 return nr_reclaimed;
1661 * Attempt to remove the specified page from its LRU. Only take this page
1662 * if it is of the appropriate PageActive status. Pages which are being
1663 * freed elsewhere are also ignored.
1665 * page: page to consider
1666 * mode: one of the LRU isolation modes defined above
1668 * returns true on success, false on failure.
1670 bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
1672 /* Only take pages on the LRU. */
1676 /* Compaction should not handle unevictable pages but CMA can do so */
1677 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1681 * To minimise LRU disruption, the caller can indicate that it only
1682 * wants to isolate pages it will be able to operate on without
1683 * blocking - clean pages for the most part.
1685 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1686 * that it is possible to migrate without blocking
1688 if (mode & ISOLATE_ASYNC_MIGRATE) {
1689 /* All the caller can do on PageWriteback is block */
1690 if (PageWriteback(page))
1693 if (PageDirty(page)) {
1694 struct address_space *mapping;
1698 * Only pages without mappings or that have a
1699 * ->migratepage callback are possible to migrate
1700 * without blocking. However, we can be racing with
1701 * truncation so it's necessary to lock the page
1702 * to stabilise the mapping as truncation holds
1703 * the page lock until after the page is removed
1704 * from the page cache.
1706 if (!trylock_page(page))
1709 mapping = page_mapping(page);
1710 migrate_dirty = !mapping || mapping->a_ops->migratepage;
1717 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1724 * Update LRU sizes after isolating pages. The LRU size updates must
1725 * be complete before mem_cgroup_update_lru_size due to a sanity check.
1727 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1728 enum lru_list lru, unsigned long *nr_zone_taken)
1732 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1733 if (!nr_zone_taken[zid])
1736 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1742 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1744 * lruvec->lru_lock is heavily contended. Some of the functions that
1745 * shrink the lists perform better by taking out a batch of pages
1746 * and working on them outside the LRU lock.
1748 * For pagecache intensive workloads, this function is the hottest
1749 * spot in the kernel (apart from copy_*_user functions).
1751 * Lru_lock must be held before calling this function.
1753 * @nr_to_scan: The number of eligible pages to look through on the list.
1754 * @lruvec: The LRU vector to pull pages from.
1755 * @dst: The temp list to put pages on to.
1756 * @nr_scanned: The number of pages that were scanned.
1757 * @sc: The scan_control struct for this reclaim session
1758 * @lru: LRU list id for isolating
1760 * returns how many pages were moved onto *@dst.
1762 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1763 struct lruvec *lruvec, struct list_head *dst,
1764 unsigned long *nr_scanned, struct scan_control *sc,
1767 struct list_head *src = &lruvec->lists[lru];
1768 unsigned long nr_taken = 0;
1769 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1770 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1771 unsigned long skipped = 0;
1772 unsigned long scan, total_scan, nr_pages;
1773 LIST_HEAD(pages_skipped);
1774 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
1778 while (scan < nr_to_scan && !list_empty(src)) {
1781 page = lru_to_page(src);
1782 prefetchw_prev_lru_page(page, src, flags);
1784 nr_pages = compound_nr(page);
1785 total_scan += nr_pages;
1787 if (page_zonenum(page) > sc->reclaim_idx) {
1788 list_move(&page->lru, &pages_skipped);
1789 nr_skipped[page_zonenum(page)] += nr_pages;
1794 * Do not count skipped pages because that makes the function
1795 * return with no isolated pages if the LRU mostly contains
1796 * ineligible pages. This causes the VM to not reclaim any
1797 * pages, triggering a premature OOM.
1799 * Account all tail pages of THP. This would not cause
1800 * premature OOM since __isolate_lru_page() returns -EBUSY
1801 * only when the page is being freed somewhere else.
1804 if (!__isolate_lru_page_prepare(page, mode)) {
1805 /* It is being freed elsewhere */
1806 list_move(&page->lru, src);
1810 * Be careful not to clear PageLRU until after we're
1811 * sure the page is not being freed elsewhere -- the
1812 * page release code relies on it.
1814 if (unlikely(!get_page_unless_zero(page))) {
1815 list_move(&page->lru, src);
1819 if (!TestClearPageLRU(page)) {
1820 /* Another thread is already isolating this page */
1822 list_move(&page->lru, src);
1826 nr_taken += nr_pages;
1827 nr_zone_taken[page_zonenum(page)] += nr_pages;
1828 list_move(&page->lru, dst);
1832 * Splice any skipped pages to the start of the LRU list. Note that
1833 * this disrupts the LRU order when reclaiming for lower zones but
1834 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1835 * scanning would soon rescan the same pages to skip and put the
1836 * system at risk of premature OOM.
1838 if (!list_empty(&pages_skipped)) {
1841 list_splice(&pages_skipped, src);
1842 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1843 if (!nr_skipped[zid])
1846 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1847 skipped += nr_skipped[zid];
1850 *nr_scanned = total_scan;
1851 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1852 total_scan, skipped, nr_taken, mode, lru);
1853 update_lru_sizes(lruvec, lru, nr_zone_taken);
1858 * isolate_lru_page - tries to isolate a page from its LRU list
1859 * @page: page to isolate from its LRU list
1861 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1862 * vmstat statistic corresponding to whatever LRU list the page was on.
1864 * Returns 0 if the page was removed from an LRU list.
1865 * Returns -EBUSY if the page was not on an LRU list.
1867 * The returned page will have PageLRU() cleared. If it was found on
1868 * the active list, it will have PageActive set. If it was found on
1869 * the unevictable list, it will have the PageUnevictable bit set. That flag
1870 * may need to be cleared by the caller before letting the page go.
1872 * The vmstat statistic corresponding to the list on which the page was
1873 * found will be decremented.
1877 * (1) Must be called with an elevated refcount on the page. This is a
1878 * fundamental difference from isolate_lru_pages (which is called
1879 * without a stable reference).
1880 * (2) the lru_lock must not be held.
1881 * (3) interrupts must be enabled.
1883 int isolate_lru_page(struct page *page)
1887 VM_BUG_ON_PAGE(!page_count(page), page);
1888 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
1890 if (TestClearPageLRU(page)) {
1891 struct lruvec *lruvec;
1894 lruvec = lock_page_lruvec_irq(page);
1895 del_page_from_lru_list(page, lruvec);
1896 unlock_page_lruvec_irq(lruvec);
1904 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1905 * then get rescheduled. When there are massive number of tasks doing page
1906 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1907 * the LRU list will go small and be scanned faster than necessary, leading to
1908 * unnecessary swapping, thrashing and OOM.
1910 static int too_many_isolated(struct pglist_data *pgdat, int file,
1911 struct scan_control *sc)
1913 unsigned long inactive, isolated;
1915 if (current_is_kswapd())
1918 if (!writeback_throttling_sane(sc))
1922 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1923 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1925 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1926 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
1930 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1931 * won't get blocked by normal direct-reclaimers, forming a circular
1934 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
1937 return isolated > inactive;
1941 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
1942 * On return, @list is reused as a list of pages to be freed by the caller.
1944 * Returns the number of pages moved to the given lruvec.
1946 static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1947 struct list_head *list)
1949 int nr_pages, nr_moved = 0;
1950 LIST_HEAD(pages_to_free);
1953 while (!list_empty(list)) {
1954 page = lru_to_page(list);
1955 VM_BUG_ON_PAGE(PageLRU(page), page);
1956 list_del(&page->lru);
1957 if (unlikely(!page_evictable(page))) {
1958 spin_unlock_irq(&lruvec->lru_lock);
1959 putback_lru_page(page);
1960 spin_lock_irq(&lruvec->lru_lock);
1965 * The SetPageLRU needs to be kept here for list integrity.
1967 * #0 move_pages_to_lru #1 release_pages
1968 * if !put_page_testzero
1969 * if (put_page_testzero())
1970 * !PageLRU //skip lru_lock
1972 * list_add(&page->lru,)
1973 * list_add(&page->lru,)
1977 if (unlikely(put_page_testzero(page))) {
1978 __clear_page_lru_flags(page);
1980 if (unlikely(PageCompound(page))) {
1981 spin_unlock_irq(&lruvec->lru_lock);
1982 destroy_compound_page(page);
1983 spin_lock_irq(&lruvec->lru_lock);
1985 list_add(&page->lru, &pages_to_free);
1991 * All pages were isolated from the same lruvec (and isolation
1992 * inhibits memcg migration).
1994 VM_BUG_ON_PAGE(!lruvec_holds_page_lru_lock(page, lruvec), page);
1995 add_page_to_lru_list(page, lruvec);
1996 nr_pages = thp_nr_pages(page);
1997 nr_moved += nr_pages;
1998 if (PageActive(page))
1999 workingset_age_nonresident(lruvec, nr_pages);
2003 * To save our caller's stack, now use input list for pages to free.
2005 list_splice(&pages_to_free, list);
2011 * If a kernel thread (such as nfsd for loop-back mounts) services
2012 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2013 * In that case we should only throttle if the backing device it is
2014 * writing to is congested. In other cases it is safe to throttle.
2016 static int current_may_throttle(void)
2018 return !(current->flags & PF_LOCAL_THROTTLE) ||
2019 current->backing_dev_info == NULL ||
2020 bdi_write_congested(current->backing_dev_info);
2024 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2025 * of reclaimed pages
2027 static noinline_for_stack unsigned long
2028 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
2029 struct scan_control *sc, enum lru_list lru)
2031 LIST_HEAD(page_list);
2032 unsigned long nr_scanned;
2033 unsigned int nr_reclaimed = 0;
2034 unsigned long nr_taken;
2035 struct reclaim_stat stat;
2036 bool file = is_file_lru(lru);
2037 enum vm_event_item item;
2038 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2039 bool stalled = false;
2041 while (unlikely(too_many_isolated(pgdat, file, sc))) {
2045 /* wait a bit for the reclaimer. */
2049 /* We are about to die and free our memory. Return now. */
2050 if (fatal_signal_pending(current))
2051 return SWAP_CLUSTER_MAX;
2056 spin_lock_irq(&lruvec->lru_lock);
2058 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2059 &nr_scanned, sc, lru);
2061 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2062 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2063 if (!cgroup_reclaim(sc))
2064 __count_vm_events(item, nr_scanned);
2065 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2066 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2068 spin_unlock_irq(&lruvec->lru_lock);
2073 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2075 spin_lock_irq(&lruvec->lru_lock);
2076 move_pages_to_lru(lruvec, &page_list);
2078 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2079 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2080 if (!cgroup_reclaim(sc))
2081 __count_vm_events(item, nr_reclaimed);
2082 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2083 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2084 spin_unlock_irq(&lruvec->lru_lock);
2086 lru_note_cost(lruvec, file, stat.nr_pageout);
2087 mem_cgroup_uncharge_list(&page_list);
2088 free_unref_page_list(&page_list);
2091 * If dirty pages are scanned that are not queued for IO, it
2092 * implies that flushers are not doing their job. This can
2093 * happen when memory pressure pushes dirty pages to the end of
2094 * the LRU before the dirty limits are breached and the dirty
2095 * data has expired. It can also happen when the proportion of
2096 * dirty pages grows not through writes but through memory
2097 * pressure reclaiming all the clean cache. And in some cases,
2098 * the flushers simply cannot keep up with the allocation
2099 * rate. Nudge the flusher threads in case they are asleep.
2101 if (stat.nr_unqueued_dirty == nr_taken)
2102 wakeup_flusher_threads(WB_REASON_VMSCAN);
2104 sc->nr.dirty += stat.nr_dirty;
2105 sc->nr.congested += stat.nr_congested;
2106 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2107 sc->nr.writeback += stat.nr_writeback;
2108 sc->nr.immediate += stat.nr_immediate;
2109 sc->nr.taken += nr_taken;
2111 sc->nr.file_taken += nr_taken;
2113 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2114 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2115 return nr_reclaimed;
2119 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2121 * We move them the other way if the page is referenced by one or more
2124 * If the pages are mostly unmapped, the processing is fast and it is
2125 * appropriate to hold lru_lock across the whole operation. But if
2126 * the pages are mapped, the processing is slow (page_referenced()), so
2127 * we should drop lru_lock around each page. It's impossible to balance
2128 * this, so instead we remove the pages from the LRU while processing them.
2129 * It is safe to rely on PG_active against the non-LRU pages in here because
2130 * nobody will play with that bit on a non-LRU page.
2132 * The downside is that we have to touch page->_refcount against each page.
2133 * But we had to alter page->flags anyway.
2135 static void shrink_active_list(unsigned long nr_to_scan,
2136 struct lruvec *lruvec,
2137 struct scan_control *sc,
2140 unsigned long nr_taken;
2141 unsigned long nr_scanned;
2142 unsigned long vm_flags;
2143 LIST_HEAD(l_hold); /* The pages which were snipped off */
2144 LIST_HEAD(l_active);
2145 LIST_HEAD(l_inactive);
2147 unsigned nr_deactivate, nr_activate;
2148 unsigned nr_rotated = 0;
2149 int file = is_file_lru(lru);
2150 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2154 spin_lock_irq(&lruvec->lru_lock);
2156 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2157 &nr_scanned, sc, lru);
2159 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2161 if (!cgroup_reclaim(sc))
2162 __count_vm_events(PGREFILL, nr_scanned);
2163 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2165 spin_unlock_irq(&lruvec->lru_lock);
2167 while (!list_empty(&l_hold)) {
2169 page = lru_to_page(&l_hold);
2170 list_del(&page->lru);
2172 if (unlikely(!page_evictable(page))) {
2173 putback_lru_page(page);
2177 if (unlikely(buffer_heads_over_limit)) {
2178 if (page_has_private(page) && trylock_page(page)) {
2179 if (page_has_private(page))
2180 try_to_release_page(page, 0);
2185 if (page_referenced(page, 0, sc->target_mem_cgroup,
2188 * Identify referenced, file-backed active pages and
2189 * give them one more trip around the active list. So
2190 * that executable code get better chances to stay in
2191 * memory under moderate memory pressure. Anon pages
2192 * are not likely to be evicted by use-once streaming
2193 * IO, plus JVM can create lots of anon VM_EXEC pages,
2194 * so we ignore them here.
2196 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
2197 nr_rotated += thp_nr_pages(page);
2198 list_add(&page->lru, &l_active);
2203 ClearPageActive(page); /* we are de-activating */
2204 SetPageWorkingset(page);
2205 list_add(&page->lru, &l_inactive);
2209 * Move pages back to the lru list.
2211 spin_lock_irq(&lruvec->lru_lock);
2213 nr_activate = move_pages_to_lru(lruvec, &l_active);
2214 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2215 /* Keep all free pages in l_active list */
2216 list_splice(&l_inactive, &l_active);
2218 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2219 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2221 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2222 spin_unlock_irq(&lruvec->lru_lock);
2224 mem_cgroup_uncharge_list(&l_active);
2225 free_unref_page_list(&l_active);
2226 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2227 nr_deactivate, nr_rotated, sc->priority, file);
2230 unsigned long reclaim_pages(struct list_head *page_list)
2232 int nid = NUMA_NO_NODE;
2233 unsigned int nr_reclaimed = 0;
2234 LIST_HEAD(node_page_list);
2235 struct reclaim_stat dummy_stat;
2237 struct scan_control sc = {
2238 .gfp_mask = GFP_KERNEL,
2239 .priority = DEF_PRIORITY,
2245 while (!list_empty(page_list)) {
2246 page = lru_to_page(page_list);
2247 if (nid == NUMA_NO_NODE) {
2248 nid = page_to_nid(page);
2249 INIT_LIST_HEAD(&node_page_list);
2252 if (nid == page_to_nid(page)) {
2253 ClearPageActive(page);
2254 list_move(&page->lru, &node_page_list);
2258 nr_reclaimed += shrink_page_list(&node_page_list,
2260 &sc, &dummy_stat, false);
2261 while (!list_empty(&node_page_list)) {
2262 page = lru_to_page(&node_page_list);
2263 list_del(&page->lru);
2264 putback_lru_page(page);
2270 if (!list_empty(&node_page_list)) {
2271 nr_reclaimed += shrink_page_list(&node_page_list,
2273 &sc, &dummy_stat, false);
2274 while (!list_empty(&node_page_list)) {
2275 page = lru_to_page(&node_page_list);
2276 list_del(&page->lru);
2277 putback_lru_page(page);
2281 return nr_reclaimed;
2284 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2285 struct lruvec *lruvec, struct scan_control *sc)
2287 if (is_active_lru(lru)) {
2288 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2289 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2291 sc->skipped_deactivate = 1;
2295 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2299 * The inactive anon list should be small enough that the VM never has
2300 * to do too much work.
2302 * The inactive file list should be small enough to leave most memory
2303 * to the established workingset on the scan-resistant active list,
2304 * but large enough to avoid thrashing the aggregate readahead window.
2306 * Both inactive lists should also be large enough that each inactive
2307 * page has a chance to be referenced again before it is reclaimed.
2309 * If that fails and refaulting is observed, the inactive list grows.
2311 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2312 * on this LRU, maintained by the pageout code. An inactive_ratio
2313 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2316 * memory ratio inactive
2317 * -------------------------------------
2326 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2328 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2329 unsigned long inactive, active;
2330 unsigned long inactive_ratio;
2333 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2334 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2336 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2338 inactive_ratio = int_sqrt(10 * gb);
2342 return inactive * inactive_ratio < active;
2353 * Determine how aggressively the anon and file LRU lists should be
2354 * scanned. The relative value of each set of LRU lists is determined
2355 * by looking at the fraction of the pages scanned we did rotate back
2356 * onto the active list instead of evict.
2358 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2359 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2361 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2364 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2365 unsigned long anon_cost, file_cost, total_cost;
2366 int swappiness = mem_cgroup_swappiness(memcg);
2367 u64 fraction[ANON_AND_FILE];
2368 u64 denominator = 0; /* gcc */
2369 enum scan_balance scan_balance;
2370 unsigned long ap, fp;
2373 /* If we have no swap space, do not bother scanning anon pages. */
2374 if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
2375 scan_balance = SCAN_FILE;
2380 * Global reclaim will swap to prevent OOM even with no
2381 * swappiness, but memcg users want to use this knob to
2382 * disable swapping for individual groups completely when
2383 * using the memory controller's swap limit feature would be
2386 if (cgroup_reclaim(sc) && !swappiness) {
2387 scan_balance = SCAN_FILE;
2392 * Do not apply any pressure balancing cleverness when the
2393 * system is close to OOM, scan both anon and file equally
2394 * (unless the swappiness setting disagrees with swapping).
2396 if (!sc->priority && swappiness) {
2397 scan_balance = SCAN_EQUAL;
2402 * If the system is almost out of file pages, force-scan anon.
2404 if (sc->file_is_tiny) {
2405 scan_balance = SCAN_ANON;
2410 * If there is enough inactive page cache, we do not reclaim
2411 * anything from the anonymous working right now.
2413 if (sc->cache_trim_mode) {
2414 scan_balance = SCAN_FILE;
2418 scan_balance = SCAN_FRACT;
2420 * Calculate the pressure balance between anon and file pages.
2422 * The amount of pressure we put on each LRU is inversely
2423 * proportional to the cost of reclaiming each list, as
2424 * determined by the share of pages that are refaulting, times
2425 * the relative IO cost of bringing back a swapped out
2426 * anonymous page vs reloading a filesystem page (swappiness).
2428 * Although we limit that influence to ensure no list gets
2429 * left behind completely: at least a third of the pressure is
2430 * applied, before swappiness.
2432 * With swappiness at 100, anon and file have equal IO cost.
2434 total_cost = sc->anon_cost + sc->file_cost;
2435 anon_cost = total_cost + sc->anon_cost;
2436 file_cost = total_cost + sc->file_cost;
2437 total_cost = anon_cost + file_cost;
2439 ap = swappiness * (total_cost + 1);
2440 ap /= anon_cost + 1;
2442 fp = (200 - swappiness) * (total_cost + 1);
2443 fp /= file_cost + 1;
2447 denominator = ap + fp;
2449 for_each_evictable_lru(lru) {
2450 int file = is_file_lru(lru);
2451 unsigned long lruvec_size;
2453 unsigned long protection;
2455 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2456 protection = mem_cgroup_protection(sc->target_mem_cgroup,
2458 sc->memcg_low_reclaim);
2462 * Scale a cgroup's reclaim pressure by proportioning
2463 * its current usage to its memory.low or memory.min
2466 * This is important, as otherwise scanning aggression
2467 * becomes extremely binary -- from nothing as we
2468 * approach the memory protection threshold, to totally
2469 * nominal as we exceed it. This results in requiring
2470 * setting extremely liberal protection thresholds. It
2471 * also means we simply get no protection at all if we
2472 * set it too low, which is not ideal.
2474 * If there is any protection in place, we reduce scan
2475 * pressure by how much of the total memory used is
2476 * within protection thresholds.
2478 * There is one special case: in the first reclaim pass,
2479 * we skip over all groups that are within their low
2480 * protection. If that fails to reclaim enough pages to
2481 * satisfy the reclaim goal, we come back and override
2482 * the best-effort low protection. However, we still
2483 * ideally want to honor how well-behaved groups are in
2484 * that case instead of simply punishing them all
2485 * equally. As such, we reclaim them based on how much
2486 * memory they are using, reducing the scan pressure
2487 * again by how much of the total memory used is under
2490 unsigned long cgroup_size = mem_cgroup_size(memcg);
2492 /* Avoid TOCTOU with earlier protection check */
2493 cgroup_size = max(cgroup_size, protection);
2495 scan = lruvec_size - lruvec_size * protection /
2499 * Minimally target SWAP_CLUSTER_MAX pages to keep
2500 * reclaim moving forwards, avoiding decrementing
2501 * sc->priority further than desirable.
2503 scan = max(scan, SWAP_CLUSTER_MAX);
2508 scan >>= sc->priority;
2511 * If the cgroup's already been deleted, make sure to
2512 * scrape out the remaining cache.
2514 if (!scan && !mem_cgroup_online(memcg))
2515 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2517 switch (scan_balance) {
2519 /* Scan lists relative to size */
2523 * Scan types proportional to swappiness and
2524 * their relative recent reclaim efficiency.
2525 * Make sure we don't miss the last page on
2526 * the offlined memory cgroups because of a
2529 scan = mem_cgroup_online(memcg) ?
2530 div64_u64(scan * fraction[file], denominator) :
2531 DIV64_U64_ROUND_UP(scan * fraction[file],
2536 /* Scan one type exclusively */
2537 if ((scan_balance == SCAN_FILE) != file)
2541 /* Look ma, no brain */
2549 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
2551 unsigned long nr[NR_LRU_LISTS];
2552 unsigned long targets[NR_LRU_LISTS];
2553 unsigned long nr_to_scan;
2555 unsigned long nr_reclaimed = 0;
2556 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
2557 struct blk_plug plug;
2560 get_scan_count(lruvec, sc, nr);
2562 /* Record the original scan target for proportional adjustments later */
2563 memcpy(targets, nr, sizeof(nr));
2566 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2567 * event that can occur when there is little memory pressure e.g.
2568 * multiple streaming readers/writers. Hence, we do not abort scanning
2569 * when the requested number of pages are reclaimed when scanning at
2570 * DEF_PRIORITY on the assumption that the fact we are direct
2571 * reclaiming implies that kswapd is not keeping up and it is best to
2572 * do a batch of work at once. For memcg reclaim one check is made to
2573 * abort proportional reclaim if either the file or anon lru has already
2574 * dropped to zero at the first pass.
2576 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
2577 sc->priority == DEF_PRIORITY);
2579 blk_start_plug(&plug);
2580 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
2581 nr[LRU_INACTIVE_FILE]) {
2582 unsigned long nr_anon, nr_file, percentage;
2583 unsigned long nr_scanned;
2585 for_each_evictable_lru(lru) {
2587 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
2588 nr[lru] -= nr_to_scan;
2590 nr_reclaimed += shrink_list(lru, nr_to_scan,
2597 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2601 * For kswapd and memcg, reclaim at least the number of pages
2602 * requested. Ensure that the anon and file LRUs are scanned
2603 * proportionally what was requested by get_scan_count(). We
2604 * stop reclaiming one LRU and reduce the amount scanning
2605 * proportional to the original scan target.
2607 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2608 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2611 * It's just vindictive to attack the larger once the smaller
2612 * has gone to zero. And given the way we stop scanning the
2613 * smaller below, this makes sure that we only make one nudge
2614 * towards proportionality once we've got nr_to_reclaim.
2616 if (!nr_file || !nr_anon)
2619 if (nr_file > nr_anon) {
2620 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2621 targets[LRU_ACTIVE_ANON] + 1;
2623 percentage = nr_anon * 100 / scan_target;
2625 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2626 targets[LRU_ACTIVE_FILE] + 1;
2628 percentage = nr_file * 100 / scan_target;
2631 /* Stop scanning the smaller of the LRU */
2633 nr[lru + LRU_ACTIVE] = 0;
2636 * Recalculate the other LRU scan count based on its original
2637 * scan target and the percentage scanning already complete
2639 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2640 nr_scanned = targets[lru] - nr[lru];
2641 nr[lru] = targets[lru] * (100 - percentage) / 100;
2642 nr[lru] -= min(nr[lru], nr_scanned);
2645 nr_scanned = targets[lru] - nr[lru];
2646 nr[lru] = targets[lru] * (100 - percentage) / 100;
2647 nr[lru] -= min(nr[lru], nr_scanned);
2649 scan_adjusted = true;
2651 blk_finish_plug(&plug);
2652 sc->nr_reclaimed += nr_reclaimed;
2655 * Even if we did not try to evict anon pages at all, we want to
2656 * rebalance the anon lru active/inactive ratio.
2658 if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
2659 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2660 sc, LRU_ACTIVE_ANON);
2663 /* Use reclaim/compaction for costly allocs or under memory pressure */
2664 static bool in_reclaim_compaction(struct scan_control *sc)
2666 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
2667 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
2668 sc->priority < DEF_PRIORITY - 2))
2675 * Reclaim/compaction is used for high-order allocation requests. It reclaims
2676 * order-0 pages before compacting the zone. should_continue_reclaim() returns
2677 * true if more pages should be reclaimed such that when the page allocator
2678 * calls try_to_compact_pages() that it will have enough free pages to succeed.
2679 * It will give up earlier than that if there is difficulty reclaiming pages.
2681 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
2682 unsigned long nr_reclaimed,
2683 struct scan_control *sc)
2685 unsigned long pages_for_compaction;
2686 unsigned long inactive_lru_pages;
2689 /* If not in reclaim/compaction mode, stop */
2690 if (!in_reclaim_compaction(sc))
2694 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
2695 * number of pages that were scanned. This will return to the caller
2696 * with the risk reclaim/compaction and the resulting allocation attempt
2697 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
2698 * allocations through requiring that the full LRU list has been scanned
2699 * first, by assuming that zero delta of sc->nr_scanned means full LRU
2700 * scan, but that approximation was wrong, and there were corner cases
2701 * where always a non-zero amount of pages were scanned.
2706 /* If compaction would go ahead or the allocation would succeed, stop */
2707 for (z = 0; z <= sc->reclaim_idx; z++) {
2708 struct zone *zone = &pgdat->node_zones[z];
2709 if (!managed_zone(zone))
2712 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2713 case COMPACT_SUCCESS:
2714 case COMPACT_CONTINUE:
2717 /* check next zone */
2723 * If we have not reclaimed enough pages for compaction and the
2724 * inactive lists are large enough, continue reclaiming
2726 pages_for_compaction = compact_gap(sc->order);
2727 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2728 if (get_nr_swap_pages() > 0)
2729 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
2731 return inactive_lru_pages > pages_for_compaction;
2734 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2736 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2737 struct mem_cgroup *memcg;
2739 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2741 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
2742 unsigned long reclaimed;
2743 unsigned long scanned;
2746 * This loop can become CPU-bound when target memcgs
2747 * aren't eligible for reclaim - either because they
2748 * don't have any reclaimable pages, or because their
2749 * memory is explicitly protected. Avoid soft lockups.
2753 mem_cgroup_calculate_protection(target_memcg, memcg);
2755 if (mem_cgroup_below_min(memcg)) {
2758 * If there is no reclaimable memory, OOM.
2761 } else if (mem_cgroup_below_low(memcg)) {
2764 * Respect the protection only as long as
2765 * there is an unprotected supply
2766 * of reclaimable memory from other cgroups.
2768 if (!sc->memcg_low_reclaim) {
2769 sc->memcg_low_skipped = 1;
2772 memcg_memory_event(memcg, MEMCG_LOW);
2775 reclaimed = sc->nr_reclaimed;
2776 scanned = sc->nr_scanned;
2778 shrink_lruvec(lruvec, sc);
2780 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
2783 /* Record the group's reclaim efficiency */
2784 vmpressure(sc->gfp_mask, memcg, false,
2785 sc->nr_scanned - scanned,
2786 sc->nr_reclaimed - reclaimed);
2788 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
2791 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2793 struct reclaim_state *reclaim_state = current->reclaim_state;
2794 unsigned long nr_reclaimed, nr_scanned;
2795 struct lruvec *target_lruvec;
2796 bool reclaimable = false;
2799 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2802 memset(&sc->nr, 0, sizeof(sc->nr));
2804 nr_reclaimed = sc->nr_reclaimed;
2805 nr_scanned = sc->nr_scanned;
2808 * Determine the scan balance between anon and file LRUs.
2810 spin_lock_irq(&target_lruvec->lru_lock);
2811 sc->anon_cost = target_lruvec->anon_cost;
2812 sc->file_cost = target_lruvec->file_cost;
2813 spin_unlock_irq(&target_lruvec->lru_lock);
2816 * Target desirable inactive:active list ratios for the anon
2817 * and file LRU lists.
2819 if (!sc->force_deactivate) {
2820 unsigned long refaults;
2822 refaults = lruvec_page_state(target_lruvec,
2823 WORKINGSET_ACTIVATE_ANON);
2824 if (refaults != target_lruvec->refaults[0] ||
2825 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2826 sc->may_deactivate |= DEACTIVATE_ANON;
2828 sc->may_deactivate &= ~DEACTIVATE_ANON;
2831 * When refaults are being observed, it means a new
2832 * workingset is being established. Deactivate to get
2833 * rid of any stale active pages quickly.
2835 refaults = lruvec_page_state(target_lruvec,
2836 WORKINGSET_ACTIVATE_FILE);
2837 if (refaults != target_lruvec->refaults[1] ||
2838 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2839 sc->may_deactivate |= DEACTIVATE_FILE;
2841 sc->may_deactivate &= ~DEACTIVATE_FILE;
2843 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2846 * If we have plenty of inactive file pages that aren't
2847 * thrashing, try to reclaim those first before touching
2850 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2851 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2852 sc->cache_trim_mode = 1;
2854 sc->cache_trim_mode = 0;
2857 * Prevent the reclaimer from falling into the cache trap: as
2858 * cache pages start out inactive, every cache fault will tip
2859 * the scan balance towards the file LRU. And as the file LRU
2860 * shrinks, so does the window for rotation from references.
2861 * This means we have a runaway feedback loop where a tiny
2862 * thrashing file LRU becomes infinitely more attractive than
2863 * anon pages. Try to detect this based on file LRU size.
2865 if (!cgroup_reclaim(sc)) {
2866 unsigned long total_high_wmark = 0;
2867 unsigned long free, anon;
2870 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2871 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2872 node_page_state(pgdat, NR_INACTIVE_FILE);
2874 for (z = 0; z < MAX_NR_ZONES; z++) {
2875 struct zone *zone = &pgdat->node_zones[z];
2876 if (!managed_zone(zone))
2879 total_high_wmark += high_wmark_pages(zone);
2883 * Consider anon: if that's low too, this isn't a
2884 * runaway file reclaim problem, but rather just
2885 * extreme pressure. Reclaim as per usual then.
2887 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2890 file + free <= total_high_wmark &&
2891 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2892 anon >> sc->priority;
2895 shrink_node_memcgs(pgdat, sc);
2897 if (reclaim_state) {
2898 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2899 reclaim_state->reclaimed_slab = 0;
2902 /* Record the subtree's reclaim efficiency */
2903 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
2904 sc->nr_scanned - nr_scanned,
2905 sc->nr_reclaimed - nr_reclaimed);
2907 if (sc->nr_reclaimed - nr_reclaimed)
2910 if (current_is_kswapd()) {
2912 * If reclaim is isolating dirty pages under writeback,
2913 * it implies that the long-lived page allocation rate
2914 * is exceeding the page laundering rate. Either the
2915 * global limits are not being effective at throttling
2916 * processes due to the page distribution throughout
2917 * zones or there is heavy usage of a slow backing
2918 * device. The only option is to throttle from reclaim
2919 * context which is not ideal as there is no guarantee
2920 * the dirtying process is throttled in the same way
2921 * balance_dirty_pages() manages.
2923 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2924 * count the number of pages under pages flagged for
2925 * immediate reclaim and stall if any are encountered
2926 * in the nr_immediate check below.
2928 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2929 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2931 /* Allow kswapd to start writing pages during reclaim.*/
2932 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2933 set_bit(PGDAT_DIRTY, &pgdat->flags);
2936 * If kswapd scans pages marked for immediate
2937 * reclaim and under writeback (nr_immediate), it
2938 * implies that pages are cycling through the LRU
2939 * faster than they are written so also forcibly stall.
2941 if (sc->nr.immediate)
2942 congestion_wait(BLK_RW_ASYNC, HZ/10);
2946 * Tag a node/memcg as congested if all the dirty pages
2947 * scanned were backed by a congested BDI and
2948 * wait_iff_congested will stall.
2950 * Legacy memcg will stall in page writeback so avoid forcibly
2951 * stalling in wait_iff_congested().
2953 if ((current_is_kswapd() ||
2954 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
2955 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2956 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
2959 * Stall direct reclaim for IO completions if underlying BDIs
2960 * and node is congested. Allow kswapd to continue until it
2961 * starts encountering unqueued dirty pages or cycling through
2962 * the LRU too quickly.
2964 if (!current_is_kswapd() && current_may_throttle() &&
2965 !sc->hibernation_mode &&
2966 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
2967 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2969 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2974 * Kswapd gives up on balancing particular nodes after too
2975 * many failures to reclaim anything from them and goes to
2976 * sleep. On reclaim progress, reset the failure counter. A
2977 * successful direct reclaim run will revive a dormant kswapd.
2980 pgdat->kswapd_failures = 0;
2984 * Returns true if compaction should go ahead for a costly-order request, or
2985 * the allocation would already succeed without compaction. Return false if we
2986 * should reclaim first.
2988 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2990 unsigned long watermark;
2991 enum compact_result suitable;
2993 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2994 if (suitable == COMPACT_SUCCESS)
2995 /* Allocation should succeed already. Don't reclaim. */
2997 if (suitable == COMPACT_SKIPPED)
2998 /* Compaction cannot yet proceed. Do reclaim. */
3002 * Compaction is already possible, but it takes time to run and there
3003 * are potentially other callers using the pages just freed. So proceed
3004 * with reclaim to make a buffer of free pages available to give
3005 * compaction a reasonable chance of completing and allocating the page.
3006 * Note that we won't actually reclaim the whole buffer in one attempt
3007 * as the target watermark in should_continue_reclaim() is lower. But if
3008 * we are already above the high+gap watermark, don't reclaim at all.
3010 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3012 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3016 * This is the direct reclaim path, for page-allocating processes. We only
3017 * try to reclaim pages from zones which will satisfy the caller's allocation
3020 * If a zone is deemed to be full of pinned pages then just give it a light
3021 * scan then give up on it.
3023 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
3027 unsigned long nr_soft_reclaimed;
3028 unsigned long nr_soft_scanned;
3030 pg_data_t *last_pgdat = NULL;
3033 * If the number of buffer_heads in the machine exceeds the maximum
3034 * allowed level, force direct reclaim to scan the highmem zone as
3035 * highmem pages could be pinning lowmem pages storing buffer_heads
3037 orig_mask = sc->gfp_mask;
3038 if (buffer_heads_over_limit) {
3039 sc->gfp_mask |= __GFP_HIGHMEM;
3040 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3043 for_each_zone_zonelist_nodemask(zone, z, zonelist,
3044 sc->reclaim_idx, sc->nodemask) {
3046 * Take care memory controller reclaiming has small influence
3049 if (!cgroup_reclaim(sc)) {
3050 if (!cpuset_zone_allowed(zone,
3051 GFP_KERNEL | __GFP_HARDWALL))
3055 * If we already have plenty of memory free for
3056 * compaction in this zone, don't free any more.
3057 * Even though compaction is invoked for any
3058 * non-zero order, only frequent costly order
3059 * reclamation is disruptive enough to become a
3060 * noticeable problem, like transparent huge
3063 if (IS_ENABLED(CONFIG_COMPACTION) &&
3064 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
3065 compaction_ready(zone, sc)) {
3066 sc->compaction_ready = true;
3071 * Shrink each node in the zonelist once. If the
3072 * zonelist is ordered by zone (not the default) then a
3073 * node may be shrunk multiple times but in that case
3074 * the user prefers lower zones being preserved.
3076 if (zone->zone_pgdat == last_pgdat)
3080 * This steals pages from memory cgroups over softlimit
3081 * and returns the number of reclaimed pages and
3082 * scanned pages. This works for global memory pressure
3083 * and balancing, not for a memcg's limit.
3085 nr_soft_scanned = 0;
3086 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
3087 sc->order, sc->gfp_mask,
3089 sc->nr_reclaimed += nr_soft_reclaimed;
3090 sc->nr_scanned += nr_soft_scanned;
3091 /* need some check for avoid more shrink_zone() */
3094 /* See comment about same check for global reclaim above */
3095 if (zone->zone_pgdat == last_pgdat)
3097 last_pgdat = zone->zone_pgdat;
3098 shrink_node(zone->zone_pgdat, sc);
3102 * Restore to original mask to avoid the impact on the caller if we
3103 * promoted it to __GFP_HIGHMEM.
3105 sc->gfp_mask = orig_mask;
3108 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
3110 struct lruvec *target_lruvec;
3111 unsigned long refaults;
3113 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3114 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3115 target_lruvec->refaults[0] = refaults;
3116 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3117 target_lruvec->refaults[1] = refaults;
3121 * This is the main entry point to direct page reclaim.
3123 * If a full scan of the inactive list fails to free enough memory then we
3124 * are "out of memory" and something needs to be killed.
3126 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3127 * high - the zone may be full of dirty or under-writeback pages, which this
3128 * caller can't do much about. We kick the writeback threads and take explicit
3129 * naps in the hope that some of these pages can be written. But if the
3130 * allocating task holds filesystem locks which prevent writeout this might not
3131 * work, and the allocation attempt will fail.
3133 * returns: 0, if no pages reclaimed
3134 * else, the number of pages reclaimed
3136 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3137 struct scan_control *sc)
3139 int initial_priority = sc->priority;
3140 pg_data_t *last_pgdat;
3144 delayacct_freepages_start();
3146 if (!cgroup_reclaim(sc))
3147 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
3150 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
3153 shrink_zones(zonelist, sc);
3155 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
3158 if (sc->compaction_ready)
3162 * If we're getting trouble reclaiming, start doing
3163 * writepage even in laptop mode.
3165 if (sc->priority < DEF_PRIORITY - 2)
3166 sc->may_writepage = 1;
3167 } while (--sc->priority >= 0);
3170 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
3172 if (zone->zone_pgdat == last_pgdat)
3174 last_pgdat = zone->zone_pgdat;
3176 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3178 if (cgroup_reclaim(sc)) {
3179 struct lruvec *lruvec;
3181 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
3183 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3187 delayacct_freepages_end();
3189 if (sc->nr_reclaimed)
3190 return sc->nr_reclaimed;
3192 /* Aborted reclaim to try compaction? don't OOM, then */
3193 if (sc->compaction_ready)
3197 * We make inactive:active ratio decisions based on the node's
3198 * composition of memory, but a restrictive reclaim_idx or a
3199 * memory.low cgroup setting can exempt large amounts of
3200 * memory from reclaim. Neither of which are very common, so
3201 * instead of doing costly eligibility calculations of the
3202 * entire cgroup subtree up front, we assume the estimates are
3203 * good, and retry with forcible deactivation if that fails.
3205 if (sc->skipped_deactivate) {
3206 sc->priority = initial_priority;
3207 sc->force_deactivate = 1;
3208 sc->skipped_deactivate = 0;
3212 /* Untapped cgroup reserves? Don't OOM, retry. */
3213 if (sc->memcg_low_skipped) {
3214 sc->priority = initial_priority;
3215 sc->force_deactivate = 0;
3216 sc->memcg_low_reclaim = 1;
3217 sc->memcg_low_skipped = 0;
3224 static bool allow_direct_reclaim(pg_data_t *pgdat)
3227 unsigned long pfmemalloc_reserve = 0;
3228 unsigned long free_pages = 0;
3232 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3235 for (i = 0; i <= ZONE_NORMAL; i++) {
3236 zone = &pgdat->node_zones[i];
3237 if (!managed_zone(zone))
3240 if (!zone_reclaimable_pages(zone))
3243 pfmemalloc_reserve += min_wmark_pages(zone);
3244 free_pages += zone_page_state(zone, NR_FREE_PAGES);
3247 /* If there are no reserves (unexpected config) then do not throttle */
3248 if (!pfmemalloc_reserve)
3251 wmark_ok = free_pages > pfmemalloc_reserve / 2;
3253 /* kswapd must be awake if processes are being throttled */
3254 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
3255 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
3256 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
3258 wake_up_interruptible(&pgdat->kswapd_wait);
3265 * Throttle direct reclaimers if backing storage is backed by the network
3266 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3267 * depleted. kswapd will continue to make progress and wake the processes
3268 * when the low watermark is reached.
3270 * Returns true if a fatal signal was delivered during throttling. If this
3271 * happens, the page allocator should not consider triggering the OOM killer.
3273 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
3274 nodemask_t *nodemask)
3278 pg_data_t *pgdat = NULL;
3281 * Kernel threads should not be throttled as they may be indirectly
3282 * responsible for cleaning pages necessary for reclaim to make forward
3283 * progress. kjournald for example may enter direct reclaim while
3284 * committing a transaction where throttling it could forcing other
3285 * processes to block on log_wait_commit().
3287 if (current->flags & PF_KTHREAD)
3291 * If a fatal signal is pending, this process should not throttle.
3292 * It should return quickly so it can exit and free its memory
3294 if (fatal_signal_pending(current))
3298 * Check if the pfmemalloc reserves are ok by finding the first node
3299 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3300 * GFP_KERNEL will be required for allocating network buffers when
3301 * swapping over the network so ZONE_HIGHMEM is unusable.
3303 * Throttling is based on the first usable node and throttled processes
3304 * wait on a queue until kswapd makes progress and wakes them. There
3305 * is an affinity then between processes waking up and where reclaim
3306 * progress has been made assuming the process wakes on the same node.
3307 * More importantly, processes running on remote nodes will not compete
3308 * for remote pfmemalloc reserves and processes on different nodes
3309 * should make reasonable progress.
3311 for_each_zone_zonelist_nodemask(zone, z, zonelist,
3312 gfp_zone(gfp_mask), nodemask) {
3313 if (zone_idx(zone) > ZONE_NORMAL)
3316 /* Throttle based on the first usable node */
3317 pgdat = zone->zone_pgdat;
3318 if (allow_direct_reclaim(pgdat))
3323 /* If no zone was usable by the allocation flags then do not throttle */
3327 /* Account for the throttling */
3328 count_vm_event(PGSCAN_DIRECT_THROTTLE);
3331 * If the caller cannot enter the filesystem, it's possible that it
3332 * is due to the caller holding an FS lock or performing a journal
3333 * transaction in the case of a filesystem like ext[3|4]. In this case,
3334 * it is not safe to block on pfmemalloc_wait as kswapd could be
3335 * blocked waiting on the same lock. Instead, throttle for up to a
3336 * second before continuing.
3338 if (!(gfp_mask & __GFP_FS)) {
3339 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3340 allow_direct_reclaim(pgdat), HZ);
3345 /* Throttle until kswapd wakes the process */
3346 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3347 allow_direct_reclaim(pgdat));
3350 if (fatal_signal_pending(current))
3357 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3358 gfp_t gfp_mask, nodemask_t *nodemask)
3360 unsigned long nr_reclaimed;
3361 struct scan_control sc = {
3362 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3363 .gfp_mask = current_gfp_context(gfp_mask),
3364 .reclaim_idx = gfp_zone(gfp_mask),
3366 .nodemask = nodemask,
3367 .priority = DEF_PRIORITY,
3368 .may_writepage = !laptop_mode,
3374 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3375 * Confirm they are large enough for max values.
3377 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3378 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3379 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3382 * Do not enter reclaim if fatal signal was delivered while throttled.
3383 * 1 is returned so that the page allocator does not OOM kill at this
3386 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
3389 set_task_reclaim_state(current, &sc.reclaim_state);
3390 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
3392 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3394 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
3395 set_task_reclaim_state(current, NULL);
3397 return nr_reclaimed;
3402 /* Only used by soft limit reclaim. Do not reuse for anything else. */
3403 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
3404 gfp_t gfp_mask, bool noswap,
3406 unsigned long *nr_scanned)
3408 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3409 struct scan_control sc = {
3410 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3411 .target_mem_cgroup = memcg,
3412 .may_writepage = !laptop_mode,
3414 .reclaim_idx = MAX_NR_ZONES - 1,
3415 .may_swap = !noswap,
3418 WARN_ON_ONCE(!current->reclaim_state);
3420 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3421 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3423 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3427 * NOTE: Although we can get the priority field, using it
3428 * here is not a good idea, since it limits the pages we can scan.
3429 * if we don't reclaim here, the shrink_node from balance_pgdat
3430 * will pick up pages from other mem cgroup's as well. We hack
3431 * the priority and make it zero.
3433 shrink_lruvec(lruvec, &sc);
3435 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3437 *nr_scanned = sc.nr_scanned;
3439 return sc.nr_reclaimed;
3442 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3443 unsigned long nr_pages,
3447 unsigned long nr_reclaimed;
3448 unsigned int noreclaim_flag;
3449 struct scan_control sc = {
3450 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3451 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3452 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3453 .reclaim_idx = MAX_NR_ZONES - 1,
3454 .target_mem_cgroup = memcg,
3455 .priority = DEF_PRIORITY,
3456 .may_writepage = !laptop_mode,
3458 .may_swap = may_swap,
3461 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3462 * equal pressure on all the nodes. This is based on the assumption that
3463 * the reclaim does not bail out early.
3465 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
3467 set_task_reclaim_state(current, &sc.reclaim_state);
3468 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3469 noreclaim_flag = memalloc_noreclaim_save();
3471 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3473 memalloc_noreclaim_restore(noreclaim_flag);
3474 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3475 set_task_reclaim_state(current, NULL);
3477 return nr_reclaimed;
3481 static void age_active_anon(struct pglist_data *pgdat,
3482 struct scan_control *sc)
3484 struct mem_cgroup *memcg;
3485 struct lruvec *lruvec;
3487 if (!total_swap_pages)
3490 lruvec = mem_cgroup_lruvec(NULL, pgdat);
3491 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3494 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3496 lruvec = mem_cgroup_lruvec(memcg, pgdat);
3497 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3498 sc, LRU_ACTIVE_ANON);
3499 memcg = mem_cgroup_iter(NULL, memcg, NULL);
3503 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
3509 * Check for watermark boosts top-down as the higher zones
3510 * are more likely to be boosted. Both watermarks and boosts
3511 * should not be checked at the same time as reclaim would
3512 * start prematurely when there is no boosting and a lower
3515 for (i = highest_zoneidx; i >= 0; i--) {
3516 zone = pgdat->node_zones + i;
3517 if (!managed_zone(zone))
3520 if (zone->watermark_boost)
3528 * Returns true if there is an eligible zone balanced for the request order
3529 * and highest_zoneidx
3531 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
3534 unsigned long mark = -1;
3538 * Check watermarks bottom-up as lower zones are more likely to
3541 for (i = 0; i <= highest_zoneidx; i++) {
3542 zone = pgdat->node_zones + i;
3544 if (!managed_zone(zone))
3547 mark = high_wmark_pages(zone);
3548 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
3553 * If a node has no populated zone within highest_zoneidx, it does not
3554 * need balancing by definition. This can happen if a zone-restricted
3555 * allocation tries to wake a remote kswapd.
3563 /* Clear pgdat state for congested, dirty or under writeback. */
3564 static void clear_pgdat_congested(pg_data_t *pgdat)
3566 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
3568 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3569 clear_bit(PGDAT_DIRTY, &pgdat->flags);
3570 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3574 * Prepare kswapd for sleeping. This verifies that there are no processes
3575 * waiting in throttle_direct_reclaim() and that watermarks have been met.
3577 * Returns true if kswapd is ready to sleep
3579 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
3580 int highest_zoneidx)
3583 * The throttled processes are normally woken up in balance_pgdat() as
3584 * soon as allow_direct_reclaim() is true. But there is a potential
3585 * race between when kswapd checks the watermarks and a process gets
3586 * throttled. There is also a potential race if processes get
3587 * throttled, kswapd wakes, a large process exits thereby balancing the
3588 * zones, which causes kswapd to exit balance_pgdat() before reaching
3589 * the wake up checks. If kswapd is going to sleep, no process should
3590 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
3591 * the wake up is premature, processes will wake kswapd and get
3592 * throttled again. The difference from wake ups in balance_pgdat() is
3593 * that here we are under prepare_to_wait().
3595 if (waitqueue_active(&pgdat->pfmemalloc_wait))
3596 wake_up_all(&pgdat->pfmemalloc_wait);
3598 /* Hopeless node, leave it to direct reclaim */
3599 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3602 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3603 clear_pgdat_congested(pgdat);
3611 * kswapd shrinks a node of pages that are at or below the highest usable
3612 * zone that is currently unbalanced.
3614 * Returns true if kswapd scanned at least the requested number of pages to
3615 * reclaim or if the lack of progress was due to pages under writeback.
3616 * This is used to determine if the scanning priority needs to be raised.
3618 static bool kswapd_shrink_node(pg_data_t *pgdat,
3619 struct scan_control *sc)
3624 /* Reclaim a number of pages proportional to the number of zones */
3625 sc->nr_to_reclaim = 0;
3626 for (z = 0; z <= sc->reclaim_idx; z++) {
3627 zone = pgdat->node_zones + z;
3628 if (!managed_zone(zone))
3631 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
3635 * Historically care was taken to put equal pressure on all zones but
3636 * now pressure is applied based on node LRU order.
3638 shrink_node(pgdat, sc);
3641 * Fragmentation may mean that the system cannot be rebalanced for
3642 * high-order allocations. If twice the allocation size has been
3643 * reclaimed then recheck watermarks only at order-0 to prevent
3644 * excessive reclaim. Assume that a process requested a high-order
3645 * can direct reclaim/compact.
3647 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
3650 return sc->nr_scanned >= sc->nr_to_reclaim;
3654 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
3655 * that are eligible for use by the caller until at least one zone is
3658 * Returns the order kswapd finished reclaiming at.
3660 * kswapd scans the zones in the highmem->normal->dma direction. It skips
3661 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
3662 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
3663 * or lower is eligible for reclaim until at least one usable zone is
3666 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
3669 unsigned long nr_soft_reclaimed;
3670 unsigned long nr_soft_scanned;
3671 unsigned long pflags;
3672 unsigned long nr_boost_reclaim;
3673 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
3676 struct scan_control sc = {
3677 .gfp_mask = GFP_KERNEL,
3682 set_task_reclaim_state(current, &sc.reclaim_state);
3683 psi_memstall_enter(&pflags);
3684 __fs_reclaim_acquire();
3686 count_vm_event(PAGEOUTRUN);
3689 * Account for the reclaim boost. Note that the zone boost is left in
3690 * place so that parallel allocations that are near the watermark will
3691 * stall or direct reclaim until kswapd is finished.
3693 nr_boost_reclaim = 0;
3694 for (i = 0; i <= highest_zoneidx; i++) {
3695 zone = pgdat->node_zones + i;
3696 if (!managed_zone(zone))
3699 nr_boost_reclaim += zone->watermark_boost;
3700 zone_boosts[i] = zone->watermark_boost;
3702 boosted = nr_boost_reclaim;
3705 sc.priority = DEF_PRIORITY;
3707 unsigned long nr_reclaimed = sc.nr_reclaimed;
3708 bool raise_priority = true;
3712 sc.reclaim_idx = highest_zoneidx;
3715 * If the number of buffer_heads exceeds the maximum allowed
3716 * then consider reclaiming from all zones. This has a dual
3717 * purpose -- on 64-bit systems it is expected that
3718 * buffer_heads are stripped during active rotation. On 32-bit
3719 * systems, highmem pages can pin lowmem memory and shrinking
3720 * buffers can relieve lowmem pressure. Reclaim may still not
3721 * go ahead if all eligible zones for the original allocation
3722 * request are balanced to avoid excessive reclaim from kswapd.
3724 if (buffer_heads_over_limit) {
3725 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
3726 zone = pgdat->node_zones + i;
3727 if (!managed_zone(zone))
3736 * If the pgdat is imbalanced then ignore boosting and preserve
3737 * the watermarks for a later time and restart. Note that the
3738 * zone watermarks will be still reset at the end of balancing
3739 * on the grounds that the normal reclaim should be enough to
3740 * re-evaluate if boosting is required when kswapd next wakes.
3742 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
3743 if (!balanced && nr_boost_reclaim) {
3744 nr_boost_reclaim = 0;
3749 * If boosting is not active then only reclaim if there are no
3750 * eligible zones. Note that sc.reclaim_idx is not used as
3751 * buffer_heads_over_limit may have adjusted it.
3753 if (!nr_boost_reclaim && balanced)
3756 /* Limit the priority of boosting to avoid reclaim writeback */
3757 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
3758 raise_priority = false;
3761 * Do not writeback or swap pages for boosted reclaim. The
3762 * intent is to relieve pressure not issue sub-optimal IO
3763 * from reclaim context. If no pages are reclaimed, the
3764 * reclaim will be aborted.
3766 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
3767 sc.may_swap = !nr_boost_reclaim;
3770 * Do some background aging of the anon list, to give
3771 * pages a chance to be referenced before reclaiming. All
3772 * pages are rotated regardless of classzone as this is
3773 * about consistent aging.
3775 age_active_anon(pgdat, &sc);
3778 * If we're getting trouble reclaiming, start doing writepage
3779 * even in laptop mode.
3781 if (sc.priority < DEF_PRIORITY - 2)
3782 sc.may_writepage = 1;
3784 /* Call soft limit reclaim before calling shrink_node. */
3786 nr_soft_scanned = 0;
3787 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
3788 sc.gfp_mask, &nr_soft_scanned);
3789 sc.nr_reclaimed += nr_soft_reclaimed;
3792 * There should be no need to raise the scanning priority if
3793 * enough pages are already being scanned that that high
3794 * watermark would be met at 100% efficiency.
3796 if (kswapd_shrink_node(pgdat, &sc))
3797 raise_priority = false;
3800 * If the low watermark is met there is no need for processes
3801 * to be throttled on pfmemalloc_wait as they should not be
3802 * able to safely make forward progress. Wake them
3804 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3805 allow_direct_reclaim(pgdat))
3806 wake_up_all(&pgdat->pfmemalloc_wait);
3808 /* Check if kswapd should be suspending */
3809 __fs_reclaim_release();
3810 ret = try_to_freeze();
3811 __fs_reclaim_acquire();
3812 if (ret || kthread_should_stop())
3816 * Raise priority if scanning rate is too low or there was no
3817 * progress in reclaiming pages
3819 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3820 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
3823 * If reclaim made no progress for a boost, stop reclaim as
3824 * IO cannot be queued and it could be an infinite loop in
3825 * extreme circumstances.
3827 if (nr_boost_reclaim && !nr_reclaimed)
3830 if (raise_priority || !nr_reclaimed)
3832 } while (sc.priority >= 1);
3834 if (!sc.nr_reclaimed)
3835 pgdat->kswapd_failures++;
3838 /* If reclaim was boosted, account for the reclaim done in this pass */
3840 unsigned long flags;
3842 for (i = 0; i <= highest_zoneidx; i++) {
3843 if (!zone_boosts[i])
3846 /* Increments are under the zone lock */
3847 zone = pgdat->node_zones + i;
3848 spin_lock_irqsave(&zone->lock, flags);
3849 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
3850 spin_unlock_irqrestore(&zone->lock, flags);
3854 * As there is now likely space, wakeup kcompact to defragment
3857 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
3860 snapshot_refaults(NULL, pgdat);
3861 __fs_reclaim_release();
3862 psi_memstall_leave(&pflags);
3863 set_task_reclaim_state(current, NULL);
3866 * Return the order kswapd stopped reclaiming at as
3867 * prepare_kswapd_sleep() takes it into account. If another caller
3868 * entered the allocator slow path while kswapd was awake, order will
3869 * remain at the higher level.
3875 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
3876 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
3877 * not a valid index then either kswapd runs for first time or kswapd couldn't
3878 * sleep after previous reclaim attempt (node is still unbalanced). In that
3879 * case return the zone index of the previous kswapd reclaim cycle.
3881 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
3882 enum zone_type prev_highest_zoneidx)
3884 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
3886 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
3889 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
3890 unsigned int highest_zoneidx)
3895 if (freezing(current) || kthread_should_stop())
3898 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3901 * Try to sleep for a short interval. Note that kcompactd will only be
3902 * woken if it is possible to sleep for a short interval. This is
3903 * deliberate on the assumption that if reclaim cannot keep an
3904 * eligible zone balanced that it's also unlikely that compaction will
3907 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3909 * Compaction records what page blocks it recently failed to
3910 * isolate pages from and skips them in the future scanning.
3911 * When kswapd is going to sleep, it is reasonable to assume
3912 * that pages and compaction may succeed so reset the cache.
3914 reset_isolation_suitable(pgdat);
3917 * We have freed the memory, now we should compact it to make
3918 * allocation of the requested order possible.
3920 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
3922 remaining = schedule_timeout(HZ/10);
3925 * If woken prematurely then reset kswapd_highest_zoneidx and
3926 * order. The values will either be from a wakeup request or
3927 * the previous request that slept prematurely.
3930 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
3931 kswapd_highest_zoneidx(pgdat,
3934 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
3935 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
3938 finish_wait(&pgdat->kswapd_wait, &wait);
3939 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3943 * After a short sleep, check if it was a premature sleep. If not, then
3944 * go fully to sleep until explicitly woken up.
3947 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3948 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3951 * vmstat counters are not perfectly accurate and the estimated
3952 * value for counters such as NR_FREE_PAGES can deviate from the
3953 * true value by nr_online_cpus * threshold. To avoid the zone
3954 * watermarks being breached while under pressure, we reduce the
3955 * per-cpu vmstat threshold while kswapd is awake and restore
3956 * them before going back to sleep.
3958 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
3960 if (!kthread_should_stop())
3963 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3966 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3968 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3970 finish_wait(&pgdat->kswapd_wait, &wait);
3974 * The background pageout daemon, started as a kernel thread
3975 * from the init process.
3977 * This basically trickles out pages so that we have _some_
3978 * free memory available even if there is no other activity
3979 * that frees anything up. This is needed for things like routing
3980 * etc, where we otherwise might have all activity going on in
3981 * asynchronous contexts that cannot page things out.
3983 * If there are applications that are active memory-allocators
3984 * (most normal use), this basically shouldn't matter.
3986 static int kswapd(void *p)
3988 unsigned int alloc_order, reclaim_order;
3989 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
3990 pg_data_t *pgdat = (pg_data_t*)p;
3991 struct task_struct *tsk = current;
3992 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
3994 if (!cpumask_empty(cpumask))
3995 set_cpus_allowed_ptr(tsk, cpumask);
3998 * Tell the memory management that we're a "memory allocator",
3999 * and that if we need more memory we should get access to it
4000 * regardless (see "__alloc_pages()"). "kswapd" should
4001 * never get caught in the normal page freeing logic.
4003 * (Kswapd normally doesn't need memory anyway, but sometimes
4004 * you need a small amount of memory in order to be able to
4005 * page out something else, and this flag essentially protects
4006 * us from recursively trying to free more memory as we're
4007 * trying to free the first piece of memory in the first place).
4009 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
4012 WRITE_ONCE(pgdat->kswapd_order, 0);
4013 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
4017 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
4018 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4022 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
4025 /* Read the new order and highest_zoneidx */
4026 alloc_order = READ_ONCE(pgdat->kswapd_order);
4027 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4029 WRITE_ONCE(pgdat->kswapd_order, 0);
4030 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
4032 ret = try_to_freeze();
4033 if (kthread_should_stop())
4037 * We can speed up thawing tasks if we don't call balance_pgdat
4038 * after returning from the refrigerator
4044 * Reclaim begins at the requested order but if a high-order
4045 * reclaim fails then kswapd falls back to reclaiming for
4046 * order-0. If that happens, kswapd will consider sleeping
4047 * for the order it finished reclaiming at (reclaim_order)
4048 * but kcompactd is woken to compact for the original
4049 * request (alloc_order).
4051 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4053 reclaim_order = balance_pgdat(pgdat, alloc_order,
4055 if (reclaim_order < alloc_order)
4056 goto kswapd_try_sleep;
4059 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
4065 * A zone is low on free memory or too fragmented for high-order memory. If
4066 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
4067 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
4068 * has failed or is not needed, still wake up kcompactd if only compaction is
4071 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
4072 enum zone_type highest_zoneidx)
4075 enum zone_type curr_idx;
4077 if (!managed_zone(zone))
4080 if (!cpuset_zone_allowed(zone, gfp_flags))
4083 pgdat = zone->zone_pgdat;
4084 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
4086 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
4087 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
4089 if (READ_ONCE(pgdat->kswapd_order) < order)
4090 WRITE_ONCE(pgdat->kswapd_order, order);
4092 if (!waitqueue_active(&pgdat->kswapd_wait))
4095 /* Hopeless node, leave it to direct reclaim if possible */
4096 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
4097 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
4098 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
4100 * There may be plenty of free memory available, but it's too
4101 * fragmented for high-order allocations. Wake up kcompactd
4102 * and rely on compaction_suitable() to determine if it's
4103 * needed. If it fails, it will defer subsequent attempts to
4104 * ratelimit its work.
4106 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
4107 wakeup_kcompactd(pgdat, order, highest_zoneidx);
4111 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
4113 wake_up_interruptible(&pgdat->kswapd_wait);
4116 #ifdef CONFIG_HIBERNATION
4118 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4121 * Rather than trying to age LRUs the aim is to preserve the overall
4122 * LRU order by reclaiming preferentially
4123 * inactive > active > active referenced > active mapped
4125 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
4127 struct scan_control sc = {
4128 .nr_to_reclaim = nr_to_reclaim,
4129 .gfp_mask = GFP_HIGHUSER_MOVABLE,
4130 .reclaim_idx = MAX_NR_ZONES - 1,
4131 .priority = DEF_PRIORITY,
4135 .hibernation_mode = 1,
4137 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
4138 unsigned long nr_reclaimed;
4139 unsigned int noreclaim_flag;
4141 fs_reclaim_acquire(sc.gfp_mask);
4142 noreclaim_flag = memalloc_noreclaim_save();
4143 set_task_reclaim_state(current, &sc.reclaim_state);
4145 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4147 set_task_reclaim_state(current, NULL);
4148 memalloc_noreclaim_restore(noreclaim_flag);
4149 fs_reclaim_release(sc.gfp_mask);
4151 return nr_reclaimed;
4153 #endif /* CONFIG_HIBERNATION */
4156 * This kswapd start function will be called by init and node-hot-add.
4157 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
4159 int kswapd_run(int nid)
4161 pg_data_t *pgdat = NODE_DATA(nid);
4167 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
4168 if (IS_ERR(pgdat->kswapd)) {
4169 /* failure at boot is fatal */
4170 BUG_ON(system_state < SYSTEM_RUNNING);
4171 pr_err("Failed to start kswapd on node %d\n", nid);
4172 ret = PTR_ERR(pgdat->kswapd);
4173 pgdat->kswapd = NULL;
4179 * Called by memory hotplug when all memory in a node is offlined. Caller must
4180 * hold mem_hotplug_begin/end().
4182 void kswapd_stop(int nid)
4184 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
4187 kthread_stop(kswapd);
4188 NODE_DATA(nid)->kswapd = NULL;
4192 static int __init kswapd_init(void)
4197 for_each_node_state(nid, N_MEMORY)
4202 module_init(kswapd_init)
4208 * If non-zero call node_reclaim when the number of free pages falls below
4211 int node_reclaim_mode __read_mostly;
4214 * Priority for NODE_RECLAIM. This determines the fraction of pages
4215 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4218 #define NODE_RECLAIM_PRIORITY 4
4221 * Percentage of pages in a zone that must be unmapped for node_reclaim to
4224 int sysctl_min_unmapped_ratio = 1;
4227 * If the number of slab pages in a zone grows beyond this percentage then
4228 * slab reclaim needs to occur.
4230 int sysctl_min_slab_ratio = 5;
4232 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
4234 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
4235 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
4236 node_page_state(pgdat, NR_ACTIVE_FILE);
4239 * It's possible for there to be more file mapped pages than
4240 * accounted for by the pages on the file LRU lists because
4241 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4243 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
4246 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4247 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
4249 unsigned long nr_pagecache_reclaimable;
4250 unsigned long delta = 0;
4253 * If RECLAIM_UNMAP is set, then all file pages are considered
4254 * potentially reclaimable. Otherwise, we have to worry about
4255 * pages like swapcache and node_unmapped_file_pages() provides
4258 if (node_reclaim_mode & RECLAIM_UNMAP)
4259 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
4261 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
4263 /* If we can't clean pages, remove dirty pages from consideration */
4264 if (!(node_reclaim_mode & RECLAIM_WRITE))
4265 delta += node_page_state(pgdat, NR_FILE_DIRTY);
4267 /* Watch for any possible underflows due to delta */
4268 if (unlikely(delta > nr_pagecache_reclaimable))
4269 delta = nr_pagecache_reclaimable;
4271 return nr_pagecache_reclaimable - delta;
4275 * Try to free up some pages from this node through reclaim.
4277 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4279 /* Minimum pages needed in order to stay on node */
4280 const unsigned long nr_pages = 1 << order;
4281 struct task_struct *p = current;
4282 unsigned int noreclaim_flag;
4283 struct scan_control sc = {
4284 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4285 .gfp_mask = current_gfp_context(gfp_mask),
4287 .priority = NODE_RECLAIM_PRIORITY,
4288 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4289 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4291 .reclaim_idx = gfp_zone(gfp_mask),
4294 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4298 fs_reclaim_acquire(sc.gfp_mask);
4300 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4301 * and we also need to be able to write out pages for RECLAIM_WRITE
4302 * and RECLAIM_UNMAP.
4304 noreclaim_flag = memalloc_noreclaim_save();
4305 p->flags |= PF_SWAPWRITE;
4306 set_task_reclaim_state(p, &sc.reclaim_state);
4308 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4310 * Free memory by calling shrink node with increasing
4311 * priorities until we have enough memory freed.
4314 shrink_node(pgdat, &sc);
4315 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
4318 set_task_reclaim_state(p, NULL);
4319 current->flags &= ~PF_SWAPWRITE;
4320 memalloc_noreclaim_restore(noreclaim_flag);
4321 fs_reclaim_release(sc.gfp_mask);
4323 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4325 return sc.nr_reclaimed >= nr_pages;
4328 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4333 * Node reclaim reclaims unmapped file backed pages and
4334 * slab pages if we are over the defined limits.
4336 * A small portion of unmapped file backed pages is needed for
4337 * file I/O otherwise pages read by file I/O will be immediately
4338 * thrown out if the node is overallocated. So we do not reclaim
4339 * if less than a specified percentage of the node is used by
4340 * unmapped file backed pages.
4342 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4343 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4344 pgdat->min_slab_pages)
4345 return NODE_RECLAIM_FULL;
4348 * Do not scan if the allocation should not be delayed.
4350 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4351 return NODE_RECLAIM_NOSCAN;
4354 * Only run node reclaim on the local node or on nodes that do not
4355 * have associated processors. This will favor the local processor
4356 * over remote processors and spread off node memory allocations
4357 * as wide as possible.
4359 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4360 return NODE_RECLAIM_NOSCAN;
4362 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4363 return NODE_RECLAIM_NOSCAN;
4365 ret = __node_reclaim(pgdat, gfp_mask, order);
4366 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4369 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
4376 * check_move_unevictable_pages - check pages for evictability and move to
4377 * appropriate zone lru list
4378 * @pvec: pagevec with lru pages to check
4380 * Checks pages for evictability, if an evictable page is in the unevictable
4381 * lru list, moves it to the appropriate evictable lru list. This function
4382 * should be only used for lru pages.
4384 void check_move_unevictable_pages(struct pagevec *pvec)
4386 struct lruvec *lruvec = NULL;
4391 for (i = 0; i < pvec->nr; i++) {
4392 struct page *page = pvec->pages[i];
4395 if (PageTransTail(page))
4398 nr_pages = thp_nr_pages(page);
4399 pgscanned += nr_pages;
4401 /* block memcg migration during page moving between lru */
4402 if (!TestClearPageLRU(page))
4405 lruvec = relock_page_lruvec_irq(page, lruvec);
4406 if (page_evictable(page) && PageUnevictable(page)) {
4407 del_page_from_lru_list(page, lruvec);
4408 ClearPageUnevictable(page);
4409 add_page_to_lru_list(page, lruvec);
4410 pgrescued += nr_pages;
4416 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
4417 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4418 unlock_page_lruvec_irq(lruvec);
4419 } else if (pgscanned) {
4420 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4423 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);