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 static void set_task_reclaim_state(struct task_struct
*task
,
275 struct reclaim_state
*rs
)
277 /* Check for an overwrite */
278 WARN_ON_ONCE(rs
&& task
->reclaim_state
);
280 /* Check for the nulling of an already-nulled member */
281 WARN_ON_ONCE(!rs
&& !task
->reclaim_state
);
283 task
->reclaim_state
= rs
;
287 * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to
288 * scan_control->nr_reclaimed.
290 static void flush_reclaim_state(struct scan_control
*sc
)
293 * Currently, reclaim_state->reclaimed includes three types of pages
294 * freed outside of vmscan:
296 * (2) Clean file pages from pruned inodes (on highmem systems).
297 * (3) XFS freed buffer pages.
299 * For all of these cases, we cannot universally link the pages to a
300 * single memcg. For example, a memcg-aware shrinker can free one object
301 * charged to the target memcg, causing an entire page to be freed.
302 * If we count the entire page as reclaimed from the memcg, we end up
303 * overestimating the reclaimed amount (potentially under-reclaiming).
305 * Only count such pages for global reclaim to prevent under-reclaiming
306 * from the target memcg; preventing unnecessary retries during memcg
307 * charging and false positives from proactive reclaim.
309 * For uncommon cases where the freed pages were actually mostly
310 * charged to the target memcg, we end up underestimating the reclaimed
311 * amount. This should be fine. The freed pages will be uncharged
312 * anyway, even if they are not counted here properly, and we will be
313 * able to make forward progress in charging (which is usually in a
316 * We can go one step further, and report the uncharged objcg pages in
317 * memcg reclaim, to make reporting more accurate and reduce
318 * underestimation, but it's probably not worth the complexity for now.
320 if (current
->reclaim_state
&& root_reclaim(sc
)) {
321 sc
->nr_reclaimed
+= current
->reclaim_state
->reclaimed
;
322 current
->reclaim_state
->reclaimed
= 0;
326 static bool can_demote(int nid
, struct scan_control
*sc
)
328 if (!numa_demotion_enabled
)
330 if (sc
&& sc
->no_demotion
)
332 if (next_demotion_node(nid
) == NUMA_NO_NODE
)
338 static inline bool can_reclaim_anon_pages(struct mem_cgroup
*memcg
,
340 struct scan_control
*sc
)
344 * For non-memcg reclaim, is there
345 * space in any swap device?
347 if (get_nr_swap_pages() > 0)
350 /* Is the memcg below its swap limit? */
351 if (mem_cgroup_get_nr_swap_pages(memcg
) > 0)
356 * The page can not be swapped.
358 * Can it be reclaimed from this node via demotion?
360 return can_demote(nid
, sc
);
364 * This misses isolated folios which are not accounted for to save counters.
365 * As the data only determines if reclaim or compaction continues, it is
366 * not expected that isolated folios will be a dominating factor.
368 unsigned long zone_reclaimable_pages(struct zone
*zone
)
372 nr
= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_FILE
) +
373 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_FILE
);
374 if (can_reclaim_anon_pages(NULL
, zone_to_nid(zone
), NULL
))
375 nr
+= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_ANON
) +
376 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_ANON
);
382 * lruvec_lru_size - Returns the number of pages on the given LRU list.
383 * @lruvec: lru vector
385 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
387 static unsigned long lruvec_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
390 unsigned long size
= 0;
393 for (zid
= 0; zid
<= zone_idx
; zid
++) {
394 struct zone
*zone
= &lruvec_pgdat(lruvec
)->node_zones
[zid
];
396 if (!managed_zone(zone
))
399 if (!mem_cgroup_disabled())
400 size
+= mem_cgroup_get_zone_lru_size(lruvec
, lru
, zid
);
402 size
+= zone_page_state(zone
, NR_ZONE_LRU_BASE
+ lru
);
407 static unsigned long drop_slab_node(int nid
)
409 unsigned long freed
= 0;
410 struct mem_cgroup
*memcg
= NULL
;
412 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
414 freed
+= shrink_slab(GFP_KERNEL
, nid
, memcg
, 0);
415 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)) != NULL
);
428 for_each_online_node(nid
) {
429 if (fatal_signal_pending(current
))
432 freed
+= drop_slab_node(nid
);
434 } while ((freed
>> shift
++) > 1);
437 static int reclaimer_offset(void)
439 BUILD_BUG_ON(PGSTEAL_DIRECT
- PGSTEAL_KSWAPD
!=
440 PGDEMOTE_DIRECT
- PGDEMOTE_KSWAPD
);
441 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED
- PGSTEAL_KSWAPD
!=
442 PGDEMOTE_KHUGEPAGED
- PGDEMOTE_KSWAPD
);
443 BUILD_BUG_ON(PGSTEAL_DIRECT
- PGSTEAL_KSWAPD
!=
444 PGSCAN_DIRECT
- PGSCAN_KSWAPD
);
445 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED
- PGSTEAL_KSWAPD
!=
446 PGSCAN_KHUGEPAGED
- PGSCAN_KSWAPD
);
448 if (current_is_kswapd())
450 if (current_is_khugepaged())
451 return PGSTEAL_KHUGEPAGED
- PGSTEAL_KSWAPD
;
452 return PGSTEAL_DIRECT
- PGSTEAL_KSWAPD
;
455 static inline int is_page_cache_freeable(struct folio
*folio
)
458 * A freeable page cache folio is referenced only by the caller
459 * that isolated the folio, the page cache and optional filesystem
460 * private data at folio->private.
462 return folio_ref_count(folio
) - folio_test_private(folio
) ==
463 1 + folio_nr_pages(folio
);
467 * We detected a synchronous write error writing a folio out. Probably
468 * -ENOSPC. We need to propagate that into the address_space for a subsequent
469 * fsync(), msync() or close().
471 * The tricky part is that after writepage we cannot touch the mapping: nothing
472 * prevents it from being freed up. But we have a ref on the folio and once
473 * that folio is locked, the mapping is pinned.
475 * We're allowed to run sleeping folio_lock() here because we know the caller has
478 static void handle_write_error(struct address_space
*mapping
,
479 struct folio
*folio
, int error
)
482 if (folio_mapping(folio
) == mapping
)
483 mapping_set_error(mapping
, error
);
487 static bool skip_throttle_noprogress(pg_data_t
*pgdat
)
489 int reclaimable
= 0, write_pending
= 0;
493 * If kswapd is disabled, reschedule if necessary but do not
494 * throttle as the system is likely near OOM.
496 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
500 * If there are a lot of dirty/writeback folios then do not
501 * throttle as throttling will occur when the folios cycle
502 * towards the end of the LRU if still under writeback.
504 for (i
= 0; i
< MAX_NR_ZONES
; i
++) {
505 struct zone
*zone
= pgdat
->node_zones
+ i
;
507 if (!managed_zone(zone
))
510 reclaimable
+= zone_reclaimable_pages(zone
);
511 write_pending
+= zone_page_state_snapshot(zone
,
512 NR_ZONE_WRITE_PENDING
);
514 if (2 * write_pending
<= reclaimable
)
520 void reclaim_throttle(pg_data_t
*pgdat
, enum vmscan_throttle_state reason
)
522 wait_queue_head_t
*wqh
= &pgdat
->reclaim_wait
[reason
];
527 * Do not throttle user workers, kthreads other than kswapd or
528 * workqueues. They may be required for reclaim to make
529 * forward progress (e.g. journalling workqueues or kthreads).
531 if (!current_is_kswapd() &&
532 current
->flags
& (PF_USER_WORKER
|PF_KTHREAD
)) {
538 * These figures are pulled out of thin air.
539 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
540 * parallel reclaimers which is a short-lived event so the timeout is
541 * short. Failing to make progress or waiting on writeback are
542 * potentially long-lived events so use a longer timeout. This is shaky
543 * logic as a failure to make progress could be due to anything from
544 * writeback to a slow device to excessive referenced folios at the tail
545 * of the inactive LRU.
548 case VMSCAN_THROTTLE_WRITEBACK
:
551 if (atomic_inc_return(&pgdat
->nr_writeback_throttled
) == 1) {
552 WRITE_ONCE(pgdat
->nr_reclaim_start
,
553 node_page_state(pgdat
, NR_THROTTLED_WRITTEN
));
557 case VMSCAN_THROTTLE_CONGESTED
:
559 case VMSCAN_THROTTLE_NOPROGRESS
:
560 if (skip_throttle_noprogress(pgdat
)) {
568 case VMSCAN_THROTTLE_ISOLATED
:
577 prepare_to_wait(wqh
, &wait
, TASK_UNINTERRUPTIBLE
);
578 ret
= schedule_timeout(timeout
);
579 finish_wait(wqh
, &wait
);
581 if (reason
== VMSCAN_THROTTLE_WRITEBACK
)
582 atomic_dec(&pgdat
->nr_writeback_throttled
);
584 trace_mm_vmscan_throttled(pgdat
->node_id
, jiffies_to_usecs(timeout
),
585 jiffies_to_usecs(timeout
- ret
),
590 * Account for folios written if tasks are throttled waiting on dirty
591 * folios to clean. If enough folios have been cleaned since throttling
592 * started then wakeup the throttled tasks.
594 void __acct_reclaim_writeback(pg_data_t
*pgdat
, struct folio
*folio
,
597 unsigned long nr_written
;
599 node_stat_add_folio(folio
, NR_THROTTLED_WRITTEN
);
602 * This is an inaccurate read as the per-cpu deltas may not
603 * be synchronised. However, given that the system is
604 * writeback throttled, it is not worth taking the penalty
605 * of getting an accurate count. At worst, the throttle
606 * timeout guarantees forward progress.
608 nr_written
= node_page_state(pgdat
, NR_THROTTLED_WRITTEN
) -
609 READ_ONCE(pgdat
->nr_reclaim_start
);
611 if (nr_written
> SWAP_CLUSTER_MAX
* nr_throttled
)
612 wake_up(&pgdat
->reclaim_wait
[VMSCAN_THROTTLE_WRITEBACK
]);
615 /* possible outcome of pageout() */
617 /* failed to write folio out, folio is locked */
619 /* move folio to the active list, folio is locked */
621 /* folio has been sent to the disk successfully, folio is unlocked */
623 /* folio is clean and locked */
628 * pageout is called by shrink_folio_list() for each dirty folio.
629 * Calls ->writepage().
631 static pageout_t
pageout(struct folio
*folio
, struct address_space
*mapping
,
632 struct swap_iocb
**plug
, struct list_head
*folio_list
)
635 * If the folio is dirty, only perform writeback if that write
636 * will be non-blocking. To prevent this allocation from being
637 * stalled by pagecache activity. But note that there may be
638 * stalls if we need to run get_block(). We could test
639 * PagePrivate for that.
641 * If this process is currently in __generic_file_write_iter() against
642 * this folio's queue, we can perform writeback even if that
645 * If the folio is swapcache, write it back even if that would
646 * block, for some throttling. This happens by accident, because
647 * swap_backing_dev_info is bust: it doesn't reflect the
648 * congestion state of the swapdevs. Easy to fix, if needed.
650 if (!is_page_cache_freeable(folio
))
654 * Some data journaling orphaned folios can have
655 * folio->mapping == NULL while being dirty with clean buffers.
657 if (folio_test_private(folio
)) {
658 if (try_to_free_buffers(folio
)) {
659 folio_clear_dirty(folio
);
660 pr_info("%s: orphaned folio\n", __func__
);
666 if (mapping
->a_ops
->writepage
== NULL
)
667 return PAGE_ACTIVATE
;
669 if (folio_clear_dirty_for_io(folio
)) {
671 struct writeback_control wbc
= {
672 .sync_mode
= WB_SYNC_NONE
,
673 .nr_to_write
= SWAP_CLUSTER_MAX
,
675 .range_end
= LLONG_MAX
,
681 * The large shmem folio can be split if CONFIG_THP_SWAP is
682 * not enabled or contiguous swap entries are failed to
685 if (shmem_mapping(mapping
) && folio_test_large(folio
))
686 wbc
.list
= folio_list
;
688 folio_set_reclaim(folio
);
689 res
= mapping
->a_ops
->writepage(&folio
->page
, &wbc
);
691 handle_write_error(mapping
, folio
, res
);
692 if (res
== AOP_WRITEPAGE_ACTIVATE
) {
693 folio_clear_reclaim(folio
);
694 return PAGE_ACTIVATE
;
697 if (!folio_test_writeback(folio
)) {
698 /* synchronous write or broken a_ops? */
699 folio_clear_reclaim(folio
);
701 trace_mm_vmscan_write_folio(folio
);
702 node_stat_add_folio(folio
, NR_VMSCAN_WRITE
);
710 * Same as remove_mapping, but if the folio is removed from the mapping, it
711 * gets returned with a refcount of 0.
713 static int __remove_mapping(struct address_space
*mapping
, struct folio
*folio
,
714 bool reclaimed
, struct mem_cgroup
*target_memcg
)
719 BUG_ON(!folio_test_locked(folio
));
720 BUG_ON(mapping
!= folio_mapping(folio
));
722 if (!folio_test_swapcache(folio
))
723 spin_lock(&mapping
->host
->i_lock
);
724 xa_lock_irq(&mapping
->i_pages
);
726 * The non racy check for a busy folio.
728 * Must be careful with the order of the tests. When someone has
729 * a ref to the folio, it may be possible that they dirty it then
730 * drop the reference. So if the dirty flag is tested before the
731 * refcount here, then the following race may occur:
733 * get_user_pages(&page);
734 * [user mapping goes away]
736 * !folio_test_dirty(folio) [good]
737 * folio_set_dirty(folio);
739 * !refcount(folio) [good, discard it]
741 * [oops, our write_to data is lost]
743 * Reversing the order of the tests ensures such a situation cannot
744 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
745 * load is not satisfied before that of folio->_refcount.
747 * Note that if the dirty flag is always set via folio_mark_dirty,
748 * and thus under the i_pages lock, then this ordering is not required.
750 refcount
= 1 + folio_nr_pages(folio
);
751 if (!folio_ref_freeze(folio
, refcount
))
753 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
754 if (unlikely(folio_test_dirty(folio
))) {
755 folio_ref_unfreeze(folio
, refcount
);
759 if (folio_test_swapcache(folio
)) {
760 swp_entry_t swap
= folio
->swap
;
762 if (reclaimed
&& !mapping_exiting(mapping
))
763 shadow
= workingset_eviction(folio
, target_memcg
);
764 __delete_from_swap_cache(folio
, swap
, shadow
);
765 mem_cgroup_swapout(folio
, swap
);
766 xa_unlock_irq(&mapping
->i_pages
);
767 put_swap_folio(folio
, swap
);
769 void (*free_folio
)(struct folio
*);
771 free_folio
= mapping
->a_ops
->free_folio
;
773 * Remember a shadow entry for reclaimed file cache in
774 * order to detect refaults, thus thrashing, later on.
776 * But don't store shadows in an address space that is
777 * already exiting. This is not just an optimization,
778 * inode reclaim needs to empty out the radix tree or
779 * the nodes are lost. Don't plant shadows behind its
782 * We also don't store shadows for DAX mappings because the
783 * only page cache folios found in these are zero pages
784 * covering holes, and because we don't want to mix DAX
785 * exceptional entries and shadow exceptional entries in the
786 * same address_space.
788 if (reclaimed
&& folio_is_file_lru(folio
) &&
789 !mapping_exiting(mapping
) && !dax_mapping(mapping
))
790 shadow
= workingset_eviction(folio
, target_memcg
);
791 __filemap_remove_folio(folio
, shadow
);
792 xa_unlock_irq(&mapping
->i_pages
);
793 if (mapping_shrinkable(mapping
))
794 inode_add_lru(mapping
->host
);
795 spin_unlock(&mapping
->host
->i_lock
);
804 xa_unlock_irq(&mapping
->i_pages
);
805 if (!folio_test_swapcache(folio
))
806 spin_unlock(&mapping
->host
->i_lock
);
811 * remove_mapping() - Attempt to remove a folio from its mapping.
812 * @mapping: The address space.
813 * @folio: The folio to remove.
815 * If the folio is dirty, under writeback or if someone else has a ref
816 * on it, removal will fail.
817 * Return: The number of pages removed from the mapping. 0 if the folio
818 * could not be removed.
819 * Context: The caller should have a single refcount on the folio and
822 long remove_mapping(struct address_space
*mapping
, struct folio
*folio
)
824 if (__remove_mapping(mapping
, folio
, false, NULL
)) {
826 * Unfreezing the refcount with 1 effectively
827 * drops the pagecache ref for us without requiring another
830 folio_ref_unfreeze(folio
, 1);
831 return folio_nr_pages(folio
);
837 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
838 * @folio: Folio to be returned to an LRU list.
840 * Add previously isolated @folio to appropriate LRU list.
841 * The folio may still be unevictable for other reasons.
843 * Context: lru_lock must not be held, interrupts must be enabled.
845 void folio_putback_lru(struct folio
*folio
)
847 folio_add_lru(folio
);
848 folio_put(folio
); /* drop ref from isolate */
851 enum folio_references
{
853 FOLIOREF_RECLAIM_CLEAN
,
858 static enum folio_references
folio_check_references(struct folio
*folio
,
859 struct scan_control
*sc
)
861 int referenced_ptes
, referenced_folio
;
862 unsigned long vm_flags
;
864 referenced_ptes
= folio_referenced(folio
, 1, sc
->target_mem_cgroup
,
866 referenced_folio
= folio_test_clear_referenced(folio
);
869 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
870 * Let the folio, now marked Mlocked, be moved to the unevictable list.
872 if (vm_flags
& VM_LOCKED
)
873 return FOLIOREF_ACTIVATE
;
876 * There are two cases to consider.
877 * 1) Rmap lock contention: rotate.
878 * 2) Skip the non-shared swapbacked folio mapped solely by
879 * the exiting or OOM-reaped process.
881 if (referenced_ptes
== -1)
882 return FOLIOREF_KEEP
;
884 if (referenced_ptes
) {
886 * All mapped folios start out with page table
887 * references from the instantiating fault, so we need
888 * to look twice if a mapped file/anon folio is used more
891 * Mark it and spare it for another trip around the
892 * inactive list. Another page table reference will
893 * lead to its activation.
895 * Note: the mark is set for activated folios as well
896 * so that recently deactivated but used folios are
899 folio_set_referenced(folio
);
901 if (referenced_folio
|| referenced_ptes
> 1)
902 return FOLIOREF_ACTIVATE
;
905 * Activate file-backed executable folios after first usage.
907 if ((vm_flags
& VM_EXEC
) && folio_is_file_lru(folio
))
908 return FOLIOREF_ACTIVATE
;
910 return FOLIOREF_KEEP
;
913 /* Reclaim if clean, defer dirty folios to writeback */
914 if (referenced_folio
&& folio_is_file_lru(folio
))
915 return FOLIOREF_RECLAIM_CLEAN
;
917 return FOLIOREF_RECLAIM
;
920 /* Check if a folio is dirty or under writeback */
921 static void folio_check_dirty_writeback(struct folio
*folio
,
922 bool *dirty
, bool *writeback
)
924 struct address_space
*mapping
;
927 * Anonymous folios are not handled by flushers and must be written
928 * from reclaim context. Do not stall reclaim based on them.
929 * MADV_FREE anonymous folios are put into inactive file list too.
930 * They could be mistakenly treated as file lru. So further anon
933 if (!folio_is_file_lru(folio
) ||
934 (folio_test_anon(folio
) && !folio_test_swapbacked(folio
))) {
940 /* By default assume that the folio flags are accurate */
941 *dirty
= folio_test_dirty(folio
);
942 *writeback
= folio_test_writeback(folio
);
944 /* Verify dirty/writeback state if the filesystem supports it */
945 if (!folio_test_private(folio
))
948 mapping
= folio_mapping(folio
);
949 if (mapping
&& mapping
->a_ops
->is_dirty_writeback
)
950 mapping
->a_ops
->is_dirty_writeback(folio
, dirty
, writeback
);
953 struct folio
*alloc_migrate_folio(struct folio
*src
, unsigned long private)
956 nodemask_t
*allowed_mask
;
957 struct migration_target_control
*mtc
;
959 mtc
= (struct migration_target_control
*)private;
961 allowed_mask
= mtc
->nmask
;
963 * make sure we allocate from the target node first also trying to
964 * demote or reclaim pages from the target node via kswapd if we are
965 * low on free memory on target node. If we don't do this and if
966 * we have free memory on the slower(lower) memtier, we would start
967 * allocating pages from slower(lower) memory tiers without even forcing
968 * a demotion of cold pages from the target memtier. This can result
969 * in the kernel placing hot pages in slower(lower) memory tiers.
972 mtc
->gfp_mask
|= __GFP_THISNODE
;
973 dst
= alloc_migration_target(src
, (unsigned long)mtc
);
977 mtc
->gfp_mask
&= ~__GFP_THISNODE
;
978 mtc
->nmask
= allowed_mask
;
980 return alloc_migration_target(src
, (unsigned long)mtc
);
984 * Take folios on @demote_folios and attempt to demote them to another node.
985 * Folios which are not demoted are left on @demote_folios.
987 static unsigned int demote_folio_list(struct list_head
*demote_folios
,
988 struct pglist_data
*pgdat
)
990 int target_nid
= next_demotion_node(pgdat
->node_id
);
991 unsigned int nr_succeeded
;
992 nodemask_t allowed_mask
;
994 struct migration_target_control mtc
= {
996 * Allocate from 'node', or fail quickly and quietly.
997 * When this happens, 'page' will likely just be discarded
998 * instead of migrated.
1000 .gfp_mask
= (GFP_HIGHUSER_MOVABLE
& ~__GFP_RECLAIM
) | __GFP_NOWARN
|
1001 __GFP_NOMEMALLOC
| GFP_NOWAIT
,
1003 .nmask
= &allowed_mask
,
1004 .reason
= MR_DEMOTION
,
1007 if (list_empty(demote_folios
))
1010 if (target_nid
== NUMA_NO_NODE
)
1013 node_get_allowed_targets(pgdat
, &allowed_mask
);
1015 /* Demotion ignores all cpuset and mempolicy settings */
1016 migrate_pages(demote_folios
, alloc_migrate_folio
, NULL
,
1017 (unsigned long)&mtc
, MIGRATE_ASYNC
, MR_DEMOTION
,
1020 return nr_succeeded
;
1023 static bool may_enter_fs(struct folio
*folio
, gfp_t gfp_mask
)
1025 if (gfp_mask
& __GFP_FS
)
1027 if (!folio_test_swapcache(folio
) || !(gfp_mask
& __GFP_IO
))
1030 * We can "enter_fs" for swap-cache with only __GFP_IO
1031 * providing this isn't SWP_FS_OPS.
1032 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1033 * but that will never affect SWP_FS_OPS, so the data_race
1036 return !data_race(folio_swap_flags(folio
) & SWP_FS_OPS
);
1040 * shrink_folio_list() returns the number of reclaimed pages
1042 static unsigned int shrink_folio_list(struct list_head
*folio_list
,
1043 struct pglist_data
*pgdat
, struct scan_control
*sc
,
1044 struct reclaim_stat
*stat
, bool ignore_references
)
1046 struct folio_batch free_folios
;
1047 LIST_HEAD(ret_folios
);
1048 LIST_HEAD(demote_folios
);
1049 unsigned int nr_reclaimed
= 0;
1050 unsigned int pgactivate
= 0;
1051 bool do_demote_pass
;
1052 struct swap_iocb
*plug
= NULL
;
1054 folio_batch_init(&free_folios
);
1055 memset(stat
, 0, sizeof(*stat
));
1057 do_demote_pass
= can_demote(pgdat
->node_id
, sc
);
1060 while (!list_empty(folio_list
)) {
1061 struct address_space
*mapping
;
1062 struct folio
*folio
;
1063 enum folio_references references
= FOLIOREF_RECLAIM
;
1064 bool dirty
, writeback
;
1065 unsigned int nr_pages
;
1069 folio
= lru_to_folio(folio_list
);
1070 list_del(&folio
->lru
);
1072 if (!folio_trylock(folio
))
1075 VM_BUG_ON_FOLIO(folio_test_active(folio
), folio
);
1077 nr_pages
= folio_nr_pages(folio
);
1079 /* Account the number of base pages */
1080 sc
->nr_scanned
+= nr_pages
;
1082 if (unlikely(!folio_evictable(folio
)))
1083 goto activate_locked
;
1085 if (!sc
->may_unmap
&& folio_mapped(folio
))
1088 /* folio_update_gen() tried to promote this page? */
1089 if (lru_gen_enabled() && !ignore_references
&&
1090 folio_mapped(folio
) && folio_test_referenced(folio
))
1094 * The number of dirty pages determines if a node is marked
1095 * reclaim_congested. kswapd will stall and start writing
1096 * folios if the tail of the LRU is all dirty unqueued folios.
1098 folio_check_dirty_writeback(folio
, &dirty
, &writeback
);
1099 if (dirty
|| writeback
)
1100 stat
->nr_dirty
+= nr_pages
;
1102 if (dirty
&& !writeback
)
1103 stat
->nr_unqueued_dirty
+= nr_pages
;
1106 * Treat this folio as congested if folios are cycling
1107 * through the LRU so quickly that the folios marked
1108 * for immediate reclaim are making it to the end of
1109 * the LRU a second time.
1111 if (writeback
&& folio_test_reclaim(folio
))
1112 stat
->nr_congested
+= nr_pages
;
1115 * If a folio at the tail of the LRU is under writeback, there
1116 * are three cases to consider.
1118 * 1) If reclaim is encountering an excessive number
1119 * of folios under writeback and this folio has both
1120 * the writeback and reclaim flags set, then it
1121 * indicates that folios are being queued for I/O but
1122 * are being recycled through the LRU before the I/O
1123 * can complete. Waiting on the folio itself risks an
1124 * indefinite stall if it is impossible to writeback
1125 * the folio due to I/O error or disconnected storage
1126 * so instead note that the LRU is being scanned too
1127 * quickly and the caller can stall after the folio
1128 * list has been processed.
1130 * 2) Global or new memcg reclaim encounters a folio that is
1131 * not marked for immediate reclaim, or the caller does not
1132 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1133 * not to fs). In this case mark the folio for immediate
1134 * reclaim and continue scanning.
1136 * Require may_enter_fs() because we would wait on fs, which
1137 * may not have submitted I/O yet. And the loop driver might
1138 * enter reclaim, and deadlock if it waits on a folio for
1139 * which it is needed to do the write (loop masks off
1140 * __GFP_IO|__GFP_FS for this reason); but more thought
1141 * would probably show more reasons.
1143 * 3) Legacy memcg encounters a folio that already has the
1144 * reclaim flag set. memcg does not have any dirty folio
1145 * throttling so we could easily OOM just because too many
1146 * folios are in writeback and there is nothing else to
1147 * reclaim. Wait for the writeback to complete.
1149 * In cases 1) and 2) we activate the folios to get them out of
1150 * the way while we continue scanning for clean folios on the
1151 * inactive list and refilling from the active list. The
1152 * observation here is that waiting for disk writes is more
1153 * expensive than potentially causing reloads down the line.
1154 * Since they're marked for immediate reclaim, they won't put
1155 * memory pressure on the cache working set any longer than it
1156 * takes to write them to disk.
1158 if (folio_test_writeback(folio
)) {
1160 if (current_is_kswapd() &&
1161 folio_test_reclaim(folio
) &&
1162 test_bit(PGDAT_WRITEBACK
, &pgdat
->flags
)) {
1163 stat
->nr_immediate
+= nr_pages
;
1164 goto activate_locked
;
1167 } else if (writeback_throttling_sane(sc
) ||
1168 !folio_test_reclaim(folio
) ||
1169 !may_enter_fs(folio
, sc
->gfp_mask
)) {
1171 * This is slightly racy -
1172 * folio_end_writeback() might have
1173 * just cleared the reclaim flag, then
1174 * setting the reclaim flag here ends up
1175 * interpreted as the readahead flag - but
1176 * that does not matter enough to care.
1177 * What we do want is for this folio to
1178 * have the reclaim flag set next time
1179 * memcg reclaim reaches the tests above,
1180 * so it will then wait for writeback to
1181 * avoid OOM; and it's also appropriate
1182 * in global reclaim.
1184 folio_set_reclaim(folio
);
1185 stat
->nr_writeback
+= nr_pages
;
1186 goto activate_locked
;
1190 folio_unlock(folio
);
1191 folio_wait_writeback(folio
);
1192 /* then go back and try same folio again */
1193 list_add_tail(&folio
->lru
, folio_list
);
1198 if (!ignore_references
)
1199 references
= folio_check_references(folio
, sc
);
1201 switch (references
) {
1202 case FOLIOREF_ACTIVATE
:
1203 goto activate_locked
;
1205 stat
->nr_ref_keep
+= nr_pages
;
1207 case FOLIOREF_RECLAIM
:
1208 case FOLIOREF_RECLAIM_CLEAN
:
1209 ; /* try to reclaim the folio below */
1213 * Before reclaiming the folio, try to relocate
1214 * its contents to another node.
1216 if (do_demote_pass
&&
1217 (thp_migration_supported() || !folio_test_large(folio
))) {
1218 list_add(&folio
->lru
, &demote_folios
);
1219 folio_unlock(folio
);
1224 * Anonymous process memory has backing store?
1225 * Try to allocate it some swap space here.
1226 * Lazyfree folio could be freed directly
1228 if (folio_test_anon(folio
) && folio_test_swapbacked(folio
)) {
1229 if (!folio_test_swapcache(folio
)) {
1230 if (!(sc
->gfp_mask
& __GFP_IO
))
1232 if (folio_maybe_dma_pinned(folio
))
1234 if (folio_test_large(folio
)) {
1235 /* cannot split folio, skip it */
1236 if (!can_split_folio(folio
, 1, NULL
))
1237 goto activate_locked
;
1239 * Split partially mapped folios right away.
1240 * We can free the unmapped pages without IO.
1242 if (data_race(!list_empty(&folio
->_deferred_list
) &&
1243 folio_test_partially_mapped(folio
)) &&
1244 split_folio_to_list(folio
, folio_list
))
1245 goto activate_locked
;
1247 if (!add_to_swap(folio
)) {
1248 int __maybe_unused order
= folio_order(folio
);
1250 if (!folio_test_large(folio
))
1251 goto activate_locked_split
;
1252 /* Fallback to swap normal pages */
1253 if (split_folio_to_list(folio
, folio_list
))
1254 goto activate_locked
;
1255 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1256 if (nr_pages
>= HPAGE_PMD_NR
) {
1257 count_memcg_folio_events(folio
,
1258 THP_SWPOUT_FALLBACK
, 1);
1259 count_vm_event(THP_SWPOUT_FALLBACK
);
1262 count_mthp_stat(order
, MTHP_STAT_SWPOUT_FALLBACK
);
1263 if (!add_to_swap(folio
))
1264 goto activate_locked_split
;
1270 * If the folio was split above, the tail pages will make
1271 * their own pass through this function and be accounted
1274 if ((nr_pages
> 1) && !folio_test_large(folio
)) {
1275 sc
->nr_scanned
-= (nr_pages
- 1);
1280 * The folio is mapped into the page tables of one or more
1281 * processes. Try to unmap it here.
1283 if (folio_mapped(folio
)) {
1284 enum ttu_flags flags
= TTU_BATCH_FLUSH
;
1285 bool was_swapbacked
= folio_test_swapbacked(folio
);
1287 if (folio_test_pmd_mappable(folio
))
1288 flags
|= TTU_SPLIT_HUGE_PMD
;
1290 * Without TTU_SYNC, try_to_unmap will only begin to
1291 * hold PTL from the first present PTE within a large
1292 * folio. Some initial PTEs might be skipped due to
1293 * races with parallel PTE writes in which PTEs can be
1294 * cleared temporarily before being written new present
1295 * values. This will lead to a large folio is still
1296 * mapped while some subpages have been partially
1297 * unmapped after try_to_unmap; TTU_SYNC helps
1298 * try_to_unmap acquire PTL from the first PTE,
1299 * eliminating the influence of temporary PTE values.
1301 if (folio_test_large(folio
))
1304 try_to_unmap(folio
, flags
);
1305 if (folio_mapped(folio
)) {
1306 stat
->nr_unmap_fail
+= nr_pages
;
1307 if (!was_swapbacked
&&
1308 folio_test_swapbacked(folio
))
1309 stat
->nr_lazyfree_fail
+= nr_pages
;
1310 goto activate_locked
;
1315 * Folio is unmapped now so it cannot be newly pinned anymore.
1316 * No point in trying to reclaim folio if it is pinned.
1317 * Furthermore we don't want to reclaim underlying fs metadata
1318 * if the folio is pinned and thus potentially modified by the
1319 * pinning process as that may upset the filesystem.
1321 if (folio_maybe_dma_pinned(folio
))
1322 goto activate_locked
;
1324 mapping
= folio_mapping(folio
);
1325 if (folio_test_dirty(folio
)) {
1327 * Only kswapd can writeback filesystem folios
1328 * to avoid risk of stack overflow. But avoid
1329 * injecting inefficient single-folio I/O into
1330 * flusher writeback as much as possible: only
1331 * write folios when we've encountered many
1332 * dirty folios, and when we've already scanned
1333 * the rest of the LRU for clean folios and see
1334 * the same dirty folios again (with the reclaim
1337 if (folio_is_file_lru(folio
) &&
1338 (!current_is_kswapd() ||
1339 !folio_test_reclaim(folio
) ||
1340 !test_bit(PGDAT_DIRTY
, &pgdat
->flags
))) {
1342 * Immediately reclaim when written back.
1343 * Similar in principle to folio_deactivate()
1344 * except we already have the folio isolated
1345 * and know it's dirty
1347 node_stat_mod_folio(folio
, NR_VMSCAN_IMMEDIATE
,
1349 folio_set_reclaim(folio
);
1351 goto activate_locked
;
1354 if (references
== FOLIOREF_RECLAIM_CLEAN
)
1356 if (!may_enter_fs(folio
, sc
->gfp_mask
))
1358 if (!sc
->may_writepage
)
1362 * Folio is dirty. Flush the TLB if a writable entry
1363 * potentially exists to avoid CPU writes after I/O
1364 * starts and then write it out here.
1366 try_to_unmap_flush_dirty();
1367 switch (pageout(folio
, mapping
, &plug
, folio_list
)) {
1372 * If shmem folio is split when writeback to swap,
1373 * the tail pages will make their own pass through
1374 * this function and be accounted then.
1376 if (nr_pages
> 1 && !folio_test_large(folio
)) {
1377 sc
->nr_scanned
-= (nr_pages
- 1);
1380 goto activate_locked
;
1382 if (nr_pages
> 1 && !folio_test_large(folio
)) {
1383 sc
->nr_scanned
-= (nr_pages
- 1);
1386 stat
->nr_pageout
+= nr_pages
;
1388 if (folio_test_writeback(folio
))
1390 if (folio_test_dirty(folio
))
1394 * A synchronous write - probably a ramdisk. Go
1395 * ahead and try to reclaim the folio.
1397 if (!folio_trylock(folio
))
1399 if (folio_test_dirty(folio
) ||
1400 folio_test_writeback(folio
))
1402 mapping
= folio_mapping(folio
);
1405 ; /* try to free the folio below */
1410 * If the folio has buffers, try to free the buffer
1411 * mappings associated with this folio. If we succeed
1412 * we try to free the folio as well.
1414 * We do this even if the folio is dirty.
1415 * filemap_release_folio() does not perform I/O, but it
1416 * is possible for a folio to have the dirty flag set,
1417 * but it is actually clean (all its buffers are clean).
1418 * This happens if the buffers were written out directly,
1419 * with submit_bh(). ext3 will do this, as well as
1420 * the blockdev mapping. filemap_release_folio() will
1421 * discover that cleanness and will drop the buffers
1422 * and mark the folio clean - it can be freed.
1424 * Rarely, folios can have buffers and no ->mapping.
1425 * These are the folios which were not successfully
1426 * invalidated in truncate_cleanup_folio(). We try to
1427 * drop those buffers here and if that worked, and the
1428 * folio is no longer mapped into process address space
1429 * (refcount == 1) it can be freed. Otherwise, leave
1430 * the folio on the LRU so it is swappable.
1432 if (folio_needs_release(folio
)) {
1433 if (!filemap_release_folio(folio
, sc
->gfp_mask
))
1434 goto activate_locked
;
1435 if (!mapping
&& folio_ref_count(folio
) == 1) {
1436 folio_unlock(folio
);
1437 if (folio_put_testzero(folio
))
1441 * rare race with speculative reference.
1442 * the speculative reference will free
1443 * this folio shortly, so we may
1444 * increment nr_reclaimed here (and
1445 * leave it off the LRU).
1447 nr_reclaimed
+= nr_pages
;
1453 if (folio_test_anon(folio
) && !folio_test_swapbacked(folio
)) {
1454 /* follow __remove_mapping for reference */
1455 if (!folio_ref_freeze(folio
, 1))
1458 * The folio has only one reference left, which is
1459 * from the isolation. After the caller puts the
1460 * folio back on the lru and drops the reference, the
1461 * folio will be freed anyway. It doesn't matter
1462 * which lru it goes on. So we don't bother checking
1463 * the dirty flag here.
1465 count_vm_events(PGLAZYFREED
, nr_pages
);
1466 count_memcg_folio_events(folio
, PGLAZYFREED
, nr_pages
);
1467 } else if (!mapping
|| !__remove_mapping(mapping
, folio
, true,
1468 sc
->target_mem_cgroup
))
1471 folio_unlock(folio
);
1474 * Folio may get swapped out as a whole, need to account
1477 nr_reclaimed
+= nr_pages
;
1479 folio_unqueue_deferred_split(folio
);
1480 if (folio_batch_add(&free_folios
, folio
) == 0) {
1481 mem_cgroup_uncharge_folios(&free_folios
);
1482 try_to_unmap_flush();
1483 free_unref_folios(&free_folios
);
1487 activate_locked_split
:
1489 * The tail pages that are failed to add into swap cache
1490 * reach here. Fixup nr_scanned and nr_pages.
1493 sc
->nr_scanned
-= (nr_pages
- 1);
1497 /* Not a candidate for swapping, so reclaim swap space. */
1498 if (folio_test_swapcache(folio
) &&
1499 (mem_cgroup_swap_full(folio
) || folio_test_mlocked(folio
)))
1500 folio_free_swap(folio
);
1501 VM_BUG_ON_FOLIO(folio_test_active(folio
), folio
);
1502 if (!folio_test_mlocked(folio
)) {
1503 int type
= folio_is_file_lru(folio
);
1504 folio_set_active(folio
);
1505 stat
->nr_activate
[type
] += nr_pages
;
1506 count_memcg_folio_events(folio
, PGACTIVATE
, nr_pages
);
1509 folio_unlock(folio
);
1511 list_add(&folio
->lru
, &ret_folios
);
1512 VM_BUG_ON_FOLIO(folio_test_lru(folio
) ||
1513 folio_test_unevictable(folio
), folio
);
1515 /* 'folio_list' is always empty here */
1517 /* Migrate folios selected for demotion */
1518 stat
->nr_demoted
= demote_folio_list(&demote_folios
, pgdat
);
1519 nr_reclaimed
+= stat
->nr_demoted
;
1520 /* Folios that could not be demoted are still in @demote_folios */
1521 if (!list_empty(&demote_folios
)) {
1522 /* Folios which weren't demoted go back on @folio_list */
1523 list_splice_init(&demote_folios
, folio_list
);
1526 * goto retry to reclaim the undemoted folios in folio_list if
1529 * Reclaiming directly from top tier nodes is not often desired
1530 * due to it breaking the LRU ordering: in general memory
1531 * should be reclaimed from lower tier nodes and demoted from
1534 * However, disabling reclaim from top tier nodes entirely
1535 * would cause ooms in edge scenarios where lower tier memory
1536 * is unreclaimable for whatever reason, eg memory being
1537 * mlocked or too hot to reclaim. We can disable reclaim
1538 * from top tier nodes in proactive reclaim though as that is
1539 * not real memory pressure.
1541 if (!sc
->proactive
) {
1542 do_demote_pass
= false;
1547 pgactivate
= stat
->nr_activate
[0] + stat
->nr_activate
[1];
1549 mem_cgroup_uncharge_folios(&free_folios
);
1550 try_to_unmap_flush();
1551 free_unref_folios(&free_folios
);
1553 list_splice(&ret_folios
, folio_list
);
1554 count_vm_events(PGACTIVATE
, pgactivate
);
1557 swap_write_unplug(plug
);
1558 return nr_reclaimed
;
1561 unsigned int reclaim_clean_pages_from_list(struct zone
*zone
,
1562 struct list_head
*folio_list
)
1564 struct scan_control sc
= {
1565 .gfp_mask
= GFP_KERNEL
,
1568 struct reclaim_stat stat
;
1569 unsigned int nr_reclaimed
;
1570 struct folio
*folio
, *next
;
1571 LIST_HEAD(clean_folios
);
1572 unsigned int noreclaim_flag
;
1574 list_for_each_entry_safe(folio
, next
, folio_list
, lru
) {
1575 if (!folio_test_hugetlb(folio
) && folio_is_file_lru(folio
) &&
1576 !folio_test_dirty(folio
) && !__folio_test_movable(folio
) &&
1577 !folio_test_unevictable(folio
)) {
1578 folio_clear_active(folio
);
1579 list_move(&folio
->lru
, &clean_folios
);
1584 * We should be safe here since we are only dealing with file pages and
1585 * we are not kswapd and therefore cannot write dirty file pages. But
1586 * call memalloc_noreclaim_save() anyway, just in case these conditions
1587 * change in the future.
1589 noreclaim_flag
= memalloc_noreclaim_save();
1590 nr_reclaimed
= shrink_folio_list(&clean_folios
, zone
->zone_pgdat
, &sc
,
1592 memalloc_noreclaim_restore(noreclaim_flag
);
1594 list_splice(&clean_folios
, folio_list
);
1595 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
1596 -(long)nr_reclaimed
);
1598 * Since lazyfree pages are isolated from file LRU from the beginning,
1599 * they will rotate back to anonymous LRU in the end if it failed to
1600 * discard so isolated count will be mismatched.
1601 * Compensate the isolated count for both LRU lists.
1603 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_ANON
,
1604 stat
.nr_lazyfree_fail
);
1605 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
1606 -(long)stat
.nr_lazyfree_fail
);
1607 return nr_reclaimed
;
1611 * Update LRU sizes after isolating pages. The LRU size updates must
1612 * be complete before mem_cgroup_update_lru_size due to a sanity check.
1614 static __always_inline
void update_lru_sizes(struct lruvec
*lruvec
,
1615 enum lru_list lru
, unsigned long *nr_zone_taken
)
1619 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1620 if (!nr_zone_taken
[zid
])
1623 update_lru_size(lruvec
, lru
, zid
, -nr_zone_taken
[zid
]);
1629 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1631 * lruvec->lru_lock is heavily contended. Some of the functions that
1632 * shrink the lists perform better by taking out a batch of pages
1633 * and working on them outside the LRU lock.
1635 * For pagecache intensive workloads, this function is the hottest
1636 * spot in the kernel (apart from copy_*_user functions).
1638 * Lru_lock must be held before calling this function.
1640 * @nr_to_scan: The number of eligible pages to look through on the list.
1641 * @lruvec: The LRU vector to pull pages from.
1642 * @dst: The temp list to put pages on to.
1643 * @nr_scanned: The number of pages that were scanned.
1644 * @sc: The scan_control struct for this reclaim session
1645 * @lru: LRU list id for isolating
1647 * returns how many pages were moved onto *@dst.
1649 static unsigned long isolate_lru_folios(unsigned long nr_to_scan
,
1650 struct lruvec
*lruvec
, struct list_head
*dst
,
1651 unsigned long *nr_scanned
, struct scan_control
*sc
,
1654 struct list_head
*src
= &lruvec
->lists
[lru
];
1655 unsigned long nr_taken
= 0;
1656 unsigned long nr_zone_taken
[MAX_NR_ZONES
] = { 0 };
1657 unsigned long nr_skipped
[MAX_NR_ZONES
] = { 0, };
1658 unsigned long skipped
= 0;
1659 unsigned long scan
, total_scan
, nr_pages
;
1660 LIST_HEAD(folios_skipped
);
1664 while (scan
< nr_to_scan
&& !list_empty(src
)) {
1665 struct list_head
*move_to
= src
;
1666 struct folio
*folio
;
1668 folio
= lru_to_folio(src
);
1669 prefetchw_prev_lru_folio(folio
, src
, flags
);
1671 nr_pages
= folio_nr_pages(folio
);
1672 total_scan
+= nr_pages
;
1674 if (folio_zonenum(folio
) > sc
->reclaim_idx
) {
1675 nr_skipped
[folio_zonenum(folio
)] += nr_pages
;
1676 move_to
= &folios_skipped
;
1681 * Do not count skipped folios because that makes the function
1682 * return with no isolated folios if the LRU mostly contains
1683 * ineligible folios. This causes the VM to not reclaim any
1684 * folios, triggering a premature OOM.
1685 * Account all pages in a folio.
1689 if (!folio_test_lru(folio
))
1691 if (!sc
->may_unmap
&& folio_mapped(folio
))
1695 * Be careful not to clear the lru flag until after we're
1696 * sure the folio is not being freed elsewhere -- the
1697 * folio release code relies on it.
1699 if (unlikely(!folio_try_get(folio
)))
1702 if (!folio_test_clear_lru(folio
)) {
1703 /* Another thread is already isolating this folio */
1708 nr_taken
+= nr_pages
;
1709 nr_zone_taken
[folio_zonenum(folio
)] += nr_pages
;
1712 list_move(&folio
->lru
, move_to
);
1716 * Splice any skipped folios to the start of the LRU list. Note that
1717 * this disrupts the LRU order when reclaiming for lower zones but
1718 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1719 * scanning would soon rescan the same folios to skip and waste lots
1722 if (!list_empty(&folios_skipped
)) {
1725 list_splice(&folios_skipped
, src
);
1726 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1727 if (!nr_skipped
[zid
])
1730 __count_zid_vm_events(PGSCAN_SKIP
, zid
, nr_skipped
[zid
]);
1731 skipped
+= nr_skipped
[zid
];
1734 *nr_scanned
= total_scan
;
1735 trace_mm_vmscan_lru_isolate(sc
->reclaim_idx
, sc
->order
, nr_to_scan
,
1736 total_scan
, skipped
, nr_taken
, lru
);
1737 update_lru_sizes(lruvec
, lru
, nr_zone_taken
);
1742 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
1743 * @folio: Folio to isolate from its LRU list.
1745 * Isolate a @folio from an LRU list and adjust the vmstat statistic
1746 * corresponding to whatever LRU list the folio was on.
1748 * The folio will have its LRU flag cleared. If it was found on the
1749 * active list, it will have the Active flag set. If it was found on the
1750 * unevictable list, it will have the Unevictable flag set. These flags
1751 * may need to be cleared by the caller before letting the page go.
1755 * (1) Must be called with an elevated refcount on the folio. This is a
1756 * fundamental difference from isolate_lru_folios() (which is called
1757 * without a stable reference).
1758 * (2) The lru_lock must not be held.
1759 * (3) Interrupts must be enabled.
1761 * Return: true if the folio was removed from an LRU list.
1762 * false if the folio was not on an LRU list.
1764 bool folio_isolate_lru(struct folio
*folio
)
1768 VM_BUG_ON_FOLIO(!folio_ref_count(folio
), folio
);
1770 if (folio_test_clear_lru(folio
)) {
1771 struct lruvec
*lruvec
;
1774 lruvec
= folio_lruvec_lock_irq(folio
);
1775 lruvec_del_folio(lruvec
, folio
);
1776 unlock_page_lruvec_irq(lruvec
);
1784 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1785 * then get rescheduled. When there are massive number of tasks doing page
1786 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1787 * the LRU list will go small and be scanned faster than necessary, leading to
1788 * unnecessary swapping, thrashing and OOM.
1790 static bool too_many_isolated(struct pglist_data
*pgdat
, int file
,
1791 struct scan_control
*sc
)
1793 unsigned long inactive
, isolated
;
1796 if (current_is_kswapd())
1799 if (!writeback_throttling_sane(sc
))
1803 inactive
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
1804 isolated
= node_page_state(pgdat
, NR_ISOLATED_FILE
);
1806 inactive
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
1807 isolated
= node_page_state(pgdat
, NR_ISOLATED_ANON
);
1811 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1812 * won't get blocked by normal direct-reclaimers, forming a circular
1815 if (gfp_has_io_fs(sc
->gfp_mask
))
1818 too_many
= isolated
> inactive
;
1820 /* Wake up tasks throttled due to too_many_isolated. */
1822 wake_throttle_isolated(pgdat
);
1828 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
1830 * Returns the number of pages moved to the given lruvec.
1832 static unsigned int move_folios_to_lru(struct lruvec
*lruvec
,
1833 struct list_head
*list
)
1835 int nr_pages
, nr_moved
= 0;
1836 struct folio_batch free_folios
;
1838 folio_batch_init(&free_folios
);
1839 while (!list_empty(list
)) {
1840 struct folio
*folio
= lru_to_folio(list
);
1842 VM_BUG_ON_FOLIO(folio_test_lru(folio
), folio
);
1843 list_del(&folio
->lru
);
1844 if (unlikely(!folio_evictable(folio
))) {
1845 spin_unlock_irq(&lruvec
->lru_lock
);
1846 folio_putback_lru(folio
);
1847 spin_lock_irq(&lruvec
->lru_lock
);
1852 * The folio_set_lru needs to be kept here for list integrity.
1854 * #0 move_folios_to_lru #1 release_pages
1855 * if (!folio_put_testzero())
1856 * if (folio_put_testzero())
1857 * !lru //skip lru_lock
1859 * list_add(&folio->lru,)
1860 * list_add(&folio->lru,)
1862 folio_set_lru(folio
);
1864 if (unlikely(folio_put_testzero(folio
))) {
1865 __folio_clear_lru_flags(folio
);
1867 folio_unqueue_deferred_split(folio
);
1868 if (folio_batch_add(&free_folios
, folio
) == 0) {
1869 spin_unlock_irq(&lruvec
->lru_lock
);
1870 mem_cgroup_uncharge_folios(&free_folios
);
1871 free_unref_folios(&free_folios
);
1872 spin_lock_irq(&lruvec
->lru_lock
);
1879 * All pages were isolated from the same lruvec (and isolation
1880 * inhibits memcg migration).
1882 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio
, lruvec
), folio
);
1883 lruvec_add_folio(lruvec
, folio
);
1884 nr_pages
= folio_nr_pages(folio
);
1885 nr_moved
+= nr_pages
;
1886 if (folio_test_active(folio
))
1887 workingset_age_nonresident(lruvec
, nr_pages
);
1890 if (free_folios
.nr
) {
1891 spin_unlock_irq(&lruvec
->lru_lock
);
1892 mem_cgroup_uncharge_folios(&free_folios
);
1893 free_unref_folios(&free_folios
);
1894 spin_lock_irq(&lruvec
->lru_lock
);
1901 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
1902 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
1903 * we should not throttle. Otherwise it is safe to do so.
1905 static int current_may_throttle(void)
1907 return !(current
->flags
& PF_LOCAL_THROTTLE
);
1911 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1912 * of reclaimed pages
1914 static unsigned long shrink_inactive_list(unsigned long nr_to_scan
,
1915 struct lruvec
*lruvec
, struct scan_control
*sc
,
1918 LIST_HEAD(folio_list
);
1919 unsigned long nr_scanned
;
1920 unsigned int nr_reclaimed
= 0;
1921 unsigned long nr_taken
;
1922 struct reclaim_stat stat
;
1923 bool file
= is_file_lru(lru
);
1924 enum vm_event_item item
;
1925 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
1926 bool stalled
= false;
1928 while (unlikely(too_many_isolated(pgdat
, file
, sc
))) {
1932 /* wait a bit for the reclaimer. */
1934 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_ISOLATED
);
1936 /* We are about to die and free our memory. Return now. */
1937 if (fatal_signal_pending(current
))
1938 return SWAP_CLUSTER_MAX
;
1943 spin_lock_irq(&lruvec
->lru_lock
);
1945 nr_taken
= isolate_lru_folios(nr_to_scan
, lruvec
, &folio_list
,
1946 &nr_scanned
, sc
, lru
);
1948 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
1949 item
= PGSCAN_KSWAPD
+ reclaimer_offset();
1950 if (!cgroup_reclaim(sc
))
1951 __count_vm_events(item
, nr_scanned
);
1952 __count_memcg_events(lruvec_memcg(lruvec
), item
, nr_scanned
);
1953 __count_vm_events(PGSCAN_ANON
+ file
, nr_scanned
);
1955 spin_unlock_irq(&lruvec
->lru_lock
);
1960 nr_reclaimed
= shrink_folio_list(&folio_list
, pgdat
, sc
, &stat
, false);
1962 spin_lock_irq(&lruvec
->lru_lock
);
1963 move_folios_to_lru(lruvec
, &folio_list
);
1965 __mod_lruvec_state(lruvec
, PGDEMOTE_KSWAPD
+ reclaimer_offset(),
1967 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
1968 item
= PGSTEAL_KSWAPD
+ reclaimer_offset();
1969 if (!cgroup_reclaim(sc
))
1970 __count_vm_events(item
, nr_reclaimed
);
1971 __count_memcg_events(lruvec_memcg(lruvec
), item
, nr_reclaimed
);
1972 __count_vm_events(PGSTEAL_ANON
+ file
, nr_reclaimed
);
1973 spin_unlock_irq(&lruvec
->lru_lock
);
1975 lru_note_cost(lruvec
, file
, stat
.nr_pageout
, nr_scanned
- nr_reclaimed
);
1978 * If dirty folios are scanned that are not queued for IO, it
1979 * implies that flushers are not doing their job. This can
1980 * happen when memory pressure pushes dirty folios to the end of
1981 * the LRU before the dirty limits are breached and the dirty
1982 * data has expired. It can also happen when the proportion of
1983 * dirty folios grows not through writes but through memory
1984 * pressure reclaiming all the clean cache. And in some cases,
1985 * the flushers simply cannot keep up with the allocation
1986 * rate. Nudge the flusher threads in case they are asleep.
1988 if (stat
.nr_unqueued_dirty
== nr_taken
) {
1989 wakeup_flusher_threads(WB_REASON_VMSCAN
);
1991 * For cgroupv1 dirty throttling is achieved by waking up
1992 * the kernel flusher here and later waiting on folios
1993 * which are in writeback to finish (see shrink_folio_list()).
1995 * Flusher may not be able to issue writeback quickly
1996 * enough for cgroupv1 writeback throttling to work
1997 * on a large system.
1999 if (!writeback_throttling_sane(sc
))
2000 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_WRITEBACK
);
2003 sc
->nr
.dirty
+= stat
.nr_dirty
;
2004 sc
->nr
.congested
+= stat
.nr_congested
;
2005 sc
->nr
.unqueued_dirty
+= stat
.nr_unqueued_dirty
;
2006 sc
->nr
.writeback
+= stat
.nr_writeback
;
2007 sc
->nr
.immediate
+= stat
.nr_immediate
;
2008 sc
->nr
.taken
+= nr_taken
;
2010 sc
->nr
.file_taken
+= nr_taken
;
2012 trace_mm_vmscan_lru_shrink_inactive(pgdat
->node_id
,
2013 nr_scanned
, nr_reclaimed
, &stat
, sc
->priority
, file
);
2014 return nr_reclaimed
;
2018 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2020 * We move them the other way if the folio is referenced by one or more
2023 * If the folios are mostly unmapped, the processing is fast and it is
2024 * appropriate to hold lru_lock across the whole operation. But if
2025 * the folios are mapped, the processing is slow (folio_referenced()), so
2026 * we should drop lru_lock around each folio. It's impossible to balance
2027 * this, so instead we remove the folios from the LRU while processing them.
2028 * It is safe to rely on the active flag against the non-LRU folios in here
2029 * because nobody will play with that bit on a non-LRU folio.
2031 * The downside is that we have to touch folio->_refcount against each folio.
2032 * But we had to alter folio->flags anyway.
2034 static void shrink_active_list(unsigned long nr_to_scan
,
2035 struct lruvec
*lruvec
,
2036 struct scan_control
*sc
,
2039 unsigned long nr_taken
;
2040 unsigned long nr_scanned
;
2041 unsigned long vm_flags
;
2042 LIST_HEAD(l_hold
); /* The folios which were snipped off */
2043 LIST_HEAD(l_active
);
2044 LIST_HEAD(l_inactive
);
2045 unsigned nr_deactivate
, nr_activate
;
2046 unsigned nr_rotated
= 0;
2047 bool file
= is_file_lru(lru
);
2048 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2052 spin_lock_irq(&lruvec
->lru_lock
);
2054 nr_taken
= isolate_lru_folios(nr_to_scan
, lruvec
, &l_hold
,
2055 &nr_scanned
, sc
, lru
);
2057 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
2059 if (!cgroup_reclaim(sc
))
2060 __count_vm_events(PGREFILL
, nr_scanned
);
2061 __count_memcg_events(lruvec_memcg(lruvec
), PGREFILL
, nr_scanned
);
2063 spin_unlock_irq(&lruvec
->lru_lock
);
2065 while (!list_empty(&l_hold
)) {
2066 struct folio
*folio
;
2069 folio
= lru_to_folio(&l_hold
);
2070 list_del(&folio
->lru
);
2072 if (unlikely(!folio_evictable(folio
))) {
2073 folio_putback_lru(folio
);
2077 if (unlikely(buffer_heads_over_limit
)) {
2078 if (folio_needs_release(folio
) &&
2079 folio_trylock(folio
)) {
2080 filemap_release_folio(folio
, 0);
2081 folio_unlock(folio
);
2085 /* Referenced or rmap lock contention: rotate */
2086 if (folio_referenced(folio
, 0, sc
->target_mem_cgroup
,
2089 * Identify referenced, file-backed active folios and
2090 * give them one more trip around the active list. So
2091 * that executable code get better chances to stay in
2092 * memory under moderate memory pressure. Anon folios
2093 * are not likely to be evicted by use-once streaming
2094 * IO, plus JVM can create lots of anon VM_EXEC folios,
2095 * so we ignore them here.
2097 if ((vm_flags
& VM_EXEC
) && folio_is_file_lru(folio
)) {
2098 nr_rotated
+= folio_nr_pages(folio
);
2099 list_add(&folio
->lru
, &l_active
);
2104 folio_clear_active(folio
); /* we are de-activating */
2105 folio_set_workingset(folio
);
2106 list_add(&folio
->lru
, &l_inactive
);
2110 * Move folios back to the lru list.
2112 spin_lock_irq(&lruvec
->lru_lock
);
2114 nr_activate
= move_folios_to_lru(lruvec
, &l_active
);
2115 nr_deactivate
= move_folios_to_lru(lruvec
, &l_inactive
);
2117 __count_vm_events(PGDEACTIVATE
, nr_deactivate
);
2118 __count_memcg_events(lruvec_memcg(lruvec
), PGDEACTIVATE
, nr_deactivate
);
2120 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
2121 spin_unlock_irq(&lruvec
->lru_lock
);
2124 lru_note_cost(lruvec
, file
, 0, nr_rotated
);
2125 trace_mm_vmscan_lru_shrink_active(pgdat
->node_id
, nr_taken
, nr_activate
,
2126 nr_deactivate
, nr_rotated
, sc
->priority
, file
);
2129 static unsigned int reclaim_folio_list(struct list_head
*folio_list
,
2130 struct pglist_data
*pgdat
)
2132 struct reclaim_stat stat
;
2133 unsigned int nr_reclaimed
;
2134 struct folio
*folio
;
2135 struct scan_control sc
= {
2136 .gfp_mask
= GFP_KERNEL
,
2143 nr_reclaimed
= shrink_folio_list(folio_list
, pgdat
, &sc
, &stat
, true);
2144 while (!list_empty(folio_list
)) {
2145 folio
= lru_to_folio(folio_list
);
2146 list_del(&folio
->lru
);
2147 folio_putback_lru(folio
);
2149 trace_mm_vmscan_reclaim_pages(pgdat
->node_id
, sc
.nr_scanned
, nr_reclaimed
, &stat
);
2151 return nr_reclaimed
;
2154 unsigned long reclaim_pages(struct list_head
*folio_list
)
2157 unsigned int nr_reclaimed
= 0;
2158 LIST_HEAD(node_folio_list
);
2159 unsigned int noreclaim_flag
;
2161 if (list_empty(folio_list
))
2162 return nr_reclaimed
;
2164 noreclaim_flag
= memalloc_noreclaim_save();
2166 nid
= folio_nid(lru_to_folio(folio_list
));
2168 struct folio
*folio
= lru_to_folio(folio_list
);
2170 if (nid
== folio_nid(folio
)) {
2171 folio_clear_active(folio
);
2172 list_move(&folio
->lru
, &node_folio_list
);
2176 nr_reclaimed
+= reclaim_folio_list(&node_folio_list
, NODE_DATA(nid
));
2177 nid
= folio_nid(lru_to_folio(folio_list
));
2178 } while (!list_empty(folio_list
));
2180 nr_reclaimed
+= reclaim_folio_list(&node_folio_list
, NODE_DATA(nid
));
2182 memalloc_noreclaim_restore(noreclaim_flag
);
2184 return nr_reclaimed
;
2187 static unsigned long shrink_list(enum lru_list lru
, unsigned long nr_to_scan
,
2188 struct lruvec
*lruvec
, struct scan_control
*sc
)
2190 if (is_active_lru(lru
)) {
2191 if (sc
->may_deactivate
& (1 << is_file_lru(lru
)))
2192 shrink_active_list(nr_to_scan
, lruvec
, sc
, lru
);
2194 sc
->skipped_deactivate
= 1;
2198 return shrink_inactive_list(nr_to_scan
, lruvec
, sc
, lru
);
2202 * The inactive anon list should be small enough that the VM never has
2203 * to do too much work.
2205 * The inactive file list should be small enough to leave most memory
2206 * to the established workingset on the scan-resistant active list,
2207 * but large enough to avoid thrashing the aggregate readahead window.
2209 * Both inactive lists should also be large enough that each inactive
2210 * folio has a chance to be referenced again before it is reclaimed.
2212 * If that fails and refaulting is observed, the inactive list grows.
2214 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2215 * on this LRU, maintained by the pageout code. An inactive_ratio
2216 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2219 * memory ratio inactive
2220 * -------------------------------------
2229 static bool inactive_is_low(struct lruvec
*lruvec
, enum lru_list inactive_lru
)
2231 enum lru_list active_lru
= inactive_lru
+ LRU_ACTIVE
;
2232 unsigned long inactive
, active
;
2233 unsigned long inactive_ratio
;
2236 inactive
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ inactive_lru
);
2237 active
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ active_lru
);
2239 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
2241 inactive_ratio
= int_sqrt(10 * gb
);
2245 return inactive
* inactive_ratio
< active
;
2255 static void prepare_scan_control(pg_data_t
*pgdat
, struct scan_control
*sc
)
2258 struct lruvec
*target_lruvec
;
2260 if (lru_gen_enabled())
2263 target_lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
, pgdat
);
2266 * Flush the memory cgroup stats in rate-limited way as we don't need
2267 * most accurate stats here. We may switch to regular stats flushing
2268 * in the future once it is cheap enough.
2270 mem_cgroup_flush_stats_ratelimited(sc
->target_mem_cgroup
);
2273 * Determine the scan balance between anon and file LRUs.
2275 spin_lock_irq(&target_lruvec
->lru_lock
);
2276 sc
->anon_cost
= target_lruvec
->anon_cost
;
2277 sc
->file_cost
= target_lruvec
->file_cost
;
2278 spin_unlock_irq(&target_lruvec
->lru_lock
);
2281 * Target desirable inactive:active list ratios for the anon
2282 * and file LRU lists.
2284 if (!sc
->force_deactivate
) {
2285 unsigned long refaults
;
2288 * When refaults are being observed, it means a new
2289 * workingset is being established. Deactivate to get
2290 * rid of any stale active pages quickly.
2292 refaults
= lruvec_page_state(target_lruvec
,
2293 WORKINGSET_ACTIVATE_ANON
);
2294 if (refaults
!= target_lruvec
->refaults
[WORKINGSET_ANON
] ||
2295 inactive_is_low(target_lruvec
, LRU_INACTIVE_ANON
))
2296 sc
->may_deactivate
|= DEACTIVATE_ANON
;
2298 sc
->may_deactivate
&= ~DEACTIVATE_ANON
;
2300 refaults
= lruvec_page_state(target_lruvec
,
2301 WORKINGSET_ACTIVATE_FILE
);
2302 if (refaults
!= target_lruvec
->refaults
[WORKINGSET_FILE
] ||
2303 inactive_is_low(target_lruvec
, LRU_INACTIVE_FILE
))
2304 sc
->may_deactivate
|= DEACTIVATE_FILE
;
2306 sc
->may_deactivate
&= ~DEACTIVATE_FILE
;
2308 sc
->may_deactivate
= DEACTIVATE_ANON
| DEACTIVATE_FILE
;
2311 * If we have plenty of inactive file pages that aren't
2312 * thrashing, try to reclaim those first before touching
2315 file
= lruvec_page_state(target_lruvec
, NR_INACTIVE_FILE
);
2316 if (file
>> sc
->priority
&& !(sc
->may_deactivate
& DEACTIVATE_FILE
) &&
2317 !sc
->no_cache_trim_mode
)
2318 sc
->cache_trim_mode
= 1;
2320 sc
->cache_trim_mode
= 0;
2323 * Prevent the reclaimer from falling into the cache trap: as
2324 * cache pages start out inactive, every cache fault will tip
2325 * the scan balance towards the file LRU. And as the file LRU
2326 * shrinks, so does the window for rotation from references.
2327 * This means we have a runaway feedback loop where a tiny
2328 * thrashing file LRU becomes infinitely more attractive than
2329 * anon pages. Try to detect this based on file LRU size.
2331 if (!cgroup_reclaim(sc
)) {
2332 unsigned long total_high_wmark
= 0;
2333 unsigned long free
, anon
;
2336 free
= sum_zone_node_page_state(pgdat
->node_id
, NR_FREE_PAGES
);
2337 file
= node_page_state(pgdat
, NR_ACTIVE_FILE
) +
2338 node_page_state(pgdat
, NR_INACTIVE_FILE
);
2340 for (z
= 0; z
< MAX_NR_ZONES
; z
++) {
2341 struct zone
*zone
= &pgdat
->node_zones
[z
];
2343 if (!managed_zone(zone
))
2346 total_high_wmark
+= high_wmark_pages(zone
);
2350 * Consider anon: if that's low too, this isn't a
2351 * runaway file reclaim problem, but rather just
2352 * extreme pressure. Reclaim as per usual then.
2354 anon
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
2357 file
+ free
<= total_high_wmark
&&
2358 !(sc
->may_deactivate
& DEACTIVATE_ANON
) &&
2359 anon
>> sc
->priority
;
2364 * Determine how aggressively the anon and file LRU lists should be
2367 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2368 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2370 static void get_scan_count(struct lruvec
*lruvec
, struct scan_control
*sc
,
2373 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2374 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
2375 unsigned long anon_cost
, file_cost
, total_cost
;
2376 int swappiness
= sc_swappiness(sc
, memcg
);
2377 u64 fraction
[ANON_AND_FILE
];
2378 u64 denominator
= 0; /* gcc */
2379 enum scan_balance scan_balance
;
2380 unsigned long ap
, fp
;
2383 /* If we have no swap space, do not bother scanning anon folios. */
2384 if (!sc
->may_swap
|| !can_reclaim_anon_pages(memcg
, pgdat
->node_id
, sc
)) {
2385 scan_balance
= SCAN_FILE
;
2390 * Global reclaim will swap to prevent OOM even with no
2391 * swappiness, but memcg users want to use this knob to
2392 * disable swapping for individual groups completely when
2393 * using the memory controller's swap limit feature would be
2396 if (cgroup_reclaim(sc
) && !swappiness
) {
2397 scan_balance
= SCAN_FILE
;
2402 * Do not apply any pressure balancing cleverness when the
2403 * system is close to OOM, scan both anon and file equally
2404 * (unless the swappiness setting disagrees with swapping).
2406 if (!sc
->priority
&& swappiness
) {
2407 scan_balance
= SCAN_EQUAL
;
2412 * If the system is almost out of file pages, force-scan anon.
2414 if (sc
->file_is_tiny
) {
2415 scan_balance
= SCAN_ANON
;
2420 * If there is enough inactive page cache, we do not reclaim
2421 * anything from the anonymous working right now.
2423 if (sc
->cache_trim_mode
) {
2424 scan_balance
= SCAN_FILE
;
2428 scan_balance
= SCAN_FRACT
;
2430 * Calculate the pressure balance between anon and file pages.
2432 * The amount of pressure we put on each LRU is inversely
2433 * proportional to the cost of reclaiming each list, as
2434 * determined by the share of pages that are refaulting, times
2435 * the relative IO cost of bringing back a swapped out
2436 * anonymous page vs reloading a filesystem page (swappiness).
2438 * Although we limit that influence to ensure no list gets
2439 * left behind completely: at least a third of the pressure is
2440 * applied, before swappiness.
2442 * With swappiness at 100, anon and file have equal IO cost.
2444 total_cost
= sc
->anon_cost
+ sc
->file_cost
;
2445 anon_cost
= total_cost
+ sc
->anon_cost
;
2446 file_cost
= total_cost
+ sc
->file_cost
;
2447 total_cost
= anon_cost
+ file_cost
;
2449 ap
= swappiness
* (total_cost
+ 1);
2450 ap
/= anon_cost
+ 1;
2452 fp
= (MAX_SWAPPINESS
- swappiness
) * (total_cost
+ 1);
2453 fp
/= file_cost
+ 1;
2457 denominator
= ap
+ fp
;
2459 for_each_evictable_lru(lru
) {
2460 bool file
= is_file_lru(lru
);
2461 unsigned long lruvec_size
;
2462 unsigned long low
, min
;
2465 lruvec_size
= lruvec_lru_size(lruvec
, lru
, sc
->reclaim_idx
);
2466 mem_cgroup_protection(sc
->target_mem_cgroup
, memcg
,
2471 * Scale a cgroup's reclaim pressure by proportioning
2472 * its current usage to its memory.low or memory.min
2475 * This is important, as otherwise scanning aggression
2476 * becomes extremely binary -- from nothing as we
2477 * approach the memory protection threshold, to totally
2478 * nominal as we exceed it. This results in requiring
2479 * setting extremely liberal protection thresholds. It
2480 * also means we simply get no protection at all if we
2481 * set it too low, which is not ideal.
2483 * If there is any protection in place, we reduce scan
2484 * pressure by how much of the total memory used is
2485 * within protection thresholds.
2487 * There is one special case: in the first reclaim pass,
2488 * we skip over all groups that are within their low
2489 * protection. If that fails to reclaim enough pages to
2490 * satisfy the reclaim goal, we come back and override
2491 * the best-effort low protection. However, we still
2492 * ideally want to honor how well-behaved groups are in
2493 * that case instead of simply punishing them all
2494 * equally. As such, we reclaim them based on how much
2495 * memory they are using, reducing the scan pressure
2496 * again by how much of the total memory used is under
2499 unsigned long cgroup_size
= mem_cgroup_size(memcg
);
2500 unsigned long protection
;
2502 /* memory.low scaling, make sure we retry before OOM */
2503 if (!sc
->memcg_low_reclaim
&& low
> min
) {
2505 sc
->memcg_low_skipped
= 1;
2510 /* Avoid TOCTOU with earlier protection check */
2511 cgroup_size
= max(cgroup_size
, protection
);
2513 scan
= lruvec_size
- lruvec_size
* protection
/
2517 * Minimally target SWAP_CLUSTER_MAX pages to keep
2518 * reclaim moving forwards, avoiding decrementing
2519 * sc->priority further than desirable.
2521 scan
= max(scan
, SWAP_CLUSTER_MAX
);
2526 scan
>>= sc
->priority
;
2529 * If the cgroup's already been deleted, make sure to
2530 * scrape out the remaining cache.
2532 if (!scan
&& !mem_cgroup_online(memcg
))
2533 scan
= min(lruvec_size
, SWAP_CLUSTER_MAX
);
2535 switch (scan_balance
) {
2537 /* Scan lists relative to size */
2541 * Scan types proportional to swappiness and
2542 * their relative recent reclaim efficiency.
2543 * Make sure we don't miss the last page on
2544 * the offlined memory cgroups because of a
2547 scan
= mem_cgroup_online(memcg
) ?
2548 div64_u64(scan
* fraction
[file
], denominator
) :
2549 DIV64_U64_ROUND_UP(scan
* fraction
[file
],
2554 /* Scan one type exclusively */
2555 if ((scan_balance
== SCAN_FILE
) != file
)
2559 /* Look ma, no brain */
2568 * Anonymous LRU management is a waste if there is
2569 * ultimately no way to reclaim the memory.
2571 static bool can_age_anon_pages(struct pglist_data
*pgdat
,
2572 struct scan_control
*sc
)
2574 /* Aging the anon LRU is valuable if swap is present: */
2575 if (total_swap_pages
> 0)
2578 /* Also valuable if anon pages can be demoted: */
2579 return can_demote(pgdat
->node_id
, sc
);
2582 #ifdef CONFIG_LRU_GEN
2584 #ifdef CONFIG_LRU_GEN_ENABLED
2585 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps
, NR_LRU_GEN_CAPS
);
2586 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2588 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps
, NR_LRU_GEN_CAPS
);
2589 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2592 static bool should_walk_mmu(void)
2594 return arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK
);
2597 static bool should_clear_pmd_young(void)
2599 return arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG
);
2602 /******************************************************************************
2604 ******************************************************************************/
2606 #define DEFINE_MAX_SEQ(lruvec) \
2607 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2609 #define DEFINE_MIN_SEQ(lruvec) \
2610 unsigned long min_seq[ANON_AND_FILE] = { \
2611 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2612 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2615 #define for_each_gen_type_zone(gen, type, zone) \
2616 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2617 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2618 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2620 #define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2621 #define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2623 static struct lruvec
*get_lruvec(struct mem_cgroup
*memcg
, int nid
)
2625 struct pglist_data
*pgdat
= NODE_DATA(nid
);
2629 struct lruvec
*lruvec
= &memcg
->nodeinfo
[nid
]->lruvec
;
2631 /* see the comment in mem_cgroup_lruvec() */
2633 lruvec
->pgdat
= pgdat
;
2638 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2640 return &pgdat
->__lruvec
;
2643 static int get_swappiness(struct lruvec
*lruvec
, struct scan_control
*sc
)
2645 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
2646 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2651 if (!can_demote(pgdat
->node_id
, sc
) &&
2652 mem_cgroup_get_nr_swap_pages(memcg
) < MIN_LRU_BATCH
)
2655 return sc_swappiness(sc
, memcg
);
2658 static int get_nr_gens(struct lruvec
*lruvec
, int type
)
2660 return lruvec
->lrugen
.max_seq
- lruvec
->lrugen
.min_seq
[type
] + 1;
2663 static bool __maybe_unused
seq_is_valid(struct lruvec
*lruvec
)
2665 /* see the comment on lru_gen_folio */
2666 return get_nr_gens(lruvec
, LRU_GEN_FILE
) >= MIN_NR_GENS
&&
2667 get_nr_gens(lruvec
, LRU_GEN_FILE
) <= get_nr_gens(lruvec
, LRU_GEN_ANON
) &&
2668 get_nr_gens(lruvec
, LRU_GEN_ANON
) <= MAX_NR_GENS
;
2671 /******************************************************************************
2673 ******************************************************************************/
2676 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
2677 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
2678 * bits in a bitmap, k is the number of hash functions and n is the number of
2681 * Page table walkers use one of the two filters to reduce their search space.
2682 * To get rid of non-leaf entries that no longer have enough leaf entries, the
2683 * aging uses the double-buffering technique to flip to the other filter each
2684 * time it produces a new generation. For non-leaf entries that have enough
2685 * leaf entries, the aging carries them over to the next generation in
2686 * walk_pmd_range(); the eviction also report them when walking the rmap
2687 * in lru_gen_look_around().
2689 * For future optimizations:
2690 * 1. It's not necessary to keep both filters all the time. The spare one can be
2691 * freed after the RCU grace period and reallocated if needed again.
2692 * 2. And when reallocating, it's worth scaling its size according to the number
2693 * of inserted entries in the other filter, to reduce the memory overhead on
2694 * small systems and false positives on large systems.
2695 * 3. Jenkins' hash function is an alternative to Knuth's.
2697 #define BLOOM_FILTER_SHIFT 15
2699 static inline int filter_gen_from_seq(unsigned long seq
)
2701 return seq
% NR_BLOOM_FILTERS
;
2704 static void get_item_key(void *item
, int *key
)
2706 u32 hash
= hash_ptr(item
, BLOOM_FILTER_SHIFT
* 2);
2708 BUILD_BUG_ON(BLOOM_FILTER_SHIFT
* 2 > BITS_PER_TYPE(u32
));
2710 key
[0] = hash
& (BIT(BLOOM_FILTER_SHIFT
) - 1);
2711 key
[1] = hash
>> BLOOM_FILTER_SHIFT
;
2714 static bool test_bloom_filter(struct lru_gen_mm_state
*mm_state
, unsigned long seq
,
2718 unsigned long *filter
;
2719 int gen
= filter_gen_from_seq(seq
);
2721 filter
= READ_ONCE(mm_state
->filters
[gen
]);
2725 get_item_key(item
, key
);
2727 return test_bit(key
[0], filter
) && test_bit(key
[1], filter
);
2730 static void update_bloom_filter(struct lru_gen_mm_state
*mm_state
, unsigned long seq
,
2734 unsigned long *filter
;
2735 int gen
= filter_gen_from_seq(seq
);
2737 filter
= READ_ONCE(mm_state
->filters
[gen
]);
2741 get_item_key(item
, key
);
2743 if (!test_bit(key
[0], filter
))
2744 set_bit(key
[0], filter
);
2745 if (!test_bit(key
[1], filter
))
2746 set_bit(key
[1], filter
);
2749 static void reset_bloom_filter(struct lru_gen_mm_state
*mm_state
, unsigned long seq
)
2751 unsigned long *filter
;
2752 int gen
= filter_gen_from_seq(seq
);
2754 filter
= mm_state
->filters
[gen
];
2756 bitmap_clear(filter
, 0, BIT(BLOOM_FILTER_SHIFT
));
2760 filter
= bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT
),
2761 __GFP_HIGH
| __GFP_NOMEMALLOC
| __GFP_NOWARN
);
2762 WRITE_ONCE(mm_state
->filters
[gen
], filter
);
2765 /******************************************************************************
2767 ******************************************************************************/
2769 #ifdef CONFIG_LRU_GEN_WALKS_MMU
2771 static struct lru_gen_mm_list
*get_mm_list(struct mem_cgroup
*memcg
)
2773 static struct lru_gen_mm_list mm_list
= {
2774 .fifo
= LIST_HEAD_INIT(mm_list
.fifo
),
2775 .lock
= __SPIN_LOCK_UNLOCKED(mm_list
.lock
),
2780 return &memcg
->mm_list
;
2782 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2787 static struct lru_gen_mm_state
*get_mm_state(struct lruvec
*lruvec
)
2789 return &lruvec
->mm_state
;
2792 static struct mm_struct
*get_next_mm(struct lru_gen_mm_walk
*walk
)
2795 struct mm_struct
*mm
;
2796 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
2797 struct lru_gen_mm_state
*mm_state
= get_mm_state(walk
->lruvec
);
2799 mm
= list_entry(mm_state
->head
, struct mm_struct
, lru_gen
.list
);
2800 key
= pgdat
->node_id
% BITS_PER_TYPE(mm
->lru_gen
.bitmap
);
2802 if (!walk
->force_scan
&& !test_bit(key
, &mm
->lru_gen
.bitmap
))
2805 clear_bit(key
, &mm
->lru_gen
.bitmap
);
2807 return mmget_not_zero(mm
) ? mm
: NULL
;
2810 void lru_gen_add_mm(struct mm_struct
*mm
)
2813 struct mem_cgroup
*memcg
= get_mem_cgroup_from_mm(mm
);
2814 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
2816 VM_WARN_ON_ONCE(!list_empty(&mm
->lru_gen
.list
));
2818 VM_WARN_ON_ONCE(mm
->lru_gen
.memcg
);
2819 mm
->lru_gen
.memcg
= memcg
;
2821 spin_lock(&mm_list
->lock
);
2823 for_each_node_state(nid
, N_MEMORY
) {
2824 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
2825 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
2827 /* the first addition since the last iteration */
2828 if (mm_state
->tail
== &mm_list
->fifo
)
2829 mm_state
->tail
= &mm
->lru_gen
.list
;
2832 list_add_tail(&mm
->lru_gen
.list
, &mm_list
->fifo
);
2834 spin_unlock(&mm_list
->lock
);
2837 void lru_gen_del_mm(struct mm_struct
*mm
)
2840 struct lru_gen_mm_list
*mm_list
;
2841 struct mem_cgroup
*memcg
= NULL
;
2843 if (list_empty(&mm
->lru_gen
.list
))
2847 memcg
= mm
->lru_gen
.memcg
;
2849 mm_list
= get_mm_list(memcg
);
2851 spin_lock(&mm_list
->lock
);
2853 for_each_node(nid
) {
2854 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
2855 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
2857 /* where the current iteration continues after */
2858 if (mm_state
->head
== &mm
->lru_gen
.list
)
2859 mm_state
->head
= mm_state
->head
->prev
;
2861 /* where the last iteration ended before */
2862 if (mm_state
->tail
== &mm
->lru_gen
.list
)
2863 mm_state
->tail
= mm_state
->tail
->next
;
2866 list_del_init(&mm
->lru_gen
.list
);
2868 spin_unlock(&mm_list
->lock
);
2871 mem_cgroup_put(mm
->lru_gen
.memcg
);
2872 mm
->lru_gen
.memcg
= NULL
;
2877 void lru_gen_migrate_mm(struct mm_struct
*mm
)
2879 struct mem_cgroup
*memcg
;
2880 struct task_struct
*task
= rcu_dereference_protected(mm
->owner
, true);
2882 VM_WARN_ON_ONCE(task
->mm
!= mm
);
2883 lockdep_assert_held(&task
->alloc_lock
);
2885 /* for mm_update_next_owner() */
2886 if (mem_cgroup_disabled())
2889 /* migration can happen before addition */
2890 if (!mm
->lru_gen
.memcg
)
2894 memcg
= mem_cgroup_from_task(task
);
2896 if (memcg
== mm
->lru_gen
.memcg
)
2899 VM_WARN_ON_ONCE(list_empty(&mm
->lru_gen
.list
));
2906 #else /* !CONFIG_LRU_GEN_WALKS_MMU */
2908 static struct lru_gen_mm_list
*get_mm_list(struct mem_cgroup
*memcg
)
2913 static struct lru_gen_mm_state
*get_mm_state(struct lruvec
*lruvec
)
2918 static struct mm_struct
*get_next_mm(struct lru_gen_mm_walk
*walk
)
2925 static void reset_mm_stats(struct lru_gen_mm_walk
*walk
, bool last
)
2929 struct lruvec
*lruvec
= walk
->lruvec
;
2930 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
2932 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec
))->lock
);
2934 hist
= lru_hist_from_seq(walk
->seq
);
2936 for (i
= 0; i
< NR_MM_STATS
; i
++) {
2937 WRITE_ONCE(mm_state
->stats
[hist
][i
],
2938 mm_state
->stats
[hist
][i
] + walk
->mm_stats
[i
]);
2939 walk
->mm_stats
[i
] = 0;
2942 if (NR_HIST_GENS
> 1 && last
) {
2943 hist
= lru_hist_from_seq(walk
->seq
+ 1);
2945 for (i
= 0; i
< NR_MM_STATS
; i
++)
2946 WRITE_ONCE(mm_state
->stats
[hist
][i
], 0);
2950 static bool iterate_mm_list(struct lru_gen_mm_walk
*walk
, struct mm_struct
**iter
)
2954 struct mm_struct
*mm
= NULL
;
2955 struct lruvec
*lruvec
= walk
->lruvec
;
2956 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
2957 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
2958 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
2961 * mm_state->seq is incremented after each iteration of mm_list. There
2962 * are three interesting cases for this page table walker:
2963 * 1. It tries to start a new iteration with a stale max_seq: there is
2964 * nothing left to do.
2965 * 2. It started the next iteration: it needs to reset the Bloom filter
2966 * so that a fresh set of PTE tables can be recorded.
2967 * 3. It ended the current iteration: it needs to reset the mm stats
2968 * counters and tell its caller to increment max_seq.
2970 spin_lock(&mm_list
->lock
);
2972 VM_WARN_ON_ONCE(mm_state
->seq
+ 1 < walk
->seq
);
2974 if (walk
->seq
<= mm_state
->seq
)
2977 if (!mm_state
->head
)
2978 mm_state
->head
= &mm_list
->fifo
;
2980 if (mm_state
->head
== &mm_list
->fifo
)
2984 mm_state
->head
= mm_state
->head
->next
;
2985 if (mm_state
->head
== &mm_list
->fifo
) {
2986 WRITE_ONCE(mm_state
->seq
, mm_state
->seq
+ 1);
2991 /* force scan for those added after the last iteration */
2992 if (!mm_state
->tail
|| mm_state
->tail
== mm_state
->head
) {
2993 mm_state
->tail
= mm_state
->head
->next
;
2994 walk
->force_scan
= true;
2996 } while (!(mm
= get_next_mm(walk
)));
2999 reset_mm_stats(walk
, last
);
3001 spin_unlock(&mm_list
->lock
);
3004 reset_bloom_filter(mm_state
, walk
->seq
+ 1);
3014 static bool iterate_mm_list_nowalk(struct lruvec
*lruvec
, unsigned long seq
)
3016 bool success
= false;
3017 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
3018 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
3019 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
3021 spin_lock(&mm_list
->lock
);
3023 VM_WARN_ON_ONCE(mm_state
->seq
+ 1 < seq
);
3025 if (seq
> mm_state
->seq
) {
3026 mm_state
->head
= NULL
;
3027 mm_state
->tail
= NULL
;
3028 WRITE_ONCE(mm_state
->seq
, mm_state
->seq
+ 1);
3032 spin_unlock(&mm_list
->lock
);
3037 /******************************************************************************
3039 ******************************************************************************/
3042 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3044 * The P term is refaulted/(evicted+protected) from a tier in the generation
3045 * currently being evicted; the I term is the exponential moving average of the
3046 * P term over the generations previously evicted, using the smoothing factor
3047 * 1/2; the D term isn't supported.
3049 * The setpoint (SP) is always the first tier of one type; the process variable
3050 * (PV) is either any tier of the other type or any other tier of the same
3053 * The error is the difference between the SP and the PV; the correction is to
3054 * turn off protection when SP>PV or turn on protection when SP<PV.
3056 * For future optimizations:
3057 * 1. The D term may discount the other two terms over time so that long-lived
3058 * generations can resist stale information.
3061 unsigned long refaulted
;
3062 unsigned long total
;
3066 static void read_ctrl_pos(struct lruvec
*lruvec
, int type
, int tier
, int gain
,
3067 struct ctrl_pos
*pos
)
3069 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3070 int hist
= lru_hist_from_seq(lrugen
->min_seq
[type
]);
3072 pos
->refaulted
= lrugen
->avg_refaulted
[type
][tier
] +
3073 atomic_long_read(&lrugen
->refaulted
[hist
][type
][tier
]);
3074 pos
->total
= lrugen
->avg_total
[type
][tier
] +
3075 atomic_long_read(&lrugen
->evicted
[hist
][type
][tier
]);
3077 pos
->total
+= lrugen
->protected[hist
][type
][tier
- 1];
3081 static void reset_ctrl_pos(struct lruvec
*lruvec
, int type
, bool carryover
)
3084 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3085 bool clear
= carryover
? NR_HIST_GENS
== 1 : NR_HIST_GENS
> 1;
3086 unsigned long seq
= carryover
? lrugen
->min_seq
[type
] : lrugen
->max_seq
+ 1;
3088 lockdep_assert_held(&lruvec
->lru_lock
);
3090 if (!carryover
&& !clear
)
3093 hist
= lru_hist_from_seq(seq
);
3095 for (tier
= 0; tier
< MAX_NR_TIERS
; tier
++) {
3099 sum
= lrugen
->avg_refaulted
[type
][tier
] +
3100 atomic_long_read(&lrugen
->refaulted
[hist
][type
][tier
]);
3101 WRITE_ONCE(lrugen
->avg_refaulted
[type
][tier
], sum
/ 2);
3103 sum
= lrugen
->avg_total
[type
][tier
] +
3104 atomic_long_read(&lrugen
->evicted
[hist
][type
][tier
]);
3106 sum
+= lrugen
->protected[hist
][type
][tier
- 1];
3107 WRITE_ONCE(lrugen
->avg_total
[type
][tier
], sum
/ 2);
3111 atomic_long_set(&lrugen
->refaulted
[hist
][type
][tier
], 0);
3112 atomic_long_set(&lrugen
->evicted
[hist
][type
][tier
], 0);
3114 WRITE_ONCE(lrugen
->protected[hist
][type
][tier
- 1], 0);
3119 static bool positive_ctrl_err(struct ctrl_pos
*sp
, struct ctrl_pos
*pv
)
3122 * Return true if the PV has a limited number of refaults or a lower
3123 * refaulted/total than the SP.
3125 return pv
->refaulted
< MIN_LRU_BATCH
||
3126 pv
->refaulted
* (sp
->total
+ MIN_LRU_BATCH
) * sp
->gain
<=
3127 (sp
->refaulted
+ 1) * pv
->total
* pv
->gain
;
3130 /******************************************************************************
3132 ******************************************************************************/
3134 /* promote pages accessed through page tables */
3135 static int folio_update_gen(struct folio
*folio
, int gen
)
3137 unsigned long new_flags
, old_flags
= READ_ONCE(folio
->flags
);
3139 VM_WARN_ON_ONCE(gen
>= MAX_NR_GENS
);
3142 /* lru_gen_del_folio() has isolated this page? */
3143 if (!(old_flags
& LRU_GEN_MASK
)) {
3144 /* for shrink_folio_list() */
3145 new_flags
= old_flags
| BIT(PG_referenced
);
3149 new_flags
= old_flags
& ~(LRU_GEN_MASK
| LRU_REFS_MASK
| LRU_REFS_FLAGS
);
3150 new_flags
|= (gen
+ 1UL) << LRU_GEN_PGOFF
;
3151 } while (!try_cmpxchg(&folio
->flags
, &old_flags
, new_flags
));
3153 return ((old_flags
& LRU_GEN_MASK
) >> LRU_GEN_PGOFF
) - 1;
3156 /* protect pages accessed multiple times through file descriptors */
3157 static int folio_inc_gen(struct lruvec
*lruvec
, struct folio
*folio
, bool reclaiming
)
3159 int type
= folio_is_file_lru(folio
);
3160 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3161 int new_gen
, old_gen
= lru_gen_from_seq(lrugen
->min_seq
[type
]);
3162 unsigned long new_flags
, old_flags
= READ_ONCE(folio
->flags
);
3164 VM_WARN_ON_ONCE_FOLIO(!(old_flags
& LRU_GEN_MASK
), folio
);
3167 new_gen
= ((old_flags
& LRU_GEN_MASK
) >> LRU_GEN_PGOFF
) - 1;
3168 /* folio_update_gen() has promoted this page? */
3169 if (new_gen
>= 0 && new_gen
!= old_gen
)
3172 new_gen
= (old_gen
+ 1) % MAX_NR_GENS
;
3174 new_flags
= old_flags
& ~(LRU_GEN_MASK
| LRU_REFS_MASK
| LRU_REFS_FLAGS
);
3175 new_flags
|= (new_gen
+ 1UL) << LRU_GEN_PGOFF
;
3176 /* for folio_end_writeback() */
3178 new_flags
|= BIT(PG_reclaim
);
3179 } while (!try_cmpxchg(&folio
->flags
, &old_flags
, new_flags
));
3181 lru_gen_update_size(lruvec
, folio
, old_gen
, new_gen
);
3186 static void update_batch_size(struct lru_gen_mm_walk
*walk
, struct folio
*folio
,
3187 int old_gen
, int new_gen
)
3189 int type
= folio_is_file_lru(folio
);
3190 int zone
= folio_zonenum(folio
);
3191 int delta
= folio_nr_pages(folio
);
3193 VM_WARN_ON_ONCE(old_gen
>= MAX_NR_GENS
);
3194 VM_WARN_ON_ONCE(new_gen
>= MAX_NR_GENS
);
3198 walk
->nr_pages
[old_gen
][type
][zone
] -= delta
;
3199 walk
->nr_pages
[new_gen
][type
][zone
] += delta
;
3202 static void reset_batch_size(struct lru_gen_mm_walk
*walk
)
3204 int gen
, type
, zone
;
3205 struct lruvec
*lruvec
= walk
->lruvec
;
3206 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3210 for_each_gen_type_zone(gen
, type
, zone
) {
3211 enum lru_list lru
= type
* LRU_INACTIVE_FILE
;
3212 int delta
= walk
->nr_pages
[gen
][type
][zone
];
3217 walk
->nr_pages
[gen
][type
][zone
] = 0;
3218 WRITE_ONCE(lrugen
->nr_pages
[gen
][type
][zone
],
3219 lrugen
->nr_pages
[gen
][type
][zone
] + delta
);
3221 if (lru_gen_is_active(lruvec
, gen
))
3223 __update_lru_size(lruvec
, lru
, zone
, delta
);
3227 static int should_skip_vma(unsigned long start
, unsigned long end
, struct mm_walk
*args
)
3229 struct address_space
*mapping
;
3230 struct vm_area_struct
*vma
= args
->vma
;
3231 struct lru_gen_mm_walk
*walk
= args
->private;
3233 if (!vma_is_accessible(vma
))
3236 if (is_vm_hugetlb_page(vma
))
3239 if (!vma_has_recency(vma
))
3242 if (vma
->vm_flags
& (VM_LOCKED
| VM_SPECIAL
))
3245 if (vma
== get_gate_vma(vma
->vm_mm
))
3248 if (vma_is_anonymous(vma
))
3249 return !walk
->can_swap
;
3251 if (WARN_ON_ONCE(!vma
->vm_file
|| !vma
->vm_file
->f_mapping
))
3254 mapping
= vma
->vm_file
->f_mapping
;
3255 if (mapping_unevictable(mapping
))
3258 if (shmem_mapping(mapping
))
3259 return !walk
->can_swap
;
3261 /* to exclude special mappings like dax, etc. */
3262 return !mapping
->a_ops
->read_folio
;
3266 * Some userspace memory allocators map many single-page VMAs. Instead of
3267 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3268 * table to reduce zigzags and improve cache performance.
3270 static bool get_next_vma(unsigned long mask
, unsigned long size
, struct mm_walk
*args
,
3271 unsigned long *vm_start
, unsigned long *vm_end
)
3273 unsigned long start
= round_up(*vm_end
, size
);
3274 unsigned long end
= (start
| ~mask
) + 1;
3275 VMA_ITERATOR(vmi
, args
->mm
, start
);
3277 VM_WARN_ON_ONCE(mask
& size
);
3278 VM_WARN_ON_ONCE((start
& mask
) != (*vm_start
& mask
));
3280 for_each_vma(vmi
, args
->vma
) {
3281 if (end
&& end
<= args
->vma
->vm_start
)
3284 if (should_skip_vma(args
->vma
->vm_start
, args
->vma
->vm_end
, args
))
3287 *vm_start
= max(start
, args
->vma
->vm_start
);
3288 *vm_end
= min(end
- 1, args
->vma
->vm_end
- 1) + 1;
3296 static unsigned long get_pte_pfn(pte_t pte
, struct vm_area_struct
*vma
, unsigned long addr
,
3297 struct pglist_data
*pgdat
)
3299 unsigned long pfn
= pte_pfn(pte
);
3301 VM_WARN_ON_ONCE(addr
< vma
->vm_start
|| addr
>= vma
->vm_end
);
3303 if (!pte_present(pte
) || is_zero_pfn(pfn
))
3306 if (WARN_ON_ONCE(pte_devmap(pte
) || pte_special(pte
)))
3309 if (!pte_young(pte
) && !mm_has_notifiers(vma
->vm_mm
))
3312 if (WARN_ON_ONCE(!pfn_valid(pfn
)))
3315 if (pfn
< pgdat
->node_start_pfn
|| pfn
>= pgdat_end_pfn(pgdat
))
3321 static unsigned long get_pmd_pfn(pmd_t pmd
, struct vm_area_struct
*vma
, unsigned long addr
,
3322 struct pglist_data
*pgdat
)
3324 unsigned long pfn
= pmd_pfn(pmd
);
3326 VM_WARN_ON_ONCE(addr
< vma
->vm_start
|| addr
>= vma
->vm_end
);
3328 if (!pmd_present(pmd
) || is_huge_zero_pmd(pmd
))
3331 if (WARN_ON_ONCE(pmd_devmap(pmd
)))
3334 if (!pmd_young(pmd
) && !mm_has_notifiers(vma
->vm_mm
))
3337 if (WARN_ON_ONCE(!pfn_valid(pfn
)))
3340 if (pfn
< pgdat
->node_start_pfn
|| pfn
>= pgdat_end_pfn(pgdat
))
3346 static struct folio
*get_pfn_folio(unsigned long pfn
, struct mem_cgroup
*memcg
,
3347 struct pglist_data
*pgdat
, bool can_swap
)
3349 struct folio
*folio
;
3351 folio
= pfn_folio(pfn
);
3352 if (folio_nid(folio
) != pgdat
->node_id
)
3355 if (folio_memcg(folio
) != memcg
)
3358 /* file VMAs can contain anon pages from COW */
3359 if (!folio_is_file_lru(folio
) && !can_swap
)
3365 static bool suitable_to_scan(int total
, int young
)
3367 int n
= clamp_t(int, cache_line_size() / sizeof(pte_t
), 2, 8);
3369 /* suitable if the average number of young PTEs per cacheline is >=1 */
3370 return young
* n
>= total
;
3373 static bool walk_pte_range(pmd_t
*pmd
, unsigned long start
, unsigned long end
,
3374 struct mm_walk
*args
)
3382 struct lru_gen_mm_walk
*walk
= args
->private;
3383 struct mem_cgroup
*memcg
= lruvec_memcg(walk
->lruvec
);
3384 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
3385 DEFINE_MAX_SEQ(walk
->lruvec
);
3386 int old_gen
, new_gen
= lru_gen_from_seq(max_seq
);
3389 pte
= pte_offset_map_rw_nolock(args
->mm
, pmd
, start
& PMD_MASK
, &pmdval
,
3393 if (!spin_trylock(ptl
)) {
3398 if (unlikely(!pmd_same(pmdval
, pmdp_get_lockless(pmd
)))) {
3399 pte_unmap_unlock(pte
, ptl
);
3403 arch_enter_lazy_mmu_mode();
3405 for (i
= pte_index(start
), addr
= start
; addr
!= end
; i
++, addr
+= PAGE_SIZE
) {
3407 struct folio
*folio
;
3408 pte_t ptent
= ptep_get(pte
+ i
);
3411 walk
->mm_stats
[MM_LEAF_TOTAL
]++;
3413 pfn
= get_pte_pfn(ptent
, args
->vma
, addr
, pgdat
);
3417 folio
= get_pfn_folio(pfn
, memcg
, pgdat
, walk
->can_swap
);
3421 if (!ptep_clear_young_notify(args
->vma
, addr
, pte
+ i
))
3425 walk
->mm_stats
[MM_LEAF_YOUNG
]++;
3427 if (pte_dirty(ptent
) && !folio_test_dirty(folio
) &&
3428 !(folio_test_anon(folio
) && folio_test_swapbacked(folio
) &&
3429 !folio_test_swapcache(folio
)))
3430 folio_mark_dirty(folio
);
3432 old_gen
= folio_update_gen(folio
, new_gen
);
3433 if (old_gen
>= 0 && old_gen
!= new_gen
)
3434 update_batch_size(walk
, folio
, old_gen
, new_gen
);
3437 if (i
< PTRS_PER_PTE
&& get_next_vma(PMD_MASK
, PAGE_SIZE
, args
, &start
, &end
))
3440 arch_leave_lazy_mmu_mode();
3441 pte_unmap_unlock(pte
, ptl
);
3443 return suitable_to_scan(total
, young
);
3446 static void walk_pmd_range_locked(pud_t
*pud
, unsigned long addr
, struct vm_area_struct
*vma
,
3447 struct mm_walk
*args
, unsigned long *bitmap
, unsigned long *first
)
3452 struct lru_gen_mm_walk
*walk
= args
->private;
3453 struct mem_cgroup
*memcg
= lruvec_memcg(walk
->lruvec
);
3454 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
3455 DEFINE_MAX_SEQ(walk
->lruvec
);
3456 int old_gen
, new_gen
= lru_gen_from_seq(max_seq
);
3458 VM_WARN_ON_ONCE(pud_leaf(*pud
));
3460 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3463 bitmap_zero(bitmap
, MIN_LRU_BATCH
);
3467 i
= addr
== -1 ? 0 : pmd_index(addr
) - pmd_index(*first
);
3468 if (i
&& i
<= MIN_LRU_BATCH
) {
3469 __set_bit(i
- 1, bitmap
);
3473 pmd
= pmd_offset(pud
, *first
);
3475 ptl
= pmd_lockptr(args
->mm
, pmd
);
3476 if (!spin_trylock(ptl
))
3479 arch_enter_lazy_mmu_mode();
3483 struct folio
*folio
;
3485 /* don't round down the first address */
3486 addr
= i
? (*first
& PMD_MASK
) + i
* PMD_SIZE
: *first
;
3488 if (!pmd_present(pmd
[i
]))
3491 if (!pmd_trans_huge(pmd
[i
])) {
3492 if (!walk
->force_scan
&& should_clear_pmd_young() &&
3493 !mm_has_notifiers(args
->mm
))
3494 pmdp_test_and_clear_young(vma
, addr
, pmd
+ i
);
3498 pfn
= get_pmd_pfn(pmd
[i
], vma
, addr
, pgdat
);
3502 folio
= get_pfn_folio(pfn
, memcg
, pgdat
, walk
->can_swap
);
3506 if (!pmdp_clear_young_notify(vma
, addr
, pmd
+ i
))
3509 walk
->mm_stats
[MM_LEAF_YOUNG
]++;
3511 if (pmd_dirty(pmd
[i
]) && !folio_test_dirty(folio
) &&
3512 !(folio_test_anon(folio
) && folio_test_swapbacked(folio
) &&
3513 !folio_test_swapcache(folio
)))
3514 folio_mark_dirty(folio
);
3516 old_gen
= folio_update_gen(folio
, new_gen
);
3517 if (old_gen
>= 0 && old_gen
!= new_gen
)
3518 update_batch_size(walk
, folio
, old_gen
, new_gen
);
3520 i
= i
> MIN_LRU_BATCH
? 0 : find_next_bit(bitmap
, MIN_LRU_BATCH
, i
) + 1;
3521 } while (i
<= MIN_LRU_BATCH
);
3523 arch_leave_lazy_mmu_mode();
3529 static void walk_pmd_range(pud_t
*pud
, unsigned long start
, unsigned long end
,
3530 struct mm_walk
*args
)
3536 struct vm_area_struct
*vma
;
3537 DECLARE_BITMAP(bitmap
, MIN_LRU_BATCH
);
3538 unsigned long first
= -1;
3539 struct lru_gen_mm_walk
*walk
= args
->private;
3540 struct lru_gen_mm_state
*mm_state
= get_mm_state(walk
->lruvec
);
3542 VM_WARN_ON_ONCE(pud_leaf(*pud
));
3545 * Finish an entire PMD in two passes: the first only reaches to PTE
3546 * tables to avoid taking the PMD lock; the second, if necessary, takes
3547 * the PMD lock to clear the accessed bit in PMD entries.
3549 pmd
= pmd_offset(pud
, start
& PUD_MASK
);
3551 /* walk_pte_range() may call get_next_vma() */
3553 for (i
= pmd_index(start
), addr
= start
; addr
!= end
; i
++, addr
= next
) {
3554 pmd_t val
= pmdp_get_lockless(pmd
+ i
);
3556 next
= pmd_addr_end(addr
, end
);
3558 if (!pmd_present(val
) || is_huge_zero_pmd(val
)) {
3559 walk
->mm_stats
[MM_LEAF_TOTAL
]++;
3563 if (pmd_trans_huge(val
)) {
3564 struct pglist_data
*pgdat
= lruvec_pgdat(walk
->lruvec
);
3565 unsigned long pfn
= get_pmd_pfn(val
, vma
, addr
, pgdat
);
3567 walk
->mm_stats
[MM_LEAF_TOTAL
]++;
3570 walk_pmd_range_locked(pud
, addr
, vma
, args
, bitmap
, &first
);
3574 if (!walk
->force_scan
&& should_clear_pmd_young() &&
3575 !mm_has_notifiers(args
->mm
)) {
3576 if (!pmd_young(val
))
3579 walk_pmd_range_locked(pud
, addr
, vma
, args
, bitmap
, &first
);
3582 if (!walk
->force_scan
&& !test_bloom_filter(mm_state
, walk
->seq
, pmd
+ i
))
3585 walk
->mm_stats
[MM_NONLEAF_FOUND
]++;
3587 if (!walk_pte_range(&val
, addr
, next
, args
))
3590 walk
->mm_stats
[MM_NONLEAF_ADDED
]++;
3592 /* carry over to the next generation */
3593 update_bloom_filter(mm_state
, walk
->seq
+ 1, pmd
+ i
);
3596 walk_pmd_range_locked(pud
, -1, vma
, args
, bitmap
, &first
);
3598 if (i
< PTRS_PER_PMD
&& get_next_vma(PUD_MASK
, PMD_SIZE
, args
, &start
, &end
))
3602 static int walk_pud_range(p4d_t
*p4d
, unsigned long start
, unsigned long end
,
3603 struct mm_walk
*args
)
3609 struct lru_gen_mm_walk
*walk
= args
->private;
3611 VM_WARN_ON_ONCE(p4d_leaf(*p4d
));
3613 pud
= pud_offset(p4d
, start
& P4D_MASK
);
3615 for (i
= pud_index(start
), addr
= start
; addr
!= end
; i
++, addr
= next
) {
3616 pud_t val
= READ_ONCE(pud
[i
]);
3618 next
= pud_addr_end(addr
, end
);
3620 if (!pud_present(val
) || WARN_ON_ONCE(pud_leaf(val
)))
3623 walk_pmd_range(&val
, addr
, next
, args
);
3625 if (need_resched() || walk
->batched
>= MAX_LRU_BATCH
) {
3626 end
= (addr
| ~PUD_MASK
) + 1;
3631 if (i
< PTRS_PER_PUD
&& get_next_vma(P4D_MASK
, PUD_SIZE
, args
, &start
, &end
))
3634 end
= round_up(end
, P4D_SIZE
);
3636 if (!end
|| !args
->vma
)
3639 walk
->next_addr
= max(end
, args
->vma
->vm_start
);
3644 static void walk_mm(struct mm_struct
*mm
, struct lru_gen_mm_walk
*walk
)
3646 static const struct mm_walk_ops mm_walk_ops
= {
3647 .test_walk
= should_skip_vma
,
3648 .p4d_entry
= walk_pud_range
,
3649 .walk_lock
= PGWALK_RDLOCK
,
3652 struct lruvec
*lruvec
= walk
->lruvec
;
3654 walk
->next_addr
= FIRST_USER_ADDRESS
;
3657 DEFINE_MAX_SEQ(lruvec
);
3661 /* another thread might have called inc_max_seq() */
3662 if (walk
->seq
!= max_seq
)
3665 /* the caller might be holding the lock for write */
3666 if (mmap_read_trylock(mm
)) {
3667 err
= walk_page_range(mm
, walk
->next_addr
, ULONG_MAX
, &mm_walk_ops
, walk
);
3669 mmap_read_unlock(mm
);
3672 if (walk
->batched
) {
3673 spin_lock_irq(&lruvec
->lru_lock
);
3674 reset_batch_size(walk
);
3675 spin_unlock_irq(&lruvec
->lru_lock
);
3679 } while (err
== -EAGAIN
);
3682 static struct lru_gen_mm_walk
*set_mm_walk(struct pglist_data
*pgdat
, bool force_alloc
)
3684 struct lru_gen_mm_walk
*walk
= current
->reclaim_state
->mm_walk
;
3686 if (pgdat
&& current_is_kswapd()) {
3687 VM_WARN_ON_ONCE(walk
);
3689 walk
= &pgdat
->mm_walk
;
3690 } else if (!walk
&& force_alloc
) {
3691 VM_WARN_ON_ONCE(current_is_kswapd());
3693 walk
= kzalloc(sizeof(*walk
), __GFP_HIGH
| __GFP_NOMEMALLOC
| __GFP_NOWARN
);
3696 current
->reclaim_state
->mm_walk
= walk
;
3701 static void clear_mm_walk(void)
3703 struct lru_gen_mm_walk
*walk
= current
->reclaim_state
->mm_walk
;
3705 VM_WARN_ON_ONCE(walk
&& memchr_inv(walk
->nr_pages
, 0, sizeof(walk
->nr_pages
)));
3706 VM_WARN_ON_ONCE(walk
&& memchr_inv(walk
->mm_stats
, 0, sizeof(walk
->mm_stats
)));
3708 current
->reclaim_state
->mm_walk
= NULL
;
3710 if (!current_is_kswapd())
3714 static bool inc_min_seq(struct lruvec
*lruvec
, int type
, bool can_swap
)
3717 int remaining
= MAX_LRU_BATCH
;
3718 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3719 int new_gen
, old_gen
= lru_gen_from_seq(lrugen
->min_seq
[type
]);
3721 if (type
== LRU_GEN_ANON
&& !can_swap
)
3724 /* prevent cold/hot inversion if force_scan is true */
3725 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
3726 struct list_head
*head
= &lrugen
->folios
[old_gen
][type
][zone
];
3728 while (!list_empty(head
)) {
3729 struct folio
*folio
= lru_to_folio(head
);
3731 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
3732 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
), folio
);
3733 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
3734 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio
) != zone
, folio
);
3736 new_gen
= folio_inc_gen(lruvec
, folio
, false);
3737 list_move_tail(&folio
->lru
, &lrugen
->folios
[new_gen
][type
][zone
]);
3744 reset_ctrl_pos(lruvec
, type
, true);
3745 WRITE_ONCE(lrugen
->min_seq
[type
], lrugen
->min_seq
[type
] + 1);
3750 static bool try_to_inc_min_seq(struct lruvec
*lruvec
, bool can_swap
)
3752 int gen
, type
, zone
;
3753 bool success
= false;
3754 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3755 DEFINE_MIN_SEQ(lruvec
);
3757 VM_WARN_ON_ONCE(!seq_is_valid(lruvec
));
3759 /* find the oldest populated generation */
3760 for (type
= !can_swap
; type
< ANON_AND_FILE
; type
++) {
3761 while (min_seq
[type
] + MIN_NR_GENS
<= lrugen
->max_seq
) {
3762 gen
= lru_gen_from_seq(min_seq
[type
]);
3764 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
3765 if (!list_empty(&lrugen
->folios
[gen
][type
][zone
]))
3775 /* see the comment on lru_gen_folio */
3777 min_seq
[LRU_GEN_ANON
] = min(min_seq
[LRU_GEN_ANON
], min_seq
[LRU_GEN_FILE
]);
3778 min_seq
[LRU_GEN_FILE
] = max(min_seq
[LRU_GEN_ANON
], lrugen
->min_seq
[LRU_GEN_FILE
]);
3781 for (type
= !can_swap
; type
< ANON_AND_FILE
; type
++) {
3782 if (min_seq
[type
] == lrugen
->min_seq
[type
])
3785 reset_ctrl_pos(lruvec
, type
, true);
3786 WRITE_ONCE(lrugen
->min_seq
[type
], min_seq
[type
]);
3793 static bool inc_max_seq(struct lruvec
*lruvec
, unsigned long seq
,
3794 bool can_swap
, bool force_scan
)
3799 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3801 if (seq
< READ_ONCE(lrugen
->max_seq
))
3804 spin_lock_irq(&lruvec
->lru_lock
);
3806 VM_WARN_ON_ONCE(!seq_is_valid(lruvec
));
3808 success
= seq
== lrugen
->max_seq
;
3812 for (type
= ANON_AND_FILE
- 1; type
>= 0; type
--) {
3813 if (get_nr_gens(lruvec
, type
) != MAX_NR_GENS
)
3816 VM_WARN_ON_ONCE(!force_scan
&& (type
== LRU_GEN_FILE
|| can_swap
));
3818 if (inc_min_seq(lruvec
, type
, can_swap
))
3821 spin_unlock_irq(&lruvec
->lru_lock
);
3827 * Update the active/inactive LRU sizes for compatibility. Both sides of
3828 * the current max_seq need to be covered, since max_seq+1 can overlap
3829 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3830 * overlap, cold/hot inversion happens.
3832 prev
= lru_gen_from_seq(lrugen
->max_seq
- 1);
3833 next
= lru_gen_from_seq(lrugen
->max_seq
+ 1);
3835 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
3836 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
3837 enum lru_list lru
= type
* LRU_INACTIVE_FILE
;
3838 long delta
= lrugen
->nr_pages
[prev
][type
][zone
] -
3839 lrugen
->nr_pages
[next
][type
][zone
];
3844 __update_lru_size(lruvec
, lru
, zone
, delta
);
3845 __update_lru_size(lruvec
, lru
+ LRU_ACTIVE
, zone
, -delta
);
3849 for (type
= 0; type
< ANON_AND_FILE
; type
++)
3850 reset_ctrl_pos(lruvec
, type
, false);
3852 WRITE_ONCE(lrugen
->timestamps
[next
], jiffies
);
3853 /* make sure preceding modifications appear */
3854 smp_store_release(&lrugen
->max_seq
, lrugen
->max_seq
+ 1);
3856 spin_unlock_irq(&lruvec
->lru_lock
);
3861 static bool try_to_inc_max_seq(struct lruvec
*lruvec
, unsigned long seq
,
3862 bool can_swap
, bool force_scan
)
3865 struct lru_gen_mm_walk
*walk
;
3866 struct mm_struct
*mm
= NULL
;
3867 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3868 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
3870 VM_WARN_ON_ONCE(seq
> READ_ONCE(lrugen
->max_seq
));
3873 return inc_max_seq(lruvec
, seq
, can_swap
, force_scan
);
3875 /* see the comment in iterate_mm_list() */
3876 if (seq
<= READ_ONCE(mm_state
->seq
))
3880 * If the hardware doesn't automatically set the accessed bit, fallback
3881 * to lru_gen_look_around(), which only clears the accessed bit in a
3882 * handful of PTEs. Spreading the work out over a period of time usually
3883 * is less efficient, but it avoids bursty page faults.
3885 if (!should_walk_mmu()) {
3886 success
= iterate_mm_list_nowalk(lruvec
, seq
);
3890 walk
= set_mm_walk(NULL
, true);
3892 success
= iterate_mm_list_nowalk(lruvec
, seq
);
3896 walk
->lruvec
= lruvec
;
3898 walk
->can_swap
= can_swap
;
3899 walk
->force_scan
= force_scan
;
3902 success
= iterate_mm_list(walk
, &mm
);
3908 success
= inc_max_seq(lruvec
, seq
, can_swap
, force_scan
);
3909 WARN_ON_ONCE(!success
);
3915 /******************************************************************************
3916 * working set protection
3917 ******************************************************************************/
3919 static void set_initial_priority(struct pglist_data
*pgdat
, struct scan_control
*sc
)
3922 unsigned long reclaimable
;
3924 if (sc
->priority
!= DEF_PRIORITY
|| sc
->nr_to_reclaim
< MIN_LRU_BATCH
)
3927 * Determine the initial priority based on
3928 * (total >> priority) * reclaimed_to_scanned_ratio = nr_to_reclaim,
3929 * where reclaimed_to_scanned_ratio = inactive / total.
3931 reclaimable
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
3932 if (can_reclaim_anon_pages(NULL
, pgdat
->node_id
, sc
))
3933 reclaimable
+= node_page_state(pgdat
, NR_INACTIVE_ANON
);
3935 /* round down reclaimable and round up sc->nr_to_reclaim */
3936 priority
= fls_long(reclaimable
) - 1 - fls_long(sc
->nr_to_reclaim
- 1);
3939 * The estimation is based on LRU pages only, so cap it to prevent
3940 * overshoots of shrinker objects by large margins.
3942 sc
->priority
= clamp(priority
, DEF_PRIORITY
/ 2, DEF_PRIORITY
);
3945 static bool lruvec_is_sizable(struct lruvec
*lruvec
, struct scan_control
*sc
)
3947 int gen
, type
, zone
;
3948 unsigned long total
= 0;
3949 bool can_swap
= get_swappiness(lruvec
, sc
);
3950 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
3951 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
3952 DEFINE_MAX_SEQ(lruvec
);
3953 DEFINE_MIN_SEQ(lruvec
);
3955 for (type
= !can_swap
; type
< ANON_AND_FILE
; type
++) {
3958 for (seq
= min_seq
[type
]; seq
<= max_seq
; seq
++) {
3959 gen
= lru_gen_from_seq(seq
);
3961 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++)
3962 total
+= max(READ_ONCE(lrugen
->nr_pages
[gen
][type
][zone
]), 0L);
3966 /* whether the size is big enough to be helpful */
3967 return mem_cgroup_online(memcg
) ? (total
>> sc
->priority
) : total
;
3970 static bool lruvec_is_reclaimable(struct lruvec
*lruvec
, struct scan_control
*sc
,
3971 unsigned long min_ttl
)
3974 unsigned long birth
;
3975 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
3976 DEFINE_MIN_SEQ(lruvec
);
3978 if (mem_cgroup_below_min(NULL
, memcg
))
3981 if (!lruvec_is_sizable(lruvec
, sc
))
3984 /* see the comment on lru_gen_folio */
3985 gen
= lru_gen_from_seq(min_seq
[LRU_GEN_FILE
]);
3986 birth
= READ_ONCE(lruvec
->lrugen
.timestamps
[gen
]);
3988 return time_is_before_jiffies(birth
+ min_ttl
);
3991 /* to protect the working set of the last N jiffies */
3992 static unsigned long lru_gen_min_ttl __read_mostly
;
3994 static void lru_gen_age_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
3996 struct mem_cgroup
*memcg
;
3997 unsigned long min_ttl
= READ_ONCE(lru_gen_min_ttl
);
3998 bool reclaimable
= !min_ttl
;
4000 VM_WARN_ON_ONCE(!current_is_kswapd());
4002 set_initial_priority(pgdat
, sc
);
4004 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
4006 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
4008 mem_cgroup_calculate_protection(NULL
, memcg
);
4011 reclaimable
= lruvec_is_reclaimable(lruvec
, sc
, min_ttl
);
4012 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)));
4015 * The main goal is to OOM kill if every generation from all memcgs is
4016 * younger than min_ttl. However, another possibility is all memcgs are
4017 * either too small or below min.
4019 if (!reclaimable
&& mutex_trylock(&oom_lock
)) {
4020 struct oom_control oc
= {
4021 .gfp_mask
= sc
->gfp_mask
,
4026 mutex_unlock(&oom_lock
);
4030 /******************************************************************************
4031 * rmap/PT walk feedback
4032 ******************************************************************************/
4035 * This function exploits spatial locality when shrink_folio_list() walks the
4036 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4037 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4038 * the PTE table to the Bloom filter. This forms a feedback loop between the
4039 * eviction and the aging.
4041 bool lru_gen_look_around(struct page_vma_mapped_walk
*pvmw
)
4044 unsigned long start
;
4046 struct lru_gen_mm_walk
*walk
;
4048 pte_t
*pte
= pvmw
->pte
;
4049 unsigned long addr
= pvmw
->address
;
4050 struct vm_area_struct
*vma
= pvmw
->vma
;
4051 struct folio
*folio
= pfn_folio(pvmw
->pfn
);
4052 bool can_swap
= !folio_is_file_lru(folio
);
4053 struct mem_cgroup
*memcg
= folio_memcg(folio
);
4054 struct pglist_data
*pgdat
= folio_pgdat(folio
);
4055 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
4056 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
4057 DEFINE_MAX_SEQ(lruvec
);
4058 int old_gen
, new_gen
= lru_gen_from_seq(max_seq
);
4060 lockdep_assert_held(pvmw
->ptl
);
4061 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio
), folio
);
4063 if (!ptep_clear_young_notify(vma
, addr
, pte
))
4066 if (spin_is_contended(pvmw
->ptl
))
4069 /* exclude special VMAs containing anon pages from COW */
4070 if (vma
->vm_flags
& VM_SPECIAL
)
4073 /* avoid taking the LRU lock under the PTL when possible */
4074 walk
= current
->reclaim_state
? current
->reclaim_state
->mm_walk
: NULL
;
4076 start
= max(addr
& PMD_MASK
, vma
->vm_start
);
4077 end
= min(addr
| ~PMD_MASK
, vma
->vm_end
- 1) + 1;
4079 if (end
- start
== PAGE_SIZE
)
4082 if (end
- start
> MIN_LRU_BATCH
* PAGE_SIZE
) {
4083 if (addr
- start
< MIN_LRU_BATCH
* PAGE_SIZE
/ 2)
4084 end
= start
+ MIN_LRU_BATCH
* PAGE_SIZE
;
4085 else if (end
- addr
< MIN_LRU_BATCH
* PAGE_SIZE
/ 2)
4086 start
= end
- MIN_LRU_BATCH
* PAGE_SIZE
;
4088 start
= addr
- MIN_LRU_BATCH
* PAGE_SIZE
/ 2;
4089 end
= addr
+ MIN_LRU_BATCH
* PAGE_SIZE
/ 2;
4093 arch_enter_lazy_mmu_mode();
4095 pte
-= (addr
- start
) / PAGE_SIZE
;
4097 for (i
= 0, addr
= start
; addr
!= end
; i
++, addr
+= PAGE_SIZE
) {
4099 pte_t ptent
= ptep_get(pte
+ i
);
4101 pfn
= get_pte_pfn(ptent
, vma
, addr
, pgdat
);
4105 folio
= get_pfn_folio(pfn
, memcg
, pgdat
, can_swap
);
4109 if (!ptep_clear_young_notify(vma
, addr
, pte
+ i
))
4114 if (pte_dirty(ptent
) && !folio_test_dirty(folio
) &&
4115 !(folio_test_anon(folio
) && folio_test_swapbacked(folio
) &&
4116 !folio_test_swapcache(folio
)))
4117 folio_mark_dirty(folio
);
4120 old_gen
= folio_update_gen(folio
, new_gen
);
4121 if (old_gen
>= 0 && old_gen
!= new_gen
)
4122 update_batch_size(walk
, folio
, old_gen
, new_gen
);
4127 old_gen
= folio_lru_gen(folio
);
4129 folio_set_referenced(folio
);
4130 else if (old_gen
!= new_gen
) {
4131 folio_clear_lru_refs(folio
);
4132 folio_activate(folio
);
4136 arch_leave_lazy_mmu_mode();
4138 /* feedback from rmap walkers to page table walkers */
4139 if (mm_state
&& suitable_to_scan(i
, young
))
4140 update_bloom_filter(mm_state
, max_seq
, pvmw
->pmd
);
4145 /******************************************************************************
4147 ******************************************************************************/
4149 /* see the comment on MEMCG_NR_GENS */
4158 static void lru_gen_rotate_memcg(struct lruvec
*lruvec
, int op
)
4162 unsigned long flags
;
4163 int bin
= get_random_u32_below(MEMCG_NR_BINS
);
4164 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
4166 spin_lock_irqsave(&pgdat
->memcg_lru
.lock
, flags
);
4168 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec
->lrugen
.list
));
4171 new = old
= lruvec
->lrugen
.gen
;
4173 /* see the comment on MEMCG_NR_GENS */
4174 if (op
== MEMCG_LRU_HEAD
)
4175 seg
= MEMCG_LRU_HEAD
;
4176 else if (op
== MEMCG_LRU_TAIL
)
4177 seg
= MEMCG_LRU_TAIL
;
4178 else if (op
== MEMCG_LRU_OLD
)
4179 new = get_memcg_gen(pgdat
->memcg_lru
.seq
);
4180 else if (op
== MEMCG_LRU_YOUNG
)
4181 new = get_memcg_gen(pgdat
->memcg_lru
.seq
+ 1);
4183 VM_WARN_ON_ONCE(true);
4185 WRITE_ONCE(lruvec
->lrugen
.seg
, seg
);
4186 WRITE_ONCE(lruvec
->lrugen
.gen
, new);
4188 hlist_nulls_del_rcu(&lruvec
->lrugen
.list
);
4190 if (op
== MEMCG_LRU_HEAD
|| op
== MEMCG_LRU_OLD
)
4191 hlist_nulls_add_head_rcu(&lruvec
->lrugen
.list
, &pgdat
->memcg_lru
.fifo
[new][bin
]);
4193 hlist_nulls_add_tail_rcu(&lruvec
->lrugen
.list
, &pgdat
->memcg_lru
.fifo
[new][bin
]);
4195 pgdat
->memcg_lru
.nr_memcgs
[old
]--;
4196 pgdat
->memcg_lru
.nr_memcgs
[new]++;
4198 if (!pgdat
->memcg_lru
.nr_memcgs
[old
] && old
== get_memcg_gen(pgdat
->memcg_lru
.seq
))
4199 WRITE_ONCE(pgdat
->memcg_lru
.seq
, pgdat
->memcg_lru
.seq
+ 1);
4201 spin_unlock_irqrestore(&pgdat
->memcg_lru
.lock
, flags
);
4206 void lru_gen_online_memcg(struct mem_cgroup
*memcg
)
4210 int bin
= get_random_u32_below(MEMCG_NR_BINS
);
4212 for_each_node(nid
) {
4213 struct pglist_data
*pgdat
= NODE_DATA(nid
);
4214 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4216 spin_lock_irq(&pgdat
->memcg_lru
.lock
);
4218 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec
->lrugen
.list
));
4220 gen
= get_memcg_gen(pgdat
->memcg_lru
.seq
);
4222 lruvec
->lrugen
.gen
= gen
;
4224 hlist_nulls_add_tail_rcu(&lruvec
->lrugen
.list
, &pgdat
->memcg_lru
.fifo
[gen
][bin
]);
4225 pgdat
->memcg_lru
.nr_memcgs
[gen
]++;
4227 spin_unlock_irq(&pgdat
->memcg_lru
.lock
);
4231 void lru_gen_offline_memcg(struct mem_cgroup
*memcg
)
4235 for_each_node(nid
) {
4236 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4238 lru_gen_rotate_memcg(lruvec
, MEMCG_LRU_OLD
);
4242 void lru_gen_release_memcg(struct mem_cgroup
*memcg
)
4247 for_each_node(nid
) {
4248 struct pglist_data
*pgdat
= NODE_DATA(nid
);
4249 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4251 spin_lock_irq(&pgdat
->memcg_lru
.lock
);
4253 if (hlist_nulls_unhashed(&lruvec
->lrugen
.list
))
4256 gen
= lruvec
->lrugen
.gen
;
4258 hlist_nulls_del_init_rcu(&lruvec
->lrugen
.list
);
4259 pgdat
->memcg_lru
.nr_memcgs
[gen
]--;
4261 if (!pgdat
->memcg_lru
.nr_memcgs
[gen
] && gen
== get_memcg_gen(pgdat
->memcg_lru
.seq
))
4262 WRITE_ONCE(pgdat
->memcg_lru
.seq
, pgdat
->memcg_lru
.seq
+ 1);
4264 spin_unlock_irq(&pgdat
->memcg_lru
.lock
);
4268 void lru_gen_soft_reclaim(struct mem_cgroup
*memcg
, int nid
)
4270 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
4272 /* see the comment on MEMCG_NR_GENS */
4273 if (READ_ONCE(lruvec
->lrugen
.seg
) != MEMCG_LRU_HEAD
)
4274 lru_gen_rotate_memcg(lruvec
, MEMCG_LRU_HEAD
);
4277 #endif /* CONFIG_MEMCG */
4279 /******************************************************************************
4281 ******************************************************************************/
4283 static bool sort_folio(struct lruvec
*lruvec
, struct folio
*folio
, struct scan_control
*sc
,
4287 bool dirty
, writeback
;
4288 int gen
= folio_lru_gen(folio
);
4289 int type
= folio_is_file_lru(folio
);
4290 int zone
= folio_zonenum(folio
);
4291 int delta
= folio_nr_pages(folio
);
4292 int refs
= folio_lru_refs(folio
);
4293 int tier
= lru_tier_from_refs(refs
);
4294 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4296 VM_WARN_ON_ONCE_FOLIO(gen
>= MAX_NR_GENS
, folio
);
4299 if (!folio_evictable(folio
)) {
4300 success
= lru_gen_del_folio(lruvec
, folio
, true);
4301 VM_WARN_ON_ONCE_FOLIO(!success
, folio
);
4302 folio_set_unevictable(folio
);
4303 lruvec_add_folio(lruvec
, folio
);
4304 __count_vm_events(UNEVICTABLE_PGCULLED
, delta
);
4309 if (gen
!= lru_gen_from_seq(lrugen
->min_seq
[type
])) {
4310 list_move(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4315 if (tier
> tier_idx
|| refs
== BIT(LRU_REFS_WIDTH
)) {
4316 int hist
= lru_hist_from_seq(lrugen
->min_seq
[type
]);
4318 gen
= folio_inc_gen(lruvec
, folio
, false);
4319 list_move_tail(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4321 WRITE_ONCE(lrugen
->protected[hist
][type
][tier
- 1],
4322 lrugen
->protected[hist
][type
][tier
- 1] + delta
);
4327 if (!folio_test_lru(folio
) || zone
> sc
->reclaim_idx
) {
4328 gen
= folio_inc_gen(lruvec
, folio
, false);
4329 list_move_tail(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4333 dirty
= folio_test_dirty(folio
);
4334 writeback
= folio_test_writeback(folio
);
4335 if (type
== LRU_GEN_FILE
&& dirty
) {
4336 sc
->nr
.file_taken
+= delta
;
4338 sc
->nr
.unqueued_dirty
+= delta
;
4341 /* waiting for writeback */
4342 if (folio_test_locked(folio
) || writeback
||
4343 (type
== LRU_GEN_FILE
&& dirty
)) {
4344 gen
= folio_inc_gen(lruvec
, folio
, true);
4345 list_move(&folio
->lru
, &lrugen
->folios
[gen
][type
][zone
]);
4352 static bool isolate_folio(struct lruvec
*lruvec
, struct folio
*folio
, struct scan_control
*sc
)
4356 /* swap constrained */
4357 if (!(sc
->gfp_mask
& __GFP_IO
) &&
4358 (folio_test_dirty(folio
) ||
4359 (folio_test_anon(folio
) && !folio_test_swapcache(folio
))))
4362 /* raced with release_pages() */
4363 if (!folio_try_get(folio
))
4366 /* raced with another isolation */
4367 if (!folio_test_clear_lru(folio
)) {
4372 /* see the comment on MAX_NR_TIERS */
4373 if (!folio_test_referenced(folio
))
4374 folio_clear_lru_refs(folio
);
4376 /* for shrink_folio_list() */
4377 folio_clear_reclaim(folio
);
4378 folio_clear_referenced(folio
);
4380 success
= lru_gen_del_folio(lruvec
, folio
, true);
4381 VM_WARN_ON_ONCE_FOLIO(!success
, folio
);
4386 static int scan_folios(struct lruvec
*lruvec
, struct scan_control
*sc
,
4387 int type
, int tier
, struct list_head
*list
)
4391 enum vm_event_item item
;
4396 int remaining
= MAX_LRU_BATCH
;
4397 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4398 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4400 VM_WARN_ON_ONCE(!list_empty(list
));
4402 if (get_nr_gens(lruvec
, type
) == MIN_NR_GENS
)
4405 gen
= lru_gen_from_seq(lrugen
->min_seq
[type
]);
4407 for (i
= MAX_NR_ZONES
; i
> 0; i
--) {
4409 int skipped_zone
= 0;
4410 int zone
= (sc
->reclaim_idx
+ i
) % MAX_NR_ZONES
;
4411 struct list_head
*head
= &lrugen
->folios
[gen
][type
][zone
];
4413 while (!list_empty(head
)) {
4414 struct folio
*folio
= lru_to_folio(head
);
4415 int delta
= folio_nr_pages(folio
);
4417 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
4418 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
), folio
);
4419 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
4420 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio
) != zone
, folio
);
4424 if (sort_folio(lruvec
, folio
, sc
, tier
))
4426 else if (isolate_folio(lruvec
, folio
, sc
)) {
4427 list_add(&folio
->lru
, list
);
4430 list_move(&folio
->lru
, &moved
);
4431 skipped_zone
+= delta
;
4434 if (!--remaining
|| max(isolated
, skipped_zone
) >= MIN_LRU_BATCH
)
4439 list_splice(&moved
, head
);
4440 __count_zid_vm_events(PGSCAN_SKIP
, zone
, skipped_zone
);
4441 skipped
+= skipped_zone
;
4444 if (!remaining
|| isolated
>= MIN_LRU_BATCH
)
4448 item
= PGSCAN_KSWAPD
+ reclaimer_offset();
4449 if (!cgroup_reclaim(sc
)) {
4450 __count_vm_events(item
, isolated
);
4451 __count_vm_events(PGREFILL
, sorted
);
4453 __count_memcg_events(memcg
, item
, isolated
);
4454 __count_memcg_events(memcg
, PGREFILL
, sorted
);
4455 __count_vm_events(PGSCAN_ANON
+ type
, isolated
);
4456 trace_mm_vmscan_lru_isolate(sc
->reclaim_idx
, sc
->order
, MAX_LRU_BATCH
,
4457 scanned
, skipped
, isolated
,
4458 type
? LRU_INACTIVE_FILE
: LRU_INACTIVE_ANON
);
4459 if (type
== LRU_GEN_FILE
)
4460 sc
->nr
.file_taken
+= isolated
;
4462 * There might not be eligible folios due to reclaim_idx. Check the
4463 * remaining to prevent livelock if it's not making progress.
4465 return isolated
|| !remaining
? scanned
: 0;
4468 static int get_tier_idx(struct lruvec
*lruvec
, int type
)
4471 struct ctrl_pos sp
, pv
;
4474 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4475 * This value is chosen because any other tier would have at least twice
4476 * as many refaults as the first tier.
4478 read_ctrl_pos(lruvec
, type
, 0, 1, &sp
);
4479 for (tier
= 1; tier
< MAX_NR_TIERS
; tier
++) {
4480 read_ctrl_pos(lruvec
, type
, tier
, 2, &pv
);
4481 if (!positive_ctrl_err(&sp
, &pv
))
4488 static int get_type_to_scan(struct lruvec
*lruvec
, int swappiness
, int *tier_idx
)
4491 struct ctrl_pos sp
, pv
;
4492 int gain
[ANON_AND_FILE
] = { swappiness
, MAX_SWAPPINESS
- swappiness
};
4495 * Compare the first tier of anon with that of file to determine which
4496 * type to scan. Also need to compare other tiers of the selected type
4497 * with the first tier of the other type to determine the last tier (of
4498 * the selected type) to evict.
4500 read_ctrl_pos(lruvec
, LRU_GEN_ANON
, 0, gain
[LRU_GEN_ANON
], &sp
);
4501 read_ctrl_pos(lruvec
, LRU_GEN_FILE
, 0, gain
[LRU_GEN_FILE
], &pv
);
4502 type
= positive_ctrl_err(&sp
, &pv
);
4504 read_ctrl_pos(lruvec
, !type
, 0, gain
[!type
], &sp
);
4505 for (tier
= 1; tier
< MAX_NR_TIERS
; tier
++) {
4506 read_ctrl_pos(lruvec
, type
, tier
, gain
[type
], &pv
);
4507 if (!positive_ctrl_err(&sp
, &pv
))
4511 *tier_idx
= tier
- 1;
4516 static int isolate_folios(struct lruvec
*lruvec
, struct scan_control
*sc
, int swappiness
,
4517 int *type_scanned
, struct list_head
*list
)
4523 DEFINE_MIN_SEQ(lruvec
);
4526 * Try to make the obvious choice first, and if anon and file are both
4527 * available from the same generation,
4528 * 1. Interpret swappiness 1 as file first and MAX_SWAPPINESS as anon
4530 * 2. If !__GFP_IO, file first since clean pagecache is more likely to
4531 * exist than clean swapcache.
4534 type
= LRU_GEN_FILE
;
4535 else if (min_seq
[LRU_GEN_ANON
] < min_seq
[LRU_GEN_FILE
])
4536 type
= LRU_GEN_ANON
;
4537 else if (swappiness
== 1)
4538 type
= LRU_GEN_FILE
;
4539 else if (swappiness
== MAX_SWAPPINESS
)
4540 type
= LRU_GEN_ANON
;
4541 else if (!(sc
->gfp_mask
& __GFP_IO
))
4542 type
= LRU_GEN_FILE
;
4544 type
= get_type_to_scan(lruvec
, swappiness
, &tier
);
4546 for (i
= !swappiness
; i
< ANON_AND_FILE
; i
++) {
4548 tier
= get_tier_idx(lruvec
, type
);
4550 scanned
= scan_folios(lruvec
, sc
, type
, tier
, list
);
4558 *type_scanned
= type
;
4563 static int evict_folios(struct lruvec
*lruvec
, struct scan_control
*sc
, int swappiness
)
4570 struct folio
*folio
;
4572 enum vm_event_item item
;
4573 struct reclaim_stat stat
;
4574 struct lru_gen_mm_walk
*walk
;
4575 bool skip_retry
= false;
4576 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4577 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
4579 spin_lock_irq(&lruvec
->lru_lock
);
4581 scanned
= isolate_folios(lruvec
, sc
, swappiness
, &type
, &list
);
4583 scanned
+= try_to_inc_min_seq(lruvec
, swappiness
);
4585 if (get_nr_gens(lruvec
, !swappiness
) == MIN_NR_GENS
)
4588 spin_unlock_irq(&lruvec
->lru_lock
);
4590 if (list_empty(&list
))
4593 reclaimed
= shrink_folio_list(&list
, pgdat
, sc
, &stat
, false);
4594 sc
->nr
.unqueued_dirty
+= stat
.nr_unqueued_dirty
;
4595 sc
->nr_reclaimed
+= reclaimed
;
4596 trace_mm_vmscan_lru_shrink_inactive(pgdat
->node_id
,
4597 scanned
, reclaimed
, &stat
, sc
->priority
,
4598 type
? LRU_INACTIVE_FILE
: LRU_INACTIVE_ANON
);
4600 list_for_each_entry_safe_reverse(folio
, next
, &list
, lru
) {
4601 if (!folio_evictable(folio
)) {
4602 list_del(&folio
->lru
);
4603 folio_putback_lru(folio
);
4607 if (folio_test_reclaim(folio
) &&
4608 (folio_test_dirty(folio
) || folio_test_writeback(folio
))) {
4609 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
4610 if (folio_test_workingset(folio
))
4611 folio_set_referenced(folio
);
4615 if (skip_retry
|| folio_test_active(folio
) || folio_test_referenced(folio
) ||
4616 folio_mapped(folio
) || folio_test_locked(folio
) ||
4617 folio_test_dirty(folio
) || folio_test_writeback(folio
)) {
4618 /* don't add rejected folios to the oldest generation */
4619 set_mask_bits(&folio
->flags
, LRU_REFS_MASK
| LRU_REFS_FLAGS
,
4624 /* retry folios that may have missed folio_rotate_reclaimable() */
4625 list_move(&folio
->lru
, &clean
);
4628 spin_lock_irq(&lruvec
->lru_lock
);
4630 move_folios_to_lru(lruvec
, &list
);
4632 walk
= current
->reclaim_state
->mm_walk
;
4633 if (walk
&& walk
->batched
) {
4634 walk
->lruvec
= lruvec
;
4635 reset_batch_size(walk
);
4638 item
= PGSTEAL_KSWAPD
+ reclaimer_offset();
4639 if (!cgroup_reclaim(sc
))
4640 __count_vm_events(item
, reclaimed
);
4641 __count_memcg_events(memcg
, item
, reclaimed
);
4642 __count_vm_events(PGSTEAL_ANON
+ type
, reclaimed
);
4644 spin_unlock_irq(&lruvec
->lru_lock
);
4646 list_splice_init(&clean
, &list
);
4648 if (!list_empty(&list
)) {
4656 static bool should_run_aging(struct lruvec
*lruvec
, unsigned long max_seq
,
4657 bool can_swap
, unsigned long *nr_to_scan
)
4659 int gen
, type
, zone
;
4660 unsigned long old
= 0;
4661 unsigned long young
= 0;
4662 unsigned long total
= 0;
4663 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4664 DEFINE_MIN_SEQ(lruvec
);
4666 /* whether this lruvec is completely out of cold folios */
4667 if (min_seq
[!can_swap
] + MIN_NR_GENS
> max_seq
) {
4672 for (type
= !can_swap
; type
< ANON_AND_FILE
; type
++) {
4675 for (seq
= min_seq
[type
]; seq
<= max_seq
; seq
++) {
4676 unsigned long size
= 0;
4678 gen
= lru_gen_from_seq(seq
);
4680 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++)
4681 size
+= max(READ_ONCE(lrugen
->nr_pages
[gen
][type
][zone
]), 0L);
4686 else if (seq
+ MIN_NR_GENS
== max_seq
)
4691 *nr_to_scan
= total
;
4694 * The aging tries to be lazy to reduce the overhead, while the eviction
4695 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4696 * ideal number of generations is MIN_NR_GENS+1.
4698 if (min_seq
[!can_swap
] + MIN_NR_GENS
< max_seq
)
4702 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4703 * of the total number of pages for each generation. A reasonable range
4704 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4705 * aging cares about the upper bound of hot pages, while the eviction
4706 * cares about the lower bound of cold pages.
4708 if (young
* MIN_NR_GENS
> total
)
4710 if (old
* (MIN_NR_GENS
+ 2) < total
)
4717 * For future optimizations:
4718 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4721 static long get_nr_to_scan(struct lruvec
*lruvec
, struct scan_control
*sc
, bool can_swap
)
4724 unsigned long nr_to_scan
;
4725 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4726 DEFINE_MAX_SEQ(lruvec
);
4728 if (mem_cgroup_below_min(sc
->target_mem_cgroup
, memcg
))
4731 success
= should_run_aging(lruvec
, max_seq
, can_swap
, &nr_to_scan
);
4733 /* try to scrape all its memory if this memcg was deleted */
4734 if (nr_to_scan
&& !mem_cgroup_online(memcg
))
4737 /* try to get away with not aging at the default priority */
4738 if (!success
|| sc
->priority
== DEF_PRIORITY
)
4739 return nr_to_scan
>> sc
->priority
;
4741 /* stop scanning this lruvec as it's low on cold folios */
4742 return try_to_inc_max_seq(lruvec
, max_seq
, can_swap
, false) ? -1 : 0;
4745 static bool should_abort_scan(struct lruvec
*lruvec
, struct scan_control
*sc
)
4748 enum zone_watermarks mark
;
4750 /* don't abort memcg reclaim to ensure fairness */
4751 if (!root_reclaim(sc
))
4754 if (sc
->nr_reclaimed
>= max(sc
->nr_to_reclaim
, compact_gap(sc
->order
)))
4757 /* check the order to exclude compaction-induced reclaim */
4758 if (!current_is_kswapd() || sc
->order
)
4761 mark
= sysctl_numa_balancing_mode
& NUMA_BALANCING_MEMORY_TIERING
?
4762 WMARK_PROMO
: WMARK_HIGH
;
4764 for (i
= 0; i
<= sc
->reclaim_idx
; i
++) {
4765 struct zone
*zone
= lruvec_pgdat(lruvec
)->node_zones
+ i
;
4766 unsigned long size
= wmark_pages(zone
, mark
) + MIN_LRU_BATCH
;
4768 if (managed_zone(zone
) && !zone_watermark_ok(zone
, 0, size
, sc
->reclaim_idx
, 0))
4772 /* kswapd should abort if all eligible zones are safe */
4776 static bool try_to_shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
4779 unsigned long scanned
= 0;
4780 int swappiness
= get_swappiness(lruvec
, sc
);
4785 nr_to_scan
= get_nr_to_scan(lruvec
, sc
, swappiness
);
4786 if (nr_to_scan
<= 0)
4789 delta
= evict_folios(lruvec
, sc
, swappiness
);
4794 if (scanned
>= nr_to_scan
)
4797 if (should_abort_scan(lruvec
, sc
))
4804 * If too many file cache in the coldest generation can't be evicted
4805 * due to being dirty, wake up the flusher.
4807 if (sc
->nr
.unqueued_dirty
&& sc
->nr
.unqueued_dirty
== sc
->nr
.file_taken
)
4808 wakeup_flusher_threads(WB_REASON_VMSCAN
);
4810 /* whether this lruvec should be rotated */
4811 return nr_to_scan
< 0;
4814 static int shrink_one(struct lruvec
*lruvec
, struct scan_control
*sc
)
4817 unsigned long scanned
= sc
->nr_scanned
;
4818 unsigned long reclaimed
= sc
->nr_reclaimed
;
4819 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
4820 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
4822 /* lru_gen_age_node() called mem_cgroup_calculate_protection() */
4823 if (mem_cgroup_below_min(NULL
, memcg
))
4824 return MEMCG_LRU_YOUNG
;
4826 if (mem_cgroup_below_low(NULL
, memcg
)) {
4827 /* see the comment on MEMCG_NR_GENS */
4828 if (READ_ONCE(lruvec
->lrugen
.seg
) != MEMCG_LRU_TAIL
)
4829 return MEMCG_LRU_TAIL
;
4831 memcg_memory_event(memcg
, MEMCG_LOW
);
4834 success
= try_to_shrink_lruvec(lruvec
, sc
);
4836 shrink_slab(sc
->gfp_mask
, pgdat
->node_id
, memcg
, sc
->priority
);
4839 vmpressure(sc
->gfp_mask
, memcg
, false, sc
->nr_scanned
- scanned
,
4840 sc
->nr_reclaimed
- reclaimed
);
4842 flush_reclaim_state(sc
);
4844 if (success
&& mem_cgroup_online(memcg
))
4845 return MEMCG_LRU_YOUNG
;
4847 if (!success
&& lruvec_is_sizable(lruvec
, sc
))
4850 /* one retry if offlined or too small */
4851 return READ_ONCE(lruvec
->lrugen
.seg
) != MEMCG_LRU_TAIL
?
4852 MEMCG_LRU_TAIL
: MEMCG_LRU_YOUNG
;
4855 static void shrink_many(struct pglist_data
*pgdat
, struct scan_control
*sc
)
4861 struct lruvec
*lruvec
;
4862 struct lru_gen_folio
*lrugen
;
4863 struct mem_cgroup
*memcg
;
4864 struct hlist_nulls_node
*pos
;
4866 gen
= get_memcg_gen(READ_ONCE(pgdat
->memcg_lru
.seq
));
4867 bin
= first_bin
= get_random_u32_below(MEMCG_NR_BINS
);
4874 hlist_nulls_for_each_entry_rcu(lrugen
, pos
, &pgdat
->memcg_lru
.fifo
[gen
][bin
], list
) {
4876 lru_gen_rotate_memcg(lruvec
, op
);
4880 mem_cgroup_put(memcg
);
4883 if (gen
!= READ_ONCE(lrugen
->gen
))
4886 lruvec
= container_of(lrugen
, struct lruvec
, lrugen
);
4887 memcg
= lruvec_memcg(lruvec
);
4889 if (!mem_cgroup_tryget(memcg
)) {
4890 lru_gen_release_memcg(memcg
);
4897 op
= shrink_one(lruvec
, sc
);
4901 if (should_abort_scan(lruvec
, sc
))
4908 lru_gen_rotate_memcg(lruvec
, op
);
4910 mem_cgroup_put(memcg
);
4912 if (!is_a_nulls(pos
))
4915 /* restart if raced with lru_gen_rotate_memcg() */
4916 if (gen
!= get_nulls_value(pos
))
4919 /* try the rest of the bins of the current generation */
4920 bin
= get_memcg_bin(bin
+ 1);
4921 if (bin
!= first_bin
)
4925 static void lru_gen_shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
4927 struct blk_plug plug
;
4929 VM_WARN_ON_ONCE(root_reclaim(sc
));
4930 VM_WARN_ON_ONCE(!sc
->may_writepage
|| !sc
->may_unmap
);
4934 blk_start_plug(&plug
);
4936 set_mm_walk(NULL
, sc
->proactive
);
4938 if (try_to_shrink_lruvec(lruvec
, sc
))
4939 lru_gen_rotate_memcg(lruvec
, MEMCG_LRU_YOUNG
);
4943 blk_finish_plug(&plug
);
4946 static void lru_gen_shrink_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
4948 struct blk_plug plug
;
4949 unsigned long reclaimed
= sc
->nr_reclaimed
;
4951 VM_WARN_ON_ONCE(!root_reclaim(sc
));
4954 * Unmapped clean folios are already prioritized. Scanning for more of
4955 * them is likely futile and can cause high reclaim latency when there
4956 * is a large number of memcgs.
4958 if (!sc
->may_writepage
|| !sc
->may_unmap
)
4963 blk_start_plug(&plug
);
4965 set_mm_walk(pgdat
, sc
->proactive
);
4967 set_initial_priority(pgdat
, sc
);
4969 if (current_is_kswapd())
4970 sc
->nr_reclaimed
= 0;
4972 if (mem_cgroup_disabled())
4973 shrink_one(&pgdat
->__lruvec
, sc
);
4975 shrink_many(pgdat
, sc
);
4977 if (current_is_kswapd())
4978 sc
->nr_reclaimed
+= reclaimed
;
4982 blk_finish_plug(&plug
);
4984 if (sc
->nr_reclaimed
> reclaimed
)
4985 pgdat
->kswapd_failures
= 0;
4988 /******************************************************************************
4990 ******************************************************************************/
4992 static bool __maybe_unused
state_is_valid(struct lruvec
*lruvec
)
4994 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
4996 if (lrugen
->enabled
) {
4999 for_each_evictable_lru(lru
) {
5000 if (!list_empty(&lruvec
->lists
[lru
]))
5004 int gen
, type
, zone
;
5006 for_each_gen_type_zone(gen
, type
, zone
) {
5007 if (!list_empty(&lrugen
->folios
[gen
][type
][zone
]))
5015 static bool fill_evictable(struct lruvec
*lruvec
)
5018 int remaining
= MAX_LRU_BATCH
;
5020 for_each_evictable_lru(lru
) {
5021 int type
= is_file_lru(lru
);
5022 bool active
= is_active_lru(lru
);
5023 struct list_head
*head
= &lruvec
->lists
[lru
];
5025 while (!list_empty(head
)) {
5027 struct folio
*folio
= lru_to_folio(head
);
5029 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
5030 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
) != active
, folio
);
5031 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
5032 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio
) != -1, folio
);
5034 lruvec_del_folio(lruvec
, folio
);
5035 success
= lru_gen_add_folio(lruvec
, folio
, false);
5036 VM_WARN_ON_ONCE(!success
);
5046 static bool drain_evictable(struct lruvec
*lruvec
)
5048 int gen
, type
, zone
;
5049 int remaining
= MAX_LRU_BATCH
;
5051 for_each_gen_type_zone(gen
, type
, zone
) {
5052 struct list_head
*head
= &lruvec
->lrugen
.folios
[gen
][type
][zone
];
5054 while (!list_empty(head
)) {
5056 struct folio
*folio
= lru_to_folio(head
);
5058 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio
), folio
);
5059 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio
), folio
);
5060 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio
) != type
, folio
);
5061 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio
) != zone
, folio
);
5063 success
= lru_gen_del_folio(lruvec
, folio
, false);
5064 VM_WARN_ON_ONCE(!success
);
5065 lruvec_add_folio(lruvec
, folio
);
5075 static void lru_gen_change_state(bool enabled
)
5077 static DEFINE_MUTEX(state_mutex
);
5079 struct mem_cgroup
*memcg
;
5084 mutex_lock(&state_mutex
);
5086 if (enabled
== lru_gen_enabled())
5090 static_branch_enable_cpuslocked(&lru_gen_caps
[LRU_GEN_CORE
]);
5092 static_branch_disable_cpuslocked(&lru_gen_caps
[LRU_GEN_CORE
]);
5094 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
5098 for_each_node(nid
) {
5099 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
5101 spin_lock_irq(&lruvec
->lru_lock
);
5103 VM_WARN_ON_ONCE(!seq_is_valid(lruvec
));
5104 VM_WARN_ON_ONCE(!state_is_valid(lruvec
));
5106 lruvec
->lrugen
.enabled
= enabled
;
5108 while (!(enabled
? fill_evictable(lruvec
) : drain_evictable(lruvec
))) {
5109 spin_unlock_irq(&lruvec
->lru_lock
);
5111 spin_lock_irq(&lruvec
->lru_lock
);
5114 spin_unlock_irq(&lruvec
->lru_lock
);
5118 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)));
5120 mutex_unlock(&state_mutex
);
5126 /******************************************************************************
5128 ******************************************************************************/
5130 static ssize_t
min_ttl_ms_show(struct kobject
*kobj
, struct kobj_attribute
*attr
, char *buf
)
5132 return sysfs_emit(buf
, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl
)));
5135 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5136 static ssize_t
min_ttl_ms_store(struct kobject
*kobj
, struct kobj_attribute
*attr
,
5137 const char *buf
, size_t len
)
5141 if (kstrtouint(buf
, 0, &msecs
))
5144 WRITE_ONCE(lru_gen_min_ttl
, msecs_to_jiffies(msecs
));
5149 static struct kobj_attribute lru_gen_min_ttl_attr
= __ATTR_RW(min_ttl_ms
);
5151 static ssize_t
enabled_show(struct kobject
*kobj
, struct kobj_attribute
*attr
, char *buf
)
5153 unsigned int caps
= 0;
5155 if (get_cap(LRU_GEN_CORE
))
5156 caps
|= BIT(LRU_GEN_CORE
);
5158 if (should_walk_mmu())
5159 caps
|= BIT(LRU_GEN_MM_WALK
);
5161 if (should_clear_pmd_young())
5162 caps
|= BIT(LRU_GEN_NONLEAF_YOUNG
);
5164 return sysfs_emit(buf
, "0x%04x\n", caps
);
5167 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5168 static ssize_t
enabled_store(struct kobject
*kobj
, struct kobj_attribute
*attr
,
5169 const char *buf
, size_t len
)
5174 if (tolower(*buf
) == 'n')
5176 else if (tolower(*buf
) == 'y')
5178 else if (kstrtouint(buf
, 0, &caps
))
5181 for (i
= 0; i
< NR_LRU_GEN_CAPS
; i
++) {
5182 bool enabled
= caps
& BIT(i
);
5184 if (i
== LRU_GEN_CORE
)
5185 lru_gen_change_state(enabled
);
5187 static_branch_enable(&lru_gen_caps
[i
]);
5189 static_branch_disable(&lru_gen_caps
[i
]);
5195 static struct kobj_attribute lru_gen_enabled_attr
= __ATTR_RW(enabled
);
5197 static struct attribute
*lru_gen_attrs
[] = {
5198 &lru_gen_min_ttl_attr
.attr
,
5199 &lru_gen_enabled_attr
.attr
,
5203 static const struct attribute_group lru_gen_attr_group
= {
5205 .attrs
= lru_gen_attrs
,
5208 /******************************************************************************
5210 ******************************************************************************/
5212 static void *lru_gen_seq_start(struct seq_file
*m
, loff_t
*pos
)
5214 struct mem_cgroup
*memcg
;
5215 loff_t nr_to_skip
= *pos
;
5217 m
->private = kvmalloc(PATH_MAX
, GFP_KERNEL
);
5219 return ERR_PTR(-ENOMEM
);
5221 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
5225 for_each_node_state(nid
, N_MEMORY
) {
5227 return get_lruvec(memcg
, nid
);
5229 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)));
5234 static void lru_gen_seq_stop(struct seq_file
*m
, void *v
)
5236 if (!IS_ERR_OR_NULL(v
))
5237 mem_cgroup_iter_break(NULL
, lruvec_memcg(v
));
5243 static void *lru_gen_seq_next(struct seq_file
*m
, void *v
, loff_t
*pos
)
5245 int nid
= lruvec_pgdat(v
)->node_id
;
5246 struct mem_cgroup
*memcg
= lruvec_memcg(v
);
5250 nid
= next_memory_node(nid
);
5251 if (nid
== MAX_NUMNODES
) {
5252 memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
);
5256 nid
= first_memory_node
;
5259 return get_lruvec(memcg
, nid
);
5262 static void lru_gen_seq_show_full(struct seq_file
*m
, struct lruvec
*lruvec
,
5263 unsigned long max_seq
, unsigned long *min_seq
,
5268 int hist
= lru_hist_from_seq(seq
);
5269 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
5270 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
5272 for (tier
= 0; tier
< MAX_NR_TIERS
; tier
++) {
5273 seq_printf(m
, " %10d", tier
);
5274 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
5275 const char *s
= "xxx";
5276 unsigned long n
[3] = {};
5278 if (seq
== max_seq
) {
5280 n
[0] = READ_ONCE(lrugen
->avg_refaulted
[type
][tier
]);
5281 n
[1] = READ_ONCE(lrugen
->avg_total
[type
][tier
]);
5282 } else if (seq
== min_seq
[type
] || NR_HIST_GENS
> 1) {
5284 n
[0] = atomic_long_read(&lrugen
->refaulted
[hist
][type
][tier
]);
5285 n
[1] = atomic_long_read(&lrugen
->evicted
[hist
][type
][tier
]);
5287 n
[2] = READ_ONCE(lrugen
->protected[hist
][type
][tier
- 1]);
5290 for (i
= 0; i
< 3; i
++)
5291 seq_printf(m
, " %10lu%c", n
[i
], s
[i
]);
5300 for (i
= 0; i
< NR_MM_STATS
; i
++) {
5301 const char *s
= "xxxx";
5302 unsigned long n
= 0;
5304 if (seq
== max_seq
&& NR_HIST_GENS
== 1) {
5306 n
= READ_ONCE(mm_state
->stats
[hist
][i
]);
5307 } else if (seq
!= max_seq
&& NR_HIST_GENS
> 1) {
5309 n
= READ_ONCE(mm_state
->stats
[hist
][i
]);
5312 seq_printf(m
, " %10lu%c", n
, s
[i
]);
5317 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5318 static int lru_gen_seq_show(struct seq_file
*m
, void *v
)
5321 bool full
= !debugfs_real_fops(m
->file
)->write
;
5322 struct lruvec
*lruvec
= v
;
5323 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
5324 int nid
= lruvec_pgdat(lruvec
)->node_id
;
5325 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
5326 DEFINE_MAX_SEQ(lruvec
);
5327 DEFINE_MIN_SEQ(lruvec
);
5329 if (nid
== first_memory_node
) {
5330 const char *path
= memcg
? m
->private : "";
5334 cgroup_path(memcg
->css
.cgroup
, m
->private, PATH_MAX
);
5336 seq_printf(m
, "memcg %5hu %s\n", mem_cgroup_id(memcg
), path
);
5339 seq_printf(m
, " node %5d\n", nid
);
5342 seq
= min_seq
[LRU_GEN_ANON
];
5343 else if (max_seq
>= MAX_NR_GENS
)
5344 seq
= max_seq
- MAX_NR_GENS
+ 1;
5348 for (; seq
<= max_seq
; seq
++) {
5350 int gen
= lru_gen_from_seq(seq
);
5351 unsigned long birth
= READ_ONCE(lruvec
->lrugen
.timestamps
[gen
]);
5353 seq_printf(m
, " %10lu %10u", seq
, jiffies_to_msecs(jiffies
- birth
));
5355 for (type
= 0; type
< ANON_AND_FILE
; type
++) {
5356 unsigned long size
= 0;
5357 char mark
= full
&& seq
< min_seq
[type
] ? 'x' : ' ';
5359 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++)
5360 size
+= max(READ_ONCE(lrugen
->nr_pages
[gen
][type
][zone
]), 0L);
5362 seq_printf(m
, " %10lu%c", size
, mark
);
5368 lru_gen_seq_show_full(m
, lruvec
, max_seq
, min_seq
, seq
);
5374 static const struct seq_operations lru_gen_seq_ops
= {
5375 .start
= lru_gen_seq_start
,
5376 .stop
= lru_gen_seq_stop
,
5377 .next
= lru_gen_seq_next
,
5378 .show
= lru_gen_seq_show
,
5381 static int run_aging(struct lruvec
*lruvec
, unsigned long seq
,
5382 bool can_swap
, bool force_scan
)
5384 DEFINE_MAX_SEQ(lruvec
);
5385 DEFINE_MIN_SEQ(lruvec
);
5393 if (!force_scan
&& min_seq
[!can_swap
] + MAX_NR_GENS
- 1 <= max_seq
)
5396 try_to_inc_max_seq(lruvec
, max_seq
, can_swap
, force_scan
);
5401 static int run_eviction(struct lruvec
*lruvec
, unsigned long seq
, struct scan_control
*sc
,
5402 int swappiness
, unsigned long nr_to_reclaim
)
5404 DEFINE_MAX_SEQ(lruvec
);
5406 if (seq
+ MIN_NR_GENS
> max_seq
)
5409 sc
->nr_reclaimed
= 0;
5411 while (!signal_pending(current
)) {
5412 DEFINE_MIN_SEQ(lruvec
);
5414 if (seq
< min_seq
[!swappiness
])
5417 if (sc
->nr_reclaimed
>= nr_to_reclaim
)
5420 if (!evict_folios(lruvec
, sc
, swappiness
))
5429 static int run_cmd(char cmd
, int memcg_id
, int nid
, unsigned long seq
,
5430 struct scan_control
*sc
, int swappiness
, unsigned long opt
)
5432 struct lruvec
*lruvec
;
5434 struct mem_cgroup
*memcg
= NULL
;
5436 if (nid
< 0 || nid
>= MAX_NUMNODES
|| !node_state(nid
, N_MEMORY
))
5439 if (!mem_cgroup_disabled()) {
5442 memcg
= mem_cgroup_from_id(memcg_id
);
5443 if (!mem_cgroup_tryget(memcg
))
5452 if (memcg_id
!= mem_cgroup_id(memcg
))
5455 lruvec
= get_lruvec(memcg
, nid
);
5457 if (swappiness
< MIN_SWAPPINESS
)
5458 swappiness
= get_swappiness(lruvec
, sc
);
5459 else if (swappiness
> MAX_SWAPPINESS
)
5464 err
= run_aging(lruvec
, seq
, swappiness
, opt
);
5467 err
= run_eviction(lruvec
, seq
, sc
, swappiness
, opt
);
5471 mem_cgroup_put(memcg
);
5476 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5477 static ssize_t
lru_gen_seq_write(struct file
*file
, const char __user
*src
,
5478 size_t len
, loff_t
*pos
)
5483 struct blk_plug plug
;
5485 struct scan_control sc
= {
5486 .may_writepage
= true,
5489 .reclaim_idx
= MAX_NR_ZONES
- 1,
5490 .gfp_mask
= GFP_KERNEL
,
5493 buf
= kvmalloc(len
+ 1, GFP_KERNEL
);
5497 if (copy_from_user(buf
, src
, len
)) {
5502 set_task_reclaim_state(current
, &sc
.reclaim_state
);
5503 flags
= memalloc_noreclaim_save();
5504 blk_start_plug(&plug
);
5505 if (!set_mm_walk(NULL
, true)) {
5513 while ((cur
= strsep(&next
, ",;\n"))) {
5517 unsigned int memcg_id
;
5520 unsigned int swappiness
= -1;
5521 unsigned long opt
= -1;
5523 cur
= skip_spaces(cur
);
5527 n
= sscanf(cur
, "%c %u %u %lu %n %u %n %lu %n", &cmd
, &memcg_id
, &nid
,
5528 &seq
, &end
, &swappiness
, &end
, &opt
, &end
);
5529 if (n
< 4 || cur
[end
]) {
5534 err
= run_cmd(cmd
, memcg_id
, nid
, seq
, &sc
, swappiness
, opt
);
5540 blk_finish_plug(&plug
);
5541 memalloc_noreclaim_restore(flags
);
5542 set_task_reclaim_state(current
, NULL
);
5549 static int lru_gen_seq_open(struct inode
*inode
, struct file
*file
)
5551 return seq_open(file
, &lru_gen_seq_ops
);
5554 static const struct file_operations lru_gen_rw_fops
= {
5555 .open
= lru_gen_seq_open
,
5557 .write
= lru_gen_seq_write
,
5558 .llseek
= seq_lseek
,
5559 .release
= seq_release
,
5562 static const struct file_operations lru_gen_ro_fops
= {
5563 .open
= lru_gen_seq_open
,
5565 .llseek
= seq_lseek
,
5566 .release
= seq_release
,
5569 /******************************************************************************
5571 ******************************************************************************/
5573 void lru_gen_init_pgdat(struct pglist_data
*pgdat
)
5577 spin_lock_init(&pgdat
->memcg_lru
.lock
);
5579 for (i
= 0; i
< MEMCG_NR_GENS
; i
++) {
5580 for (j
= 0; j
< MEMCG_NR_BINS
; j
++)
5581 INIT_HLIST_NULLS_HEAD(&pgdat
->memcg_lru
.fifo
[i
][j
], i
);
5585 void lru_gen_init_lruvec(struct lruvec
*lruvec
)
5588 int gen
, type
, zone
;
5589 struct lru_gen_folio
*lrugen
= &lruvec
->lrugen
;
5590 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
5592 lrugen
->max_seq
= MIN_NR_GENS
+ 1;
5593 lrugen
->enabled
= lru_gen_enabled();
5595 for (i
= 0; i
<= MIN_NR_GENS
+ 1; i
++)
5596 lrugen
->timestamps
[i
] = jiffies
;
5598 for_each_gen_type_zone(gen
, type
, zone
)
5599 INIT_LIST_HEAD(&lrugen
->folios
[gen
][type
][zone
]);
5602 mm_state
->seq
= MIN_NR_GENS
;
5607 void lru_gen_init_memcg(struct mem_cgroup
*memcg
)
5609 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
5614 INIT_LIST_HEAD(&mm_list
->fifo
);
5615 spin_lock_init(&mm_list
->lock
);
5618 void lru_gen_exit_memcg(struct mem_cgroup
*memcg
)
5622 struct lru_gen_mm_list
*mm_list
= get_mm_list(memcg
);
5624 VM_WARN_ON_ONCE(mm_list
&& !list_empty(&mm_list
->fifo
));
5626 for_each_node(nid
) {
5627 struct lruvec
*lruvec
= get_lruvec(memcg
, nid
);
5628 struct lru_gen_mm_state
*mm_state
= get_mm_state(lruvec
);
5630 VM_WARN_ON_ONCE(memchr_inv(lruvec
->lrugen
.nr_pages
, 0,
5631 sizeof(lruvec
->lrugen
.nr_pages
)));
5633 lruvec
->lrugen
.list
.next
= LIST_POISON1
;
5638 for (i
= 0; i
< NR_BLOOM_FILTERS
; i
++) {
5639 bitmap_free(mm_state
->filters
[i
]);
5640 mm_state
->filters
[i
] = NULL
;
5645 #endif /* CONFIG_MEMCG */
5647 static int __init
init_lru_gen(void)
5649 BUILD_BUG_ON(MIN_NR_GENS
+ 1 >= MAX_NR_GENS
);
5650 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH
) <= MAX_NR_GENS
);
5652 if (sysfs_create_group(mm_kobj
, &lru_gen_attr_group
))
5653 pr_err("lru_gen: failed to create sysfs group\n");
5655 debugfs_create_file("lru_gen", 0644, NULL
, NULL
, &lru_gen_rw_fops
);
5656 debugfs_create_file("lru_gen_full", 0444, NULL
, NULL
, &lru_gen_ro_fops
);
5660 late_initcall(init_lru_gen
);
5662 #else /* !CONFIG_LRU_GEN */
5664 static void lru_gen_age_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
5669 static void lru_gen_shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
5674 static void lru_gen_shrink_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
5679 #endif /* CONFIG_LRU_GEN */
5681 static void shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
5683 unsigned long nr
[NR_LRU_LISTS
];
5684 unsigned long targets
[NR_LRU_LISTS
];
5685 unsigned long nr_to_scan
;
5687 unsigned long nr_reclaimed
= 0;
5688 unsigned long nr_to_reclaim
= sc
->nr_to_reclaim
;
5689 bool proportional_reclaim
;
5690 struct blk_plug plug
;
5692 if (lru_gen_enabled() && !root_reclaim(sc
)) {
5693 lru_gen_shrink_lruvec(lruvec
, sc
);
5697 get_scan_count(lruvec
, sc
, nr
);
5699 /* Record the original scan target for proportional adjustments later */
5700 memcpy(targets
, nr
, sizeof(nr
));
5703 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5704 * event that can occur when there is little memory pressure e.g.
5705 * multiple streaming readers/writers. Hence, we do not abort scanning
5706 * when the requested number of pages are reclaimed when scanning at
5707 * DEF_PRIORITY on the assumption that the fact we are direct
5708 * reclaiming implies that kswapd is not keeping up and it is best to
5709 * do a batch of work at once. For memcg reclaim one check is made to
5710 * abort proportional reclaim if either the file or anon lru has already
5711 * dropped to zero at the first pass.
5713 proportional_reclaim
= (!cgroup_reclaim(sc
) && !current_is_kswapd() &&
5714 sc
->priority
== DEF_PRIORITY
);
5716 blk_start_plug(&plug
);
5717 while (nr
[LRU_INACTIVE_ANON
] || nr
[LRU_ACTIVE_FILE
] ||
5718 nr
[LRU_INACTIVE_FILE
]) {
5719 unsigned long nr_anon
, nr_file
, percentage
;
5720 unsigned long nr_scanned
;
5722 for_each_evictable_lru(lru
) {
5724 nr_to_scan
= min(nr
[lru
], SWAP_CLUSTER_MAX
);
5725 nr
[lru
] -= nr_to_scan
;
5727 nr_reclaimed
+= shrink_list(lru
, nr_to_scan
,
5734 if (nr_reclaimed
< nr_to_reclaim
|| proportional_reclaim
)
5738 * For kswapd and memcg, reclaim at least the number of pages
5739 * requested. Ensure that the anon and file LRUs are scanned
5740 * proportionally what was requested by get_scan_count(). We
5741 * stop reclaiming one LRU and reduce the amount scanning
5742 * proportional to the original scan target.
5744 nr_file
= nr
[LRU_INACTIVE_FILE
] + nr
[LRU_ACTIVE_FILE
];
5745 nr_anon
= nr
[LRU_INACTIVE_ANON
] + nr
[LRU_ACTIVE_ANON
];
5748 * It's just vindictive to attack the larger once the smaller
5749 * has gone to zero. And given the way we stop scanning the
5750 * smaller below, this makes sure that we only make one nudge
5751 * towards proportionality once we've got nr_to_reclaim.
5753 if (!nr_file
|| !nr_anon
)
5756 if (nr_file
> nr_anon
) {
5757 unsigned long scan_target
= targets
[LRU_INACTIVE_ANON
] +
5758 targets
[LRU_ACTIVE_ANON
] + 1;
5760 percentage
= nr_anon
* 100 / scan_target
;
5762 unsigned long scan_target
= targets
[LRU_INACTIVE_FILE
] +
5763 targets
[LRU_ACTIVE_FILE
] + 1;
5765 percentage
= nr_file
* 100 / scan_target
;
5768 /* Stop scanning the smaller of the LRU */
5770 nr
[lru
+ LRU_ACTIVE
] = 0;
5773 * Recalculate the other LRU scan count based on its original
5774 * scan target and the percentage scanning already complete
5776 lru
= (lru
== LRU_FILE
) ? LRU_BASE
: LRU_FILE
;
5777 nr_scanned
= targets
[lru
] - nr
[lru
];
5778 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
5779 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
5782 nr_scanned
= targets
[lru
] - nr
[lru
];
5783 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
5784 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
5786 blk_finish_plug(&plug
);
5787 sc
->nr_reclaimed
+= nr_reclaimed
;
5790 * Even if we did not try to evict anon pages at all, we want to
5791 * rebalance the anon lru active/inactive ratio.
5793 if (can_age_anon_pages(lruvec_pgdat(lruvec
), sc
) &&
5794 inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
5795 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
5796 sc
, LRU_ACTIVE_ANON
);
5799 /* Use reclaim/compaction for costly allocs or under memory pressure */
5800 static bool in_reclaim_compaction(struct scan_control
*sc
)
5802 if (gfp_compaction_allowed(sc
->gfp_mask
) && sc
->order
&&
5803 (sc
->order
> PAGE_ALLOC_COSTLY_ORDER
||
5804 sc
->priority
< DEF_PRIORITY
- 2))
5811 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5812 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5813 * true if more pages should be reclaimed such that when the page allocator
5814 * calls try_to_compact_pages() that it will have enough free pages to succeed.
5815 * It will give up earlier than that if there is difficulty reclaiming pages.
5817 static inline bool should_continue_reclaim(struct pglist_data
*pgdat
,
5818 unsigned long nr_reclaimed
,
5819 struct scan_control
*sc
)
5821 unsigned long pages_for_compaction
;
5822 unsigned long inactive_lru_pages
;
5825 /* If not in reclaim/compaction mode, stop */
5826 if (!in_reclaim_compaction(sc
))
5830 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5831 * number of pages that were scanned. This will return to the caller
5832 * with the risk reclaim/compaction and the resulting allocation attempt
5833 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5834 * allocations through requiring that the full LRU list has been scanned
5835 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5836 * scan, but that approximation was wrong, and there were corner cases
5837 * where always a non-zero amount of pages were scanned.
5842 /* If compaction would go ahead or the allocation would succeed, stop */
5843 for (z
= 0; z
<= sc
->reclaim_idx
; z
++) {
5844 struct zone
*zone
= &pgdat
->node_zones
[z
];
5845 if (!managed_zone(zone
))
5848 /* Allocation can already succeed, nothing to do */
5849 if (zone_watermark_ok(zone
, sc
->order
, min_wmark_pages(zone
),
5850 sc
->reclaim_idx
, 0))
5853 if (compaction_suitable(zone
, sc
->order
, sc
->reclaim_idx
))
5858 * If we have not reclaimed enough pages for compaction and the
5859 * inactive lists are large enough, continue reclaiming
5861 pages_for_compaction
= compact_gap(sc
->order
);
5862 inactive_lru_pages
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
5863 if (can_reclaim_anon_pages(NULL
, pgdat
->node_id
, sc
))
5864 inactive_lru_pages
+= node_page_state(pgdat
, NR_INACTIVE_ANON
);
5866 return inactive_lru_pages
> pages_for_compaction
;
5869 static void shrink_node_memcgs(pg_data_t
*pgdat
, struct scan_control
*sc
)
5871 struct mem_cgroup
*target_memcg
= sc
->target_mem_cgroup
;
5872 struct mem_cgroup_reclaim_cookie reclaim
= {
5875 struct mem_cgroup_reclaim_cookie
*partial
= &reclaim
;
5876 struct mem_cgroup
*memcg
;
5879 * In most cases, direct reclaimers can do partial walks
5880 * through the cgroup tree, using an iterator state that
5881 * persists across invocations. This strikes a balance between
5882 * fairness and allocation latency.
5884 * For kswapd, reliable forward progress is more important
5885 * than a quick return to idle. Always do full walks.
5887 if (current_is_kswapd() || sc
->memcg_full_walk
)
5890 memcg
= mem_cgroup_iter(target_memcg
, NULL
, partial
);
5892 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
5893 unsigned long reclaimed
;
5894 unsigned long scanned
;
5897 * This loop can become CPU-bound when target memcgs
5898 * aren't eligible for reclaim - either because they
5899 * don't have any reclaimable pages, or because their
5900 * memory is explicitly protected. Avoid soft lockups.
5904 mem_cgroup_calculate_protection(target_memcg
, memcg
);
5906 if (mem_cgroup_below_min(target_memcg
, memcg
)) {
5909 * If there is no reclaimable memory, OOM.
5912 } else if (mem_cgroup_below_low(target_memcg
, memcg
)) {
5915 * Respect the protection only as long as
5916 * there is an unprotected supply
5917 * of reclaimable memory from other cgroups.
5919 if (!sc
->memcg_low_reclaim
) {
5920 sc
->memcg_low_skipped
= 1;
5923 memcg_memory_event(memcg
, MEMCG_LOW
);
5926 reclaimed
= sc
->nr_reclaimed
;
5927 scanned
= sc
->nr_scanned
;
5929 shrink_lruvec(lruvec
, sc
);
5931 shrink_slab(sc
->gfp_mask
, pgdat
->node_id
, memcg
,
5934 /* Record the group's reclaim efficiency */
5936 vmpressure(sc
->gfp_mask
, memcg
, false,
5937 sc
->nr_scanned
- scanned
,
5938 sc
->nr_reclaimed
- reclaimed
);
5940 /* If partial walks are allowed, bail once goal is reached */
5941 if (partial
&& sc
->nr_reclaimed
>= sc
->nr_to_reclaim
) {
5942 mem_cgroup_iter_break(target_memcg
, memcg
);
5945 } while ((memcg
= mem_cgroup_iter(target_memcg
, memcg
, partial
)));
5948 static void shrink_node(pg_data_t
*pgdat
, struct scan_control
*sc
)
5950 unsigned long nr_reclaimed
, nr_scanned
, nr_node_reclaimed
;
5951 struct lruvec
*target_lruvec
;
5952 bool reclaimable
= false;
5954 if (lru_gen_enabled() && root_reclaim(sc
)) {
5955 memset(&sc
->nr
, 0, sizeof(sc
->nr
));
5956 lru_gen_shrink_node(pgdat
, sc
);
5960 target_lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
, pgdat
);
5963 memset(&sc
->nr
, 0, sizeof(sc
->nr
));
5965 nr_reclaimed
= sc
->nr_reclaimed
;
5966 nr_scanned
= sc
->nr_scanned
;
5968 prepare_scan_control(pgdat
, sc
);
5970 shrink_node_memcgs(pgdat
, sc
);
5972 flush_reclaim_state(sc
);
5974 nr_node_reclaimed
= sc
->nr_reclaimed
- nr_reclaimed
;
5976 /* Record the subtree's reclaim efficiency */
5978 vmpressure(sc
->gfp_mask
, sc
->target_mem_cgroup
, true,
5979 sc
->nr_scanned
- nr_scanned
, nr_node_reclaimed
);
5981 if (nr_node_reclaimed
)
5984 if (current_is_kswapd()) {
5986 * If reclaim is isolating dirty pages under writeback,
5987 * it implies that the long-lived page allocation rate
5988 * is exceeding the page laundering rate. Either the
5989 * global limits are not being effective at throttling
5990 * processes due to the page distribution throughout
5991 * zones or there is heavy usage of a slow backing
5992 * device. The only option is to throttle from reclaim
5993 * context which is not ideal as there is no guarantee
5994 * the dirtying process is throttled in the same way
5995 * balance_dirty_pages() manages.
5997 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5998 * count the number of pages under pages flagged for
5999 * immediate reclaim and stall if any are encountered
6000 * in the nr_immediate check below.
6002 if (sc
->nr
.writeback
&& sc
->nr
.writeback
== sc
->nr
.taken
)
6003 set_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
6005 /* Allow kswapd to start writing pages during reclaim.*/
6006 if (sc
->nr
.unqueued_dirty
&&
6007 sc
->nr
.unqueued_dirty
== sc
->nr
.file_taken
)
6008 set_bit(PGDAT_DIRTY
, &pgdat
->flags
);
6011 * If kswapd scans pages marked for immediate
6012 * reclaim and under writeback (nr_immediate), it
6013 * implies that pages are cycling through the LRU
6014 * faster than they are written so forcibly stall
6015 * until some pages complete writeback.
6017 if (sc
->nr
.immediate
)
6018 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_WRITEBACK
);
6022 * Tag a node/memcg as congested if all the dirty pages were marked
6023 * for writeback and immediate reclaim (counted in nr.congested).
6025 * Legacy memcg will stall in page writeback so avoid forcibly
6026 * stalling in reclaim_throttle().
6028 if (sc
->nr
.dirty
&& sc
->nr
.dirty
== sc
->nr
.congested
) {
6029 if (cgroup_reclaim(sc
) && writeback_throttling_sane(sc
))
6030 set_bit(LRUVEC_CGROUP_CONGESTED
, &target_lruvec
->flags
);
6032 if (current_is_kswapd())
6033 set_bit(LRUVEC_NODE_CONGESTED
, &target_lruvec
->flags
);
6037 * Stall direct reclaim for IO completions if the lruvec is
6038 * node is congested. Allow kswapd to continue until it
6039 * starts encountering unqueued dirty pages or cycling through
6040 * the LRU too quickly.
6042 if (!current_is_kswapd() && current_may_throttle() &&
6043 !sc
->hibernation_mode
&&
6044 (test_bit(LRUVEC_CGROUP_CONGESTED
, &target_lruvec
->flags
) ||
6045 test_bit(LRUVEC_NODE_CONGESTED
, &target_lruvec
->flags
)))
6046 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_CONGESTED
);
6048 if (should_continue_reclaim(pgdat
, nr_node_reclaimed
, sc
))
6052 * Kswapd gives up on balancing particular nodes after too
6053 * many failures to reclaim anything from them and goes to
6054 * sleep. On reclaim progress, reset the failure counter. A
6055 * successful direct reclaim run will revive a dormant kswapd.
6058 pgdat
->kswapd_failures
= 0;
6059 else if (sc
->cache_trim_mode
)
6060 sc
->cache_trim_mode_failed
= 1;
6064 * Returns true if compaction should go ahead for a costly-order request, or
6065 * the allocation would already succeed without compaction. Return false if we
6066 * should reclaim first.
6068 static inline bool compaction_ready(struct zone
*zone
, struct scan_control
*sc
)
6070 unsigned long watermark
;
6072 if (!gfp_compaction_allowed(sc
->gfp_mask
))
6075 /* Allocation can already succeed, nothing to do */
6076 if (zone_watermark_ok(zone
, sc
->order
, min_wmark_pages(zone
),
6077 sc
->reclaim_idx
, 0))
6080 /* Compaction cannot yet proceed. Do reclaim. */
6081 if (!compaction_suitable(zone
, sc
->order
, sc
->reclaim_idx
))
6085 * Compaction is already possible, but it takes time to run and there
6086 * are potentially other callers using the pages just freed. So proceed
6087 * with reclaim to make a buffer of free pages available to give
6088 * compaction a reasonable chance of completing and allocating the page.
6089 * Note that we won't actually reclaim the whole buffer in one attempt
6090 * as the target watermark in should_continue_reclaim() is lower. But if
6091 * we are already above the high+gap watermark, don't reclaim at all.
6093 watermark
= high_wmark_pages(zone
) + compact_gap(sc
->order
);
6095 return zone_watermark_ok_safe(zone
, 0, watermark
, sc
->reclaim_idx
);
6098 static void consider_reclaim_throttle(pg_data_t
*pgdat
, struct scan_control
*sc
)
6101 * If reclaim is making progress greater than 12% efficiency then
6102 * wake all the NOPROGRESS throttled tasks.
6104 if (sc
->nr_reclaimed
> (sc
->nr_scanned
>> 3)) {
6105 wait_queue_head_t
*wqh
;
6107 wqh
= &pgdat
->reclaim_wait
[VMSCAN_THROTTLE_NOPROGRESS
];
6108 if (waitqueue_active(wqh
))
6115 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6116 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6117 * under writeback and marked for immediate reclaim at the tail of the
6120 if (current_is_kswapd() || cgroup_reclaim(sc
))
6123 /* Throttle if making no progress at high prioities. */
6124 if (sc
->priority
== 1 && !sc
->nr_reclaimed
)
6125 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_NOPROGRESS
);
6129 * This is the direct reclaim path, for page-allocating processes. We only
6130 * try to reclaim pages from zones which will satisfy the caller's allocation
6133 * If a zone is deemed to be full of pinned pages then just give it a light
6134 * scan then give up on it.
6136 static void shrink_zones(struct zonelist
*zonelist
, struct scan_control
*sc
)
6140 unsigned long nr_soft_reclaimed
;
6141 unsigned long nr_soft_scanned
;
6143 pg_data_t
*last_pgdat
= NULL
;
6144 pg_data_t
*first_pgdat
= NULL
;
6147 * If the number of buffer_heads in the machine exceeds the maximum
6148 * allowed level, force direct reclaim to scan the highmem zone as
6149 * highmem pages could be pinning lowmem pages storing buffer_heads
6151 orig_mask
= sc
->gfp_mask
;
6152 if (buffer_heads_over_limit
) {
6153 sc
->gfp_mask
|= __GFP_HIGHMEM
;
6154 sc
->reclaim_idx
= gfp_zone(sc
->gfp_mask
);
6157 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
6158 sc
->reclaim_idx
, sc
->nodemask
) {
6160 * Take care memory controller reclaiming has small influence
6163 if (!cgroup_reclaim(sc
)) {
6164 if (!cpuset_zone_allowed(zone
,
6165 GFP_KERNEL
| __GFP_HARDWALL
))
6169 * If we already have plenty of memory free for
6170 * compaction in this zone, don't free any more.
6171 * Even though compaction is invoked for any
6172 * non-zero order, only frequent costly order
6173 * reclamation is disruptive enough to become a
6174 * noticeable problem, like transparent huge
6177 if (IS_ENABLED(CONFIG_COMPACTION
) &&
6178 sc
->order
> PAGE_ALLOC_COSTLY_ORDER
&&
6179 compaction_ready(zone
, sc
)) {
6180 sc
->compaction_ready
= true;
6185 * Shrink each node in the zonelist once. If the
6186 * zonelist is ordered by zone (not the default) then a
6187 * node may be shrunk multiple times but in that case
6188 * the user prefers lower zones being preserved.
6190 if (zone
->zone_pgdat
== last_pgdat
)
6194 * This steals pages from memory cgroups over softlimit
6195 * and returns the number of reclaimed pages and
6196 * scanned pages. This works for global memory pressure
6197 * and balancing, not for a memcg's limit.
6199 nr_soft_scanned
= 0;
6200 nr_soft_reclaimed
= memcg1_soft_limit_reclaim(zone
->zone_pgdat
,
6201 sc
->order
, sc
->gfp_mask
,
6203 sc
->nr_reclaimed
+= nr_soft_reclaimed
;
6204 sc
->nr_scanned
+= nr_soft_scanned
;
6205 /* need some check for avoid more shrink_zone() */
6209 first_pgdat
= zone
->zone_pgdat
;
6211 /* See comment about same check for global reclaim above */
6212 if (zone
->zone_pgdat
== last_pgdat
)
6214 last_pgdat
= zone
->zone_pgdat
;
6215 shrink_node(zone
->zone_pgdat
, sc
);
6219 consider_reclaim_throttle(first_pgdat
, sc
);
6222 * Restore to original mask to avoid the impact on the caller if we
6223 * promoted it to __GFP_HIGHMEM.
6225 sc
->gfp_mask
= orig_mask
;
6228 static void snapshot_refaults(struct mem_cgroup
*target_memcg
, pg_data_t
*pgdat
)
6230 struct lruvec
*target_lruvec
;
6231 unsigned long refaults
;
6233 if (lru_gen_enabled())
6236 target_lruvec
= mem_cgroup_lruvec(target_memcg
, pgdat
);
6237 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_ANON
);
6238 target_lruvec
->refaults
[WORKINGSET_ANON
] = refaults
;
6239 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_FILE
);
6240 target_lruvec
->refaults
[WORKINGSET_FILE
] = refaults
;
6244 * This is the main entry point to direct page reclaim.
6246 * If a full scan of the inactive list fails to free enough memory then we
6247 * are "out of memory" and something needs to be killed.
6249 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6250 * high - the zone may be full of dirty or under-writeback pages, which this
6251 * caller can't do much about. We kick the writeback threads and take explicit
6252 * naps in the hope that some of these pages can be written. But if the
6253 * allocating task holds filesystem locks which prevent writeout this might not
6254 * work, and the allocation attempt will fail.
6256 * returns: 0, if no pages reclaimed
6257 * else, the number of pages reclaimed
6259 static unsigned long do_try_to_free_pages(struct zonelist
*zonelist
,
6260 struct scan_control
*sc
)
6262 int initial_priority
= sc
->priority
;
6263 pg_data_t
*last_pgdat
;
6267 delayacct_freepages_start();
6269 if (!cgroup_reclaim(sc
))
6270 __count_zid_vm_events(ALLOCSTALL
, sc
->reclaim_idx
, 1);
6274 vmpressure_prio(sc
->gfp_mask
, sc
->target_mem_cgroup
,
6277 shrink_zones(zonelist
, sc
);
6279 if (sc
->nr_reclaimed
>= sc
->nr_to_reclaim
)
6282 if (sc
->compaction_ready
)
6286 * If we're getting trouble reclaiming, start doing
6287 * writepage even in laptop mode.
6289 if (sc
->priority
< DEF_PRIORITY
- 2)
6290 sc
->may_writepage
= 1;
6291 } while (--sc
->priority
>= 0);
6294 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
, sc
->reclaim_idx
,
6296 if (zone
->zone_pgdat
== last_pgdat
)
6298 last_pgdat
= zone
->zone_pgdat
;
6300 snapshot_refaults(sc
->target_mem_cgroup
, zone
->zone_pgdat
);
6302 if (cgroup_reclaim(sc
)) {
6303 struct lruvec
*lruvec
;
6305 lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
,
6307 clear_bit(LRUVEC_CGROUP_CONGESTED
, &lruvec
->flags
);
6311 delayacct_freepages_end();
6313 if (sc
->nr_reclaimed
)
6314 return sc
->nr_reclaimed
;
6316 /* Aborted reclaim to try compaction? don't OOM, then */
6317 if (sc
->compaction_ready
)
6321 * In most cases, direct reclaimers can do partial walks
6322 * through the cgroup tree to meet the reclaim goal while
6323 * keeping latency low. Since the iterator state is shared
6324 * among all direct reclaim invocations (to retain fairness
6325 * among cgroups), though, high concurrency can result in
6326 * individual threads not seeing enough cgroups to make
6327 * meaningful forward progress. Avoid false OOMs in this case.
6329 if (!sc
->memcg_full_walk
) {
6330 sc
->priority
= initial_priority
;
6331 sc
->memcg_full_walk
= 1;
6336 * We make inactive:active ratio decisions based on the node's
6337 * composition of memory, but a restrictive reclaim_idx or a
6338 * memory.low cgroup setting can exempt large amounts of
6339 * memory from reclaim. Neither of which are very common, so
6340 * instead of doing costly eligibility calculations of the
6341 * entire cgroup subtree up front, we assume the estimates are
6342 * good, and retry with forcible deactivation if that fails.
6344 if (sc
->skipped_deactivate
) {
6345 sc
->priority
= initial_priority
;
6346 sc
->force_deactivate
= 1;
6347 sc
->skipped_deactivate
= 0;
6351 /* Untapped cgroup reserves? Don't OOM, retry. */
6352 if (sc
->memcg_low_skipped
) {
6353 sc
->priority
= initial_priority
;
6354 sc
->force_deactivate
= 0;
6355 sc
->memcg_low_reclaim
= 1;
6356 sc
->memcg_low_skipped
= 0;
6363 static bool allow_direct_reclaim(pg_data_t
*pgdat
)
6366 unsigned long pfmemalloc_reserve
= 0;
6367 unsigned long free_pages
= 0;
6371 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
6374 for (i
= 0; i
<= ZONE_NORMAL
; i
++) {
6375 zone
= &pgdat
->node_zones
[i
];
6376 if (!managed_zone(zone
))
6379 if (!zone_reclaimable_pages(zone
))
6382 pfmemalloc_reserve
+= min_wmark_pages(zone
);
6383 free_pages
+= zone_page_state_snapshot(zone
, NR_FREE_PAGES
);
6386 /* If there are no reserves (unexpected config) then do not throttle */
6387 if (!pfmemalloc_reserve
)
6390 wmark_ok
= free_pages
> pfmemalloc_reserve
/ 2;
6392 /* kswapd must be awake if processes are being throttled */
6393 if (!wmark_ok
&& waitqueue_active(&pgdat
->kswapd_wait
)) {
6394 if (READ_ONCE(pgdat
->kswapd_highest_zoneidx
) > ZONE_NORMAL
)
6395 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, ZONE_NORMAL
);
6397 wake_up_interruptible(&pgdat
->kswapd_wait
);
6404 * Throttle direct reclaimers if backing storage is backed by the network
6405 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6406 * depleted. kswapd will continue to make progress and wake the processes
6407 * when the low watermark is reached.
6409 * Returns true if a fatal signal was delivered during throttling. If this
6410 * happens, the page allocator should not consider triggering the OOM killer.
6412 static bool throttle_direct_reclaim(gfp_t gfp_mask
, struct zonelist
*zonelist
,
6413 nodemask_t
*nodemask
)
6417 pg_data_t
*pgdat
= NULL
;
6420 * Kernel threads should not be throttled as they may be indirectly
6421 * responsible for cleaning pages necessary for reclaim to make forward
6422 * progress. kjournald for example may enter direct reclaim while
6423 * committing a transaction where throttling it could forcing other
6424 * processes to block on log_wait_commit().
6426 if (current
->flags
& PF_KTHREAD
)
6430 * If a fatal signal is pending, this process should not throttle.
6431 * It should return quickly so it can exit and free its memory
6433 if (fatal_signal_pending(current
))
6437 * Check if the pfmemalloc reserves are ok by finding the first node
6438 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6439 * GFP_KERNEL will be required for allocating network buffers when
6440 * swapping over the network so ZONE_HIGHMEM is unusable.
6442 * Throttling is based on the first usable node and throttled processes
6443 * wait on a queue until kswapd makes progress and wakes them. There
6444 * is an affinity then between processes waking up and where reclaim
6445 * progress has been made assuming the process wakes on the same node.
6446 * More importantly, processes running on remote nodes will not compete
6447 * for remote pfmemalloc reserves and processes on different nodes
6448 * should make reasonable progress.
6450 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
6451 gfp_zone(gfp_mask
), nodemask
) {
6452 if (zone_idx(zone
) > ZONE_NORMAL
)
6455 /* Throttle based on the first usable node */
6456 pgdat
= zone
->zone_pgdat
;
6457 if (allow_direct_reclaim(pgdat
))
6462 /* If no zone was usable by the allocation flags then do not throttle */
6466 /* Account for the throttling */
6467 count_vm_event(PGSCAN_DIRECT_THROTTLE
);
6470 * If the caller cannot enter the filesystem, it's possible that it
6471 * is due to the caller holding an FS lock or performing a journal
6472 * transaction in the case of a filesystem like ext[3|4]. In this case,
6473 * it is not safe to block on pfmemalloc_wait as kswapd could be
6474 * blocked waiting on the same lock. Instead, throttle for up to a
6475 * second before continuing.
6477 if (!(gfp_mask
& __GFP_FS
))
6478 wait_event_interruptible_timeout(pgdat
->pfmemalloc_wait
,
6479 allow_direct_reclaim(pgdat
), HZ
);
6481 /* Throttle until kswapd wakes the process */
6482 wait_event_killable(zone
->zone_pgdat
->pfmemalloc_wait
,
6483 allow_direct_reclaim(pgdat
));
6485 if (fatal_signal_pending(current
))
6492 unsigned long try_to_free_pages(struct zonelist
*zonelist
, int order
,
6493 gfp_t gfp_mask
, nodemask_t
*nodemask
)
6495 unsigned long nr_reclaimed
;
6496 struct scan_control sc
= {
6497 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
6498 .gfp_mask
= current_gfp_context(gfp_mask
),
6499 .reclaim_idx
= gfp_zone(gfp_mask
),
6501 .nodemask
= nodemask
,
6502 .priority
= DEF_PRIORITY
,
6503 .may_writepage
= !laptop_mode
,
6509 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6510 * Confirm they are large enough for max values.
6512 BUILD_BUG_ON(MAX_PAGE_ORDER
>= S8_MAX
);
6513 BUILD_BUG_ON(DEF_PRIORITY
> S8_MAX
);
6514 BUILD_BUG_ON(MAX_NR_ZONES
> S8_MAX
);
6517 * Do not enter reclaim if fatal signal was delivered while throttled.
6518 * 1 is returned so that the page allocator does not OOM kill at this
6521 if (throttle_direct_reclaim(sc
.gfp_mask
, zonelist
, nodemask
))
6524 set_task_reclaim_state(current
, &sc
.reclaim_state
);
6525 trace_mm_vmscan_direct_reclaim_begin(order
, sc
.gfp_mask
);
6527 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
6529 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed
);
6530 set_task_reclaim_state(current
, NULL
);
6532 return nr_reclaimed
;
6537 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6538 unsigned long mem_cgroup_shrink_node(struct mem_cgroup
*memcg
,
6539 gfp_t gfp_mask
, bool noswap
,
6541 unsigned long *nr_scanned
)
6543 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
6544 struct scan_control sc
= {
6545 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
6546 .target_mem_cgroup
= memcg
,
6547 .may_writepage
= !laptop_mode
,
6549 .reclaim_idx
= MAX_NR_ZONES
- 1,
6550 .may_swap
= !noswap
,
6553 WARN_ON_ONCE(!current
->reclaim_state
);
6555 sc
.gfp_mask
= (gfp_mask
& GFP_RECLAIM_MASK
) |
6556 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
);
6558 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc
.order
,
6562 * NOTE: Although we can get the priority field, using it
6563 * here is not a good idea, since it limits the pages we can scan.
6564 * if we don't reclaim here, the shrink_node from balance_pgdat
6565 * will pick up pages from other mem cgroup's as well. We hack
6566 * the priority and make it zero.
6568 shrink_lruvec(lruvec
, &sc
);
6570 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc
.nr_reclaimed
);
6572 *nr_scanned
= sc
.nr_scanned
;
6574 return sc
.nr_reclaimed
;
6577 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup
*memcg
,
6578 unsigned long nr_pages
,
6580 unsigned int reclaim_options
,
6583 unsigned long nr_reclaimed
;
6584 unsigned int noreclaim_flag
;
6585 struct scan_control sc
= {
6586 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
6587 .proactive_swappiness
= swappiness
,
6588 .gfp_mask
= (current_gfp_context(gfp_mask
) & GFP_RECLAIM_MASK
) |
6589 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
),
6590 .reclaim_idx
= MAX_NR_ZONES
- 1,
6591 .target_mem_cgroup
= memcg
,
6592 .priority
= DEF_PRIORITY
,
6593 .may_writepage
= !laptop_mode
,
6595 .may_swap
= !!(reclaim_options
& MEMCG_RECLAIM_MAY_SWAP
),
6596 .proactive
= !!(reclaim_options
& MEMCG_RECLAIM_PROACTIVE
),
6599 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6600 * equal pressure on all the nodes. This is based on the assumption that
6601 * the reclaim does not bail out early.
6603 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
6605 set_task_reclaim_state(current
, &sc
.reclaim_state
);
6606 trace_mm_vmscan_memcg_reclaim_begin(0, sc
.gfp_mask
);
6607 noreclaim_flag
= memalloc_noreclaim_save();
6609 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
6611 memalloc_noreclaim_restore(noreclaim_flag
);
6612 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed
);
6613 set_task_reclaim_state(current
, NULL
);
6615 return nr_reclaimed
;
6619 static void kswapd_age_node(struct pglist_data
*pgdat
, struct scan_control
*sc
)
6621 struct mem_cgroup
*memcg
;
6622 struct lruvec
*lruvec
;
6624 if (lru_gen_enabled()) {
6625 lru_gen_age_node(pgdat
, sc
);
6629 if (!can_age_anon_pages(pgdat
, sc
))
6632 lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
6633 if (!inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
6636 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
6638 lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
6639 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
6640 sc
, LRU_ACTIVE_ANON
);
6641 memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
);
6645 static bool pgdat_watermark_boosted(pg_data_t
*pgdat
, int highest_zoneidx
)
6651 * Check for watermark boosts top-down as the higher zones
6652 * are more likely to be boosted. Both watermarks and boosts
6653 * should not be checked at the same time as reclaim would
6654 * start prematurely when there is no boosting and a lower
6657 for (i
= highest_zoneidx
; i
>= 0; i
--) {
6658 zone
= pgdat
->node_zones
+ i
;
6659 if (!managed_zone(zone
))
6662 if (zone
->watermark_boost
)
6670 * Returns true if there is an eligible zone balanced for the request order
6671 * and highest_zoneidx
6673 static bool pgdat_balanced(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
6676 unsigned long mark
= -1;
6680 * Check watermarks bottom-up as lower zones are more likely to
6683 for (i
= 0; i
<= highest_zoneidx
; i
++) {
6684 zone
= pgdat
->node_zones
+ i
;
6686 if (!managed_zone(zone
))
6689 if (sysctl_numa_balancing_mode
& NUMA_BALANCING_MEMORY_TIERING
)
6690 mark
= promo_wmark_pages(zone
);
6692 mark
= high_wmark_pages(zone
);
6693 if (zone_watermark_ok_safe(zone
, order
, mark
, highest_zoneidx
))
6698 * If a node has no managed zone within highest_zoneidx, it does not
6699 * need balancing by definition. This can happen if a zone-restricted
6700 * allocation tries to wake a remote kswapd.
6708 /* Clear pgdat state for congested, dirty or under writeback. */
6709 static void clear_pgdat_congested(pg_data_t
*pgdat
)
6711 struct lruvec
*lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
6713 clear_bit(LRUVEC_NODE_CONGESTED
, &lruvec
->flags
);
6714 clear_bit(LRUVEC_CGROUP_CONGESTED
, &lruvec
->flags
);
6715 clear_bit(PGDAT_DIRTY
, &pgdat
->flags
);
6716 clear_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
6720 * Prepare kswapd for sleeping. This verifies that there are no processes
6721 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6723 * Returns true if kswapd is ready to sleep
6725 static bool prepare_kswapd_sleep(pg_data_t
*pgdat
, int order
,
6726 int highest_zoneidx
)
6729 * The throttled processes are normally woken up in balance_pgdat() as
6730 * soon as allow_direct_reclaim() is true. But there is a potential
6731 * race between when kswapd checks the watermarks and a process gets
6732 * throttled. There is also a potential race if processes get
6733 * throttled, kswapd wakes, a large process exits thereby balancing the
6734 * zones, which causes kswapd to exit balance_pgdat() before reaching
6735 * the wake up checks. If kswapd is going to sleep, no process should
6736 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6737 * the wake up is premature, processes will wake kswapd and get
6738 * throttled again. The difference from wake ups in balance_pgdat() is
6739 * that here we are under prepare_to_wait().
6741 if (waitqueue_active(&pgdat
->pfmemalloc_wait
))
6742 wake_up_all(&pgdat
->pfmemalloc_wait
);
6744 /* Hopeless node, leave it to direct reclaim */
6745 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
6748 if (pgdat_balanced(pgdat
, order
, highest_zoneidx
)) {
6749 clear_pgdat_congested(pgdat
);
6757 * kswapd shrinks a node of pages that are at or below the highest usable
6758 * zone that is currently unbalanced.
6760 * Returns true if kswapd scanned at least the requested number of pages to
6761 * reclaim or if the lack of progress was due to pages under writeback.
6762 * This is used to determine if the scanning priority needs to be raised.
6764 static bool kswapd_shrink_node(pg_data_t
*pgdat
,
6765 struct scan_control
*sc
)
6769 unsigned long nr_reclaimed
= sc
->nr_reclaimed
;
6771 /* Reclaim a number of pages proportional to the number of zones */
6772 sc
->nr_to_reclaim
= 0;
6773 for (z
= 0; z
<= sc
->reclaim_idx
; z
++) {
6774 zone
= pgdat
->node_zones
+ z
;
6775 if (!managed_zone(zone
))
6778 sc
->nr_to_reclaim
+= max(high_wmark_pages(zone
), SWAP_CLUSTER_MAX
);
6782 * Historically care was taken to put equal pressure on all zones but
6783 * now pressure is applied based on node LRU order.
6785 shrink_node(pgdat
, sc
);
6788 * Fragmentation may mean that the system cannot be rebalanced for
6789 * high-order allocations. If twice the allocation size has been
6790 * reclaimed then recheck watermarks only at order-0 to prevent
6791 * excessive reclaim. Assume that a process requested a high-order
6792 * can direct reclaim/compact.
6794 if (sc
->order
&& sc
->nr_reclaimed
>= compact_gap(sc
->order
))
6797 /* account for progress from mm_account_reclaimed_pages() */
6798 return max(sc
->nr_scanned
, sc
->nr_reclaimed
- nr_reclaimed
) >= sc
->nr_to_reclaim
;
6801 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6803 update_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
, bool active
)
6808 for (i
= 0; i
<= highest_zoneidx
; i
++) {
6809 zone
= pgdat
->node_zones
+ i
;
6811 if (!managed_zone(zone
))
6815 set_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
6817 clear_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
6822 set_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
6824 update_reclaim_active(pgdat
, highest_zoneidx
, true);
6828 clear_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
6830 update_reclaim_active(pgdat
, highest_zoneidx
, false);
6834 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6835 * that are eligible for use by the caller until at least one zone is
6838 * Returns the order kswapd finished reclaiming at.
6840 * kswapd scans the zones in the highmem->normal->dma direction. It skips
6841 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6842 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6843 * or lower is eligible for reclaim until at least one usable zone is
6846 static int balance_pgdat(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
6849 unsigned long nr_soft_reclaimed
;
6850 unsigned long nr_soft_scanned
;
6851 unsigned long pflags
;
6852 unsigned long nr_boost_reclaim
;
6853 unsigned long zone_boosts
[MAX_NR_ZONES
] = { 0, };
6856 struct scan_control sc
= {
6857 .gfp_mask
= GFP_KERNEL
,
6862 set_task_reclaim_state(current
, &sc
.reclaim_state
);
6863 psi_memstall_enter(&pflags
);
6864 __fs_reclaim_acquire(_THIS_IP_
);
6866 count_vm_event(PAGEOUTRUN
);
6869 * Account for the reclaim boost. Note that the zone boost is left in
6870 * place so that parallel allocations that are near the watermark will
6871 * stall or direct reclaim until kswapd is finished.
6873 nr_boost_reclaim
= 0;
6874 for (i
= 0; i
<= highest_zoneidx
; i
++) {
6875 zone
= pgdat
->node_zones
+ i
;
6876 if (!managed_zone(zone
))
6879 nr_boost_reclaim
+= zone
->watermark_boost
;
6880 zone_boosts
[i
] = zone
->watermark_boost
;
6882 boosted
= nr_boost_reclaim
;
6885 set_reclaim_active(pgdat
, highest_zoneidx
);
6886 sc
.priority
= DEF_PRIORITY
;
6888 unsigned long nr_reclaimed
= sc
.nr_reclaimed
;
6889 bool raise_priority
= true;
6894 sc
.reclaim_idx
= highest_zoneidx
;
6897 * If the number of buffer_heads exceeds the maximum allowed
6898 * then consider reclaiming from all zones. This has a dual
6899 * purpose -- on 64-bit systems it is expected that
6900 * buffer_heads are stripped during active rotation. On 32-bit
6901 * systems, highmem pages can pin lowmem memory and shrinking
6902 * buffers can relieve lowmem pressure. Reclaim may still not
6903 * go ahead if all eligible zones for the original allocation
6904 * request are balanced to avoid excessive reclaim from kswapd.
6906 if (buffer_heads_over_limit
) {
6907 for (i
= MAX_NR_ZONES
- 1; i
>= 0; i
--) {
6908 zone
= pgdat
->node_zones
+ i
;
6909 if (!managed_zone(zone
))
6918 * If the pgdat is imbalanced then ignore boosting and preserve
6919 * the watermarks for a later time and restart. Note that the
6920 * zone watermarks will be still reset at the end of balancing
6921 * on the grounds that the normal reclaim should be enough to
6922 * re-evaluate if boosting is required when kswapd next wakes.
6924 balanced
= pgdat_balanced(pgdat
, sc
.order
, highest_zoneidx
);
6925 if (!balanced
&& nr_boost_reclaim
) {
6926 nr_boost_reclaim
= 0;
6931 * If boosting is not active then only reclaim if there are no
6932 * eligible zones. Note that sc.reclaim_idx is not used as
6933 * buffer_heads_over_limit may have adjusted it.
6935 if (!nr_boost_reclaim
&& balanced
)
6938 /* Limit the priority of boosting to avoid reclaim writeback */
6939 if (nr_boost_reclaim
&& sc
.priority
== DEF_PRIORITY
- 2)
6940 raise_priority
= false;
6943 * Do not writeback or swap pages for boosted reclaim. The
6944 * intent is to relieve pressure not issue sub-optimal IO
6945 * from reclaim context. If no pages are reclaimed, the
6946 * reclaim will be aborted.
6948 sc
.may_writepage
= !laptop_mode
&& !nr_boost_reclaim
;
6949 sc
.may_swap
= !nr_boost_reclaim
;
6952 * Do some background aging, to give pages a chance to be
6953 * referenced before reclaiming. All pages are rotated
6954 * regardless of classzone as this is about consistent aging.
6956 kswapd_age_node(pgdat
, &sc
);
6959 * If we're getting trouble reclaiming, start doing writepage
6960 * even in laptop mode.
6962 if (sc
.priority
< DEF_PRIORITY
- 2)
6963 sc
.may_writepage
= 1;
6965 /* Call soft limit reclaim before calling shrink_node. */
6967 nr_soft_scanned
= 0;
6968 nr_soft_reclaimed
= memcg1_soft_limit_reclaim(pgdat
, sc
.order
,
6969 sc
.gfp_mask
, &nr_soft_scanned
);
6970 sc
.nr_reclaimed
+= nr_soft_reclaimed
;
6973 * There should be no need to raise the scanning priority if
6974 * enough pages are already being scanned that that high
6975 * watermark would be met at 100% efficiency.
6977 if (kswapd_shrink_node(pgdat
, &sc
))
6978 raise_priority
= false;
6981 * If the low watermark is met there is no need for processes
6982 * to be throttled on pfmemalloc_wait as they should not be
6983 * able to safely make forward progress. Wake them
6985 if (waitqueue_active(&pgdat
->pfmemalloc_wait
) &&
6986 allow_direct_reclaim(pgdat
))
6987 wake_up_all(&pgdat
->pfmemalloc_wait
);
6989 /* Check if kswapd should be suspending */
6990 __fs_reclaim_release(_THIS_IP_
);
6991 ret
= kthread_freezable_should_stop(&was_frozen
);
6992 __fs_reclaim_acquire(_THIS_IP_
);
6993 if (was_frozen
|| ret
)
6997 * Raise priority if scanning rate is too low or there was no
6998 * progress in reclaiming pages
7000 nr_reclaimed
= sc
.nr_reclaimed
- nr_reclaimed
;
7001 nr_boost_reclaim
-= min(nr_boost_reclaim
, nr_reclaimed
);
7004 * If reclaim made no progress for a boost, stop reclaim as
7005 * IO cannot be queued and it could be an infinite loop in
7006 * extreme circumstances.
7008 if (nr_boost_reclaim
&& !nr_reclaimed
)
7011 if (raise_priority
|| !nr_reclaimed
)
7013 } while (sc
.priority
>= 1);
7016 * Restart only if it went through the priority loop all the way,
7017 * but cache_trim_mode didn't work.
7019 if (!sc
.nr_reclaimed
&& sc
.priority
< 1 &&
7020 !sc
.no_cache_trim_mode
&& sc
.cache_trim_mode_failed
) {
7021 sc
.no_cache_trim_mode
= 1;
7025 if (!sc
.nr_reclaimed
)
7026 pgdat
->kswapd_failures
++;
7029 clear_reclaim_active(pgdat
, highest_zoneidx
);
7031 /* If reclaim was boosted, account for the reclaim done in this pass */
7033 unsigned long flags
;
7035 for (i
= 0; i
<= highest_zoneidx
; i
++) {
7036 if (!zone_boosts
[i
])
7039 /* Increments are under the zone lock */
7040 zone
= pgdat
->node_zones
+ i
;
7041 spin_lock_irqsave(&zone
->lock
, flags
);
7042 zone
->watermark_boost
-= min(zone
->watermark_boost
, zone_boosts
[i
]);
7043 spin_unlock_irqrestore(&zone
->lock
, flags
);
7047 * As there is now likely space, wakeup kcompact to defragment
7050 wakeup_kcompactd(pgdat
, pageblock_order
, highest_zoneidx
);
7053 snapshot_refaults(NULL
, pgdat
);
7054 __fs_reclaim_release(_THIS_IP_
);
7055 psi_memstall_leave(&pflags
);
7056 set_task_reclaim_state(current
, NULL
);
7059 * Return the order kswapd stopped reclaiming at as
7060 * prepare_kswapd_sleep() takes it into account. If another caller
7061 * entered the allocator slow path while kswapd was awake, order will
7062 * remain at the higher level.
7068 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7069 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7070 * not a valid index then either kswapd runs for first time or kswapd couldn't
7071 * sleep after previous reclaim attempt (node is still unbalanced). In that
7072 * case return the zone index of the previous kswapd reclaim cycle.
7074 static enum zone_type
kswapd_highest_zoneidx(pg_data_t
*pgdat
,
7075 enum zone_type prev_highest_zoneidx
)
7077 enum zone_type curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
7079 return curr_idx
== MAX_NR_ZONES
? prev_highest_zoneidx
: curr_idx
;
7082 static void kswapd_try_to_sleep(pg_data_t
*pgdat
, int alloc_order
, int reclaim_order
,
7083 unsigned int highest_zoneidx
)
7088 if (freezing(current
) || kthread_should_stop())
7091 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
7094 * Try to sleep for a short interval. Note that kcompactd will only be
7095 * woken if it is possible to sleep for a short interval. This is
7096 * deliberate on the assumption that if reclaim cannot keep an
7097 * eligible zone balanced that it's also unlikely that compaction will
7100 if (prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
7102 * Compaction records what page blocks it recently failed to
7103 * isolate pages from and skips them in the future scanning.
7104 * When kswapd is going to sleep, it is reasonable to assume
7105 * that pages and compaction may succeed so reset the cache.
7107 reset_isolation_suitable(pgdat
);
7110 * We have freed the memory, now we should compact it to make
7111 * allocation of the requested order possible.
7113 wakeup_kcompactd(pgdat
, alloc_order
, highest_zoneidx
);
7115 remaining
= schedule_timeout(HZ
/10);
7118 * If woken prematurely then reset kswapd_highest_zoneidx and
7119 * order. The values will either be from a wakeup request or
7120 * the previous request that slept prematurely.
7123 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
,
7124 kswapd_highest_zoneidx(pgdat
,
7127 if (READ_ONCE(pgdat
->kswapd_order
) < reclaim_order
)
7128 WRITE_ONCE(pgdat
->kswapd_order
, reclaim_order
);
7131 finish_wait(&pgdat
->kswapd_wait
, &wait
);
7132 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
7136 * After a short sleep, check if it was a premature sleep. If not, then
7137 * go fully to sleep until explicitly woken up.
7140 prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
7141 trace_mm_vmscan_kswapd_sleep(pgdat
->node_id
);
7144 * vmstat counters are not perfectly accurate and the estimated
7145 * value for counters such as NR_FREE_PAGES can deviate from the
7146 * true value by nr_online_cpus * threshold. To avoid the zone
7147 * watermarks being breached while under pressure, we reduce the
7148 * per-cpu vmstat threshold while kswapd is awake and restore
7149 * them before going back to sleep.
7151 set_pgdat_percpu_threshold(pgdat
, calculate_normal_threshold
);
7153 if (!kthread_should_stop())
7156 set_pgdat_percpu_threshold(pgdat
, calculate_pressure_threshold
);
7159 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY
);
7161 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY
);
7163 finish_wait(&pgdat
->kswapd_wait
, &wait
);
7167 * The background pageout daemon, started as a kernel thread
7168 * from the init process.
7170 * This basically trickles out pages so that we have _some_
7171 * free memory available even if there is no other activity
7172 * that frees anything up. This is needed for things like routing
7173 * etc, where we otherwise might have all activity going on in
7174 * asynchronous contexts that cannot page things out.
7176 * If there are applications that are active memory-allocators
7177 * (most normal use), this basically shouldn't matter.
7179 static int kswapd(void *p
)
7181 unsigned int alloc_order
, reclaim_order
;
7182 unsigned int highest_zoneidx
= MAX_NR_ZONES
- 1;
7183 pg_data_t
*pgdat
= (pg_data_t
*)p
;
7184 struct task_struct
*tsk
= current
;
7185 const struct cpumask
*cpumask
= cpumask_of_node(pgdat
->node_id
);
7187 if (!cpumask_empty(cpumask
))
7188 set_cpus_allowed_ptr(tsk
, cpumask
);
7191 * Tell the memory management that we're a "memory allocator",
7192 * and that if we need more memory we should get access to it
7193 * regardless (see "__alloc_pages()"). "kswapd" should
7194 * never get caught in the normal page freeing logic.
7196 * (Kswapd normally doesn't need memory anyway, but sometimes
7197 * you need a small amount of memory in order to be able to
7198 * page out something else, and this flag essentially protects
7199 * us from recursively trying to free more memory as we're
7200 * trying to free the first piece of memory in the first place).
7202 tsk
->flags
|= PF_MEMALLOC
| PF_KSWAPD
;
7205 WRITE_ONCE(pgdat
->kswapd_order
, 0);
7206 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
7207 atomic_set(&pgdat
->nr_writeback_throttled
, 0);
7211 alloc_order
= reclaim_order
= READ_ONCE(pgdat
->kswapd_order
);
7212 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
7216 kswapd_try_to_sleep(pgdat
, alloc_order
, reclaim_order
,
7219 /* Read the new order and highest_zoneidx */
7220 alloc_order
= READ_ONCE(pgdat
->kswapd_order
);
7221 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
7223 WRITE_ONCE(pgdat
->kswapd_order
, 0);
7224 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
7226 if (kthread_freezable_should_stop(&was_frozen
))
7230 * We can speed up thawing tasks if we don't call balance_pgdat
7231 * after returning from the refrigerator
7237 * Reclaim begins at the requested order but if a high-order
7238 * reclaim fails then kswapd falls back to reclaiming for
7239 * order-0. If that happens, kswapd will consider sleeping
7240 * for the order it finished reclaiming at (reclaim_order)
7241 * but kcompactd is woken to compact for the original
7242 * request (alloc_order).
7244 trace_mm_vmscan_kswapd_wake(pgdat
->node_id
, highest_zoneidx
,
7246 reclaim_order
= balance_pgdat(pgdat
, alloc_order
,
7248 if (reclaim_order
< alloc_order
)
7249 goto kswapd_try_sleep
;
7252 tsk
->flags
&= ~(PF_MEMALLOC
| PF_KSWAPD
);
7258 * A zone is low on free memory or too fragmented for high-order memory. If
7259 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7260 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7261 * has failed or is not needed, still wake up kcompactd if only compaction is
7264 void wakeup_kswapd(struct zone
*zone
, gfp_t gfp_flags
, int order
,
7265 enum zone_type highest_zoneidx
)
7268 enum zone_type curr_idx
;
7270 if (!managed_zone(zone
))
7273 if (!cpuset_zone_allowed(zone
, gfp_flags
))
7276 pgdat
= zone
->zone_pgdat
;
7277 curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
7279 if (curr_idx
== MAX_NR_ZONES
|| curr_idx
< highest_zoneidx
)
7280 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, highest_zoneidx
);
7282 if (READ_ONCE(pgdat
->kswapd_order
) < order
)
7283 WRITE_ONCE(pgdat
->kswapd_order
, order
);
7285 if (!waitqueue_active(&pgdat
->kswapd_wait
))
7288 /* Hopeless node, leave it to direct reclaim if possible */
7289 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
||
7290 (pgdat_balanced(pgdat
, order
, highest_zoneidx
) &&
7291 !pgdat_watermark_boosted(pgdat
, highest_zoneidx
))) {
7293 * There may be plenty of free memory available, but it's too
7294 * fragmented for high-order allocations. Wake up kcompactd
7295 * and rely on compaction_suitable() to determine if it's
7296 * needed. If it fails, it will defer subsequent attempts to
7297 * ratelimit its work.
7299 if (!(gfp_flags
& __GFP_DIRECT_RECLAIM
))
7300 wakeup_kcompactd(pgdat
, order
, highest_zoneidx
);
7304 trace_mm_vmscan_wakeup_kswapd(pgdat
->node_id
, highest_zoneidx
, order
,
7306 wake_up_interruptible(&pgdat
->kswapd_wait
);
7309 #ifdef CONFIG_HIBERNATION
7311 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7314 * Rather than trying to age LRUs the aim is to preserve the overall
7315 * LRU order by reclaiming preferentially
7316 * inactive > active > active referenced > active mapped
7318 unsigned long shrink_all_memory(unsigned long nr_to_reclaim
)
7320 struct scan_control sc
= {
7321 .nr_to_reclaim
= nr_to_reclaim
,
7322 .gfp_mask
= GFP_HIGHUSER_MOVABLE
,
7323 .reclaim_idx
= MAX_NR_ZONES
- 1,
7324 .priority
= DEF_PRIORITY
,
7328 .hibernation_mode
= 1,
7330 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
7331 unsigned long nr_reclaimed
;
7332 unsigned int noreclaim_flag
;
7334 fs_reclaim_acquire(sc
.gfp_mask
);
7335 noreclaim_flag
= memalloc_noreclaim_save();
7336 set_task_reclaim_state(current
, &sc
.reclaim_state
);
7338 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
7340 set_task_reclaim_state(current
, NULL
);
7341 memalloc_noreclaim_restore(noreclaim_flag
);
7342 fs_reclaim_release(sc
.gfp_mask
);
7344 return nr_reclaimed
;
7346 #endif /* CONFIG_HIBERNATION */
7349 * This kswapd start function will be called by init and node-hot-add.
7351 void __meminit
kswapd_run(int nid
)
7353 pg_data_t
*pgdat
= NODE_DATA(nid
);
7355 pgdat_kswapd_lock(pgdat
);
7356 if (!pgdat
->kswapd
) {
7357 pgdat
->kswapd
= kthread_run(kswapd
, pgdat
, "kswapd%d", nid
);
7358 if (IS_ERR(pgdat
->kswapd
)) {
7359 /* failure at boot is fatal */
7360 pr_err("Failed to start kswapd on node %d,ret=%ld\n",
7361 nid
, PTR_ERR(pgdat
->kswapd
));
7362 BUG_ON(system_state
< SYSTEM_RUNNING
);
7363 pgdat
->kswapd
= NULL
;
7366 pgdat_kswapd_unlock(pgdat
);
7370 * Called by memory hotplug when all memory in a node is offlined. Caller must
7371 * be holding mem_hotplug_begin/done().
7373 void __meminit
kswapd_stop(int nid
)
7375 pg_data_t
*pgdat
= NODE_DATA(nid
);
7376 struct task_struct
*kswapd
;
7378 pgdat_kswapd_lock(pgdat
);
7379 kswapd
= pgdat
->kswapd
;
7381 kthread_stop(kswapd
);
7382 pgdat
->kswapd
= NULL
;
7384 pgdat_kswapd_unlock(pgdat
);
7387 static int __init
kswapd_init(void)
7392 for_each_node_state(nid
, N_MEMORY
)
7397 module_init(kswapd_init
)
7403 * If non-zero call node_reclaim when the number of free pages falls below
7406 int node_reclaim_mode __read_mostly
;
7409 * Priority for NODE_RECLAIM. This determines the fraction of pages
7410 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7413 #define NODE_RECLAIM_PRIORITY 4
7416 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7419 int sysctl_min_unmapped_ratio
= 1;
7422 * If the number of slab pages in a zone grows beyond this percentage then
7423 * slab reclaim needs to occur.
7425 int sysctl_min_slab_ratio
= 5;
7427 static inline unsigned long node_unmapped_file_pages(struct pglist_data
*pgdat
)
7429 unsigned long file_mapped
= node_page_state(pgdat
, NR_FILE_MAPPED
);
7430 unsigned long file_lru
= node_page_state(pgdat
, NR_INACTIVE_FILE
) +
7431 node_page_state(pgdat
, NR_ACTIVE_FILE
);
7434 * It's possible for there to be more file mapped pages than
7435 * accounted for by the pages on the file LRU lists because
7436 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7438 return (file_lru
> file_mapped
) ? (file_lru
- file_mapped
) : 0;
7441 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7442 static unsigned long node_pagecache_reclaimable(struct pglist_data
*pgdat
)
7444 unsigned long nr_pagecache_reclaimable
;
7445 unsigned long delta
= 0;
7448 * If RECLAIM_UNMAP is set, then all file pages are considered
7449 * potentially reclaimable. Otherwise, we have to worry about
7450 * pages like swapcache and node_unmapped_file_pages() provides
7453 if (node_reclaim_mode
& RECLAIM_UNMAP
)
7454 nr_pagecache_reclaimable
= node_page_state(pgdat
, NR_FILE_PAGES
);
7456 nr_pagecache_reclaimable
= node_unmapped_file_pages(pgdat
);
7458 /* If we can't clean pages, remove dirty pages from consideration */
7459 if (!(node_reclaim_mode
& RECLAIM_WRITE
))
7460 delta
+= node_page_state(pgdat
, NR_FILE_DIRTY
);
7462 /* Watch for any possible underflows due to delta */
7463 if (unlikely(delta
> nr_pagecache_reclaimable
))
7464 delta
= nr_pagecache_reclaimable
;
7466 return nr_pagecache_reclaimable
- delta
;
7470 * Try to free up some pages from this node through reclaim.
7472 static int __node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
7474 /* Minimum pages needed in order to stay on node */
7475 const unsigned long nr_pages
= 1 << order
;
7476 struct task_struct
*p
= current
;
7477 unsigned int noreclaim_flag
;
7478 struct scan_control sc
= {
7479 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
7480 .gfp_mask
= current_gfp_context(gfp_mask
),
7482 .priority
= NODE_RECLAIM_PRIORITY
,
7483 .may_writepage
= !!(node_reclaim_mode
& RECLAIM_WRITE
),
7484 .may_unmap
= !!(node_reclaim_mode
& RECLAIM_UNMAP
),
7486 .reclaim_idx
= gfp_zone(gfp_mask
),
7488 unsigned long pflags
;
7490 trace_mm_vmscan_node_reclaim_begin(pgdat
->node_id
, order
,
7494 psi_memstall_enter(&pflags
);
7495 delayacct_freepages_start();
7496 fs_reclaim_acquire(sc
.gfp_mask
);
7498 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7500 noreclaim_flag
= memalloc_noreclaim_save();
7501 set_task_reclaim_state(p
, &sc
.reclaim_state
);
7503 if (node_pagecache_reclaimable(pgdat
) > pgdat
->min_unmapped_pages
||
7504 node_page_state_pages(pgdat
, NR_SLAB_RECLAIMABLE_B
) > pgdat
->min_slab_pages
) {
7506 * Free memory by calling shrink node with increasing
7507 * priorities until we have enough memory freed.
7510 shrink_node(pgdat
, &sc
);
7511 } while (sc
.nr_reclaimed
< nr_pages
&& --sc
.priority
>= 0);
7514 set_task_reclaim_state(p
, NULL
);
7515 memalloc_noreclaim_restore(noreclaim_flag
);
7516 fs_reclaim_release(sc
.gfp_mask
);
7517 psi_memstall_leave(&pflags
);
7518 delayacct_freepages_end();
7520 trace_mm_vmscan_node_reclaim_end(sc
.nr_reclaimed
);
7522 return sc
.nr_reclaimed
>= nr_pages
;
7525 int node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
7530 * Node reclaim reclaims unmapped file backed pages and
7531 * slab pages if we are over the defined limits.
7533 * A small portion of unmapped file backed pages is needed for
7534 * file I/O otherwise pages read by file I/O will be immediately
7535 * thrown out if the node is overallocated. So we do not reclaim
7536 * if less than a specified percentage of the node is used by
7537 * unmapped file backed pages.
7539 if (node_pagecache_reclaimable(pgdat
) <= pgdat
->min_unmapped_pages
&&
7540 node_page_state_pages(pgdat
, NR_SLAB_RECLAIMABLE_B
) <=
7541 pgdat
->min_slab_pages
)
7542 return NODE_RECLAIM_FULL
;
7545 * Do not scan if the allocation should not be delayed.
7547 if (!gfpflags_allow_blocking(gfp_mask
) || (current
->flags
& PF_MEMALLOC
))
7548 return NODE_RECLAIM_NOSCAN
;
7551 * Only run node reclaim on the local node or on nodes that do not
7552 * have associated processors. This will favor the local processor
7553 * over remote processors and spread off node memory allocations
7554 * as wide as possible.
7556 if (node_state(pgdat
->node_id
, N_CPU
) && pgdat
->node_id
!= numa_node_id())
7557 return NODE_RECLAIM_NOSCAN
;
7559 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
))
7560 return NODE_RECLAIM_NOSCAN
;
7562 ret
= __node_reclaim(pgdat
, gfp_mask
, order
);
7563 clear_bit(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
);
7566 count_vm_event(PGSCAN_ZONE_RECLAIM_SUCCESS
);
7568 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED
);
7575 * check_move_unevictable_folios - Move evictable folios to appropriate zone
7577 * @fbatch: Batch of lru folios to check.
7579 * Checks folios for evictability, if an evictable folio is in the unevictable
7580 * lru list, moves it to the appropriate evictable lru list. This function
7581 * should be only used for lru folios.
7583 void check_move_unevictable_folios(struct folio_batch
*fbatch
)
7585 struct lruvec
*lruvec
= NULL
;
7590 for (i
= 0; i
< fbatch
->nr
; i
++) {
7591 struct folio
*folio
= fbatch
->folios
[i
];
7592 int nr_pages
= folio_nr_pages(folio
);
7594 pgscanned
+= nr_pages
;
7596 /* block memcg migration while the folio moves between lrus */
7597 if (!folio_test_clear_lru(folio
))
7600 lruvec
= folio_lruvec_relock_irq(folio
, lruvec
);
7601 if (folio_evictable(folio
) && folio_test_unevictable(folio
)) {
7602 lruvec_del_folio(lruvec
, folio
);
7603 folio_clear_unevictable(folio
);
7604 lruvec_add_folio(lruvec
, folio
);
7605 pgrescued
+= nr_pages
;
7607 folio_set_lru(folio
);
7611 __count_vm_events(UNEVICTABLE_PGRESCUED
, pgrescued
);
7612 __count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
7613 unlock_page_lruvec_irq(lruvec
);
7614 } else if (pgscanned
) {
7615 count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
7618 EXPORT_SYMBOL_GPL(check_move_unevictable_folios
);