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