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