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