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