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