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