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