1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
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.
11 */
12
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
15 #include <linux/mm.h>
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>
60
61 #include <asm/tlbflush.h>
62 #include <asm/div64.h>
63
64 #include <linux/swapops.h>
65 #include <linux/balloon_compaction.h>
66 #include <linux/sched/sysctl.h>
67
68 #include "internal.h"
69 #include "swap.h"
70
71 #define CREATE_TRACE_POINTS
72 #include <trace/events/vmscan.h>
73
74 struct scan_control {
75 /* How many pages shrink_list() should reclaim */
76 unsigned long nr_to_reclaim;
77
78 /*
79 * Nodemask of nodes allowed by the caller. If NULL, all nodes
80 * are scanned.
81 */
82 nodemask_t *nodemask;
83
84 /*
85 * The memory cgroup that hit its limit and as a result is the
86 * primary target of this reclaim invocation.
87 */
88 struct mem_cgroup *target_mem_cgroup;
89
90 /*
91 * Scan pressure balancing between anon and file LRUs
92 */
93 unsigned long anon_cost;
94 unsigned long file_cost;
95
96 #ifdef CONFIG_MEMCG
97 /* Swappiness value for proactive reclaim. Always use sc_swappiness()! */
98 int *proactive_swappiness;
99 #endif
100
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;
107
108 /* Writepage batching in laptop mode; RECLAIM_WRITE */
109 unsigned int may_writepage:1;
110
111 /* Can mapped folios be reclaimed? */
112 unsigned int may_unmap:1;
113
114 /* Can folios be swapped as part of reclaim? */
115 unsigned int may_swap:1;
116
117 /* Not allow cache_trim_mode to be turned on as part of reclaim? */
118 unsigned int no_cache_trim_mode:1;
119
120 /* Has cache_trim_mode failed at least once? */
121 unsigned int cache_trim_mode_failed:1;
122
123 /* Proactive reclaim invoked by userspace through memory.reclaim */
124 unsigned int proactive:1;
125
126 /*
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.
133 */
134 unsigned int memcg_low_reclaim:1;
135 unsigned int memcg_low_skipped:1;
136
137 /* Shared cgroup tree walk failed, rescan the whole tree */
138 unsigned int memcg_full_walk:1;
139
140 unsigned int hibernation_mode:1;
141
142 /* One of the zones is ready for compaction */
143 unsigned int compaction_ready:1;
144
145 /* There is easily reclaimable cold cache in the current node */
146 unsigned int cache_trim_mode:1;
147
148 /* The file folios on the current node are dangerously low */
149 unsigned int file_is_tiny:1;
150
151 /* Always discard instead of demoting to lower tier memory */
152 unsigned int no_demotion:1;
153
154 /* Allocation order */
155 s8 order;
156
157 /* Scan (total_size >> priority) pages at once */
158 s8 priority;
159
160 /* The highest zone to isolate folios for reclaim from */
161 s8 reclaim_idx;
162
163 /* This context's GFP mask */
164 gfp_t gfp_mask;
165
166 /* Incremented by the number of inactive pages that were scanned */
167 unsigned long nr_scanned;
168
169 /* Number of pages freed so far during a call to shrink_zones() */
170 unsigned long nr_reclaimed;
171
172 struct {
173 unsigned int dirty;
174 unsigned int unqueued_dirty;
175 unsigned int congested;
176 unsigned int writeback;
177 unsigned int immediate;
178 unsigned int file_taken;
179 unsigned int taken;
180 } nr;
181
182 /* for recording the reclaimed slab by now */
183 struct reclaim_state reclaim_state;
184 };
185
186 #ifdef ARCH_HAS_PREFETCHW
187 #define prefetchw_prev_lru_folio(_folio, _base, _field) \
188 do { \
189 if ((_folio)->lru.prev != _base) { \
190 struct folio *prev; \
191 \
192 prev = lru_to_folio(&(_folio->lru)); \
193 prefetchw(&prev->_field); \
194 } \
195 } while (0)
196 #else
197 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
198 #endif
199
200 /*
201 * From 0 .. MAX_SWAPPINESS. Higher means more swappy.
202 */
203 int vm_swappiness = 60;
204
205 #ifdef CONFIG_MEMCG
206
207 /* Returns true for reclaim through cgroup limits or cgroup interfaces. */
cgroup_reclaim(struct scan_control * sc)208 static bool cgroup_reclaim(struct scan_control *sc)
209 {
210 return sc->target_mem_cgroup;
211 }
212
213 /*
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.
216 */
root_reclaim(struct scan_control * sc)217 static bool root_reclaim(struct scan_control *sc)
218 {
219 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
220 }
221
222 /**
223 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
224 * @sc: scan_control in question
225 *
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.
231 *
232 * This function tests whether the vmscan currently in progress can assume
233 * that the normal dirty throttling mechanism is operational.
234 */
writeback_throttling_sane(struct scan_control * sc)235 static bool writeback_throttling_sane(struct scan_control *sc)
236 {
237 if (!cgroup_reclaim(sc))
238 return true;
239 #ifdef CONFIG_CGROUP_WRITEBACK
240 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
241 return true;
242 #endif
243 return false;
244 }
245
sc_swappiness(struct scan_control * sc,struct mem_cgroup * memcg)246 static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)
247 {
248 if (sc->proactive && sc->proactive_swappiness)
249 return *sc->proactive_swappiness;
250 return mem_cgroup_swappiness(memcg);
251 }
252 #else
cgroup_reclaim(struct scan_control * sc)253 static bool cgroup_reclaim(struct scan_control *sc)
254 {
255 return false;
256 }
257
root_reclaim(struct scan_control * sc)258 static bool root_reclaim(struct scan_control *sc)
259 {
260 return true;
261 }
262
writeback_throttling_sane(struct scan_control * sc)263 static bool writeback_throttling_sane(struct scan_control *sc)
264 {
265 return true;
266 }
267
sc_swappiness(struct scan_control * sc,struct mem_cgroup * memcg)268 static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)
269 {
270 return READ_ONCE(vm_swappiness);
271 }
272 #endif
273
set_task_reclaim_state(struct task_struct * task,struct reclaim_state * rs)274 static void set_task_reclaim_state(struct task_struct *task,
275 struct reclaim_state *rs)
276 {
277 /* Check for an overwrite */
278 WARN_ON_ONCE(rs && task->reclaim_state);
279
280 /* Check for the nulling of an already-nulled member */
281 WARN_ON_ONCE(!rs && !task->reclaim_state);
282
283 task->reclaim_state = rs;
284 }
285
286 /*
287 * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to
288 * scan_control->nr_reclaimed.
289 */
flush_reclaim_state(struct scan_control * sc)290 static void flush_reclaim_state(struct scan_control *sc)
291 {
292 /*
293 * Currently, reclaim_state->reclaimed includes three types of pages
294 * freed outside of vmscan:
295 * (1) Slab pages.
296 * (2) Clean file pages from pruned inodes (on highmem systems).
297 * (3) XFS freed buffer pages.
298 *
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).
304 *
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.
308 *
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
314 * retry loop).
315 *
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.
319 */
320 if (current->reclaim_state && root_reclaim(sc)) {
321 sc->nr_reclaimed += current->reclaim_state->reclaimed;
322 current->reclaim_state->reclaimed = 0;
323 }
324 }
325
can_demote(int nid,struct scan_control * sc)326 static bool can_demote(int nid, struct scan_control *sc)
327 {
328 if (!numa_demotion_enabled)
329 return false;
330 if (sc && sc->no_demotion)
331 return false;
332 if (next_demotion_node(nid) == NUMA_NO_NODE)
333 return false;
334
335 return true;
336 }
337
can_reclaim_anon_pages(struct mem_cgroup * memcg,int nid,struct scan_control * sc)338 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
339 int nid,
340 struct scan_control *sc)
341 {
342 if (memcg == NULL) {
343 /*
344 * For non-memcg reclaim, is there
345 * space in any swap device?
346 */
347 if (get_nr_swap_pages() > 0)
348 return true;
349 } else {
350 /* Is the memcg below its swap limit? */
351 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
352 return true;
353 }
354
355 /*
356 * The page can not be swapped.
357 *
358 * Can it be reclaimed from this node via demotion?
359 */
360 return can_demote(nid, sc);
361 }
362
363 /*
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.
367 */
zone_reclaimable_pages(struct zone * zone)368 unsigned long zone_reclaimable_pages(struct zone *zone)
369 {
370 unsigned long nr;
371
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);
377
378 return nr;
379 }
380
381 /**
382 * lruvec_lru_size - Returns the number of pages on the given LRU list.
383 * @lruvec: lru vector
384 * @lru: lru to use
385 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
386 */
lruvec_lru_size(struct lruvec * lruvec,enum lru_list lru,int zone_idx)387 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
388 int zone_idx)
389 {
390 unsigned long size = 0;
391 int zid;
392
393 for (zid = 0; zid <= zone_idx; zid++) {
394 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
395
396 if (!managed_zone(zone))
397 continue;
398
399 if (!mem_cgroup_disabled())
400 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
401 else
402 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
403 }
404 return size;
405 }
406
drop_slab_node(int nid)407 static unsigned long drop_slab_node(int nid)
408 {
409 unsigned long freed = 0;
410 struct mem_cgroup *memcg = NULL;
411
412 memcg = mem_cgroup_iter(NULL, NULL, NULL);
413 do {
414 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
415 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
416
417 return freed;
418 }
419
drop_slab(void)420 void drop_slab(void)
421 {
422 int nid;
423 int shift = 0;
424 unsigned long freed;
425
426 do {
427 freed = 0;
428 for_each_online_node(nid) {
429 if (fatal_signal_pending(current))
430 return;
431
432 freed += drop_slab_node(nid);
433 }
434 } while ((freed >> shift++) > 1);
435 }
436
reclaimer_offset(void)437 static int reclaimer_offset(void)
438 {
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);
447
448 if (current_is_kswapd())
449 return 0;
450 if (current_is_khugepaged())
451 return PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD;
452 return PGSTEAL_DIRECT - PGSTEAL_KSWAPD;
453 }
454
is_page_cache_freeable(struct folio * folio)455 static inline int is_page_cache_freeable(struct folio *folio)
456 {
457 /*
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.
461 */
462 return folio_ref_count(folio) - folio_test_private(folio) ==
463 1 + folio_nr_pages(folio);
464 }
465
466 /*
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().
470 *
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.
474 *
475 * We're allowed to run sleeping folio_lock() here because we know the caller has
476 * __GFP_FS.
477 */
handle_write_error(struct address_space * mapping,struct folio * folio,int error)478 static void handle_write_error(struct address_space *mapping,
479 struct folio *folio, int error)
480 {
481 folio_lock(folio);
482 if (folio_mapping(folio) == mapping)
483 mapping_set_error(mapping, error);
484 folio_unlock(folio);
485 }
486
skip_throttle_noprogress(pg_data_t * pgdat)487 static bool skip_throttle_noprogress(pg_data_t *pgdat)
488 {
489 int reclaimable = 0, write_pending = 0;
490 int i;
491
492 /*
493 * If kswapd is disabled, reschedule if necessary but do not
494 * throttle as the system is likely near OOM.
495 */
496 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
497 return true;
498
499 /*
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.
503 */
504 for (i = 0; i < MAX_NR_ZONES; i++) {
505 struct zone *zone = pgdat->node_zones + i;
506
507 if (!managed_zone(zone))
508 continue;
509
510 reclaimable += zone_reclaimable_pages(zone);
511 write_pending += zone_page_state_snapshot(zone,
512 NR_ZONE_WRITE_PENDING);
513 }
514 if (2 * write_pending <= reclaimable)
515 return true;
516
517 return false;
518 }
519
reclaim_throttle(pg_data_t * pgdat,enum vmscan_throttle_state reason)520 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
521 {
522 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
523 long timeout, ret;
524 DEFINE_WAIT(wait);
525
526 /*
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).
530 */
531 if (!current_is_kswapd() &&
532 current->flags & (PF_USER_WORKER|PF_KTHREAD)) {
533 cond_resched();
534 return;
535 }
536
537 /*
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.
546 */
547 switch(reason) {
548 case VMSCAN_THROTTLE_WRITEBACK:
549 timeout = HZ/10;
550
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));
554 }
555
556 break;
557 case VMSCAN_THROTTLE_CONGESTED:
558 fallthrough;
559 case VMSCAN_THROTTLE_NOPROGRESS:
560 if (skip_throttle_noprogress(pgdat)) {
561 cond_resched();
562 return;
563 }
564
565 timeout = 1;
566
567 break;
568 case VMSCAN_THROTTLE_ISOLATED:
569 timeout = HZ/50;
570 break;
571 default:
572 WARN_ON_ONCE(1);
573 timeout = HZ;
574 break;
575 }
576
577 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
578 ret = schedule_timeout(timeout);
579 finish_wait(wqh, &wait);
580
581 if (reason == VMSCAN_THROTTLE_WRITEBACK)
582 atomic_dec(&pgdat->nr_writeback_throttled);
583
584 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
585 jiffies_to_usecs(timeout - ret),
586 reason);
587 }
588
589 /*
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.
593 */
__acct_reclaim_writeback(pg_data_t * pgdat,struct folio * folio,int nr_throttled)594 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
595 int nr_throttled)
596 {
597 unsigned long nr_written;
598
599 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
600
601 /*
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.
607 */
608 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
609 READ_ONCE(pgdat->nr_reclaim_start);
610
611 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
612 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
613 }
614
615 /* possible outcome of pageout() */
616 typedef enum {
617 /* failed to write folio out, folio is locked */
618 PAGE_KEEP,
619 /* move folio to the active list, folio is locked */
620 PAGE_ACTIVATE,
621 /* folio has been sent to the disk successfully, folio is unlocked */
622 PAGE_SUCCESS,
623 /* folio is clean and locked */
624 PAGE_CLEAN,
625 } pageout_t;
626
627 /*
628 * pageout is called by shrink_folio_list() for each dirty folio.
629 * Calls ->writepage().
630 */
pageout(struct folio * folio,struct address_space * mapping,struct swap_iocb ** plug,struct list_head * folio_list)631 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
632 struct swap_iocb **plug, struct list_head *folio_list)
633 {
634 /*
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.
640 *
641 * If this process is currently in __generic_file_write_iter() against
642 * this folio's queue, we can perform writeback even if that
643 * will block.
644 *
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.
649 */
650 if (!is_page_cache_freeable(folio))
651 return PAGE_KEEP;
652 if (!mapping) {
653 /*
654 * Some data journaling orphaned folios can have
655 * folio->mapping == NULL while being dirty with clean buffers.
656 */
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__);
661 return PAGE_CLEAN;
662 }
663 }
664 return PAGE_KEEP;
665 }
666 if (mapping->a_ops->writepage == NULL)
667 return PAGE_ACTIVATE;
668
669 if (folio_clear_dirty_for_io(folio)) {
670 int res;
671 struct writeback_control wbc = {
672 .sync_mode = WB_SYNC_NONE,
673 .nr_to_write = SWAP_CLUSTER_MAX,
674 .range_start = 0,
675 .range_end = LLONG_MAX,
676 .for_reclaim = 1,
677 .swap_plug = plug,
678 };
679
680 /*
681 * The large shmem folio can be split if CONFIG_THP_SWAP is
682 * not enabled or contiguous swap entries are failed to
683 * allocate.
684 */
685 if (shmem_mapping(mapping) && folio_test_large(folio))
686 wbc.list = folio_list;
687
688 folio_set_reclaim(folio);
689 res = mapping->a_ops->writepage(&folio->page, &wbc);
690 if (res < 0)
691 handle_write_error(mapping, folio, res);
692 if (res == AOP_WRITEPAGE_ACTIVATE) {
693 folio_clear_reclaim(folio);
694 return PAGE_ACTIVATE;
695 }
696
697 if (!folio_test_writeback(folio)) {
698 /* synchronous write or broken a_ops? */
699 folio_clear_reclaim(folio);
700 }
701 trace_mm_vmscan_write_folio(folio);
702 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
703 return PAGE_SUCCESS;
704 }
705
706 return PAGE_CLEAN;
707 }
708
709 /*
710 * Same as remove_mapping, but if the folio is removed from the mapping, it
711 * gets returned with a refcount of 0.
712 */
__remove_mapping(struct address_space * mapping,struct folio * folio,bool reclaimed,struct mem_cgroup * target_memcg)713 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
714 bool reclaimed, struct mem_cgroup *target_memcg)
715 {
716 int refcount;
717 void *shadow = NULL;
718
719 BUG_ON(!folio_test_locked(folio));
720 BUG_ON(mapping != folio_mapping(folio));
721
722 if (!folio_test_swapcache(folio))
723 spin_lock(&mapping->host->i_lock);
724 xa_lock_irq(&mapping->i_pages);
725 /*
726 * The non racy check for a busy folio.
727 *
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:
732 *
733 * get_user_pages(&page);
734 * [user mapping goes away]
735 * write_to(page);
736 * !folio_test_dirty(folio) [good]
737 * folio_set_dirty(folio);
738 * folio_put(folio);
739 * !refcount(folio) [good, discard it]
740 *
741 * [oops, our write_to data is lost]
742 *
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.
746 *
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.
749 */
750 refcount = 1 + folio_nr_pages(folio);
751 if (!folio_ref_freeze(folio, refcount))
752 goto cannot_free;
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);
756 goto cannot_free;
757 }
758
759 if (folio_test_swapcache(folio)) {
760 swp_entry_t swap = folio->swap;
761
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);
768 } else {
769 void (*free_folio)(struct folio *);
770
771 free_folio = mapping->a_ops->free_folio;
772 /*
773 * Remember a shadow entry for reclaimed file cache in
774 * order to detect refaults, thus thrashing, later on.
775 *
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
780 * back.
781 *
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.
787 */
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);
796
797 if (free_folio)
798 free_folio(folio);
799 }
800
801 return 1;
802
803 cannot_free:
804 xa_unlock_irq(&mapping->i_pages);
805 if (!folio_test_swapcache(folio))
806 spin_unlock(&mapping->host->i_lock);
807 return 0;
808 }
809
810 /**
811 * remove_mapping() - Attempt to remove a folio from its mapping.
812 * @mapping: The address space.
813 * @folio: The folio to remove.
814 *
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
820 * hold its lock.
821 */
remove_mapping(struct address_space * mapping,struct folio * folio)822 long remove_mapping(struct address_space *mapping, struct folio *folio)
823 {
824 if (__remove_mapping(mapping, folio, false, NULL)) {
825 /*
826 * Unfreezing the refcount with 1 effectively
827 * drops the pagecache ref for us without requiring another
828 * atomic operation.
829 */
830 folio_ref_unfreeze(folio, 1);
831 return folio_nr_pages(folio);
832 }
833 return 0;
834 }
835
836 /**
837 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
838 * @folio: Folio to be returned to an LRU list.
839 *
840 * Add previously isolated @folio to appropriate LRU list.
841 * The folio may still be unevictable for other reasons.
842 *
843 * Context: lru_lock must not be held, interrupts must be enabled.
844 */
folio_putback_lru(struct folio * folio)845 void folio_putback_lru(struct folio *folio)
846 {
847 folio_add_lru(folio);
848 folio_put(folio); /* drop ref from isolate */
849 }
850
851 enum folio_references {
852 FOLIOREF_RECLAIM,
853 FOLIOREF_RECLAIM_CLEAN,
854 FOLIOREF_KEEP,
855 FOLIOREF_ACTIVATE,
856 };
857
folio_check_references(struct folio * folio,struct scan_control * sc)858 static enum folio_references folio_check_references(struct folio *folio,
859 struct scan_control *sc)
860 {
861 int referenced_ptes, referenced_folio;
862 unsigned long vm_flags;
863
864 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
865 &vm_flags);
866 referenced_folio = folio_test_clear_referenced(folio);
867
868 /*
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.
871 */
872 if (vm_flags & VM_LOCKED)
873 return FOLIOREF_ACTIVATE;
874
875 /*
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.
880 */
881 if (referenced_ptes == -1)
882 return FOLIOREF_KEEP;
883
884 if (referenced_ptes) {
885 /*
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
889 * than once.
890 *
891 * Mark it and spare it for another trip around the
892 * inactive list. Another page table reference will
893 * lead to its activation.
894 *
895 * Note: the mark is set for activated folios as well
896 * so that recently deactivated but used folios are
897 * quickly recovered.
898 */
899 folio_set_referenced(folio);
900
901 if (referenced_folio || referenced_ptes > 1)
902 return FOLIOREF_ACTIVATE;
903
904 /*
905 * Activate file-backed executable folios after first usage.
906 */
907 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
908 return FOLIOREF_ACTIVATE;
909
910 return FOLIOREF_KEEP;
911 }
912
913 /* Reclaim if clean, defer dirty folios to writeback */
914 if (referenced_folio && folio_is_file_lru(folio))
915 return FOLIOREF_RECLAIM_CLEAN;
916
917 return FOLIOREF_RECLAIM;
918 }
919
920 /* Check if a folio is dirty or under writeback */
folio_check_dirty_writeback(struct folio * folio,bool * dirty,bool * writeback)921 static void folio_check_dirty_writeback(struct folio *folio,
922 bool *dirty, bool *writeback)
923 {
924 struct address_space *mapping;
925
926 /*
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
931 * test is needed.
932 */
933 if (!folio_is_file_lru(folio) ||
934 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
935 *dirty = false;
936 *writeback = false;
937 return;
938 }
939
940 /* By default assume that the folio flags are accurate */
941 *dirty = folio_test_dirty(folio);
942 *writeback = folio_test_writeback(folio);
943
944 /* Verify dirty/writeback state if the filesystem supports it */
945 if (!folio_test_private(folio))
946 return;
947
948 mapping = folio_mapping(folio);
949 if (mapping && mapping->a_ops->is_dirty_writeback)
950 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
951 }
952
alloc_migrate_folio(struct folio * src,unsigned long private)953 struct folio *alloc_migrate_folio(struct folio *src, unsigned long private)
954 {
955 struct folio *dst;
956 nodemask_t *allowed_mask;
957 struct migration_target_control *mtc;
958
959 mtc = (struct migration_target_control *)private;
960
961 allowed_mask = mtc->nmask;
962 /*
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.
970 */
971 mtc->nmask = NULL;
972 mtc->gfp_mask |= __GFP_THISNODE;
973 dst = alloc_migration_target(src, (unsigned long)mtc);
974 if (dst)
975 return dst;
976
977 mtc->gfp_mask &= ~__GFP_THISNODE;
978 mtc->nmask = allowed_mask;
979
980 return alloc_migration_target(src, (unsigned long)mtc);
981 }
982
983 /*
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.
986 */
demote_folio_list(struct list_head * demote_folios,struct pglist_data * pgdat)987 static unsigned int demote_folio_list(struct list_head *demote_folios,
988 struct pglist_data *pgdat)
989 {
990 int target_nid = next_demotion_node(pgdat->node_id);
991 unsigned int nr_succeeded;
992 nodemask_t allowed_mask;
993
994 struct migration_target_control mtc = {
995 /*
996 * Allocate from 'node', or fail quickly and quietly.
997 * When this happens, 'page' will likely just be discarded
998 * instead of migrated.
999 */
1000 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | __GFP_NOWARN |
1001 __GFP_NOMEMALLOC | GFP_NOWAIT,
1002 .nid = target_nid,
1003 .nmask = &allowed_mask,
1004 .reason = MR_DEMOTION,
1005 };
1006
1007 if (list_empty(demote_folios))
1008 return 0;
1009
1010 if (target_nid == NUMA_NO_NODE)
1011 return 0;
1012
1013 node_get_allowed_targets(pgdat, &allowed_mask);
1014
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,
1018 &nr_succeeded);
1019
1020 return nr_succeeded;
1021 }
1022
may_enter_fs(struct folio * folio,gfp_t gfp_mask)1023 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1024 {
1025 if (gfp_mask & __GFP_FS)
1026 return true;
1027 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1028 return false;
1029 /*
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
1034 * is safe.
1035 */
1036 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1037 }
1038
1039 /*
1040 * shrink_folio_list() returns the number of reclaimed pages
1041 */
shrink_folio_list(struct list_head * folio_list,struct pglist_data * pgdat,struct scan_control * sc,struct reclaim_stat * stat,bool ignore_references)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)
1045 {
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;
1053
1054 folio_batch_init(&free_folios);
1055 memset(stat, 0, sizeof(*stat));
1056 cond_resched();
1057 do_demote_pass = can_demote(pgdat->node_id, sc);
1058
1059 retry:
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;
1066
1067 cond_resched();
1068
1069 folio = lru_to_folio(folio_list);
1070 list_del(&folio->lru);
1071
1072 if (!folio_trylock(folio))
1073 goto keep;
1074
1075 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1076
1077 nr_pages = folio_nr_pages(folio);
1078
1079 /* Account the number of base pages */
1080 sc->nr_scanned += nr_pages;
1081
1082 if (unlikely(!folio_evictable(folio)))
1083 goto activate_locked;
1084
1085 if (!sc->may_unmap && folio_mapped(folio))
1086 goto keep_locked;
1087
1088 /* folio_update_gen() tried to promote this page? */
1089 if (lru_gen_enabled() && !ignore_references &&
1090 folio_mapped(folio) && folio_test_referenced(folio))
1091 goto keep_locked;
1092
1093 /*
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.
1097 */
1098 folio_check_dirty_writeback(folio, &dirty, &writeback);
1099 if (dirty || writeback)
1100 stat->nr_dirty += nr_pages;
1101
1102 if (dirty && !writeback)
1103 stat->nr_unqueued_dirty += nr_pages;
1104
1105 /*
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.
1110 */
1111 if (writeback && folio_test_reclaim(folio))
1112 stat->nr_congested += nr_pages;
1113
1114 /*
1115 * If a folio at the tail of the LRU is under writeback, there
1116 * are three cases to consider.
1117 *
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.
1129 *
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.
1135 *
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.
1142 *
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.
1148 *
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.
1157 */
1158 if (folio_test_writeback(folio)) {
1159 /* Case 1 above */
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;
1165
1166 /* Case 2 above */
1167 } else if (writeback_throttling_sane(sc) ||
1168 !folio_test_reclaim(folio) ||
1169 !may_enter_fs(folio, sc->gfp_mask)) {
1170 /*
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.
1183 */
1184 folio_set_reclaim(folio);
1185 stat->nr_writeback += nr_pages;
1186 goto activate_locked;
1187
1188 /* Case 3 above */
1189 } else {
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);
1194 continue;
1195 }
1196 }
1197
1198 if (!ignore_references)
1199 references = folio_check_references(folio, sc);
1200
1201 switch (references) {
1202 case FOLIOREF_ACTIVATE:
1203 goto activate_locked;
1204 case FOLIOREF_KEEP:
1205 stat->nr_ref_keep += nr_pages;
1206 goto keep_locked;
1207 case FOLIOREF_RECLAIM:
1208 case FOLIOREF_RECLAIM_CLEAN:
1209 ; /* try to reclaim the folio below */
1210 }
1211
1212 /*
1213 * Before reclaiming the folio, try to relocate
1214 * its contents to another node.
1215 */
1216 if (do_demote_pass &&
1217 (thp_migration_supported() || !folio_test_large(folio))) {
1218 list_add(&folio->lru, &demote_folios);
1219 folio_unlock(folio);
1220 continue;
1221 }
1222
1223 /*
1224 * Anonymous process memory has backing store?
1225 * Try to allocate it some swap space here.
1226 * Lazyfree folio could be freed directly
1227 */
1228 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1229 if (!folio_test_swapcache(folio)) {
1230 if (!(sc->gfp_mask & __GFP_IO))
1231 goto keep_locked;
1232 if (folio_maybe_dma_pinned(folio))
1233 goto keep_locked;
1234 if (folio_test_large(folio)) {
1235 /* cannot split folio, skip it */
1236 if (!can_split_folio(folio, 1, NULL))
1237 goto activate_locked;
1238 /*
1239 * Split partially mapped folios right away.
1240 * We can free the unmapped pages without IO.
1241 */
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;
1246 }
1247 if (!add_to_swap(folio)) {
1248 int __maybe_unused order = folio_order(folio);
1249
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);
1260 }
1261 count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
1262 #endif
1263 if (!add_to_swap(folio))
1264 goto activate_locked_split;
1265 }
1266 }
1267 }
1268
1269 /*
1270 * If the folio was split above, the tail pages will make
1271 * their own pass through this function and be accounted
1272 * then.
1273 */
1274 if ((nr_pages > 1) && !folio_test_large(folio)) {
1275 sc->nr_scanned -= (nr_pages - 1);
1276 nr_pages = 1;
1277 }
1278
1279 /*
1280 * The folio is mapped into the page tables of one or more
1281 * processes. Try to unmap it here.
1282 */
1283 if (folio_mapped(folio)) {
1284 enum ttu_flags flags = TTU_BATCH_FLUSH;
1285 bool was_swapbacked = folio_test_swapbacked(folio);
1286
1287 if (folio_test_pmd_mappable(folio))
1288 flags |= TTU_SPLIT_HUGE_PMD;
1289 /*
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.
1300 */
1301 if (folio_test_large(folio))
1302 flags |= TTU_SYNC;
1303
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;
1311 }
1312 }
1313
1314 /*
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.
1320 */
1321 if (folio_maybe_dma_pinned(folio))
1322 goto activate_locked;
1323
1324 mapping = folio_mapping(folio);
1325 if (folio_test_dirty(folio)) {
1326 /*
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
1335 * flag set).
1336 */
1337 if (folio_is_file_lru(folio) &&
1338 (!current_is_kswapd() ||
1339 !folio_test_reclaim(folio) ||
1340 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1341 /*
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
1346 */
1347 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1348 nr_pages);
1349 folio_set_reclaim(folio);
1350
1351 goto activate_locked;
1352 }
1353
1354 if (references == FOLIOREF_RECLAIM_CLEAN)
1355 goto keep_locked;
1356 if (!may_enter_fs(folio, sc->gfp_mask))
1357 goto keep_locked;
1358 if (!sc->may_writepage)
1359 goto keep_locked;
1360
1361 /*
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.
1365 */
1366 try_to_unmap_flush_dirty();
1367 switch (pageout(folio, mapping, &plug, folio_list)) {
1368 case PAGE_KEEP:
1369 goto keep_locked;
1370 case PAGE_ACTIVATE:
1371 /*
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.
1375 */
1376 if (nr_pages > 1 && !folio_test_large(folio)) {
1377 sc->nr_scanned -= (nr_pages - 1);
1378 nr_pages = 1;
1379 }
1380 goto activate_locked;
1381 case PAGE_SUCCESS:
1382 if (nr_pages > 1 && !folio_test_large(folio)) {
1383 sc->nr_scanned -= (nr_pages - 1);
1384 nr_pages = 1;
1385 }
1386 stat->nr_pageout += nr_pages;
1387
1388 if (folio_test_writeback(folio))
1389 goto keep;
1390 if (folio_test_dirty(folio))
1391 goto keep;
1392
1393 /*
1394 * A synchronous write - probably a ramdisk. Go
1395 * ahead and try to reclaim the folio.
1396 */
1397 if (!folio_trylock(folio))
1398 goto keep;
1399 if (folio_test_dirty(folio) ||
1400 folio_test_writeback(folio))
1401 goto keep_locked;
1402 mapping = folio_mapping(folio);
1403 fallthrough;
1404 case PAGE_CLEAN:
1405 ; /* try to free the folio below */
1406 }
1407 }
1408
1409 /*
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.
1413 *
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.
1423 *
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.
1431 */
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))
1438 goto free_it;
1439 else {
1440 /*
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).
1446 */
1447 nr_reclaimed += nr_pages;
1448 continue;
1449 }
1450 }
1451 }
1452
1453 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1454 /* follow __remove_mapping for reference */
1455 if (!folio_ref_freeze(folio, 1))
1456 goto keep_locked;
1457 /*
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.
1464 */
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))
1469 goto keep_locked;
1470
1471 folio_unlock(folio);
1472 free_it:
1473 /*
1474 * Folio may get swapped out as a whole, need to account
1475 * all pages in it.
1476 */
1477 nr_reclaimed += nr_pages;
1478
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);
1484 }
1485 continue;
1486
1487 activate_locked_split:
1488 /*
1489 * The tail pages that are failed to add into swap cache
1490 * reach here. Fixup nr_scanned and nr_pages.
1491 */
1492 if (nr_pages > 1) {
1493 sc->nr_scanned -= (nr_pages - 1);
1494 nr_pages = 1;
1495 }
1496 activate_locked:
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);
1507 }
1508 keep_locked:
1509 folio_unlock(folio);
1510 keep:
1511 list_add(&folio->lru, &ret_folios);
1512 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
1513 folio_test_unevictable(folio), folio);
1514 }
1515 /* 'folio_list' is always empty here */
1516
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);
1524
1525 /*
1526 * goto retry to reclaim the undemoted folios in folio_list if
1527 * desired.
1528 *
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
1532 * top tier nodes.
1533 *
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.
1540 */
1541 if (!sc->proactive) {
1542 do_demote_pass = false;
1543 goto retry;
1544 }
1545 }
1546
1547 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1548
1549 mem_cgroup_uncharge_folios(&free_folios);
1550 try_to_unmap_flush();
1551 free_unref_folios(&free_folios);
1552
1553 list_splice(&ret_folios, folio_list);
1554 count_vm_events(PGACTIVATE, pgactivate);
1555
1556 if (plug)
1557 swap_write_unplug(plug);
1558 return nr_reclaimed;
1559 }
1560
reclaim_clean_pages_from_list(struct zone * zone,struct list_head * folio_list)1561 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1562 struct list_head *folio_list)
1563 {
1564 struct scan_control sc = {
1565 .gfp_mask = GFP_KERNEL,
1566 .may_unmap = 1,
1567 };
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;
1573
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);
1580 }
1581 }
1582
1583 /*
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.
1588 */
1589 noreclaim_flag = memalloc_noreclaim_save();
1590 nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
1591 &stat, true);
1592 memalloc_noreclaim_restore(noreclaim_flag);
1593
1594 list_splice(&clean_folios, folio_list);
1595 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1596 -(long)nr_reclaimed);
1597 /*
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.
1602 */
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;
1608 }
1609
1610 /*
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.
1613 */
update_lru_sizes(struct lruvec * lruvec,enum lru_list lru,unsigned long * nr_zone_taken)1614 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1615 enum lru_list lru, unsigned long *nr_zone_taken)
1616 {
1617 int zid;
1618
1619 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1620 if (!nr_zone_taken[zid])
1621 continue;
1622
1623 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1624 }
1625
1626 }
1627
1628 /*
1629 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1630 *
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.
1634 *
1635 * For pagecache intensive workloads, this function is the hottest
1636 * spot in the kernel (apart from copy_*_user functions).
1637 *
1638 * Lru_lock must be held before calling this function.
1639 *
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
1646 *
1647 * returns how many pages were moved onto *@dst.
1648 */
isolate_lru_folios(unsigned long nr_to_scan,struct lruvec * lruvec,struct list_head * dst,unsigned long * nr_scanned,struct scan_control * sc,enum lru_list lru)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,
1652 enum lru_list lru)
1653 {
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);
1661
1662 total_scan = 0;
1663 scan = 0;
1664 while (scan < nr_to_scan && !list_empty(src)) {
1665 struct list_head *move_to = src;
1666 struct folio *folio;
1667
1668 folio = lru_to_folio(src);
1669 prefetchw_prev_lru_folio(folio, src, flags);
1670
1671 nr_pages = folio_nr_pages(folio);
1672 total_scan += nr_pages;
1673
1674 if (folio_zonenum(folio) > sc->reclaim_idx) {
1675 nr_skipped[folio_zonenum(folio)] += nr_pages;
1676 move_to = &folios_skipped;
1677 goto move;
1678 }
1679
1680 /*
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.
1686 */
1687 scan += nr_pages;
1688
1689 if (!folio_test_lru(folio))
1690 goto move;
1691 if (!sc->may_unmap && folio_mapped(folio))
1692 goto move;
1693
1694 /*
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.
1698 */
1699 if (unlikely(!folio_try_get(folio)))
1700 goto move;
1701
1702 if (!folio_test_clear_lru(folio)) {
1703 /* Another thread is already isolating this folio */
1704 folio_put(folio);
1705 goto move;
1706 }
1707
1708 nr_taken += nr_pages;
1709 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
1710 move_to = dst;
1711 move:
1712 list_move(&folio->lru, move_to);
1713 }
1714
1715 /*
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
1720 * of cpu cycles.
1721 */
1722 if (!list_empty(&folios_skipped)) {
1723 int zid;
1724
1725 list_splice(&folios_skipped, src);
1726 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1727 if (!nr_skipped[zid])
1728 continue;
1729
1730 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1731 skipped += nr_skipped[zid];
1732 }
1733 }
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);
1738 return nr_taken;
1739 }
1740
1741 /**
1742 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
1743 * @folio: Folio to isolate from its LRU list.
1744 *
1745 * Isolate a @folio from an LRU list and adjust the vmstat statistic
1746 * corresponding to whatever LRU list the folio was on.
1747 *
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.
1752 *
1753 * Context:
1754 *
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.
1760 *
1761 * Return: true if the folio was removed from an LRU list.
1762 * false if the folio was not on an LRU list.
1763 */
folio_isolate_lru(struct folio * folio)1764 bool folio_isolate_lru(struct folio *folio)
1765 {
1766 bool ret = false;
1767
1768 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
1769
1770 if (folio_test_clear_lru(folio)) {
1771 struct lruvec *lruvec;
1772
1773 folio_get(folio);
1774 lruvec = folio_lruvec_lock_irq(folio);
1775 lruvec_del_folio(lruvec, folio);
1776 unlock_page_lruvec_irq(lruvec);
1777 ret = true;
1778 }
1779
1780 return ret;
1781 }
1782
1783 /*
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.
1789 */
too_many_isolated(struct pglist_data * pgdat,int file,struct scan_control * sc)1790 static bool too_many_isolated(struct pglist_data *pgdat, int file,
1791 struct scan_control *sc)
1792 {
1793 unsigned long inactive, isolated;
1794 bool too_many;
1795
1796 if (current_is_kswapd())
1797 return false;
1798
1799 if (!writeback_throttling_sane(sc))
1800 return false;
1801
1802 if (file) {
1803 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1804 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1805 } else {
1806 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1807 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
1808 }
1809
1810 /*
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
1813 * deadlock.
1814 */
1815 if (gfp_has_io_fs(sc->gfp_mask))
1816 inactive >>= 3;
1817
1818 too_many = isolated > inactive;
1819
1820 /* Wake up tasks throttled due to too_many_isolated. */
1821 if (!too_many)
1822 wake_throttle_isolated(pgdat);
1823
1824 return too_many;
1825 }
1826
1827 /*
1828 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
1829 *
1830 * Returns the number of pages moved to the given lruvec.
1831 */
move_folios_to_lru(struct lruvec * lruvec,struct list_head * list)1832 static unsigned int move_folios_to_lru(struct lruvec *lruvec,
1833 struct list_head *list)
1834 {
1835 int nr_pages, nr_moved = 0;
1836 struct folio_batch free_folios;
1837
1838 folio_batch_init(&free_folios);
1839 while (!list_empty(list)) {
1840 struct folio *folio = lru_to_folio(list);
1841
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);
1848 continue;
1849 }
1850
1851 /*
1852 * The folio_set_lru needs to be kept here for list integrity.
1853 * Otherwise:
1854 * #0 move_folios_to_lru #1 release_pages
1855 * if (!folio_put_testzero())
1856 * if (folio_put_testzero())
1857 * !lru //skip lru_lock
1858 * folio_set_lru()
1859 * list_add(&folio->lru,)
1860 * list_add(&folio->lru,)
1861 */
1862 folio_set_lru(folio);
1863
1864 if (unlikely(folio_put_testzero(folio))) {
1865 __folio_clear_lru_flags(folio);
1866
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);
1873 }
1874
1875 continue;
1876 }
1877
1878 /*
1879 * All pages were isolated from the same lruvec (and isolation
1880 * inhibits memcg migration).
1881 */
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);
1888 }
1889
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);
1895 }
1896
1897 return nr_moved;
1898 }
1899
1900 /*
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.
1904 */
current_may_throttle(void)1905 static int current_may_throttle(void)
1906 {
1907 return !(current->flags & PF_LOCAL_THROTTLE);
1908 }
1909
1910 /*
1911 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1912 * of reclaimed pages
1913 */
shrink_inactive_list(unsigned long nr_to_scan,struct lruvec * lruvec,struct scan_control * sc,enum lru_list lru)1914 static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
1915 struct lruvec *lruvec, struct scan_control *sc,
1916 enum lru_list lru)
1917 {
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;
1927
1928 while (unlikely(too_many_isolated(pgdat, file, sc))) {
1929 if (stalled)
1930 return 0;
1931
1932 /* wait a bit for the reclaimer. */
1933 stalled = true;
1934 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
1935
1936 /* We are about to die and free our memory. Return now. */
1937 if (fatal_signal_pending(current))
1938 return SWAP_CLUSTER_MAX;
1939 }
1940
1941 lru_add_drain();
1942
1943 spin_lock_irq(&lruvec->lru_lock);
1944
1945 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
1946 &nr_scanned, sc, lru);
1947
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);
1954
1955 spin_unlock_irq(&lruvec->lru_lock);
1956
1957 if (nr_taken == 0)
1958 return 0;
1959
1960 nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
1961
1962 spin_lock_irq(&lruvec->lru_lock);
1963 move_folios_to_lru(lruvec, &folio_list);
1964
1965 __mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(),
1966 stat.nr_demoted);
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);
1974
1975 lru_note_cost(lruvec, file, stat.nr_pageout, nr_scanned - nr_reclaimed);
1976
1977 /*
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.
1987 */
1988 if (stat.nr_unqueued_dirty == nr_taken) {
1989 wakeup_flusher_threads(WB_REASON_VMSCAN);
1990 /*
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()).
1994 *
1995 * Flusher may not be able to issue writeback quickly
1996 * enough for cgroupv1 writeback throttling to work
1997 * on a large system.
1998 */
1999 if (!writeback_throttling_sane(sc))
2000 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
2001 }
2002
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;
2009 if (file)
2010 sc->nr.file_taken += nr_taken;
2011
2012 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2013 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2014 return nr_reclaimed;
2015 }
2016
2017 /*
2018 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2019 *
2020 * We move them the other way if the folio is referenced by one or more
2021 * processes.
2022 *
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.
2030 *
2031 * The downside is that we have to touch folio->_refcount against each folio.
2032 * But we had to alter folio->flags anyway.
2033 */
shrink_active_list(unsigned long nr_to_scan,struct lruvec * lruvec,struct scan_control * sc,enum lru_list lru)2034 static void shrink_active_list(unsigned long nr_to_scan,
2035 struct lruvec *lruvec,
2036 struct scan_control *sc,
2037 enum lru_list lru)
2038 {
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);
2049
2050 lru_add_drain();
2051
2052 spin_lock_irq(&lruvec->lru_lock);
2053
2054 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
2055 &nr_scanned, sc, lru);
2056
2057 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2058
2059 if (!cgroup_reclaim(sc))
2060 __count_vm_events(PGREFILL, nr_scanned);
2061 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2062
2063 spin_unlock_irq(&lruvec->lru_lock);
2064
2065 while (!list_empty(&l_hold)) {
2066 struct folio *folio;
2067
2068 cond_resched();
2069 folio = lru_to_folio(&l_hold);
2070 list_del(&folio->lru);
2071
2072 if (unlikely(!folio_evictable(folio))) {
2073 folio_putback_lru(folio);
2074 continue;
2075 }
2076
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);
2082 }
2083 }
2084
2085 /* Referenced or rmap lock contention: rotate */
2086 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2087 &vm_flags) != 0) {
2088 /*
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.
2096 */
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);
2100 continue;
2101 }
2102 }
2103
2104 folio_clear_active(folio); /* we are de-activating */
2105 folio_set_workingset(folio);
2106 list_add(&folio->lru, &l_inactive);
2107 }
2108
2109 /*
2110 * Move folios back to the lru list.
2111 */
2112 spin_lock_irq(&lruvec->lru_lock);
2113
2114 nr_activate = move_folios_to_lru(lruvec, &l_active);
2115 nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
2116
2117 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2118 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2119
2120 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2121 spin_unlock_irq(&lruvec->lru_lock);
2122
2123 if (nr_rotated)
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);
2127 }
2128
reclaim_folio_list(struct list_head * folio_list,struct pglist_data * pgdat)2129 static unsigned int reclaim_folio_list(struct list_head *folio_list,
2130 struct pglist_data *pgdat)
2131 {
2132 struct reclaim_stat dummy_stat;
2133 unsigned int nr_reclaimed;
2134 struct folio *folio;
2135 struct scan_control sc = {
2136 .gfp_mask = GFP_KERNEL,
2137 .may_writepage = 1,
2138 .may_unmap = 1,
2139 .may_swap = 1,
2140 .no_demotion = 1,
2141 };
2142
2143 nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_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);
2148 }
2149
2150 return nr_reclaimed;
2151 }
2152
reclaim_pages(struct list_head * folio_list)2153 unsigned long reclaim_pages(struct list_head *folio_list)
2154 {
2155 int nid;
2156 unsigned int nr_reclaimed = 0;
2157 LIST_HEAD(node_folio_list);
2158 unsigned int noreclaim_flag;
2159
2160 if (list_empty(folio_list))
2161 return nr_reclaimed;
2162
2163 noreclaim_flag = memalloc_noreclaim_save();
2164
2165 nid = folio_nid(lru_to_folio(folio_list));
2166 do {
2167 struct folio *folio = lru_to_folio(folio_list);
2168
2169 if (nid == folio_nid(folio)) {
2170 folio_clear_active(folio);
2171 list_move(&folio->lru, &node_folio_list);
2172 continue;
2173 }
2174
2175 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2176 nid = folio_nid(lru_to_folio(folio_list));
2177 } while (!list_empty(folio_list));
2178
2179 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2180
2181 memalloc_noreclaim_restore(noreclaim_flag);
2182
2183 return nr_reclaimed;
2184 }
2185
shrink_list(enum lru_list lru,unsigned long nr_to_scan,struct lruvec * lruvec,struct scan_control * sc)2186 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2187 struct lruvec *lruvec, struct scan_control *sc)
2188 {
2189 if (is_active_lru(lru)) {
2190 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2191 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2192 else
2193 sc->skipped_deactivate = 1;
2194 return 0;
2195 }
2196
2197 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2198 }
2199
2200 /*
2201 * The inactive anon list should be small enough that the VM never has
2202 * to do too much work.
2203 *
2204 * The inactive file list should be small enough to leave most memory
2205 * to the established workingset on the scan-resistant active list,
2206 * but large enough to avoid thrashing the aggregate readahead window.
2207 *
2208 * Both inactive lists should also be large enough that each inactive
2209 * folio has a chance to be referenced again before it is reclaimed.
2210 *
2211 * If that fails and refaulting is observed, the inactive list grows.
2212 *
2213 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2214 * on this LRU, maintained by the pageout code. An inactive_ratio
2215 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2216 *
2217 * total target max
2218 * memory ratio inactive
2219 * -------------------------------------
2220 * 10MB 1 5MB
2221 * 100MB 1 50MB
2222 * 1GB 3 250MB
2223 * 10GB 10 0.9GB
2224 * 100GB 31 3GB
2225 * 1TB 101 10GB
2226 * 10TB 320 32GB
2227 */
inactive_is_low(struct lruvec * lruvec,enum lru_list inactive_lru)2228 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2229 {
2230 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2231 unsigned long inactive, active;
2232 unsigned long inactive_ratio;
2233 unsigned long gb;
2234
2235 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2236 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2237
2238 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2239 if (gb)
2240 inactive_ratio = int_sqrt(10 * gb);
2241 else
2242 inactive_ratio = 1;
2243
2244 return inactive * inactive_ratio < active;
2245 }
2246
2247 enum scan_balance {
2248 SCAN_EQUAL,
2249 SCAN_FRACT,
2250 SCAN_ANON,
2251 SCAN_FILE,
2252 };
2253
prepare_scan_control(pg_data_t * pgdat,struct scan_control * sc)2254 static void prepare_scan_control(pg_data_t *pgdat, struct scan_control *sc)
2255 {
2256 unsigned long file;
2257 struct lruvec *target_lruvec;
2258
2259 if (lru_gen_enabled())
2260 return;
2261
2262 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2263
2264 /*
2265 * Flush the memory cgroup stats in rate-limited way as we don't need
2266 * most accurate stats here. We may switch to regular stats flushing
2267 * in the future once it is cheap enough.
2268 */
2269 mem_cgroup_flush_stats_ratelimited(sc->target_mem_cgroup);
2270
2271 /*
2272 * Determine the scan balance between anon and file LRUs.
2273 */
2274 spin_lock_irq(&target_lruvec->lru_lock);
2275 sc->anon_cost = target_lruvec->anon_cost;
2276 sc->file_cost = target_lruvec->file_cost;
2277 spin_unlock_irq(&target_lruvec->lru_lock);
2278
2279 /*
2280 * Target desirable inactive:active list ratios for the anon
2281 * and file LRU lists.
2282 */
2283 if (!sc->force_deactivate) {
2284 unsigned long refaults;
2285
2286 /*
2287 * When refaults are being observed, it means a new
2288 * workingset is being established. Deactivate to get
2289 * rid of any stale active pages quickly.
2290 */
2291 refaults = lruvec_page_state(target_lruvec,
2292 WORKINGSET_ACTIVATE_ANON);
2293 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2294 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2295 sc->may_deactivate |= DEACTIVATE_ANON;
2296 else
2297 sc->may_deactivate &= ~DEACTIVATE_ANON;
2298
2299 refaults = lruvec_page_state(target_lruvec,
2300 WORKINGSET_ACTIVATE_FILE);
2301 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2302 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2303 sc->may_deactivate |= DEACTIVATE_FILE;
2304 else
2305 sc->may_deactivate &= ~DEACTIVATE_FILE;
2306 } else
2307 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2308
2309 /*
2310 * If we have plenty of inactive file pages that aren't
2311 * thrashing, try to reclaim those first before touching
2312 * anonymous pages.
2313 */
2314 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2315 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE) &&
2316 !sc->no_cache_trim_mode)
2317 sc->cache_trim_mode = 1;
2318 else
2319 sc->cache_trim_mode = 0;
2320
2321 /*
2322 * Prevent the reclaimer from falling into the cache trap: as
2323 * cache pages start out inactive, every cache fault will tip
2324 * the scan balance towards the file LRU. And as the file LRU
2325 * shrinks, so does the window for rotation from references.
2326 * This means we have a runaway feedback loop where a tiny
2327 * thrashing file LRU becomes infinitely more attractive than
2328 * anon pages. Try to detect this based on file LRU size.
2329 */
2330 if (!cgroup_reclaim(sc)) {
2331 unsigned long total_high_wmark = 0;
2332 unsigned long free, anon;
2333 int z;
2334
2335 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2336 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2337 node_page_state(pgdat, NR_INACTIVE_FILE);
2338
2339 for (z = 0; z < MAX_NR_ZONES; z++) {
2340 struct zone *zone = &pgdat->node_zones[z];
2341
2342 if (!managed_zone(zone))
2343 continue;
2344
2345 total_high_wmark += high_wmark_pages(zone);
2346 }
2347
2348 /*
2349 * Consider anon: if that's low too, this isn't a
2350 * runaway file reclaim problem, but rather just
2351 * extreme pressure. Reclaim as per usual then.
2352 */
2353 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2354
2355 sc->file_is_tiny =
2356 file + free <= total_high_wmark &&
2357 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2358 anon >> sc->priority;
2359 }
2360 }
2361
2362 /*
2363 * Determine how aggressively the anon and file LRU lists should be
2364 * scanned.
2365 *
2366 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2367 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2368 */
get_scan_count(struct lruvec * lruvec,struct scan_control * sc,unsigned long * nr)2369 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2370 unsigned long *nr)
2371 {
2372 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2373 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2374 unsigned long anon_cost, file_cost, total_cost;
2375 int swappiness = sc_swappiness(sc, memcg);
2376 u64 fraction[ANON_AND_FILE];
2377 u64 denominator = 0; /* gcc */
2378 enum scan_balance scan_balance;
2379 unsigned long ap, fp;
2380 enum lru_list lru;
2381
2382 /* If we have no swap space, do not bother scanning anon folios. */
2383 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2384 scan_balance = SCAN_FILE;
2385 goto out;
2386 }
2387
2388 /*
2389 * Global reclaim will swap to prevent OOM even with no
2390 * swappiness, but memcg users want to use this knob to
2391 * disable swapping for individual groups completely when
2392 * using the memory controller's swap limit feature would be
2393 * too expensive.
2394 */
2395 if (cgroup_reclaim(sc) && !swappiness) {
2396 scan_balance = SCAN_FILE;
2397 goto out;
2398 }
2399
2400 /*
2401 * Do not apply any pressure balancing cleverness when the
2402 * system is close to OOM, scan both anon and file equally
2403 * (unless the swappiness setting disagrees with swapping).
2404 */
2405 if (!sc->priority && swappiness) {
2406 scan_balance = SCAN_EQUAL;
2407 goto out;
2408 }
2409
2410 /*
2411 * If the system is almost out of file pages, force-scan anon.
2412 */
2413 if (sc->file_is_tiny) {
2414 scan_balance = SCAN_ANON;
2415 goto out;
2416 }
2417
2418 /*
2419 * If there is enough inactive page cache, we do not reclaim
2420 * anything from the anonymous working right now.
2421 */
2422 if (sc->cache_trim_mode) {
2423 scan_balance = SCAN_FILE;
2424 goto out;
2425 }
2426
2427 scan_balance = SCAN_FRACT;
2428 /*
2429 * Calculate the pressure balance between anon and file pages.
2430 *
2431 * The amount of pressure we put on each LRU is inversely
2432 * proportional to the cost of reclaiming each list, as
2433 * determined by the share of pages that are refaulting, times
2434 * the relative IO cost of bringing back a swapped out
2435 * anonymous page vs reloading a filesystem page (swappiness).
2436 *
2437 * Although we limit that influence to ensure no list gets
2438 * left behind completely: at least a third of the pressure is
2439 * applied, before swappiness.
2440 *
2441 * With swappiness at 100, anon and file have equal IO cost.
2442 */
2443 total_cost = sc->anon_cost + sc->file_cost;
2444 anon_cost = total_cost + sc->anon_cost;
2445 file_cost = total_cost + sc->file_cost;
2446 total_cost = anon_cost + file_cost;
2447
2448 ap = swappiness * (total_cost + 1);
2449 ap /= anon_cost + 1;
2450
2451 fp = (MAX_SWAPPINESS - swappiness) * (total_cost + 1);
2452 fp /= file_cost + 1;
2453
2454 fraction[0] = ap;
2455 fraction[1] = fp;
2456 denominator = ap + fp;
2457 out:
2458 for_each_evictable_lru(lru) {
2459 bool file = is_file_lru(lru);
2460 unsigned long lruvec_size;
2461 unsigned long low, min;
2462 unsigned long scan;
2463
2464 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2465 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2466 &min, &low);
2467
2468 if (min || low) {
2469 /*
2470 * Scale a cgroup's reclaim pressure by proportioning
2471 * its current usage to its memory.low or memory.min
2472 * setting.
2473 *
2474 * This is important, as otherwise scanning aggression
2475 * becomes extremely binary -- from nothing as we
2476 * approach the memory protection threshold, to totally
2477 * nominal as we exceed it. This results in requiring
2478 * setting extremely liberal protection thresholds. It
2479 * also means we simply get no protection at all if we
2480 * set it too low, which is not ideal.
2481 *
2482 * If there is any protection in place, we reduce scan
2483 * pressure by how much of the total memory used is
2484 * within protection thresholds.
2485 *
2486 * There is one special case: in the first reclaim pass,
2487 * we skip over all groups that are within their low
2488 * protection. If that fails to reclaim enough pages to
2489 * satisfy the reclaim goal, we come back and override
2490 * the best-effort low protection. However, we still
2491 * ideally want to honor how well-behaved groups are in
2492 * that case instead of simply punishing them all
2493 * equally. As such, we reclaim them based on how much
2494 * memory they are using, reducing the scan pressure
2495 * again by how much of the total memory used is under
2496 * hard protection.
2497 */
2498 unsigned long cgroup_size = mem_cgroup_size(memcg);
2499 unsigned long protection;
2500
2501 /* memory.low scaling, make sure we retry before OOM */
2502 if (!sc->memcg_low_reclaim && low > min) {
2503 protection = low;
2504 sc->memcg_low_skipped = 1;
2505 } else {
2506 protection = min;
2507 }
2508
2509 /* Avoid TOCTOU with earlier protection check */
2510 cgroup_size = max(cgroup_size, protection);
2511
2512 scan = lruvec_size - lruvec_size * protection /
2513 (cgroup_size + 1);
2514
2515 /*
2516 * Minimally target SWAP_CLUSTER_MAX pages to keep
2517 * reclaim moving forwards, avoiding decrementing
2518 * sc->priority further than desirable.
2519 */
2520 scan = max(scan, SWAP_CLUSTER_MAX);
2521 } else {
2522 scan = lruvec_size;
2523 }
2524
2525 scan >>= sc->priority;
2526
2527 /*
2528 * If the cgroup's already been deleted, make sure to
2529 * scrape out the remaining cache.
2530 */
2531 if (!scan && !mem_cgroup_online(memcg))
2532 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2533
2534 switch (scan_balance) {
2535 case SCAN_EQUAL:
2536 /* Scan lists relative to size */
2537 break;
2538 case SCAN_FRACT:
2539 /*
2540 * Scan types proportional to swappiness and
2541 * their relative recent reclaim efficiency.
2542 * Make sure we don't miss the last page on
2543 * the offlined memory cgroups because of a
2544 * round-off error.
2545 */
2546 scan = mem_cgroup_online(memcg) ?
2547 div64_u64(scan * fraction[file], denominator) :
2548 DIV64_U64_ROUND_UP(scan * fraction[file],
2549 denominator);
2550 break;
2551 case SCAN_FILE:
2552 case SCAN_ANON:
2553 /* Scan one type exclusively */
2554 if ((scan_balance == SCAN_FILE) != file)
2555 scan = 0;
2556 break;
2557 default:
2558 /* Look ma, no brain */
2559 BUG();
2560 }
2561
2562 nr[lru] = scan;
2563 }
2564 }
2565
2566 /*
2567 * Anonymous LRU management is a waste if there is
2568 * ultimately no way to reclaim the memory.
2569 */
can_age_anon_pages(struct pglist_data * pgdat,struct scan_control * sc)2570 static bool can_age_anon_pages(struct pglist_data *pgdat,
2571 struct scan_control *sc)
2572 {
2573 /* Aging the anon LRU is valuable if swap is present: */
2574 if (total_swap_pages > 0)
2575 return true;
2576
2577 /* Also valuable if anon pages can be demoted: */
2578 return can_demote(pgdat->node_id, sc);
2579 }
2580
2581 #ifdef CONFIG_LRU_GEN
2582
2583 #ifdef CONFIG_LRU_GEN_ENABLED
2584 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2585 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2586 #else
2587 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2588 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2589 #endif
2590
should_walk_mmu(void)2591 static bool should_walk_mmu(void)
2592 {
2593 return arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK);
2594 }
2595
should_clear_pmd_young(void)2596 static bool should_clear_pmd_young(void)
2597 {
2598 return arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG);
2599 }
2600
2601 /******************************************************************************
2602 * shorthand helpers
2603 ******************************************************************************/
2604
2605 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2606
2607 #define DEFINE_MAX_SEQ(lruvec) \
2608 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2609
2610 #define DEFINE_MIN_SEQ(lruvec) \
2611 unsigned long min_seq[ANON_AND_FILE] = { \
2612 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2613 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2614 }
2615
2616 #define for_each_gen_type_zone(gen, type, zone) \
2617 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2618 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2619 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2620
2621 #define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2622 #define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2623
get_lruvec(struct mem_cgroup * memcg,int nid)2624 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2625 {
2626 struct pglist_data *pgdat = NODE_DATA(nid);
2627
2628 #ifdef CONFIG_MEMCG
2629 if (memcg) {
2630 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2631
2632 /* see the comment in mem_cgroup_lruvec() */
2633 if (!lruvec->pgdat)
2634 lruvec->pgdat = pgdat;
2635
2636 return lruvec;
2637 }
2638 #endif
2639 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2640
2641 return &pgdat->__lruvec;
2642 }
2643
get_swappiness(struct lruvec * lruvec,struct scan_control * sc)2644 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2645 {
2646 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2647 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2648
2649 if (!sc->may_swap)
2650 return 0;
2651
2652 if (!can_demote(pgdat->node_id, sc) &&
2653 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2654 return 0;
2655
2656 return sc_swappiness(sc, memcg);
2657 }
2658
get_nr_gens(struct lruvec * lruvec,int type)2659 static int get_nr_gens(struct lruvec *lruvec, int type)
2660 {
2661 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2662 }
2663
seq_is_valid(struct lruvec * lruvec)2664 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2665 {
2666 /* see the comment on lru_gen_folio */
2667 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2668 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2669 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2670 }
2671
2672 /******************************************************************************
2673 * Bloom filters
2674 ******************************************************************************/
2675
2676 /*
2677 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
2678 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
2679 * bits in a bitmap, k is the number of hash functions and n is the number of
2680 * inserted items.
2681 *
2682 * Page table walkers use one of the two filters to reduce their search space.
2683 * To get rid of non-leaf entries that no longer have enough leaf entries, the
2684 * aging uses the double-buffering technique to flip to the other filter each
2685 * time it produces a new generation. For non-leaf entries that have enough
2686 * leaf entries, the aging carries them over to the next generation in
2687 * walk_pmd_range(); the eviction also report them when walking the rmap
2688 * in lru_gen_look_around().
2689 *
2690 * For future optimizations:
2691 * 1. It's not necessary to keep both filters all the time. The spare one can be
2692 * freed after the RCU grace period and reallocated if needed again.
2693 * 2. And when reallocating, it's worth scaling its size according to the number
2694 * of inserted entries in the other filter, to reduce the memory overhead on
2695 * small systems and false positives on large systems.
2696 * 3. Jenkins' hash function is an alternative to Knuth's.
2697 */
2698 #define BLOOM_FILTER_SHIFT 15
2699
filter_gen_from_seq(unsigned long seq)2700 static inline int filter_gen_from_seq(unsigned long seq)
2701 {
2702 return seq % NR_BLOOM_FILTERS;
2703 }
2704
get_item_key(void * item,int * key)2705 static void get_item_key(void *item, int *key)
2706 {
2707 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
2708
2709 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
2710
2711 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
2712 key[1] = hash >> BLOOM_FILTER_SHIFT;
2713 }
2714
test_bloom_filter(struct lru_gen_mm_state * mm_state,unsigned long seq,void * item)2715 static bool test_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq,
2716 void *item)
2717 {
2718 int key[2];
2719 unsigned long *filter;
2720 int gen = filter_gen_from_seq(seq);
2721
2722 filter = READ_ONCE(mm_state->filters[gen]);
2723 if (!filter)
2724 return true;
2725
2726 get_item_key(item, key);
2727
2728 return test_bit(key[0], filter) && test_bit(key[1], filter);
2729 }
2730
update_bloom_filter(struct lru_gen_mm_state * mm_state,unsigned long seq,void * item)2731 static void update_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq,
2732 void *item)
2733 {
2734 int key[2];
2735 unsigned long *filter;
2736 int gen = filter_gen_from_seq(seq);
2737
2738 filter = READ_ONCE(mm_state->filters[gen]);
2739 if (!filter)
2740 return;
2741
2742 get_item_key(item, key);
2743
2744 if (!test_bit(key[0], filter))
2745 set_bit(key[0], filter);
2746 if (!test_bit(key[1], filter))
2747 set_bit(key[1], filter);
2748 }
2749
reset_bloom_filter(struct lru_gen_mm_state * mm_state,unsigned long seq)2750 static void reset_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq)
2751 {
2752 unsigned long *filter;
2753 int gen = filter_gen_from_seq(seq);
2754
2755 filter = mm_state->filters[gen];
2756 if (filter) {
2757 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
2758 return;
2759 }
2760
2761 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
2762 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
2763 WRITE_ONCE(mm_state->filters[gen], filter);
2764 }
2765
2766 /******************************************************************************
2767 * mm_struct list
2768 ******************************************************************************/
2769
2770 #ifdef CONFIG_LRU_GEN_WALKS_MMU
2771
get_mm_list(struct mem_cgroup * memcg)2772 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2773 {
2774 static struct lru_gen_mm_list mm_list = {
2775 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2776 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2777 };
2778
2779 #ifdef CONFIG_MEMCG
2780 if (memcg)
2781 return &memcg->mm_list;
2782 #endif
2783 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2784
2785 return &mm_list;
2786 }
2787
get_mm_state(struct lruvec * lruvec)2788 static struct lru_gen_mm_state *get_mm_state(struct lruvec *lruvec)
2789 {
2790 return &lruvec->mm_state;
2791 }
2792
get_next_mm(struct lru_gen_mm_walk * walk)2793 static struct mm_struct *get_next_mm(struct lru_gen_mm_walk *walk)
2794 {
2795 int key;
2796 struct mm_struct *mm;
2797 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
2798 struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec);
2799
2800 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
2801 key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
2802
2803 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
2804 return NULL;
2805
2806 clear_bit(key, &mm->lru_gen.bitmap);
2807
2808 return mmget_not_zero(mm) ? mm : NULL;
2809 }
2810
lru_gen_add_mm(struct mm_struct * mm)2811 void lru_gen_add_mm(struct mm_struct *mm)
2812 {
2813 int nid;
2814 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2815 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2816
2817 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2818 #ifdef CONFIG_MEMCG
2819 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2820 mm->lru_gen.memcg = memcg;
2821 #endif
2822 spin_lock(&mm_list->lock);
2823
2824 for_each_node_state(nid, N_MEMORY) {
2825 struct lruvec *lruvec = get_lruvec(memcg, nid);
2826 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2827
2828 /* the first addition since the last iteration */
2829 if (mm_state->tail == &mm_list->fifo)
2830 mm_state->tail = &mm->lru_gen.list;
2831 }
2832
2833 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
2834
2835 spin_unlock(&mm_list->lock);
2836 }
2837
lru_gen_del_mm(struct mm_struct * mm)2838 void lru_gen_del_mm(struct mm_struct *mm)
2839 {
2840 int nid;
2841 struct lru_gen_mm_list *mm_list;
2842 struct mem_cgroup *memcg = NULL;
2843
2844 if (list_empty(&mm->lru_gen.list))
2845 return;
2846
2847 #ifdef CONFIG_MEMCG
2848 memcg = mm->lru_gen.memcg;
2849 #endif
2850 mm_list = get_mm_list(memcg);
2851
2852 spin_lock(&mm_list->lock);
2853
2854 for_each_node(nid) {
2855 struct lruvec *lruvec = get_lruvec(memcg, nid);
2856 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2857
2858 /* where the current iteration continues after */
2859 if (mm_state->head == &mm->lru_gen.list)
2860 mm_state->head = mm_state->head->prev;
2861
2862 /* where the last iteration ended before */
2863 if (mm_state->tail == &mm->lru_gen.list)
2864 mm_state->tail = mm_state->tail->next;
2865 }
2866
2867 list_del_init(&mm->lru_gen.list);
2868
2869 spin_unlock(&mm_list->lock);
2870
2871 #ifdef CONFIG_MEMCG
2872 mem_cgroup_put(mm->lru_gen.memcg);
2873 mm->lru_gen.memcg = NULL;
2874 #endif
2875 }
2876
2877 #ifdef CONFIG_MEMCG
lru_gen_migrate_mm(struct mm_struct * mm)2878 void lru_gen_migrate_mm(struct mm_struct *mm)
2879 {
2880 struct mem_cgroup *memcg;
2881 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
2882
2883 VM_WARN_ON_ONCE(task->mm != mm);
2884 lockdep_assert_held(&task->alloc_lock);
2885
2886 /* for mm_update_next_owner() */
2887 if (mem_cgroup_disabled())
2888 return;
2889
2890 /* migration can happen before addition */
2891 if (!mm->lru_gen.memcg)
2892 return;
2893
2894 rcu_read_lock();
2895 memcg = mem_cgroup_from_task(task);
2896 rcu_read_unlock();
2897 if (memcg == mm->lru_gen.memcg)
2898 return;
2899
2900 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
2901
2902 lru_gen_del_mm(mm);
2903 lru_gen_add_mm(mm);
2904 }
2905 #endif
2906
2907 #else /* !CONFIG_LRU_GEN_WALKS_MMU */
2908
get_mm_list(struct mem_cgroup * memcg)2909 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2910 {
2911 return NULL;
2912 }
2913
get_mm_state(struct lruvec * lruvec)2914 static struct lru_gen_mm_state *get_mm_state(struct lruvec *lruvec)
2915 {
2916 return NULL;
2917 }
2918
get_next_mm(struct lru_gen_mm_walk * walk)2919 static struct mm_struct *get_next_mm(struct lru_gen_mm_walk *walk)
2920 {
2921 return NULL;
2922 }
2923
2924 #endif
2925
reset_mm_stats(struct lru_gen_mm_walk * walk,bool last)2926 static void reset_mm_stats(struct lru_gen_mm_walk *walk, bool last)
2927 {
2928 int i;
2929 int hist;
2930 struct lruvec *lruvec = walk->lruvec;
2931 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2932
2933 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
2934
2935 hist = lru_hist_from_seq(walk->seq);
2936
2937 for (i = 0; i < NR_MM_STATS; i++) {
2938 WRITE_ONCE(mm_state->stats[hist][i],
2939 mm_state->stats[hist][i] + walk->mm_stats[i]);
2940 walk->mm_stats[i] = 0;
2941 }
2942
2943 if (NR_HIST_GENS > 1 && last) {
2944 hist = lru_hist_from_seq(walk->seq + 1);
2945
2946 for (i = 0; i < NR_MM_STATS; i++)
2947 WRITE_ONCE(mm_state->stats[hist][i], 0);
2948 }
2949 }
2950
iterate_mm_list(struct lru_gen_mm_walk * walk,struct mm_struct ** iter)2951 static bool iterate_mm_list(struct lru_gen_mm_walk *walk, struct mm_struct **iter)
2952 {
2953 bool first = false;
2954 bool last = false;
2955 struct mm_struct *mm = NULL;
2956 struct lruvec *lruvec = walk->lruvec;
2957 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2958 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2959 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
2960
2961 /*
2962 * mm_state->seq is incremented after each iteration of mm_list. There
2963 * are three interesting cases for this page table walker:
2964 * 1. It tries to start a new iteration with a stale max_seq: there is
2965 * nothing left to do.
2966 * 2. It started the next iteration: it needs to reset the Bloom filter
2967 * so that a fresh set of PTE tables can be recorded.
2968 * 3. It ended the current iteration: it needs to reset the mm stats
2969 * counters and tell its caller to increment max_seq.
2970 */
2971 spin_lock(&mm_list->lock);
2972
2973 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->seq);
2974
2975 if (walk->seq <= mm_state->seq)
2976 goto done;
2977
2978 if (!mm_state->head)
2979 mm_state->head = &mm_list->fifo;
2980
2981 if (mm_state->head == &mm_list->fifo)
2982 first = true;
2983
2984 do {
2985 mm_state->head = mm_state->head->next;
2986 if (mm_state->head == &mm_list->fifo) {
2987 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
2988 last = true;
2989 break;
2990 }
2991
2992 /* force scan for those added after the last iteration */
2993 if (!mm_state->tail || mm_state->tail == mm_state->head) {
2994 mm_state->tail = mm_state->head->next;
2995 walk->force_scan = true;
2996 }
2997 } while (!(mm = get_next_mm(walk)));
2998 done:
2999 if (*iter || last)
3000 reset_mm_stats(walk, last);
3001
3002 spin_unlock(&mm_list->lock);
3003
3004 if (mm && first)
3005 reset_bloom_filter(mm_state, walk->seq + 1);
3006
3007 if (*iter)
3008 mmput_async(*iter);
3009
3010 *iter = mm;
3011
3012 return last;
3013 }
3014
iterate_mm_list_nowalk(struct lruvec * lruvec,unsigned long seq)3015 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long seq)
3016 {
3017 bool success = false;
3018 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3019 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3020 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
3021
3022 spin_lock(&mm_list->lock);
3023
3024 VM_WARN_ON_ONCE(mm_state->seq + 1 < seq);
3025
3026 if (seq > mm_state->seq) {
3027 mm_state->head = NULL;
3028 mm_state->tail = NULL;
3029 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3030 success = true;
3031 }
3032
3033 spin_unlock(&mm_list->lock);
3034
3035 return success;
3036 }
3037
3038 /******************************************************************************
3039 * PID controller
3040 ******************************************************************************/
3041
3042 /*
3043 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3044 *
3045 * The P term is refaulted/(evicted+protected) from a tier in the generation
3046 * currently being evicted; the I term is the exponential moving average of the
3047 * P term over the generations previously evicted, using the smoothing factor
3048 * 1/2; the D term isn't supported.
3049 *
3050 * The setpoint (SP) is always the first tier of one type; the process variable
3051 * (PV) is either any tier of the other type or any other tier of the same
3052 * type.
3053 *
3054 * The error is the difference between the SP and the PV; the correction is to
3055 * turn off protection when SP>PV or turn on protection when SP<PV.
3056 *
3057 * For future optimizations:
3058 * 1. The D term may discount the other two terms over time so that long-lived
3059 * generations can resist stale information.
3060 */
3061 struct ctrl_pos {
3062 unsigned long refaulted;
3063 unsigned long total;
3064 int gain;
3065 };
3066
read_ctrl_pos(struct lruvec * lruvec,int type,int tier,int gain,struct ctrl_pos * pos)3067 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3068 struct ctrl_pos *pos)
3069 {
3070 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3071 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3072
3073 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3074 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3075 pos->total = lrugen->avg_total[type][tier] +
3076 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3077 if (tier)
3078 pos->total += lrugen->protected[hist][type][tier - 1];
3079 pos->gain = gain;
3080 }
3081
reset_ctrl_pos(struct lruvec * lruvec,int type,bool carryover)3082 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3083 {
3084 int hist, tier;
3085 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3086 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3087 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3088
3089 lockdep_assert_held(&lruvec->lru_lock);
3090
3091 if (!carryover && !clear)
3092 return;
3093
3094 hist = lru_hist_from_seq(seq);
3095
3096 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3097 if (carryover) {
3098 unsigned long sum;
3099
3100 sum = lrugen->avg_refaulted[type][tier] +
3101 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3102 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3103
3104 sum = lrugen->avg_total[type][tier] +
3105 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3106 if (tier)
3107 sum += lrugen->protected[hist][type][tier - 1];
3108 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3109 }
3110
3111 if (clear) {
3112 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3113 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3114 if (tier)
3115 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3116 }
3117 }
3118 }
3119
positive_ctrl_err(struct ctrl_pos * sp,struct ctrl_pos * pv)3120 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3121 {
3122 /*
3123 * Return true if the PV has a limited number of refaults or a lower
3124 * refaulted/total than the SP.
3125 */
3126 return pv->refaulted < MIN_LRU_BATCH ||
3127 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3128 (sp->refaulted + 1) * pv->total * pv->gain;
3129 }
3130
3131 /******************************************************************************
3132 * the aging
3133 ******************************************************************************/
3134
3135 /* promote pages accessed through page tables */
folio_update_gen(struct folio * folio,int gen)3136 static int folio_update_gen(struct folio *folio, int gen)
3137 {
3138 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3139
3140 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3141 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3142
3143 do {
3144 /* lru_gen_del_folio() has isolated this page? */
3145 if (!(old_flags & LRU_GEN_MASK)) {
3146 /* for shrink_folio_list() */
3147 new_flags = old_flags | BIT(PG_referenced);
3148 continue;
3149 }
3150
3151 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3152 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3153 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3154
3155 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3156 }
3157
3158 /* protect pages accessed multiple times through file descriptors */
folio_inc_gen(struct lruvec * lruvec,struct folio * folio,bool reclaiming)3159 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3160 {
3161 int type = folio_is_file_lru(folio);
3162 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3163 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3164 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3165
3166 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3167
3168 do {
3169 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3170 /* folio_update_gen() has promoted this page? */
3171 if (new_gen >= 0 && new_gen != old_gen)
3172 return new_gen;
3173
3174 new_gen = (old_gen + 1) % MAX_NR_GENS;
3175
3176 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3177 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3178 /* for folio_end_writeback() */
3179 if (reclaiming)
3180 new_flags |= BIT(PG_reclaim);
3181 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3182
3183 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3184
3185 return new_gen;
3186 }
3187
update_batch_size(struct lru_gen_mm_walk * walk,struct folio * folio,int old_gen,int new_gen)3188 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3189 int old_gen, int new_gen)
3190 {
3191 int type = folio_is_file_lru(folio);
3192 int zone = folio_zonenum(folio);
3193 int delta = folio_nr_pages(folio);
3194
3195 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3196 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3197
3198 walk->batched++;
3199
3200 walk->nr_pages[old_gen][type][zone] -= delta;
3201 walk->nr_pages[new_gen][type][zone] += delta;
3202 }
3203
reset_batch_size(struct lru_gen_mm_walk * walk)3204 static void reset_batch_size(struct lru_gen_mm_walk *walk)
3205 {
3206 int gen, type, zone;
3207 struct lruvec *lruvec = walk->lruvec;
3208 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3209
3210 walk->batched = 0;
3211
3212 for_each_gen_type_zone(gen, type, zone) {
3213 enum lru_list lru = type * LRU_INACTIVE_FILE;
3214 int delta = walk->nr_pages[gen][type][zone];
3215
3216 if (!delta)
3217 continue;
3218
3219 walk->nr_pages[gen][type][zone] = 0;
3220 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3221 lrugen->nr_pages[gen][type][zone] + delta);
3222
3223 if (lru_gen_is_active(lruvec, gen))
3224 lru += LRU_ACTIVE;
3225 __update_lru_size(lruvec, lru, zone, delta);
3226 }
3227 }
3228
should_skip_vma(unsigned long start,unsigned long end,struct mm_walk * args)3229 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3230 {
3231 struct address_space *mapping;
3232 struct vm_area_struct *vma = args->vma;
3233 struct lru_gen_mm_walk *walk = args->private;
3234
3235 if (!vma_is_accessible(vma))
3236 return true;
3237
3238 if (is_vm_hugetlb_page(vma))
3239 return true;
3240
3241 if (!vma_has_recency(vma))
3242 return true;
3243
3244 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
3245 return true;
3246
3247 if (vma == get_gate_vma(vma->vm_mm))
3248 return true;
3249
3250 if (vma_is_anonymous(vma))
3251 return !walk->can_swap;
3252
3253 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3254 return true;
3255
3256 mapping = vma->vm_file->f_mapping;
3257 if (mapping_unevictable(mapping))
3258 return true;
3259
3260 if (shmem_mapping(mapping))
3261 return !walk->can_swap;
3262
3263 /* to exclude special mappings like dax, etc. */
3264 return !mapping->a_ops->read_folio;
3265 }
3266
3267 /*
3268 * Some userspace memory allocators map many single-page VMAs. Instead of
3269 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3270 * table to reduce zigzags and improve cache performance.
3271 */
get_next_vma(unsigned long mask,unsigned long size,struct mm_walk * args,unsigned long * vm_start,unsigned long * vm_end)3272 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3273 unsigned long *vm_start, unsigned long *vm_end)
3274 {
3275 unsigned long start = round_up(*vm_end, size);
3276 unsigned long end = (start | ~mask) + 1;
3277 VMA_ITERATOR(vmi, args->mm, start);
3278
3279 VM_WARN_ON_ONCE(mask & size);
3280 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3281
3282 for_each_vma(vmi, args->vma) {
3283 if (end && end <= args->vma->vm_start)
3284 return false;
3285
3286 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
3287 continue;
3288
3289 *vm_start = max(start, args->vma->vm_start);
3290 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3291
3292 return true;
3293 }
3294
3295 return false;
3296 }
3297
get_pte_pfn(pte_t pte,struct vm_area_struct * vma,unsigned long addr,struct pglist_data * pgdat)3298 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr,
3299 struct pglist_data *pgdat)
3300 {
3301 unsigned long pfn = pte_pfn(pte);
3302
3303 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3304
3305 if (!pte_present(pte) || is_zero_pfn(pfn))
3306 return -1;
3307
3308 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3309 return -1;
3310
3311 if (!pte_young(pte) && !mm_has_notifiers(vma->vm_mm))
3312 return -1;
3313
3314 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3315 return -1;
3316
3317 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3318 return -1;
3319
3320 return pfn;
3321 }
3322
get_pmd_pfn(pmd_t pmd,struct vm_area_struct * vma,unsigned long addr,struct pglist_data * pgdat)3323 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr,
3324 struct pglist_data *pgdat)
3325 {
3326 unsigned long pfn = pmd_pfn(pmd);
3327
3328 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3329
3330 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3331 return -1;
3332
3333 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3334 return -1;
3335
3336 if (!pmd_young(pmd) && !mm_has_notifiers(vma->vm_mm))
3337 return -1;
3338
3339 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3340 return -1;
3341
3342 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3343 return -1;
3344
3345 return pfn;
3346 }
3347
get_pfn_folio(unsigned long pfn,struct mem_cgroup * memcg,struct pglist_data * pgdat,bool can_swap)3348 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3349 struct pglist_data *pgdat, bool can_swap)
3350 {
3351 struct folio *folio;
3352
3353 folio = pfn_folio(pfn);
3354 if (folio_nid(folio) != pgdat->node_id)
3355 return NULL;
3356
3357 if (folio_memcg_rcu(folio) != memcg)
3358 return NULL;
3359
3360 /* file VMAs can contain anon pages from COW */
3361 if (!folio_is_file_lru(folio) && !can_swap)
3362 return NULL;
3363
3364 return folio;
3365 }
3366
suitable_to_scan(int total,int young)3367 static bool suitable_to_scan(int total, int young)
3368 {
3369 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3370
3371 /* suitable if the average number of young PTEs per cacheline is >=1 */
3372 return young * n >= total;
3373 }
3374
walk_pte_range(pmd_t * pmd,unsigned long start,unsigned long end,struct mm_walk * args)3375 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3376 struct mm_walk *args)
3377 {
3378 int i;
3379 pte_t *pte;
3380 spinlock_t *ptl;
3381 unsigned long addr;
3382 int total = 0;
3383 int young = 0;
3384 struct lru_gen_mm_walk *walk = args->private;
3385 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3386 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3387 DEFINE_MAX_SEQ(walk->lruvec);
3388 int old_gen, new_gen = lru_gen_from_seq(max_seq);
3389
3390 pte = pte_offset_map_nolock(args->mm, pmd, start & PMD_MASK, &ptl);
3391 if (!pte)
3392 return false;
3393 if (!spin_trylock(ptl)) {
3394 pte_unmap(pte);
3395 return false;
3396 }
3397
3398 arch_enter_lazy_mmu_mode();
3399 restart:
3400 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3401 unsigned long pfn;
3402 struct folio *folio;
3403 pte_t ptent = ptep_get(pte + i);
3404
3405 total++;
3406 walk->mm_stats[MM_LEAF_TOTAL]++;
3407
3408 pfn = get_pte_pfn(ptent, args->vma, addr, pgdat);
3409 if (pfn == -1)
3410 continue;
3411
3412 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3413 if (!folio)
3414 continue;
3415
3416 if (!ptep_clear_young_notify(args->vma, addr, pte + i))
3417 continue;
3418
3419 young++;
3420 walk->mm_stats[MM_LEAF_YOUNG]++;
3421
3422 if (pte_dirty(ptent) && !folio_test_dirty(folio) &&
3423 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3424 !folio_test_swapcache(folio)))
3425 folio_mark_dirty(folio);
3426
3427 old_gen = folio_update_gen(folio, new_gen);
3428 if (old_gen >= 0 && old_gen != new_gen)
3429 update_batch_size(walk, folio, old_gen, new_gen);
3430 }
3431
3432 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3433 goto restart;
3434
3435 arch_leave_lazy_mmu_mode();
3436 pte_unmap_unlock(pte, ptl);
3437
3438 return suitable_to_scan(total, young);
3439 }
3440
walk_pmd_range_locked(pud_t * pud,unsigned long addr,struct vm_area_struct * vma,struct mm_walk * args,unsigned long * bitmap,unsigned long * first)3441 static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
3442 struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
3443 {
3444 int i;
3445 pmd_t *pmd;
3446 spinlock_t *ptl;
3447 struct lru_gen_mm_walk *walk = args->private;
3448 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3449 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3450 DEFINE_MAX_SEQ(walk->lruvec);
3451 int old_gen, new_gen = lru_gen_from_seq(max_seq);
3452
3453 VM_WARN_ON_ONCE(pud_leaf(*pud));
3454
3455 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3456 if (*first == -1) {
3457 *first = addr;
3458 bitmap_zero(bitmap, MIN_LRU_BATCH);
3459 return;
3460 }
3461
3462 i = addr == -1 ? 0 : pmd_index(addr) - pmd_index(*first);
3463 if (i && i <= MIN_LRU_BATCH) {
3464 __set_bit(i - 1, bitmap);
3465 return;
3466 }
3467
3468 pmd = pmd_offset(pud, *first);
3469
3470 ptl = pmd_lockptr(args->mm, pmd);
3471 if (!spin_trylock(ptl))
3472 goto done;
3473
3474 arch_enter_lazy_mmu_mode();
3475
3476 do {
3477 unsigned long pfn;
3478 struct folio *folio;
3479
3480 /* don't round down the first address */
3481 addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first;
3482
3483 if (!pmd_present(pmd[i]))
3484 goto next;
3485
3486 if (!pmd_trans_huge(pmd[i])) {
3487 if (!walk->force_scan && should_clear_pmd_young() &&
3488 !mm_has_notifiers(args->mm))
3489 pmdp_test_and_clear_young(vma, addr, pmd + i);
3490 goto next;
3491 }
3492
3493 pfn = get_pmd_pfn(pmd[i], vma, addr, pgdat);
3494 if (pfn == -1)
3495 goto next;
3496
3497 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3498 if (!folio)
3499 goto next;
3500
3501 if (!pmdp_clear_young_notify(vma, addr, pmd + i))
3502 goto next;
3503
3504 walk->mm_stats[MM_LEAF_YOUNG]++;
3505
3506 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
3507 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3508 !folio_test_swapcache(folio)))
3509 folio_mark_dirty(folio);
3510
3511 old_gen = folio_update_gen(folio, new_gen);
3512 if (old_gen >= 0 && old_gen != new_gen)
3513 update_batch_size(walk, folio, old_gen, new_gen);
3514 next:
3515 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3516 } while (i <= MIN_LRU_BATCH);
3517
3518 arch_leave_lazy_mmu_mode();
3519 spin_unlock(ptl);
3520 done:
3521 *first = -1;
3522 }
3523
walk_pmd_range(pud_t * pud,unsigned long start,unsigned long end,struct mm_walk * args)3524 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3525 struct mm_walk *args)
3526 {
3527 int i;
3528 pmd_t *pmd;
3529 unsigned long next;
3530 unsigned long addr;
3531 struct vm_area_struct *vma;
3532 DECLARE_BITMAP(bitmap, MIN_LRU_BATCH);
3533 unsigned long first = -1;
3534 struct lru_gen_mm_walk *walk = args->private;
3535 struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec);
3536
3537 VM_WARN_ON_ONCE(pud_leaf(*pud));
3538
3539 /*
3540 * Finish an entire PMD in two passes: the first only reaches to PTE
3541 * tables to avoid taking the PMD lock; the second, if necessary, takes
3542 * the PMD lock to clear the accessed bit in PMD entries.
3543 */
3544 pmd = pmd_offset(pud, start & PUD_MASK);
3545 restart:
3546 /* walk_pte_range() may call get_next_vma() */
3547 vma = args->vma;
3548 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3549 pmd_t val = pmdp_get_lockless(pmd + i);
3550
3551 next = pmd_addr_end(addr, end);
3552
3553 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3554 walk->mm_stats[MM_LEAF_TOTAL]++;
3555 continue;
3556 }
3557
3558 if (pmd_trans_huge(val)) {
3559 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3560 unsigned long pfn = get_pmd_pfn(val, vma, addr, pgdat);
3561
3562 walk->mm_stats[MM_LEAF_TOTAL]++;
3563
3564 if (pfn != -1)
3565 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
3566 continue;
3567 }
3568
3569 if (!walk->force_scan && should_clear_pmd_young() &&
3570 !mm_has_notifiers(args->mm)) {
3571 if (!pmd_young(val))
3572 continue;
3573
3574 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
3575 }
3576
3577 if (!walk->force_scan && !test_bloom_filter(mm_state, walk->seq, pmd + i))
3578 continue;
3579
3580 walk->mm_stats[MM_NONLEAF_FOUND]++;
3581
3582 if (!walk_pte_range(&val, addr, next, args))
3583 continue;
3584
3585 walk->mm_stats[MM_NONLEAF_ADDED]++;
3586
3587 /* carry over to the next generation */
3588 update_bloom_filter(mm_state, walk->seq + 1, pmd + i);
3589 }
3590
3591 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
3592
3593 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3594 goto restart;
3595 }
3596
walk_pud_range(p4d_t * p4d,unsigned long start,unsigned long end,struct mm_walk * args)3597 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3598 struct mm_walk *args)
3599 {
3600 int i;
3601 pud_t *pud;
3602 unsigned long addr;
3603 unsigned long next;
3604 struct lru_gen_mm_walk *walk = args->private;
3605
3606 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3607
3608 pud = pud_offset(p4d, start & P4D_MASK);
3609 restart:
3610 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3611 pud_t val = READ_ONCE(pud[i]);
3612
3613 next = pud_addr_end(addr, end);
3614
3615 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3616 continue;
3617
3618 walk_pmd_range(&val, addr, next, args);
3619
3620 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3621 end = (addr | ~PUD_MASK) + 1;
3622 goto done;
3623 }
3624 }
3625
3626 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3627 goto restart;
3628
3629 end = round_up(end, P4D_SIZE);
3630 done:
3631 if (!end || !args->vma)
3632 return 1;
3633
3634 walk->next_addr = max(end, args->vma->vm_start);
3635
3636 return -EAGAIN;
3637 }
3638
walk_mm(struct mm_struct * mm,struct lru_gen_mm_walk * walk)3639 static void walk_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3640 {
3641 static const struct mm_walk_ops mm_walk_ops = {
3642 .test_walk = should_skip_vma,
3643 .p4d_entry = walk_pud_range,
3644 .walk_lock = PGWALK_RDLOCK,
3645 };
3646
3647 int err;
3648 struct lruvec *lruvec = walk->lruvec;
3649 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3650
3651 walk->next_addr = FIRST_USER_ADDRESS;
3652
3653 do {
3654 DEFINE_MAX_SEQ(lruvec);
3655
3656 err = -EBUSY;
3657
3658 /* another thread might have called inc_max_seq() */
3659 if (walk->seq != max_seq)
3660 break;
3661
3662 /* folio_update_gen() requires stable folio_memcg() */
3663 if (!mem_cgroup_trylock_pages(memcg))
3664 break;
3665
3666 /* the caller might be holding the lock for write */
3667 if (mmap_read_trylock(mm)) {
3668 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3669
3670 mmap_read_unlock(mm);
3671 }
3672
3673 mem_cgroup_unlock_pages();
3674
3675 if (walk->batched) {
3676 spin_lock_irq(&lruvec->lru_lock);
3677 reset_batch_size(walk);
3678 spin_unlock_irq(&lruvec->lru_lock);
3679 }
3680
3681 cond_resched();
3682 } while (err == -EAGAIN);
3683 }
3684
set_mm_walk(struct pglist_data * pgdat,bool force_alloc)3685 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
3686 {
3687 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3688
3689 if (pgdat && current_is_kswapd()) {
3690 VM_WARN_ON_ONCE(walk);
3691
3692 walk = &pgdat->mm_walk;
3693 } else if (!walk && force_alloc) {
3694 VM_WARN_ON_ONCE(current_is_kswapd());
3695
3696 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3697 }
3698
3699 current->reclaim_state->mm_walk = walk;
3700
3701 return walk;
3702 }
3703
clear_mm_walk(void)3704 static void clear_mm_walk(void)
3705 {
3706 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3707
3708 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
3709 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
3710
3711 current->reclaim_state->mm_walk = NULL;
3712
3713 if (!current_is_kswapd())
3714 kfree(walk);
3715 }
3716
inc_min_seq(struct lruvec * lruvec,int type,bool can_swap)3717 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
3718 {
3719 int zone;
3720 int remaining = MAX_LRU_BATCH;
3721 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3722 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3723
3724 if (type == LRU_GEN_ANON && !can_swap)
3725 goto done;
3726
3727 /* prevent cold/hot inversion if force_scan is true */
3728 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3729 struct list_head *head = &lrugen->folios[old_gen][type][zone];
3730
3731 while (!list_empty(head)) {
3732 struct folio *folio = lru_to_folio(head);
3733
3734 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
3735 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
3736 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
3737 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
3738
3739 new_gen = folio_inc_gen(lruvec, folio, false);
3740 list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
3741
3742 if (!--remaining)
3743 return false;
3744 }
3745 }
3746 done:
3747 reset_ctrl_pos(lruvec, type, true);
3748 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3749
3750 return true;
3751 }
3752
try_to_inc_min_seq(struct lruvec * lruvec,bool can_swap)3753 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3754 {
3755 int gen, type, zone;
3756 bool success = false;
3757 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3758 DEFINE_MIN_SEQ(lruvec);
3759
3760 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3761
3762 /* find the oldest populated generation */
3763 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3764 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3765 gen = lru_gen_from_seq(min_seq[type]);
3766
3767 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3768 if (!list_empty(&lrugen->folios[gen][type][zone]))
3769 goto next;
3770 }
3771
3772 min_seq[type]++;
3773 }
3774 next:
3775 ;
3776 }
3777
3778 /* see the comment on lru_gen_folio */
3779 if (can_swap) {
3780 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3781 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3782 }
3783
3784 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3785 if (min_seq[type] == lrugen->min_seq[type])
3786 continue;
3787
3788 reset_ctrl_pos(lruvec, type, true);
3789 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3790 success = true;
3791 }
3792
3793 return success;
3794 }
3795
inc_max_seq(struct lruvec * lruvec,unsigned long seq,bool can_swap,bool force_scan)3796 static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq,
3797 bool can_swap, bool force_scan)
3798 {
3799 bool success;
3800 int prev, next;
3801 int type, zone;
3802 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3803 restart:
3804 if (seq < READ_ONCE(lrugen->max_seq))
3805 return false;
3806
3807 spin_lock_irq(&lruvec->lru_lock);
3808
3809 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3810
3811 success = seq == lrugen->max_seq;
3812 if (!success)
3813 goto unlock;
3814
3815 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
3816 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3817 continue;
3818
3819 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
3820
3821 if (inc_min_seq(lruvec, type, can_swap))
3822 continue;
3823
3824 spin_unlock_irq(&lruvec->lru_lock);
3825 cond_resched();
3826 goto restart;
3827 }
3828
3829 /*
3830 * Update the active/inactive LRU sizes for compatibility. Both sides of
3831 * the current max_seq need to be covered, since max_seq+1 can overlap
3832 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3833 * overlap, cold/hot inversion happens.
3834 */
3835 prev = lru_gen_from_seq(lrugen->max_seq - 1);
3836 next = lru_gen_from_seq(lrugen->max_seq + 1);
3837
3838 for (type = 0; type < ANON_AND_FILE; type++) {
3839 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3840 enum lru_list lru = type * LRU_INACTIVE_FILE;
3841 long delta = lrugen->nr_pages[prev][type][zone] -
3842 lrugen->nr_pages[next][type][zone];
3843
3844 if (!delta)
3845 continue;
3846
3847 __update_lru_size(lruvec, lru, zone, delta);
3848 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3849 }
3850 }
3851
3852 for (type = 0; type < ANON_AND_FILE; type++)
3853 reset_ctrl_pos(lruvec, type, false);
3854
3855 WRITE_ONCE(lrugen->timestamps[next], jiffies);
3856 /* make sure preceding modifications appear */
3857 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3858 unlock:
3859 spin_unlock_irq(&lruvec->lru_lock);
3860
3861 return success;
3862 }
3863
try_to_inc_max_seq(struct lruvec * lruvec,unsigned long seq,bool can_swap,bool force_scan)3864 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq,
3865 bool can_swap, bool force_scan)
3866 {
3867 bool success;
3868 struct lru_gen_mm_walk *walk;
3869 struct mm_struct *mm = NULL;
3870 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3871 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
3872
3873 VM_WARN_ON_ONCE(seq > READ_ONCE(lrugen->max_seq));
3874
3875 if (!mm_state)
3876 return inc_max_seq(lruvec, seq, can_swap, force_scan);
3877
3878 /* see the comment in iterate_mm_list() */
3879 if (seq <= READ_ONCE(mm_state->seq))
3880 return false;
3881
3882 /*
3883 * If the hardware doesn't automatically set the accessed bit, fallback
3884 * to lru_gen_look_around(), which only clears the accessed bit in a
3885 * handful of PTEs. Spreading the work out over a period of time usually
3886 * is less efficient, but it avoids bursty page faults.
3887 */
3888 if (!should_walk_mmu()) {
3889 success = iterate_mm_list_nowalk(lruvec, seq);
3890 goto done;
3891 }
3892
3893 walk = set_mm_walk(NULL, true);
3894 if (!walk) {
3895 success = iterate_mm_list_nowalk(lruvec, seq);
3896 goto done;
3897 }
3898
3899 walk->lruvec = lruvec;
3900 walk->seq = seq;
3901 walk->can_swap = can_swap;
3902 walk->force_scan = force_scan;
3903
3904 do {
3905 success = iterate_mm_list(walk, &mm);
3906 if (mm)
3907 walk_mm(mm, walk);
3908 } while (mm);
3909 done:
3910 if (success) {
3911 success = inc_max_seq(lruvec, seq, can_swap, force_scan);
3912 WARN_ON_ONCE(!success);
3913 }
3914
3915 return success;
3916 }
3917
3918 /******************************************************************************
3919 * working set protection
3920 ******************************************************************************/
3921
set_initial_priority(struct pglist_data * pgdat,struct scan_control * sc)3922 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
3923 {
3924 int priority;
3925 unsigned long reclaimable;
3926
3927 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
3928 return;
3929 /*
3930 * Determine the initial priority based on
3931 * (total >> priority) * reclaimed_to_scanned_ratio = nr_to_reclaim,
3932 * where reclaimed_to_scanned_ratio = inactive / total.
3933 */
3934 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
3935 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
3936 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
3937
3938 /* round down reclaimable and round up sc->nr_to_reclaim */
3939 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
3940
3941 /*
3942 * The estimation is based on LRU pages only, so cap it to prevent
3943 * overshoots of shrinker objects by large margins.
3944 */
3945 sc->priority = clamp(priority, DEF_PRIORITY / 2, DEF_PRIORITY);
3946 }
3947
lruvec_is_sizable(struct lruvec * lruvec,struct scan_control * sc)3948 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
3949 {
3950 int gen, type, zone;
3951 unsigned long total = 0;
3952 bool can_swap = get_swappiness(lruvec, sc);
3953 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3954 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3955 DEFINE_MAX_SEQ(lruvec);
3956 DEFINE_MIN_SEQ(lruvec);
3957
3958 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3959 unsigned long seq;
3960
3961 for (seq = min_seq[type]; seq <= max_seq; seq++) {
3962 gen = lru_gen_from_seq(seq);
3963
3964 for (zone = 0; zone < MAX_NR_ZONES; zone++)
3965 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
3966 }
3967 }
3968
3969 /* whether the size is big enough to be helpful */
3970 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
3971 }
3972
lruvec_is_reclaimable(struct lruvec * lruvec,struct scan_control * sc,unsigned long min_ttl)3973 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
3974 unsigned long min_ttl)
3975 {
3976 int gen;
3977 unsigned long birth;
3978 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3979 DEFINE_MIN_SEQ(lruvec);
3980
3981 if (mem_cgroup_below_min(NULL, memcg))
3982 return false;
3983
3984 if (!lruvec_is_sizable(lruvec, sc))
3985 return false;
3986
3987 /* see the comment on lru_gen_folio */
3988 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
3989 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
3990
3991 return time_is_before_jiffies(birth + min_ttl);
3992 }
3993
3994 /* to protect the working set of the last N jiffies */
3995 static unsigned long lru_gen_min_ttl __read_mostly;
3996
lru_gen_age_node(struct pglist_data * pgdat,struct scan_control * sc)3997 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3998 {
3999 struct mem_cgroup *memcg;
4000 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4001 bool reclaimable = !min_ttl;
4002
4003 VM_WARN_ON_ONCE(!current_is_kswapd());
4004
4005 set_initial_priority(pgdat, sc);
4006
4007 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4008 do {
4009 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4010
4011 mem_cgroup_calculate_protection(NULL, memcg);
4012
4013 if (!reclaimable)
4014 reclaimable = lruvec_is_reclaimable(lruvec, sc, min_ttl);
4015 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4016
4017 /*
4018 * The main goal is to OOM kill if every generation from all memcgs is
4019 * younger than min_ttl. However, another possibility is all memcgs are
4020 * either too small or below min.
4021 */
4022 if (!reclaimable && mutex_trylock(&oom_lock)) {
4023 struct oom_control oc = {
4024 .gfp_mask = sc->gfp_mask,
4025 };
4026
4027 out_of_memory(&oc);
4028
4029 mutex_unlock(&oom_lock);
4030 }
4031 }
4032
4033 /******************************************************************************
4034 * rmap/PT walk feedback
4035 ******************************************************************************/
4036
4037 /*
4038 * This function exploits spatial locality when shrink_folio_list() walks the
4039 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4040 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4041 * the PTE table to the Bloom filter. This forms a feedback loop between the
4042 * eviction and the aging.
4043 */
lru_gen_look_around(struct page_vma_mapped_walk * pvmw)4044 bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4045 {
4046 int i;
4047 unsigned long start;
4048 unsigned long end;
4049 struct lru_gen_mm_walk *walk;
4050 int young = 1;
4051 pte_t *pte = pvmw->pte;
4052 unsigned long addr = pvmw->address;
4053 struct vm_area_struct *vma = pvmw->vma;
4054 struct folio *folio = pfn_folio(pvmw->pfn);
4055 bool can_swap = !folio_is_file_lru(folio);
4056 struct mem_cgroup *memcg = folio_memcg(folio);
4057 struct pglist_data *pgdat = folio_pgdat(folio);
4058 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4059 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
4060 DEFINE_MAX_SEQ(lruvec);
4061 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4062
4063 lockdep_assert_held(pvmw->ptl);
4064 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4065
4066 if (!ptep_clear_young_notify(vma, addr, pte))
4067 return false;
4068
4069 if (spin_is_contended(pvmw->ptl))
4070 return true;
4071
4072 /* exclude special VMAs containing anon pages from COW */
4073 if (vma->vm_flags & VM_SPECIAL)
4074 return true;
4075
4076 /* avoid taking the LRU lock under the PTL when possible */
4077 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4078
4079 start = max(addr & PMD_MASK, vma->vm_start);
4080 end = min(addr | ~PMD_MASK, vma->vm_end - 1) + 1;
4081
4082 if (end - start == PAGE_SIZE)
4083 return true;
4084
4085 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4086 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4087 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4088 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
4089 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4090 else {
4091 start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
4092 end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
4093 }
4094 }
4095
4096 /* folio_update_gen() requires stable folio_memcg() */
4097 if (!mem_cgroup_trylock_pages(memcg))
4098 return true;
4099
4100 arch_enter_lazy_mmu_mode();
4101
4102 pte -= (addr - start) / PAGE_SIZE;
4103
4104 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4105 unsigned long pfn;
4106 pte_t ptent = ptep_get(pte + i);
4107
4108 pfn = get_pte_pfn(ptent, vma, addr, pgdat);
4109 if (pfn == -1)
4110 continue;
4111
4112 folio = get_pfn_folio(pfn, memcg, pgdat, can_swap);
4113 if (!folio)
4114 continue;
4115
4116 if (!ptep_clear_young_notify(vma, addr, pte + i))
4117 continue;
4118
4119 young++;
4120
4121 if (pte_dirty(ptent) && !folio_test_dirty(folio) &&
4122 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4123 !folio_test_swapcache(folio)))
4124 folio_mark_dirty(folio);
4125
4126 if (walk) {
4127 old_gen = folio_update_gen(folio, new_gen);
4128 if (old_gen >= 0 && old_gen != new_gen)
4129 update_batch_size(walk, folio, old_gen, new_gen);
4130
4131 continue;
4132 }
4133
4134 old_gen = folio_lru_gen(folio);
4135 if (old_gen < 0)
4136 folio_set_referenced(folio);
4137 else if (old_gen != new_gen)
4138 folio_activate(folio);
4139 }
4140
4141 arch_leave_lazy_mmu_mode();
4142 mem_cgroup_unlock_pages();
4143
4144 /* feedback from rmap walkers to page table walkers */
4145 if (mm_state && suitable_to_scan(i, young))
4146 update_bloom_filter(mm_state, max_seq, pvmw->pmd);
4147
4148 return true;
4149 }
4150
4151 /******************************************************************************
4152 * memcg LRU
4153 ******************************************************************************/
4154
4155 /* see the comment on MEMCG_NR_GENS */
4156 enum {
4157 MEMCG_LRU_NOP,
4158 MEMCG_LRU_HEAD,
4159 MEMCG_LRU_TAIL,
4160 MEMCG_LRU_OLD,
4161 MEMCG_LRU_YOUNG,
4162 };
4163
lru_gen_rotate_memcg(struct lruvec * lruvec,int op)4164 static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
4165 {
4166 int seg;
4167 int old, new;
4168 unsigned long flags;
4169 int bin = get_random_u32_below(MEMCG_NR_BINS);
4170 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4171
4172 spin_lock_irqsave(&pgdat->memcg_lru.lock, flags);
4173
4174 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4175
4176 seg = 0;
4177 new = old = lruvec->lrugen.gen;
4178
4179 /* see the comment on MEMCG_NR_GENS */
4180 if (op == MEMCG_LRU_HEAD)
4181 seg = MEMCG_LRU_HEAD;
4182 else if (op == MEMCG_LRU_TAIL)
4183 seg = MEMCG_LRU_TAIL;
4184 else if (op == MEMCG_LRU_OLD)
4185 new = get_memcg_gen(pgdat->memcg_lru.seq);
4186 else if (op == MEMCG_LRU_YOUNG)
4187 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
4188 else
4189 VM_WARN_ON_ONCE(true);
4190
4191 WRITE_ONCE(lruvec->lrugen.seg, seg);
4192 WRITE_ONCE(lruvec->lrugen.gen, new);
4193
4194 hlist_nulls_del_rcu(&lruvec->lrugen.list);
4195
4196 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
4197 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4198 else
4199 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4200
4201 pgdat->memcg_lru.nr_memcgs[old]--;
4202 pgdat->memcg_lru.nr_memcgs[new]++;
4203
4204 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
4205 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4206
4207 spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags);
4208 }
4209
4210 #ifdef CONFIG_MEMCG
4211
lru_gen_online_memcg(struct mem_cgroup * memcg)4212 void lru_gen_online_memcg(struct mem_cgroup *memcg)
4213 {
4214 int gen;
4215 int nid;
4216 int bin = get_random_u32_below(MEMCG_NR_BINS);
4217
4218 for_each_node(nid) {
4219 struct pglist_data *pgdat = NODE_DATA(nid);
4220 struct lruvec *lruvec = get_lruvec(memcg, nid);
4221
4222 spin_lock_irq(&pgdat->memcg_lru.lock);
4223
4224 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
4225
4226 gen = get_memcg_gen(pgdat->memcg_lru.seq);
4227
4228 lruvec->lrugen.gen = gen;
4229
4230 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
4231 pgdat->memcg_lru.nr_memcgs[gen]++;
4232
4233 spin_unlock_irq(&pgdat->memcg_lru.lock);
4234 }
4235 }
4236
lru_gen_offline_memcg(struct mem_cgroup * memcg)4237 void lru_gen_offline_memcg(struct mem_cgroup *memcg)
4238 {
4239 int nid;
4240
4241 for_each_node(nid) {
4242 struct lruvec *lruvec = get_lruvec(memcg, nid);
4243
4244 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
4245 }
4246 }
4247
lru_gen_release_memcg(struct mem_cgroup * memcg)4248 void lru_gen_release_memcg(struct mem_cgroup *memcg)
4249 {
4250 int gen;
4251 int nid;
4252
4253 for_each_node(nid) {
4254 struct pglist_data *pgdat = NODE_DATA(nid);
4255 struct lruvec *lruvec = get_lruvec(memcg, nid);
4256
4257 spin_lock_irq(&pgdat->memcg_lru.lock);
4258
4259 if (hlist_nulls_unhashed(&lruvec->lrugen.list))
4260 goto unlock;
4261
4262 gen = lruvec->lrugen.gen;
4263
4264 hlist_nulls_del_init_rcu(&lruvec->lrugen.list);
4265 pgdat->memcg_lru.nr_memcgs[gen]--;
4266
4267 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
4268 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4269 unlock:
4270 spin_unlock_irq(&pgdat->memcg_lru.lock);
4271 }
4272 }
4273
lru_gen_soft_reclaim(struct mem_cgroup * memcg,int nid)4274 void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
4275 {
4276 struct lruvec *lruvec = get_lruvec(memcg, nid);
4277
4278 /* see the comment on MEMCG_NR_GENS */
4279 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_HEAD)
4280 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
4281 }
4282
4283 #endif /* CONFIG_MEMCG */
4284
4285 /******************************************************************************
4286 * the eviction
4287 ******************************************************************************/
4288
sort_folio(struct lruvec * lruvec,struct folio * folio,struct scan_control * sc,int tier_idx)4289 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc,
4290 int tier_idx)
4291 {
4292 bool success;
4293 int gen = folio_lru_gen(folio);
4294 int type = folio_is_file_lru(folio);
4295 int zone = folio_zonenum(folio);
4296 int delta = folio_nr_pages(folio);
4297 int refs = folio_lru_refs(folio);
4298 int tier = lru_tier_from_refs(refs);
4299 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4300
4301 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4302
4303 /* unevictable */
4304 if (!folio_evictable(folio)) {
4305 success = lru_gen_del_folio(lruvec, folio, true);
4306 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4307 folio_set_unevictable(folio);
4308 lruvec_add_folio(lruvec, folio);
4309 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4310 return true;
4311 }
4312
4313 /* promoted */
4314 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4315 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4316 return true;
4317 }
4318
4319 /* protected */
4320 if (tier > tier_idx || refs == BIT(LRU_REFS_WIDTH)) {
4321 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4322
4323 gen = folio_inc_gen(lruvec, folio, false);
4324 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4325
4326 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4327 lrugen->protected[hist][type][tier - 1] + delta);
4328 return true;
4329 }
4330
4331 /* ineligible */
4332 if (!folio_test_lru(folio) || zone > sc->reclaim_idx) {
4333 gen = folio_inc_gen(lruvec, folio, false);
4334 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4335 return true;
4336 }
4337
4338 /* waiting for writeback */
4339 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4340 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4341 gen = folio_inc_gen(lruvec, folio, true);
4342 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4343 return true;
4344 }
4345
4346 return false;
4347 }
4348
isolate_folio(struct lruvec * lruvec,struct folio * folio,struct scan_control * sc)4349 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4350 {
4351 bool success;
4352
4353 /* swap constrained */
4354 if (!(sc->gfp_mask & __GFP_IO) &&
4355 (folio_test_dirty(folio) ||
4356 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4357 return false;
4358
4359 /* raced with release_pages() */
4360 if (!folio_try_get(folio))
4361 return false;
4362
4363 /* raced with another isolation */
4364 if (!folio_test_clear_lru(folio)) {
4365 folio_put(folio);
4366 return false;
4367 }
4368
4369 /* see the comment on MAX_NR_TIERS */
4370 if (!folio_test_referenced(folio))
4371 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4372
4373 /* for shrink_folio_list() */
4374 folio_clear_reclaim(folio);
4375 folio_clear_referenced(folio);
4376
4377 success = lru_gen_del_folio(lruvec, folio, true);
4378 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4379
4380 return true;
4381 }
4382
scan_folios(struct lruvec * lruvec,struct scan_control * sc,int type,int tier,struct list_head * list)4383 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4384 int type, int tier, struct list_head *list)
4385 {
4386 int i;
4387 int gen;
4388 enum vm_event_item item;
4389 int sorted = 0;
4390 int scanned = 0;
4391 int isolated = 0;
4392 int skipped = 0;
4393 int remaining = MAX_LRU_BATCH;
4394 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4395 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4396
4397 VM_WARN_ON_ONCE(!list_empty(list));
4398
4399 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4400 return 0;
4401
4402 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4403
4404 for (i = MAX_NR_ZONES; i > 0; i--) {
4405 LIST_HEAD(moved);
4406 int skipped_zone = 0;
4407 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
4408 struct list_head *head = &lrugen->folios[gen][type][zone];
4409
4410 while (!list_empty(head)) {
4411 struct folio *folio = lru_to_folio(head);
4412 int delta = folio_nr_pages(folio);
4413
4414 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4415 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4416 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4417 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4418
4419 scanned += delta;
4420
4421 if (sort_folio(lruvec, folio, sc, tier))
4422 sorted += delta;
4423 else if (isolate_folio(lruvec, folio, sc)) {
4424 list_add(&folio->lru, list);
4425 isolated += delta;
4426 } else {
4427 list_move(&folio->lru, &moved);
4428 skipped_zone += delta;
4429 }
4430
4431 if (!--remaining || max(isolated, skipped_zone) >= MIN_LRU_BATCH)
4432 break;
4433 }
4434
4435 if (skipped_zone) {
4436 list_splice(&moved, head);
4437 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped_zone);
4438 skipped += skipped_zone;
4439 }
4440
4441 if (!remaining || isolated >= MIN_LRU_BATCH)
4442 break;
4443 }
4444
4445 item = PGSCAN_KSWAPD + reclaimer_offset();
4446 if (!cgroup_reclaim(sc)) {
4447 __count_vm_events(item, isolated);
4448 __count_vm_events(PGREFILL, sorted);
4449 }
4450 __count_memcg_events(memcg, item, isolated);
4451 __count_memcg_events(memcg, PGREFILL, sorted);
4452 __count_vm_events(PGSCAN_ANON + type, isolated);
4453 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, MAX_LRU_BATCH,
4454 scanned, skipped, isolated,
4455 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
4456
4457 /*
4458 * There might not be eligible folios due to reclaim_idx. Check the
4459 * remaining to prevent livelock if it's not making progress.
4460 */
4461 return isolated || !remaining ? scanned : 0;
4462 }
4463
get_tier_idx(struct lruvec * lruvec,int type)4464 static int get_tier_idx(struct lruvec *lruvec, int type)
4465 {
4466 int tier;
4467 struct ctrl_pos sp, pv;
4468
4469 /*
4470 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4471 * This value is chosen because any other tier would have at least twice
4472 * as many refaults as the first tier.
4473 */
4474 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4475 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4476 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4477 if (!positive_ctrl_err(&sp, &pv))
4478 break;
4479 }
4480
4481 return tier - 1;
4482 }
4483
get_type_to_scan(struct lruvec * lruvec,int swappiness,int * tier_idx)4484 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4485 {
4486 int type, tier;
4487 struct ctrl_pos sp, pv;
4488 int gain[ANON_AND_FILE] = { swappiness, MAX_SWAPPINESS - swappiness };
4489
4490 /*
4491 * Compare the first tier of anon with that of file to determine which
4492 * type to scan. Also need to compare other tiers of the selected type
4493 * with the first tier of the other type to determine the last tier (of
4494 * the selected type) to evict.
4495 */
4496 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4497 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4498 type = positive_ctrl_err(&sp, &pv);
4499
4500 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4501 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4502 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4503 if (!positive_ctrl_err(&sp, &pv))
4504 break;
4505 }
4506
4507 *tier_idx = tier - 1;
4508
4509 return type;
4510 }
4511
isolate_folios(struct lruvec * lruvec,struct scan_control * sc,int swappiness,int * type_scanned,struct list_head * list)4512 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4513 int *type_scanned, struct list_head *list)
4514 {
4515 int i;
4516 int type;
4517 int scanned;
4518 int tier = -1;
4519 DEFINE_MIN_SEQ(lruvec);
4520
4521 /*
4522 * Try to make the obvious choice first, and if anon and file are both
4523 * available from the same generation,
4524 * 1. Interpret swappiness 1 as file first and MAX_SWAPPINESS as anon
4525 * first.
4526 * 2. If !__GFP_IO, file first since clean pagecache is more likely to
4527 * exist than clean swapcache.
4528 */
4529 if (!swappiness)
4530 type = LRU_GEN_FILE;
4531 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4532 type = LRU_GEN_ANON;
4533 else if (swappiness == 1)
4534 type = LRU_GEN_FILE;
4535 else if (swappiness == MAX_SWAPPINESS)
4536 type = LRU_GEN_ANON;
4537 else if (!(sc->gfp_mask & __GFP_IO))
4538 type = LRU_GEN_FILE;
4539 else
4540 type = get_type_to_scan(lruvec, swappiness, &tier);
4541
4542 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4543 if (tier < 0)
4544 tier = get_tier_idx(lruvec, type);
4545
4546 scanned = scan_folios(lruvec, sc, type, tier, list);
4547 if (scanned)
4548 break;
4549
4550 type = !type;
4551 tier = -1;
4552 }
4553
4554 *type_scanned = type;
4555
4556 return scanned;
4557 }
4558
evict_folios(struct lruvec * lruvec,struct scan_control * sc,int swappiness)4559 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
4560 {
4561 int type;
4562 int scanned;
4563 int reclaimed;
4564 LIST_HEAD(list);
4565 LIST_HEAD(clean);
4566 struct folio *folio;
4567 struct folio *next;
4568 enum vm_event_item item;
4569 struct reclaim_stat stat;
4570 struct lru_gen_mm_walk *walk;
4571 bool skip_retry = false;
4572 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4573 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4574
4575 spin_lock_irq(&lruvec->lru_lock);
4576
4577 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
4578
4579 scanned += try_to_inc_min_seq(lruvec, swappiness);
4580
4581 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4582 scanned = 0;
4583
4584 spin_unlock_irq(&lruvec->lru_lock);
4585
4586 if (list_empty(&list))
4587 return scanned;
4588 retry:
4589 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
4590 sc->nr_reclaimed += reclaimed;
4591 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
4592 scanned, reclaimed, &stat, sc->priority,
4593 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
4594
4595 list_for_each_entry_safe_reverse(folio, next, &list, lru) {
4596 if (!folio_evictable(folio)) {
4597 list_del(&folio->lru);
4598 folio_putback_lru(folio);
4599 continue;
4600 }
4601
4602 if (folio_test_reclaim(folio) &&
4603 (folio_test_dirty(folio) || folio_test_writeback(folio))) {
4604 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
4605 if (folio_test_workingset(folio))
4606 folio_set_referenced(folio);
4607 continue;
4608 }
4609
4610 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
4611 folio_mapped(folio) || folio_test_locked(folio) ||
4612 folio_test_dirty(folio) || folio_test_writeback(folio)) {
4613 /* don't add rejected folios to the oldest generation */
4614 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4615 BIT(PG_active));
4616 continue;
4617 }
4618
4619 /* retry folios that may have missed folio_rotate_reclaimable() */
4620 list_move(&folio->lru, &clean);
4621 }
4622
4623 spin_lock_irq(&lruvec->lru_lock);
4624
4625 move_folios_to_lru(lruvec, &list);
4626
4627 walk = current->reclaim_state->mm_walk;
4628 if (walk && walk->batched) {
4629 walk->lruvec = lruvec;
4630 reset_batch_size(walk);
4631 }
4632
4633 item = PGSTEAL_KSWAPD + reclaimer_offset();
4634 if (!cgroup_reclaim(sc))
4635 __count_vm_events(item, reclaimed);
4636 __count_memcg_events(memcg, item, reclaimed);
4637 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4638
4639 spin_unlock_irq(&lruvec->lru_lock);
4640
4641 list_splice_init(&clean, &list);
4642
4643 if (!list_empty(&list)) {
4644 skip_retry = true;
4645 goto retry;
4646 }
4647
4648 return scanned;
4649 }
4650
should_run_aging(struct lruvec * lruvec,unsigned long max_seq,bool can_swap,unsigned long * nr_to_scan)4651 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4652 bool can_swap, unsigned long *nr_to_scan)
4653 {
4654 int gen, type, zone;
4655 unsigned long old = 0;
4656 unsigned long young = 0;
4657 unsigned long total = 0;
4658 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4659 DEFINE_MIN_SEQ(lruvec);
4660
4661 /* whether this lruvec is completely out of cold folios */
4662 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4663 *nr_to_scan = 0;
4664 return true;
4665 }
4666
4667 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4668 unsigned long seq;
4669
4670 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4671 unsigned long size = 0;
4672
4673 gen = lru_gen_from_seq(seq);
4674
4675 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4676 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4677
4678 total += size;
4679 if (seq == max_seq)
4680 young += size;
4681 else if (seq + MIN_NR_GENS == max_seq)
4682 old += size;
4683 }
4684 }
4685
4686 *nr_to_scan = total;
4687
4688 /*
4689 * The aging tries to be lazy to reduce the overhead, while the eviction
4690 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4691 * ideal number of generations is MIN_NR_GENS+1.
4692 */
4693 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4694 return false;
4695
4696 /*
4697 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4698 * of the total number of pages for each generation. A reasonable range
4699 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4700 * aging cares about the upper bound of hot pages, while the eviction
4701 * cares about the lower bound of cold pages.
4702 */
4703 if (young * MIN_NR_GENS > total)
4704 return true;
4705 if (old * (MIN_NR_GENS + 2) < total)
4706 return true;
4707
4708 return false;
4709 }
4710
4711 /*
4712 * For future optimizations:
4713 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4714 * reclaim.
4715 */
get_nr_to_scan(struct lruvec * lruvec,struct scan_control * sc,bool can_swap)4716 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4717 {
4718 bool success;
4719 unsigned long nr_to_scan;
4720 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4721 DEFINE_MAX_SEQ(lruvec);
4722
4723 if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg))
4724 return -1;
4725
4726 success = should_run_aging(lruvec, max_seq, can_swap, &nr_to_scan);
4727
4728 /* try to scrape all its memory if this memcg was deleted */
4729 if (nr_to_scan && !mem_cgroup_online(memcg))
4730 return nr_to_scan;
4731
4732 /* try to get away with not aging at the default priority */
4733 if (!success || sc->priority == DEF_PRIORITY)
4734 return nr_to_scan >> sc->priority;
4735
4736 /* stop scanning this lruvec as it's low on cold folios */
4737 return try_to_inc_max_seq(lruvec, max_seq, can_swap, false) ? -1 : 0;
4738 }
4739
should_abort_scan(struct lruvec * lruvec,struct scan_control * sc)4740 static bool should_abort_scan(struct lruvec *lruvec, struct scan_control *sc)
4741 {
4742 int i;
4743 enum zone_watermarks mark;
4744
4745 /* don't abort memcg reclaim to ensure fairness */
4746 if (!root_reclaim(sc))
4747 return false;
4748
4749 if (sc->nr_reclaimed >= max(sc->nr_to_reclaim, compact_gap(sc->order)))
4750 return true;
4751
4752 /* check the order to exclude compaction-induced reclaim */
4753 if (!current_is_kswapd() || sc->order)
4754 return false;
4755
4756 mark = sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ?
4757 WMARK_PROMO : WMARK_HIGH;
4758
4759 for (i = 0; i <= sc->reclaim_idx; i++) {
4760 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4761 unsigned long size = wmark_pages(zone, mark) + MIN_LRU_BATCH;
4762
4763 if (managed_zone(zone) && !zone_watermark_ok(zone, 0, size, sc->reclaim_idx, 0))
4764 return false;
4765 }
4766
4767 /* kswapd should abort if all eligible zones are safe */
4768 return true;
4769 }
4770
try_to_shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)4771 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4772 {
4773 long nr_to_scan;
4774 unsigned long scanned = 0;
4775 int swappiness = get_swappiness(lruvec, sc);
4776
4777 while (true) {
4778 int delta;
4779
4780 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4781 if (nr_to_scan <= 0)
4782 break;
4783
4784 delta = evict_folios(lruvec, sc, swappiness);
4785 if (!delta)
4786 break;
4787
4788 scanned += delta;
4789 if (scanned >= nr_to_scan)
4790 break;
4791
4792 if (should_abort_scan(lruvec, sc))
4793 break;
4794
4795 cond_resched();
4796 }
4797
4798 /* whether this lruvec should be rotated */
4799 return nr_to_scan < 0;
4800 }
4801
shrink_one(struct lruvec * lruvec,struct scan_control * sc)4802 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4803 {
4804 bool success;
4805 unsigned long scanned = sc->nr_scanned;
4806 unsigned long reclaimed = sc->nr_reclaimed;
4807 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4808 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4809
4810 /* lru_gen_age_node() called mem_cgroup_calculate_protection() */
4811 if (mem_cgroup_below_min(NULL, memcg))
4812 return MEMCG_LRU_YOUNG;
4813
4814 if (mem_cgroup_below_low(NULL, memcg)) {
4815 /* see the comment on MEMCG_NR_GENS */
4816 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL)
4817 return MEMCG_LRU_TAIL;
4818
4819 memcg_memory_event(memcg, MEMCG_LOW);
4820 }
4821
4822 success = try_to_shrink_lruvec(lruvec, sc);
4823
4824 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
4825
4826 if (!sc->proactive)
4827 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
4828 sc->nr_reclaimed - reclaimed);
4829
4830 flush_reclaim_state(sc);
4831
4832 if (success && mem_cgroup_online(memcg))
4833 return MEMCG_LRU_YOUNG;
4834
4835 if (!success && lruvec_is_sizable(lruvec, sc))
4836 return 0;
4837
4838 /* one retry if offlined or too small */
4839 return READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL ?
4840 MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
4841 }
4842
shrink_many(struct pglist_data * pgdat,struct scan_control * sc)4843 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
4844 {
4845 int op;
4846 int gen;
4847 int bin;
4848 int first_bin;
4849 struct lruvec *lruvec;
4850 struct lru_gen_folio *lrugen;
4851 struct mem_cgroup *memcg;
4852 struct hlist_nulls_node *pos;
4853
4854 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
4855 bin = first_bin = get_random_u32_below(MEMCG_NR_BINS);
4856 restart:
4857 op = 0;
4858 memcg = NULL;
4859
4860 rcu_read_lock();
4861
4862 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
4863 if (op) {
4864 lru_gen_rotate_memcg(lruvec, op);
4865 op = 0;
4866 }
4867
4868 mem_cgroup_put(memcg);
4869 memcg = NULL;
4870
4871 if (gen != READ_ONCE(lrugen->gen))
4872 continue;
4873
4874 lruvec = container_of(lrugen, struct lruvec, lrugen);
4875 memcg = lruvec_memcg(lruvec);
4876
4877 if (!mem_cgroup_tryget(memcg)) {
4878 lru_gen_release_memcg(memcg);
4879 memcg = NULL;
4880 continue;
4881 }
4882
4883 rcu_read_unlock();
4884
4885 op = shrink_one(lruvec, sc);
4886
4887 rcu_read_lock();
4888
4889 if (should_abort_scan(lruvec, sc))
4890 break;
4891 }
4892
4893 rcu_read_unlock();
4894
4895 if (op)
4896 lru_gen_rotate_memcg(lruvec, op);
4897
4898 mem_cgroup_put(memcg);
4899
4900 if (!is_a_nulls(pos))
4901 return;
4902
4903 /* restart if raced with lru_gen_rotate_memcg() */
4904 if (gen != get_nulls_value(pos))
4905 goto restart;
4906
4907 /* try the rest of the bins of the current generation */
4908 bin = get_memcg_bin(bin + 1);
4909 if (bin != first_bin)
4910 goto restart;
4911 }
4912
lru_gen_shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)4913 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4914 {
4915 struct blk_plug plug;
4916
4917 VM_WARN_ON_ONCE(root_reclaim(sc));
4918 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
4919
4920 lru_add_drain();
4921
4922 blk_start_plug(&plug);
4923
4924 set_mm_walk(NULL, sc->proactive);
4925
4926 if (try_to_shrink_lruvec(lruvec, sc))
4927 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
4928
4929 clear_mm_walk();
4930
4931 blk_finish_plug(&plug);
4932 }
4933
lru_gen_shrink_node(struct pglist_data * pgdat,struct scan_control * sc)4934 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
4935 {
4936 struct blk_plug plug;
4937 unsigned long reclaimed = sc->nr_reclaimed;
4938
4939 VM_WARN_ON_ONCE(!root_reclaim(sc));
4940
4941 /*
4942 * Unmapped clean folios are already prioritized. Scanning for more of
4943 * them is likely futile and can cause high reclaim latency when there
4944 * is a large number of memcgs.
4945 */
4946 if (!sc->may_writepage || !sc->may_unmap)
4947 goto done;
4948
4949 lru_add_drain();
4950
4951 blk_start_plug(&plug);
4952
4953 set_mm_walk(pgdat, sc->proactive);
4954
4955 set_initial_priority(pgdat, sc);
4956
4957 if (current_is_kswapd())
4958 sc->nr_reclaimed = 0;
4959
4960 if (mem_cgroup_disabled())
4961 shrink_one(&pgdat->__lruvec, sc);
4962 else
4963 shrink_many(pgdat, sc);
4964
4965 if (current_is_kswapd())
4966 sc->nr_reclaimed += reclaimed;
4967
4968 clear_mm_walk();
4969
4970 blk_finish_plug(&plug);
4971 done:
4972 if (sc->nr_reclaimed > reclaimed)
4973 pgdat->kswapd_failures = 0;
4974 }
4975
4976 /******************************************************************************
4977 * state change
4978 ******************************************************************************/
4979
state_is_valid(struct lruvec * lruvec)4980 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4981 {
4982 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4983
4984 if (lrugen->enabled) {
4985 enum lru_list lru;
4986
4987 for_each_evictable_lru(lru) {
4988 if (!list_empty(&lruvec->lists[lru]))
4989 return false;
4990 }
4991 } else {
4992 int gen, type, zone;
4993
4994 for_each_gen_type_zone(gen, type, zone) {
4995 if (!list_empty(&lrugen->folios[gen][type][zone]))
4996 return false;
4997 }
4998 }
4999
5000 return true;
5001 }
5002
fill_evictable(struct lruvec * lruvec)5003 static bool fill_evictable(struct lruvec *lruvec)
5004 {
5005 enum lru_list lru;
5006 int remaining = MAX_LRU_BATCH;
5007
5008 for_each_evictable_lru(lru) {
5009 int type = is_file_lru(lru);
5010 bool active = is_active_lru(lru);
5011 struct list_head *head = &lruvec->lists[lru];
5012
5013 while (!list_empty(head)) {
5014 bool success;
5015 struct folio *folio = lru_to_folio(head);
5016
5017 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5018 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5019 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5020 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5021
5022 lruvec_del_folio(lruvec, folio);
5023 success = lru_gen_add_folio(lruvec, folio, false);
5024 VM_WARN_ON_ONCE(!success);
5025
5026 if (!--remaining)
5027 return false;
5028 }
5029 }
5030
5031 return true;
5032 }
5033
drain_evictable(struct lruvec * lruvec)5034 static bool drain_evictable(struct lruvec *lruvec)
5035 {
5036 int gen, type, zone;
5037 int remaining = MAX_LRU_BATCH;
5038
5039 for_each_gen_type_zone(gen, type, zone) {
5040 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
5041
5042 while (!list_empty(head)) {
5043 bool success;
5044 struct folio *folio = lru_to_folio(head);
5045
5046 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5047 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5048 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5049 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5050
5051 success = lru_gen_del_folio(lruvec, folio, false);
5052 VM_WARN_ON_ONCE(!success);
5053 lruvec_add_folio(lruvec, folio);
5054
5055 if (!--remaining)
5056 return false;
5057 }
5058 }
5059
5060 return true;
5061 }
5062
lru_gen_change_state(bool enabled)5063 static void lru_gen_change_state(bool enabled)
5064 {
5065 static DEFINE_MUTEX(state_mutex);
5066
5067 struct mem_cgroup *memcg;
5068
5069 cgroup_lock();
5070 cpus_read_lock();
5071 get_online_mems();
5072 mutex_lock(&state_mutex);
5073
5074 if (enabled == lru_gen_enabled())
5075 goto unlock;
5076
5077 if (enabled)
5078 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5079 else
5080 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5081
5082 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5083 do {
5084 int nid;
5085
5086 for_each_node(nid) {
5087 struct lruvec *lruvec = get_lruvec(memcg, nid);
5088
5089 spin_lock_irq(&lruvec->lru_lock);
5090
5091 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5092 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5093
5094 lruvec->lrugen.enabled = enabled;
5095
5096 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5097 spin_unlock_irq(&lruvec->lru_lock);
5098 cond_resched();
5099 spin_lock_irq(&lruvec->lru_lock);
5100 }
5101
5102 spin_unlock_irq(&lruvec->lru_lock);
5103 }
5104
5105 cond_resched();
5106 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5107 unlock:
5108 mutex_unlock(&state_mutex);
5109 put_online_mems();
5110 cpus_read_unlock();
5111 cgroup_unlock();
5112 }
5113
5114 /******************************************************************************
5115 * sysfs interface
5116 ******************************************************************************/
5117
min_ttl_ms_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)5118 static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5119 {
5120 return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5121 }
5122
5123 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
min_ttl_ms_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)5124 static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr,
5125 const char *buf, size_t len)
5126 {
5127 unsigned int msecs;
5128
5129 if (kstrtouint(buf, 0, &msecs))
5130 return -EINVAL;
5131
5132 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5133
5134 return len;
5135 }
5136
5137 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms);
5138
enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)5139 static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5140 {
5141 unsigned int caps = 0;
5142
5143 if (get_cap(LRU_GEN_CORE))
5144 caps |= BIT(LRU_GEN_CORE);
5145
5146 if (should_walk_mmu())
5147 caps |= BIT(LRU_GEN_MM_WALK);
5148
5149 if (should_clear_pmd_young())
5150 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5151
5152 return sysfs_emit(buf, "0x%04x\n", caps);
5153 }
5154
5155 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)5156 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
5157 const char *buf, size_t len)
5158 {
5159 int i;
5160 unsigned int caps;
5161
5162 if (tolower(*buf) == 'n')
5163 caps = 0;
5164 else if (tolower(*buf) == 'y')
5165 caps = -1;
5166 else if (kstrtouint(buf, 0, &caps))
5167 return -EINVAL;
5168
5169 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5170 bool enabled = caps & BIT(i);
5171
5172 if (i == LRU_GEN_CORE)
5173 lru_gen_change_state(enabled);
5174 else if (enabled)
5175 static_branch_enable(&lru_gen_caps[i]);
5176 else
5177 static_branch_disable(&lru_gen_caps[i]);
5178 }
5179
5180 return len;
5181 }
5182
5183 static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled);
5184
5185 static struct attribute *lru_gen_attrs[] = {
5186 &lru_gen_min_ttl_attr.attr,
5187 &lru_gen_enabled_attr.attr,
5188 NULL
5189 };
5190
5191 static const struct attribute_group lru_gen_attr_group = {
5192 .name = "lru_gen",
5193 .attrs = lru_gen_attrs,
5194 };
5195
5196 /******************************************************************************
5197 * debugfs interface
5198 ******************************************************************************/
5199
lru_gen_seq_start(struct seq_file * m,loff_t * pos)5200 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5201 {
5202 struct mem_cgroup *memcg;
5203 loff_t nr_to_skip = *pos;
5204
5205 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5206 if (!m->private)
5207 return ERR_PTR(-ENOMEM);
5208
5209 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5210 do {
5211 int nid;
5212
5213 for_each_node_state(nid, N_MEMORY) {
5214 if (!nr_to_skip--)
5215 return get_lruvec(memcg, nid);
5216 }
5217 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5218
5219 return NULL;
5220 }
5221
lru_gen_seq_stop(struct seq_file * m,void * v)5222 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5223 {
5224 if (!IS_ERR_OR_NULL(v))
5225 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5226
5227 kvfree(m->private);
5228 m->private = NULL;
5229 }
5230
lru_gen_seq_next(struct seq_file * m,void * v,loff_t * pos)5231 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5232 {
5233 int nid = lruvec_pgdat(v)->node_id;
5234 struct mem_cgroup *memcg = lruvec_memcg(v);
5235
5236 ++*pos;
5237
5238 nid = next_memory_node(nid);
5239 if (nid == MAX_NUMNODES) {
5240 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5241 if (!memcg)
5242 return NULL;
5243
5244 nid = first_memory_node;
5245 }
5246
5247 return get_lruvec(memcg, nid);
5248 }
5249
lru_gen_seq_show_full(struct seq_file * m,struct lruvec * lruvec,unsigned long max_seq,unsigned long * min_seq,unsigned long seq)5250 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5251 unsigned long max_seq, unsigned long *min_seq,
5252 unsigned long seq)
5253 {
5254 int i;
5255 int type, tier;
5256 int hist = lru_hist_from_seq(seq);
5257 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5258 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
5259
5260 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5261 seq_printf(m, " %10d", tier);
5262 for (type = 0; type < ANON_AND_FILE; type++) {
5263 const char *s = "xxx";
5264 unsigned long n[3] = {};
5265
5266 if (seq == max_seq) {
5267 s = "RTx";
5268 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5269 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5270 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5271 s = "rep";
5272 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5273 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5274 if (tier)
5275 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5276 }
5277
5278 for (i = 0; i < 3; i++)
5279 seq_printf(m, " %10lu%c", n[i], s[i]);
5280 }
5281 seq_putc(m, '\n');
5282 }
5283
5284 if (!mm_state)
5285 return;
5286
5287 seq_puts(m, " ");
5288 for (i = 0; i < NR_MM_STATS; i++) {
5289 const char *s = "xxxx";
5290 unsigned long n = 0;
5291
5292 if (seq == max_seq && NR_HIST_GENS == 1) {
5293 s = "TYFA";
5294 n = READ_ONCE(mm_state->stats[hist][i]);
5295 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5296 s = "tyfa";
5297 n = READ_ONCE(mm_state->stats[hist][i]);
5298 }
5299
5300 seq_printf(m, " %10lu%c", n, s[i]);
5301 }
5302 seq_putc(m, '\n');
5303 }
5304
5305 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
lru_gen_seq_show(struct seq_file * m,void * v)5306 static int lru_gen_seq_show(struct seq_file *m, void *v)
5307 {
5308 unsigned long seq;
5309 bool full = !debugfs_real_fops(m->file)->write;
5310 struct lruvec *lruvec = v;
5311 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5312 int nid = lruvec_pgdat(lruvec)->node_id;
5313 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5314 DEFINE_MAX_SEQ(lruvec);
5315 DEFINE_MIN_SEQ(lruvec);
5316
5317 if (nid == first_memory_node) {
5318 const char *path = memcg ? m->private : "";
5319
5320 #ifdef CONFIG_MEMCG
5321 if (memcg)
5322 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5323 #endif
5324 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5325 }
5326
5327 seq_printf(m, " node %5d\n", nid);
5328
5329 if (!full)
5330 seq = min_seq[LRU_GEN_ANON];
5331 else if (max_seq >= MAX_NR_GENS)
5332 seq = max_seq - MAX_NR_GENS + 1;
5333 else
5334 seq = 0;
5335
5336 for (; seq <= max_seq; seq++) {
5337 int type, zone;
5338 int gen = lru_gen_from_seq(seq);
5339 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5340
5341 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5342
5343 for (type = 0; type < ANON_AND_FILE; type++) {
5344 unsigned long size = 0;
5345 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5346
5347 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5348 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5349
5350 seq_printf(m, " %10lu%c", size, mark);
5351 }
5352
5353 seq_putc(m, '\n');
5354
5355 if (full)
5356 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5357 }
5358
5359 return 0;
5360 }
5361
5362 static const struct seq_operations lru_gen_seq_ops = {
5363 .start = lru_gen_seq_start,
5364 .stop = lru_gen_seq_stop,
5365 .next = lru_gen_seq_next,
5366 .show = lru_gen_seq_show,
5367 };
5368
run_aging(struct lruvec * lruvec,unsigned long seq,bool can_swap,bool force_scan)5369 static int run_aging(struct lruvec *lruvec, unsigned long seq,
5370 bool can_swap, bool force_scan)
5371 {
5372 DEFINE_MAX_SEQ(lruvec);
5373 DEFINE_MIN_SEQ(lruvec);
5374
5375 if (seq < max_seq)
5376 return 0;
5377
5378 if (seq > max_seq)
5379 return -EINVAL;
5380
5381 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5382 return -ERANGE;
5383
5384 try_to_inc_max_seq(lruvec, max_seq, can_swap, force_scan);
5385
5386 return 0;
5387 }
5388
run_eviction(struct lruvec * lruvec,unsigned long seq,struct scan_control * sc,int swappiness,unsigned long nr_to_reclaim)5389 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5390 int swappiness, unsigned long nr_to_reclaim)
5391 {
5392 DEFINE_MAX_SEQ(lruvec);
5393
5394 if (seq + MIN_NR_GENS > max_seq)
5395 return -EINVAL;
5396
5397 sc->nr_reclaimed = 0;
5398
5399 while (!signal_pending(current)) {
5400 DEFINE_MIN_SEQ(lruvec);
5401
5402 if (seq < min_seq[!swappiness])
5403 return 0;
5404
5405 if (sc->nr_reclaimed >= nr_to_reclaim)
5406 return 0;
5407
5408 if (!evict_folios(lruvec, sc, swappiness))
5409 return 0;
5410
5411 cond_resched();
5412 }
5413
5414 return -EINTR;
5415 }
5416
run_cmd(char cmd,int memcg_id,int nid,unsigned long seq,struct scan_control * sc,int swappiness,unsigned long opt)5417 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5418 struct scan_control *sc, int swappiness, unsigned long opt)
5419 {
5420 struct lruvec *lruvec;
5421 int err = -EINVAL;
5422 struct mem_cgroup *memcg = NULL;
5423
5424 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5425 return -EINVAL;
5426
5427 if (!mem_cgroup_disabled()) {
5428 rcu_read_lock();
5429
5430 memcg = mem_cgroup_from_id(memcg_id);
5431 if (!mem_cgroup_tryget(memcg))
5432 memcg = NULL;
5433
5434 rcu_read_unlock();
5435
5436 if (!memcg)
5437 return -EINVAL;
5438 }
5439
5440 if (memcg_id != mem_cgroup_id(memcg))
5441 goto done;
5442
5443 lruvec = get_lruvec(memcg, nid);
5444
5445 if (swappiness < MIN_SWAPPINESS)
5446 swappiness = get_swappiness(lruvec, sc);
5447 else if (swappiness > MAX_SWAPPINESS)
5448 goto done;
5449
5450 switch (cmd) {
5451 case '+':
5452 err = run_aging(lruvec, seq, swappiness, opt);
5453 break;
5454 case '-':
5455 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5456 break;
5457 }
5458 done:
5459 mem_cgroup_put(memcg);
5460
5461 return err;
5462 }
5463
5464 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
lru_gen_seq_write(struct file * file,const char __user * src,size_t len,loff_t * pos)5465 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5466 size_t len, loff_t *pos)
5467 {
5468 void *buf;
5469 char *cur, *next;
5470 unsigned int flags;
5471 struct blk_plug plug;
5472 int err = -EINVAL;
5473 struct scan_control sc = {
5474 .may_writepage = true,
5475 .may_unmap = true,
5476 .may_swap = true,
5477 .reclaim_idx = MAX_NR_ZONES - 1,
5478 .gfp_mask = GFP_KERNEL,
5479 };
5480
5481 buf = kvmalloc(len + 1, GFP_KERNEL);
5482 if (!buf)
5483 return -ENOMEM;
5484
5485 if (copy_from_user(buf, src, len)) {
5486 kvfree(buf);
5487 return -EFAULT;
5488 }
5489
5490 set_task_reclaim_state(current, &sc.reclaim_state);
5491 flags = memalloc_noreclaim_save();
5492 blk_start_plug(&plug);
5493 if (!set_mm_walk(NULL, true)) {
5494 err = -ENOMEM;
5495 goto done;
5496 }
5497
5498 next = buf;
5499 next[len] = '\0';
5500
5501 while ((cur = strsep(&next, ",;\n"))) {
5502 int n;
5503 int end;
5504 char cmd;
5505 unsigned int memcg_id;
5506 unsigned int nid;
5507 unsigned long seq;
5508 unsigned int swappiness = -1;
5509 unsigned long opt = -1;
5510
5511 cur = skip_spaces(cur);
5512 if (!*cur)
5513 continue;
5514
5515 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5516 &seq, &end, &swappiness, &end, &opt, &end);
5517 if (n < 4 || cur[end]) {
5518 err = -EINVAL;
5519 break;
5520 }
5521
5522 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5523 if (err)
5524 break;
5525 }
5526 done:
5527 clear_mm_walk();
5528 blk_finish_plug(&plug);
5529 memalloc_noreclaim_restore(flags);
5530 set_task_reclaim_state(current, NULL);
5531
5532 kvfree(buf);
5533
5534 return err ? : len;
5535 }
5536
lru_gen_seq_open(struct inode * inode,struct file * file)5537 static int lru_gen_seq_open(struct inode *inode, struct file *file)
5538 {
5539 return seq_open(file, &lru_gen_seq_ops);
5540 }
5541
5542 static const struct file_operations lru_gen_rw_fops = {
5543 .open = lru_gen_seq_open,
5544 .read = seq_read,
5545 .write = lru_gen_seq_write,
5546 .llseek = seq_lseek,
5547 .release = seq_release,
5548 };
5549
5550 static const struct file_operations lru_gen_ro_fops = {
5551 .open = lru_gen_seq_open,
5552 .read = seq_read,
5553 .llseek = seq_lseek,
5554 .release = seq_release,
5555 };
5556
5557 /******************************************************************************
5558 * initialization
5559 ******************************************************************************/
5560
lru_gen_init_pgdat(struct pglist_data * pgdat)5561 void lru_gen_init_pgdat(struct pglist_data *pgdat)
5562 {
5563 int i, j;
5564
5565 spin_lock_init(&pgdat->memcg_lru.lock);
5566
5567 for (i = 0; i < MEMCG_NR_GENS; i++) {
5568 for (j = 0; j < MEMCG_NR_BINS; j++)
5569 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5570 }
5571 }
5572
lru_gen_init_lruvec(struct lruvec * lruvec)5573 void lru_gen_init_lruvec(struct lruvec *lruvec)
5574 {
5575 int i;
5576 int gen, type, zone;
5577 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5578 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
5579
5580 lrugen->max_seq = MIN_NR_GENS + 1;
5581 lrugen->enabled = lru_gen_enabled();
5582
5583 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5584 lrugen->timestamps[i] = jiffies;
5585
5586 for_each_gen_type_zone(gen, type, zone)
5587 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
5588
5589 if (mm_state)
5590 mm_state->seq = MIN_NR_GENS;
5591 }
5592
5593 #ifdef CONFIG_MEMCG
5594
lru_gen_init_memcg(struct mem_cgroup * memcg)5595 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5596 {
5597 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
5598
5599 if (!mm_list)
5600 return;
5601
5602 INIT_LIST_HEAD(&mm_list->fifo);
5603 spin_lock_init(&mm_list->lock);
5604 }
5605
lru_gen_exit_memcg(struct mem_cgroup * memcg)5606 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5607 {
5608 int i;
5609 int nid;
5610 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
5611
5612 VM_WARN_ON_ONCE(mm_list && !list_empty(&mm_list->fifo));
5613
5614 for_each_node(nid) {
5615 struct lruvec *lruvec = get_lruvec(memcg, nid);
5616 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
5617
5618 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5619 sizeof(lruvec->lrugen.nr_pages)));
5620
5621 lruvec->lrugen.list.next = LIST_POISON1;
5622
5623 if (!mm_state)
5624 continue;
5625
5626 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5627 bitmap_free(mm_state->filters[i]);
5628 mm_state->filters[i] = NULL;
5629 }
5630 }
5631 }
5632
5633 #endif /* CONFIG_MEMCG */
5634
init_lru_gen(void)5635 static int __init init_lru_gen(void)
5636 {
5637 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5638 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5639
5640 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5641 pr_err("lru_gen: failed to create sysfs group\n");
5642
5643 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5644 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5645
5646 return 0;
5647 };
5648 late_initcall(init_lru_gen);
5649
5650 #else /* !CONFIG_LRU_GEN */
5651
lru_gen_age_node(struct pglist_data * pgdat,struct scan_control * sc)5652 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5653 {
5654 BUILD_BUG();
5655 }
5656
lru_gen_shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)5657 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5658 {
5659 BUILD_BUG();
5660 }
5661
lru_gen_shrink_node(struct pglist_data * pgdat,struct scan_control * sc)5662 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5663 {
5664 BUILD_BUG();
5665 }
5666
5667 #endif /* CONFIG_LRU_GEN */
5668
shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)5669 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5670 {
5671 unsigned long nr[NR_LRU_LISTS];
5672 unsigned long targets[NR_LRU_LISTS];
5673 unsigned long nr_to_scan;
5674 enum lru_list lru;
5675 unsigned long nr_reclaimed = 0;
5676 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5677 bool proportional_reclaim;
5678 struct blk_plug plug;
5679
5680 if (lru_gen_enabled() && !root_reclaim(sc)) {
5681 lru_gen_shrink_lruvec(lruvec, sc);
5682 return;
5683 }
5684
5685 get_scan_count(lruvec, sc, nr);
5686
5687 /* Record the original scan target for proportional adjustments later */
5688 memcpy(targets, nr, sizeof(nr));
5689
5690 /*
5691 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5692 * event that can occur when there is little memory pressure e.g.
5693 * multiple streaming readers/writers. Hence, we do not abort scanning
5694 * when the requested number of pages are reclaimed when scanning at
5695 * DEF_PRIORITY on the assumption that the fact we are direct
5696 * reclaiming implies that kswapd is not keeping up and it is best to
5697 * do a batch of work at once. For memcg reclaim one check is made to
5698 * abort proportional reclaim if either the file or anon lru has already
5699 * dropped to zero at the first pass.
5700 */
5701 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5702 sc->priority == DEF_PRIORITY);
5703
5704 blk_start_plug(&plug);
5705 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5706 nr[LRU_INACTIVE_FILE]) {
5707 unsigned long nr_anon, nr_file, percentage;
5708 unsigned long nr_scanned;
5709
5710 for_each_evictable_lru(lru) {
5711 if (nr[lru]) {
5712 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5713 nr[lru] -= nr_to_scan;
5714
5715 nr_reclaimed += shrink_list(lru, nr_to_scan,
5716 lruvec, sc);
5717 }
5718 }
5719
5720 cond_resched();
5721
5722 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
5723 continue;
5724
5725 /*
5726 * For kswapd and memcg, reclaim at least the number of pages
5727 * requested. Ensure that the anon and file LRUs are scanned
5728 * proportionally what was requested by get_scan_count(). We
5729 * stop reclaiming one LRU and reduce the amount scanning
5730 * proportional to the original scan target.
5731 */
5732 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5733 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5734
5735 /*
5736 * It's just vindictive to attack the larger once the smaller
5737 * has gone to zero. And given the way we stop scanning the
5738 * smaller below, this makes sure that we only make one nudge
5739 * towards proportionality once we've got nr_to_reclaim.
5740 */
5741 if (!nr_file || !nr_anon)
5742 break;
5743
5744 if (nr_file > nr_anon) {
5745 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5746 targets[LRU_ACTIVE_ANON] + 1;
5747 lru = LRU_BASE;
5748 percentage = nr_anon * 100 / scan_target;
5749 } else {
5750 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5751 targets[LRU_ACTIVE_FILE] + 1;
5752 lru = LRU_FILE;
5753 percentage = nr_file * 100 / scan_target;
5754 }
5755
5756 /* Stop scanning the smaller of the LRU */
5757 nr[lru] = 0;
5758 nr[lru + LRU_ACTIVE] = 0;
5759
5760 /*
5761 * Recalculate the other LRU scan count based on its original
5762 * scan target and the percentage scanning already complete
5763 */
5764 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5765 nr_scanned = targets[lru] - nr[lru];
5766 nr[lru] = targets[lru] * (100 - percentage) / 100;
5767 nr[lru] -= min(nr[lru], nr_scanned);
5768
5769 lru += LRU_ACTIVE;
5770 nr_scanned = targets[lru] - nr[lru];
5771 nr[lru] = targets[lru] * (100 - percentage) / 100;
5772 nr[lru] -= min(nr[lru], nr_scanned);
5773 }
5774 blk_finish_plug(&plug);
5775 sc->nr_reclaimed += nr_reclaimed;
5776
5777 /*
5778 * Even if we did not try to evict anon pages at all, we want to
5779 * rebalance the anon lru active/inactive ratio.
5780 */
5781 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5782 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5783 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5784 sc, LRU_ACTIVE_ANON);
5785 }
5786
5787 /* Use reclaim/compaction for costly allocs or under memory pressure */
in_reclaim_compaction(struct scan_control * sc)5788 static bool in_reclaim_compaction(struct scan_control *sc)
5789 {
5790 if (gfp_compaction_allowed(sc->gfp_mask) && sc->order &&
5791 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
5792 sc->priority < DEF_PRIORITY - 2))
5793 return true;
5794
5795 return false;
5796 }
5797
5798 /*
5799 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5800 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5801 * true if more pages should be reclaimed such that when the page allocator
5802 * calls try_to_compact_pages() that it will have enough free pages to succeed.
5803 * It will give up earlier than that if there is difficulty reclaiming pages.
5804 */
should_continue_reclaim(struct pglist_data * pgdat,unsigned long nr_reclaimed,struct scan_control * sc)5805 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
5806 unsigned long nr_reclaimed,
5807 struct scan_control *sc)
5808 {
5809 unsigned long pages_for_compaction;
5810 unsigned long inactive_lru_pages;
5811 int z;
5812
5813 /* If not in reclaim/compaction mode, stop */
5814 if (!in_reclaim_compaction(sc))
5815 return false;
5816
5817 /*
5818 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5819 * number of pages that were scanned. This will return to the caller
5820 * with the risk reclaim/compaction and the resulting allocation attempt
5821 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5822 * allocations through requiring that the full LRU list has been scanned
5823 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5824 * scan, but that approximation was wrong, and there were corner cases
5825 * where always a non-zero amount of pages were scanned.
5826 */
5827 if (!nr_reclaimed)
5828 return false;
5829
5830 /* If compaction would go ahead or the allocation would succeed, stop */
5831 for (z = 0; z <= sc->reclaim_idx; z++) {
5832 struct zone *zone = &pgdat->node_zones[z];
5833 if (!managed_zone(zone))
5834 continue;
5835
5836 /* Allocation can already succeed, nothing to do */
5837 if (zone_watermark_ok(zone, sc->order, min_wmark_pages(zone),
5838 sc->reclaim_idx, 0))
5839 return false;
5840
5841 if (compaction_suitable(zone, sc->order, sc->reclaim_idx))
5842 return false;
5843 }
5844
5845 /*
5846 * If we have not reclaimed enough pages for compaction and the
5847 * inactive lists are large enough, continue reclaiming
5848 */
5849 pages_for_compaction = compact_gap(sc->order);
5850 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
5851 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
5852 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5853
5854 return inactive_lru_pages > pages_for_compaction;
5855 }
5856
shrink_node_memcgs(pg_data_t * pgdat,struct scan_control * sc)5857 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
5858 {
5859 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
5860 struct mem_cgroup_reclaim_cookie reclaim = {
5861 .pgdat = pgdat,
5862 };
5863 struct mem_cgroup_reclaim_cookie *partial = &reclaim;
5864 struct mem_cgroup *memcg;
5865
5866 /*
5867 * In most cases, direct reclaimers can do partial walks
5868 * through the cgroup tree, using an iterator state that
5869 * persists across invocations. This strikes a balance between
5870 * fairness and allocation latency.
5871 *
5872 * For kswapd, reliable forward progress is more important
5873 * than a quick return to idle. Always do full walks.
5874 */
5875 if (current_is_kswapd() || sc->memcg_full_walk)
5876 partial = NULL;
5877
5878 memcg = mem_cgroup_iter(target_memcg, NULL, partial);
5879 do {
5880 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
5881 unsigned long reclaimed;
5882 unsigned long scanned;
5883
5884 /*
5885 * This loop can become CPU-bound when target memcgs
5886 * aren't eligible for reclaim - either because they
5887 * don't have any reclaimable pages, or because their
5888 * memory is explicitly protected. Avoid soft lockups.
5889 */
5890 cond_resched();
5891
5892 mem_cgroup_calculate_protection(target_memcg, memcg);
5893
5894 if (mem_cgroup_below_min(target_memcg, memcg)) {
5895 /*
5896 * Hard protection.
5897 * If there is no reclaimable memory, OOM.
5898 */
5899 continue;
5900 } else if (mem_cgroup_below_low(target_memcg, memcg)) {
5901 /*
5902 * Soft protection.
5903 * Respect the protection only as long as
5904 * there is an unprotected supply
5905 * of reclaimable memory from other cgroups.
5906 */
5907 if (!sc->memcg_low_reclaim) {
5908 sc->memcg_low_skipped = 1;
5909 continue;
5910 }
5911 memcg_memory_event(memcg, MEMCG_LOW);
5912 }
5913
5914 reclaimed = sc->nr_reclaimed;
5915 scanned = sc->nr_scanned;
5916
5917 shrink_lruvec(lruvec, sc);
5918
5919 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5920 sc->priority);
5921
5922 /* Record the group's reclaim efficiency */
5923 if (!sc->proactive)
5924 vmpressure(sc->gfp_mask, memcg, false,
5925 sc->nr_scanned - scanned,
5926 sc->nr_reclaimed - reclaimed);
5927
5928 /* If partial walks are allowed, bail once goal is reached */
5929 if (partial && sc->nr_reclaimed >= sc->nr_to_reclaim) {
5930 mem_cgroup_iter_break(target_memcg, memcg);
5931 break;
5932 }
5933 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, partial)));
5934 }
5935
shrink_node(pg_data_t * pgdat,struct scan_control * sc)5936 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
5937 {
5938 unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed;
5939 struct lruvec *target_lruvec;
5940 bool reclaimable = false;
5941
5942 if (lru_gen_enabled() && root_reclaim(sc)) {
5943 lru_gen_shrink_node(pgdat, sc);
5944 return;
5945 }
5946
5947 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5948
5949 again:
5950 memset(&sc->nr, 0, sizeof(sc->nr));
5951
5952 nr_reclaimed = sc->nr_reclaimed;
5953 nr_scanned = sc->nr_scanned;
5954
5955 prepare_scan_control(pgdat, sc);
5956
5957 shrink_node_memcgs(pgdat, sc);
5958
5959 flush_reclaim_state(sc);
5960
5961 nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed;
5962
5963 /* Record the subtree's reclaim efficiency */
5964 if (!sc->proactive)
5965 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
5966 sc->nr_scanned - nr_scanned, nr_node_reclaimed);
5967
5968 if (nr_node_reclaimed)
5969 reclaimable = true;
5970
5971 if (current_is_kswapd()) {
5972 /*
5973 * If reclaim is isolating dirty pages under writeback,
5974 * it implies that the long-lived page allocation rate
5975 * is exceeding the page laundering rate. Either the
5976 * global limits are not being effective at throttling
5977 * processes due to the page distribution throughout
5978 * zones or there is heavy usage of a slow backing
5979 * device. The only option is to throttle from reclaim
5980 * context which is not ideal as there is no guarantee
5981 * the dirtying process is throttled in the same way
5982 * balance_dirty_pages() manages.
5983 *
5984 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5985 * count the number of pages under pages flagged for
5986 * immediate reclaim and stall if any are encountered
5987 * in the nr_immediate check below.
5988 */
5989 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5990 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
5991
5992 /* Allow kswapd to start writing pages during reclaim.*/
5993 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5994 set_bit(PGDAT_DIRTY, &pgdat->flags);
5995
5996 /*
5997 * If kswapd scans pages marked for immediate
5998 * reclaim and under writeback (nr_immediate), it
5999 * implies that pages are cycling through the LRU
6000 * faster than they are written so forcibly stall
6001 * until some pages complete writeback.
6002 */
6003 if (sc->nr.immediate)
6004 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6005 }
6006
6007 /*
6008 * Tag a node/memcg as congested if all the dirty pages were marked
6009 * for writeback and immediate reclaim (counted in nr.congested).
6010 *
6011 * Legacy memcg will stall in page writeback so avoid forcibly
6012 * stalling in reclaim_throttle().
6013 */
6014 if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested) {
6015 if (cgroup_reclaim(sc) && writeback_throttling_sane(sc))
6016 set_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags);
6017
6018 if (current_is_kswapd())
6019 set_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags);
6020 }
6021
6022 /*
6023 * Stall direct reclaim for IO completions if the lruvec is
6024 * node is congested. Allow kswapd to continue until it
6025 * starts encountering unqueued dirty pages or cycling through
6026 * the LRU too quickly.
6027 */
6028 if (!current_is_kswapd() && current_may_throttle() &&
6029 !sc->hibernation_mode &&
6030 (test_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags) ||
6031 test_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags)))
6032 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6033
6034 if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc))
6035 goto again;
6036
6037 /*
6038 * Kswapd gives up on balancing particular nodes after too
6039 * many failures to reclaim anything from them and goes to
6040 * sleep. On reclaim progress, reset the failure counter. A
6041 * successful direct reclaim run will revive a dormant kswapd.
6042 */
6043 if (reclaimable)
6044 pgdat->kswapd_failures = 0;
6045 else if (sc->cache_trim_mode)
6046 sc->cache_trim_mode_failed = 1;
6047 }
6048
6049 /*
6050 * Returns true if compaction should go ahead for a costly-order request, or
6051 * the allocation would already succeed without compaction. Return false if we
6052 * should reclaim first.
6053 */
compaction_ready(struct zone * zone,struct scan_control * sc)6054 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6055 {
6056 unsigned long watermark;
6057
6058 if (!gfp_compaction_allowed(sc->gfp_mask))
6059 return false;
6060
6061 /* Allocation can already succeed, nothing to do */
6062 if (zone_watermark_ok(zone, sc->order, min_wmark_pages(zone),
6063 sc->reclaim_idx, 0))
6064 return true;
6065
6066 /* Compaction cannot yet proceed. Do reclaim. */
6067 if (!compaction_suitable(zone, sc->order, sc->reclaim_idx))
6068 return false;
6069
6070 /*
6071 * Compaction is already possible, but it takes time to run and there
6072 * are potentially other callers using the pages just freed. So proceed
6073 * with reclaim to make a buffer of free pages available to give
6074 * compaction a reasonable chance of completing and allocating the page.
6075 * Note that we won't actually reclaim the whole buffer in one attempt
6076 * as the target watermark in should_continue_reclaim() is lower. But if
6077 * we are already above the high+gap watermark, don't reclaim at all.
6078 */
6079 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6080
6081 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6082 }
6083
consider_reclaim_throttle(pg_data_t * pgdat,struct scan_control * sc)6084 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6085 {
6086 /*
6087 * If reclaim is making progress greater than 12% efficiency then
6088 * wake all the NOPROGRESS throttled tasks.
6089 */
6090 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6091 wait_queue_head_t *wqh;
6092
6093 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6094 if (waitqueue_active(wqh))
6095 wake_up(wqh);
6096
6097 return;
6098 }
6099
6100 /*
6101 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6102 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6103 * under writeback and marked for immediate reclaim at the tail of the
6104 * LRU.
6105 */
6106 if (current_is_kswapd() || cgroup_reclaim(sc))
6107 return;
6108
6109 /* Throttle if making no progress at high prioities. */
6110 if (sc->priority == 1 && !sc->nr_reclaimed)
6111 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6112 }
6113
6114 /*
6115 * This is the direct reclaim path, for page-allocating processes. We only
6116 * try to reclaim pages from zones which will satisfy the caller's allocation
6117 * request.
6118 *
6119 * If a zone is deemed to be full of pinned pages then just give it a light
6120 * scan then give up on it.
6121 */
shrink_zones(struct zonelist * zonelist,struct scan_control * sc)6122 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6123 {
6124 struct zoneref *z;
6125 struct zone *zone;
6126 unsigned long nr_soft_reclaimed;
6127 unsigned long nr_soft_scanned;
6128 gfp_t orig_mask;
6129 pg_data_t *last_pgdat = NULL;
6130 pg_data_t *first_pgdat = NULL;
6131
6132 /*
6133 * If the number of buffer_heads in the machine exceeds the maximum
6134 * allowed level, force direct reclaim to scan the highmem zone as
6135 * highmem pages could be pinning lowmem pages storing buffer_heads
6136 */
6137 orig_mask = sc->gfp_mask;
6138 if (buffer_heads_over_limit) {
6139 sc->gfp_mask |= __GFP_HIGHMEM;
6140 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6141 }
6142
6143 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6144 sc->reclaim_idx, sc->nodemask) {
6145 /*
6146 * Take care memory controller reclaiming has small influence
6147 * to global LRU.
6148 */
6149 if (!cgroup_reclaim(sc)) {
6150 if (!cpuset_zone_allowed(zone,
6151 GFP_KERNEL | __GFP_HARDWALL))
6152 continue;
6153
6154 /*
6155 * If we already have plenty of memory free for
6156 * compaction in this zone, don't free any more.
6157 * Even though compaction is invoked for any
6158 * non-zero order, only frequent costly order
6159 * reclamation is disruptive enough to become a
6160 * noticeable problem, like transparent huge
6161 * page allocations.
6162 */
6163 if (IS_ENABLED(CONFIG_COMPACTION) &&
6164 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6165 compaction_ready(zone, sc)) {
6166 sc->compaction_ready = true;
6167 continue;
6168 }
6169
6170 /*
6171 * Shrink each node in the zonelist once. If the
6172 * zonelist is ordered by zone (not the default) then a
6173 * node may be shrunk multiple times but in that case
6174 * the user prefers lower zones being preserved.
6175 */
6176 if (zone->zone_pgdat == last_pgdat)
6177 continue;
6178
6179 /*
6180 * This steals pages from memory cgroups over softlimit
6181 * and returns the number of reclaimed pages and
6182 * scanned pages. This works for global memory pressure
6183 * and balancing, not for a memcg's limit.
6184 */
6185 nr_soft_scanned = 0;
6186 nr_soft_reclaimed = memcg1_soft_limit_reclaim(zone->zone_pgdat,
6187 sc->order, sc->gfp_mask,
6188 &nr_soft_scanned);
6189 sc->nr_reclaimed += nr_soft_reclaimed;
6190 sc->nr_scanned += nr_soft_scanned;
6191 /* need some check for avoid more shrink_zone() */
6192 }
6193
6194 if (!first_pgdat)
6195 first_pgdat = zone->zone_pgdat;
6196
6197 /* See comment about same check for global reclaim above */
6198 if (zone->zone_pgdat == last_pgdat)
6199 continue;
6200 last_pgdat = zone->zone_pgdat;
6201 shrink_node(zone->zone_pgdat, sc);
6202 }
6203
6204 if (first_pgdat)
6205 consider_reclaim_throttle(first_pgdat, sc);
6206
6207 /*
6208 * Restore to original mask to avoid the impact on the caller if we
6209 * promoted it to __GFP_HIGHMEM.
6210 */
6211 sc->gfp_mask = orig_mask;
6212 }
6213
snapshot_refaults(struct mem_cgroup * target_memcg,pg_data_t * pgdat)6214 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6215 {
6216 struct lruvec *target_lruvec;
6217 unsigned long refaults;
6218
6219 if (lru_gen_enabled())
6220 return;
6221
6222 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6223 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6224 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6225 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6226 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6227 }
6228
6229 /*
6230 * This is the main entry point to direct page reclaim.
6231 *
6232 * If a full scan of the inactive list fails to free enough memory then we
6233 * are "out of memory" and something needs to be killed.
6234 *
6235 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6236 * high - the zone may be full of dirty or under-writeback pages, which this
6237 * caller can't do much about. We kick the writeback threads and take explicit
6238 * naps in the hope that some of these pages can be written. But if the
6239 * allocating task holds filesystem locks which prevent writeout this might not
6240 * work, and the allocation attempt will fail.
6241 *
6242 * returns: 0, if no pages reclaimed
6243 * else, the number of pages reclaimed
6244 */
do_try_to_free_pages(struct zonelist * zonelist,struct scan_control * sc)6245 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6246 struct scan_control *sc)
6247 {
6248 int initial_priority = sc->priority;
6249 pg_data_t *last_pgdat;
6250 struct zoneref *z;
6251 struct zone *zone;
6252 retry:
6253 delayacct_freepages_start();
6254
6255 if (!cgroup_reclaim(sc))
6256 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6257
6258 do {
6259 if (!sc->proactive)
6260 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6261 sc->priority);
6262 sc->nr_scanned = 0;
6263 shrink_zones(zonelist, sc);
6264
6265 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6266 break;
6267
6268 if (sc->compaction_ready)
6269 break;
6270
6271 /*
6272 * If we're getting trouble reclaiming, start doing
6273 * writepage even in laptop mode.
6274 */
6275 if (sc->priority < DEF_PRIORITY - 2)
6276 sc->may_writepage = 1;
6277 } while (--sc->priority >= 0);
6278
6279 last_pgdat = NULL;
6280 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6281 sc->nodemask) {
6282 if (zone->zone_pgdat == last_pgdat)
6283 continue;
6284 last_pgdat = zone->zone_pgdat;
6285
6286 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6287
6288 if (cgroup_reclaim(sc)) {
6289 struct lruvec *lruvec;
6290
6291 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6292 zone->zone_pgdat);
6293 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags);
6294 }
6295 }
6296
6297 delayacct_freepages_end();
6298
6299 if (sc->nr_reclaimed)
6300 return sc->nr_reclaimed;
6301
6302 /* Aborted reclaim to try compaction? don't OOM, then */
6303 if (sc->compaction_ready)
6304 return 1;
6305
6306 /*
6307 * In most cases, direct reclaimers can do partial walks
6308 * through the cgroup tree to meet the reclaim goal while
6309 * keeping latency low. Since the iterator state is shared
6310 * among all direct reclaim invocations (to retain fairness
6311 * among cgroups), though, high concurrency can result in
6312 * individual threads not seeing enough cgroups to make
6313 * meaningful forward progress. Avoid false OOMs in this case.
6314 */
6315 if (!sc->memcg_full_walk) {
6316 sc->priority = initial_priority;
6317 sc->memcg_full_walk = 1;
6318 goto retry;
6319 }
6320
6321 /*
6322 * We make inactive:active ratio decisions based on the node's
6323 * composition of memory, but a restrictive reclaim_idx or a
6324 * memory.low cgroup setting can exempt large amounts of
6325 * memory from reclaim. Neither of which are very common, so
6326 * instead of doing costly eligibility calculations of the
6327 * entire cgroup subtree up front, we assume the estimates are
6328 * good, and retry with forcible deactivation if that fails.
6329 */
6330 if (sc->skipped_deactivate) {
6331 sc->priority = initial_priority;
6332 sc->force_deactivate = 1;
6333 sc->skipped_deactivate = 0;
6334 goto retry;
6335 }
6336
6337 /* Untapped cgroup reserves? Don't OOM, retry. */
6338 if (sc->memcg_low_skipped) {
6339 sc->priority = initial_priority;
6340 sc->force_deactivate = 0;
6341 sc->memcg_low_reclaim = 1;
6342 sc->memcg_low_skipped = 0;
6343 goto retry;
6344 }
6345
6346 return 0;
6347 }
6348
allow_direct_reclaim(pg_data_t * pgdat)6349 static bool allow_direct_reclaim(pg_data_t *pgdat)
6350 {
6351 struct zone *zone;
6352 unsigned long pfmemalloc_reserve = 0;
6353 unsigned long free_pages = 0;
6354 int i;
6355 bool wmark_ok;
6356
6357 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6358 return true;
6359
6360 for (i = 0; i <= ZONE_NORMAL; i++) {
6361 zone = &pgdat->node_zones[i];
6362 if (!managed_zone(zone))
6363 continue;
6364
6365 if (!zone_reclaimable_pages(zone))
6366 continue;
6367
6368 pfmemalloc_reserve += min_wmark_pages(zone);
6369 free_pages += zone_page_state_snapshot(zone, NR_FREE_PAGES);
6370 }
6371
6372 /* If there are no reserves (unexpected config) then do not throttle */
6373 if (!pfmemalloc_reserve)
6374 return true;
6375
6376 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6377
6378 /* kswapd must be awake if processes are being throttled */
6379 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6380 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6381 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6382
6383 wake_up_interruptible(&pgdat->kswapd_wait);
6384 }
6385
6386 return wmark_ok;
6387 }
6388
6389 /*
6390 * Throttle direct reclaimers if backing storage is backed by the network
6391 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6392 * depleted. kswapd will continue to make progress and wake the processes
6393 * when the low watermark is reached.
6394 *
6395 * Returns true if a fatal signal was delivered during throttling. If this
6396 * happens, the page allocator should not consider triggering the OOM killer.
6397 */
throttle_direct_reclaim(gfp_t gfp_mask,struct zonelist * zonelist,nodemask_t * nodemask)6398 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6399 nodemask_t *nodemask)
6400 {
6401 struct zoneref *z;
6402 struct zone *zone;
6403 pg_data_t *pgdat = NULL;
6404
6405 /*
6406 * Kernel threads should not be throttled as they may be indirectly
6407 * responsible for cleaning pages necessary for reclaim to make forward
6408 * progress. kjournald for example may enter direct reclaim while
6409 * committing a transaction where throttling it could forcing other
6410 * processes to block on log_wait_commit().
6411 */
6412 if (current->flags & PF_KTHREAD)
6413 goto out;
6414
6415 /*
6416 * If a fatal signal is pending, this process should not throttle.
6417 * It should return quickly so it can exit and free its memory
6418 */
6419 if (fatal_signal_pending(current))
6420 goto out;
6421
6422 /*
6423 * Check if the pfmemalloc reserves are ok by finding the first node
6424 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6425 * GFP_KERNEL will be required for allocating network buffers when
6426 * swapping over the network so ZONE_HIGHMEM is unusable.
6427 *
6428 * Throttling is based on the first usable node and throttled processes
6429 * wait on a queue until kswapd makes progress and wakes them. There
6430 * is an affinity then between processes waking up and where reclaim
6431 * progress has been made assuming the process wakes on the same node.
6432 * More importantly, processes running on remote nodes will not compete
6433 * for remote pfmemalloc reserves and processes on different nodes
6434 * should make reasonable progress.
6435 */
6436 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6437 gfp_zone(gfp_mask), nodemask) {
6438 if (zone_idx(zone) > ZONE_NORMAL)
6439 continue;
6440
6441 /* Throttle based on the first usable node */
6442 pgdat = zone->zone_pgdat;
6443 if (allow_direct_reclaim(pgdat))
6444 goto out;
6445 break;
6446 }
6447
6448 /* If no zone was usable by the allocation flags then do not throttle */
6449 if (!pgdat)
6450 goto out;
6451
6452 /* Account for the throttling */
6453 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6454
6455 /*
6456 * If the caller cannot enter the filesystem, it's possible that it
6457 * is due to the caller holding an FS lock or performing a journal
6458 * transaction in the case of a filesystem like ext[3|4]. In this case,
6459 * it is not safe to block on pfmemalloc_wait as kswapd could be
6460 * blocked waiting on the same lock. Instead, throttle for up to a
6461 * second before continuing.
6462 */
6463 if (!(gfp_mask & __GFP_FS))
6464 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6465 allow_direct_reclaim(pgdat), HZ);
6466 else
6467 /* Throttle until kswapd wakes the process */
6468 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6469 allow_direct_reclaim(pgdat));
6470
6471 if (fatal_signal_pending(current))
6472 return true;
6473
6474 out:
6475 return false;
6476 }
6477
try_to_free_pages(struct zonelist * zonelist,int order,gfp_t gfp_mask,nodemask_t * nodemask)6478 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6479 gfp_t gfp_mask, nodemask_t *nodemask)
6480 {
6481 unsigned long nr_reclaimed;
6482 struct scan_control sc = {
6483 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6484 .gfp_mask = current_gfp_context(gfp_mask),
6485 .reclaim_idx = gfp_zone(gfp_mask),
6486 .order = order,
6487 .nodemask = nodemask,
6488 .priority = DEF_PRIORITY,
6489 .may_writepage = !laptop_mode,
6490 .may_unmap = 1,
6491 .may_swap = 1,
6492 };
6493
6494 /*
6495 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6496 * Confirm they are large enough for max values.
6497 */
6498 BUILD_BUG_ON(MAX_PAGE_ORDER >= S8_MAX);
6499 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6500 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6501
6502 /*
6503 * Do not enter reclaim if fatal signal was delivered while throttled.
6504 * 1 is returned so that the page allocator does not OOM kill at this
6505 * point.
6506 */
6507 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6508 return 1;
6509
6510 set_task_reclaim_state(current, &sc.reclaim_state);
6511 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6512
6513 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6514
6515 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6516 set_task_reclaim_state(current, NULL);
6517
6518 return nr_reclaimed;
6519 }
6520
6521 #ifdef CONFIG_MEMCG
6522
6523 /* Only used by soft limit reclaim. Do not reuse for anything else. */
mem_cgroup_shrink_node(struct mem_cgroup * memcg,gfp_t gfp_mask,bool noswap,pg_data_t * pgdat,unsigned long * nr_scanned)6524 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6525 gfp_t gfp_mask, bool noswap,
6526 pg_data_t *pgdat,
6527 unsigned long *nr_scanned)
6528 {
6529 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6530 struct scan_control sc = {
6531 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6532 .target_mem_cgroup = memcg,
6533 .may_writepage = !laptop_mode,
6534 .may_unmap = 1,
6535 .reclaim_idx = MAX_NR_ZONES - 1,
6536 .may_swap = !noswap,
6537 };
6538
6539 WARN_ON_ONCE(!current->reclaim_state);
6540
6541 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6542 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6543
6544 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6545 sc.gfp_mask);
6546
6547 /*
6548 * NOTE: Although we can get the priority field, using it
6549 * here is not a good idea, since it limits the pages we can scan.
6550 * if we don't reclaim here, the shrink_node from balance_pgdat
6551 * will pick up pages from other mem cgroup's as well. We hack
6552 * the priority and make it zero.
6553 */
6554 shrink_lruvec(lruvec, &sc);
6555
6556 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6557
6558 *nr_scanned = sc.nr_scanned;
6559
6560 return sc.nr_reclaimed;
6561 }
6562
try_to_free_mem_cgroup_pages(struct mem_cgroup * memcg,unsigned long nr_pages,gfp_t gfp_mask,unsigned int reclaim_options,int * swappiness)6563 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6564 unsigned long nr_pages,
6565 gfp_t gfp_mask,
6566 unsigned int reclaim_options,
6567 int *swappiness)
6568 {
6569 unsigned long nr_reclaimed;
6570 unsigned int noreclaim_flag;
6571 struct scan_control sc = {
6572 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6573 .proactive_swappiness = swappiness,
6574 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6575 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6576 .reclaim_idx = MAX_NR_ZONES - 1,
6577 .target_mem_cgroup = memcg,
6578 .priority = DEF_PRIORITY,
6579 .may_writepage = !laptop_mode,
6580 .may_unmap = 1,
6581 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6582 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
6583 };
6584 /*
6585 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6586 * equal pressure on all the nodes. This is based on the assumption that
6587 * the reclaim does not bail out early.
6588 */
6589 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6590
6591 set_task_reclaim_state(current, &sc.reclaim_state);
6592 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6593 noreclaim_flag = memalloc_noreclaim_save();
6594
6595 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6596
6597 memalloc_noreclaim_restore(noreclaim_flag);
6598 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6599 set_task_reclaim_state(current, NULL);
6600
6601 return nr_reclaimed;
6602 }
6603 #endif
6604
kswapd_age_node(struct pglist_data * pgdat,struct scan_control * sc)6605 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6606 {
6607 struct mem_cgroup *memcg;
6608 struct lruvec *lruvec;
6609
6610 if (lru_gen_enabled()) {
6611 lru_gen_age_node(pgdat, sc);
6612 return;
6613 }
6614
6615 if (!can_age_anon_pages(pgdat, sc))
6616 return;
6617
6618 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6619 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6620 return;
6621
6622 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6623 do {
6624 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6625 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6626 sc, LRU_ACTIVE_ANON);
6627 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6628 } while (memcg);
6629 }
6630
pgdat_watermark_boosted(pg_data_t * pgdat,int highest_zoneidx)6631 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
6632 {
6633 int i;
6634 struct zone *zone;
6635
6636 /*
6637 * Check for watermark boosts top-down as the higher zones
6638 * are more likely to be boosted. Both watermarks and boosts
6639 * should not be checked at the same time as reclaim would
6640 * start prematurely when there is no boosting and a lower
6641 * zone is balanced.
6642 */
6643 for (i = highest_zoneidx; i >= 0; i--) {
6644 zone = pgdat->node_zones + i;
6645 if (!managed_zone(zone))
6646 continue;
6647
6648 if (zone->watermark_boost)
6649 return true;
6650 }
6651
6652 return false;
6653 }
6654
6655 /*
6656 * Returns true if there is an eligible zone balanced for the request order
6657 * and highest_zoneidx
6658 */
pgdat_balanced(pg_data_t * pgdat,int order,int highest_zoneidx)6659 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
6660 {
6661 int i;
6662 unsigned long mark = -1;
6663 struct zone *zone;
6664
6665 /*
6666 * Check watermarks bottom-up as lower zones are more likely to
6667 * meet watermarks.
6668 */
6669 for (i = 0; i <= highest_zoneidx; i++) {
6670 zone = pgdat->node_zones + i;
6671
6672 if (!managed_zone(zone))
6673 continue;
6674
6675 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
6676 mark = promo_wmark_pages(zone);
6677 else
6678 mark = high_wmark_pages(zone);
6679 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
6680 return true;
6681 }
6682
6683 /*
6684 * If a node has no managed zone within highest_zoneidx, it does not
6685 * need balancing by definition. This can happen if a zone-restricted
6686 * allocation tries to wake a remote kswapd.
6687 */
6688 if (mark == -1)
6689 return true;
6690
6691 return false;
6692 }
6693
6694 /* Clear pgdat state for congested, dirty or under writeback. */
clear_pgdat_congested(pg_data_t * pgdat)6695 static void clear_pgdat_congested(pg_data_t *pgdat)
6696 {
6697 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6698
6699 clear_bit(LRUVEC_NODE_CONGESTED, &lruvec->flags);
6700 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags);
6701 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6702 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6703 }
6704
6705 /*
6706 * Prepare kswapd for sleeping. This verifies that there are no processes
6707 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6708 *
6709 * Returns true if kswapd is ready to sleep
6710 */
prepare_kswapd_sleep(pg_data_t * pgdat,int order,int highest_zoneidx)6711 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6712 int highest_zoneidx)
6713 {
6714 /*
6715 * The throttled processes are normally woken up in balance_pgdat() as
6716 * soon as allow_direct_reclaim() is true. But there is a potential
6717 * race between when kswapd checks the watermarks and a process gets
6718 * throttled. There is also a potential race if processes get
6719 * throttled, kswapd wakes, a large process exits thereby balancing the
6720 * zones, which causes kswapd to exit balance_pgdat() before reaching
6721 * the wake up checks. If kswapd is going to sleep, no process should
6722 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6723 * the wake up is premature, processes will wake kswapd and get
6724 * throttled again. The difference from wake ups in balance_pgdat() is
6725 * that here we are under prepare_to_wait().
6726 */
6727 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6728 wake_up_all(&pgdat->pfmemalloc_wait);
6729
6730 /* Hopeless node, leave it to direct reclaim */
6731 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6732 return true;
6733
6734 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
6735 clear_pgdat_congested(pgdat);
6736 return true;
6737 }
6738
6739 return false;
6740 }
6741
6742 /*
6743 * kswapd shrinks a node of pages that are at or below the highest usable
6744 * zone that is currently unbalanced.
6745 *
6746 * Returns true if kswapd scanned at least the requested number of pages to
6747 * reclaim or if the lack of progress was due to pages under writeback.
6748 * This is used to determine if the scanning priority needs to be raised.
6749 */
kswapd_shrink_node(pg_data_t * pgdat,struct scan_control * sc)6750 static bool kswapd_shrink_node(pg_data_t *pgdat,
6751 struct scan_control *sc)
6752 {
6753 struct zone *zone;
6754 int z;
6755 unsigned long nr_reclaimed = sc->nr_reclaimed;
6756
6757 /* Reclaim a number of pages proportional to the number of zones */
6758 sc->nr_to_reclaim = 0;
6759 for (z = 0; z <= sc->reclaim_idx; z++) {
6760 zone = pgdat->node_zones + z;
6761 if (!managed_zone(zone))
6762 continue;
6763
6764 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6765 }
6766
6767 /*
6768 * Historically care was taken to put equal pressure on all zones but
6769 * now pressure is applied based on node LRU order.
6770 */
6771 shrink_node(pgdat, sc);
6772
6773 /*
6774 * Fragmentation may mean that the system cannot be rebalanced for
6775 * high-order allocations. If twice the allocation size has been
6776 * reclaimed then recheck watermarks only at order-0 to prevent
6777 * excessive reclaim. Assume that a process requested a high-order
6778 * can direct reclaim/compact.
6779 */
6780 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6781 sc->order = 0;
6782
6783 /* account for progress from mm_account_reclaimed_pages() */
6784 return max(sc->nr_scanned, sc->nr_reclaimed - nr_reclaimed) >= sc->nr_to_reclaim;
6785 }
6786
6787 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6788 static inline void
update_reclaim_active(pg_data_t * pgdat,int highest_zoneidx,bool active)6789 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6790 {
6791 int i;
6792 struct zone *zone;
6793
6794 for (i = 0; i <= highest_zoneidx; i++) {
6795 zone = pgdat->node_zones + i;
6796
6797 if (!managed_zone(zone))
6798 continue;
6799
6800 if (active)
6801 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6802 else
6803 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6804 }
6805 }
6806
6807 static inline void
set_reclaim_active(pg_data_t * pgdat,int highest_zoneidx)6808 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6809 {
6810 update_reclaim_active(pgdat, highest_zoneidx, true);
6811 }
6812
6813 static inline void
clear_reclaim_active(pg_data_t * pgdat,int highest_zoneidx)6814 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6815 {
6816 update_reclaim_active(pgdat, highest_zoneidx, false);
6817 }
6818
6819 /*
6820 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6821 * that are eligible for use by the caller until at least one zone is
6822 * balanced.
6823 *
6824 * Returns the order kswapd finished reclaiming at.
6825 *
6826 * kswapd scans the zones in the highmem->normal->dma direction. It skips
6827 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6828 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6829 * or lower is eligible for reclaim until at least one usable zone is
6830 * balanced.
6831 */
balance_pgdat(pg_data_t * pgdat,int order,int highest_zoneidx)6832 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
6833 {
6834 int i;
6835 unsigned long nr_soft_reclaimed;
6836 unsigned long nr_soft_scanned;
6837 unsigned long pflags;
6838 unsigned long nr_boost_reclaim;
6839 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6840 bool boosted;
6841 struct zone *zone;
6842 struct scan_control sc = {
6843 .gfp_mask = GFP_KERNEL,
6844 .order = order,
6845 .may_unmap = 1,
6846 };
6847
6848 set_task_reclaim_state(current, &sc.reclaim_state);
6849 psi_memstall_enter(&pflags);
6850 __fs_reclaim_acquire(_THIS_IP_);
6851
6852 count_vm_event(PAGEOUTRUN);
6853
6854 /*
6855 * Account for the reclaim boost. Note that the zone boost is left in
6856 * place so that parallel allocations that are near the watermark will
6857 * stall or direct reclaim until kswapd is finished.
6858 */
6859 nr_boost_reclaim = 0;
6860 for (i = 0; i <= highest_zoneidx; i++) {
6861 zone = pgdat->node_zones + i;
6862 if (!managed_zone(zone))
6863 continue;
6864
6865 nr_boost_reclaim += zone->watermark_boost;
6866 zone_boosts[i] = zone->watermark_boost;
6867 }
6868 boosted = nr_boost_reclaim;
6869
6870 restart:
6871 set_reclaim_active(pgdat, highest_zoneidx);
6872 sc.priority = DEF_PRIORITY;
6873 do {
6874 unsigned long nr_reclaimed = sc.nr_reclaimed;
6875 bool raise_priority = true;
6876 bool balanced;
6877 bool ret;
6878 bool was_frozen;
6879
6880 sc.reclaim_idx = highest_zoneidx;
6881
6882 /*
6883 * If the number of buffer_heads exceeds the maximum allowed
6884 * then consider reclaiming from all zones. This has a dual
6885 * purpose -- on 64-bit systems it is expected that
6886 * buffer_heads are stripped during active rotation. On 32-bit
6887 * systems, highmem pages can pin lowmem memory and shrinking
6888 * buffers can relieve lowmem pressure. Reclaim may still not
6889 * go ahead if all eligible zones for the original allocation
6890 * request are balanced to avoid excessive reclaim from kswapd.
6891 */
6892 if (buffer_heads_over_limit) {
6893 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6894 zone = pgdat->node_zones + i;
6895 if (!managed_zone(zone))
6896 continue;
6897
6898 sc.reclaim_idx = i;
6899 break;
6900 }
6901 }
6902
6903 /*
6904 * If the pgdat is imbalanced then ignore boosting and preserve
6905 * the watermarks for a later time and restart. Note that the
6906 * zone watermarks will be still reset at the end of balancing
6907 * on the grounds that the normal reclaim should be enough to
6908 * re-evaluate if boosting is required when kswapd next wakes.
6909 */
6910 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
6911 if (!balanced && nr_boost_reclaim) {
6912 nr_boost_reclaim = 0;
6913 goto restart;
6914 }
6915
6916 /*
6917 * If boosting is not active then only reclaim if there are no
6918 * eligible zones. Note that sc.reclaim_idx is not used as
6919 * buffer_heads_over_limit may have adjusted it.
6920 */
6921 if (!nr_boost_reclaim && balanced)
6922 goto out;
6923
6924 /* Limit the priority of boosting to avoid reclaim writeback */
6925 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6926 raise_priority = false;
6927
6928 /*
6929 * Do not writeback or swap pages for boosted reclaim. The
6930 * intent is to relieve pressure not issue sub-optimal IO
6931 * from reclaim context. If no pages are reclaimed, the
6932 * reclaim will be aborted.
6933 */
6934 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6935 sc.may_swap = !nr_boost_reclaim;
6936
6937 /*
6938 * Do some background aging, to give pages a chance to be
6939 * referenced before reclaiming. All pages are rotated
6940 * regardless of classzone as this is about consistent aging.
6941 */
6942 kswapd_age_node(pgdat, &sc);
6943
6944 /*
6945 * If we're getting trouble reclaiming, start doing writepage
6946 * even in laptop mode.
6947 */
6948 if (sc.priority < DEF_PRIORITY - 2)
6949 sc.may_writepage = 1;
6950
6951 /* Call soft limit reclaim before calling shrink_node. */
6952 sc.nr_scanned = 0;
6953 nr_soft_scanned = 0;
6954 nr_soft_reclaimed = memcg1_soft_limit_reclaim(pgdat, sc.order,
6955 sc.gfp_mask, &nr_soft_scanned);
6956 sc.nr_reclaimed += nr_soft_reclaimed;
6957
6958 /*
6959 * There should be no need to raise the scanning priority if
6960 * enough pages are already being scanned that that high
6961 * watermark would be met at 100% efficiency.
6962 */
6963 if (kswapd_shrink_node(pgdat, &sc))
6964 raise_priority = false;
6965
6966 /*
6967 * If the low watermark is met there is no need for processes
6968 * to be throttled on pfmemalloc_wait as they should not be
6969 * able to safely make forward progress. Wake them
6970 */
6971 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
6972 allow_direct_reclaim(pgdat))
6973 wake_up_all(&pgdat->pfmemalloc_wait);
6974
6975 /* Check if kswapd should be suspending */
6976 __fs_reclaim_release(_THIS_IP_);
6977 ret = kthread_freezable_should_stop(&was_frozen);
6978 __fs_reclaim_acquire(_THIS_IP_);
6979 if (was_frozen || ret)
6980 break;
6981
6982 /*
6983 * Raise priority if scanning rate is too low or there was no
6984 * progress in reclaiming pages
6985 */
6986 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
6987 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6988
6989 /*
6990 * If reclaim made no progress for a boost, stop reclaim as
6991 * IO cannot be queued and it could be an infinite loop in
6992 * extreme circumstances.
6993 */
6994 if (nr_boost_reclaim && !nr_reclaimed)
6995 break;
6996
6997 if (raise_priority || !nr_reclaimed)
6998 sc.priority--;
6999 } while (sc.priority >= 1);
7000
7001 /*
7002 * Restart only if it went through the priority loop all the way,
7003 * but cache_trim_mode didn't work.
7004 */
7005 if (!sc.nr_reclaimed && sc.priority < 1 &&
7006 !sc.no_cache_trim_mode && sc.cache_trim_mode_failed) {
7007 sc.no_cache_trim_mode = 1;
7008 goto restart;
7009 }
7010
7011 if (!sc.nr_reclaimed)
7012 pgdat->kswapd_failures++;
7013
7014 out:
7015 clear_reclaim_active(pgdat, highest_zoneidx);
7016
7017 /* If reclaim was boosted, account for the reclaim done in this pass */
7018 if (boosted) {
7019 unsigned long flags;
7020
7021 for (i = 0; i <= highest_zoneidx; i++) {
7022 if (!zone_boosts[i])
7023 continue;
7024
7025 /* Increments are under the zone lock */
7026 zone = pgdat->node_zones + i;
7027 spin_lock_irqsave(&zone->lock, flags);
7028 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7029 spin_unlock_irqrestore(&zone->lock, flags);
7030 }
7031
7032 /*
7033 * As there is now likely space, wakeup kcompact to defragment
7034 * pageblocks.
7035 */
7036 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7037 }
7038
7039 snapshot_refaults(NULL, pgdat);
7040 __fs_reclaim_release(_THIS_IP_);
7041 psi_memstall_leave(&pflags);
7042 set_task_reclaim_state(current, NULL);
7043
7044 /*
7045 * Return the order kswapd stopped reclaiming at as
7046 * prepare_kswapd_sleep() takes it into account. If another caller
7047 * entered the allocator slow path while kswapd was awake, order will
7048 * remain at the higher level.
7049 */
7050 return sc.order;
7051 }
7052
7053 /*
7054 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7055 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7056 * not a valid index then either kswapd runs for first time or kswapd couldn't
7057 * sleep after previous reclaim attempt (node is still unbalanced). In that
7058 * case return the zone index of the previous kswapd reclaim cycle.
7059 */
kswapd_highest_zoneidx(pg_data_t * pgdat,enum zone_type prev_highest_zoneidx)7060 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7061 enum zone_type prev_highest_zoneidx)
7062 {
7063 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7064
7065 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7066 }
7067
kswapd_try_to_sleep(pg_data_t * pgdat,int alloc_order,int reclaim_order,unsigned int highest_zoneidx)7068 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7069 unsigned int highest_zoneidx)
7070 {
7071 long remaining = 0;
7072 DEFINE_WAIT(wait);
7073
7074 if (freezing(current) || kthread_should_stop())
7075 return;
7076
7077 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7078
7079 /*
7080 * Try to sleep for a short interval. Note that kcompactd will only be
7081 * woken if it is possible to sleep for a short interval. This is
7082 * deliberate on the assumption that if reclaim cannot keep an
7083 * eligible zone balanced that it's also unlikely that compaction will
7084 * succeed.
7085 */
7086 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7087 /*
7088 * Compaction records what page blocks it recently failed to
7089 * isolate pages from and skips them in the future scanning.
7090 * When kswapd is going to sleep, it is reasonable to assume
7091 * that pages and compaction may succeed so reset the cache.
7092 */
7093 reset_isolation_suitable(pgdat);
7094
7095 /*
7096 * We have freed the memory, now we should compact it to make
7097 * allocation of the requested order possible.
7098 */
7099 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7100
7101 remaining = schedule_timeout(HZ/10);
7102
7103 /*
7104 * If woken prematurely then reset kswapd_highest_zoneidx and
7105 * order. The values will either be from a wakeup request or
7106 * the previous request that slept prematurely.
7107 */
7108 if (remaining) {
7109 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7110 kswapd_highest_zoneidx(pgdat,
7111 highest_zoneidx));
7112
7113 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7114 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7115 }
7116
7117 finish_wait(&pgdat->kswapd_wait, &wait);
7118 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7119 }
7120
7121 /*
7122 * After a short sleep, check if it was a premature sleep. If not, then
7123 * go fully to sleep until explicitly woken up.
7124 */
7125 if (!remaining &&
7126 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7127 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7128
7129 /*
7130 * vmstat counters are not perfectly accurate and the estimated
7131 * value for counters such as NR_FREE_PAGES can deviate from the
7132 * true value by nr_online_cpus * threshold. To avoid the zone
7133 * watermarks being breached while under pressure, we reduce the
7134 * per-cpu vmstat threshold while kswapd is awake and restore
7135 * them before going back to sleep.
7136 */
7137 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7138
7139 if (!kthread_should_stop())
7140 schedule();
7141
7142 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7143 } else {
7144 if (remaining)
7145 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7146 else
7147 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7148 }
7149 finish_wait(&pgdat->kswapd_wait, &wait);
7150 }
7151
7152 /*
7153 * The background pageout daemon, started as a kernel thread
7154 * from the init process.
7155 *
7156 * This basically trickles out pages so that we have _some_
7157 * free memory available even if there is no other activity
7158 * that frees anything up. This is needed for things like routing
7159 * etc, where we otherwise might have all activity going on in
7160 * asynchronous contexts that cannot page things out.
7161 *
7162 * If there are applications that are active memory-allocators
7163 * (most normal use), this basically shouldn't matter.
7164 */
kswapd(void * p)7165 static int kswapd(void *p)
7166 {
7167 unsigned int alloc_order, reclaim_order;
7168 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7169 pg_data_t *pgdat = (pg_data_t *)p;
7170 struct task_struct *tsk = current;
7171 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7172
7173 if (!cpumask_empty(cpumask))
7174 set_cpus_allowed_ptr(tsk, cpumask);
7175
7176 /*
7177 * Tell the memory management that we're a "memory allocator",
7178 * and that if we need more memory we should get access to it
7179 * regardless (see "__alloc_pages()"). "kswapd" should
7180 * never get caught in the normal page freeing logic.
7181 *
7182 * (Kswapd normally doesn't need memory anyway, but sometimes
7183 * you need a small amount of memory in order to be able to
7184 * page out something else, and this flag essentially protects
7185 * us from recursively trying to free more memory as we're
7186 * trying to free the first piece of memory in the first place).
7187 */
7188 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7189 set_freezable();
7190
7191 WRITE_ONCE(pgdat->kswapd_order, 0);
7192 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7193 atomic_set(&pgdat->nr_writeback_throttled, 0);
7194 for ( ; ; ) {
7195 bool was_frozen;
7196
7197 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7198 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7199 highest_zoneidx);
7200
7201 kswapd_try_sleep:
7202 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7203 highest_zoneidx);
7204
7205 /* Read the new order and highest_zoneidx */
7206 alloc_order = READ_ONCE(pgdat->kswapd_order);
7207 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7208 highest_zoneidx);
7209 WRITE_ONCE(pgdat->kswapd_order, 0);
7210 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7211
7212 if (kthread_freezable_should_stop(&was_frozen))
7213 break;
7214
7215 /*
7216 * We can speed up thawing tasks if we don't call balance_pgdat
7217 * after returning from the refrigerator
7218 */
7219 if (was_frozen)
7220 continue;
7221
7222 /*
7223 * Reclaim begins at the requested order but if a high-order
7224 * reclaim fails then kswapd falls back to reclaiming for
7225 * order-0. If that happens, kswapd will consider sleeping
7226 * for the order it finished reclaiming at (reclaim_order)
7227 * but kcompactd is woken to compact for the original
7228 * request (alloc_order).
7229 */
7230 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7231 alloc_order);
7232 reclaim_order = balance_pgdat(pgdat, alloc_order,
7233 highest_zoneidx);
7234 if (reclaim_order < alloc_order)
7235 goto kswapd_try_sleep;
7236 }
7237
7238 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7239
7240 return 0;
7241 }
7242
7243 /*
7244 * A zone is low on free memory or too fragmented for high-order memory. If
7245 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7246 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7247 * has failed or is not needed, still wake up kcompactd if only compaction is
7248 * needed.
7249 */
wakeup_kswapd(struct zone * zone,gfp_t gfp_flags,int order,enum zone_type highest_zoneidx)7250 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7251 enum zone_type highest_zoneidx)
7252 {
7253 pg_data_t *pgdat;
7254 enum zone_type curr_idx;
7255
7256 if (!managed_zone(zone))
7257 return;
7258
7259 if (!cpuset_zone_allowed(zone, gfp_flags))
7260 return;
7261
7262 pgdat = zone->zone_pgdat;
7263 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7264
7265 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7266 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7267
7268 if (READ_ONCE(pgdat->kswapd_order) < order)
7269 WRITE_ONCE(pgdat->kswapd_order, order);
7270
7271 if (!waitqueue_active(&pgdat->kswapd_wait))
7272 return;
7273
7274 /* Hopeless node, leave it to direct reclaim if possible */
7275 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7276 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7277 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7278 /*
7279 * There may be plenty of free memory available, but it's too
7280 * fragmented for high-order allocations. Wake up kcompactd
7281 * and rely on compaction_suitable() to determine if it's
7282 * needed. If it fails, it will defer subsequent attempts to
7283 * ratelimit its work.
7284 */
7285 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7286 wakeup_kcompactd(pgdat, order, highest_zoneidx);
7287 return;
7288 }
7289
7290 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7291 gfp_flags);
7292 wake_up_interruptible(&pgdat->kswapd_wait);
7293 }
7294
7295 #ifdef CONFIG_HIBERNATION
7296 /*
7297 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7298 * freed pages.
7299 *
7300 * Rather than trying to age LRUs the aim is to preserve the overall
7301 * LRU order by reclaiming preferentially
7302 * inactive > active > active referenced > active mapped
7303 */
shrink_all_memory(unsigned long nr_to_reclaim)7304 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7305 {
7306 struct scan_control sc = {
7307 .nr_to_reclaim = nr_to_reclaim,
7308 .gfp_mask = GFP_HIGHUSER_MOVABLE,
7309 .reclaim_idx = MAX_NR_ZONES - 1,
7310 .priority = DEF_PRIORITY,
7311 .may_writepage = 1,
7312 .may_unmap = 1,
7313 .may_swap = 1,
7314 .hibernation_mode = 1,
7315 };
7316 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7317 unsigned long nr_reclaimed;
7318 unsigned int noreclaim_flag;
7319
7320 fs_reclaim_acquire(sc.gfp_mask);
7321 noreclaim_flag = memalloc_noreclaim_save();
7322 set_task_reclaim_state(current, &sc.reclaim_state);
7323
7324 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7325
7326 set_task_reclaim_state(current, NULL);
7327 memalloc_noreclaim_restore(noreclaim_flag);
7328 fs_reclaim_release(sc.gfp_mask);
7329
7330 return nr_reclaimed;
7331 }
7332 #endif /* CONFIG_HIBERNATION */
7333
7334 /*
7335 * This kswapd start function will be called by init and node-hot-add.
7336 */
kswapd_run(int nid)7337 void __meminit kswapd_run(int nid)
7338 {
7339 pg_data_t *pgdat = NODE_DATA(nid);
7340
7341 pgdat_kswapd_lock(pgdat);
7342 if (!pgdat->kswapd) {
7343 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7344 if (IS_ERR(pgdat->kswapd)) {
7345 /* failure at boot is fatal */
7346 pr_err("Failed to start kswapd on node %d,ret=%ld\n",
7347 nid, PTR_ERR(pgdat->kswapd));
7348 BUG_ON(system_state < SYSTEM_RUNNING);
7349 pgdat->kswapd = NULL;
7350 }
7351 }
7352 pgdat_kswapd_unlock(pgdat);
7353 }
7354
7355 /*
7356 * Called by memory hotplug when all memory in a node is offlined. Caller must
7357 * be holding mem_hotplug_begin/done().
7358 */
kswapd_stop(int nid)7359 void __meminit kswapd_stop(int nid)
7360 {
7361 pg_data_t *pgdat = NODE_DATA(nid);
7362 struct task_struct *kswapd;
7363
7364 pgdat_kswapd_lock(pgdat);
7365 kswapd = pgdat->kswapd;
7366 if (kswapd) {
7367 kthread_stop(kswapd);
7368 pgdat->kswapd = NULL;
7369 }
7370 pgdat_kswapd_unlock(pgdat);
7371 }
7372
kswapd_init(void)7373 static int __init kswapd_init(void)
7374 {
7375 int nid;
7376
7377 swap_setup();
7378 for_each_node_state(nid, N_MEMORY)
7379 kswapd_run(nid);
7380 return 0;
7381 }
7382
7383 module_init(kswapd_init)
7384
7385 #ifdef CONFIG_NUMA
7386 /*
7387 * Node reclaim mode
7388 *
7389 * If non-zero call node_reclaim when the number of free pages falls below
7390 * the watermarks.
7391 */
7392 int node_reclaim_mode __read_mostly;
7393
7394 /*
7395 * Priority for NODE_RECLAIM. This determines the fraction of pages
7396 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7397 * a zone.
7398 */
7399 #define NODE_RECLAIM_PRIORITY 4
7400
7401 /*
7402 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7403 * occur.
7404 */
7405 int sysctl_min_unmapped_ratio = 1;
7406
7407 /*
7408 * If the number of slab pages in a zone grows beyond this percentage then
7409 * slab reclaim needs to occur.
7410 */
7411 int sysctl_min_slab_ratio = 5;
7412
node_unmapped_file_pages(struct pglist_data * pgdat)7413 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7414 {
7415 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7416 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7417 node_page_state(pgdat, NR_ACTIVE_FILE);
7418
7419 /*
7420 * It's possible for there to be more file mapped pages than
7421 * accounted for by the pages on the file LRU lists because
7422 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7423 */
7424 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7425 }
7426
7427 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
node_pagecache_reclaimable(struct pglist_data * pgdat)7428 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7429 {
7430 unsigned long nr_pagecache_reclaimable;
7431 unsigned long delta = 0;
7432
7433 /*
7434 * If RECLAIM_UNMAP is set, then all file pages are considered
7435 * potentially reclaimable. Otherwise, we have to worry about
7436 * pages like swapcache and node_unmapped_file_pages() provides
7437 * a better estimate
7438 */
7439 if (node_reclaim_mode & RECLAIM_UNMAP)
7440 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7441 else
7442 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7443
7444 /* If we can't clean pages, remove dirty pages from consideration */
7445 if (!(node_reclaim_mode & RECLAIM_WRITE))
7446 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7447
7448 /* Watch for any possible underflows due to delta */
7449 if (unlikely(delta > nr_pagecache_reclaimable))
7450 delta = nr_pagecache_reclaimable;
7451
7452 return nr_pagecache_reclaimable - delta;
7453 }
7454
7455 /*
7456 * Try to free up some pages from this node through reclaim.
7457 */
__node_reclaim(struct pglist_data * pgdat,gfp_t gfp_mask,unsigned int order)7458 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7459 {
7460 /* Minimum pages needed in order to stay on node */
7461 const unsigned long nr_pages = 1 << order;
7462 struct task_struct *p = current;
7463 unsigned int noreclaim_flag;
7464 struct scan_control sc = {
7465 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7466 .gfp_mask = current_gfp_context(gfp_mask),
7467 .order = order,
7468 .priority = NODE_RECLAIM_PRIORITY,
7469 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7470 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7471 .may_swap = 1,
7472 .reclaim_idx = gfp_zone(gfp_mask),
7473 };
7474 unsigned long pflags;
7475
7476 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7477 sc.gfp_mask);
7478
7479 cond_resched();
7480 psi_memstall_enter(&pflags);
7481 delayacct_freepages_start();
7482 fs_reclaim_acquire(sc.gfp_mask);
7483 /*
7484 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7485 */
7486 noreclaim_flag = memalloc_noreclaim_save();
7487 set_task_reclaim_state(p, &sc.reclaim_state);
7488
7489 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7490 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7491 /*
7492 * Free memory by calling shrink node with increasing
7493 * priorities until we have enough memory freed.
7494 */
7495 do {
7496 shrink_node(pgdat, &sc);
7497 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7498 }
7499
7500 set_task_reclaim_state(p, NULL);
7501 memalloc_noreclaim_restore(noreclaim_flag);
7502 fs_reclaim_release(sc.gfp_mask);
7503 psi_memstall_leave(&pflags);
7504 delayacct_freepages_end();
7505
7506 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7507
7508 return sc.nr_reclaimed >= nr_pages;
7509 }
7510
node_reclaim(struct pglist_data * pgdat,gfp_t gfp_mask,unsigned int order)7511 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7512 {
7513 int ret;
7514
7515 /*
7516 * Node reclaim reclaims unmapped file backed pages and
7517 * slab pages if we are over the defined limits.
7518 *
7519 * A small portion of unmapped file backed pages is needed for
7520 * file I/O otherwise pages read by file I/O will be immediately
7521 * thrown out if the node is overallocated. So we do not reclaim
7522 * if less than a specified percentage of the node is used by
7523 * unmapped file backed pages.
7524 */
7525 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7526 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7527 pgdat->min_slab_pages)
7528 return NODE_RECLAIM_FULL;
7529
7530 /*
7531 * Do not scan if the allocation should not be delayed.
7532 */
7533 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7534 return NODE_RECLAIM_NOSCAN;
7535
7536 /*
7537 * Only run node reclaim on the local node or on nodes that do not
7538 * have associated processors. This will favor the local processor
7539 * over remote processors and spread off node memory allocations
7540 * as wide as possible.
7541 */
7542 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7543 return NODE_RECLAIM_NOSCAN;
7544
7545 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7546 return NODE_RECLAIM_NOSCAN;
7547
7548 ret = __node_reclaim(pgdat, gfp_mask, order);
7549 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7550
7551 if (ret)
7552 count_vm_event(PGSCAN_ZONE_RECLAIM_SUCCESS);
7553 else
7554 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7555
7556 return ret;
7557 }
7558 #endif
7559
7560 /**
7561 * check_move_unevictable_folios - Move evictable folios to appropriate zone
7562 * lru list
7563 * @fbatch: Batch of lru folios to check.
7564 *
7565 * Checks folios for evictability, if an evictable folio is in the unevictable
7566 * lru list, moves it to the appropriate evictable lru list. This function
7567 * should be only used for lru folios.
7568 */
check_move_unevictable_folios(struct folio_batch * fbatch)7569 void check_move_unevictable_folios(struct folio_batch *fbatch)
7570 {
7571 struct lruvec *lruvec = NULL;
7572 int pgscanned = 0;
7573 int pgrescued = 0;
7574 int i;
7575
7576 for (i = 0; i < fbatch->nr; i++) {
7577 struct folio *folio = fbatch->folios[i];
7578 int nr_pages = folio_nr_pages(folio);
7579
7580 pgscanned += nr_pages;
7581
7582 /* block memcg migration while the folio moves between lrus */
7583 if (!folio_test_clear_lru(folio))
7584 continue;
7585
7586 lruvec = folio_lruvec_relock_irq(folio, lruvec);
7587 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
7588 lruvec_del_folio(lruvec, folio);
7589 folio_clear_unevictable(folio);
7590 lruvec_add_folio(lruvec, folio);
7591 pgrescued += nr_pages;
7592 }
7593 folio_set_lru(folio);
7594 }
7595
7596 if (lruvec) {
7597 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7598 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7599 unlock_page_lruvec_irq(lruvec);
7600 } else if (pgscanned) {
7601 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7602 }
7603 }
7604 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);
7605