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