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 try_to_release_page(),
  30                                        buffer_heads_over_limit */
  31#include <linux/mm_inline.h>
  32#include <linux/backing-dev.h>
  33#include <linux/rmap.h>
  34#include <linux/topology.h>
  35#include <linux/cpu.h>
  36#include <linux/cpuset.h>
  37#include <linux/compaction.h>
  38#include <linux/notifier.h>
  39#include <linux/rwsem.h>
  40#include <linux/delay.h>
  41#include <linux/kthread.h>
  42#include <linux/freezer.h>
  43#include <linux/memcontrol.h>
  44#include <linux/delayacct.h>
  45#include <linux/sysctl.h>
  46#include <linux/oom.h>
  47#include <linux/pagevec.h>
  48#include <linux/prefetch.h>
  49#include <linux/printk.h>
  50#include <linux/dax.h>
  51#include <linux/psi.h>
  52
  53#include <asm/tlbflush.h>
  54#include <asm/div64.h>
  55
  56#include <linux/swapops.h>
  57#include <linux/balloon_compaction.h>
  58
  59#include "internal.h"
  60
  61#define CREATE_TRACE_POINTS
  62#include <trace/events/vmscan.h>
  63
  64struct scan_control {
  65        /* How many pages shrink_list() should reclaim */
  66        unsigned long nr_to_reclaim;
  67
  68        /*
  69         * Nodemask of nodes allowed by the caller. If NULL, all nodes
  70         * are scanned.
  71         */
  72        nodemask_t      *nodemask;
  73
  74        /*
  75         * The memory cgroup that hit its limit and as a result is the
  76         * primary target of this reclaim invocation.
  77         */
  78        struct mem_cgroup *target_mem_cgroup;
  79
  80        /*
  81         * Scan pressure balancing between anon and file LRUs
  82         */
  83        unsigned long   anon_cost;
  84        unsigned long   file_cost;
  85
  86        /* Can active pages be deactivated as part of reclaim? */
  87#define DEACTIVATE_ANON 1
  88#define DEACTIVATE_FILE 2
  89        unsigned int may_deactivate:2;
  90        unsigned int force_deactivate:1;
  91        unsigned int skipped_deactivate:1;
  92
  93        /* Writepage batching in laptop mode; RECLAIM_WRITE */
  94        unsigned int may_writepage:1;
  95
  96        /* Can mapped pages be reclaimed? */
  97        unsigned int may_unmap:1;
  98
  99        /* Can pages be swapped as part of reclaim? */
 100        unsigned int may_swap:1;
 101
 102        /*
 103         * Cgroup memory below memory.low is protected as long as we
 104         * don't threaten to OOM. If any cgroup is reclaimed at
 105         * reduced force or passed over entirely due to its memory.low
 106         * setting (memcg_low_skipped), and nothing is reclaimed as a
 107         * result, then go back for one more cycle that reclaims the protected
 108         * memory (memcg_low_reclaim) to avert OOM.
 109         */
 110        unsigned int memcg_low_reclaim:1;
 111        unsigned int memcg_low_skipped:1;
 112
 113        unsigned int hibernation_mode:1;
 114
 115        /* One of the zones is ready for compaction */
 116        unsigned int compaction_ready:1;
 117
 118        /* There is easily reclaimable cold cache in the current node */
 119        unsigned int cache_trim_mode:1;
 120
 121        /* The file pages on the current node are dangerously low */
 122        unsigned int file_is_tiny:1;
 123
 124        /* Allocation order */
 125        s8 order;
 126
 127        /* Scan (total_size >> priority) pages at once */
 128        s8 priority;
 129
 130        /* The highest zone to isolate pages for reclaim from */
 131        s8 reclaim_idx;
 132
 133        /* This context's GFP mask */
 134        gfp_t gfp_mask;
 135
 136        /* Incremented by the number of inactive pages that were scanned */
 137        unsigned long nr_scanned;
 138
 139        /* Number of pages freed so far during a call to shrink_zones() */
 140        unsigned long nr_reclaimed;
 141
 142        struct {
 143                unsigned int dirty;
 144                unsigned int unqueued_dirty;
 145                unsigned int congested;
 146                unsigned int writeback;
 147                unsigned int immediate;
 148                unsigned int file_taken;
 149                unsigned int taken;
 150        } nr;
 151
 152        /* for recording the reclaimed slab by now */
 153        struct reclaim_state reclaim_state;
 154};
 155
 156#ifdef ARCH_HAS_PREFETCHW
 157#define prefetchw_prev_lru_page(_page, _base, _field)                   \
 158        do {                                                            \
 159                if ((_page)->lru.prev != _base) {                       \
 160                        struct page *prev;                              \
 161                                                                        \
 162                        prev = lru_to_page(&(_page->lru));              \
 163                        prefetchw(&prev->_field);                       \
 164                }                                                       \
 165        } while (0)
 166#else
 167#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
 168#endif
 169
 170/*
 171 * From 0 .. 200.  Higher means more swappy.
 172 */
 173int vm_swappiness = 60;
 174
 175static void set_task_reclaim_state(struct task_struct *task,
 176                                   struct reclaim_state *rs)
 177{
 178        /* Check for an overwrite */
 179        WARN_ON_ONCE(rs && task->reclaim_state);
 180
 181        /* Check for the nulling of an already-nulled member */
 182        WARN_ON_ONCE(!rs && !task->reclaim_state);
 183
 184        task->reclaim_state = rs;
 185}
 186
 187static LIST_HEAD(shrinker_list);
 188static DECLARE_RWSEM(shrinker_rwsem);
 189
 190#ifdef CONFIG_MEMCG
 191static int shrinker_nr_max;
 192
 193/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
 194static inline int shrinker_map_size(int nr_items)
 195{
 196        return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
 197}
 198
 199static inline int shrinker_defer_size(int nr_items)
 200{
 201        return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
 202}
 203
 204static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
 205                                                     int nid)
 206{
 207        return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
 208                                         lockdep_is_held(&shrinker_rwsem));
 209}
 210
 211static int expand_one_shrinker_info(struct mem_cgroup *memcg,
 212                                    int map_size, int defer_size,
 213                                    int old_map_size, int old_defer_size)
 214{
 215        struct shrinker_info *new, *old;
 216        struct mem_cgroup_per_node *pn;
 217        int nid;
 218        int size = map_size + defer_size;
 219
 220        for_each_node(nid) {
 221                pn = memcg->nodeinfo[nid];
 222                old = shrinker_info_protected(memcg, nid);
 223                /* Not yet online memcg */
 224                if (!old)
 225                        return 0;
 226
 227                new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
 228                if (!new)
 229                        return -ENOMEM;
 230
 231                new->nr_deferred = (atomic_long_t *)(new + 1);
 232                new->map = (void *)new->nr_deferred + defer_size;
 233
 234                /* map: set all old bits, clear all new bits */
 235                memset(new->map, (int)0xff, old_map_size);
 236                memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
 237                /* nr_deferred: copy old values, clear all new values */
 238                memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
 239                memset((void *)new->nr_deferred + old_defer_size, 0,
 240                       defer_size - old_defer_size);
 241
 242                rcu_assign_pointer(pn->shrinker_info, new);
 243                kvfree_rcu(old, rcu);
 244        }
 245
 246        return 0;
 247}
 248
 249void free_shrinker_info(struct mem_cgroup *memcg)
 250{
 251        struct mem_cgroup_per_node *pn;
 252        struct shrinker_info *info;
 253        int nid;
 254
 255        for_each_node(nid) {
 256                pn = memcg->nodeinfo[nid];
 257                info = rcu_dereference_protected(pn->shrinker_info, true);
 258                kvfree(info);
 259                rcu_assign_pointer(pn->shrinker_info, NULL);
 260        }
 261}
 262
 263int alloc_shrinker_info(struct mem_cgroup *memcg)
 264{
 265        struct shrinker_info *info;
 266        int nid, size, ret = 0;
 267        int map_size, defer_size = 0;
 268
 269        down_write(&shrinker_rwsem);
 270        map_size = shrinker_map_size(shrinker_nr_max);
 271        defer_size = shrinker_defer_size(shrinker_nr_max);
 272        size = map_size + defer_size;
 273        for_each_node(nid) {
 274                info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
 275                if (!info) {
 276                        free_shrinker_info(memcg);
 277                        ret = -ENOMEM;
 278                        break;
 279                }
 280                info->nr_deferred = (atomic_long_t *)(info + 1);
 281                info->map = (void *)info->nr_deferred + defer_size;
 282                rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
 283        }
 284        up_write(&shrinker_rwsem);
 285
 286        return ret;
 287}
 288
 289static inline bool need_expand(int nr_max)
 290{
 291        return round_up(nr_max, BITS_PER_LONG) >
 292               round_up(shrinker_nr_max, BITS_PER_LONG);
 293}
 294
 295static int expand_shrinker_info(int new_id)
 296{
 297        int ret = 0;
 298        int new_nr_max = new_id + 1;
 299        int map_size, defer_size = 0;
 300        int old_map_size, old_defer_size = 0;
 301        struct mem_cgroup *memcg;
 302
 303        if (!need_expand(new_nr_max))
 304                goto out;
 305
 306        if (!root_mem_cgroup)
 307                goto out;
 308
 309        lockdep_assert_held(&shrinker_rwsem);
 310
 311        map_size = shrinker_map_size(new_nr_max);
 312        defer_size = shrinker_defer_size(new_nr_max);
 313        old_map_size = shrinker_map_size(shrinker_nr_max);
 314        old_defer_size = shrinker_defer_size(shrinker_nr_max);
 315
 316        memcg = mem_cgroup_iter(NULL, NULL, NULL);
 317        do {
 318                ret = expand_one_shrinker_info(memcg, map_size, defer_size,
 319                                               old_map_size, old_defer_size);
 320                if (ret) {
 321                        mem_cgroup_iter_break(NULL, memcg);
 322                        goto out;
 323                }
 324        } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
 325out:
 326        if (!ret)
 327                shrinker_nr_max = new_nr_max;
 328
 329        return ret;
 330}
 331
 332void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
 333{
 334        if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
 335                struct shrinker_info *info;
 336
 337                rcu_read_lock();
 338                info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
 339                /* Pairs with smp mb in shrink_slab() */
 340                smp_mb__before_atomic();
 341                set_bit(shrinker_id, info->map);
 342                rcu_read_unlock();
 343        }
 344}
 345
 346static DEFINE_IDR(shrinker_idr);
 347
 348static int prealloc_memcg_shrinker(struct shrinker *shrinker)
 349{
 350        int id, ret = -ENOMEM;
 351
 352        if (mem_cgroup_disabled())
 353                return -ENOSYS;
 354
 355        down_write(&shrinker_rwsem);
 356        /* This may call shrinker, so it must use down_read_trylock() */
 357        id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
 358        if (id < 0)
 359                goto unlock;
 360
 361        if (id >= shrinker_nr_max) {
 362                if (expand_shrinker_info(id)) {
 363                        idr_remove(&shrinker_idr, id);
 364                        goto unlock;
 365                }
 366        }
 367        shrinker->id = id;
 368        ret = 0;
 369unlock:
 370        up_write(&shrinker_rwsem);
 371        return ret;
 372}
 373
 374static void unregister_memcg_shrinker(struct shrinker *shrinker)
 375{
 376        int id = shrinker->id;
 377
 378        BUG_ON(id < 0);
 379
 380        lockdep_assert_held(&shrinker_rwsem);
 381
 382        idr_remove(&shrinker_idr, id);
 383}
 384
 385static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
 386                                   struct mem_cgroup *memcg)
 387{
 388        struct shrinker_info *info;
 389
 390        info = shrinker_info_protected(memcg, nid);
 391        return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
 392}
 393
 394static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
 395                                  struct mem_cgroup *memcg)
 396{
 397        struct shrinker_info *info;
 398
 399        info = shrinker_info_protected(memcg, nid);
 400        return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
 401}
 402
 403void reparent_shrinker_deferred(struct mem_cgroup *memcg)
 404{
 405        int i, nid;
 406        long nr;
 407        struct mem_cgroup *parent;
 408        struct shrinker_info *child_info, *parent_info;
 409
 410        parent = parent_mem_cgroup(memcg);
 411        if (!parent)
 412                parent = root_mem_cgroup;
 413
 414        /* Prevent from concurrent shrinker_info expand */
 415        down_read(&shrinker_rwsem);
 416        for_each_node(nid) {
 417                child_info = shrinker_info_protected(memcg, nid);
 418                parent_info = shrinker_info_protected(parent, nid);
 419                for (i = 0; i < shrinker_nr_max; i++) {
 420                        nr = atomic_long_read(&child_info->nr_deferred[i]);
 421                        atomic_long_add(nr, &parent_info->nr_deferred[i]);
 422                }
 423        }
 424        up_read(&shrinker_rwsem);
 425}
 426
 427static bool cgroup_reclaim(struct scan_control *sc)
 428{
 429        return sc->target_mem_cgroup;
 430}
 431
 432/**
 433 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
 434 * @sc: scan_control in question
 435 *
 436 * The normal page dirty throttling mechanism in balance_dirty_pages() is
 437 * completely broken with the legacy memcg and direct stalling in
 438 * shrink_page_list() is used for throttling instead, which lacks all the
 439 * niceties such as fairness, adaptive pausing, bandwidth proportional
 440 * allocation and configurability.
 441 *
 442 * This function tests whether the vmscan currently in progress can assume
 443 * that the normal dirty throttling mechanism is operational.
 444 */
 445static bool writeback_throttling_sane(struct scan_control *sc)
 446{
 447        if (!cgroup_reclaim(sc))
 448                return true;
 449#ifdef CONFIG_CGROUP_WRITEBACK
 450        if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
 451                return true;
 452#endif
 453        return false;
 454}
 455#else
 456static int prealloc_memcg_shrinker(struct shrinker *shrinker)
 457{
 458        return -ENOSYS;
 459}
 460
 461static void unregister_memcg_shrinker(struct shrinker *shrinker)
 462{
 463}
 464
 465static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
 466                                   struct mem_cgroup *memcg)
 467{
 468        return 0;
 469}
 470
 471static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
 472                                  struct mem_cgroup *memcg)
 473{
 474        return 0;
 475}
 476
 477static bool cgroup_reclaim(struct scan_control *sc)
 478{
 479        return false;
 480}
 481
 482static bool writeback_throttling_sane(struct scan_control *sc)
 483{
 484        return true;
 485}
 486#endif
 487
 488static long xchg_nr_deferred(struct shrinker *shrinker,
 489                             struct shrink_control *sc)
 490{
 491        int nid = sc->nid;
 492
 493        if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
 494                nid = 0;
 495
 496        if (sc->memcg &&
 497            (shrinker->flags & SHRINKER_MEMCG_AWARE))
 498                return xchg_nr_deferred_memcg(nid, shrinker,
 499                                              sc->memcg);
 500
 501        return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
 502}
 503
 504
 505static long add_nr_deferred(long nr, struct shrinker *shrinker,
 506                            struct shrink_control *sc)
 507{
 508        int nid = sc->nid;
 509
 510        if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
 511                nid = 0;
 512
 513        if (sc->memcg &&
 514            (shrinker->flags & SHRINKER_MEMCG_AWARE))
 515                return add_nr_deferred_memcg(nr, nid, shrinker,
 516                                             sc->memcg);
 517
 518        return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
 519}
 520
 521/*
 522 * This misses isolated pages which are not accounted for to save counters.
 523 * As the data only determines if reclaim or compaction continues, it is
 524 * not expected that isolated pages will be a dominating factor.
 525 */
 526unsigned long zone_reclaimable_pages(struct zone *zone)
 527{
 528        unsigned long nr;
 529
 530        nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
 531                zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
 532        if (get_nr_swap_pages() > 0)
 533                nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
 534                        zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
 535
 536        return nr;
 537}
 538
 539/**
 540 * lruvec_lru_size -  Returns the number of pages on the given LRU list.
 541 * @lruvec: lru vector
 542 * @lru: lru to use
 543 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
 544 */
 545static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
 546                                     int zone_idx)
 547{
 548        unsigned long size = 0;
 549        int zid;
 550
 551        for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
 552                struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
 553
 554                if (!managed_zone(zone))
 555                        continue;
 556
 557                if (!mem_cgroup_disabled())
 558                        size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
 559                else
 560                        size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
 561        }
 562        return size;
 563}
 564
 565/*
 566 * Add a shrinker callback to be called from the vm.
 567 */
 568int prealloc_shrinker(struct shrinker *shrinker)
 569{
 570        unsigned int size;
 571        int err;
 572
 573        if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
 574                err = prealloc_memcg_shrinker(shrinker);
 575                if (err != -ENOSYS)
 576                        return err;
 577
 578                shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
 579        }
 580
 581        size = sizeof(*shrinker->nr_deferred);
 582        if (shrinker->flags & SHRINKER_NUMA_AWARE)
 583                size *= nr_node_ids;
 584
 585        shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
 586        if (!shrinker->nr_deferred)
 587                return -ENOMEM;
 588
 589        return 0;
 590}
 591
 592void free_prealloced_shrinker(struct shrinker *shrinker)
 593{
 594        if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
 595                down_write(&shrinker_rwsem);
 596                unregister_memcg_shrinker(shrinker);
 597                up_write(&shrinker_rwsem);
 598                return;
 599        }
 600
 601        kfree(shrinker->nr_deferred);
 602        shrinker->nr_deferred = NULL;
 603}
 604
 605void register_shrinker_prepared(struct shrinker *shrinker)
 606{
 607        down_write(&shrinker_rwsem);
 608        list_add_tail(&shrinker->list, &shrinker_list);
 609        shrinker->flags |= SHRINKER_REGISTERED;
 610        up_write(&shrinker_rwsem);
 611}
 612
 613int register_shrinker(struct shrinker *shrinker)
 614{
 615        int err = prealloc_shrinker(shrinker);
 616
 617        if (err)
 618                return err;
 619        register_shrinker_prepared(shrinker);
 620        return 0;
 621}
 622EXPORT_SYMBOL(register_shrinker);
 623
 624/*
 625 * Remove one
 626 */
 627void unregister_shrinker(struct shrinker *shrinker)
 628{
 629        if (!(shrinker->flags & SHRINKER_REGISTERED))
 630                return;
 631
 632        down_write(&shrinker_rwsem);
 633        list_del(&shrinker->list);
 634        shrinker->flags &= ~SHRINKER_REGISTERED;
 635        if (shrinker->flags & SHRINKER_MEMCG_AWARE)
 636                unregister_memcg_shrinker(shrinker);
 637        up_write(&shrinker_rwsem);
 638
 639        kfree(shrinker->nr_deferred);
 640        shrinker->nr_deferred = NULL;
 641}
 642EXPORT_SYMBOL(unregister_shrinker);
 643
 644#define SHRINK_BATCH 128
 645
 646static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
 647                                    struct shrinker *shrinker, int priority)
 648{
 649        unsigned long freed = 0;
 650        unsigned long long delta;
 651        long total_scan;
 652        long freeable;
 653        long nr;
 654        long new_nr;
 655        long batch_size = shrinker->batch ? shrinker->batch
 656                                          : SHRINK_BATCH;
 657        long scanned = 0, next_deferred;
 658
 659        freeable = shrinker->count_objects(shrinker, shrinkctl);
 660        if (freeable == 0 || freeable == SHRINK_EMPTY)
 661                return freeable;
 662
 663        /*
 664         * copy the current shrinker scan count into a local variable
 665         * and zero it so that other concurrent shrinker invocations
 666         * don't also do this scanning work.
 667         */
 668        nr = xchg_nr_deferred(shrinker, shrinkctl);
 669
 670        if (shrinker->seeks) {
 671                delta = freeable >> priority;
 672                delta *= 4;
 673                do_div(delta, shrinker->seeks);
 674        } else {
 675                /*
 676                 * These objects don't require any IO to create. Trim
 677                 * them aggressively under memory pressure to keep
 678                 * them from causing refetches in the IO caches.
 679                 */
 680                delta = freeable / 2;
 681        }
 682
 683        total_scan = nr >> priority;
 684        total_scan += delta;
 685        total_scan = min(total_scan, (2 * freeable));
 686
 687        trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
 688                                   freeable, delta, total_scan, priority);
 689
 690        /*
 691         * Normally, we should not scan less than batch_size objects in one
 692         * pass to avoid too frequent shrinker calls, but if the slab has less
 693         * than batch_size objects in total and we are really tight on memory,
 694         * we will try to reclaim all available objects, otherwise we can end
 695         * up failing allocations although there are plenty of reclaimable
 696         * objects spread over several slabs with usage less than the
 697         * batch_size.
 698         *
 699         * We detect the "tight on memory" situations by looking at the total
 700         * number of objects we want to scan (total_scan). If it is greater
 701         * than the total number of objects on slab (freeable), we must be
 702         * scanning at high prio and therefore should try to reclaim as much as
 703         * possible.
 704         */
 705        while (total_scan >= batch_size ||
 706               total_scan >= freeable) {
 707                unsigned long ret;
 708                unsigned long nr_to_scan = min(batch_size, total_scan);
 709
 710                shrinkctl->nr_to_scan = nr_to_scan;
 711                shrinkctl->nr_scanned = nr_to_scan;
 712                ret = shrinker->scan_objects(shrinker, shrinkctl);
 713                if (ret == SHRINK_STOP)
 714                        break;
 715                freed += ret;
 716
 717                count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
 718                total_scan -= shrinkctl->nr_scanned;
 719                scanned += shrinkctl->nr_scanned;
 720
 721                cond_resched();
 722        }
 723
 724        /*
 725         * The deferred work is increased by any new work (delta) that wasn't
 726         * done, decreased by old deferred work that was done now.
 727         *
 728         * And it is capped to two times of the freeable items.
 729         */
 730        next_deferred = max_t(long, (nr + delta - scanned), 0);
 731        next_deferred = min(next_deferred, (2 * freeable));
 732
 733        /*
 734         * move the unused scan count back into the shrinker in a
 735         * manner that handles concurrent updates.
 736         */
 737        new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
 738
 739        trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
 740        return freed;
 741}
 742
 743#ifdef CONFIG_MEMCG
 744static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
 745                        struct mem_cgroup *memcg, int priority)
 746{
 747        struct shrinker_info *info;
 748        unsigned long ret, freed = 0;
 749        int i;
 750
 751        if (!mem_cgroup_online(memcg))
 752                return 0;
 753
 754        if (!down_read_trylock(&shrinker_rwsem))
 755                return 0;
 756
 757        info = shrinker_info_protected(memcg, nid);
 758        if (unlikely(!info))
 759                goto unlock;
 760
 761        for_each_set_bit(i, info->map, shrinker_nr_max) {
 762                struct shrink_control sc = {
 763                        .gfp_mask = gfp_mask,
 764                        .nid = nid,
 765                        .memcg = memcg,
 766                };
 767                struct shrinker *shrinker;
 768
 769                shrinker = idr_find(&shrinker_idr, i);
 770                if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
 771                        if (!shrinker)
 772                                clear_bit(i, info->map);
 773                        continue;
 774                }
 775
 776                /* Call non-slab shrinkers even though kmem is disabled */
 777                if (!memcg_kmem_enabled() &&
 778                    !(shrinker->flags & SHRINKER_NONSLAB))
 779                        continue;
 780
 781                ret = do_shrink_slab(&sc, shrinker, priority);
 782                if (ret == SHRINK_EMPTY) {
 783                        clear_bit(i, info->map);
 784                        /*
 785                         * After the shrinker reported that it had no objects to
 786                         * free, but before we cleared the corresponding bit in
 787                         * the memcg shrinker map, a new object might have been
 788                         * added. To make sure, we have the bit set in this
 789                         * case, we invoke the shrinker one more time and reset
 790                         * the bit if it reports that it is not empty anymore.
 791                         * The memory barrier here pairs with the barrier in
 792                         * set_shrinker_bit():
 793                         *
 794                         * list_lru_add()     shrink_slab_memcg()
 795                         *   list_add_tail()    clear_bit()
 796                         *   <MB>               <MB>
 797                         *   set_bit()          do_shrink_slab()
 798                         */
 799                        smp_mb__after_atomic();
 800                        ret = do_shrink_slab(&sc, shrinker, priority);
 801                        if (ret == SHRINK_EMPTY)
 802                                ret = 0;
 803                        else
 804                                set_shrinker_bit(memcg, nid, i);
 805                }
 806                freed += ret;
 807
 808                if (rwsem_is_contended(&shrinker_rwsem)) {
 809                        freed = freed ? : 1;
 810                        break;
 811                }
 812        }
 813unlock:
 814        up_read(&shrinker_rwsem);
 815        return freed;
 816}
 817#else /* CONFIG_MEMCG */
 818static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
 819                        struct mem_cgroup *memcg, int priority)
 820{
 821        return 0;
 822}
 823#endif /* CONFIG_MEMCG */
 824
 825/**
 826 * shrink_slab - shrink slab caches
 827 * @gfp_mask: allocation context
 828 * @nid: node whose slab caches to target
 829 * @memcg: memory cgroup whose slab caches to target
 830 * @priority: the reclaim priority
 831 *
 832 * Call the shrink functions to age shrinkable caches.
 833 *
 834 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
 835 * unaware shrinkers will receive a node id of 0 instead.
 836 *
 837 * @memcg specifies the memory cgroup to target. Unaware shrinkers
 838 * are called only if it is the root cgroup.
 839 *
 840 * @priority is sc->priority, we take the number of objects and >> by priority
 841 * in order to get the scan target.
 842 *
 843 * Returns the number of reclaimed slab objects.
 844 */
 845static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
 846                                 struct mem_cgroup *memcg,
 847                                 int priority)
 848{
 849        unsigned long ret, freed = 0;
 850        struct shrinker *shrinker;
 851
 852        /*
 853         * The root memcg might be allocated even though memcg is disabled
 854         * via "cgroup_disable=memory" boot parameter.  This could make
 855         * mem_cgroup_is_root() return false, then just run memcg slab
 856         * shrink, but skip global shrink.  This may result in premature
 857         * oom.
 858         */
 859        if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
 860                return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
 861
 862        if (!down_read_trylock(&shrinker_rwsem))
 863                goto out;
 864
 865        list_for_each_entry(shrinker, &shrinker_list, list) {
 866                struct shrink_control sc = {
 867                        .gfp_mask = gfp_mask,
 868                        .nid = nid,
 869                        .memcg = memcg,
 870                };
 871
 872                ret = do_shrink_slab(&sc, shrinker, priority);
 873                if (ret == SHRINK_EMPTY)
 874                        ret = 0;
 875                freed += ret;
 876                /*
 877                 * Bail out if someone want to register a new shrinker to
 878                 * prevent the registration from being stalled for long periods
 879                 * by parallel ongoing shrinking.
 880                 */
 881                if (rwsem_is_contended(&shrinker_rwsem)) {
 882                        freed = freed ? : 1;
 883                        break;
 884                }
 885        }
 886
 887        up_read(&shrinker_rwsem);
 888out:
 889        cond_resched();
 890        return freed;
 891}
 892
 893void drop_slab_node(int nid)
 894{
 895        unsigned long freed;
 896
 897        do {
 898                struct mem_cgroup *memcg = NULL;
 899
 900                if (fatal_signal_pending(current))
 901                        return;
 902
 903                freed = 0;
 904                memcg = mem_cgroup_iter(NULL, NULL, NULL);
 905                do {
 906                        freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
 907                } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
 908        } while (freed > 10);
 909}
 910
 911void drop_slab(void)
 912{
 913        int nid;
 914
 915        for_each_online_node(nid)
 916                drop_slab_node(nid);
 917}
 918
 919static inline int is_page_cache_freeable(struct page *page)
 920{
 921        /*
 922         * A freeable page cache page is referenced only by the caller
 923         * that isolated the page, the page cache and optional buffer
 924         * heads at page->private.
 925         */
 926        int page_cache_pins = thp_nr_pages(page);
 927        return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
 928}
 929
 930static int may_write_to_inode(struct inode *inode)
 931{
 932        if (current->flags & PF_SWAPWRITE)
 933                return 1;
 934        if (!inode_write_congested(inode))
 935                return 1;
 936        if (inode_to_bdi(inode) == current->backing_dev_info)
 937                return 1;
 938        return 0;
 939}
 940
 941/*
 942 * We detected a synchronous write error writing a page out.  Probably
 943 * -ENOSPC.  We need to propagate that into the address_space for a subsequent
 944 * fsync(), msync() or close().
 945 *
 946 * The tricky part is that after writepage we cannot touch the mapping: nothing
 947 * prevents it from being freed up.  But we have a ref on the page and once
 948 * that page is locked, the mapping is pinned.
 949 *
 950 * We're allowed to run sleeping lock_page() here because we know the caller has
 951 * __GFP_FS.
 952 */
 953static void handle_write_error(struct address_space *mapping,
 954                                struct page *page, int error)
 955{
 956        lock_page(page);
 957        if (page_mapping(page) == mapping)
 958                mapping_set_error(mapping, error);
 959        unlock_page(page);
 960}
 961
 962/* possible outcome of pageout() */
 963typedef enum {
 964        /* failed to write page out, page is locked */
 965        PAGE_KEEP,
 966        /* move page to the active list, page is locked */
 967        PAGE_ACTIVATE,
 968        /* page has been sent to the disk successfully, page is unlocked */
 969        PAGE_SUCCESS,
 970        /* page is clean and locked */
 971        PAGE_CLEAN,
 972} pageout_t;
 973
 974/*
 975 * pageout is called by shrink_page_list() for each dirty page.
 976 * Calls ->writepage().
 977 */
 978static pageout_t pageout(struct page *page, struct address_space *mapping)
 979{
 980        /*
 981         * If the page is dirty, only perform writeback if that write
 982         * will be non-blocking.  To prevent this allocation from being
 983         * stalled by pagecache activity.  But note that there may be
 984         * stalls if we need to run get_block().  We could test
 985         * PagePrivate for that.
 986         *
 987         * If this process is currently in __generic_file_write_iter() against
 988         * this page's queue, we can perform writeback even if that
 989         * will block.
 990         *
 991         * If the page is swapcache, write it back even if that would
 992         * block, for some throttling. This happens by accident, because
 993         * swap_backing_dev_info is bust: it doesn't reflect the
 994         * congestion state of the swapdevs.  Easy to fix, if needed.
 995         */
 996        if (!is_page_cache_freeable(page))
 997                return PAGE_KEEP;
 998        if (!mapping) {
 999                /*
1000                 * Some data journaling orphaned pages can have
1001                 * page->mapping == NULL while being dirty with clean buffers.
1002                 */
1003                if (page_has_private(page)) {
1004                        if (try_to_free_buffers(page)) {
1005                                ClearPageDirty(page);
1006                                pr_info("%s: orphaned page\n", __func__);
1007                                return PAGE_CLEAN;
1008                        }
1009                }
1010                return PAGE_KEEP;
1011        }
1012        if (mapping->a_ops->writepage == NULL)
1013                return PAGE_ACTIVATE;
1014        if (!may_write_to_inode(mapping->host))
1015                return PAGE_KEEP;
1016
1017        if (clear_page_dirty_for_io(page)) {
1018                int res;
1019                struct writeback_control wbc = {
1020                        .sync_mode = WB_SYNC_NONE,
1021                        .nr_to_write = SWAP_CLUSTER_MAX,
1022                        .range_start = 0,
1023                        .range_end = LLONG_MAX,
1024                        .for_reclaim = 1,
1025                };
1026
1027                SetPageReclaim(page);
1028                res = mapping->a_ops->writepage(page, &wbc);
1029                if (res < 0)
1030                        handle_write_error(mapping, page, res);
1031                if (res == AOP_WRITEPAGE_ACTIVATE) {
1032                        ClearPageReclaim(page);
1033                        return PAGE_ACTIVATE;
1034                }
1035
1036                if (!PageWriteback(page)) {
1037                        /* synchronous write or broken a_ops? */
1038                        ClearPageReclaim(page);
1039                }
1040                trace_mm_vmscan_writepage(page);
1041                inc_node_page_state(page, NR_VMSCAN_WRITE);
1042                return PAGE_SUCCESS;
1043        }
1044
1045        return PAGE_CLEAN;
1046}
1047
1048/*
1049 * Same as remove_mapping, but if the page is removed from the mapping, it
1050 * gets returned with a refcount of 0.
1051 */
1052static int __remove_mapping(struct address_space *mapping, struct page *page,
1053                            bool reclaimed, struct mem_cgroup *target_memcg)
1054{
1055        unsigned long flags;
1056        int refcount;
1057        void *shadow = NULL;
1058
1059        BUG_ON(!PageLocked(page));
1060        BUG_ON(mapping != page_mapping(page));
1061
1062        xa_lock_irqsave(&mapping->i_pages, flags);
1063        /*
1064         * The non racy check for a busy page.
1065         *
1066         * Must be careful with the order of the tests. When someone has
1067         * a ref to the page, it may be possible that they dirty it then
1068         * drop the reference. So if PageDirty is tested before page_count
1069         * here, then the following race may occur:
1070         *
1071         * get_user_pages(&page);
1072         * [user mapping goes away]
1073         * write_to(page);
1074         *                              !PageDirty(page)    [good]
1075         * SetPageDirty(page);
1076         * put_page(page);
1077         *                              !page_count(page)   [good, discard it]
1078         *
1079         * [oops, our write_to data is lost]
1080         *
1081         * Reversing the order of the tests ensures such a situation cannot
1082         * escape unnoticed. The smp_rmb is needed to ensure the page->flags
1083         * load is not satisfied before that of page->_refcount.
1084         *
1085         * Note that if SetPageDirty is always performed via set_page_dirty,
1086         * and thus under the i_pages lock, then this ordering is not required.
1087         */
1088        refcount = 1 + compound_nr(page);
1089        if (!page_ref_freeze(page, refcount))
1090                goto cannot_free;
1091        /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1092        if (unlikely(PageDirty(page))) {
1093                page_ref_unfreeze(page, refcount);
1094                goto cannot_free;
1095        }
1096
1097        if (PageSwapCache(page)) {
1098                swp_entry_t swap = { .val = page_private(page) };
1099                mem_cgroup_swapout(page, swap);
1100                if (reclaimed && !mapping_exiting(mapping))
1101                        shadow = workingset_eviction(page, target_memcg);
1102                __delete_from_swap_cache(page, swap, shadow);
1103                xa_unlock_irqrestore(&mapping->i_pages, flags);
1104                put_swap_page(page, swap);
1105        } else {
1106                void (*freepage)(struct page *);
1107
1108                freepage = mapping->a_ops->freepage;
1109                /*
1110                 * Remember a shadow entry for reclaimed file cache in
1111                 * order to detect refaults, thus thrashing, later on.
1112                 *
1113                 * But don't store shadows in an address space that is
1114                 * already exiting.  This is not just an optimization,
1115                 * inode reclaim needs to empty out the radix tree or
1116                 * the nodes are lost.  Don't plant shadows behind its
1117                 * back.
1118                 *
1119                 * We also don't store shadows for DAX mappings because the
1120                 * only page cache pages found in these are zero pages
1121                 * covering holes, and because we don't want to mix DAX
1122                 * exceptional entries and shadow exceptional entries in the
1123                 * same address_space.
1124                 */
1125                if (reclaimed && page_is_file_lru(page) &&
1126                    !mapping_exiting(mapping) && !dax_mapping(mapping))
1127                        shadow = workingset_eviction(page, target_memcg);
1128                __delete_from_page_cache(page, shadow);
1129                xa_unlock_irqrestore(&mapping->i_pages, flags);
1130
1131                if (freepage != NULL)
1132                        freepage(page);
1133        }
1134
1135        return 1;
1136
1137cannot_free:
1138        xa_unlock_irqrestore(&mapping->i_pages, flags);
1139        return 0;
1140}
1141
1142/*
1143 * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
1144 * someone else has a ref on the page, abort and return 0.  If it was
1145 * successfully detached, return 1.  Assumes the caller has a single ref on
1146 * this page.
1147 */
1148int remove_mapping(struct address_space *mapping, struct page *page)
1149{
1150        if (__remove_mapping(mapping, page, false, NULL)) {
1151                /*
1152                 * Unfreezing the refcount with 1 rather than 2 effectively
1153                 * drops the pagecache ref for us without requiring another
1154                 * atomic operation.
1155                 */
1156                page_ref_unfreeze(page, 1);
1157                return 1;
1158        }
1159        return 0;
1160}
1161
1162/**
1163 * putback_lru_page - put previously isolated page onto appropriate LRU list
1164 * @page: page to be put back to appropriate lru list
1165 *
1166 * Add previously isolated @page to appropriate LRU list.
1167 * Page may still be unevictable for other reasons.
1168 *
1169 * lru_lock must not be held, interrupts must be enabled.
1170 */
1171void putback_lru_page(struct page *page)
1172{
1173        lru_cache_add(page);
1174        put_page(page);         /* drop ref from isolate */
1175}
1176
1177enum page_references {
1178        PAGEREF_RECLAIM,
1179        PAGEREF_RECLAIM_CLEAN,
1180        PAGEREF_KEEP,
1181        PAGEREF_ACTIVATE,
1182};
1183
1184static enum page_references page_check_references(struct page *page,
1185                                                  struct scan_control *sc)
1186{
1187        int referenced_ptes, referenced_page;
1188        unsigned long vm_flags;
1189
1190        referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1191                                          &vm_flags);
1192        referenced_page = TestClearPageReferenced(page);
1193
1194        /*
1195         * Mlock lost the isolation race with us.  Let try_to_unmap()
1196         * move the page to the unevictable list.
1197         */
1198        if (vm_flags & VM_LOCKED)
1199                return PAGEREF_RECLAIM;
1200
1201        if (referenced_ptes) {
1202                /*
1203                 * All mapped pages start out with page table
1204                 * references from the instantiating fault, so we need
1205                 * to look twice if a mapped file page is used more
1206                 * than once.
1207                 *
1208                 * Mark it and spare it for another trip around the
1209                 * inactive list.  Another page table reference will
1210                 * lead to its activation.
1211                 *
1212                 * Note: the mark is set for activated pages as well
1213                 * so that recently deactivated but used pages are
1214                 * quickly recovered.
1215                 */
1216                SetPageReferenced(page);
1217
1218                if (referenced_page || referenced_ptes > 1)
1219                        return PAGEREF_ACTIVATE;
1220
1221                /*
1222                 * Activate file-backed executable pages after first usage.
1223                 */
1224                if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1225                        return PAGEREF_ACTIVATE;
1226
1227                return PAGEREF_KEEP;
1228        }
1229
1230        /* Reclaim if clean, defer dirty pages to writeback */
1231        if (referenced_page && !PageSwapBacked(page))
1232                return PAGEREF_RECLAIM_CLEAN;
1233
1234        return PAGEREF_RECLAIM;
1235}
1236
1237/* Check if a page is dirty or under writeback */
1238static void page_check_dirty_writeback(struct page *page,
1239                                       bool *dirty, bool *writeback)
1240{
1241        struct address_space *mapping;
1242
1243        /*
1244         * Anonymous pages are not handled by flushers and must be written
1245         * from reclaim context. Do not stall reclaim based on them
1246         */
1247        if (!page_is_file_lru(page) ||
1248            (PageAnon(page) && !PageSwapBacked(page))) {
1249                *dirty = false;
1250                *writeback = false;
1251                return;
1252        }
1253
1254        /* By default assume that the page flags are accurate */
1255        *dirty = PageDirty(page);
1256        *writeback = PageWriteback(page);
1257
1258        /* Verify dirty/writeback state if the filesystem supports it */
1259        if (!page_has_private(page))
1260                return;
1261
1262        mapping = page_mapping(page);
1263        if (mapping && mapping->a_ops->is_dirty_writeback)
1264                mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1265}
1266
1267/*
1268 * shrink_page_list() returns the number of reclaimed pages
1269 */
1270static unsigned int shrink_page_list(struct list_head *page_list,
1271                                     struct pglist_data *pgdat,
1272                                     struct scan_control *sc,
1273                                     struct reclaim_stat *stat,
1274                                     bool ignore_references)
1275{
1276        LIST_HEAD(ret_pages);
1277        LIST_HEAD(free_pages);
1278        unsigned int nr_reclaimed = 0;
1279        unsigned int pgactivate = 0;
1280
1281        memset(stat, 0, sizeof(*stat));
1282        cond_resched();
1283
1284        while (!list_empty(page_list)) {
1285                struct address_space *mapping;
1286                struct page *page;
1287                enum page_references references = PAGEREF_RECLAIM;
1288                bool dirty, writeback, may_enter_fs;
1289                unsigned int nr_pages;
1290
1291                cond_resched();
1292
1293                page = lru_to_page(page_list);
1294                list_del(&page->lru);
1295
1296                if (!trylock_page(page))
1297                        goto keep;
1298
1299                VM_BUG_ON_PAGE(PageActive(page), page);
1300
1301                nr_pages = compound_nr(page);
1302
1303                /* Account the number of base pages even though THP */
1304                sc->nr_scanned += nr_pages;
1305
1306                if (unlikely(!page_evictable(page)))
1307                        goto activate_locked;
1308
1309                if (!sc->may_unmap && page_mapped(page))
1310                        goto keep_locked;
1311
1312                may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1313                        (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1314
1315                /*
1316                 * The number of dirty pages determines if a node is marked
1317                 * reclaim_congested which affects wait_iff_congested. kswapd
1318                 * will stall and start writing pages if the tail of the LRU
1319                 * is all dirty unqueued pages.
1320                 */
1321                page_check_dirty_writeback(page, &dirty, &writeback);
1322                if (dirty || writeback)
1323                        stat->nr_dirty++;
1324
1325                if (dirty && !writeback)
1326                        stat->nr_unqueued_dirty++;
1327
1328                /*
1329                 * Treat this page as congested if the underlying BDI is or if
1330                 * pages are cycling through the LRU so quickly that the
1331                 * pages marked for immediate reclaim are making it to the
1332                 * end of the LRU a second time.
1333                 */
1334                mapping = page_mapping(page);
1335                if (((dirty || writeback) && mapping &&
1336                     inode_write_congested(mapping->host)) ||
1337                    (writeback && PageReclaim(page)))
1338                        stat->nr_congested++;
1339
1340                /*
1341                 * If a page at the tail of the LRU is under writeback, there
1342                 * are three cases to consider.
1343                 *
1344                 * 1) If reclaim is encountering an excessive number of pages
1345                 *    under writeback and this page is both under writeback and
1346                 *    PageReclaim then it indicates that pages are being queued
1347                 *    for IO but are being recycled through the LRU before the
1348                 *    IO can complete. Waiting on the page itself risks an
1349                 *    indefinite stall if it is impossible to writeback the
1350                 *    page due to IO error or disconnected storage so instead
1351                 *    note that the LRU is being scanned too quickly and the
1352                 *    caller can stall after page list has been processed.
1353                 *
1354                 * 2) Global or new memcg reclaim encounters a page that is
1355                 *    not marked for immediate reclaim, or the caller does not
1356                 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1357                 *    not to fs). In this case mark the page for immediate
1358                 *    reclaim and continue scanning.
1359                 *
1360                 *    Require may_enter_fs because we would wait on fs, which
1361                 *    may not have submitted IO yet. And the loop driver might
1362                 *    enter reclaim, and deadlock if it waits on a page for
1363                 *    which it is needed to do the write (loop masks off
1364                 *    __GFP_IO|__GFP_FS for this reason); but more thought
1365                 *    would probably show more reasons.
1366                 *
1367                 * 3) Legacy memcg encounters a page that is already marked
1368                 *    PageReclaim. memcg does not have any dirty pages
1369                 *    throttling so we could easily OOM just because too many
1370                 *    pages are in writeback and there is nothing else to
1371                 *    reclaim. Wait for the writeback to complete.
1372                 *
1373                 * In cases 1) and 2) we activate the pages to get them out of
1374                 * the way while we continue scanning for clean pages on the
1375                 * inactive list and refilling from the active list. The
1376                 * observation here is that waiting for disk writes is more
1377                 * expensive than potentially causing reloads down the line.
1378                 * Since they're marked for immediate reclaim, they won't put
1379                 * memory pressure on the cache working set any longer than it
1380                 * takes to write them to disk.
1381                 */
1382                if (PageWriteback(page)) {
1383                        /* Case 1 above */
1384                        if (current_is_kswapd() &&
1385                            PageReclaim(page) &&
1386                            test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1387                                stat->nr_immediate++;
1388                                goto activate_locked;
1389
1390                        /* Case 2 above */
1391                        } else if (writeback_throttling_sane(sc) ||
1392                            !PageReclaim(page) || !may_enter_fs) {
1393                                /*
1394                                 * This is slightly racy - end_page_writeback()
1395                                 * might have just cleared PageReclaim, then
1396                                 * setting PageReclaim here end up interpreted
1397                                 * as PageReadahead - but that does not matter
1398                                 * enough to care.  What we do want is for this
1399                                 * page to have PageReclaim set next time memcg
1400                                 * reclaim reaches the tests above, so it will
1401                                 * then wait_on_page_writeback() to avoid OOM;
1402                                 * and it's also appropriate in global reclaim.
1403                                 */
1404                                SetPageReclaim(page);
1405                                stat->nr_writeback++;
1406                                goto activate_locked;
1407
1408                        /* Case 3 above */
1409                        } else {
1410                                unlock_page(page);
1411                                wait_on_page_writeback(page);
1412                                /* then go back and try same page again */
1413                                list_add_tail(&page->lru, page_list);
1414                                continue;
1415                        }
1416                }
1417
1418                if (!ignore_references)
1419                        references = page_check_references(page, sc);
1420
1421                switch (references) {
1422                case PAGEREF_ACTIVATE:
1423                        goto activate_locked;
1424                case PAGEREF_KEEP:
1425                        stat->nr_ref_keep += nr_pages;
1426                        goto keep_locked;
1427                case PAGEREF_RECLAIM:
1428                case PAGEREF_RECLAIM_CLEAN:
1429                        ; /* try to reclaim the page below */
1430                }
1431
1432                /*
1433                 * Anonymous process memory has backing store?
1434                 * Try to allocate it some swap space here.
1435                 * Lazyfree page could be freed directly
1436                 */
1437                if (PageAnon(page) && PageSwapBacked(page)) {
1438                        if (!PageSwapCache(page)) {
1439                                if (!(sc->gfp_mask & __GFP_IO))
1440                                        goto keep_locked;
1441                                if (page_maybe_dma_pinned(page))
1442                                        goto keep_locked;
1443                                if (PageTransHuge(page)) {
1444                                        /* cannot split THP, skip it */
1445                                        if (!can_split_huge_page(page, NULL))
1446                                                goto activate_locked;
1447                                        /*
1448                                         * Split pages without a PMD map right
1449                                         * away. Chances are some or all of the
1450                                         * tail pages can be freed without IO.
1451                                         */
1452                                        if (!compound_mapcount(page) &&
1453                                            split_huge_page_to_list(page,
1454                                                                    page_list))
1455                                                goto activate_locked;
1456                                }
1457                                if (!add_to_swap(page)) {
1458                                        if (!PageTransHuge(page))
1459                                                goto activate_locked_split;
1460                                        /* Fallback to swap normal pages */
1461                                        if (split_huge_page_to_list(page,
1462                                                                    page_list))
1463                                                goto activate_locked;
1464#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1465                                        count_vm_event(THP_SWPOUT_FALLBACK);
1466#endif
1467                                        if (!add_to_swap(page))
1468                                                goto activate_locked_split;
1469                                }
1470
1471                                may_enter_fs = true;
1472
1473                                /* Adding to swap updated mapping */
1474                                mapping = page_mapping(page);
1475                        }
1476                } else if (unlikely(PageTransHuge(page))) {
1477                        /* Split file THP */
1478                        if (split_huge_page_to_list(page, page_list))
1479                                goto keep_locked;
1480                }
1481
1482                /*
1483                 * THP may get split above, need minus tail pages and update
1484                 * nr_pages to avoid accounting tail pages twice.
1485                 *
1486                 * The tail pages that are added into swap cache successfully
1487                 * reach here.
1488                 */
1489                if ((nr_pages > 1) && !PageTransHuge(page)) {
1490                        sc->nr_scanned -= (nr_pages - 1);
1491                        nr_pages = 1;
1492                }
1493
1494                /*
1495                 * The page is mapped into the page tables of one or more
1496                 * processes. Try to unmap it here.
1497                 */
1498                if (page_mapped(page)) {
1499                        enum ttu_flags flags = TTU_BATCH_FLUSH;
1500                        bool was_swapbacked = PageSwapBacked(page);
1501
1502                        if (unlikely(PageTransHuge(page)))
1503                                flags |= TTU_SPLIT_HUGE_PMD;
1504
1505                        if (!try_to_unmap(page, flags)) {
1506                                stat->nr_unmap_fail += nr_pages;
1507                                if (!was_swapbacked && PageSwapBacked(page))
1508                                        stat->nr_lazyfree_fail += nr_pages;
1509                                goto activate_locked;
1510                        }
1511                }
1512
1513                if (PageDirty(page)) {
1514                        /*
1515                         * Only kswapd can writeback filesystem pages
1516                         * to avoid risk of stack overflow. But avoid
1517                         * injecting inefficient single-page IO into
1518                         * flusher writeback as much as possible: only
1519                         * write pages when we've encountered many
1520                         * dirty pages, and when we've already scanned
1521                         * the rest of the LRU for clean pages and see
1522                         * the same dirty pages again (PageReclaim).
1523                         */
1524                        if (page_is_file_lru(page) &&
1525                            (!current_is_kswapd() || !PageReclaim(page) ||
1526                             !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1527                                /*
1528                                 * Immediately reclaim when written back.
1529                                 * Similar in principal to deactivate_page()
1530                                 * except we already have the page isolated
1531                                 * and know it's dirty
1532                                 */
1533                                inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
1534                                SetPageReclaim(page);
1535
1536                                goto activate_locked;
1537                        }
1538
1539                        if (references == PAGEREF_RECLAIM_CLEAN)
1540                                goto keep_locked;
1541                        if (!may_enter_fs)
1542                                goto keep_locked;
1543                        if (!sc->may_writepage)
1544                                goto keep_locked;
1545
1546                        /*
1547                         * Page is dirty. Flush the TLB if a writable entry
1548                         * potentially exists to avoid CPU writes after IO
1549                         * starts and then write it out here.
1550                         */
1551                        try_to_unmap_flush_dirty();
1552                        switch (pageout(page, mapping)) {
1553                        case PAGE_KEEP:
1554                                goto keep_locked;
1555                        case PAGE_ACTIVATE:
1556                                goto activate_locked;
1557                        case PAGE_SUCCESS:
1558                                stat->nr_pageout += thp_nr_pages(page);
1559
1560                                if (PageWriteback(page))
1561                                        goto keep;
1562                                if (PageDirty(page))
1563                                        goto keep;
1564
1565                                /*
1566                                 * A synchronous write - probably a ramdisk.  Go
1567                                 * ahead and try to reclaim the page.
1568                                 */
1569                                if (!trylock_page(page))
1570                                        goto keep;
1571                                if (PageDirty(page) || PageWriteback(page))
1572                                        goto keep_locked;
1573                                mapping = page_mapping(page);
1574                                fallthrough;
1575                        case PAGE_CLEAN:
1576                                ; /* try to free the page below */
1577                        }
1578                }
1579
1580                /*
1581                 * If the page has buffers, try to free the buffer mappings
1582                 * associated with this page. If we succeed we try to free
1583                 * the page as well.
1584                 *
1585                 * We do this even if the page is PageDirty().
1586                 * try_to_release_page() does not perform I/O, but it is
1587                 * possible for a page to have PageDirty set, but it is actually
1588                 * clean (all its buffers are clean).  This happens if the
1589                 * buffers were written out directly, with submit_bh(). ext3
1590                 * will do this, as well as the blockdev mapping.
1591                 * try_to_release_page() will discover that cleanness and will
1592                 * drop the buffers and mark the page clean - it can be freed.
1593                 *
1594                 * Rarely, pages can have buffers and no ->mapping.  These are
1595                 * the pages which were not successfully invalidated in
1596                 * truncate_cleanup_page().  We try to drop those buffers here
1597                 * and if that worked, and the page is no longer mapped into
1598                 * process address space (page_count == 1) it can be freed.
1599                 * Otherwise, leave the page on the LRU so it is swappable.
1600                 */
1601                if (page_has_private(page)) {
1602                        if (!try_to_release_page(page, sc->gfp_mask))
1603                                goto activate_locked;
1604                        if (!mapping && page_count(page) == 1) {
1605                                unlock_page(page);
1606                                if (put_page_testzero(page))
1607                                        goto free_it;
1608                                else {
1609                                        /*
1610                                         * rare race with speculative reference.
1611                                         * the speculative reference will free
1612                                         * this page shortly, so we may
1613                                         * increment nr_reclaimed here (and
1614                                         * leave it off the LRU).
1615                                         */
1616                                        nr_reclaimed++;
1617                                        continue;
1618                                }
1619                        }
1620                }
1621
1622                if (PageAnon(page) && !PageSwapBacked(page)) {
1623                        /* follow __remove_mapping for reference */
1624                        if (!page_ref_freeze(page, 1))
1625                                goto keep_locked;
1626                        if (PageDirty(page)) {
1627                                page_ref_unfreeze(page, 1);
1628                                goto keep_locked;
1629                        }
1630
1631                        count_vm_event(PGLAZYFREED);
1632                        count_memcg_page_event(page, PGLAZYFREED);
1633                } else if (!mapping || !__remove_mapping(mapping, page, true,
1634                                                         sc->target_mem_cgroup))
1635                        goto keep_locked;
1636
1637                unlock_page(page);
1638free_it:
1639                /*
1640                 * THP may get swapped out in a whole, need account
1641                 * all base pages.
1642                 */
1643                nr_reclaimed += nr_pages;
1644
1645                /*
1646                 * Is there need to periodically free_page_list? It would
1647                 * appear not as the counts should be low
1648                 */
1649                if (unlikely(PageTransHuge(page)))
1650                        destroy_compound_page(page);
1651                else
1652                        list_add(&page->lru, &free_pages);
1653                continue;
1654
1655activate_locked_split:
1656                /*
1657                 * The tail pages that are failed to add into swap cache
1658                 * reach here.  Fixup nr_scanned and nr_pages.
1659                 */
1660                if (nr_pages > 1) {
1661                        sc->nr_scanned -= (nr_pages - 1);
1662                        nr_pages = 1;
1663                }
1664activate_locked:
1665                /* Not a candidate for swapping, so reclaim swap space. */
1666                if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1667                                                PageMlocked(page)))
1668                        try_to_free_swap(page);
1669                VM_BUG_ON_PAGE(PageActive(page), page);
1670                if (!PageMlocked(page)) {
1671                        int type = page_is_file_lru(page);
1672                        SetPageActive(page);
1673                        stat->nr_activate[type] += nr_pages;
1674                        count_memcg_page_event(page, PGACTIVATE);
1675                }
1676keep_locked:
1677                unlock_page(page);
1678keep:
1679                list_add(&page->lru, &ret_pages);
1680                VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
1681        }
1682
1683        pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1684
1685        mem_cgroup_uncharge_list(&free_pages);
1686        try_to_unmap_flush();
1687        free_unref_page_list(&free_pages);
1688
1689        list_splice(&ret_pages, page_list);
1690        count_vm_events(PGACTIVATE, pgactivate);
1691
1692        return nr_reclaimed;
1693}
1694
1695unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1696                                            struct list_head *page_list)
1697{
1698        struct scan_control sc = {
1699                .gfp_mask = GFP_KERNEL,
1700                .priority = DEF_PRIORITY,
1701                .may_unmap = 1,
1702        };
1703        struct reclaim_stat stat;
1704        unsigned int nr_reclaimed;
1705        struct page *page, *next;
1706        LIST_HEAD(clean_pages);
1707
1708        list_for_each_entry_safe(page, next, page_list, lru) {
1709                if (!PageHuge(page) && page_is_file_lru(page) &&
1710                    !PageDirty(page) && !__PageMovable(page) &&
1711                    !PageUnevictable(page)) {
1712                        ClearPageActive(page);
1713                        list_move(&page->lru, &clean_pages);
1714                }
1715        }
1716
1717        nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1718                                        &stat, true);
1719        list_splice(&clean_pages, page_list);
1720        mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1721                            -(long)nr_reclaimed);
1722        /*
1723         * Since lazyfree pages are isolated from file LRU from the beginning,
1724         * they will rotate back to anonymous LRU in the end if it failed to
1725         * discard so isolated count will be mismatched.
1726         * Compensate the isolated count for both LRU lists.
1727         */
1728        mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1729                            stat.nr_lazyfree_fail);
1730        mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1731                            -(long)stat.nr_lazyfree_fail);
1732        return nr_reclaimed;
1733}
1734
1735/*
1736 * Attempt to remove the specified page from its LRU.  Only take this page
1737 * if it is of the appropriate PageActive status.  Pages which are being
1738 * freed elsewhere are also ignored.
1739 *
1740 * page:        page to consider
1741 * mode:        one of the LRU isolation modes defined above
1742 *
1743 * returns true on success, false on failure.
1744 */
1745bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
1746{
1747        /* Only take pages on the LRU. */
1748        if (!PageLRU(page))
1749                return false;
1750
1751        /* Compaction should not handle unevictable pages but CMA can do so */
1752        if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1753                return false;
1754
1755        /*
1756         * To minimise LRU disruption, the caller can indicate that it only
1757         * wants to isolate pages it will be able to operate on without
1758         * blocking - clean pages for the most part.
1759         *
1760         * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1761         * that it is possible to migrate without blocking
1762         */
1763        if (mode & ISOLATE_ASYNC_MIGRATE) {
1764                /* All the caller can do on PageWriteback is block */
1765                if (PageWriteback(page))
1766                        return false;
1767
1768                if (PageDirty(page)) {
1769                        struct address_space *mapping;
1770                        bool migrate_dirty;
1771
1772                        /*
1773                         * Only pages without mappings or that have a
1774                         * ->migratepage callback are possible to migrate
1775                         * without blocking. However, we can be racing with
1776                         * truncation so it's necessary to lock the page
1777                         * to stabilise the mapping as truncation holds
1778                         * the page lock until after the page is removed
1779                         * from the page cache.
1780                         */
1781                        if (!trylock_page(page))
1782                                return false;
1783
1784                        mapping = page_mapping(page);
1785                        migrate_dirty = !mapping || mapping->a_ops->migratepage;
1786                        unlock_page(page);
1787                        if (!migrate_dirty)
1788                                return false;
1789                }
1790        }
1791
1792        if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1793                return false;
1794
1795        return true;
1796}
1797
1798/*
1799 * Update LRU sizes after isolating pages. The LRU size updates must
1800 * be complete before mem_cgroup_update_lru_size due to a sanity check.
1801 */
1802static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1803                        enum lru_list lru, unsigned long *nr_zone_taken)
1804{
1805        int zid;
1806
1807        for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1808                if (!nr_zone_taken[zid])
1809                        continue;
1810
1811                update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1812        }
1813
1814}
1815
1816/**
1817 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1818 *
1819 * lruvec->lru_lock is heavily contended.  Some of the functions that
1820 * shrink the lists perform better by taking out a batch of pages
1821 * and working on them outside the LRU lock.
1822 *
1823 * For pagecache intensive workloads, this function is the hottest
1824 * spot in the kernel (apart from copy_*_user functions).
1825 *
1826 * Lru_lock must be held before calling this function.
1827 *
1828 * @nr_to_scan: The number of eligible pages to look through on the list.
1829 * @lruvec:     The LRU vector to pull pages from.
1830 * @dst:        The temp list to put pages on to.
1831 * @nr_scanned: The number of pages that were scanned.
1832 * @sc:         The scan_control struct for this reclaim session
1833 * @lru:        LRU list id for isolating
1834 *
1835 * returns how many pages were moved onto *@dst.
1836 */
1837static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1838                struct lruvec *lruvec, struct list_head *dst,
1839                unsigned long *nr_scanned, struct scan_control *sc,
1840                enum lru_list lru)
1841{
1842        struct list_head *src = &lruvec->lists[lru];
1843        unsigned long nr_taken = 0;
1844        unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1845        unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1846        unsigned long skipped = 0;
1847        unsigned long scan, total_scan, nr_pages;
1848        LIST_HEAD(pages_skipped);
1849        isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
1850
1851        total_scan = 0;
1852        scan = 0;
1853        while (scan < nr_to_scan && !list_empty(src)) {
1854                struct page *page;
1855
1856                page = lru_to_page(src);
1857                prefetchw_prev_lru_page(page, src, flags);
1858
1859                nr_pages = compound_nr(page);
1860                total_scan += nr_pages;
1861
1862                if (page_zonenum(page) > sc->reclaim_idx) {
1863                        list_move(&page->lru, &pages_skipped);
1864                        nr_skipped[page_zonenum(page)] += nr_pages;
1865                        continue;
1866                }
1867
1868                /*
1869                 * Do not count skipped pages because that makes the function
1870                 * return with no isolated pages if the LRU mostly contains
1871                 * ineligible pages.  This causes the VM to not reclaim any
1872                 * pages, triggering a premature OOM.
1873                 *
1874                 * Account all tail pages of THP.  This would not cause
1875                 * premature OOM since __isolate_lru_page() returns -EBUSY
1876                 * only when the page is being freed somewhere else.
1877                 */
1878                scan += nr_pages;
1879                if (!__isolate_lru_page_prepare(page, mode)) {
1880                        /* It is being freed elsewhere */
1881                        list_move(&page->lru, src);
1882                        continue;
1883                }
1884                /*
1885                 * Be careful not to clear PageLRU until after we're
1886                 * sure the page is not being freed elsewhere -- the
1887                 * page release code relies on it.
1888                 */
1889                if (unlikely(!get_page_unless_zero(page))) {
1890                        list_move(&page->lru, src);
1891                        continue;
1892                }
1893
1894                if (!TestClearPageLRU(page)) {
1895                        /* Another thread is already isolating this page */
1896                        put_page(page);
1897                        list_move(&page->lru, src);
1898                        continue;
1899                }
1900
1901                nr_taken += nr_pages;
1902                nr_zone_taken[page_zonenum(page)] += nr_pages;
1903                list_move(&page->lru, dst);
1904        }
1905
1906        /*
1907         * Splice any skipped pages to the start of the LRU list. Note that
1908         * this disrupts the LRU order when reclaiming for lower zones but
1909         * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1910         * scanning would soon rescan the same pages to skip and put the
1911         * system at risk of premature OOM.
1912         */
1913        if (!list_empty(&pages_skipped)) {
1914                int zid;
1915
1916                list_splice(&pages_skipped, src);
1917                for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1918                        if (!nr_skipped[zid])
1919                                continue;
1920
1921                        __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1922                        skipped += nr_skipped[zid];
1923                }
1924        }
1925        *nr_scanned = total_scan;
1926        trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1927                                    total_scan, skipped, nr_taken, mode, lru);
1928        update_lru_sizes(lruvec, lru, nr_zone_taken);
1929        return nr_taken;
1930}
1931
1932/**
1933 * isolate_lru_page - tries to isolate a page from its LRU list
1934 * @page: page to isolate from its LRU list
1935 *
1936 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1937 * vmstat statistic corresponding to whatever LRU list the page was on.
1938 *
1939 * Returns 0 if the page was removed from an LRU list.
1940 * Returns -EBUSY if the page was not on an LRU list.
1941 *
1942 * The returned page will have PageLRU() cleared.  If it was found on
1943 * the active list, it will have PageActive set.  If it was found on
1944 * the unevictable list, it will have the PageUnevictable bit set. That flag
1945 * may need to be cleared by the caller before letting the page go.
1946 *
1947 * The vmstat statistic corresponding to the list on which the page was
1948 * found will be decremented.
1949 *
1950 * Restrictions:
1951 *
1952 * (1) Must be called with an elevated refcount on the page. This is a
1953 *     fundamental difference from isolate_lru_pages (which is called
1954 *     without a stable reference).
1955 * (2) the lru_lock must not be held.
1956 * (3) interrupts must be enabled.
1957 */
1958int isolate_lru_page(struct page *page)
1959{
1960        int ret = -EBUSY;
1961
1962        VM_BUG_ON_PAGE(!page_count(page), page);
1963        WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
1964
1965        if (TestClearPageLRU(page)) {
1966                struct lruvec *lruvec;
1967
1968                get_page(page);
1969                lruvec = lock_page_lruvec_irq(page);
1970                del_page_from_lru_list(page, lruvec);
1971                unlock_page_lruvec_irq(lruvec);
1972                ret = 0;
1973        }
1974
1975        return ret;
1976}
1977
1978/*
1979 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1980 * then get rescheduled. When there are massive number of tasks doing page
1981 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1982 * the LRU list will go small and be scanned faster than necessary, leading to
1983 * unnecessary swapping, thrashing and OOM.
1984 */
1985static int too_many_isolated(struct pglist_data *pgdat, int file,
1986                struct scan_control *sc)
1987{
1988        unsigned long inactive, isolated;
1989
1990        if (current_is_kswapd())
1991                return 0;
1992
1993        if (!writeback_throttling_sane(sc))
1994                return 0;
1995
1996        if (file) {
1997                inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1998                isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1999        } else {
2000                inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2001                isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2002        }
2003
2004        /*
2005         * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2006         * won't get blocked by normal direct-reclaimers, forming a circular
2007         * deadlock.
2008         */
2009        if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2010                inactive >>= 3;
2011
2012        return isolated > inactive;
2013}
2014
2015/*
2016 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2017 * On return, @list is reused as a list of pages to be freed by the caller.
2018 *
2019 * Returns the number of pages moved to the given lruvec.
2020 */
2021static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
2022                                                     struct list_head *list)
2023{
2024        int nr_pages, nr_moved = 0;
2025        LIST_HEAD(pages_to_free);
2026        struct page *page;
2027
2028        while (!list_empty(list)) {
2029                page = lru_to_page(list);
2030                VM_BUG_ON_PAGE(PageLRU(page), page);
2031                list_del(&page->lru);
2032                if (unlikely(!page_evictable(page))) {
2033                        spin_unlock_irq(&lruvec->lru_lock);
2034                        putback_lru_page(page);
2035                        spin_lock_irq(&lruvec->lru_lock);
2036                        continue;
2037                }
2038
2039                /*
2040                 * The SetPageLRU needs to be kept here for list integrity.
2041                 * Otherwise:
2042                 *   #0 move_pages_to_lru             #1 release_pages
2043                 *   if !put_page_testzero
2044                 *                                    if (put_page_testzero())
2045                 *                                      !PageLRU //skip lru_lock
2046                 *     SetPageLRU()
2047                 *     list_add(&page->lru,)
2048                 *                                        list_add(&page->lru,)
2049                 */
2050                SetPageLRU(page);
2051
2052                if (unlikely(put_page_testzero(page))) {
2053                        __clear_page_lru_flags(page);
2054
2055                        if (unlikely(PageCompound(page))) {
2056                                spin_unlock_irq(&lruvec->lru_lock);
2057                                destroy_compound_page(page);
2058                                spin_lock_irq(&lruvec->lru_lock);
2059                        } else
2060                                list_add(&page->lru, &pages_to_free);
2061
2062                        continue;
2063                }
2064
2065                /*
2066                 * All pages were isolated from the same lruvec (and isolation
2067                 * inhibits memcg migration).
2068                 */
2069                VM_BUG_ON_PAGE(!lruvec_holds_page_lru_lock(page, lruvec), page);
2070                add_page_to_lru_list(page, lruvec);
2071                nr_pages = thp_nr_pages(page);
2072                nr_moved += nr_pages;
2073                if (PageActive(page))
2074                        workingset_age_nonresident(lruvec, nr_pages);
2075        }
2076
2077        /*
2078         * To save our caller's stack, now use input list for pages to free.
2079         */
2080        list_splice(&pages_to_free, list);
2081
2082        return nr_moved;
2083}
2084
2085/*
2086 * If a kernel thread (such as nfsd for loop-back mounts) services
2087 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2088 * In that case we should only throttle if the backing device it is
2089 * writing to is congested.  In other cases it is safe to throttle.
2090 */
2091static int current_may_throttle(void)
2092{
2093        return !(current->flags & PF_LOCAL_THROTTLE) ||
2094                current->backing_dev_info == NULL ||
2095                bdi_write_congested(current->backing_dev_info);
2096}
2097
2098/*
2099 * shrink_inactive_list() is a helper for shrink_node().  It returns the number
2100 * of reclaimed pages
2101 */
2102static noinline_for_stack unsigned long
2103shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
2104                     struct scan_control *sc, enum lru_list lru)
2105{
2106        LIST_HEAD(page_list);
2107        unsigned long nr_scanned;
2108        unsigned int nr_reclaimed = 0;
2109        unsigned long nr_taken;
2110        struct reclaim_stat stat;
2111        bool file = is_file_lru(lru);
2112        enum vm_event_item item;
2113        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2114        bool stalled = false;
2115
2116        while (unlikely(too_many_isolated(pgdat, file, sc))) {
2117                if (stalled)
2118                        return 0;
2119
2120                /* wait a bit for the reclaimer. */
2121                msleep(100);
2122                stalled = true;
2123
2124                /* We are about to die and free our memory. Return now. */
2125                if (fatal_signal_pending(current))
2126                        return SWAP_CLUSTER_MAX;
2127        }
2128
2129        lru_add_drain();
2130
2131        spin_lock_irq(&lruvec->lru_lock);
2132
2133        nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2134                                     &nr_scanned, sc, lru);
2135
2136        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2137        item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2138        if (!cgroup_reclaim(sc))
2139                __count_vm_events(item, nr_scanned);
2140        __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2141        __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2142
2143        spin_unlock_irq(&lruvec->lru_lock);
2144
2145        if (nr_taken == 0)
2146                return 0;
2147
2148        nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2149
2150        spin_lock_irq(&lruvec->lru_lock);
2151        move_pages_to_lru(lruvec, &page_list);
2152
2153        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2154        item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2155        if (!cgroup_reclaim(sc))
2156                __count_vm_events(item, nr_reclaimed);
2157        __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2158        __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2159        spin_unlock_irq(&lruvec->lru_lock);
2160
2161        lru_note_cost(lruvec, file, stat.nr_pageout);
2162        mem_cgroup_uncharge_list(&page_list);
2163        free_unref_page_list(&page_list);
2164
2165        /*
2166         * If dirty pages are scanned that are not queued for IO, it
2167         * implies that flushers are not doing their job. This can
2168         * happen when memory pressure pushes dirty pages to the end of
2169         * the LRU before the dirty limits are breached and the dirty
2170         * data has expired. It can also happen when the proportion of
2171         * dirty pages grows not through writes but through memory
2172         * pressure reclaiming all the clean cache. And in some cases,
2173         * the flushers simply cannot keep up with the allocation
2174         * rate. Nudge the flusher threads in case they are asleep.
2175         */
2176        if (stat.nr_unqueued_dirty == nr_taken)
2177                wakeup_flusher_threads(WB_REASON_VMSCAN);
2178
2179        sc->nr.dirty += stat.nr_dirty;
2180        sc->nr.congested += stat.nr_congested;
2181        sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2182        sc->nr.writeback += stat.nr_writeback;
2183        sc->nr.immediate += stat.nr_immediate;
2184        sc->nr.taken += nr_taken;
2185        if (file)
2186                sc->nr.file_taken += nr_taken;
2187
2188        trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2189                        nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2190        return nr_reclaimed;
2191}
2192
2193/*
2194 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2195 *
2196 * We move them the other way if the page is referenced by one or more
2197 * processes.
2198 *
2199 * If the pages are mostly unmapped, the processing is fast and it is
2200 * appropriate to hold lru_lock across the whole operation.  But if
2201 * the pages are mapped, the processing is slow (page_referenced()), so
2202 * we should drop lru_lock around each page.  It's impossible to balance
2203 * this, so instead we remove the pages from the LRU while processing them.
2204 * It is safe to rely on PG_active against the non-LRU pages in here because
2205 * nobody will play with that bit on a non-LRU page.
2206 *
2207 * The downside is that we have to touch page->_refcount against each page.
2208 * But we had to alter page->flags anyway.
2209 */
2210static void shrink_active_list(unsigned long nr_to_scan,
2211                               struct lruvec *lruvec,
2212                               struct scan_control *sc,
2213                               enum lru_list lru)
2214{
2215        unsigned long nr_taken;
2216        unsigned long nr_scanned;
2217        unsigned long vm_flags;
2218        LIST_HEAD(l_hold);      /* The pages which were snipped off */
2219        LIST_HEAD(l_active);
2220        LIST_HEAD(l_inactive);
2221        struct page *page;
2222        unsigned nr_deactivate, nr_activate;
2223        unsigned nr_rotated = 0;
2224        int file = is_file_lru(lru);
2225        struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2226
2227        lru_add_drain();
2228
2229        spin_lock_irq(&lruvec->lru_lock);
2230
2231        nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2232                                     &nr_scanned, sc, lru);
2233
2234        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2235
2236        if (!cgroup_reclaim(sc))
2237                __count_vm_events(PGREFILL, nr_scanned);
2238        __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2239
2240        spin_unlock_irq(&lruvec->lru_lock);
2241
2242        while (!list_empty(&l_hold)) {
2243                cond_resched();
2244                page = lru_to_page(&l_hold);
2245                list_del(&page->lru);
2246
2247                if (unlikely(!page_evictable(page))) {
2248                        putback_lru_page(page);
2249                        continue;
2250                }
2251
2252                if (unlikely(buffer_heads_over_limit)) {
2253                        if (page_has_private(page) && trylock_page(page)) {
2254                                if (page_has_private(page))
2255                                        try_to_release_page(page, 0);
2256                                unlock_page(page);
2257                        }
2258                }
2259
2260                if (page_referenced(page, 0, sc->target_mem_cgroup,
2261                                    &vm_flags)) {
2262                        /*
2263                         * Identify referenced, file-backed active pages and
2264                         * give them one more trip around the active list. So
2265                         * that executable code get better chances to stay in
2266                         * memory under moderate memory pressure.  Anon pages
2267                         * are not likely to be evicted by use-once streaming
2268                         * IO, plus JVM can create lots of anon VM_EXEC pages,
2269                         * so we ignore them here.
2270                         */
2271                        if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
2272                                nr_rotated += thp_nr_pages(page);
2273                                list_add(&page->lru, &l_active);
2274                                continue;
2275                        }
2276                }
2277
2278                ClearPageActive(page);  /* we are de-activating */
2279                SetPageWorkingset(page);
2280                list_add(&page->lru, &l_inactive);
2281        }
2282
2283        /*
2284         * Move pages back to the lru list.
2285         */
2286        spin_lock_irq(&lruvec->lru_lock);
2287
2288        nr_activate = move_pages_to_lru(lruvec, &l_active);
2289        nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2290        /* Keep all free pages in l_active list */
2291        list_splice(&l_inactive, &l_active);
2292
2293        __count_vm_events(PGDEACTIVATE, nr_deactivate);
2294        __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2295
2296        __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2297        spin_unlock_irq(&lruvec->lru_lock);
2298
2299        mem_cgroup_uncharge_list(&l_active);
2300        free_unref_page_list(&l_active);
2301        trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2302                        nr_deactivate, nr_rotated, sc->priority, file);
2303}
2304
2305unsigned long reclaim_pages(struct list_head *page_list)
2306{
2307        int nid = NUMA_NO_NODE;
2308        unsigned int nr_reclaimed = 0;
2309        LIST_HEAD(node_page_list);
2310        struct reclaim_stat dummy_stat;
2311        struct page *page;
2312        struct scan_control sc = {
2313                .gfp_mask = GFP_KERNEL,
2314                .priority = DEF_PRIORITY,
2315                .may_writepage = 1,
2316                .may_unmap = 1,
2317                .may_swap = 1,
2318        };
2319
2320        while (!list_empty(page_list)) {
2321                page = lru_to_page(page_list);
2322                if (nid == NUMA_NO_NODE) {
2323                        nid = page_to_nid(page);
2324                        INIT_LIST_HEAD(&node_page_list);
2325                }
2326
2327                if (nid == page_to_nid(page)) {
2328                        ClearPageActive(page);
2329                        list_move(&page->lru, &node_page_list);
2330                        continue;
2331                }
2332
2333                nr_reclaimed += shrink_page_list(&node_page_list,
2334                                                NODE_DATA(nid),
2335                                                &sc, &dummy_stat, false);
2336                while (!list_empty(&node_page_list)) {
2337                        page = lru_to_page(&node_page_list);
2338                        list_del(&page->lru);
2339                        putback_lru_page(page);
2340                }
2341
2342                nid = NUMA_NO_NODE;
2343        }
2344
2345        if (!list_empty(&node_page_list)) {
2346                nr_reclaimed += shrink_page_list(&node_page_list,
2347                                                NODE_DATA(nid),
2348                                                &sc, &dummy_stat, false);
2349                while (!list_empty(&node_page_list)) {
2350                        page = lru_to_page(&node_page_list);
2351                        list_del(&page->lru);
2352                        putback_lru_page(page);
2353                }
2354        }
2355
2356        return nr_reclaimed;
2357}
2358
2359static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2360                                 struct lruvec *lruvec, struct scan_control *sc)
2361{
2362        if (is_active_lru(lru)) {
2363                if (sc->may_deactivate & (1 << is_file_lru(lru)))
2364                        shrink_active_list(nr_to_scan, lruvec, sc, lru);
2365                else
2366                        sc->skipped_deactivate = 1;
2367                return 0;
2368        }
2369
2370        return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2371}
2372
2373/*
2374 * The inactive anon list should be small enough that the VM never has
2375 * to do too much work.
2376 *
2377 * The inactive file list should be small enough to leave most memory
2378 * to the established workingset on the scan-resistant active list,
2379 * but large enough to avoid thrashing the aggregate readahead window.
2380 *
2381 * Both inactive lists should also be large enough that each inactive
2382 * page has a chance to be referenced again before it is reclaimed.
2383 *
2384 * If that fails and refaulting is observed, the inactive list grows.
2385 *
2386 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2387 * on this LRU, maintained by the pageout code. An inactive_ratio
2388 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2389 *
2390 * total     target    max
2391 * memory    ratio     inactive
2392 * -------------------------------------
2393 *   10MB       1         5MB
2394 *  100MB       1        50MB
2395 *    1GB       3       250MB
2396 *   10GB      10       0.9GB
2397 *  100GB      31         3GB
2398 *    1TB     101        10GB
2399 *   10TB     320        32GB
2400 */
2401static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2402{
2403        enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2404        unsigned long inactive, active;
2405        unsigned long inactive_ratio;
2406        unsigned long gb;
2407
2408        inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2409        active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2410
2411        gb = (inactive + active) >> (30 - PAGE_SHIFT);
2412        if (gb)
2413                inactive_ratio = int_sqrt(10 * gb);
2414        else
2415                inactive_ratio = 1;
2416
2417        return inactive * inactive_ratio < active;
2418}
2419
2420enum scan_balance {
2421        SCAN_EQUAL,
2422        SCAN_FRACT,
2423        SCAN_ANON,
2424        SCAN_FILE,
2425};
2426
2427/*
2428 * Determine how aggressively the anon and file LRU lists should be
2429 * scanned.  The relative value of each set of LRU lists is determined
2430 * by looking at the fraction of the pages scanned we did rotate back
2431 * onto the active list instead of evict.
2432 *
2433 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2434 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2435 */
2436static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2437                           unsigned long *nr)
2438{
2439        struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2440        unsigned long anon_cost, file_cost, total_cost;
2441        int swappiness = mem_cgroup_swappiness(memcg);
2442        u64 fraction[ANON_AND_FILE];
2443        u64 denominator = 0;    /* gcc */
2444        enum scan_balance scan_balance;
2445        unsigned long ap, fp;
2446        enum lru_list lru;
2447
2448        /* If we have no swap space, do not bother scanning anon pages. */
2449        if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
2450                scan_balance = SCAN_FILE;
2451                goto out;
2452        }
2453
2454        /*
2455         * Global reclaim will swap to prevent OOM even with no
2456         * swappiness, but memcg users want to use this knob to
2457         * disable swapping for individual groups completely when
2458         * using the memory controller's swap limit feature would be
2459         * too expensive.
2460         */
2461        if (cgroup_reclaim(sc) && !swappiness) {
2462                scan_balance = SCAN_FILE;
2463                goto out;
2464        }
2465
2466        /*
2467         * Do not apply any pressure balancing cleverness when the
2468         * system is close to OOM, scan both anon and file equally
2469         * (unless the swappiness setting disagrees with swapping).
2470         */
2471        if (!sc->priority && swappiness) {
2472                scan_balance = SCAN_EQUAL;
2473                goto out;
2474        }
2475
2476        /*
2477         * If the system is almost out of file pages, force-scan anon.
2478         */
2479        if (sc->file_is_tiny) {
2480                scan_balance = SCAN_ANON;
2481                goto out;
2482        }
2483
2484        /*
2485         * If there is enough inactive page cache, we do not reclaim
2486         * anything from the anonymous working right now.
2487         */
2488        if (sc->cache_trim_mode) {
2489                scan_balance = SCAN_FILE;
2490                goto out;
2491        }
2492
2493        scan_balance = SCAN_FRACT;
2494        /*
2495         * Calculate the pressure balance between anon and file pages.
2496         *
2497         * The amount of pressure we put on each LRU is inversely
2498         * proportional to the cost of reclaiming each list, as
2499         * determined by the share of pages that are refaulting, times
2500         * the relative IO cost of bringing back a swapped out
2501         * anonymous page vs reloading a filesystem page (swappiness).
2502         *
2503         * Although we limit that influence to ensure no list gets
2504         * left behind completely: at least a third of the pressure is
2505         * applied, before swappiness.
2506         *
2507         * With swappiness at 100, anon and file have equal IO cost.
2508         */
2509        total_cost = sc->anon_cost + sc->file_cost;
2510        anon_cost = total_cost + sc->anon_cost;
2511        file_cost = total_cost + sc->file_cost;
2512        total_cost = anon_cost + file_cost;
2513
2514        ap = swappiness * (total_cost + 1);
2515        ap /= anon_cost + 1;
2516
2517        fp = (200 - swappiness) * (total_cost + 1);
2518        fp /= file_cost + 1;
2519
2520        fraction[0] = ap;
2521        fraction[1] = fp;
2522        denominator = ap + fp;
2523out:
2524        for_each_evictable_lru(lru) {
2525                int file = is_file_lru(lru);
2526                unsigned long lruvec_size;
2527                unsigned long low, min;
2528                unsigned long scan;
2529
2530                lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2531                mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2532                                      &min, &low);
2533
2534                if (min || low) {
2535                        /*
2536                         * Scale a cgroup's reclaim pressure by proportioning
2537                         * its current usage to its memory.low or memory.min
2538                         * setting.
2539                         *
2540                         * This is important, as otherwise scanning aggression
2541                         * becomes extremely binary -- from nothing as we
2542                         * approach the memory protection threshold, to totally
2543                         * nominal as we exceed it.  This results in requiring
2544                         * setting extremely liberal protection thresholds. It
2545                         * also means we simply get no protection at all if we
2546                         * set it too low, which is not ideal.
2547                         *
2548                         * If there is any protection in place, we reduce scan
2549                         * pressure by how much of the total memory used is
2550                         * within protection thresholds.
2551                         *
2552                         * There is one special case: in the first reclaim pass,
2553                         * we skip over all groups that are within their low
2554                         * protection. If that fails to reclaim enough pages to
2555                         * satisfy the reclaim goal, we come back and override
2556                         * the best-effort low protection. However, we still
2557                         * ideally want to honor how well-behaved groups are in
2558                         * that case instead of simply punishing them all
2559                         * equally. As such, we reclaim them based on how much
2560                         * memory they are using, reducing the scan pressure
2561                         * again by how much of the total memory used is under
2562                         * hard protection.
2563                         */
2564                        unsigned long cgroup_size = mem_cgroup_size(memcg);
2565                        unsigned long protection;
2566
2567                        /* memory.low scaling, make sure we retry before OOM */
2568                        if (!sc->memcg_low_reclaim && low > min) {
2569                                protection = low;
2570                                sc->memcg_low_skipped = 1;
2571                        } else {
2572                                protection = min;
2573                        }
2574
2575                        /* Avoid TOCTOU with earlier protection check */
2576                        cgroup_size = max(cgroup_size, protection);
2577
2578                        scan = lruvec_size - lruvec_size * protection /
2579                                cgroup_size;
2580
2581                        /*
2582                         * Minimally target SWAP_CLUSTER_MAX pages to keep
2583                         * reclaim moving forwards, avoiding decrementing
2584                         * sc->priority further than desirable.
2585                         */
2586                        scan = max(scan, SWAP_CLUSTER_MAX);
2587                } else {
2588                        scan = lruvec_size;
2589                }
2590
2591                scan >>= sc->priority;
2592
2593                /*
2594                 * If the cgroup's already been deleted, make sure to
2595                 * scrape out the remaining cache.
2596                 */
2597                if (!scan && !mem_cgroup_online(memcg))
2598                        scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2599
2600                switch (scan_balance) {
2601                case SCAN_EQUAL:
2602                        /* Scan lists relative to size */
2603                        break;
2604                case SCAN_FRACT:
2605                        /*
2606                         * Scan types proportional to swappiness and
2607                         * their relative recent reclaim efficiency.
2608                         * Make sure we don't miss the last page on
2609                         * the offlined memory cgroups because of a
2610                         * round-off error.
2611                         */
2612                        scan = mem_cgroup_online(memcg) ?
2613                               div64_u64(scan * fraction[file], denominator) :
2614                               DIV64_U64_ROUND_UP(scan * fraction[file],
2615                                                  denominator);
2616                        break;
2617                case SCAN_FILE:
2618                case SCAN_ANON:
2619                        /* Scan one type exclusively */
2620                        if ((scan_balance == SCAN_FILE) != file)
2621                                scan = 0;
2622                        break;
2623                default:
2624                        /* Look ma, no brain */
2625                        BUG();
2626                }
2627
2628                nr[lru] = scan;
2629        }
2630}
2631
2632static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
2633{
2634        unsigned long nr[NR_LRU_LISTS];
2635        unsigned long targets[NR_LRU_LISTS];
2636        unsigned long nr_to_scan;
2637        enum lru_list lru;
2638        unsigned long nr_reclaimed = 0;
2639        unsigned long nr_to_reclaim = sc->nr_to_reclaim;
2640        struct blk_plug plug;
2641        bool scan_adjusted;
2642
2643        get_scan_count(lruvec, sc, nr);
2644
2645        /* Record the original scan target for proportional adjustments later */
2646        memcpy(targets, nr, sizeof(nr));
2647
2648        /*
2649         * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2650         * event that can occur when there is little memory pressure e.g.
2651         * multiple streaming readers/writers. Hence, we do not abort scanning
2652         * when the requested number of pages are reclaimed when scanning at
2653         * DEF_PRIORITY on the assumption that the fact we are direct
2654         * reclaiming implies that kswapd is not keeping up and it is best to
2655         * do a batch of work at once. For memcg reclaim one check is made to
2656         * abort proportional reclaim if either the file or anon lru has already
2657         * dropped to zero at the first pass.
2658         */
2659        scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
2660                         sc->priority == DEF_PRIORITY);
2661
2662        blk_start_plug(&plug);
2663        while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
2664                                        nr[LRU_INACTIVE_FILE]) {
2665                unsigned long nr_anon, nr_file, percentage;
2666                unsigned long nr_scanned;
2667
2668                for_each_evictable_lru(lru) {
2669                        if (nr[lru]) {
2670                                nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
2671                                nr[lru] -= nr_to_scan;
2672
2673                                nr_reclaimed += shrink_list(lru, nr_to_scan,
2674                                                            lruvec, sc);
2675                        }
2676                }
2677
2678                cond_resched();
2679
2680                if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2681                        continue;
2682
2683                /*
2684                 * For kswapd and memcg, reclaim at least the number of pages
2685                 * requested. Ensure that the anon and file LRUs are scanned
2686                 * proportionally what was requested by get_scan_count(). We
2687                 * stop reclaiming one LRU and reduce the amount scanning
2688                 * proportional to the original scan target.
2689                 */
2690                nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2691                nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2692
2693                /*
2694                 * It's just vindictive to attack the larger once the smaller
2695                 * has gone to zero.  And given the way we stop scanning the
2696                 * smaller below, this makes sure that we only make one nudge
2697                 * towards proportionality once we've got nr_to_reclaim.
2698                 */
2699                if (!nr_file || !nr_anon)
2700                        break;
2701
2702                if (nr_file > nr_anon) {
2703                        unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2704                                                targets[LRU_ACTIVE_ANON] + 1;
2705                        lru = LRU_BASE;
2706                        percentage = nr_anon * 100 / scan_target;
2707                } else {
2708                        unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2709                                                targets[LRU_ACTIVE_FILE] + 1;
2710                        lru = LRU_FILE;
2711                        percentage = nr_file * 100 / scan_target;
2712                }
2713
2714                /* Stop scanning the smaller of the LRU */
2715                nr[lru] = 0;
2716                nr[lru + LRU_ACTIVE] = 0;
2717
2718                /*
2719                 * Recalculate the other LRU scan count based on its original
2720                 * scan target and the percentage scanning already complete
2721                 */
2722                lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2723                nr_scanned = targets[lru] - nr[lru];
2724                nr[lru] = targets[lru] * (100 - percentage) / 100;
2725                nr[lru] -= min(nr[lru], nr_scanned);
2726
2727                lru += LRU_ACTIVE;
2728                nr_scanned = targets[lru] - nr[lru];
2729                nr[lru] = targets[lru] * (100 - percentage) / 100;
2730                nr[lru] -= min(nr[lru], nr_scanned);
2731
2732                scan_adjusted = true;
2733        }
2734        blk_finish_plug(&plug);
2735        sc->nr_reclaimed += nr_reclaimed;
2736
2737        /*
2738         * Even if we did not try to evict anon pages at all, we want to
2739         * rebalance the anon lru active/inactive ratio.
2740         */
2741        if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
2742                shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2743                                   sc, LRU_ACTIVE_ANON);
2744}
2745
2746/* Use reclaim/compaction for costly allocs or under memory pressure */
2747static bool in_reclaim_compaction(struct scan_control *sc)
2748{
2749        if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
2750                        (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
2751                         sc->priority < DEF_PRIORITY - 2))
2752                return true;
2753
2754        return false;
2755}
2756
2757/*
2758 * Reclaim/compaction is used for high-order allocation requests. It reclaims
2759 * order-0 pages before compacting the zone. should_continue_reclaim() returns
2760 * true if more pages should be reclaimed such that when the page allocator
2761 * calls try_to_compact_pages() that it will have enough free pages to succeed.
2762 * It will give up earlier than that if there is difficulty reclaiming pages.
2763 */
2764static inline bool should_continue_reclaim(struct pglist_data *pgdat,
2765                                        unsigned long nr_reclaimed,
2766                                        struct scan_control *sc)
2767{
2768        unsigned long pages_for_compaction;
2769        unsigned long inactive_lru_pages;
2770        int z;
2771
2772        /* If not in reclaim/compaction mode, stop */
2773        if (!in_reclaim_compaction(sc))
2774                return false;
2775
2776        /*
2777         * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
2778         * number of pages that were scanned. This will return to the caller
2779         * with the risk reclaim/compaction and the resulting allocation attempt
2780         * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
2781         * allocations through requiring that the full LRU list has been scanned
2782         * first, by assuming that zero delta of sc->nr_scanned means full LRU
2783         * scan, but that approximation was wrong, and there were corner cases
2784         * where always a non-zero amount of pages were scanned.
2785         */
2786        if (!nr_reclaimed)
2787                return false;
2788
2789        /* If compaction would go ahead or the allocation would succeed, stop */
2790        for (z = 0; z <= sc->reclaim_idx; z++) {
2791                struct zone *zone = &pgdat->node_zones[z];
2792                if (!managed_zone(zone))
2793                        continue;
2794
2795                switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2796                case COMPACT_SUCCESS:
2797                case COMPACT_CONTINUE:
2798                        return false;
2799                default:
2800                        /* check next zone */
2801                        ;
2802                }
2803        }
2804
2805        /*
2806         * If we have not reclaimed enough pages for compaction and the
2807         * inactive lists are large enough, continue reclaiming
2808         */
2809        pages_for_compaction = compact_gap(sc->order);
2810        inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2811        if (get_nr_swap_pages() > 0)
2812                inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
2813
2814        return inactive_lru_pages > pages_for_compaction;
2815}
2816
2817static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2818{
2819        struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2820        struct mem_cgroup *memcg;
2821
2822        memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2823        do {
2824                struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
2825                unsigned long reclaimed;
2826                unsigned long scanned;
2827
2828                /*
2829                 * This loop can become CPU-bound when target memcgs
2830                 * aren't eligible for reclaim - either because they
2831                 * don't have any reclaimable pages, or because their
2832                 * memory is explicitly protected. Avoid soft lockups.
2833                 */
2834                cond_resched();
2835
2836                mem_cgroup_calculate_protection(target_memcg, memcg);
2837
2838                if (mem_cgroup_below_min(memcg)) {
2839                        /*
2840                         * Hard protection.
2841                         * If there is no reclaimable memory, OOM.
2842                         */
2843                        continue;
2844                } else if (mem_cgroup_below_low(memcg)) {
2845                        /*
2846                         * Soft protection.
2847                         * Respect the protection only as long as
2848                         * there is an unprotected supply
2849                         * of reclaimable memory from other cgroups.
2850                         */
2851                        if (!sc->memcg_low_reclaim) {
2852                                sc->memcg_low_skipped = 1;
2853                                continue;
2854                        }
2855                        memcg_memory_event(memcg, MEMCG_LOW);
2856                }
2857
2858                reclaimed = sc->nr_reclaimed;
2859                scanned = sc->nr_scanned;
2860
2861                shrink_lruvec(lruvec, sc);
2862
2863                shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
2864                            sc->priority);
2865
2866                /* Record the group's reclaim efficiency */
2867                vmpressure(sc->gfp_mask, memcg, false,
2868                           sc->nr_scanned - scanned,
2869                           sc->nr_reclaimed - reclaimed);
2870
2871        } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
2872}
2873
2874static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2875{
2876        struct reclaim_state *reclaim_state = current->reclaim_state;
2877        unsigned long nr_reclaimed, nr_scanned;
2878        struct lruvec *target_lruvec;
2879        bool reclaimable = false;
2880        unsigned long file;
2881
2882        target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2883
2884again:
2885        memset(&sc->nr, 0, sizeof(sc->nr));
2886
2887        nr_reclaimed = sc->nr_reclaimed;
2888        nr_scanned = sc->nr_scanned;
2889
2890        /*
2891         * Determine the scan balance between anon and file LRUs.
2892         */
2893        spin_lock_irq(&target_lruvec->lru_lock);
2894        sc->anon_cost = target_lruvec->anon_cost;
2895        sc->file_cost = target_lruvec->file_cost;
2896        spin_unlock_irq(&target_lruvec->lru_lock);
2897
2898        /*
2899         * Target desirable inactive:active list ratios for the anon
2900         * and file LRU lists.
2901         */
2902        if (!sc->force_deactivate) {
2903                unsigned long refaults;
2904
2905                refaults = lruvec_page_state(target_lruvec,
2906                                WORKINGSET_ACTIVATE_ANON);
2907                if (refaults != target_lruvec->refaults[0] ||
2908                        inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2909                        sc->may_deactivate |= DEACTIVATE_ANON;
2910                else
2911                        sc->may_deactivate &= ~DEACTIVATE_ANON;
2912
2913                /*
2914                 * When refaults are being observed, it means a new
2915                 * workingset is being established. Deactivate to get
2916                 * rid of any stale active pages quickly.
2917                 */
2918                refaults = lruvec_page_state(target_lruvec,
2919                                WORKINGSET_ACTIVATE_FILE);
2920                if (refaults != target_lruvec->refaults[1] ||
2921                    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2922                        sc->may_deactivate |= DEACTIVATE_FILE;
2923                else
2924                        sc->may_deactivate &= ~DEACTIVATE_FILE;
2925        } else
2926                sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2927
2928        /*
2929         * If we have plenty of inactive file pages that aren't
2930         * thrashing, try to reclaim those first before touching
2931         * anonymous pages.
2932         */
2933        file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2934        if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2935                sc->cache_trim_mode = 1;
2936        else
2937                sc->cache_trim_mode = 0;
2938
2939        /*
2940         * Prevent the reclaimer from falling into the cache trap: as
2941         * cache pages start out inactive, every cache fault will tip
2942         * the scan balance towards the file LRU.  And as the file LRU
2943         * shrinks, so does the window for rotation from references.
2944         * This means we have a runaway feedback loop where a tiny
2945         * thrashing file LRU becomes infinitely more attractive than
2946         * anon pages.  Try to detect this based on file LRU size.
2947         */
2948        if (!cgroup_reclaim(sc)) {
2949                unsigned long total_high_wmark = 0;
2950                unsigned long free, anon;
2951                int z;
2952
2953                free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2954                file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2955                           node_page_state(pgdat, NR_INACTIVE_FILE);
2956
2957                for (z = 0; z < MAX_NR_ZONES; z++) {
2958                        struct zone *zone = &pgdat->node_zones[z];
2959                        if (!managed_zone(zone))
2960                                continue;
2961
2962                        total_high_wmark += high_wmark_pages(zone);
2963                }
2964
2965                /*
2966                 * Consider anon: if that's low too, this isn't a
2967                 * runaway file reclaim problem, but rather just
2968                 * extreme pressure. Reclaim as per usual then.
2969                 */
2970                anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2971
2972                sc->file_is_tiny =
2973                        file + free <= total_high_wmark &&
2974                        !(sc->may_deactivate & DEACTIVATE_ANON) &&
2975                        anon >> sc->priority;
2976        }
2977
2978        shrink_node_memcgs(pgdat, sc);
2979
2980        if (reclaim_state) {
2981                sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2982                reclaim_state->reclaimed_slab = 0;
2983        }
2984
2985        /* Record the subtree's reclaim efficiency */
2986        vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
2987                   sc->nr_scanned - nr_scanned,
2988                   sc->nr_reclaimed - nr_reclaimed);
2989
2990        if (sc->nr_reclaimed - nr_reclaimed)
2991                reclaimable = true;
2992
2993        if (current_is_kswapd()) {
2994                /*
2995                 * If reclaim is isolating dirty pages under writeback,
2996                 * it implies that the long-lived page allocation rate
2997                 * is exceeding the page laundering rate. Either the
2998                 * global limits are not being effective at throttling
2999                 * processes due to the page distribution throughout
3000                 * zones or there is heavy usage of a slow backing
3001                 * device. The only option is to throttle from reclaim
3002                 * context which is not ideal as there is no guarantee
3003                 * the dirtying process is throttled in the same way
3004                 * balance_dirty_pages() manages.
3005                 *
3006                 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3007                 * count the number of pages under pages flagged for
3008                 * immediate reclaim and stall if any are encountered
3009                 * in the nr_immediate check below.
3010                 */
3011                if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3012                        set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3013
3014                /* Allow kswapd to start writing pages during reclaim.*/
3015                if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3016                        set_bit(PGDAT_DIRTY, &pgdat->flags);
3017
3018                /*
3019                 * If kswapd scans pages marked for immediate
3020                 * reclaim and under writeback (nr_immediate), it
3021                 * implies that pages are cycling through the LRU
3022                 * faster than they are written so also forcibly stall.
3023                 */
3024                if (sc->nr.immediate)
3025                        congestion_wait(BLK_RW_ASYNC, HZ/10);
3026        }
3027
3028        /*
3029         * Tag a node/memcg as congested if all the dirty pages
3030         * scanned were backed by a congested BDI and
3031         * wait_iff_congested will stall.
3032         *
3033         * Legacy memcg will stall in page writeback so avoid forcibly
3034         * stalling in wait_iff_congested().
3035         */
3036        if ((current_is_kswapd() ||
3037             (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3038            sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
3039                set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3040
3041        /*
3042         * Stall direct reclaim for IO completions if underlying BDIs
3043         * and node is congested. Allow kswapd to continue until it
3044         * starts encountering unqueued dirty pages or cycling through
3045         * the LRU too quickly.
3046         */
3047        if (!current_is_kswapd() && current_may_throttle() &&
3048            !sc->hibernation_mode &&
3049            test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
3050                wait_iff_congested(BLK_RW_ASYNC, HZ/10);
3051
3052        if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3053                                    sc))
3054                goto again;
3055
3056        /*
3057         * Kswapd gives up on balancing particular nodes after too
3058         * many failures to reclaim anything from them and goes to
3059         * sleep. On reclaim progress, reset the failure counter. A
3060         * successful direct reclaim run will revive a dormant kswapd.
3061         */
3062        if (reclaimable)
3063                pgdat->kswapd_failures = 0;
3064}
3065
3066/*
3067 * Returns true if compaction should go ahead for a costly-order request, or
3068 * the allocation would already succeed without compaction. Return false if we
3069 * should reclaim first.
3070 */
3071static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3072{
3073        unsigned long watermark;
3074        enum compact_result suitable;
3075
3076        suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3077        if (suitable == COMPACT_SUCCESS)
3078                /* Allocation should succeed already. Don't reclaim. */
3079                return true;
3080        if (suitable == COMPACT_SKIPPED)
3081                /* Compaction cannot yet proceed. Do reclaim. */
3082                return false;
3083
3084        /*
3085         * Compaction is already possible, but it takes time to run and there
3086         * are potentially other callers using the pages just freed. So proceed
3087         * with reclaim to make a buffer of free pages available to give
3088         * compaction a reasonable chance of completing and allocating the page.
3089         * Note that we won't actually reclaim the whole buffer in one attempt
3090         * as the target watermark in should_continue_reclaim() is lower. But if
3091         * we are already above the high+gap watermark, don't reclaim at all.
3092         */
3093        watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3094
3095        return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3096}
3097
3098/*
3099 * This is the direct reclaim path, for page-allocating processes.  We only
3100 * try to reclaim pages from zones which will satisfy the caller's allocation
3101 * request.
3102 *
3103 * If a zone is deemed to be full of pinned pages then just give it a light
3104 * scan then give up on it.
3105 */
3106static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
3107{
3108        struct zoneref *z;
3109        struct zone *zone;
3110        unsigned long nr_soft_reclaimed;
3111        unsigned long nr_soft_scanned;
3112        gfp_t orig_mask;
3113        pg_data_t *last_pgdat = NULL;
3114
3115        /*
3116         * If the number of buffer_heads in the machine exceeds the maximum
3117         * allowed level, force direct reclaim to scan the highmem zone as
3118         * highmem pages could be pinning lowmem pages storing buffer_heads
3119         */
3120        orig_mask = sc->gfp_mask;
3121        if (buffer_heads_over_limit) {
3122                sc->gfp_mask |= __GFP_HIGHMEM;
3123                sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3124        }
3125
3126        for_each_zone_zonelist_nodemask(zone, z, zonelist,
3127                                        sc->reclaim_idx, sc->nodemask) {
3128                /*
3129                 * Take care memory controller reclaiming has small influence
3130                 * to global LRU.
3131                 */
3132                if (!cgroup_reclaim(sc)) {
3133                        if (!cpuset_zone_allowed(zone,
3134                                                 GFP_KERNEL | __GFP_HARDWALL))
3135                                continue;
3136
3137                        /*
3138                         * If we already have plenty of memory free for
3139                         * compaction in this zone, don't free any more.
3140                         * Even though compaction is invoked for any
3141                         * non-zero order, only frequent costly order
3142                         * reclamation is disruptive enough to become a
3143                         * noticeable problem, like transparent huge
3144                         * page allocations.
3145                         */
3146                        if (IS_ENABLED(CONFIG_COMPACTION) &&
3147                            sc->order > PAGE_ALLOC_COSTLY_ORDER &&
3148                            compaction_ready(zone, sc)) {
3149                                sc->compaction_ready = true;
3150                                continue;
3151                        }
3152
3153                        /*
3154                         * Shrink each node in the zonelist once. If the
3155                         * zonelist is ordered by zone (not the default) then a
3156                         * node may be shrunk multiple times but in that case
3157                         * the user prefers lower zones being preserved.
3158                         */
3159                        if (zone->zone_pgdat == last_pgdat)
3160                                continue;
3161
3162                        /*
3163                         * This steals pages from memory cgroups over softlimit
3164                         * and returns the number of reclaimed pages and
3165                         * scanned pages. This works for global memory pressure
3166                         * and balancing, not for a memcg's limit.
3167                         */
3168                        nr_soft_scanned = 0;
3169                        nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
3170                                                sc->order, sc->gfp_mask,
3171                                                &nr_soft_scanned);
3172                        sc->nr_reclaimed += nr_soft_reclaimed;
3173                        sc->nr_scanned += nr_soft_scanned;
3174                        /* need some check for avoid more shrink_zone() */
3175                }
3176
3177                /* See comment about same check for global reclaim above */
3178                if (zone->zone_pgdat == last_pgdat)
3179                        continue;
3180                last_pgdat = zone->zone_pgdat;
3181                shrink_node(zone->zone_pgdat, sc);
3182        }
3183
3184        /*
3185         * Restore to original mask to avoid the impact on the caller if we
3186         * promoted it to __GFP_HIGHMEM.
3187         */
3188        sc->gfp_mask = orig_mask;
3189}
3190
3191static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
3192{
3193        struct lruvec *target_lruvec;
3194        unsigned long refaults;
3195
3196        target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3197        refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3198        target_lruvec->refaults[0] = refaults;
3199        refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3200        target_lruvec->refaults[1] = refaults;
3201}
3202
3203/*
3204 * This is the main entry point to direct page reclaim.
3205 *
3206 * If a full scan of the inactive list fails to free enough memory then we
3207 * are "out of memory" and something needs to be killed.
3208 *
3209 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3210 * high - the zone may be full of dirty or under-writeback pages, which this
3211 * caller can't do much about.  We kick the writeback threads and take explicit
3212 * naps in the hope that some of these pages can be written.  But if the
3213 * allocating task holds filesystem locks which prevent writeout this might not
3214 * work, and the allocation attempt will fail.
3215 *
3216 * returns:     0, if no pages reclaimed
3217 *              else, the number of pages reclaimed
3218 */
3219static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3220                                          struct scan_control *sc)
3221{
3222        int initial_priority = sc->priority;
3223        pg_data_t *last_pgdat;
3224        struct zoneref *z;
3225        struct zone *zone;
3226retry:
3227        delayacct_freepages_start();
3228
3229        if (!cgroup_reclaim(sc))
3230                __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
3231
3232        do {
3233                vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
3234                                sc->priority);
3235                sc->nr_scanned = 0;
3236                shrink_zones(zonelist, sc);
3237
3238                if (sc->nr_reclaimed >= sc->nr_to_reclaim)
3239                        break;
3240
3241                if (sc->compaction_ready)
3242                        break;
3243
3244                /*
3245                 * If we're getting trouble reclaiming, start doing
3246                 * writepage even in laptop mode.
3247                 */
3248                if (sc->priority < DEF_PRIORITY - 2)
3249                        sc->may_writepage = 1;
3250        } while (--sc->priority >= 0);
3251
3252        last_pgdat = NULL;
3253        for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
3254                                        sc->nodemask) {
3255                if (zone->zone_pgdat == last_pgdat)
3256                        continue;
3257                last_pgdat = zone->zone_pgdat;
3258
3259                snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3260
3261                if (cgroup_reclaim(sc)) {
3262                        struct lruvec *lruvec;
3263
3264                        lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
3265                                                   zone->zone_pgdat);
3266                        clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3267                }
3268        }
3269
3270        delayacct_freepages_end();
3271
3272        if (sc->nr_reclaimed)
3273                return sc->nr_reclaimed;
3274
3275        /* Aborted reclaim to try compaction? don't OOM, then */
3276        if (sc->compaction_ready)
3277                return 1;
3278
3279        /*
3280         * We make inactive:active ratio decisions based on the node's
3281         * composition of memory, but a restrictive reclaim_idx or a
3282         * memory.low cgroup setting can exempt large amounts of
3283         * memory from reclaim. Neither of which are very common, so
3284         * instead of doing costly eligibility calculations of the
3285         * entire cgroup subtree up front, we assume the estimates are
3286         * good, and retry with forcible deactivation if that fails.
3287         */
3288        if (sc->skipped_deactivate) {
3289                sc->priority = initial_priority;
3290                sc->force_deactivate = 1;
3291                sc->skipped_deactivate = 0;
3292                goto retry;
3293        }
3294
3295        /* Untapped cgroup reserves?  Don't OOM, retry. */
3296        if (sc->memcg_low_skipped) {
3297                sc->priority = initial_priority;
3298                sc->force_deactivate = 0;
3299                sc->memcg_low_reclaim = 1;
3300                sc->memcg_low_skipped = 0;
3301                goto retry;
3302        }
3303
3304        return 0;
3305}
3306
3307static bool allow_direct_reclaim(pg_data_t *pgdat)
3308{
3309        struct zone *zone;
3310        unsigned long pfmemalloc_reserve = 0;
3311        unsigned long free_pages = 0;
3312        int i;
3313        bool wmark_ok;
3314
3315        if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3316                return true;
3317
3318        for (i = 0; i <= ZONE_NORMAL; i++) {
3319                zone = &pgdat->node_zones[i];
3320                if (!managed_zone(zone))
3321                        continue;
3322
3323                if (!zone_reclaimable_pages(zone))
3324                        continue;
3325
3326                pfmemalloc_reserve += min_wmark_pages(zone);
3327                free_pages += zone_page_state(zone, NR_FREE_PAGES);
3328        }
3329
3330        /* If there are no reserves (unexpected config) then do not throttle */
3331        if (!pfmemalloc_reserve)
3332                return true;
3333
3334        wmark_ok = free_pages > pfmemalloc_reserve / 2;
3335
3336        /* kswapd must be awake if processes are being throttled */
3337        if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
3338                if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
3339                        WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
3340
3341                wake_up_interruptible(&pgdat->kswapd_wait);
3342        }
3343
3344        return wmark_ok;
3345}
3346
3347/*
3348 * Throttle direct reclaimers if backing storage is backed by the network
3349 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3350 * depleted. kswapd will continue to make progress and wake the processes
3351 * when the low watermark is reached.
3352 *
3353 * Returns true if a fatal signal was delivered during throttling. If this
3354 * happens, the page allocator should not consider triggering the OOM killer.
3355 */
3356static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
3357                                        nodemask_t *nodemask)
3358{
3359        struct zoneref *z;
3360        struct zone *zone;
3361        pg_data_t *pgdat = NULL;
3362
3363        /*
3364         * Kernel threads should not be throttled as they may be indirectly
3365         * responsible for cleaning pages necessary for reclaim to make forward
3366         * progress. kjournald for example may enter direct reclaim while
3367         * committing a transaction where throttling it could forcing other
3368         * processes to block on log_wait_commit().
3369         */
3370        if (current->flags & PF_KTHREAD)
3371                goto out;
3372
3373        /*
3374         * If a fatal signal is pending, this process should not throttle.
3375         * It should return quickly so it can exit and free its memory
3376         */
3377        if (fatal_signal_pending(current))
3378                goto out;
3379
3380        /*
3381         * Check if the pfmemalloc reserves are ok by finding the first node
3382         * with a usable ZONE_NORMAL or lower zone. The expectation is that
3383         * GFP_KERNEL will be required for allocating network buffers when
3384         * swapping over the network so ZONE_HIGHMEM is unusable.
3385         *
3386         * Throttling is based on the first usable node and throttled processes
3387         * wait on a queue until kswapd makes progress and wakes them. There
3388         * is an affinity then between processes waking up and where reclaim
3389         * progress has been made assuming the process wakes on the same node.
3390         * More importantly, processes running on remote nodes will not compete
3391         * for remote pfmemalloc reserves and processes on different nodes
3392         * should make reasonable progress.
3393         */
3394        for_each_zone_zonelist_nodemask(zone, z, zonelist,
3395                                        gfp_zone(gfp_mask), nodemask) {
3396                if (zone_idx(zone) > ZONE_NORMAL)
3397                        continue;
3398
3399                /* Throttle based on the first usable node */
3400                pgdat = zone->zone_pgdat;
3401                if (allow_direct_reclaim(pgdat))
3402                        goto out;
3403                break;
3404        }
3405
3406        /* If no zone was usable by the allocation flags then do not throttle */
3407        if (!pgdat)
3408                goto out;
3409
3410        /* Account for the throttling */
3411        count_vm_event(PGSCAN_DIRECT_THROTTLE);
3412
3413        /*
3414         * If the caller cannot enter the filesystem, it's possible that it
3415         * is due to the caller holding an FS lock or performing a journal
3416         * transaction in the case of a filesystem like ext[3|4]. In this case,
3417         * it is not safe to block on pfmemalloc_wait as kswapd could be
3418         * blocked waiting on the same lock. Instead, throttle for up to a
3419         * second before continuing.
3420         */
3421        if (!(gfp_mask & __GFP_FS)) {
3422                wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3423                        allow_direct_reclaim(pgdat), HZ);
3424
3425                goto check_pending;
3426        }
3427
3428        /* Throttle until kswapd wakes the process */
3429        wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3430                allow_direct_reclaim(pgdat));
3431
3432check_pending:
3433        if (fatal_signal_pending(current))
3434                return true;
3435
3436out:
3437        return false;
3438}
3439
3440unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3441                                gfp_t gfp_mask, nodemask_t *nodemask)
3442{
3443        unsigned long nr_reclaimed;
3444        struct scan_control sc = {
3445                .nr_to_reclaim = SWAP_CLUSTER_MAX,
3446                .gfp_mask = current_gfp_context(gfp_mask),
3447                .reclaim_idx = gfp_zone(gfp_mask),
3448                .order = order,
3449                .nodemask = nodemask,
3450                .priority = DEF_PRIORITY,
3451                .may_writepage = !laptop_mode,
3452                .may_unmap = 1,
3453                .may_swap = 1,
3454        };
3455
3456        /*
3457         * scan_control uses s8 fields for order, priority, and reclaim_idx.
3458         * Confirm they are large enough for max values.
3459         */
3460        BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3461        BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3462        BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3463
3464        /*
3465         * Do not enter reclaim if fatal signal was delivered while throttled.
3466         * 1 is returned so that the page allocator does not OOM kill at this
3467         * point.
3468         */
3469        if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
3470                return 1;
3471
3472        set_task_reclaim_state(current, &sc.reclaim_state);
3473        trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
3474
3475        nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3476
3477        trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
3478        set_task_reclaim_state(current, NULL);
3479
3480        return nr_reclaimed;
3481}
3482
3483#ifdef CONFIG_MEMCG
3484
3485/* Only used by soft limit reclaim. Do not reuse for anything else. */
3486unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
3487                                                gfp_t gfp_mask, bool noswap,
3488                                                pg_data_t *pgdat,
3489                                                unsigned long *nr_scanned)
3490{
3491        struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3492        struct scan_control sc = {
3493                .nr_to_reclaim = SWAP_CLUSTER_MAX,
3494                .target_mem_cgroup = memcg,
3495                .may_writepage = !laptop_mode,
3496                .may_unmap = 1,
3497                .reclaim_idx = MAX_NR_ZONES - 1,
3498                .may_swap = !noswap,
3499        };
3500
3501        WARN_ON_ONCE(!current->reclaim_state);
3502
3503        sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3504                        (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3505
3506        trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3507                                                      sc.gfp_mask);
3508
3509        /*
3510         * NOTE: Although we can get the priority field, using it
3511         * here is not a good idea, since it limits the pages we can scan.
3512         * if we don't reclaim here, the shrink_node from balance_pgdat
3513         * will pick up pages from other mem cgroup's as well. We hack
3514         * the priority and make it zero.
3515         */
3516        shrink_lruvec(lruvec, &sc);
3517
3518        trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3519
3520        *nr_scanned = sc.nr_scanned;
3521
3522        return sc.nr_reclaimed;
3523}
3524
3525unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3526                                           unsigned long nr_pages,
3527                                           gfp_t gfp_mask,
3528                                           bool may_swap)
3529{
3530        unsigned long nr_reclaimed;
3531        unsigned int noreclaim_flag;
3532        struct scan_control sc = {
3533                .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3534                .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3535                                (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3536                .reclaim_idx = MAX_NR_ZONES - 1,
3537                .target_mem_cgroup = memcg,
3538                .priority = DEF_PRIORITY,
3539                .may_writepage = !laptop_mode,
3540                .may_unmap = 1,
3541                .may_swap = may_swap,
3542        };
3543        /*
3544         * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3545         * equal pressure on all the nodes. This is based on the assumption that
3546         * the reclaim does not bail out early.
3547         */
3548        struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
3549
3550        set_task_reclaim_state(current, &sc.reclaim_state);
3551        trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3552        noreclaim_flag = memalloc_noreclaim_save();
3553
3554        nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3555
3556        memalloc_noreclaim_restore(noreclaim_flag);
3557        trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3558        set_task_reclaim_state(current, NULL);
3559
3560        return nr_reclaimed;
3561}
3562#endif
3563
3564static void age_active_anon(struct pglist_data *pgdat,
3565                                struct scan_control *sc)
3566{
3567        struct mem_cgroup *memcg;
3568        struct lruvec *lruvec;
3569
3570        if (!total_swap_pages)
3571                return;
3572
3573        lruvec = mem_cgroup_lruvec(NULL, pgdat);
3574        if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3575                return;
3576
3577        memcg = mem_cgroup_iter(NULL, NULL, NULL);
3578        do {
3579                lruvec = mem_cgroup_lruvec(memcg, pgdat);
3580                shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3581                                   sc, LRU_ACTIVE_ANON);
3582                memcg = mem_cgroup_iter(NULL, memcg, NULL);
3583        } while (memcg);
3584}
3585
3586static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
3587{
3588        int i;
3589        struct zone *zone;
3590
3591        /*
3592         * Check for watermark boosts top-down as the higher zones
3593         * are more likely to be boosted. Both watermarks and boosts
3594         * should not be checked at the same time as reclaim would
3595         * start prematurely when there is no boosting and a lower
3596         * zone is balanced.
3597         */
3598        for (i = highest_zoneidx; i >= 0; i--) {
3599                zone = pgdat->node_zones + i;
3600                if (!managed_zone(zone))
3601                        continue;
3602
3603                if (zone->watermark_boost)
3604                        return true;
3605        }
3606
3607        return false;
3608}
3609
3610/*
3611 * Returns true if there is an eligible zone balanced for the request order
3612 * and highest_zoneidx
3613 */
3614static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
3615{
3616        int i;
3617        unsigned long mark = -1;
3618        struct zone *zone;
3619
3620        /*
3621         * Check watermarks bottom-up as lower zones are more likely to
3622         * meet watermarks.
3623         */
3624        for (i = 0; i <= highest_zoneidx; i++) {
3625                zone = pgdat->node_zones + i;
3626
3627                if (!managed_zone(zone))
3628                        continue;
3629
3630                mark = high_wmark_pages(zone);
3631                if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
3632                        return true;
3633        }
3634
3635        /*
3636         * If a node has no populated zone within highest_zoneidx, it does not
3637         * need balancing by definition. This can happen if a zone-restricted
3638         * allocation tries to wake a remote kswapd.
3639         */
3640        if (mark == -1)
3641                return true;
3642
3643        return false;
3644}
3645
3646/* Clear pgdat state for congested, dirty or under writeback. */
3647static void clear_pgdat_congested(pg_data_t *pgdat)
3648{
3649        struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
3650
3651        clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3652        clear_bit(PGDAT_DIRTY, &pgdat->flags);
3653        clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3654}
3655
3656/*
3657 * Prepare kswapd for sleeping. This verifies that there are no processes
3658 * waiting in throttle_direct_reclaim() and that watermarks have been met.
3659 *
3660 * Returns true if kswapd is ready to sleep
3661 */
3662static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
3663                                int highest_zoneidx)
3664{
3665        /*
3666         * The throttled processes are normally woken up in balance_pgdat() as
3667         * soon as allow_direct_reclaim() is true. But there is a potential
3668         * race between when kswapd checks the watermarks and a process gets
3669         * throttled. There is also a potential race if processes get
3670         * throttled, kswapd wakes, a large process exits thereby balancing the
3671         * zones, which causes kswapd to exit balance_pgdat() before reaching
3672         * the wake up checks. If kswapd is going to sleep, no process should
3673         * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
3674         * the wake up is premature, processes will wake kswapd and get
3675         * throttled again. The difference from wake ups in balance_pgdat() is
3676         * that here we are under prepare_to_wait().
3677         */
3678        if (waitqueue_active(&pgdat->pfmemalloc_wait))
3679                wake_up_all(&pgdat->pfmemalloc_wait);
3680
3681        /* Hopeless node, leave it to direct reclaim */
3682        if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3683                return true;
3684
3685        if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3686                clear_pgdat_congested(pgdat);
3687                return true;
3688        }
3689
3690        return false;
3691}
3692
3693/*
3694 * kswapd shrinks a node of pages that are at or below the highest usable
3695 * zone that is currently unbalanced.
3696 *
3697 * Returns true if kswapd scanned at least the requested number of pages to
3698 * reclaim or if the lack of progress was due to pages under writeback.
3699 * This is used to determine if the scanning priority needs to be raised.
3700 */
3701static bool kswapd_shrink_node(pg_data_t *pgdat,
3702                               struct scan_control *sc)
3703{
3704        struct zone *zone;
3705        int z;
3706
3707        /* Reclaim a number of pages proportional to the number of zones */
3708        sc->nr_to_reclaim = 0;
3709        for (z = 0; z <= sc->reclaim_idx; z++) {
3710                zone = pgdat->node_zones + z;
3711                if (!managed_zone(zone))
3712                        continue;
3713
3714                sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
3715        }
3716
3717        /*
3718         * Historically care was taken to put equal pressure on all zones but
3719         * now pressure is applied based on node LRU order.
3720         */
3721        shrink_node(pgdat, sc);
3722
3723        /*
3724         * Fragmentation may mean that the system cannot be rebalanced for
3725         * high-order allocations. If twice the allocation size has been
3726         * reclaimed then recheck watermarks only at order-0 to prevent
3727         * excessive reclaim. Assume that a process requested a high-order
3728         * can direct reclaim/compact.
3729         */
3730        if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
3731                sc->order = 0;
3732
3733        return sc->nr_scanned >= sc->nr_to_reclaim;
3734}
3735
3736/*
3737 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
3738 * that are eligible for use by the caller until at least one zone is
3739 * balanced.
3740 *
3741 * Returns the order kswapd finished reclaiming at.
3742 *
3743 * kswapd scans the zones in the highmem->normal->dma direction.  It skips
3744 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
3745 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
3746 * or lower is eligible for reclaim until at least one usable zone is
3747 * balanced.
3748 */
3749static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
3750{
3751        int i;
3752        unsigned long nr_soft_reclaimed;
3753        unsigned long nr_soft_scanned;
3754        unsigned long pflags;
3755        unsigned long nr_boost_reclaim;
3756        unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
3757        bool boosted;
3758        struct zone *zone;
3759        struct scan_control sc = {
3760                .gfp_mask = GFP_KERNEL,
3761                .order = order,
3762                .may_unmap = 1,
3763        };
3764
3765        set_task_reclaim_state(current, &sc.reclaim_state);
3766        psi_memstall_enter(&pflags);
3767        __fs_reclaim_acquire();
3768
3769        count_vm_event(PAGEOUTRUN);
3770
3771        /*
3772         * Account for the reclaim boost. Note that the zone boost is left in
3773         * place so that parallel allocations that are near the watermark will
3774         * stall or direct reclaim until kswapd is finished.
3775         */
3776        nr_boost_reclaim = 0;
3777        for (i = 0; i <= highest_zoneidx; i++) {
3778                zone = pgdat->node_zones + i;
3779                if (!managed_zone(zone))
3780                        continue;
3781
3782                nr_boost_reclaim += zone->watermark_boost;
3783                zone_boosts[i] = zone->watermark_boost;
3784        }
3785        boosted = nr_boost_reclaim;
3786
3787restart:
3788        sc.priority = DEF_PRIORITY;
3789        do {
3790                unsigned long nr_reclaimed = sc.nr_reclaimed;
3791                bool raise_priority = true;
3792                bool balanced;
3793                bool ret;
3794
3795                sc.reclaim_idx = highest_zoneidx;
3796
3797                /*
3798                 * If the number of buffer_heads exceeds the maximum allowed
3799                 * then consider reclaiming from all zones. This has a dual
3800                 * purpose -- on 64-bit systems it is expected that
3801                 * buffer_heads are stripped during active rotation. On 32-bit
3802                 * systems, highmem pages can pin lowmem memory and shrinking
3803                 * buffers can relieve lowmem pressure. Reclaim may still not
3804                 * go ahead if all eligible zones for the original allocation
3805                 * request are balanced to avoid excessive reclaim from kswapd.
3806                 */
3807                if (buffer_heads_over_limit) {
3808                        for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
3809                                zone = pgdat->node_zones + i;
3810                                if (!managed_zone(zone))
3811                                        continue;
3812
3813                                sc.reclaim_idx = i;
3814                                break;
3815                        }
3816                }
3817
3818                /*
3819                 * If the pgdat is imbalanced then ignore boosting and preserve
3820                 * the watermarks for a later time and restart. Note that the
3821                 * zone watermarks will be still reset at the end of balancing
3822                 * on the grounds that the normal reclaim should be enough to
3823                 * re-evaluate if boosting is required when kswapd next wakes.
3824                 */
3825                balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
3826                if (!balanced && nr_boost_reclaim) {
3827                        nr_boost_reclaim = 0;
3828                        goto restart;
3829                }
3830
3831                /*
3832                 * If boosting is not active then only reclaim if there are no
3833                 * eligible zones. Note that sc.reclaim_idx is not used as
3834                 * buffer_heads_over_limit may have adjusted it.
3835                 */
3836                if (!nr_boost_reclaim && balanced)
3837                        goto out;
3838
3839                /* Limit the priority of boosting to avoid reclaim writeback */
3840                if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
3841                        raise_priority = false;
3842
3843                /*
3844                 * Do not writeback or swap pages for boosted reclaim. The
3845                 * intent is to relieve pressure not issue sub-optimal IO
3846                 * from reclaim context. If no pages are reclaimed, the
3847                 * reclaim will be aborted.
3848                 */
3849                sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
3850                sc.may_swap = !nr_boost_reclaim;
3851
3852                /*
3853                 * Do some background aging of the anon list, to give
3854                 * pages a chance to be referenced before reclaiming. All
3855                 * pages are rotated regardless of classzone as this is
3856                 * about consistent aging.
3857                 */
3858                age_active_anon(pgdat, &sc);
3859
3860                /*
3861                 * If we're getting trouble reclaiming, start doing writepage
3862                 * even in laptop mode.
3863                 */
3864                if (sc.priority < DEF_PRIORITY - 2)
3865                        sc.may_writepage = 1;
3866
3867                /* Call soft limit reclaim before calling shrink_node. */
3868                sc.nr_scanned = 0;
3869                nr_soft_scanned = 0;
3870                nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
3871                                                sc.gfp_mask, &nr_soft_scanned);
3872                sc.nr_reclaimed += nr_soft_reclaimed;
3873
3874                /*
3875                 * There should be no need to raise the scanning priority if
3876                 * enough pages are already being scanned that that high
3877                 * watermark would be met at 100% efficiency.
3878                 */
3879                if (kswapd_shrink_node(pgdat, &sc))
3880                        raise_priority = false;
3881
3882                /*
3883                 * If the low watermark is met there is no need for processes
3884                 * to be throttled on pfmemalloc_wait as they should not be
3885                 * able to safely make forward progress. Wake them
3886                 */
3887                if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3888                                allow_direct_reclaim(pgdat))
3889                        wake_up_all(&pgdat->pfmemalloc_wait);
3890
3891                /* Check if kswapd should be suspending */
3892                __fs_reclaim_release();
3893                ret = try_to_freeze();
3894                __fs_reclaim_acquire();
3895                if (ret || kthread_should_stop())
3896                        break;
3897
3898                /*
3899                 * Raise priority if scanning rate is too low or there was no
3900                 * progress in reclaiming pages
3901                 */
3902                nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3903                nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
3904
3905                /*
3906                 * If reclaim made no progress for a boost, stop reclaim as
3907                 * IO cannot be queued and it could be an infinite loop in
3908                 * extreme circumstances.
3909                 */
3910                if (nr_boost_reclaim && !nr_reclaimed)
3911                        break;
3912
3913                if (raise_priority || !nr_reclaimed)
3914                        sc.priority--;
3915        } while (sc.priority >= 1);
3916
3917        if (!sc.nr_reclaimed)
3918                pgdat->kswapd_failures++;
3919
3920out:
3921        /* If reclaim was boosted, account for the reclaim done in this pass */
3922        if (boosted) {
3923                unsigned long flags;
3924
3925                for (i = 0; i <= highest_zoneidx; i++) {
3926                        if (!zone_boosts[i])
3927                                continue;
3928
3929                        /* Increments are under the zone lock */
3930                        zone = pgdat->node_zones + i;
3931                        spin_lock_irqsave(&zone->lock, flags);
3932                        zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
3933                        spin_unlock_irqrestore(&zone->lock, flags);
3934                }
3935
3936                /*
3937                 * As there is now likely space, wakeup kcompact to defragment
3938                 * pageblocks.
3939                 */
3940                wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
3941        }
3942
3943        snapshot_refaults(NULL, pgdat);
3944        __fs_reclaim_release();
3945        psi_memstall_leave(&pflags);
3946        set_task_reclaim_state(current, NULL);
3947
3948        /*
3949         * Return the order kswapd stopped reclaiming at as
3950         * prepare_kswapd_sleep() takes it into account. If another caller
3951         * entered the allocator slow path while kswapd was awake, order will
3952         * remain at the higher level.
3953         */
3954        return sc.order;
3955}
3956
3957/*
3958 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
3959 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
3960 * not a valid index then either kswapd runs for first time or kswapd couldn't
3961 * sleep after previous reclaim attempt (node is still unbalanced). In that
3962 * case return the zone index of the previous kswapd reclaim cycle.
3963 */
3964static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
3965                                           enum zone_type prev_highest_zoneidx)
3966{
3967        enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
3968
3969        return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
3970}
3971
3972static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
3973                                unsigned int highest_zoneidx)
3974{
3975        long remaining = 0;
3976        DEFINE_WAIT(wait);
3977
3978        if (freezing(current) || kthread_should_stop())
3979                return;
3980
3981        prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3982
3983        /*
3984         * Try to sleep for a short interval. Note that kcompactd will only be
3985         * woken if it is possible to sleep for a short interval. This is
3986         * deliberate on the assumption that if reclaim cannot keep an
3987         * eligible zone balanced that it's also unlikely that compaction will
3988         * succeed.
3989         */
3990        if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3991                /*
3992                 * Compaction records what page blocks it recently failed to
3993                 * isolate pages from and skips them in the future scanning.
3994                 * When kswapd is going to sleep, it is reasonable to assume
3995                 * that pages and compaction may succeed so reset the cache.
3996                 */
3997                reset_isolation_suitable(pgdat);
3998
3999                /*
4000                 * We have freed the memory, now we should compact it to make
4001                 * allocation of the requested order possible.
4002                 */
4003                wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
4004
4005                remaining = schedule_timeout(HZ/10);
4006
4007                /*
4008                 * If woken prematurely then reset kswapd_highest_zoneidx and
4009                 * order. The values will either be from a wakeup request or
4010                 * the previous request that slept prematurely.
4011                 */
4012                if (remaining) {
4013                        WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
4014                                        kswapd_highest_zoneidx(pgdat,
4015                                                        highest_zoneidx));
4016
4017                        if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
4018                                WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
4019                }
4020
4021                finish_wait(&pgdat->kswapd_wait, &wait);
4022                prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4023        }
4024
4025        /*
4026         * After a short sleep, check if it was a premature sleep. If not, then
4027         * go fully to sleep until explicitly woken up.
4028         */
4029        if (!remaining &&
4030            prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4031                trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4032
4033                /*
4034                 * vmstat counters are not perfectly accurate and the estimated
4035                 * value for counters such as NR_FREE_PAGES can deviate from the
4036                 * true value by nr_online_cpus * threshold. To avoid the zone
4037                 * watermarks being breached while under pressure, we reduce the
4038                 * per-cpu vmstat threshold while kswapd is awake and restore
4039                 * them before going back to sleep.
4040                 */
4041                set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
4042
4043                if (!kthread_should_stop())
4044                        schedule();
4045
4046                set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4047        } else {
4048                if (remaining)
4049                        count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4050                else
4051                        count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4052        }
4053        finish_wait(&pgdat->kswapd_wait, &wait);
4054}
4055
4056/*
4057 * The background pageout daemon, started as a kernel thread
4058 * from the init process.
4059 *
4060 * This basically trickles out pages so that we have _some_
4061 * free memory available even if there is no other activity
4062 * that frees anything up. This is needed for things like routing
4063 * etc, where we otherwise might have all activity going on in
4064 * asynchronous contexts that cannot page things out.
4065 *
4066 * If there are applications that are active memory-allocators
4067 * (most normal use), this basically shouldn't matter.
4068 */
4069static int kswapd(void *p)
4070{
4071        unsigned int alloc_order, reclaim_order;
4072        unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
4073        pg_data_t *pgdat = (pg_data_t *)p;
4074        struct task_struct *tsk = current;
4075        const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
4076
4077        if (!cpumask_empty(cpumask))
4078                set_cpus_allowed_ptr(tsk, cpumask);
4079
4080        /*
4081         * Tell the memory management that we're a "memory allocator",
4082         * and that if we need more memory we should get access to it
4083         * regardless (see "__alloc_pages()"). "kswapd" should
4084         * never get caught in the normal page freeing logic.
4085         *
4086         * (Kswapd normally doesn't need memory anyway, but sometimes
4087         * you need a small amount of memory in order to be able to
4088         * page out something else, and this flag essentially protects
4089         * us from recursively trying to free more memory as we're
4090         * trying to free the first piece of memory in the first place).
4091         */
4092        tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
4093        set_freezable();
4094
4095        WRITE_ONCE(pgdat->kswapd_order, 0);
4096        WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
4097        for ( ; ; ) {
4098                bool ret;
4099
4100                alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
4101                highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4102                                                        highest_zoneidx);
4103
4104kswapd_try_sleep:
4105                kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
4106                                        highest_zoneidx);
4107
4108                /* Read the new order and highest_zoneidx */
4109                alloc_order = READ_ONCE(pgdat->kswapd_order);
4110                highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4111                                                        highest_zoneidx);
4112                WRITE_ONCE(pgdat->kswapd_order, 0);
4113                WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
4114
4115                ret = try_to_freeze();
4116                if (kthread_should_stop())
4117                        break;
4118
4119                /*
4120                 * We can speed up thawing tasks if we don't call balance_pgdat
4121                 * after returning from the refrigerator
4122                 */
4123                if (ret)
4124                        continue;
4125
4126                /*
4127                 * Reclaim begins at the requested order but if a high-order
4128                 * reclaim fails then kswapd falls back to reclaiming for
4129                 * order-0. If that happens, kswapd will consider sleeping
4130                 * for the order it finished reclaiming at (reclaim_order)
4131                 * but kcompactd is woken to compact for the original
4132                 * request (alloc_order).
4133                 */
4134                trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4135                                                alloc_order);
4136                reclaim_order = balance_pgdat(pgdat, alloc_order,
4137                                                highest_zoneidx);
4138                if (reclaim_order < alloc_order)
4139                        goto kswapd_try_sleep;
4140        }
4141
4142        tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
4143
4144        return 0;
4145}
4146
4147/*
4148 * A zone is low on free memory or too fragmented for high-order memory.  If
4149 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
4150 * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
4151 * has failed or is not needed, still wake up kcompactd if only compaction is
4152 * needed.
4153 */
4154void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
4155                   enum zone_type highest_zoneidx)
4156{
4157        pg_data_t *pgdat;
4158        enum zone_type curr_idx;
4159
4160        if (!managed_zone(zone))
4161                return;
4162
4163        if (!cpuset_zone_allowed(zone, gfp_flags))
4164                return;
4165
4166        pgdat = zone->zone_pgdat;
4167        curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
4168
4169        if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
4170                WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
4171
4172        if (READ_ONCE(pgdat->kswapd_order) < order)
4173                WRITE_ONCE(pgdat->kswapd_order, order);
4174
4175        if (!waitqueue_active(&pgdat->kswapd_wait))
4176                return;
4177
4178        /* Hopeless node, leave it to direct reclaim if possible */
4179        if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
4180            (pgdat_balanced(pgdat, order, highest_zoneidx) &&
4181             !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
4182                /*
4183                 * There may be plenty of free memory available, but it's too
4184                 * fragmented for high-order allocations.  Wake up kcompactd
4185                 * and rely on compaction_suitable() to determine if it's
4186                 * needed.  If it fails, it will defer subsequent attempts to
4187                 * ratelimit its work.
4188                 */
4189                if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
4190                        wakeup_kcompactd(pgdat, order, highest_zoneidx);
4191                return;
4192        }
4193
4194        trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
4195                                      gfp_flags);
4196        wake_up_interruptible(&pgdat->kswapd_wait);
4197}
4198
4199#ifdef CONFIG_HIBERNATION
4200/*
4201 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4202 * freed pages.
4203 *
4204 * Rather than trying to age LRUs the aim is to preserve the overall
4205 * LRU order by reclaiming preferentially
4206 * inactive > active > active referenced > active mapped
4207 */
4208unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
4209{
4210        struct scan_control sc = {
4211                .nr_to_reclaim = nr_to_reclaim,
4212                .gfp_mask = GFP_HIGHUSER_MOVABLE,
4213                .reclaim_idx = MAX_NR_ZONES - 1,
4214                .priority = DEF_PRIORITY,
4215                .may_writepage = 1,
4216                .may_unmap = 1,
4217                .may_swap = 1,
4218                .hibernation_mode = 1,
4219        };
4220        struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
4221        unsigned long nr_reclaimed;
4222        unsigned int noreclaim_flag;
4223
4224        fs_reclaim_acquire(sc.gfp_mask);
4225        noreclaim_flag = memalloc_noreclaim_save();
4226        set_task_reclaim_state(current, &sc.reclaim_state);
4227
4228        nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4229
4230        set_task_reclaim_state(current, NULL);
4231        memalloc_noreclaim_restore(noreclaim_flag);
4232        fs_reclaim_release(sc.gfp_mask);
4233
4234        return nr_reclaimed;
4235}
4236#endif /* CONFIG_HIBERNATION */
4237
4238/*
4239 * This kswapd start function will be called by init and node-hot-add.
4240 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
4241 */
4242int kswapd_run(int nid)
4243{
4244        pg_data_t *pgdat = NODE_DATA(nid);
4245        int ret = 0;
4246
4247        if (pgdat->kswapd)
4248                return 0;
4249
4250        pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
4251        if (IS_ERR(pgdat->kswapd)) {
4252                /* failure at boot is fatal */
4253                BUG_ON(system_state < SYSTEM_RUNNING);
4254                pr_err("Failed to start kswapd on node %d\n", nid);
4255                ret = PTR_ERR(pgdat->kswapd);
4256                pgdat->kswapd = NULL;
4257        }
4258        return ret;
4259}
4260
4261/*
4262 * Called by memory hotplug when all memory in a node is offlined.  Caller must
4263 * hold mem_hotplug_begin/end().
4264 */
4265void kswapd_stop(int nid)
4266{
4267        struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
4268
4269        if (kswapd) {
4270                kthread_stop(kswapd);
4271                NODE_DATA(nid)->kswapd = NULL;
4272        }
4273}
4274
4275static int __init kswapd_init(void)
4276{
4277        int nid;
4278
4279        swap_setup();
4280        for_each_node_state(nid, N_MEMORY)
4281                kswapd_run(nid);
4282        return 0;
4283}
4284
4285module_init(kswapd_init)
4286
4287#ifdef CONFIG_NUMA
4288/*
4289 * Node reclaim mode
4290 *
4291 * If non-zero call node_reclaim when the number of free pages falls below
4292 * the watermarks.
4293 */
4294int node_reclaim_mode __read_mostly;
4295
4296/*
4297 * Priority for NODE_RECLAIM. This determines the fraction of pages
4298 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4299 * a zone.
4300 */
4301#define NODE_RECLAIM_PRIORITY 4
4302
4303/*
4304 * Percentage of pages in a zone that must be unmapped for node_reclaim to
4305 * occur.
4306 */
4307int sysctl_min_unmapped_ratio = 1;
4308
4309/*
4310 * If the number of slab pages in a zone grows beyond this percentage then
4311 * slab reclaim needs to occur.
4312 */
4313int sysctl_min_slab_ratio = 5;
4314
4315static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
4316{
4317        unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
4318        unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
4319                node_page_state(pgdat, NR_ACTIVE_FILE);
4320
4321        /*
4322         * It's possible for there to be more file mapped pages than
4323         * accounted for by the pages on the file LRU lists because
4324         * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4325         */
4326        return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
4327}
4328
4329/* Work out how many page cache pages we can reclaim in this reclaim_mode */
4330static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
4331{
4332        unsigned long nr_pagecache_reclaimable;
4333        unsigned long delta = 0;
4334
4335        /*
4336         * If RECLAIM_UNMAP is set, then all file pages are considered
4337         * potentially reclaimable. Otherwise, we have to worry about
4338         * pages like swapcache and node_unmapped_file_pages() provides
4339         * a better estimate
4340         */
4341        if (node_reclaim_mode & RECLAIM_UNMAP)
4342                nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
4343        else
4344                nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
4345
4346        /* If we can't clean pages, remove dirty pages from consideration */
4347        if (!(node_reclaim_mode & RECLAIM_WRITE))
4348                delta += node_page_state(pgdat, NR_FILE_DIRTY);
4349
4350        /* Watch for any possible underflows due to delta */
4351        if (unlikely(delta > nr_pagecache_reclaimable))
4352                delta = nr_pagecache_reclaimable;
4353
4354        return nr_pagecache_reclaimable - delta;
4355}
4356
4357/*
4358 * Try to free up some pages from this node through reclaim.
4359 */
4360static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4361{
4362        /* Minimum pages needed in order to stay on node */
4363        const unsigned long nr_pages = 1 << order;
4364        struct task_struct *p = current;
4365        unsigned int noreclaim_flag;
4366        struct scan_control sc = {
4367                .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4368                .gfp_mask = current_gfp_context(gfp_mask),
4369                .order = order,
4370                .priority = NODE_RECLAIM_PRIORITY,
4371                .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4372                .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4373                .may_swap = 1,
4374                .reclaim_idx = gfp_zone(gfp_mask),
4375        };
4376
4377        trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4378                                           sc.gfp_mask);
4379
4380        cond_resched();
4381        fs_reclaim_acquire(sc.gfp_mask);
4382        /*
4383         * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4384         * and we also need to be able to write out pages for RECLAIM_WRITE
4385         * and RECLAIM_UNMAP.
4386         */
4387        noreclaim_flag = memalloc_noreclaim_save();
4388        p->flags |= PF_SWAPWRITE;
4389        set_task_reclaim_state(p, &sc.reclaim_state);
4390
4391        if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4392                /*
4393                 * Free memory by calling shrink node with increasing
4394                 * priorities until we have enough memory freed.
4395                 */
4396                do {
4397                        shrink_node(pgdat, &sc);
4398                } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
4399        }
4400
4401        set_task_reclaim_state(p, NULL);
4402        current->flags &= ~PF_SWAPWRITE;
4403        memalloc_noreclaim_restore(noreclaim_flag);
4404        fs_reclaim_release(sc.gfp_mask);
4405
4406        trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4407
4408        return sc.nr_reclaimed >= nr_pages;
4409}
4410
4411int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4412{
4413        int ret;
4414
4415        /*
4416         * Node reclaim reclaims unmapped file backed pages and
4417         * slab pages if we are over the defined limits.
4418         *
4419         * A small portion of unmapped file backed pages is needed for
4420         * file I/O otherwise pages read by file I/O will be immediately
4421         * thrown out if the node is overallocated. So we do not reclaim
4422         * if less than a specified percentage of the node is used by
4423         * unmapped file backed pages.
4424         */
4425        if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4426            node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4427            pgdat->min_slab_pages)
4428                return NODE_RECLAIM_FULL;
4429
4430        /*
4431         * Do not scan if the allocation should not be delayed.
4432         */
4433        if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4434                return NODE_RECLAIM_NOSCAN;
4435
4436        /*
4437         * Only run node reclaim on the local node or on nodes that do not
4438         * have associated processors. This will favor the local processor
4439         * over remote processors and spread off node memory allocations
4440         * as wide as possible.
4441         */
4442        if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4443                return NODE_RECLAIM_NOSCAN;
4444
4445        if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4446                return NODE_RECLAIM_NOSCAN;
4447
4448        ret = __node_reclaim(pgdat, gfp_mask, order);
4449        clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4450
4451        if (!ret)
4452                count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
4453
4454        return ret;
4455}
4456#endif
4457
4458/**
4459 * check_move_unevictable_pages - check pages for evictability and move to
4460 * appropriate zone lru list
4461 * @pvec: pagevec with lru pages to check
4462 *
4463 * Checks pages for evictability, if an evictable page is in the unevictable
4464 * lru list, moves it to the appropriate evictable lru list. This function
4465 * should be only used for lru pages.
4466 */
4467void check_move_unevictable_pages(struct pagevec *pvec)
4468{
4469        struct lruvec *lruvec = NULL;
4470        int pgscanned = 0;
4471        int pgrescued = 0;
4472        int i;
4473
4474        for (i = 0; i < pvec->nr; i++) {
4475                struct page *page = pvec->pages[i];
4476                int nr_pages;
4477
4478                if (PageTransTail(page))
4479                        continue;
4480
4481                nr_pages = thp_nr_pages(page);
4482                pgscanned += nr_pages;
4483
4484                /* block memcg migration during page moving between lru */
4485                if (!TestClearPageLRU(page))
4486                        continue;
4487
4488                lruvec = relock_page_lruvec_irq(page, lruvec);
4489                if (page_evictable(page) && PageUnevictable(page)) {
4490                        del_page_from_lru_list(page, lruvec);
4491                        ClearPageUnevictable(page);
4492                        add_page_to_lru_list(page, lruvec);
4493                        pgrescued += nr_pages;
4494                }
4495                SetPageLRU(page);
4496        }
4497
4498        if (lruvec) {
4499                __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
4500                __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4501                unlock_page_lruvec_irq(lruvec);
4502        } else if (pgscanned) {
4503                count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4504        }
4505}
4506EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4507