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