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