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