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