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.
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 buffer_heads_over_limit */
30 #include <linux/mm_inline.h>
31 #include <linux/backing-dev.h>
32 #include <linux/rmap.h>
33 #include <linux/topology.h>
34 #include <linux/cpu.h>
35 #include <linux/cpuset.h>
36 #include <linux/compaction.h>
37 #include <linux/notifier.h>
38 #include <linux/delay.h>
39 #include <linux/kthread.h>
40 #include <linux/freezer.h>
41 #include <linux/memcontrol.h>
42 #include <linux/migrate.h>
43 #include <linux/delayacct.h>
44 #include <linux/sysctl.h>
45 #include <linux/memory-tiers.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>
52 #include <linux/pagewalk.h>
53 #include <linux/shmem_fs.h>
54 #include <linux/ctype.h>
55 #include <linux/debugfs.h>
56 #include <linux/khugepaged.h>
57 #include <linux/rculist_nulls.h>
58 #include <linux/random.h>
60 #include <asm/tlbflush.h>
61 #include <asm/div64.h>
63 #include <linux/swapops.h>
64 #include <linux/balloon_compaction.h>
65 #include <linux/sched/sysctl.h>
70 #define CREATE_TRACE_POINTS
71 #include <trace/events/vmscan.h>
74 /* How many pages shrink_list() should reclaim */
75 unsigned long nr_to_reclaim;
78 * Nodemask of nodes allowed by the caller. If NULL, all nodes
84 * The memory cgroup that hit its limit and as a result is the
85 * primary target of this reclaim invocation.
87 struct mem_cgroup *target_mem_cgroup;
90 * Scan pressure balancing between anon and file LRUs
92 unsigned long anon_cost;
93 unsigned long file_cost;
96 /* Swappiness value for proactive reclaim. Always use sc_swappiness()! */
97 int *proactive_swappiness;
100 /* Can active folios be deactivated as part of reclaim? */
101 #define DEACTIVATE_ANON 1
102 #define DEACTIVATE_FILE 2
103 unsigned int may_deactivate:2;
104 unsigned int force_deactivate:1;
105 unsigned int skipped_deactivate:1;
107 /* Writepage batching in laptop mode; RECLAIM_WRITE */
108 unsigned int may_writepage:1;
110 /* Can mapped folios be reclaimed? */
111 unsigned int may_unmap:1;
113 /* Can folios be swapped as part of reclaim? */
114 unsigned int may_swap:1;
116 /* Not allow cache_trim_mode to be turned on as part of reclaim? */
117 unsigned int no_cache_trim_mode:1;
119 /* Has cache_trim_mode failed at least once? */
120 unsigned int cache_trim_mode_failed:1;
122 /* Proactive reclaim invoked by userspace through memory.reclaim */
123 unsigned int proactive:1;
126 * Cgroup memory below memory.low is protected as long as we
127 * don't threaten to OOM. If any cgroup is reclaimed at
128 * reduced force or passed over entirely due to its memory.low
129 * setting (memcg_low_skipped), and nothing is reclaimed as a
130 * result, then go back for one more cycle that reclaims the protected
131 * memory (memcg_low_reclaim) to avert OOM.
133 unsigned int memcg_low_reclaim:1;
134 unsigned int memcg_low_skipped:1;
136 /* Shared cgroup tree walk failed, rescan the whole tree */
137 unsigned int memcg_full_walk:1;
139 unsigned int hibernation_mode:1;
141 /* One of the zones is ready for compaction */
142 unsigned int compaction_ready:1;
144 /* There is easily reclaimable cold cache in the current node */
145 unsigned int cache_trim_mode:1;
147 /* The file folios on the current node are dangerously low */
148 unsigned int file_is_tiny:1;
150 /* Always discard instead of demoting to lower tier memory */
151 unsigned int no_demotion:1;
153 /* Allocation order */
156 /* Scan (total_size >> priority) pages at once */
159 /* The highest zone to isolate folios for reclaim from */
162 /* This context's GFP mask */
165 /* Incremented by the number of inactive pages that were scanned */
166 unsigned long nr_scanned;
168 /* Number of pages freed so far during a call to shrink_zones() */
169 unsigned long nr_reclaimed;
173 unsigned int unqueued_dirty;
174 unsigned int congested;
175 unsigned int writeback;
176 unsigned int immediate;
177 unsigned int file_taken;
181 /* for recording the reclaimed slab by now */
182 struct reclaim_state reclaim_state;
185 #ifdef ARCH_HAS_PREFETCHW
186 #define prefetchw_prev_lru_folio(_folio, _base, _field) \
188 if ((_folio)->lru.prev != _base) { \
189 struct folio *prev; \
191 prev = lru_to_folio(&(_folio->lru)); \
192 prefetchw(&prev->_field); \
196 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
200 * From 0 .. MAX_SWAPPINESS. Higher means more swappy.
202 int vm_swappiness = 60;
206 /* Returns true for reclaim through cgroup limits or cgroup interfaces. */
207 static bool cgroup_reclaim(struct scan_control *sc)
209 return sc->target_mem_cgroup;
213 * Returns true for reclaim on the root cgroup. This is true for direct
214 * allocator reclaim and reclaim through cgroup interfaces on the root cgroup.
216 static bool root_reclaim(struct scan_control *sc)
218 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
222 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
223 * @sc: scan_control in question
225 * The normal page dirty throttling mechanism in balance_dirty_pages() is
226 * completely broken with the legacy memcg and direct stalling in
227 * shrink_folio_list() is used for throttling instead, which lacks all the
228 * niceties such as fairness, adaptive pausing, bandwidth proportional
229 * allocation and configurability.
231 * This function tests whether the vmscan currently in progress can assume
232 * that the normal dirty throttling mechanism is operational.
234 static bool writeback_throttling_sane(struct scan_control *sc)
236 if (!cgroup_reclaim(sc))
238 #ifdef CONFIG_CGROUP_WRITEBACK
239 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
245 static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)
247 if (sc->proactive && sc->proactive_swappiness)
248 return *sc->proactive_swappiness;
249 return mem_cgroup_swappiness(memcg);
252 static bool cgroup_reclaim(struct scan_control *sc)
257 static bool root_reclaim(struct scan_control *sc)
262 static bool writeback_throttling_sane(struct scan_control *sc)
267 static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)
269 return READ_ONCE(vm_swappiness);
273 static void set_task_reclaim_state(struct task_struct *task,
274 struct reclaim_state *rs)
276 /* Check for an overwrite */
277 WARN_ON_ONCE(rs && task->reclaim_state);
279 /* Check for the nulling of an already-nulled member */
280 WARN_ON_ONCE(!rs && !task->reclaim_state);
282 task->reclaim_state = rs;
286 * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to
287 * scan_control->nr_reclaimed.
289 static void flush_reclaim_state(struct scan_control *sc)
292 * Currently, reclaim_state->reclaimed includes three types of pages
293 * freed outside of vmscan:
295 * (2) Clean file pages from pruned inodes (on highmem systems).
296 * (3) XFS freed buffer pages.
298 * For all of these cases, we cannot universally link the pages to a
299 * single memcg. For example, a memcg-aware shrinker can free one object
300 * charged to the target memcg, causing an entire page to be freed.
301 * If we count the entire page as reclaimed from the memcg, we end up
302 * overestimating the reclaimed amount (potentially under-reclaiming).
304 * Only count such pages for global reclaim to prevent under-reclaiming
305 * from the target memcg; preventing unnecessary retries during memcg
306 * charging and false positives from proactive reclaim.
308 * For uncommon cases where the freed pages were actually mostly
309 * charged to the target memcg, we end up underestimating the reclaimed
310 * amount. This should be fine. The freed pages will be uncharged
311 * anyway, even if they are not counted here properly, and we will be
312 * able to make forward progress in charging (which is usually in a
315 * We can go one step further, and report the uncharged objcg pages in
316 * memcg reclaim, to make reporting more accurate and reduce
317 * underestimation, but it's probably not worth the complexity for now.
319 if (current->reclaim_state && root_reclaim(sc)) {
320 sc->nr_reclaimed += current->reclaim_state->reclaimed;
321 current->reclaim_state->reclaimed = 0;
325 static bool can_demote(int nid, struct scan_control *sc)
327 if (!numa_demotion_enabled)
329 if (sc && sc->no_demotion)
331 if (next_demotion_node(nid) == NUMA_NO_NODE)
337 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
339 struct scan_control *sc)
343 * For non-memcg reclaim, is there
344 * space in any swap device?
346 if (get_nr_swap_pages() > 0)
349 /* Is the memcg below its swap limit? */
350 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
355 * The page can not be swapped.
357 * Can it be reclaimed from this node via demotion?
359 return can_demote(nid, sc);
363 * This misses isolated folios which are not accounted for to save counters.
364 * As the data only determines if reclaim or compaction continues, it is
365 * not expected that isolated folios will be a dominating factor.
367 unsigned long zone_reclaimable_pages(struct zone *zone)
371 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
372 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
373 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
374 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
375 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
381 * lruvec_lru_size - Returns the number of pages on the given LRU list.
382 * @lruvec: lru vector
384 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
386 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
389 unsigned long size = 0;
392 for (zid = 0; zid <= zone_idx; zid++) {
393 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
395 if (!managed_zone(zone))
398 if (!mem_cgroup_disabled())
399 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
401 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
406 static unsigned long drop_slab_node(int nid)
408 unsigned long freed = 0;
409 struct mem_cgroup *memcg = NULL;
411 memcg = mem_cgroup_iter(NULL, NULL, NULL);
413 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
414 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
427 for_each_online_node(nid) {
428 if (fatal_signal_pending(current))
431 freed += drop_slab_node(nid);
433 } while ((freed >> shift++) > 1);
436 static int reclaimer_offset(void)
438 BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
439 PGDEMOTE_DIRECT - PGDEMOTE_KSWAPD);
440 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
441 PGDEMOTE_KHUGEPAGED - PGDEMOTE_KSWAPD);
442 BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
443 PGSCAN_DIRECT - PGSCAN_KSWAPD);
444 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
445 PGSCAN_KHUGEPAGED - PGSCAN_KSWAPD);
447 if (current_is_kswapd())
449 if (current_is_khugepaged())
450 return PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD;
451 return PGSTEAL_DIRECT - PGSTEAL_KSWAPD;
454 static inline int is_page_cache_freeable(struct folio *folio)
457 * A freeable page cache folio is referenced only by the caller
458 * that isolated the folio, the page cache and optional filesystem
459 * private data at folio->private.
461 return folio_ref_count(folio) - folio_test_private(folio) ==
462 1 + folio_nr_pages(folio);
466 * We detected a synchronous write error writing a folio out. Probably
467 * -ENOSPC. We need to propagate that into the address_space for a subsequent
468 * fsync(), msync() or close().
470 * The tricky part is that after writepage we cannot touch the mapping: nothing
471 * prevents it from being freed up. But we have a ref on the folio and once
472 * that folio is locked, the mapping is pinned.
474 * We're allowed to run sleeping folio_lock() here because we know the caller has
477 static void handle_write_error(struct address_space *mapping,
478 struct folio *folio, int error)
481 if (folio_mapping(folio) == mapping)
482 mapping_set_error(mapping, error);
486 static bool skip_throttle_noprogress(pg_data_t *pgdat)
488 int reclaimable = 0, write_pending = 0;
492 * If kswapd is disabled, reschedule if necessary but do not
493 * throttle as the system is likely near OOM.
495 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
499 * If there are a lot of dirty/writeback folios then do not
500 * throttle as throttling will occur when the folios cycle
501 * towards the end of the LRU if still under writeback.
503 for (i = 0; i < MAX_NR_ZONES; i++) {
504 struct zone *zone = pgdat->node_zones + i;
506 if (!managed_zone(zone))
509 reclaimable += zone_reclaimable_pages(zone);
510 write_pending += zone_page_state_snapshot(zone,
511 NR_ZONE_WRITE_PENDING);
513 if (2 * write_pending <= reclaimable)
519 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
521 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
526 * Do not throttle user workers, kthreads other than kswapd or
527 * workqueues. They may be required for reclaim to make
528 * forward progress (e.g. journalling workqueues or kthreads).
530 if (!current_is_kswapd() &&
531 current->flags & (PF_USER_WORKER|PF_KTHREAD)) {
537 * These figures are pulled out of thin air.
538 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
539 * parallel reclaimers which is a short-lived event so the timeout is
540 * short. Failing to make progress or waiting on writeback are
541 * potentially long-lived events so use a longer timeout. This is shaky
542 * logic as a failure to make progress could be due to anything from
543 * writeback to a slow device to excessive referenced folios at the tail
544 * of the inactive LRU.
547 case VMSCAN_THROTTLE_WRITEBACK:
550 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
551 WRITE_ONCE(pgdat->nr_reclaim_start,
552 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
556 case VMSCAN_THROTTLE_CONGESTED:
558 case VMSCAN_THROTTLE_NOPROGRESS:
559 if (skip_throttle_noprogress(pgdat)) {
567 case VMSCAN_THROTTLE_ISOLATED:
576 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
577 ret = schedule_timeout(timeout);
578 finish_wait(wqh, &wait);
580 if (reason == VMSCAN_THROTTLE_WRITEBACK)
581 atomic_dec(&pgdat->nr_writeback_throttled);
583 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
584 jiffies_to_usecs(timeout - ret),
589 * Account for folios written if tasks are throttled waiting on dirty
590 * folios to clean. If enough folios have been cleaned since throttling
591 * started then wakeup the throttled tasks.
593 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
596 unsigned long nr_written;
598 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
601 * This is an inaccurate read as the per-cpu deltas may not
602 * be synchronised. However, given that the system is
603 * writeback throttled, it is not worth taking the penalty
604 * of getting an accurate count. At worst, the throttle
605 * timeout guarantees forward progress.
607 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
608 READ_ONCE(pgdat->nr_reclaim_start);
610 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
611 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
614 /* possible outcome of pageout() */
616 /* failed to write folio out, folio is locked */
618 /* move folio to the active list, folio is locked */
620 /* folio has been sent to the disk successfully, folio is unlocked */
622 /* folio is clean and locked */
627 * pageout is called by shrink_folio_list() for each dirty folio.
628 * Calls ->writepage().
630 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
631 struct swap_iocb **plug, struct list_head *folio_list)
634 * If the folio is dirty, only perform writeback if that write
635 * will be non-blocking. To prevent this allocation from being
636 * stalled by pagecache activity. But note that there may be
637 * stalls if we need to run get_block(). We could test
638 * PagePrivate for that.
640 * If this process is currently in __generic_file_write_iter() against
641 * this folio's queue, we can perform writeback even if that
644 * If the folio is swapcache, write it back even if that would
645 * block, for some throttling. This happens by accident, because
646 * swap_backing_dev_info is bust: it doesn't reflect the
647 * congestion state of the swapdevs. Easy to fix, if needed.
649 if (!is_page_cache_freeable(folio))
653 * Some data journaling orphaned folios can have
654 * folio->mapping == NULL while being dirty with clean buffers.
656 if (folio_test_private(folio)) {
657 if (try_to_free_buffers(folio)) {
658 folio_clear_dirty(folio);
659 pr_info("%s: orphaned folio\n", __func__);
665 if (mapping->a_ops->writepage == NULL)
666 return PAGE_ACTIVATE;
668 if (folio_clear_dirty_for_io(folio)) {
670 struct writeback_control wbc = {
671 .sync_mode = WB_SYNC_NONE,
672 .nr_to_write = SWAP_CLUSTER_MAX,
674 .range_end = LLONG_MAX,
680 * The large shmem folio can be split if CONFIG_THP_SWAP is
681 * not enabled or contiguous swap entries are failed to
684 if (shmem_mapping(mapping) && folio_test_large(folio))
685 wbc.list = folio_list;
687 folio_set_reclaim(folio);
688 res = mapping->a_ops->writepage(&folio->page, &wbc);
690 handle_write_error(mapping, folio, res);
691 if (res == AOP_WRITEPAGE_ACTIVATE) {
692 folio_clear_reclaim(folio);
693 return PAGE_ACTIVATE;
696 if (!folio_test_writeback(folio)) {
697 /* synchronous write or broken a_ops? */
698 folio_clear_reclaim(folio);
700 trace_mm_vmscan_write_folio(folio);
701 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
709 * Same as remove_mapping, but if the folio is removed from the mapping, it
710 * gets returned with a refcount of 0.
712 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
713 bool reclaimed, struct mem_cgroup *target_memcg)
718 BUG_ON(!folio_test_locked(folio));
719 BUG_ON(mapping != folio_mapping(folio));
721 if (!folio_test_swapcache(folio))
722 spin_lock(&mapping->host->i_lock);
723 xa_lock_irq(&mapping->i_pages);
725 * The non racy check for a busy folio.
727 * Must be careful with the order of the tests. When someone has
728 * a ref to the folio, it may be possible that they dirty it then
729 * drop the reference. So if the dirty flag is tested before the
730 * refcount here, then the following race may occur:
732 * get_user_pages(&page);
733 * [user mapping goes away]
735 * !folio_test_dirty(folio) [good]
736 * folio_set_dirty(folio);
738 * !refcount(folio) [good, discard it]
740 * [oops, our write_to data is lost]
742 * Reversing the order of the tests ensures such a situation cannot
743 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
744 * load is not satisfied before that of folio->_refcount.
746 * Note that if the dirty flag is always set via folio_mark_dirty,
747 * and thus under the i_pages lock, then this ordering is not required.
749 refcount = 1 + folio_nr_pages(folio);
750 if (!folio_ref_freeze(folio, refcount))
752 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
753 if (unlikely(folio_test_dirty(folio))) {
754 folio_ref_unfreeze(folio, refcount);
758 if (folio_test_swapcache(folio)) {
759 swp_entry_t swap = folio->swap;
761 if (reclaimed && !mapping_exiting(mapping))
762 shadow = workingset_eviction(folio, target_memcg);
763 __delete_from_swap_cache(folio, swap, shadow);
764 mem_cgroup_swapout(folio, swap);
765 xa_unlock_irq(&mapping->i_pages);
766 put_swap_folio(folio, swap);
768 void (*free_folio)(struct folio *);
770 free_folio = mapping->a_ops->free_folio;
772 * Remember a shadow entry for reclaimed file cache in
773 * order to detect refaults, thus thrashing, later on.
775 * But don't store shadows in an address space that is
776 * already exiting. This is not just an optimization,
777 * inode reclaim needs to empty out the radix tree or
778 * the nodes are lost. Don't plant shadows behind its
781 * We also don't store shadows for DAX mappings because the
782 * only page cache folios found in these are zero pages
783 * covering holes, and because we don't want to mix DAX
784 * exceptional entries and shadow exceptional entries in the
785 * same address_space.
787 if (reclaimed && folio_is_file_lru(folio) &&
788 !mapping_exiting(mapping) && !dax_mapping(mapping))
789 shadow = workingset_eviction(folio, target_memcg);
790 __filemap_remove_folio(folio, shadow);
791 xa_unlock_irq(&mapping->i_pages);
792 if (mapping_shrinkable(mapping))
793 inode_add_lru(mapping->host);
794 spin_unlock(&mapping->host->i_lock);
803 xa_unlock_irq(&mapping->i_pages);
804 if (!folio_test_swapcache(folio))
805 spin_unlock(&mapping->host->i_lock);
810 * remove_mapping() - Attempt to remove a folio from its mapping.
811 * @mapping: The address space.
812 * @folio: The folio to remove.
814 * If the folio is dirty, under writeback or if someone else has a ref
815 * on it, removal will fail.
816 * Return: The number of pages removed from the mapping. 0 if the folio
817 * could not be removed.
818 * Context: The caller should have a single refcount on the folio and
821 long remove_mapping(struct address_space *mapping, struct folio *folio)
823 if (__remove_mapping(mapping, folio, false, NULL)) {
825 * Unfreezing the refcount with 1 effectively
826 * drops the pagecache ref for us without requiring another
829 folio_ref_unfreeze(folio, 1);
830 return folio_nr_pages(folio);
836 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
837 * @folio: Folio to be returned to an LRU list.
839 * Add previously isolated @folio to appropriate LRU list.
840 * The folio may still be unevictable for other reasons.
842 * Context: lru_lock must not be held, interrupts must be enabled.
844 void folio_putback_lru(struct folio *folio)
846 folio_add_lru(folio);
847 folio_put(folio); /* drop ref from isolate */
850 enum folio_references {
852 FOLIOREF_RECLAIM_CLEAN,
857 static enum folio_references folio_check_references(struct folio *folio,
858 struct scan_control *sc)
860 int referenced_ptes, referenced_folio;
861 unsigned long vm_flags;
863 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
865 referenced_folio = folio_test_clear_referenced(folio);
868 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
869 * Let the folio, now marked Mlocked, be moved to the unevictable list.
871 if (vm_flags & VM_LOCKED)
872 return FOLIOREF_ACTIVATE;
875 * There are two cases to consider.
876 * 1) Rmap lock contention: rotate.
877 * 2) Skip the non-shared swapbacked folio mapped solely by
878 * the exiting or OOM-reaped process.
880 if (referenced_ptes == -1)
881 return FOLIOREF_KEEP;
883 if (referenced_ptes) {
885 * All mapped folios start out with page table
886 * references from the instantiating fault, so we need
887 * to look twice if a mapped file/anon folio is used more
890 * Mark it and spare it for another trip around the
891 * inactive list. Another page table reference will
892 * lead to its activation.
894 * Note: the mark is set for activated folios as well
895 * so that recently deactivated but used folios are
898 folio_set_referenced(folio);
900 if (referenced_folio || referenced_ptes > 1)
901 return FOLIOREF_ACTIVATE;
904 * Activate file-backed executable folios after first usage.
906 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
907 return FOLIOREF_ACTIVATE;
909 return FOLIOREF_KEEP;
912 /* Reclaim if clean, defer dirty folios to writeback */
913 if (referenced_folio && folio_is_file_lru(folio))
914 return FOLIOREF_RECLAIM_CLEAN;
916 return FOLIOREF_RECLAIM;
919 /* Check if a folio is dirty or under writeback */
920 static void folio_check_dirty_writeback(struct folio *folio,
921 bool *dirty, bool *writeback)
923 struct address_space *mapping;
926 * Anonymous folios are not handled by flushers and must be written
927 * from reclaim context. Do not stall reclaim based on them.
928 * MADV_FREE anonymous folios are put into inactive file list too.
929 * They could be mistakenly treated as file lru. So further anon
932 if (!folio_is_file_lru(folio) ||
933 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
939 /* By default assume that the folio flags are accurate */
940 *dirty = folio_test_dirty(folio);
941 *writeback = folio_test_writeback(folio);
943 /* Verify dirty/writeback state if the filesystem supports it */
944 if (!folio_test_private(folio))
947 mapping = folio_mapping(folio);
948 if (mapping && mapping->a_ops->is_dirty_writeback)
949 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
952 struct folio *alloc_migrate_folio(struct folio *src, unsigned long private)
955 nodemask_t *allowed_mask;
956 struct migration_target_control *mtc;
958 mtc = (struct migration_target_control *)private;
960 allowed_mask = mtc->nmask;
962 * make sure we allocate from the target node first also trying to
963 * demote or reclaim pages from the target node via kswapd if we are
964 * low on free memory on target node. If we don't do this and if
965 * we have free memory on the slower(lower) memtier, we would start
966 * allocating pages from slower(lower) memory tiers without even forcing
967 * a demotion of cold pages from the target memtier. This can result
968 * in the kernel placing hot pages in slower(lower) memory tiers.
971 mtc->gfp_mask |= __GFP_THISNODE;
972 dst = alloc_migration_target(src, (unsigned long)mtc);
976 mtc->gfp_mask &= ~__GFP_THISNODE;
977 mtc->nmask = allowed_mask;
979 return alloc_migration_target(src, (unsigned long)mtc);
983 * Take folios on @demote_folios and attempt to demote them to another node.
984 * Folios which are not demoted are left on @demote_folios.
986 static unsigned int demote_folio_list(struct list_head *demote_folios,
987 struct pglist_data *pgdat)
989 int target_nid = next_demotion_node(pgdat->node_id);
990 unsigned int nr_succeeded;
991 nodemask_t allowed_mask;
993 struct migration_target_control mtc = {
995 * Allocate from 'node', or fail quickly and quietly.
996 * When this happens, 'page' will likely just be discarded
997 * instead of migrated.
999 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | __GFP_NOWARN |
1000 __GFP_NOMEMALLOC | GFP_NOWAIT,
1002 .nmask = &allowed_mask,
1003 .reason = MR_DEMOTION,
1006 if (list_empty(demote_folios))
1009 if (target_nid == NUMA_NO_NODE)
1012 node_get_allowed_targets(pgdat, &allowed_mask);
1014 /* Demotion ignores all cpuset and mempolicy settings */
1015 migrate_pages(demote_folios, alloc_migrate_folio, NULL,
1016 (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION,
1019 return nr_succeeded;
1022 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1024 if (gfp_mask & __GFP_FS)
1026 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1029 * We can "enter_fs" for swap-cache with only __GFP_IO
1030 * providing this isn't SWP_FS_OPS.
1031 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1032 * but that will never affect SWP_FS_OPS, so the data_race
1035 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1039 * shrink_folio_list() returns the number of reclaimed pages
1041 static unsigned int shrink_folio_list(struct list_head *folio_list,
1042 struct pglist_data *pgdat, struct scan_control *sc,
1043 struct reclaim_stat *stat, bool ignore_references)
1045 struct folio_batch free_folios;
1046 LIST_HEAD(ret_folios);
1047 LIST_HEAD(demote_folios);
1048 unsigned int nr_reclaimed = 0;
1049 unsigned int pgactivate = 0;
1050 bool do_demote_pass;
1051 struct swap_iocb *plug = NULL;
1053 folio_batch_init(&free_folios);
1054 memset(stat, 0, sizeof(*stat));
1056 do_demote_pass = can_demote(pgdat->node_id, sc);
1059 while (!list_empty(folio_list)) {
1060 struct address_space *mapping;
1061 struct folio *folio;
1062 enum folio_references references = FOLIOREF_RECLAIM;
1063 bool dirty, writeback;
1064 unsigned int nr_pages;
1068 folio = lru_to_folio(folio_list);
1069 list_del(&folio->lru);
1071 if (!folio_trylock(folio))
1074 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1076 nr_pages = folio_nr_pages(folio);
1078 /* Account the number of base pages */
1079 sc->nr_scanned += nr_pages;
1081 if (unlikely(!folio_evictable(folio)))
1082 goto activate_locked;
1084 if (!sc->may_unmap && folio_mapped(folio))
1087 /* folio_update_gen() tried to promote this page? */
1088 if (lru_gen_enabled() && !ignore_references &&
1089 folio_mapped(folio) && folio_test_referenced(folio))
1093 * The number of dirty pages determines if a node is marked
1094 * reclaim_congested. kswapd will stall and start writing
1095 * folios if the tail of the LRU is all dirty unqueued folios.
1097 folio_check_dirty_writeback(folio, &dirty, &writeback);
1098 if (dirty || writeback)
1099 stat->nr_dirty += nr_pages;
1101 if (dirty && !writeback)
1102 stat->nr_unqueued_dirty += nr_pages;
1105 * Treat this folio as congested if folios are cycling
1106 * through the LRU so quickly that the folios marked
1107 * for immediate reclaim are making it to the end of
1108 * the LRU a second time.
1110 if (writeback && folio_test_reclaim(folio))
1111 stat->nr_congested += nr_pages;
1114 * If a folio at the tail of the LRU is under writeback, there
1115 * are three cases to consider.
1117 * 1) If reclaim is encountering an excessive number
1118 * of folios under writeback and this folio has both
1119 * the writeback and reclaim flags set, then it
1120 * indicates that folios are being queued for I/O but
1121 * are being recycled through the LRU before the I/O
1122 * can complete. Waiting on the folio itself risks an
1123 * indefinite stall if it is impossible to writeback
1124 * the folio due to I/O error or disconnected storage
1125 * so instead note that the LRU is being scanned too
1126 * quickly and the caller can stall after the folio
1127 * list has been processed.
1129 * 2) Global or new memcg reclaim encounters a folio that is
1130 * not marked for immediate reclaim, or the caller does not
1131 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1132 * not to fs). In this case mark the folio for immediate
1133 * reclaim and continue scanning.
1135 * Require may_enter_fs() because we would wait on fs, which
1136 * may not have submitted I/O yet. And the loop driver might
1137 * enter reclaim, and deadlock if it waits on a folio for
1138 * which it is needed to do the write (loop masks off
1139 * __GFP_IO|__GFP_FS for this reason); but more thought
1140 * would probably show more reasons.
1142 * 3) Legacy memcg encounters a folio that already has the
1143 * reclaim flag set. memcg does not have any dirty folio
1144 * throttling so we could easily OOM just because too many
1145 * folios are in writeback and there is nothing else to
1146 * reclaim. Wait for the writeback to complete.
1148 * In cases 1) and 2) we activate the folios to get them out of
1149 * the way while we continue scanning for clean folios on the
1150 * inactive list and refilling from the active list. The
1151 * observation here is that waiting for disk writes is more
1152 * expensive than potentially causing reloads down the line.
1153 * Since they're marked for immediate reclaim, they won't put
1154 * memory pressure on the cache working set any longer than it
1155 * takes to write them to disk.
1157 if (folio_test_writeback(folio)) {
1159 if (current_is_kswapd() &&
1160 folio_test_reclaim(folio) &&
1161 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1162 stat->nr_immediate += nr_pages;
1163 goto activate_locked;
1166 } else if (writeback_throttling_sane(sc) ||
1167 !folio_test_reclaim(folio) ||
1168 !may_enter_fs(folio, sc->gfp_mask)) {
1170 * This is slightly racy -
1171 * folio_end_writeback() might have
1172 * just cleared the reclaim flag, then
1173 * setting the reclaim flag here ends up
1174 * interpreted as the readahead flag - but
1175 * that does not matter enough to care.
1176 * What we do want is for this folio to
1177 * have the reclaim flag set next time
1178 * memcg reclaim reaches the tests above,
1179 * so it will then wait for writeback to
1180 * avoid OOM; and it's also appropriate
1181 * in global reclaim.
1183 folio_set_reclaim(folio);
1184 stat->nr_writeback += nr_pages;
1185 goto activate_locked;
1189 folio_unlock(folio);
1190 folio_wait_writeback(folio);
1191 /* then go back and try same folio again */
1192 list_add_tail(&folio->lru, folio_list);
1197 if (!ignore_references)
1198 references = folio_check_references(folio, sc);
1200 switch (references) {
1201 case FOLIOREF_ACTIVATE:
1202 goto activate_locked;
1204 stat->nr_ref_keep += nr_pages;
1206 case FOLIOREF_RECLAIM:
1207 case FOLIOREF_RECLAIM_CLEAN:
1208 ; /* try to reclaim the folio below */
1212 * Before reclaiming the folio, try to relocate
1213 * its contents to another node.
1215 if (do_demote_pass &&
1216 (thp_migration_supported() || !folio_test_large(folio))) {
1217 list_add(&folio->lru, &demote_folios);
1218 folio_unlock(folio);
1223 * Anonymous process memory has backing store?
1224 * Try to allocate it some swap space here.
1225 * Lazyfree folio could be freed directly
1227 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1228 if (!folio_test_swapcache(folio)) {
1229 if (!(sc->gfp_mask & __GFP_IO))
1231 if (folio_maybe_dma_pinned(folio))
1233 if (folio_test_large(folio)) {
1234 /* cannot split folio, skip it */
1235 if (!can_split_folio(folio, 1, NULL))
1236 goto activate_locked;
1238 * Split partially mapped folios right away.
1239 * We can free the unmapped pages without IO.
1241 if (data_race(!list_empty(&folio->_deferred_list) &&
1242 folio_test_partially_mapped(folio)) &&
1243 split_folio_to_list(folio, folio_list))
1244 goto activate_locked;
1246 if (!add_to_swap(folio)) {
1247 int __maybe_unused order = folio_order(folio);
1249 if (!folio_test_large(folio))
1250 goto activate_locked_split;
1251 /* Fallback to swap normal pages */
1252 if (split_folio_to_list(folio, folio_list))
1253 goto activate_locked;
1254 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1255 if (nr_pages >= HPAGE_PMD_NR) {
1256 count_memcg_folio_events(folio,
1257 THP_SWPOUT_FALLBACK, 1);
1258 count_vm_event(THP_SWPOUT_FALLBACK);
1260 count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
1262 if (!add_to_swap(folio))
1263 goto activate_locked_split;
1269 * If the folio was split above, the tail pages will make
1270 * their own pass through this function and be accounted
1273 if ((nr_pages > 1) && !folio_test_large(folio)) {
1274 sc->nr_scanned -= (nr_pages - 1);
1279 * The folio is mapped into the page tables of one or more
1280 * processes. Try to unmap it here.
1282 if (folio_mapped(folio)) {
1283 enum ttu_flags flags = TTU_BATCH_FLUSH;
1284 bool was_swapbacked = folio_test_swapbacked(folio);
1286 if (folio_test_pmd_mappable(folio))
1287 flags |= TTU_SPLIT_HUGE_PMD;
1289 * Without TTU_SYNC, try_to_unmap will only begin to
1290 * hold PTL from the first present PTE within a large
1291 * folio. Some initial PTEs might be skipped due to
1292 * races with parallel PTE writes in which PTEs can be
1293 * cleared temporarily before being written new present
1294 * values. This will lead to a large folio is still
1295 * mapped while some subpages have been partially
1296 * unmapped after try_to_unmap; TTU_SYNC helps
1297 * try_to_unmap acquire PTL from the first PTE,
1298 * eliminating the influence of temporary PTE values.
1300 if (folio_test_large(folio))
1303 try_to_unmap(folio, flags);
1304 if (folio_mapped(folio)) {
1305 stat->nr_unmap_fail += nr_pages;
1306 if (!was_swapbacked &&
1307 folio_test_swapbacked(folio))
1308 stat->nr_lazyfree_fail += nr_pages;
1309 goto activate_locked;
1314 * Folio is unmapped now so it cannot be newly pinned anymore.
1315 * No point in trying to reclaim folio if it is pinned.
1316 * Furthermore we don't want to reclaim underlying fs metadata
1317 * if the folio is pinned and thus potentially modified by the
1318 * pinning process as that may upset the filesystem.
1320 if (folio_maybe_dma_pinned(folio))
1321 goto activate_locked;
1323 mapping = folio_mapping(folio);
1324 if (folio_test_dirty(folio)) {
1326 * Only kswapd can writeback filesystem folios
1327 * to avoid risk of stack overflow. But avoid
1328 * injecting inefficient single-folio I/O into
1329 * flusher writeback as much as possible: only
1330 * write folios when we've encountered many
1331 * dirty folios, and when we've already scanned
1332 * the rest of the LRU for clean folios and see
1333 * the same dirty folios again (with the reclaim
1336 if (folio_is_file_lru(folio) &&
1337 (!current_is_kswapd() ||
1338 !folio_test_reclaim(folio) ||
1339 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1341 * Immediately reclaim when written back.
1342 * Similar in principle to folio_deactivate()
1343 * except we already have the folio isolated
1344 * and know it's dirty
1346 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1348 folio_set_reclaim(folio);
1350 goto activate_locked;
1353 if (references == FOLIOREF_RECLAIM_CLEAN)
1355 if (!may_enter_fs(folio, sc->gfp_mask))
1357 if (!sc->may_writepage)
1361 * Folio is dirty. Flush the TLB if a writable entry
1362 * potentially exists to avoid CPU writes after I/O
1363 * starts and then write it out here.
1365 try_to_unmap_flush_dirty();
1366 switch (pageout(folio, mapping, &plug, folio_list)) {
1371 * If shmem folio is split when writeback to swap,
1372 * the tail pages will make their own pass through
1373 * this function and be accounted then.
1375 if (nr_pages > 1 && !folio_test_large(folio)) {
1376 sc->nr_scanned -= (nr_pages - 1);
1379 goto activate_locked;
1381 if (nr_pages > 1 && !folio_test_large(folio)) {
1382 sc->nr_scanned -= (nr_pages - 1);
1385 stat->nr_pageout += nr_pages;
1387 if (folio_test_writeback(folio))
1389 if (folio_test_dirty(folio))
1393 * A synchronous write - probably a ramdisk. Go
1394 * ahead and try to reclaim the folio.
1396 if (!folio_trylock(folio))
1398 if (folio_test_dirty(folio) ||
1399 folio_test_writeback(folio))
1401 mapping = folio_mapping(folio);
1404 ; /* try to free the folio below */
1409 * If the folio has buffers, try to free the buffer
1410 * mappings associated with this folio. If we succeed
1411 * we try to free the folio as well.
1413 * We do this even if the folio is dirty.
1414 * filemap_release_folio() does not perform I/O, but it
1415 * is possible for a folio to have the dirty flag set,
1416 * but it is actually clean (all its buffers are clean).
1417 * This happens if the buffers were written out directly,
1418 * with submit_bh(). ext3 will do this, as well as
1419 * the blockdev mapping. filemap_release_folio() will
1420 * discover that cleanness and will drop the buffers
1421 * and mark the folio clean - it can be freed.
1423 * Rarely, folios can have buffers and no ->mapping.
1424 * These are the folios which were not successfully
1425 * invalidated in truncate_cleanup_folio(). We try to
1426 * drop those buffers here and if that worked, and the
1427 * folio is no longer mapped into process address space
1428 * (refcount == 1) it can be freed. Otherwise, leave
1429 * the folio on the LRU so it is swappable.
1431 if (folio_needs_release(folio)) {
1432 if (!filemap_release_folio(folio, sc->gfp_mask))
1433 goto activate_locked;
1434 if (!mapping && folio_ref_count(folio) == 1) {
1435 folio_unlock(folio);
1436 if (folio_put_testzero(folio))
1440 * rare race with speculative reference.
1441 * the speculative reference will free
1442 * this folio shortly, so we may
1443 * increment nr_reclaimed here (and
1444 * leave it off the LRU).
1446 nr_reclaimed += nr_pages;
1452 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1453 /* follow __remove_mapping for reference */
1454 if (!folio_ref_freeze(folio, 1))
1457 * The folio has only one reference left, which is
1458 * from the isolation. After the caller puts the
1459 * folio back on the lru and drops the reference, the
1460 * folio will be freed anyway. It doesn't matter
1461 * which lru it goes on. So we don't bother checking
1462 * the dirty flag here.
1464 count_vm_events(PGLAZYFREED, nr_pages);
1465 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
1466 } else if (!mapping || !__remove_mapping(mapping, folio, true,
1467 sc->target_mem_cgroup))
1470 folio_unlock(folio);
1473 * Folio may get swapped out as a whole, need to account
1476 nr_reclaimed += nr_pages;
1478 folio_undo_large_rmappable(folio);
1479 if (folio_batch_add(&free_folios, folio) == 0) {
1480 mem_cgroup_uncharge_folios(&free_folios);
1481 try_to_unmap_flush();
1482 free_unref_folios(&free_folios);
1486 activate_locked_split:
1488 * The tail pages that are failed to add into swap cache
1489 * reach here. Fixup nr_scanned and nr_pages.
1492 sc->nr_scanned -= (nr_pages - 1);
1496 /* Not a candidate for swapping, so reclaim swap space. */
1497 if (folio_test_swapcache(folio) &&
1498 (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
1499 folio_free_swap(folio);
1500 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1501 if (!folio_test_mlocked(folio)) {
1502 int type = folio_is_file_lru(folio);
1503 folio_set_active(folio);
1504 stat->nr_activate[type] += nr_pages;
1505 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
1508 folio_unlock(folio);
1510 list_add(&folio->lru, &ret_folios);
1511 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
1512 folio_test_unevictable(folio), folio);
1514 /* 'folio_list' is always empty here */
1516 /* Migrate folios selected for demotion */
1517 stat->nr_demoted = demote_folio_list(&demote_folios, pgdat);
1518 nr_reclaimed += stat->nr_demoted;
1519 /* Folios that could not be demoted are still in @demote_folios */
1520 if (!list_empty(&demote_folios)) {
1521 /* Folios which weren't demoted go back on @folio_list */
1522 list_splice_init(&demote_folios, folio_list);
1525 * goto retry to reclaim the undemoted folios in folio_list if
1528 * Reclaiming directly from top tier nodes is not often desired
1529 * due to it breaking the LRU ordering: in general memory
1530 * should be reclaimed from lower tier nodes and demoted from
1533 * However, disabling reclaim from top tier nodes entirely
1534 * would cause ooms in edge scenarios where lower tier memory
1535 * is unreclaimable for whatever reason, eg memory being
1536 * mlocked or too hot to reclaim. We can disable reclaim
1537 * from top tier nodes in proactive reclaim though as that is
1538 * not real memory pressure.
1540 if (!sc->proactive) {
1541 do_demote_pass = false;
1546 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1548 mem_cgroup_uncharge_folios(&free_folios);
1549 try_to_unmap_flush();
1550 free_unref_folios(&free_folios);
1552 list_splice(&ret_folios, folio_list);
1553 count_vm_events(PGACTIVATE, pgactivate);
1556 swap_write_unplug(plug);
1557 return nr_reclaimed;
1560 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1561 struct list_head *folio_list)
1563 struct scan_control sc = {
1564 .gfp_mask = GFP_KERNEL,
1567 struct reclaim_stat stat;
1568 unsigned int nr_reclaimed;
1569 struct folio *folio, *next;
1570 LIST_HEAD(clean_folios);
1571 unsigned int noreclaim_flag;
1573 list_for_each_entry_safe(folio, next, folio_list, lru) {
1574 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
1575 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
1576 !folio_test_unevictable(folio)) {
1577 folio_clear_active(folio);
1578 list_move(&folio->lru, &clean_folios);
1583 * We should be safe here since we are only dealing with file pages and
1584 * we are not kswapd and therefore cannot write dirty file pages. But
1585 * call memalloc_noreclaim_save() anyway, just in case these conditions
1586 * change in the future.
1588 noreclaim_flag = memalloc_noreclaim_save();
1589 nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
1591 memalloc_noreclaim_restore(noreclaim_flag);
1593 list_splice(&clean_folios, folio_list);
1594 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1595 -(long)nr_reclaimed);
1597 * Since lazyfree pages are isolated from file LRU from the beginning,
1598 * they will rotate back to anonymous LRU in the end if it failed to
1599 * discard so isolated count will be mismatched.
1600 * Compensate the isolated count for both LRU lists.
1602 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1603 stat.nr_lazyfree_fail);
1604 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1605 -(long)stat.nr_lazyfree_fail);
1606 return nr_reclaimed;
1610 * Update LRU sizes after isolating pages. The LRU size updates must
1611 * be complete before mem_cgroup_update_lru_size due to a sanity check.
1613 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1614 enum lru_list lru, unsigned long *nr_zone_taken)
1618 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1619 if (!nr_zone_taken[zid])
1622 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1628 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1630 * lruvec->lru_lock is heavily contended. Some of the functions that
1631 * shrink the lists perform better by taking out a batch of pages
1632 * and working on them outside the LRU lock.
1634 * For pagecache intensive workloads, this function is the hottest
1635 * spot in the kernel (apart from copy_*_user functions).
1637 * Lru_lock must be held before calling this function.
1639 * @nr_to_scan: The number of eligible pages to look through on the list.
1640 * @lruvec: The LRU vector to pull pages from.
1641 * @dst: The temp list to put pages on to.
1642 * @nr_scanned: The number of pages that were scanned.
1643 * @sc: The scan_control struct for this reclaim session
1644 * @lru: LRU list id for isolating
1646 * returns how many pages were moved onto *@dst.
1648 static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
1649 struct lruvec *lruvec, struct list_head *dst,
1650 unsigned long *nr_scanned, struct scan_control *sc,
1653 struct list_head *src = &lruvec->lists[lru];
1654 unsigned long nr_taken = 0;
1655 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1656 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1657 unsigned long skipped = 0;
1658 unsigned long scan, total_scan, nr_pages;
1659 LIST_HEAD(folios_skipped);
1663 while (scan < nr_to_scan && !list_empty(src)) {
1664 struct list_head *move_to = src;
1665 struct folio *folio;
1667 folio = lru_to_folio(src);
1668 prefetchw_prev_lru_folio(folio, src, flags);
1670 nr_pages = folio_nr_pages(folio);
1671 total_scan += nr_pages;
1673 if (folio_zonenum(folio) > sc->reclaim_idx) {
1674 nr_skipped[folio_zonenum(folio)] += nr_pages;
1675 move_to = &folios_skipped;
1680 * Do not count skipped folios because that makes the function
1681 * return with no isolated folios if the LRU mostly contains
1682 * ineligible folios. This causes the VM to not reclaim any
1683 * folios, triggering a premature OOM.
1684 * Account all pages in a folio.
1688 if (!folio_test_lru(folio))
1690 if (!sc->may_unmap && folio_mapped(folio))
1694 * Be careful not to clear the lru flag until after we're
1695 * sure the folio is not being freed elsewhere -- the
1696 * folio release code relies on it.
1698 if (unlikely(!folio_try_get(folio)))
1701 if (!folio_test_clear_lru(folio)) {
1702 /* Another thread is already isolating this folio */
1707 nr_taken += nr_pages;
1708 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
1711 list_move(&folio->lru, move_to);
1715 * Splice any skipped folios to the start of the LRU list. Note that
1716 * this disrupts the LRU order when reclaiming for lower zones but
1717 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1718 * scanning would soon rescan the same folios to skip and waste lots
1721 if (!list_empty(&folios_skipped)) {
1724 list_splice(&folios_skipped, src);
1725 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1726 if (!nr_skipped[zid])
1729 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1730 skipped += nr_skipped[zid];
1733 *nr_scanned = total_scan;
1734 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1735 total_scan, skipped, nr_taken, lru);
1736 update_lru_sizes(lruvec, lru, nr_zone_taken);
1741 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
1742 * @folio: Folio to isolate from its LRU list.
1744 * Isolate a @folio from an LRU list and adjust the vmstat statistic
1745 * corresponding to whatever LRU list the folio was on.
1747 * The folio will have its LRU flag cleared. If it was found on the
1748 * active list, it will have the Active flag set. If it was found on the
1749 * unevictable list, it will have the Unevictable flag set. These flags
1750 * may need to be cleared by the caller before letting the page go.
1754 * (1) Must be called with an elevated refcount on the folio. This is a
1755 * fundamental difference from isolate_lru_folios() (which is called
1756 * without a stable reference).
1757 * (2) The lru_lock must not be held.
1758 * (3) Interrupts must be enabled.
1760 * Return: true if the folio was removed from an LRU list.
1761 * false if the folio was not on an LRU list.
1763 bool folio_isolate_lru(struct folio *folio)
1767 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
1769 if (folio_test_clear_lru(folio)) {
1770 struct lruvec *lruvec;
1773 lruvec = folio_lruvec_lock_irq(folio);
1774 lruvec_del_folio(lruvec, folio);
1775 unlock_page_lruvec_irq(lruvec);
1783 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1784 * then get rescheduled. When there are massive number of tasks doing page
1785 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1786 * the LRU list will go small and be scanned faster than necessary, leading to
1787 * unnecessary swapping, thrashing and OOM.
1789 static bool too_many_isolated(struct pglist_data *pgdat, int file,
1790 struct scan_control *sc)
1792 unsigned long inactive, isolated;
1795 if (current_is_kswapd())
1798 if (!writeback_throttling_sane(sc))
1802 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1803 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1805 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1806 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
1810 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1811 * won't get blocked by normal direct-reclaimers, forming a circular
1814 if (gfp_has_io_fs(sc->gfp_mask))
1817 too_many = isolated > inactive;
1819 /* Wake up tasks throttled due to too_many_isolated. */
1821 wake_throttle_isolated(pgdat);
1827 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
1829 * Returns the number of pages moved to the given lruvec.
1831 static unsigned int move_folios_to_lru(struct lruvec *lruvec,
1832 struct list_head *list)
1834 int nr_pages, nr_moved = 0;
1835 struct folio_batch free_folios;
1837 folio_batch_init(&free_folios);
1838 while (!list_empty(list)) {
1839 struct folio *folio = lru_to_folio(list);
1841 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
1842 list_del(&folio->lru);
1843 if (unlikely(!folio_evictable(folio))) {
1844 spin_unlock_irq(&lruvec->lru_lock);
1845 folio_putback_lru(folio);
1846 spin_lock_irq(&lruvec->lru_lock);
1851 * The folio_set_lru needs to be kept here for list integrity.
1853 * #0 move_folios_to_lru #1 release_pages
1854 * if (!folio_put_testzero())
1855 * if (folio_put_testzero())
1856 * !lru //skip lru_lock
1858 * list_add(&folio->lru,)
1859 * list_add(&folio->lru,)
1861 folio_set_lru(folio);
1863 if (unlikely(folio_put_testzero(folio))) {
1864 __folio_clear_lru_flags(folio);
1866 folio_undo_large_rmappable(folio);
1867 if (folio_batch_add(&free_folios, folio) == 0) {
1868 spin_unlock_irq(&lruvec->lru_lock);
1869 mem_cgroup_uncharge_folios(&free_folios);
1870 free_unref_folios(&free_folios);
1871 spin_lock_irq(&lruvec->lru_lock);
1878 * All pages were isolated from the same lruvec (and isolation
1879 * inhibits memcg migration).
1881 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
1882 lruvec_add_folio(lruvec, folio);
1883 nr_pages = folio_nr_pages(folio);
1884 nr_moved += nr_pages;
1885 if (folio_test_active(folio))
1886 workingset_age_nonresident(lruvec, nr_pages);
1889 if (free_folios.nr) {
1890 spin_unlock_irq(&lruvec->lru_lock);
1891 mem_cgroup_uncharge_folios(&free_folios);
1892 free_unref_folios(&free_folios);
1893 spin_lock_irq(&lruvec->lru_lock);
1900 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
1901 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
1902 * we should not throttle. Otherwise it is safe to do so.
1904 static int current_may_throttle(void)
1906 return !(current->flags & PF_LOCAL_THROTTLE);
1910 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1911 * of reclaimed pages
1913 static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
1914 struct lruvec *lruvec, struct scan_control *sc,
1917 LIST_HEAD(folio_list);
1918 unsigned long nr_scanned;
1919 unsigned int nr_reclaimed = 0;
1920 unsigned long nr_taken;
1921 struct reclaim_stat stat;
1922 bool file = is_file_lru(lru);
1923 enum vm_event_item item;
1924 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1925 bool stalled = false;
1927 while (unlikely(too_many_isolated(pgdat, file, sc))) {
1931 /* wait a bit for the reclaimer. */
1933 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
1935 /* We are about to die and free our memory. Return now. */
1936 if (fatal_signal_pending(current))
1937 return SWAP_CLUSTER_MAX;
1942 spin_lock_irq(&lruvec->lru_lock);
1944 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
1945 &nr_scanned, sc, lru);
1947 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1948 item = PGSCAN_KSWAPD + reclaimer_offset();
1949 if (!cgroup_reclaim(sc))
1950 __count_vm_events(item, nr_scanned);
1951 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1952 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
1954 spin_unlock_irq(&lruvec->lru_lock);
1959 nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
1961 spin_lock_irq(&lruvec->lru_lock);
1962 move_folios_to_lru(lruvec, &folio_list);
1964 __mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(),
1966 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1967 item = PGSTEAL_KSWAPD + reclaimer_offset();
1968 if (!cgroup_reclaim(sc))
1969 __count_vm_events(item, nr_reclaimed);
1970 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1971 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
1972 spin_unlock_irq(&lruvec->lru_lock);
1974 lru_note_cost(lruvec, file, stat.nr_pageout, nr_scanned - nr_reclaimed);
1977 * If dirty folios are scanned that are not queued for IO, it
1978 * implies that flushers are not doing their job. This can
1979 * happen when memory pressure pushes dirty folios to the end of
1980 * the LRU before the dirty limits are breached and the dirty
1981 * data has expired. It can also happen when the proportion of
1982 * dirty folios grows not through writes but through memory
1983 * pressure reclaiming all the clean cache. And in some cases,
1984 * the flushers simply cannot keep up with the allocation
1985 * rate. Nudge the flusher threads in case they are asleep.
1987 if (stat.nr_unqueued_dirty == nr_taken) {
1988 wakeup_flusher_threads(WB_REASON_VMSCAN);
1990 * For cgroupv1 dirty throttling is achieved by waking up
1991 * the kernel flusher here and later waiting on folios
1992 * which are in writeback to finish (see shrink_folio_list()).
1994 * Flusher may not be able to issue writeback quickly
1995 * enough for cgroupv1 writeback throttling to work
1996 * on a large system.
1998 if (!writeback_throttling_sane(sc))
1999 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
2002 sc->nr.dirty += stat.nr_dirty;
2003 sc->nr.congested += stat.nr_congested;
2004 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2005 sc->nr.writeback += stat.nr_writeback;
2006 sc->nr.immediate += stat.nr_immediate;
2007 sc->nr.taken += nr_taken;
2009 sc->nr.file_taken += nr_taken;
2011 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2012 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2013 return nr_reclaimed;
2017 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2019 * We move them the other way if the folio is referenced by one or more
2022 * If the folios are mostly unmapped, the processing is fast and it is
2023 * appropriate to hold lru_lock across the whole operation. But if
2024 * the folios are mapped, the processing is slow (folio_referenced()), so
2025 * we should drop lru_lock around each folio. It's impossible to balance
2026 * this, so instead we remove the folios from the LRU while processing them.
2027 * It is safe to rely on the active flag against the non-LRU folios in here
2028 * because nobody will play with that bit on a non-LRU folio.
2030 * The downside is that we have to touch folio->_refcount against each folio.
2031 * But we had to alter folio->flags anyway.
2033 static void shrink_active_list(unsigned long nr_to_scan,
2034 struct lruvec *lruvec,
2035 struct scan_control *sc,
2038 unsigned long nr_taken;
2039 unsigned long nr_scanned;
2040 unsigned long vm_flags;
2041 LIST_HEAD(l_hold); /* The folios which were snipped off */
2042 LIST_HEAD(l_active);
2043 LIST_HEAD(l_inactive);
2044 unsigned nr_deactivate, nr_activate;
2045 unsigned nr_rotated = 0;
2046 bool file = is_file_lru(lru);
2047 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2051 spin_lock_irq(&lruvec->lru_lock);
2053 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
2054 &nr_scanned, sc, lru);
2056 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2058 if (!cgroup_reclaim(sc))
2059 __count_vm_events(PGREFILL, nr_scanned);
2060 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2062 spin_unlock_irq(&lruvec->lru_lock);
2064 while (!list_empty(&l_hold)) {
2065 struct folio *folio;
2068 folio = lru_to_folio(&l_hold);
2069 list_del(&folio->lru);
2071 if (unlikely(!folio_evictable(folio))) {
2072 folio_putback_lru(folio);
2076 if (unlikely(buffer_heads_over_limit)) {
2077 if (folio_needs_release(folio) &&
2078 folio_trylock(folio)) {
2079 filemap_release_folio(folio, 0);
2080 folio_unlock(folio);
2084 /* Referenced or rmap lock contention: rotate */
2085 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2088 * Identify referenced, file-backed active folios and
2089 * give them one more trip around the active list. So
2090 * that executable code get better chances to stay in
2091 * memory under moderate memory pressure. Anon folios
2092 * are not likely to be evicted by use-once streaming
2093 * IO, plus JVM can create lots of anon VM_EXEC folios,
2094 * so we ignore them here.
2096 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2097 nr_rotated += folio_nr_pages(folio);
2098 list_add(&folio->lru, &l_active);
2103 folio_clear_active(folio); /* we are de-activating */
2104 folio_set_workingset(folio);
2105 list_add(&folio->lru, &l_inactive);
2109 * Move folios back to the lru list.
2111 spin_lock_irq(&lruvec->lru_lock);
2113 nr_activate = move_folios_to_lru(lruvec, &l_active);
2114 nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
2116 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2117 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2119 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2120 spin_unlock_irq(&lruvec->lru_lock);
2123 lru_note_cost(lruvec, file, 0, nr_rotated);
2124 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2125 nr_deactivate, nr_rotated, sc->priority, file);
2128 static unsigned int reclaim_folio_list(struct list_head *folio_list,
2129 struct pglist_data *pgdat)
2131 struct reclaim_stat dummy_stat;
2132 unsigned int nr_reclaimed;
2133 struct folio *folio;
2134 struct scan_control sc = {
2135 .gfp_mask = GFP_KERNEL,
2142 nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_stat, true);
2143 while (!list_empty(folio_list)) {
2144 folio = lru_to_folio(folio_list);
2145 list_del(&folio->lru);
2146 folio_putback_lru(folio);
2149 return nr_reclaimed;
2152 unsigned long reclaim_pages(struct list_head *folio_list)
2155 unsigned int nr_reclaimed = 0;
2156 LIST_HEAD(node_folio_list);
2157 unsigned int noreclaim_flag;
2159 if (list_empty(folio_list))
2160 return nr_reclaimed;
2162 noreclaim_flag = memalloc_noreclaim_save();
2164 nid = folio_nid(lru_to_folio(folio_list));
2166 struct folio *folio = lru_to_folio(folio_list);
2168 if (nid == folio_nid(folio)) {
2169 folio_clear_active(folio);
2170 list_move(&folio->lru, &node_folio_list);
2174 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2175 nid = folio_nid(lru_to_folio(folio_list));
2176 } while (!list_empty(folio_list));
2178 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2180 memalloc_noreclaim_restore(noreclaim_flag);
2182 return nr_reclaimed;
2185 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2186 struct lruvec *lruvec, struct scan_control *sc)
2188 if (is_active_lru(lru)) {
2189 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2190 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2192 sc->skipped_deactivate = 1;
2196 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2200 * The inactive anon list should be small enough that the VM never has
2201 * to do too much work.
2203 * The inactive file list should be small enough to leave most memory
2204 * to the established workingset on the scan-resistant active list,
2205 * but large enough to avoid thrashing the aggregate readahead window.
2207 * Both inactive lists should also be large enough that each inactive
2208 * folio has a chance to be referenced again before it is reclaimed.
2210 * If that fails and refaulting is observed, the inactive list grows.
2212 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2213 * on this LRU, maintained by the pageout code. An inactive_ratio
2214 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2217 * memory ratio inactive
2218 * -------------------------------------
2227 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2229 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2230 unsigned long inactive, active;
2231 unsigned long inactive_ratio;
2234 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2235 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2237 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2239 inactive_ratio = int_sqrt(10 * gb);
2243 return inactive * inactive_ratio < active;
2253 static void prepare_scan_control(pg_data_t *pgdat, struct scan_control *sc)
2256 struct lruvec *target_lruvec;
2258 if (lru_gen_enabled())
2261 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2264 * Flush the memory cgroup stats in rate-limited way as we don't need
2265 * most accurate stats here. We may switch to regular stats flushing
2266 * in the future once it is cheap enough.
2268 mem_cgroup_flush_stats_ratelimited(sc->target_mem_cgroup);
2271 * Determine the scan balance between anon and file LRUs.
2273 spin_lock_irq(&target_lruvec->lru_lock);
2274 sc->anon_cost = target_lruvec->anon_cost;
2275 sc->file_cost = target_lruvec->file_cost;
2276 spin_unlock_irq(&target_lruvec->lru_lock);
2279 * Target desirable inactive:active list ratios for the anon
2280 * and file LRU lists.
2282 if (!sc->force_deactivate) {
2283 unsigned long refaults;
2286 * When refaults are being observed, it means a new
2287 * workingset is being established. Deactivate to get
2288 * rid of any stale active pages quickly.
2290 refaults = lruvec_page_state(target_lruvec,
2291 WORKINGSET_ACTIVATE_ANON);
2292 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2293 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2294 sc->may_deactivate |= DEACTIVATE_ANON;
2296 sc->may_deactivate &= ~DEACTIVATE_ANON;
2298 refaults = lruvec_page_state(target_lruvec,
2299 WORKINGSET_ACTIVATE_FILE);
2300 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2301 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2302 sc->may_deactivate |= DEACTIVATE_FILE;
2304 sc->may_deactivate &= ~DEACTIVATE_FILE;
2306 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2309 * If we have plenty of inactive file pages that aren't
2310 * thrashing, try to reclaim those first before touching
2313 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2314 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE) &&
2315 !sc->no_cache_trim_mode)
2316 sc->cache_trim_mode = 1;
2318 sc->cache_trim_mode = 0;
2321 * Prevent the reclaimer from falling into the cache trap: as
2322 * cache pages start out inactive, every cache fault will tip
2323 * the scan balance towards the file LRU. And as the file LRU
2324 * shrinks, so does the window for rotation from references.
2325 * This means we have a runaway feedback loop where a tiny
2326 * thrashing file LRU becomes infinitely more attractive than
2327 * anon pages. Try to detect this based on file LRU size.
2329 if (!cgroup_reclaim(sc)) {
2330 unsigned long total_high_wmark = 0;
2331 unsigned long free, anon;
2334 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2335 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2336 node_page_state(pgdat, NR_INACTIVE_FILE);
2338 for (z = 0; z < MAX_NR_ZONES; z++) {
2339 struct zone *zone = &pgdat->node_zones[z];
2341 if (!managed_zone(zone))
2344 total_high_wmark += high_wmark_pages(zone);
2348 * Consider anon: if that's low too, this isn't a
2349 * runaway file reclaim problem, but rather just
2350 * extreme pressure. Reclaim as per usual then.
2352 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2355 file + free <= total_high_wmark &&
2356 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2357 anon >> sc->priority;
2362 * Determine how aggressively the anon and file LRU lists should be
2365 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2366 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2368 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2371 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2372 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2373 unsigned long anon_cost, file_cost, total_cost;
2374 int swappiness = sc_swappiness(sc, memcg);
2375 u64 fraction[ANON_AND_FILE];
2376 u64 denominator = 0; /* gcc */
2377 enum scan_balance scan_balance;
2378 unsigned long ap, fp;
2381 /* If we have no swap space, do not bother scanning anon folios. */
2382 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2383 scan_balance = SCAN_FILE;
2388 * Global reclaim will swap to prevent OOM even with no
2389 * swappiness, but memcg users want to use this knob to
2390 * disable swapping for individual groups completely when
2391 * using the memory controller's swap limit feature would be
2394 if (cgroup_reclaim(sc) && !swappiness) {
2395 scan_balance = SCAN_FILE;
2400 * Do not apply any pressure balancing cleverness when the
2401 * system is close to OOM, scan both anon and file equally
2402 * (unless the swappiness setting disagrees with swapping).
2404 if (!sc->priority && swappiness) {
2405 scan_balance = SCAN_EQUAL;
2410 * If the system is almost out of file pages, force-scan anon.
2412 if (sc->file_is_tiny) {
2413 scan_balance = SCAN_ANON;
2418 * If there is enough inactive page cache, we do not reclaim
2419 * anything from the anonymous working right now.
2421 if (sc->cache_trim_mode) {
2422 scan_balance = SCAN_FILE;
2426 scan_balance = SCAN_FRACT;
2428 * Calculate the pressure balance between anon and file pages.
2430 * The amount of pressure we put on each LRU is inversely
2431 * proportional to the cost of reclaiming each list, as
2432 * determined by the share of pages that are refaulting, times
2433 * the relative IO cost of bringing back a swapped out
2434 * anonymous page vs reloading a filesystem page (swappiness).
2436 * Although we limit that influence to ensure no list gets
2437 * left behind completely: at least a third of the pressure is
2438 * applied, before swappiness.
2440 * With swappiness at 100, anon and file have equal IO cost.
2442 total_cost = sc->anon_cost + sc->file_cost;
2443 anon_cost = total_cost + sc->anon_cost;
2444 file_cost = total_cost + sc->file_cost;
2445 total_cost = anon_cost + file_cost;
2447 ap = swappiness * (total_cost + 1);
2448 ap /= anon_cost + 1;
2450 fp = (MAX_SWAPPINESS - swappiness) * (total_cost + 1);
2451 fp /= file_cost + 1;
2455 denominator = ap + fp;
2457 for_each_evictable_lru(lru) {
2458 bool file = is_file_lru(lru);
2459 unsigned long lruvec_size;
2460 unsigned long low, min;
2463 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2464 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2469 * Scale a cgroup's reclaim pressure by proportioning
2470 * its current usage to its memory.low or memory.min
2473 * This is important, as otherwise scanning aggression
2474 * becomes extremely binary -- from nothing as we
2475 * approach the memory protection threshold, to totally
2476 * nominal as we exceed it. This results in requiring
2477 * setting extremely liberal protection thresholds. It
2478 * also means we simply get no protection at all if we
2479 * set it too low, which is not ideal.
2481 * If there is any protection in place, we reduce scan
2482 * pressure by how much of the total memory used is
2483 * within protection thresholds.
2485 * There is one special case: in the first reclaim pass,
2486 * we skip over all groups that are within their low
2487 * protection. If that fails to reclaim enough pages to
2488 * satisfy the reclaim goal, we come back and override
2489 * the best-effort low protection. However, we still
2490 * ideally want to honor how well-behaved groups are in
2491 * that case instead of simply punishing them all
2492 * equally. As such, we reclaim them based on how much
2493 * memory they are using, reducing the scan pressure
2494 * again by how much of the total memory used is under
2497 unsigned long cgroup_size = mem_cgroup_size(memcg);
2498 unsigned long protection;
2500 /* memory.low scaling, make sure we retry before OOM */
2501 if (!sc->memcg_low_reclaim && low > min) {
2503 sc->memcg_low_skipped = 1;
2508 /* Avoid TOCTOU with earlier protection check */
2509 cgroup_size = max(cgroup_size, protection);
2511 scan = lruvec_size - lruvec_size * protection /
2515 * Minimally target SWAP_CLUSTER_MAX pages to keep
2516 * reclaim moving forwards, avoiding decrementing
2517 * sc->priority further than desirable.
2519 scan = max(scan, SWAP_CLUSTER_MAX);
2524 scan >>= sc->priority;
2527 * If the cgroup's already been deleted, make sure to
2528 * scrape out the remaining cache.
2530 if (!scan && !mem_cgroup_online(memcg))
2531 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2533 switch (scan_balance) {
2535 /* Scan lists relative to size */
2539 * Scan types proportional to swappiness and
2540 * their relative recent reclaim efficiency.
2541 * Make sure we don't miss the last page on
2542 * the offlined memory cgroups because of a
2545 scan = mem_cgroup_online(memcg) ?
2546 div64_u64(scan * fraction[file], denominator) :
2547 DIV64_U64_ROUND_UP(scan * fraction[file],
2552 /* Scan one type exclusively */
2553 if ((scan_balance == SCAN_FILE) != file)
2557 /* Look ma, no brain */
2566 * Anonymous LRU management is a waste if there is
2567 * ultimately no way to reclaim the memory.
2569 static bool can_age_anon_pages(struct pglist_data *pgdat,
2570 struct scan_control *sc)
2572 /* Aging the anon LRU is valuable if swap is present: */
2573 if (total_swap_pages > 0)
2576 /* Also valuable if anon pages can be demoted: */
2577 return can_demote(pgdat->node_id, sc);
2580 #ifdef CONFIG_LRU_GEN
2582 #ifdef CONFIG_LRU_GEN_ENABLED
2583 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2584 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2586 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2587 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2590 static bool should_walk_mmu(void)
2592 return arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK);
2595 static bool should_clear_pmd_young(void)
2597 return arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG);
2600 /******************************************************************************
2602 ******************************************************************************/
2604 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2606 #define DEFINE_MAX_SEQ(lruvec) \
2607 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2609 #define DEFINE_MIN_SEQ(lruvec) \
2610 unsigned long min_seq[ANON_AND_FILE] = { \
2611 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2612 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2615 #define for_each_gen_type_zone(gen, type, zone) \
2616 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2617 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2618 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2620 #define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2621 #define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2623 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2625 struct pglist_data *pgdat = NODE_DATA(nid);
2629 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2631 /* see the comment in mem_cgroup_lruvec() */
2633 lruvec->pgdat = pgdat;
2638 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2640 return &pgdat->__lruvec;
2643 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2645 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2646 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2651 if (!can_demote(pgdat->node_id, sc) &&
2652 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2655 return sc_swappiness(sc, memcg);
2658 static int get_nr_gens(struct lruvec *lruvec, int type)
2660 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2663 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2665 /* see the comment on lru_gen_folio */
2666 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2667 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2668 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2671 /******************************************************************************
2673 ******************************************************************************/
2676 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
2677 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
2678 * bits in a bitmap, k is the number of hash functions and n is the number of
2681 * Page table walkers use one of the two filters to reduce their search space.
2682 * To get rid of non-leaf entries that no longer have enough leaf entries, the
2683 * aging uses the double-buffering technique to flip to the other filter each
2684 * time it produces a new generation. For non-leaf entries that have enough
2685 * leaf entries, the aging carries them over to the next generation in
2686 * walk_pmd_range(); the eviction also report them when walking the rmap
2687 * in lru_gen_look_around().
2689 * For future optimizations:
2690 * 1. It's not necessary to keep both filters all the time. The spare one can be
2691 * freed after the RCU grace period and reallocated if needed again.
2692 * 2. And when reallocating, it's worth scaling its size according to the number
2693 * of inserted entries in the other filter, to reduce the memory overhead on
2694 * small systems and false positives on large systems.
2695 * 3. Jenkins' hash function is an alternative to Knuth's.
2697 #define BLOOM_FILTER_SHIFT 15
2699 static inline int filter_gen_from_seq(unsigned long seq)
2701 return seq % NR_BLOOM_FILTERS;
2704 static void get_item_key(void *item, int *key)
2706 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
2708 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
2710 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
2711 key[1] = hash >> BLOOM_FILTER_SHIFT;
2714 static bool test_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq,
2718 unsigned long *filter;
2719 int gen = filter_gen_from_seq(seq);
2721 filter = READ_ONCE(mm_state->filters[gen]);
2725 get_item_key(item, key);
2727 return test_bit(key[0], filter) && test_bit(key[1], filter);
2730 static void update_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq,
2734 unsigned long *filter;
2735 int gen = filter_gen_from_seq(seq);
2737 filter = READ_ONCE(mm_state->filters[gen]);
2741 get_item_key(item, key);
2743 if (!test_bit(key[0], filter))
2744 set_bit(key[0], filter);
2745 if (!test_bit(key[1], filter))
2746 set_bit(key[1], filter);
2749 static void reset_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq)
2751 unsigned long *filter;
2752 int gen = filter_gen_from_seq(seq);
2754 filter = mm_state->filters[gen];
2756 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
2760 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
2761 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
2762 WRITE_ONCE(mm_state->filters[gen], filter);
2765 /******************************************************************************
2767 ******************************************************************************/
2769 #ifdef CONFIG_LRU_GEN_WALKS_MMU
2771 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2773 static struct lru_gen_mm_list mm_list = {
2774 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2775 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2780 return &memcg->mm_list;
2782 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2787 static struct lru_gen_mm_state *get_mm_state(struct lruvec *lruvec)
2789 return &lruvec->mm_state;
2792 static struct mm_struct *get_next_mm(struct lru_gen_mm_walk *walk)
2795 struct mm_struct *mm;
2796 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
2797 struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec);
2799 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
2800 key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
2802 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
2805 clear_bit(key, &mm->lru_gen.bitmap);
2807 return mmget_not_zero(mm) ? mm : NULL;
2810 void lru_gen_add_mm(struct mm_struct *mm)
2813 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2814 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2816 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2818 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2819 mm->lru_gen.memcg = memcg;
2821 spin_lock(&mm_list->lock);
2823 for_each_node_state(nid, N_MEMORY) {
2824 struct lruvec *lruvec = get_lruvec(memcg, nid);
2825 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2827 /* the first addition since the last iteration */
2828 if (mm_state->tail == &mm_list->fifo)
2829 mm_state->tail = &mm->lru_gen.list;
2832 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
2834 spin_unlock(&mm_list->lock);
2837 void lru_gen_del_mm(struct mm_struct *mm)
2840 struct lru_gen_mm_list *mm_list;
2841 struct mem_cgroup *memcg = NULL;
2843 if (list_empty(&mm->lru_gen.list))
2847 memcg = mm->lru_gen.memcg;
2849 mm_list = get_mm_list(memcg);
2851 spin_lock(&mm_list->lock);
2853 for_each_node(nid) {
2854 struct lruvec *lruvec = get_lruvec(memcg, nid);
2855 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2857 /* where the current iteration continues after */
2858 if (mm_state->head == &mm->lru_gen.list)
2859 mm_state->head = mm_state->head->prev;
2861 /* where the last iteration ended before */
2862 if (mm_state->tail == &mm->lru_gen.list)
2863 mm_state->tail = mm_state->tail->next;
2866 list_del_init(&mm->lru_gen.list);
2868 spin_unlock(&mm_list->lock);
2871 mem_cgroup_put(mm->lru_gen.memcg);
2872 mm->lru_gen.memcg = NULL;
2877 void lru_gen_migrate_mm(struct mm_struct *mm)
2879 struct mem_cgroup *memcg;
2880 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
2882 VM_WARN_ON_ONCE(task->mm != mm);
2883 lockdep_assert_held(&task->alloc_lock);
2885 /* for mm_update_next_owner() */
2886 if (mem_cgroup_disabled())
2889 /* migration can happen before addition */
2890 if (!mm->lru_gen.memcg)
2894 memcg = mem_cgroup_from_task(task);
2896 if (memcg == mm->lru_gen.memcg)
2899 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
2906 #else /* !CONFIG_LRU_GEN_WALKS_MMU */
2908 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2913 static struct lru_gen_mm_state *get_mm_state(struct lruvec *lruvec)
2918 static struct mm_struct *get_next_mm(struct lru_gen_mm_walk *walk)
2925 static void reset_mm_stats(struct lru_gen_mm_walk *walk, bool last)
2929 struct lruvec *lruvec = walk->lruvec;
2930 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2932 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
2934 hist = lru_hist_from_seq(walk->seq);
2936 for (i = 0; i < NR_MM_STATS; i++) {
2937 WRITE_ONCE(mm_state->stats[hist][i],
2938 mm_state->stats[hist][i] + walk->mm_stats[i]);
2939 walk->mm_stats[i] = 0;
2942 if (NR_HIST_GENS > 1 && last) {
2943 hist = lru_hist_from_seq(walk->seq + 1);
2945 for (i = 0; i < NR_MM_STATS; i++)
2946 WRITE_ONCE(mm_state->stats[hist][i], 0);
2950 static bool iterate_mm_list(struct lru_gen_mm_walk *walk, struct mm_struct **iter)
2954 struct mm_struct *mm = NULL;
2955 struct lruvec *lruvec = walk->lruvec;
2956 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2957 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2958 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2961 * mm_state->seq is incremented after each iteration of mm_list. There
2962 * are three interesting cases for this page table walker:
2963 * 1. It tries to start a new iteration with a stale max_seq: there is
2964 * nothing left to do.
2965 * 2. It started the next iteration: it needs to reset the Bloom filter
2966 * so that a fresh set of PTE tables can be recorded.
2967 * 3. It ended the current iteration: it needs to reset the mm stats
2968 * counters and tell its caller to increment max_seq.
2970 spin_lock(&mm_list->lock);
2972 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->seq);
2974 if (walk->seq <= mm_state->seq)
2977 if (!mm_state->head)
2978 mm_state->head = &mm_list->fifo;
2980 if (mm_state->head == &mm_list->fifo)
2984 mm_state->head = mm_state->head->next;
2985 if (mm_state->head == &mm_list->fifo) {
2986 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
2991 /* force scan for those added after the last iteration */
2992 if (!mm_state->tail || mm_state->tail == mm_state->head) {
2993 mm_state->tail = mm_state->head->next;
2994 walk->force_scan = true;
2996 } while (!(mm = get_next_mm(walk)));
2999 reset_mm_stats(walk, last);
3001 spin_unlock(&mm_list->lock);
3004 reset_bloom_filter(mm_state, walk->seq + 1);
3014 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long seq)
3016 bool success = false;
3017 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3018 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3019 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
3021 spin_lock(&mm_list->lock);
3023 VM_WARN_ON_ONCE(mm_state->seq + 1 < seq);
3025 if (seq > mm_state->seq) {
3026 mm_state->head = NULL;
3027 mm_state->tail = NULL;
3028 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3032 spin_unlock(&mm_list->lock);
3037 /******************************************************************************
3039 ******************************************************************************/
3042 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3044 * The P term is refaulted/(evicted+protected) from a tier in the generation
3045 * currently being evicted; the I term is the exponential moving average of the
3046 * P term over the generations previously evicted, using the smoothing factor
3047 * 1/2; the D term isn't supported.
3049 * The setpoint (SP) is always the first tier of one type; the process variable
3050 * (PV) is either any tier of the other type or any other tier of the same
3053 * The error is the difference between the SP and the PV; the correction is to
3054 * turn off protection when SP>PV or turn on protection when SP<PV.
3056 * For future optimizations:
3057 * 1. The D term may discount the other two terms over time so that long-lived
3058 * generations can resist stale information.
3061 unsigned long refaulted;
3062 unsigned long total;
3066 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3067 struct ctrl_pos *pos)
3069 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3070 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3072 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3073 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3074 pos->total = lrugen->avg_total[type][tier] +
3075 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3077 pos->total += lrugen->protected[hist][type][tier - 1];
3081 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3084 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3085 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3086 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3088 lockdep_assert_held(&lruvec->lru_lock);
3090 if (!carryover && !clear)
3093 hist = lru_hist_from_seq(seq);
3095 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3099 sum = lrugen->avg_refaulted[type][tier] +
3100 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3101 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3103 sum = lrugen->avg_total[type][tier] +
3104 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3106 sum += lrugen->protected[hist][type][tier - 1];
3107 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3111 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3112 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3114 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3119 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3122 * Return true if the PV has a limited number of refaults or a lower
3123 * refaulted/total than the SP.
3125 return pv->refaulted < MIN_LRU_BATCH ||
3126 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3127 (sp->refaulted + 1) * pv->total * pv->gain;
3130 /******************************************************************************
3132 ******************************************************************************/
3134 /* promote pages accessed through page tables */
3135 static int folio_update_gen(struct folio *folio, int gen)
3137 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3139 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3140 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3143 /* lru_gen_del_folio() has isolated this page? */
3144 if (!(old_flags & LRU_GEN_MASK)) {
3145 /* for shrink_folio_list() */
3146 new_flags = old_flags | BIT(PG_referenced);
3150 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3151 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3152 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3154 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3157 /* protect pages accessed multiple times through file descriptors */
3158 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3160 int type = folio_is_file_lru(folio);
3161 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3162 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3163 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3165 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3168 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3169 /* folio_update_gen() has promoted this page? */
3170 if (new_gen >= 0 && new_gen != old_gen)
3173 new_gen = (old_gen + 1) % MAX_NR_GENS;
3175 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3176 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3177 /* for folio_end_writeback() */
3179 new_flags |= BIT(PG_reclaim);
3180 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3182 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3187 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3188 int old_gen, int new_gen)
3190 int type = folio_is_file_lru(folio);
3191 int zone = folio_zonenum(folio);
3192 int delta = folio_nr_pages(folio);
3194 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3195 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3199 walk->nr_pages[old_gen][type][zone] -= delta;
3200 walk->nr_pages[new_gen][type][zone] += delta;
3203 static void reset_batch_size(struct lru_gen_mm_walk *walk)
3205 int gen, type, zone;
3206 struct lruvec *lruvec = walk->lruvec;
3207 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3211 for_each_gen_type_zone(gen, type, zone) {
3212 enum lru_list lru = type * LRU_INACTIVE_FILE;
3213 int delta = walk->nr_pages[gen][type][zone];
3218 walk->nr_pages[gen][type][zone] = 0;
3219 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3220 lrugen->nr_pages[gen][type][zone] + delta);
3222 if (lru_gen_is_active(lruvec, gen))
3224 __update_lru_size(lruvec, lru, zone, delta);
3228 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3230 struct address_space *mapping;
3231 struct vm_area_struct *vma = args->vma;
3232 struct lru_gen_mm_walk *walk = args->private;
3234 if (!vma_is_accessible(vma))
3237 if (is_vm_hugetlb_page(vma))
3240 if (!vma_has_recency(vma))
3243 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
3246 if (vma == get_gate_vma(vma->vm_mm))
3249 if (vma_is_anonymous(vma))
3250 return !walk->can_swap;
3252 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3255 mapping = vma->vm_file->f_mapping;
3256 if (mapping_unevictable(mapping))
3259 if (shmem_mapping(mapping))
3260 return !walk->can_swap;
3262 /* to exclude special mappings like dax, etc. */
3263 return !mapping->a_ops->read_folio;
3267 * Some userspace memory allocators map many single-page VMAs. Instead of
3268 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3269 * table to reduce zigzags and improve cache performance.
3271 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3272 unsigned long *vm_start, unsigned long *vm_end)
3274 unsigned long start = round_up(*vm_end, size);
3275 unsigned long end = (start | ~mask) + 1;
3276 VMA_ITERATOR(vmi, args->mm, start);
3278 VM_WARN_ON_ONCE(mask & size);
3279 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3281 for_each_vma(vmi, args->vma) {
3282 if (end && end <= args->vma->vm_start)
3285 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
3288 *vm_start = max(start, args->vma->vm_start);
3289 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3297 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3299 unsigned long pfn = pte_pfn(pte);
3301 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3303 if (!pte_present(pte) || is_zero_pfn(pfn))
3306 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3309 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3315 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3317 unsigned long pfn = pmd_pfn(pmd);
3319 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3321 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3324 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3327 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3333 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3334 struct pglist_data *pgdat, bool can_swap)
3336 struct folio *folio;
3338 /* try to avoid unnecessary memory loads */
3339 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3342 folio = pfn_folio(pfn);
3343 if (folio_nid(folio) != pgdat->node_id)
3346 if (folio_memcg_rcu(folio) != memcg)
3349 /* file VMAs can contain anon pages from COW */
3350 if (!folio_is_file_lru(folio) && !can_swap)
3356 static bool suitable_to_scan(int total, int young)
3358 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3360 /* suitable if the average number of young PTEs per cacheline is >=1 */
3361 return young * n >= total;
3364 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3365 struct mm_walk *args)
3373 struct lru_gen_mm_walk *walk = args->private;
3374 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3375 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3376 DEFINE_MAX_SEQ(walk->lruvec);
3377 int old_gen, new_gen = lru_gen_from_seq(max_seq);
3379 pte = pte_offset_map_nolock(args->mm, pmd, start & PMD_MASK, &ptl);
3382 if (!spin_trylock(ptl)) {
3387 arch_enter_lazy_mmu_mode();
3389 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3391 struct folio *folio;
3392 pte_t ptent = ptep_get(pte + i);
3395 walk->mm_stats[MM_LEAF_TOTAL]++;
3397 pfn = get_pte_pfn(ptent, args->vma, addr);
3401 if (!pte_young(ptent)) {
3402 walk->mm_stats[MM_LEAF_OLD]++;
3406 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3410 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3411 VM_WARN_ON_ONCE(true);
3414 walk->mm_stats[MM_LEAF_YOUNG]++;
3416 if (pte_dirty(ptent) && !folio_test_dirty(folio) &&
3417 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3418 !folio_test_swapcache(folio)))
3419 folio_mark_dirty(folio);
3421 old_gen = folio_update_gen(folio, new_gen);
3422 if (old_gen >= 0 && old_gen != new_gen)
3423 update_batch_size(walk, folio, old_gen, new_gen);
3426 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3429 arch_leave_lazy_mmu_mode();
3430 pte_unmap_unlock(pte, ptl);
3432 return suitable_to_scan(total, young);
3435 static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
3436 struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
3441 struct lru_gen_mm_walk *walk = args->private;
3442 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3443 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3444 DEFINE_MAX_SEQ(walk->lruvec);
3445 int old_gen, new_gen = lru_gen_from_seq(max_seq);
3447 VM_WARN_ON_ONCE(pud_leaf(*pud));
3449 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3452 bitmap_zero(bitmap, MIN_LRU_BATCH);
3456 i = addr == -1 ? 0 : pmd_index(addr) - pmd_index(*first);
3457 if (i && i <= MIN_LRU_BATCH) {
3458 __set_bit(i - 1, bitmap);
3462 pmd = pmd_offset(pud, *first);
3464 ptl = pmd_lockptr(args->mm, pmd);
3465 if (!spin_trylock(ptl))
3468 arch_enter_lazy_mmu_mode();
3472 struct folio *folio;
3474 /* don't round down the first address */
3475 addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first;
3477 pfn = get_pmd_pfn(pmd[i], vma, addr);
3481 if (!pmd_trans_huge(pmd[i])) {
3482 if (!walk->force_scan && should_clear_pmd_young())
3483 pmdp_test_and_clear_young(vma, addr, pmd + i);
3487 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3491 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3494 walk->mm_stats[MM_LEAF_YOUNG]++;
3496 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
3497 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3498 !folio_test_swapcache(folio)))
3499 folio_mark_dirty(folio);
3501 old_gen = folio_update_gen(folio, new_gen);
3502 if (old_gen >= 0 && old_gen != new_gen)
3503 update_batch_size(walk, folio, old_gen, new_gen);
3505 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3506 } while (i <= MIN_LRU_BATCH);
3508 arch_leave_lazy_mmu_mode();
3514 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3515 struct mm_walk *args)
3521 struct vm_area_struct *vma;
3522 DECLARE_BITMAP(bitmap, MIN_LRU_BATCH);
3523 unsigned long first = -1;
3524 struct lru_gen_mm_walk *walk = args->private;
3525 struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec);
3527 VM_WARN_ON_ONCE(pud_leaf(*pud));
3530 * Finish an entire PMD in two passes: the first only reaches to PTE
3531 * tables to avoid taking the PMD lock; the second, if necessary, takes
3532 * the PMD lock to clear the accessed bit in PMD entries.
3534 pmd = pmd_offset(pud, start & PUD_MASK);
3536 /* walk_pte_range() may call get_next_vma() */
3538 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3539 pmd_t val = pmdp_get_lockless(pmd + i);
3541 next = pmd_addr_end(addr, end);
3543 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3544 walk->mm_stats[MM_LEAF_TOTAL]++;
3548 if (pmd_trans_huge(val)) {
3549 unsigned long pfn = pmd_pfn(val);
3550 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3552 walk->mm_stats[MM_LEAF_TOTAL]++;
3554 if (!pmd_young(val)) {
3555 walk->mm_stats[MM_LEAF_OLD]++;
3559 /* try to avoid unnecessary memory loads */
3560 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3563 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
3567 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3569 if (!walk->force_scan && should_clear_pmd_young()) {
3570 if (!pmd_young(val))
3573 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
3576 if (!walk->force_scan && !test_bloom_filter(mm_state, walk->seq, pmd + i))
3579 walk->mm_stats[MM_NONLEAF_FOUND]++;
3581 if (!walk_pte_range(&val, addr, next, args))
3584 walk->mm_stats[MM_NONLEAF_ADDED]++;
3586 /* carry over to the next generation */
3587 update_bloom_filter(mm_state, walk->seq + 1, pmd + i);
3590 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
3592 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3596 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3597 struct mm_walk *args)
3603 struct lru_gen_mm_walk *walk = args->private;
3605 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3607 pud = pud_offset(p4d, start & P4D_MASK);
3609 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3610 pud_t val = READ_ONCE(pud[i]);
3612 next = pud_addr_end(addr, end);
3614 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3617 walk_pmd_range(&val, addr, next, args);
3619 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3620 end = (addr | ~PUD_MASK) + 1;
3625 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3628 end = round_up(end, P4D_SIZE);
3630 if (!end || !args->vma)
3633 walk->next_addr = max(end, args->vma->vm_start);
3638 static void walk_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3640 static const struct mm_walk_ops mm_walk_ops = {
3641 .test_walk = should_skip_vma,
3642 .p4d_entry = walk_pud_range,
3643 .walk_lock = PGWALK_RDLOCK,
3647 struct lruvec *lruvec = walk->lruvec;
3648 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3650 walk->next_addr = FIRST_USER_ADDRESS;
3653 DEFINE_MAX_SEQ(lruvec);
3657 /* another thread might have called inc_max_seq() */
3658 if (walk->seq != max_seq)
3661 /* folio_update_gen() requires stable folio_memcg() */
3662 if (!mem_cgroup_trylock_pages(memcg))
3665 /* the caller might be holding the lock for write */
3666 if (mmap_read_trylock(mm)) {
3667 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3669 mmap_read_unlock(mm);
3672 mem_cgroup_unlock_pages();
3674 if (walk->batched) {
3675 spin_lock_irq(&lruvec->lru_lock);
3676 reset_batch_size(walk);
3677 spin_unlock_irq(&lruvec->lru_lock);
3681 } while (err == -EAGAIN);
3684 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
3686 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3688 if (pgdat && current_is_kswapd()) {
3689 VM_WARN_ON_ONCE(walk);
3691 walk = &pgdat->mm_walk;
3692 } else if (!walk && force_alloc) {
3693 VM_WARN_ON_ONCE(current_is_kswapd());
3695 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3698 current->reclaim_state->mm_walk = walk;
3703 static void clear_mm_walk(void)
3705 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3707 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
3708 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
3710 current->reclaim_state->mm_walk = NULL;
3712 if (!current_is_kswapd())
3716 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
3719 int remaining = MAX_LRU_BATCH;
3720 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3721 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3723 if (type == LRU_GEN_ANON && !can_swap)
3726 /* prevent cold/hot inversion if force_scan is true */
3727 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3728 struct list_head *head = &lrugen->folios[old_gen][type][zone];
3730 while (!list_empty(head)) {
3731 struct folio *folio = lru_to_folio(head);
3733 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
3734 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
3735 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
3736 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
3738 new_gen = folio_inc_gen(lruvec, folio, false);
3739 list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
3746 reset_ctrl_pos(lruvec, type, true);
3747 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3752 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3754 int gen, type, zone;
3755 bool success = false;
3756 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3757 DEFINE_MIN_SEQ(lruvec);
3759 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3761 /* find the oldest populated generation */
3762 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3763 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3764 gen = lru_gen_from_seq(min_seq[type]);
3766 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3767 if (!list_empty(&lrugen->folios[gen][type][zone]))
3777 /* see the comment on lru_gen_folio */
3779 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3780 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3783 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3784 if (min_seq[type] == lrugen->min_seq[type])
3787 reset_ctrl_pos(lruvec, type, true);
3788 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3795 static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq,
3796 bool can_swap, bool force_scan)
3801 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3803 if (seq < READ_ONCE(lrugen->max_seq))
3806 spin_lock_irq(&lruvec->lru_lock);
3808 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3810 success = seq == lrugen->max_seq;
3814 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
3815 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3818 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
3820 if (inc_min_seq(lruvec, type, can_swap))
3823 spin_unlock_irq(&lruvec->lru_lock);
3829 * Update the active/inactive LRU sizes for compatibility. Both sides of
3830 * the current max_seq need to be covered, since max_seq+1 can overlap
3831 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3832 * overlap, cold/hot inversion happens.
3834 prev = lru_gen_from_seq(lrugen->max_seq - 1);
3835 next = lru_gen_from_seq(lrugen->max_seq + 1);
3837 for (type = 0; type < ANON_AND_FILE; type++) {
3838 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3839 enum lru_list lru = type * LRU_INACTIVE_FILE;
3840 long delta = lrugen->nr_pages[prev][type][zone] -
3841 lrugen->nr_pages[next][type][zone];
3846 __update_lru_size(lruvec, lru, zone, delta);
3847 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3851 for (type = 0; type < ANON_AND_FILE; type++)
3852 reset_ctrl_pos(lruvec, type, false);
3854 WRITE_ONCE(lrugen->timestamps[next], jiffies);
3855 /* make sure preceding modifications appear */
3856 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3858 spin_unlock_irq(&lruvec->lru_lock);
3863 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq,
3864 bool can_swap, bool force_scan)
3867 struct lru_gen_mm_walk *walk;
3868 struct mm_struct *mm = NULL;
3869 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3870 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
3872 VM_WARN_ON_ONCE(seq > READ_ONCE(lrugen->max_seq));
3875 return inc_max_seq(lruvec, seq, can_swap, force_scan);
3877 /* see the comment in iterate_mm_list() */
3878 if (seq <= READ_ONCE(mm_state->seq))
3882 * If the hardware doesn't automatically set the accessed bit, fallback
3883 * to lru_gen_look_around(), which only clears the accessed bit in a
3884 * handful of PTEs. Spreading the work out over a period of time usually
3885 * is less efficient, but it avoids bursty page faults.
3887 if (!should_walk_mmu()) {
3888 success = iterate_mm_list_nowalk(lruvec, seq);
3892 walk = set_mm_walk(NULL, true);
3894 success = iterate_mm_list_nowalk(lruvec, seq);
3898 walk->lruvec = lruvec;
3900 walk->can_swap = can_swap;
3901 walk->force_scan = force_scan;
3904 success = iterate_mm_list(walk, &mm);
3910 success = inc_max_seq(lruvec, seq, can_swap, force_scan);
3911 WARN_ON_ONCE(!success);
3917 /******************************************************************************
3918 * working set protection
3919 ******************************************************************************/
3921 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
3924 unsigned long reclaimable;
3926 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
3929 * Determine the initial priority based on
3930 * (total >> priority) * reclaimed_to_scanned_ratio = nr_to_reclaim,
3931 * where reclaimed_to_scanned_ratio = inactive / total.
3933 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
3934 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
3935 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
3937 /* round down reclaimable and round up sc->nr_to_reclaim */
3938 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
3941 * The estimation is based on LRU pages only, so cap it to prevent
3942 * overshoots of shrinker objects by large margins.
3944 sc->priority = clamp(priority, DEF_PRIORITY / 2, DEF_PRIORITY);
3947 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
3949 int gen, type, zone;
3950 unsigned long total = 0;
3951 bool can_swap = get_swappiness(lruvec, sc);
3952 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3953 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3954 DEFINE_MAX_SEQ(lruvec);
3955 DEFINE_MIN_SEQ(lruvec);
3957 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3960 for (seq = min_seq[type]; seq <= max_seq; seq++) {
3961 gen = lru_gen_from_seq(seq);
3963 for (zone = 0; zone < MAX_NR_ZONES; zone++)
3964 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
3968 /* whether the size is big enough to be helpful */
3969 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
3972 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
3973 unsigned long min_ttl)
3976 unsigned long birth;
3977 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3978 DEFINE_MIN_SEQ(lruvec);
3980 if (mem_cgroup_below_min(NULL, memcg))
3983 if (!lruvec_is_sizable(lruvec, sc))
3986 /* see the comment on lru_gen_folio */
3987 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
3988 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
3990 return time_is_before_jiffies(birth + min_ttl);
3993 /* to protect the working set of the last N jiffies */
3994 static unsigned long lru_gen_min_ttl __read_mostly;
3996 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3998 struct mem_cgroup *memcg;
3999 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4000 bool reclaimable = !min_ttl;
4002 VM_WARN_ON_ONCE(!current_is_kswapd());
4004 set_initial_priority(pgdat, sc);
4006 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4008 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4010 mem_cgroup_calculate_protection(NULL, memcg);
4013 reclaimable = lruvec_is_reclaimable(lruvec, sc, min_ttl);
4014 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4017 * The main goal is to OOM kill if every generation from all memcgs is
4018 * younger than min_ttl. However, another possibility is all memcgs are
4019 * either too small or below min.
4021 if (!reclaimable && mutex_trylock(&oom_lock)) {
4022 struct oom_control oc = {
4023 .gfp_mask = sc->gfp_mask,
4028 mutex_unlock(&oom_lock);
4032 /******************************************************************************
4033 * rmap/PT walk feedback
4034 ******************************************************************************/
4037 * This function exploits spatial locality when shrink_folio_list() walks the
4038 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4039 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4040 * the PTE table to the Bloom filter. This forms a feedback loop between the
4041 * eviction and the aging.
4043 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4046 unsigned long start;
4048 struct lru_gen_mm_walk *walk;
4050 pte_t *pte = pvmw->pte;
4051 unsigned long addr = pvmw->address;
4052 struct vm_area_struct *vma = pvmw->vma;
4053 struct folio *folio = pfn_folio(pvmw->pfn);
4054 bool can_swap = !folio_is_file_lru(folio);
4055 struct mem_cgroup *memcg = folio_memcg(folio);
4056 struct pglist_data *pgdat = folio_pgdat(folio);
4057 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4058 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
4059 DEFINE_MAX_SEQ(lruvec);
4060 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4062 lockdep_assert_held(pvmw->ptl);
4063 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4065 if (spin_is_contended(pvmw->ptl))
4068 /* exclude special VMAs containing anon pages from COW */
4069 if (vma->vm_flags & VM_SPECIAL)
4072 /* avoid taking the LRU lock under the PTL when possible */
4073 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4075 start = max(addr & PMD_MASK, vma->vm_start);
4076 end = min(addr | ~PMD_MASK, vma->vm_end - 1) + 1;
4078 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4079 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4080 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4081 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
4082 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4084 start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
4085 end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
4089 /* folio_update_gen() requires stable folio_memcg() */
4090 if (!mem_cgroup_trylock_pages(memcg))
4093 arch_enter_lazy_mmu_mode();
4095 pte -= (addr - start) / PAGE_SIZE;
4097 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4099 pte_t ptent = ptep_get(pte + i);
4101 pfn = get_pte_pfn(ptent, vma, addr);
4105 if (!pte_young(ptent))
4108 folio = get_pfn_folio(pfn, memcg, pgdat, can_swap);
4112 if (!ptep_test_and_clear_young(vma, addr, pte + i))
4113 VM_WARN_ON_ONCE(true);
4117 if (pte_dirty(ptent) && !folio_test_dirty(folio) &&
4118 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4119 !folio_test_swapcache(folio)))
4120 folio_mark_dirty(folio);
4123 old_gen = folio_update_gen(folio, new_gen);
4124 if (old_gen >= 0 && old_gen != new_gen)
4125 update_batch_size(walk, folio, old_gen, new_gen);
4130 old_gen = folio_lru_gen(folio);
4132 folio_set_referenced(folio);
4133 else if (old_gen != new_gen)
4134 folio_activate(folio);
4137 arch_leave_lazy_mmu_mode();
4138 mem_cgroup_unlock_pages();
4140 /* feedback from rmap walkers to page table walkers */
4141 if (mm_state && suitable_to_scan(i, young))
4142 update_bloom_filter(mm_state, max_seq, pvmw->pmd);
4145 /******************************************************************************
4147 ******************************************************************************/
4149 /* see the comment on MEMCG_NR_GENS */
4158 static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
4162 unsigned long flags;
4163 int bin = get_random_u32_below(MEMCG_NR_BINS);
4164 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4166 spin_lock_irqsave(&pgdat->memcg_lru.lock, flags);
4168 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4171 new = old = lruvec->lrugen.gen;
4173 /* see the comment on MEMCG_NR_GENS */
4174 if (op == MEMCG_LRU_HEAD)
4175 seg = MEMCG_LRU_HEAD;
4176 else if (op == MEMCG_LRU_TAIL)
4177 seg = MEMCG_LRU_TAIL;
4178 else if (op == MEMCG_LRU_OLD)
4179 new = get_memcg_gen(pgdat->memcg_lru.seq);
4180 else if (op == MEMCG_LRU_YOUNG)
4181 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
4183 VM_WARN_ON_ONCE(true);
4185 WRITE_ONCE(lruvec->lrugen.seg, seg);
4186 WRITE_ONCE(lruvec->lrugen.gen, new);
4188 hlist_nulls_del_rcu(&lruvec->lrugen.list);
4190 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
4191 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4193 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4195 pgdat->memcg_lru.nr_memcgs[old]--;
4196 pgdat->memcg_lru.nr_memcgs[new]++;
4198 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
4199 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4201 spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags);
4206 void lru_gen_online_memcg(struct mem_cgroup *memcg)
4210 int bin = get_random_u32_below(MEMCG_NR_BINS);
4212 for_each_node(nid) {
4213 struct pglist_data *pgdat = NODE_DATA(nid);
4214 struct lruvec *lruvec = get_lruvec(memcg, nid);
4216 spin_lock_irq(&pgdat->memcg_lru.lock);
4218 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
4220 gen = get_memcg_gen(pgdat->memcg_lru.seq);
4222 lruvec->lrugen.gen = gen;
4224 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
4225 pgdat->memcg_lru.nr_memcgs[gen]++;
4227 spin_unlock_irq(&pgdat->memcg_lru.lock);
4231 void lru_gen_offline_memcg(struct mem_cgroup *memcg)
4235 for_each_node(nid) {
4236 struct lruvec *lruvec = get_lruvec(memcg, nid);
4238 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
4242 void lru_gen_release_memcg(struct mem_cgroup *memcg)
4247 for_each_node(nid) {
4248 struct pglist_data *pgdat = NODE_DATA(nid);
4249 struct lruvec *lruvec = get_lruvec(memcg, nid);
4251 spin_lock_irq(&pgdat->memcg_lru.lock);
4253 if (hlist_nulls_unhashed(&lruvec->lrugen.list))
4256 gen = lruvec->lrugen.gen;
4258 hlist_nulls_del_init_rcu(&lruvec->lrugen.list);
4259 pgdat->memcg_lru.nr_memcgs[gen]--;
4261 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
4262 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4264 spin_unlock_irq(&pgdat->memcg_lru.lock);
4268 void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
4270 struct lruvec *lruvec = get_lruvec(memcg, nid);
4272 /* see the comment on MEMCG_NR_GENS */
4273 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_HEAD)
4274 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
4277 #endif /* CONFIG_MEMCG */
4279 /******************************************************************************
4281 ******************************************************************************/
4283 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc,
4287 int gen = folio_lru_gen(folio);
4288 int type = folio_is_file_lru(folio);
4289 int zone = folio_zonenum(folio);
4290 int delta = folio_nr_pages(folio);
4291 int refs = folio_lru_refs(folio);
4292 int tier = lru_tier_from_refs(refs);
4293 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4295 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4298 if (!folio_evictable(folio)) {
4299 success = lru_gen_del_folio(lruvec, folio, true);
4300 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4301 folio_set_unevictable(folio);
4302 lruvec_add_folio(lruvec, folio);
4303 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4308 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4309 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4314 if (tier > tier_idx || refs == BIT(LRU_REFS_WIDTH)) {
4315 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4317 gen = folio_inc_gen(lruvec, folio, false);
4318 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4320 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4321 lrugen->protected[hist][type][tier - 1] + delta);
4326 if (!folio_test_lru(folio) || zone > sc->reclaim_idx) {
4327 gen = folio_inc_gen(lruvec, folio, false);
4328 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4332 /* waiting for writeback */
4333 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4334 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4335 gen = folio_inc_gen(lruvec, folio, true);
4336 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4343 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4347 /* swap constrained */
4348 if (!(sc->gfp_mask & __GFP_IO) &&
4349 (folio_test_dirty(folio) ||
4350 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4353 /* raced with release_pages() */
4354 if (!folio_try_get(folio))
4357 /* raced with another isolation */
4358 if (!folio_test_clear_lru(folio)) {
4363 /* see the comment on MAX_NR_TIERS */
4364 if (!folio_test_referenced(folio))
4365 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4367 /* for shrink_folio_list() */
4368 folio_clear_reclaim(folio);
4369 folio_clear_referenced(folio);
4371 success = lru_gen_del_folio(lruvec, folio, true);
4372 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4377 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4378 int type, int tier, struct list_head *list)
4382 enum vm_event_item item;
4387 int remaining = MAX_LRU_BATCH;
4388 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4389 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4391 VM_WARN_ON_ONCE(!list_empty(list));
4393 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4396 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4398 for (i = MAX_NR_ZONES; i > 0; i--) {
4400 int skipped_zone = 0;
4401 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
4402 struct list_head *head = &lrugen->folios[gen][type][zone];
4404 while (!list_empty(head)) {
4405 struct folio *folio = lru_to_folio(head);
4406 int delta = folio_nr_pages(folio);
4408 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4409 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4410 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4411 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4415 if (sort_folio(lruvec, folio, sc, tier))
4417 else if (isolate_folio(lruvec, folio, sc)) {
4418 list_add(&folio->lru, list);
4421 list_move(&folio->lru, &moved);
4422 skipped_zone += delta;
4425 if (!--remaining || max(isolated, skipped_zone) >= MIN_LRU_BATCH)
4430 list_splice(&moved, head);
4431 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped_zone);
4432 skipped += skipped_zone;
4435 if (!remaining || isolated >= MIN_LRU_BATCH)
4439 item = PGSCAN_KSWAPD + reclaimer_offset();
4440 if (!cgroup_reclaim(sc)) {
4441 __count_vm_events(item, isolated);
4442 __count_vm_events(PGREFILL, sorted);
4444 __count_memcg_events(memcg, item, isolated);
4445 __count_memcg_events(memcg, PGREFILL, sorted);
4446 __count_vm_events(PGSCAN_ANON + type, isolated);
4447 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, MAX_LRU_BATCH,
4448 scanned, skipped, isolated,
4449 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
4452 * There might not be eligible folios due to reclaim_idx. Check the
4453 * remaining to prevent livelock if it's not making progress.
4455 return isolated || !remaining ? scanned : 0;
4458 static int get_tier_idx(struct lruvec *lruvec, int type)
4461 struct ctrl_pos sp, pv;
4464 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4465 * This value is chosen because any other tier would have at least twice
4466 * as many refaults as the first tier.
4468 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4469 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4470 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4471 if (!positive_ctrl_err(&sp, &pv))
4478 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4481 struct ctrl_pos sp, pv;
4482 int gain[ANON_AND_FILE] = { swappiness, MAX_SWAPPINESS - swappiness };
4485 * Compare the first tier of anon with that of file to determine which
4486 * type to scan. Also need to compare other tiers of the selected type
4487 * with the first tier of the other type to determine the last tier (of
4488 * the selected type) to evict.
4490 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4491 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4492 type = positive_ctrl_err(&sp, &pv);
4494 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4495 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4496 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4497 if (!positive_ctrl_err(&sp, &pv))
4501 *tier_idx = tier - 1;
4506 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4507 int *type_scanned, struct list_head *list)
4513 DEFINE_MIN_SEQ(lruvec);
4516 * Try to make the obvious choice first, and if anon and file are both
4517 * available from the same generation,
4518 * 1. Interpret swappiness 1 as file first and MAX_SWAPPINESS as anon
4520 * 2. If !__GFP_IO, file first since clean pagecache is more likely to
4521 * exist than clean swapcache.
4524 type = LRU_GEN_FILE;
4525 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4526 type = LRU_GEN_ANON;
4527 else if (swappiness == 1)
4528 type = LRU_GEN_FILE;
4529 else if (swappiness == MAX_SWAPPINESS)
4530 type = LRU_GEN_ANON;
4531 else if (!(sc->gfp_mask & __GFP_IO))
4532 type = LRU_GEN_FILE;
4534 type = get_type_to_scan(lruvec, swappiness, &tier);
4536 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4538 tier = get_tier_idx(lruvec, type);
4540 scanned = scan_folios(lruvec, sc, type, tier, list);
4548 *type_scanned = type;
4553 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
4560 struct folio *folio;
4562 enum vm_event_item item;
4563 struct reclaim_stat stat;
4564 struct lru_gen_mm_walk *walk;
4565 bool skip_retry = false;
4566 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4567 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4569 spin_lock_irq(&lruvec->lru_lock);
4571 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
4573 scanned += try_to_inc_min_seq(lruvec, swappiness);
4575 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4578 spin_unlock_irq(&lruvec->lru_lock);
4580 if (list_empty(&list))
4583 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
4584 sc->nr_reclaimed += reclaimed;
4585 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
4586 scanned, reclaimed, &stat, sc->priority,
4587 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
4589 list_for_each_entry_safe_reverse(folio, next, &list, lru) {
4590 if (!folio_evictable(folio)) {
4591 list_del(&folio->lru);
4592 folio_putback_lru(folio);
4596 if (folio_test_reclaim(folio) &&
4597 (folio_test_dirty(folio) || folio_test_writeback(folio))) {
4598 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
4599 if (folio_test_workingset(folio))
4600 folio_set_referenced(folio);
4604 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
4605 folio_mapped(folio) || folio_test_locked(folio) ||
4606 folio_test_dirty(folio) || folio_test_writeback(folio)) {
4607 /* don't add rejected folios to the oldest generation */
4608 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4613 /* retry folios that may have missed folio_rotate_reclaimable() */
4614 list_move(&folio->lru, &clean);
4617 spin_lock_irq(&lruvec->lru_lock);
4619 move_folios_to_lru(lruvec, &list);
4621 walk = current->reclaim_state->mm_walk;
4622 if (walk && walk->batched) {
4623 walk->lruvec = lruvec;
4624 reset_batch_size(walk);
4627 item = PGSTEAL_KSWAPD + reclaimer_offset();
4628 if (!cgroup_reclaim(sc))
4629 __count_vm_events(item, reclaimed);
4630 __count_memcg_events(memcg, item, reclaimed);
4631 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4633 spin_unlock_irq(&lruvec->lru_lock);
4635 list_splice_init(&clean, &list);
4637 if (!list_empty(&list)) {
4645 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4646 bool can_swap, unsigned long *nr_to_scan)
4648 int gen, type, zone;
4649 unsigned long old = 0;
4650 unsigned long young = 0;
4651 unsigned long total = 0;
4652 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4653 DEFINE_MIN_SEQ(lruvec);
4655 /* whether this lruvec is completely out of cold folios */
4656 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4661 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4664 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4665 unsigned long size = 0;
4667 gen = lru_gen_from_seq(seq);
4669 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4670 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4675 else if (seq + MIN_NR_GENS == max_seq)
4680 *nr_to_scan = total;
4683 * The aging tries to be lazy to reduce the overhead, while the eviction
4684 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4685 * ideal number of generations is MIN_NR_GENS+1.
4687 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4691 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4692 * of the total number of pages for each generation. A reasonable range
4693 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4694 * aging cares about the upper bound of hot pages, while the eviction
4695 * cares about the lower bound of cold pages.
4697 if (young * MIN_NR_GENS > total)
4699 if (old * (MIN_NR_GENS + 2) < total)
4706 * For future optimizations:
4707 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4710 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4713 unsigned long nr_to_scan;
4714 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4715 DEFINE_MAX_SEQ(lruvec);
4717 if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg))
4720 success = should_run_aging(lruvec, max_seq, can_swap, &nr_to_scan);
4722 /* try to scrape all its memory if this memcg was deleted */
4723 if (nr_to_scan && !mem_cgroup_online(memcg))
4726 /* try to get away with not aging at the default priority */
4727 if (!success || sc->priority == DEF_PRIORITY)
4728 return nr_to_scan >> sc->priority;
4730 /* stop scanning this lruvec as it's low on cold folios */
4731 return try_to_inc_max_seq(lruvec, max_seq, can_swap, false) ? -1 : 0;
4734 static bool should_abort_scan(struct lruvec *lruvec, struct scan_control *sc)
4737 enum zone_watermarks mark;
4739 /* don't abort memcg reclaim to ensure fairness */
4740 if (!root_reclaim(sc))
4743 if (sc->nr_reclaimed >= max(sc->nr_to_reclaim, compact_gap(sc->order)))
4746 /* check the order to exclude compaction-induced reclaim */
4747 if (!current_is_kswapd() || sc->order)
4750 mark = sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ?
4751 WMARK_PROMO : WMARK_HIGH;
4753 for (i = 0; i <= sc->reclaim_idx; i++) {
4754 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4755 unsigned long size = wmark_pages(zone, mark) + MIN_LRU_BATCH;
4757 if (managed_zone(zone) && !zone_watermark_ok(zone, 0, size, sc->reclaim_idx, 0))
4761 /* kswapd should abort if all eligible zones are safe */
4765 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4768 unsigned long scanned = 0;
4769 int swappiness = get_swappiness(lruvec, sc);
4774 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4775 if (nr_to_scan <= 0)
4778 delta = evict_folios(lruvec, sc, swappiness);
4783 if (scanned >= nr_to_scan)
4786 if (should_abort_scan(lruvec, sc))
4792 /* whether this lruvec should be rotated */
4793 return nr_to_scan < 0;
4796 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4799 unsigned long scanned = sc->nr_scanned;
4800 unsigned long reclaimed = sc->nr_reclaimed;
4801 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4802 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4804 /* lru_gen_age_node() called mem_cgroup_calculate_protection() */
4805 if (mem_cgroup_below_min(NULL, memcg))
4806 return MEMCG_LRU_YOUNG;
4808 if (mem_cgroup_below_low(NULL, memcg)) {
4809 /* see the comment on MEMCG_NR_GENS */
4810 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL)
4811 return MEMCG_LRU_TAIL;
4813 memcg_memory_event(memcg, MEMCG_LOW);
4816 success = try_to_shrink_lruvec(lruvec, sc);
4818 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
4821 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
4822 sc->nr_reclaimed - reclaimed);
4824 flush_reclaim_state(sc);
4826 if (success && mem_cgroup_online(memcg))
4827 return MEMCG_LRU_YOUNG;
4829 if (!success && lruvec_is_sizable(lruvec, sc))
4832 /* one retry if offlined or too small */
4833 return READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL ?
4834 MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
4837 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
4843 struct lruvec *lruvec;
4844 struct lru_gen_folio *lrugen;
4845 struct mem_cgroup *memcg;
4846 struct hlist_nulls_node *pos;
4848 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
4849 bin = first_bin = get_random_u32_below(MEMCG_NR_BINS);
4856 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
4858 lru_gen_rotate_memcg(lruvec, op);
4862 mem_cgroup_put(memcg);
4865 if (gen != READ_ONCE(lrugen->gen))
4868 lruvec = container_of(lrugen, struct lruvec, lrugen);
4869 memcg = lruvec_memcg(lruvec);
4871 if (!mem_cgroup_tryget(memcg)) {
4872 lru_gen_release_memcg(memcg);
4879 op = shrink_one(lruvec, sc);
4883 if (should_abort_scan(lruvec, sc))
4890 lru_gen_rotate_memcg(lruvec, op);
4892 mem_cgroup_put(memcg);
4894 if (!is_a_nulls(pos))
4897 /* restart if raced with lru_gen_rotate_memcg() */
4898 if (gen != get_nulls_value(pos))
4901 /* try the rest of the bins of the current generation */
4902 bin = get_memcg_bin(bin + 1);
4903 if (bin != first_bin)
4907 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4909 struct blk_plug plug;
4911 VM_WARN_ON_ONCE(root_reclaim(sc));
4912 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
4916 blk_start_plug(&plug);
4918 set_mm_walk(NULL, sc->proactive);
4920 if (try_to_shrink_lruvec(lruvec, sc))
4921 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
4925 blk_finish_plug(&plug);
4928 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
4930 struct blk_plug plug;
4931 unsigned long reclaimed = sc->nr_reclaimed;
4933 VM_WARN_ON_ONCE(!root_reclaim(sc));
4936 * Unmapped clean folios are already prioritized. Scanning for more of
4937 * them is likely futile and can cause high reclaim latency when there
4938 * is a large number of memcgs.
4940 if (!sc->may_writepage || !sc->may_unmap)
4945 blk_start_plug(&plug);
4947 set_mm_walk(pgdat, sc->proactive);
4949 set_initial_priority(pgdat, sc);
4951 if (current_is_kswapd())
4952 sc->nr_reclaimed = 0;
4954 if (mem_cgroup_disabled())
4955 shrink_one(&pgdat->__lruvec, sc);
4957 shrink_many(pgdat, sc);
4959 if (current_is_kswapd())
4960 sc->nr_reclaimed += reclaimed;
4964 blk_finish_plug(&plug);
4966 /* kswapd should never fail */
4967 pgdat->kswapd_failures = 0;
4970 /******************************************************************************
4972 ******************************************************************************/
4974 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4976 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4978 if (lrugen->enabled) {
4981 for_each_evictable_lru(lru) {
4982 if (!list_empty(&lruvec->lists[lru]))
4986 int gen, type, zone;
4988 for_each_gen_type_zone(gen, type, zone) {
4989 if (!list_empty(&lrugen->folios[gen][type][zone]))
4997 static bool fill_evictable(struct lruvec *lruvec)
5000 int remaining = MAX_LRU_BATCH;
5002 for_each_evictable_lru(lru) {
5003 int type = is_file_lru(lru);
5004 bool active = is_active_lru(lru);
5005 struct list_head *head = &lruvec->lists[lru];
5007 while (!list_empty(head)) {
5009 struct folio *folio = lru_to_folio(head);
5011 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5012 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5013 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5014 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5016 lruvec_del_folio(lruvec, folio);
5017 success = lru_gen_add_folio(lruvec, folio, false);
5018 VM_WARN_ON_ONCE(!success);
5028 static bool drain_evictable(struct lruvec *lruvec)
5030 int gen, type, zone;
5031 int remaining = MAX_LRU_BATCH;
5033 for_each_gen_type_zone(gen, type, zone) {
5034 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
5036 while (!list_empty(head)) {
5038 struct folio *folio = lru_to_folio(head);
5040 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5041 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5042 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5043 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5045 success = lru_gen_del_folio(lruvec, folio, false);
5046 VM_WARN_ON_ONCE(!success);
5047 lruvec_add_folio(lruvec, folio);
5057 static void lru_gen_change_state(bool enabled)
5059 static DEFINE_MUTEX(state_mutex);
5061 struct mem_cgroup *memcg;
5066 mutex_lock(&state_mutex);
5068 if (enabled == lru_gen_enabled())
5072 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5074 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5076 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5080 for_each_node(nid) {
5081 struct lruvec *lruvec = get_lruvec(memcg, nid);
5083 spin_lock_irq(&lruvec->lru_lock);
5085 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5086 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5088 lruvec->lrugen.enabled = enabled;
5090 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5091 spin_unlock_irq(&lruvec->lru_lock);
5093 spin_lock_irq(&lruvec->lru_lock);
5096 spin_unlock_irq(&lruvec->lru_lock);
5100 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5102 mutex_unlock(&state_mutex);
5108 /******************************************************************************
5110 ******************************************************************************/
5112 static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5114 return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5117 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5118 static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr,
5119 const char *buf, size_t len)
5123 if (kstrtouint(buf, 0, &msecs))
5126 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5131 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms);
5133 static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5135 unsigned int caps = 0;
5137 if (get_cap(LRU_GEN_CORE))
5138 caps |= BIT(LRU_GEN_CORE);
5140 if (should_walk_mmu())
5141 caps |= BIT(LRU_GEN_MM_WALK);
5143 if (should_clear_pmd_young())
5144 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5146 return sysfs_emit(buf, "0x%04x\n", caps);
5149 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5150 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
5151 const char *buf, size_t len)
5156 if (tolower(*buf) == 'n')
5158 else if (tolower(*buf) == 'y')
5160 else if (kstrtouint(buf, 0, &caps))
5163 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5164 bool enabled = caps & BIT(i);
5166 if (i == LRU_GEN_CORE)
5167 lru_gen_change_state(enabled);
5169 static_branch_enable(&lru_gen_caps[i]);
5171 static_branch_disable(&lru_gen_caps[i]);
5177 static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled);
5179 static struct attribute *lru_gen_attrs[] = {
5180 &lru_gen_min_ttl_attr.attr,
5181 &lru_gen_enabled_attr.attr,
5185 static const struct attribute_group lru_gen_attr_group = {
5187 .attrs = lru_gen_attrs,
5190 /******************************************************************************
5192 ******************************************************************************/
5194 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5196 struct mem_cgroup *memcg;
5197 loff_t nr_to_skip = *pos;
5199 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5201 return ERR_PTR(-ENOMEM);
5203 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5207 for_each_node_state(nid, N_MEMORY) {
5209 return get_lruvec(memcg, nid);
5211 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5216 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5218 if (!IS_ERR_OR_NULL(v))
5219 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5225 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5227 int nid = lruvec_pgdat(v)->node_id;
5228 struct mem_cgroup *memcg = lruvec_memcg(v);
5232 nid = next_memory_node(nid);
5233 if (nid == MAX_NUMNODES) {
5234 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5238 nid = first_memory_node;
5241 return get_lruvec(memcg, nid);
5244 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5245 unsigned long max_seq, unsigned long *min_seq,
5250 int hist = lru_hist_from_seq(seq);
5251 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5252 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
5254 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5255 seq_printf(m, " %10d", tier);
5256 for (type = 0; type < ANON_AND_FILE; type++) {
5257 const char *s = " ";
5258 unsigned long n[3] = {};
5260 if (seq == max_seq) {
5262 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5263 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5264 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5266 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5267 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5269 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5272 for (i = 0; i < 3; i++)
5273 seq_printf(m, " %10lu%c", n[i], s[i]);
5282 for (i = 0; i < NR_MM_STATS; i++) {
5283 const char *s = " ";
5284 unsigned long n = 0;
5286 if (seq == max_seq && NR_HIST_GENS == 1) {
5288 n = READ_ONCE(mm_state->stats[hist][i]);
5289 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5291 n = READ_ONCE(mm_state->stats[hist][i]);
5294 seq_printf(m, " %10lu%c", n, s[i]);
5299 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5300 static int lru_gen_seq_show(struct seq_file *m, void *v)
5303 bool full = !debugfs_real_fops(m->file)->write;
5304 struct lruvec *lruvec = v;
5305 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5306 int nid = lruvec_pgdat(lruvec)->node_id;
5307 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5308 DEFINE_MAX_SEQ(lruvec);
5309 DEFINE_MIN_SEQ(lruvec);
5311 if (nid == first_memory_node) {
5312 const char *path = memcg ? m->private : "";
5316 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5318 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5321 seq_printf(m, " node %5d\n", nid);
5324 seq = min_seq[LRU_GEN_ANON];
5325 else if (max_seq >= MAX_NR_GENS)
5326 seq = max_seq - MAX_NR_GENS + 1;
5330 for (; seq <= max_seq; seq++) {
5332 int gen = lru_gen_from_seq(seq);
5333 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5335 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5337 for (type = 0; type < ANON_AND_FILE; type++) {
5338 unsigned long size = 0;
5339 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5341 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5342 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5344 seq_printf(m, " %10lu%c", size, mark);
5350 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5356 static const struct seq_operations lru_gen_seq_ops = {
5357 .start = lru_gen_seq_start,
5358 .stop = lru_gen_seq_stop,
5359 .next = lru_gen_seq_next,
5360 .show = lru_gen_seq_show,
5363 static int run_aging(struct lruvec *lruvec, unsigned long seq,
5364 bool can_swap, bool force_scan)
5366 DEFINE_MAX_SEQ(lruvec);
5367 DEFINE_MIN_SEQ(lruvec);
5375 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5378 try_to_inc_max_seq(lruvec, max_seq, can_swap, force_scan);
5383 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5384 int swappiness, unsigned long nr_to_reclaim)
5386 DEFINE_MAX_SEQ(lruvec);
5388 if (seq + MIN_NR_GENS > max_seq)
5391 sc->nr_reclaimed = 0;
5393 while (!signal_pending(current)) {
5394 DEFINE_MIN_SEQ(lruvec);
5396 if (seq < min_seq[!swappiness])
5399 if (sc->nr_reclaimed >= nr_to_reclaim)
5402 if (!evict_folios(lruvec, sc, swappiness))
5411 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5412 struct scan_control *sc, int swappiness, unsigned long opt)
5414 struct lruvec *lruvec;
5416 struct mem_cgroup *memcg = NULL;
5418 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5421 if (!mem_cgroup_disabled()) {
5424 memcg = mem_cgroup_from_id(memcg_id);
5425 if (!mem_cgroup_tryget(memcg))
5434 if (memcg_id != mem_cgroup_id(memcg))
5437 lruvec = get_lruvec(memcg, nid);
5439 if (swappiness < MIN_SWAPPINESS)
5440 swappiness = get_swappiness(lruvec, sc);
5441 else if (swappiness > MAX_SWAPPINESS)
5446 err = run_aging(lruvec, seq, swappiness, opt);
5449 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5453 mem_cgroup_put(memcg);
5458 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5459 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5460 size_t len, loff_t *pos)
5465 struct blk_plug plug;
5467 struct scan_control sc = {
5468 .may_writepage = true,
5471 .reclaim_idx = MAX_NR_ZONES - 1,
5472 .gfp_mask = GFP_KERNEL,
5475 buf = kvmalloc(len + 1, GFP_KERNEL);
5479 if (copy_from_user(buf, src, len)) {
5484 set_task_reclaim_state(current, &sc.reclaim_state);
5485 flags = memalloc_noreclaim_save();
5486 blk_start_plug(&plug);
5487 if (!set_mm_walk(NULL, true)) {
5495 while ((cur = strsep(&next, ",;\n"))) {
5499 unsigned int memcg_id;
5502 unsigned int swappiness = -1;
5503 unsigned long opt = -1;
5505 cur = skip_spaces(cur);
5509 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5510 &seq, &end, &swappiness, &end, &opt, &end);
5511 if (n < 4 || cur[end]) {
5516 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5522 blk_finish_plug(&plug);
5523 memalloc_noreclaim_restore(flags);
5524 set_task_reclaim_state(current, NULL);
5531 static int lru_gen_seq_open(struct inode *inode, struct file *file)
5533 return seq_open(file, &lru_gen_seq_ops);
5536 static const struct file_operations lru_gen_rw_fops = {
5537 .open = lru_gen_seq_open,
5539 .write = lru_gen_seq_write,
5540 .llseek = seq_lseek,
5541 .release = seq_release,
5544 static const struct file_operations lru_gen_ro_fops = {
5545 .open = lru_gen_seq_open,
5547 .llseek = seq_lseek,
5548 .release = seq_release,
5551 /******************************************************************************
5553 ******************************************************************************/
5555 void lru_gen_init_pgdat(struct pglist_data *pgdat)
5559 spin_lock_init(&pgdat->memcg_lru.lock);
5561 for (i = 0; i < MEMCG_NR_GENS; i++) {
5562 for (j = 0; j < MEMCG_NR_BINS; j++)
5563 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5567 void lru_gen_init_lruvec(struct lruvec *lruvec)
5570 int gen, type, zone;
5571 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5572 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
5574 lrugen->max_seq = MIN_NR_GENS + 1;
5575 lrugen->enabled = lru_gen_enabled();
5577 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5578 lrugen->timestamps[i] = jiffies;
5580 for_each_gen_type_zone(gen, type, zone)
5581 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
5584 mm_state->seq = MIN_NR_GENS;
5589 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5591 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
5596 INIT_LIST_HEAD(&mm_list->fifo);
5597 spin_lock_init(&mm_list->lock);
5600 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5604 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
5606 VM_WARN_ON_ONCE(mm_list && !list_empty(&mm_list->fifo));
5608 for_each_node(nid) {
5609 struct lruvec *lruvec = get_lruvec(memcg, nid);
5610 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
5612 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5613 sizeof(lruvec->lrugen.nr_pages)));
5615 lruvec->lrugen.list.next = LIST_POISON1;
5620 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5621 bitmap_free(mm_state->filters[i]);
5622 mm_state->filters[i] = NULL;
5627 #endif /* CONFIG_MEMCG */
5629 static int __init init_lru_gen(void)
5631 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5632 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5634 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5635 pr_err("lru_gen: failed to create sysfs group\n");
5637 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5638 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5642 late_initcall(init_lru_gen);
5644 #else /* !CONFIG_LRU_GEN */
5646 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5651 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5656 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5661 #endif /* CONFIG_LRU_GEN */
5663 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5665 unsigned long nr[NR_LRU_LISTS];
5666 unsigned long targets[NR_LRU_LISTS];
5667 unsigned long nr_to_scan;
5669 unsigned long nr_reclaimed = 0;
5670 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5671 bool proportional_reclaim;
5672 struct blk_plug plug;
5674 if (lru_gen_enabled() && !root_reclaim(sc)) {
5675 lru_gen_shrink_lruvec(lruvec, sc);
5679 get_scan_count(lruvec, sc, nr);
5681 /* Record the original scan target for proportional adjustments later */
5682 memcpy(targets, nr, sizeof(nr));
5685 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5686 * event that can occur when there is little memory pressure e.g.
5687 * multiple streaming readers/writers. Hence, we do not abort scanning
5688 * when the requested number of pages are reclaimed when scanning at
5689 * DEF_PRIORITY on the assumption that the fact we are direct
5690 * reclaiming implies that kswapd is not keeping up and it is best to
5691 * do a batch of work at once. For memcg reclaim one check is made to
5692 * abort proportional reclaim if either the file or anon lru has already
5693 * dropped to zero at the first pass.
5695 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5696 sc->priority == DEF_PRIORITY);
5698 blk_start_plug(&plug);
5699 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5700 nr[LRU_INACTIVE_FILE]) {
5701 unsigned long nr_anon, nr_file, percentage;
5702 unsigned long nr_scanned;
5704 for_each_evictable_lru(lru) {
5706 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5707 nr[lru] -= nr_to_scan;
5709 nr_reclaimed += shrink_list(lru, nr_to_scan,
5716 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
5720 * For kswapd and memcg, reclaim at least the number of pages
5721 * requested. Ensure that the anon and file LRUs are scanned
5722 * proportionally what was requested by get_scan_count(). We
5723 * stop reclaiming one LRU and reduce the amount scanning
5724 * proportional to the original scan target.
5726 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5727 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5730 * It's just vindictive to attack the larger once the smaller
5731 * has gone to zero. And given the way we stop scanning the
5732 * smaller below, this makes sure that we only make one nudge
5733 * towards proportionality once we've got nr_to_reclaim.
5735 if (!nr_file || !nr_anon)
5738 if (nr_file > nr_anon) {
5739 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5740 targets[LRU_ACTIVE_ANON] + 1;
5742 percentage = nr_anon * 100 / scan_target;
5744 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5745 targets[LRU_ACTIVE_FILE] + 1;
5747 percentage = nr_file * 100 / scan_target;
5750 /* Stop scanning the smaller of the LRU */
5752 nr[lru + LRU_ACTIVE] = 0;
5755 * Recalculate the other LRU scan count based on its original
5756 * scan target and the percentage scanning already complete
5758 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5759 nr_scanned = targets[lru] - nr[lru];
5760 nr[lru] = targets[lru] * (100 - percentage) / 100;
5761 nr[lru] -= min(nr[lru], nr_scanned);
5764 nr_scanned = targets[lru] - nr[lru];
5765 nr[lru] = targets[lru] * (100 - percentage) / 100;
5766 nr[lru] -= min(nr[lru], nr_scanned);
5768 blk_finish_plug(&plug);
5769 sc->nr_reclaimed += nr_reclaimed;
5772 * Even if we did not try to evict anon pages at all, we want to
5773 * rebalance the anon lru active/inactive ratio.
5775 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5776 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5777 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5778 sc, LRU_ACTIVE_ANON);
5781 /* Use reclaim/compaction for costly allocs or under memory pressure */
5782 static bool in_reclaim_compaction(struct scan_control *sc)
5784 if (gfp_compaction_allowed(sc->gfp_mask) && sc->order &&
5785 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
5786 sc->priority < DEF_PRIORITY - 2))
5793 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5794 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5795 * true if more pages should be reclaimed such that when the page allocator
5796 * calls try_to_compact_pages() that it will have enough free pages to succeed.
5797 * It will give up earlier than that if there is difficulty reclaiming pages.
5799 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
5800 unsigned long nr_reclaimed,
5801 struct scan_control *sc)
5803 unsigned long pages_for_compaction;
5804 unsigned long inactive_lru_pages;
5807 /* If not in reclaim/compaction mode, stop */
5808 if (!in_reclaim_compaction(sc))
5812 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5813 * number of pages that were scanned. This will return to the caller
5814 * with the risk reclaim/compaction and the resulting allocation attempt
5815 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5816 * allocations through requiring that the full LRU list has been scanned
5817 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5818 * scan, but that approximation was wrong, and there were corner cases
5819 * where always a non-zero amount of pages were scanned.
5824 /* If compaction would go ahead or the allocation would succeed, stop */
5825 for (z = 0; z <= sc->reclaim_idx; z++) {
5826 struct zone *zone = &pgdat->node_zones[z];
5827 if (!managed_zone(zone))
5830 /* Allocation can already succeed, nothing to do */
5831 if (zone_watermark_ok(zone, sc->order, min_wmark_pages(zone),
5832 sc->reclaim_idx, 0))
5835 if (compaction_suitable(zone, sc->order, sc->reclaim_idx))
5840 * If we have not reclaimed enough pages for compaction and the
5841 * inactive lists are large enough, continue reclaiming
5843 pages_for_compaction = compact_gap(sc->order);
5844 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
5845 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
5846 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5848 return inactive_lru_pages > pages_for_compaction;
5851 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
5853 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
5854 struct mem_cgroup_reclaim_cookie reclaim = {
5857 struct mem_cgroup_reclaim_cookie *partial = &reclaim;
5858 struct mem_cgroup *memcg;
5861 * In most cases, direct reclaimers can do partial walks
5862 * through the cgroup tree, using an iterator state that
5863 * persists across invocations. This strikes a balance between
5864 * fairness and allocation latency.
5866 * For kswapd, reliable forward progress is more important
5867 * than a quick return to idle. Always do full walks.
5869 if (current_is_kswapd() || sc->memcg_full_walk)
5872 memcg = mem_cgroup_iter(target_memcg, NULL, partial);
5874 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
5875 unsigned long reclaimed;
5876 unsigned long scanned;
5879 * This loop can become CPU-bound when target memcgs
5880 * aren't eligible for reclaim - either because they
5881 * don't have any reclaimable pages, or because their
5882 * memory is explicitly protected. Avoid soft lockups.
5886 mem_cgroup_calculate_protection(target_memcg, memcg);
5888 if (mem_cgroup_below_min(target_memcg, memcg)) {
5891 * If there is no reclaimable memory, OOM.
5894 } else if (mem_cgroup_below_low(target_memcg, memcg)) {
5897 * Respect the protection only as long as
5898 * there is an unprotected supply
5899 * of reclaimable memory from other cgroups.
5901 if (!sc->memcg_low_reclaim) {
5902 sc->memcg_low_skipped = 1;
5905 memcg_memory_event(memcg, MEMCG_LOW);
5908 reclaimed = sc->nr_reclaimed;
5909 scanned = sc->nr_scanned;
5911 shrink_lruvec(lruvec, sc);
5913 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5916 /* Record the group's reclaim efficiency */
5918 vmpressure(sc->gfp_mask, memcg, false,
5919 sc->nr_scanned - scanned,
5920 sc->nr_reclaimed - reclaimed);
5922 /* If partial walks are allowed, bail once goal is reached */
5923 if (partial && sc->nr_reclaimed >= sc->nr_to_reclaim) {
5924 mem_cgroup_iter_break(target_memcg, memcg);
5927 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, partial)));
5930 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
5932 unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed;
5933 struct lruvec *target_lruvec;
5934 bool reclaimable = false;
5936 if (lru_gen_enabled() && root_reclaim(sc)) {
5937 lru_gen_shrink_node(pgdat, sc);
5941 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5944 memset(&sc->nr, 0, sizeof(sc->nr));
5946 nr_reclaimed = sc->nr_reclaimed;
5947 nr_scanned = sc->nr_scanned;
5949 prepare_scan_control(pgdat, sc);
5951 shrink_node_memcgs(pgdat, sc);
5953 flush_reclaim_state(sc);
5955 nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed;
5957 /* Record the subtree's reclaim efficiency */
5959 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
5960 sc->nr_scanned - nr_scanned, nr_node_reclaimed);
5962 if (nr_node_reclaimed)
5965 if (current_is_kswapd()) {
5967 * If reclaim is isolating dirty pages under writeback,
5968 * it implies that the long-lived page allocation rate
5969 * is exceeding the page laundering rate. Either the
5970 * global limits are not being effective at throttling
5971 * processes due to the page distribution throughout
5972 * zones or there is heavy usage of a slow backing
5973 * device. The only option is to throttle from reclaim
5974 * context which is not ideal as there is no guarantee
5975 * the dirtying process is throttled in the same way
5976 * balance_dirty_pages() manages.
5978 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5979 * count the number of pages under pages flagged for
5980 * immediate reclaim and stall if any are encountered
5981 * in the nr_immediate check below.
5983 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5984 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
5986 /* Allow kswapd to start writing pages during reclaim.*/
5987 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5988 set_bit(PGDAT_DIRTY, &pgdat->flags);
5991 * If kswapd scans pages marked for immediate
5992 * reclaim and under writeback (nr_immediate), it
5993 * implies that pages are cycling through the LRU
5994 * faster than they are written so forcibly stall
5995 * until some pages complete writeback.
5997 if (sc->nr.immediate)
5998 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6002 * Tag a node/memcg as congested if all the dirty pages were marked
6003 * for writeback and immediate reclaim (counted in nr.congested).
6005 * Legacy memcg will stall in page writeback so avoid forcibly
6006 * stalling in reclaim_throttle().
6008 if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested) {
6009 if (cgroup_reclaim(sc) && writeback_throttling_sane(sc))
6010 set_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags);
6012 if (current_is_kswapd())
6013 set_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags);
6017 * Stall direct reclaim for IO completions if the lruvec is
6018 * node is congested. Allow kswapd to continue until it
6019 * starts encountering unqueued dirty pages or cycling through
6020 * the LRU too quickly.
6022 if (!current_is_kswapd() && current_may_throttle() &&
6023 !sc->hibernation_mode &&
6024 (test_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags) ||
6025 test_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags)))
6026 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6028 if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc))
6032 * Kswapd gives up on balancing particular nodes after too
6033 * many failures to reclaim anything from them and goes to
6034 * sleep. On reclaim progress, reset the failure counter. A
6035 * successful direct reclaim run will revive a dormant kswapd.
6038 pgdat->kswapd_failures = 0;
6039 else if (sc->cache_trim_mode)
6040 sc->cache_trim_mode_failed = 1;
6044 * Returns true if compaction should go ahead for a costly-order request, or
6045 * the allocation would already succeed without compaction. Return false if we
6046 * should reclaim first.
6048 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6050 unsigned long watermark;
6052 if (!gfp_compaction_allowed(sc->gfp_mask))
6055 /* Allocation can already succeed, nothing to do */
6056 if (zone_watermark_ok(zone, sc->order, min_wmark_pages(zone),
6057 sc->reclaim_idx, 0))
6060 /* Compaction cannot yet proceed. Do reclaim. */
6061 if (!compaction_suitable(zone, sc->order, sc->reclaim_idx))
6065 * Compaction is already possible, but it takes time to run and there
6066 * are potentially other callers using the pages just freed. So proceed
6067 * with reclaim to make a buffer of free pages available to give
6068 * compaction a reasonable chance of completing and allocating the page.
6069 * Note that we won't actually reclaim the whole buffer in one attempt
6070 * as the target watermark in should_continue_reclaim() is lower. But if
6071 * we are already above the high+gap watermark, don't reclaim at all.
6073 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6075 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6078 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6081 * If reclaim is making progress greater than 12% efficiency then
6082 * wake all the NOPROGRESS throttled tasks.
6084 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6085 wait_queue_head_t *wqh;
6087 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6088 if (waitqueue_active(wqh))
6095 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6096 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6097 * under writeback and marked for immediate reclaim at the tail of the
6100 if (current_is_kswapd() || cgroup_reclaim(sc))
6103 /* Throttle if making no progress at high prioities. */
6104 if (sc->priority == 1 && !sc->nr_reclaimed)
6105 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6109 * This is the direct reclaim path, for page-allocating processes. We only
6110 * try to reclaim pages from zones which will satisfy the caller's allocation
6113 * If a zone is deemed to be full of pinned pages then just give it a light
6114 * scan then give up on it.
6116 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6120 unsigned long nr_soft_reclaimed;
6121 unsigned long nr_soft_scanned;
6123 pg_data_t *last_pgdat = NULL;
6124 pg_data_t *first_pgdat = NULL;
6127 * If the number of buffer_heads in the machine exceeds the maximum
6128 * allowed level, force direct reclaim to scan the highmem zone as
6129 * highmem pages could be pinning lowmem pages storing buffer_heads
6131 orig_mask = sc->gfp_mask;
6132 if (buffer_heads_over_limit) {
6133 sc->gfp_mask |= __GFP_HIGHMEM;
6134 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6137 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6138 sc->reclaim_idx, sc->nodemask) {
6140 * Take care memory controller reclaiming has small influence
6143 if (!cgroup_reclaim(sc)) {
6144 if (!cpuset_zone_allowed(zone,
6145 GFP_KERNEL | __GFP_HARDWALL))
6149 * If we already have plenty of memory free for
6150 * compaction in this zone, don't free any more.
6151 * Even though compaction is invoked for any
6152 * non-zero order, only frequent costly order
6153 * reclamation is disruptive enough to become a
6154 * noticeable problem, like transparent huge
6157 if (IS_ENABLED(CONFIG_COMPACTION) &&
6158 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6159 compaction_ready(zone, sc)) {
6160 sc->compaction_ready = true;
6165 * Shrink each node in the zonelist once. If the
6166 * zonelist is ordered by zone (not the default) then a
6167 * node may be shrunk multiple times but in that case
6168 * the user prefers lower zones being preserved.
6170 if (zone->zone_pgdat == last_pgdat)
6174 * This steals pages from memory cgroups over softlimit
6175 * and returns the number of reclaimed pages and
6176 * scanned pages. This works for global memory pressure
6177 * and balancing, not for a memcg's limit.
6179 nr_soft_scanned = 0;
6180 nr_soft_reclaimed = memcg1_soft_limit_reclaim(zone->zone_pgdat,
6181 sc->order, sc->gfp_mask,
6183 sc->nr_reclaimed += nr_soft_reclaimed;
6184 sc->nr_scanned += nr_soft_scanned;
6185 /* need some check for avoid more shrink_zone() */
6189 first_pgdat = zone->zone_pgdat;
6191 /* See comment about same check for global reclaim above */
6192 if (zone->zone_pgdat == last_pgdat)
6194 last_pgdat = zone->zone_pgdat;
6195 shrink_node(zone->zone_pgdat, sc);
6199 consider_reclaim_throttle(first_pgdat, sc);
6202 * Restore to original mask to avoid the impact on the caller if we
6203 * promoted it to __GFP_HIGHMEM.
6205 sc->gfp_mask = orig_mask;
6208 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6210 struct lruvec *target_lruvec;
6211 unsigned long refaults;
6213 if (lru_gen_enabled())
6216 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6217 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6218 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6219 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6220 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6224 * This is the main entry point to direct page reclaim.
6226 * If a full scan of the inactive list fails to free enough memory then we
6227 * are "out of memory" and something needs to be killed.
6229 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6230 * high - the zone may be full of dirty or under-writeback pages, which this
6231 * caller can't do much about. We kick the writeback threads and take explicit
6232 * naps in the hope that some of these pages can be written. But if the
6233 * allocating task holds filesystem locks which prevent writeout this might not
6234 * work, and the allocation attempt will fail.
6236 * returns: 0, if no pages reclaimed
6237 * else, the number of pages reclaimed
6239 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6240 struct scan_control *sc)
6242 int initial_priority = sc->priority;
6243 pg_data_t *last_pgdat;
6247 delayacct_freepages_start();
6249 if (!cgroup_reclaim(sc))
6250 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6254 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6257 shrink_zones(zonelist, sc);
6259 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6262 if (sc->compaction_ready)
6266 * If we're getting trouble reclaiming, start doing
6267 * writepage even in laptop mode.
6269 if (sc->priority < DEF_PRIORITY - 2)
6270 sc->may_writepage = 1;
6271 } while (--sc->priority >= 0);
6274 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6276 if (zone->zone_pgdat == last_pgdat)
6278 last_pgdat = zone->zone_pgdat;
6280 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6282 if (cgroup_reclaim(sc)) {
6283 struct lruvec *lruvec;
6285 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6287 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags);
6291 delayacct_freepages_end();
6293 if (sc->nr_reclaimed)
6294 return sc->nr_reclaimed;
6296 /* Aborted reclaim to try compaction? don't OOM, then */
6297 if (sc->compaction_ready)
6301 * In most cases, direct reclaimers can do partial walks
6302 * through the cgroup tree to meet the reclaim goal while
6303 * keeping latency low. Since the iterator state is shared
6304 * among all direct reclaim invocations (to retain fairness
6305 * among cgroups), though, high concurrency can result in
6306 * individual threads not seeing enough cgroups to make
6307 * meaningful forward progress. Avoid false OOMs in this case.
6309 if (!sc->memcg_full_walk) {
6310 sc->priority = initial_priority;
6311 sc->memcg_full_walk = 1;
6316 * We make inactive:active ratio decisions based on the node's
6317 * composition of memory, but a restrictive reclaim_idx or a
6318 * memory.low cgroup setting can exempt large amounts of
6319 * memory from reclaim. Neither of which are very common, so
6320 * instead of doing costly eligibility calculations of the
6321 * entire cgroup subtree up front, we assume the estimates are
6322 * good, and retry with forcible deactivation if that fails.
6324 if (sc->skipped_deactivate) {
6325 sc->priority = initial_priority;
6326 sc->force_deactivate = 1;
6327 sc->skipped_deactivate = 0;
6331 /* Untapped cgroup reserves? Don't OOM, retry. */
6332 if (sc->memcg_low_skipped) {
6333 sc->priority = initial_priority;
6334 sc->force_deactivate = 0;
6335 sc->memcg_low_reclaim = 1;
6336 sc->memcg_low_skipped = 0;
6343 static bool allow_direct_reclaim(pg_data_t *pgdat)
6346 unsigned long pfmemalloc_reserve = 0;
6347 unsigned long free_pages = 0;
6351 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6354 for (i = 0; i <= ZONE_NORMAL; i++) {
6355 zone = &pgdat->node_zones[i];
6356 if (!managed_zone(zone))
6359 if (!zone_reclaimable_pages(zone))
6362 pfmemalloc_reserve += min_wmark_pages(zone);
6363 free_pages += zone_page_state_snapshot(zone, NR_FREE_PAGES);
6366 /* If there are no reserves (unexpected config) then do not throttle */
6367 if (!pfmemalloc_reserve)
6370 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6372 /* kswapd must be awake if processes are being throttled */
6373 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6374 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6375 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6377 wake_up_interruptible(&pgdat->kswapd_wait);
6384 * Throttle direct reclaimers if backing storage is backed by the network
6385 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6386 * depleted. kswapd will continue to make progress and wake the processes
6387 * when the low watermark is reached.
6389 * Returns true if a fatal signal was delivered during throttling. If this
6390 * happens, the page allocator should not consider triggering the OOM killer.
6392 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6393 nodemask_t *nodemask)
6397 pg_data_t *pgdat = NULL;
6400 * Kernel threads should not be throttled as they may be indirectly
6401 * responsible for cleaning pages necessary for reclaim to make forward
6402 * progress. kjournald for example may enter direct reclaim while
6403 * committing a transaction where throttling it could forcing other
6404 * processes to block on log_wait_commit().
6406 if (current->flags & PF_KTHREAD)
6410 * If a fatal signal is pending, this process should not throttle.
6411 * It should return quickly so it can exit and free its memory
6413 if (fatal_signal_pending(current))
6417 * Check if the pfmemalloc reserves are ok by finding the first node
6418 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6419 * GFP_KERNEL will be required for allocating network buffers when
6420 * swapping over the network so ZONE_HIGHMEM is unusable.
6422 * Throttling is based on the first usable node and throttled processes
6423 * wait on a queue until kswapd makes progress and wakes them. There
6424 * is an affinity then between processes waking up and where reclaim
6425 * progress has been made assuming the process wakes on the same node.
6426 * More importantly, processes running on remote nodes will not compete
6427 * for remote pfmemalloc reserves and processes on different nodes
6428 * should make reasonable progress.
6430 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6431 gfp_zone(gfp_mask), nodemask) {
6432 if (zone_idx(zone) > ZONE_NORMAL)
6435 /* Throttle based on the first usable node */
6436 pgdat = zone->zone_pgdat;
6437 if (allow_direct_reclaim(pgdat))
6442 /* If no zone was usable by the allocation flags then do not throttle */
6446 /* Account for the throttling */
6447 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6450 * If the caller cannot enter the filesystem, it's possible that it
6451 * is due to the caller holding an FS lock or performing a journal
6452 * transaction in the case of a filesystem like ext[3|4]. In this case,
6453 * it is not safe to block on pfmemalloc_wait as kswapd could be
6454 * blocked waiting on the same lock. Instead, throttle for up to a
6455 * second before continuing.
6457 if (!(gfp_mask & __GFP_FS))
6458 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6459 allow_direct_reclaim(pgdat), HZ);
6461 /* Throttle until kswapd wakes the process */
6462 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6463 allow_direct_reclaim(pgdat));
6465 if (fatal_signal_pending(current))
6472 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6473 gfp_t gfp_mask, nodemask_t *nodemask)
6475 unsigned long nr_reclaimed;
6476 struct scan_control sc = {
6477 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6478 .gfp_mask = current_gfp_context(gfp_mask),
6479 .reclaim_idx = gfp_zone(gfp_mask),
6481 .nodemask = nodemask,
6482 .priority = DEF_PRIORITY,
6483 .may_writepage = !laptop_mode,
6489 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6490 * Confirm they are large enough for max values.
6492 BUILD_BUG_ON(MAX_PAGE_ORDER >= S8_MAX);
6493 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6494 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6497 * Do not enter reclaim if fatal signal was delivered while throttled.
6498 * 1 is returned so that the page allocator does not OOM kill at this
6501 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6504 set_task_reclaim_state(current, &sc.reclaim_state);
6505 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6507 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6509 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6510 set_task_reclaim_state(current, NULL);
6512 return nr_reclaimed;
6517 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6518 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6519 gfp_t gfp_mask, bool noswap,
6521 unsigned long *nr_scanned)
6523 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6524 struct scan_control sc = {
6525 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6526 .target_mem_cgroup = memcg,
6527 .may_writepage = !laptop_mode,
6529 .reclaim_idx = MAX_NR_ZONES - 1,
6530 .may_swap = !noswap,
6533 WARN_ON_ONCE(!current->reclaim_state);
6535 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6536 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6538 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6542 * NOTE: Although we can get the priority field, using it
6543 * here is not a good idea, since it limits the pages we can scan.
6544 * if we don't reclaim here, the shrink_node from balance_pgdat
6545 * will pick up pages from other mem cgroup's as well. We hack
6546 * the priority and make it zero.
6548 shrink_lruvec(lruvec, &sc);
6550 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6552 *nr_scanned = sc.nr_scanned;
6554 return sc.nr_reclaimed;
6557 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6558 unsigned long nr_pages,
6560 unsigned int reclaim_options,
6563 unsigned long nr_reclaimed;
6564 unsigned int noreclaim_flag;
6565 struct scan_control sc = {
6566 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6567 .proactive_swappiness = swappiness,
6568 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6569 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6570 .reclaim_idx = MAX_NR_ZONES - 1,
6571 .target_mem_cgroup = memcg,
6572 .priority = DEF_PRIORITY,
6573 .may_writepage = !laptop_mode,
6575 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6576 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
6579 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6580 * equal pressure on all the nodes. This is based on the assumption that
6581 * the reclaim does not bail out early.
6583 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6585 set_task_reclaim_state(current, &sc.reclaim_state);
6586 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6587 noreclaim_flag = memalloc_noreclaim_save();
6589 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6591 memalloc_noreclaim_restore(noreclaim_flag);
6592 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6593 set_task_reclaim_state(current, NULL);
6595 return nr_reclaimed;
6599 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6601 struct mem_cgroup *memcg;
6602 struct lruvec *lruvec;
6604 if (lru_gen_enabled()) {
6605 lru_gen_age_node(pgdat, sc);
6609 if (!can_age_anon_pages(pgdat, sc))
6612 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6613 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6616 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6618 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6619 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6620 sc, LRU_ACTIVE_ANON);
6621 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6625 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
6631 * Check for watermark boosts top-down as the higher zones
6632 * are more likely to be boosted. Both watermarks and boosts
6633 * should not be checked at the same time as reclaim would
6634 * start prematurely when there is no boosting and a lower
6637 for (i = highest_zoneidx; i >= 0; i--) {
6638 zone = pgdat->node_zones + i;
6639 if (!managed_zone(zone))
6642 if (zone->watermark_boost)
6650 * Returns true if there is an eligible zone balanced for the request order
6651 * and highest_zoneidx
6653 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
6656 unsigned long mark = -1;
6660 * Check watermarks bottom-up as lower zones are more likely to
6663 for (i = 0; i <= highest_zoneidx; i++) {
6664 zone = pgdat->node_zones + i;
6666 if (!managed_zone(zone))
6669 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
6670 mark = promo_wmark_pages(zone);
6672 mark = high_wmark_pages(zone);
6673 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
6678 * If a node has no managed zone within highest_zoneidx, it does not
6679 * need balancing by definition. This can happen if a zone-restricted
6680 * allocation tries to wake a remote kswapd.
6688 /* Clear pgdat state for congested, dirty or under writeback. */
6689 static void clear_pgdat_congested(pg_data_t *pgdat)
6691 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6693 clear_bit(LRUVEC_NODE_CONGESTED, &lruvec->flags);
6694 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags);
6695 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6696 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6700 * Prepare kswapd for sleeping. This verifies that there are no processes
6701 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6703 * Returns true if kswapd is ready to sleep
6705 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6706 int highest_zoneidx)
6709 * The throttled processes are normally woken up in balance_pgdat() as
6710 * soon as allow_direct_reclaim() is true. But there is a potential
6711 * race between when kswapd checks the watermarks and a process gets
6712 * throttled. There is also a potential race if processes get
6713 * throttled, kswapd wakes, a large process exits thereby balancing the
6714 * zones, which causes kswapd to exit balance_pgdat() before reaching
6715 * the wake up checks. If kswapd is going to sleep, no process should
6716 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6717 * the wake up is premature, processes will wake kswapd and get
6718 * throttled again. The difference from wake ups in balance_pgdat() is
6719 * that here we are under prepare_to_wait().
6721 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6722 wake_up_all(&pgdat->pfmemalloc_wait);
6724 /* Hopeless node, leave it to direct reclaim */
6725 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6728 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
6729 clear_pgdat_congested(pgdat);
6737 * kswapd shrinks a node of pages that are at or below the highest usable
6738 * zone that is currently unbalanced.
6740 * Returns true if kswapd scanned at least the requested number of pages to
6741 * reclaim or if the lack of progress was due to pages under writeback.
6742 * This is used to determine if the scanning priority needs to be raised.
6744 static bool kswapd_shrink_node(pg_data_t *pgdat,
6745 struct scan_control *sc)
6749 unsigned long nr_reclaimed = sc->nr_reclaimed;
6751 /* Reclaim a number of pages proportional to the number of zones */
6752 sc->nr_to_reclaim = 0;
6753 for (z = 0; z <= sc->reclaim_idx; z++) {
6754 zone = pgdat->node_zones + z;
6755 if (!managed_zone(zone))
6758 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6762 * Historically care was taken to put equal pressure on all zones but
6763 * now pressure is applied based on node LRU order.
6765 shrink_node(pgdat, sc);
6768 * Fragmentation may mean that the system cannot be rebalanced for
6769 * high-order allocations. If twice the allocation size has been
6770 * reclaimed then recheck watermarks only at order-0 to prevent
6771 * excessive reclaim. Assume that a process requested a high-order
6772 * can direct reclaim/compact.
6774 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6777 /* account for progress from mm_account_reclaimed_pages() */
6778 return max(sc->nr_scanned, sc->nr_reclaimed - nr_reclaimed) >= sc->nr_to_reclaim;
6781 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6783 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6788 for (i = 0; i <= highest_zoneidx; i++) {
6789 zone = pgdat->node_zones + i;
6791 if (!managed_zone(zone))
6795 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6797 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6802 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6804 update_reclaim_active(pgdat, highest_zoneidx, true);
6808 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6810 update_reclaim_active(pgdat, highest_zoneidx, false);
6814 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6815 * that are eligible for use by the caller until at least one zone is
6818 * Returns the order kswapd finished reclaiming at.
6820 * kswapd scans the zones in the highmem->normal->dma direction. It skips
6821 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6822 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6823 * or lower is eligible for reclaim until at least one usable zone is
6826 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
6829 unsigned long nr_soft_reclaimed;
6830 unsigned long nr_soft_scanned;
6831 unsigned long pflags;
6832 unsigned long nr_boost_reclaim;
6833 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6836 struct scan_control sc = {
6837 .gfp_mask = GFP_KERNEL,
6842 set_task_reclaim_state(current, &sc.reclaim_state);
6843 psi_memstall_enter(&pflags);
6844 __fs_reclaim_acquire(_THIS_IP_);
6846 count_vm_event(PAGEOUTRUN);
6849 * Account for the reclaim boost. Note that the zone boost is left in
6850 * place so that parallel allocations that are near the watermark will
6851 * stall or direct reclaim until kswapd is finished.
6853 nr_boost_reclaim = 0;
6854 for (i = 0; i <= highest_zoneidx; i++) {
6855 zone = pgdat->node_zones + i;
6856 if (!managed_zone(zone))
6859 nr_boost_reclaim += zone->watermark_boost;
6860 zone_boosts[i] = zone->watermark_boost;
6862 boosted = nr_boost_reclaim;
6865 set_reclaim_active(pgdat, highest_zoneidx);
6866 sc.priority = DEF_PRIORITY;
6868 unsigned long nr_reclaimed = sc.nr_reclaimed;
6869 bool raise_priority = true;
6874 sc.reclaim_idx = highest_zoneidx;
6877 * If the number of buffer_heads exceeds the maximum allowed
6878 * then consider reclaiming from all zones. This has a dual
6879 * purpose -- on 64-bit systems it is expected that
6880 * buffer_heads are stripped during active rotation. On 32-bit
6881 * systems, highmem pages can pin lowmem memory and shrinking
6882 * buffers can relieve lowmem pressure. Reclaim may still not
6883 * go ahead if all eligible zones for the original allocation
6884 * request are balanced to avoid excessive reclaim from kswapd.
6886 if (buffer_heads_over_limit) {
6887 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6888 zone = pgdat->node_zones + i;
6889 if (!managed_zone(zone))
6898 * If the pgdat is imbalanced then ignore boosting and preserve
6899 * the watermarks for a later time and restart. Note that the
6900 * zone watermarks will be still reset at the end of balancing
6901 * on the grounds that the normal reclaim should be enough to
6902 * re-evaluate if boosting is required when kswapd next wakes.
6904 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
6905 if (!balanced && nr_boost_reclaim) {
6906 nr_boost_reclaim = 0;
6911 * If boosting is not active then only reclaim if there are no
6912 * eligible zones. Note that sc.reclaim_idx is not used as
6913 * buffer_heads_over_limit may have adjusted it.
6915 if (!nr_boost_reclaim && balanced)
6918 /* Limit the priority of boosting to avoid reclaim writeback */
6919 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6920 raise_priority = false;
6923 * Do not writeback or swap pages for boosted reclaim. The
6924 * intent is to relieve pressure not issue sub-optimal IO
6925 * from reclaim context. If no pages are reclaimed, the
6926 * reclaim will be aborted.
6928 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6929 sc.may_swap = !nr_boost_reclaim;
6932 * Do some background aging, to give pages a chance to be
6933 * referenced before reclaiming. All pages are rotated
6934 * regardless of classzone as this is about consistent aging.
6936 kswapd_age_node(pgdat, &sc);
6939 * If we're getting trouble reclaiming, start doing writepage
6940 * even in laptop mode.
6942 if (sc.priority < DEF_PRIORITY - 2)
6943 sc.may_writepage = 1;
6945 /* Call soft limit reclaim before calling shrink_node. */
6947 nr_soft_scanned = 0;
6948 nr_soft_reclaimed = memcg1_soft_limit_reclaim(pgdat, sc.order,
6949 sc.gfp_mask, &nr_soft_scanned);
6950 sc.nr_reclaimed += nr_soft_reclaimed;
6953 * There should be no need to raise the scanning priority if
6954 * enough pages are already being scanned that that high
6955 * watermark would be met at 100% efficiency.
6957 if (kswapd_shrink_node(pgdat, &sc))
6958 raise_priority = false;
6961 * If the low watermark is met there is no need for processes
6962 * to be throttled on pfmemalloc_wait as they should not be
6963 * able to safely make forward progress. Wake them
6965 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
6966 allow_direct_reclaim(pgdat))
6967 wake_up_all(&pgdat->pfmemalloc_wait);
6969 /* Check if kswapd should be suspending */
6970 __fs_reclaim_release(_THIS_IP_);
6971 ret = kthread_freezable_should_stop(&was_frozen);
6972 __fs_reclaim_acquire(_THIS_IP_);
6973 if (was_frozen || ret)
6977 * Raise priority if scanning rate is too low or there was no
6978 * progress in reclaiming pages
6980 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
6981 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6984 * If reclaim made no progress for a boost, stop reclaim as
6985 * IO cannot be queued and it could be an infinite loop in
6986 * extreme circumstances.
6988 if (nr_boost_reclaim && !nr_reclaimed)
6991 if (raise_priority || !nr_reclaimed)
6993 } while (sc.priority >= 1);
6996 * Restart only if it went through the priority loop all the way,
6997 * but cache_trim_mode didn't work.
6999 if (!sc.nr_reclaimed && sc.priority < 1 &&
7000 !sc.no_cache_trim_mode && sc.cache_trim_mode_failed) {
7001 sc.no_cache_trim_mode = 1;
7005 if (!sc.nr_reclaimed)
7006 pgdat->kswapd_failures++;
7009 clear_reclaim_active(pgdat, highest_zoneidx);
7011 /* If reclaim was boosted, account for the reclaim done in this pass */
7013 unsigned long flags;
7015 for (i = 0; i <= highest_zoneidx; i++) {
7016 if (!zone_boosts[i])
7019 /* Increments are under the zone lock */
7020 zone = pgdat->node_zones + i;
7021 spin_lock_irqsave(&zone->lock, flags);
7022 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7023 spin_unlock_irqrestore(&zone->lock, flags);
7027 * As there is now likely space, wakeup kcompact to defragment
7030 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7033 snapshot_refaults(NULL, pgdat);
7034 __fs_reclaim_release(_THIS_IP_);
7035 psi_memstall_leave(&pflags);
7036 set_task_reclaim_state(current, NULL);
7039 * Return the order kswapd stopped reclaiming at as
7040 * prepare_kswapd_sleep() takes it into account. If another caller
7041 * entered the allocator slow path while kswapd was awake, order will
7042 * remain at the higher level.
7048 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7049 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7050 * not a valid index then either kswapd runs for first time or kswapd couldn't
7051 * sleep after previous reclaim attempt (node is still unbalanced). In that
7052 * case return the zone index of the previous kswapd reclaim cycle.
7054 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7055 enum zone_type prev_highest_zoneidx)
7057 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7059 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7062 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7063 unsigned int highest_zoneidx)
7068 if (freezing(current) || kthread_should_stop())
7071 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7074 * Try to sleep for a short interval. Note that kcompactd will only be
7075 * woken if it is possible to sleep for a short interval. This is
7076 * deliberate on the assumption that if reclaim cannot keep an
7077 * eligible zone balanced that it's also unlikely that compaction will
7080 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7082 * Compaction records what page blocks it recently failed to
7083 * isolate pages from and skips them in the future scanning.
7084 * When kswapd is going to sleep, it is reasonable to assume
7085 * that pages and compaction may succeed so reset the cache.
7087 reset_isolation_suitable(pgdat);
7090 * We have freed the memory, now we should compact it to make
7091 * allocation of the requested order possible.
7093 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7095 remaining = schedule_timeout(HZ/10);
7098 * If woken prematurely then reset kswapd_highest_zoneidx and
7099 * order. The values will either be from a wakeup request or
7100 * the previous request that slept prematurely.
7103 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7104 kswapd_highest_zoneidx(pgdat,
7107 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7108 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7111 finish_wait(&pgdat->kswapd_wait, &wait);
7112 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7116 * After a short sleep, check if it was a premature sleep. If not, then
7117 * go fully to sleep until explicitly woken up.
7120 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7121 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7124 * vmstat counters are not perfectly accurate and the estimated
7125 * value for counters such as NR_FREE_PAGES can deviate from the
7126 * true value by nr_online_cpus * threshold. To avoid the zone
7127 * watermarks being breached while under pressure, we reduce the
7128 * per-cpu vmstat threshold while kswapd is awake and restore
7129 * them before going back to sleep.
7131 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7133 if (!kthread_should_stop())
7136 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7139 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7141 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7143 finish_wait(&pgdat->kswapd_wait, &wait);
7147 * The background pageout daemon, started as a kernel thread
7148 * from the init process.
7150 * This basically trickles out pages so that we have _some_
7151 * free memory available even if there is no other activity
7152 * that frees anything up. This is needed for things like routing
7153 * etc, where we otherwise might have all activity going on in
7154 * asynchronous contexts that cannot page things out.
7156 * If there are applications that are active memory-allocators
7157 * (most normal use), this basically shouldn't matter.
7159 static int kswapd(void *p)
7161 unsigned int alloc_order, reclaim_order;
7162 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7163 pg_data_t *pgdat = (pg_data_t *)p;
7164 struct task_struct *tsk = current;
7165 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7167 if (!cpumask_empty(cpumask))
7168 set_cpus_allowed_ptr(tsk, cpumask);
7171 * Tell the memory management that we're a "memory allocator",
7172 * and that if we need more memory we should get access to it
7173 * regardless (see "__alloc_pages()"). "kswapd" should
7174 * never get caught in the normal page freeing logic.
7176 * (Kswapd normally doesn't need memory anyway, but sometimes
7177 * you need a small amount of memory in order to be able to
7178 * page out something else, and this flag essentially protects
7179 * us from recursively trying to free more memory as we're
7180 * trying to free the first piece of memory in the first place).
7182 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7185 WRITE_ONCE(pgdat->kswapd_order, 0);
7186 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7187 atomic_set(&pgdat->nr_writeback_throttled, 0);
7191 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7192 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7196 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7199 /* Read the new order and highest_zoneidx */
7200 alloc_order = READ_ONCE(pgdat->kswapd_order);
7201 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7203 WRITE_ONCE(pgdat->kswapd_order, 0);
7204 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7206 if (kthread_freezable_should_stop(&was_frozen))
7210 * We can speed up thawing tasks if we don't call balance_pgdat
7211 * after returning from the refrigerator
7217 * Reclaim begins at the requested order but if a high-order
7218 * reclaim fails then kswapd falls back to reclaiming for
7219 * order-0. If that happens, kswapd will consider sleeping
7220 * for the order it finished reclaiming at (reclaim_order)
7221 * but kcompactd is woken to compact for the original
7222 * request (alloc_order).
7224 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7226 reclaim_order = balance_pgdat(pgdat, alloc_order,
7228 if (reclaim_order < alloc_order)
7229 goto kswapd_try_sleep;
7232 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7238 * A zone is low on free memory or too fragmented for high-order memory. If
7239 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7240 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7241 * has failed or is not needed, still wake up kcompactd if only compaction is
7244 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7245 enum zone_type highest_zoneidx)
7248 enum zone_type curr_idx;
7250 if (!managed_zone(zone))
7253 if (!cpuset_zone_allowed(zone, gfp_flags))
7256 pgdat = zone->zone_pgdat;
7257 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7259 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7260 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7262 if (READ_ONCE(pgdat->kswapd_order) < order)
7263 WRITE_ONCE(pgdat->kswapd_order, order);
7265 if (!waitqueue_active(&pgdat->kswapd_wait))
7268 /* Hopeless node, leave it to direct reclaim if possible */
7269 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7270 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7271 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7273 * There may be plenty of free memory available, but it's too
7274 * fragmented for high-order allocations. Wake up kcompactd
7275 * and rely on compaction_suitable() to determine if it's
7276 * needed. If it fails, it will defer subsequent attempts to
7277 * ratelimit its work.
7279 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7280 wakeup_kcompactd(pgdat, order, highest_zoneidx);
7284 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7286 wake_up_interruptible(&pgdat->kswapd_wait);
7289 #ifdef CONFIG_HIBERNATION
7291 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7294 * Rather than trying to age LRUs the aim is to preserve the overall
7295 * LRU order by reclaiming preferentially
7296 * inactive > active > active referenced > active mapped
7298 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7300 struct scan_control sc = {
7301 .nr_to_reclaim = nr_to_reclaim,
7302 .gfp_mask = GFP_HIGHUSER_MOVABLE,
7303 .reclaim_idx = MAX_NR_ZONES - 1,
7304 .priority = DEF_PRIORITY,
7308 .hibernation_mode = 1,
7310 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7311 unsigned long nr_reclaimed;
7312 unsigned int noreclaim_flag;
7314 fs_reclaim_acquire(sc.gfp_mask);
7315 noreclaim_flag = memalloc_noreclaim_save();
7316 set_task_reclaim_state(current, &sc.reclaim_state);
7318 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7320 set_task_reclaim_state(current, NULL);
7321 memalloc_noreclaim_restore(noreclaim_flag);
7322 fs_reclaim_release(sc.gfp_mask);
7324 return nr_reclaimed;
7326 #endif /* CONFIG_HIBERNATION */
7329 * This kswapd start function will be called by init and node-hot-add.
7331 void __meminit kswapd_run(int nid)
7333 pg_data_t *pgdat = NODE_DATA(nid);
7335 pgdat_kswapd_lock(pgdat);
7336 if (!pgdat->kswapd) {
7337 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7338 if (IS_ERR(pgdat->kswapd)) {
7339 /* failure at boot is fatal */
7340 pr_err("Failed to start kswapd on node %d,ret=%ld\n",
7341 nid, PTR_ERR(pgdat->kswapd));
7342 BUG_ON(system_state < SYSTEM_RUNNING);
7343 pgdat->kswapd = NULL;
7346 pgdat_kswapd_unlock(pgdat);
7350 * Called by memory hotplug when all memory in a node is offlined. Caller must
7351 * be holding mem_hotplug_begin/done().
7353 void __meminit kswapd_stop(int nid)
7355 pg_data_t *pgdat = NODE_DATA(nid);
7356 struct task_struct *kswapd;
7358 pgdat_kswapd_lock(pgdat);
7359 kswapd = pgdat->kswapd;
7361 kthread_stop(kswapd);
7362 pgdat->kswapd = NULL;
7364 pgdat_kswapd_unlock(pgdat);
7367 static int __init kswapd_init(void)
7372 for_each_node_state(nid, N_MEMORY)
7377 module_init(kswapd_init)
7383 * If non-zero call node_reclaim when the number of free pages falls below
7386 int node_reclaim_mode __read_mostly;
7389 * Priority for NODE_RECLAIM. This determines the fraction of pages
7390 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7393 #define NODE_RECLAIM_PRIORITY 4
7396 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7399 int sysctl_min_unmapped_ratio = 1;
7402 * If the number of slab pages in a zone grows beyond this percentage then
7403 * slab reclaim needs to occur.
7405 int sysctl_min_slab_ratio = 5;
7407 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7409 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7410 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7411 node_page_state(pgdat, NR_ACTIVE_FILE);
7414 * It's possible for there to be more file mapped pages than
7415 * accounted for by the pages on the file LRU lists because
7416 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7418 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7421 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7422 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7424 unsigned long nr_pagecache_reclaimable;
7425 unsigned long delta = 0;
7428 * If RECLAIM_UNMAP is set, then all file pages are considered
7429 * potentially reclaimable. Otherwise, we have to worry about
7430 * pages like swapcache and node_unmapped_file_pages() provides
7433 if (node_reclaim_mode & RECLAIM_UNMAP)
7434 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7436 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7438 /* If we can't clean pages, remove dirty pages from consideration */
7439 if (!(node_reclaim_mode & RECLAIM_WRITE))
7440 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7442 /* Watch for any possible underflows due to delta */
7443 if (unlikely(delta > nr_pagecache_reclaimable))
7444 delta = nr_pagecache_reclaimable;
7446 return nr_pagecache_reclaimable - delta;
7450 * Try to free up some pages from this node through reclaim.
7452 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7454 /* Minimum pages needed in order to stay on node */
7455 const unsigned long nr_pages = 1 << order;
7456 struct task_struct *p = current;
7457 unsigned int noreclaim_flag;
7458 struct scan_control sc = {
7459 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7460 .gfp_mask = current_gfp_context(gfp_mask),
7462 .priority = NODE_RECLAIM_PRIORITY,
7463 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7464 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7466 .reclaim_idx = gfp_zone(gfp_mask),
7468 unsigned long pflags;
7470 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7474 psi_memstall_enter(&pflags);
7475 delayacct_freepages_start();
7476 fs_reclaim_acquire(sc.gfp_mask);
7478 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7480 noreclaim_flag = memalloc_noreclaim_save();
7481 set_task_reclaim_state(p, &sc.reclaim_state);
7483 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7484 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7486 * Free memory by calling shrink node with increasing
7487 * priorities until we have enough memory freed.
7490 shrink_node(pgdat, &sc);
7491 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7494 set_task_reclaim_state(p, NULL);
7495 memalloc_noreclaim_restore(noreclaim_flag);
7496 fs_reclaim_release(sc.gfp_mask);
7497 psi_memstall_leave(&pflags);
7498 delayacct_freepages_end();
7500 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7502 return sc.nr_reclaimed >= nr_pages;
7505 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7510 * Node reclaim reclaims unmapped file backed pages and
7511 * slab pages if we are over the defined limits.
7513 * A small portion of unmapped file backed pages is needed for
7514 * file I/O otherwise pages read by file I/O will be immediately
7515 * thrown out if the node is overallocated. So we do not reclaim
7516 * if less than a specified percentage of the node is used by
7517 * unmapped file backed pages.
7519 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7520 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7521 pgdat->min_slab_pages)
7522 return NODE_RECLAIM_FULL;
7525 * Do not scan if the allocation should not be delayed.
7527 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7528 return NODE_RECLAIM_NOSCAN;
7531 * Only run node reclaim on the local node or on nodes that do not
7532 * have associated processors. This will favor the local processor
7533 * over remote processors and spread off node memory allocations
7534 * as wide as possible.
7536 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7537 return NODE_RECLAIM_NOSCAN;
7539 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7540 return NODE_RECLAIM_NOSCAN;
7542 ret = __node_reclaim(pgdat, gfp_mask, order);
7543 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7546 count_vm_event(PGSCAN_ZONE_RECLAIM_SUCCESS);
7548 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7555 * check_move_unevictable_folios - Move evictable folios to appropriate zone
7557 * @fbatch: Batch of lru folios to check.
7559 * Checks folios for evictability, if an evictable folio is in the unevictable
7560 * lru list, moves it to the appropriate evictable lru list. This function
7561 * should be only used for lru folios.
7563 void check_move_unevictable_folios(struct folio_batch *fbatch)
7565 struct lruvec *lruvec = NULL;
7570 for (i = 0; i < fbatch->nr; i++) {
7571 struct folio *folio = fbatch->folios[i];
7572 int nr_pages = folio_nr_pages(folio);
7574 pgscanned += nr_pages;
7576 /* block memcg migration while the folio moves between lrus */
7577 if (!folio_test_clear_lru(folio))
7580 lruvec = folio_lruvec_relock_irq(folio, lruvec);
7581 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
7582 lruvec_del_folio(lruvec, folio);
7583 folio_clear_unevictable(folio);
7584 lruvec_add_folio(lruvec, folio);
7585 pgrescued += nr_pages;
7587 folio_set_lru(folio);
7591 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7592 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7593 unlock_page_lruvec_irq(lruvec);
7594 } else if (pgscanned) {
7595 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7598 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);