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