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