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