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