xref: /linux/mm/workingset.c (revision 5a4d8944)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2a528910eSJohannes Weiner /*
3a528910eSJohannes Weiner  * Workingset detection
4a528910eSJohannes Weiner  *
5a528910eSJohannes Weiner  * Copyright (C) 2013 Red Hat, Inc., Johannes Weiner
6a528910eSJohannes Weiner  */
7a528910eSJohannes Weiner 
8a528910eSJohannes Weiner #include <linux/memcontrol.h>
9170b04b7SJoonsoo Kim #include <linux/mm_inline.h>
10a528910eSJohannes Weiner #include <linux/writeback.h>
113a4f8a0bSHugh Dickins #include <linux/shmem_fs.h>
12a528910eSJohannes Weiner #include <linux/pagemap.h>
13a528910eSJohannes Weiner #include <linux/atomic.h>
14a528910eSJohannes Weiner #include <linux/module.h>
15a528910eSJohannes Weiner #include <linux/swap.h>
1614b46879SJohannes Weiner #include <linux/dax.h>
17a528910eSJohannes Weiner #include <linux/fs.h>
18a528910eSJohannes Weiner #include <linux/mm.h>
19b64e74e9SChristoph Hellwig #include "internal.h"
20a528910eSJohannes Weiner 
21a528910eSJohannes Weiner /*
22a528910eSJohannes Weiner  *		Double CLOCK lists
23a528910eSJohannes Weiner  *
241e6b1085SMel Gorman  * Per node, two clock lists are maintained for file pages: the
25a528910eSJohannes Weiner  * inactive and the active list.  Freshly faulted pages start out at
26a528910eSJohannes Weiner  * the head of the inactive list and page reclaim scans pages from the
27a528910eSJohannes Weiner  * tail.  Pages that are accessed multiple times on the inactive list
28a528910eSJohannes Weiner  * are promoted to the active list, to protect them from reclaim,
29a528910eSJohannes Weiner  * whereas active pages are demoted to the inactive list when the
30a528910eSJohannes Weiner  * active list grows too big.
31a528910eSJohannes Weiner  *
32a528910eSJohannes Weiner  *   fault ------------------------+
33a528910eSJohannes Weiner  *                                 |
34a528910eSJohannes Weiner  *              +--------------+   |            +-------------+
35a528910eSJohannes Weiner  *   reclaim <- |   inactive   | <-+-- demotion |    active   | <--+
36a528910eSJohannes Weiner  *              +--------------+                +-------------+    |
37a528910eSJohannes Weiner  *                     |                                           |
38a528910eSJohannes Weiner  *                     +-------------- promotion ------------------+
39a528910eSJohannes Weiner  *
40a528910eSJohannes Weiner  *
41a528910eSJohannes Weiner  *		Access frequency and refault distance
42a528910eSJohannes Weiner  *
43a528910eSJohannes Weiner  * A workload is thrashing when its pages are frequently used but they
44a528910eSJohannes Weiner  * are evicted from the inactive list every time before another access
45a528910eSJohannes Weiner  * would have promoted them to the active list.
46a528910eSJohannes Weiner  *
47a528910eSJohannes Weiner  * In cases where the average access distance between thrashing pages
48a528910eSJohannes Weiner  * is bigger than the size of memory there is nothing that can be
49a528910eSJohannes Weiner  * done - the thrashing set could never fit into memory under any
50a528910eSJohannes Weiner  * circumstance.
51a528910eSJohannes Weiner  *
52a528910eSJohannes Weiner  * However, the average access distance could be bigger than the
53a528910eSJohannes Weiner  * inactive list, yet smaller than the size of memory.  In this case,
54a528910eSJohannes Weiner  * the set could fit into memory if it weren't for the currently
55a528910eSJohannes Weiner  * active pages - which may be used more, hopefully less frequently:
56a528910eSJohannes Weiner  *
57a528910eSJohannes Weiner  *      +-memory available to cache-+
58a528910eSJohannes Weiner  *      |                           |
59a528910eSJohannes Weiner  *      +-inactive------+-active----+
60a528910eSJohannes Weiner  *  a b | c d e f g h i | J K L M N |
61a528910eSJohannes Weiner  *      +---------------+-----------+
62a528910eSJohannes Weiner  *
63a528910eSJohannes Weiner  * It is prohibitively expensive to accurately track access frequency
64a528910eSJohannes Weiner  * of pages.  But a reasonable approximation can be made to measure
65a528910eSJohannes Weiner  * thrashing on the inactive list, after which refaulting pages can be
66a528910eSJohannes Weiner  * activated optimistically to compete with the existing active pages.
67a528910eSJohannes Weiner  *
68a528910eSJohannes Weiner  * Approximating inactive page access frequency - Observations:
69a528910eSJohannes Weiner  *
70a528910eSJohannes Weiner  * 1. When a page is accessed for the first time, it is added to the
71a528910eSJohannes Weiner  *    head of the inactive list, slides every existing inactive page
72a528910eSJohannes Weiner  *    towards the tail by one slot, and pushes the current tail page
73a528910eSJohannes Weiner  *    out of memory.
74a528910eSJohannes Weiner  *
75a528910eSJohannes Weiner  * 2. When a page is accessed for the second time, it is promoted to
76a528910eSJohannes Weiner  *    the active list, shrinking the inactive list by one slot.  This
77a528910eSJohannes Weiner  *    also slides all inactive pages that were faulted into the cache
78a528910eSJohannes Weiner  *    more recently than the activated page towards the tail of the
79a528910eSJohannes Weiner  *    inactive list.
80a528910eSJohannes Weiner  *
81a528910eSJohannes Weiner  * Thus:
82a528910eSJohannes Weiner  *
83a528910eSJohannes Weiner  * 1. The sum of evictions and activations between any two points in
84a528910eSJohannes Weiner  *    time indicate the minimum number of inactive pages accessed in
85a528910eSJohannes Weiner  *    between.
86a528910eSJohannes Weiner  *
87a528910eSJohannes Weiner  * 2. Moving one inactive page N page slots towards the tail of the
88a528910eSJohannes Weiner  *    list requires at least N inactive page accesses.
89a528910eSJohannes Weiner  *
90a528910eSJohannes Weiner  * Combining these:
91a528910eSJohannes Weiner  *
92a528910eSJohannes Weiner  * 1. When a page is finally evicted from memory, the number of
93a528910eSJohannes Weiner  *    inactive pages accessed while the page was in cache is at least
94a528910eSJohannes Weiner  *    the number of page slots on the inactive list.
95a528910eSJohannes Weiner  *
96a528910eSJohannes Weiner  * 2. In addition, measuring the sum of evictions and activations (E)
97a528910eSJohannes Weiner  *    at the time of a page's eviction, and comparing it to another
98a528910eSJohannes Weiner  *    reading (R) at the time the page faults back into memory tells
99a528910eSJohannes Weiner  *    the minimum number of accesses while the page was not cached.
100a528910eSJohannes Weiner  *    This is called the refault distance.
101a528910eSJohannes Weiner  *
102a528910eSJohannes Weiner  * Because the first access of the page was the fault and the second
103a528910eSJohannes Weiner  * access the refault, we combine the in-cache distance with the
104a528910eSJohannes Weiner  * out-of-cache distance to get the complete minimum access distance
105a528910eSJohannes Weiner  * of this page:
106a528910eSJohannes Weiner  *
107a528910eSJohannes Weiner  *      NR_inactive + (R - E)
108a528910eSJohannes Weiner  *
109a528910eSJohannes Weiner  * And knowing the minimum access distance of a page, we can easily
110a528910eSJohannes Weiner  * tell if the page would be able to stay in cache assuming all page
111a528910eSJohannes Weiner  * slots in the cache were available:
112a528910eSJohannes Weiner  *
113a528910eSJohannes Weiner  *   NR_inactive + (R - E) <= NR_inactive + NR_active
114a528910eSJohannes Weiner  *
115ed8f3f99SYang Yang  * If we have swap we should consider about NR_inactive_anon and
116ed8f3f99SYang Yang  * NR_active_anon, so for page cache and anonymous respectively:
117a528910eSJohannes Weiner  *
118ed8f3f99SYang Yang  *   NR_inactive_file + (R - E) <= NR_inactive_file + NR_active_file
119ed8f3f99SYang Yang  *   + NR_inactive_anon + NR_active_anon
120ed8f3f99SYang Yang  *
121ed8f3f99SYang Yang  *   NR_inactive_anon + (R - E) <= NR_inactive_anon + NR_active_anon
122ed8f3f99SYang Yang  *   + NR_inactive_file + NR_active_file
123ed8f3f99SYang Yang  *
124ed8f3f99SYang Yang  * Which can be further simplified to:
125ed8f3f99SYang Yang  *
126ed8f3f99SYang Yang  *   (R - E) <= NR_active_file + NR_inactive_anon + NR_active_anon
127ed8f3f99SYang Yang  *
128ed8f3f99SYang Yang  *   (R - E) <= NR_active_anon + NR_inactive_file + NR_active_file
129a528910eSJohannes Weiner  *
130a528910eSJohannes Weiner  * Put into words, the refault distance (out-of-cache) can be seen as
131a528910eSJohannes Weiner  * a deficit in inactive list space (in-cache).  If the inactive list
132a528910eSJohannes Weiner  * had (R - E) more page slots, the page would not have been evicted
133a528910eSJohannes Weiner  * in between accesses, but activated instead.  And on a full system,
134a528910eSJohannes Weiner  * the only thing eating into inactive list space is active pages.
135a528910eSJohannes Weiner  *
136a528910eSJohannes Weiner  *
1371899ad18SJohannes Weiner  *		Refaulting inactive pages
138a528910eSJohannes Weiner  *
139a528910eSJohannes Weiner  * All that is known about the active list is that the pages have been
140a528910eSJohannes Weiner  * accessed more than once in the past.  This means that at any given
141a528910eSJohannes Weiner  * time there is actually a good chance that pages on the active list
142a528910eSJohannes Weiner  * are no longer in active use.
143a528910eSJohannes Weiner  *
144a528910eSJohannes Weiner  * So when a refault distance of (R - E) is observed and there are at
145ed8f3f99SYang Yang  * least (R - E) pages in the userspace workingset, the refaulting page
146ed8f3f99SYang Yang  * is activated optimistically in the hope that (R - E) pages are actually
147a528910eSJohannes Weiner  * used less frequently than the refaulting page - or even not used at
148a528910eSJohannes Weiner  * all anymore.
149a528910eSJohannes Weiner  *
1501899ad18SJohannes Weiner  * That means if inactive cache is refaulting with a suitable refault
1511899ad18SJohannes Weiner  * distance, we assume the cache workingset is transitioning and put
152ed8f3f99SYang Yang  * pressure on the current workingset.
1531899ad18SJohannes Weiner  *
154a528910eSJohannes Weiner  * If this is wrong and demotion kicks in, the pages which are truly
155a528910eSJohannes Weiner  * used more frequently will be reactivated while the less frequently
156a528910eSJohannes Weiner  * used once will be evicted from memory.
157a528910eSJohannes Weiner  *
158a528910eSJohannes Weiner  * But if this is right, the stale pages will be pushed out of memory
159a528910eSJohannes Weiner  * and the used pages get to stay in cache.
160a528910eSJohannes Weiner  *
1611899ad18SJohannes Weiner  *		Refaulting active pages
1621899ad18SJohannes Weiner  *
1631899ad18SJohannes Weiner  * If on the other hand the refaulting pages have recently been
1641899ad18SJohannes Weiner  * deactivated, it means that the active list is no longer protecting
1651899ad18SJohannes Weiner  * actively used cache from reclaim. The cache is NOT transitioning to
1661899ad18SJohannes Weiner  * a different workingset; the existing workingset is thrashing in the
1671899ad18SJohannes Weiner  * space allocated to the page cache.
1681899ad18SJohannes Weiner  *
169a528910eSJohannes Weiner  *
170a528910eSJohannes Weiner  *		Implementation
171a528910eSJohannes Weiner  *
17231d8fcacSJohannes Weiner  * For each node's LRU lists, a counter for inactive evictions and
17331d8fcacSJohannes Weiner  * activations is maintained (node->nonresident_age).
174a528910eSJohannes Weiner  *
175a528910eSJohannes Weiner  * On eviction, a snapshot of this counter (along with some bits to
176a97e7904SMatthew Wilcox  * identify the node) is stored in the now empty page cache
177a528910eSJohannes Weiner  * slot of the evicted page.  This is called a shadow entry.
178a528910eSJohannes Weiner  *
179a528910eSJohannes Weiner  * On cache misses for which there are shadow entries, an eligible
180a528910eSJohannes Weiner  * refault distance will immediately activate the refaulting page.
181a528910eSJohannes Weiner  */
182a528910eSJohannes Weiner 
1833ebc57f4SMiaohe Lin #define WORKINGSET_SHIFT 1
1843159f943SMatthew Wilcox #define EVICTION_SHIFT	((BITS_PER_LONG - BITS_PER_XA_VALUE) +	\
1853ebc57f4SMiaohe Lin 			 WORKINGSET_SHIFT + NODES_SHIFT + \
1863ebc57f4SMiaohe Lin 			 MEM_CGROUP_ID_SHIFT)
187689c94f0SJohannes Weiner #define EVICTION_MASK	(~0UL >> EVICTION_SHIFT)
188689c94f0SJohannes Weiner 
189612e4493SJohannes Weiner /*
190612e4493SJohannes Weiner  * Eviction timestamps need to be able to cover the full range of
191a97e7904SMatthew Wilcox  * actionable refaults. However, bits are tight in the xarray
192612e4493SJohannes Weiner  * entry, and after storing the identifier for the lruvec there might
193612e4493SJohannes Weiner  * not be enough left to represent every single actionable refault. In
194612e4493SJohannes Weiner  * that case, we have to sacrifice granularity for distance, and group
195612e4493SJohannes Weiner  * evictions into coarser buckets by shaving off lower timestamp bits.
196612e4493SJohannes Weiner  */
197612e4493SJohannes Weiner static unsigned int bucket_order __read_mostly;
198612e4493SJohannes Weiner 
pack_shadow(int memcgid,pg_data_t * pgdat,unsigned long eviction,bool workingset)1991899ad18SJohannes Weiner static void *pack_shadow(int memcgid, pg_data_t *pgdat, unsigned long eviction,
2001899ad18SJohannes Weiner 			 bool workingset)
201a528910eSJohannes Weiner {
2023159f943SMatthew Wilcox 	eviction &= EVICTION_MASK;
20323047a96SJohannes Weiner 	eviction = (eviction << MEM_CGROUP_ID_SHIFT) | memcgid;
2041e6b1085SMel Gorman 	eviction = (eviction << NODES_SHIFT) | pgdat->node_id;
2053ebc57f4SMiaohe Lin 	eviction = (eviction << WORKINGSET_SHIFT) | workingset;
206a528910eSJohannes Weiner 
2073159f943SMatthew Wilcox 	return xa_mk_value(eviction);
208a528910eSJohannes Weiner }
209a528910eSJohannes Weiner 
unpack_shadow(void * shadow,int * memcgidp,pg_data_t ** pgdat,unsigned long * evictionp,bool * workingsetp)2101e6b1085SMel Gorman static void unpack_shadow(void *shadow, int *memcgidp, pg_data_t **pgdat,
2111899ad18SJohannes Weiner 			  unsigned long *evictionp, bool *workingsetp)
212a528910eSJohannes Weiner {
2133159f943SMatthew Wilcox 	unsigned long entry = xa_to_value(shadow);
2141e6b1085SMel Gorman 	int memcgid, nid;
2151899ad18SJohannes Weiner 	bool workingset;
216a528910eSJohannes Weiner 
2173ebc57f4SMiaohe Lin 	workingset = entry & ((1UL << WORKINGSET_SHIFT) - 1);
2183ebc57f4SMiaohe Lin 	entry >>= WORKINGSET_SHIFT;
219a528910eSJohannes Weiner 	nid = entry & ((1UL << NODES_SHIFT) - 1);
220a528910eSJohannes Weiner 	entry >>= NODES_SHIFT;
22123047a96SJohannes Weiner 	memcgid = entry & ((1UL << MEM_CGROUP_ID_SHIFT) - 1);
22223047a96SJohannes Weiner 	entry >>= MEM_CGROUP_ID_SHIFT;
223a528910eSJohannes Weiner 
22423047a96SJohannes Weiner 	*memcgidp = memcgid;
2251e6b1085SMel Gorman 	*pgdat = NODE_DATA(nid);
226ac35a490SYu Zhao 	*evictionp = entry;
2271899ad18SJohannes Weiner 	*workingsetp = workingset;
228a528910eSJohannes Weiner }
229a528910eSJohannes Weiner 
230ac35a490SYu Zhao #ifdef CONFIG_LRU_GEN
231ac35a490SYu Zhao 
lru_gen_eviction(struct folio * folio)232ac35a490SYu Zhao static void *lru_gen_eviction(struct folio *folio)
233ac35a490SYu Zhao {
234ac35a490SYu Zhao 	int hist;
235ac35a490SYu Zhao 	unsigned long token;
236ac35a490SYu Zhao 	unsigned long min_seq;
237ac35a490SYu Zhao 	struct lruvec *lruvec;
238391655feSYu Zhao 	struct lru_gen_folio *lrugen;
239ac35a490SYu Zhao 	int type = folio_is_file_lru(folio);
240ac35a490SYu Zhao 	int delta = folio_nr_pages(folio);
241ac35a490SYu Zhao 	int refs = folio_lru_refs(folio);
242ac35a490SYu Zhao 	int tier = lru_tier_from_refs(refs);
243ac35a490SYu Zhao 	struct mem_cgroup *memcg = folio_memcg(folio);
244ac35a490SYu Zhao 	struct pglist_data *pgdat = folio_pgdat(folio);
245ac35a490SYu Zhao 
246ac35a490SYu Zhao 	BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_WIDTH > BITS_PER_LONG - EVICTION_SHIFT);
247ac35a490SYu Zhao 
248ac35a490SYu Zhao 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
249ac35a490SYu Zhao 	lrugen = &lruvec->lrugen;
250ac35a490SYu Zhao 	min_seq = READ_ONCE(lrugen->min_seq[type]);
251ac35a490SYu Zhao 	token = (min_seq << LRU_REFS_WIDTH) | max(refs - 1, 0);
252ac35a490SYu Zhao 
253ac35a490SYu Zhao 	hist = lru_hist_from_seq(min_seq);
254ac35a490SYu Zhao 	atomic_long_add(delta, &lrugen->evicted[hist][type][tier]);
255ac35a490SYu Zhao 
256ac35a490SYu Zhao 	return pack_shadow(mem_cgroup_id(memcg), pgdat, token, refs);
257ac35a490SYu Zhao }
258ac35a490SYu Zhao 
259ffcb5f52SNhat Pham /*
260ffcb5f52SNhat Pham  * Tests if the shadow entry is for a folio that was recently evicted.
261d7f1afd0ST.J. Alumbaugh  * Fills in @lruvec, @token, @workingset with the values unpacked from shadow.
262ffcb5f52SNhat Pham  */
lru_gen_test_recent(void * shadow,bool file,struct lruvec ** lruvec,unsigned long * token,bool * workingset)263d7f1afd0ST.J. Alumbaugh static bool lru_gen_test_recent(void *shadow, bool file, struct lruvec **lruvec,
264d7f1afd0ST.J. Alumbaugh 				unsigned long *token, bool *workingset)
265ffcb5f52SNhat Pham {
266d7f1afd0ST.J. Alumbaugh 	int memcg_id;
267ffcb5f52SNhat Pham 	unsigned long min_seq;
268d7f1afd0ST.J. Alumbaugh 	struct mem_cgroup *memcg;
269d7f1afd0ST.J. Alumbaugh 	struct pglist_data *pgdat;
270ffcb5f52SNhat Pham 
271d7f1afd0ST.J. Alumbaugh 	unpack_shadow(shadow, &memcg_id, &pgdat, token, workingset);
272ffcb5f52SNhat Pham 
273d7f1afd0ST.J. Alumbaugh 	memcg = mem_cgroup_from_id(memcg_id);
274d7f1afd0ST.J. Alumbaugh 	*lruvec = mem_cgroup_lruvec(memcg, pgdat);
275ffcb5f52SNhat Pham 
276d7f1afd0ST.J. Alumbaugh 	min_seq = READ_ONCE((*lruvec)->lrugen.min_seq[file]);
277ffcb5f52SNhat Pham 	return (*token >> LRU_REFS_WIDTH) == (min_seq & (EVICTION_MASK >> LRU_REFS_WIDTH));
278ffcb5f52SNhat Pham }
279ffcb5f52SNhat Pham 
lru_gen_refault(struct folio * folio,void * shadow)280ac35a490SYu Zhao static void lru_gen_refault(struct folio *folio, void *shadow)
281ac35a490SYu Zhao {
2823af0191aSKalesh Singh 	bool recent;
283ac35a490SYu Zhao 	int hist, tier, refs;
284ac35a490SYu Zhao 	bool workingset;
285ac35a490SYu Zhao 	unsigned long token;
286ac35a490SYu Zhao 	struct lruvec *lruvec;
287391655feSYu Zhao 	struct lru_gen_folio *lrugen;
288ac35a490SYu Zhao 	int type = folio_is_file_lru(folio);
289ac35a490SYu Zhao 	int delta = folio_nr_pages(folio);
290ac35a490SYu Zhao 
291ac35a490SYu Zhao 	rcu_read_lock();
292ac35a490SYu Zhao 
2933af0191aSKalesh Singh 	recent = lru_gen_test_recent(shadow, type, &lruvec, &token, &workingset);
2943af0191aSKalesh Singh 	if (lruvec != folio_lruvec(folio))
295ffcb5f52SNhat Pham 		goto unlock;
296ffcb5f52SNhat Pham 
2973af0191aSKalesh Singh 	mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + type, delta);
2983af0191aSKalesh Singh 
2993af0191aSKalesh Singh 	if (!recent)
300ac35a490SYu Zhao 		goto unlock;
301ac35a490SYu Zhao 
302ac35a490SYu Zhao 	lrugen = &lruvec->lrugen;
303ac35a490SYu Zhao 
304d7f1afd0ST.J. Alumbaugh 	hist = lru_hist_from_seq(READ_ONCE(lrugen->min_seq[type]));
305ac35a490SYu Zhao 	/* see the comment in folio_lru_refs() */
306ac35a490SYu Zhao 	refs = (token & (BIT(LRU_REFS_WIDTH) - 1)) + workingset;
307ac35a490SYu Zhao 	tier = lru_tier_from_refs(refs);
308ac35a490SYu Zhao 
309ac35a490SYu Zhao 	atomic_long_add(delta, &lrugen->refaulted[hist][type][tier]);
3103af0191aSKalesh Singh 	mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
311ac35a490SYu Zhao 
312ac35a490SYu Zhao 	/*
313ac35a490SYu Zhao 	 * Count the following two cases as stalls:
314ac35a490SYu Zhao 	 * 1. For pages accessed through page tables, hotter pages pushed out
315ac35a490SYu Zhao 	 *    hot pages which refaulted immediately.
316ac35a490SYu Zhao 	 * 2. For pages accessed multiple times through file descriptors,
31708148805SYu Zhao 	 *    they would have been protected by sort_folio().
318ac35a490SYu Zhao 	 */
31908148805SYu Zhao 	if (lru_gen_in_fault() || refs >= BIT(LRU_REFS_WIDTH) - 1) {
32008148805SYu Zhao 		set_mask_bits(&folio->flags, 0, LRU_REFS_MASK | BIT(PG_workingset));
321ac35a490SYu Zhao 		mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + type, delta);
322ac35a490SYu Zhao 	}
323ac35a490SYu Zhao unlock:
324ac35a490SYu Zhao 	rcu_read_unlock();
325ac35a490SYu Zhao }
326ac35a490SYu Zhao 
327ac35a490SYu Zhao #else /* !CONFIG_LRU_GEN */
328ac35a490SYu Zhao 
lru_gen_eviction(struct folio * folio)329ac35a490SYu Zhao static void *lru_gen_eviction(struct folio *folio)
330ac35a490SYu Zhao {
331ac35a490SYu Zhao 	return NULL;
332ac35a490SYu Zhao }
333ac35a490SYu Zhao 
lru_gen_test_recent(void * shadow,bool file,struct lruvec ** lruvec,unsigned long * token,bool * workingset)334d7f1afd0ST.J. Alumbaugh static bool lru_gen_test_recent(void *shadow, bool file, struct lruvec **lruvec,
335d7f1afd0ST.J. Alumbaugh 				unsigned long *token, bool *workingset)
336ffcb5f52SNhat Pham {
337ffcb5f52SNhat Pham 	return false;
338ffcb5f52SNhat Pham }
339ffcb5f52SNhat Pham 
lru_gen_refault(struct folio * folio,void * shadow)340ac35a490SYu Zhao static void lru_gen_refault(struct folio *folio, void *shadow)
341ac35a490SYu Zhao {
342ac35a490SYu Zhao }
343ac35a490SYu Zhao 
344ac35a490SYu Zhao #endif /* CONFIG_LRU_GEN */
345ac35a490SYu Zhao 
34631d8fcacSJohannes Weiner /**
34731d8fcacSJohannes Weiner  * workingset_age_nonresident - age non-resident entries as LRU ages
348e755f4afSXiaofei Tan  * @lruvec: the lruvec that was aged
34931d8fcacSJohannes Weiner  * @nr_pages: the number of pages to count
35031d8fcacSJohannes Weiner  *
35131d8fcacSJohannes Weiner  * As in-memory pages are aged, non-resident pages need to be aged as
35231d8fcacSJohannes Weiner  * well, in order for the refault distances later on to be comparable
35331d8fcacSJohannes Weiner  * to the in-memory dimensions. This function allows reclaim and LRU
35431d8fcacSJohannes Weiner  * operations to drive the non-resident aging along in parallel.
35531d8fcacSJohannes Weiner  */
workingset_age_nonresident(struct lruvec * lruvec,unsigned long nr_pages)35631d8fcacSJohannes Weiner void workingset_age_nonresident(struct lruvec *lruvec, unsigned long nr_pages)
357b910718aSJohannes Weiner {
358b910718aSJohannes Weiner 	/*
359b910718aSJohannes Weiner 	 * Reclaiming a cgroup means reclaiming all its children in a
360b910718aSJohannes Weiner 	 * round-robin fashion. That means that each cgroup has an LRU
361b910718aSJohannes Weiner 	 * order that is composed of the LRU orders of its child
362b910718aSJohannes Weiner 	 * cgroups; and every page has an LRU position not just in the
363b910718aSJohannes Weiner 	 * cgroup that owns it, but in all of that group's ancestors.
364b910718aSJohannes Weiner 	 *
365b910718aSJohannes Weiner 	 * So when the physical inactive list of a leaf cgroup ages,
366b910718aSJohannes Weiner 	 * the virtual inactive lists of all its parents, including
367b910718aSJohannes Weiner 	 * the root cgroup's, age as well.
368b910718aSJohannes Weiner 	 */
369b910718aSJohannes Weiner 	do {
37031d8fcacSJohannes Weiner 		atomic_long_add(nr_pages, &lruvec->nonresident_age);
37131d8fcacSJohannes Weiner 	} while ((lruvec = parent_lruvec(lruvec)));
372b910718aSJohannes Weiner }
373b910718aSJohannes Weiner 
374a528910eSJohannes Weiner /**
3758927f647SMatthew Wilcox (Oracle)  * workingset_eviction - note the eviction of a folio from memory
376b910718aSJohannes Weiner  * @target_memcg: the cgroup that is causing the reclaim
3778927f647SMatthew Wilcox (Oracle)  * @folio: the folio being evicted
378a528910eSJohannes Weiner  *
3798927f647SMatthew Wilcox (Oracle)  * Return: a shadow entry to be stored in @folio->mapping->i_pages in place
3808927f647SMatthew Wilcox (Oracle)  * of the evicted @folio so that a later refault can be detected.
381a528910eSJohannes Weiner  */
workingset_eviction(struct folio * folio,struct mem_cgroup * target_memcg)3828927f647SMatthew Wilcox (Oracle) void *workingset_eviction(struct folio *folio, struct mem_cgroup *target_memcg)
383a528910eSJohannes Weiner {
3848927f647SMatthew Wilcox (Oracle) 	struct pglist_data *pgdat = folio_pgdat(folio);
385a528910eSJohannes Weiner 	unsigned long eviction;
38623047a96SJohannes Weiner 	struct lruvec *lruvec;
387b910718aSJohannes Weiner 	int memcgid;
388a528910eSJohannes Weiner 
3898927f647SMatthew Wilcox (Oracle) 	/* Folio is fully exclusive and pins folio's memory cgroup pointer */
3908927f647SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
3918927f647SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
3928927f647SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
39323047a96SJohannes Weiner 
394ac35a490SYu Zhao 	if (lru_gen_enabled())
395ac35a490SYu Zhao 		return lru_gen_eviction(folio);
396ac35a490SYu Zhao 
397b910718aSJohannes Weiner 	lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
398b910718aSJohannes Weiner 	/* XXX: target_memcg can be NULL, go through lruvec */
399b910718aSJohannes Weiner 	memcgid = mem_cgroup_id(lruvec_memcg(lruvec));
40031d8fcacSJohannes Weiner 	eviction = atomic_long_read(&lruvec->nonresident_age);
401ac35a490SYu Zhao 	eviction >>= bucket_order;
4028927f647SMatthew Wilcox (Oracle) 	workingset_age_nonresident(lruvec, folio_nr_pages(folio));
4038927f647SMatthew Wilcox (Oracle) 	return pack_shadow(memcgid, pgdat, eviction,
4048927f647SMatthew Wilcox (Oracle) 				folio_test_workingset(folio));
405a528910eSJohannes Weiner }
406a528910eSJohannes Weiner 
407a528910eSJohannes Weiner /**
408ffcb5f52SNhat Pham  * workingset_test_recent - tests if the shadow entry is for a folio that was
409ffcb5f52SNhat Pham  * recently evicted. Also fills in @workingset with the value unpacked from
410ffcb5f52SNhat Pham  * shadow.
411ffcb5f52SNhat Pham  * @shadow: the shadow entry to be tested.
412ffcb5f52SNhat Pham  * @file: whether the corresponding folio is from the file lru.
413ffcb5f52SNhat Pham  * @workingset: where the workingset value unpacked from shadow should
414ffcb5f52SNhat Pham  * be stored.
415*5a4d8944SNhat Pham  * @flush: whether to flush cgroup rstat.
416a528910eSJohannes Weiner  *
417ffcb5f52SNhat Pham  * Return: true if the shadow is for a recently evicted folio; false otherwise.
418a528910eSJohannes Weiner  */
workingset_test_recent(void * shadow,bool file,bool * workingset,bool flush)419*5a4d8944SNhat Pham bool workingset_test_recent(void *shadow, bool file, bool *workingset,
420*5a4d8944SNhat Pham 				bool flush)
421a528910eSJohannes Weiner {
422b910718aSJohannes Weiner 	struct mem_cgroup *eviction_memcg;
423b910718aSJohannes Weiner 	struct lruvec *eviction_lruvec;
424a528910eSJohannes Weiner 	unsigned long refault_distance;
42534e58cacSJohannes Weiner 	unsigned long workingset_size;
426162453bfSJohannes Weiner 	unsigned long refault;
42723047a96SJohannes Weiner 	int memcgid;
428ffcb5f52SNhat Pham 	struct pglist_data *pgdat;
429ffcb5f52SNhat Pham 	unsigned long eviction;
430a528910eSJohannes Weiner 
431b0068472SYosry Ahmed 	rcu_read_lock();
432b0068472SYosry Ahmed 
433b0068472SYosry Ahmed 	if (lru_gen_enabled()) {
434b0068472SYosry Ahmed 		bool recent = lru_gen_test_recent(shadow, file,
435b0068472SYosry Ahmed 				&eviction_lruvec, &eviction, workingset);
436b0068472SYosry Ahmed 
437b0068472SYosry Ahmed 		rcu_read_unlock();
438b0068472SYosry Ahmed 		return recent;
439b0068472SYosry Ahmed 	}
440b0068472SYosry Ahmed 
441ac35a490SYu Zhao 
442ffcb5f52SNhat Pham 	unpack_shadow(shadow, &memcgid, &pgdat, &eviction, workingset);
443ac35a490SYu Zhao 	eviction <<= bucket_order;
444162453bfSJohannes Weiner 
44523047a96SJohannes Weiner 	/*
44623047a96SJohannes Weiner 	 * Look up the memcg associated with the stored ID. It might
4470995d7e5SMatthew Wilcox (Oracle) 	 * have been deleted since the folio's eviction.
44823047a96SJohannes Weiner 	 *
44923047a96SJohannes Weiner 	 * Note that in rare events the ID could have been recycled
4500995d7e5SMatthew Wilcox (Oracle) 	 * for a new cgroup that refaults a shared folio. This is
45123047a96SJohannes Weiner 	 * impossible to tell from the available data. However, this
45223047a96SJohannes Weiner 	 * should be a rare and limited disturbance, and activations
45323047a96SJohannes Weiner 	 * are always speculative anyway. Ultimately, it's the aging
45423047a96SJohannes Weiner 	 * algorithm's job to shake out the minimum access frequency
45523047a96SJohannes Weiner 	 * for the active cache.
45623047a96SJohannes Weiner 	 *
45723047a96SJohannes Weiner 	 * XXX: On !CONFIG_MEMCG, this will always return NULL; it
45823047a96SJohannes Weiner 	 * would be better if the root_mem_cgroup existed in all
45923047a96SJohannes Weiner 	 * configurations instead.
46023047a96SJohannes Weiner 	 */
461b910718aSJohannes Weiner 	eviction_memcg = mem_cgroup_from_id(memcgid);
462b0068472SYosry Ahmed 	if (!mem_cgroup_disabled() &&
463b0068472SYosry Ahmed 	    (!eviction_memcg || !mem_cgroup_tryget(eviction_memcg))) {
464b0068472SYosry Ahmed 		rcu_read_unlock();
465ffcb5f52SNhat Pham 		return false;
466b0068472SYosry Ahmed 	}
467b0068472SYosry Ahmed 
468b0068472SYosry Ahmed 	rcu_read_unlock();
469b0068472SYosry Ahmed 
4707d7ef0a4SYosry Ahmed 	/*
4717d7ef0a4SYosry Ahmed 	 * Flush stats (and potentially sleep) outside the RCU read section.
472*5a4d8944SNhat Pham 	 *
473*5a4d8944SNhat Pham 	 * Note that workingset_test_recent() itself might be called in RCU read
474*5a4d8944SNhat Pham 	 * section (for e.g, in cachestat) - these callers need to skip flushing
475*5a4d8944SNhat Pham 	 * stats (via the flush argument).
476*5a4d8944SNhat Pham 	 *
4777d7ef0a4SYosry Ahmed 	 * XXX: With per-memcg flushing and thresholding, is ratelimiting
4787d7ef0a4SYosry Ahmed 	 * still needed here?
4797d7ef0a4SYosry Ahmed 	 */
480*5a4d8944SNhat Pham 	if (flush)
4817d7ef0a4SYosry Ahmed 		mem_cgroup_flush_stats_ratelimited(eviction_memcg);
482ffcb5f52SNhat Pham 
483b910718aSJohannes Weiner 	eviction_lruvec = mem_cgroup_lruvec(eviction_memcg, pgdat);
48431d8fcacSJohannes Weiner 	refault = atomic_long_read(&eviction_lruvec->nonresident_age);
485162453bfSJohannes Weiner 
486162453bfSJohannes Weiner 	/*
4871899ad18SJohannes Weiner 	 * Calculate the refault distance
488162453bfSJohannes Weiner 	 *
4891899ad18SJohannes Weiner 	 * The unsigned subtraction here gives an accurate distance
49031d8fcacSJohannes Weiner 	 * across nonresident_age overflows in most cases. There is a
4911899ad18SJohannes Weiner 	 * special case: usually, shadow entries have a short lifetime
4921899ad18SJohannes Weiner 	 * and are either refaulted or reclaimed along with the inode
4931899ad18SJohannes Weiner 	 * before they get too old.  But it is not impossible for the
49431d8fcacSJohannes Weiner 	 * nonresident_age to lap a shadow entry in the field, which
49531d8fcacSJohannes Weiner 	 * can then result in a false small refault distance, leading
49631d8fcacSJohannes Weiner 	 * to a false activation should this old entry actually
49731d8fcacSJohannes Weiner 	 * refault again.  However, earlier kernels used to deactivate
4981899ad18SJohannes Weiner 	 * unconditionally with *every* reclaim invocation for the
4991899ad18SJohannes Weiner 	 * longest time, so the occasional inappropriate activation
5001899ad18SJohannes Weiner 	 * leading to pressure on the active list is not a problem.
501162453bfSJohannes Weiner 	 */
502162453bfSJohannes Weiner 	refault_distance = (refault - eviction) & EVICTION_MASK;
503162453bfSJohannes Weiner 
504b910718aSJohannes Weiner 	/*
5051899ad18SJohannes Weiner 	 * Compare the distance to the existing workingset size. We
50634e58cacSJohannes Weiner 	 * don't activate pages that couldn't stay resident even if
507aae466b0SJoonsoo Kim 	 * all the memory was available to the workingset. Whether
508aae466b0SJoonsoo Kim 	 * workingset competition needs to consider anon or not depends
509ed8f3f99SYang Yang 	 * on having free swap space.
5101899ad18SJohannes Weiner 	 */
51134e58cacSJohannes Weiner 	workingset_size = lruvec_page_state(eviction_lruvec, NR_ACTIVE_FILE);
512aae466b0SJoonsoo Kim 	if (!file) {
513aae466b0SJoonsoo Kim 		workingset_size += lruvec_page_state(eviction_lruvec,
514aae466b0SJoonsoo Kim 						     NR_INACTIVE_FILE);
515aae466b0SJoonsoo Kim 	}
516f78dfc7bSJohannes Weiner 	if (mem_cgroup_get_nr_swap_pages(eviction_memcg) > 0) {
51734e58cacSJohannes Weiner 		workingset_size += lruvec_page_state(eviction_lruvec,
51834e58cacSJohannes Weiner 						     NR_ACTIVE_ANON);
519aae466b0SJoonsoo Kim 		if (file) {
520aae466b0SJoonsoo Kim 			workingset_size += lruvec_page_state(eviction_lruvec,
521aae466b0SJoonsoo Kim 						     NR_INACTIVE_ANON);
522aae466b0SJoonsoo Kim 		}
52334e58cacSJohannes Weiner 	}
524ffcb5f52SNhat Pham 
525b0068472SYosry Ahmed 	mem_cgroup_put(eviction_memcg);
526ffcb5f52SNhat Pham 	return refault_distance <= workingset_size;
527ffcb5f52SNhat Pham }
528ffcb5f52SNhat Pham 
529ffcb5f52SNhat Pham /**
530ffcb5f52SNhat Pham  * workingset_refault - Evaluate the refault of a previously evicted folio.
531ffcb5f52SNhat Pham  * @folio: The freshly allocated replacement folio.
532ffcb5f52SNhat Pham  * @shadow: Shadow entry of the evicted folio.
533ffcb5f52SNhat Pham  *
534ffcb5f52SNhat Pham  * Calculates and evaluates the refault distance of the previously
535ffcb5f52SNhat Pham  * evicted folio in the context of the node and the memcg whose memory
536ffcb5f52SNhat Pham  * pressure caused the eviction.
537ffcb5f52SNhat Pham  */
workingset_refault(struct folio * folio,void * shadow)538ffcb5f52SNhat Pham void workingset_refault(struct folio *folio, void *shadow)
539ffcb5f52SNhat Pham {
540ffcb5f52SNhat Pham 	bool file = folio_is_file_lru(folio);
541ffcb5f52SNhat Pham 	struct pglist_data *pgdat;
542ffcb5f52SNhat Pham 	struct mem_cgroup *memcg;
543ffcb5f52SNhat Pham 	struct lruvec *lruvec;
544ffcb5f52SNhat Pham 	bool workingset;
545ffcb5f52SNhat Pham 	long nr;
546ffcb5f52SNhat Pham 
547ffcb5f52SNhat Pham 	if (lru_gen_enabled()) {
548ffcb5f52SNhat Pham 		lru_gen_refault(folio, shadow);
549ffcb5f52SNhat Pham 		return;
550ffcb5f52SNhat Pham 	}
551ffcb5f52SNhat Pham 
552ffcb5f52SNhat Pham 	/*
553ffcb5f52SNhat Pham 	 * The activation decision for this folio is made at the level
554ffcb5f52SNhat Pham 	 * where the eviction occurred, as that is where the LRU order
555ffcb5f52SNhat Pham 	 * during folio reclaim is being determined.
556ffcb5f52SNhat Pham 	 *
557ffcb5f52SNhat Pham 	 * However, the cgroup that will own the folio is the one that
558b0068472SYosry Ahmed 	 * is actually experiencing the refault event. Make sure the folio is
559b0068472SYosry Ahmed 	 * locked to guarantee folio_memcg() stability throughout.
560ffcb5f52SNhat Pham 	 */
561b0068472SYosry Ahmed 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
562ffcb5f52SNhat Pham 	nr = folio_nr_pages(folio);
563ffcb5f52SNhat Pham 	memcg = folio_memcg(folio);
564ffcb5f52SNhat Pham 	pgdat = folio_pgdat(folio);
565ffcb5f52SNhat Pham 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
566ffcb5f52SNhat Pham 
567ffcb5f52SNhat Pham 	mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + file, nr);
568ffcb5f52SNhat Pham 
569*5a4d8944SNhat Pham 	if (!workingset_test_recent(shadow, file, &workingset, true))
570b0068472SYosry Ahmed 		return;
5711899ad18SJohannes Weiner 
5720995d7e5SMatthew Wilcox (Oracle) 	folio_set_active(folio);
5730995d7e5SMatthew Wilcox (Oracle) 	workingset_age_nonresident(lruvec, nr);
5740995d7e5SMatthew Wilcox (Oracle) 	mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + file, nr);
5751899ad18SJohannes Weiner 
5760995d7e5SMatthew Wilcox (Oracle) 	/* Folio was active prior to eviction */
5771899ad18SJohannes Weiner 	if (workingset) {
5780995d7e5SMatthew Wilcox (Oracle) 		folio_set_workingset(folio);
5796e1ca48dSVishal Moola (Oracle) 		/*
5806e1ca48dSVishal Moola (Oracle) 		 * XXX: Move to folio_add_lru() when it supports new vs
5816e1ca48dSVishal Moola (Oracle) 		 * putback
5826e1ca48dSVishal Moola (Oracle) 		 */
5830538a82cSJohannes Weiner 		lru_note_cost_refault(folio);
5840995d7e5SMatthew Wilcox (Oracle) 		mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + file, nr);
585a528910eSJohannes Weiner 	}
586a528910eSJohannes Weiner }
587a528910eSJohannes Weiner 
588a528910eSJohannes Weiner /**
589a528910eSJohannes Weiner  * workingset_activation - note a page activation
590c5ce619aSMatthew Wilcox (Oracle)  * @folio: Folio that is being activated.
591a528910eSJohannes Weiner  */
workingset_activation(struct folio * folio)592c5ce619aSMatthew Wilcox (Oracle) void workingset_activation(struct folio *folio)
593a528910eSJohannes Weiner {
59455779ec7SJohannes Weiner 	struct mem_cgroup *memcg;
59523047a96SJohannes Weiner 
59655779ec7SJohannes Weiner 	rcu_read_lock();
59723047a96SJohannes Weiner 	/*
59823047a96SJohannes Weiner 	 * Filter non-memcg pages here, e.g. unmap can call
59923047a96SJohannes Weiner 	 * mark_page_accessed() on VDSO pages.
60023047a96SJohannes Weiner 	 *
60123047a96SJohannes Weiner 	 * XXX: See workingset_refault() - this should return
60223047a96SJohannes Weiner 	 * root_mem_cgroup even for !CONFIG_MEMCG.
60323047a96SJohannes Weiner 	 */
604c5ce619aSMatthew Wilcox (Oracle) 	memcg = folio_memcg_rcu(folio);
60555779ec7SJohannes Weiner 	if (!mem_cgroup_disabled() && !memcg)
60623047a96SJohannes Weiner 		goto out;
607c5ce619aSMatthew Wilcox (Oracle) 	workingset_age_nonresident(folio_lruvec(folio), folio_nr_pages(folio));
60823047a96SJohannes Weiner out:
60955779ec7SJohannes Weiner 	rcu_read_unlock();
610a528910eSJohannes Weiner }
611449dd698SJohannes Weiner 
612449dd698SJohannes Weiner /*
613449dd698SJohannes Weiner  * Shadow entries reflect the share of the working set that does not
614449dd698SJohannes Weiner  * fit into memory, so their number depends on the access pattern of
615449dd698SJohannes Weiner  * the workload.  In most cases, they will refault or get reclaimed
616449dd698SJohannes Weiner  * along with the inode, but a (malicious) workload that streams
617449dd698SJohannes Weiner  * through files with a total size several times that of available
618449dd698SJohannes Weiner  * memory, while preventing the inodes from being reclaimed, can
619449dd698SJohannes Weiner  * create excessive amounts of shadow nodes.  To keep a lid on this,
620449dd698SJohannes Weiner  * track shadow nodes and reclaim them when they grow way past the
621449dd698SJohannes Weiner  * point where they would still be useful.
622449dd698SJohannes Weiner  */
623449dd698SJohannes Weiner 
6249bbdc0f3SMuchun Song struct list_lru shadow_nodes;
62514b46879SJohannes Weiner 
workingset_update_node(struct xa_node * node)626a97e7904SMatthew Wilcox void workingset_update_node(struct xa_node *node)
62714b46879SJohannes Weiner {
6282386eef2SSebastian Andrzej Siewior 	struct address_space *mapping;
6294715c6a7SShakeel Butt 	struct page *page = virt_to_page(node);
6302386eef2SSebastian Andrzej Siewior 
63114b46879SJohannes Weiner 	/*
63214b46879SJohannes Weiner 	 * Track non-empty nodes that contain only shadow entries;
63314b46879SJohannes Weiner 	 * unlink those that contain pages or are being freed.
63414b46879SJohannes Weiner 	 *
63514b46879SJohannes Weiner 	 * Avoid acquiring the list_lru lock when the nodes are
63614b46879SJohannes Weiner 	 * already where they should be. The list_empty() test is safe
637b93b0163SMatthew Wilcox 	 * as node->private_list is protected by the i_pages lock.
63814b46879SJohannes Weiner 	 */
6392386eef2SSebastian Andrzej Siewior 	mapping = container_of(node->array, struct address_space, i_pages);
6402386eef2SSebastian Andrzej Siewior 	lockdep_assert_held(&mapping->i_pages.xa_lock);
64168d48e6aSJohannes Weiner 
64201959dfeSMatthew Wilcox 	if (node->count && node->count == node->nr_values) {
64368d48e6aSJohannes Weiner 		if (list_empty(&node->private_list)) {
6440a97c01cSNhat Pham 			list_lru_add_obj(&shadow_nodes, &node->private_list);
6454715c6a7SShakeel Butt 			__inc_node_page_state(page, WORKINGSET_NODES);
64668d48e6aSJohannes Weiner 		}
64714b46879SJohannes Weiner 	} else {
64868d48e6aSJohannes Weiner 		if (!list_empty(&node->private_list)) {
6490a97c01cSNhat Pham 			list_lru_del_obj(&shadow_nodes, &node->private_list);
6504715c6a7SShakeel Butt 			__dec_node_page_state(page, WORKINGSET_NODES);
65168d48e6aSJohannes Weiner 		}
65214b46879SJohannes Weiner 	}
65314b46879SJohannes Weiner }
654449dd698SJohannes Weiner 
count_shadow_nodes(struct shrinker * shrinker,struct shrink_control * sc)655449dd698SJohannes Weiner static unsigned long count_shadow_nodes(struct shrinker *shrinker,
656449dd698SJohannes Weiner 					struct shrink_control *sc)
657449dd698SJohannes Weiner {
658449dd698SJohannes Weiner 	unsigned long max_nodes;
65914b46879SJohannes Weiner 	unsigned long nodes;
66095f9ab2dSJohannes Weiner 	unsigned long pages;
661449dd698SJohannes Weiner 
66214b46879SJohannes Weiner 	nodes = list_lru_shrink_count(&shadow_nodes, sc);
663725cac1cSMiaohe Lin 	if (!nodes)
664725cac1cSMiaohe Lin 		return SHRINK_EMPTY;
665449dd698SJohannes Weiner 
666449dd698SJohannes Weiner 	/*
667a97e7904SMatthew Wilcox 	 * Approximate a reasonable limit for the nodes
668b5388998SJohannes Weiner 	 * containing shadow entries. We don't need to keep more
669b5388998SJohannes Weiner 	 * shadow entries than possible pages on the active list,
670b5388998SJohannes Weiner 	 * since refault distances bigger than that are dismissed.
671b5388998SJohannes Weiner 	 *
672b5388998SJohannes Weiner 	 * The size of the active list converges toward 100% of
673b5388998SJohannes Weiner 	 * overall page cache as memory grows, with only a tiny
674b5388998SJohannes Weiner 	 * inactive list. Assume the total cache size for that.
675b5388998SJohannes Weiner 	 *
676b5388998SJohannes Weiner 	 * Nodes might be sparsely populated, with only one shadow
677b5388998SJohannes Weiner 	 * entry in the extreme case. Obviously, we cannot keep one
678b5388998SJohannes Weiner 	 * node for every eligible shadow entry, so compromise on a
679b5388998SJohannes Weiner 	 * worst-case density of 1/8th. Below that, not all eligible
680b5388998SJohannes Weiner 	 * refaults can be detected anymore.
681449dd698SJohannes Weiner 	 *
682a97e7904SMatthew Wilcox 	 * On 64-bit with 7 xa_nodes per page and 64 slots
683449dd698SJohannes Weiner 	 * each, this will reclaim shadow entries when they consume
684b5388998SJohannes Weiner 	 * ~1.8% of available memory:
685449dd698SJohannes Weiner 	 *
686a97e7904SMatthew Wilcox 	 * PAGE_SIZE / xa_nodes / node_entries * 8 / PAGE_SIZE
687449dd698SJohannes Weiner 	 */
68895f9ab2dSJohannes Weiner #ifdef CONFIG_MEMCG
689b5388998SJohannes Weiner 	if (sc->memcg) {
69095f9ab2dSJohannes Weiner 		struct lruvec *lruvec;
6912b487e59SJohannes Weiner 		int i;
69295f9ab2dSJohannes Weiner 
693d4a5b369SShakeel Butt 		mem_cgroup_flush_stats_ratelimited(sc->memcg);
694867e5e1dSJohannes Weiner 		lruvec = mem_cgroup_lruvec(sc->memcg, NODE_DATA(sc->nid));
6952b487e59SJohannes Weiner 		for (pages = 0, i = 0; i < NR_LRU_LISTS; i++)
696205b20ccSJohannes Weiner 			pages += lruvec_page_state_local(lruvec,
697205b20ccSJohannes Weiner 							 NR_LRU_BASE + i);
698d42f3245SRoman Gushchin 		pages += lruvec_page_state_local(
699d42f3245SRoman Gushchin 			lruvec, NR_SLAB_RECLAIMABLE_B) >> PAGE_SHIFT;
700d42f3245SRoman Gushchin 		pages += lruvec_page_state_local(
701d42f3245SRoman Gushchin 			lruvec, NR_SLAB_UNRECLAIMABLE_B) >> PAGE_SHIFT;
70295f9ab2dSJohannes Weiner 	} else
70395f9ab2dSJohannes Weiner #endif
70495f9ab2dSJohannes Weiner 		pages = node_present_pages(sc->nid);
70595f9ab2dSJohannes Weiner 
706dad4f140SLinus Torvalds 	max_nodes = pages >> (XA_CHUNK_SHIFT - 3);
707449dd698SJohannes Weiner 
70814b46879SJohannes Weiner 	if (nodes <= max_nodes)
709449dd698SJohannes Weiner 		return 0;
71014b46879SJohannes Weiner 	return nodes - max_nodes;
711449dd698SJohannes Weiner }
712449dd698SJohannes Weiner 
shadow_lru_isolate(struct list_head * item,struct list_lru_one * lru,spinlock_t * lru_lock,void * arg)713449dd698SJohannes Weiner static enum lru_status shadow_lru_isolate(struct list_head *item,
7143f97b163SVladimir Davydov 					  struct list_lru_one *lru,
715449dd698SJohannes Weiner 					  spinlock_t *lru_lock,
716a97e7904SMatthew Wilcox 					  void *arg) __must_hold(lru_lock)
717449dd698SJohannes Weiner {
718a97e7904SMatthew Wilcox 	struct xa_node *node = container_of(item, struct xa_node, private_list);
719449dd698SJohannes Weiner 	struct address_space *mapping;
720449dd698SJohannes Weiner 	int ret;
721449dd698SJohannes Weiner 
722449dd698SJohannes Weiner 	/*
723f82cd2f0SMatthew Wilcox (Oracle) 	 * Page cache insertions and deletions synchronously maintain
724b93b0163SMatthew Wilcox 	 * the shadow node LRU under the i_pages lock and the
725449dd698SJohannes Weiner 	 * lru_lock.  Because the page cache tree is emptied before
726449dd698SJohannes Weiner 	 * the inode can be destroyed, holding the lru_lock pins any
727a97e7904SMatthew Wilcox 	 * address_space that has nodes on the LRU.
728449dd698SJohannes Weiner 	 *
729b93b0163SMatthew Wilcox 	 * We can then safely transition to the i_pages lock to
730449dd698SJohannes Weiner 	 * pin only the address_space of the particular node we want
731449dd698SJohannes Weiner 	 * to reclaim, take the node off-LRU, and drop the lru_lock.
732449dd698SJohannes Weiner 	 */
733449dd698SJohannes Weiner 
73401959dfeSMatthew Wilcox 	mapping = container_of(node->array, struct address_space, i_pages);
735449dd698SJohannes Weiner 
736449dd698SJohannes Weiner 	/* Coming from the list, invert the lock order */
737b93b0163SMatthew Wilcox 	if (!xa_trylock(&mapping->i_pages)) {
7386ca342d0SSebastian Andrzej Siewior 		spin_unlock_irq(lru_lock);
739449dd698SJohannes Weiner 		ret = LRU_RETRY;
740449dd698SJohannes Weiner 		goto out;
741449dd698SJohannes Weiner 	}
742449dd698SJohannes Weiner 
7435649d113SYang Yang 	/* For page cache we need to hold i_lock */
7445649d113SYang Yang 	if (mapping->host != NULL) {
74551b8c1feSJohannes Weiner 		if (!spin_trylock(&mapping->host->i_lock)) {
74651b8c1feSJohannes Weiner 			xa_unlock(&mapping->i_pages);
74751b8c1feSJohannes Weiner 			spin_unlock_irq(lru_lock);
74851b8c1feSJohannes Weiner 			ret = LRU_RETRY;
74951b8c1feSJohannes Weiner 			goto out;
75051b8c1feSJohannes Weiner 		}
7515649d113SYang Yang 	}
75251b8c1feSJohannes Weiner 
7533f97b163SVladimir Davydov 	list_lru_isolate(lru, item);
7544715c6a7SShakeel Butt 	__dec_node_page_state(virt_to_page(node), WORKINGSET_NODES);
75568d48e6aSJohannes Weiner 
756449dd698SJohannes Weiner 	spin_unlock(lru_lock);
757449dd698SJohannes Weiner 
758449dd698SJohannes Weiner 	/*
759449dd698SJohannes Weiner 	 * The nodes should only contain one or more shadow entries,
760449dd698SJohannes Weiner 	 * no pages, so we expect to be able to remove them all and
761449dd698SJohannes Weiner 	 * delete and free the empty node afterwards.
762449dd698SJohannes Weiner 	 */
76301959dfeSMatthew Wilcox 	if (WARN_ON_ONCE(!node->nr_values))
764b936887eSJohannes Weiner 		goto out_invalid;
76501959dfeSMatthew Wilcox 	if (WARN_ON_ONCE(node->count != node->nr_values))
766b936887eSJohannes Weiner 		goto out_invalid;
767f82cd2f0SMatthew Wilcox (Oracle) 	xa_delete_node(node, workingset_update_node);
768da3ceeffSMuchun Song 	__inc_lruvec_kmem_state(node, WORKINGSET_NODERECLAIM);
769449dd698SJohannes Weiner 
770b936887eSJohannes Weiner out_invalid:
7716ca342d0SSebastian Andrzej Siewior 	xa_unlock_irq(&mapping->i_pages);
7725649d113SYang Yang 	if (mapping->host != NULL) {
77351b8c1feSJohannes Weiner 		if (mapping_shrinkable(mapping))
77451b8c1feSJohannes Weiner 			inode_add_lru(mapping->host);
77551b8c1feSJohannes Weiner 		spin_unlock(&mapping->host->i_lock);
7765649d113SYang Yang 	}
777449dd698SJohannes Weiner 	ret = LRU_REMOVED_RETRY;
778449dd698SJohannes Weiner out:
779449dd698SJohannes Weiner 	cond_resched();
7806ca342d0SSebastian Andrzej Siewior 	spin_lock_irq(lru_lock);
781449dd698SJohannes Weiner 	return ret;
782449dd698SJohannes Weiner }
783449dd698SJohannes Weiner 
scan_shadow_nodes(struct shrinker * shrinker,struct shrink_control * sc)784449dd698SJohannes Weiner static unsigned long scan_shadow_nodes(struct shrinker *shrinker,
785449dd698SJohannes Weiner 				       struct shrink_control *sc)
786449dd698SJohannes Weiner {
787b93b0163SMatthew Wilcox 	/* list_lru lock nests inside the IRQ-safe i_pages lock */
7886b51e881SSebastian Andrzej Siewior 	return list_lru_shrink_walk_irq(&shadow_nodes, sc, shadow_lru_isolate,
7896b51e881SSebastian Andrzej Siewior 					NULL);
790449dd698SJohannes Weiner }
791449dd698SJohannes Weiner 
792449dd698SJohannes Weiner /*
793449dd698SJohannes Weiner  * Our list_lru->lock is IRQ-safe as it nests inside the IRQ-safe
794b93b0163SMatthew Wilcox  * i_pages lock.
795449dd698SJohannes Weiner  */
796449dd698SJohannes Weiner static struct lock_class_key shadow_nodes_key;
797449dd698SJohannes Weiner 
workingset_init(void)798449dd698SJohannes Weiner static int __init workingset_init(void)
799449dd698SJohannes Weiner {
800219c666eSQi Zheng 	struct shrinker *workingset_shadow_shrinker;
801612e4493SJohannes Weiner 	unsigned int timestamp_bits;
802612e4493SJohannes Weiner 	unsigned int max_order;
803219c666eSQi Zheng 	int ret = -ENOMEM;
804449dd698SJohannes Weiner 
805612e4493SJohannes Weiner 	BUILD_BUG_ON(BITS_PER_LONG < EVICTION_SHIFT);
806612e4493SJohannes Weiner 	/*
807612e4493SJohannes Weiner 	 * Calculate the eviction bucket size to cover the longest
808612e4493SJohannes Weiner 	 * actionable refault distance, which is currently half of
809612e4493SJohannes Weiner 	 * memory (totalram_pages/2). However, memory hotplug may add
810612e4493SJohannes Weiner 	 * some more pages at runtime, so keep working with up to
811612e4493SJohannes Weiner 	 * double the initial memory by using totalram_pages as-is.
812612e4493SJohannes Weiner 	 */
813612e4493SJohannes Weiner 	timestamp_bits = BITS_PER_LONG - EVICTION_SHIFT;
814ca79b0c2SArun KS 	max_order = fls_long(totalram_pages() - 1);
815612e4493SJohannes Weiner 	if (max_order > timestamp_bits)
816612e4493SJohannes Weiner 		bucket_order = max_order - timestamp_bits;
817d3d36c4bSAnton Blanchard 	pr_info("workingset: timestamp_bits=%d max_order=%d bucket_order=%u\n",
818612e4493SJohannes Weiner 	       timestamp_bits, max_order, bucket_order);
819612e4493SJohannes Weiner 
820219c666eSQi Zheng 	workingset_shadow_shrinker = shrinker_alloc(SHRINKER_NUMA_AWARE |
821219c666eSQi Zheng 						    SHRINKER_MEMCG_AWARE,
822219c666eSQi Zheng 						    "mm-shadow");
823219c666eSQi Zheng 	if (!workingset_shadow_shrinker)
824449dd698SJohannes Weiner 		goto err;
825219c666eSQi Zheng 
826c92e8e10SKirill Tkhai 	ret = __list_lru_init(&shadow_nodes, true, &shadow_nodes_key,
827219c666eSQi Zheng 			      workingset_shadow_shrinker);
828449dd698SJohannes Weiner 	if (ret)
829449dd698SJohannes Weiner 		goto err_list_lru;
830219c666eSQi Zheng 
831219c666eSQi Zheng 	workingset_shadow_shrinker->count_objects = count_shadow_nodes;
832219c666eSQi Zheng 	workingset_shadow_shrinker->scan_objects = scan_shadow_nodes;
833219c666eSQi Zheng 	/* ->count reports only fully expendable nodes */
834219c666eSQi Zheng 	workingset_shadow_shrinker->seeks = 0;
835219c666eSQi Zheng 
836219c666eSQi Zheng 	shrinker_register(workingset_shadow_shrinker);
837449dd698SJohannes Weiner 	return 0;
838449dd698SJohannes Weiner err_list_lru:
839219c666eSQi Zheng 	shrinker_free(workingset_shadow_shrinker);
840449dd698SJohannes Weiner err:
841449dd698SJohannes Weiner 	return ret;
842449dd698SJohannes Weiner }
843449dd698SJohannes Weiner module_init(workingset_init);
844