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