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