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