1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 #include <linux/sched/mm.h>
17 #include <linux/module.h>
18 #include <linux/gfp.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/swap.h>
21 #include <linux/pagemap.h>
22 #include <linux/init.h>
23 #include <linux/highmem.h>
24 #include <linux/vmpressure.h>
25 #include <linux/vmstat.h>
26 #include <linux/file.h>
27 #include <linux/writeback.h>
28 #include <linux/blkdev.h>
29 #include <linux/buffer_head.h> /* for 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>
59 #include <linux/mmu_notifier.h>
61 #include <asm/tlbflush.h>
62 #include <asm/div64.h>
64 #include <linux/swapops.h>
65 #include <linux/balloon_compaction.h>
66 #include <linux/sched/sysctl.h>
71 #define CREATE_TRACE_POINTS
72 #include <trace/events/vmscan.h>
75 /* How many pages shrink_list() should reclaim */
76 unsigned long nr_to_reclaim
;
79 * Nodemask of nodes allowed by the caller. If NULL, all nodes
85 * The memory cgroup that hit its limit and as a result is the
86 * primary target of this reclaim invocation.
88 struct mem_cgroup
*target_mem_cgroup
;
91 * Scan pressure balancing between anon and file LRUs
93 unsigned long anon_cost
;
94 unsigned long file_cost
;
97 /* Swappiness value for proactive reclaim. Always use sc_swappiness()! */
98 int *proactive_swappiness
;
101 /* Can active folios be deactivated as part of reclaim? */
102 #define DEACTIVATE_ANON 1
103 #define DEACTIVATE_FILE 2
104 unsigned int may_deactivate
:2;
105 unsigned int force_deactivate
:1;
106 unsigned int skipped_deactivate
:1;
108 /* Writepage batching in laptop mode; RECLAIM_WRITE */
109 unsigned int may_writepage
:1;
111 /* Can mapped folios be reclaimed? */
112 unsigned int may_unmap
:1;
114 /* Can folios be swapped as part of reclaim? */
115 unsigned int may_swap
:1;
117 /* Not allow cache_trim_mode to be turned on as part of reclaim? */
118 unsigned int no_cache_trim_mode
:1;
120 /* Has cache_trim_mode failed at least once? */
121 unsigned int cache_trim_mode_failed
:1;
123 /* Proactive reclaim invoked by userspace through memory.reclaim */
124 unsigned int proactive
:1;
127 * Cgroup memory below memory.low is protected as long as we
128 * don't threaten to OOM. If any cgroup is reclaimed at
129 * reduced force or passed over entirely due to its memory.low
130 * setting (memcg_low_skipped), and nothing is reclaimed as a
131 * result, then go back for one more cycle that reclaims the protected
132 * memory (memcg_low_reclaim) to avert OOM.
134 unsigned int memcg_low_reclaim
:1;
135 unsigned int memcg_low_skipped
:1;
137 /* Shared cgroup tree walk failed, rescan the whole tree */
138 unsigned int memcg_full_walk
:1;
140 unsigned int hibernation_mode
:1;
142 /* One of the zones is ready for compaction */
143 unsigned int compaction_ready
:1;
145 /* There is easily reclaimable cold cache in the current node */
146 unsigned int cache_trim_mode
:1;
148 /* The file folios on the current node are dangerously low */
149 unsigned int file_is_tiny
:1;
151 /* Always discard instead of demoting to lower tier memory */
152 unsigned int no_demotion
:1;
154 /* Allocation order */
157 /* Scan (total_size >> priority) pages at once */
160 /* The highest zone to isolate folios for reclaim from */
163 /* This context's GFP mask */
166 /* Incremented by the number of inactive pages that were scanned */
167 unsigned long nr_scanned
;
169 /* Number of pages freed so far during a call to shrink_zones() */
170 unsigned long nr_reclaimed
;
174 unsigned int unqueued_dirty
;
175 unsigned int congested
;
176 unsigned int writeback
;
177 unsigned int immediate
;
178 unsigned int file_taken
;
182 /* for recording the reclaimed slab by now */
183 struct reclaim_state reclaim_state
;
186 #ifdef ARCH_HAS_PREFETCHW
187 #define prefetchw_prev_lru_folio(_folio, _base, _field) \
189 if ((_folio)->lru.prev != _base) { \
190 struct folio *prev; \
192 prev = lru_to_folio(&(_folio->lru)); \
193 prefetchw(&prev->_field); \
197 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
201 * From 0 .. MAX_SWAPPINESS. Higher means more swappy.
203 int vm_swappiness
= 60;
207 /* Returns true for reclaim through cgroup limits or cgroup interfaces. */
208 static bool cgroup_reclaim(struct scan_control
*sc
)
210 return sc
->target_mem_cgroup
;
214 * Returns true for reclaim on the root cgroup. This is true for direct
215 * allocator reclaim and reclaim through cgroup interfaces on the root cgroup.
217 static bool root_reclaim(struct scan_control
*sc
)
219 return !sc
->target_mem_cgroup
|| mem_cgroup_is_root(sc
->target_mem_cgroup
);
223 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
224 * @sc: scan_control in question
226 * The normal page dirty throttling mechanism in balance_dirty_pages() is
227 * completely broken with the legacy memcg and direct stalling in
228 * shrink_folio_list() is used for throttling instead, which lacks all the
229 * niceties such as fairness, adaptive pausing, bandwidth proportional
230 * allocation and configurability.
232 * This function tests whether the vmscan currently in progress can assume
233 * that the normal dirty throttling mechanism is operational.
235 static bool writeback_throttling_sane(struct scan_control
*sc
)
237 if (!cgroup_reclaim(sc
))
239 #ifdef CONFIG_CGROUP_WRITEBACK
240 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
))
246 static int sc_swappiness(struct scan_control
*sc
, struct mem_cgroup
*memcg
)
248 if (sc
->proactive
&& sc
->proactive_swappiness
)
249 return *sc
->proactive_swappiness
;
250 return mem_cgroup_swappiness(memcg
);
253 static bool cgroup_reclaim(struct scan_control
*sc
)
258 static bool root_reclaim(struct scan_control
*sc
)
263 static bool writeback_throttling_sane(struct scan_control
*sc
)
268 static int sc_swappiness(struct scan_control
*sc
, struct mem_cgroup
*memcg
)
270 return READ_ONCE(vm_swappiness
);
274 /* for_each_managed_zone_pgdat - helper macro to iterate over all managed zones in a pgdat up to
275 * and including the specified highidx
276 * @zone: The current zone in the iterator
277 * @pgdat: The pgdat which node_zones are being iterated
278 * @idx: The index variable
279 * @highidx: The index of the highest zone to return
281 * This macro iterates through all managed zones up to and including the specified highidx.
282 * The zone iterator enters an invalid state after macro call and must be reinitialized
283 * before it can be used again.
285 #define for_each_managed_zone_pgdat(zone, pgdat, idx, highidx) \
286 for ((idx) = 0, (zone) = (pgdat)->node_zones; \
287 (idx) <= (highidx); \
289 if (!managed_zone(zone)) \
293 static void set_task_reclaim_state(struct task_struct
*task
,
294 struct reclaim_state
*rs
)
296 /* Check for an overwrite */
297 WARN_ON_ONCE(rs
&& task
->reclaim_state
);
299 /* Check for the nulling of an already-nulled member */
300 WARN_ON_ONCE(!rs
&& !task
->reclaim_state
);
302 task
->reclaim_state
= rs
;
306 * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to
307 * scan_control->nr_reclaimed.
309 static void flush_reclaim_state(struct scan_control
*sc
)
312 * Currently, reclaim_state->reclaimed includes three types of pages
313 * freed outside of vmscan:
315 * (2) Clean file pages from pruned inodes (on highmem systems).
316 * (3) XFS freed buffer pages.
318 * For all of these cases, we cannot universally link the pages to a
319 * single memcg. For example, a memcg-aware shrinker can free one object
320 * charged to the target memcg, causing an entire page to be freed.
321 * If we count the entire page as reclaimed from the memcg, we end up
322 * overestimating the reclaimed amount (potentially under-reclaiming).
324 * Only count such pages for global reclaim to prevent under-reclaiming
325 * from the target memcg; preventing unnecessary retries during memcg
326 * charging and false positives from proactive reclaim.
328 * For uncommon cases where the freed pages were actually mostly
329 * charged to the target memcg, we end up underestimating the reclaimed
330 * amount. This should be fine. The freed pages will be uncharged
331 * anyway, even if they are not counted here properly, and we will be
332 * able to make forward progress in charging (which is usually in a
335 * We can go one step further, and report the uncharged objcg pages in
336 * memcg reclaim, to make reporting more accurate and reduce
337 * underestimation, but it's probably not worth the complexity for now.
339 if (current
->reclaim_state
&& root_reclaim(sc
)) {
340 sc
->nr_reclaimed
+= current
->reclaim_state
->reclaimed
;
341 current
->reclaim_state
->reclaimed
= 0;
345 static bool can_demote(int nid
, struct scan_control
*sc
,
346 struct mem_cgroup
*memcg
)
350 if (!numa_demotion_enabled
)
352 if (sc
&& sc
->no_demotion
)
355 demotion_nid
= next_demotion_node(nid
);
356 if (demotion_nid
== NUMA_NO_NODE
)
359 /* If demotion node isn't in the cgroup's mems_allowed, fall back */
360 return mem_cgroup_node_allowed(memcg
, demotion_nid
);
363 static inline bool can_reclaim_anon_pages(struct mem_cgroup
*memcg
,
365 struct scan_control
*sc
)
369 * For non-memcg reclaim, is there
370 * space in any swap device?
372 if (get_nr_swap_pages() > 0)
375 /* Is the memcg below its swap limit? */
376 if (mem_cgroup_get_nr_swap_pages(memcg
) > 0)
381 * The page can not be swapped.
383 * Can it be reclaimed from this node via demotion?
385 return can_demote(nid
, sc
, memcg
);
389 * This misses isolated folios which are not accounted for to save counters.
390 * As the data only determines if reclaim or compaction continues, it is
391 * not expected that isolated folios will be a dominating factor.
393 unsigned long zone_reclaimable_pages(struct zone
*zone
)
397 nr
= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_FILE
) +
398 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_FILE
);
399 if (can_reclaim_anon_pages(NULL
, zone_to_nid(zone
), NULL
))
400 nr
+= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_ANON
) +
401 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_ANON
);
403 * If there are no reclaimable file-backed or anonymous pages,
404 * ensure zones with sufficient free pages are not skipped.
405 * This prevents zones like DMA32 from being ignored in reclaim
406 * scenarios where they can still help alleviate memory pressure.
409 nr
= zone_page_state_snapshot(zone
, NR_FREE_PAGES
);
414 * lruvec_lru_size - Returns the number of pages on the given LRU list.
415 * @lruvec: lru vector
417 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
419 static unsigned long lruvec_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
422 unsigned long size
= 0;
426 for_each_managed_zone_pgdat(zone
, lruvec_pgdat(lruvec
), zid
, zone_idx
) {
427 if (!mem_cgroup_disabled())
428 size
+= mem_cgroup_get_zone_lru_size(lruvec
, lru
, zid
);
430 size
+= zone_page_state(zone
, NR_ZONE_LRU_BASE
+ lru
);
435 static unsigned long drop_slab_node(int nid
)
437 unsigned long freed
= 0;
438 struct mem_cgroup
*memcg
= NULL
;
440 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
442 freed
+= shrink_slab(GFP_KERNEL
, nid
, memcg
, 0);
443 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)) != NULL
);
456 for_each_online_node(nid
) {
457 if (fatal_signal_pending(current
))
460 freed
+= drop_slab_node(nid
);
462 } while ((freed
>> shift
++) > 1);
465 #define CHECK_RECLAIMER_OFFSET(type) \
467 BUILD_BUG_ON(PGSTEAL_##type - PGSTEAL_KSWAPD != \
468 PGDEMOTE_##type - PGDEMOTE_KSWAPD); \
469 BUILD_BUG_ON(PGSTEAL_##type - PGSTEAL_KSWAPD != \
470 PGSCAN_##type - PGSCAN_KSWAPD); \
473 static int reclaimer_offset(struct scan_control
*sc
)
475 CHECK_RECLAIMER_OFFSET(DIRECT
);
476 CHECK_RECLAIMER_OFFSET(KHUGEPAGED
);
477 CHECK_RECLAIMER_OFFSET(PROACTIVE
);
479 if (current_is_kswapd())
481 if (current_is_khugepaged())
482 return PGSTEAL_KHUGEPAGED
- PGSTEAL_KSWAPD
;
484 return PGSTEAL_PROACTIVE
- PGSTEAL_KSWAPD
;
485 return PGSTEAL_DIRECT
- PGSTEAL_KSWAPD
;
488 static inline int is_page_cache_freeable(struct folio
*folio
)
491 * A freeable page cache folio is referenced only by the caller
492 * that isolated the folio, the page cache and optional filesystem
493 * private data at folio->private.
495 return folio_ref_count(folio
) - folio_test_private(folio
) ==
496 1 + folio_nr_pages(folio
);
500 * We detected a synchronous write error writing a folio out. Probably
501 * -ENOSPC. We need to propagate that into the address_space for a subsequent
502 * fsync(), msync() or close().
504 * The tricky part is that after writepage we cannot touch the mapping: nothing
505 * prevents it from being freed up. But we have a ref on the folio and once
506 * that folio is locked, the mapping is pinned.
508 * We're allowed to run sleeping folio_lock() here because we know the caller has
511 static void handle_write_error(struct address_space
*mapping
,
512 struct folio
*folio
, int error
)
515 if (folio_mapping(folio
) == mapping
)
516 mapping_set_error(mapping
, error
);
520 static bool skip_throttle_noprogress(pg_data_t
*pgdat
)
522 int reclaimable
= 0, write_pending
= 0;
526 * If kswapd is disabled, reschedule if necessary but do not
527 * throttle as the system is likely near OOM.
529 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
533 * If there are a lot of dirty/writeback folios then do not
534 * throttle as throttling will occur when the folios cycle
535 * towards the end of the LRU if still under writeback.
537 for_each_managed_zone_pgdat(zone
, pgdat
, i
, MAX_NR_ZONES
- 1) {
538 reclaimable
+= zone_reclaimable_pages(zone
);
539 write_pending
+= zone_page_state_snapshot(zone
,
540 NR_ZONE_WRITE_PENDING
);
542 if (2 * write_pending
<= reclaimable
)
548 void reclaim_throttle(pg_data_t
*pgdat
, enum vmscan_throttle_state reason
)
550 wait_queue_head_t
*wqh
= &pgdat
->reclaim_wait
[reason
];
555 * Do not throttle user workers, kthreads other than kswapd or
556 * workqueues. They may be required for reclaim to make
557 * forward progress (e.g. journalling workqueues or kthreads).
559 if (!current_is_kswapd() &&
560 current
->flags
& (PF_USER_WORKER
|PF_KTHREAD
)) {
566 * These figures are pulled out of thin air.
567 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
568 * parallel reclaimers which is a short-lived event so the timeout is
569 * short. Failing to make progress or waiting on writeback are
570 * potentially long-lived events so use a longer timeout. This is shaky
571 * logic as a failure to make progress could be due to anything from
572 * writeback to a slow device to excessive referenced folios at the tail
573 * of the inactive LRU.
576 case VMSCAN_THROTTLE_WRITEBACK
:
579 if (atomic_inc_return(&pgdat
->nr_writeback_throttled
) == 1) {
580 WRITE_ONCE(pgdat
->nr_reclaim_start
,
581 node_page_state(pgdat
, NR_THROTTLED_WRITTEN
));
585 case VMSCAN_THROTTLE_CONGESTED
:
587 case VMSCAN_THROTTLE_NOPROGRESS
:
588 if (skip_throttle_noprogress(pgdat
)) {
596 case VMSCAN_THROTTLE_ISOLATED
:
605 prepare_to_wait(wqh
, &wait
, TASK_UNINTERRUPTIBLE
);
606 ret
= schedule_timeout(timeout
);
607 finish_wait(wqh
, &wait
);
609 if (reason
== VMSCAN_THROTTLE_WRITEBACK
)
610 atomic_dec(&pgdat
->nr_writeback_throttled
);
612 trace_mm_vmscan_throttled(pgdat
->node_id
, jiffies_to_usecs(timeout
),
613 jiffies_to_usecs(timeout
- ret
),
618 * Account for folios written if tasks are throttled waiting on dirty
619 * folios to clean. If enough folios have been cleaned since throttling
620 * started then wakeup the throttled tasks.
622 void __acct_reclaim_writeback(pg_data_t
*pgdat
, struct folio
*folio
,
625 unsigned long nr_written
;
627 node_stat_add_folio(folio
, NR_THROTTLED_WRITTEN
);
630 * This is an inaccurate read as the per-cpu deltas may not
631 * be synchronised. However, given that the system is
632 * writeback throttled, it is not worth taking the penalty
633 * of getting an accurate count. At worst, the throttle
634 * timeout guarantees forward progress.
636 nr_written
= node_page_state(pgdat
, NR_THROTTLED_WRITTEN
) -
637 READ_ONCE(pgdat
->nr_reclaim_start
);
639 if (nr_written
> SWAP_CLUSTER_MAX
* nr_throttled
)
640 wake_up(&pgdat
->reclaim_wait
[VMSCAN_THROTTLE_WRITEBACK
]);
643 /* possible outcome of pageout() */
645 /* failed to write folio out, folio is locked */
647 /* move folio to the active list, folio is locked */
649 /* folio has been sent to the disk successfully, folio is unlocked */
651 /* folio is clean and locked */
656 * pageout is called by shrink_folio_list() for each dirty folio.
658 static pageout_t
pageout(struct folio
*folio
, struct address_space
*mapping
,
659 struct swap_iocb
**plug
, struct list_head
*folio_list
)
661 int (*writeout
)(struct folio
*, struct writeback_control
*);
664 * We no longer attempt to writeback filesystem folios here, other
665 * than tmpfs/shmem. That's taken care of in page-writeback.
666 * If we find a dirty filesystem folio at the end of the LRU list,
667 * typically that means the filesystem is saturating the storage
668 * with contiguous writes and telling it to write a folio here
669 * would only make the situation worse by injecting an element
672 * If the folio is swapcache, write it back even if that would
673 * block, for some throttling. This happens by accident, because
674 * swap_backing_dev_info is bust: it doesn't reflect the
675 * congestion state of the swapdevs. Easy to fix, if needed.
677 if (!is_page_cache_freeable(folio
))
681 * Some data journaling orphaned folios can have
682 * folio->mapping == NULL while being dirty with clean buffers.
684 if (folio_test_private(folio
)) {
685 if (try_to_free_buffers(folio
)) {
686 folio_clear_dirty(folio
);
687 pr_info("%s: orphaned folio\n", __func__
);
693 if (shmem_mapping(mapping
))
694 writeout
= shmem_writeout
;
695 else if (folio_test_anon(folio
))
696 writeout
= swap_writeout
;
698 return PAGE_ACTIVATE
;
700 if (folio_clear_dirty_for_io(folio
)) {
702 struct writeback_control wbc
= {
703 .sync_mode
= WB_SYNC_NONE
,
704 .nr_to_write
= SWAP_CLUSTER_MAX
,
706 .range_end
= LLONG_MAX
,
712 * The large shmem folio can be split if CONFIG_THP_SWAP is
713 * not enabled or contiguous swap entries are failed to
716 if (shmem_mapping(mapping
) && folio_test_large(folio
))
717 wbc
.list
= folio_list
;
719 folio_set_reclaim(folio
);
720 res
= writeout(folio
, &wbc
);
722 handle_write_error(mapping
, folio
, res
);
723 if (res
== AOP_WRITEPAGE_ACTIVATE
) {
724 folio_clear_reclaim(folio
);
725 return PAGE_ACTIVATE
;
728 if (!folio_test_writeback(folio
)) {
729 /* synchronous write? */
730 folio_clear_reclaim(folio
);
732 trace_mm_vmscan_write_folio(folio
);
733 node_stat_add_folio(folio
, NR_VMSCAN_WRITE
);
741 * Same as remove_mapping, but if the folio is removed from the mapping, it
742 * gets returned with a refcount of 0.
744 static int __remove_mapping(struct address_space
*mapping
, struct folio
*folio
,
745 bool reclaimed
, struct mem_cgroup
*target_memcg
)
750 BUG_ON(!folio_test_locked(folio
));
751 BUG_ON(mapping
!= folio_mapping(folio
));
753 if (!folio_test_swapcache(folio
))
754 spin_lock(&mapping
->host
->i_lock
);
755 xa_lock_irq(&mapping
->i_pages
);
757 * The non racy check for a busy folio.
759 * Must be careful with the order of the tests. When someone has
760 * a ref to the folio, it may be possible that they dirty it then
761 * drop the reference. So if the dirty flag is tested before the
762 * refcount here, then the following race may occur:
764 * get_user_pages(&page);
765 * [user mapping goes away]
767 * !folio_test_dirty(folio) [good]
768 * folio_set_dirty(folio);
770 * !refcount(folio) [good, discard it]
772 * [oops, our write_to data is lost]
774 * Reversing the order of the tests ensures such a situation cannot
775 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
776 * load is not satisfied before that of folio->_refcount.
778 * Note that if the dirty flag is always set via folio_mark_dirty,
779 * and thus under the i_pages lock, then this ordering is not required.
781 refcount
= 1 + folio_nr_pages(folio
);
782 if (!folio_ref_freeze(folio
, refcount
))
784 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
785 if (unlikely(folio_test_dirty(folio
))) {
786 folio_ref_unfreeze(folio
, refcount
);
790 if (folio_test_swapcache(folio
)) {
791 swp_entry_t swap
= folio
->swap
;
793 if (reclaimed
&& !mapping_exiting(mapping
))
794 shadow
= workingset_eviction(folio
, target_memcg
);
795 __delete_from_swap_cache(folio
, swap
, shadow
);
796 memcg1_swapout(folio
, swap
);
797 xa_unlock_irq(&mapping
->i_pages
);
798 put_swap_folio(folio
, swap
);
800 void (*free_folio
)(struct folio
*);
802 free_folio
= mapping
->a_ops
->free_folio
;
804 * Remember a shadow entry for reclaimed file cache in
805 * order to detect refaults, thus thrashing, later on.
807 * But don't store shadows in an address space that is
808 * already exiting. This is not just an optimization,
809 * inode reclaim needs to empty out the radix tree or
810 * the nodes are lost. Don't plant shadows behind its
813 * We also don't store shadows for DAX mappings because the
814 * only page cache folios found in these are zero pages
815 * covering holes, and because we don't want to mix DAX
816 * exceptional entries and shadow exceptional entries in the
817 * same address_space.
819 if (reclaimed
&& folio_is_file_lru(folio
) &&
820 !mapping_exiting(mapping
) && !dax_mapping(mapping
))
821 shadow
= workingset_eviction(folio
, target_memcg
);
822 __filemap_remove_folio(folio
, shadow
);
823 xa_unlock_irq(&mapping
->i_pages
);
824 if (mapping_shrinkable(mapping
))
825 inode_add_lru(mapping
->host
);
826 spin_unlock(&mapping
->host
->i_lock
);
835 xa_unlock_irq(&mapping
->i_pages
);
836 if (!folio_test_swapcache(folio
))
837 spin_unlock(&mapping
->host
->i_lock
);
842 * remove_mapping() - Attempt to remove a folio from its mapping.
843 * @mapping: The address space.
844 * @folio: The folio to remove.
846 * If the folio is dirty, under writeback or if someone else has a ref
847 * on it, removal will fail.
848 * Return: The number of pages removed from the mapping. 0 if the folio
849 * could not be removed.
850 * Context: The caller should have a single refcount on the folio and
853 long remove_mapping(struct address_space
*mapping
, struct folio
*folio
)
855 if (__remove_mapping(mapping
, folio
, false, NULL
)) {
857 * Unfreezing the refcount with 1 effectively
858 * drops the pagecache ref for us without requiring another
861 folio_ref_unfreeze(folio
, 1);
862 return folio_nr_pages(folio
);
868 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
869 * @folio: Folio to be returned to an LRU list.
871 * Add previously isolated @folio to appropriate LRU list.
872 * The folio may still be unevictable for other reasons.
874 * Context: lru_lock must not be held, interrupts must be enabled.
876 void folio_putback_lru(struct folio
*folio
)
878 folio_add_lru(folio
);
879 folio_put(folio
); /* drop ref from isolate */
882 enum folio_references
{
884 FOLIOREF_RECLAIM_CLEAN
,
889 #ifdef CONFIG_LRU_GEN
891 * Only used on a mapped folio in the eviction (rmap walk) path, where promotion
892 * needs to be done by taking the folio off the LRU list and then adding it back
893 * with PG_active set. In contrast, the aging (page table walk) path uses
894 * folio_update_gen().
896 static bool lru_gen_set_refs(struct folio
*folio
)
898 /* see the comment on LRU_REFS_FLAGS */
899 if (!folio_test_referenced(folio
) && !folio_test_workingset(folio
)) {
900 set_mask_bits(&folio
->flags
, LRU_REFS_MASK
, BIT(PG_referenced
));
904 set_mask_bits(&folio
->flags
, LRU_REFS_FLAGS
, BIT(PG_workingset
));
908 static bool lru_gen_set_refs(struct folio
*folio
)
912 #endif /* CONFIG_LRU_GEN */
914 static enum folio_references
folio_check_references(struct folio
*folio
,
915 struct scan_control
*sc
)
917 int referenced_ptes
, referenced_folio
;
918 unsigned long vm_flags
;
920 referenced_ptes
= folio_referenced(folio
, 1, sc
->target_mem_cgroup
,
924 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
925 * Let the folio, now marked Mlocked, be moved to the unevictable list.
927 if (vm_flags
& VM_LOCKED
)
928 return FOLIOREF_ACTIVATE
;
931 * There are two cases to consider.
932 * 1) Rmap lock contention: rotate.
933 * 2) Skip the non-shared swapbacked folio mapped solely by
934 * the exiting or OOM-reaped process.
936 if (referenced_ptes
== -1)
937 return FOLIOREF_KEEP
;
939 if (lru_gen_enabled()) {
940 if (!referenced_ptes
)
941 return FOLIOREF_RECLAIM
;
943 return lru_gen_set_refs(folio
) ? FOLIOREF_ACTIVATE
: FOLIOREF_KEEP
;
946 referenced_folio
= folio_test_clear_referenced(folio
);
948 if (referenced_ptes
) {
950 * All mapped folios start out with page table
951 * references from the instantiating fault, so we need
952 * to look twice if a mapped file/anon folio is used more
955 * Mark it and spare it for another trip around the
956 * inactive list. Another page table reference will
957 * lead to its activation.
959 * Note: the mark is set for activated folios as well
960 * so that recently deactivated but used folios are
963 folio_set_referenced(folio
);
965 if (referenced_folio
|| referenced_ptes
> 1)
966 return FOLIOREF_ACTIVATE
;
969 * Activate file-backed executable folios after first usage.
971 if ((vm_flags
& VM_EXEC
) && folio_is_file_lru(folio
))
972 return FOLIOREF_ACTIVATE
;
974 return FOLIOREF_KEEP
;
977 /* Reclaim if clean, defer dirty folios to writeback */
978 if (referenced_folio
&& folio_is_file_lru(folio
))
979 return FOLIOREF_RECLAIM_CLEAN
;
981 return FOLIOREF_RECLAIM
;
984 /* Check if a folio is dirty or under writeback */
985 static void folio_check_dirty_writeback(struct folio
*folio
,
986 bool *dirty
, bool *writeback
)
988 struct address_space
*mapping
;
991 * Anonymous folios are not handled by flushers and must be written
992 * from reclaim context. Do not stall reclaim based on them.
993 * MADV_FREE anonymous folios are put into inactive file list too.
994 * They could be mistakenly treated as file lru. So further anon
997 if (!folio_is_file_lru(folio
) ||
998 (folio_test_anon(folio
) && !folio_test_swapbacked(folio
))) {
1004 /* By default assume that the folio flags are accurate */
1005 *dirty
= folio_test_dirty(folio
);
1006 *writeback
= folio_test_writeback(folio
);
1008 /* Verify dirty/writeback state if the filesystem supports it */
1009 if (!folio_test_private(folio
))
1012 mapping
= folio_mapping(folio
);
1013 if (mapping
&& mapping
->a_ops
->is_dirty_writeback
)
1014 mapping
->a_ops
->is_dirty_writeback(folio
, dirty
, writeback
);
1017 struct folio
*alloc_migrate_folio(struct folio
*src
, unsigned long private)
1020 nodemask_t
*allowed_mask
;
1021 struct migration_target_control
*mtc
;
1023 mtc
= (struct migration_target_control
*)private;
1025 allowed_mask
= mtc
->nmask
;
1027 * make sure we allocate from the target node first also trying to
1028 * demote or reclaim pages from the target node via kswapd if we are
1029 * low on free memory on target node. If we don't do this and if
1030 * we have free memory on the slower(lower) memtier, we would start
1031 * allocating pages from slower(lower) memory tiers without even forcing
1032 * a demotion of cold pages from the target memtier. This can result
1033 * in the kernel placing hot pages in slower(lower) memory tiers.
1036 mtc
->gfp_mask
|= __GFP_THISNODE
;
1037 dst
= alloc_migration_target(src
, (unsigned long)mtc
);
1041 mtc
->gfp_mask
&= ~__GFP_THISNODE
;
1042 mtc
->nmask
= allowed_mask
;
1044 return alloc_migration_target(src
, (unsigned long)mtc
);
1048 * Take folios on @demote_folios and attempt to demote them to another node.
1049 * Folios which are not demoted are left on @demote_folios.
1051 static unsigned int demote_folio_list(struct list_head
*demote_folios
,
1052 struct pglist_data
*pgdat
)
1054 int target_nid
= next_demotion_node(pgdat
->node_id
);
1055 unsigned int nr_succeeded
;
1056 nodemask_t allowed_mask
;
1058 struct migration_target_control mtc
= {
1060 * Allocate from 'node', or fail quickly and quietly.
1061 * When this happens, 'page' will likely just be discarded
1062 * instead of migrated.
1064 .gfp_mask
= (GFP_HIGHUSER_MOVABLE
& ~__GFP_RECLAIM
) | __GFP_NOWARN
|
1065 __GFP_NOMEMALLOC
| GFP_NOWAIT
,
1067 .nmask
= &allowed_mask
,
1068 .reason
= MR_DEMOTION
,
1071 if (list_empty(demote_folios
))
1074 if (target_nid
== NUMA_NO_NODE
)
1077 node_get_allowed_targets(pgdat
, &allowed_mask
);
1079 /* Demotion ignores all cpuset and mempolicy settings */
1080 migrate_pages(demote_folios
, alloc_migrate_folio
, NULL
,
1081 (unsigned long)&mtc
, MIGRATE_ASYNC
, MR_DEMOTION
,
1084 return nr_succeeded
;
1087 static bool may_enter_fs(struct folio
*folio
, gfp_t gfp_mask
)
1089 if (gfp_mask
& __GFP_FS
)
1091 if (!folio_test_swapcache(folio
) || !(gfp_mask
& __GFP_IO
))
1094 * We can "enter_fs" for swap-cache with only __GFP_IO
1095 * providing this isn't SWP_FS_OPS.
1096 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1097 * but that will never affect SWP_FS_OPS, so the data_race
1100 return !data_race(folio_swap_flags(folio
) & SWP_FS_OPS
);
1104 * shrink_folio_list() returns the number of reclaimed pages
1106 static unsigned int shrink_folio_list(struct list_head
*folio_list
,
1107 struct pglist_data
*pgdat
, struct scan_control
*sc
,
1108 struct reclaim_stat
*stat
, bool ignore_references
,
1109 struct mem_cgroup
*memcg
)
1111 struct folio_batch free_folios
;
1112 LIST_HEAD(ret_folios
);
1113 LIST_HEAD(demote_folios
);
1114 unsigned int nr_reclaimed
= 0, nr_demoted
= 0;
1115 unsigned int pgactivate
= 0;
1116 bool do_demote_pass
;
1117 struct swap_iocb
*plug
= NULL
;
1119 folio_batch_init(&free_folios
);
1120 memset(stat
, 0, sizeof(*stat
));
1122 do_demote_pass
= can_demote(pgdat
->node_id
, sc
, memcg
);
1125 while (!list_empty(folio_list
)) {
1126 struct address_space
*mapping
;
1127 struct folio
*folio
;
1128 enum folio_references references
= FOLIOREF_RECLAIM
;
1129 bool dirty
, writeback
;
1130 unsigned int nr_pages
;
1134 folio
= lru_to_folio(folio_list
);
1135 list_del(&folio
->lru
);
1137 if (!folio_trylock(folio
))
1140 if (folio_contain_hwpoisoned_page(folio
)) {
1141 unmap_poisoned_folio(folio
, folio_pfn(folio
), false);
1142 folio_unlock(folio
);
1147 VM_BUG_ON_FOLIO(folio_test_active(folio
), folio
);
1149 nr_pages
= folio_nr_pages(folio
);
1151 /* Account the number of base pages */
1152 sc
->nr_scanned
+= nr_pages
;
1154 if (unlikely(!folio_evictable(folio
)))
1155 goto activate_locked
;
1157 if (!sc
->may_unmap
&& folio_mapped(folio
))
1161 * The number of dirty pages determines if a node is marked
1162 * reclaim_congested. kswapd will stall and start writing
1163 * folios if the tail of the LRU is all dirty unqueued folios.
1165 folio_check_dirty_writeback(folio
, &dirty
, &writeback
);
1166 if (dirty
|| writeback
)
1167 stat
->nr_dirty
+= nr_pages
;
1169 if (dirty
&& !writeback
)
1170 stat
->nr_unqueued_dirty
+= nr_pages
;
1173 * Treat this folio as congested if folios are cycling
1174 * through the LRU so quickly that the folios marked
1175 * for immediate reclaim are making it to the end of
1176 * the LRU a second time.
1178 if (writeback
&& folio_test_reclaim(folio
))
1179 stat
->nr_congested
+= nr_pages
;
1182 * If a folio at the tail of the LRU is under writeback, there
1183 * are three cases to consider.
1185 * 1) If reclaim is encountering an excessive number
1186 * of folios under writeback and this folio has both
1187 * the writeback and reclaim flags set, then it
1188 * indicates that folios are being queued for I/O but
1189 * are being recycled through the LRU before the I/O
1190 * can complete. Waiting on the folio itself risks an
1191 * indefinite stall if it is impossible to writeback
1192 * the folio due to I/O error or disconnected storage
1193 * so instead note that the LRU is being scanned too
1194 * quickly and the caller can stall after the folio
1195 * list has been processed.
1197 * 2) Global or new memcg reclaim encounters a folio that is
1198 * not marked for immediate reclaim, or the caller does not
1199 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1200 * not to fs), or the folio belongs to a mapping where
1201 * waiting on writeback during reclaim may lead to a deadlock.
1202 * In this case mark the folio for immediate reclaim and
1203 * continue scanning.
1205 * Require may_enter_fs() because we would wait on fs, which
1206 * may not have submitted I/O yet. And the loop driver might
1207 * enter reclaim, and deadlock if it waits on a folio for
1208 * which it is needed to do the write (loop masks off
1209 * __GFP_IO|__GFP_FS for this reason); but more thought
1210 * would probably show more reasons.
1212 * 3) Legacy memcg encounters a folio that already has the
1213 * reclaim flag set. memcg does not have any dirty folio
1214 * throttling so we could easily OOM just because too many
1215 * folios are in writeback and there is nothing else to
1216 * reclaim. Wait for the writeback to complete.
1218 * In cases 1) and 2) we activate the folios to get them out of
1219 * the way while we continue scanning for clean folios on the
1220 * inactive list and refilling from the active list. The
1221 * observation here is that waiting for disk writes is more
1222 * expensive than potentially causing reloads down the line.
1223 * Since they're marked for immediate reclaim, they won't put
1224 * memory pressure on the cache working set any longer than it
1225 * takes to write them to disk.
1227 if (folio_test_writeback(folio
)) {
1228 mapping
= folio_mapping(folio
);
1231 if (current_is_kswapd() &&
1232 folio_test_reclaim(folio
) &&
1233 test_bit(PGDAT_WRITEBACK
, &pgdat
->flags
)) {
1234 stat
->nr_immediate
+= nr_pages
;
1235 goto activate_locked
;
1238 } else if (writeback_throttling_sane(sc
) ||
1239 !folio_test_reclaim(folio
) ||
1240 !may_enter_fs(folio
, sc
->gfp_mask
) ||
1242 mapping_writeback_may_deadlock_on_reclaim(mapping
))) {
1244 * This is slightly racy -
1245 * folio_end_writeback() might have
1246 * just cleared the reclaim flag, then
1247 * setting the reclaim flag here ends up
1248 * interpreted as the readahead flag - but
1249 * that does not matter enough to care.
1250 * What we do want is for this folio to
1251 * have the reclaim flag set next time
1252 * memcg reclaim reaches the tests above,
1253 * so it will then wait for writeback to
1254 * avoid OOM; and it's also appropriate
1255 * in global reclaim.
1257 folio_set_reclaim(folio
);
1258 stat
->nr_writeback
+= nr_pages
;
1259 goto activate_locked
;
1263 folio_unlock(folio
);
1264 folio_wait_writeback(folio
);
1265 /* then go back and try same folio again */
1266 list_add_tail(&folio
->lru
, folio_list
);
1271 if (!ignore_references
)
1272 references
= folio_check_references(folio
, sc
);
1274 switch (references
) {
1275 case FOLIOREF_ACTIVATE
:
1276 goto activate_locked
;
1278 stat
->nr_ref_keep
+= nr_pages
;
1280 case FOLIOREF_RECLAIM
:
1281 case FOLIOREF_RECLAIM_CLEAN
:
1282 ; /* try to reclaim the folio below */
1286 * Before reclaiming the folio, try to relocate
1287 * its contents to another node.
1289 if (do_demote_pass
&&
1290 (thp_migration_supported() || !folio_test_large(folio
))) {
1291 list_add(&folio
->lru
, &demote_folios
);
1292 folio_unlock(folio
);
1297 * Anonymous process memory has backing store?
1298 * Try to allocate it some swap space here.
1299 * Lazyfree folio could be freed directly
1301 if (folio_test_anon(folio
) && folio_test_swapbacked(folio
)) {
1302 if (!folio_test_swapcache(folio
)) {
1303 if (!(sc
->gfp_mask
& __GFP_IO
))
1305 if (folio_maybe_dma_pinned(folio
))
1307 if (folio_test_large(folio
)) {
1308 /* cannot split folio, skip it */
1309 if (!can_split_folio(folio
, 1, NULL
))
1310 goto activate_locked
;
1312 * Split partially mapped folios right away.
1313 * We can free the unmapped pages without IO.
1315 if (data_race(!list_empty(&folio
->_deferred_list
) &&
1316 folio_test_partially_mapped(folio
)) &&
1317 split_folio_to_list(folio
, folio_list
))
1318 goto activate_locked
;
1320 if (folio_alloc_swap(folio
, __GFP_HIGH
| __GFP_NOWARN
)) {
1321 int __maybe_unused order
= folio_order(folio
);
1323 if (!folio_test_large(folio
))
1324 goto activate_locked_split
;
1325 /* Fallback to swap normal pages */
1326 if (split_folio_to_list(folio
, folio_list
))
1327 goto activate_locked
;
1328 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1329 if (nr_pages
>= HPAGE_PMD_NR
) {
1330 count_memcg_folio_events(folio
,
1331 THP_SWPOUT_FALLBACK
, 1);
1332 count_vm_event(THP_SWPOUT_FALLBACK
);
1335 count_mthp_stat(order
, MTHP_STAT_SWPOUT_FALLBACK
);
1336 if (folio_alloc_swap(folio
, __GFP_HIGH
| __GFP_NOWARN
))
1337 goto activate_locked_split
;
1340 * Normally the folio will be dirtied in unmap because its
1341 * pte should be dirty. A special case is MADV_FREE page. The
1342 * page's pte could have dirty bit cleared but the folio's
1343 * SwapBacked flag is still set because clearing the dirty bit
1344 * and SwapBacked flag has no lock protected. For such folio,
1345 * unmap will not set dirty bit for it, so folio reclaim will
1346 * not write the folio out. This can cause data corruption when
1347 * the folio is swapped in later. Always setting the dirty flag
1348 * for the folio solves the problem.
1350 folio_mark_dirty(folio
);
1355 * If the folio was split above, the tail pages will make
1356 * their own pass through this function and be accounted
1359 if ((nr_pages
> 1) && !folio_test_large(folio
)) {
1360 sc
->nr_scanned
-= (nr_pages
- 1);
1365 * The folio is mapped into the page tables of one or more
1366 * processes. Try to unmap it here.
1368 if (folio_mapped(folio
)) {
1369 enum ttu_flags flags
= TTU_BATCH_FLUSH
;
1370 bool was_swapbacked
= folio_test_swapbacked(folio
);
1372 if (folio_test_pmd_mappable(folio
))
1373 flags
|= TTU_SPLIT_HUGE_PMD
;
1375 * Without TTU_SYNC, try_to_unmap will only begin to
1376 * hold PTL from the first present PTE within a large
1377 * folio. Some initial PTEs might be skipped due to
1378 * races with parallel PTE writes in which PTEs can be
1379 * cleared temporarily before being written new present
1380 * values. This will lead to a large folio is still
1381 * mapped while some subpages have been partially
1382 * unmapped after try_to_unmap; TTU_SYNC helps
1383 * try_to_unmap acquire PTL from the first PTE,
1384 * eliminating the influence of temporary PTE values.
1386 if (folio_test_large(folio
))
1389 try_to_unmap(folio
, flags
);
1390 if (folio_mapped(folio
)) {
1391 stat
->nr_unmap_fail
+= nr_pages
;
1392 if (!was_swapbacked
&&
1393 folio_test_swapbacked(folio
))
1394 stat
->nr_lazyfree_fail
+= nr_pages
;
1395 goto activate_locked
;
1400 * Folio is unmapped now so it cannot be newly pinned anymore.
1401 * No point in trying to reclaim folio if it is pinned.
1402 * Furthermore we don't want to reclaim underlying fs metadata
1403 * if the folio is pinned and thus potentially modified by the
1404 * pinning process as that may upset the filesystem.
1406 if (folio_maybe_dma_pinned(folio
))
1407 goto activate_locked
;
1409 mapping
= folio_mapping(folio
);
1410 if (folio_test_dirty(folio
)) {
1412 * Only kswapd can writeback filesystem folios
1413 * to avoid risk of stack overflow. But avoid
1414 * injecting inefficient single-folio I/O into
1415 * flusher writeback as much as possible: only
1416 * write folios when we've encountered many
1417 * dirty folios, and when we've already scanned
1418 * the rest of the LRU for clean folios and see
1419 * the same dirty folios again (with the reclaim
1422 if (folio_is_file_lru(folio
) &&
1423 (!current_is_kswapd() ||
1424 !folio_test_reclaim(folio
) ||
1425 !test_bit(PGDAT_DIRTY
, &pgdat
->flags
))) {
1427 * Immediately reclaim when written back.
1428 * Similar in principle to folio_deactivate()
1429 * except we already have the folio isolated
1430 * and know it's dirty
1432 node_stat_mod_folio(folio
, NR_VMSCAN_IMMEDIATE
,
1434 folio_set_reclaim(folio
);
1436 goto activate_locked
;
1439 if (references
== FOLIOREF_RECLAIM_CLEAN
)
1441 if (!may_enter_fs(folio
, sc
->gfp_mask
))
1443 if (!sc
->may_writepage
)
1447 * Folio is dirty. Flush the TLB if a writable entry
1448 * potentially exists to avoid CPU writes after I/O
1449 * starts and then write it out here.
1451 try_to_unmap_flush_dirty();
1452 switch (pageout(folio
, mapping
, &plug
, folio_list
)) {
1457 * If shmem folio is split when writeback to swap,
1458 * the tail pages will make their own pass through
1459 * this function and be accounted then.
1461 if (nr_pages
> 1 && !folio_test_large(folio
)) {
1462 sc
->nr_scanned
-= (nr_pages
- 1);
1465 goto activate_locked
;
1467 if (nr_pages
> 1 && !folio_test_large(folio
)) {
1468 sc
->nr_scanned
-= (nr_pages
- 1);
1471 stat
->nr_pageout
+= nr_pages
;
1473 if (folio_test_writeback(folio
))
1475 if (folio_test_dirty(folio
))
1479 * A synchronous write - probably a ramdisk. Go
1480 * ahead and try to reclaim the folio.
1482 if (!folio_trylock(folio
))
1484 if (folio_test_dirty(folio
) ||
1485 folio_test_writeback(folio
))
1487 mapping
= folio_mapping(folio
);
1490 ; /* try to free the folio below */
1495 * If the folio has buffers, try to free the buffer
1496 * mappings associated with this folio. If we succeed
1497 * we try to free the folio as well.
1499 * We do this even if the folio is dirty.
1500 * filemap_release_folio() does not perform I/O, but it
1501 * is possible for a folio to have the dirty flag set,
1502 * but it is actually clean (all its buffers are clean).
1503 * This happens if the buffers were written out directly,
1504 * with submit_bh(). ext3 will do this, as well as
1505 * the blockdev mapping. filemap_release_folio() will
1506 * discover that cleanness and will drop the buffers
1507 * and mark the folio clean - it can be freed.
1509 * Rarely, folios can have buffers and no ->mapping.
1510 * These are the folios which were not successfully
1511 * invalidated in truncate_cleanup_folio(). We try to
1512 * drop those buffers here and if that worked, and the
1513 * folio is no longer mapped into process address space
1514 * (refcount == 1) it can be freed. Otherwise, leave
1515 * the folio on the LRU so it is swappable.
1517 if (folio_needs_release(folio
)) {
1518 if (!filemap_release_folio(folio
, sc
->gfp_mask
))
1519 goto activate_locked
;
1520 if (!mapping
&& folio_ref_count(folio
) == 1) {
1521 folio_unlock(folio
);
1522 if (folio_put_testzero(folio
))
1526 * rare race with speculative reference.
1527 * the speculative reference will free
1528 * this folio shortly, so we may
1529 * increment nr_reclaimed here (and
1530 * leave it off the LRU).
1532 nr_reclaimed
+= nr_pages
;
1538 if (folio_test_anon(folio
) && !folio_test_swapbacked(folio
)) {
1539 /* follow __remove_mapping for reference */
1540 if (!folio_ref_freeze(folio
, 1))
1543 * The folio has only one reference left, which is
1544 * from the isolation. After the caller puts the
1545 * folio back on the lru and drops the reference, the
1546 * folio will be freed anyway. It doesn't matter
1547 * which lru it goes on. So we don't bother checking
1548 * the dirty flag here.
1550 count_vm_events(PGLAZYFREED
, nr_pages
);
1551 count_memcg_folio_events(folio
, PGLAZYFREED
, nr_pages
);
1552 } else if (!mapping
|| !__remove_mapping(mapping
, folio
, true,
1553 sc
->target_mem_cgroup
))
1556 folio_unlock(folio
);
1559 * Folio may get swapped out as a whole, need to account
1562 nr_reclaimed
+= nr_pages
;
1564 folio_unqueue_deferred_split(folio
);
1565 if (folio_batch_add(&free_folios
, folio
) == 0) {
1566 mem_cgroup_uncharge_folios(&free_folios
);
1567 try_to_unmap_flush();
1568 free_unref_folios(&free_folios
);
1572 activate_locked_split
:
1574 * The tail pages that are failed to add into swap cache
1575 * reach here. Fixup nr_scanned and nr_pages.
1578 sc
->nr_scanned
-= (nr_pages
- 1);
1582 /* Not a candidate for swapping, so reclaim swap space. */
1583 if (folio_test_swapcache(folio
) &&
1584 (mem_cgroup_swap_full(folio
) || folio_test_mlocked(folio
)))
1585 folio_free_swap(folio
);
1586 VM_BUG_ON_FOLIO(folio_test_active(folio
), folio
);
1587 if (!folio_test_mlocked(folio
)) {
1588 int type
= folio_is_file_lru(folio
);
1589 folio_set_active(folio
);
1590 stat
->nr_activate
[type
] += nr_pages
;
1591 count_memcg_folio_events(folio
, PGACTIVATE
, nr_pages
);
1594 folio_unlock(folio
);
1596 list_add(&folio
->lru
, &ret_folios
);
1597 VM_BUG_ON_FOLIO(folio_test_lru(folio
) ||
1598 folio_test_unevictable(folio
), folio
);
1600 /* 'folio_list' is always empty here */
1602 /* Migrate folios selected for demotion */
1603 nr_demoted
= demote_folio_list(&demote_folios
, pgdat
);
1604 nr_reclaimed
+= nr_demoted
;
1605 stat
->nr_demoted
+= nr_demoted
;
1606 /* Folios that could not be demoted are still in @demote_folios */
1607 if (!list_empty(&demote_folios
)) {
1608 /* Folios which weren't demoted go back on @folio_list */
1609 list_splice_init(&demote_folios
, folio_list
);
1612 * goto retry to reclaim the undemoted folios in folio_list if
1615 * Reclaiming directly from top tier nodes is not often desired
1616 * due to it breaking the LRU ordering: in general memory
1617 * should be reclaimed from lower tier nodes and demoted from
1620 * However, disabling reclaim from top tier nodes entirely
1621 * would cause ooms in edge scenarios where lower tier memory
1622 * is unreclaimable for whatever reason, eg memory being
1623 * mlocked or too hot to reclaim. We can disable reclaim
1624 * from top tier nodes in proactive reclaim though as that is
1625 * not real memory pressure.
1627 if (!sc
->proactive
) {
1628 do_demote_pass
= false;
1633 pgactivate
= stat
->nr_activate
[0] + stat
->nr_activate
[1];
1635 mem_cgroup_uncharge_folios(&free_folios
);
1636 try_to_unmap_flush();
1637 free_unref_folios(&free_folios
);
1639 list_splice(&ret_folios
, folio_list
);
1640 count_vm_events(PGACTIVATE
, pgactivate
);
1643 swap_write_unplug(plug
);
1644 return nr_reclaimed
;
1647 unsigned int reclaim_clean_pages_from_list(struct zone
*zone
,
1648 struct list_head
*folio_list
)
1650 struct scan_control sc
= {
1651 .gfp_mask
= GFP_KERNEL
,
1654 struct reclaim_stat stat
;
1655 unsigned int nr_reclaimed
;
1656 struct folio
*folio
, *next
;
1657 LIST_HEAD(clean_folios
);
1658 unsigned int noreclaim_flag
;
1660 list_for_each_entry_safe(folio
, next
, folio_list
, lru
) {
1661 if (!folio_test_hugetlb(folio
) && folio_is_file_lru(folio
) &&
1662 !folio_test_dirty(folio
) && !__folio_test_movable(folio
) &&
1663 !folio_test_unevictable(folio
)) {
1664 folio_clear_active(folio
);
1665 list_move(&folio
->lru
, &clean_folios
);
1670 * We should be safe here since we are only dealing with file pages and
1671 * we are not kswapd and therefore cannot write dirty file pages. But
1672 * call memalloc_noreclaim_save() anyway, just in case these conditions
1673 * change in the future.
1675 noreclaim_flag
= memalloc_noreclaim_save();
1676 nr_reclaimed
= shrink_folio_list(&clean_folios
, zone
->zone_pgdat
, &sc
,
1678 memalloc_noreclaim_restore(noreclaim_flag
);
1680 list_splice(&clean_folios
, folio_list
);
1681 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
1682 -(long)nr_reclaimed
);
1684 * Since lazyfree pages are isolated from file LRU from the beginning,
1685 * they will rotate back to anonymous LRU in the end if it failed to
1686 * discard so isolated count will be mismatched.
1687 * Compensate the isolated count for both LRU lists.
1689 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_ANON
,
1690 stat
.nr_lazyfree_fail
);
1691 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
1692 -(long)stat
.nr_lazyfree_fail
);
1693 return nr_reclaimed
;
1697 * Update LRU sizes after isolating pages. The LRU size updates must
1698 * be complete before mem_cgroup_update_lru_size due to a sanity check.
1700 static __always_inline
void update_lru_sizes(struct lruvec
*lruvec
,
1701 enum lru_list lru
, unsigned long *nr_zone_taken
)
1705 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1706 if (!nr_zone_taken
[zid
])
1709 update_lru_size(lruvec
, lru
, zid
, -nr_zone_taken
[zid
]);
1715 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1717 * lruvec->lru_lock is heavily contended. Some of the functions that
1718 * shrink the lists perform better by taking out a batch of pages
1719 * and working on them outside the LRU lock.
1721 * For pagecache intensive workloads, this function is the hottest
1722 * spot in the kernel (apart from copy_*_user functions).
1724 * Lru_lock must be held before calling this function.
1726 * @nr_to_scan: The number of eligible pages to look through on the list.
1727 * @lruvec: The LRU vector to pull pages from.
1728 * @dst: The temp list to put pages on to.
1729 * @nr_scanned: The number of pages that were scanned.
1730 * @sc: The scan_control struct for this reclaim session
1731 * @lru: LRU list id for isolating
1733 * returns how many pages were moved onto *@dst.
1735 static unsigned long isolate_lru_folios(unsigned long nr_to_scan
,
1736 struct lruvec
*lruvec
, struct list_head
*dst
,
1737 unsigned long *nr_scanned
, struct scan_control
*sc
,
1740 struct list_head
*src
= &lruvec
->lists
[lru
];
1741 unsigned long nr_taken
= 0;
1742 unsigned long nr_zone_taken
[MAX_NR_ZONES
] = { 0 };
1743 unsigned long nr_skipped
[MAX_NR_ZONES
] = { 0, };
1744 unsigned long skipped
= 0, total_scan
= 0, scan
= 0;
1745 unsigned long nr_pages
;
1746 unsigned long max_nr_skipped
= 0;
1747 LIST_HEAD(folios_skipped
);
1749 while (scan
< nr_to_scan
&& !list_empty(src
)) {
1750 struct list_head
*move_to
= src
;
1751 struct folio
*folio
;
1753 folio
= lru_to_folio(src
);
1754 prefetchw_prev_lru_folio(folio
, src
, flags
);
1756 nr_pages
= folio_nr_pages(folio
);
1757 total_scan
+= nr_pages
;
1759 /* Using max_nr_skipped to prevent hard LOCKUP*/
1760 if (max_nr_skipped
< SWAP_CLUSTER_MAX_SKIPPED
&&
1761 (folio_zonenum(folio
) > sc
->reclaim_idx
)) {
1762 nr_skipped
[folio_zonenum(folio
)] += nr_pages
;
1763 move_to
= &folios_skipped
;
1769 * Do not count skipped folios because that makes the function
1770 * return with no isolated folios if the LRU mostly contains
1771 * ineligible folios. This causes the VM to not reclaim any
1772 * folios, triggering a premature OOM.
1773 * Account all pages in a folio.
1777 if (!folio_test_lru(folio
))
1779 if (!sc
->may_unmap
&& folio_mapped(folio
))
1783 * Be careful not to clear the lru flag until after we're
1784 * sure the folio is not being freed elsewhere -- the
1785 * folio release code relies on it.
1787 if (unlikely(!folio_try_get(folio
)))
1790 if (!folio_test_clear_lru(folio
)) {
1791 /* Another thread is already isolating this folio */
1796 nr_taken
+= nr_pages
;
1797 nr_zone_taken
[folio_zonenum(folio
)] += nr_pages
;
1800 list_move(&folio
->lru
, move_to
);
1804 * Splice any skipped folios to the start of the LRU list. Note that
1805 * this disrupts the LRU order when reclaiming for lower zones but
1806 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1807 * scanning would soon rescan the same folios to skip and waste lots
1810 if (!list_empty(&folios_skipped
)) {
1813 list_splice(&folios_skipped
, src
);
1814 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1815 if (!nr_skipped
[zid
])
1818 __count_zid_vm_events(PGSCAN_SKIP
, zid
, nr_skipped
[zid
]);
1819 skipped
+= nr_skipped
[zid
];
1822 *nr_scanned
= total_scan
;
1823 trace_mm_vmscan_lru_isolate(sc
->reclaim_idx
, sc
->order
, nr_to_scan
,
1824 total_scan
, skipped
, nr_taken
, lru
);
1825 update_lru_sizes(lruvec
, lru
, nr_zone_taken
);
1830 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
1831 * @folio: Folio to isolate from its LRU list.
1833 * Isolate a @folio from an LRU list and adjust the vmstat statistic
1834 * corresponding to whatever LRU list the folio was on.
1836 * The folio will have its LRU flag cleared. If it was found on the
1837 * active list, it will have the Active flag set. If it was found on the
1838 * unevictable list, it will have the Unevictable flag set. These flags
1839 * may need to be cleared by the caller before letting the page go.
1843 * (1) Must be called with an elevated refcount on the folio. This is a
1844 * fundamental difference from isolate_lru_folios() (which is called
1845 * without a stable reference).
1846 * (2) The lru_lock must not be held.
1847 * (3) Interrupts must be enabled.
1849 * Return: true if the folio was removed from an LRU list.
1850 * false if the folio was not on an LRU list.
1852 bool folio_isolate_lru(struct folio
*folio
)
1856 VM_BUG_ON_FOLIO(!folio_ref_count(folio
), folio
);
1858 if (folio_test_clear_lru(folio
)) {
1859 struct lruvec
*lruvec
;
1862 lruvec
= folio_lruvec_lock_irq(folio
);
1863 lruvec_del_folio(lruvec
, folio
);
1864 unlock_page_lruvec_irq(lruvec
);
1872 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1873 * then get rescheduled. When there are massive number of tasks doing page
1874 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1875 * the LRU list will go small and be scanned faster than necessary, leading to
1876 * unnecessary swapping, thrashing and OOM.
1878 static bool too_many_isolated(struct pglist_data
*pgdat
, int file
,
1879 struct scan_control
*sc
)
1881 unsigned long inactive
, isolated
;
1884 if (current_is_kswapd())
1887 if (!writeback_throttling_sane(sc
))
1891 inactive
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
1892 isolated
= node_page_state(pgdat
, NR_ISOLATED_FILE
);
1894 inactive
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
1895 isolated
= node_page_state(pgdat
, NR_ISOLATED_ANON
);
1899 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1900 * won't get blocked by normal direct-reclaimers, forming a circular
1903 if (gfp_has_io_fs(sc
->gfp_mask
))
1906 too_many
= isolated
> inactive
;
1908 /* Wake up tasks throttled due to too_many_isolated. */
1910 wake_throttle_isolated(pgdat
);
1916 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
1918 * Returns the number of pages moved to the given lruvec.
1920 static unsigned int move_folios_to_lru(struct lruvec
*lruvec
,
1921 struct list_head
*list
)
1923 int nr_pages
, nr_moved
= 0;
1924 struct folio_batch free_folios
;
1926 folio_batch_init(&free_folios
);
1927 while (!list_empty(list
)) {
1928 struct folio
*folio
= lru_to_folio(list
);
1930 VM_BUG_ON_FOLIO(folio_test_lru(folio
), folio
);
1931 list_del(&folio
->lru
);
1932 if (unlikely(!folio_evictable(folio
))) {
1933 spin_unlock_irq(&lruvec
->lru_lock
);
1934 folio_putback_lru(folio
);
1935 spin_lock_irq(&lruvec
->lru_lock
);
1940 * The folio_set_lru needs to be kept here for list integrity.
1942 * #0 move_folios_to_lru #1 release_pages
1943 * if (!folio_put_testzero())
1944 * if (folio_put_testzero())
1945 * !lru //skip lru_lock
1947 * list_add(&folio->lru,)
1948 * list_add(&folio->lru,)
1950 folio_set_lru(folio
);
1952 if (unlikely(folio_put_testzero(folio
))) {
1953 __folio_clear_lru_flags(folio
);
1955 folio_unqueue_deferred_split(folio
);
1956 if (folio_batch_add(&free_folios
, folio
) == 0) {
1957 spin_unlock_irq(&lruvec
->lru_lock
);
1958 mem_cgroup_uncharge_folios(&free_folios
);
1959 free_unref_folios(&free_folios
);
1960 spin_lock_irq(&lruvec
->lru_lock
);
1967 * All pages were isolated from the same lruvec (and isolation
1968 * inhibits memcg migration).
1970 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio
, lruvec
), folio
);
1971 lruvec_add_folio(lruvec
, folio
);
1972 nr_pages
= folio_nr_pages(folio
);
1973 nr_moved
+= nr_pages
;
1974 if (folio_test_active(folio
))
1975 workingset_age_nonresident(lruvec
, nr_pages
);
1978 if (free_folios
.nr
) {
1979 spin_unlock_irq(&lruvec
->lru_lock
);
1980 mem_cgroup_uncharge_folios(&free_folios
);
1981 free_unref_folios(&free_folios
);
1982 spin_lock_irq(&lruvec
->lru_lock
);
1989 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
1990 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
1991 * we should not throttle. Otherwise it is safe to do so.
1993 static int current_may_throttle(void)
1995 return !(current
->flags
& PF_LOCAL_THROTTLE
);
1999 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2000 * of reclaimed pages
2002 static unsigned long shrink_inactive_list(unsigned long nr_to_scan
,
2003 struct lruvec
*lruvec
, struct scan_control
*sc
,
2006 LIST_HEAD(folio_list
);
2007 unsigned long nr_scanned
;
2008 unsigned int nr_reclaimed
= 0;
2009 unsigned long nr_taken
;
2010 struct reclaim_stat stat
;
2011 bool file
= is_file_lru(lru
);
2012 enum vm_event_item item
;
2013 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2014 bool stalled
= false;
2016 while (unlikely(too_many_isolated(pgdat
, file
, sc
))) {
2020 /* wait a bit for the reclaimer. */
2022 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_ISOLATED
);
2024 /* We are about to die and free our memory. Return now. */
2025 if (fatal_signal_pending(current
))
2026 return SWAP_CLUSTER_MAX
;
2031 spin_lock_irq(&lruvec
->lru_lock
);
2033 nr_taken
= isolate_lru_folios(nr_to_scan
, lruvec
, &folio_list
,
2034 &nr_scanned
, sc
, lru
);
2036 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
2037 item
= PGSCAN_KSWAPD
+ reclaimer_offset(sc
);
2038 if (!cgroup_reclaim(sc
))
2039 __count_vm_events(item
, nr_scanned
);
2040 count_memcg_events(lruvec_memcg(lruvec
), item
, nr_scanned
);
2041 __count_vm_events(PGSCAN_ANON
+ file
, nr_scanned
);
2043 spin_unlock_irq(&lruvec
->lru_lock
);
2048 nr_reclaimed
= shrink_folio_list(&folio_list
, pgdat
, sc
, &stat
, false,
2049 lruvec_memcg(lruvec
));
2051 spin_lock_irq(&lruvec
->lru_lock
);
2052 move_folios_to_lru(lruvec
, &folio_list
);
2054 __mod_lruvec_state(lruvec
, PGDEMOTE_KSWAPD
+ reclaimer_offset(sc
),
2056 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
2057 item
= PGSTEAL_KSWAPD
+ reclaimer_offset(sc
);
2058 if (!cgroup_reclaim(sc
))
2059 __count_vm_events(item
, nr_reclaimed
);
2060 count_memcg_events(lruvec_memcg(lruvec
), item
, nr_reclaimed
);
2061 __count_vm_events(PGSTEAL_ANON
+ file
, nr_reclaimed
);
2062 spin_unlock_irq(&lruvec
->lru_lock
);
2064 lru_note_cost(lruvec
, file
, stat
.nr_pageout
, nr_scanned
- nr_reclaimed
);
2067 * If dirty folios are scanned that are not queued for IO, it
2068 * implies that flushers are not doing their job. This can
2069 * happen when memory pressure pushes dirty folios to the end of
2070 * the LRU before the dirty limits are breached and the dirty
2071 * data has expired. It can also happen when the proportion of
2072 * dirty folios grows not through writes but through memory
2073 * pressure reclaiming all the clean cache. And in some cases,
2074 * the flushers simply cannot keep up with the allocation
2075 * rate. Nudge the flusher threads in case they are asleep.
2077 if (stat
.nr_unqueued_dirty
== nr_taken
) {
2078 wakeup_flusher_threads(WB_REASON_VMSCAN
);
2080 * For cgroupv1 dirty throttling is achieved by waking up
2081 * the kernel flusher here and later waiting on folios
2082 * which are in writeback to finish (see shrink_folio_list()).
2084 * Flusher may not be able to issue writeback quickly
2085 * enough for cgroupv1 writeback throttling to work
2086 * on a large system.
2088 if (!writeback_throttling_sane(sc
))
2089 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_WRITEBACK
);
2092 sc
->nr
.dirty
+= stat
.nr_dirty
;
2093 sc
->nr
.congested
+= stat
.nr_congested
;
2094 sc
->nr
.unqueued_dirty
+= stat
.nr_unqueued_dirty
;
2095 sc
->nr
.writeback
+= stat
.nr_writeback
;
2096 sc
->nr
.immediate
+= stat
.nr_immediate
;
2097 sc
->nr
.taken
+= nr_taken
;
2099 sc
->nr
.file_taken
+= nr_taken
;
2101 trace_mm_vmscan_lru_shrink_inactive(pgdat
->node_id
,
2102 nr_scanned
, nr_reclaimed
, &stat
, sc
->priority
, file
);
2103 return nr_reclaimed
;
2107 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2109 * We move them the other way if the folio is referenced by one or more
2112 * If the folios are mostly unmapped, the processing is fast and it is
2113 * appropriate to hold lru_lock across the whole operation. But if
2114 * the folios are mapped, the processing is slow (folio_referenced()), so
2115 * we should drop lru_lock around each folio. It's impossible to balance
2116 * this, so instead we remove the folios from the LRU while processing them.
2117 * It is safe to rely on the active flag against the non-LRU folios in here
2118 * because nobody will play with that bit on a non-LRU folio.
2120 * The downside is that we have to touch folio->_refcount against each folio.
2121 * But we had to alter folio->flags anyway.
2123 static void shrink_active_list(unsigned long nr_to_scan
,
2124 struct lruvec
*lruvec
,
2125 struct scan_control
*sc
,
2128 unsigned long nr_taken
;
2129 unsigned long nr_scanned
;
2130 unsigned long vm_flags
;
2131 LIST_HEAD(l_hold
); /* The folios which were snipped off */
2132 LIST_HEAD(l_active
);
2133 LIST_HEAD(l_inactive
);
2134 unsigned nr_deactivate
, nr_activate
;
2135 unsigned nr_rotated
= 0;
2136 bool file
= is_file_lru(lru
);
2137 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2141 spin_lock_irq(&lruvec
->lru_lock
);
2143 nr_taken
= isolate_lru_folios(nr_to_scan
, lruvec
, &l_hold
,
2144 &nr_scanned
, sc
, lru
);
2146 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
2148 if (!cgroup_reclaim(sc
))
2149 __count_vm_events(PGREFILL
, nr_scanned
);
2150 count_memcg_events(lruvec_memcg(lruvec
), PGREFILL
, nr_scanned
);
2152 spin_unlock_irq(&lruvec
->lru_lock
);
2154 while (!list_empty(&l_hold
)) {
2155 struct folio
*folio
;
2158 folio
= lru_to_folio(&l_hold
);
2159 list_del(&folio
->lru
);
2161 if (unlikely(!folio_evictable(folio
))) {
2162 folio_putback_lru(folio
);
2166 if (unlikely(buffer_heads_over_limit
)) {
2167 if (folio_needs_release(folio
) &&
2168 folio_trylock(folio
)) {
2169 filemap_release_folio(folio
, 0);
2170 folio_unlock(folio
);
2174 /* Referenced or rmap lock contention: rotate */
2175 if (folio_referenced(folio
, 0, sc
->target_mem_cgroup
,
2178 * Identify referenced, file-backed active folios and
2179 * give them one more trip around the active list. So
2180 * that executable code get better chances to stay in
2181 * memory under moderate memory pressure. Anon folios
2182 * are not likely to be evicted by use-once streaming
2183 * IO, plus JVM can create lots of anon VM_EXEC folios,
2184 * so we ignore them here.
2186 if ((vm_flags
& VM_EXEC
) && folio_is_file_lru(folio
)) {
2187 nr_rotated
+= folio_nr_pages(folio
);
2188 list_add(&folio
->lru
, &l_active
);
2193 folio_clear_active(folio
); /* we are de-activating */
2194 folio_set_workingset(folio
);
2195 list_add(&folio
->lru
, &l_inactive
);
2199 * Move folios back to the lru list.
2201 spin_lock_irq(&lruvec
->lru_lock
);
2203 nr_activate
= move_folios_to_lru(lruvec
, &l_active
);
2204 nr_deactivate
= move_folios_to_lru(lruvec
, &l_inactive
);
2206 __count_vm_events(PGDEACTIVATE
, nr_deactivate
);
2207 count_memcg_events(lruvec_memcg(lruvec
), PGDEACTIVATE
, nr_deactivate
);
2209 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
2210 spin_unlock_irq(&lruvec
->lru_lock
);
2213 lru_note_cost(lruvec
, file
, 0, nr_rotated
);
2214 trace_mm_vmscan_lru_shrink_active(pgdat
->node_id
, nr_taken
, nr_activate
,
2215 nr_deactivate
, nr_rotated
, sc
->priority
, file
);
2218 static unsigned int reclaim_folio_list(struct list_head
*folio_list
,
2219 struct pglist_data
*pgdat
)
2221 struct reclaim_stat stat
;
2222 unsigned int nr_reclaimed
;
2223 struct folio
*folio
;
2224 struct scan_control sc
= {
2225 .gfp_mask
= GFP_KERNEL
,
2232 nr_reclaimed
= shrink_folio_list(folio_list
, pgdat
, &sc
, &stat
, true, NULL
);
2233 while (!list_empty(folio_list
)) {
2234 folio
= lru_to_folio(folio_list
);
2235 list_del(&folio
->lru
);
2236 folio_putback_lru(folio
);
2238 trace_mm_vmscan_reclaim_pages(pgdat
->node_id
, sc
.nr_scanned
, nr_reclaimed
, &stat
);
2240 return nr_reclaimed
;
2243 unsigned long reclaim_pages(struct list_head
*folio_list
)
2246 unsigned int nr_reclaimed
= 0;
2247 LIST_HEAD(node_folio_list
);
2248 unsigned int noreclaim_flag
;
2250 if (list_empty(folio_list
))
2251 return nr_reclaimed
;
2253 noreclaim_flag
= memalloc_noreclaim_save();
2255 nid
= folio_nid(lru_to_folio(folio_list
));
2257 struct folio
*folio
= lru_to_folio(folio_list
);
2259 if (nid
== folio_nid(folio
)) {
2260 folio_clear_active(folio
);
2261 list_move(&folio
->lru
, &node_folio_list
);
2265 nr_reclaimed
+= reclaim_folio_list(&node_folio_list
, NODE_DATA(nid
));
2266 nid
= folio_nid(lru_to_folio(folio_list
));
2267 } while (!list_empty(folio_list
));
2269 nr_reclaimed
+= reclaim_folio_list(&node_folio_list
, NODE_DATA(nid
));
2271 memalloc_noreclaim_restore(noreclaim_flag
);
2273 return nr_reclaimed
;
2276 static unsigned long shrink_list(enum lru_list lru
, unsigned long nr_to_scan
,
2277 struct lruvec
*lruvec
, struct scan_control
*sc
)
2279 if (is_active_lru(lru
)) {
2280 if (sc
->may_deactivate
& (1 << is_file_lru(lru
)))
2281 shrink_active_list(nr_to_scan
, lruvec
, sc
, lru
);
2283 sc
->skipped_deactivate
= 1;
2287 return shrink_inactive_list(nr_to_scan
, lruvec
, sc
, lru
);
2291 * The inactive anon list should be small enough that the VM never has
2292 * to do too much work.
2294 * The inactive file list should be small enough to leave most memory
2295 * to the established workingset on the scan-resistant active list,
2296 * but large enough to avoid thrashing the aggregate readahead window.
2298 * Both inactive lists should also be large enough that each inactive
2299 * folio has a chance to be referenced again before it is reclaimed.
2301 * If that fails and refaulting is observed, the inactive list grows.
2303 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2304 * on this LRU, maintained by the pageout code. An inactive_ratio
2305 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2308 * memory ratio inactive
2309 * -------------------------------------
2318 static bool inactive_is_low(struct lruvec
*lruvec
, enum lru_list inactive_lru
)
2320 enum lru_list active_lru
= inactive_lru
+ LRU_ACTIVE
;
2321 unsigned long inactive
, active
;
2322 unsigned long inactive_ratio
;
2325 inactive
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ inactive_lru
);
2326 active
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ active_lru
);
2328 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
2330 inactive_ratio
= int_sqrt(10 * gb
);
2334 return inactive
* inactive_ratio
< active
;
2344 static void prepare_scan_control(pg_data_t
*pgdat
, struct scan_control
*sc
)
2347 struct lruvec
*target_lruvec
;
2349 if (lru_gen_enabled())
2352 target_lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
, pgdat
);
2355 * Flush the memory cgroup stats in rate-limited way as we don't need
2356 * most accurate stats here. We may switch to regular stats flushing
2357 * in the future once it is cheap enough.
2359 mem_cgroup_flush_stats_ratelimited(sc
->target_mem_cgroup
);
2362 * Determine the scan balance between anon and file LRUs.
2364 spin_lock_irq(&target_lruvec
->lru_lock
);
2365 sc
->anon_cost
= target_lruvec
->anon_cost
;
2366 sc
->file_cost
= target_lruvec
->file_cost
;
2367 spin_unlock_irq(&target_lruvec
->lru_lock
);
2370 * Target desirable inactive:active list ratios for the anon
2371 * and file LRU lists.
2373 if (!sc
->force_deactivate
) {
2374 unsigned long refaults
;
2377 * When refaults are being observed, it means a new
2378 * workingset is being established. Deactivate to get
2379 * rid of any stale active pages quickly.
2381 refaults
= lruvec_page_state(target_lruvec
,
2382 WORKINGSET_ACTIVATE_ANON
);
2383 if (refaults
!= target_lruvec
->refaults
[WORKINGSET_ANON
] ||
2384 inactive_is_low(target_lruvec
, LRU_INACTIVE_ANON
))
2385 sc
->may_deactivate
|= DEACTIVATE_ANON
;
2387 sc
->may_deactivate
&= ~DEACTIVATE_ANON
;
2389 refaults
= lruvec_page_state(target_lruvec
,
2390 WORKINGSET_ACTIVATE_FILE
);
2391 if (refaults
!= target_lruvec
->refaults
[WORKINGSET_FILE
] ||
2392 inactive_is_low(target_lruvec
, LRU_INACTIVE_FILE
))
2393 sc
->may_deactivate
|= DEACTIVATE_FILE
;
2395 sc
->may_deactivate
&= ~DEACTIVATE_FILE
;
2397 sc
->may_deactivate
= DEACTIVATE_ANON
| DEACTIVATE_FILE
;
2400 * If we have plenty of inactive file pages that aren't
2401 * thrashing, try to reclaim those first before touching
2404 file
= lruvec_page_state(target_lruvec
, NR_INACTIVE_FILE
);
2405 if (file
>> sc
->priority
&& !(sc
->may_deactivate
& DEACTIVATE_FILE
) &&
2406 !sc
->no_cache_trim_mode
)
2407 sc
->cache_trim_mode
= 1;
2409 sc
->cache_trim_mode
= 0;
2412 * Prevent the reclaimer from falling into the cache trap: as
2413 * cache pages start out inactive, every cache fault will tip
2414 * the scan balance towards the file LRU. And as the file LRU
2415 * shrinks, so does the window for rotation from references.
2416 * This means we have a runaway feedback loop where a tiny
2417 * thrashing file LRU becomes infinitely more attractive than
2418 * anon pages. Try to detect this based on file LRU size.
2420 if (!cgroup_reclaim(sc
)) {
2421 unsigned long total_high_wmark
= 0;
2422 unsigned long free
, anon
;
2426 free
= sum_zone_node_page_state(pgdat
->node_id
, NR_FREE_PAGES
);
2427 file
= node_page_state(pgdat
, NR_ACTIVE_FILE
) +
2428 node_page_state(pgdat
, NR_INACTIVE_FILE
);
2430 for_each_managed_zone_pgdat(zone
, pgdat
, z
, MAX_NR_ZONES
- 1) {
2431 total_high_wmark
+= high_wmark_pages(zone
);
2435 * Consider anon: if that's low too, this isn't a
2436 * runaway file reclaim problem, but rather just
2437 * extreme pressure. Reclaim as per usual then.
2439 anon
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
2442 file
+ free
<= total_high_wmark
&&
2443 !(sc
->may_deactivate
& DEACTIVATE_ANON
) &&
2444 anon
>> sc
->priority
;
2448 static inline void calculate_pressure_balance(struct scan_control
*sc
,
2449 int swappiness
, u64
*fraction
, u64
*denominator
)
2451 unsigned long anon_cost
, file_cost
, total_cost
;
2452 unsigned long ap
, fp
;
2455 * Calculate the pressure balance between anon and file pages.
2457 * The amount of pressure we put on each LRU is inversely
2458 * proportional to the cost of reclaiming each list, as
2459 * determined by the share of pages that are refaulting, times
2460 * the relative IO cost of bringing back a swapped out
2461 * anonymous page vs reloading a filesystem page (swappiness).
2463 * Although we limit that influence to ensure no list gets
2464 * left behind completely: at least a third of the pressure is
2465 * applied, before swappiness.
2467 * With swappiness at 100, anon and file have equal IO cost.
2469 total_cost
= sc
->anon_cost
+ sc
->file_cost
;
2470 anon_cost
= total_cost
+ sc
->anon_cost
;
2471 file_cost
= total_cost
+ sc
->file_cost
;
2472 total_cost
= anon_cost
+ file_cost
;
2474 ap
= swappiness
* (total_cost
+ 1);
2475 ap
/= anon_cost
+ 1;
2477 fp
= (MAX_SWAPPINESS
- swappiness
) * (total_cost
+ 1);
2478 fp
/= file_cost
+ 1;
2480 fraction
[WORKINGSET_ANON
] = ap
;
2481 fraction
[WORKINGSET_FILE
] = fp
;
2482 *denominator
= ap
+ fp
;
2486 * Determine how aggressively the anon and file LRU lists should be
2489 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2490 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2492 static void get_scan_count(struct lruvec
*lruvec
, struct scan_control
*sc
,
2495 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2496 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
2497 int swappiness
= sc_swappiness(sc
, memcg
);
2498 u64 fraction
[ANON_AND_FILE
];
2499 u64 denominator
= 0; /* gcc */
2500 enum scan_balance scan_balance
;
2503 /* If we have no swap space, do not bother scanning anon folios. */
2504 if (!sc
->may_swap
|| !can_reclaim_anon_pages(memcg
, pgdat
->node_id
, sc
)) {
2505 scan_balance
= SCAN_FILE
;
2510 * Global reclaim will swap to prevent OOM even with no
2511 * swappiness, but memcg users want to use this knob to
2512 * disable swapping for individual groups completely when
2513 * using the memory controller's swap limit feature would be
2516 if (cgroup_reclaim(sc
) && !swappiness
) {
2517 scan_balance
= SCAN_FILE
;
2521 /* Proactive reclaim initiated by userspace for anonymous memory only */
2522 if (swappiness
== SWAPPINESS_ANON_ONLY
) {
2523 WARN_ON_ONCE(!sc
->proactive
);
2524 scan_balance
= SCAN_ANON
;
2529 * Do not apply any pressure balancing cleverness when the
2530 * system is close to OOM, scan both anon and file equally
2531 * (unless the swappiness setting disagrees with swapping).
2533 if (!sc
->priority
&& swappiness
) {
2534 scan_balance
= SCAN_EQUAL
;
2539 * If the system is almost out of file pages, force-scan anon.
2541 if (sc
->file_is_tiny
) {
2542 scan_balance
= SCAN_ANON
;
2547 * If there is enough inactive page cache, we do not reclaim
2548 * anything from the anonymous working right now to make sure
2549 * a streaming file access pattern doesn't cause swapping.
2551 if (sc
->cache_trim_mode
) {
2552 scan_balance
= SCAN_FILE
;
2556 scan_balance
= SCAN_FRACT
;
2557 calculate_pressure_balance(sc
, swappiness
, fraction
, &denominator
);
2560 for_each_evictable_lru(lru
) {
2561 bool file
= is_file_lru(lru
);
2562 unsigned long lruvec_size
;
2563 unsigned long low
, min
;
2566 lruvec_size
= lruvec_lru_size(lruvec
, lru
, sc
->reclaim_idx
);
2567 mem_cgroup_protection(sc
->target_mem_cgroup
, memcg
,
2572 * Scale a cgroup's reclaim pressure by proportioning
2573 * its current usage to its memory.low or memory.min
2576 * This is important, as otherwise scanning aggression
2577 * becomes extremely binary -- from nothing as we
2578 * approach the memory protection threshold, to totally
2579 * nominal as we exceed it. This results in requiring
2580 * setting extremely liberal protection thresholds. It
2581 * also means we simply get no protection at all if we
2582 * set it too low, which is not ideal.
2584 * If there is any protection in place, we reduce scan
2585 * pressure by how much of the total memory used is
2586 * within protection thresholds.
2588 * There is one special case: in the first reclaim pass,
2589 * we skip over all groups that are within their low
2590 * protection. If that fails to reclaim enough pages to
2591 * satisfy the reclaim goal, we come back and override
2592 * the best-effort low protection. However, we still
2593 * ideally want to honor how well-behaved groups are in
2594 * that case instead of simply punishing them all
2595 * equally. As such, we reclaim them based on how much
2596 * memory they are using, reducing the scan pressure
2597 * again by how much of the total memory used is under
2600 unsigned long cgroup_size
= mem_cgroup_size(memcg
);
2601 unsigned long protection
;
2603 /* memory.low scaling, make sure we retry before OOM */
2604 if (!sc
->memcg_low_reclaim
&& low
> min
) {
2606 sc
->memcg_low_skipped
= 1;
2611 /* Avoid TOCTOU with earlier protection check */
2612 cgroup_size
= max(cgroup_size
, protection
);
2614 scan
= lruvec_size
- lruvec_size
* protection
/
2618 * Minimally target SWAP_CLUSTER_MAX pages to keep
2619 * reclaim moving forwards, avoiding decrementing
2620 * sc->priority further than desirable.
2622 scan
= max(scan
, SWAP_CLUSTER_MAX
);
2627 scan
>>= sc
->priority
;
2630 * If the cgroup's already been deleted, make sure to
2631 * scrape out the remaining cache.
2633 if (!scan
&& !mem_cgroup_online(memcg
))
2634 scan
= min(lruvec_size
, SWAP_CLUSTER_MAX
);
2636 switch (scan_balance
) {
2638 /* Scan lists relative to size */
2642 * Scan types proportional to swappiness and
2643 * their relative recent reclaim efficiency.
2644 * Make sure we don't miss the last page on
2645 * the offlined memory cgroups because of a
2648 scan
= mem_cgroup_online(memcg
) ?
2649 div64_u64(scan
* fraction
[file
], denominator
) :
2650 DIV64_U64_ROUND_UP(scan
* fraction
[file
],
2655 /* Scan one type exclusively */
2656 if ((scan_balance
== SCAN_FILE
) != file
)
2660 /* Look ma, no brain */
2669 * Anonymous LRU management is a waste if there is
2670 * ultimately no way to reclaim the memory.
2672 static bool can_age_anon_pages(struct lruvec
*lruvec
,
2673 struct scan_control
*sc
)
2675 /* Aging the anon LRU is valuable if swap is present: */
2676 if (total_swap_pages
> 0)
2679 /* Also valuable if anon pages can be demoted: */
2680 return can_demote(lruvec_pgdat(lruvec
)->node_id
, sc
,
2681 lruvec_memcg(lruvec
));
2684 #ifdef CONFIG_LRU_GEN
2686 #ifdef CONFIG_LRU_GEN_ENABLED
2687 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps
, NR_LRU_GEN_CAPS
);
2688 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2690 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps
, NR_LRU_GEN_CAPS
);
2691 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2694 static bool should_walk_mmu(void)
2696 return arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK
);
2699 static bool should_clear_pmd_young(void)
2701 return arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG
);
2704 /******************************************************************************
2706 ******************************************************************************/
2708 #define DEFINE_MAX_SEQ(lruvec) \
2709 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2711 #define DEFINE_MIN_SEQ(lruvec) \
2712 unsigned long min_seq[ANON_AND_FILE] = { \
2713 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2714 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2717 /* Get the min/max evictable type based on swappiness */
2718 #define min_type(swappiness) (!(swappiness))
2719 #define max_type(swappiness) ((swappiness) < SWAPPINESS_ANON_ONLY)
2721 #define evictable_min_seq(min_seq, swappiness) \
2722 min((min_seq)[min_type(swappiness)], (min_seq)[max_type(swappiness)])
2724 #define for_each_gen_type_zone(gen, type, zone) \
2725 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2726 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2727 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2729 #define for_each_evictable_type(type, swappiness) \
2730 for ((type) = min_type(swappiness); (type) <= max_type(swappiness); (type)++)
2732 #define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2733 #define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2735 static struct lruvec
*get_lruvec(struct mem_cgroup
*memcg
, int nid
)
2737 struct pglist_data
*pgdat
= NODE_DATA(nid
);
2741 struct lruvec
*lruvec
= &memcg
->nodeinfo
[nid
]->lruvec
;
2743 /* see the comment in mem_cgroup_lruvec() */
2745 lruvec
->pgdat
= pgdat
;
2750 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2752 return &pgdat
->__lruvec
;
2755 static int get_swappiness(struct lruvec
*lruvec
, struct scan_control
*sc
)
2757 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
2758 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2763 if (!can_demote(pgdat
->node_id
, sc
, memcg
) &&
2764 mem_cgroup_get_nr_swap_pages(memcg
) < MIN_LRU_BATCH
)
2767 return sc_swappiness(sc
, memcg
);
2770 static int get_nr_gens(struct lruvec
*lruvec
, int type
)
2772 return lruvec
->lrugen
.max_seq
- lruvec
->lrugen
.min_seq
[type
] + 1;
2775 static bool __maybe_unused
seq_is_valid(struct lruvec
*lruvec
)
2779 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
2780 int n
= get_nr_gens(lruvec
, type
);
2782 if (n
< MIN_NR_GENS
|| n
> MAX_NR_GENS
)
2789 /******************************************************************************
2791 ******************************************************************************/
2794 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
2795 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
2796 * bits in a bitmap, k is the number of hash functions and n is the number of
2799 * Page table walkers use one of the two filters to reduce their search space.
2800 * To get rid of non-leaf entries that no longer have enough leaf entries, the
2801 * aging uses the double-buffering technique to flip to the other filter each
2802 * time it produces a new generation. For non-leaf entries that have enough
2803 * leaf entries, the aging carries them over to the next generation in
2804 * walk_pmd_range(); the eviction also report them when walking the rmap
2805 * in lru_gen_look_around().
2807 * For future optimizations:
2808 * 1. It's not necessary to keep both filters all the time. The spare one can be
2809 * freed after the RCU grace period and reallocated if needed again.
2810 * 2. And when reallocating, it's worth scaling its size according to the number
2811 * of inserted entries in the other filter, to reduce the memory overhead on
2812 * small systems and false positives on large systems.
2813 * 3. Jenkins' hash function is an alternative to Knuth's.
2815 #define BLOOM_FILTER_SHIFT 15
2817 static inline int filter_gen_from_seq(unsigned long seq
)
2819 return seq
% NR_BLOOM_FILTERS
;
2822 static void get_item_key(void *item
, int *key
)
2824 u32 hash
= hash_ptr(item
, BLOOM_FILTER_SHIFT
* 2);
2826 BUILD_BUG_ON(BLOOM_FILTER_SHIFT
* 2 > BITS_PER_TYPE(u32
));
2828 key
[0] = hash
& (BIT(BLOOM_FILTER_SHIFT
) - 1);
2829 key
[1] = hash
>> BLOOM_FILTER_SHIFT
;
2832 static bool test_bloom_filter(struct lru_gen_mm_state
*mm_state
, unsigned long seq
,
2836 unsigned long *filter
;
2837 int gen
= filter_gen_from_seq(seq
);
2839 filter
= READ_ONCE(mm_state
->filters
[gen
]);
2843 get_item_key(item
, key
);
2845 return test_bit(key
[0], filter
) && test_bit(key
[1], filter
);
2848 static void update_bloom_filter(struct lru_gen_mm_state
*mm_state
, unsigned long seq
,
2852 unsigned long *filter
;
2853 int gen
= filter_gen_from_seq(seq
);
2855 filter
= READ_ONCE(mm_state
->filters
[gen
]);
2859 get_item_key(item
, key
);
2861 if (!test_bit(key
[0], filter
))
2862 set_bit(key
[0], filter
);
2863 if (!test_bit(key
[1], filter
))
2864 set_bit(key
[1], filter
);
2867 static void reset_bloom_filter(struct lru_gen_mm_state
*mm_state
, unsigned long seq
)
2869 unsigned long *filter
;
2870 int gen
= filter_gen_from_seq(seq
);
2872 filter
= mm_state
->filters
[gen
];
2874 bitmap_clear(filter
, 0, BIT(BLOOM_FILTER_SHIFT
));
2878 filter
= bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT
),
2879 __GFP_HIGH
| __GFP_NOMEMALLOC
| __GFP_NOWARN
);
2880 WRITE_ONCE(mm_state
->filters
[gen
], filter
);
2883 /******************************************************************************
2885 ******************************************************************************/
2887 #ifdef CONFIG_LRU_GEN_WALKS_MMU
2889 static struct lru_gen_mm_list
*get_mm_list(struct mem_cgroup
*memcg
)
2891 static struct lru_gen_mm_list mm_list
= {
2892 .fifo
= LIST_HEAD_INIT(mm_list
.fifo
),
2893 .lock
= __SPIN_LOCK_UNLOCKED(mm_list
.lock
),
2898 return &memcg
->mm_list
;
2900 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2905 static struct lru_gen_mm_state
*get_mm_state(struct lruvec
*lruvec
)
2907 return &lruvec
->mm_state
;
2910 static struct mm_struct
*get_next_mm(struct lru_gen_mm_walk
*walk
)
2913 struct mm_struct
*mm
;
2914 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
2915 struct lru_gen_mm_state
*mm_state
= get_mm_state(walk
->lruvec
);
2917 mm
= list_entry(mm_state
->head
, struct mm_struct
, lru_gen
.list
);
2918 key
= pgdat
->node_id
% BITS_PER_TYPE(mm
->lru_gen
.bitmap
);
2920 if (!walk
->force_scan
&& !test_bit(key
, &mm
->lru_gen
.bitmap
))
2923 clear_bit(key
, &mm
->lru_gen
.bitmap
);
2925 return mmget_not_zero(mm
) ? mm
: NULL
;
2928 void lru_gen_add_mm(struct mm_struct
*mm
)
2931 struct mem_cgroup
*memcg
= get_mem_cgroup_from_mm(mm
);
2932 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
2934 VM_WARN_ON_ONCE(!list_empty(&mm
->lru_gen
.list
));
2936 VM_WARN_ON_ONCE(mm
->lru_gen
.memcg
);
2937 mm
->lru_gen
.memcg
= memcg
;
2939 spin_lock(&mm_list
->lock
);
2941 for_each_node_state(nid
, N_MEMORY
) {
2942 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
2943 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
2945 /* the first addition since the last iteration */
2946 if (mm_state
->tail
== &mm_list
->fifo
)
2947 mm_state
->tail
= &mm
->lru_gen
.list
;
2950 list_add_tail(&mm
->lru_gen
.list
, &mm_list
->fifo
);
2952 spin_unlock(&mm_list
->lock
);
2955 void lru_gen_del_mm(struct mm_struct
*mm
)
2958 struct lru_gen_mm_list
*mm_list
;
2959 struct mem_cgroup
*memcg
= NULL
;
2961 if (list_empty(&mm
->lru_gen
.list
))
2965 memcg
= mm
->lru_gen
.memcg
;
2967 mm_list
= get_mm_list(memcg
);
2969 spin_lock(&mm_list
->lock
);
2971 for_each_node(nid
) {
2972 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
2973 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
2975 /* where the current iteration continues after */
2976 if (mm_state
->head
== &mm
->lru_gen
.list
)
2977 mm_state
->head
= mm_state
->head
->prev
;
2979 /* where the last iteration ended before */
2980 if (mm_state
->tail
== &mm
->lru_gen
.list
)
2981 mm_state
->tail
= mm_state
->tail
->next
;
2984 list_del_init(&mm
->lru_gen
.list
);
2986 spin_unlock(&mm_list
->lock
);
2989 mem_cgroup_put(mm
->lru_gen
.memcg
);
2990 mm
->lru_gen
.memcg
= NULL
;
2995 void lru_gen_migrate_mm(struct mm_struct
*mm
)
2997 struct mem_cgroup
*memcg
;
2998 struct task_struct
*task
= rcu_dereference_protected(mm
->owner
, true);
3000 VM_WARN_ON_ONCE(task
->mm
!= mm
);
3001 lockdep_assert_held(&task
->alloc_lock
);
3003 /* for mm_update_next_owner() */
3004 if (mem_cgroup_disabled())
3007 /* migration can happen before addition */
3008 if (!mm
->lru_gen
.memcg
)
3012 memcg
= mem_cgroup_from_task(task
);
3014 if (memcg
== mm
->lru_gen
.memcg
)
3017 VM_WARN_ON_ONCE(list_empty(&mm
->lru_gen
.list
));
3024 #else /* !CONFIG_LRU_GEN_WALKS_MMU */
3026 static struct lru_gen_mm_list
*get_mm_list(struct mem_cgroup
*memcg
)
3031 static struct lru_gen_mm_state
*get_mm_state(struct lruvec
*lruvec
)
3036 static struct mm_struct
*get_next_mm(struct lru_gen_mm_walk
*walk
)
3043 static void reset_mm_stats(struct lru_gen_mm_walk
*walk
, bool last
)
3047 struct lruvec
*lruvec
= walk
->lruvec
;
3048 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
3050 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec
))->lock
);
3052 hist
= lru_hist_from_seq(walk
->seq
);
3054 for (i
= 0; i
< NR_MM_STATS
; i
++) {
3055 WRITE_ONCE(mm_state
->stats
[hist
][i
],
3056 mm_state
->stats
[hist
][i
] + walk
->mm_stats
[i
]);
3057 walk
->mm_stats
[i
] = 0;
3060 if (NR_HIST_GENS
> 1 && last
) {
3061 hist
= lru_hist_from_seq(walk
->seq
+ 1);
3063 for (i
= 0; i
< NR_MM_STATS
; i
++)
3064 WRITE_ONCE(mm_state
->stats
[hist
][i
], 0);
3068 static bool iterate_mm_list(struct lru_gen_mm_walk
*walk
, struct mm_struct
**iter
)
3072 struct mm_struct
*mm
= NULL
;
3073 struct lruvec
*lruvec
= walk
->lruvec
;
3074 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
3075 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
3076 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
3079 * mm_state->seq is incremented after each iteration of mm_list. There
3080 * are three interesting cases for this page table walker:
3081 * 1. It tries to start a new iteration with a stale max_seq: there is
3082 * nothing left to do.
3083 * 2. It started the next iteration: it needs to reset the Bloom filter
3084 * so that a fresh set of PTE tables can be recorded.
3085 * 3. It ended the current iteration: it needs to reset the mm stats
3086 * counters and tell its caller to increment max_seq.
3088 spin_lock(&mm_list
->lock
);
3090 VM_WARN_ON_ONCE(mm_state
->seq
+ 1 < walk
->seq
);
3092 if (walk
->seq
<= mm_state
->seq
)
3095 if (!mm_state
->head
)
3096 mm_state
->head
= &mm_list
->fifo
;
3098 if (mm_state
->head
== &mm_list
->fifo
)
3102 mm_state
->head
= mm_state
->head
->next
;
3103 if (mm_state
->head
== &mm_list
->fifo
) {
3104 WRITE_ONCE(mm_state
->seq
, mm_state
->seq
+ 1);
3109 /* force scan for those added after the last iteration */
3110 if (!mm_state
->tail
|| mm_state
->tail
== mm_state
->head
) {
3111 mm_state
->tail
= mm_state
->head
->next
;
3112 walk
->force_scan
= true;
3114 } while (!(mm
= get_next_mm(walk
)));
3117 reset_mm_stats(walk
, last
);
3119 spin_unlock(&mm_list
->lock
);
3122 reset_bloom_filter(mm_state
, walk
->seq
+ 1);
3132 static bool iterate_mm_list_nowalk(struct lruvec
*lruvec
, unsigned long seq
)
3134 bool success
= false;
3135 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
3136 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
3137 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
3139 spin_lock(&mm_list
->lock
);
3141 VM_WARN_ON_ONCE(mm_state
->seq
+ 1 < seq
);
3143 if (seq
> mm_state
->seq
) {
3144 mm_state
->head
= NULL
;
3145 mm_state
->tail
= NULL
;
3146 WRITE_ONCE(mm_state
->seq
, mm_state
->seq
+ 1);
3150 spin_unlock(&mm_list
->lock
);
3155 /******************************************************************************
3157 ******************************************************************************/
3160 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3162 * The P term is refaulted/(evicted+protected) from a tier in the generation
3163 * currently being evicted; the I term is the exponential moving average of the
3164 * P term over the generations previously evicted, using the smoothing factor
3165 * 1/2; the D term isn't supported.
3167 * The setpoint (SP) is always the first tier of one type; the process variable
3168 * (PV) is either any tier of the other type or any other tier of the same
3171 * The error is the difference between the SP and the PV; the correction is to
3172 * turn off protection when SP>PV or turn on protection when SP<PV.
3174 * For future optimizations:
3175 * 1. The D term may discount the other two terms over time so that long-lived
3176 * generations can resist stale information.
3179 unsigned long refaulted
;
3180 unsigned long total
;
3184 static void read_ctrl_pos(struct lruvec
*lruvec
, int type
, int tier
, int gain
,
3185 struct ctrl_pos
*pos
)
3188 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3189 int hist
= lru_hist_from_seq(lrugen
->min_seq
[type
]);
3192 pos
->refaulted
= pos
->total
= 0;
3194 for (i
= tier
% MAX_NR_TIERS
; i
<= min(tier
, MAX_NR_TIERS
- 1); i
++) {
3195 pos
->refaulted
+= lrugen
->avg_refaulted
[type
][i
] +
3196 atomic_long_read(&lrugen
->refaulted
[hist
][type
][i
]);
3197 pos
->total
+= lrugen
->avg_total
[type
][i
] +
3198 lrugen
->protected[hist
][type
][i
] +
3199 atomic_long_read(&lrugen
->evicted
[hist
][type
][i
]);
3203 static void reset_ctrl_pos(struct lruvec
*lruvec
, int type
, bool carryover
)
3206 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3207 bool clear
= carryover
? NR_HIST_GENS
== 1 : NR_HIST_GENS
> 1;
3208 unsigned long seq
= carryover
? lrugen
->min_seq
[type
] : lrugen
->max_seq
+ 1;
3210 lockdep_assert_held(&lruvec
->lru_lock
);
3212 if (!carryover
&& !clear
)
3215 hist
= lru_hist_from_seq(seq
);
3217 for (tier
= 0; tier
< MAX_NR_TIERS
; tier
++) {
3221 sum
= lrugen
->avg_refaulted
[type
][tier
] +
3222 atomic_long_read(&lrugen
->refaulted
[hist
][type
][tier
]);
3223 WRITE_ONCE(lrugen
->avg_refaulted
[type
][tier
], sum
/ 2);
3225 sum
= lrugen
->avg_total
[type
][tier
] +
3226 lrugen
->protected[hist
][type
][tier
] +
3227 atomic_long_read(&lrugen
->evicted
[hist
][type
][tier
]);
3228 WRITE_ONCE(lrugen
->avg_total
[type
][tier
], sum
/ 2);
3232 atomic_long_set(&lrugen
->refaulted
[hist
][type
][tier
], 0);
3233 atomic_long_set(&lrugen
->evicted
[hist
][type
][tier
], 0);
3234 WRITE_ONCE(lrugen
->protected[hist
][type
][tier
], 0);
3239 static bool positive_ctrl_err(struct ctrl_pos
*sp
, struct ctrl_pos
*pv
)
3242 * Return true if the PV has a limited number of refaults or a lower
3243 * refaulted/total than the SP.
3245 return pv
->refaulted
< MIN_LRU_BATCH
||
3246 pv
->refaulted
* (sp
->total
+ MIN_LRU_BATCH
) * sp
->gain
<=
3247 (sp
->refaulted
+ 1) * pv
->total
* pv
->gain
;
3250 /******************************************************************************
3252 ******************************************************************************/
3254 /* promote pages accessed through page tables */
3255 static int folio_update_gen(struct folio
*folio
, int gen
)
3257 unsigned long new_flags
, old_flags
= READ_ONCE(folio
->flags
);
3259 VM_WARN_ON_ONCE(gen
>= MAX_NR_GENS
);
3261 /* see the comment on LRU_REFS_FLAGS */
3262 if (!folio_test_referenced(folio
) && !folio_test_workingset(folio
)) {
3263 set_mask_bits(&folio
->flags
, LRU_REFS_MASK
, BIT(PG_referenced
));
3268 /* lru_gen_del_folio() has isolated this page? */
3269 if (!(old_flags
& LRU_GEN_MASK
))
3272 new_flags
= old_flags
& ~(LRU_GEN_MASK
| LRU_REFS_FLAGS
);
3273 new_flags
|= ((gen
+ 1UL) << LRU_GEN_PGOFF
) | BIT(PG_workingset
);
3274 } while (!try_cmpxchg(&folio
->flags
, &old_flags
, new_flags
));
3276 return ((old_flags
& LRU_GEN_MASK
) >> LRU_GEN_PGOFF
) - 1;
3279 /* protect pages accessed multiple times through file descriptors */
3280 static int folio_inc_gen(struct lruvec
*lruvec
, struct folio
*folio
, bool reclaiming
)
3282 int type
= folio_is_file_lru(folio
);
3283 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3284 int new_gen
, old_gen
= lru_gen_from_seq(lrugen
->min_seq
[type
]);
3285 unsigned long new_flags
, old_flags
= READ_ONCE(folio
->flags
);
3287 VM_WARN_ON_ONCE_FOLIO(!(old_flags
& LRU_GEN_MASK
), folio
);
3290 new_gen
= ((old_flags
& LRU_GEN_MASK
) >> LRU_GEN_PGOFF
) - 1;
3291 /* folio_update_gen() has promoted this page? */
3292 if (new_gen
>= 0 && new_gen
!= old_gen
)
3295 new_gen
= (old_gen
+ 1) % MAX_NR_GENS
;
3297 new_flags
= old_flags
& ~(LRU_GEN_MASK
| LRU_REFS_FLAGS
);
3298 new_flags
|= (new_gen
+ 1UL) << LRU_GEN_PGOFF
;
3299 /* for folio_end_writeback() */
3301 new_flags
|= BIT(PG_reclaim
);
3302 } while (!try_cmpxchg(&folio
->flags
, &old_flags
, new_flags
));
3304 lru_gen_update_size(lruvec
, folio
, old_gen
, new_gen
);
3309 static void update_batch_size(struct lru_gen_mm_walk
*walk
, struct folio
*folio
,
3310 int old_gen
, int new_gen
)
3312 int type
= folio_is_file_lru(folio
);
3313 int zone
= folio_zonenum(folio
);
3314 int delta
= folio_nr_pages(folio
);
3316 VM_WARN_ON_ONCE(old_gen
>= MAX_NR_GENS
);
3317 VM_WARN_ON_ONCE(new_gen
>= MAX_NR_GENS
);
3321 walk
->nr_pages
[old_gen
][type
][zone
] -= delta
;
3322 walk
->nr_pages
[new_gen
][type
][zone
] += delta
;
3325 static void reset_batch_size(struct lru_gen_mm_walk
*walk
)
3327 int gen
, type
, zone
;
3328 struct lruvec
*lruvec
= walk
->lruvec
;
3329 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3333 for_each_gen_type_zone(gen
, type
, zone
) {
3334 enum lru_list lru
= type
* LRU_INACTIVE_FILE
;
3335 int delta
= walk
->nr_pages
[gen
][type
][zone
];
3340 walk
->nr_pages
[gen
][type
][zone
] = 0;
3341 WRITE_ONCE(lrugen
->nr_pages
[gen
][type
][zone
],
3342 lrugen
->nr_pages
[gen
][type
][zone
] + delta
);
3344 if (lru_gen_is_active(lruvec
, gen
))
3346 __update_lru_size(lruvec
, lru
, zone
, delta
);
3350 static int should_skip_vma(unsigned long start
, unsigned long end
, struct mm_walk
*args
)
3352 struct address_space
*mapping
;
3353 struct vm_area_struct
*vma
= args
->vma
;
3354 struct lru_gen_mm_walk
*walk
= args
->private;
3356 if (!vma_is_accessible(vma
))
3359 if (is_vm_hugetlb_page(vma
))
3362 if (!vma_has_recency(vma
))
3365 if (vma
->vm_flags
& (VM_LOCKED
| VM_SPECIAL
))
3368 if (vma
== get_gate_vma(vma
->vm_mm
))
3371 if (vma_is_anonymous(vma
))
3372 return !walk
->swappiness
;
3374 if (WARN_ON_ONCE(!vma
->vm_file
|| !vma
->vm_file
->f_mapping
))
3377 mapping
= vma
->vm_file
->f_mapping
;
3378 if (mapping_unevictable(mapping
))
3381 if (shmem_mapping(mapping
))
3382 return !walk
->swappiness
;
3384 if (walk
->swappiness
> MAX_SWAPPINESS
)
3387 /* to exclude special mappings like dax, etc. */
3388 return !mapping
->a_ops
->read_folio
;
3392 * Some userspace memory allocators map many single-page VMAs. Instead of
3393 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3394 * table to reduce zigzags and improve cache performance.
3396 static bool get_next_vma(unsigned long mask
, unsigned long size
, struct mm_walk
*args
,
3397 unsigned long *vm_start
, unsigned long *vm_end
)
3399 unsigned long start
= round_up(*vm_end
, size
);
3400 unsigned long end
= (start
| ~mask
) + 1;
3401 VMA_ITERATOR(vmi
, args
->mm
, start
);
3403 VM_WARN_ON_ONCE(mask
& size
);
3404 VM_WARN_ON_ONCE((start
& mask
) != (*vm_start
& mask
));
3406 for_each_vma(vmi
, args
->vma
) {
3407 if (end
&& end
<= args
->vma
->vm_start
)
3410 if (should_skip_vma(args
->vma
->vm_start
, args
->vma
->vm_end
, args
))
3413 *vm_start
= max(start
, args
->vma
->vm_start
);
3414 *vm_end
= min(end
- 1, args
->vma
->vm_end
- 1) + 1;
3422 static unsigned long get_pte_pfn(pte_t pte
, struct vm_area_struct
*vma
, unsigned long addr
,
3423 struct pglist_data
*pgdat
)
3425 unsigned long pfn
= pte_pfn(pte
);
3427 VM_WARN_ON_ONCE(addr
< vma
->vm_start
|| addr
>= vma
->vm_end
);
3429 if (!pte_present(pte
) || is_zero_pfn(pfn
))
3432 if (WARN_ON_ONCE(pte_devmap(pte
) || pte_special(pte
)))
3435 if (!pte_young(pte
) && !mm_has_notifiers(vma
->vm_mm
))
3438 if (WARN_ON_ONCE(!pfn_valid(pfn
)))
3441 if (pfn
< pgdat
->node_start_pfn
|| pfn
>= pgdat_end_pfn(pgdat
))
3447 static unsigned long get_pmd_pfn(pmd_t pmd
, struct vm_area_struct
*vma
, unsigned long addr
,
3448 struct pglist_data
*pgdat
)
3450 unsigned long pfn
= pmd_pfn(pmd
);
3452 VM_WARN_ON_ONCE(addr
< vma
->vm_start
|| addr
>= vma
->vm_end
);
3454 if (!pmd_present(pmd
) || is_huge_zero_pmd(pmd
))
3457 if (WARN_ON_ONCE(pmd_devmap(pmd
)))
3460 if (!pmd_young(pmd
) && !mm_has_notifiers(vma
->vm_mm
))
3463 if (WARN_ON_ONCE(!pfn_valid(pfn
)))
3466 if (pfn
< pgdat
->node_start_pfn
|| pfn
>= pgdat_end_pfn(pgdat
))
3472 static struct folio
*get_pfn_folio(unsigned long pfn
, struct mem_cgroup
*memcg
,
3473 struct pglist_data
*pgdat
)
3475 struct folio
*folio
= pfn_folio(pfn
);
3477 if (folio_lru_gen(folio
) < 0)
3480 if (folio_nid(folio
) != pgdat
->node_id
)
3483 if (folio_memcg(folio
) != memcg
)
3489 static bool suitable_to_scan(int total
, int young
)
3491 int n
= clamp_t(int, cache_line_size() / sizeof(pte_t
), 2, 8);
3493 /* suitable if the average number of young PTEs per cacheline is >=1 */
3494 return young
* n
>= total
;
3497 static void walk_update_folio(struct lru_gen_mm_walk
*walk
, struct folio
*folio
,
3498 int new_gen
, bool dirty
)
3505 if (dirty
&& !folio_test_dirty(folio
) &&
3506 !(folio_test_anon(folio
) && folio_test_swapbacked(folio
) &&
3507 !folio_test_swapcache(folio
)))
3508 folio_mark_dirty(folio
);
3511 old_gen
= folio_update_gen(folio
, new_gen
);
3512 if (old_gen
>= 0 && old_gen
!= new_gen
)
3513 update_batch_size(walk
, folio
, old_gen
, new_gen
);
3514 } else if (lru_gen_set_refs(folio
)) {
3515 old_gen
= folio_lru_gen(folio
);
3516 if (old_gen
>= 0 && old_gen
!= new_gen
)
3517 folio_activate(folio
);
3521 static bool walk_pte_range(pmd_t
*pmd
, unsigned long start
, unsigned long end
,
3522 struct mm_walk
*args
)
3531 struct folio
*last
= NULL
;
3532 struct lru_gen_mm_walk
*walk
= args
->private;
3533 struct mem_cgroup
*memcg
= lruvec_memcg(walk
->lruvec
);
3534 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
3535 DEFINE_MAX_SEQ(walk
->lruvec
);
3536 int gen
= lru_gen_from_seq(max_seq
);
3539 pte
= pte_offset_map_rw_nolock(args
->mm
, pmd
, start
& PMD_MASK
, &pmdval
, &ptl
);
3543 if (!spin_trylock(ptl
)) {
3548 if (unlikely(!pmd_same(pmdval
, pmdp_get_lockless(pmd
)))) {
3549 pte_unmap_unlock(pte
, ptl
);
3553 arch_enter_lazy_mmu_mode();
3555 for (i
= pte_index(start
), addr
= start
; addr
!= end
; i
++, addr
+= PAGE_SIZE
) {
3557 struct folio
*folio
;
3558 pte_t ptent
= ptep_get(pte
+ i
);
3561 walk
->mm_stats
[MM_LEAF_TOTAL
]++;
3563 pfn
= get_pte_pfn(ptent
, args
->vma
, addr
, pgdat
);
3567 folio
= get_pfn_folio(pfn
, memcg
, pgdat
);
3571 if (!ptep_clear_young_notify(args
->vma
, addr
, pte
+ i
))
3574 if (last
!= folio
) {
3575 walk_update_folio(walk
, last
, gen
, dirty
);
3581 if (pte_dirty(ptent
))
3585 walk
->mm_stats
[MM_LEAF_YOUNG
]++;
3588 walk_update_folio(walk
, last
, gen
, dirty
);
3591 if (i
< PTRS_PER_PTE
&& get_next_vma(PMD_MASK
, PAGE_SIZE
, args
, &start
, &end
))
3594 arch_leave_lazy_mmu_mode();
3595 pte_unmap_unlock(pte
, ptl
);
3597 return suitable_to_scan(total
, young
);
3600 static void walk_pmd_range_locked(pud_t
*pud
, unsigned long addr
, struct vm_area_struct
*vma
,
3601 struct mm_walk
*args
, unsigned long *bitmap
, unsigned long *first
)
3607 struct folio
*last
= NULL
;
3608 struct lru_gen_mm_walk
*walk
= args
->private;
3609 struct mem_cgroup
*memcg
= lruvec_memcg(walk
->lruvec
);
3610 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
3611 DEFINE_MAX_SEQ(walk
->lruvec
);
3612 int gen
= lru_gen_from_seq(max_seq
);
3614 VM_WARN_ON_ONCE(pud_leaf(*pud
));
3616 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3619 bitmap_zero(bitmap
, MIN_LRU_BATCH
);
3623 i
= addr
== -1 ? 0 : pmd_index(addr
) - pmd_index(*first
);
3624 if (i
&& i
<= MIN_LRU_BATCH
) {
3625 __set_bit(i
- 1, bitmap
);
3629 pmd
= pmd_offset(pud
, *first
);
3631 ptl
= pmd_lockptr(args
->mm
, pmd
);
3632 if (!spin_trylock(ptl
))
3635 arch_enter_lazy_mmu_mode();
3639 struct folio
*folio
;
3641 /* don't round down the first address */
3642 addr
= i
? (*first
& PMD_MASK
) + i
* PMD_SIZE
: *first
;
3644 if (!pmd_present(pmd
[i
]))
3647 if (!pmd_trans_huge(pmd
[i
])) {
3648 if (!walk
->force_scan
&& should_clear_pmd_young() &&
3649 !mm_has_notifiers(args
->mm
))
3650 pmdp_test_and_clear_young(vma
, addr
, pmd
+ i
);
3654 pfn
= get_pmd_pfn(pmd
[i
], vma
, addr
, pgdat
);
3658 folio
= get_pfn_folio(pfn
, memcg
, pgdat
);
3662 if (!pmdp_clear_young_notify(vma
, addr
, pmd
+ i
))
3665 if (last
!= folio
) {
3666 walk_update_folio(walk
, last
, gen
, dirty
);
3672 if (pmd_dirty(pmd
[i
]))
3675 walk
->mm_stats
[MM_LEAF_YOUNG
]++;
3677 i
= i
> MIN_LRU_BATCH
? 0 : find_next_bit(bitmap
, MIN_LRU_BATCH
, i
) + 1;
3678 } while (i
<= MIN_LRU_BATCH
);
3680 walk_update_folio(walk
, last
, gen
, dirty
);
3682 arch_leave_lazy_mmu_mode();
3688 static void walk_pmd_range(pud_t
*pud
, unsigned long start
, unsigned long end
,
3689 struct mm_walk
*args
)
3695 struct vm_area_struct
*vma
;
3696 DECLARE_BITMAP(bitmap
, MIN_LRU_BATCH
);
3697 unsigned long first
= -1;
3698 struct lru_gen_mm_walk
*walk
= args
->private;
3699 struct lru_gen_mm_state
*mm_state
= get_mm_state(walk
->lruvec
);
3701 VM_WARN_ON_ONCE(pud_leaf(*pud
));
3704 * Finish an entire PMD in two passes: the first only reaches to PTE
3705 * tables to avoid taking the PMD lock; the second, if necessary, takes
3706 * the PMD lock to clear the accessed bit in PMD entries.
3708 pmd
= pmd_offset(pud
, start
& PUD_MASK
);
3710 /* walk_pte_range() may call get_next_vma() */
3712 for (i
= pmd_index(start
), addr
= start
; addr
!= end
; i
++, addr
= next
) {
3713 pmd_t val
= pmdp_get_lockless(pmd
+ i
);
3715 next
= pmd_addr_end(addr
, end
);
3717 if (!pmd_present(val
) || is_huge_zero_pmd(val
)) {
3718 walk
->mm_stats
[MM_LEAF_TOTAL
]++;
3722 if (pmd_trans_huge(val
)) {
3723 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
3724 unsigned long pfn
= get_pmd_pfn(val
, vma
, addr
, pgdat
);
3726 walk
->mm_stats
[MM_LEAF_TOTAL
]++;
3729 walk_pmd_range_locked(pud
, addr
, vma
, args
, bitmap
, &first
);
3733 if (!walk
->force_scan
&& should_clear_pmd_young() &&
3734 !mm_has_notifiers(args
->mm
)) {
3735 if (!pmd_young(val
))
3738 walk_pmd_range_locked(pud
, addr
, vma
, args
, bitmap
, &first
);
3741 if (!walk
->force_scan
&& !test_bloom_filter(mm_state
, walk
->seq
, pmd
+ i
))
3744 walk
->mm_stats
[MM_NONLEAF_FOUND
]++;
3746 if (!walk_pte_range(&val
, addr
, next
, args
))
3749 walk
->mm_stats
[MM_NONLEAF_ADDED
]++;
3751 /* carry over to the next generation */
3752 update_bloom_filter(mm_state
, walk
->seq
+ 1, pmd
+ i
);
3755 walk_pmd_range_locked(pud
, -1, vma
, args
, bitmap
, &first
);
3757 if (i
< PTRS_PER_PMD
&& get_next_vma(PUD_MASK
, PMD_SIZE
, args
, &start
, &end
))
3761 static int walk_pud_range(p4d_t
*p4d
, unsigned long start
, unsigned long end
,
3762 struct mm_walk
*args
)
3768 struct lru_gen_mm_walk
*walk
= args
->private;
3770 VM_WARN_ON_ONCE(p4d_leaf(*p4d
));
3772 pud
= pud_offset(p4d
, start
& P4D_MASK
);
3774 for (i
= pud_index(start
), addr
= start
; addr
!= end
; i
++, addr
= next
) {
3775 pud_t val
= READ_ONCE(pud
[i
]);
3777 next
= pud_addr_end(addr
, end
);
3779 if (!pud_present(val
) || WARN_ON_ONCE(pud_leaf(val
)))
3782 walk_pmd_range(&val
, addr
, next
, args
);
3784 if (need_resched() || walk
->batched
>= MAX_LRU_BATCH
) {
3785 end
= (addr
| ~PUD_MASK
) + 1;
3790 if (i
< PTRS_PER_PUD
&& get_next_vma(P4D_MASK
, PUD_SIZE
, args
, &start
, &end
))
3793 end
= round_up(end
, P4D_SIZE
);
3795 if (!end
|| !args
->vma
)
3798 walk
->next_addr
= max(end
, args
->vma
->vm_start
);
3803 static void walk_mm(struct mm_struct
*mm
, struct lru_gen_mm_walk
*walk
)
3805 static const struct mm_walk_ops mm_walk_ops
= {
3806 .test_walk
= should_skip_vma
,
3807 .p4d_entry
= walk_pud_range
,
3808 .walk_lock
= PGWALK_RDLOCK
,
3811 struct lruvec
*lruvec
= walk
->lruvec
;
3813 walk
->next_addr
= FIRST_USER_ADDRESS
;
3816 DEFINE_MAX_SEQ(lruvec
);
3820 /* another thread might have called inc_max_seq() */
3821 if (walk
->seq
!= max_seq
)
3824 /* the caller might be holding the lock for write */
3825 if (mmap_read_trylock(mm
)) {
3826 err
= walk_page_range(mm
, walk
->next_addr
, ULONG_MAX
, &mm_walk_ops
, walk
);
3828 mmap_read_unlock(mm
);
3831 if (walk
->batched
) {
3832 spin_lock_irq(&lruvec
->lru_lock
);
3833 reset_batch_size(walk
);
3834 spin_unlock_irq(&lruvec
->lru_lock
);
3838 } while (err
== -EAGAIN
);
3841 static struct lru_gen_mm_walk
*set_mm_walk(struct pglist_data
*pgdat
, bool force_alloc
)
3843 struct lru_gen_mm_walk
*walk
= current
->reclaim_state
->mm_walk
;
3845 if (pgdat
&& current_is_kswapd()) {
3846 VM_WARN_ON_ONCE(walk
);
3848 walk
= &pgdat
->mm_walk
;
3849 } else if (!walk
&& force_alloc
) {
3850 VM_WARN_ON_ONCE(current_is_kswapd());
3852 walk
= kzalloc(sizeof(*walk
), __GFP_HIGH
| __GFP_NOMEMALLOC
| __GFP_NOWARN
);
3855 current
->reclaim_state
->mm_walk
= walk
;
3860 static void clear_mm_walk(void)
3862 struct lru_gen_mm_walk
*walk
= current
->reclaim_state
->mm_walk
;
3864 VM_WARN_ON_ONCE(walk
&& memchr_inv(walk
->nr_pages
, 0, sizeof(walk
->nr_pages
)));
3865 VM_WARN_ON_ONCE(walk
&& memchr_inv(walk
->mm_stats
, 0, sizeof(walk
->mm_stats
)));
3867 current
->reclaim_state
->mm_walk
= NULL
;
3869 if (!current_is_kswapd())
3873 static bool inc_min_seq(struct lruvec
*lruvec
, int type
, int swappiness
)
3876 int remaining
= MAX_LRU_BATCH
;
3877 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3878 int hist
= lru_hist_from_seq(lrugen
->min_seq
[type
]);
3879 int new_gen
, old_gen
= lru_gen_from_seq(lrugen
->min_seq
[type
]);
3881 /* For file type, skip the check if swappiness is anon only */
3882 if (type
&& (swappiness
== SWAPPINESS_ANON_ONLY
))
3885 /* For anon type, skip the check if swappiness is zero (file only) */
3886 if (!type
&& !swappiness
)
3889 /* prevent cold/hot inversion if the type is evictable */
3890 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
3891 struct list_head
*head
= &lrugen
->folios
[old_gen
][type
][zone
];
3893 while (!list_empty(head
)) {
3894 struct folio
*folio
= lru_to_folio(head
);
3895 int refs
= folio_lru_refs(folio
);
3896 bool workingset
= folio_test_workingset(folio
);
3898 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
3899 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
), folio
);
3900 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
3901 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio
) != zone
, folio
);
3903 new_gen
= folio_inc_gen(lruvec
, folio
, false);
3904 list_move_tail(&folio
->lru
, &lrugen
->folios
[new_gen
][type
][zone
]);
3906 /* don't count the workingset being lazily promoted */
3907 if (refs
+ workingset
!= BIT(LRU_REFS_WIDTH
) + 1) {
3908 int tier
= lru_tier_from_refs(refs
, workingset
);
3909 int delta
= folio_nr_pages(folio
);
3911 WRITE_ONCE(lrugen
->protected[hist
][type
][tier
],
3912 lrugen
->protected[hist
][type
][tier
] + delta
);
3920 reset_ctrl_pos(lruvec
, type
, true);
3921 WRITE_ONCE(lrugen
->min_seq
[type
], lrugen
->min_seq
[type
] + 1);
3926 static bool try_to_inc_min_seq(struct lruvec
*lruvec
, int swappiness
)
3928 int gen
, type
, zone
;
3929 bool success
= false;
3930 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3931 DEFINE_MIN_SEQ(lruvec
);
3933 VM_WARN_ON_ONCE(!seq_is_valid(lruvec
));
3935 /* find the oldest populated generation */
3936 for_each_evictable_type(type
, swappiness
) {
3937 while (min_seq
[type
] + MIN_NR_GENS
<= lrugen
->max_seq
) {
3938 gen
= lru_gen_from_seq(min_seq
[type
]);
3940 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
3941 if (!list_empty(&lrugen
->folios
[gen
][type
][zone
]))
3951 /* see the comment on lru_gen_folio */
3952 if (swappiness
&& swappiness
<= MAX_SWAPPINESS
) {
3953 unsigned long seq
= lrugen
->max_seq
- MIN_NR_GENS
;
3955 if (min_seq
[LRU_GEN_ANON
] > seq
&& min_seq
[LRU_GEN_FILE
] < seq
)
3956 min_seq
[LRU_GEN_ANON
] = seq
;
3957 else if (min_seq
[LRU_GEN_FILE
] > seq
&& min_seq
[LRU_GEN_ANON
] < seq
)
3958 min_seq
[LRU_GEN_FILE
] = seq
;
3961 for_each_evictable_type(type
, swappiness
) {
3962 if (min_seq
[type
] <= lrugen
->min_seq
[type
])
3965 reset_ctrl_pos(lruvec
, type
, true);
3966 WRITE_ONCE(lrugen
->min_seq
[type
], min_seq
[type
]);
3973 static bool inc_max_seq(struct lruvec
*lruvec
, unsigned long seq
, int swappiness
)
3978 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3980 if (seq
< READ_ONCE(lrugen
->max_seq
))
3983 spin_lock_irq(&lruvec
->lru_lock
);
3985 VM_WARN_ON_ONCE(!seq_is_valid(lruvec
));
3987 success
= seq
== lrugen
->max_seq
;
3991 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
3992 if (get_nr_gens(lruvec
, type
) != MAX_NR_GENS
)
3995 if (inc_min_seq(lruvec
, type
, swappiness
))
3998 spin_unlock_irq(&lruvec
->lru_lock
);
4004 * Update the active/inactive LRU sizes for compatibility. Both sides of
4005 * the current max_seq need to be covered, since max_seq+1 can overlap
4006 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4007 * overlap, cold/hot inversion happens.
4009 prev
= lru_gen_from_seq(lrugen
->max_seq
- 1);
4010 next
= lru_gen_from_seq(lrugen
->max_seq
+ 1);
4012 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
4013 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
4014 enum lru_list lru
= type
* LRU_INACTIVE_FILE
;
4015 long delta
= lrugen
->nr_pages
[prev
][type
][zone
] -
4016 lrugen
->nr_pages
[next
][type
][zone
];
4021 __update_lru_size(lruvec
, lru
, zone
, delta
);
4022 __update_lru_size(lruvec
, lru
+ LRU_ACTIVE
, zone
, -delta
);
4026 for (type
= 0; type
< ANON_AND_FILE
; type
++)
4027 reset_ctrl_pos(lruvec
, type
, false);
4029 WRITE_ONCE(lrugen
->timestamps
[next
], jiffies
);
4030 /* make sure preceding modifications appear */
4031 smp_store_release(&lrugen
->max_seq
, lrugen
->max_seq
+ 1);
4033 spin_unlock_irq(&lruvec
->lru_lock
);
4038 static bool try_to_inc_max_seq(struct lruvec
*lruvec
, unsigned long seq
,
4039 int swappiness
, bool force_scan
)
4042 struct lru_gen_mm_walk
*walk
;
4043 struct mm_struct
*mm
= NULL
;
4044 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4045 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
4047 VM_WARN_ON_ONCE(seq
> READ_ONCE(lrugen
->max_seq
));
4050 return inc_max_seq(lruvec
, seq
, swappiness
);
4052 /* see the comment in iterate_mm_list() */
4053 if (seq
<= READ_ONCE(mm_state
->seq
))
4057 * If the hardware doesn't automatically set the accessed bit, fallback
4058 * to lru_gen_look_around(), which only clears the accessed bit in a
4059 * handful of PTEs. Spreading the work out over a period of time usually
4060 * is less efficient, but it avoids bursty page faults.
4062 if (!should_walk_mmu()) {
4063 success
= iterate_mm_list_nowalk(lruvec
, seq
);
4067 walk
= set_mm_walk(NULL
, true);
4069 success
= iterate_mm_list_nowalk(lruvec
, seq
);
4073 walk
->lruvec
= lruvec
;
4075 walk
->swappiness
= swappiness
;
4076 walk
->force_scan
= force_scan
;
4079 success
= iterate_mm_list(walk
, &mm
);
4085 success
= inc_max_seq(lruvec
, seq
, swappiness
);
4086 WARN_ON_ONCE(!success
);
4092 /******************************************************************************
4093 * working set protection
4094 ******************************************************************************/
4096 static void set_initial_priority(struct pglist_data
*pgdat
, struct scan_control
*sc
)
4099 unsigned long reclaimable
;
4101 if (sc
->priority
!= DEF_PRIORITY
|| sc
->nr_to_reclaim
< MIN_LRU_BATCH
)
4104 * Determine the initial priority based on
4105 * (total >> priority) * reclaimed_to_scanned_ratio = nr_to_reclaim,
4106 * where reclaimed_to_scanned_ratio = inactive / total.
4108 reclaimable
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
4109 if (can_reclaim_anon_pages(NULL
, pgdat
->node_id
, sc
))
4110 reclaimable
+= node_page_state(pgdat
, NR_INACTIVE_ANON
);
4112 /* round down reclaimable and round up sc->nr_to_reclaim */
4113 priority
= fls_long(reclaimable
) - 1 - fls_long(sc
->nr_to_reclaim
- 1);
4116 * The estimation is based on LRU pages only, so cap it to prevent
4117 * overshoots of shrinker objects by large margins.
4119 sc
->priority
= clamp(priority
, DEF_PRIORITY
/ 2, DEF_PRIORITY
);
4122 static bool lruvec_is_sizable(struct lruvec
*lruvec
, struct scan_control
*sc
)
4124 int gen
, type
, zone
;
4125 unsigned long total
= 0;
4126 int swappiness
= get_swappiness(lruvec
, sc
);
4127 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4128 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4129 DEFINE_MAX_SEQ(lruvec
);
4130 DEFINE_MIN_SEQ(lruvec
);
4132 for_each_evictable_type(type
, swappiness
) {
4135 for (seq
= min_seq
[type
]; seq
<= max_seq
; seq
++) {
4136 gen
= lru_gen_from_seq(seq
);
4138 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++)
4139 total
+= max(READ_ONCE(lrugen
->nr_pages
[gen
][type
][zone
]), 0L);
4143 /* whether the size is big enough to be helpful */
4144 return mem_cgroup_online(memcg
) ? (total
>> sc
->priority
) : total
;
4147 static bool lruvec_is_reclaimable(struct lruvec
*lruvec
, struct scan_control
*sc
,
4148 unsigned long min_ttl
)
4151 unsigned long birth
;
4152 int swappiness
= get_swappiness(lruvec
, sc
);
4153 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4154 DEFINE_MIN_SEQ(lruvec
);
4156 if (mem_cgroup_below_min(NULL
, memcg
))
4159 if (!lruvec_is_sizable(lruvec
, sc
))
4162 gen
= lru_gen_from_seq(evictable_min_seq(min_seq
, swappiness
));
4163 birth
= READ_ONCE(lruvec
->lrugen
.timestamps
[gen
]);
4165 return time_is_before_jiffies(birth
+ min_ttl
);
4168 /* to protect the working set of the last N jiffies */
4169 static unsigned long lru_gen_min_ttl __read_mostly
;
4171 static void lru_gen_age_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
4173 struct mem_cgroup
*memcg
;
4174 unsigned long min_ttl
= READ_ONCE(lru_gen_min_ttl
);
4175 bool reclaimable
= !min_ttl
;
4177 VM_WARN_ON_ONCE(!current_is_kswapd());
4179 set_initial_priority(pgdat
, sc
);
4181 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
4183 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
4185 mem_cgroup_calculate_protection(NULL
, memcg
);
4188 reclaimable
= lruvec_is_reclaimable(lruvec
, sc
, min_ttl
);
4189 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)));
4192 * The main goal is to OOM kill if every generation from all memcgs is
4193 * younger than min_ttl. However, another possibility is all memcgs are
4194 * either too small or below min.
4196 if (!reclaimable
&& mutex_trylock(&oom_lock
)) {
4197 struct oom_control oc
= {
4198 .gfp_mask
= sc
->gfp_mask
,
4203 mutex_unlock(&oom_lock
);
4207 /******************************************************************************
4208 * rmap/PT walk feedback
4209 ******************************************************************************/
4212 * This function exploits spatial locality when shrink_folio_list() walks the
4213 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4214 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4215 * the PTE table to the Bloom filter. This forms a feedback loop between the
4216 * eviction and the aging.
4218 bool lru_gen_look_around(struct page_vma_mapped_walk
*pvmw
)
4222 unsigned long start
;
4224 struct lru_gen_mm_walk
*walk
;
4225 struct folio
*last
= NULL
;
4227 pte_t
*pte
= pvmw
->pte
;
4228 unsigned long addr
= pvmw
->address
;
4229 struct vm_area_struct
*vma
= pvmw
->vma
;
4230 struct folio
*folio
= pfn_folio(pvmw
->pfn
);
4231 struct mem_cgroup
*memcg
= folio_memcg(folio
);
4232 struct pglist_data
*pgdat
= folio_pgdat(folio
);
4233 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
4234 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
4235 DEFINE_MAX_SEQ(lruvec
);
4236 int gen
= lru_gen_from_seq(max_seq
);
4238 lockdep_assert_held(pvmw
->ptl
);
4239 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio
), folio
);
4241 if (!ptep_clear_young_notify(vma
, addr
, pte
))
4244 if (spin_is_contended(pvmw
->ptl
))
4247 /* exclude special VMAs containing anon pages from COW */
4248 if (vma
->vm_flags
& VM_SPECIAL
)
4251 /* avoid taking the LRU lock under the PTL when possible */
4252 walk
= current
->reclaim_state
? current
->reclaim_state
->mm_walk
: NULL
;
4254 start
= max(addr
& PMD_MASK
, vma
->vm_start
);
4255 end
= min(addr
| ~PMD_MASK
, vma
->vm_end
- 1) + 1;
4257 if (end
- start
== PAGE_SIZE
)
4260 if (end
- start
> MIN_LRU_BATCH
* PAGE_SIZE
) {
4261 if (addr
- start
< MIN_LRU_BATCH
* PAGE_SIZE
/ 2)
4262 end
= start
+ MIN_LRU_BATCH
* PAGE_SIZE
;
4263 else if (end
- addr
< MIN_LRU_BATCH
* PAGE_SIZE
/ 2)
4264 start
= end
- MIN_LRU_BATCH
* PAGE_SIZE
;
4266 start
= addr
- MIN_LRU_BATCH
* PAGE_SIZE
/ 2;
4267 end
= addr
+ MIN_LRU_BATCH
* PAGE_SIZE
/ 2;
4271 arch_enter_lazy_mmu_mode();
4273 pte
-= (addr
- start
) / PAGE_SIZE
;
4275 for (i
= 0, addr
= start
; addr
!= end
; i
++, addr
+= PAGE_SIZE
) {
4277 pte_t ptent
= ptep_get(pte
+ i
);
4279 pfn
= get_pte_pfn(ptent
, vma
, addr
, pgdat
);
4283 folio
= get_pfn_folio(pfn
, memcg
, pgdat
);
4287 if (!ptep_clear_young_notify(vma
, addr
, pte
+ i
))
4290 if (last
!= folio
) {
4291 walk_update_folio(walk
, last
, gen
, dirty
);
4297 if (pte_dirty(ptent
))
4303 walk_update_folio(walk
, last
, gen
, dirty
);
4305 arch_leave_lazy_mmu_mode();
4307 /* feedback from rmap walkers to page table walkers */
4308 if (mm_state
&& suitable_to_scan(i
, young
))
4309 update_bloom_filter(mm_state
, max_seq
, pvmw
->pmd
);
4314 /******************************************************************************
4316 ******************************************************************************/
4318 /* see the comment on MEMCG_NR_GENS */
4327 static void lru_gen_rotate_memcg(struct lruvec
*lruvec
, int op
)
4331 unsigned long flags
;
4332 int bin
= get_random_u32_below(MEMCG_NR_BINS
);
4333 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
4335 spin_lock_irqsave(&pgdat
->memcg_lru
.lock
, flags
);
4337 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec
->lrugen
.list
));
4340 new = old
= lruvec
->lrugen
.gen
;
4342 /* see the comment on MEMCG_NR_GENS */
4343 if (op
== MEMCG_LRU_HEAD
)
4344 seg
= MEMCG_LRU_HEAD
;
4345 else if (op
== MEMCG_LRU_TAIL
)
4346 seg
= MEMCG_LRU_TAIL
;
4347 else if (op
== MEMCG_LRU_OLD
)
4348 new = get_memcg_gen(pgdat
->memcg_lru
.seq
);
4349 else if (op
== MEMCG_LRU_YOUNG
)
4350 new = get_memcg_gen(pgdat
->memcg_lru
.seq
+ 1);
4352 VM_WARN_ON_ONCE(true);
4354 WRITE_ONCE(lruvec
->lrugen
.seg
, seg
);
4355 WRITE_ONCE(lruvec
->lrugen
.gen
, new);
4357 hlist_nulls_del_rcu(&lruvec
->lrugen
.list
);
4359 if (op
== MEMCG_LRU_HEAD
|| op
== MEMCG_LRU_OLD
)
4360 hlist_nulls_add_head_rcu(&lruvec
->lrugen
.list
, &pgdat
->memcg_lru
.fifo
[new][bin
]);
4362 hlist_nulls_add_tail_rcu(&lruvec
->lrugen
.list
, &pgdat
->memcg_lru
.fifo
[new][bin
]);
4364 pgdat
->memcg_lru
.nr_memcgs
[old
]--;
4365 pgdat
->memcg_lru
.nr_memcgs
[new]++;
4367 if (!pgdat
->memcg_lru
.nr_memcgs
[old
] && old
== get_memcg_gen(pgdat
->memcg_lru
.seq
))
4368 WRITE_ONCE(pgdat
->memcg_lru
.seq
, pgdat
->memcg_lru
.seq
+ 1);
4370 spin_unlock_irqrestore(&pgdat
->memcg_lru
.lock
, flags
);
4375 void lru_gen_online_memcg(struct mem_cgroup
*memcg
)
4379 int bin
= get_random_u32_below(MEMCG_NR_BINS
);
4381 for_each_node(nid
) {
4382 struct pglist_data
*pgdat
= NODE_DATA(nid
);
4383 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4385 spin_lock_irq(&pgdat
->memcg_lru
.lock
);
4387 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec
->lrugen
.list
));
4389 gen
= get_memcg_gen(pgdat
->memcg_lru
.seq
);
4391 lruvec
->lrugen
.gen
= gen
;
4393 hlist_nulls_add_tail_rcu(&lruvec
->lrugen
.list
, &pgdat
->memcg_lru
.fifo
[gen
][bin
]);
4394 pgdat
->memcg_lru
.nr_memcgs
[gen
]++;
4396 spin_unlock_irq(&pgdat
->memcg_lru
.lock
);
4400 void lru_gen_offline_memcg(struct mem_cgroup
*memcg
)
4404 for_each_node(nid
) {
4405 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4407 lru_gen_rotate_memcg(lruvec
, MEMCG_LRU_OLD
);
4411 void lru_gen_release_memcg(struct mem_cgroup
*memcg
)
4416 for_each_node(nid
) {
4417 struct pglist_data
*pgdat
= NODE_DATA(nid
);
4418 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4420 spin_lock_irq(&pgdat
->memcg_lru
.lock
);
4422 if (hlist_nulls_unhashed(&lruvec
->lrugen
.list
))
4425 gen
= lruvec
->lrugen
.gen
;
4427 hlist_nulls_del_init_rcu(&lruvec
->lrugen
.list
);
4428 pgdat
->memcg_lru
.nr_memcgs
[gen
]--;
4430 if (!pgdat
->memcg_lru
.nr_memcgs
[gen
] && gen
== get_memcg_gen(pgdat
->memcg_lru
.seq
))
4431 WRITE_ONCE(pgdat
->memcg_lru
.seq
, pgdat
->memcg_lru
.seq
+ 1);
4433 spin_unlock_irq(&pgdat
->memcg_lru
.lock
);
4437 void lru_gen_soft_reclaim(struct mem_cgroup
*memcg
, int nid
)
4439 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4441 /* see the comment on MEMCG_NR_GENS */
4442 if (READ_ONCE(lruvec
->lrugen
.seg
) != MEMCG_LRU_HEAD
)
4443 lru_gen_rotate_memcg(lruvec
, MEMCG_LRU_HEAD
);
4446 #endif /* CONFIG_MEMCG */
4448 /******************************************************************************
4450 ******************************************************************************/
4452 static bool sort_folio(struct lruvec
*lruvec
, struct folio
*folio
, struct scan_control
*sc
,
4456 bool dirty
, writeback
;
4457 int gen
= folio_lru_gen(folio
);
4458 int type
= folio_is_file_lru(folio
);
4459 int zone
= folio_zonenum(folio
);
4460 int delta
= folio_nr_pages(folio
);
4461 int refs
= folio_lru_refs(folio
);
4462 bool workingset
= folio_test_workingset(folio
);
4463 int tier
= lru_tier_from_refs(refs
, workingset
);
4464 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4466 VM_WARN_ON_ONCE_FOLIO(gen
>= MAX_NR_GENS
, folio
);
4469 if (!folio_evictable(folio
)) {
4470 success
= lru_gen_del_folio(lruvec
, folio
, true);
4471 VM_WARN_ON_ONCE_FOLIO(!success
, folio
);
4472 folio_set_unevictable(folio
);
4473 lruvec_add_folio(lruvec
, folio
);
4474 __count_vm_events(UNEVICTABLE_PGCULLED
, delta
);
4479 if (gen
!= lru_gen_from_seq(lrugen
->min_seq
[type
])) {
4480 list_move(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4485 if (tier
> tier_idx
|| refs
+ workingset
== BIT(LRU_REFS_WIDTH
) + 1) {
4486 gen
= folio_inc_gen(lruvec
, folio
, false);
4487 list_move(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4489 /* don't count the workingset being lazily promoted */
4490 if (refs
+ workingset
!= BIT(LRU_REFS_WIDTH
) + 1) {
4491 int hist
= lru_hist_from_seq(lrugen
->min_seq
[type
]);
4493 WRITE_ONCE(lrugen
->protected[hist
][type
][tier
],
4494 lrugen
->protected[hist
][type
][tier
] + delta
);
4500 if (!folio_test_lru(folio
) || zone
> sc
->reclaim_idx
) {
4501 gen
= folio_inc_gen(lruvec
, folio
, false);
4502 list_move_tail(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4506 dirty
= folio_test_dirty(folio
);
4507 writeback
= folio_test_writeback(folio
);
4508 if (type
== LRU_GEN_FILE
&& dirty
) {
4509 sc
->nr
.file_taken
+= delta
;
4511 sc
->nr
.unqueued_dirty
+= delta
;
4514 /* waiting for writeback */
4515 if (writeback
|| (type
== LRU_GEN_FILE
&& dirty
)) {
4516 gen
= folio_inc_gen(lruvec
, folio
, true);
4517 list_move(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4524 static bool isolate_folio(struct lruvec
*lruvec
, struct folio
*folio
, struct scan_control
*sc
)
4528 /* swap constrained */
4529 if (!(sc
->gfp_mask
& __GFP_IO
) &&
4530 (folio_test_dirty(folio
) ||
4531 (folio_test_anon(folio
) && !folio_test_swapcache(folio
))))
4534 /* raced with release_pages() */
4535 if (!folio_try_get(folio
))
4538 /* raced with another isolation */
4539 if (!folio_test_clear_lru(folio
)) {
4544 /* see the comment on LRU_REFS_FLAGS */
4545 if (!folio_test_referenced(folio
))
4546 set_mask_bits(&folio
->flags
, LRU_REFS_MASK
, 0);
4548 /* for shrink_folio_list() */
4549 folio_clear_reclaim(folio
);
4551 success
= lru_gen_del_folio(lruvec
, folio
, true);
4552 VM_WARN_ON_ONCE_FOLIO(!success
, folio
);
4557 static int scan_folios(struct lruvec
*lruvec
, struct scan_control
*sc
,
4558 int type
, int tier
, struct list_head
*list
)
4562 enum vm_event_item item
;
4567 int remaining
= MAX_LRU_BATCH
;
4568 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4569 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4571 VM_WARN_ON_ONCE(!list_empty(list
));
4573 if (get_nr_gens(lruvec
, type
) == MIN_NR_GENS
)
4576 gen
= lru_gen_from_seq(lrugen
->min_seq
[type
]);
4578 for (i
= MAX_NR_ZONES
; i
> 0; i
--) {
4580 int skipped_zone
= 0;
4581 int zone
= (sc
->reclaim_idx
+ i
) % MAX_NR_ZONES
;
4582 struct list_head
*head
= &lrugen
->folios
[gen
][type
][zone
];
4584 while (!list_empty(head
)) {
4585 struct folio
*folio
= lru_to_folio(head
);
4586 int delta
= folio_nr_pages(folio
);
4588 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
4589 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
), folio
);
4590 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
4591 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio
) != zone
, folio
);
4595 if (sort_folio(lruvec
, folio
, sc
, tier
))
4597 else if (isolate_folio(lruvec
, folio
, sc
)) {
4598 list_add(&folio
->lru
, list
);
4601 list_move(&folio
->lru
, &moved
);
4602 skipped_zone
+= delta
;
4605 if (!--remaining
|| max(isolated
, skipped_zone
) >= MIN_LRU_BATCH
)
4610 list_splice(&moved
, head
);
4611 __count_zid_vm_events(PGSCAN_SKIP
, zone
, skipped_zone
);
4612 skipped
+= skipped_zone
;
4615 if (!remaining
|| isolated
>= MIN_LRU_BATCH
)
4619 item
= PGSCAN_KSWAPD
+ reclaimer_offset(sc
);
4620 if (!cgroup_reclaim(sc
)) {
4621 __count_vm_events(item
, isolated
);
4622 __count_vm_events(PGREFILL
, sorted
);
4624 count_memcg_events(memcg
, item
, isolated
);
4625 count_memcg_events(memcg
, PGREFILL
, sorted
);
4626 __count_vm_events(PGSCAN_ANON
+ type
, isolated
);
4627 trace_mm_vmscan_lru_isolate(sc
->reclaim_idx
, sc
->order
, MAX_LRU_BATCH
,
4628 scanned
, skipped
, isolated
,
4629 type
? LRU_INACTIVE_FILE
: LRU_INACTIVE_ANON
);
4630 if (type
== LRU_GEN_FILE
)
4631 sc
->nr
.file_taken
+= isolated
;
4633 * There might not be eligible folios due to reclaim_idx. Check the
4634 * remaining to prevent livelock if it's not making progress.
4636 return isolated
|| !remaining
? scanned
: 0;
4639 static int get_tier_idx(struct lruvec
*lruvec
, int type
)
4642 struct ctrl_pos sp
, pv
;
4645 * To leave a margin for fluctuations, use a larger gain factor (2:3).
4646 * This value is chosen because any other tier would have at least twice
4647 * as many refaults as the first tier.
4649 read_ctrl_pos(lruvec
, type
, 0, 2, &sp
);
4650 for (tier
= 1; tier
< MAX_NR_TIERS
; tier
++) {
4651 read_ctrl_pos(lruvec
, type
, tier
, 3, &pv
);
4652 if (!positive_ctrl_err(&sp
, &pv
))
4659 static int get_type_to_scan(struct lruvec
*lruvec
, int swappiness
)
4661 struct ctrl_pos sp
, pv
;
4663 if (swappiness
<= MIN_SWAPPINESS
+ 1)
4664 return LRU_GEN_FILE
;
4666 if (swappiness
>= MAX_SWAPPINESS
)
4667 return LRU_GEN_ANON
;
4669 * Compare the sum of all tiers of anon with that of file to determine
4670 * which type to scan.
4672 read_ctrl_pos(lruvec
, LRU_GEN_ANON
, MAX_NR_TIERS
, swappiness
, &sp
);
4673 read_ctrl_pos(lruvec
, LRU_GEN_FILE
, MAX_NR_TIERS
, MAX_SWAPPINESS
- swappiness
, &pv
);
4675 return positive_ctrl_err(&sp
, &pv
);
4678 static int isolate_folios(struct lruvec
*lruvec
, struct scan_control
*sc
, int swappiness
,
4679 int *type_scanned
, struct list_head
*list
)
4682 int type
= get_type_to_scan(lruvec
, swappiness
);
4684 for_each_evictable_type(i
, swappiness
) {
4686 int tier
= get_tier_idx(lruvec
, type
);
4688 *type_scanned
= type
;
4690 scanned
= scan_folios(lruvec
, sc
, type
, tier
, list
);
4700 static int evict_folios(struct lruvec
*lruvec
, struct scan_control
*sc
, int swappiness
)
4707 struct folio
*folio
;
4709 enum vm_event_item item
;
4710 struct reclaim_stat stat
;
4711 struct lru_gen_mm_walk
*walk
;
4712 bool skip_retry
= false;
4713 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4714 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4715 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
4717 spin_lock_irq(&lruvec
->lru_lock
);
4719 scanned
= isolate_folios(lruvec
, sc
, swappiness
, &type
, &list
);
4721 scanned
+= try_to_inc_min_seq(lruvec
, swappiness
);
4723 if (evictable_min_seq(lrugen
->min_seq
, swappiness
) + MIN_NR_GENS
> lrugen
->max_seq
)
4726 spin_unlock_irq(&lruvec
->lru_lock
);
4728 if (list_empty(&list
))
4731 reclaimed
= shrink_folio_list(&list
, pgdat
, sc
, &stat
, false, memcg
);
4732 sc
->nr
.unqueued_dirty
+= stat
.nr_unqueued_dirty
;
4733 sc
->nr_reclaimed
+= reclaimed
;
4734 trace_mm_vmscan_lru_shrink_inactive(pgdat
->node_id
,
4735 scanned
, reclaimed
, &stat
, sc
->priority
,
4736 type
? LRU_INACTIVE_FILE
: LRU_INACTIVE_ANON
);
4738 list_for_each_entry_safe_reverse(folio
, next
, &list
, lru
) {
4739 DEFINE_MIN_SEQ(lruvec
);
4741 if (!folio_evictable(folio
)) {
4742 list_del(&folio
->lru
);
4743 folio_putback_lru(folio
);
4747 /* retry folios that may have missed folio_rotate_reclaimable() */
4748 if (!skip_retry
&& !folio_test_active(folio
) && !folio_mapped(folio
) &&
4749 !folio_test_dirty(folio
) && !folio_test_writeback(folio
)) {
4750 list_move(&folio
->lru
, &clean
);
4754 /* don't add rejected folios to the oldest generation */
4755 if (lru_gen_folio_seq(lruvec
, folio
, false) == min_seq
[type
])
4756 set_mask_bits(&folio
->flags
, LRU_REFS_FLAGS
, BIT(PG_active
));
4759 spin_lock_irq(&lruvec
->lru_lock
);
4761 move_folios_to_lru(lruvec
, &list
);
4763 walk
= current
->reclaim_state
->mm_walk
;
4764 if (walk
&& walk
->batched
) {
4765 walk
->lruvec
= lruvec
;
4766 reset_batch_size(walk
);
4769 __mod_lruvec_state(lruvec
, PGDEMOTE_KSWAPD
+ reclaimer_offset(sc
),
4772 item
= PGSTEAL_KSWAPD
+ reclaimer_offset(sc
);
4773 if (!cgroup_reclaim(sc
))
4774 __count_vm_events(item
, reclaimed
);
4775 count_memcg_events(memcg
, item
, reclaimed
);
4776 __count_vm_events(PGSTEAL_ANON
+ type
, reclaimed
);
4778 spin_unlock_irq(&lruvec
->lru_lock
);
4780 list_splice_init(&clean
, &list
);
4782 if (!list_empty(&list
)) {
4790 static bool should_run_aging(struct lruvec
*lruvec
, unsigned long max_seq
,
4791 int swappiness
, unsigned long *nr_to_scan
)
4793 int gen
, type
, zone
;
4794 unsigned long size
= 0;
4795 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4796 DEFINE_MIN_SEQ(lruvec
);
4799 /* have to run aging, since eviction is not possible anymore */
4800 if (evictable_min_seq(min_seq
, swappiness
) + MIN_NR_GENS
> max_seq
)
4803 for_each_evictable_type(type
, swappiness
) {
4806 for (seq
= min_seq
[type
]; seq
<= max_seq
; seq
++) {
4807 gen
= lru_gen_from_seq(seq
);
4809 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++)
4810 size
+= max(READ_ONCE(lrugen
->nr_pages
[gen
][type
][zone
]), 0L);
4815 /* better to run aging even though eviction is still possible */
4816 return evictable_min_seq(min_seq
, swappiness
) + MIN_NR_GENS
== max_seq
;
4820 * For future optimizations:
4821 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4824 static long get_nr_to_scan(struct lruvec
*lruvec
, struct scan_control
*sc
, int swappiness
)
4827 unsigned long nr_to_scan
;
4828 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4829 DEFINE_MAX_SEQ(lruvec
);
4831 if (mem_cgroup_below_min(sc
->target_mem_cgroup
, memcg
))
4834 success
= should_run_aging(lruvec
, max_seq
, swappiness
, &nr_to_scan
);
4836 /* try to scrape all its memory if this memcg was deleted */
4837 if (nr_to_scan
&& !mem_cgroup_online(memcg
))
4840 /* try to get away with not aging at the default priority */
4841 if (!success
|| sc
->priority
== DEF_PRIORITY
)
4842 return nr_to_scan
>> sc
->priority
;
4844 /* stop scanning this lruvec as it's low on cold folios */
4845 return try_to_inc_max_seq(lruvec
, max_seq
, swappiness
, false) ? -1 : 0;
4848 static bool should_abort_scan(struct lruvec
*lruvec
, struct scan_control
*sc
)
4851 enum zone_watermarks mark
;
4853 /* don't abort memcg reclaim to ensure fairness */
4854 if (!root_reclaim(sc
))
4857 if (sc
->nr_reclaimed
>= max(sc
->nr_to_reclaim
, compact_gap(sc
->order
)))
4860 /* check the order to exclude compaction-induced reclaim */
4861 if (!current_is_kswapd() || sc
->order
)
4864 mark
= sysctl_numa_balancing_mode
& NUMA_BALANCING_MEMORY_TIERING
?
4865 WMARK_PROMO
: WMARK_HIGH
;
4867 for (i
= 0; i
<= sc
->reclaim_idx
; i
++) {
4868 struct zone
*zone
= lruvec_pgdat(lruvec
)->node_zones
+ i
;
4869 unsigned long size
= wmark_pages(zone
, mark
) + MIN_LRU_BATCH
;
4871 if (managed_zone(zone
) && !zone_watermark_ok(zone
, 0, size
, sc
->reclaim_idx
, 0))
4875 /* kswapd should abort if all eligible zones are safe */
4879 static bool try_to_shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
4882 unsigned long scanned
= 0;
4883 int swappiness
= get_swappiness(lruvec
, sc
);
4888 nr_to_scan
= get_nr_to_scan(lruvec
, sc
, swappiness
);
4889 if (nr_to_scan
<= 0)
4892 delta
= evict_folios(lruvec
, sc
, swappiness
);
4897 if (scanned
>= nr_to_scan
)
4900 if (should_abort_scan(lruvec
, sc
))
4907 * If too many file cache in the coldest generation can't be evicted
4908 * due to being dirty, wake up the flusher.
4910 if (sc
->nr
.unqueued_dirty
&& sc
->nr
.unqueued_dirty
== sc
->nr
.file_taken
)
4911 wakeup_flusher_threads(WB_REASON_VMSCAN
);
4913 /* whether this lruvec should be rotated */
4914 return nr_to_scan
< 0;
4917 static int shrink_one(struct lruvec
*lruvec
, struct scan_control
*sc
)
4920 unsigned long scanned
= sc
->nr_scanned
;
4921 unsigned long reclaimed
= sc
->nr_reclaimed
;
4922 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4923 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
4925 /* lru_gen_age_node() called mem_cgroup_calculate_protection() */
4926 if (mem_cgroup_below_min(NULL
, memcg
))
4927 return MEMCG_LRU_YOUNG
;
4929 if (mem_cgroup_below_low(NULL
, memcg
)) {
4930 /* see the comment on MEMCG_NR_GENS */
4931 if (READ_ONCE(lruvec
->lrugen
.seg
) != MEMCG_LRU_TAIL
)
4932 return MEMCG_LRU_TAIL
;
4934 memcg_memory_event(memcg
, MEMCG_LOW
);
4937 success
= try_to_shrink_lruvec(lruvec
, sc
);
4939 shrink_slab(sc
->gfp_mask
, pgdat
->node_id
, memcg
, sc
->priority
);
4942 vmpressure(sc
->gfp_mask
, memcg
, false, sc
->nr_scanned
- scanned
,
4943 sc
->nr_reclaimed
- reclaimed
);
4945 flush_reclaim_state(sc
);
4947 if (success
&& mem_cgroup_online(memcg
))
4948 return MEMCG_LRU_YOUNG
;
4950 if (!success
&& lruvec_is_sizable(lruvec
, sc
))
4953 /* one retry if offlined or too small */
4954 return READ_ONCE(lruvec
->lrugen
.seg
) != MEMCG_LRU_TAIL
?
4955 MEMCG_LRU_TAIL
: MEMCG_LRU_YOUNG
;
4958 static void shrink_many(struct pglist_data
*pgdat
, struct scan_control
*sc
)
4964 struct lruvec
*lruvec
;
4965 struct lru_gen_folio
*lrugen
;
4966 struct mem_cgroup
*memcg
;
4967 struct hlist_nulls_node
*pos
;
4969 gen
= get_memcg_gen(READ_ONCE(pgdat
->memcg_lru
.seq
));
4970 bin
= first_bin
= get_random_u32_below(MEMCG_NR_BINS
);
4977 hlist_nulls_for_each_entry_rcu(lrugen
, pos
, &pgdat
->memcg_lru
.fifo
[gen
][bin
], list
) {
4979 lru_gen_rotate_memcg(lruvec
, op
);
4983 mem_cgroup_put(memcg
);
4986 if (gen
!= READ_ONCE(lrugen
->gen
))
4989 lruvec
= container_of(lrugen
, struct lruvec
, lrugen
);
4990 memcg
= lruvec_memcg(lruvec
);
4992 if (!mem_cgroup_tryget(memcg
)) {
4993 lru_gen_release_memcg(memcg
);
5000 op
= shrink_one(lruvec
, sc
);
5004 if (should_abort_scan(lruvec
, sc
))
5011 lru_gen_rotate_memcg(lruvec
, op
);
5013 mem_cgroup_put(memcg
);
5015 if (!is_a_nulls(pos
))
5018 /* restart if raced with lru_gen_rotate_memcg() */
5019 if (gen
!= get_nulls_value(pos
))
5022 /* try the rest of the bins of the current generation */
5023 bin
= get_memcg_bin(bin
+ 1);
5024 if (bin
!= first_bin
)
5028 static void lru_gen_shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
5030 struct blk_plug plug
;
5032 VM_WARN_ON_ONCE(root_reclaim(sc
));
5033 VM_WARN_ON_ONCE(!sc
->may_writepage
|| !sc
->may_unmap
);
5037 blk_start_plug(&plug
);
5039 set_mm_walk(NULL
, sc
->proactive
);
5041 if (try_to_shrink_lruvec(lruvec
, sc
))
5042 lru_gen_rotate_memcg(lruvec
, MEMCG_LRU_YOUNG
);
5046 blk_finish_plug(&plug
);
5049 static void lru_gen_shrink_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
5051 struct blk_plug plug
;
5052 unsigned long reclaimed
= sc
->nr_reclaimed
;
5054 VM_WARN_ON_ONCE(!root_reclaim(sc
));
5057 * Unmapped clean folios are already prioritized. Scanning for more of
5058 * them is likely futile and can cause high reclaim latency when there
5059 * is a large number of memcgs.
5061 if (!sc
->may_writepage
|| !sc
->may_unmap
)
5066 blk_start_plug(&plug
);
5068 set_mm_walk(pgdat
, sc
->proactive
);
5070 set_initial_priority(pgdat
, sc
);
5072 if (current_is_kswapd())
5073 sc
->nr_reclaimed
= 0;
5075 if (mem_cgroup_disabled())
5076 shrink_one(&pgdat
->__lruvec
, sc
);
5078 shrink_many(pgdat
, sc
);
5080 if (current_is_kswapd())
5081 sc
->nr_reclaimed
+= reclaimed
;
5085 blk_finish_plug(&plug
);
5087 if (sc
->nr_reclaimed
> reclaimed
)
5088 pgdat
->kswapd_failures
= 0;
5091 /******************************************************************************
5093 ******************************************************************************/
5095 static bool __maybe_unused
state_is_valid(struct lruvec
*lruvec
)
5097 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
5099 if (lrugen
->enabled
) {
5102 for_each_evictable_lru(lru
) {
5103 if (!list_empty(&lruvec
->lists
[lru
]))
5107 int gen
, type
, zone
;
5109 for_each_gen_type_zone(gen
, type
, zone
) {
5110 if (!list_empty(&lrugen
->folios
[gen
][type
][zone
]))
5118 static bool fill_evictable(struct lruvec
*lruvec
)
5121 int remaining
= MAX_LRU_BATCH
;
5123 for_each_evictable_lru(lru
) {
5124 int type
= is_file_lru(lru
);
5125 bool active
= is_active_lru(lru
);
5126 struct list_head
*head
= &lruvec
->lists
[lru
];
5128 while (!list_empty(head
)) {
5130 struct folio
*folio
= lru_to_folio(head
);
5132 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
5133 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
) != active
, folio
);
5134 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
5135 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio
) != -1, folio
);
5137 lruvec_del_folio(lruvec
, folio
);
5138 success
= lru_gen_add_folio(lruvec
, folio
, false);
5139 VM_WARN_ON_ONCE(!success
);
5149 static bool drain_evictable(struct lruvec
*lruvec
)
5151 int gen
, type
, zone
;
5152 int remaining
= MAX_LRU_BATCH
;
5154 for_each_gen_type_zone(gen
, type
, zone
) {
5155 struct list_head
*head
= &lruvec
->lrugen
.folios
[gen
][type
][zone
];
5157 while (!list_empty(head
)) {
5159 struct folio
*folio
= lru_to_folio(head
);
5161 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
5162 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
), folio
);
5163 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
5164 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio
) != zone
, folio
);
5166 success
= lru_gen_del_folio(lruvec
, folio
, false);
5167 VM_WARN_ON_ONCE(!success
);
5168 lruvec_add_folio(lruvec
, folio
);
5178 static void lru_gen_change_state(bool enabled
)
5180 static DEFINE_MUTEX(state_mutex
);
5182 struct mem_cgroup
*memcg
;
5187 mutex_lock(&state_mutex
);
5189 if (enabled
== lru_gen_enabled())
5193 static_branch_enable_cpuslocked(&lru_gen_caps
[LRU_GEN_CORE
]);
5195 static_branch_disable_cpuslocked(&lru_gen_caps
[LRU_GEN_CORE
]);
5197 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
5201 for_each_node(nid
) {
5202 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
5204 spin_lock_irq(&lruvec
->lru_lock
);
5206 VM_WARN_ON_ONCE(!seq_is_valid(lruvec
));
5207 VM_WARN_ON_ONCE(!state_is_valid(lruvec
));
5209 lruvec
->lrugen
.enabled
= enabled
;
5211 while (!(enabled
? fill_evictable(lruvec
) : drain_evictable(lruvec
))) {
5212 spin_unlock_irq(&lruvec
->lru_lock
);
5214 spin_lock_irq(&lruvec
->lru_lock
);
5217 spin_unlock_irq(&lruvec
->lru_lock
);
5221 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)));
5223 mutex_unlock(&state_mutex
);
5229 /******************************************************************************
5231 ******************************************************************************/
5233 static ssize_t
min_ttl_ms_show(struct kobject
*kobj
, struct kobj_attribute
*attr
, char *buf
)
5235 return sysfs_emit(buf
, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl
)));
5238 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5239 static ssize_t
min_ttl_ms_store(struct kobject
*kobj
, struct kobj_attribute
*attr
,
5240 const char *buf
, size_t len
)
5244 if (kstrtouint(buf
, 0, &msecs
))
5247 WRITE_ONCE(lru_gen_min_ttl
, msecs_to_jiffies(msecs
));
5252 static struct kobj_attribute lru_gen_min_ttl_attr
= __ATTR_RW(min_ttl_ms
);
5254 static ssize_t
enabled_show(struct kobject
*kobj
, struct kobj_attribute
*attr
, char *buf
)
5256 unsigned int caps
= 0;
5258 if (get_cap(LRU_GEN_CORE
))
5259 caps
|= BIT(LRU_GEN_CORE
);
5261 if (should_walk_mmu())
5262 caps
|= BIT(LRU_GEN_MM_WALK
);
5264 if (should_clear_pmd_young())
5265 caps
|= BIT(LRU_GEN_NONLEAF_YOUNG
);
5267 return sysfs_emit(buf
, "0x%04x\n", caps
);
5270 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5271 static ssize_t
enabled_store(struct kobject
*kobj
, struct kobj_attribute
*attr
,
5272 const char *buf
, size_t len
)
5277 if (tolower(*buf
) == 'n')
5279 else if (tolower(*buf
) == 'y')
5281 else if (kstrtouint(buf
, 0, &caps
))
5284 for (i
= 0; i
< NR_LRU_GEN_CAPS
; i
++) {
5285 bool enabled
= caps
& BIT(i
);
5287 if (i
== LRU_GEN_CORE
)
5288 lru_gen_change_state(enabled
);
5290 static_branch_enable(&lru_gen_caps
[i
]);
5292 static_branch_disable(&lru_gen_caps
[i
]);
5298 static struct kobj_attribute lru_gen_enabled_attr
= __ATTR_RW(enabled
);
5300 static struct attribute
*lru_gen_attrs
[] = {
5301 &lru_gen_min_ttl_attr
.attr
,
5302 &lru_gen_enabled_attr
.attr
,
5306 static const struct attribute_group lru_gen_attr_group
= {
5308 .attrs
= lru_gen_attrs
,
5311 /******************************************************************************
5313 ******************************************************************************/
5315 static void *lru_gen_seq_start(struct seq_file
*m
, loff_t
*pos
)
5317 struct mem_cgroup
*memcg
;
5318 loff_t nr_to_skip
= *pos
;
5320 m
->private = kvmalloc(PATH_MAX
, GFP_KERNEL
);
5322 return ERR_PTR(-ENOMEM
);
5324 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
5328 for_each_node_state(nid
, N_MEMORY
) {
5330 return get_lruvec(memcg
, nid
);
5332 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)));
5337 static void lru_gen_seq_stop(struct seq_file
*m
, void *v
)
5339 if (!IS_ERR_OR_NULL(v
))
5340 mem_cgroup_iter_break(NULL
, lruvec_memcg(v
));
5346 static void *lru_gen_seq_next(struct seq_file
*m
, void *v
, loff_t
*pos
)
5348 int nid
= lruvec_pgdat(v
)->node_id
;
5349 struct mem_cgroup
*memcg
= lruvec_memcg(v
);
5353 nid
= next_memory_node(nid
);
5354 if (nid
== MAX_NUMNODES
) {
5355 memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
);
5359 nid
= first_memory_node
;
5362 return get_lruvec(memcg
, nid
);
5365 static void lru_gen_seq_show_full(struct seq_file
*m
, struct lruvec
*lruvec
,
5366 unsigned long max_seq
, unsigned long *min_seq
,
5371 int hist
= lru_hist_from_seq(seq
);
5372 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
5373 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
5375 for (tier
= 0; tier
< MAX_NR_TIERS
; tier
++) {
5376 seq_printf(m
, " %10d", tier
);
5377 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
5378 const char *s
= "xxx";
5379 unsigned long n
[3] = {};
5381 if (seq
== max_seq
) {
5383 n
[0] = READ_ONCE(lrugen
->avg_refaulted
[type
][tier
]);
5384 n
[1] = READ_ONCE(lrugen
->avg_total
[type
][tier
]);
5385 } else if (seq
== min_seq
[type
] || NR_HIST_GENS
> 1) {
5387 n
[0] = atomic_long_read(&lrugen
->refaulted
[hist
][type
][tier
]);
5388 n
[1] = atomic_long_read(&lrugen
->evicted
[hist
][type
][tier
]);
5389 n
[2] = READ_ONCE(lrugen
->protected[hist
][type
][tier
]);
5392 for (i
= 0; i
< 3; i
++)
5393 seq_printf(m
, " %10lu%c", n
[i
], s
[i
]);
5402 for (i
= 0; i
< NR_MM_STATS
; i
++) {
5403 const char *s
= "xxxx";
5404 unsigned long n
= 0;
5406 if (seq
== max_seq
&& NR_HIST_GENS
== 1) {
5408 n
= READ_ONCE(mm_state
->stats
[hist
][i
]);
5409 } else if (seq
!= max_seq
&& NR_HIST_GENS
> 1) {
5411 n
= READ_ONCE(mm_state
->stats
[hist
][i
]);
5414 seq_printf(m
, " %10lu%c", n
, s
[i
]);
5419 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5420 static int lru_gen_seq_show(struct seq_file
*m
, void *v
)
5423 bool full
= !debugfs_real_fops(m
->file
)->write
;
5424 struct lruvec
*lruvec
= v
;
5425 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
5426 int nid
= lruvec_pgdat(lruvec
)->node_id
;
5427 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
5428 DEFINE_MAX_SEQ(lruvec
);
5429 DEFINE_MIN_SEQ(lruvec
);
5431 if (nid
== first_memory_node
) {
5432 const char *path
= memcg
? m
->private : "";
5436 cgroup_path(memcg
->css
.cgroup
, m
->private, PATH_MAX
);
5438 seq_printf(m
, "memcg %5hu %s\n", mem_cgroup_id(memcg
), path
);
5441 seq_printf(m
, " node %5d\n", nid
);
5444 seq
= evictable_min_seq(min_seq
, MAX_SWAPPINESS
/ 2);
5445 else if (max_seq
>= MAX_NR_GENS
)
5446 seq
= max_seq
- MAX_NR_GENS
+ 1;
5450 for (; seq
<= max_seq
; seq
++) {
5452 int gen
= lru_gen_from_seq(seq
);
5453 unsigned long birth
= READ_ONCE(lruvec
->lrugen
.timestamps
[gen
]);
5455 seq_printf(m
, " %10lu %10u", seq
, jiffies_to_msecs(jiffies
- birth
));
5457 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
5458 unsigned long size
= 0;
5459 char mark
= full
&& seq
< min_seq
[type
] ? 'x' : ' ';
5461 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++)
5462 size
+= max(READ_ONCE(lrugen
->nr_pages
[gen
][type
][zone
]), 0L);
5464 seq_printf(m
, " %10lu%c", size
, mark
);
5470 lru_gen_seq_show_full(m
, lruvec
, max_seq
, min_seq
, seq
);
5476 static const struct seq_operations lru_gen_seq_ops
= {
5477 .start
= lru_gen_seq_start
,
5478 .stop
= lru_gen_seq_stop
,
5479 .next
= lru_gen_seq_next
,
5480 .show
= lru_gen_seq_show
,
5483 static int run_aging(struct lruvec
*lruvec
, unsigned long seq
,
5484 int swappiness
, bool force_scan
)
5486 DEFINE_MAX_SEQ(lruvec
);
5491 return try_to_inc_max_seq(lruvec
, max_seq
, swappiness
, force_scan
) ? 0 : -EEXIST
;
5494 static int run_eviction(struct lruvec
*lruvec
, unsigned long seq
, struct scan_control
*sc
,
5495 int swappiness
, unsigned long nr_to_reclaim
)
5497 DEFINE_MAX_SEQ(lruvec
);
5499 if (seq
+ MIN_NR_GENS
> max_seq
)
5502 sc
->nr_reclaimed
= 0;
5504 while (!signal_pending(current
)) {
5505 DEFINE_MIN_SEQ(lruvec
);
5507 if (seq
< evictable_min_seq(min_seq
, swappiness
))
5510 if (sc
->nr_reclaimed
>= nr_to_reclaim
)
5513 if (!evict_folios(lruvec
, sc
, swappiness
))
5522 static int run_cmd(char cmd
, int memcg_id
, int nid
, unsigned long seq
,
5523 struct scan_control
*sc
, int swappiness
, unsigned long opt
)
5525 struct lruvec
*lruvec
;
5527 struct mem_cgroup
*memcg
= NULL
;
5529 if (nid
< 0 || nid
>= MAX_NUMNODES
|| !node_state(nid
, N_MEMORY
))
5532 if (!mem_cgroup_disabled()) {
5535 memcg
= mem_cgroup_from_id(memcg_id
);
5536 if (!mem_cgroup_tryget(memcg
))
5545 if (memcg_id
!= mem_cgroup_id(memcg
))
5548 lruvec
= get_lruvec(memcg
, nid
);
5550 if (swappiness
< MIN_SWAPPINESS
)
5551 swappiness
= get_swappiness(lruvec
, sc
);
5552 else if (swappiness
> SWAPPINESS_ANON_ONLY
)
5557 err
= run_aging(lruvec
, seq
, swappiness
, opt
);
5560 err
= run_eviction(lruvec
, seq
, sc
, swappiness
, opt
);
5564 mem_cgroup_put(memcg
);
5569 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5570 static ssize_t
lru_gen_seq_write(struct file
*file
, const char __user
*src
,
5571 size_t len
, loff_t
*pos
)
5576 struct blk_plug plug
;
5578 struct scan_control sc
= {
5579 .may_writepage
= true,
5582 .reclaim_idx
= MAX_NR_ZONES
- 1,
5583 .gfp_mask
= GFP_KERNEL
,
5586 buf
= kvmalloc(len
+ 1, GFP_KERNEL
);
5590 if (copy_from_user(buf
, src
, len
)) {
5595 set_task_reclaim_state(current
, &sc
.reclaim_state
);
5596 flags
= memalloc_noreclaim_save();
5597 blk_start_plug(&plug
);
5598 if (!set_mm_walk(NULL
, true)) {
5606 while ((cur
= strsep(&next
, ",;\n"))) {
5609 char cmd
, swap_string
[5];
5610 unsigned int memcg_id
;
5613 unsigned int swappiness
;
5614 unsigned long opt
= -1;
5616 cur
= skip_spaces(cur
);
5620 n
= sscanf(cur
, "%c %u %u %lu %n %4s %n %lu %n", &cmd
, &memcg_id
, &nid
,
5621 &seq
, &end
, swap_string
, &end
, &opt
, &end
);
5622 if (n
< 4 || cur
[end
]) {
5629 } else if (!strcmp("max", swap_string
)) {
5630 /* set by userspace for anonymous memory only */
5631 swappiness
= SWAPPINESS_ANON_ONLY
;
5633 err
= kstrtouint(swap_string
, 0, &swappiness
);
5638 err
= run_cmd(cmd
, memcg_id
, nid
, seq
, &sc
, swappiness
, opt
);
5644 blk_finish_plug(&plug
);
5645 memalloc_noreclaim_restore(flags
);
5646 set_task_reclaim_state(current
, NULL
);
5653 static int lru_gen_seq_open(struct inode
*inode
, struct file
*file
)
5655 return seq_open(file
, &lru_gen_seq_ops
);
5658 static const struct file_operations lru_gen_rw_fops
= {
5659 .open
= lru_gen_seq_open
,
5661 .write
= lru_gen_seq_write
,
5662 .llseek
= seq_lseek
,
5663 .release
= seq_release
,
5666 static const struct file_operations lru_gen_ro_fops
= {
5667 .open
= lru_gen_seq_open
,
5669 .llseek
= seq_lseek
,
5670 .release
= seq_release
,
5673 /******************************************************************************
5675 ******************************************************************************/
5677 void lru_gen_init_pgdat(struct pglist_data
*pgdat
)
5681 spin_lock_init(&pgdat
->memcg_lru
.lock
);
5683 for (i
= 0; i
< MEMCG_NR_GENS
; i
++) {
5684 for (j
= 0; j
< MEMCG_NR_BINS
; j
++)
5685 INIT_HLIST_NULLS_HEAD(&pgdat
->memcg_lru
.fifo
[i
][j
], i
);
5689 void lru_gen_init_lruvec(struct lruvec
*lruvec
)
5692 int gen
, type
, zone
;
5693 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
5694 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
5696 lrugen
->max_seq
= MIN_NR_GENS
+ 1;
5697 lrugen
->enabled
= lru_gen_enabled();
5699 for (i
= 0; i
<= MIN_NR_GENS
+ 1; i
++)
5700 lrugen
->timestamps
[i
] = jiffies
;
5702 for_each_gen_type_zone(gen
, type
, zone
)
5703 INIT_LIST_HEAD(&lrugen
->folios
[gen
][type
][zone
]);
5706 mm_state
->seq
= MIN_NR_GENS
;
5711 void lru_gen_init_memcg(struct mem_cgroup
*memcg
)
5713 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
5718 INIT_LIST_HEAD(&mm_list
->fifo
);
5719 spin_lock_init(&mm_list
->lock
);
5722 void lru_gen_exit_memcg(struct mem_cgroup
*memcg
)
5726 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
5728 VM_WARN_ON_ONCE(mm_list
&& !list_empty(&mm_list
->fifo
));
5730 for_each_node(nid
) {
5731 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
5732 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
5734 VM_WARN_ON_ONCE(memchr_inv(lruvec
->lrugen
.nr_pages
, 0,
5735 sizeof(lruvec
->lrugen
.nr_pages
)));
5737 lruvec
->lrugen
.list
.next
= LIST_POISON1
;
5742 for (i
= 0; i
< NR_BLOOM_FILTERS
; i
++) {
5743 bitmap_free(mm_state
->filters
[i
]);
5744 mm_state
->filters
[i
] = NULL
;
5749 #endif /* CONFIG_MEMCG */
5751 static int __init
init_lru_gen(void)
5753 BUILD_BUG_ON(MIN_NR_GENS
+ 1 >= MAX_NR_GENS
);
5754 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH
) <= MAX_NR_GENS
);
5756 if (sysfs_create_group(mm_kobj
, &lru_gen_attr_group
))
5757 pr_err("lru_gen: failed to create sysfs group\n");
5759 debugfs_create_file("lru_gen", 0644, NULL
, NULL
, &lru_gen_rw_fops
);
5760 debugfs_create_file("lru_gen_full", 0444, NULL
, NULL
, &lru_gen_ro_fops
);
5764 late_initcall(init_lru_gen
);
5766 #else /* !CONFIG_LRU_GEN */
5768 static void lru_gen_age_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
5773 static void lru_gen_shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
5778 static void lru_gen_shrink_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
5783 #endif /* CONFIG_LRU_GEN */
5785 static void shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
5787 unsigned long nr
[NR_LRU_LISTS
];
5788 unsigned long targets
[NR_LRU_LISTS
];
5789 unsigned long nr_to_scan
;
5791 unsigned long nr_reclaimed
= 0;
5792 unsigned long nr_to_reclaim
= sc
->nr_to_reclaim
;
5793 bool proportional_reclaim
;
5794 struct blk_plug plug
;
5796 if (lru_gen_enabled() && !root_reclaim(sc
)) {
5797 lru_gen_shrink_lruvec(lruvec
, sc
);
5801 get_scan_count(lruvec
, sc
, nr
);
5803 /* Record the original scan target for proportional adjustments later */
5804 memcpy(targets
, nr
, sizeof(nr
));
5807 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5808 * event that can occur when there is little memory pressure e.g.
5809 * multiple streaming readers/writers. Hence, we do not abort scanning
5810 * when the requested number of pages are reclaimed when scanning at
5811 * DEF_PRIORITY on the assumption that the fact we are direct
5812 * reclaiming implies that kswapd is not keeping up and it is best to
5813 * do a batch of work at once. For memcg reclaim one check is made to
5814 * abort proportional reclaim if either the file or anon lru has already
5815 * dropped to zero at the first pass.
5817 proportional_reclaim
= (!cgroup_reclaim(sc
) && !current_is_kswapd() &&
5818 sc
->priority
== DEF_PRIORITY
);
5820 blk_start_plug(&plug
);
5821 while (nr
[LRU_INACTIVE_ANON
] || nr
[LRU_ACTIVE_FILE
] ||
5822 nr
[LRU_INACTIVE_FILE
]) {
5823 unsigned long nr_anon
, nr_file
, percentage
;
5824 unsigned long nr_scanned
;
5826 for_each_evictable_lru(lru
) {
5828 nr_to_scan
= min(nr
[lru
], SWAP_CLUSTER_MAX
);
5829 nr
[lru
] -= nr_to_scan
;
5831 nr_reclaimed
+= shrink_list(lru
, nr_to_scan
,
5838 if (nr_reclaimed
< nr_to_reclaim
|| proportional_reclaim
)
5842 * For kswapd and memcg, reclaim at least the number of pages
5843 * requested. Ensure that the anon and file LRUs are scanned
5844 * proportionally what was requested by get_scan_count(). We
5845 * stop reclaiming one LRU and reduce the amount scanning
5846 * proportional to the original scan target.
5848 nr_file
= nr
[LRU_INACTIVE_FILE
] + nr
[LRU_ACTIVE_FILE
];
5849 nr_anon
= nr
[LRU_INACTIVE_ANON
] + nr
[LRU_ACTIVE_ANON
];
5852 * It's just vindictive to attack the larger once the smaller
5853 * has gone to zero. And given the way we stop scanning the
5854 * smaller below, this makes sure that we only make one nudge
5855 * towards proportionality once we've got nr_to_reclaim.
5857 if (!nr_file
|| !nr_anon
)
5860 if (nr_file
> nr_anon
) {
5861 unsigned long scan_target
= targets
[LRU_INACTIVE_ANON
] +
5862 targets
[LRU_ACTIVE_ANON
] + 1;
5864 percentage
= nr_anon
* 100 / scan_target
;
5866 unsigned long scan_target
= targets
[LRU_INACTIVE_FILE
] +
5867 targets
[LRU_ACTIVE_FILE
] + 1;
5869 percentage
= nr_file
* 100 / scan_target
;
5872 /* Stop scanning the smaller of the LRU */
5874 nr
[lru
+ LRU_ACTIVE
] = 0;
5877 * Recalculate the other LRU scan count based on its original
5878 * scan target and the percentage scanning already complete
5880 lru
= (lru
== LRU_FILE
) ? LRU_BASE
: LRU_FILE
;
5881 nr_scanned
= targets
[lru
] - nr
[lru
];
5882 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
5883 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
5886 nr_scanned
= targets
[lru
] - nr
[lru
];
5887 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
5888 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
5890 blk_finish_plug(&plug
);
5891 sc
->nr_reclaimed
+= nr_reclaimed
;
5894 * Even if we did not try to evict anon pages at all, we want to
5895 * rebalance the anon lru active/inactive ratio.
5897 if (can_age_anon_pages(lruvec
, sc
) &&
5898 inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
5899 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
5900 sc
, LRU_ACTIVE_ANON
);
5903 /* Use reclaim/compaction for costly allocs or under memory pressure */
5904 static bool in_reclaim_compaction(struct scan_control
*sc
)
5906 if (gfp_compaction_allowed(sc
->gfp_mask
) && sc
->order
&&
5907 (sc
->order
> PAGE_ALLOC_COSTLY_ORDER
||
5908 sc
->priority
< DEF_PRIORITY
- 2))
5915 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5916 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5917 * true if more pages should be reclaimed such that when the page allocator
5918 * calls try_to_compact_pages() that it will have enough free pages to succeed.
5919 * It will give up earlier than that if there is difficulty reclaiming pages.
5921 static inline bool should_continue_reclaim(struct pglist_data
*pgdat
,
5922 unsigned long nr_reclaimed
,
5923 struct scan_control
*sc
)
5925 unsigned long pages_for_compaction
;
5926 unsigned long inactive_lru_pages
;
5930 /* If not in reclaim/compaction mode, stop */
5931 if (!in_reclaim_compaction(sc
))
5935 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5936 * number of pages that were scanned. This will return to the caller
5937 * with the risk reclaim/compaction and the resulting allocation attempt
5938 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5939 * allocations through requiring that the full LRU list has been scanned
5940 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5941 * scan, but that approximation was wrong, and there were corner cases
5942 * where always a non-zero amount of pages were scanned.
5947 /* If compaction would go ahead or the allocation would succeed, stop */
5948 for_each_managed_zone_pgdat(zone
, pgdat
, z
, sc
->reclaim_idx
) {
5949 unsigned long watermark
= min_wmark_pages(zone
);
5951 /* Allocation can already succeed, nothing to do */
5952 if (zone_watermark_ok(zone
, sc
->order
, watermark
,
5953 sc
->reclaim_idx
, 0))
5956 if (compaction_suitable(zone
, sc
->order
, watermark
,
5962 * If we have not reclaimed enough pages for compaction and the
5963 * inactive lists are large enough, continue reclaiming
5965 pages_for_compaction
= compact_gap(sc
->order
);
5966 inactive_lru_pages
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
5967 if (can_reclaim_anon_pages(NULL
, pgdat
->node_id
, sc
))
5968 inactive_lru_pages
+= node_page_state(pgdat
, NR_INACTIVE_ANON
);
5970 return inactive_lru_pages
> pages_for_compaction
;
5973 static void shrink_node_memcgs(pg_data_t
*pgdat
, struct scan_control
*sc
)
5975 struct mem_cgroup
*target_memcg
= sc
->target_mem_cgroup
;
5976 struct mem_cgroup_reclaim_cookie reclaim
= {
5979 struct mem_cgroup_reclaim_cookie
*partial
= &reclaim
;
5980 struct mem_cgroup
*memcg
;
5983 * In most cases, direct reclaimers can do partial walks
5984 * through the cgroup tree, using an iterator state that
5985 * persists across invocations. This strikes a balance between
5986 * fairness and allocation latency.
5988 * For kswapd, reliable forward progress is more important
5989 * than a quick return to idle. Always do full walks.
5991 if (current_is_kswapd() || sc
->memcg_full_walk
)
5994 memcg
= mem_cgroup_iter(target_memcg
, NULL
, partial
);
5996 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
5997 unsigned long reclaimed
;
5998 unsigned long scanned
;
6001 * This loop can become CPU-bound when target memcgs
6002 * aren't eligible for reclaim - either because they
6003 * don't have any reclaimable pages, or because their
6004 * memory is explicitly protected. Avoid soft lockups.
6008 mem_cgroup_calculate_protection(target_memcg
, memcg
);
6010 if (mem_cgroup_below_min(target_memcg
, memcg
)) {
6013 * If there is no reclaimable memory, OOM.
6016 } else if (mem_cgroup_below_low(target_memcg
, memcg
)) {
6019 * Respect the protection only as long as
6020 * there is an unprotected supply
6021 * of reclaimable memory from other cgroups.
6023 if (!sc
->memcg_low_reclaim
) {
6024 sc
->memcg_low_skipped
= 1;
6027 memcg_memory_event(memcg
, MEMCG_LOW
);
6030 reclaimed
= sc
->nr_reclaimed
;
6031 scanned
= sc
->nr_scanned
;
6033 shrink_lruvec(lruvec
, sc
);
6035 shrink_slab(sc
->gfp_mask
, pgdat
->node_id
, memcg
,
6038 /* Record the group's reclaim efficiency */
6040 vmpressure(sc
->gfp_mask
, memcg
, false,
6041 sc
->nr_scanned
- scanned
,
6042 sc
->nr_reclaimed
- reclaimed
);
6044 /* If partial walks are allowed, bail once goal is reached */
6045 if (partial
&& sc
->nr_reclaimed
>= sc
->nr_to_reclaim
) {
6046 mem_cgroup_iter_break(target_memcg
, memcg
);
6049 } while ((memcg
= mem_cgroup_iter(target_memcg
, memcg
, partial
)));
6052 static void shrink_node(pg_data_t
*pgdat
, struct scan_control
*sc
)
6054 unsigned long nr_reclaimed
, nr_scanned
, nr_node_reclaimed
;
6055 struct lruvec
*target_lruvec
;
6056 bool reclaimable
= false;
6058 if (lru_gen_enabled() && root_reclaim(sc
)) {
6059 memset(&sc
->nr
, 0, sizeof(sc
->nr
));
6060 lru_gen_shrink_node(pgdat
, sc
);
6064 target_lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
, pgdat
);
6067 memset(&sc
->nr
, 0, sizeof(sc
->nr
));
6069 nr_reclaimed
= sc
->nr_reclaimed
;
6070 nr_scanned
= sc
->nr_scanned
;
6072 prepare_scan_control(pgdat
, sc
);
6074 shrink_node_memcgs(pgdat
, sc
);
6076 flush_reclaim_state(sc
);
6078 nr_node_reclaimed
= sc
->nr_reclaimed
- nr_reclaimed
;
6080 /* Record the subtree's reclaim efficiency */
6082 vmpressure(sc
->gfp_mask
, sc
->target_mem_cgroup
, true,
6083 sc
->nr_scanned
- nr_scanned
, nr_node_reclaimed
);
6085 if (nr_node_reclaimed
)
6088 if (current_is_kswapd()) {
6090 * If reclaim is isolating dirty pages under writeback,
6091 * it implies that the long-lived page allocation rate
6092 * is exceeding the page laundering rate. Either the
6093 * global limits are not being effective at throttling
6094 * processes due to the page distribution throughout
6095 * zones or there is heavy usage of a slow backing
6096 * device. The only option is to throttle from reclaim
6097 * context which is not ideal as there is no guarantee
6098 * the dirtying process is throttled in the same way
6099 * balance_dirty_pages() manages.
6101 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6102 * count the number of pages under pages flagged for
6103 * immediate reclaim and stall if any are encountered
6104 * in the nr_immediate check below.
6106 if (sc
->nr
.writeback
&& sc
->nr
.writeback
== sc
->nr
.taken
)
6107 set_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
6109 /* Allow kswapd to start writing pages during reclaim.*/
6110 if (sc
->nr
.unqueued_dirty
&&
6111 sc
->nr
.unqueued_dirty
== sc
->nr
.file_taken
)
6112 set_bit(PGDAT_DIRTY
, &pgdat
->flags
);
6115 * If kswapd scans pages marked for immediate
6116 * reclaim and under writeback (nr_immediate), it
6117 * implies that pages are cycling through the LRU
6118 * faster than they are written so forcibly stall
6119 * until some pages complete writeback.
6121 if (sc
->nr
.immediate
)
6122 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_WRITEBACK
);
6126 * Tag a node/memcg as congested if all the dirty pages were marked
6127 * for writeback and immediate reclaim (counted in nr.congested).
6129 * Legacy memcg will stall in page writeback so avoid forcibly
6130 * stalling in reclaim_throttle().
6132 if (sc
->nr
.dirty
&& sc
->nr
.dirty
== sc
->nr
.congested
) {
6133 if (cgroup_reclaim(sc
) && writeback_throttling_sane(sc
))
6134 set_bit(LRUVEC_CGROUP_CONGESTED
, &target_lruvec
->flags
);
6136 if (current_is_kswapd())
6137 set_bit(LRUVEC_NODE_CONGESTED
, &target_lruvec
->flags
);
6141 * Stall direct reclaim for IO completions if the lruvec is
6142 * node is congested. Allow kswapd to continue until it
6143 * starts encountering unqueued dirty pages or cycling through
6144 * the LRU too quickly.
6146 if (!current_is_kswapd() && current_may_throttle() &&
6147 !sc
->hibernation_mode
&&
6148 (test_bit(LRUVEC_CGROUP_CONGESTED
, &target_lruvec
->flags
) ||
6149 test_bit(LRUVEC_NODE_CONGESTED
, &target_lruvec
->flags
)))
6150 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_CONGESTED
);
6152 if (should_continue_reclaim(pgdat
, nr_node_reclaimed
, sc
))
6156 * Kswapd gives up on balancing particular nodes after too
6157 * many failures to reclaim anything from them and goes to
6158 * sleep. On reclaim progress, reset the failure counter. A
6159 * successful direct reclaim run will revive a dormant kswapd.
6162 pgdat
->kswapd_failures
= 0;
6163 else if (sc
->cache_trim_mode
)
6164 sc
->cache_trim_mode_failed
= 1;
6168 * Returns true if compaction should go ahead for a costly-order request, or
6169 * the allocation would already succeed without compaction. Return false if we
6170 * should reclaim first.
6172 static inline bool compaction_ready(struct zone
*zone
, struct scan_control
*sc
)
6174 unsigned long watermark
;
6176 if (!gfp_compaction_allowed(sc
->gfp_mask
))
6179 /* Allocation can already succeed, nothing to do */
6180 if (zone_watermark_ok(zone
, sc
->order
, min_wmark_pages(zone
),
6181 sc
->reclaim_idx
, 0))
6185 * Direct reclaim usually targets the min watermark, but compaction
6186 * takes time to run and there are potentially other callers using the
6187 * pages just freed. So target a higher buffer to give compaction a
6188 * reasonable chance of completing and allocating the pages.
6190 * Note that we won't actually reclaim the whole buffer in one attempt
6191 * as the target watermark in should_continue_reclaim() is lower. But if
6192 * we are already above the high+gap watermark, don't reclaim at all.
6194 watermark
= high_wmark_pages(zone
);
6195 if (compaction_suitable(zone
, sc
->order
, watermark
, sc
->reclaim_idx
))
6201 static void consider_reclaim_throttle(pg_data_t
*pgdat
, struct scan_control
*sc
)
6204 * If reclaim is making progress greater than 12% efficiency then
6205 * wake all the NOPROGRESS throttled tasks.
6207 if (sc
->nr_reclaimed
> (sc
->nr_scanned
>> 3)) {
6208 wait_queue_head_t
*wqh
;
6210 wqh
= &pgdat
->reclaim_wait
[VMSCAN_THROTTLE_NOPROGRESS
];
6211 if (waitqueue_active(wqh
))
6218 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6219 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6220 * under writeback and marked for immediate reclaim at the tail of the
6223 if (current_is_kswapd() || cgroup_reclaim(sc
))
6226 /* Throttle if making no progress at high prioities. */
6227 if (sc
->priority
== 1 && !sc
->nr_reclaimed
)
6228 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_NOPROGRESS
);
6232 * This is the direct reclaim path, for page-allocating processes. We only
6233 * try to reclaim pages from zones which will satisfy the caller's allocation
6236 * If a zone is deemed to be full of pinned pages then just give it a light
6237 * scan then give up on it.
6239 static void shrink_zones(struct zonelist
*zonelist
, struct scan_control
*sc
)
6243 unsigned long nr_soft_reclaimed
;
6244 unsigned long nr_soft_scanned
;
6246 pg_data_t
*last_pgdat
= NULL
;
6247 pg_data_t
*first_pgdat
= NULL
;
6250 * If the number of buffer_heads in the machine exceeds the maximum
6251 * allowed level, force direct reclaim to scan the highmem zone as
6252 * highmem pages could be pinning lowmem pages storing buffer_heads
6254 orig_mask
= sc
->gfp_mask
;
6255 if (buffer_heads_over_limit
) {
6256 sc
->gfp_mask
|= __GFP_HIGHMEM
;
6257 sc
->reclaim_idx
= gfp_zone(sc
->gfp_mask
);
6260 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
6261 sc
->reclaim_idx
, sc
->nodemask
) {
6263 * Take care memory controller reclaiming has small influence
6266 if (!cgroup_reclaim(sc
)) {
6267 if (!cpuset_zone_allowed(zone
,
6268 GFP_KERNEL
| __GFP_HARDWALL
))
6272 * If we already have plenty of memory free for
6273 * compaction in this zone, don't free any more.
6274 * Even though compaction is invoked for any
6275 * non-zero order, only frequent costly order
6276 * reclamation is disruptive enough to become a
6277 * noticeable problem, like transparent huge
6280 if (IS_ENABLED(CONFIG_COMPACTION
) &&
6281 sc
->order
> PAGE_ALLOC_COSTLY_ORDER
&&
6282 compaction_ready(zone
, sc
)) {
6283 sc
->compaction_ready
= true;
6288 * Shrink each node in the zonelist once. If the
6289 * zonelist is ordered by zone (not the default) then a
6290 * node may be shrunk multiple times but in that case
6291 * the user prefers lower zones being preserved.
6293 if (zone
->zone_pgdat
== last_pgdat
)
6297 * This steals pages from memory cgroups over softlimit
6298 * and returns the number of reclaimed pages and
6299 * scanned pages. This works for global memory pressure
6300 * and balancing, not for a memcg's limit.
6302 nr_soft_scanned
= 0;
6303 nr_soft_reclaimed
= memcg1_soft_limit_reclaim(zone
->zone_pgdat
,
6304 sc
->order
, sc
->gfp_mask
,
6306 sc
->nr_reclaimed
+= nr_soft_reclaimed
;
6307 sc
->nr_scanned
+= nr_soft_scanned
;
6308 /* need some check for avoid more shrink_zone() */
6312 first_pgdat
= zone
->zone_pgdat
;
6314 /* See comment about same check for global reclaim above */
6315 if (zone
->zone_pgdat
== last_pgdat
)
6317 last_pgdat
= zone
->zone_pgdat
;
6318 shrink_node(zone
->zone_pgdat
, sc
);
6322 consider_reclaim_throttle(first_pgdat
, sc
);
6325 * Restore to original mask to avoid the impact on the caller if we
6326 * promoted it to __GFP_HIGHMEM.
6328 sc
->gfp_mask
= orig_mask
;
6331 static void snapshot_refaults(struct mem_cgroup
*target_memcg
, pg_data_t
*pgdat
)
6333 struct lruvec
*target_lruvec
;
6334 unsigned long refaults
;
6336 if (lru_gen_enabled())
6339 target_lruvec
= mem_cgroup_lruvec(target_memcg
, pgdat
);
6340 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_ANON
);
6341 target_lruvec
->refaults
[WORKINGSET_ANON
] = refaults
;
6342 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_FILE
);
6343 target_lruvec
->refaults
[WORKINGSET_FILE
] = refaults
;
6347 * This is the main entry point to direct page reclaim.
6349 * If a full scan of the inactive list fails to free enough memory then we
6350 * are "out of memory" and something needs to be killed.
6352 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6353 * high - the zone may be full of dirty or under-writeback pages, which this
6354 * caller can't do much about. We kick the writeback threads and take explicit
6355 * naps in the hope that some of these pages can be written. But if the
6356 * allocating task holds filesystem locks which prevent writeout this might not
6357 * work, and the allocation attempt will fail.
6359 * returns: 0, if no pages reclaimed
6360 * else, the number of pages reclaimed
6362 static unsigned long do_try_to_free_pages(struct zonelist
*zonelist
,
6363 struct scan_control
*sc
)
6365 int initial_priority
= sc
->priority
;
6366 pg_data_t
*last_pgdat
;
6370 delayacct_freepages_start();
6372 if (!cgroup_reclaim(sc
))
6373 __count_zid_vm_events(ALLOCSTALL
, sc
->reclaim_idx
, 1);
6377 vmpressure_prio(sc
->gfp_mask
, sc
->target_mem_cgroup
,
6380 shrink_zones(zonelist
, sc
);
6382 if (sc
->nr_reclaimed
>= sc
->nr_to_reclaim
)
6385 if (sc
->compaction_ready
)
6389 * If we're getting trouble reclaiming, start doing
6390 * writepage even in laptop mode.
6392 if (sc
->priority
< DEF_PRIORITY
- 2)
6393 sc
->may_writepage
= 1;
6394 } while (--sc
->priority
>= 0);
6397 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
, sc
->reclaim_idx
,
6399 if (zone
->zone_pgdat
== last_pgdat
)
6401 last_pgdat
= zone
->zone_pgdat
;
6403 snapshot_refaults(sc
->target_mem_cgroup
, zone
->zone_pgdat
);
6405 if (cgroup_reclaim(sc
)) {
6406 struct lruvec
*lruvec
;
6408 lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
,
6410 clear_bit(LRUVEC_CGROUP_CONGESTED
, &lruvec
->flags
);
6414 delayacct_freepages_end();
6416 if (sc
->nr_reclaimed
)
6417 return sc
->nr_reclaimed
;
6419 /* Aborted reclaim to try compaction? don't OOM, then */
6420 if (sc
->compaction_ready
)
6424 * In most cases, direct reclaimers can do partial walks
6425 * through the cgroup tree to meet the reclaim goal while
6426 * keeping latency low. Since the iterator state is shared
6427 * among all direct reclaim invocations (to retain fairness
6428 * among cgroups), though, high concurrency can result in
6429 * individual threads not seeing enough cgroups to make
6430 * meaningful forward progress. Avoid false OOMs in this case.
6432 if (!sc
->memcg_full_walk
) {
6433 sc
->priority
= initial_priority
;
6434 sc
->memcg_full_walk
= 1;
6439 * We make inactive:active ratio decisions based on the node's
6440 * composition of memory, but a restrictive reclaim_idx or a
6441 * memory.low cgroup setting can exempt large amounts of
6442 * memory from reclaim. Neither of which are very common, so
6443 * instead of doing costly eligibility calculations of the
6444 * entire cgroup subtree up front, we assume the estimates are
6445 * good, and retry with forcible deactivation if that fails.
6447 if (sc
->skipped_deactivate
) {
6448 sc
->priority
= initial_priority
;
6449 sc
->force_deactivate
= 1;
6450 sc
->skipped_deactivate
= 0;
6454 /* Untapped cgroup reserves? Don't OOM, retry. */
6455 if (sc
->memcg_low_skipped
) {
6456 sc
->priority
= initial_priority
;
6457 sc
->force_deactivate
= 0;
6458 sc
->memcg_low_reclaim
= 1;
6459 sc
->memcg_low_skipped
= 0;
6466 static bool allow_direct_reclaim(pg_data_t
*pgdat
)
6469 unsigned long pfmemalloc_reserve
= 0;
6470 unsigned long free_pages
= 0;
6474 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
6477 for_each_managed_zone_pgdat(zone
, pgdat
, i
, ZONE_NORMAL
) {
6478 if (!zone_reclaimable_pages(zone
))
6481 pfmemalloc_reserve
+= min_wmark_pages(zone
);
6482 free_pages
+= zone_page_state_snapshot(zone
, NR_FREE_PAGES
);
6485 /* If there are no reserves (unexpected config) then do not throttle */
6486 if (!pfmemalloc_reserve
)
6489 wmark_ok
= free_pages
> pfmemalloc_reserve
/ 2;
6491 /* kswapd must be awake if processes are being throttled */
6492 if (!wmark_ok
&& waitqueue_active(&pgdat
->kswapd_wait
)) {
6493 if (READ_ONCE(pgdat
->kswapd_highest_zoneidx
) > ZONE_NORMAL
)
6494 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, ZONE_NORMAL
);
6496 wake_up_interruptible(&pgdat
->kswapd_wait
);
6503 * Throttle direct reclaimers if backing storage is backed by the network
6504 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6505 * depleted. kswapd will continue to make progress and wake the processes
6506 * when the low watermark is reached.
6508 * Returns true if a fatal signal was delivered during throttling. If this
6509 * happens, the page allocator should not consider triggering the OOM killer.
6511 static bool throttle_direct_reclaim(gfp_t gfp_mask
, struct zonelist
*zonelist
,
6512 nodemask_t
*nodemask
)
6516 pg_data_t
*pgdat
= NULL
;
6519 * Kernel threads should not be throttled as they may be indirectly
6520 * responsible for cleaning pages necessary for reclaim to make forward
6521 * progress. kjournald for example may enter direct reclaim while
6522 * committing a transaction where throttling it could forcing other
6523 * processes to block on log_wait_commit().
6525 if (current
->flags
& PF_KTHREAD
)
6529 * If a fatal signal is pending, this process should not throttle.
6530 * It should return quickly so it can exit and free its memory
6532 if (fatal_signal_pending(current
))
6536 * Check if the pfmemalloc reserves are ok by finding the first node
6537 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6538 * GFP_KERNEL will be required for allocating network buffers when
6539 * swapping over the network so ZONE_HIGHMEM is unusable.
6541 * Throttling is based on the first usable node and throttled processes
6542 * wait on a queue until kswapd makes progress and wakes them. There
6543 * is an affinity then between processes waking up and where reclaim
6544 * progress has been made assuming the process wakes on the same node.
6545 * More importantly, processes running on remote nodes will not compete
6546 * for remote pfmemalloc reserves and processes on different nodes
6547 * should make reasonable progress.
6549 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
6550 gfp_zone(gfp_mask
), nodemask
) {
6551 if (zone_idx(zone
) > ZONE_NORMAL
)
6554 /* Throttle based on the first usable node */
6555 pgdat
= zone
->zone_pgdat
;
6556 if (allow_direct_reclaim(pgdat
))
6561 /* If no zone was usable by the allocation flags then do not throttle */
6565 /* Account for the throttling */
6566 count_vm_event(PGSCAN_DIRECT_THROTTLE
);
6569 * If the caller cannot enter the filesystem, it's possible that it
6570 * is due to the caller holding an FS lock or performing a journal
6571 * transaction in the case of a filesystem like ext[3|4]. In this case,
6572 * it is not safe to block on pfmemalloc_wait as kswapd could be
6573 * blocked waiting on the same lock. Instead, throttle for up to a
6574 * second before continuing.
6576 if (!(gfp_mask
& __GFP_FS
))
6577 wait_event_interruptible_timeout(pgdat
->pfmemalloc_wait
,
6578 allow_direct_reclaim(pgdat
), HZ
);
6580 /* Throttle until kswapd wakes the process */
6581 wait_event_killable(zone
->zone_pgdat
->pfmemalloc_wait
,
6582 allow_direct_reclaim(pgdat
));
6584 if (fatal_signal_pending(current
))
6591 unsigned long try_to_free_pages(struct zonelist
*zonelist
, int order
,
6592 gfp_t gfp_mask
, nodemask_t
*nodemask
)
6594 unsigned long nr_reclaimed
;
6595 struct scan_control sc
= {
6596 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
6597 .gfp_mask
= current_gfp_context(gfp_mask
),
6598 .reclaim_idx
= gfp_zone(gfp_mask
),
6600 .nodemask
= nodemask
,
6601 .priority
= DEF_PRIORITY
,
6602 .may_writepage
= !laptop_mode
,
6608 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6609 * Confirm they are large enough for max values.
6611 BUILD_BUG_ON(MAX_PAGE_ORDER
>= S8_MAX
);
6612 BUILD_BUG_ON(DEF_PRIORITY
> S8_MAX
);
6613 BUILD_BUG_ON(MAX_NR_ZONES
> S8_MAX
);
6616 * Do not enter reclaim if fatal signal was delivered while throttled.
6617 * 1 is returned so that the page allocator does not OOM kill at this
6620 if (throttle_direct_reclaim(sc
.gfp_mask
, zonelist
, nodemask
))
6623 set_task_reclaim_state(current
, &sc
.reclaim_state
);
6624 trace_mm_vmscan_direct_reclaim_begin(order
, sc
.gfp_mask
);
6626 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
6628 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed
);
6629 set_task_reclaim_state(current
, NULL
);
6631 return nr_reclaimed
;
6636 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6637 unsigned long mem_cgroup_shrink_node(struct mem_cgroup
*memcg
,
6638 gfp_t gfp_mask
, bool noswap
,
6640 unsigned long *nr_scanned
)
6642 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
6643 struct scan_control sc
= {
6644 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
6645 .target_mem_cgroup
= memcg
,
6646 .may_writepage
= !laptop_mode
,
6648 .reclaim_idx
= MAX_NR_ZONES
- 1,
6649 .may_swap
= !noswap
,
6652 WARN_ON_ONCE(!current
->reclaim_state
);
6654 sc
.gfp_mask
= (gfp_mask
& GFP_RECLAIM_MASK
) |
6655 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
);
6657 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc
.order
,
6661 * NOTE: Although we can get the priority field, using it
6662 * here is not a good idea, since it limits the pages we can scan.
6663 * if we don't reclaim here, the shrink_node from balance_pgdat
6664 * will pick up pages from other mem cgroup's as well. We hack
6665 * the priority and make it zero.
6667 shrink_lruvec(lruvec
, &sc
);
6669 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc
.nr_reclaimed
);
6671 *nr_scanned
= sc
.nr_scanned
;
6673 return sc
.nr_reclaimed
;
6676 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup
*memcg
,
6677 unsigned long nr_pages
,
6679 unsigned int reclaim_options
,
6682 unsigned long nr_reclaimed
;
6683 unsigned int noreclaim_flag
;
6684 struct scan_control sc
= {
6685 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
6686 .proactive_swappiness
= swappiness
,
6687 .gfp_mask
= (current_gfp_context(gfp_mask
) & GFP_RECLAIM_MASK
) |
6688 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
),
6689 .reclaim_idx
= MAX_NR_ZONES
- 1,
6690 .target_mem_cgroup
= memcg
,
6691 .priority
= DEF_PRIORITY
,
6692 .may_writepage
= !laptop_mode
,
6694 .may_swap
= !!(reclaim_options
& MEMCG_RECLAIM_MAY_SWAP
),
6695 .proactive
= !!(reclaim_options
& MEMCG_RECLAIM_PROACTIVE
),
6698 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6699 * equal pressure on all the nodes. This is based on the assumption that
6700 * the reclaim does not bail out early.
6702 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
6704 set_task_reclaim_state(current
, &sc
.reclaim_state
);
6705 trace_mm_vmscan_memcg_reclaim_begin(0, sc
.gfp_mask
);
6706 noreclaim_flag
= memalloc_noreclaim_save();
6708 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
6710 memalloc_noreclaim_restore(noreclaim_flag
);
6711 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed
);
6712 set_task_reclaim_state(current
, NULL
);
6714 return nr_reclaimed
;
6718 static void kswapd_age_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
6720 struct mem_cgroup
*memcg
;
6721 struct lruvec
*lruvec
;
6723 if (lru_gen_enabled()) {
6724 lru_gen_age_node(pgdat
, sc
);
6728 lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
6729 if (!can_age_anon_pages(lruvec
, sc
))
6732 if (!inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
6735 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
6737 lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
6738 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
6739 sc
, LRU_ACTIVE_ANON
);
6740 memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
);
6744 static bool pgdat_watermark_boosted(pg_data_t
*pgdat
, int highest_zoneidx
)
6750 * Check for watermark boosts top-down as the higher zones
6751 * are more likely to be boosted. Both watermarks and boosts
6752 * should not be checked at the same time as reclaim would
6753 * start prematurely when there is no boosting and a lower
6756 for (i
= highest_zoneidx
; i
>= 0; i
--) {
6757 zone
= pgdat
->node_zones
+ i
;
6758 if (!managed_zone(zone
))
6761 if (zone
->watermark_boost
)
6769 * Returns true if there is an eligible zone balanced for the request order
6770 * and highest_zoneidx
6772 static bool pgdat_balanced(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
6775 unsigned long mark
= -1;
6779 * Check watermarks bottom-up as lower zones are more likely to
6782 for_each_managed_zone_pgdat(zone
, pgdat
, i
, highest_zoneidx
) {
6783 enum zone_stat_item item
;
6784 unsigned long free_pages
;
6786 if (sysctl_numa_balancing_mode
& NUMA_BALANCING_MEMORY_TIERING
)
6787 mark
= promo_wmark_pages(zone
);
6789 mark
= high_wmark_pages(zone
);
6792 * In defrag_mode, watermarks must be met in whole
6793 * blocks to avoid polluting allocator fallbacks.
6795 * However, kswapd usually cannot accomplish this on
6796 * its own and needs kcompactd support. Once it's
6797 * reclaimed a compaction gap, and kswapd_shrink_node
6798 * has dropped order, simply ensure there are enough
6799 * base pages for compaction, wake kcompactd & sleep.
6801 if (defrag_mode
&& order
)
6802 item
= NR_FREE_PAGES_BLOCKS
;
6804 item
= NR_FREE_PAGES
;
6807 * When there is a high number of CPUs in the system,
6808 * the cumulative error from the vmstat per-cpu cache
6809 * can blur the line between the watermarks. In that
6810 * case, be safe and get an accurate snapshot.
6812 * TODO: NR_FREE_PAGES_BLOCKS moves in steps of
6813 * pageblock_nr_pages, while the vmstat pcp threshold
6814 * is limited to 125. On many configurations that
6815 * counter won't actually be per-cpu cached. But keep
6816 * things simple for now; revisit when somebody cares.
6818 free_pages
= zone_page_state(zone
, item
);
6819 if (zone
->percpu_drift_mark
&& free_pages
< zone
->percpu_drift_mark
)
6820 free_pages
= zone_page_state_snapshot(zone
, item
);
6822 if (__zone_watermark_ok(zone
, order
, mark
, highest_zoneidx
,
6828 * If a node has no managed zone within highest_zoneidx, it does not
6829 * need balancing by definition. This can happen if a zone-restricted
6830 * allocation tries to wake a remote kswapd.
6838 /* Clear pgdat state for congested, dirty or under writeback. */
6839 static void clear_pgdat_congested(pg_data_t
*pgdat
)
6841 struct lruvec
*lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
6843 clear_bit(LRUVEC_NODE_CONGESTED
, &lruvec
->flags
);
6844 clear_bit(LRUVEC_CGROUP_CONGESTED
, &lruvec
->flags
);
6845 clear_bit(PGDAT_DIRTY
, &pgdat
->flags
);
6846 clear_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
6850 * Prepare kswapd for sleeping. This verifies that there are no processes
6851 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6853 * Returns true if kswapd is ready to sleep
6855 static bool prepare_kswapd_sleep(pg_data_t
*pgdat
, int order
,
6856 int highest_zoneidx
)
6859 * The throttled processes are normally woken up in balance_pgdat() as
6860 * soon as allow_direct_reclaim() is true. But there is a potential
6861 * race between when kswapd checks the watermarks and a process gets
6862 * throttled. There is also a potential race if processes get
6863 * throttled, kswapd wakes, a large process exits thereby balancing the
6864 * zones, which causes kswapd to exit balance_pgdat() before reaching
6865 * the wake up checks. If kswapd is going to sleep, no process should
6866 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6867 * the wake up is premature, processes will wake kswapd and get
6868 * throttled again. The difference from wake ups in balance_pgdat() is
6869 * that here we are under prepare_to_wait().
6871 if (waitqueue_active(&pgdat
->pfmemalloc_wait
))
6872 wake_up_all(&pgdat
->pfmemalloc_wait
);
6874 /* Hopeless node, leave it to direct reclaim */
6875 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
6878 if (pgdat_balanced(pgdat
, order
, highest_zoneidx
)) {
6879 clear_pgdat_congested(pgdat
);
6887 * kswapd shrinks a node of pages that are at or below the highest usable
6888 * zone that is currently unbalanced.
6890 * Returns true if kswapd scanned at least the requested number of pages to
6891 * reclaim or if the lack of progress was due to pages under writeback.
6892 * This is used to determine if the scanning priority needs to be raised.
6894 static bool kswapd_shrink_node(pg_data_t
*pgdat
,
6895 struct scan_control
*sc
)
6899 unsigned long nr_reclaimed
= sc
->nr_reclaimed
;
6901 /* Reclaim a number of pages proportional to the number of zones */
6902 sc
->nr_to_reclaim
= 0;
6903 for_each_managed_zone_pgdat(zone
, pgdat
, z
, sc
->reclaim_idx
) {
6904 sc
->nr_to_reclaim
+= max(high_wmark_pages(zone
), SWAP_CLUSTER_MAX
);
6908 * Historically care was taken to put equal pressure on all zones but
6909 * now pressure is applied based on node LRU order.
6911 shrink_node(pgdat
, sc
);
6914 * Fragmentation may mean that the system cannot be rebalanced for
6915 * high-order allocations. If twice the allocation size has been
6916 * reclaimed then recheck watermarks only at order-0 to prevent
6917 * excessive reclaim. Assume that a process requested a high-order
6918 * can direct reclaim/compact.
6920 if (sc
->order
&& sc
->nr_reclaimed
>= compact_gap(sc
->order
))
6923 /* account for progress from mm_account_reclaimed_pages() */
6924 return max(sc
->nr_scanned
, sc
->nr_reclaimed
- nr_reclaimed
) >= sc
->nr_to_reclaim
;
6927 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6929 update_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
, bool active
)
6934 for_each_managed_zone_pgdat(zone
, pgdat
, i
, highest_zoneidx
) {
6936 set_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
6938 clear_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
6943 set_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
6945 update_reclaim_active(pgdat
, highest_zoneidx
, true);
6949 clear_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
6951 update_reclaim_active(pgdat
, highest_zoneidx
, false);
6955 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6956 * that are eligible for use by the caller until at least one zone is
6959 * Returns the order kswapd finished reclaiming at.
6961 * kswapd scans the zones in the highmem->normal->dma direction. It skips
6962 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6963 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6964 * or lower is eligible for reclaim until at least one usable zone is
6967 static int balance_pgdat(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
6970 unsigned long nr_soft_reclaimed
;
6971 unsigned long nr_soft_scanned
;
6972 unsigned long pflags
;
6973 unsigned long nr_boost_reclaim
;
6974 unsigned long zone_boosts
[MAX_NR_ZONES
] = { 0, };
6977 struct scan_control sc
= {
6978 .gfp_mask
= GFP_KERNEL
,
6983 set_task_reclaim_state(current
, &sc
.reclaim_state
);
6984 psi_memstall_enter(&pflags
);
6985 __fs_reclaim_acquire(_THIS_IP_
);
6987 count_vm_event(PAGEOUTRUN
);
6990 * Account for the reclaim boost. Note that the zone boost is left in
6991 * place so that parallel allocations that are near the watermark will
6992 * stall or direct reclaim until kswapd is finished.
6994 nr_boost_reclaim
= 0;
6995 for_each_managed_zone_pgdat(zone
, pgdat
, i
, highest_zoneidx
) {
6996 nr_boost_reclaim
+= zone
->watermark_boost
;
6997 zone_boosts
[i
] = zone
->watermark_boost
;
6999 boosted
= nr_boost_reclaim
;
7002 set_reclaim_active(pgdat
, highest_zoneidx
);
7003 sc
.priority
= DEF_PRIORITY
;
7005 unsigned long nr_reclaimed
= sc
.nr_reclaimed
;
7006 bool raise_priority
= true;
7011 sc
.reclaim_idx
= highest_zoneidx
;
7014 * If the number of buffer_heads exceeds the maximum allowed
7015 * then consider reclaiming from all zones. This has a dual
7016 * purpose -- on 64-bit systems it is expected that
7017 * buffer_heads are stripped during active rotation. On 32-bit
7018 * systems, highmem pages can pin lowmem memory and shrinking
7019 * buffers can relieve lowmem pressure. Reclaim may still not
7020 * go ahead if all eligible zones for the original allocation
7021 * request are balanced to avoid excessive reclaim from kswapd.
7023 if (buffer_heads_over_limit
) {
7024 for (i
= MAX_NR_ZONES
- 1; i
>= 0; i
--) {
7025 zone
= pgdat
->node_zones
+ i
;
7026 if (!managed_zone(zone
))
7035 * If the pgdat is imbalanced then ignore boosting and preserve
7036 * the watermarks for a later time and restart. Note that the
7037 * zone watermarks will be still reset at the end of balancing
7038 * on the grounds that the normal reclaim should be enough to
7039 * re-evaluate if boosting is required when kswapd next wakes.
7041 balanced
= pgdat_balanced(pgdat
, sc
.order
, highest_zoneidx
);
7042 if (!balanced
&& nr_boost_reclaim
) {
7043 nr_boost_reclaim
= 0;
7048 * If boosting is not active then only reclaim if there are no
7049 * eligible zones. Note that sc.reclaim_idx is not used as
7050 * buffer_heads_over_limit may have adjusted it.
7052 if (!nr_boost_reclaim
&& balanced
)
7055 /* Limit the priority of boosting to avoid reclaim writeback */
7056 if (nr_boost_reclaim
&& sc
.priority
== DEF_PRIORITY
- 2)
7057 raise_priority
= false;
7060 * Do not writeback or swap pages for boosted reclaim. The
7061 * intent is to relieve pressure not issue sub-optimal IO
7062 * from reclaim context. If no pages are reclaimed, the
7063 * reclaim will be aborted.
7065 sc
.may_writepage
= !laptop_mode
&& !nr_boost_reclaim
;
7066 sc
.may_swap
= !nr_boost_reclaim
;
7069 * Do some background aging, to give pages a chance to be
7070 * referenced before reclaiming. All pages are rotated
7071 * regardless of classzone as this is about consistent aging.
7073 kswapd_age_node(pgdat
, &sc
);
7076 * If we're getting trouble reclaiming, start doing writepage
7077 * even in laptop mode.
7079 if (sc
.priority
< DEF_PRIORITY
- 2)
7080 sc
.may_writepage
= 1;
7082 /* Call soft limit reclaim before calling shrink_node. */
7084 nr_soft_scanned
= 0;
7085 nr_soft_reclaimed
= memcg1_soft_limit_reclaim(pgdat
, sc
.order
,
7086 sc
.gfp_mask
, &nr_soft_scanned
);
7087 sc
.nr_reclaimed
+= nr_soft_reclaimed
;
7090 * There should be no need to raise the scanning priority if
7091 * enough pages are already being scanned that that high
7092 * watermark would be met at 100% efficiency.
7094 if (kswapd_shrink_node(pgdat
, &sc
))
7095 raise_priority
= false;
7098 * If the low watermark is met there is no need for processes
7099 * to be throttled on pfmemalloc_wait as they should not be
7100 * able to safely make forward progress. Wake them
7102 if (waitqueue_active(&pgdat
->pfmemalloc_wait
) &&
7103 allow_direct_reclaim(pgdat
))
7104 wake_up_all(&pgdat
->pfmemalloc_wait
);
7106 /* Check if kswapd should be suspending */
7107 __fs_reclaim_release(_THIS_IP_
);
7108 ret
= kthread_freezable_should_stop(&was_frozen
);
7109 __fs_reclaim_acquire(_THIS_IP_
);
7110 if (was_frozen
|| ret
)
7114 * Raise priority if scanning rate is too low or there was no
7115 * progress in reclaiming pages
7117 nr_reclaimed
= sc
.nr_reclaimed
- nr_reclaimed
;
7118 nr_boost_reclaim
-= min(nr_boost_reclaim
, nr_reclaimed
);
7121 * If reclaim made no progress for a boost, stop reclaim as
7122 * IO cannot be queued and it could be an infinite loop in
7123 * extreme circumstances.
7125 if (nr_boost_reclaim
&& !nr_reclaimed
)
7128 if (raise_priority
|| !nr_reclaimed
)
7130 } while (sc
.priority
>= 1);
7133 * Restart only if it went through the priority loop all the way,
7134 * but cache_trim_mode didn't work.
7136 if (!sc
.nr_reclaimed
&& sc
.priority
< 1 &&
7137 !sc
.no_cache_trim_mode
&& sc
.cache_trim_mode_failed
) {
7138 sc
.no_cache_trim_mode
= 1;
7142 if (!sc
.nr_reclaimed
)
7143 pgdat
->kswapd_failures
++;
7146 clear_reclaim_active(pgdat
, highest_zoneidx
);
7148 /* If reclaim was boosted, account for the reclaim done in this pass */
7150 unsigned long flags
;
7152 for (i
= 0; i
<= highest_zoneidx
; i
++) {
7153 if (!zone_boosts
[i
])
7156 /* Increments are under the zone lock */
7157 zone
= pgdat
->node_zones
+ i
;
7158 spin_lock_irqsave(&zone
->lock
, flags
);
7159 zone
->watermark_boost
-= min(zone
->watermark_boost
, zone_boosts
[i
]);
7160 spin_unlock_irqrestore(&zone
->lock
, flags
);
7164 * As there is now likely space, wakeup kcompact to defragment
7167 wakeup_kcompactd(pgdat
, pageblock_order
, highest_zoneidx
);
7170 snapshot_refaults(NULL
, pgdat
);
7171 __fs_reclaim_release(_THIS_IP_
);
7172 psi_memstall_leave(&pflags
);
7173 set_task_reclaim_state(current
, NULL
);
7176 * Return the order kswapd stopped reclaiming at as
7177 * prepare_kswapd_sleep() takes it into account. If another caller
7178 * entered the allocator slow path while kswapd was awake, order will
7179 * remain at the higher level.
7185 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7186 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7187 * not a valid index then either kswapd runs for first time or kswapd couldn't
7188 * sleep after previous reclaim attempt (node is still unbalanced). In that
7189 * case return the zone index of the previous kswapd reclaim cycle.
7191 static enum zone_type
kswapd_highest_zoneidx(pg_data_t
*pgdat
,
7192 enum zone_type prev_highest_zoneidx
)
7194 enum zone_type curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
7196 return curr_idx
== MAX_NR_ZONES
? prev_highest_zoneidx
: curr_idx
;
7199 static void kswapd_try_to_sleep(pg_data_t
*pgdat
, int alloc_order
, int reclaim_order
,
7200 unsigned int highest_zoneidx
)
7205 if (freezing(current
) || kthread_should_stop())
7208 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
7211 * Try to sleep for a short interval. Note that kcompactd will only be
7212 * woken if it is possible to sleep for a short interval. This is
7213 * deliberate on the assumption that if reclaim cannot keep an
7214 * eligible zone balanced that it's also unlikely that compaction will
7217 if (prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
7219 * Compaction records what page blocks it recently failed to
7220 * isolate pages from and skips them in the future scanning.
7221 * When kswapd is going to sleep, it is reasonable to assume
7222 * that pages and compaction may succeed so reset the cache.
7224 reset_isolation_suitable(pgdat
);
7227 * We have freed the memory, now we should compact it to make
7228 * allocation of the requested order possible.
7230 wakeup_kcompactd(pgdat
, alloc_order
, highest_zoneidx
);
7232 remaining
= schedule_timeout(HZ
/10);
7235 * If woken prematurely then reset kswapd_highest_zoneidx and
7236 * order. The values will either be from a wakeup request or
7237 * the previous request that slept prematurely.
7240 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
,
7241 kswapd_highest_zoneidx(pgdat
,
7244 if (READ_ONCE(pgdat
->kswapd_order
) < reclaim_order
)
7245 WRITE_ONCE(pgdat
->kswapd_order
, reclaim_order
);
7248 finish_wait(&pgdat
->kswapd_wait
, &wait
);
7249 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
7253 * After a short sleep, check if it was a premature sleep. If not, then
7254 * go fully to sleep until explicitly woken up.
7257 prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
7258 trace_mm_vmscan_kswapd_sleep(pgdat
->node_id
);
7261 * vmstat counters are not perfectly accurate and the estimated
7262 * value for counters such as NR_FREE_PAGES can deviate from the
7263 * true value by nr_online_cpus * threshold. To avoid the zone
7264 * watermarks being breached while under pressure, we reduce the
7265 * per-cpu vmstat threshold while kswapd is awake and restore
7266 * them before going back to sleep.
7268 set_pgdat_percpu_threshold(pgdat
, calculate_normal_threshold
);
7270 if (!kthread_should_stop())
7273 set_pgdat_percpu_threshold(pgdat
, calculate_pressure_threshold
);
7276 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY
);
7278 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY
);
7280 finish_wait(&pgdat
->kswapd_wait
, &wait
);
7284 * The background pageout daemon, started as a kernel thread
7285 * from the init process.
7287 * This basically trickles out pages so that we have _some_
7288 * free memory available even if there is no other activity
7289 * that frees anything up. This is needed for things like routing
7290 * etc, where we otherwise might have all activity going on in
7291 * asynchronous contexts that cannot page things out.
7293 * If there are applications that are active memory-allocators
7294 * (most normal use), this basically shouldn't matter.
7296 static int kswapd(void *p
)
7298 unsigned int alloc_order
, reclaim_order
;
7299 unsigned int highest_zoneidx
= MAX_NR_ZONES
- 1;
7300 pg_data_t
*pgdat
= (pg_data_t
*)p
;
7301 struct task_struct
*tsk
= current
;
7304 * Tell the memory management that we're a "memory allocator",
7305 * and that if we need more memory we should get access to it
7306 * regardless (see "__alloc_pages()"). "kswapd" should
7307 * never get caught in the normal page freeing logic.
7309 * (Kswapd normally doesn't need memory anyway, but sometimes
7310 * you need a small amount of memory in order to be able to
7311 * page out something else, and this flag essentially protects
7312 * us from recursively trying to free more memory as we're
7313 * trying to free the first piece of memory in the first place).
7315 tsk
->flags
|= PF_MEMALLOC
| PF_KSWAPD
;
7318 WRITE_ONCE(pgdat
->kswapd_order
, 0);
7319 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
7320 atomic_set(&pgdat
->nr_writeback_throttled
, 0);
7324 alloc_order
= reclaim_order
= READ_ONCE(pgdat
->kswapd_order
);
7325 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
7329 kswapd_try_to_sleep(pgdat
, alloc_order
, reclaim_order
,
7332 /* Read the new order and highest_zoneidx */
7333 alloc_order
= READ_ONCE(pgdat
->kswapd_order
);
7334 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
7336 WRITE_ONCE(pgdat
->kswapd_order
, 0);
7337 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
7339 if (kthread_freezable_should_stop(&was_frozen
))
7343 * We can speed up thawing tasks if we don't call balance_pgdat
7344 * after returning from the refrigerator
7350 * Reclaim begins at the requested order but if a high-order
7351 * reclaim fails then kswapd falls back to reclaiming for
7352 * order-0. If that happens, kswapd will consider sleeping
7353 * for the order it finished reclaiming at (reclaim_order)
7354 * but kcompactd is woken to compact for the original
7355 * request (alloc_order).
7357 trace_mm_vmscan_kswapd_wake(pgdat
->node_id
, highest_zoneidx
,
7359 reclaim_order
= balance_pgdat(pgdat
, alloc_order
,
7361 if (reclaim_order
< alloc_order
)
7362 goto kswapd_try_sleep
;
7365 tsk
->flags
&= ~(PF_MEMALLOC
| PF_KSWAPD
);
7371 * A zone is low on free memory or too fragmented for high-order memory. If
7372 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7373 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7374 * has failed or is not needed, still wake up kcompactd if only compaction is
7377 void wakeup_kswapd(struct zone
*zone
, gfp_t gfp_flags
, int order
,
7378 enum zone_type highest_zoneidx
)
7381 enum zone_type curr_idx
;
7383 if (!managed_zone(zone
))
7386 if (!cpuset_zone_allowed(zone
, gfp_flags
))
7389 pgdat
= zone
->zone_pgdat
;
7390 curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
7392 if (curr_idx
== MAX_NR_ZONES
|| curr_idx
< highest_zoneidx
)
7393 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, highest_zoneidx
);
7395 if (READ_ONCE(pgdat
->kswapd_order
) < order
)
7396 WRITE_ONCE(pgdat
->kswapd_order
, order
);
7398 if (!waitqueue_active(&pgdat
->kswapd_wait
))
7401 /* Hopeless node, leave it to direct reclaim if possible */
7402 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
||
7403 (pgdat_balanced(pgdat
, order
, highest_zoneidx
) &&
7404 !pgdat_watermark_boosted(pgdat
, highest_zoneidx
))) {
7406 * There may be plenty of free memory available, but it's too
7407 * fragmented for high-order allocations. Wake up kcompactd
7408 * and rely on compaction_suitable() to determine if it's
7409 * needed. If it fails, it will defer subsequent attempts to
7410 * ratelimit its work.
7412 if (!(gfp_flags
& __GFP_DIRECT_RECLAIM
))
7413 wakeup_kcompactd(pgdat
, order
, highest_zoneidx
);
7417 trace_mm_vmscan_wakeup_kswapd(pgdat
->node_id
, highest_zoneidx
, order
,
7419 wake_up_interruptible(&pgdat
->kswapd_wait
);
7422 #ifdef CONFIG_HIBERNATION
7424 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7427 * Rather than trying to age LRUs the aim is to preserve the overall
7428 * LRU order by reclaiming preferentially
7429 * inactive > active > active referenced > active mapped
7431 unsigned long shrink_all_memory(unsigned long nr_to_reclaim
)
7433 struct scan_control sc
= {
7434 .nr_to_reclaim
= nr_to_reclaim
,
7435 .gfp_mask
= GFP_HIGHUSER_MOVABLE
,
7436 .reclaim_idx
= MAX_NR_ZONES
- 1,
7437 .priority
= DEF_PRIORITY
,
7441 .hibernation_mode
= 1,
7443 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
7444 unsigned long nr_reclaimed
;
7445 unsigned int noreclaim_flag
;
7447 fs_reclaim_acquire(sc
.gfp_mask
);
7448 noreclaim_flag
= memalloc_noreclaim_save();
7449 set_task_reclaim_state(current
, &sc
.reclaim_state
);
7451 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
7453 set_task_reclaim_state(current
, NULL
);
7454 memalloc_noreclaim_restore(noreclaim_flag
);
7455 fs_reclaim_release(sc
.gfp_mask
);
7457 return nr_reclaimed
;
7459 #endif /* CONFIG_HIBERNATION */
7462 * This kswapd start function will be called by init and node-hot-add.
7464 void __meminit
kswapd_run(int nid
)
7466 pg_data_t
*pgdat
= NODE_DATA(nid
);
7468 pgdat_kswapd_lock(pgdat
);
7469 if (!pgdat
->kswapd
) {
7470 pgdat
->kswapd
= kthread_create_on_node(kswapd
, pgdat
, nid
, "kswapd%d", nid
);
7471 if (IS_ERR(pgdat
->kswapd
)) {
7472 /* failure at boot is fatal */
7473 pr_err("Failed to start kswapd on node %d,ret=%ld\n",
7474 nid
, PTR_ERR(pgdat
->kswapd
));
7475 BUG_ON(system_state
< SYSTEM_RUNNING
);
7476 pgdat
->kswapd
= NULL
;
7478 wake_up_process(pgdat
->kswapd
);
7481 pgdat_kswapd_unlock(pgdat
);
7485 * Called by memory hotplug when all memory in a node is offlined. Caller must
7486 * be holding mem_hotplug_begin/done().
7488 void __meminit
kswapd_stop(int nid
)
7490 pg_data_t
*pgdat
= NODE_DATA(nid
);
7491 struct task_struct
*kswapd
;
7493 pgdat_kswapd_lock(pgdat
);
7494 kswapd
= pgdat
->kswapd
;
7496 kthread_stop(kswapd
);
7497 pgdat
->kswapd
= NULL
;
7499 pgdat_kswapd_unlock(pgdat
);
7502 static const struct ctl_table vmscan_sysctl_table
[] = {
7504 .procname
= "swappiness",
7505 .data
= &vm_swappiness
,
7506 .maxlen
= sizeof(vm_swappiness
),
7508 .proc_handler
= proc_dointvec_minmax
,
7509 .extra1
= SYSCTL_ZERO
,
7510 .extra2
= SYSCTL_TWO_HUNDRED
,
7514 .procname
= "zone_reclaim_mode",
7515 .data
= &node_reclaim_mode
,
7516 .maxlen
= sizeof(node_reclaim_mode
),
7518 .proc_handler
= proc_dointvec_minmax
,
7519 .extra1
= SYSCTL_ZERO
,
7524 static int __init
kswapd_init(void)
7529 for_each_node_state(nid
, N_MEMORY
)
7531 register_sysctl_init("vm", vmscan_sysctl_table
);
7535 module_init(kswapd_init
)
7541 * If non-zero call node_reclaim when the number of free pages falls below
7544 int node_reclaim_mode __read_mostly
;
7547 * Priority for NODE_RECLAIM. This determines the fraction of pages
7548 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7551 #define NODE_RECLAIM_PRIORITY 4
7554 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7557 int sysctl_min_unmapped_ratio
= 1;
7560 * If the number of slab pages in a zone grows beyond this percentage then
7561 * slab reclaim needs to occur.
7563 int sysctl_min_slab_ratio
= 5;
7565 static inline unsigned long node_unmapped_file_pages(struct pglist_data
*pgdat
)
7567 unsigned long file_mapped
= node_page_state(pgdat
, NR_FILE_MAPPED
);
7568 unsigned long file_lru
= node_page_state(pgdat
, NR_INACTIVE_FILE
) +
7569 node_page_state(pgdat
, NR_ACTIVE_FILE
);
7572 * It's possible for there to be more file mapped pages than
7573 * accounted for by the pages on the file LRU lists because
7574 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7576 return (file_lru
> file_mapped
) ? (file_lru
- file_mapped
) : 0;
7579 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7580 static unsigned long node_pagecache_reclaimable(struct pglist_data
*pgdat
)
7582 unsigned long nr_pagecache_reclaimable
;
7583 unsigned long delta
= 0;
7586 * If RECLAIM_UNMAP is set, then all file pages are considered
7587 * potentially reclaimable. Otherwise, we have to worry about
7588 * pages like swapcache and node_unmapped_file_pages() provides
7591 if (node_reclaim_mode
& RECLAIM_UNMAP
)
7592 nr_pagecache_reclaimable
= node_page_state(pgdat
, NR_FILE_PAGES
);
7594 nr_pagecache_reclaimable
= node_unmapped_file_pages(pgdat
);
7596 /* If we can't clean pages, remove dirty pages from consideration */
7597 if (!(node_reclaim_mode
& RECLAIM_WRITE
))
7598 delta
+= node_page_state(pgdat
, NR_FILE_DIRTY
);
7600 /* Watch for any possible underflows due to delta */
7601 if (unlikely(delta
> nr_pagecache_reclaimable
))
7602 delta
= nr_pagecache_reclaimable
;
7604 return nr_pagecache_reclaimable
- delta
;
7608 * Try to free up some pages from this node through reclaim.
7610 static int __node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
7612 /* Minimum pages needed in order to stay on node */
7613 const unsigned long nr_pages
= 1 << order
;
7614 struct task_struct
*p
= current
;
7615 unsigned int noreclaim_flag
;
7616 struct scan_control sc
= {
7617 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
7618 .gfp_mask
= current_gfp_context(gfp_mask
),
7620 .priority
= NODE_RECLAIM_PRIORITY
,
7621 .may_writepage
= !!(node_reclaim_mode
& RECLAIM_WRITE
),
7622 .may_unmap
= !!(node_reclaim_mode
& RECLAIM_UNMAP
),
7624 .reclaim_idx
= gfp_zone(gfp_mask
),
7626 unsigned long pflags
;
7628 trace_mm_vmscan_node_reclaim_begin(pgdat
->node_id
, order
,
7632 psi_memstall_enter(&pflags
);
7633 delayacct_freepages_start();
7634 fs_reclaim_acquire(sc
.gfp_mask
);
7636 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7638 noreclaim_flag
= memalloc_noreclaim_save();
7639 set_task_reclaim_state(p
, &sc
.reclaim_state
);
7641 if (node_pagecache_reclaimable(pgdat
) > pgdat
->min_unmapped_pages
||
7642 node_page_state_pages(pgdat
, NR_SLAB_RECLAIMABLE_B
) > pgdat
->min_slab_pages
) {
7644 * Free memory by calling shrink node with increasing
7645 * priorities until we have enough memory freed.
7648 shrink_node(pgdat
, &sc
);
7649 } while (sc
.nr_reclaimed
< nr_pages
&& --sc
.priority
>= 0);
7652 set_task_reclaim_state(p
, NULL
);
7653 memalloc_noreclaim_restore(noreclaim_flag
);
7654 fs_reclaim_release(sc
.gfp_mask
);
7655 psi_memstall_leave(&pflags
);
7656 delayacct_freepages_end();
7658 trace_mm_vmscan_node_reclaim_end(sc
.nr_reclaimed
);
7660 return sc
.nr_reclaimed
>= nr_pages
;
7663 int node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
7668 * Node reclaim reclaims unmapped file backed pages and
7669 * slab pages if we are over the defined limits.
7671 * A small portion of unmapped file backed pages is needed for
7672 * file I/O otherwise pages read by file I/O will be immediately
7673 * thrown out if the node is overallocated. So we do not reclaim
7674 * if less than a specified percentage of the node is used by
7675 * unmapped file backed pages.
7677 if (node_pagecache_reclaimable(pgdat
) <= pgdat
->min_unmapped_pages
&&
7678 node_page_state_pages(pgdat
, NR_SLAB_RECLAIMABLE_B
) <=
7679 pgdat
->min_slab_pages
)
7680 return NODE_RECLAIM_FULL
;
7683 * Do not scan if the allocation should not be delayed.
7685 if (!gfpflags_allow_blocking(gfp_mask
) || (current
->flags
& PF_MEMALLOC
))
7686 return NODE_RECLAIM_NOSCAN
;
7689 * Only run node reclaim on the local node or on nodes that do not
7690 * have associated processors. This will favor the local processor
7691 * over remote processors and spread off node memory allocations
7692 * as wide as possible.
7694 if (node_state(pgdat
->node_id
, N_CPU
) && pgdat
->node_id
!= numa_node_id())
7695 return NODE_RECLAIM_NOSCAN
;
7697 if (test_and_set_bit_lock(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
))
7698 return NODE_RECLAIM_NOSCAN
;
7700 ret
= __node_reclaim(pgdat
, gfp_mask
, order
);
7701 clear_bit_unlock(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
);
7704 count_vm_event(PGSCAN_ZONE_RECLAIM_SUCCESS
);
7706 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED
);
7713 * check_move_unevictable_folios - Move evictable folios to appropriate zone
7715 * @fbatch: Batch of lru folios to check.
7717 * Checks folios for evictability, if an evictable folio is in the unevictable
7718 * lru list, moves it to the appropriate evictable lru list. This function
7719 * should be only used for lru folios.
7721 void check_move_unevictable_folios(struct folio_batch
*fbatch
)
7723 struct lruvec
*lruvec
= NULL
;
7728 for (i
= 0; i
< fbatch
->nr
; i
++) {
7729 struct folio
*folio
= fbatch
->folios
[i
];
7730 int nr_pages
= folio_nr_pages(folio
);
7732 pgscanned
+= nr_pages
;
7734 /* block memcg migration while the folio moves between lrus */
7735 if (!folio_test_clear_lru(folio
))
7738 lruvec
= folio_lruvec_relock_irq(folio
, lruvec
);
7739 if (folio_evictable(folio
) && folio_test_unevictable(folio
)) {
7740 lruvec_del_folio(lruvec
, folio
);
7741 folio_clear_unevictable(folio
);
7742 lruvec_add_folio(lruvec
, folio
);
7743 pgrescued
+= nr_pages
;
7745 folio_set_lru(folio
);
7749 __count_vm_events(UNEVICTABLE_PGRESCUED
, pgrescued
);
7750 __count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
7751 unlock_page_lruvec_irq(lruvec
);
7752 } else if (pgscanned
) {
7753 count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
7756 EXPORT_SYMBOL_GPL(check_move_unevictable_folios
);