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