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