GNU Linux-libre 6.4.15-gnu
[releases.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                 .walk_lock = PGWALK_RDLOCK,
4253         };
4254
4255         int err;
4256         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4257
4258         walk->next_addr = FIRST_USER_ADDRESS;
4259
4260         do {
4261                 DEFINE_MAX_SEQ(lruvec);
4262
4263                 err = -EBUSY;
4264
4265                 /* another thread might have called inc_max_seq() */
4266                 if (walk->max_seq != max_seq)
4267                         break;
4268
4269                 /* folio_update_gen() requires stable folio_memcg() */
4270                 if (!mem_cgroup_trylock_pages(memcg))
4271                         break;
4272
4273                 /* the caller might be holding the lock for write */
4274                 if (mmap_read_trylock(mm)) {
4275                         err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4276
4277                         mmap_read_unlock(mm);
4278                 }
4279
4280                 mem_cgroup_unlock_pages();
4281
4282                 if (walk->batched) {
4283                         spin_lock_irq(&lruvec->lru_lock);
4284                         reset_batch_size(lruvec, walk);
4285                         spin_unlock_irq(&lruvec->lru_lock);
4286                 }
4287
4288                 cond_resched();
4289         } while (err == -EAGAIN);
4290 }
4291
4292 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
4293 {
4294         struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4295
4296         if (pgdat && current_is_kswapd()) {
4297                 VM_WARN_ON_ONCE(walk);
4298
4299                 walk = &pgdat->mm_walk;
4300         } else if (!walk && force_alloc) {
4301                 VM_WARN_ON_ONCE(current_is_kswapd());
4302
4303                 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4304         }
4305
4306         current->reclaim_state->mm_walk = walk;
4307
4308         return walk;
4309 }
4310
4311 static void clear_mm_walk(void)
4312 {
4313         struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4314
4315         VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4316         VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4317
4318         current->reclaim_state->mm_walk = NULL;
4319
4320         if (!current_is_kswapd())
4321                 kfree(walk);
4322 }
4323
4324 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
4325 {
4326         int zone;
4327         int remaining = MAX_LRU_BATCH;
4328         struct lru_gen_folio *lrugen = &lruvec->lrugen;
4329         int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4330
4331         if (type == LRU_GEN_ANON && !can_swap)
4332                 goto done;
4333
4334         /* prevent cold/hot inversion if force_scan is true */
4335         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4336                 struct list_head *head = &lrugen->folios[old_gen][type][zone];
4337
4338                 while (!list_empty(head)) {
4339                         struct folio *folio = lru_to_folio(head);
4340
4341                         VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4342                         VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4343                         VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4344                         VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4345
4346                         new_gen = folio_inc_gen(lruvec, folio, false);
4347                         list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
4348
4349                         if (!--remaining)
4350                                 return false;
4351                 }
4352         }
4353 done:
4354         reset_ctrl_pos(lruvec, type, true);
4355         WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4356
4357         return true;
4358 }
4359
4360 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4361 {
4362         int gen, type, zone;
4363         bool success = false;
4364         struct lru_gen_folio *lrugen = &lruvec->lrugen;
4365         DEFINE_MIN_SEQ(lruvec);
4366
4367         VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4368
4369         /* find the oldest populated generation */
4370         for (type = !can_swap; type < ANON_AND_FILE; type++) {
4371                 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4372                         gen = lru_gen_from_seq(min_seq[type]);
4373
4374                         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4375                                 if (!list_empty(&lrugen->folios[gen][type][zone]))
4376                                         goto next;
4377                         }
4378
4379                         min_seq[type]++;
4380                 }
4381 next:
4382                 ;
4383         }
4384
4385         /* see the comment on lru_gen_folio */
4386         if (can_swap) {
4387                 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4388                 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4389         }
4390
4391         for (type = !can_swap; type < ANON_AND_FILE; type++) {
4392                 if (min_seq[type] == lrugen->min_seq[type])
4393                         continue;
4394
4395                 reset_ctrl_pos(lruvec, type, true);
4396                 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4397                 success = true;
4398         }
4399
4400         return success;
4401 }
4402
4403 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
4404 {
4405         int prev, next;
4406         int type, zone;
4407         struct lru_gen_folio *lrugen = &lruvec->lrugen;
4408
4409         spin_lock_irq(&lruvec->lru_lock);
4410
4411         VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4412
4413         for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4414                 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4415                         continue;
4416
4417                 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
4418
4419                 while (!inc_min_seq(lruvec, type, can_swap)) {
4420                         spin_unlock_irq(&lruvec->lru_lock);
4421                         cond_resched();
4422                         spin_lock_irq(&lruvec->lru_lock);
4423                 }
4424         }
4425
4426         /*
4427          * Update the active/inactive LRU sizes for compatibility. Both sides of
4428          * the current max_seq need to be covered, since max_seq+1 can overlap
4429          * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4430          * overlap, cold/hot inversion happens.
4431          */
4432         prev = lru_gen_from_seq(lrugen->max_seq - 1);
4433         next = lru_gen_from_seq(lrugen->max_seq + 1);
4434
4435         for (type = 0; type < ANON_AND_FILE; type++) {
4436                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4437                         enum lru_list lru = type * LRU_INACTIVE_FILE;
4438                         long delta = lrugen->nr_pages[prev][type][zone] -
4439                                      lrugen->nr_pages[next][type][zone];
4440
4441                         if (!delta)
4442                                 continue;
4443
4444                         __update_lru_size(lruvec, lru, zone, delta);
4445                         __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4446                 }
4447         }
4448
4449         for (type = 0; type < ANON_AND_FILE; type++)
4450                 reset_ctrl_pos(lruvec, type, false);
4451
4452         WRITE_ONCE(lrugen->timestamps[next], jiffies);
4453         /* make sure preceding modifications appear */
4454         smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4455
4456         spin_unlock_irq(&lruvec->lru_lock);
4457 }
4458
4459 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4460                                struct scan_control *sc, bool can_swap, bool force_scan)
4461 {
4462         bool success;
4463         struct lru_gen_mm_walk *walk;
4464         struct mm_struct *mm = NULL;
4465         struct lru_gen_folio *lrugen = &lruvec->lrugen;
4466
4467         VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4468
4469         /* see the comment in iterate_mm_list() */
4470         if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4471                 success = false;
4472                 goto done;
4473         }
4474
4475         /*
4476          * If the hardware doesn't automatically set the accessed bit, fallback
4477          * to lru_gen_look_around(), which only clears the accessed bit in a
4478          * handful of PTEs. Spreading the work out over a period of time usually
4479          * is less efficient, but it avoids bursty page faults.
4480          */
4481         if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
4482                 success = iterate_mm_list_nowalk(lruvec, max_seq);
4483                 goto done;
4484         }
4485
4486         walk = set_mm_walk(NULL, true);
4487         if (!walk) {
4488                 success = iterate_mm_list_nowalk(lruvec, max_seq);
4489                 goto done;
4490         }
4491
4492         walk->lruvec = lruvec;
4493         walk->max_seq = max_seq;
4494         walk->can_swap = can_swap;
4495         walk->force_scan = force_scan;
4496
4497         do {
4498                 success = iterate_mm_list(lruvec, walk, &mm);
4499                 if (mm)
4500                         walk_mm(lruvec, mm, walk);
4501         } while (mm);
4502 done:
4503         if (success)
4504                 inc_max_seq(lruvec, can_swap, force_scan);
4505
4506         return success;
4507 }
4508
4509 /******************************************************************************
4510  *                          working set protection
4511  ******************************************************************************/
4512
4513 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
4514 {
4515         int gen, type, zone;
4516         unsigned long total = 0;
4517         bool can_swap = get_swappiness(lruvec, sc);
4518         struct lru_gen_folio *lrugen = &lruvec->lrugen;
4519         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4520         DEFINE_MAX_SEQ(lruvec);
4521         DEFINE_MIN_SEQ(lruvec);
4522
4523         for (type = !can_swap; type < ANON_AND_FILE; type++) {
4524                 unsigned long seq;
4525
4526                 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4527                         gen = lru_gen_from_seq(seq);
4528
4529                         for (zone = 0; zone < MAX_NR_ZONES; zone++)
4530                                 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4531                 }
4532         }
4533
4534         /* whether the size is big enough to be helpful */
4535         return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4536 }
4537
4538 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4539                                   unsigned long min_ttl)
4540 {
4541         int gen;
4542         unsigned long birth;
4543         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4544         DEFINE_MIN_SEQ(lruvec);
4545
4546         /* see the comment on lru_gen_folio */
4547         gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4548         birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4549
4550         if (time_is_after_jiffies(birth + min_ttl))
4551                 return false;
4552
4553         if (!lruvec_is_sizable(lruvec, sc))
4554                 return false;
4555
4556         mem_cgroup_calculate_protection(NULL, memcg);
4557
4558         return !mem_cgroup_below_min(NULL, memcg);
4559 }
4560
4561 /* to protect the working set of the last N jiffies */
4562 static unsigned long lru_gen_min_ttl __read_mostly;
4563
4564 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4565 {
4566         struct mem_cgroup *memcg;
4567         unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4568
4569         VM_WARN_ON_ONCE(!current_is_kswapd());
4570
4571         /* check the order to exclude compaction-induced reclaim */
4572         if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
4573                 return;
4574
4575         memcg = mem_cgroup_iter(NULL, NULL, NULL);
4576         do {
4577                 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4578
4579                 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4580                         mem_cgroup_iter_break(NULL, memcg);
4581                         return;
4582                 }
4583
4584                 cond_resched();
4585         } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4586
4587         /*
4588          * The main goal is to OOM kill if every generation from all memcgs is
4589          * younger than min_ttl. However, another possibility is all memcgs are
4590          * either too small or below min.
4591          */
4592         if (mutex_trylock(&oom_lock)) {
4593                 struct oom_control oc = {
4594                         .gfp_mask = sc->gfp_mask,
4595                 };
4596
4597                 out_of_memory(&oc);
4598
4599                 mutex_unlock(&oom_lock);
4600         }
4601 }
4602
4603 /******************************************************************************
4604  *                          rmap/PT walk feedback
4605  ******************************************************************************/
4606
4607 /*
4608  * This function exploits spatial locality when shrink_folio_list() walks the
4609  * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4610  * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4611  * the PTE table to the Bloom filter. This forms a feedback loop between the
4612  * eviction and the aging.
4613  */
4614 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4615 {
4616         int i;
4617         unsigned long start;
4618         unsigned long end;
4619         struct lru_gen_mm_walk *walk;
4620         int young = 0;
4621         pte_t *pte = pvmw->pte;
4622         unsigned long addr = pvmw->address;
4623         struct folio *folio = pfn_folio(pvmw->pfn);
4624         struct mem_cgroup *memcg = folio_memcg(folio);
4625         struct pglist_data *pgdat = folio_pgdat(folio);
4626         struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4627         DEFINE_MAX_SEQ(lruvec);
4628         int old_gen, new_gen = lru_gen_from_seq(max_seq);
4629
4630         lockdep_assert_held(pvmw->ptl);
4631         VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4632
4633         if (spin_is_contended(pvmw->ptl))
4634                 return;
4635
4636         /* avoid taking the LRU lock under the PTL when possible */
4637         walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4638
4639         start = max(addr & PMD_MASK, pvmw->vma->vm_start);
4640         end = min(addr | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4641
4642         if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4643                 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4644                         end = start + MIN_LRU_BATCH * PAGE_SIZE;
4645                 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
4646                         start = end - MIN_LRU_BATCH * PAGE_SIZE;
4647                 else {
4648                         start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
4649                         end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
4650                 }
4651         }
4652
4653         /* folio_update_gen() requires stable folio_memcg() */
4654         if (!mem_cgroup_trylock_pages(memcg))
4655                 return;
4656
4657         arch_enter_lazy_mmu_mode();
4658
4659         pte -= (addr - start) / PAGE_SIZE;
4660
4661         for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4662                 unsigned long pfn;
4663
4664                 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4665                 if (pfn == -1)
4666                         continue;
4667
4668                 if (!pte_young(pte[i]))
4669                         continue;
4670
4671                 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
4672                 if (!folio)
4673                         continue;
4674
4675                 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4676                         VM_WARN_ON_ONCE(true);
4677
4678                 young++;
4679
4680                 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4681                     !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4682                       !folio_test_swapcache(folio)))
4683                         folio_mark_dirty(folio);
4684
4685                 if (walk) {
4686                         old_gen = folio_update_gen(folio, new_gen);
4687                         if (old_gen >= 0 && old_gen != new_gen)
4688                                 update_batch_size(walk, folio, old_gen, new_gen);
4689
4690                         continue;
4691                 }
4692
4693                 old_gen = folio_lru_gen(folio);
4694                 if (old_gen < 0)
4695                         folio_set_referenced(folio);
4696                 else if (old_gen != new_gen)
4697                         folio_activate(folio);
4698         }
4699
4700         arch_leave_lazy_mmu_mode();
4701         mem_cgroup_unlock_pages();
4702
4703         /* feedback from rmap walkers to page table walkers */
4704         if (suitable_to_scan(i, young))
4705                 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4706 }
4707
4708 /******************************************************************************
4709  *                          memcg LRU
4710  ******************************************************************************/
4711
4712 /* see the comment on MEMCG_NR_GENS */
4713 enum {
4714         MEMCG_LRU_NOP,
4715         MEMCG_LRU_HEAD,
4716         MEMCG_LRU_TAIL,
4717         MEMCG_LRU_OLD,
4718         MEMCG_LRU_YOUNG,
4719 };
4720
4721 #ifdef CONFIG_MEMCG
4722
4723 static int lru_gen_memcg_seg(struct lruvec *lruvec)
4724 {
4725         return READ_ONCE(lruvec->lrugen.seg);
4726 }
4727
4728 static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
4729 {
4730         int seg;
4731         int old, new;
4732         unsigned long flags;
4733         int bin = get_random_u32_below(MEMCG_NR_BINS);
4734         struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4735
4736         spin_lock_irqsave(&pgdat->memcg_lru.lock, flags);
4737
4738         VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4739
4740         seg = 0;
4741         new = old = lruvec->lrugen.gen;
4742
4743         /* see the comment on MEMCG_NR_GENS */
4744         if (op == MEMCG_LRU_HEAD)
4745                 seg = MEMCG_LRU_HEAD;
4746         else if (op == MEMCG_LRU_TAIL)
4747                 seg = MEMCG_LRU_TAIL;
4748         else if (op == MEMCG_LRU_OLD)
4749                 new = get_memcg_gen(pgdat->memcg_lru.seq);
4750         else if (op == MEMCG_LRU_YOUNG)
4751                 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
4752         else
4753                 VM_WARN_ON_ONCE(true);
4754
4755         hlist_nulls_del_rcu(&lruvec->lrugen.list);
4756
4757         if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
4758                 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4759         else
4760                 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4761
4762         pgdat->memcg_lru.nr_memcgs[old]--;
4763         pgdat->memcg_lru.nr_memcgs[new]++;
4764
4765         lruvec->lrugen.gen = new;
4766         WRITE_ONCE(lruvec->lrugen.seg, seg);
4767
4768         if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
4769                 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4770
4771         spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags);
4772 }
4773
4774 void lru_gen_online_memcg(struct mem_cgroup *memcg)
4775 {
4776         int gen;
4777         int nid;
4778         int bin = get_random_u32_below(MEMCG_NR_BINS);
4779
4780         for_each_node(nid) {
4781                 struct pglist_data *pgdat = NODE_DATA(nid);
4782                 struct lruvec *lruvec = get_lruvec(memcg, nid);
4783
4784                 spin_lock_irq(&pgdat->memcg_lru.lock);
4785
4786                 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
4787
4788                 gen = get_memcg_gen(pgdat->memcg_lru.seq);
4789
4790                 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
4791                 pgdat->memcg_lru.nr_memcgs[gen]++;
4792
4793                 lruvec->lrugen.gen = gen;
4794
4795                 spin_unlock_irq(&pgdat->memcg_lru.lock);
4796         }
4797 }
4798
4799 void lru_gen_offline_memcg(struct mem_cgroup *memcg)
4800 {
4801         int nid;
4802
4803         for_each_node(nid) {
4804                 struct lruvec *lruvec = get_lruvec(memcg, nid);
4805
4806                 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
4807         }
4808 }
4809
4810 void lru_gen_release_memcg(struct mem_cgroup *memcg)
4811 {
4812         int gen;
4813         int nid;
4814
4815         for_each_node(nid) {
4816                 struct pglist_data *pgdat = NODE_DATA(nid);
4817                 struct lruvec *lruvec = get_lruvec(memcg, nid);
4818
4819                 spin_lock_irq(&pgdat->memcg_lru.lock);
4820
4821                 if (hlist_nulls_unhashed(&lruvec->lrugen.list))
4822                         goto unlock;
4823
4824                 gen = lruvec->lrugen.gen;
4825
4826                 hlist_nulls_del_init_rcu(&lruvec->lrugen.list);
4827                 pgdat->memcg_lru.nr_memcgs[gen]--;
4828
4829                 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
4830                         WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4831 unlock:
4832                 spin_unlock_irq(&pgdat->memcg_lru.lock);
4833         }
4834 }
4835
4836 void lru_gen_soft_reclaim(struct lruvec *lruvec)
4837 {
4838         /* see the comment on MEMCG_NR_GENS */
4839         if (lru_gen_memcg_seg(lruvec) != MEMCG_LRU_HEAD)
4840                 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
4841 }
4842
4843 #else /* !CONFIG_MEMCG */
4844
4845 static int lru_gen_memcg_seg(struct lruvec *lruvec)
4846 {
4847         return 0;
4848 }
4849
4850 #endif
4851
4852 /******************************************************************************
4853  *                          the eviction
4854  ******************************************************************************/
4855
4856 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4857 {
4858         bool success;
4859         int gen = folio_lru_gen(folio);
4860         int type = folio_is_file_lru(folio);
4861         int zone = folio_zonenum(folio);
4862         int delta = folio_nr_pages(folio);
4863         int refs = folio_lru_refs(folio);
4864         int tier = lru_tier_from_refs(refs);
4865         struct lru_gen_folio *lrugen = &lruvec->lrugen;
4866
4867         VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4868
4869         /* unevictable */
4870         if (!folio_evictable(folio)) {
4871                 success = lru_gen_del_folio(lruvec, folio, true);
4872                 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4873                 folio_set_unevictable(folio);
4874                 lruvec_add_folio(lruvec, folio);
4875                 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4876                 return true;
4877         }
4878
4879         /* dirty lazyfree */
4880         if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4881                 success = lru_gen_del_folio(lruvec, folio, true);
4882                 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4883                 folio_set_swapbacked(folio);
4884                 lruvec_add_folio_tail(lruvec, folio);
4885                 return true;
4886         }
4887
4888         /* promoted */
4889         if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4890                 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4891                 return true;
4892         }
4893
4894         /* protected */
4895         if (tier > tier_idx) {
4896                 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4897
4898                 gen = folio_inc_gen(lruvec, folio, false);
4899                 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4900
4901                 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4902                            lrugen->protected[hist][type][tier - 1] + delta);
4903                 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4904                 return true;
4905         }
4906
4907         /* waiting for writeback */
4908         if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4909             (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4910                 gen = folio_inc_gen(lruvec, folio, true);
4911                 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4912                 return true;
4913         }
4914
4915         return false;
4916 }
4917
4918 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4919 {
4920         bool success;
4921
4922         /* swapping inhibited */
4923         if (!(sc->gfp_mask & __GFP_IO) &&
4924             (folio_test_dirty(folio) ||
4925              (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4926                 return false;
4927
4928         /* raced with release_pages() */
4929         if (!folio_try_get(folio))
4930                 return false;
4931
4932         /* raced with another isolation */
4933         if (!folio_test_clear_lru(folio)) {
4934                 folio_put(folio);
4935                 return false;
4936         }
4937
4938         /* see the comment on MAX_NR_TIERS */
4939         if (!folio_test_referenced(folio))
4940                 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4941
4942         /* for shrink_folio_list() */
4943         folio_clear_reclaim(folio);
4944         folio_clear_referenced(folio);
4945
4946         success = lru_gen_del_folio(lruvec, folio, true);
4947         VM_WARN_ON_ONCE_FOLIO(!success, folio);
4948
4949         return true;
4950 }
4951
4952 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4953                        int type, int tier, struct list_head *list)
4954 {
4955         int gen, zone;
4956         enum vm_event_item item;
4957         int sorted = 0;
4958         int scanned = 0;
4959         int isolated = 0;
4960         int remaining = MAX_LRU_BATCH;
4961         struct lru_gen_folio *lrugen = &lruvec->lrugen;
4962         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4963
4964         VM_WARN_ON_ONCE(!list_empty(list));
4965
4966         if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4967                 return 0;
4968
4969         gen = lru_gen_from_seq(lrugen->min_seq[type]);
4970
4971         for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4972                 LIST_HEAD(moved);
4973                 int skipped = 0;
4974                 struct list_head *head = &lrugen->folios[gen][type][zone];
4975
4976                 while (!list_empty(head)) {
4977                         struct folio *folio = lru_to_folio(head);
4978                         int delta = folio_nr_pages(folio);
4979
4980                         VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4981                         VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4982                         VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4983                         VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4984
4985                         scanned += delta;
4986
4987                         if (sort_folio(lruvec, folio, tier))
4988                                 sorted += delta;
4989                         else if (isolate_folio(lruvec, folio, sc)) {
4990                                 list_add(&folio->lru, list);
4991                                 isolated += delta;
4992                         } else {
4993                                 list_move(&folio->lru, &moved);
4994                                 skipped += delta;
4995                         }
4996
4997                         if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4998                                 break;
4999                 }
5000
5001                 if (skipped) {
5002                         list_splice(&moved, head);
5003                         __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
5004                 }
5005
5006                 if (!remaining || isolated >= MIN_LRU_BATCH)
5007                         break;
5008         }
5009
5010         item = PGSCAN_KSWAPD + reclaimer_offset();
5011         if (!cgroup_reclaim(sc)) {
5012                 __count_vm_events(item, isolated);
5013                 __count_vm_events(PGREFILL, sorted);
5014         }
5015         __count_memcg_events(memcg, item, isolated);
5016         __count_memcg_events(memcg, PGREFILL, sorted);
5017         __count_vm_events(PGSCAN_ANON + type, isolated);
5018
5019         /*
5020          * There might not be eligible folios due to reclaim_idx. Check the
5021          * remaining to prevent livelock if it's not making progress.
5022          */
5023         return isolated || !remaining ? scanned : 0;
5024 }
5025
5026 static int get_tier_idx(struct lruvec *lruvec, int type)
5027 {
5028         int tier;
5029         struct ctrl_pos sp, pv;
5030
5031         /*
5032          * To leave a margin for fluctuations, use a larger gain factor (1:2).
5033          * This value is chosen because any other tier would have at least twice
5034          * as many refaults as the first tier.
5035          */
5036         read_ctrl_pos(lruvec, type, 0, 1, &sp);
5037         for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5038                 read_ctrl_pos(lruvec, type, tier, 2, &pv);
5039                 if (!positive_ctrl_err(&sp, &pv))
5040                         break;
5041         }
5042
5043         return tier - 1;
5044 }
5045
5046 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
5047 {
5048         int type, tier;
5049         struct ctrl_pos sp, pv;
5050         int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
5051
5052         /*
5053          * Compare the first tier of anon with that of file to determine which
5054          * type to scan. Also need to compare other tiers of the selected type
5055          * with the first tier of the other type to determine the last tier (of
5056          * the selected type) to evict.
5057          */
5058         read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
5059         read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
5060         type = positive_ctrl_err(&sp, &pv);
5061
5062         read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
5063         for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5064                 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
5065                 if (!positive_ctrl_err(&sp, &pv))
5066                         break;
5067         }
5068
5069         *tier_idx = tier - 1;
5070
5071         return type;
5072 }
5073
5074 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
5075                           int *type_scanned, struct list_head *list)
5076 {
5077         int i;
5078         int type;
5079         int scanned;
5080         int tier = -1;
5081         DEFINE_MIN_SEQ(lruvec);
5082
5083         /*
5084          * Try to make the obvious choice first. When anon and file are both
5085          * available from the same generation, interpret swappiness 1 as file
5086          * first and 200 as anon first.
5087          */
5088         if (!swappiness)
5089                 type = LRU_GEN_FILE;
5090         else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
5091                 type = LRU_GEN_ANON;
5092         else if (swappiness == 1)
5093                 type = LRU_GEN_FILE;
5094         else if (swappiness == 200)
5095                 type = LRU_GEN_ANON;
5096         else
5097                 type = get_type_to_scan(lruvec, swappiness, &tier);
5098
5099         for (i = !swappiness; i < ANON_AND_FILE; i++) {
5100                 if (tier < 0)
5101                         tier = get_tier_idx(lruvec, type);
5102
5103                 scanned = scan_folios(lruvec, sc, type, tier, list);
5104                 if (scanned)
5105                         break;
5106
5107                 type = !type;
5108                 tier = -1;
5109         }
5110
5111         *type_scanned = type;
5112
5113         return scanned;
5114 }
5115
5116 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
5117 {
5118         int type;
5119         int scanned;
5120         int reclaimed;
5121         LIST_HEAD(list);
5122         LIST_HEAD(clean);
5123         struct folio *folio;
5124         struct folio *next;
5125         enum vm_event_item item;
5126         struct reclaim_stat stat;
5127         struct lru_gen_mm_walk *walk;
5128         bool skip_retry = false;
5129         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5130         struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5131
5132         spin_lock_irq(&lruvec->lru_lock);
5133
5134         scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
5135
5136         scanned += try_to_inc_min_seq(lruvec, swappiness);
5137
5138         if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
5139                 scanned = 0;
5140
5141         spin_unlock_irq(&lruvec->lru_lock);
5142
5143         if (list_empty(&list))
5144                 return scanned;
5145 retry:
5146         reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
5147         sc->nr_reclaimed += reclaimed;
5148
5149         list_for_each_entry_safe_reverse(folio, next, &list, lru) {
5150                 if (!folio_evictable(folio)) {
5151                         list_del(&folio->lru);
5152                         folio_putback_lru(folio);
5153                         continue;
5154                 }
5155
5156                 if (folio_test_reclaim(folio) &&
5157                     (folio_test_dirty(folio) || folio_test_writeback(folio))) {
5158                         /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
5159                         if (folio_test_workingset(folio))
5160                                 folio_set_referenced(folio);
5161                         continue;
5162                 }
5163
5164                 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
5165                     folio_mapped(folio) || folio_test_locked(folio) ||
5166                     folio_test_dirty(folio) || folio_test_writeback(folio)) {
5167                         /* don't add rejected folios to the oldest generation */
5168                         set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
5169                                       BIT(PG_active));
5170                         continue;
5171                 }
5172
5173                 /* retry folios that may have missed folio_rotate_reclaimable() */
5174                 list_move(&folio->lru, &clean);
5175                 sc->nr_scanned -= folio_nr_pages(folio);
5176         }
5177
5178         spin_lock_irq(&lruvec->lru_lock);
5179
5180         move_folios_to_lru(lruvec, &list);
5181
5182         walk = current->reclaim_state->mm_walk;
5183         if (walk && walk->batched)
5184                 reset_batch_size(lruvec, walk);
5185
5186         item = PGSTEAL_KSWAPD + reclaimer_offset();
5187         if (!cgroup_reclaim(sc))
5188                 __count_vm_events(item, reclaimed);
5189         __count_memcg_events(memcg, item, reclaimed);
5190         __count_vm_events(PGSTEAL_ANON + type, reclaimed);
5191
5192         spin_unlock_irq(&lruvec->lru_lock);
5193
5194         mem_cgroup_uncharge_list(&list);
5195         free_unref_page_list(&list);
5196
5197         INIT_LIST_HEAD(&list);
5198         list_splice_init(&clean, &list);
5199
5200         if (!list_empty(&list)) {
5201                 skip_retry = true;
5202                 goto retry;
5203         }
5204
5205         return scanned;
5206 }
5207
5208 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
5209                              struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
5210 {
5211         int gen, type, zone;
5212         unsigned long old = 0;
5213         unsigned long young = 0;
5214         unsigned long total = 0;
5215         struct lru_gen_folio *lrugen = &lruvec->lrugen;
5216         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5217         DEFINE_MIN_SEQ(lruvec);
5218
5219         /* whether this lruvec is completely out of cold folios */
5220         if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
5221                 *nr_to_scan = 0;
5222                 return true;
5223         }
5224
5225         for (type = !can_swap; type < ANON_AND_FILE; type++) {
5226                 unsigned long seq;
5227
5228                 for (seq = min_seq[type]; seq <= max_seq; seq++) {
5229                         unsigned long size = 0;
5230
5231                         gen = lru_gen_from_seq(seq);
5232
5233                         for (zone = 0; zone < MAX_NR_ZONES; zone++)
5234                                 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5235
5236                         total += size;
5237                         if (seq == max_seq)
5238                                 young += size;
5239                         else if (seq + MIN_NR_GENS == max_seq)
5240                                 old += size;
5241                 }
5242         }
5243
5244         /* try to scrape all its memory if this memcg was deleted */
5245         *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
5246
5247         /*
5248          * The aging tries to be lazy to reduce the overhead, while the eviction
5249          * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
5250          * ideal number of generations is MIN_NR_GENS+1.
5251          */
5252         if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
5253                 return false;
5254
5255         /*
5256          * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
5257          * of the total number of pages for each generation. A reasonable range
5258          * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
5259          * aging cares about the upper bound of hot pages, while the eviction
5260          * cares about the lower bound of cold pages.
5261          */
5262         if (young * MIN_NR_GENS > total)
5263                 return true;
5264         if (old * (MIN_NR_GENS + 2) < total)
5265                 return true;
5266
5267         return false;
5268 }
5269
5270 /*
5271  * For future optimizations:
5272  * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
5273  *    reclaim.
5274  */
5275 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
5276 {
5277         unsigned long nr_to_scan;
5278         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5279         DEFINE_MAX_SEQ(lruvec);
5280
5281         if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg))
5282                 return 0;
5283
5284         if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
5285                 return nr_to_scan;
5286
5287         /* skip the aging path at the default priority */
5288         if (sc->priority == DEF_PRIORITY)
5289                 return nr_to_scan;
5290
5291         /* skip this lruvec as it's low on cold folios */
5292         return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
5293 }
5294
5295 static unsigned long get_nr_to_reclaim(struct scan_control *sc)
5296 {
5297         /* don't abort memcg reclaim to ensure fairness */
5298         if (!global_reclaim(sc))
5299                 return -1;
5300
5301         return max(sc->nr_to_reclaim, compact_gap(sc->order));
5302 }
5303
5304 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5305 {
5306         long nr_to_scan;
5307         unsigned long scanned = 0;
5308         unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5309         int swappiness = get_swappiness(lruvec, sc);
5310
5311         /* clean file folios are more likely to exist */
5312         if (swappiness && !(sc->gfp_mask & __GFP_IO))
5313                 swappiness = 1;
5314
5315         while (true) {
5316                 int delta;
5317
5318                 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
5319                 if (nr_to_scan <= 0)
5320                         break;
5321
5322                 delta = evict_folios(lruvec, sc, swappiness);
5323                 if (!delta)
5324                         break;
5325
5326                 scanned += delta;
5327                 if (scanned >= nr_to_scan)
5328                         break;
5329
5330                 if (sc->nr_reclaimed >= nr_to_reclaim)
5331                         break;
5332
5333                 cond_resched();
5334         }
5335
5336         /* whether try_to_inc_max_seq() was successful */
5337         return nr_to_scan < 0;
5338 }
5339
5340 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
5341 {
5342         bool success;
5343         unsigned long scanned = sc->nr_scanned;
5344         unsigned long reclaimed = sc->nr_reclaimed;
5345         int seg = lru_gen_memcg_seg(lruvec);
5346         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5347         struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5348
5349         /* see the comment on MEMCG_NR_GENS */
5350         if (!lruvec_is_sizable(lruvec, sc))
5351                 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
5352
5353         mem_cgroup_calculate_protection(NULL, memcg);
5354
5355         if (mem_cgroup_below_min(NULL, memcg))
5356                 return MEMCG_LRU_YOUNG;
5357
5358         if (mem_cgroup_below_low(NULL, memcg)) {
5359                 /* see the comment on MEMCG_NR_GENS */
5360                 if (seg != MEMCG_LRU_TAIL)
5361                         return MEMCG_LRU_TAIL;
5362
5363                 memcg_memory_event(memcg, MEMCG_LOW);
5364         }
5365
5366         success = try_to_shrink_lruvec(lruvec, sc);
5367
5368         shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
5369
5370         if (!sc->proactive)
5371                 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
5372                            sc->nr_reclaimed - reclaimed);
5373
5374         flush_reclaim_state(sc);
5375
5376         return success ? MEMCG_LRU_YOUNG : 0;
5377 }
5378
5379 #ifdef CONFIG_MEMCG
5380
5381 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5382 {
5383         int op;
5384         int gen;
5385         int bin;
5386         int first_bin;
5387         struct lruvec *lruvec;
5388         struct lru_gen_folio *lrugen;
5389         struct mem_cgroup *memcg;
5390         const struct hlist_nulls_node *pos;
5391         unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5392
5393         bin = first_bin = get_random_u32_below(MEMCG_NR_BINS);
5394 restart:
5395         op = 0;
5396         memcg = NULL;
5397         gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5398
5399         rcu_read_lock();
5400
5401         hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5402                 if (op) {
5403                         lru_gen_rotate_memcg(lruvec, op);
5404                         op = 0;
5405                 }
5406
5407                 mem_cgroup_put(memcg);
5408
5409                 lruvec = container_of(lrugen, struct lruvec, lrugen);
5410                 memcg = lruvec_memcg(lruvec);
5411
5412                 if (!mem_cgroup_tryget(memcg)) {
5413                         lru_gen_release_memcg(memcg);
5414                         memcg = NULL;
5415                         continue;
5416                 }
5417
5418                 rcu_read_unlock();
5419
5420                 op = shrink_one(lruvec, sc);
5421
5422                 rcu_read_lock();
5423
5424                 if (sc->nr_reclaimed >= nr_to_reclaim)
5425                         break;
5426         }
5427
5428         rcu_read_unlock();
5429
5430         if (op)
5431                 lru_gen_rotate_memcg(lruvec, op);
5432
5433         mem_cgroup_put(memcg);
5434
5435         if (sc->nr_reclaimed >= nr_to_reclaim)
5436                 return;
5437
5438         /* restart if raced with lru_gen_rotate_memcg() */
5439         if (gen != get_nulls_value(pos))
5440                 goto restart;
5441
5442         /* try the rest of the bins of the current generation */
5443         bin = get_memcg_bin(bin + 1);
5444         if (bin != first_bin)
5445                 goto restart;
5446 }
5447
5448 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5449 {
5450         struct blk_plug plug;
5451
5452         VM_WARN_ON_ONCE(global_reclaim(sc));
5453         VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
5454
5455         lru_add_drain();
5456
5457         blk_start_plug(&plug);
5458
5459         set_mm_walk(NULL, sc->proactive);
5460
5461         if (try_to_shrink_lruvec(lruvec, sc))
5462                 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5463
5464         clear_mm_walk();
5465
5466         blk_finish_plug(&plug);
5467 }
5468
5469 #else /* !CONFIG_MEMCG */
5470
5471 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5472 {
5473         BUILD_BUG();
5474 }
5475
5476 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5477 {
5478         BUILD_BUG();
5479 }
5480
5481 #endif
5482
5483 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5484 {
5485         int priority;
5486         unsigned long reclaimable;
5487         struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5488
5489         if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5490                 return;
5491         /*
5492          * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5493          * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5494          * estimated reclaimed_to_scanned_ratio = inactive / total.
5495          */
5496         reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5497         if (get_swappiness(lruvec, sc))
5498                 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5499
5500         reclaimable /= MEMCG_NR_GENS;
5501
5502         /* round down reclaimable and round up sc->nr_to_reclaim */
5503         priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5504
5505         sc->priority = clamp(priority, 0, DEF_PRIORITY);
5506 }
5507
5508 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5509 {
5510         struct blk_plug plug;
5511         unsigned long reclaimed = sc->nr_reclaimed;
5512
5513         VM_WARN_ON_ONCE(!global_reclaim(sc));
5514
5515         /*
5516          * Unmapped clean folios are already prioritized. Scanning for more of
5517          * them is likely futile and can cause high reclaim latency when there
5518          * is a large number of memcgs.
5519          */
5520         if (!sc->may_writepage || !sc->may_unmap)
5521                 goto done;
5522
5523         lru_add_drain();
5524
5525         blk_start_plug(&plug);
5526
5527         set_mm_walk(pgdat, sc->proactive);
5528
5529         set_initial_priority(pgdat, sc);
5530
5531         if (current_is_kswapd())
5532                 sc->nr_reclaimed = 0;
5533
5534         if (mem_cgroup_disabled())
5535                 shrink_one(&pgdat->__lruvec, sc);
5536         else
5537                 shrink_many(pgdat, sc);
5538
5539         if (current_is_kswapd())
5540                 sc->nr_reclaimed += reclaimed;
5541
5542         clear_mm_walk();
5543
5544         blk_finish_plug(&plug);
5545 done:
5546         /* kswapd should never fail */
5547         pgdat->kswapd_failures = 0;
5548 }
5549
5550 /******************************************************************************
5551  *                          state change
5552  ******************************************************************************/
5553
5554 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5555 {
5556         struct lru_gen_folio *lrugen = &lruvec->lrugen;
5557
5558         if (lrugen->enabled) {
5559                 enum lru_list lru;
5560
5561                 for_each_evictable_lru(lru) {
5562                         if (!list_empty(&lruvec->lists[lru]))
5563                                 return false;
5564                 }
5565         } else {
5566                 int gen, type, zone;
5567
5568                 for_each_gen_type_zone(gen, type, zone) {
5569                         if (!list_empty(&lrugen->folios[gen][type][zone]))
5570                                 return false;
5571                 }
5572         }
5573
5574         return true;
5575 }
5576
5577 static bool fill_evictable(struct lruvec *lruvec)
5578 {
5579         enum lru_list lru;
5580         int remaining = MAX_LRU_BATCH;
5581
5582         for_each_evictable_lru(lru) {
5583                 int type = is_file_lru(lru);
5584                 bool active = is_active_lru(lru);
5585                 struct list_head *head = &lruvec->lists[lru];
5586
5587                 while (!list_empty(head)) {
5588                         bool success;
5589                         struct folio *folio = lru_to_folio(head);
5590
5591                         VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5592                         VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5593                         VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5594                         VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5595
5596                         lruvec_del_folio(lruvec, folio);
5597                         success = lru_gen_add_folio(lruvec, folio, false);
5598                         VM_WARN_ON_ONCE(!success);
5599
5600                         if (!--remaining)
5601                                 return false;
5602                 }
5603         }
5604
5605         return true;
5606 }
5607
5608 static bool drain_evictable(struct lruvec *lruvec)
5609 {
5610         int gen, type, zone;
5611         int remaining = MAX_LRU_BATCH;
5612
5613         for_each_gen_type_zone(gen, type, zone) {
5614                 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
5615
5616                 while (!list_empty(head)) {
5617                         bool success;
5618                         struct folio *folio = lru_to_folio(head);
5619
5620                         VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5621                         VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5622                         VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5623                         VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5624
5625                         success = lru_gen_del_folio(lruvec, folio, false);
5626                         VM_WARN_ON_ONCE(!success);
5627                         lruvec_add_folio(lruvec, folio);
5628
5629                         if (!--remaining)
5630                                 return false;
5631                 }
5632         }
5633
5634         return true;
5635 }
5636
5637 static void lru_gen_change_state(bool enabled)
5638 {
5639         static DEFINE_MUTEX(state_mutex);
5640
5641         struct mem_cgroup *memcg;
5642
5643         cgroup_lock();
5644         cpus_read_lock();
5645         get_online_mems();
5646         mutex_lock(&state_mutex);
5647
5648         if (enabled == lru_gen_enabled())
5649                 goto unlock;
5650
5651         if (enabled)
5652                 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5653         else
5654                 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5655
5656         memcg = mem_cgroup_iter(NULL, NULL, NULL);
5657         do {
5658                 int nid;
5659
5660                 for_each_node(nid) {
5661                         struct lruvec *lruvec = get_lruvec(memcg, nid);
5662
5663                         spin_lock_irq(&lruvec->lru_lock);
5664
5665                         VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5666                         VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5667
5668                         lruvec->lrugen.enabled = enabled;
5669
5670                         while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5671                                 spin_unlock_irq(&lruvec->lru_lock);
5672                                 cond_resched();
5673                                 spin_lock_irq(&lruvec->lru_lock);
5674                         }
5675
5676                         spin_unlock_irq(&lruvec->lru_lock);
5677                 }
5678
5679                 cond_resched();
5680         } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5681 unlock:
5682         mutex_unlock(&state_mutex);
5683         put_online_mems();
5684         cpus_read_unlock();
5685         cgroup_unlock();
5686 }
5687
5688 /******************************************************************************
5689  *                          sysfs interface
5690  ******************************************************************************/
5691
5692 static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5693 {
5694         return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5695 }
5696
5697 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5698 static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr,
5699                                 const char *buf, size_t len)
5700 {
5701         unsigned int msecs;
5702
5703         if (kstrtouint(buf, 0, &msecs))
5704                 return -EINVAL;
5705
5706         WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5707
5708         return len;
5709 }
5710
5711 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms);
5712
5713 static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5714 {
5715         unsigned int caps = 0;
5716
5717         if (get_cap(LRU_GEN_CORE))
5718                 caps |= BIT(LRU_GEN_CORE);
5719
5720         if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5721                 caps |= BIT(LRU_GEN_MM_WALK);
5722
5723         if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
5724                 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5725
5726         return sysfs_emit(buf, "0x%04x\n", caps);
5727 }
5728
5729 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5730 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
5731                              const char *buf, size_t len)
5732 {
5733         int i;
5734         unsigned int caps;
5735
5736         if (tolower(*buf) == 'n')
5737                 caps = 0;
5738         else if (tolower(*buf) == 'y')
5739                 caps = -1;
5740         else if (kstrtouint(buf, 0, &caps))
5741                 return -EINVAL;
5742
5743         for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5744                 bool enabled = caps & BIT(i);
5745
5746                 if (i == LRU_GEN_CORE)
5747                         lru_gen_change_state(enabled);
5748                 else if (enabled)
5749                         static_branch_enable(&lru_gen_caps[i]);
5750                 else
5751                         static_branch_disable(&lru_gen_caps[i]);
5752         }
5753
5754         return len;
5755 }
5756
5757 static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled);
5758
5759 static struct attribute *lru_gen_attrs[] = {
5760         &lru_gen_min_ttl_attr.attr,
5761         &lru_gen_enabled_attr.attr,
5762         NULL
5763 };
5764
5765 static const struct attribute_group lru_gen_attr_group = {
5766         .name = "lru_gen",
5767         .attrs = lru_gen_attrs,
5768 };
5769
5770 /******************************************************************************
5771  *                          debugfs interface
5772  ******************************************************************************/
5773
5774 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5775 {
5776         struct mem_cgroup *memcg;
5777         loff_t nr_to_skip = *pos;
5778
5779         m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5780         if (!m->private)
5781                 return ERR_PTR(-ENOMEM);
5782
5783         memcg = mem_cgroup_iter(NULL, NULL, NULL);
5784         do {
5785                 int nid;
5786
5787                 for_each_node_state(nid, N_MEMORY) {
5788                         if (!nr_to_skip--)
5789                                 return get_lruvec(memcg, nid);
5790                 }
5791         } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5792
5793         return NULL;
5794 }
5795
5796 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5797 {
5798         if (!IS_ERR_OR_NULL(v))
5799                 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5800
5801         kvfree(m->private);
5802         m->private = NULL;
5803 }
5804
5805 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5806 {
5807         int nid = lruvec_pgdat(v)->node_id;
5808         struct mem_cgroup *memcg = lruvec_memcg(v);
5809
5810         ++*pos;
5811
5812         nid = next_memory_node(nid);
5813         if (nid == MAX_NUMNODES) {
5814                 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5815                 if (!memcg)
5816                         return NULL;
5817
5818                 nid = first_memory_node;
5819         }
5820
5821         return get_lruvec(memcg, nid);
5822 }
5823
5824 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5825                                   unsigned long max_seq, unsigned long *min_seq,
5826                                   unsigned long seq)
5827 {
5828         int i;
5829         int type, tier;
5830         int hist = lru_hist_from_seq(seq);
5831         struct lru_gen_folio *lrugen = &lruvec->lrugen;
5832
5833         for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5834                 seq_printf(m, "            %10d", tier);
5835                 for (type = 0; type < ANON_AND_FILE; type++) {
5836                         const char *s = "   ";
5837                         unsigned long n[3] = {};
5838
5839                         if (seq == max_seq) {
5840                                 s = "RT ";
5841                                 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5842                                 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5843                         } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5844                                 s = "rep";
5845                                 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5846                                 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5847                                 if (tier)
5848                                         n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5849                         }
5850
5851                         for (i = 0; i < 3; i++)
5852                                 seq_printf(m, " %10lu%c", n[i], s[i]);
5853                 }
5854                 seq_putc(m, '\n');
5855         }
5856
5857         seq_puts(m, "                      ");
5858         for (i = 0; i < NR_MM_STATS; i++) {
5859                 const char *s = "      ";
5860                 unsigned long n = 0;
5861
5862                 if (seq == max_seq && NR_HIST_GENS == 1) {
5863                         s = "LOYNFA";
5864                         n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5865                 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5866                         s = "loynfa";
5867                         n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5868                 }
5869
5870                 seq_printf(m, " %10lu%c", n, s[i]);
5871         }
5872         seq_putc(m, '\n');
5873 }
5874
5875 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5876 static int lru_gen_seq_show(struct seq_file *m, void *v)
5877 {
5878         unsigned long seq;
5879         bool full = !debugfs_real_fops(m->file)->write;
5880         struct lruvec *lruvec = v;
5881         struct lru_gen_folio *lrugen = &lruvec->lrugen;
5882         int nid = lruvec_pgdat(lruvec)->node_id;
5883         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5884         DEFINE_MAX_SEQ(lruvec);
5885         DEFINE_MIN_SEQ(lruvec);
5886
5887         if (nid == first_memory_node) {
5888                 const char *path = memcg ? m->private : "";
5889
5890 #ifdef CONFIG_MEMCG
5891                 if (memcg)
5892                         cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5893 #endif
5894                 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5895         }
5896
5897         seq_printf(m, " node %5d\n", nid);
5898
5899         if (!full)
5900                 seq = min_seq[LRU_GEN_ANON];
5901         else if (max_seq >= MAX_NR_GENS)
5902                 seq = max_seq - MAX_NR_GENS + 1;
5903         else
5904                 seq = 0;
5905
5906         for (; seq <= max_seq; seq++) {
5907                 int type, zone;
5908                 int gen = lru_gen_from_seq(seq);
5909                 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5910
5911                 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5912
5913                 for (type = 0; type < ANON_AND_FILE; type++) {
5914                         unsigned long size = 0;
5915                         char mark = full && seq < min_seq[type] ? 'x' : ' ';
5916
5917                         for (zone = 0; zone < MAX_NR_ZONES; zone++)
5918                                 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5919
5920                         seq_printf(m, " %10lu%c", size, mark);
5921                 }
5922
5923                 seq_putc(m, '\n');
5924
5925                 if (full)
5926                         lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5927         }
5928
5929         return 0;
5930 }
5931
5932 static const struct seq_operations lru_gen_seq_ops = {
5933         .start = lru_gen_seq_start,
5934         .stop = lru_gen_seq_stop,
5935         .next = lru_gen_seq_next,
5936         .show = lru_gen_seq_show,
5937 };
5938
5939 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5940                      bool can_swap, bool force_scan)
5941 {
5942         DEFINE_MAX_SEQ(lruvec);
5943         DEFINE_MIN_SEQ(lruvec);
5944
5945         if (seq < max_seq)
5946                 return 0;
5947
5948         if (seq > max_seq)
5949                 return -EINVAL;
5950
5951         if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5952                 return -ERANGE;
5953
5954         try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5955
5956         return 0;
5957 }
5958
5959 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5960                         int swappiness, unsigned long nr_to_reclaim)
5961 {
5962         DEFINE_MAX_SEQ(lruvec);
5963
5964         if (seq + MIN_NR_GENS > max_seq)
5965                 return -EINVAL;
5966
5967         sc->nr_reclaimed = 0;
5968
5969         while (!signal_pending(current)) {
5970                 DEFINE_MIN_SEQ(lruvec);
5971
5972                 if (seq < min_seq[!swappiness])
5973                         return 0;
5974
5975                 if (sc->nr_reclaimed >= nr_to_reclaim)
5976                         return 0;
5977
5978                 if (!evict_folios(lruvec, sc, swappiness))
5979                         return 0;
5980
5981                 cond_resched();
5982         }
5983
5984         return -EINTR;
5985 }
5986
5987 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5988                    struct scan_control *sc, int swappiness, unsigned long opt)
5989 {
5990         struct lruvec *lruvec;
5991         int err = -EINVAL;
5992         struct mem_cgroup *memcg = NULL;
5993
5994         if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5995                 return -EINVAL;
5996
5997         if (!mem_cgroup_disabled()) {
5998                 rcu_read_lock();
5999
6000                 memcg = mem_cgroup_from_id(memcg_id);
6001                 if (!mem_cgroup_tryget(memcg))
6002                         memcg = NULL;
6003
6004                 rcu_read_unlock();
6005
6006                 if (!memcg)
6007                         return -EINVAL;
6008         }
6009
6010         if (memcg_id != mem_cgroup_id(memcg))
6011                 goto done;
6012
6013         lruvec = get_lruvec(memcg, nid);
6014
6015         if (swappiness < 0)
6016                 swappiness = get_swappiness(lruvec, sc);
6017         else if (swappiness > 200)
6018                 goto done;
6019
6020         switch (cmd) {
6021         case '+':
6022                 err = run_aging(lruvec, seq, sc, swappiness, opt);
6023                 break;
6024         case '-':
6025                 err = run_eviction(lruvec, seq, sc, swappiness, opt);
6026                 break;
6027         }
6028 done:
6029         mem_cgroup_put(memcg);
6030
6031         return err;
6032 }
6033
6034 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
6035 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
6036                                  size_t len, loff_t *pos)
6037 {
6038         void *buf;
6039         char *cur, *next;
6040         unsigned int flags;
6041         struct blk_plug plug;
6042         int err = -EINVAL;
6043         struct scan_control sc = {
6044                 .may_writepage = true,
6045                 .may_unmap = true,
6046                 .may_swap = true,
6047                 .reclaim_idx = MAX_NR_ZONES - 1,
6048                 .gfp_mask = GFP_KERNEL,
6049         };
6050
6051         buf = kvmalloc(len + 1, GFP_KERNEL);
6052         if (!buf)
6053                 return -ENOMEM;
6054
6055         if (copy_from_user(buf, src, len)) {
6056                 kvfree(buf);
6057                 return -EFAULT;
6058         }
6059
6060         set_task_reclaim_state(current, &sc.reclaim_state);
6061         flags = memalloc_noreclaim_save();
6062         blk_start_plug(&plug);
6063         if (!set_mm_walk(NULL, true)) {
6064                 err = -ENOMEM;
6065                 goto done;
6066         }
6067
6068         next = buf;
6069         next[len] = '\0';
6070
6071         while ((cur = strsep(&next, ",;\n"))) {
6072                 int n;
6073                 int end;
6074                 char cmd;
6075                 unsigned int memcg_id;
6076                 unsigned int nid;
6077                 unsigned long seq;
6078                 unsigned int swappiness = -1;
6079                 unsigned long opt = -1;
6080
6081                 cur = skip_spaces(cur);
6082                 if (!*cur)
6083                         continue;
6084
6085                 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
6086                            &seq, &end, &swappiness, &end, &opt, &end);
6087                 if (n < 4 || cur[end]) {
6088                         err = -EINVAL;
6089                         break;
6090                 }
6091
6092                 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
6093                 if (err)
6094                         break;
6095         }
6096 done:
6097         clear_mm_walk();
6098         blk_finish_plug(&plug);
6099         memalloc_noreclaim_restore(flags);
6100         set_task_reclaim_state(current, NULL);
6101
6102         kvfree(buf);
6103
6104         return err ? : len;
6105 }
6106
6107 static int lru_gen_seq_open(struct inode *inode, struct file *file)
6108 {
6109         return seq_open(file, &lru_gen_seq_ops);
6110 }
6111
6112 static const struct file_operations lru_gen_rw_fops = {
6113         .open = lru_gen_seq_open,
6114         .read = seq_read,
6115         .write = lru_gen_seq_write,
6116         .llseek = seq_lseek,
6117         .release = seq_release,
6118 };
6119
6120 static const struct file_operations lru_gen_ro_fops = {
6121         .open = lru_gen_seq_open,
6122         .read = seq_read,
6123         .llseek = seq_lseek,
6124         .release = seq_release,
6125 };
6126
6127 /******************************************************************************
6128  *                          initialization
6129  ******************************************************************************/
6130
6131 void lru_gen_init_lruvec(struct lruvec *lruvec)
6132 {
6133         int i;
6134         int gen, type, zone;
6135         struct lru_gen_folio *lrugen = &lruvec->lrugen;
6136
6137         lrugen->max_seq = MIN_NR_GENS + 1;
6138         lrugen->enabled = lru_gen_enabled();
6139
6140         for (i = 0; i <= MIN_NR_GENS + 1; i++)
6141                 lrugen->timestamps[i] = jiffies;
6142
6143         for_each_gen_type_zone(gen, type, zone)
6144                 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
6145
6146         lruvec->mm_state.seq = MIN_NR_GENS;
6147 }
6148
6149 #ifdef CONFIG_MEMCG
6150
6151 void lru_gen_init_pgdat(struct pglist_data *pgdat)
6152 {
6153         int i, j;
6154
6155         spin_lock_init(&pgdat->memcg_lru.lock);
6156
6157         for (i = 0; i < MEMCG_NR_GENS; i++) {
6158                 for (j = 0; j < MEMCG_NR_BINS; j++)
6159                         INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
6160         }
6161 }
6162
6163 void lru_gen_init_memcg(struct mem_cgroup *memcg)
6164 {
6165         INIT_LIST_HEAD(&memcg->mm_list.fifo);
6166         spin_lock_init(&memcg->mm_list.lock);
6167 }
6168
6169 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
6170 {
6171         int i;
6172         int nid;
6173
6174         VM_WARN_ON_ONCE(!list_empty(&memcg->mm_list.fifo));
6175
6176         for_each_node(nid) {
6177                 struct lruvec *lruvec = get_lruvec(memcg, nid);
6178
6179                 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
6180                                            sizeof(lruvec->lrugen.nr_pages)));
6181
6182                 lruvec->lrugen.list.next = LIST_POISON1;
6183
6184                 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
6185                         bitmap_free(lruvec->mm_state.filters[i]);
6186                         lruvec->mm_state.filters[i] = NULL;
6187                 }
6188         }
6189 }
6190
6191 #endif /* CONFIG_MEMCG */
6192
6193 static int __init init_lru_gen(void)
6194 {
6195         BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
6196         BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
6197
6198         if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
6199                 pr_err("lru_gen: failed to create sysfs group\n");
6200
6201         debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
6202         debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
6203
6204         return 0;
6205 };
6206 late_initcall(init_lru_gen);
6207
6208 #else /* !CONFIG_LRU_GEN */
6209
6210 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6211 {
6212 }
6213
6214 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
6215 {
6216 }
6217
6218 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
6219 {
6220 }
6221
6222 #endif /* CONFIG_LRU_GEN */
6223
6224 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
6225 {
6226         unsigned long nr[NR_LRU_LISTS];
6227         unsigned long targets[NR_LRU_LISTS];
6228         unsigned long nr_to_scan;
6229         enum lru_list lru;
6230         unsigned long nr_reclaimed = 0;
6231         unsigned long nr_to_reclaim = sc->nr_to_reclaim;
6232         bool proportional_reclaim;
6233         struct blk_plug plug;
6234
6235         if (lru_gen_enabled() && !global_reclaim(sc)) {
6236                 lru_gen_shrink_lruvec(lruvec, sc);
6237                 return;
6238         }
6239
6240         get_scan_count(lruvec, sc, nr);
6241
6242         /* Record the original scan target for proportional adjustments later */
6243         memcpy(targets, nr, sizeof(nr));
6244
6245         /*
6246          * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
6247          * event that can occur when there is little memory pressure e.g.
6248          * multiple streaming readers/writers. Hence, we do not abort scanning
6249          * when the requested number of pages are reclaimed when scanning at
6250          * DEF_PRIORITY on the assumption that the fact we are direct
6251          * reclaiming implies that kswapd is not keeping up and it is best to
6252          * do a batch of work at once. For memcg reclaim one check is made to
6253          * abort proportional reclaim if either the file or anon lru has already
6254          * dropped to zero at the first pass.
6255          */
6256         proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
6257                                 sc->priority == DEF_PRIORITY);
6258
6259         blk_start_plug(&plug);
6260         while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
6261                                         nr[LRU_INACTIVE_FILE]) {
6262                 unsigned long nr_anon, nr_file, percentage;
6263                 unsigned long nr_scanned;
6264
6265                 for_each_evictable_lru(lru) {
6266                         if (nr[lru]) {
6267                                 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6268                                 nr[lru] -= nr_to_scan;
6269
6270                                 nr_reclaimed += shrink_list(lru, nr_to_scan,
6271                                                             lruvec, sc);
6272                         }
6273                 }
6274
6275                 cond_resched();
6276
6277                 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
6278                         continue;
6279
6280                 /*
6281                  * For kswapd and memcg, reclaim at least the number of pages
6282                  * requested. Ensure that the anon and file LRUs are scanned
6283                  * proportionally what was requested by get_scan_count(). We
6284                  * stop reclaiming one LRU and reduce the amount scanning
6285                  * proportional to the original scan target.
6286                  */
6287                 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6288                 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6289
6290                 /*
6291                  * It's just vindictive to attack the larger once the smaller
6292                  * has gone to zero.  And given the way we stop scanning the
6293                  * smaller below, this makes sure that we only make one nudge
6294                  * towards proportionality once we've got nr_to_reclaim.
6295                  */
6296                 if (!nr_file || !nr_anon)
6297                         break;
6298
6299                 if (nr_file > nr_anon) {
6300                         unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6301                                                 targets[LRU_ACTIVE_ANON] + 1;
6302                         lru = LRU_BASE;
6303                         percentage = nr_anon * 100 / scan_target;
6304                 } else {
6305                         unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6306                                                 targets[LRU_ACTIVE_FILE] + 1;
6307                         lru = LRU_FILE;
6308                         percentage = nr_file * 100 / scan_target;
6309                 }
6310
6311                 /* Stop scanning the smaller of the LRU */
6312                 nr[lru] = 0;
6313                 nr[lru + LRU_ACTIVE] = 0;
6314
6315                 /*
6316                  * Recalculate the other LRU scan count based on its original
6317                  * scan target and the percentage scanning already complete
6318                  */
6319                 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
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                 lru += LRU_ACTIVE;
6325                 nr_scanned = targets[lru] - nr[lru];
6326                 nr[lru] = targets[lru] * (100 - percentage) / 100;
6327                 nr[lru] -= min(nr[lru], nr_scanned);
6328         }
6329         blk_finish_plug(&plug);
6330         sc->nr_reclaimed += nr_reclaimed;
6331
6332         /*
6333          * Even if we did not try to evict anon pages at all, we want to
6334          * rebalance the anon lru active/inactive ratio.
6335          */
6336         if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6337             inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6338                 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6339                                    sc, LRU_ACTIVE_ANON);
6340 }
6341
6342 /* Use reclaim/compaction for costly allocs or under memory pressure */
6343 static bool in_reclaim_compaction(struct scan_control *sc)
6344 {
6345         if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
6346                         (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
6347                          sc->priority < DEF_PRIORITY - 2))
6348                 return true;
6349
6350         return false;
6351 }
6352
6353 /*
6354  * Reclaim/compaction is used for high-order allocation requests. It reclaims
6355  * order-0 pages before compacting the zone. should_continue_reclaim() returns
6356  * true if more pages should be reclaimed such that when the page allocator
6357  * calls try_to_compact_pages() that it will have enough free pages to succeed.
6358  * It will give up earlier than that if there is difficulty reclaiming pages.
6359  */
6360 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
6361                                         unsigned long nr_reclaimed,
6362                                         struct scan_control *sc)
6363 {
6364         unsigned long pages_for_compaction;
6365         unsigned long inactive_lru_pages;
6366         int z;
6367
6368         /* If not in reclaim/compaction mode, stop */
6369         if (!in_reclaim_compaction(sc))
6370                 return false;
6371
6372         /*
6373          * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6374          * number of pages that were scanned. This will return to the caller
6375          * with the risk reclaim/compaction and the resulting allocation attempt
6376          * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6377          * allocations through requiring that the full LRU list has been scanned
6378          * first, by assuming that zero delta of sc->nr_scanned means full LRU
6379          * scan, but that approximation was wrong, and there were corner cases
6380          * where always a non-zero amount of pages were scanned.
6381          */
6382         if (!nr_reclaimed)
6383                 return false;
6384
6385         /* If compaction would go ahead or the allocation would succeed, stop */
6386         for (z = 0; z <= sc->reclaim_idx; z++) {
6387                 struct zone *zone = &pgdat->node_zones[z];
6388                 if (!managed_zone(zone))
6389                         continue;
6390
6391                 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
6392                 case COMPACT_SUCCESS:
6393                 case COMPACT_CONTINUE:
6394                         return false;
6395                 default:
6396                         /* check next zone */
6397                         ;
6398                 }
6399         }
6400
6401         /*
6402          * If we have not reclaimed enough pages for compaction and the
6403          * inactive lists are large enough, continue reclaiming
6404          */
6405         pages_for_compaction = compact_gap(sc->order);
6406         inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
6407         if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
6408                 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6409
6410         return inactive_lru_pages > pages_for_compaction;
6411 }
6412
6413 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
6414 {
6415         struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
6416         struct mem_cgroup *memcg;
6417
6418         memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
6419         do {
6420                 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6421                 unsigned long reclaimed;
6422                 unsigned long scanned;
6423
6424                 /*
6425                  * This loop can become CPU-bound when target memcgs
6426                  * aren't eligible for reclaim - either because they
6427                  * don't have any reclaimable pages, or because their
6428                  * memory is explicitly protected. Avoid soft lockups.
6429                  */
6430                 cond_resched();
6431
6432                 mem_cgroup_calculate_protection(target_memcg, memcg);
6433
6434                 if (mem_cgroup_below_min(target_memcg, memcg)) {
6435                         /*
6436                          * Hard protection.
6437                          * If there is no reclaimable memory, OOM.
6438                          */
6439                         continue;
6440                 } else if (mem_cgroup_below_low(target_memcg, memcg)) {
6441                         /*
6442                          * Soft protection.
6443                          * Respect the protection only as long as
6444                          * there is an unprotected supply
6445                          * of reclaimable memory from other cgroups.
6446                          */
6447                         if (!sc->memcg_low_reclaim) {
6448                                 sc->memcg_low_skipped = 1;
6449                                 continue;
6450                         }
6451                         memcg_memory_event(memcg, MEMCG_LOW);
6452                 }
6453
6454                 reclaimed = sc->nr_reclaimed;
6455                 scanned = sc->nr_scanned;
6456
6457                 shrink_lruvec(lruvec, sc);
6458
6459                 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6460                             sc->priority);
6461
6462                 /* Record the group's reclaim efficiency */
6463                 if (!sc->proactive)
6464                         vmpressure(sc->gfp_mask, memcg, false,
6465                                    sc->nr_scanned - scanned,
6466                                    sc->nr_reclaimed - reclaimed);
6467
6468         } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6469 }
6470
6471 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
6472 {
6473         unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed;
6474         struct lruvec *target_lruvec;
6475         bool reclaimable = false;
6476
6477         if (lru_gen_enabled() && global_reclaim(sc)) {
6478                 lru_gen_shrink_node(pgdat, sc);
6479                 return;
6480         }
6481
6482         target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6483
6484 again:
6485         memset(&sc->nr, 0, sizeof(sc->nr));
6486
6487         nr_reclaimed = sc->nr_reclaimed;
6488         nr_scanned = sc->nr_scanned;
6489
6490         prepare_scan_count(pgdat, sc);
6491
6492         shrink_node_memcgs(pgdat, sc);
6493
6494         flush_reclaim_state(sc);
6495
6496         nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed;
6497
6498         /* Record the subtree's reclaim efficiency */
6499         if (!sc->proactive)
6500                 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6501                            sc->nr_scanned - nr_scanned, nr_node_reclaimed);
6502
6503         if (nr_node_reclaimed)
6504                 reclaimable = true;
6505
6506         if (current_is_kswapd()) {
6507                 /*
6508                  * If reclaim is isolating dirty pages under writeback,
6509                  * it implies that the long-lived page allocation rate
6510                  * is exceeding the page laundering rate. Either the
6511                  * global limits are not being effective at throttling
6512                  * processes due to the page distribution throughout
6513                  * zones or there is heavy usage of a slow backing
6514                  * device. The only option is to throttle from reclaim
6515                  * context which is not ideal as there is no guarantee
6516                  * the dirtying process is throttled in the same way
6517                  * balance_dirty_pages() manages.
6518                  *
6519                  * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6520                  * count the number of pages under pages flagged for
6521                  * immediate reclaim and stall if any are encountered
6522                  * in the nr_immediate check below.
6523                  */
6524                 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6525                         set_bit(PGDAT_WRITEBACK, &pgdat->flags);
6526
6527                 /* Allow kswapd to start writing pages during reclaim.*/
6528                 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6529                         set_bit(PGDAT_DIRTY, &pgdat->flags);
6530
6531                 /*
6532                  * If kswapd scans pages marked for immediate
6533                  * reclaim and under writeback (nr_immediate), it
6534                  * implies that pages are cycling through the LRU
6535                  * faster than they are written so forcibly stall
6536                  * until some pages complete writeback.
6537                  */
6538                 if (sc->nr.immediate)
6539                         reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6540         }
6541
6542         /*
6543          * Tag a node/memcg as congested if all the dirty pages were marked
6544          * for writeback and immediate reclaim (counted in nr.congested).
6545          *
6546          * Legacy memcg will stall in page writeback so avoid forcibly
6547          * stalling in reclaim_throttle().
6548          */
6549         if ((current_is_kswapd() ||
6550              (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
6551             sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
6552                 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
6553
6554         /*
6555          * Stall direct reclaim for IO completions if the lruvec is
6556          * node is congested. Allow kswapd to continue until it
6557          * starts encountering unqueued dirty pages or cycling through
6558          * the LRU too quickly.
6559          */
6560         if (!current_is_kswapd() && current_may_throttle() &&
6561             !sc->hibernation_mode &&
6562             test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
6563                 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6564
6565         if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc))
6566                 goto again;
6567
6568         /*
6569          * Kswapd gives up on balancing particular nodes after too
6570          * many failures to reclaim anything from them and goes to
6571          * sleep. On reclaim progress, reset the failure counter. A
6572          * successful direct reclaim run will revive a dormant kswapd.
6573          */
6574         if (reclaimable)
6575                 pgdat->kswapd_failures = 0;
6576 }
6577
6578 /*
6579  * Returns true if compaction should go ahead for a costly-order request, or
6580  * the allocation would already succeed without compaction. Return false if we
6581  * should reclaim first.
6582  */
6583 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6584 {
6585         unsigned long watermark;
6586         enum compact_result suitable;
6587
6588         suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6589         if (suitable == COMPACT_SUCCESS)
6590                 /* Allocation should succeed already. Don't reclaim. */
6591                 return true;
6592         if (suitable == COMPACT_SKIPPED)
6593                 /* Compaction cannot yet proceed. Do reclaim. */
6594                 return false;
6595
6596         /*
6597          * Compaction is already possible, but it takes time to run and there
6598          * are potentially other callers using the pages just freed. So proceed
6599          * with reclaim to make a buffer of free pages available to give
6600          * compaction a reasonable chance of completing and allocating the page.
6601          * Note that we won't actually reclaim the whole buffer in one attempt
6602          * as the target watermark in should_continue_reclaim() is lower. But if
6603          * we are already above the high+gap watermark, don't reclaim at all.
6604          */
6605         watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6606
6607         return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6608 }
6609
6610 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6611 {
6612         /*
6613          * If reclaim is making progress greater than 12% efficiency then
6614          * wake all the NOPROGRESS throttled tasks.
6615          */
6616         if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6617                 wait_queue_head_t *wqh;
6618
6619                 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6620                 if (waitqueue_active(wqh))
6621                         wake_up(wqh);
6622
6623                 return;
6624         }
6625
6626         /*
6627          * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6628          * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6629          * under writeback and marked for immediate reclaim at the tail of the
6630          * LRU.
6631          */
6632         if (current_is_kswapd() || cgroup_reclaim(sc))
6633                 return;
6634
6635         /* Throttle if making no progress at high prioities. */
6636         if (sc->priority == 1 && !sc->nr_reclaimed)
6637                 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6638 }
6639
6640 /*
6641  * This is the direct reclaim path, for page-allocating processes.  We only
6642  * try to reclaim pages from zones which will satisfy the caller's allocation
6643  * request.
6644  *
6645  * If a zone is deemed to be full of pinned pages then just give it a light
6646  * scan then give up on it.
6647  */
6648 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6649 {
6650         struct zoneref *z;
6651         struct zone *zone;
6652         unsigned long nr_soft_reclaimed;
6653         unsigned long nr_soft_scanned;
6654         gfp_t orig_mask;
6655         pg_data_t *last_pgdat = NULL;
6656         pg_data_t *first_pgdat = NULL;
6657
6658         /*
6659          * If the number of buffer_heads in the machine exceeds the maximum
6660          * allowed level, force direct reclaim to scan the highmem zone as
6661          * highmem pages could be pinning lowmem pages storing buffer_heads
6662          */
6663         orig_mask = sc->gfp_mask;
6664         if (buffer_heads_over_limit) {
6665                 sc->gfp_mask |= __GFP_HIGHMEM;
6666                 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6667         }
6668
6669         for_each_zone_zonelist_nodemask(zone, z, zonelist,
6670                                         sc->reclaim_idx, sc->nodemask) {
6671                 /*
6672                  * Take care memory controller reclaiming has small influence
6673                  * to global LRU.
6674                  */
6675                 if (!cgroup_reclaim(sc)) {
6676                         if (!cpuset_zone_allowed(zone,
6677                                                  GFP_KERNEL | __GFP_HARDWALL))
6678                                 continue;
6679
6680                         /*
6681                          * If we already have plenty of memory free for
6682                          * compaction in this zone, don't free any more.
6683                          * Even though compaction is invoked for any
6684                          * non-zero order, only frequent costly order
6685                          * reclamation is disruptive enough to become a
6686                          * noticeable problem, like transparent huge
6687                          * page allocations.
6688                          */
6689                         if (IS_ENABLED(CONFIG_COMPACTION) &&
6690                             sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6691                             compaction_ready(zone, sc)) {
6692                                 sc->compaction_ready = true;
6693                                 continue;
6694                         }
6695
6696                         /*
6697                          * Shrink each node in the zonelist once. If the
6698                          * zonelist is ordered by zone (not the default) then a
6699                          * node may be shrunk multiple times but in that case
6700                          * the user prefers lower zones being preserved.
6701                          */
6702                         if (zone->zone_pgdat == last_pgdat)
6703                                 continue;
6704
6705                         /*
6706                          * This steals pages from memory cgroups over softlimit
6707                          * and returns the number of reclaimed pages and
6708                          * scanned pages. This works for global memory pressure
6709                          * and balancing, not for a memcg's limit.
6710                          */
6711                         nr_soft_scanned = 0;
6712                         nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
6713                                                 sc->order, sc->gfp_mask,
6714                                                 &nr_soft_scanned);
6715                         sc->nr_reclaimed += nr_soft_reclaimed;
6716                         sc->nr_scanned += nr_soft_scanned;
6717                         /* need some check for avoid more shrink_zone() */
6718                 }
6719
6720                 if (!first_pgdat)
6721                         first_pgdat = zone->zone_pgdat;
6722
6723                 /* See comment about same check for global reclaim above */
6724                 if (zone->zone_pgdat == last_pgdat)
6725                         continue;
6726                 last_pgdat = zone->zone_pgdat;
6727                 shrink_node(zone->zone_pgdat, sc);
6728         }
6729
6730         if (first_pgdat)
6731                 consider_reclaim_throttle(first_pgdat, sc);
6732
6733         /*
6734          * Restore to original mask to avoid the impact on the caller if we
6735          * promoted it to __GFP_HIGHMEM.
6736          */
6737         sc->gfp_mask = orig_mask;
6738 }
6739
6740 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6741 {
6742         struct lruvec *target_lruvec;
6743         unsigned long refaults;
6744
6745         if (lru_gen_enabled())
6746                 return;
6747
6748         target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6749         refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6750         target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6751         refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6752         target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6753 }
6754
6755 /*
6756  * This is the main entry point to direct page reclaim.
6757  *
6758  * If a full scan of the inactive list fails to free enough memory then we
6759  * are "out of memory" and something needs to be killed.
6760  *
6761  * If the caller is !__GFP_FS then the probability of a failure is reasonably
6762  * high - the zone may be full of dirty or under-writeback pages, which this
6763  * caller can't do much about.  We kick the writeback threads and take explicit
6764  * naps in the hope that some of these pages can be written.  But if the
6765  * allocating task holds filesystem locks which prevent writeout this might not
6766  * work, and the allocation attempt will fail.
6767  *
6768  * returns:     0, if no pages reclaimed
6769  *              else, the number of pages reclaimed
6770  */
6771 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6772                                           struct scan_control *sc)
6773 {
6774         int initial_priority = sc->priority;
6775         pg_data_t *last_pgdat;
6776         struct zoneref *z;
6777         struct zone *zone;
6778 retry:
6779         delayacct_freepages_start();
6780
6781         if (!cgroup_reclaim(sc))
6782                 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6783
6784         do {
6785                 if (!sc->proactive)
6786                         vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6787                                         sc->priority);
6788                 sc->nr_scanned = 0;
6789                 shrink_zones(zonelist, sc);
6790
6791                 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6792                         break;
6793
6794                 if (sc->compaction_ready)
6795                         break;
6796
6797                 /*
6798                  * If we're getting trouble reclaiming, start doing
6799                  * writepage even in laptop mode.
6800                  */
6801                 if (sc->priority < DEF_PRIORITY - 2)
6802                         sc->may_writepage = 1;
6803         } while (--sc->priority >= 0);
6804
6805         last_pgdat = NULL;
6806         for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6807                                         sc->nodemask) {
6808                 if (zone->zone_pgdat == last_pgdat)
6809                         continue;
6810                 last_pgdat = zone->zone_pgdat;
6811
6812                 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6813
6814                 if (cgroup_reclaim(sc)) {
6815                         struct lruvec *lruvec;
6816
6817                         lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6818                                                    zone->zone_pgdat);
6819                         clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6820                 }
6821         }
6822
6823         delayacct_freepages_end();
6824
6825         if (sc->nr_reclaimed)
6826                 return sc->nr_reclaimed;
6827
6828         /* Aborted reclaim to try compaction? don't OOM, then */
6829         if (sc->compaction_ready)
6830                 return 1;
6831
6832         /*
6833          * We make inactive:active ratio decisions based on the node's
6834          * composition of memory, but a restrictive reclaim_idx or a
6835          * memory.low cgroup setting can exempt large amounts of
6836          * memory from reclaim. Neither of which are very common, so
6837          * instead of doing costly eligibility calculations of the
6838          * entire cgroup subtree up front, we assume the estimates are
6839          * good, and retry with forcible deactivation if that fails.
6840          */
6841         if (sc->skipped_deactivate) {
6842                 sc->priority = initial_priority;
6843                 sc->force_deactivate = 1;
6844                 sc->skipped_deactivate = 0;
6845                 goto retry;
6846         }
6847
6848         /* Untapped cgroup reserves?  Don't OOM, retry. */
6849         if (sc->memcg_low_skipped) {
6850                 sc->priority = initial_priority;
6851                 sc->force_deactivate = 0;
6852                 sc->memcg_low_reclaim = 1;
6853                 sc->memcg_low_skipped = 0;
6854                 goto retry;
6855         }
6856
6857         return 0;
6858 }
6859
6860 static bool allow_direct_reclaim(pg_data_t *pgdat)
6861 {
6862         struct zone *zone;
6863         unsigned long pfmemalloc_reserve = 0;
6864         unsigned long free_pages = 0;
6865         int i;
6866         bool wmark_ok;
6867
6868         if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6869                 return true;
6870
6871         for (i = 0; i <= ZONE_NORMAL; i++) {
6872                 zone = &pgdat->node_zones[i];
6873                 if (!managed_zone(zone))
6874                         continue;
6875
6876                 if (!zone_reclaimable_pages(zone))
6877                         continue;
6878
6879                 pfmemalloc_reserve += min_wmark_pages(zone);
6880                 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6881         }
6882
6883         /* If there are no reserves (unexpected config) then do not throttle */
6884         if (!pfmemalloc_reserve)
6885                 return true;
6886
6887         wmark_ok = free_pages > pfmemalloc_reserve / 2;
6888
6889         /* kswapd must be awake if processes are being throttled */
6890         if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6891                 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6892                         WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6893
6894                 wake_up_interruptible(&pgdat->kswapd_wait);
6895         }
6896
6897         return wmark_ok;
6898 }
6899
6900 /*
6901  * Throttle direct reclaimers if backing storage is backed by the network
6902  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6903  * depleted. kswapd will continue to make progress and wake the processes
6904  * when the low watermark is reached.
6905  *
6906  * Returns true if a fatal signal was delivered during throttling. If this
6907  * happens, the page allocator should not consider triggering the OOM killer.
6908  */
6909 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6910                                         nodemask_t *nodemask)
6911 {
6912         struct zoneref *z;
6913         struct zone *zone;
6914         pg_data_t *pgdat = NULL;
6915
6916         /*
6917          * Kernel threads should not be throttled as they may be indirectly
6918          * responsible for cleaning pages necessary for reclaim to make forward
6919          * progress. kjournald for example may enter direct reclaim while
6920          * committing a transaction where throttling it could forcing other
6921          * processes to block on log_wait_commit().
6922          */
6923         if (current->flags & PF_KTHREAD)
6924                 goto out;
6925
6926         /*
6927          * If a fatal signal is pending, this process should not throttle.
6928          * It should return quickly so it can exit and free its memory
6929          */
6930         if (fatal_signal_pending(current))
6931                 goto out;
6932
6933         /*
6934          * Check if the pfmemalloc reserves are ok by finding the first node
6935          * with a usable ZONE_NORMAL or lower zone. The expectation is that
6936          * GFP_KERNEL will be required for allocating network buffers when
6937          * swapping over the network so ZONE_HIGHMEM is unusable.
6938          *
6939          * Throttling is based on the first usable node and throttled processes
6940          * wait on a queue until kswapd makes progress and wakes them. There
6941          * is an affinity then between processes waking up and where reclaim
6942          * progress has been made assuming the process wakes on the same node.
6943          * More importantly, processes running on remote nodes will not compete
6944          * for remote pfmemalloc reserves and processes on different nodes
6945          * should make reasonable progress.
6946          */
6947         for_each_zone_zonelist_nodemask(zone, z, zonelist,
6948                                         gfp_zone(gfp_mask), nodemask) {
6949                 if (zone_idx(zone) > ZONE_NORMAL)
6950                         continue;
6951
6952                 /* Throttle based on the first usable node */
6953                 pgdat = zone->zone_pgdat;
6954                 if (allow_direct_reclaim(pgdat))
6955                         goto out;
6956                 break;
6957         }
6958
6959         /* If no zone was usable by the allocation flags then do not throttle */
6960         if (!pgdat)
6961                 goto out;
6962
6963         /* Account for the throttling */
6964         count_vm_event(PGSCAN_DIRECT_THROTTLE);
6965
6966         /*
6967          * If the caller cannot enter the filesystem, it's possible that it
6968          * is due to the caller holding an FS lock or performing a journal
6969          * transaction in the case of a filesystem like ext[3|4]. In this case,
6970          * it is not safe to block on pfmemalloc_wait as kswapd could be
6971          * blocked waiting on the same lock. Instead, throttle for up to a
6972          * second before continuing.
6973          */
6974         if (!(gfp_mask & __GFP_FS))
6975                 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6976                         allow_direct_reclaim(pgdat), HZ);
6977         else
6978                 /* Throttle until kswapd wakes the process */
6979                 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6980                         allow_direct_reclaim(pgdat));
6981
6982         if (fatal_signal_pending(current))
6983                 return true;
6984
6985 out:
6986         return false;
6987 }
6988
6989 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6990                                 gfp_t gfp_mask, nodemask_t *nodemask)
6991 {
6992         unsigned long nr_reclaimed;
6993         struct scan_control sc = {
6994                 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6995                 .gfp_mask = current_gfp_context(gfp_mask),
6996                 .reclaim_idx = gfp_zone(gfp_mask),
6997                 .order = order,
6998                 .nodemask = nodemask,
6999                 .priority = DEF_PRIORITY,
7000                 .may_writepage = !laptop_mode,
7001                 .may_unmap = 1,
7002                 .may_swap = 1,
7003         };
7004
7005         /*
7006          * scan_control uses s8 fields for order, priority, and reclaim_idx.
7007          * Confirm they are large enough for max values.
7008          */
7009         BUILD_BUG_ON(MAX_ORDER >= S8_MAX);
7010         BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
7011         BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
7012
7013         /*
7014          * Do not enter reclaim if fatal signal was delivered while throttled.
7015          * 1 is returned so that the page allocator does not OOM kill at this
7016          * point.
7017          */
7018         if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
7019                 return 1;
7020
7021         set_task_reclaim_state(current, &sc.reclaim_state);
7022         trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
7023
7024         nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7025
7026         trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
7027         set_task_reclaim_state(current, NULL);
7028
7029         return nr_reclaimed;
7030 }
7031
7032 #ifdef CONFIG_MEMCG
7033
7034 /* Only used by soft limit reclaim. Do not reuse for anything else. */
7035 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
7036                                                 gfp_t gfp_mask, bool noswap,
7037                                                 pg_data_t *pgdat,
7038                                                 unsigned long *nr_scanned)
7039 {
7040         struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
7041         struct scan_control sc = {
7042                 .nr_to_reclaim = SWAP_CLUSTER_MAX,
7043                 .target_mem_cgroup = memcg,
7044                 .may_writepage = !laptop_mode,
7045                 .may_unmap = 1,
7046                 .reclaim_idx = MAX_NR_ZONES - 1,
7047                 .may_swap = !noswap,
7048         };
7049
7050         WARN_ON_ONCE(!current->reclaim_state);
7051
7052         sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
7053                         (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
7054
7055         trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
7056                                                       sc.gfp_mask);
7057
7058         /*
7059          * NOTE: Although we can get the priority field, using it
7060          * here is not a good idea, since it limits the pages we can scan.
7061          * if we don't reclaim here, the shrink_node from balance_pgdat
7062          * will pick up pages from other mem cgroup's as well. We hack
7063          * the priority and make it zero.
7064          */
7065         shrink_lruvec(lruvec, &sc);
7066
7067         trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
7068
7069         *nr_scanned = sc.nr_scanned;
7070
7071         return sc.nr_reclaimed;
7072 }
7073
7074 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
7075                                            unsigned long nr_pages,
7076                                            gfp_t gfp_mask,
7077                                            unsigned int reclaim_options)
7078 {
7079         unsigned long nr_reclaimed;
7080         unsigned int noreclaim_flag;
7081         struct scan_control sc = {
7082                 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7083                 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
7084                                 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
7085                 .reclaim_idx = MAX_NR_ZONES - 1,
7086                 .target_mem_cgroup = memcg,
7087                 .priority = DEF_PRIORITY,
7088                 .may_writepage = !laptop_mode,
7089                 .may_unmap = 1,
7090                 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
7091                 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
7092         };
7093         /*
7094          * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
7095          * equal pressure on all the nodes. This is based on the assumption that
7096          * the reclaim does not bail out early.
7097          */
7098         struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7099
7100         set_task_reclaim_state(current, &sc.reclaim_state);
7101         trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
7102         noreclaim_flag = memalloc_noreclaim_save();
7103
7104         nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7105
7106         memalloc_noreclaim_restore(noreclaim_flag);
7107         trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
7108         set_task_reclaim_state(current, NULL);
7109
7110         return nr_reclaimed;
7111 }
7112 #endif
7113
7114 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
7115 {
7116         struct mem_cgroup *memcg;
7117         struct lruvec *lruvec;
7118
7119         if (lru_gen_enabled()) {
7120                 lru_gen_age_node(pgdat, sc);
7121                 return;
7122         }
7123
7124         if (!can_age_anon_pages(pgdat, sc))
7125                 return;
7126
7127         lruvec = mem_cgroup_lruvec(NULL, pgdat);
7128         if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
7129                 return;
7130
7131         memcg = mem_cgroup_iter(NULL, NULL, NULL);
7132         do {
7133                 lruvec = mem_cgroup_lruvec(memcg, pgdat);
7134                 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
7135                                    sc, LRU_ACTIVE_ANON);
7136                 memcg = mem_cgroup_iter(NULL, memcg, NULL);
7137         } while (memcg);
7138 }
7139
7140 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
7141 {
7142         int i;
7143         struct zone *zone;
7144
7145         /*
7146          * Check for watermark boosts top-down as the higher zones
7147          * are more likely to be boosted. Both watermarks and boosts
7148          * should not be checked at the same time as reclaim would
7149          * start prematurely when there is no boosting and a lower
7150          * zone is balanced.
7151          */
7152         for (i = highest_zoneidx; i >= 0; i--) {
7153                 zone = pgdat->node_zones + i;
7154                 if (!managed_zone(zone))
7155                         continue;
7156
7157                 if (zone->watermark_boost)
7158                         return true;
7159         }
7160
7161         return false;
7162 }
7163
7164 /*
7165  * Returns true if there is an eligible zone balanced for the request order
7166  * and highest_zoneidx
7167  */
7168 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
7169 {
7170         int i;
7171         unsigned long mark = -1;
7172         struct zone *zone;
7173
7174         /*
7175          * Check watermarks bottom-up as lower zones are more likely to
7176          * meet watermarks.
7177          */
7178         for (i = 0; i <= highest_zoneidx; i++) {
7179                 zone = pgdat->node_zones + i;
7180
7181                 if (!managed_zone(zone))
7182                         continue;
7183
7184                 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
7185                         mark = wmark_pages(zone, WMARK_PROMO);
7186                 else
7187                         mark = high_wmark_pages(zone);
7188                 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
7189                         return true;
7190         }
7191
7192         /*
7193          * If a node has no managed zone within highest_zoneidx, it does not
7194          * need balancing by definition. This can happen if a zone-restricted
7195          * allocation tries to wake a remote kswapd.
7196          */
7197         if (mark == -1)
7198                 return true;
7199
7200         return false;
7201 }
7202
7203 /* Clear pgdat state for congested, dirty or under writeback. */
7204 static void clear_pgdat_congested(pg_data_t *pgdat)
7205 {
7206         struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
7207
7208         clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
7209         clear_bit(PGDAT_DIRTY, &pgdat->flags);
7210         clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
7211 }
7212
7213 /*
7214  * Prepare kswapd for sleeping. This verifies that there are no processes
7215  * waiting in throttle_direct_reclaim() and that watermarks have been met.
7216  *
7217  * Returns true if kswapd is ready to sleep
7218  */
7219 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
7220                                 int highest_zoneidx)
7221 {
7222         /*
7223          * The throttled processes are normally woken up in balance_pgdat() as
7224          * soon as allow_direct_reclaim() is true. But there is a potential
7225          * race between when kswapd checks the watermarks and a process gets
7226          * throttled. There is also a potential race if processes get
7227          * throttled, kswapd wakes, a large process exits thereby balancing the
7228          * zones, which causes kswapd to exit balance_pgdat() before reaching
7229          * the wake up checks. If kswapd is going to sleep, no process should
7230          * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
7231          * the wake up is premature, processes will wake kswapd and get
7232          * throttled again. The difference from wake ups in balance_pgdat() is
7233          * that here we are under prepare_to_wait().
7234          */
7235         if (waitqueue_active(&pgdat->pfmemalloc_wait))
7236                 wake_up_all(&pgdat->pfmemalloc_wait);
7237
7238         /* Hopeless node, leave it to direct reclaim */
7239         if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
7240                 return true;
7241
7242         if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
7243                 clear_pgdat_congested(pgdat);
7244                 return true;
7245         }
7246
7247         return false;
7248 }
7249
7250 /*
7251  * kswapd shrinks a node of pages that are at or below the highest usable
7252  * zone that is currently unbalanced.
7253  *
7254  * Returns true if kswapd scanned at least the requested number of pages to
7255  * reclaim or if the lack of progress was due to pages under writeback.
7256  * This is used to determine if the scanning priority needs to be raised.
7257  */
7258 static bool kswapd_shrink_node(pg_data_t *pgdat,
7259                                struct scan_control *sc)
7260 {
7261         struct zone *zone;
7262         int z;
7263
7264         /* Reclaim a number of pages proportional to the number of zones */
7265         sc->nr_to_reclaim = 0;
7266         for (z = 0; z <= sc->reclaim_idx; z++) {
7267                 zone = pgdat->node_zones + z;
7268                 if (!managed_zone(zone))
7269                         continue;
7270
7271                 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
7272         }
7273
7274         /*
7275          * Historically care was taken to put equal pressure on all zones but
7276          * now pressure is applied based on node LRU order.
7277          */
7278         shrink_node(pgdat, sc);
7279
7280         /*
7281          * Fragmentation may mean that the system cannot be rebalanced for
7282          * high-order allocations. If twice the allocation size has been
7283          * reclaimed then recheck watermarks only at order-0 to prevent
7284          * excessive reclaim. Assume that a process requested a high-order
7285          * can direct reclaim/compact.
7286          */
7287         if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
7288                 sc->order = 0;
7289
7290         return sc->nr_scanned >= sc->nr_to_reclaim;
7291 }
7292
7293 /* Page allocator PCP high watermark is lowered if reclaim is active. */
7294 static inline void
7295 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7296 {
7297         int i;
7298         struct zone *zone;
7299
7300         for (i = 0; i <= highest_zoneidx; i++) {
7301                 zone = pgdat->node_zones + i;
7302
7303                 if (!managed_zone(zone))
7304                         continue;
7305
7306                 if (active)
7307                         set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7308                 else
7309                         clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7310         }
7311 }
7312
7313 static inline void
7314 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7315 {
7316         update_reclaim_active(pgdat, highest_zoneidx, true);
7317 }
7318
7319 static inline void
7320 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7321 {
7322         update_reclaim_active(pgdat, highest_zoneidx, false);
7323 }
7324
7325 /*
7326  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7327  * that are eligible for use by the caller until at least one zone is
7328  * balanced.
7329  *
7330  * Returns the order kswapd finished reclaiming at.
7331  *
7332  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
7333  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
7334  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
7335  * or lower is eligible for reclaim until at least one usable zone is
7336  * balanced.
7337  */
7338 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
7339 {
7340         int i;
7341         unsigned long nr_soft_reclaimed;
7342         unsigned long nr_soft_scanned;
7343         unsigned long pflags;
7344         unsigned long nr_boost_reclaim;
7345         unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7346         bool boosted;
7347         struct zone *zone;
7348         struct scan_control sc = {
7349                 .gfp_mask = GFP_KERNEL,
7350                 .order = order,
7351                 .may_unmap = 1,
7352         };
7353
7354         set_task_reclaim_state(current, &sc.reclaim_state);
7355         psi_memstall_enter(&pflags);
7356         __fs_reclaim_acquire(_THIS_IP_);
7357
7358         count_vm_event(PAGEOUTRUN);
7359
7360         /*
7361          * Account for the reclaim boost. Note that the zone boost is left in
7362          * place so that parallel allocations that are near the watermark will
7363          * stall or direct reclaim until kswapd is finished.
7364          */
7365         nr_boost_reclaim = 0;
7366         for (i = 0; i <= highest_zoneidx; i++) {
7367                 zone = pgdat->node_zones + i;
7368                 if (!managed_zone(zone))
7369                         continue;
7370
7371                 nr_boost_reclaim += zone->watermark_boost;
7372                 zone_boosts[i] = zone->watermark_boost;
7373         }
7374         boosted = nr_boost_reclaim;
7375
7376 restart:
7377         set_reclaim_active(pgdat, highest_zoneidx);
7378         sc.priority = DEF_PRIORITY;
7379         do {
7380                 unsigned long nr_reclaimed = sc.nr_reclaimed;
7381                 bool raise_priority = true;
7382                 bool balanced;
7383                 bool ret;
7384
7385                 sc.reclaim_idx = highest_zoneidx;
7386
7387                 /*
7388                  * If the number of buffer_heads exceeds the maximum allowed
7389                  * then consider reclaiming from all zones. This has a dual
7390                  * purpose -- on 64-bit systems it is expected that
7391                  * buffer_heads are stripped during active rotation. On 32-bit
7392                  * systems, highmem pages can pin lowmem memory and shrinking
7393                  * buffers can relieve lowmem pressure. Reclaim may still not
7394                  * go ahead if all eligible zones for the original allocation
7395                  * request are balanced to avoid excessive reclaim from kswapd.
7396                  */
7397                 if (buffer_heads_over_limit) {
7398                         for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7399                                 zone = pgdat->node_zones + i;
7400                                 if (!managed_zone(zone))
7401                                         continue;
7402
7403                                 sc.reclaim_idx = i;
7404                                 break;
7405                         }
7406                 }
7407
7408                 /*
7409                  * If the pgdat is imbalanced then ignore boosting and preserve
7410                  * the watermarks for a later time and restart. Note that the
7411                  * zone watermarks will be still reset at the end of balancing
7412                  * on the grounds that the normal reclaim should be enough to
7413                  * re-evaluate if boosting is required when kswapd next wakes.
7414                  */
7415                 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
7416                 if (!balanced && nr_boost_reclaim) {
7417                         nr_boost_reclaim = 0;
7418                         goto restart;
7419                 }
7420
7421                 /*
7422                  * If boosting is not active then only reclaim if there are no
7423                  * eligible zones. Note that sc.reclaim_idx is not used as
7424                  * buffer_heads_over_limit may have adjusted it.
7425                  */
7426                 if (!nr_boost_reclaim && balanced)
7427                         goto out;
7428
7429                 /* Limit the priority of boosting to avoid reclaim writeback */
7430                 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7431                         raise_priority = false;
7432
7433                 /*
7434                  * Do not writeback or swap pages for boosted reclaim. The
7435                  * intent is to relieve pressure not issue sub-optimal IO
7436                  * from reclaim context. If no pages are reclaimed, the
7437                  * reclaim will be aborted.
7438                  */
7439                 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7440                 sc.may_swap = !nr_boost_reclaim;
7441
7442                 /*
7443                  * Do some background aging, to give pages a chance to be
7444                  * referenced before reclaiming. All pages are rotated
7445                  * regardless of classzone as this is about consistent aging.
7446                  */
7447                 kswapd_age_node(pgdat, &sc);
7448
7449                 /*
7450                  * If we're getting trouble reclaiming, start doing writepage
7451                  * even in laptop mode.
7452                  */
7453                 if (sc.priority < DEF_PRIORITY - 2)
7454                         sc.may_writepage = 1;
7455
7456                 /* Call soft limit reclaim before calling shrink_node. */
7457                 sc.nr_scanned = 0;
7458                 nr_soft_scanned = 0;
7459                 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
7460                                                 sc.gfp_mask, &nr_soft_scanned);
7461                 sc.nr_reclaimed += nr_soft_reclaimed;
7462
7463                 /*
7464                  * There should be no need to raise the scanning priority if
7465                  * enough pages are already being scanned that that high
7466                  * watermark would be met at 100% efficiency.
7467                  */
7468                 if (kswapd_shrink_node(pgdat, &sc))
7469                         raise_priority = false;
7470
7471                 /*
7472                  * If the low watermark is met there is no need for processes
7473                  * to be throttled on pfmemalloc_wait as they should not be
7474                  * able to safely make forward progress. Wake them
7475                  */
7476                 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
7477                                 allow_direct_reclaim(pgdat))
7478                         wake_up_all(&pgdat->pfmemalloc_wait);
7479
7480                 /* Check if kswapd should be suspending */
7481                 __fs_reclaim_release(_THIS_IP_);
7482                 ret = try_to_freeze();
7483                 __fs_reclaim_acquire(_THIS_IP_);
7484                 if (ret || kthread_should_stop())
7485                         break;
7486
7487                 /*
7488                  * Raise priority if scanning rate is too low or there was no
7489                  * progress in reclaiming pages
7490                  */
7491                 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
7492                 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7493
7494                 /*
7495                  * If reclaim made no progress for a boost, stop reclaim as
7496                  * IO cannot be queued and it could be an infinite loop in
7497                  * extreme circumstances.
7498                  */
7499                 if (nr_boost_reclaim && !nr_reclaimed)
7500                         break;
7501
7502                 if (raise_priority || !nr_reclaimed)
7503                         sc.priority--;
7504         } while (sc.priority >= 1);
7505
7506         if (!sc.nr_reclaimed)
7507                 pgdat->kswapd_failures++;
7508
7509 out:
7510         clear_reclaim_active(pgdat, highest_zoneidx);
7511
7512         /* If reclaim was boosted, account for the reclaim done in this pass */
7513         if (boosted) {
7514                 unsigned long flags;
7515
7516                 for (i = 0; i <= highest_zoneidx; i++) {
7517                         if (!zone_boosts[i])
7518                                 continue;
7519
7520                         /* Increments are under the zone lock */
7521                         zone = pgdat->node_zones + i;
7522                         spin_lock_irqsave(&zone->lock, flags);
7523                         zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7524                         spin_unlock_irqrestore(&zone->lock, flags);
7525                 }
7526
7527                 /*
7528                  * As there is now likely space, wakeup kcompact to defragment
7529                  * pageblocks.
7530                  */
7531                 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7532         }
7533
7534         snapshot_refaults(NULL, pgdat);
7535         __fs_reclaim_release(_THIS_IP_);
7536         psi_memstall_leave(&pflags);
7537         set_task_reclaim_state(current, NULL);
7538
7539         /*
7540          * Return the order kswapd stopped reclaiming at as
7541          * prepare_kswapd_sleep() takes it into account. If another caller
7542          * entered the allocator slow path while kswapd was awake, order will
7543          * remain at the higher level.
7544          */
7545         return sc.order;
7546 }
7547
7548 /*
7549  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7550  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7551  * not a valid index then either kswapd runs for first time or kswapd couldn't
7552  * sleep after previous reclaim attempt (node is still unbalanced). In that
7553  * case return the zone index of the previous kswapd reclaim cycle.
7554  */
7555 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7556                                            enum zone_type prev_highest_zoneidx)
7557 {
7558         enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7559
7560         return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7561 }
7562
7563 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7564                                 unsigned int highest_zoneidx)
7565 {
7566         long remaining = 0;
7567         DEFINE_WAIT(wait);
7568
7569         if (freezing(current) || kthread_should_stop())
7570                 return;
7571
7572         prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7573
7574         /*
7575          * Try to sleep for a short interval. Note that kcompactd will only be
7576          * woken if it is possible to sleep for a short interval. This is
7577          * deliberate on the assumption that if reclaim cannot keep an
7578          * eligible zone balanced that it's also unlikely that compaction will
7579          * succeed.
7580          */
7581         if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7582                 /*
7583                  * Compaction records what page blocks it recently failed to
7584                  * isolate pages from and skips them in the future scanning.
7585                  * When kswapd is going to sleep, it is reasonable to assume
7586                  * that pages and compaction may succeed so reset the cache.
7587                  */
7588                 reset_isolation_suitable(pgdat);
7589
7590                 /*
7591                  * We have freed the memory, now we should compact it to make
7592                  * allocation of the requested order possible.
7593                  */
7594                 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7595
7596                 remaining = schedule_timeout(HZ/10);
7597
7598                 /*
7599                  * If woken prematurely then reset kswapd_highest_zoneidx and
7600                  * order. The values will either be from a wakeup request or
7601                  * the previous request that slept prematurely.
7602                  */
7603                 if (remaining) {
7604                         WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7605                                         kswapd_highest_zoneidx(pgdat,
7606                                                         highest_zoneidx));
7607
7608                         if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7609                                 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7610                 }
7611
7612                 finish_wait(&pgdat->kswapd_wait, &wait);
7613                 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7614         }
7615
7616         /*
7617          * After a short sleep, check if it was a premature sleep. If not, then
7618          * go fully to sleep until explicitly woken up.
7619          */
7620         if (!remaining &&
7621             prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7622                 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7623
7624                 /*
7625                  * vmstat counters are not perfectly accurate and the estimated
7626                  * value for counters such as NR_FREE_PAGES can deviate from the
7627                  * true value by nr_online_cpus * threshold. To avoid the zone
7628                  * watermarks being breached while under pressure, we reduce the
7629                  * per-cpu vmstat threshold while kswapd is awake and restore
7630                  * them before going back to sleep.
7631                  */
7632                 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7633
7634                 if (!kthread_should_stop())
7635                         schedule();
7636
7637                 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7638         } else {
7639                 if (remaining)
7640                         count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7641                 else
7642                         count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7643         }
7644         finish_wait(&pgdat->kswapd_wait, &wait);
7645 }
7646
7647 /*
7648  * The background pageout daemon, started as a kernel thread
7649  * from the init process.
7650  *
7651  * This basically trickles out pages so that we have _some_
7652  * free memory available even if there is no other activity
7653  * that frees anything up. This is needed for things like routing
7654  * etc, where we otherwise might have all activity going on in
7655  * asynchronous contexts that cannot page things out.
7656  *
7657  * If there are applications that are active memory-allocators
7658  * (most normal use), this basically shouldn't matter.
7659  */
7660 static int kswapd(void *p)
7661 {
7662         unsigned int alloc_order, reclaim_order;
7663         unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7664         pg_data_t *pgdat = (pg_data_t *)p;
7665         struct task_struct *tsk = current;
7666         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7667
7668         if (!cpumask_empty(cpumask))
7669                 set_cpus_allowed_ptr(tsk, cpumask);
7670
7671         /*
7672          * Tell the memory management that we're a "memory allocator",
7673          * and that if we need more memory we should get access to it
7674          * regardless (see "__alloc_pages()"). "kswapd" should
7675          * never get caught in the normal page freeing logic.
7676          *
7677          * (Kswapd normally doesn't need memory anyway, but sometimes
7678          * you need a small amount of memory in order to be able to
7679          * page out something else, and this flag essentially protects
7680          * us from recursively trying to free more memory as we're
7681          * trying to free the first piece of memory in the first place).
7682          */
7683         tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7684         set_freezable();
7685
7686         WRITE_ONCE(pgdat->kswapd_order, 0);
7687         WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7688         atomic_set(&pgdat->nr_writeback_throttled, 0);
7689         for ( ; ; ) {
7690                 bool ret;
7691
7692                 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7693                 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7694                                                         highest_zoneidx);
7695
7696 kswapd_try_sleep:
7697                 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7698                                         highest_zoneidx);
7699
7700                 /* Read the new order and highest_zoneidx */
7701                 alloc_order = READ_ONCE(pgdat->kswapd_order);
7702                 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7703                                                         highest_zoneidx);
7704                 WRITE_ONCE(pgdat->kswapd_order, 0);
7705                 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7706
7707                 ret = try_to_freeze();
7708                 if (kthread_should_stop())
7709                         break;
7710
7711                 /*
7712                  * We can speed up thawing tasks if we don't call balance_pgdat
7713                  * after returning from the refrigerator
7714                  */
7715                 if (ret)
7716                         continue;
7717
7718                 /*
7719                  * Reclaim begins at the requested order but if a high-order
7720                  * reclaim fails then kswapd falls back to reclaiming for
7721                  * order-0. If that happens, kswapd will consider sleeping
7722                  * for the order it finished reclaiming at (reclaim_order)
7723                  * but kcompactd is woken to compact for the original
7724                  * request (alloc_order).
7725                  */
7726                 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7727                                                 alloc_order);
7728                 reclaim_order = balance_pgdat(pgdat, alloc_order,
7729                                                 highest_zoneidx);
7730                 if (reclaim_order < alloc_order)
7731                         goto kswapd_try_sleep;
7732         }
7733
7734         tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7735
7736         return 0;
7737 }
7738
7739 /*
7740  * A zone is low on free memory or too fragmented for high-order memory.  If
7741  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7742  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
7743  * has failed or is not needed, still wake up kcompactd if only compaction is
7744  * needed.
7745  */
7746 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7747                    enum zone_type highest_zoneidx)
7748 {
7749         pg_data_t *pgdat;
7750         enum zone_type curr_idx;
7751
7752         if (!managed_zone(zone))
7753                 return;
7754
7755         if (!cpuset_zone_allowed(zone, gfp_flags))
7756                 return;
7757
7758         pgdat = zone->zone_pgdat;
7759         curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7760
7761         if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7762                 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7763
7764         if (READ_ONCE(pgdat->kswapd_order) < order)
7765                 WRITE_ONCE(pgdat->kswapd_order, order);
7766
7767         if (!waitqueue_active(&pgdat->kswapd_wait))
7768                 return;
7769
7770         /* Hopeless node, leave it to direct reclaim if possible */
7771         if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7772             (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7773              !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7774                 /*
7775                  * There may be plenty of free memory available, but it's too
7776                  * fragmented for high-order allocations.  Wake up kcompactd
7777                  * and rely on compaction_suitable() to determine if it's
7778                  * needed.  If it fails, it will defer subsequent attempts to
7779                  * ratelimit its work.
7780                  */
7781                 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7782                         wakeup_kcompactd(pgdat, order, highest_zoneidx);
7783                 return;
7784         }
7785
7786         trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7787                                       gfp_flags);
7788         wake_up_interruptible(&pgdat->kswapd_wait);
7789 }
7790
7791 #ifdef CONFIG_HIBERNATION
7792 /*
7793  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7794  * freed pages.
7795  *
7796  * Rather than trying to age LRUs the aim is to preserve the overall
7797  * LRU order by reclaiming preferentially
7798  * inactive > active > active referenced > active mapped
7799  */
7800 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7801 {
7802         struct scan_control sc = {
7803                 .nr_to_reclaim = nr_to_reclaim,
7804                 .gfp_mask = GFP_HIGHUSER_MOVABLE,
7805                 .reclaim_idx = MAX_NR_ZONES - 1,
7806                 .priority = DEF_PRIORITY,
7807                 .may_writepage = 1,
7808                 .may_unmap = 1,
7809                 .may_swap = 1,
7810                 .hibernation_mode = 1,
7811         };
7812         struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7813         unsigned long nr_reclaimed;
7814         unsigned int noreclaim_flag;
7815
7816         fs_reclaim_acquire(sc.gfp_mask);
7817         noreclaim_flag = memalloc_noreclaim_save();
7818         set_task_reclaim_state(current, &sc.reclaim_state);
7819
7820         nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7821
7822         set_task_reclaim_state(current, NULL);
7823         memalloc_noreclaim_restore(noreclaim_flag);
7824         fs_reclaim_release(sc.gfp_mask);
7825
7826         return nr_reclaimed;
7827 }
7828 #endif /* CONFIG_HIBERNATION */
7829
7830 /*
7831  * This kswapd start function will be called by init and node-hot-add.
7832  */
7833 void kswapd_run(int nid)
7834 {
7835         pg_data_t *pgdat = NODE_DATA(nid);
7836
7837         pgdat_kswapd_lock(pgdat);
7838         if (!pgdat->kswapd) {
7839                 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7840                 if (IS_ERR(pgdat->kswapd)) {
7841                         /* failure at boot is fatal */
7842                         BUG_ON(system_state < SYSTEM_RUNNING);
7843                         pr_err("Failed to start kswapd on node %d\n", nid);
7844                         pgdat->kswapd = NULL;
7845                 }
7846         }
7847         pgdat_kswapd_unlock(pgdat);
7848 }
7849
7850 /*
7851  * Called by memory hotplug when all memory in a node is offlined.  Caller must
7852  * be holding mem_hotplug_begin/done().
7853  */
7854 void kswapd_stop(int nid)
7855 {
7856         pg_data_t *pgdat = NODE_DATA(nid);
7857         struct task_struct *kswapd;
7858
7859         pgdat_kswapd_lock(pgdat);
7860         kswapd = pgdat->kswapd;
7861         if (kswapd) {
7862                 kthread_stop(kswapd);
7863                 pgdat->kswapd = NULL;
7864         }
7865         pgdat_kswapd_unlock(pgdat);
7866 }
7867
7868 static int __init kswapd_init(void)
7869 {
7870         int nid;
7871
7872         swap_setup();
7873         for_each_node_state(nid, N_MEMORY)
7874                 kswapd_run(nid);
7875         return 0;
7876 }
7877
7878 module_init(kswapd_init)
7879
7880 #ifdef CONFIG_NUMA
7881 /*
7882  * Node reclaim mode
7883  *
7884  * If non-zero call node_reclaim when the number of free pages falls below
7885  * the watermarks.
7886  */
7887 int node_reclaim_mode __read_mostly;
7888
7889 /*
7890  * Priority for NODE_RECLAIM. This determines the fraction of pages
7891  * of a node considered for each zone_reclaim. 4 scans 1/16th of
7892  * a zone.
7893  */
7894 #define NODE_RECLAIM_PRIORITY 4
7895
7896 /*
7897  * Percentage of pages in a zone that must be unmapped for node_reclaim to
7898  * occur.
7899  */
7900 int sysctl_min_unmapped_ratio = 1;
7901
7902 /*
7903  * If the number of slab pages in a zone grows beyond this percentage then
7904  * slab reclaim needs to occur.
7905  */
7906 int sysctl_min_slab_ratio = 5;
7907
7908 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7909 {
7910         unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7911         unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7912                 node_page_state(pgdat, NR_ACTIVE_FILE);
7913
7914         /*
7915          * It's possible for there to be more file mapped pages than
7916          * accounted for by the pages on the file LRU lists because
7917          * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7918          */
7919         return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7920 }
7921
7922 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7923 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7924 {
7925         unsigned long nr_pagecache_reclaimable;
7926         unsigned long delta = 0;
7927
7928         /*
7929          * If RECLAIM_UNMAP is set, then all file pages are considered
7930          * potentially reclaimable. Otherwise, we have to worry about
7931          * pages like swapcache and node_unmapped_file_pages() provides
7932          * a better estimate
7933          */
7934         if (node_reclaim_mode & RECLAIM_UNMAP)
7935                 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7936         else
7937                 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7938
7939         /* If we can't clean pages, remove dirty pages from consideration */
7940         if (!(node_reclaim_mode & RECLAIM_WRITE))
7941                 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7942
7943         /* Watch for any possible underflows due to delta */
7944         if (unlikely(delta > nr_pagecache_reclaimable))
7945                 delta = nr_pagecache_reclaimable;
7946
7947         return nr_pagecache_reclaimable - delta;
7948 }
7949
7950 /*
7951  * Try to free up some pages from this node through reclaim.
7952  */
7953 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7954 {
7955         /* Minimum pages needed in order to stay on node */
7956         const unsigned long nr_pages = 1 << order;
7957         struct task_struct *p = current;
7958         unsigned int noreclaim_flag;
7959         struct scan_control sc = {
7960                 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7961                 .gfp_mask = current_gfp_context(gfp_mask),
7962                 .order = order,
7963                 .priority = NODE_RECLAIM_PRIORITY,
7964                 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7965                 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7966                 .may_swap = 1,
7967                 .reclaim_idx = gfp_zone(gfp_mask),
7968         };
7969         unsigned long pflags;
7970
7971         trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7972                                            sc.gfp_mask);
7973
7974         cond_resched();
7975         psi_memstall_enter(&pflags);
7976         fs_reclaim_acquire(sc.gfp_mask);
7977         /*
7978          * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7979          */
7980         noreclaim_flag = memalloc_noreclaim_save();
7981         set_task_reclaim_state(p, &sc.reclaim_state);
7982
7983         if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7984             node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7985                 /*
7986                  * Free memory by calling shrink node with increasing
7987                  * priorities until we have enough memory freed.
7988                  */
7989                 do {
7990                         shrink_node(pgdat, &sc);
7991                 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7992         }
7993
7994         set_task_reclaim_state(p, NULL);
7995         memalloc_noreclaim_restore(noreclaim_flag);
7996         fs_reclaim_release(sc.gfp_mask);
7997         psi_memstall_leave(&pflags);
7998
7999         trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
8000
8001         return sc.nr_reclaimed >= nr_pages;
8002 }
8003
8004 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
8005 {
8006         int ret;
8007
8008         /*
8009          * Node reclaim reclaims unmapped file backed pages and
8010          * slab pages if we are over the defined limits.
8011          *
8012          * A small portion of unmapped file backed pages is needed for
8013          * file I/O otherwise pages read by file I/O will be immediately
8014          * thrown out if the node is overallocated. So we do not reclaim
8015          * if less than a specified percentage of the node is used by
8016          * unmapped file backed pages.
8017          */
8018         if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
8019             node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
8020             pgdat->min_slab_pages)
8021                 return NODE_RECLAIM_FULL;
8022
8023         /*
8024          * Do not scan if the allocation should not be delayed.
8025          */
8026         if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
8027                 return NODE_RECLAIM_NOSCAN;
8028
8029         /*
8030          * Only run node reclaim on the local node or on nodes that do not
8031          * have associated processors. This will favor the local processor
8032          * over remote processors and spread off node memory allocations
8033          * as wide as possible.
8034          */
8035         if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
8036                 return NODE_RECLAIM_NOSCAN;
8037
8038         if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
8039                 return NODE_RECLAIM_NOSCAN;
8040
8041         ret = __node_reclaim(pgdat, gfp_mask, order);
8042         clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
8043
8044         if (!ret)
8045                 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
8046
8047         return ret;
8048 }
8049 #endif
8050
8051 void check_move_unevictable_pages(struct pagevec *pvec)
8052 {
8053         struct folio_batch fbatch;
8054         unsigned i;
8055
8056         folio_batch_init(&fbatch);
8057         for (i = 0; i < pvec->nr; i++) {
8058                 struct page *page = pvec->pages[i];
8059
8060                 if (PageTransTail(page))
8061                         continue;
8062                 folio_batch_add(&fbatch, page_folio(page));
8063         }
8064         check_move_unevictable_folios(&fbatch);
8065 }
8066 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
8067
8068 /**
8069  * check_move_unevictable_folios - Move evictable folios to appropriate zone
8070  * lru list
8071  * @fbatch: Batch of lru folios to check.
8072  *
8073  * Checks folios for evictability, if an evictable folio is in the unevictable
8074  * lru list, moves it to the appropriate evictable lru list. This function
8075  * should be only used for lru folios.
8076  */
8077 void check_move_unevictable_folios(struct folio_batch *fbatch)
8078 {
8079         struct lruvec *lruvec = NULL;
8080         int pgscanned = 0;
8081         int pgrescued = 0;
8082         int i;
8083
8084         for (i = 0; i < fbatch->nr; i++) {
8085                 struct folio *folio = fbatch->folios[i];
8086                 int nr_pages = folio_nr_pages(folio);
8087
8088                 pgscanned += nr_pages;
8089
8090                 /* block memcg migration while the folio moves between lrus */
8091                 if (!folio_test_clear_lru(folio))
8092                         continue;
8093
8094                 lruvec = folio_lruvec_relock_irq(folio, lruvec);
8095                 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
8096                         lruvec_del_folio(lruvec, folio);
8097                         folio_clear_unevictable(folio);
8098                         lruvec_add_folio(lruvec, folio);
8099                         pgrescued += nr_pages;
8100                 }
8101                 folio_set_lru(folio);
8102         }
8103
8104         if (lruvec) {
8105                 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
8106                 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
8107                 unlock_page_lruvec_irq(lruvec);
8108         } else if (pgscanned) {
8109                 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
8110         }
8111 }
8112 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);