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