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