linux/mm/vmscan.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
   4 *
   5 *  Swap reorganised 29.12.95, Stephen Tweedie.
   6 *  kswapd added: 7.1.96  sct
   7 *  Removed kswapd_ctl limits, and swap out as many pages as needed
   8 *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
   9 *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
  10 *  Multiqueue VM started 5.8.00, Rik van Riel.
  11 */
  12
  13#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  14
  15#include <linux/mm.h>
  16#include <linux/sched/mm.h>
  17#include <linux/module.h>
  18#include <linux/gfp.h>
  19#include <linux/kernel_stat.h>
  20#include <linux/swap.h>
  21#include <linux/pagemap.h>
  22#include <linux/init.h>
  23#include <linux/highmem.h>
  24#include <linux/vmpressure.h>
  25#include <linux/vmstat.h>
  26#include <linux/file.h>
  27#include <linux/writeback.h>
  28#include <linux/blkdev.h>
  29#include <linux/buffer_head.h>  /* for buffer_heads_over_limit */
  30#include <linux/mm_inline.h>
  31#include <linux/backing-dev.h>
  32#include <linux/rmap.h>
  33#include <linux/topology.h>
  34#include <linux/cpu.h>
  35#include <linux/cpuset.h>
  36#include <linux/compaction.h>
  37#include <linux/notifier.h>
  38#include <linux/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
  73struct 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 */
 188int vm_swappiness = 60;
 189
 190#ifdef CONFIG_MEMCG
 191
 192/* Returns true for reclaim through cgroup limits or cgroup interfaces. */
 193static 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 */
 202static 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 */
 220static 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
 231static bool cgroup_reclaim(struct scan_control *sc)
 232{
 233        return false;
 234}
 235
 236static bool root_reclaim(struct scan_control *sc)
 237{
 238        return true;
 239}
 240
 241static bool writeback_throttling_sane(struct scan_control *sc)
 242{
 243        return true;
 244}
 245#endif
 246
 247static 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 */
 263static 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
 299static 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
 311static 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 */
 341unsigned 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 */
 360static 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
 380static 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
 393void 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
 410static int reclaimer_offset(void)
 411{
 412        BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
 413                        PGDEMOTE_DIRECT - PGDEMOTE_KSWAPD);
 414        BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
 415                        PGSCAN_DIRECT - PGSCAN_KSWAPD);
 416        BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
 417                        PGDEMOTE_KHUGEPAGED - PGDEMOTE_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
 428static 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 */
 451static 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
 460static 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
 493void 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 */
 567void __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() */
 589typedef 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 */
 604static 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 */
 678static 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
 768cannot_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 */
 787long 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 */
 810void folio_putback_lru(struct folio *folio)
 811{
 812        folio_add_lru(folio);
 813        folio_put(folio);               /* drop ref from isolate */
 814}
 815
 816enum folio_references {
 817        FOLIOREF_RECLAIM,
 818        FOLIOREF_RECLAIM_CLEAN,
 819        FOLIOREF_KEEP,
 820        FOLIOREF_ACTIVATE,
 821};
 822
 823static 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 */
 881static 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
 913static 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 */
 948static 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        __count_vm_events(PGDEMOTE_KSWAPD + reclaimer_offset(), nr_succeeded);
 981
 982        return nr_succeeded;
 983}
 984
 985static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
 986{
 987        if (gfp_mask & __GFP_FS)
 988                return true;
 989        if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
 990                return false;
 991        /*
 992         * We can "enter_fs" for swap-cache with only __GFP_IO
 993         * providing this isn't SWP_FS_OPS.
 994         * ->flags can be updated non-atomicially (scan_swap_map_slots),
 995         * but that will never affect SWP_FS_OPS, so the data_race
 996         * is safe.
 997         */
 998        return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
 999}
1000
1001/*
1002 * shrink_folio_list() returns the number of reclaimed pages
1003 */
1004static unsigned int shrink_folio_list(struct list_head *folio_list,
1005                struct pglist_data *pgdat, struct scan_control *sc,
1006                struct reclaim_stat *stat, bool ignore_references)
1007{
1008        LIST_HEAD(ret_folios);
1009        LIST_HEAD(free_folios);
1010        LIST_HEAD(demote_folios);
1011        unsigned int nr_reclaimed = 0;
1012        unsigned int pgactivate = 0;
1013        bool do_demote_pass;
1014        struct swap_iocb *plug = NULL;
1015
1016        memset(stat, 0, sizeof(*stat));
1017        cond_resched();
1018        do_demote_pass = can_demote(pgdat->node_id, sc);
1019
1020retry:
1021        while (!list_empty(folio_list)) {
1022                struct address_space *mapping;
1023                struct folio *folio;
1024                enum folio_references references = FOLIOREF_RECLAIM;
1025                bool dirty, writeback;
1026                unsigned int nr_pages;
1027
1028                cond_resched();
1029
1030                folio = lru_to_folio(folio_list);
1031                list_del(&folio->lru);
1032
1033                if (!folio_trylock(folio))
1034                        goto keep;
1035
1036                VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1037
1038                nr_pages = folio_nr_pages(folio);
1039
1040                /* Account the number of base pages */
1041                sc->nr_scanned += nr_pages;
1042
1043                if (unlikely(!folio_evictable(folio)))
1044                        goto activate_locked;
1045
1046                if (!sc->may_unmap && folio_mapped(folio))
1047                        goto keep_locked;
1048
1049                /* folio_update_gen() tried to promote this page? */
1050                if (lru_gen_enabled() && !ignore_references &&
1051                    folio_mapped(folio) && folio_test_referenced(folio))
1052                        goto keep_locked;
1053
1054                /*
1055                 * The number of dirty pages determines if a node is marked
1056                 * reclaim_congested. kswapd will stall and start writing
1057                 * folios if the tail of the LRU is all dirty unqueued folios.
1058                 */
1059                folio_check_dirty_writeback(folio, &dirty, &writeback);
1060                if (dirty || writeback)
1061                        stat->nr_dirty += nr_pages;
1062
1063                if (dirty && !writeback)
1064                        stat->nr_unqueued_dirty += nr_pages;
1065
1066                /*
1067                 * Treat this folio as congested if folios are cycling
1068                 * through the LRU so quickly that the folios marked
1069                 * for immediate reclaim are making it to the end of
1070                 * the LRU a second time.
1071                 */
1072                if (writeback && folio_test_reclaim(folio))
1073                        stat->nr_congested += nr_pages;
1074
1075                /*
1076                 * If a folio at the tail of the LRU is under writeback, there
1077                 * are three cases to consider.
1078                 *
1079                 * 1) If reclaim is encountering an excessive number
1080                 *    of folios under writeback and this folio has both
1081                 *    the writeback and reclaim flags set, then it
1082                 *    indicates that folios are being queued for I/O but
1083                 *    are being recycled through the LRU before the I/O
1084                 *    can complete. Waiting on the folio itself risks an
1085                 *    indefinite stall if it is impossible to writeback
1086                 *    the folio due to I/O error or disconnected storage
1087                 *    so instead note that the LRU is being scanned too
1088                 *    quickly and the caller can stall after the folio
1089                 *    list has been processed.
1090                 *
1091                 * 2) Global or new memcg reclaim encounters a folio that is
1092                 *    not marked for immediate reclaim, or the caller does not
1093                 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1094                 *    not to fs). In this case mark the folio for immediate
1095                 *    reclaim and continue scanning.
1096                 *
1097                 *    Require may_enter_fs() because we would wait on fs, which
1098                 *    may not have submitted I/O yet. And the loop driver might
1099                 *    enter reclaim, and deadlock if it waits on a folio for
1100                 *    which it is needed to do the write (loop masks off
1101                 *    __GFP_IO|__GFP_FS for this reason); but more thought
1102                 *    would probably show more reasons.
1103                 *
1104                 * 3) Legacy memcg encounters a folio that already has the
1105                 *    reclaim flag set. memcg does not have any dirty folio
1106                 *    throttling so we could easily OOM just because too many
1107                 *    folios are in writeback and there is nothing else to
1108                 *    reclaim. Wait for the writeback to complete.
1109                 *
1110                 * In cases 1) and 2) we activate the folios to get them out of
1111                 * the way while we continue scanning for clean folios on the
1112                 * inactive list and refilling from the active list. The
1113                 * observation here is that waiting for disk writes is more
1114                 * expensive than potentially causing reloads down the line.
1115                 * Since they're marked for immediate reclaim, they won't put
1116                 * memory pressure on the cache working set any longer than it
1117                 * takes to write them to disk.
1118                 */
1119                if (folio_test_writeback(folio)) {
1120                        /* Case 1 above */
1121                        if (current_is_kswapd() &&
1122                            folio_test_reclaim(folio) &&
1123                            test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1124                                stat->nr_immediate += nr_pages;
1125                                goto activate_locked;
1126
1127                        /* Case 2 above */
1128                        } else if (writeback_throttling_sane(sc) ||
1129                            !folio_test_reclaim(folio) ||
1130                            !may_enter_fs(folio, sc->gfp_mask)) {
1131                                /*
1132                                 * This is slightly racy -
1133                                 * folio_end_writeback() might have
1134                                 * just cleared the reclaim flag, then
1135                                 * setting the reclaim flag here ends up
1136                                 * interpreted as the readahead flag - but
1137                                 * that does not matter enough to care.
1138                                 * What we do want is for this folio to
1139                                 * have the reclaim flag set next time
1140                                 * memcg reclaim reaches the tests above,
1141                                 * so it will then wait for writeback to
1142                                 * avoid OOM; and it's also appropriate
1143                                 * in global reclaim.
1144                                 */
1145                                folio_set_reclaim(folio);
1146                                stat->nr_writeback += nr_pages;
1147                                goto activate_locked;
1148
1149                        /* Case 3 above */
1150                        } else {
1151                                folio_unlock(folio);
1152                                folio_wait_writeback(folio);
1153                                /* then go back and try same folio again */
1154                                list_add_tail(&folio->lru, folio_list);
1155                                continue;
1156                        }
1157                }
1158
1159                if (!ignore_references)
1160                        references = folio_check_references(folio, sc);
1161
1162                switch (references) {
1163                case FOLIOREF_ACTIVATE:
1164                        goto activate_locked;
1165                case FOLIOREF_KEEP:
1166                        stat->nr_ref_keep += nr_pages;
1167                        goto keep_locked;
1168                case FOLIOREF_RECLAIM:
1169                case FOLIOREF_RECLAIM_CLEAN:
1170                        ; /* try to reclaim the folio below */
1171                }
1172
1173                /*
1174                 * Before reclaiming the folio, try to relocate
1175                 * its contents to another node.
1176                 */
1177                if (do_demote_pass &&
1178                    (thp_migration_supported() || !folio_test_large(folio))) {
1179                        list_add(&folio->lru, &demote_folios);
1180                        folio_unlock(folio);
1181                        continue;
1182                }
1183
1184                /*
1185                 * Anonymous process memory has backing store?
1186                 * Try to allocate it some swap space here.
1187                 * Lazyfree folio could be freed directly
1188                 */
1189                if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1190                        if (!folio_test_swapcache(folio)) {
1191                                if (!(sc->gfp_mask & __GFP_IO))
1192                                        goto keep_locked;
1193                                if (folio_maybe_dma_pinned(folio))
1194                                        goto keep_locked;
1195                                if (folio_test_large(folio)) {
1196                                        /* cannot split folio, skip it */
1197                                        if (!can_split_folio(folio, NULL))
1198                                                goto activate_locked;
1199                                        /*
1200                                         * Split folios without a PMD map right
1201                                         * away. Chances are some or all of the
1202                                         * tail pages can be freed without IO.
1203                                         */
1204                                        if (!folio_entire_mapcount(folio) &&
1205                                            split_folio_to_list(folio,
1206                                                                folio_list))
1207                                                goto activate_locked;
1208                                }
1209                                if (!add_to_swap(folio)) {
1210                                        if (!folio_test_large(folio))
1211                                                goto activate_locked_split;
1212                                        /* Fallback to swap normal pages */
1213                                        if (split_folio_to_list(folio,
1214                                                                folio_list))
1215                                                goto activate_locked;
1216#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1217                                        count_memcg_folio_events(folio, THP_SWPOUT_FALLBACK, 1);
1218                                        count_vm_event(THP_SWPOUT_FALLBACK);
1219#endif
1220                                        if (!add_to_swap(folio))
1221                                                goto activate_locked_split;
1222                                }
1223                        }
1224                } else if (folio_test_swapbacked(folio) &&
1225                           folio_test_large(folio)) {
1226                        /* Split shmem folio */
1227                        if (split_folio_to_list(folio, folio_list))
1228                                goto keep_locked;
1229                }
1230
1231                /*
1232                 * If the folio was split above, the tail pages will make
1233                 * their own pass through this function and be accounted
1234                 * then.
1235                 */
1236                if ((nr_pages > 1) && !folio_test_large(folio)) {
1237                        sc->nr_scanned -= (nr_pages - 1);
1238                        nr_pages = 1;
1239                }
1240
1241                /*
1242                 * The folio is mapped into the page tables of one or more
1243                 * processes. Try to unmap it here.
1244                 */
1245                if (folio_mapped(folio)) {
1246                        enum ttu_flags flags = TTU_BATCH_FLUSH;
1247                        bool was_swapbacked = folio_test_swapbacked(folio);
1248
1249                        if (folio_test_pmd_mappable(folio))
1250                                flags |= TTU_SPLIT_HUGE_PMD;
1251
1252                        try_to_unmap(folio, flags);
1253                        if (folio_mapped(folio)) {
1254                                stat->nr_unmap_fail += nr_pages;
1255                                if (!was_swapbacked &&
1256                                    folio_test_swapbacked(folio))
1257                                        stat->nr_lazyfree_fail += nr_pages;
1258                                goto activate_locked;
1259                        }
1260                }
1261
1262                /*
1263                 * Folio is unmapped now so it cannot be newly pinned anymore.
1264                 * No point in trying to reclaim folio if it is pinned.
1265                 * Furthermore we don't want to reclaim underlying fs metadata
1266                 * if the folio is pinned and thus potentially modified by the
1267                 * pinning process as that may upset the filesystem.
1268                 */
1269                if (folio_maybe_dma_pinned(folio))
1270                        goto activate_locked;
1271
1272                mapping = folio_mapping(folio);
1273                if (folio_test_dirty(folio)) {
1274                        /*
1275                         * Only kswapd can writeback filesystem folios
1276                         * to avoid risk of stack overflow. But avoid
1277                         * injecting inefficient single-folio I/O into
1278                         * flusher writeback as much as possible: only
1279                         * write folios when we've encountered many
1280                         * dirty folios, and when we've already scanned
1281                         * the rest of the LRU for clean folios and see
1282                         * the same dirty folios again (with the reclaim
1283                         * flag set).
1284                         */
1285                        if (folio_is_file_lru(folio) &&
1286                            (!current_is_kswapd() ||
1287                             !folio_test_reclaim(folio) ||
1288                             !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1289                                /*
1290                                 * Immediately reclaim when written back.
1291                                 * Similar in principle to folio_deactivate()
1292                                 * except we already have the folio isolated
1293                                 * and know it's dirty
1294                                 */
1295                                node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1296                                                nr_pages);
1297                                folio_set_reclaim(folio);
1298
1299                                goto activate_locked;
1300                        }
1301
1302                        if (references == FOLIOREF_RECLAIM_CLEAN)
1303                                goto keep_locked;
1304                        if (!may_enter_fs(folio, sc->gfp_mask))
1305                                goto keep_locked;
1306                        if (!sc->may_writepage)
1307                                goto keep_locked;
1308
1309                        /*
1310                         * Folio is dirty. Flush the TLB if a writable entry
1311                         * potentially exists to avoid CPU writes after I/O
1312                         * starts and then write it out here.
1313                         */
1314                        try_to_unmap_flush_dirty();
1315                        switch (pageout(folio, mapping, &plug)) {
1316                        case PAGE_KEEP:
1317                                goto keep_locked;
1318                        case PAGE_ACTIVATE:
1319                                goto activate_locked;
1320                        case PAGE_SUCCESS:
1321                                stat->nr_pageout += nr_pages;
1322
1323                                if (folio_test_writeback(folio))
1324                                        goto keep;
1325                                if (folio_test_dirty(folio))
1326                                        goto keep;
1327
1328                                /*
1329                                 * A synchronous write - probably a ramdisk.  Go
1330                                 * ahead and try to reclaim the folio.
1331                                 */
1332                                if (!folio_trylock(folio))
1333                                        goto keep;
1334                                if (folio_test_dirty(folio) ||
1335                                    folio_test_writeback(folio))
1336                                        goto keep_locked;
1337                                mapping = folio_mapping(folio);
1338                                fallthrough;
1339                        case PAGE_CLEAN:
1340                                ; /* try to free the folio below */
1341                        }
1342                }
1343
1344                /*
1345                 * If the folio has buffers, try to free the buffer
1346                 * mappings associated with this folio. If we succeed
1347                 * we try to free the folio as well.
1348                 *
1349                 * We do this even if the folio is dirty.
1350                 * filemap_release_folio() does not perform I/O, but it
1351                 * is possible for a folio to have the dirty flag set,
1352                 * but it is actually clean (all its buffers are clean).
1353                 * This happens if the buffers were written out directly,
1354                 * with submit_bh(). ext3 will do this, as well as
1355                 * the blockdev mapping.  filemap_release_folio() will
1356                 * discover that cleanness and will drop the buffers
1357                 * and mark the folio clean - it can be freed.
1358                 *
1359                 * Rarely, folios can have buffers and no ->mapping.
1360                 * These are the folios which were not successfully
1361                 * invalidated in truncate_cleanup_folio().  We try to
1362                 * drop those buffers here and if that worked, and the
1363                 * folio is no longer mapped into process address space
1364                 * (refcount == 1) it can be freed.  Otherwise, leave
1365                 * the folio on the LRU so it is swappable.
1366                 */
1367                if (folio_needs_release(folio)) {
1368                        if (!filemap_release_folio(folio, sc->gfp_mask))
1369                                goto activate_locked;
1370                        if (!mapping && folio_ref_count(folio) == 1) {
1371                                folio_unlock(folio);
1372                                if (folio_put_testzero(folio))
1373                                        goto free_it;
1374                                else {
1375                                        /*
1376                                         * rare race with speculative reference.
1377                                         * the speculative reference will free
1378                                         * this folio shortly, so we may
1379                                         * increment nr_reclaimed here (and
1380                                         * leave it off the LRU).
1381                                         */
1382                                        nr_reclaimed += nr_pages;
1383                                        continue;
1384                                }
1385                        }
1386                }
1387
1388                if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1389                        /* follow __remove_mapping for reference */
1390                        if (!folio_ref_freeze(folio, 1))
1391                                goto keep_locked;
1392                        /*
1393                         * The folio has only one reference left, which is
1394                         * from the isolation. After the caller puts the
1395                         * folio back on the lru and drops the reference, the
1396                         * folio will be freed anyway. It doesn't matter
1397                         * which lru it goes on. So we don't bother checking
1398                         * the dirty flag here.
1399                         */
1400                        count_vm_events(PGLAZYFREED, nr_pages);
1401                        count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
1402                } else if (!mapping || !__remove_mapping(mapping, folio, true,
1403                                                         sc->target_mem_cgroup))
1404                        goto keep_locked;
1405
1406                folio_unlock(folio);
1407free_it:
1408                /*
1409                 * Folio may get swapped out as a whole, need to account
1410                 * all pages in it.
1411                 */
1412                nr_reclaimed += nr_pages;
1413
1414                /*
1415                 * Is there need to periodically free_folio_list? It would
1416                 * appear not as the counts should be low
1417                 */
1418                if (unlikely(folio_test_large(folio)))
1419                        destroy_large_folio(folio);
1420                else
1421                        list_add(&folio->lru, &free_folios);
1422                continue;
1423
1424activate_locked_split:
1425                /*
1426                 * The tail pages that are failed to add into swap cache
1427                 * reach here.  Fixup nr_scanned and nr_pages.
1428                 */
1429                if (nr_pages > 1) {
1430                        sc->nr_scanned -= (nr_pages - 1);
1431                        nr_pages = 1;
1432                }
1433activate_locked:
1434                /* Not a candidate for swapping, so reclaim swap space. */
1435                if (folio_test_swapcache(folio) &&
1436                    (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
1437                        folio_free_swap(folio);
1438                VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1439                if (!folio_test_mlocked(folio)) {
1440                        int type = folio_is_file_lru(folio);
1441                        folio_set_active(folio);
1442                        stat->nr_activate[type] += nr_pages;
1443                        count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
1444                }
1445keep_locked:
1446                folio_unlock(folio);
1447keep:
1448                list_add(&folio->lru, &ret_folios);
1449                VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
1450                                folio_test_unevictable(folio), folio);
1451        }
1452        /* 'folio_list' is always empty here */
1453
1454        /* Migrate folios selected for demotion */
1455        nr_reclaimed += demote_folio_list(&demote_folios, pgdat);
1456        /* Folios that could not be demoted are still in @demote_folios */
1457        if (!list_empty(&demote_folios)) {
1458                /* Folios which weren't demoted go back on @folio_list */
1459                list_splice_init(&demote_folios, folio_list);
1460
1461                /*
1462                 * goto retry to reclaim the undemoted folios in folio_list if
1463                 * desired.
1464                 *
1465                 * Reclaiming directly from top tier nodes is not often desired
1466                 * due to it breaking the LRU ordering: in general memory
1467                 * should be reclaimed from lower tier nodes and demoted from
1468                 * top tier nodes.
1469                 *
1470                 * However, disabling reclaim from top tier nodes entirely
1471                 * would cause ooms in edge scenarios where lower tier memory
1472                 * is unreclaimable for whatever reason, eg memory being
1473                 * mlocked or too hot to reclaim. We can disable reclaim
1474                 * from top tier nodes in proactive reclaim though as that is
1475                 * not real memory pressure.
1476                 */
1477                if (!sc->proactive) {
1478                        do_demote_pass = false;
1479                        goto retry;
1480                }
1481        }
1482
1483        pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1484
1485        mem_cgroup_uncharge_list(&free_folios);
1486        try_to_unmap_flush();
1487        free_unref_page_list(&free_folios);
1488
1489        list_splice(&ret_folios, folio_list);
1490        count_vm_events(PGACTIVATE, pgactivate);
1491
1492        if (plug)
1493                swap_write_unplug(plug);
1494        return nr_reclaimed;
1495}
1496
1497unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1498                                           struct list_head *folio_list)
1499{
1500        struct scan_control sc = {
1501                .gfp_mask = GFP_KERNEL,
1502                .may_unmap = 1,
1503        };
1504        struct reclaim_stat stat;
1505        unsigned int nr_reclaimed;
1506        struct folio *folio, *next;
1507        LIST_HEAD(clean_folios);
1508        unsigned int noreclaim_flag;
1509
1510        list_for_each_entry_safe(folio, next, folio_list, lru) {
1511                if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
1512                    !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
1513                    !folio_test_unevictable(folio)) {
1514                        folio_clear_active(folio);
1515                        list_move(&folio->lru, &clean_folios);
1516                }
1517        }
1518
1519        /*
1520         * We should be safe here since we are only dealing with file pages and
1521         * we are not kswapd and therefore cannot write dirty file pages. But
1522         * call memalloc_noreclaim_save() anyway, just in case these conditions
1523         * change in the future.
1524         */
1525        noreclaim_flag = memalloc_noreclaim_save();
1526        nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
1527                                        &stat, true);
1528        memalloc_noreclaim_restore(noreclaim_flag);
1529
1530        list_splice(&clean_folios, folio_list);
1531        mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1532                            -(long)nr_reclaimed);
1533        /*
1534         * Since lazyfree pages are isolated from file LRU from the beginning,
1535         * they will rotate back to anonymous LRU in the end if it failed to
1536         * discard so isolated count will be mismatched.
1537         * Compensate the isolated count for both LRU lists.
1538         */
1539        mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1540                            stat.nr_lazyfree_fail);
1541        mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1542                            -(long)stat.nr_lazyfree_fail);
1543        return nr_reclaimed;
1544}
1545
1546/*
1547 * Update LRU sizes after isolating pages. The LRU size updates must
1548 * be complete before mem_cgroup_update_lru_size due to a sanity check.
1549 */
1550static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1551                        enum lru_list lru, unsigned long *nr_zone_taken)
1552{
1553        int zid;
1554
1555        for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1556                if (!nr_zone_taken[zid])
1557                        continue;
1558
1559                update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1560        }
1561
1562}
1563
1564#ifdef CONFIG_CMA
1565/*
1566 * It is waste of effort to scan and reclaim CMA pages if it is not available
1567 * for current allocation context. Kswapd can not be enrolled as it can not
1568 * distinguish this scenario by using sc->gfp_mask = GFP_KERNEL
1569 */
1570static bool skip_cma(struct folio *folio, struct scan_control *sc)
1571{
1572        return !current_is_kswapd() &&
1573                        gfp_migratetype(sc->gfp_mask) != MIGRATE_MOVABLE &&
1574                        folio_migratetype(folio) == MIGRATE_CMA;
1575}
1576#else
1577static bool skip_cma(struct folio *folio, struct scan_control *sc)
1578{
1579        return false;
1580}
1581#endif
1582
1583/*
1584 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1585 *
1586 * lruvec->lru_lock is heavily contended.  Some of the functions that
1587 * shrink the lists perform better by taking out a batch of pages
1588 * and working on them outside the LRU lock.
1589 *
1590 * For pagecache intensive workloads, this function is the hottest
1591 * spot in the kernel (apart from copy_*_user functions).
1592 *
1593 * Lru_lock must be held before calling this function.
1594 *
1595 * @nr_to_scan: The number of eligible pages to look through on the list.
1596 * @lruvec:     The LRU vector to pull pages from.
1597 * @dst:        The temp list to put pages on to.
1598 * @nr_scanned: The number of pages that were scanned.
1599 * @sc:         The scan_control struct for this reclaim session
1600 * @lru:        LRU list id for isolating
1601 *
1602 * returns how many pages were moved onto *@dst.
1603 */
1604static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
1605                struct lruvec *lruvec, struct list_head *dst,
1606                unsigned long *nr_scanned, struct scan_control *sc,
1607                enum lru_list lru)
1608{
1609        struct list_head *src = &lruvec->lists[lru];
1610        unsigned long nr_taken = 0;
1611        unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1612        unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1613        unsigned long skipped = 0;
1614        unsigned long scan, total_scan, nr_pages;
1615        LIST_HEAD(folios_skipped);
1616
1617        total_scan = 0;
1618        scan = 0;
1619        while (scan < nr_to_scan && !list_empty(src)) {
1620                struct list_head *move_to = src;
1621                struct folio *folio;
1622
1623                folio = lru_to_folio(src);
1624                prefetchw_prev_lru_folio(folio, src, flags);
1625
1626                nr_pages = folio_nr_pages(folio);
1627                total_scan += nr_pages;
1628
1629                if (folio_zonenum(folio) > sc->reclaim_idx ||
1630                                skip_cma(folio, sc)) {
1631                        nr_skipped[folio_zonenum(folio)] += nr_pages;
1632                        move_to = &folios_skipped;
1633                        goto move;
1634                }
1635
1636                /*
1637                 * Do not count skipped folios because that makes the function
1638                 * return with no isolated folios if the LRU mostly contains
1639                 * ineligible folios.  This causes the VM to not reclaim any
1640                 * folios, triggering a premature OOM.
1641                 * Account all pages in a folio.
1642                 */
1643                scan += nr_pages;
1644
1645                if (!folio_test_lru(folio))
1646                        goto move;
1647                if (!sc->may_unmap && folio_mapped(folio))
1648                        goto move;
1649
1650                /*
1651                 * Be careful not to clear the lru flag until after we're
1652                 * sure the folio is not being freed elsewhere -- the
1653                 * folio release code relies on it.
1654                 */
1655                if (unlikely(!folio_try_get(folio)))
1656                        goto move;
1657
1658                if (!folio_test_clear_lru(folio)) {
1659                        /* Another thread is already isolating this folio */
1660                        folio_put(folio);
1661                        goto move;
1662                }
1663
1664                nr_taken += nr_pages;
1665                nr_zone_taken[folio_zonenum(folio)] += nr_pages;
1666                move_to = dst;
1667move:
1668                list_move(&folio->lru, move_to);
1669        }
1670
1671        /*
1672         * Splice any skipped folios to the start of the LRU list. Note that
1673         * this disrupts the LRU order when reclaiming for lower zones but
1674         * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1675         * scanning would soon rescan the same folios to skip and waste lots
1676         * of cpu cycles.
1677         */
1678        if (!list_empty(&folios_skipped)) {
1679                int zid;
1680
1681                list_splice(&folios_skipped, src);
1682                for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1683                        if (!nr_skipped[zid])
1684                                continue;
1685
1686                        __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1687                        skipped += nr_skipped[zid];
1688                }
1689        }
1690        *nr_scanned = total_scan;
1691        trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1692                                    total_scan, skipped, nr_taken, lru);
1693        update_lru_sizes(lruvec, lru, nr_zone_taken);
1694        return nr_taken;
1695}
1696
1697/**
1698 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
1699 * @folio: Folio to isolate from its LRU list.
1700 *
1701 * Isolate a @folio from an LRU list and adjust the vmstat statistic
1702 * corresponding to whatever LRU list the folio was on.
1703 *
1704 * The folio will have its LRU flag cleared.  If it was found on the
1705 * active list, it will have the Active flag set.  If it was found on the
1706 * unevictable list, it will have the Unevictable flag set.  These flags
1707 * may need to be cleared by the caller before letting the page go.
1708 *
1709 * Context:
1710 *
1711 * (1) Must be called with an elevated refcount on the folio. This is a
1712 *     fundamental difference from isolate_lru_folios() (which is called
1713 *     without a stable reference).
1714 * (2) The lru_lock must not be held.
1715 * (3) Interrupts must be enabled.
1716 *
1717 * Return: true if the folio was removed from an LRU list.
1718 * false if the folio was not on an LRU list.
1719 */
1720bool folio_isolate_lru(struct folio *folio)
1721{
1722        bool ret = false;
1723
1724        VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
1725
1726        if (folio_test_clear_lru(folio)) {
1727                struct lruvec *lruvec;
1728
1729                folio_get(folio);
1730                lruvec = folio_lruvec_lock_irq(folio);
1731                lruvec_del_folio(lruvec, folio);
1732                unlock_page_lruvec_irq(lruvec);
1733                ret = true;
1734        }
1735
1736        return ret;
1737}
1738
1739/*
1740 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1741 * then get rescheduled. When there are massive number of tasks doing page
1742 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1743 * the LRU list will go small and be scanned faster than necessary, leading to
1744 * unnecessary swapping, thrashing and OOM.
1745 */
1746static int too_many_isolated(struct pglist_data *pgdat, int file,
1747                struct scan_control *sc)
1748{
1749        unsigned long inactive, isolated;
1750        bool too_many;
1751
1752        if (current_is_kswapd())
1753                return 0;
1754
1755        if (!writeback_throttling_sane(sc))
1756                return 0;
1757
1758        if (file) {
1759                inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1760                isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1761        } else {
1762                inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1763                isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
1764        }
1765
1766        /*
1767         * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1768         * won't get blocked by normal direct-reclaimers, forming a circular
1769         * deadlock.
1770         */
1771        if (gfp_has_io_fs(sc->gfp_mask))
1772                inactive >>= 3;
1773
1774        too_many = isolated > inactive;
1775
1776        /* Wake up tasks throttled due to too_many_isolated. */
1777        if (!too_many)
1778                wake_throttle_isolated(pgdat);
1779
1780        return too_many;
1781}
1782
1783/*
1784 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
1785 * On return, @list is reused as a list of folios to be freed by the caller.
1786 *
1787 * Returns the number of pages moved to the given lruvec.
1788 */
1789static unsigned int move_folios_to_lru(struct lruvec *lruvec,
1790                struct list_head *list)
1791{
1792        int nr_pages, nr_moved = 0;
1793        LIST_HEAD(folios_to_free);
1794
1795        while (!list_empty(list)) {
1796                struct folio *folio = lru_to_folio(list);
1797
1798                VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
1799                list_del(&folio->lru);
1800                if (unlikely(!folio_evictable(folio))) {
1801                        spin_unlock_irq(&lruvec->lru_lock);
1802                        folio_putback_lru(folio);
1803                        spin_lock_irq(&lruvec->lru_lock);
1804                        continue;
1805                }
1806
1807                /*
1808                 * The folio_set_lru needs to be kept here for list integrity.
1809                 * Otherwise:
1810                 *   #0 move_folios_to_lru             #1 release_pages
1811                 *   if (!folio_put_testzero())
1812                 *                                    if (folio_put_testzero())
1813                 *                                      !lru //skip lru_lock
1814                 *     folio_set_lru()
1815                 *     list_add(&folio->lru,)
1816                 *                                        list_add(&folio->lru,)
1817                 */
1818                folio_set_lru(folio);
1819
1820                if (unlikely(folio_put_testzero(folio))) {
1821                        __folio_clear_lru_flags(folio);
1822
1823                        if (unlikely(folio_test_large(folio))) {
1824                                spin_unlock_irq(&lruvec->lru_lock);
1825                                destroy_large_folio(folio);
1826                                spin_lock_irq(&lruvec->lru_lock);
1827                        } else
1828                                list_add(&folio->lru, &folios_to_free);
1829
1830                        continue;
1831                }
1832
1833                /*
1834                 * All pages were isolated from the same lruvec (and isolation
1835                 * inhibits memcg migration).
1836                 */
1837                VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
1838                lruvec_add_folio(lruvec, folio);
1839                nr_pages = folio_nr_pages(folio);
1840                nr_moved += nr_pages;
1841                if (folio_test_active(folio))
1842                        workingset_age_nonresident(lruvec, nr_pages);
1843        }
1844
1845        /*
1846         * To save our caller's stack, now use input list for pages to free.
1847         */
1848        list_splice(&folios_to_free, list);
1849
1850        return nr_moved;
1851}
1852
1853/*
1854 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
1855 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
1856 * we should not throttle.  Otherwise it is safe to do so.
1857 */
1858static int current_may_throttle(void)
1859{
1860        return !(current->flags & PF_LOCAL_THROTTLE);
1861}
1862
1863/*
1864 * shrink_inactive_list() is a helper for shrink_node().  It returns the number
1865 * of reclaimed pages
1866 */
1867static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
1868                struct lruvec *lruvec, struct scan_control *sc,
1869                enum lru_list lru)
1870{
1871        LIST_HEAD(folio_list);
1872        unsigned long nr_scanned;
1873        unsigned int nr_reclaimed = 0;
1874        unsigned long nr_taken;
1875        struct reclaim_stat stat;
1876        bool file = is_file_lru(lru);
1877        enum vm_event_item item;
1878        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1879        bool stalled = false;
1880
1881        while (unlikely(too_many_isolated(pgdat, file, sc))) {
1882                if (stalled)
1883                        return 0;
1884
1885                /* wait a bit for the reclaimer. */
1886                stalled = true;
1887                reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
1888
1889                /* We are about to die and free our memory. Return now. */
1890                if (fatal_signal_pending(current))
1891                        return SWAP_CLUSTER_MAX;
1892        }
1893
1894        lru_add_drain();
1895
1896        spin_lock_irq(&lruvec->lru_lock);
1897
1898        nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
1899                                     &nr_scanned, sc, lru);
1900
1901        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1902        item = PGSCAN_KSWAPD + reclaimer_offset();
1903        if (!cgroup_reclaim(sc))
1904                __count_vm_events(item, nr_scanned);
1905        __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1906        __count_vm_events(PGSCAN_ANON + file, nr_scanned);
1907
1908        spin_unlock_irq(&lruvec->lru_lock);
1909
1910        if (nr_taken == 0)
1911                return 0;
1912
1913        nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
1914
1915        spin_lock_irq(&lruvec->lru_lock);
1916        move_folios_to_lru(lruvec, &folio_list);
1917
1918        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1919        item = PGSTEAL_KSWAPD + reclaimer_offset();
1920        if (!cgroup_reclaim(sc))
1921                __count_vm_events(item, nr_reclaimed);
1922        __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1923        __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
1924        spin_unlock_irq(&lruvec->lru_lock);
1925
1926        lru_note_cost(lruvec, file, stat.nr_pageout, nr_scanned - nr_reclaimed);
1927        mem_cgroup_uncharge_list(&folio_list);
1928        free_unref_page_list(&folio_list);
1929
1930        /*
1931         * If dirty folios are scanned that are not queued for IO, it
1932         * implies that flushers are not doing their job. This can
1933         * happen when memory pressure pushes dirty folios to the end of
1934         * the LRU before the dirty limits are breached and the dirty
1935         * data has expired. It can also happen when the proportion of
1936         * dirty folios grows not through writes but through memory
1937         * pressure reclaiming all the clean cache. And in some cases,
1938         * the flushers simply cannot keep up with the allocation
1939         * rate. Nudge the flusher threads in case they are asleep.
1940         */
1941        if (stat.nr_unqueued_dirty == nr_taken) {
1942                wakeup_flusher_threads(WB_REASON_VMSCAN);
1943                /*
1944                 * For cgroupv1 dirty throttling is achieved by waking up
1945                 * the kernel flusher here and later waiting on folios
1946                 * which are in writeback to finish (see shrink_folio_list()).
1947                 *
1948                 * Flusher may not be able to issue writeback quickly
1949                 * enough for cgroupv1 writeback throttling to work
1950                 * on a large system.
1951                 */
1952                if (!writeback_throttling_sane(sc))
1953                        reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
1954        }
1955
1956        sc->nr.dirty += stat.nr_dirty;
1957        sc->nr.congested += stat.nr_congested;
1958        sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1959        sc->nr.writeback += stat.nr_writeback;
1960        sc->nr.immediate += stat.nr_immediate;
1961        sc->nr.taken += nr_taken;
1962        if (file)
1963                sc->nr.file_taken += nr_taken;
1964
1965        trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1966                        nr_scanned, nr_reclaimed, &stat, sc->priority, file);
1967        return nr_reclaimed;
1968}
1969
1970/*
1971 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
1972 *
1973 * We move them the other way if the folio is referenced by one or more
1974 * processes.
1975 *
1976 * If the folios are mostly unmapped, the processing is fast and it is
1977 * appropriate to hold lru_lock across the whole operation.  But if
1978 * the folios are mapped, the processing is slow (folio_referenced()), so
1979 * we should drop lru_lock around each folio.  It's impossible to balance
1980 * this, so instead we remove the folios from the LRU while processing them.
1981 * It is safe to rely on the active flag against the non-LRU folios in here
1982 * because nobody will play with that bit on a non-LRU folio.
1983 *
1984 * The downside is that we have to touch folio->_refcount against each folio.
1985 * But we had to alter folio->flags anyway.
1986 */
1987static void shrink_active_list(unsigned long nr_to_scan,
1988                               struct lruvec *lruvec,
1989                               struct scan_control *sc,
1990                               enum lru_list lru)
1991{
1992        unsigned long nr_taken;
1993        unsigned long nr_scanned;
1994        unsigned long vm_flags;
1995        LIST_HEAD(l_hold);      /* The folios which were snipped off */
1996        LIST_HEAD(l_active);
1997        LIST_HEAD(l_inactive);
1998        unsigned nr_deactivate, nr_activate;
1999        unsigned nr_rotated = 0;
2000        int file = is_file_lru(lru);
2001        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2002
2003        lru_add_drain();
2004
2005        spin_lock_irq(&lruvec->lru_lock);
2006
2007        nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
2008                                     &nr_scanned, sc, lru);
2009
2010        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2011
2012        if (!cgroup_reclaim(sc))
2013                __count_vm_events(PGREFILL, nr_scanned);
2014        __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2015
2016        spin_unlock_irq(&lruvec->lru_lock);
2017
2018        while (!list_empty(&l_hold)) {
2019                struct folio *folio;
2020
2021                cond_resched();
2022                folio = lru_to_folio(&l_hold);
2023                list_del(&folio->lru);
2024
2025                if (unlikely(!folio_evictable(folio))) {
2026                        folio_putback_lru(folio);
2027                        continue;
2028                }
2029
2030                if (unlikely(buffer_heads_over_limit)) {
2031                        if (folio_needs_release(folio) &&
2032                            folio_trylock(folio)) {
2033                                filemap_release_folio(folio, 0);
2034                                folio_unlock(folio);
2035                        }
2036                }
2037
2038                /* Referenced or rmap lock contention: rotate */
2039                if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2040                                     &vm_flags) != 0) {
2041                        /*
2042                         * Identify referenced, file-backed active folios and
2043                         * give them one more trip around the active list. So
2044                         * that executable code get better chances to stay in
2045                         * memory under moderate memory pressure.  Anon folios
2046                         * are not likely to be evicted by use-once streaming
2047                         * IO, plus JVM can create lots of anon VM_EXEC folios,
2048                         * so we ignore them here.
2049                         */
2050                        if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2051                                nr_rotated += folio_nr_pages(folio);
2052                                list_add(&folio->lru, &l_active);
2053                                continue;
2054                        }
2055                }
2056
2057                folio_clear_active(folio);      /* we are de-activating */
2058                folio_set_workingset(folio);
2059                list_add(&folio->lru, &l_inactive);
2060        }
2061
2062        /*
2063         * Move folios back to the lru list.
2064         */
2065        spin_lock_irq(&lruvec->lru_lock);
2066
2067        nr_activate = move_folios_to_lru(lruvec, &l_active);
2068        nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
2069        /* Keep all free folios in l_active list */
2070        list_splice(&l_inactive, &l_active);
2071
2072        __count_vm_events(PGDEACTIVATE, nr_deactivate);
2073        __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2074
2075        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2076        spin_unlock_irq(&lruvec->lru_lock);
2077
2078        if (nr_rotated)
2079                lru_note_cost(lruvec, file, 0, nr_rotated);
2080        mem_cgroup_uncharge_list(&l_active);
2081        free_unref_page_list(&l_active);
2082        trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2083                        nr_deactivate, nr_rotated, sc->priority, file);
2084}
2085
2086static unsigned int reclaim_folio_list(struct list_head *folio_list,
2087                                      struct pglist_data *pgdat)
2088{
2089        struct reclaim_stat dummy_stat;
2090        unsigned int nr_reclaimed;
2091        struct folio *folio;
2092        struct scan_control sc = {
2093                .gfp_mask = GFP_KERNEL,
2094                .may_writepage = 1,
2095                .may_unmap = 1,
2096                .may_swap = 1,
2097                .no_demotion = 1,
2098        };
2099
2100        nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_stat, false);
2101        while (!list_empty(folio_list)) {
2102                folio = lru_to_folio(folio_list);
2103                list_del(&folio->lru);
2104                folio_putback_lru(folio);
2105        }
2106
2107        return nr_reclaimed;
2108}
2109
2110unsigned long reclaim_pages(struct list_head *folio_list)
2111{
2112        int nid;
2113        unsigned int nr_reclaimed = 0;
2114        LIST_HEAD(node_folio_list);
2115        unsigned int noreclaim_flag;
2116
2117        if (list_empty(folio_list))
2118                return nr_reclaimed;
2119
2120        noreclaim_flag = memalloc_noreclaim_save();
2121
2122        nid = folio_nid(lru_to_folio(folio_list));
2123        do {
2124                struct folio *folio = lru_to_folio(folio_list);
2125
2126                if (nid == folio_nid(folio)) {
2127                        folio_clear_active(folio);
2128                        list_move(&folio->lru, &node_folio_list);
2129                        continue;
2130                }
2131
2132                nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2133                nid = folio_nid(lru_to_folio(folio_list));
2134        } while (!list_empty(folio_list));
2135
2136        nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2137
2138        memalloc_noreclaim_restore(noreclaim_flag);
2139
2140        return nr_reclaimed;
2141}
2142
2143static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2144                                 struct lruvec *lruvec, struct scan_control *sc)
2145{
2146        if (is_active_lru(lru)) {
2147                if (sc->may_deactivate & (1 << is_file_lru(lru)))
2148                        shrink_active_list(nr_to_scan, lruvec, sc, lru);
2149                else
2150                        sc->skipped_deactivate = 1;
2151                return 0;
2152        }
2153
2154        return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2155}
2156
2157/*
2158 * The inactive anon list should be small enough that the VM never has
2159 * to do too much work.
2160 *
2161 * The inactive file list should be small enough to leave most memory
2162 * to the established workingset on the scan-resistant active list,
2163 * but large enough to avoid thrashing the aggregate readahead window.
2164 *
2165 * Both inactive lists should also be large enough that each inactive
2166 * folio has a chance to be referenced again before it is reclaimed.
2167 *
2168 * If that fails and refaulting is observed, the inactive list grows.
2169 *
2170 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2171 * on this LRU, maintained by the pageout code. An inactive_ratio
2172 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2173 *
2174 * total     target    max
2175 * memory    ratio     inactive
2176 * -------------------------------------
2177 *   10MB       1         5MB
2178 *  100MB       1        50MB
2179 *    1GB       3       250MB
2180 *   10GB      10       0.9GB
2181 *  100GB      31         3GB
2182 *    1TB     101        10GB
2183 *   10TB     320        32GB
2184 */
2185static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2186{
2187        enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2188        unsigned long inactive, active;
2189        unsigned long inactive_ratio;
2190        unsigned long gb;
2191
2192        inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2193        active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2194
2195        gb = (inactive + active) >> (30 - PAGE_SHIFT);
2196        if (gb)
2197                inactive_ratio = int_sqrt(10 * gb);
2198        else
2199                inactive_ratio = 1;
2200
2201        return inactive * inactive_ratio < active;
2202}
2203
2204enum scan_balance {
2205        SCAN_EQUAL,
2206        SCAN_FRACT,
2207        SCAN_ANON,
2208        SCAN_FILE,
2209};
2210
2211static void prepare_scan_control(pg_data_t *pgdat, struct scan_control *sc)
2212{
2213        unsigned long file;
2214        struct lruvec *target_lruvec;
2215
2216        if (lru_gen_enabled())
2217                return;
2218
2219        target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2220
2221        /*
2222         * Flush the memory cgroup stats, so that we read accurate per-memcg
2223         * lruvec stats for heuristics.
2224         */
2225        mem_cgroup_flush_stats();
2226
2227        /*
2228         * Determine the scan balance between anon and file LRUs.
2229         */
2230        spin_lock_irq(&target_lruvec->lru_lock);
2231        sc->anon_cost = target_lruvec->anon_cost;
2232        sc->file_cost = target_lruvec->file_cost;
2233        spin_unlock_irq(&target_lruvec->lru_lock);
2234
2235        /*
2236         * Target desirable inactive:active list ratios for the anon
2237         * and file LRU lists.
2238         */
2239        if (!sc->force_deactivate) {
2240                unsigned long refaults;
2241
2242                /*
2243                 * When refaults are being observed, it means a new
2244                 * workingset is being established. Deactivate to get
2245                 * rid of any stale active pages quickly.
2246                 */
2247                refaults = lruvec_page_state(target_lruvec,
2248                                WORKINGSET_ACTIVATE_ANON);
2249                if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2250                        inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2251                        sc->may_deactivate |= DEACTIVATE_ANON;
2252                else
2253                        sc->may_deactivate &= ~DEACTIVATE_ANON;
2254
2255                refaults = lruvec_page_state(target_lruvec,
2256                                WORKINGSET_ACTIVATE_FILE);
2257                if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2258                    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2259                        sc->may_deactivate |= DEACTIVATE_FILE;
2260                else
2261                        sc->may_deactivate &= ~DEACTIVATE_FILE;
2262        } else
2263                sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2264
2265        /*
2266         * If we have plenty of inactive file pages that aren't
2267         * thrashing, try to reclaim those first before touching
2268         * anonymous pages.
2269         */
2270        file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2271        if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2272                sc->cache_trim_mode = 1;
2273        else
2274                sc->cache_trim_mode = 0;
2275
2276        /*
2277         * Prevent the reclaimer from falling into the cache trap: as
2278         * cache pages start out inactive, every cache fault will tip
2279         * the scan balance towards the file LRU.  And as the file LRU
2280         * shrinks, so does the window for rotation from references.
2281         * This means we have a runaway feedback loop where a tiny
2282         * thrashing file LRU becomes infinitely more attractive than
2283         * anon pages.  Try to detect this based on file LRU size.
2284         */
2285        if (!cgroup_reclaim(sc)) {
2286                unsigned long total_high_wmark = 0;
2287                unsigned long free, anon;
2288                int z;
2289
2290                free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2291                file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2292                           node_page_state(pgdat, NR_INACTIVE_FILE);
2293
2294                for (z = 0; z < MAX_NR_ZONES; z++) {
2295                        struct zone *zone = &pgdat->node_zones[z];
2296
2297                        if (!managed_zone(zone))
2298                                continue;
2299
2300                        total_high_wmark += high_wmark_pages(zone);
2301                }
2302
2303                /*
2304                 * Consider anon: if that's low too, this isn't a
2305                 * runaway file reclaim problem, but rather just
2306                 * extreme pressure. Reclaim as per usual then.
2307                 */
2308                anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2309
2310                sc->file_is_tiny =
2311                        file + free <= total_high_wmark &&
2312                        !(sc->may_deactivate & DEACTIVATE_ANON) &&
2313                        anon >> sc->priority;
2314        }
2315}
2316
2317/*
2318 * Determine how aggressively the anon and file LRU lists should be
2319 * scanned.
2320 *
2321 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2322 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2323 */
2324static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2325                           unsigned long *nr)
2326{
2327        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2328        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2329        unsigned long anon_cost, file_cost, total_cost;
2330        int swappiness = mem_cgroup_swappiness(memcg);
2331        u64 fraction[ANON_AND_FILE];
2332        u64 denominator = 0;    /* gcc */
2333        enum scan_balance scan_balance;
2334        unsigned long ap, fp;
2335        enum lru_list lru;
2336
2337        /* If we have no swap space, do not bother scanning anon folios. */
2338        if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2339                scan_balance = SCAN_FILE;
2340                goto out;
2341        }
2342
2343        /*
2344         * Global reclaim will swap to prevent OOM even with no
2345         * swappiness, but memcg users want to use this knob to
2346         * disable swapping for individual groups completely when
2347         * using the memory controller's swap limit feature would be
2348         * too expensive.
2349         */
2350        if (cgroup_reclaim(sc) && !swappiness) {
2351                scan_balance = SCAN_FILE;
2352                goto out;
2353        }
2354
2355        /*
2356         * Do not apply any pressure balancing cleverness when the
2357         * system is close to OOM, scan both anon and file equally
2358         * (unless the swappiness setting disagrees with swapping).
2359         */
2360        if (!sc->priority && swappiness) {
2361                scan_balance = SCAN_EQUAL;
2362                goto out;
2363        }
2364
2365        /*
2366         * If the system is almost out of file pages, force-scan anon.
2367         */
2368        if (sc->file_is_tiny) {
2369                scan_balance = SCAN_ANON;
2370                goto out;
2371        }
2372
2373        /*
2374         * If there is enough inactive page cache, we do not reclaim
2375         * anything from the anonymous working right now.
2376         */
2377        if (sc->cache_trim_mode) {
2378                scan_balance = SCAN_FILE;
2379                goto out;
2380        }
2381
2382        scan_balance = SCAN_FRACT;
2383        /*
2384         * Calculate the pressure balance between anon and file pages.
2385         *
2386         * The amount of pressure we put on each LRU is inversely
2387         * proportional to the cost of reclaiming each list, as
2388         * determined by the share of pages that are refaulting, times
2389         * the relative IO cost of bringing back a swapped out
2390         * anonymous page vs reloading a filesystem page (swappiness).
2391         *
2392         * Although we limit that influence to ensure no list gets
2393         * left behind completely: at least a third of the pressure is
2394         * applied, before swappiness.
2395         *
2396         * With swappiness at 100, anon and file have equal IO cost.
2397         */
2398        total_cost = sc->anon_cost + sc->file_cost;
2399        anon_cost = total_cost + sc->anon_cost;
2400        file_cost = total_cost + sc->file_cost;
2401        total_cost = anon_cost + file_cost;
2402
2403        ap = swappiness * (total_cost + 1);
2404        ap /= anon_cost + 1;
2405
2406        fp = (200 - swappiness) * (total_cost + 1);
2407        fp /= file_cost + 1;
2408
2409        fraction[0] = ap;
2410        fraction[1] = fp;
2411        denominator = ap + fp;
2412out:
2413        for_each_evictable_lru(lru) {
2414                int file = is_file_lru(lru);
2415                unsigned long lruvec_size;
2416                unsigned long low, min;
2417                unsigned long scan;
2418
2419                lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2420                mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2421                                      &min, &low);
2422
2423                if (min || low) {
2424                        /*
2425                         * Scale a cgroup's reclaim pressure by proportioning
2426                         * its current usage to its memory.low or memory.min
2427                         * setting.
2428                         *
2429                         * This is important, as otherwise scanning aggression
2430                         * becomes extremely binary -- from nothing as we
2431                         * approach the memory protection threshold, to totally
2432                         * nominal as we exceed it.  This results in requiring
2433                         * setting extremely liberal protection thresholds. It
2434                         * also means we simply get no protection at all if we
2435                         * set it too low, which is not ideal.
2436                         *
2437                         * If there is any protection in place, we reduce scan
2438                         * pressure by how much of the total memory used is
2439                         * within protection thresholds.
2440                         *
2441                         * There is one special case: in the first reclaim pass,
2442                         * we skip over all groups that are within their low
2443                         * protection. If that fails to reclaim enough pages to
2444                         * satisfy the reclaim goal, we come back and override
2445                         * the best-effort low protection. However, we still
2446                         * ideally want to honor how well-behaved groups are in
2447                         * that case instead of simply punishing them all
2448                         * equally. As such, we reclaim them based on how much
2449                         * memory they are using, reducing the scan pressure
2450                         * again by how much of the total memory used is under
2451                         * hard protection.
2452                         */
2453                        unsigned long cgroup_size = mem_cgroup_size(memcg);
2454                        unsigned long protection;
2455
2456                        /* memory.low scaling, make sure we retry before OOM */
2457                        if (!sc->memcg_low_reclaim && low > min) {
2458                                protection = low;
2459                                sc->memcg_low_skipped = 1;
2460                        } else {
2461                                protection = min;
2462                        }
2463
2464                        /* Avoid TOCTOU with earlier protection check */
2465                        cgroup_size = max(cgroup_size, protection);
2466
2467                        scan = lruvec_size - lruvec_size * protection /
2468                                (cgroup_size + 1);
2469
2470                        /*
2471                         * Minimally target SWAP_CLUSTER_MAX pages to keep
2472                         * reclaim moving forwards, avoiding decrementing
2473                         * sc->priority further than desirable.
2474                         */
2475                        scan = max(scan, SWAP_CLUSTER_MAX);
2476                } else {
2477                        scan = lruvec_size;
2478                }
2479
2480                scan >>= sc->priority;
2481
2482                /*
2483                 * If the cgroup's already been deleted, make sure to
2484                 * scrape out the remaining cache.
2485                 */
2486                if (!scan && !mem_cgroup_online(memcg))
2487                        scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2488
2489                switch (scan_balance) {
2490                case SCAN_EQUAL:
2491                        /* Scan lists relative to size */
2492                        break;
2493                case SCAN_FRACT:
2494                        /*
2495                         * Scan types proportional to swappiness and
2496                         * their relative recent reclaim efficiency.
2497                         * Make sure we don't miss the last page on
2498                         * the offlined memory cgroups because of a
2499                         * round-off error.
2500                         */
2501                        scan = mem_cgroup_online(memcg) ?
2502                               div64_u64(scan * fraction[file], denominator) :
2503                               DIV64_U64_ROUND_UP(scan * fraction[file],
2504                                                  denominator);
2505                        break;
2506                case SCAN_FILE:
2507                case SCAN_ANON:
2508                        /* Scan one type exclusively */
2509                        if ((scan_balance == SCAN_FILE) != file)
2510                                scan = 0;
2511                        break;
2512                default:
2513                        /* Look ma, no brain */
2514                        BUG();
2515                }
2516
2517                nr[lru] = scan;
2518        }
2519}
2520
2521/*
2522 * Anonymous LRU management is a waste if there is
2523 * ultimately no way to reclaim the memory.
2524 */
2525static bool can_age_anon_pages(struct pglist_data *pgdat,
2526                               struct scan_control *sc)
2527{
2528        /* Aging the anon LRU is valuable if swap is present: */
2529        if (total_swap_pages > 0)
2530                return true;
2531
2532        /* Also valuable if anon pages can be demoted: */
2533        return can_demote(pgdat->node_id, sc);
2534}
2535
2536#ifdef CONFIG_LRU_GEN
2537
2538#ifdef CONFIG_LRU_GEN_ENABLED
2539DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2540#define get_cap(cap)    static_branch_likely(&lru_gen_caps[cap])
2541#else
2542DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2543#define get_cap(cap)    static_branch_unlikely(&lru_gen_caps[cap])
2544#endif
2545
2546static bool should_walk_mmu(void)
2547{
2548        return arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK);
2549}
2550
2551static bool should_clear_pmd_young(void)
2552{
2553        return arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG);
2554}
2555
2556/******************************************************************************
2557 *                          shorthand helpers
2558 ******************************************************************************/
2559
2560#define LRU_REFS_FLAGS  (BIT(PG_referenced) | BIT(PG_workingset))
2561
2562#define DEFINE_MAX_SEQ(lruvec)                                          \
2563        unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2564
2565#define DEFINE_MIN_SEQ(lruvec)                                          \
2566        unsigned long min_seq[ANON_AND_FILE] = {                        \
2567                READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]),      \
2568                READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]),      \
2569        }
2570
2571#define for_each_gen_type_zone(gen, type, zone)                         \
2572        for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++)                   \
2573                for ((type) = 0; (type) < ANON_AND_FILE; (type)++)      \
2574                        for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2575
2576#define get_memcg_gen(seq)      ((seq) % MEMCG_NR_GENS)
2577#define get_memcg_bin(bin)      ((bin) % MEMCG_NR_BINS)
2578
2579static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2580{
2581        struct pglist_data *pgdat = NODE_DATA(nid);
2582
2583#ifdef CONFIG_MEMCG
2584        if (memcg) {
2585                struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2586
2587                /* see the comment in mem_cgroup_lruvec() */
2588                if (!lruvec->pgdat)
2589                        lruvec->pgdat = pgdat;
2590
2591                return lruvec;
2592        }
2593#endif
2594        VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2595
2596        return &pgdat->__lruvec;
2597}
2598
2599static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2600{
2601        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2602        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2603
2604        if (!sc->may_swap)
2605                return 0;
2606
2607        if (!can_demote(pgdat->node_id, sc) &&
2608            mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2609                return 0;
2610
2611        return mem_cgroup_swappiness(memcg);
2612}
2613
2614static int get_nr_gens(struct lruvec *lruvec, int type)
2615{
2616        return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2617}
2618
2619static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2620{
2621        /* see the comment on lru_gen_folio */
2622        return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2623               get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2624               get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2625}
2626
2627/******************************************************************************
2628 *                          Bloom filters
2629 ******************************************************************************/
2630
2631/*
2632 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
2633 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
2634 * bits in a bitmap, k is the number of hash functions and n is the number of
2635 * inserted items.
2636 *
2637 * Page table walkers use one of the two filters to reduce their search space.
2638 * To get rid of non-leaf entries that no longer have enough leaf entries, the
2639 * aging uses the double-buffering technique to flip to the other filter each
2640 * time it produces a new generation. For non-leaf entries that have enough
2641 * leaf entries, the aging carries them over to the next generation in
2642 * walk_pmd_range(); the eviction also report them when walking the rmap
2643 * in lru_gen_look_around().
2644 *
2645 * For future optimizations:
2646 * 1. It's not necessary to keep both filters all the time. The spare one can be
2647 *    freed after the RCU grace period and reallocated if needed again.
2648 * 2. And when reallocating, it's worth scaling its size according to the number
2649 *    of inserted entries in the other filter, to reduce the memory overhead on
2650 *    small systems and false positives on large systems.
2651 * 3. Jenkins' hash function is an alternative to Knuth's.
2652 */
2653#define BLOOM_FILTER_SHIFT      15
2654
2655static inline int filter_gen_from_seq(unsigned long seq)
2656{
2657        return seq % NR_BLOOM_FILTERS;
2658}
2659
2660static void get_item_key(void *item, int *key)
2661{
2662        u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
2663
2664        BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
2665
2666        key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
2667        key[1] = hash >> BLOOM_FILTER_SHIFT;
2668}
2669
2670static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
2671{
2672        int key[2];
2673        unsigned long *filter;
2674        int gen = filter_gen_from_seq(seq);
2675
2676        filter = READ_ONCE(lruvec->mm_state.filters[gen]);
2677        if (!filter)
2678                return true;
2679
2680        get_item_key(item, key);
2681
2682        return test_bit(key[0], filter) && test_bit(key[1], filter);
2683}
2684
2685static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
2686{
2687        int key[2];
2688        unsigned long *filter;
2689        int gen = filter_gen_from_seq(seq);
2690
2691        filter = READ_ONCE(lruvec->mm_state.filters[gen]);
2692        if (!filter)
2693                return;
2694
2695        get_item_key(item, key);
2696
2697        if (!test_bit(key[0], filter))
2698                set_bit(key[0], filter);
2699        if (!test_bit(key[1], filter))
2700                set_bit(key[1], filter);
2701}
2702
2703static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
2704{
2705        unsigned long *filter;
2706        int gen = filter_gen_from_seq(seq);
2707
2708        filter = lruvec->mm_state.filters[gen];
2709        if (filter) {
2710                bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
2711                return;
2712        }
2713
2714        filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
2715                               __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
2716        WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
2717}
2718
2719/******************************************************************************
2720 *                          mm_struct list
2721 ******************************************************************************/
2722
2723static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2724{
2725        static struct lru_gen_mm_list mm_list = {
2726                .fifo = LIST_HEAD_INIT(mm_list.fifo),
2727                .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2728        };
2729
2730#ifdef CONFIG_MEMCG
2731        if (memcg)
2732                return &memcg->mm_list;
2733#endif
2734        VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2735
2736        return &mm_list;
2737}
2738
2739void lru_gen_add_mm(struct mm_struct *mm)
2740{
2741        int nid;
2742        struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2743        struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2744
2745        VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2746#ifdef CONFIG_MEMCG
2747        VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2748        mm->lru_gen.memcg = memcg;
2749#endif
2750        spin_lock(&mm_list->lock);
2751
2752        for_each_node_state(nid, N_MEMORY) {
2753                struct lruvec *lruvec = get_lruvec(memcg, nid);
2754
2755                /* the first addition since the last iteration */
2756                if (lruvec->mm_state.tail == &mm_list->fifo)
2757                        lruvec->mm_state.tail = &mm->lru_gen.list;
2758        }
2759
2760        list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
2761
2762        spin_unlock(&mm_list->lock);
2763}
2764
2765void lru_gen_del_mm(struct mm_struct *mm)
2766{
2767        int nid;
2768        struct lru_gen_mm_list *mm_list;
2769        struct mem_cgroup *memcg = NULL;
2770
2771        if (list_empty(&mm->lru_gen.list))
2772                return;
2773
2774#ifdef CONFIG_MEMCG
2775        memcg = mm->lru_gen.memcg;
2776#endif
2777        mm_list = get_mm_list(memcg);
2778
2779        spin_lock(&mm_list->lock);
2780
2781        for_each_node(nid) {
2782                struct lruvec *lruvec = get_lruvec(memcg, nid);
2783
2784                /* where the current iteration continues after */
2785                if (lruvec->mm_state.head == &mm->lru_gen.list)
2786                        lruvec->mm_state.head = lruvec->mm_state.head->prev;
2787
2788                /* where the last iteration ended before */
2789                if (lruvec->mm_state.tail == &mm->lru_gen.list)
2790                        lruvec->mm_state.tail = lruvec->mm_state.tail->next;
2791        }
2792
2793        list_del_init(&mm->lru_gen.list);
2794
2795        spin_unlock(&mm_list->lock);
2796
2797#ifdef CONFIG_MEMCG
2798        mem_cgroup_put(mm->lru_gen.memcg);
2799        mm->lru_gen.memcg = NULL;
2800#endif
2801}
2802
2803#ifdef CONFIG_MEMCG
2804void lru_gen_migrate_mm(struct mm_struct *mm)
2805{
2806        struct mem_cgroup *memcg;
2807        struct task_struct *task = rcu_dereference_protected(mm->owner, true);
2808
2809        VM_WARN_ON_ONCE(task->mm != mm);
2810        lockdep_assert_held(&task->alloc_lock);
2811
2812        /* for mm_update_next_owner() */
2813        if (mem_cgroup_disabled())
2814                return;
2815
2816        /* migration can happen before addition */
2817        if (!mm->lru_gen.memcg)
2818                return;
2819
2820        rcu_read_lock();
2821        memcg = mem_cgroup_from_task(task);
2822        rcu_read_unlock();
2823        if (memcg == mm->lru_gen.memcg)
2824                return;
2825
2826        VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
2827
2828        lru_gen_del_mm(mm);
2829        lru_gen_add_mm(mm);
2830}
2831#endif
2832
2833static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
2834{
2835        int i;
2836        int hist;
2837
2838        lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
2839
2840        if (walk) {
2841                hist = lru_hist_from_seq(walk->max_seq);
2842
2843                for (i = 0; i < NR_MM_STATS; i++) {
2844                        WRITE_ONCE(lruvec->mm_state.stats[hist][i],
2845                                   lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
2846                        walk->mm_stats[i] = 0;
2847                }
2848        }
2849
2850        if (NR_HIST_GENS > 1 && last) {
2851                hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
2852
2853                for (i = 0; i < NR_MM_STATS; i++)
2854                        WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
2855        }
2856}
2857
2858static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
2859{
2860        int type;
2861        unsigned long size = 0;
2862        struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
2863        int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
2864
2865        if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
2866                return true;
2867
2868        clear_bit(key, &mm->lru_gen.bitmap);
2869
2870        for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
2871                size += type ? get_mm_counter(mm, MM_FILEPAGES) :
2872                               get_mm_counter(mm, MM_ANONPAGES) +
2873                               get_mm_counter(mm, MM_SHMEMPAGES);
2874        }
2875
2876        if (size < MIN_LRU_BATCH)
2877                return true;
2878
2879        return !mmget_not_zero(mm);
2880}
2881
2882static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
2883                            struct mm_struct **iter)
2884{
2885        bool first = false;
2886        bool last = false;
2887        struct mm_struct *mm = NULL;
2888        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2889        struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2890        struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
2891
2892        /*
2893         * mm_state->seq is incremented after each iteration of mm_list. There
2894         * are three interesting cases for this page table walker:
2895         * 1. It tries to start a new iteration with a stale max_seq: there is
2896         *    nothing left to do.
2897         * 2. It started the next iteration: it needs to reset the Bloom filter
2898         *    so that a fresh set of PTE tables can be recorded.
2899         * 3. It ended the current iteration: it needs to reset the mm stats
2900         *    counters and tell its caller to increment max_seq.
2901         */
2902        spin_lock(&mm_list->lock);
2903
2904        VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
2905
2906        if (walk->max_seq <= mm_state->seq)
2907                goto done;
2908
2909        if (!mm_state->head)
2910                mm_state->head = &mm_list->fifo;
2911
2912        if (mm_state->head == &mm_list->fifo)
2913                first = true;
2914
2915        do {
2916                mm_state->head = mm_state->head->next;
2917                if (mm_state->head == &mm_list->fifo) {
2918                        WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
2919                        last = true;
2920                        break;
2921                }
2922
2923                /* force scan for those added after the last iteration */
2924                if (!mm_state->tail || mm_state->tail == mm_state->head) {
2925                        mm_state->tail = mm_state->head->next;
2926                        walk->force_scan = true;
2927                }
2928
2929                mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
2930                if (should_skip_mm(mm, walk))
2931                        mm = NULL;
2932        } while (!mm);
2933done:
2934        if (*iter || last)
2935                reset_mm_stats(lruvec, walk, last);
2936
2937        spin_unlock(&mm_list->lock);
2938
2939        if (mm && first)
2940                reset_bloom_filter(lruvec, walk->max_seq + 1);
2941
2942        if (*iter)
2943                mmput_async(*iter);
2944
2945        *iter = mm;
2946
2947        return last;
2948}
2949
2950static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
2951{
2952        bool success = false;
2953        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2954        struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2955        struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
2956
2957        spin_lock(&mm_list->lock);
2958
2959        VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
2960
2961        if (max_seq > mm_state->seq) {
2962                mm_state->head = NULL;
2963                mm_state->tail = NULL;
2964                WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
2965                reset_mm_stats(lruvec, NULL, true);
2966                success = true;
2967        }
2968
2969        spin_unlock(&mm_list->lock);
2970
2971        return success;
2972}
2973
2974/******************************************************************************
2975 *                          PID controller
2976 ******************************************************************************/
2977
2978/*
2979 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
2980 *
2981 * The P term is refaulted/(evicted+protected) from a tier in the generation
2982 * currently being evicted; the I term is the exponential moving average of the
2983 * P term over the generations previously evicted, using the smoothing factor
2984 * 1/2; the D term isn't supported.
2985 *
2986 * The setpoint (SP) is always the first tier of one type; the process variable
2987 * (PV) is either any tier of the other type or any other tier of the same
2988 * type.
2989 *
2990 * The error is the difference between the SP and the PV; the correction is to
2991 * turn off protection when SP>PV or turn on protection when SP<PV.
2992 *
2993 * For future optimizations:
2994 * 1. The D term may discount the other two terms over time so that long-lived
2995 *    generations can resist stale information.
2996 */
2997struct ctrl_pos {
2998        unsigned long refaulted;
2999        unsigned long total;
3000        int gain;
3001};
3002
3003static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3004                          struct ctrl_pos *pos)
3005{
3006        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3007        int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3008
3009        pos->refaulted = lrugen->avg_refaulted[type][tier] +
3010                         atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3011        pos->total = lrugen->avg_total[type][tier] +
3012                     atomic_long_read(&lrugen->evicted[hist][type][tier]);
3013        if (tier)
3014                pos->total += lrugen->protected[hist][type][tier - 1];
3015        pos->gain = gain;
3016}
3017
3018static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3019{
3020        int hist, tier;
3021        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3022        bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3023        unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3024
3025        lockdep_assert_held(&lruvec->lru_lock);
3026
3027        if (!carryover && !clear)
3028                return;
3029
3030        hist = lru_hist_from_seq(seq);
3031
3032        for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3033                if (carryover) {
3034                        unsigned long sum;
3035
3036                        sum = lrugen->avg_refaulted[type][tier] +
3037                              atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3038                        WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3039
3040                        sum = lrugen->avg_total[type][tier] +
3041                              atomic_long_read(&lrugen->evicted[hist][type][tier]);
3042                        if (tier)
3043                                sum += lrugen->protected[hist][type][tier - 1];
3044                        WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3045                }
3046
3047                if (clear) {
3048                        atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3049                        atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3050                        if (tier)
3051                                WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3052                }
3053        }
3054}
3055
3056static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3057{
3058        /*
3059         * Return true if the PV has a limited number of refaults or a lower
3060         * refaulted/total than the SP.
3061         */
3062        return pv->refaulted < MIN_LRU_BATCH ||
3063               pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3064               (sp->refaulted + 1) * pv->total * pv->gain;
3065}
3066
3067/******************************************************************************
3068 *                          the aging
3069 ******************************************************************************/
3070
3071/* promote pages accessed through page tables */
3072static int folio_update_gen(struct folio *folio, int gen)
3073{
3074        unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3075
3076        VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3077        VM_WARN_ON_ONCE(!rcu_read_lock_held());
3078
3079        do {
3080                /* lru_gen_del_folio() has isolated this page? */
3081                if (!(old_flags & LRU_GEN_MASK)) {
3082                        /* for shrink_folio_list() */
3083                        new_flags = old_flags | BIT(PG_referenced);
3084                        continue;
3085                }
3086
3087                new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3088                new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3089        } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3090
3091        return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3092}
3093
3094/* protect pages accessed multiple times through file descriptors */
3095static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3096{
3097        int type = folio_is_file_lru(folio);
3098        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3099        int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3100        unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3101
3102        VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3103
3104        do {
3105                new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3106                /* folio_update_gen() has promoted this page? */
3107                if (new_gen >= 0 && new_gen != old_gen)
3108                        return new_gen;
3109
3110                new_gen = (old_gen + 1) % MAX_NR_GENS;
3111
3112                new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3113                new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3114                /* for folio_end_writeback() */
3115                if (reclaiming)
3116                        new_flags |= BIT(PG_reclaim);
3117        } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3118
3119        lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3120
3121        return new_gen;
3122}
3123
3124static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3125                              int old_gen, int new_gen)
3126{
3127        int type = folio_is_file_lru(folio);
3128        int zone = folio_zonenum(folio);
3129        int delta = folio_nr_pages(folio);
3130
3131        VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3132        VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3133
3134        walk->batched++;
3135
3136        walk->nr_pages[old_gen][type][zone] -= delta;
3137        walk->nr_pages[new_gen][type][zone] += delta;
3138}
3139
3140static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3141{
3142        int gen, type, zone;
3143        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3144
3145        walk->batched = 0;
3146
3147        for_each_gen_type_zone(gen, type, zone) {
3148                enum lru_list lru = type * LRU_INACTIVE_FILE;
3149                int delta = walk->nr_pages[gen][type][zone];
3150
3151                if (!delta)
3152                        continue;
3153
3154                walk->nr_pages[gen][type][zone] = 0;
3155                WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3156                           lrugen->nr_pages[gen][type][zone] + delta);
3157
3158                if (lru_gen_is_active(lruvec, gen))
3159                        lru += LRU_ACTIVE;
3160                __update_lru_size(lruvec, lru, zone, delta);
3161        }
3162}
3163
3164static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3165{
3166        struct address_space *mapping;
3167        struct vm_area_struct *vma = args->vma;
3168        struct lru_gen_mm_walk *walk = args->private;
3169
3170        if (!vma_is_accessible(vma))
3171                return true;
3172
3173        if (is_vm_hugetlb_page(vma))
3174                return true;
3175
3176        if (!vma_has_recency(vma))
3177                return true;
3178
3179        if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
3180                return true;
3181
3182        if (vma == get_gate_vma(vma->vm_mm))
3183                return true;
3184
3185        if (vma_is_anonymous(vma))
3186                return !walk->can_swap;
3187
3188        if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3189                return true;
3190
3191        mapping = vma->vm_file->f_mapping;
3192        if (mapping_unevictable(mapping))
3193                return true;
3194
3195        if (shmem_mapping(mapping))
3196                return !walk->can_swap;
3197
3198        /* to exclude special mappings like dax, etc. */
3199        return !mapping->a_ops->read_folio;
3200}
3201
3202/*
3203 * Some userspace memory allocators map many single-page VMAs. Instead of
3204 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3205 * table to reduce zigzags and improve cache performance.
3206 */
3207static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3208                         unsigned long *vm_start, unsigned long *vm_end)
3209{
3210        unsigned long start = round_up(*vm_end, size);
3211        unsigned long end = (start | ~mask) + 1;
3212        VMA_ITERATOR(vmi, args->mm, start);
3213
3214        VM_WARN_ON_ONCE(mask & size);
3215        VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3216
3217        for_each_vma(vmi, args->vma) {
3218                if (end && end <= args->vma->vm_start)
3219                        return false;
3220
3221                if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
3222                        continue;
3223
3224                *vm_start = max(start, args->vma->vm_start);
3225                *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3226
3227                return true;
3228        }
3229
3230        return false;
3231}
3232
3233static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3234{
3235        unsigned long pfn = pte_pfn(pte);
3236
3237        VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3238
3239        if (!pte_present(pte) || is_zero_pfn(pfn))
3240                return -1;
3241
3242        if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3243                return -1;
3244
3245        if (WARN_ON_ONCE(!pfn_valid(pfn)))
3246                return -1;
3247
3248        return pfn;
3249}
3250
3251#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3252static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3253{
3254        unsigned long pfn = pmd_pfn(pmd);
3255
3256        VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3257
3258        if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3259                return -1;
3260
3261        if (WARN_ON_ONCE(pmd_devmap(pmd)))
3262                return -1;
3263
3264        if (WARN_ON_ONCE(!pfn_valid(pfn)))
3265                return -1;
3266
3267        return pfn;
3268}
3269#endif
3270
3271static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3272                                   struct pglist_data *pgdat, bool can_swap)
3273{
3274        struct folio *folio;
3275
3276        /* try to avoid unnecessary memory loads */
3277        if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3278                return NULL;
3279
3280        folio = pfn_folio(pfn);
3281        if (folio_nid(folio) != pgdat->node_id)
3282                return NULL;
3283
3284        if (folio_memcg_rcu(folio) != memcg)
3285                return NULL;
3286
3287        /* file VMAs can contain anon pages from COW */
3288        if (!folio_is_file_lru(folio) && !can_swap)
3289                return NULL;
3290
3291        return folio;
3292}
3293
3294static bool suitable_to_scan(int total, int young)
3295{
3296        int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3297
3298        /* suitable if the average number of young PTEs per cacheline is >=1 */
3299        return young * n >= total;
3300}
3301
3302static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3303                           struct mm_walk *args)
3304{
3305        int i;
3306        pte_t *pte;
3307        spinlock_t *ptl;
3308        unsigned long addr;
3309        int total = 0;
3310        int young = 0;
3311        struct lru_gen_mm_walk *walk = args->private;
3312        struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3313        struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3314        int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3315
3316        pte = pte_offset_map_nolock(args->mm, pmd, start & PMD_MASK, &ptl);
3317        if (!pte)
3318                return false;
3319        if (!spin_trylock(ptl)) {
3320                pte_unmap(pte);
3321                return false;
3322        }
3323
3324        arch_enter_lazy_mmu_mode();
3325restart:
3326        for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3327                unsigned long pfn;
3328                struct folio *folio;
3329                pte_t ptent = ptep_get(pte + i);
3330
3331                total++;
3332                walk->mm_stats[MM_LEAF_TOTAL]++;
3333
3334                pfn = get_pte_pfn(ptent, args->vma, addr);
3335                if (pfn == -1)
3336                        continue;
3337
3338                if (!pte_young(ptent)) {
3339                        walk->mm_stats[MM_LEAF_OLD]++;
3340                        continue;
3341                }
3342
3343                folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3344                if (!folio)
3345                        continue;
3346
3347                if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3348                        VM_WARN_ON_ONCE(true);
3349
3350                young++;
3351                walk->mm_stats[MM_LEAF_YOUNG]++;
3352
3353                if (pte_dirty(ptent) && !folio_test_dirty(folio) &&
3354                    !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3355                      !folio_test_swapcache(folio)))
3356                        folio_mark_dirty(folio);
3357
3358                old_gen = folio_update_gen(folio, new_gen);
3359                if (old_gen >= 0 && old_gen != new_gen)
3360                        update_batch_size(walk, folio, old_gen, new_gen);
3361        }
3362
3363        if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3364                goto restart;
3365
3366        arch_leave_lazy_mmu_mode();
3367        pte_unmap_unlock(pte, ptl);
3368
3369        return suitable_to_scan(total, young);
3370}
3371
3372#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3373static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
3374                                  struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
3375{
3376        int i;
3377        pmd_t *pmd;
3378        spinlock_t *ptl;
3379        struct lru_gen_mm_walk *walk = args->private;
3380        struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3381        struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3382        int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3383
3384        VM_WARN_ON_ONCE(pud_leaf(*pud));
3385
3386        /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3387        if (*first == -1) {
3388                *first = addr;
3389                bitmap_zero(bitmap, MIN_LRU_BATCH);
3390                return;
3391        }
3392
3393        i = addr == -1 ? 0 : pmd_index(addr) - pmd_index(*first);
3394        if (i && i <= MIN_LRU_BATCH) {
3395                __set_bit(i - 1, bitmap);
3396                return;
3397        }
3398
3399        pmd = pmd_offset(pud, *first);
3400
3401        ptl = pmd_lockptr(args->mm, pmd);
3402        if (!spin_trylock(ptl))
3403                goto done;
3404
3405        arch_enter_lazy_mmu_mode();
3406
3407        do {
3408                unsigned long pfn;
3409                struct folio *folio;
3410
3411                /* don't round down the first address */
3412                addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first;
3413
3414                pfn = get_pmd_pfn(pmd[i], vma, addr);
3415                if (pfn == -1)
3416                        goto next;
3417
3418                if (!pmd_trans_huge(pmd[i])) {
3419                        if (should_clear_pmd_young())
3420                                pmdp_test_and_clear_young(vma, addr, pmd + i);
3421                        goto next;
3422                }
3423
3424                folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3425                if (!folio)
3426                        goto next;
3427
3428                if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3429                        goto next;
3430
3431                walk->mm_stats[MM_LEAF_YOUNG]++;
3432
3433                if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
3434                    !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3435                      !folio_test_swapcache(folio)))
3436                        folio_mark_dirty(folio);
3437
3438                old_gen = folio_update_gen(folio, new_gen);
3439                if (old_gen >= 0 && old_gen != new_gen)
3440                        update_batch_size(walk, folio, old_gen, new_gen);
3441next:
3442                i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3443        } while (i <= MIN_LRU_BATCH);
3444
3445        arch_leave_lazy_mmu_mode();
3446        spin_unlock(ptl);
3447done:
3448        *first = -1;
3449}
3450#else
3451static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
3452                                  struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
3453{
3454}
3455#endif
3456
3457static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3458                           struct mm_walk *args)
3459{
3460        int i;
3461        pmd_t *pmd;
3462        unsigned long next;
3463        unsigned long addr;
3464        struct vm_area_struct *vma;
3465        DECLARE_BITMAP(bitmap, MIN_LRU_BATCH);
3466        unsigned long first = -1;
3467        struct lru_gen_mm_walk *walk = args->private;
3468
3469        VM_WARN_ON_ONCE(pud_leaf(*pud));
3470
3471        /*
3472         * Finish an entire PMD in two passes: the first only reaches to PTE
3473         * tables to avoid taking the PMD lock; the second, if necessary, takes
3474         * the PMD lock to clear the accessed bit in PMD entries.
3475         */
3476        pmd = pmd_offset(pud, start & PUD_MASK);
3477restart:
3478        /* walk_pte_range() may call get_next_vma() */
3479        vma = args->vma;
3480        for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3481                pmd_t val = pmdp_get_lockless(pmd + i);
3482
3483                next = pmd_addr_end(addr, end);
3484
3485                if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3486                        walk->mm_stats[MM_LEAF_TOTAL]++;
3487                        continue;
3488                }
3489
3490#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3491                if (pmd_trans_huge(val)) {
3492                        unsigned long pfn = pmd_pfn(val);
3493                        struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3494
3495                        walk->mm_stats[MM_LEAF_TOTAL]++;
3496
3497                        if (!pmd_young(val)) {
3498                                walk->mm_stats[MM_LEAF_OLD]++;
3499                                continue;
3500                        }
3501
3502                        /* try to avoid unnecessary memory loads */
3503                        if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3504                                continue;
3505
3506                        walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
3507                        continue;
3508                }
3509#endif
3510                walk->mm_stats[MM_NONLEAF_TOTAL]++;
3511
3512                if (should_clear_pmd_young()) {
3513                        if (!pmd_young(val))
3514                                continue;
3515
3516                        walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
3517                }
3518
3519                if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3520                        continue;
3521
3522                walk->mm_stats[MM_NONLEAF_FOUND]++;
3523
3524                if (!walk_pte_range(&val, addr, next, args))
3525                        continue;
3526
3527                walk->mm_stats[MM_NONLEAF_ADDED]++;
3528
3529                /* carry over to the next generation */
3530                update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3531        }
3532
3533        walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
3534
3535        if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3536                goto restart;
3537}
3538
3539static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3540                          struct mm_walk *args)
3541{
3542        int i;
3543        pud_t *pud;
3544        unsigned long addr;
3545        unsigned long next;
3546        struct lru_gen_mm_walk *walk = args->private;
3547
3548        VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3549
3550        pud = pud_offset(p4d, start & P4D_MASK);
3551restart:
3552        for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3553                pud_t val = READ_ONCE(pud[i]);
3554
3555                next = pud_addr_end(addr, end);
3556
3557                if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3558                        continue;
3559
3560                walk_pmd_range(&val, addr, next, args);
3561
3562                if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3563                        end = (addr | ~PUD_MASK) + 1;
3564                        goto done;
3565                }
3566        }
3567
3568        if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3569                goto restart;
3570
3571        end = round_up(end, P4D_SIZE);
3572done:
3573        if (!end || !args->vma)
3574                return 1;
3575
3576        walk->next_addr = max(end, args->vma->vm_start);
3577
3578        return -EAGAIN;
3579}
3580
3581static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3582{
3583        static const struct mm_walk_ops mm_walk_ops = {
3584                .test_walk = should_skip_vma,
3585                .p4d_entry = walk_pud_range,
3586                .walk_lock = PGWALK_RDLOCK,
3587        };
3588
3589        int err;
3590        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3591
3592        walk->next_addr = FIRST_USER_ADDRESS;
3593
3594        do {
3595                DEFINE_MAX_SEQ(lruvec);
3596
3597                err = -EBUSY;
3598
3599                /* another thread might have called inc_max_seq() */
3600                if (walk->max_seq != max_seq)
3601                        break;
3602
3603                /* folio_update_gen() requires stable folio_memcg() */
3604                if (!mem_cgroup_trylock_pages(memcg))
3605                        break;
3606
3607                /* the caller might be holding the lock for write */
3608                if (mmap_read_trylock(mm)) {
3609                        err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3610
3611                        mmap_read_unlock(mm);
3612                }
3613
3614                mem_cgroup_unlock_pages();
3615
3616                if (walk->batched) {
3617                        spin_lock_irq(&lruvec->lru_lock);
3618                        reset_batch_size(lruvec, walk);
3619                        spin_unlock_irq(&lruvec->lru_lock);
3620                }
3621
3622                cond_resched();
3623        } while (err == -EAGAIN);
3624}
3625
3626static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
3627{
3628        struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3629
3630        if (pgdat && current_is_kswapd()) {
3631                VM_WARN_ON_ONCE(walk);
3632
3633                walk = &pgdat->mm_walk;
3634        } else if (!walk && force_alloc) {
3635                VM_WARN_ON_ONCE(current_is_kswapd());
3636
3637                walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3638        }
3639
3640        current->reclaim_state->mm_walk = walk;
3641
3642        return walk;
3643}
3644
3645static void clear_mm_walk(void)
3646{
3647        struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3648
3649        VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
3650        VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
3651
3652        current->reclaim_state->mm_walk = NULL;
3653
3654        if (!current_is_kswapd())
3655                kfree(walk);
3656}
3657
3658static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
3659{
3660        int zone;
3661        int remaining = MAX_LRU_BATCH;
3662        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3663        int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3664
3665        if (type == LRU_GEN_ANON && !can_swap)
3666                goto done;
3667
3668        /* prevent cold/hot inversion if force_scan is true */
3669        for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3670                struct list_head *head = &lrugen->folios[old_gen][type][zone];
3671
3672                while (!list_empty(head)) {
3673                        struct folio *folio = lru_to_folio(head);
3674
3675                        VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
3676                        VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
3677                        VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
3678                        VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
3679
3680                        new_gen = folio_inc_gen(lruvec, folio, false);
3681                        list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
3682
3683                        if (!--remaining)
3684                                return false;
3685                }
3686        }
3687done:
3688        reset_ctrl_pos(lruvec, type, true);
3689        WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3690
3691        return true;
3692}
3693
3694static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3695{
3696        int gen, type, zone;
3697        bool success = false;
3698        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3699        DEFINE_MIN_SEQ(lruvec);
3700
3701        VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3702
3703        /* find the oldest populated generation */
3704        for (type = !can_swap; type < ANON_AND_FILE; type++) {
3705                while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3706                        gen = lru_gen_from_seq(min_seq[type]);
3707
3708                        for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3709                                if (!list_empty(&lrugen->folios[gen][type][zone]))
3710                                        goto next;
3711                        }
3712
3713                        min_seq[type]++;
3714                }
3715next:
3716                ;
3717        }
3718
3719        /* see the comment on lru_gen_folio */
3720        if (can_swap) {
3721                min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3722                min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3723        }
3724
3725        for (type = !can_swap; type < ANON_AND_FILE; type++) {
3726                if (min_seq[type] == lrugen->min_seq[type])
3727                        continue;
3728
3729                reset_ctrl_pos(lruvec, type, true);
3730                WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3731                success = true;
3732        }
3733
3734        return success;
3735}
3736
3737static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
3738{
3739        int prev, next;
3740        int type, zone;
3741        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3742restart:
3743        spin_lock_irq(&lruvec->lru_lock);
3744
3745        VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3746
3747        for (type = ANON_AND_FILE - 1; type >= 0; type--) {
3748                if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3749                        continue;
3750
3751                VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
3752
3753                if (inc_min_seq(lruvec, type, can_swap))
3754                        continue;
3755
3756                spin_unlock_irq(&lruvec->lru_lock);
3757                cond_resched();
3758                goto restart;
3759        }
3760
3761        /*
3762         * Update the active/inactive LRU sizes for compatibility. Both sides of
3763         * the current max_seq need to be covered, since max_seq+1 can overlap
3764         * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3765         * overlap, cold/hot inversion happens.
3766         */
3767        prev = lru_gen_from_seq(lrugen->max_seq - 1);
3768        next = lru_gen_from_seq(lrugen->max_seq + 1);
3769
3770        for (type = 0; type < ANON_AND_FILE; type++) {
3771                for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3772                        enum lru_list lru = type * LRU_INACTIVE_FILE;
3773                        long delta = lrugen->nr_pages[prev][type][zone] -
3774                                     lrugen->nr_pages[next][type][zone];
3775
3776                        if (!delta)
3777                                continue;
3778
3779                        __update_lru_size(lruvec, lru, zone, delta);
3780                        __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3781                }
3782        }
3783
3784        for (type = 0; type < ANON_AND_FILE; type++)
3785                reset_ctrl_pos(lruvec, type, false);
3786
3787        WRITE_ONCE(lrugen->timestamps[next], jiffies);
3788        /* make sure preceding modifications appear */
3789        smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3790
3791        spin_unlock_irq(&lruvec->lru_lock);
3792}
3793
3794static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
3795                               struct scan_control *sc, bool can_swap, bool force_scan)
3796{
3797        bool success;
3798        struct lru_gen_mm_walk *walk;
3799        struct mm_struct *mm = NULL;
3800        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3801
3802        VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
3803
3804        /* see the comment in iterate_mm_list() */
3805        if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
3806                success = false;
3807                goto done;
3808        }
3809
3810        /*
3811         * If the hardware doesn't automatically set the accessed bit, fallback
3812         * to lru_gen_look_around(), which only clears the accessed bit in a
3813         * handful of PTEs. Spreading the work out over a period of time usually
3814         * is less efficient, but it avoids bursty page faults.
3815         */
3816        if (!should_walk_mmu()) {
3817                success = iterate_mm_list_nowalk(lruvec, max_seq);
3818                goto done;
3819        }
3820
3821        walk = set_mm_walk(NULL, true);
3822        if (!walk) {
3823                success = iterate_mm_list_nowalk(lruvec, max_seq);
3824                goto done;
3825        }
3826
3827        walk->lruvec = lruvec;
3828        walk->max_seq = max_seq;
3829        walk->can_swap = can_swap;
3830        walk->force_scan = force_scan;
3831
3832        do {
3833                success = iterate_mm_list(lruvec, walk, &mm);
3834                if (mm)
3835                        walk_mm(lruvec, mm, walk);
3836        } while (mm);
3837done:
3838        if (success)
3839                inc_max_seq(lruvec, can_swap, force_scan);
3840
3841        return success;
3842}
3843
3844/******************************************************************************
3845 *                          working set protection
3846 ******************************************************************************/
3847
3848static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
3849{
3850        int gen, type, zone;
3851        unsigned long total = 0;
3852        bool can_swap = get_swappiness(lruvec, sc);
3853        struct lru_gen_folio *lrugen = &lruvec->lrugen;
3854        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3855        DEFINE_MAX_SEQ(lruvec);
3856        DEFINE_MIN_SEQ(lruvec);
3857
3858        for (type = !can_swap; type < ANON_AND_FILE; type++) {
3859                unsigned long seq;
3860
3861                for (seq = min_seq[type]; seq <= max_seq; seq++) {
3862                        gen = lru_gen_from_seq(seq);
3863
3864                        for (zone = 0; zone < MAX_NR_ZONES; zone++)
3865                                total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
3866                }
3867        }
3868
3869        /* whether the size is big enough to be helpful */
3870        return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
3871}
3872
3873static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
3874                                  unsigned long min_ttl)
3875{
3876        int gen;
3877        unsigned long birth;
3878        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3879        DEFINE_MIN_SEQ(lruvec);
3880
3881        /* see the comment on lru_gen_folio */
3882        gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
3883        birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
3884
3885        if (time_is_after_jiffies(birth + min_ttl))
3886                return false;
3887
3888        if (!lruvec_is_sizable(lruvec, sc))
3889                return false;
3890
3891        mem_cgroup_calculate_protection(NULL, memcg);
3892
3893        return !mem_cgroup_below_min(NULL, memcg);
3894}
3895
3896/* to protect the working set of the last N jiffies */
3897static unsigned long lru_gen_min_ttl __read_mostly;
3898
3899static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3900{
3901        struct mem_cgroup *memcg;
3902        unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
3903
3904        VM_WARN_ON_ONCE(!current_is_kswapd());
3905
3906        /* check the order to exclude compaction-induced reclaim */
3907        if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
3908                return;
3909
3910        memcg = mem_cgroup_iter(NULL, NULL, NULL);
3911        do {
3912                struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3913
3914                if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
3915                        mem_cgroup_iter_break(NULL, memcg);
3916                        return;
3917                }
3918
3919                cond_resched();
3920        } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
3921
3922        /*
3923         * The main goal is to OOM kill if every generation from all memcgs is
3924         * younger than min_ttl. However, another possibility is all memcgs are
3925         * either too small or below min.
3926         */
3927        if (mutex_trylock(&oom_lock)) {
3928                struct oom_control oc = {
3929                        .gfp_mask = sc->gfp_mask,
3930                };
3931
3932                out_of_memory(&oc);
3933
3934                mutex_unlock(&oom_lock);
3935        }
3936}
3937
3938/******************************************************************************
3939 *                          rmap/PT walk feedback
3940 ******************************************************************************/
3941
3942/*
3943 * This function exploits spatial locality when shrink_folio_list() walks the
3944 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
3945 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
3946 * the PTE table to the Bloom filter. This forms a feedback loop between the
3947 * eviction and the aging.
3948 */
3949void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
3950{
3951        int i;
3952        unsigned long start;
3953        unsigned long end;
3954        struct lru_gen_mm_walk *walk;
3955        int young = 0;
3956        pte_t *pte = pvmw->pte;
3957        unsigned long addr = pvmw->address;
3958        struct vm_area_struct *vma = pvmw->vma;
3959        struct folio *folio = pfn_folio(pvmw->pfn);
3960        bool can_swap = !folio_is_file_lru(folio);
3961        struct mem_cgroup *memcg = folio_memcg(folio);
3962        struct pglist_data *pgdat = folio_pgdat(folio);
3963        struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3964        DEFINE_MAX_SEQ(lruvec);
3965        int old_gen, new_gen = lru_gen_from_seq(max_seq);
3966
3967        lockdep_assert_held(pvmw->ptl);
3968        VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
3969
3970        if (spin_is_contended(pvmw->ptl))
3971                return;
3972
3973        /* exclude special VMAs containing anon pages from COW */
3974        if (vma->vm_flags & VM_SPECIAL)
3975                return;
3976
3977        /* avoid taking the LRU lock under the PTL when possible */
3978        walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
3979
3980        start = max(addr & PMD_MASK, vma->vm_start);
3981        end = min(addr | ~PMD_MASK, vma->vm_end - 1) + 1;
3982
3983        if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
3984                if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
3985                        end = start + MIN_LRU_BATCH * PAGE_SIZE;
3986                else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
3987                        start = end - MIN_LRU_BATCH * PAGE_SIZE;
3988                else {
3989                        start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
3990                        end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
3991                }
3992        }
3993
3994        /* folio_update_gen() requires stable folio_memcg() */
3995        if (!mem_cgroup_trylock_pages(memcg))
3996                return;
3997
3998        arch_enter_lazy_mmu_mode();
3999
4000        pte -= (addr - start) / PAGE_SIZE;
4001
4002        for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4003                unsigned long pfn;
4004                pte_t ptent = ptep_get(pte + i);
4005
4006                pfn = get_pte_pfn(ptent, vma, addr);
4007                if (pfn == -1)
4008                        continue;
4009
4010                if (!pte_young(ptent))
4011                        continue;
4012
4013                folio = get_pfn_folio(pfn, memcg, pgdat, can_swap);
4014                if (!folio)
4015                        continue;
4016
4017                if (!ptep_test_and_clear_young(vma, addr, pte + i))
4018                        VM_WARN_ON_ONCE(true);
4019
4020                young++;
4021
4022                if (pte_dirty(ptent) && !folio_test_dirty(folio) &&
4023                    !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4024                      !folio_test_swapcache(folio)))
4025                        folio_mark_dirty(folio);
4026
4027                if (walk) {
4028                        old_gen = folio_update_gen(folio, new_gen);
4029                        if (old_gen >= 0 && old_gen != new_gen)
4030                                update_batch_size(walk, folio, old_gen, new_gen);
4031
4032                        continue;
4033                }
4034
4035                old_gen = folio_lru_gen(folio);
4036                if (old_gen < 0)
4037                        folio_set_referenced(folio);
4038                else if (old_gen != new_gen)
4039                        folio_activate(folio);
4040        }
4041
4042        arch_leave_lazy_mmu_mode();
4043        mem_cgroup_unlock_pages();
4044
4045        /* feedback from rmap walkers to page table walkers */
4046        if (suitable_to_scan(i, young))
4047                update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4048}
4049
4050/******************************************************************************
4051 *                          memcg LRU
4052 ******************************************************************************/
4053
4054/* see the comment on MEMCG_NR_GENS */
4055enum {
4056        MEMCG_LRU_NOP,
4057        MEMCG_LRU_HEAD,
4058        MEMCG_LRU_TAIL,
4059        MEMCG_LRU_OLD,
4060        MEMCG_LRU_YOUNG,
4061};
4062
4063#ifdef CONFIG_MEMCG
4064
4065static int lru_gen_memcg_seg(struct lruvec *lruvec)
4066{
4067        return READ_ONCE(lruvec->lrugen.seg);
4068}
4069
4070static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
4071{
4072        int seg;
4073        int old, new;
4074        unsigned long flags;
4075        int bin = get_random_u32_below(MEMCG_NR_BINS);
4076        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4077
4078        spin_lock_irqsave(&pgdat->memcg_lru.lock, flags);
4079
4080        VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4081
4082        seg = 0;
4083        new = old = lruvec->lrugen.gen;
4084
4085        /* see the comment on MEMCG_NR_GENS */
4086        if (op == MEMCG_LRU_HEAD)
4087                seg = MEMCG_LRU_HEAD;
4088        else if (op == MEMCG_LRU_TAIL)
4089                seg = MEMCG_LRU_TAIL;
4090        else if (op == MEMCG_LRU_OLD)
4091                new = get_memcg_gen(pgdat->memcg_lru.seq);
4092        else if (op == MEMCG_LRU_YOUNG)
4093                new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
4094        else
4095                VM_WARN_ON_ONCE(true);
4096
4097        WRITE_ONCE(lruvec->lrugen.seg, seg);
4098        WRITE_ONCE(lruvec->lrugen.gen, new);
4099
4100        hlist_nulls_del_rcu(&lruvec->lrugen.list);
4101
4102        if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
4103                hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4104        else
4105                hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4106
4107        pgdat->memcg_lru.nr_memcgs[old]--;
4108        pgdat->memcg_lru.nr_memcgs[new]++;
4109
4110        if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
4111                WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4112
4113        spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags);
4114}
4115
4116void lru_gen_online_memcg(struct mem_cgroup *memcg)
4117{
4118        int gen;
4119        int nid;
4120        int bin = get_random_u32_below(MEMCG_NR_BINS);
4121
4122        for_each_node(nid) {
4123                struct pglist_data *pgdat = NODE_DATA(nid);
4124                struct lruvec *lruvec = get_lruvec(memcg, nid);
4125
4126                spin_lock_irq(&pgdat->memcg_lru.lock);
4127
4128                VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
4129
4130                gen = get_memcg_gen(pgdat->memcg_lru.seq);
4131
4132                lruvec->lrugen.gen = gen;
4133
4134                hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
4135                pgdat->memcg_lru.nr_memcgs[gen]++;
4136
4137                spin_unlock_irq(&pgdat->memcg_lru.lock);
4138        }
4139}
4140
4141void lru_gen_offline_memcg(struct mem_cgroup *memcg)
4142{
4143        int nid;
4144
4145        for_each_node(nid) {
4146                struct lruvec *lruvec = get_lruvec(memcg, nid);
4147
4148                lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
4149        }
4150}
4151
4152void lru_gen_release_memcg(struct mem_cgroup *memcg)
4153{
4154        int gen;
4155        int nid;
4156
4157        for_each_node(nid) {
4158                struct pglist_data *pgdat = NODE_DATA(nid);
4159                struct lruvec *lruvec = get_lruvec(memcg, nid);
4160
4161                spin_lock_irq(&pgdat->memcg_lru.lock);
4162
4163                if (hlist_nulls_unhashed(&lruvec->lrugen.list))
4164                        goto unlock;
4165
4166                gen = lruvec->lrugen.gen;
4167
4168                hlist_nulls_del_init_rcu(&lruvec->lrugen.list);
4169                pgdat->memcg_lru.nr_memcgs[gen]--;
4170
4171                if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
4172                        WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4173unlock:
4174                spin_unlock_irq(&pgdat->memcg_lru.lock);
4175        }
4176}
4177
4178void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
4179{
4180        struct lruvec *lruvec = get_lruvec(memcg, nid);
4181
4182        /* see the comment on MEMCG_NR_GENS */
4183        if (lru_gen_memcg_seg(lruvec) != MEMCG_LRU_HEAD)
4184                lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
4185}
4186
4187#else /* !CONFIG_MEMCG */
4188
4189static int lru_gen_memcg_seg(struct lruvec *lruvec)
4190{
4191        return 0;
4192}
4193
4194#endif
4195
4196/******************************************************************************
4197 *                          the eviction
4198 ******************************************************************************/
4199
4200static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc,
4201                       int tier_idx)
4202{
4203        bool success;
4204        int gen = folio_lru_gen(folio);
4205        int type = folio_is_file_lru(folio);
4206        int zone = folio_zonenum(folio);
4207        int delta = folio_nr_pages(folio);
4208        int refs = folio_lru_refs(folio);
4209        int tier = lru_tier_from_refs(refs);
4210        struct lru_gen_folio *lrugen = &lruvec->lrugen;
4211
4212        VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4213
4214        /* unevictable */
4215        if (!folio_evictable(folio)) {
4216                success = lru_gen_del_folio(lruvec, folio, true);
4217                VM_WARN_ON_ONCE_FOLIO(!success, folio);
4218                folio_set_unevictable(folio);
4219                lruvec_add_folio(lruvec, folio);
4220                __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4221                return true;
4222        }
4223
4224        /* dirty lazyfree */
4225        if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4226                success = lru_gen_del_folio(lruvec, folio, true);
4227                VM_WARN_ON_ONCE_FOLIO(!success, folio);
4228                folio_set_swapbacked(folio);
4229                lruvec_add_folio_tail(lruvec, folio);
4230                return true;
4231        }
4232
4233        /* promoted */
4234        if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4235                list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4236                return true;
4237        }
4238
4239        /* protected */
4240        if (tier > tier_idx || refs == BIT(LRU_REFS_WIDTH)) {
4241                int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4242
4243                gen = folio_inc_gen(lruvec, folio, false);
4244                list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4245
4246                WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4247                           lrugen->protected[hist][type][tier - 1] + delta);
4248                return true;
4249        }
4250
4251        /* ineligible */
4252        if (zone > sc->reclaim_idx || skip_cma(folio, sc)) {
4253                gen = folio_inc_gen(lruvec, folio, false);
4254                list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4255                return true;
4256        }
4257
4258        /* waiting for writeback */
4259        if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4260            (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4261                gen = folio_inc_gen(lruvec, folio, true);
4262                list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4263                return true;
4264        }
4265
4266        return false;
4267}
4268
4269static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4270{
4271        bool success;
4272
4273        /* swapping inhibited */
4274        if (!(sc->gfp_mask & __GFP_IO) &&
4275            (folio_test_dirty(folio) ||
4276             (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4277                return false;
4278
4279        /* raced with release_pages() */
4280        if (!folio_try_get(folio))
4281                return false;
4282
4283        /* raced with another isolation */
4284        if (!folio_test_clear_lru(folio)) {
4285                folio_put(folio);
4286                return false;
4287        }
4288
4289        /* see the comment on MAX_NR_TIERS */
4290        if (!folio_test_referenced(folio))
4291                set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4292
4293        /* for shrink_folio_list() */
4294        folio_clear_reclaim(folio);
4295        folio_clear_referenced(folio);
4296
4297        success = lru_gen_del_folio(lruvec, folio, true);
4298        VM_WARN_ON_ONCE_FOLIO(!success, folio);
4299
4300        return true;
4301}
4302
4303static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4304                       int type, int tier, struct list_head *list)
4305{
4306        int i;
4307        int gen;
4308        enum vm_event_item item;
4309        int sorted = 0;
4310        int scanned = 0;
4311        int isolated = 0;
4312        int skipped = 0;
4313        int remaining = MAX_LRU_BATCH;
4314        struct lru_gen_folio *lrugen = &lruvec->lrugen;
4315        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4316
4317        VM_WARN_ON_ONCE(!list_empty(list));
4318
4319        if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4320                return 0;
4321
4322        gen = lru_gen_from_seq(lrugen->min_seq[type]);
4323
4324        for (i = MAX_NR_ZONES; i > 0; i--) {
4325                LIST_HEAD(moved);
4326                int skipped_zone = 0;
4327                int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
4328                struct list_head *head = &lrugen->folios[gen][type][zone];
4329
4330                while (!list_empty(head)) {
4331                        struct folio *folio = lru_to_folio(head);
4332                        int delta = folio_nr_pages(folio);
4333
4334                        VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4335                        VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4336                        VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4337                        VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4338
4339                        scanned += delta;
4340
4341                        if (sort_folio(lruvec, folio, sc, tier))
4342                                sorted += delta;
4343                        else if (isolate_folio(lruvec, folio, sc)) {
4344                                list_add(&folio->lru, list);
4345                                isolated += delta;
4346                        } else {
4347                                list_move(&folio->lru, &moved);
4348                                skipped_zone += delta;
4349                        }
4350
4351                        if (!--remaining || max(isolated, skipped_zone) >= MIN_LRU_BATCH)
4352                                break;
4353                }
4354
4355                if (skipped_zone) {
4356                        list_splice(&moved, head);
4357                        __count_zid_vm_events(PGSCAN_SKIP, zone, skipped_zone);
4358                        skipped += skipped_zone;
4359                }
4360
4361                if (!remaining || isolated >= MIN_LRU_BATCH)
4362                        break;
4363        }
4364
4365        item = PGSCAN_KSWAPD + reclaimer_offset();
4366        if (!cgroup_reclaim(sc)) {
4367                __count_vm_events(item, isolated);
4368                __count_vm_events(PGREFILL, sorted);
4369        }
4370        __count_memcg_events(memcg, item, isolated);
4371        __count_memcg_events(memcg, PGREFILL, sorted);
4372        __count_vm_events(PGSCAN_ANON + type, isolated);
4373        trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, MAX_LRU_BATCH,
4374                                scanned, skipped, isolated,
4375                                type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
4376
4377        /*
4378         * There might not be eligible folios due to reclaim_idx. Check the
4379         * remaining to prevent livelock if it's not making progress.
4380         */
4381        return isolated || !remaining ? scanned : 0;
4382}
4383
4384static int get_tier_idx(struct lruvec *lruvec, int type)
4385{
4386        int tier;
4387        struct ctrl_pos sp, pv;
4388
4389        /*
4390         * To leave a margin for fluctuations, use a larger gain factor (1:2).
4391         * This value is chosen because any other tier would have at least twice
4392         * as many refaults as the first tier.
4393         */
4394        read_ctrl_pos(lruvec, type, 0, 1, &sp);
4395        for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4396                read_ctrl_pos(lruvec, type, tier, 2, &pv);
4397                if (!positive_ctrl_err(&sp, &pv))
4398                        break;
4399        }
4400
4401        return tier - 1;
4402}
4403
4404static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4405{
4406        int type, tier;
4407        struct ctrl_pos sp, pv;
4408        int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4409
4410        /*
4411         * Compare the first tier of anon with that of file to determine which
4412         * type to scan. Also need to compare other tiers of the selected type
4413         * with the first tier of the other type to determine the last tier (of
4414         * the selected type) to evict.
4415         */
4416        read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4417        read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4418        type = positive_ctrl_err(&sp, &pv);
4419
4420        read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4421        for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4422                read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4423                if (!positive_ctrl_err(&sp, &pv))
4424                        break;
4425        }
4426
4427        *tier_idx = tier - 1;
4428
4429        return type;
4430}
4431
4432static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4433                          int *type_scanned, struct list_head *list)
4434{
4435        int i;
4436        int type;
4437        int scanned;
4438        int tier = -1;
4439        DEFINE_MIN_SEQ(lruvec);
4440
4441        /*
4442         * Try to make the obvious choice first. When anon and file are both
4443         * available from the same generation, interpret swappiness 1 as file
4444         * first and 200 as anon first.
4445         */
4446        if (!swappiness)
4447                type = LRU_GEN_FILE;
4448        else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4449                type = LRU_GEN_ANON;
4450        else if (swappiness == 1)
4451                type = LRU_GEN_FILE;
4452        else if (swappiness == 200)
4453                type = LRU_GEN_ANON;
4454        else
4455                type = get_type_to_scan(lruvec, swappiness, &tier);
4456
4457        for (i = !swappiness; i < ANON_AND_FILE; i++) {
4458                if (tier < 0)
4459                        tier = get_tier_idx(lruvec, type);
4460
4461                scanned = scan_folios(lruvec, sc, type, tier, list);
4462                if (scanned)
4463                        break;
4464
4465                type = !type;
4466                tier = -1;
4467        }
4468
4469        *type_scanned = type;
4470
4471        return scanned;
4472}
4473
4474static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
4475{
4476        int type;
4477        int scanned;
4478        int reclaimed;
4479        LIST_HEAD(list);
4480        LIST_HEAD(clean);
4481        struct folio *folio;
4482        struct folio *next;
4483        enum vm_event_item item;
4484        struct reclaim_stat stat;
4485        struct lru_gen_mm_walk *walk;
4486        bool skip_retry = false;
4487        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4488        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4489
4490        spin_lock_irq(&lruvec->lru_lock);
4491
4492        scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
4493
4494        scanned += try_to_inc_min_seq(lruvec, swappiness);
4495
4496        if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4497                scanned = 0;
4498
4499        spin_unlock_irq(&lruvec->lru_lock);
4500
4501        if (list_empty(&list))
4502                return scanned;
4503retry:
4504        reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
4505        sc->nr_reclaimed += reclaimed;
4506        trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
4507                        scanned, reclaimed, &stat, sc->priority,
4508                        type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
4509
4510        list_for_each_entry_safe_reverse(folio, next, &list, lru) {
4511                if (!folio_evictable(folio)) {
4512                        list_del(&folio->lru);
4513                        folio_putback_lru(folio);
4514                        continue;
4515                }
4516
4517                if (folio_test_reclaim(folio) &&
4518                    (folio_test_dirty(folio) || folio_test_writeback(folio))) {
4519                        /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
4520                        if (folio_test_workingset(folio))
4521                                folio_set_referenced(folio);
4522                        continue;
4523                }
4524
4525                if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
4526                    folio_mapped(folio) || folio_test_locked(folio) ||
4527                    folio_test_dirty(folio) || folio_test_writeback(folio)) {
4528                        /* don't add rejected folios to the oldest generation */
4529                        set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4530                                      BIT(PG_active));
4531                        continue;
4532                }
4533
4534                /* retry folios that may have missed folio_rotate_reclaimable() */
4535                list_move(&folio->lru, &clean);
4536                sc->nr_scanned -= folio_nr_pages(folio);
4537        }
4538
4539        spin_lock_irq(&lruvec->lru_lock);
4540
4541        move_folios_to_lru(lruvec, &list);
4542
4543        walk = current->reclaim_state->mm_walk;
4544        if (walk && walk->batched)
4545                reset_batch_size(lruvec, walk);
4546
4547        item = PGSTEAL_KSWAPD + reclaimer_offset();
4548        if (!cgroup_reclaim(sc))
4549                __count_vm_events(item, reclaimed);
4550        __count_memcg_events(memcg, item, reclaimed);
4551        __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4552
4553        spin_unlock_irq(&lruvec->lru_lock);
4554
4555        mem_cgroup_uncharge_list(&list);
4556        free_unref_page_list(&list);
4557
4558        INIT_LIST_HEAD(&list);
4559        list_splice_init(&clean, &list);
4560
4561        if (!list_empty(&list)) {
4562                skip_retry = true;
4563                goto retry;
4564        }
4565
4566        return scanned;
4567}
4568
4569static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4570                             struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4571{
4572        int gen, type, zone;
4573        unsigned long old = 0;
4574        unsigned long young = 0;
4575        unsigned long total = 0;
4576        struct lru_gen_folio *lrugen = &lruvec->lrugen;
4577        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4578        DEFINE_MIN_SEQ(lruvec);
4579
4580        /* whether this lruvec is completely out of cold folios */
4581        if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4582                *nr_to_scan = 0;
4583                return true;
4584        }
4585
4586        for (type = !can_swap; type < ANON_AND_FILE; type++) {
4587                unsigned long seq;
4588
4589                for (seq = min_seq[type]; seq <= max_seq; seq++) {
4590                        unsigned long size = 0;
4591
4592                        gen = lru_gen_from_seq(seq);
4593
4594                        for (zone = 0; zone < MAX_NR_ZONES; zone++)
4595                                size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4596
4597                        total += size;
4598                        if (seq == max_seq)
4599                                young += size;
4600                        else if (seq + MIN_NR_GENS == max_seq)
4601                                old += size;
4602                }
4603        }
4604
4605        /* try to scrape all its memory if this memcg was deleted */
4606        if (!mem_cgroup_online(memcg)) {
4607                *nr_to_scan = total;
4608                return false;
4609        }
4610
4611        *nr_to_scan = total >> sc->priority;
4612
4613        /*
4614         * The aging tries to be lazy to reduce the overhead, while the eviction
4615         * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4616         * ideal number of generations is MIN_NR_GENS+1.
4617         */
4618        if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4619                return false;
4620
4621        /*
4622         * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4623         * of the total number of pages for each generation. A reasonable range
4624         * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4625         * aging cares about the upper bound of hot pages, while the eviction
4626         * cares about the lower bound of cold pages.
4627         */
4628        if (young * MIN_NR_GENS > total)
4629                return true;
4630        if (old * (MIN_NR_GENS + 2) < total)
4631                return true;
4632
4633        return false;
4634}
4635
4636/*
4637 * For future optimizations:
4638 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4639 *    reclaim.
4640 */
4641static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4642{