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