• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
4  *
5  *  Swap reorganised 29.12.95, Stephen Tweedie.
6  *  kswapd added: 7.1.96  sct
7  *  Removed kswapd_ctl limits, and swap out as many pages as needed
8  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10  *  Multiqueue VM started 5.8.00, Rik van Riel.
11  */
12 
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 
15 #include <linux/mm.h>
16 #include <linux/sched/mm.h>
17 #include <linux/module.h>
18 #include <linux/gfp.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/swap.h>
21 #include <linux/pagemap.h>
22 #include <linux/init.h>
23 #include <linux/highmem.h>
24 #include <linux/vmpressure.h>
25 #include <linux/vmstat.h>
26 #include <linux/file.h>
27 #include <linux/writeback.h>
28 #include <linux/blkdev.h>
29 #include <linux/buffer_head.h>	/* for try_to_release_page(),
30 					buffer_heads_over_limit */
31 #include <linux/mm_inline.h>
32 #include <linux/backing-dev.h>
33 #include <linux/rmap.h>
34 #include <linux/topology.h>
35 #include <linux/cpu.h>
36 #include <linux/cpuset.h>
37 #include <linux/compaction.h>
38 #include <linux/notifier.h>
39 #include <linux/rwsem.h>
40 #include <linux/delay.h>
41 #include <linux/kthread.h>
42 #include <linux/freezer.h>
43 #include <linux/memcontrol.h>
44 #include <linux/migrate.h>
45 #include <linux/delayacct.h>
46 #include <linux/sysctl.h>
47 #include <linux/oom.h>
48 #include <linux/pagevec.h>
49 #include <linux/prefetch.h>
50 #include <linux/printk.h>
51 #include <linux/dax.h>
52 #include <linux/psi.h>
53 #include <linux/pagewalk.h>
54 #include <linux/shmem_fs.h>
55 #include <linux/ctype.h>
56 #include <linux/debugfs.h>
57 #include <linux/rculist_nulls.h>
58 #include <linux/random.h>
59 
60 #include <asm/tlbflush.h>
61 #include <asm/div64.h>
62 
63 #include <linux/swapops.h>
64 #include <linux/balloon_compaction.h>
65 
66 #include "internal.h"
67 
68 #define CREATE_TRACE_POINTS
69 #include <trace/events/vmscan.h>
70 
71 #undef CREATE_TRACE_POINTS
72 #include <trace/hooks/vmscan.h>
73 
74 #undef CREATE_TRACE_POINTS
75 #include <trace/hooks/mm.h>
76 
77 EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_begin);
78 EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_end);
79 
80 struct scan_control {
81 	/* How many pages shrink_list() should reclaim */
82 	unsigned long nr_to_reclaim;
83 
84 	/*
85 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
86 	 * are scanned.
87 	 */
88 	nodemask_t	*nodemask;
89 
90 	/*
91 	 * The memory cgroup that hit its limit and as a result is the
92 	 * primary target of this reclaim invocation.
93 	 */
94 	struct mem_cgroup *target_mem_cgroup;
95 
96 	/*
97 	 * Scan pressure balancing between anon and file LRUs
98 	 */
99 	unsigned long	anon_cost;
100 	unsigned long	file_cost;
101 
102 	/* Can active pages be deactivated as part of reclaim? */
103 #define DEACTIVATE_ANON 1
104 #define DEACTIVATE_FILE 2
105 	unsigned int may_deactivate:2;
106 	unsigned int force_deactivate:1;
107 	unsigned int skipped_deactivate:1;
108 
109 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
110 	unsigned int may_writepage:1;
111 
112 	/* Can mapped pages be reclaimed? */
113 	unsigned int may_unmap:1;
114 
115 	/* Can pages be swapped as part of reclaim? */
116 	unsigned int may_swap:1;
117 
118 	/* Proactive reclaim invoked by userspace through memory.reclaim */
119 	unsigned int proactive:1;
120 
121 	/*
122 	 * Cgroup memory below memory.low is protected as long as we
123 	 * don't threaten to OOM. If any cgroup is reclaimed at
124 	 * reduced force or passed over entirely due to its memory.low
125 	 * setting (memcg_low_skipped), and nothing is reclaimed as a
126 	 * result, then go back for one more cycle that reclaims the protected
127 	 * memory (memcg_low_reclaim) to avert OOM.
128 	 */
129 	unsigned int memcg_low_reclaim:1;
130 	unsigned int memcg_low_skipped:1;
131 
132 	unsigned int hibernation_mode:1;
133 
134 	/* One of the zones is ready for compaction */
135 	unsigned int compaction_ready:1;
136 
137 	/* There is easily reclaimable cold cache in the current node */
138 	unsigned int cache_trim_mode:1;
139 
140 	/* The file pages on the current node are dangerously low */
141 	unsigned int file_is_tiny:1;
142 
143 	/* Always discard instead of demoting to lower tier memory */
144 	unsigned int no_demotion:1;
145 
146 	/* Allocation order */
147 	s8 order;
148 
149 	/* Scan (total_size >> priority) pages at once */
150 	s8 priority;
151 
152 	/* The highest zone to isolate pages for reclaim from */
153 	s8 reclaim_idx;
154 
155 	/* This context's GFP mask */
156 	gfp_t gfp_mask;
157 
158 	/* Incremented by the number of inactive pages that were scanned */
159 	unsigned long nr_scanned;
160 
161 	/* Number of pages freed so far during a call to shrink_zones() */
162 	unsigned long nr_reclaimed;
163 
164 	struct {
165 		unsigned int dirty;
166 		unsigned int unqueued_dirty;
167 		unsigned int congested;
168 		unsigned int writeback;
169 		unsigned int immediate;
170 		unsigned int file_taken;
171 		unsigned int taken;
172 	} nr;
173 
174 	/* for recording the reclaimed slab by now */
175 	struct reclaim_state reclaim_state;
176 };
177 
178 #ifdef ARCH_HAS_PREFETCHW
179 #define prefetchw_prev_lru_page(_page, _base, _field)			\
180 	do {								\
181 		if ((_page)->lru.prev != _base) {			\
182 			struct page *prev;				\
183 									\
184 			prev = lru_to_page(&(_page->lru));		\
185 			prefetchw(&prev->_field);			\
186 		}							\
187 	} while (0)
188 #else
189 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
190 #endif
191 
192 /*
193  * From 0 .. 200.  Higher means more swappy.
194  */
195 int vm_swappiness = 60;
196 
set_task_reclaim_state(struct task_struct * task,struct reclaim_state * rs)197 static void set_task_reclaim_state(struct task_struct *task,
198 				   struct reclaim_state *rs)
199 {
200 	/* Check for an overwrite */
201 	WARN_ON_ONCE(rs && task->reclaim_state);
202 
203 	/* Check for the nulling of an already-nulled member */
204 	WARN_ON_ONCE(!rs && !task->reclaim_state);
205 
206 	task->reclaim_state = rs;
207 }
208 
209 static LIST_HEAD(shrinker_list);
210 static DECLARE_RWSEM(shrinker_rwsem);
211 
212 #ifdef CONFIG_MEMCG
213 static int shrinker_nr_max;
214 
215 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
shrinker_map_size(int nr_items)216 static inline int shrinker_map_size(int nr_items)
217 {
218 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
219 }
220 
shrinker_defer_size(int nr_items)221 static inline int shrinker_defer_size(int nr_items)
222 {
223 	return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
224 }
225 
shrinker_info_protected(struct mem_cgroup * memcg,int nid)226 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
227 						     int nid)
228 {
229 	return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
230 					 lockdep_is_held(&shrinker_rwsem));
231 }
232 
expand_one_shrinker_info(struct mem_cgroup * memcg,int map_size,int defer_size,int old_map_size,int old_defer_size)233 static int expand_one_shrinker_info(struct mem_cgroup *memcg,
234 				    int map_size, int defer_size,
235 				    int old_map_size, int old_defer_size)
236 {
237 	struct shrinker_info *new, *old;
238 	struct mem_cgroup_per_node *pn;
239 	int nid;
240 	int size = map_size + defer_size;
241 
242 	for_each_node(nid) {
243 		pn = memcg->nodeinfo[nid];
244 		old = shrinker_info_protected(memcg, nid);
245 		/* Not yet online memcg */
246 		if (!old)
247 			return 0;
248 
249 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
250 		if (!new)
251 			return -ENOMEM;
252 
253 		new->nr_deferred = (atomic_long_t *)(new + 1);
254 		new->map = (void *)new->nr_deferred + defer_size;
255 
256 		/* map: set all old bits, clear all new bits */
257 		memset(new->map, (int)0xff, old_map_size);
258 		memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
259 		/* nr_deferred: copy old values, clear all new values */
260 		memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
261 		memset((void *)new->nr_deferred + old_defer_size, 0,
262 		       defer_size - old_defer_size);
263 
264 		rcu_assign_pointer(pn->shrinker_info, new);
265 		kvfree_rcu(old, rcu);
266 	}
267 
268 	return 0;
269 }
270 
free_shrinker_info(struct mem_cgroup * memcg)271 void free_shrinker_info(struct mem_cgroup *memcg)
272 {
273 	struct mem_cgroup_per_node *pn;
274 	struct shrinker_info *info;
275 	int nid;
276 
277 	for_each_node(nid) {
278 		pn = memcg->nodeinfo[nid];
279 		info = rcu_dereference_protected(pn->shrinker_info, true);
280 		kvfree(info);
281 		rcu_assign_pointer(pn->shrinker_info, NULL);
282 	}
283 }
284 
alloc_shrinker_info(struct mem_cgroup * memcg)285 int alloc_shrinker_info(struct mem_cgroup *memcg)
286 {
287 	struct shrinker_info *info;
288 	int nid, size, ret = 0;
289 	int map_size, defer_size = 0;
290 
291 	down_write(&shrinker_rwsem);
292 	map_size = shrinker_map_size(shrinker_nr_max);
293 	defer_size = shrinker_defer_size(shrinker_nr_max);
294 	size = map_size + defer_size;
295 	for_each_node(nid) {
296 		info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
297 		if (!info) {
298 			free_shrinker_info(memcg);
299 			ret = -ENOMEM;
300 			break;
301 		}
302 		info->nr_deferred = (atomic_long_t *)(info + 1);
303 		info->map = (void *)info->nr_deferred + defer_size;
304 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
305 	}
306 	up_write(&shrinker_rwsem);
307 
308 	return ret;
309 }
310 
need_expand(int nr_max)311 static inline bool need_expand(int nr_max)
312 {
313 	return round_up(nr_max, BITS_PER_LONG) >
314 	       round_up(shrinker_nr_max, BITS_PER_LONG);
315 }
316 
expand_shrinker_info(int new_id)317 static int expand_shrinker_info(int new_id)
318 {
319 	int ret = 0;
320 	int new_nr_max = new_id + 1;
321 	int map_size, defer_size = 0;
322 	int old_map_size, old_defer_size = 0;
323 	struct mem_cgroup *memcg;
324 
325 	if (!need_expand(new_nr_max))
326 		goto out;
327 
328 	if (!root_mem_cgroup)
329 		goto out;
330 
331 	lockdep_assert_held(&shrinker_rwsem);
332 
333 	map_size = shrinker_map_size(new_nr_max);
334 	defer_size = shrinker_defer_size(new_nr_max);
335 	old_map_size = shrinker_map_size(shrinker_nr_max);
336 	old_defer_size = shrinker_defer_size(shrinker_nr_max);
337 
338 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
339 	do {
340 		ret = expand_one_shrinker_info(memcg, map_size, defer_size,
341 					       old_map_size, old_defer_size);
342 		if (ret) {
343 			mem_cgroup_iter_break(NULL, memcg);
344 			goto out;
345 		}
346 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
347 out:
348 	if (!ret)
349 		shrinker_nr_max = new_nr_max;
350 
351 	return ret;
352 }
353 
set_shrinker_bit(struct mem_cgroup * memcg,int nid,int shrinker_id)354 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
355 {
356 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
357 		struct shrinker_info *info;
358 
359 		rcu_read_lock();
360 		info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
361 		/* Pairs with smp mb in shrink_slab() */
362 		smp_mb__before_atomic();
363 		set_bit(shrinker_id, info->map);
364 		rcu_read_unlock();
365 	}
366 }
367 
368 static DEFINE_IDR(shrinker_idr);
369 
prealloc_memcg_shrinker(struct shrinker * shrinker)370 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
371 {
372 	int id, ret = -ENOMEM;
373 
374 	if (mem_cgroup_disabled())
375 		return -ENOSYS;
376 
377 	down_write(&shrinker_rwsem);
378 	/* This may call shrinker, so it must use down_read_trylock() */
379 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
380 	if (id < 0)
381 		goto unlock;
382 
383 	if (id >= shrinker_nr_max) {
384 		if (expand_shrinker_info(id)) {
385 			idr_remove(&shrinker_idr, id);
386 			goto unlock;
387 		}
388 	}
389 	shrinker->id = id;
390 	ret = 0;
391 unlock:
392 	up_write(&shrinker_rwsem);
393 	return ret;
394 }
395 
unregister_memcg_shrinker(struct shrinker * shrinker)396 static void unregister_memcg_shrinker(struct shrinker *shrinker)
397 {
398 	int id = shrinker->id;
399 
400 	BUG_ON(id < 0);
401 
402 	lockdep_assert_held(&shrinker_rwsem);
403 
404 	idr_remove(&shrinker_idr, id);
405 }
406 
xchg_nr_deferred_memcg(int nid,struct shrinker * shrinker,struct mem_cgroup * memcg)407 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
408 				   struct mem_cgroup *memcg)
409 {
410 	struct shrinker_info *info;
411 
412 	info = shrinker_info_protected(memcg, nid);
413 	return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
414 }
415 
add_nr_deferred_memcg(long nr,int nid,struct shrinker * shrinker,struct mem_cgroup * memcg)416 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
417 				  struct mem_cgroup *memcg)
418 {
419 	struct shrinker_info *info;
420 
421 	info = shrinker_info_protected(memcg, nid);
422 	return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
423 }
424 
reparent_shrinker_deferred(struct mem_cgroup * memcg)425 void reparent_shrinker_deferred(struct mem_cgroup *memcg)
426 {
427 	int i, nid;
428 	long nr;
429 	struct mem_cgroup *parent;
430 	struct shrinker_info *child_info, *parent_info;
431 
432 	parent = parent_mem_cgroup(memcg);
433 	if (!parent)
434 		parent = root_mem_cgroup;
435 
436 	/* Prevent from concurrent shrinker_info expand */
437 	down_read(&shrinker_rwsem);
438 	for_each_node(nid) {
439 		child_info = shrinker_info_protected(memcg, nid);
440 		parent_info = shrinker_info_protected(parent, nid);
441 		for (i = 0; i < shrinker_nr_max; i++) {
442 			nr = atomic_long_read(&child_info->nr_deferred[i]);
443 			atomic_long_add(nr, &parent_info->nr_deferred[i]);
444 		}
445 	}
446 	up_read(&shrinker_rwsem);
447 }
448 
cgroup_reclaim(struct scan_control * sc)449 static bool cgroup_reclaim(struct scan_control *sc)
450 {
451 	return sc->target_mem_cgroup;
452 }
453 
global_reclaim(struct scan_control * sc)454 static bool global_reclaim(struct scan_control *sc)
455 {
456 	return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
457 }
458 
459 /**
460  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
461  * @sc: scan_control in question
462  *
463  * The normal page dirty throttling mechanism in balance_dirty_pages() is
464  * completely broken with the legacy memcg and direct stalling in
465  * shrink_page_list() is used for throttling instead, which lacks all the
466  * niceties such as fairness, adaptive pausing, bandwidth proportional
467  * allocation and configurability.
468  *
469  * This function tests whether the vmscan currently in progress can assume
470  * that the normal dirty throttling mechanism is operational.
471  */
writeback_throttling_sane(struct scan_control * sc)472 static bool writeback_throttling_sane(struct scan_control *sc)
473 {
474 	if (!cgroup_reclaim(sc))
475 		return true;
476 #ifdef CONFIG_CGROUP_WRITEBACK
477 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
478 		return true;
479 #endif
480 	return false;
481 }
482 #else
prealloc_memcg_shrinker(struct shrinker * shrinker)483 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
484 {
485 	return -ENOSYS;
486 }
487 
unregister_memcg_shrinker(struct shrinker * shrinker)488 static void unregister_memcg_shrinker(struct shrinker *shrinker)
489 {
490 }
491 
xchg_nr_deferred_memcg(int nid,struct shrinker * shrinker,struct mem_cgroup * memcg)492 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
493 				   struct mem_cgroup *memcg)
494 {
495 	return 0;
496 }
497 
add_nr_deferred_memcg(long nr,int nid,struct shrinker * shrinker,struct mem_cgroup * memcg)498 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
499 				  struct mem_cgroup *memcg)
500 {
501 	return 0;
502 }
503 
cgroup_reclaim(struct scan_control * sc)504 static bool cgroup_reclaim(struct scan_control *sc)
505 {
506 	return false;
507 }
508 
global_reclaim(struct scan_control * sc)509 static bool global_reclaim(struct scan_control *sc)
510 {
511 	return true;
512 }
513 
writeback_throttling_sane(struct scan_control * sc)514 static bool writeback_throttling_sane(struct scan_control *sc)
515 {
516 	return true;
517 }
518 #endif
519 
xchg_nr_deferred(struct shrinker * shrinker,struct shrink_control * sc)520 static long xchg_nr_deferred(struct shrinker *shrinker,
521 			     struct shrink_control *sc)
522 {
523 	int nid = sc->nid;
524 
525 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
526 		nid = 0;
527 
528 	if (sc->memcg &&
529 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
530 		return xchg_nr_deferred_memcg(nid, shrinker,
531 					      sc->memcg);
532 
533 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
534 }
535 
536 
add_nr_deferred(long nr,struct shrinker * shrinker,struct shrink_control * sc)537 static long add_nr_deferred(long nr, struct shrinker *shrinker,
538 			    struct shrink_control *sc)
539 {
540 	int nid = sc->nid;
541 
542 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
543 		nid = 0;
544 
545 	if (sc->memcg &&
546 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
547 		return add_nr_deferred_memcg(nr, nid, shrinker,
548 					     sc->memcg);
549 
550 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
551 }
552 
can_demote(int nid,struct scan_control * sc)553 static bool can_demote(int nid, struct scan_control *sc)
554 {
555 	if (!numa_demotion_enabled)
556 		return false;
557 	if (sc) {
558 		if (sc->no_demotion)
559 			return false;
560 		/* It is pointless to do demotion in memcg reclaim */
561 		if (cgroup_reclaim(sc))
562 			return false;
563 	}
564 	if (next_demotion_node(nid) == NUMA_NO_NODE)
565 		return false;
566 
567 	return true;
568 }
569 
can_reclaim_anon_pages(struct mem_cgroup * memcg,int nid,struct scan_control * sc)570 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
571 					  int nid,
572 					  struct scan_control *sc)
573 {
574 	if (memcg == NULL) {
575 		/*
576 		 * For non-memcg reclaim, is there
577 		 * space in any swap device?
578 		 */
579 		if (get_nr_swap_pages() > 0)
580 			return true;
581 	} else {
582 		/* Is the memcg below its swap limit? */
583 		if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
584 			return true;
585 	}
586 
587 	/*
588 	 * The page can not be swapped.
589 	 *
590 	 * Can it be reclaimed from this node via demotion?
591 	 */
592 	return can_demote(nid, sc);
593 }
594 
595 /*
596  * This misses isolated pages which are not accounted for to save counters.
597  * As the data only determines if reclaim or compaction continues, it is
598  * not expected that isolated pages will be a dominating factor.
599  */
zone_reclaimable_pages(struct zone * zone)600 unsigned long zone_reclaimable_pages(struct zone *zone)
601 {
602 	unsigned long nr;
603 
604 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
605 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
606 	if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
607 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
608 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
609 
610 	return nr;
611 }
612 
613 /**
614  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
615  * @lruvec: lru vector
616  * @lru: lru to use
617  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
618  */
lruvec_lru_size(struct lruvec * lruvec,enum lru_list lru,int zone_idx)619 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
620 				     int zone_idx)
621 {
622 	unsigned long size = 0;
623 	int zid;
624 
625 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
626 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
627 
628 		if (!managed_zone(zone))
629 			continue;
630 
631 		if (!mem_cgroup_disabled())
632 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
633 		else
634 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
635 	}
636 	return size;
637 }
638 
639 /*
640  * Add a shrinker callback to be called from the vm.
641  */
prealloc_shrinker(struct shrinker * shrinker)642 int prealloc_shrinker(struct shrinker *shrinker)
643 {
644 	unsigned int size;
645 	int err;
646 
647 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
648 		err = prealloc_memcg_shrinker(shrinker);
649 		if (err != -ENOSYS)
650 			return err;
651 
652 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
653 	}
654 
655 	size = sizeof(*shrinker->nr_deferred);
656 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
657 		size *= nr_node_ids;
658 
659 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
660 	if (!shrinker->nr_deferred)
661 		return -ENOMEM;
662 
663 	return 0;
664 }
665 
free_prealloced_shrinker(struct shrinker * shrinker)666 void free_prealloced_shrinker(struct shrinker *shrinker)
667 {
668 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
669 		down_write(&shrinker_rwsem);
670 		unregister_memcg_shrinker(shrinker);
671 		up_write(&shrinker_rwsem);
672 		return;
673 	}
674 
675 	kfree(shrinker->nr_deferred);
676 	shrinker->nr_deferred = NULL;
677 }
678 
register_shrinker_prepared(struct shrinker * shrinker)679 void register_shrinker_prepared(struct shrinker *shrinker)
680 {
681 	down_write(&shrinker_rwsem);
682 	list_add_tail(&shrinker->list, &shrinker_list);
683 	shrinker->flags |= SHRINKER_REGISTERED;
684 	up_write(&shrinker_rwsem);
685 }
686 
register_shrinker(struct shrinker * shrinker)687 int register_shrinker(struct shrinker *shrinker)
688 {
689 	int err = prealloc_shrinker(shrinker);
690 
691 	if (err)
692 		return err;
693 	register_shrinker_prepared(shrinker);
694 	return 0;
695 }
696 EXPORT_SYMBOL(register_shrinker);
697 
698 /*
699  * Remove one
700  */
unregister_shrinker(struct shrinker * shrinker)701 void unregister_shrinker(struct shrinker *shrinker)
702 {
703 	if (!(shrinker->flags & SHRINKER_REGISTERED))
704 		return;
705 
706 	down_write(&shrinker_rwsem);
707 	list_del(&shrinker->list);
708 	shrinker->flags &= ~SHRINKER_REGISTERED;
709 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
710 		unregister_memcg_shrinker(shrinker);
711 	up_write(&shrinker_rwsem);
712 
713 	kfree(shrinker->nr_deferred);
714 	shrinker->nr_deferred = NULL;
715 }
716 EXPORT_SYMBOL(unregister_shrinker);
717 
718 #define SHRINK_BATCH 128
719 
do_shrink_slab(struct shrink_control * shrinkctl,struct shrinker * shrinker,int priority)720 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
721 				    struct shrinker *shrinker, int priority)
722 {
723 	unsigned long freed = 0;
724 	unsigned long long delta;
725 	long total_scan;
726 	long freeable;
727 	long nr;
728 	long new_nr;
729 	long batch_size = shrinker->batch ? shrinker->batch
730 					  : SHRINK_BATCH;
731 	long scanned = 0, next_deferred;
732 
733 	trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
734 
735 	freeable = shrinker->count_objects(shrinker, shrinkctl);
736 	if (freeable == 0 || freeable == SHRINK_EMPTY)
737 		return freeable;
738 
739 	/*
740 	 * copy the current shrinker scan count into a local variable
741 	 * and zero it so that other concurrent shrinker invocations
742 	 * don't also do this scanning work.
743 	 */
744 	nr = xchg_nr_deferred(shrinker, shrinkctl);
745 
746 	if (shrinker->seeks) {
747 		delta = freeable >> priority;
748 		delta *= 4;
749 		do_div(delta, shrinker->seeks);
750 	} else {
751 		/*
752 		 * These objects don't require any IO to create. Trim
753 		 * them aggressively under memory pressure to keep
754 		 * them from causing refetches in the IO caches.
755 		 */
756 		delta = freeable / 2;
757 	}
758 
759 	total_scan = nr >> priority;
760 	total_scan += delta;
761 	total_scan = min(total_scan, (2 * freeable));
762 
763 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
764 				   freeable, delta, total_scan, priority);
765 
766 	/*
767 	 * Normally, we should not scan less than batch_size objects in one
768 	 * pass to avoid too frequent shrinker calls, but if the slab has less
769 	 * than batch_size objects in total and we are really tight on memory,
770 	 * we will try to reclaim all available objects, otherwise we can end
771 	 * up failing allocations although there are plenty of reclaimable
772 	 * objects spread over several slabs with usage less than the
773 	 * batch_size.
774 	 *
775 	 * We detect the "tight on memory" situations by looking at the total
776 	 * number of objects we want to scan (total_scan). If it is greater
777 	 * than the total number of objects on slab (freeable), we must be
778 	 * scanning at high prio and therefore should try to reclaim as much as
779 	 * possible.
780 	 */
781 	while (total_scan >= batch_size ||
782 	       total_scan >= freeable) {
783 		unsigned long ret;
784 		unsigned long nr_to_scan = min(batch_size, total_scan);
785 
786 		shrinkctl->nr_to_scan = nr_to_scan;
787 		shrinkctl->nr_scanned = nr_to_scan;
788 		ret = shrinker->scan_objects(shrinker, shrinkctl);
789 		if (ret == SHRINK_STOP)
790 			break;
791 		freed += ret;
792 
793 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
794 		total_scan -= shrinkctl->nr_scanned;
795 		scanned += shrinkctl->nr_scanned;
796 
797 		cond_resched();
798 	}
799 
800 	/*
801 	 * The deferred work is increased by any new work (delta) that wasn't
802 	 * done, decreased by old deferred work that was done now.
803 	 *
804 	 * And it is capped to two times of the freeable items.
805 	 */
806 	next_deferred = max_t(long, (nr + delta - scanned), 0);
807 	next_deferred = min(next_deferred, (2 * freeable));
808 
809 	/*
810 	 * move the unused scan count back into the shrinker in a
811 	 * manner that handles concurrent updates.
812 	 */
813 	new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
814 
815 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
816 	return freed;
817 }
818 
819 #ifdef CONFIG_MEMCG
shrink_slab_memcg(gfp_t gfp_mask,int nid,struct mem_cgroup * memcg,int priority)820 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
821 			struct mem_cgroup *memcg, int priority)
822 {
823 	struct shrinker_info *info;
824 	unsigned long ret, freed = 0;
825 	int i;
826 
827 	if (!mem_cgroup_online(memcg))
828 		return 0;
829 
830 	if (!down_read_trylock(&shrinker_rwsem))
831 		return 0;
832 
833 	info = shrinker_info_protected(memcg, nid);
834 	if (unlikely(!info))
835 		goto unlock;
836 
837 	for_each_set_bit(i, info->map, shrinker_nr_max) {
838 		struct shrink_control sc = {
839 			.gfp_mask = gfp_mask,
840 			.nid = nid,
841 			.memcg = memcg,
842 		};
843 		struct shrinker *shrinker;
844 
845 		shrinker = idr_find(&shrinker_idr, i);
846 		if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
847 			if (!shrinker)
848 				clear_bit(i, info->map);
849 			continue;
850 		}
851 
852 		/* Call non-slab shrinkers even though kmem is disabled */
853 		if (!memcg_kmem_enabled() &&
854 		    !(shrinker->flags & SHRINKER_NONSLAB))
855 			continue;
856 
857 		ret = do_shrink_slab(&sc, shrinker, priority);
858 		if (ret == SHRINK_EMPTY) {
859 			clear_bit(i, info->map);
860 			/*
861 			 * After the shrinker reported that it had no objects to
862 			 * free, but before we cleared the corresponding bit in
863 			 * the memcg shrinker map, a new object might have been
864 			 * added. To make sure, we have the bit set in this
865 			 * case, we invoke the shrinker one more time and reset
866 			 * the bit if it reports that it is not empty anymore.
867 			 * The memory barrier here pairs with the barrier in
868 			 * set_shrinker_bit():
869 			 *
870 			 * list_lru_add()     shrink_slab_memcg()
871 			 *   list_add_tail()    clear_bit()
872 			 *   <MB>               <MB>
873 			 *   set_bit()          do_shrink_slab()
874 			 */
875 			smp_mb__after_atomic();
876 			ret = do_shrink_slab(&sc, shrinker, priority);
877 			if (ret == SHRINK_EMPTY)
878 				ret = 0;
879 			else
880 				set_shrinker_bit(memcg, nid, i);
881 		}
882 		freed += ret;
883 
884 		if (rwsem_is_contended(&shrinker_rwsem)) {
885 			freed = freed ? : 1;
886 			break;
887 		}
888 	}
889 unlock:
890 	up_read(&shrinker_rwsem);
891 	return freed;
892 }
893 #else /* CONFIG_MEMCG */
shrink_slab_memcg(gfp_t gfp_mask,int nid,struct mem_cgroup * memcg,int priority)894 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
895 			struct mem_cgroup *memcg, int priority)
896 {
897 	return 0;
898 }
899 #endif /* CONFIG_MEMCG */
900 
901 /**
902  * shrink_slab - shrink slab caches
903  * @gfp_mask: allocation context
904  * @nid: node whose slab caches to target
905  * @memcg: memory cgroup whose slab caches to target
906  * @priority: the reclaim priority
907  *
908  * Call the shrink functions to age shrinkable caches.
909  *
910  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
911  * unaware shrinkers will receive a node id of 0 instead.
912  *
913  * @memcg specifies the memory cgroup to target. Unaware shrinkers
914  * are called only if it is the root cgroup.
915  *
916  * @priority is sc->priority, we take the number of objects and >> by priority
917  * in order to get the scan target.
918  *
919  * Returns the number of reclaimed slab objects.
920  */
shrink_slab(gfp_t gfp_mask,int nid,struct mem_cgroup * memcg,int priority)921 unsigned long shrink_slab(gfp_t gfp_mask, int nid,
922 				 struct mem_cgroup *memcg,
923 				 int priority)
924 {
925 	unsigned long ret, freed = 0;
926 	struct shrinker *shrinker;
927 	bool bypass = false;
928 
929 	trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
930 	if (bypass)
931 		return 0;
932 
933 	/*
934 	 * The root memcg might be allocated even though memcg is disabled
935 	 * via "cgroup_disable=memory" boot parameter.  This could make
936 	 * mem_cgroup_is_root() return false, then just run memcg slab
937 	 * shrink, but skip global shrink.  This may result in premature
938 	 * oom.
939 	 */
940 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
941 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
942 
943 	if (!down_read_trylock(&shrinker_rwsem))
944 		goto out;
945 
946 	list_for_each_entry(shrinker, &shrinker_list, list) {
947 		struct shrink_control sc = {
948 			.gfp_mask = gfp_mask,
949 			.nid = nid,
950 			.memcg = memcg,
951 		};
952 
953 		ret = do_shrink_slab(&sc, shrinker, priority);
954 		if (ret == SHRINK_EMPTY)
955 			ret = 0;
956 		freed += ret;
957 		/*
958 		 * Bail out if someone want to register a new shrinker to
959 		 * prevent the registration from being stalled for long periods
960 		 * by parallel ongoing shrinking.
961 		 */
962 		if (rwsem_is_contended(&shrinker_rwsem)) {
963 			freed = freed ? : 1;
964 			break;
965 		}
966 	}
967 
968 	up_read(&shrinker_rwsem);
969 out:
970 	cond_resched();
971 	return freed;
972 }
973 EXPORT_SYMBOL_GPL(shrink_slab);
974 
drop_slab_node(int nid)975 void drop_slab_node(int nid)
976 {
977 	unsigned long freed;
978 	int shift = 0;
979 
980 	do {
981 		struct mem_cgroup *memcg = NULL;
982 
983 		if (fatal_signal_pending(current))
984 			return;
985 
986 		freed = 0;
987 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
988 		do {
989 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
990 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
991 	} while ((freed >> shift++) > 1);
992 }
993 
drop_slab(void)994 void drop_slab(void)
995 {
996 	int nid;
997 
998 	for_each_online_node(nid)
999 		drop_slab_node(nid);
1000 }
1001 
is_page_cache_freeable(struct page * page)1002 static inline int is_page_cache_freeable(struct page *page)
1003 {
1004 	/*
1005 	 * A freeable page cache page is referenced only by the caller
1006 	 * that isolated the page, the page cache and optional buffer
1007 	 * heads at page->private.
1008 	 */
1009 	int page_cache_pins = thp_nr_pages(page);
1010 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
1011 }
1012 
may_write_to_inode(struct inode * inode)1013 static int may_write_to_inode(struct inode *inode)
1014 {
1015 	if (current->flags & PF_SWAPWRITE)
1016 		return 1;
1017 	if (!inode_write_congested(inode))
1018 		return 1;
1019 	if (inode_to_bdi(inode) == current->backing_dev_info)
1020 		return 1;
1021 	return 0;
1022 }
1023 
1024 /*
1025  * We detected a synchronous write error writing a page out.  Probably
1026  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
1027  * fsync(), msync() or close().
1028  *
1029  * The tricky part is that after writepage we cannot touch the mapping: nothing
1030  * prevents it from being freed up.  But we have a ref on the page and once
1031  * that page is locked, the mapping is pinned.
1032  *
1033  * We're allowed to run sleeping lock_page() here because we know the caller has
1034  * __GFP_FS.
1035  */
handle_write_error(struct address_space * mapping,struct page * page,int error)1036 static void handle_write_error(struct address_space *mapping,
1037 				struct page *page, int error)
1038 {
1039 	lock_page(page);
1040 	if (page_mapping(page) == mapping)
1041 		mapping_set_error(mapping, error);
1042 	unlock_page(page);
1043 }
1044 
1045 /* possible outcome of pageout() */
1046 typedef enum {
1047 	/* failed to write page out, page is locked */
1048 	PAGE_KEEP,
1049 	/* move page to the active list, page is locked */
1050 	PAGE_ACTIVATE,
1051 	/* page has been sent to the disk successfully, page is unlocked */
1052 	PAGE_SUCCESS,
1053 	/* page is clean and locked */
1054 	PAGE_CLEAN,
1055 } pageout_t;
1056 
1057 /*
1058  * pageout is called by shrink_page_list() for each dirty page.
1059  * Calls ->writepage().
1060  */
pageout(struct page * page,struct address_space * mapping)1061 static pageout_t pageout(struct page *page, struct address_space *mapping)
1062 {
1063 	/*
1064 	 * If the page is dirty, only perform writeback if that write
1065 	 * will be non-blocking.  To prevent this allocation from being
1066 	 * stalled by pagecache activity.  But note that there may be
1067 	 * stalls if we need to run get_block().  We could test
1068 	 * PagePrivate for that.
1069 	 *
1070 	 * If this process is currently in __generic_file_write_iter() against
1071 	 * this page's queue, we can perform writeback even if that
1072 	 * will block.
1073 	 *
1074 	 * If the page is swapcache, write it back even if that would
1075 	 * block, for some throttling. This happens by accident, because
1076 	 * swap_backing_dev_info is bust: it doesn't reflect the
1077 	 * congestion state of the swapdevs.  Easy to fix, if needed.
1078 	 */
1079 	if (!is_page_cache_freeable(page))
1080 		return PAGE_KEEP;
1081 	if (!mapping) {
1082 		/*
1083 		 * Some data journaling orphaned pages can have
1084 		 * page->mapping == NULL while being dirty with clean buffers.
1085 		 */
1086 		if (page_has_private(page)) {
1087 			if (try_to_free_buffers(page)) {
1088 				ClearPageDirty(page);
1089 				pr_info("%s: orphaned page\n", __func__);
1090 				return PAGE_CLEAN;
1091 			}
1092 		}
1093 		return PAGE_KEEP;
1094 	}
1095 	if (mapping->a_ops->writepage == NULL)
1096 		return PAGE_ACTIVATE;
1097 	if (!may_write_to_inode(mapping->host))
1098 		return PAGE_KEEP;
1099 
1100 	if (clear_page_dirty_for_io(page)) {
1101 		int res;
1102 		struct writeback_control wbc = {
1103 			.sync_mode = WB_SYNC_NONE,
1104 			.nr_to_write = SWAP_CLUSTER_MAX,
1105 			.range_start = 0,
1106 			.range_end = LLONG_MAX,
1107 			.for_reclaim = 1,
1108 		};
1109 
1110 		SetPageReclaim(page);
1111 		res = mapping->a_ops->writepage(page, &wbc);
1112 		if (res < 0)
1113 			handle_write_error(mapping, page, res);
1114 		if (res == AOP_WRITEPAGE_ACTIVATE) {
1115 			ClearPageReclaim(page);
1116 			return PAGE_ACTIVATE;
1117 		}
1118 
1119 		if (!PageWriteback(page)) {
1120 			/* synchronous write or broken a_ops? */
1121 			ClearPageReclaim(page);
1122 		}
1123 		trace_mm_vmscan_writepage(page);
1124 		inc_node_page_state(page, NR_VMSCAN_WRITE);
1125 		return PAGE_SUCCESS;
1126 	}
1127 
1128 	return PAGE_CLEAN;
1129 }
1130 
1131 /*
1132  * Same as remove_mapping, but if the page is removed from the mapping, it
1133  * gets returned with a refcount of 0.
1134  */
__remove_mapping(struct address_space * mapping,struct page * page,bool reclaimed,struct mem_cgroup * target_memcg)1135 static int __remove_mapping(struct address_space *mapping, struct page *page,
1136 			    bool reclaimed, struct mem_cgroup *target_memcg)
1137 {
1138 	int refcount;
1139 	void *shadow = NULL;
1140 
1141 	BUG_ON(!PageLocked(page));
1142 	BUG_ON(mapping != page_mapping(page));
1143 
1144 	xa_lock_irq(&mapping->i_pages);
1145 	/*
1146 	 * The non racy check for a busy page.
1147 	 *
1148 	 * Must be careful with the order of the tests. When someone has
1149 	 * a ref to the page, it may be possible that they dirty it then
1150 	 * drop the reference. So if PageDirty is tested before page_count
1151 	 * here, then the following race may occur:
1152 	 *
1153 	 * get_user_pages(&page);
1154 	 * [user mapping goes away]
1155 	 * write_to(page);
1156 	 *				!PageDirty(page)    [good]
1157 	 * SetPageDirty(page);
1158 	 * put_page(page);
1159 	 *				!page_count(page)   [good, discard it]
1160 	 *
1161 	 * [oops, our write_to data is lost]
1162 	 *
1163 	 * Reversing the order of the tests ensures such a situation cannot
1164 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
1165 	 * load is not satisfied before that of page->_refcount.
1166 	 *
1167 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1168 	 * and thus under the i_pages lock, then this ordering is not required.
1169 	 */
1170 	refcount = 1 + compound_nr(page);
1171 	if (!page_ref_freeze(page, refcount))
1172 		goto cannot_free;
1173 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1174 	if (unlikely(PageDirty(page))) {
1175 		page_ref_unfreeze(page, refcount);
1176 		goto cannot_free;
1177 	}
1178 
1179 	if (PageSwapCache(page)) {
1180 		swp_entry_t swap = { .val = page_private(page) };
1181 
1182 		/* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
1183 		if (reclaimed && !mapping_exiting(mapping))
1184 			shadow = workingset_eviction(page, target_memcg);
1185 		mem_cgroup_swapout(page, swap);
1186 		__delete_from_swap_cache(page, swap, shadow);
1187 		xa_unlock_irq(&mapping->i_pages);
1188 		put_swap_page(page, swap);
1189 	} else {
1190 		void (*freepage)(struct page *);
1191 
1192 		freepage = mapping->a_ops->freepage;
1193 		/*
1194 		 * Remember a shadow entry for reclaimed file cache in
1195 		 * order to detect refaults, thus thrashing, later on.
1196 		 *
1197 		 * But don't store shadows in an address space that is
1198 		 * already exiting.  This is not just an optimization,
1199 		 * inode reclaim needs to empty out the radix tree or
1200 		 * the nodes are lost.  Don't plant shadows behind its
1201 		 * back.
1202 		 *
1203 		 * We also don't store shadows for DAX mappings because the
1204 		 * only page cache pages found in these are zero pages
1205 		 * covering holes, and because we don't want to mix DAX
1206 		 * exceptional entries and shadow exceptional entries in the
1207 		 * same address_space.
1208 		 */
1209 		if (reclaimed && page_is_file_lru(page) &&
1210 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
1211 			shadow = workingset_eviction(page, target_memcg);
1212 		__delete_from_page_cache(page, shadow);
1213 		xa_unlock_irq(&mapping->i_pages);
1214 
1215 		if (freepage != NULL)
1216 			freepage(page);
1217 	}
1218 
1219 	return 1;
1220 
1221 cannot_free:
1222 	xa_unlock_irq(&mapping->i_pages);
1223 	return 0;
1224 }
1225 
1226 /*
1227  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
1228  * someone else has a ref on the page, abort and return 0.  If it was
1229  * successfully detached, return 1.  Assumes the caller has a single ref on
1230  * this page.
1231  */
remove_mapping(struct address_space * mapping,struct page * page)1232 int remove_mapping(struct address_space *mapping, struct page *page)
1233 {
1234 	if (__remove_mapping(mapping, page, false, NULL)) {
1235 		/*
1236 		 * Unfreezing the refcount with 1 rather than 2 effectively
1237 		 * drops the pagecache ref for us without requiring another
1238 		 * atomic operation.
1239 		 */
1240 		page_ref_unfreeze(page, 1);
1241 		return 1;
1242 	}
1243 	return 0;
1244 }
1245 
1246 /**
1247  * putback_lru_page - put previously isolated page onto appropriate LRU list
1248  * @page: page to be put back to appropriate lru list
1249  *
1250  * Add previously isolated @page to appropriate LRU list.
1251  * Page may still be unevictable for other reasons.
1252  *
1253  * lru_lock must not be held, interrupts must be enabled.
1254  */
putback_lru_page(struct page * page)1255 void putback_lru_page(struct page *page)
1256 {
1257 	lru_cache_add(page);
1258 	put_page(page);		/* drop ref from isolate */
1259 }
1260 
1261 enum page_references {
1262 	PAGEREF_RECLAIM,
1263 	PAGEREF_RECLAIM_CLEAN,
1264 	PAGEREF_KEEP,
1265 	PAGEREF_ACTIVATE,
1266 };
1267 
page_check_references(struct page * page,struct scan_control * sc)1268 static enum page_references page_check_references(struct page *page,
1269 						  struct scan_control *sc)
1270 {
1271 	int referenced_ptes, referenced_page;
1272 	unsigned long vm_flags;
1273 
1274 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1275 					  &vm_flags);
1276 	referenced_page = TestClearPageReferenced(page);
1277 
1278 	/*
1279 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1280 	 * move the page to the unevictable list.
1281 	 */
1282 	if (vm_flags & VM_LOCKED)
1283 		return PAGEREF_RECLAIM;
1284 
1285 	/* rmap lock contention: rotate */
1286 	if (referenced_ptes == -1)
1287 		return PAGEREF_KEEP;
1288 
1289 	if (referenced_ptes) {
1290 		/*
1291 		 * All mapped pages start out with page table
1292 		 * references from the instantiating fault, so we need
1293 		 * to look twice if a mapped file page is used more
1294 		 * than once.
1295 		 *
1296 		 * Mark it and spare it for another trip around the
1297 		 * inactive list.  Another page table reference will
1298 		 * lead to its activation.
1299 		 *
1300 		 * Note: the mark is set for activated pages as well
1301 		 * so that recently deactivated but used pages are
1302 		 * quickly recovered.
1303 		 */
1304 		SetPageReferenced(page);
1305 
1306 		if (referenced_page || referenced_ptes > 1)
1307 			return PAGEREF_ACTIVATE;
1308 
1309 		/*
1310 		 * Activate file-backed executable pages after first usage.
1311 		 */
1312 		if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1313 			return PAGEREF_ACTIVATE;
1314 
1315 		return PAGEREF_KEEP;
1316 	}
1317 
1318 	/* Reclaim if clean, defer dirty pages to writeback */
1319 	if (referenced_page && !PageSwapBacked(page))
1320 		return PAGEREF_RECLAIM_CLEAN;
1321 
1322 	return PAGEREF_RECLAIM;
1323 }
1324 
1325 /* Check if a page is dirty or under writeback */
page_check_dirty_writeback(struct page * page,bool * dirty,bool * writeback)1326 static void page_check_dirty_writeback(struct page *page,
1327 				       bool *dirty, bool *writeback)
1328 {
1329 	struct address_space *mapping;
1330 
1331 	/*
1332 	 * Anonymous pages are not handled by flushers and must be written
1333 	 * from reclaim context. Do not stall reclaim based on them
1334 	 */
1335 	if (!page_is_file_lru(page) ||
1336 	    (PageAnon(page) && !PageSwapBacked(page))) {
1337 		*dirty = false;
1338 		*writeback = false;
1339 		return;
1340 	}
1341 
1342 	/* By default assume that the page flags are accurate */
1343 	*dirty = PageDirty(page);
1344 	*writeback = PageWriteback(page);
1345 
1346 	/* Verify dirty/writeback state if the filesystem supports it */
1347 	if (!page_has_private(page))
1348 		return;
1349 
1350 	mapping = page_mapping(page);
1351 	if (mapping && mapping->a_ops->is_dirty_writeback)
1352 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1353 }
1354 
alloc_demote_page(struct page * page,unsigned long node)1355 static struct page *alloc_demote_page(struct page *page, unsigned long node)
1356 {
1357 	struct migration_target_control mtc = {
1358 		/*
1359 		 * Allocate from 'node', or fail quickly and quietly.
1360 		 * When this happens, 'page' will likely just be discarded
1361 		 * instead of migrated.
1362 		 */
1363 		.gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1364 			    __GFP_THISNODE  | __GFP_NOWARN |
1365 			    __GFP_NOMEMALLOC | GFP_NOWAIT,
1366 		.nid = node
1367 	};
1368 
1369 	return alloc_migration_target(page, (unsigned long)&mtc);
1370 }
1371 
1372 /*
1373  * Take pages on @demote_list and attempt to demote them to
1374  * another node.  Pages which are not demoted are left on
1375  * @demote_pages.
1376  */
demote_page_list(struct list_head * demote_pages,struct pglist_data * pgdat)1377 static unsigned int demote_page_list(struct list_head *demote_pages,
1378 				     struct pglist_data *pgdat)
1379 {
1380 	int target_nid = next_demotion_node(pgdat->node_id);
1381 	unsigned int nr_succeeded;
1382 	int err;
1383 
1384 	if (list_empty(demote_pages))
1385 		return 0;
1386 
1387 	if (target_nid == NUMA_NO_NODE)
1388 		return 0;
1389 
1390 	/* Demotion ignores all cpuset and mempolicy settings */
1391 	err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1392 			    target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1393 			    &nr_succeeded);
1394 
1395 	if (current_is_kswapd())
1396 		__count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1397 	else
1398 		__count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1399 
1400 	return nr_succeeded;
1401 }
1402 
1403 /*
1404  * shrink_page_list() returns the number of reclaimed pages
1405  */
shrink_page_list(struct list_head * page_list,struct pglist_data * pgdat,struct scan_control * sc,struct reclaim_stat * stat,bool ignore_references)1406 static unsigned int shrink_page_list(struct list_head *page_list,
1407 				     struct pglist_data *pgdat,
1408 				     struct scan_control *sc,
1409 				     struct reclaim_stat *stat,
1410 				     bool ignore_references)
1411 {
1412 	LIST_HEAD(ret_pages);
1413 	LIST_HEAD(free_pages);
1414 	LIST_HEAD(demote_pages);
1415 	unsigned int nr_reclaimed = 0;
1416 	unsigned int pgactivate = 0;
1417 	bool do_demote_pass;
1418 
1419 	memset(stat, 0, sizeof(*stat));
1420 	cond_resched();
1421 	do_demote_pass = can_demote(pgdat->node_id, sc);
1422 
1423 retry:
1424 	while (!list_empty(page_list)) {
1425 		struct address_space *mapping;
1426 		struct page *page;
1427 		enum page_references references = PAGEREF_RECLAIM;
1428 		bool dirty, writeback, may_enter_fs;
1429 		unsigned int nr_pages;
1430 
1431 		cond_resched();
1432 
1433 		page = lru_to_page(page_list);
1434 		list_del(&page->lru);
1435 
1436 		if (!trylock_page(page))
1437 			goto keep;
1438 
1439 		VM_BUG_ON_PAGE(PageActive(page), page);
1440 
1441 		nr_pages = compound_nr(page);
1442 
1443 		/* Account the number of base pages even though THP */
1444 		sc->nr_scanned += nr_pages;
1445 
1446 		if (unlikely(!page_evictable(page)))
1447 			goto activate_locked;
1448 
1449 		if (!sc->may_unmap && page_mapped(page))
1450 			goto keep_locked;
1451 
1452 		/* page_update_gen() tried to promote this page? */
1453 		if (lru_gen_enabled() && !ignore_references &&
1454 		    page_mapped(page) && PageReferenced(page))
1455 			goto keep_locked;
1456 
1457 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1458 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1459 
1460 		/*
1461 		 * The number of dirty pages determines if a node is marked
1462 		 * reclaim_congested which affects wait_iff_congested. kswapd
1463 		 * will stall and start writing pages if the tail of the LRU
1464 		 * is all dirty unqueued pages.
1465 		 */
1466 		page_check_dirty_writeback(page, &dirty, &writeback);
1467 		if (dirty || writeback)
1468 			stat->nr_dirty++;
1469 
1470 		if (dirty && !writeback)
1471 			stat->nr_unqueued_dirty++;
1472 
1473 		/*
1474 		 * Treat this page as congested if the underlying BDI is or if
1475 		 * pages are cycling through the LRU so quickly that the
1476 		 * pages marked for immediate reclaim are making it to the
1477 		 * end of the LRU a second time.
1478 		 */
1479 		mapping = page_mapping(page);
1480 		if (((dirty || writeback) && mapping &&
1481 		     inode_write_congested(mapping->host)) ||
1482 		    (writeback && PageReclaim(page)))
1483 			stat->nr_congested++;
1484 
1485 		/*
1486 		 * If a page at the tail of the LRU is under writeback, there
1487 		 * are three cases to consider.
1488 		 *
1489 		 * 1) If reclaim is encountering an excessive number of pages
1490 		 *    under writeback and this page is both under writeback and
1491 		 *    PageReclaim then it indicates that pages are being queued
1492 		 *    for IO but are being recycled through the LRU before the
1493 		 *    IO can complete. Waiting on the page itself risks an
1494 		 *    indefinite stall if it is impossible to writeback the
1495 		 *    page due to IO error or disconnected storage so instead
1496 		 *    note that the LRU is being scanned too quickly and the
1497 		 *    caller can stall after page list has been processed.
1498 		 *
1499 		 * 2) Global or new memcg reclaim encounters a page that is
1500 		 *    not marked for immediate reclaim, or the caller does not
1501 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1502 		 *    not to fs). In this case mark the page for immediate
1503 		 *    reclaim and continue scanning.
1504 		 *
1505 		 *    Require may_enter_fs because we would wait on fs, which
1506 		 *    may not have submitted IO yet. And the loop driver might
1507 		 *    enter reclaim, and deadlock if it waits on a page for
1508 		 *    which it is needed to do the write (loop masks off
1509 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1510 		 *    would probably show more reasons.
1511 		 *
1512 		 * 3) Legacy memcg encounters a page that is already marked
1513 		 *    PageReclaim. memcg does not have any dirty pages
1514 		 *    throttling so we could easily OOM just because too many
1515 		 *    pages are in writeback and there is nothing else to
1516 		 *    reclaim. Wait for the writeback to complete.
1517 		 *
1518 		 * In cases 1) and 2) we activate the pages to get them out of
1519 		 * the way while we continue scanning for clean pages on the
1520 		 * inactive list and refilling from the active list. The
1521 		 * observation here is that waiting for disk writes is more
1522 		 * expensive than potentially causing reloads down the line.
1523 		 * Since they're marked for immediate reclaim, they won't put
1524 		 * memory pressure on the cache working set any longer than it
1525 		 * takes to write them to disk.
1526 		 */
1527 		if (PageWriteback(page)) {
1528 			/* Case 1 above */
1529 			if (current_is_kswapd() &&
1530 			    PageReclaim(page) &&
1531 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1532 				stat->nr_immediate++;
1533 				goto activate_locked;
1534 
1535 			/* Case 2 above */
1536 			} else if (writeback_throttling_sane(sc) ||
1537 			    !PageReclaim(page) || !may_enter_fs) {
1538 				/*
1539 				 * This is slightly racy - end_page_writeback()
1540 				 * might have just cleared PageReclaim, then
1541 				 * setting PageReclaim here end up interpreted
1542 				 * as PageReadahead - but that does not matter
1543 				 * enough to care.  What we do want is for this
1544 				 * page to have PageReclaim set next time memcg
1545 				 * reclaim reaches the tests above, so it will
1546 				 * then wait_on_page_writeback() to avoid OOM;
1547 				 * and it's also appropriate in global reclaim.
1548 				 */
1549 				SetPageReclaim(page);
1550 				stat->nr_writeback++;
1551 				goto activate_locked;
1552 
1553 			/* Case 3 above */
1554 			} else {
1555 				unlock_page(page);
1556 				wait_on_page_writeback(page);
1557 				/* then go back and try same page again */
1558 				list_add_tail(&page->lru, page_list);
1559 				continue;
1560 			}
1561 		}
1562 
1563 		if (!ignore_references)
1564 			references = page_check_references(page, sc);
1565 
1566 		switch (references) {
1567 		case PAGEREF_ACTIVATE:
1568 			goto activate_locked;
1569 		case PAGEREF_KEEP:
1570 			stat->nr_ref_keep += nr_pages;
1571 			goto keep_locked;
1572 		case PAGEREF_RECLAIM:
1573 		case PAGEREF_RECLAIM_CLEAN:
1574 			; /* try to reclaim the page below */
1575 		}
1576 
1577 		/*
1578 		 * Before reclaiming the page, try to relocate
1579 		 * its contents to another node.
1580 		 */
1581 		if (do_demote_pass &&
1582 		    (thp_migration_supported() || !PageTransHuge(page))) {
1583 			list_add(&page->lru, &demote_pages);
1584 			unlock_page(page);
1585 			continue;
1586 		}
1587 
1588 		/*
1589 		 * Anonymous process memory has backing store?
1590 		 * Try to allocate it some swap space here.
1591 		 * Lazyfree page could be freed directly
1592 		 */
1593 		if (PageAnon(page) && PageSwapBacked(page)) {
1594 			if (!PageSwapCache(page)) {
1595 				if (!(sc->gfp_mask & __GFP_IO))
1596 					goto keep_locked;
1597 				if (page_maybe_dma_pinned(page))
1598 					goto keep_locked;
1599 				if (PageTransHuge(page)) {
1600 					/* cannot split THP, skip it */
1601 					if (!can_split_huge_page(page, NULL))
1602 						goto activate_locked;
1603 					/*
1604 					 * Split pages without a PMD map right
1605 					 * away. Chances are some or all of the
1606 					 * tail pages can be freed without IO.
1607 					 */
1608 					if (!compound_mapcount(page) &&
1609 					    split_huge_page_to_list(page,
1610 								    page_list))
1611 						goto activate_locked;
1612 				}
1613 				if (!add_to_swap(page)) {
1614 					if (!PageTransHuge(page))
1615 						goto activate_locked_split;
1616 					/* Fallback to swap normal pages */
1617 					if (split_huge_page_to_list(page,
1618 								    page_list))
1619 						goto activate_locked;
1620 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1621 					count_vm_event(THP_SWPOUT_FALLBACK);
1622 #endif
1623 					if (!add_to_swap(page))
1624 						goto activate_locked_split;
1625 				}
1626 
1627 				may_enter_fs = true;
1628 
1629 				/* Adding to swap updated mapping */
1630 				mapping = page_mapping(page);
1631 			}
1632 		} else if (unlikely(PageTransHuge(page))) {
1633 			/* Split file THP */
1634 			if (split_huge_page_to_list(page, page_list))
1635 				goto keep_locked;
1636 		}
1637 
1638 		/*
1639 		 * THP may get split above, need minus tail pages and update
1640 		 * nr_pages to avoid accounting tail pages twice.
1641 		 *
1642 		 * The tail pages that are added into swap cache successfully
1643 		 * reach here.
1644 		 */
1645 		if ((nr_pages > 1) && !PageTransHuge(page)) {
1646 			sc->nr_scanned -= (nr_pages - 1);
1647 			nr_pages = 1;
1648 		}
1649 
1650 		/*
1651 		 * The page is mapped into the page tables of one or more
1652 		 * processes. Try to unmap it here.
1653 		 */
1654 		if (page_mapped(page)) {
1655 			enum ttu_flags flags = TTU_BATCH_FLUSH;
1656 			bool was_swapbacked = PageSwapBacked(page);
1657 
1658 			if (unlikely(PageTransHuge(page)))
1659 				flags |= TTU_SPLIT_HUGE_PMD;
1660 
1661 			try_to_unmap(page, flags);
1662 			if (page_mapped(page)) {
1663 				stat->nr_unmap_fail += nr_pages;
1664 				if (!was_swapbacked && PageSwapBacked(page))
1665 					stat->nr_lazyfree_fail += nr_pages;
1666 				goto activate_locked;
1667 			}
1668 		}
1669 
1670 		if (PageDirty(page)) {
1671 			/*
1672 			 * Only kswapd can writeback filesystem pages
1673 			 * to avoid risk of stack overflow. But avoid
1674 			 * injecting inefficient single-page IO into
1675 			 * flusher writeback as much as possible: only
1676 			 * write pages when we've encountered many
1677 			 * dirty pages, and when we've already scanned
1678 			 * the rest of the LRU for clean pages and see
1679 			 * the same dirty pages again (PageReclaim).
1680 			 */
1681 			if (page_is_file_lru(page) &&
1682 			    (!current_is_kswapd() || !PageReclaim(page) ||
1683 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1684 				/*
1685 				 * Immediately reclaim when written back.
1686 				 * Similar in principal to deactivate_page()
1687 				 * except we already have the page isolated
1688 				 * and know it's dirty
1689 				 */
1690 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
1691 				SetPageReclaim(page);
1692 
1693 				goto activate_locked;
1694 			}
1695 
1696 			if (references == PAGEREF_RECLAIM_CLEAN)
1697 				goto keep_locked;
1698 			if (!may_enter_fs)
1699 				goto keep_locked;
1700 			if (!sc->may_writepage)
1701 				goto keep_locked;
1702 
1703 			/*
1704 			 * Page is dirty. Flush the TLB if a writable entry
1705 			 * potentially exists to avoid CPU writes after IO
1706 			 * starts and then write it out here.
1707 			 */
1708 			try_to_unmap_flush_dirty();
1709 			switch (pageout(page, mapping)) {
1710 			case PAGE_KEEP:
1711 				goto keep_locked;
1712 			case PAGE_ACTIVATE:
1713 				goto activate_locked;
1714 			case PAGE_SUCCESS:
1715 				stat->nr_pageout += thp_nr_pages(page);
1716 
1717 				if (PageWriteback(page))
1718 					goto keep;
1719 				if (PageDirty(page))
1720 					goto keep;
1721 
1722 				/*
1723 				 * A synchronous write - probably a ramdisk.  Go
1724 				 * ahead and try to reclaim the page.
1725 				 */
1726 				if (!trylock_page(page))
1727 					goto keep;
1728 				if (PageDirty(page) || PageWriteback(page))
1729 					goto keep_locked;
1730 				mapping = page_mapping(page);
1731 				fallthrough;
1732 			case PAGE_CLEAN:
1733 				; /* try to free the page below */
1734 			}
1735 		}
1736 
1737 		/*
1738 		 * If the page has buffers, try to free the buffer mappings
1739 		 * associated with this page. If we succeed we try to free
1740 		 * the page as well.
1741 		 *
1742 		 * We do this even if the page is PageDirty().
1743 		 * try_to_release_page() does not perform I/O, but it is
1744 		 * possible for a page to have PageDirty set, but it is actually
1745 		 * clean (all its buffers are clean).  This happens if the
1746 		 * buffers were written out directly, with submit_bh(). ext3
1747 		 * will do this, as well as the blockdev mapping.
1748 		 * try_to_release_page() will discover that cleanness and will
1749 		 * drop the buffers and mark the page clean - it can be freed.
1750 		 *
1751 		 * Rarely, pages can have buffers and no ->mapping.  These are
1752 		 * the pages which were not successfully invalidated in
1753 		 * truncate_cleanup_page().  We try to drop those buffers here
1754 		 * and if that worked, and the page is no longer mapped into
1755 		 * process address space (page_count == 1) it can be freed.
1756 		 * Otherwise, leave the page on the LRU so it is swappable.
1757 		 */
1758 		if (page_has_private(page)) {
1759 			if (!try_to_release_page(page, sc->gfp_mask))
1760 				goto activate_locked;
1761 			if (!mapping && page_count(page) == 1) {
1762 				unlock_page(page);
1763 				if (put_page_testzero(page))
1764 					goto free_it;
1765 				else {
1766 					/*
1767 					 * rare race with speculative reference.
1768 					 * the speculative reference will free
1769 					 * this page shortly, so we may
1770 					 * increment nr_reclaimed here (and
1771 					 * leave it off the LRU).
1772 					 */
1773 					nr_reclaimed++;
1774 					continue;
1775 				}
1776 			}
1777 		}
1778 
1779 		if (PageAnon(page) && !PageSwapBacked(page)) {
1780 			/* follow __remove_mapping for reference */
1781 			if (!page_ref_freeze(page, 1))
1782 				goto keep_locked;
1783 			/*
1784 			 * The page has only one reference left, which is
1785 			 * from the isolation. After the caller puts the
1786 			 * page back on lru and drops the reference, the
1787 			 * page will be freed anyway. It doesn't matter
1788 			 * which lru it goes. So we don't bother checking
1789 			 * PageDirty here.
1790 			 */
1791 			count_vm_event(PGLAZYFREED);
1792 			count_memcg_page_event(page, PGLAZYFREED);
1793 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1794 							 sc->target_mem_cgroup))
1795 			goto keep_locked;
1796 
1797 		unlock_page(page);
1798 free_it:
1799 		/*
1800 		 * THP may get swapped out in a whole, need account
1801 		 * all base pages.
1802 		 */
1803 		nr_reclaimed += nr_pages;
1804 
1805 		/*
1806 		 * Is there need to periodically free_page_list? It would
1807 		 * appear not as the counts should be low
1808 		 */
1809 		if (unlikely(PageTransHuge(page)))
1810 			destroy_compound_page(page);
1811 		else
1812 			list_add(&page->lru, &free_pages);
1813 		continue;
1814 
1815 activate_locked_split:
1816 		/*
1817 		 * The tail pages that are failed to add into swap cache
1818 		 * reach here.  Fixup nr_scanned and nr_pages.
1819 		 */
1820 		if (nr_pages > 1) {
1821 			sc->nr_scanned -= (nr_pages - 1);
1822 			nr_pages = 1;
1823 		}
1824 activate_locked:
1825 		/* Not a candidate for swapping, so reclaim swap space. */
1826 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1827 						PageMlocked(page)))
1828 			try_to_free_swap(page);
1829 		VM_BUG_ON_PAGE(PageActive(page), page);
1830 		if (!PageMlocked(page)) {
1831 			int type = page_is_file_lru(page);
1832 			SetPageActive(page);
1833 			stat->nr_activate[type] += nr_pages;
1834 			count_memcg_page_event(page, PGACTIVATE);
1835 		}
1836 keep_locked:
1837 		unlock_page(page);
1838 keep:
1839 		list_add(&page->lru, &ret_pages);
1840 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
1841 	}
1842 	/* 'page_list' is always empty here */
1843 
1844 	/* Migrate pages selected for demotion */
1845 	nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1846 	/* Pages that could not be demoted are still in @demote_pages */
1847 	if (!list_empty(&demote_pages)) {
1848 		/* Pages which failed to demoted go back on @page_list for retry: */
1849 		list_splice_init(&demote_pages, page_list);
1850 		do_demote_pass = false;
1851 		goto retry;
1852 	}
1853 
1854 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1855 
1856 	mem_cgroup_uncharge_list(&free_pages);
1857 	try_to_unmap_flush();
1858 	free_unref_page_list(&free_pages);
1859 
1860 	list_splice(&ret_pages, page_list);
1861 	count_vm_events(PGACTIVATE, pgactivate);
1862 
1863 	return nr_reclaimed;
1864 }
1865 
reclaim_clean_pages_from_list(struct zone * zone,struct list_head * page_list)1866 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1867 					    struct list_head *page_list)
1868 {
1869 	struct scan_control sc = {
1870 		.gfp_mask = GFP_KERNEL,
1871 		.may_unmap = 1,
1872 	};
1873 	struct reclaim_stat stat;
1874 	unsigned int nr_reclaimed;
1875 	struct page *page, *next;
1876 	LIST_HEAD(clean_pages);
1877 	unsigned int noreclaim_flag;
1878 
1879 	list_for_each_entry_safe(page, next, page_list, lru) {
1880 		if (!PageHuge(page) && page_is_file_lru(page) &&
1881 		    !PageDirty(page) && !__PageMovable(page) &&
1882 		    !PageUnevictable(page)) {
1883 			ClearPageActive(page);
1884 			list_move(&page->lru, &clean_pages);
1885 		}
1886 	}
1887 
1888 	/*
1889 	 * We should be safe here since we are only dealing with file pages and
1890 	 * we are not kswapd and therefore cannot write dirty file pages. But
1891 	 * call memalloc_noreclaim_save() anyway, just in case these conditions
1892 	 * change in the future.
1893 	 */
1894 	noreclaim_flag = memalloc_noreclaim_save();
1895 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1896 					&stat, true);
1897 	memalloc_noreclaim_restore(noreclaim_flag);
1898 
1899 	list_splice(&clean_pages, page_list);
1900 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1901 			    -(long)nr_reclaimed);
1902 	/*
1903 	 * Since lazyfree pages are isolated from file LRU from the beginning,
1904 	 * they will rotate back to anonymous LRU in the end if it failed to
1905 	 * discard so isolated count will be mismatched.
1906 	 * Compensate the isolated count for both LRU lists.
1907 	 */
1908 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1909 			    stat.nr_lazyfree_fail);
1910 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1911 			    -(long)stat.nr_lazyfree_fail);
1912 	return nr_reclaimed;
1913 }
1914 
1915 /*
1916  * Update LRU sizes after isolating pages. The LRU size updates must
1917  * be complete before mem_cgroup_update_lru_size due to a sanity check.
1918  */
update_lru_sizes(struct lruvec * lruvec,enum lru_list lru,unsigned long * nr_zone_taken)1919 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1920 			enum lru_list lru, unsigned long *nr_zone_taken)
1921 {
1922 	int zid;
1923 
1924 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1925 		if (!nr_zone_taken[zid])
1926 			continue;
1927 
1928 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1929 	}
1930 
1931 }
1932 
1933 #ifdef CONFIG_CMA
1934 /*
1935  * It is waste of effort to scan and reclaim CMA pages if it is not available
1936  * for current allocation context. Kswapd can not be enrolled as it can not
1937  * distinguish this scenario by using sc->gfp_mask = GFP_KERNEL
1938  */
skip_cma(struct page * page,struct scan_control * sc)1939 static bool skip_cma(struct page *page, struct scan_control *sc)
1940 {
1941 	return !current_is_kswapd() &&
1942 			gfp_migratetype(sc->gfp_mask) != MIGRATE_MOVABLE &&
1943 			get_pageblock_migratetype(page) == MIGRATE_CMA;
1944 }
1945 #else
skip_cma(struct page * page,struct scan_control * sc)1946 static bool skip_cma(struct page *page, struct scan_control *sc)
1947 {
1948 	return false;
1949 }
1950 #endif
1951 
1952 /*
1953  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1954  *
1955  * lruvec->lru_lock is heavily contended.  Some of the functions that
1956  * shrink the lists perform better by taking out a batch of pages
1957  * and working on them outside the LRU lock.
1958  *
1959  * For pagecache intensive workloads, this function is the hottest
1960  * spot in the kernel (apart from copy_*_user functions).
1961  *
1962  * Lru_lock must be held before calling this function.
1963  *
1964  * @nr_to_scan:	The number of eligible pages to look through on the list.
1965  * @lruvec:	The LRU vector to pull pages from.
1966  * @dst:	The temp list to put pages on to.
1967  * @nr_scanned:	The number of pages that were scanned.
1968  * @sc:		The scan_control struct for this reclaim session
1969  * @lru:	LRU list id for isolating
1970  *
1971  * returns how many pages were moved onto *@dst.
1972  */
isolate_lru_pages(unsigned long nr_to_scan,struct lruvec * lruvec,struct list_head * dst,unsigned long * nr_scanned,struct scan_control * sc,enum lru_list lru)1973 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1974 		struct lruvec *lruvec, struct list_head *dst,
1975 		unsigned long *nr_scanned, struct scan_control *sc,
1976 		enum lru_list lru)
1977 {
1978 	struct list_head *src = &lruvec->lists[lru];
1979 	unsigned long nr_taken = 0;
1980 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1981 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1982 	unsigned long skipped = 0;
1983 	unsigned long scan, total_scan, nr_pages;
1984 	LIST_HEAD(pages_skipped);
1985 
1986 	total_scan = 0;
1987 	scan = 0;
1988 	while (scan < nr_to_scan && !list_empty(src)) {
1989 		struct list_head *move_to = src;
1990 		struct page *page;
1991 
1992 		page = lru_to_page(src);
1993 		prefetchw_prev_lru_page(page, src, flags);
1994 
1995 		nr_pages = compound_nr(page);
1996 		total_scan += nr_pages;
1997 
1998 		if (page_zonenum(page) > sc->reclaim_idx ||
1999 				skip_cma(page, sc)) {
2000 			nr_skipped[page_zonenum(page)] += nr_pages;
2001 			move_to = &pages_skipped;
2002 			goto move;
2003 		}
2004 
2005 		/*
2006 		 * Do not count skipped pages because that makes the function
2007 		 * return with no isolated pages if the LRU mostly contains
2008 		 * ineligible pages.  This causes the VM to not reclaim any
2009 		 * pages, triggering a premature OOM.
2010 		 * Account all tail pages of THP.
2011 		 */
2012 		scan += nr_pages;
2013 
2014 		if (!PageLRU(page))
2015 			goto move;
2016 		if (!sc->may_unmap && page_mapped(page))
2017 			goto move;
2018 
2019 		/*
2020 		 * Be careful not to clear PageLRU until after we're
2021 		 * sure the page is not being freed elsewhere -- the
2022 		 * page release code relies on it.
2023 		 */
2024 		if (unlikely(!get_page_unless_zero(page)))
2025 			goto move;
2026 
2027 		if (!TestClearPageLRU(page)) {
2028 			/* Another thread is already isolating this page */
2029 			put_page(page);
2030 			goto move;
2031 		}
2032 
2033 		nr_taken += nr_pages;
2034 		nr_zone_taken[page_zonenum(page)] += nr_pages;
2035 		move_to = dst;
2036 move:
2037 		list_move(&page->lru, move_to);
2038 	}
2039 
2040 	/*
2041 	 * Splice any skipped pages to the start of the LRU list. Note that
2042 	 * this disrupts the LRU order when reclaiming for lower zones but
2043 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2044 	 * scanning would soon rescan the same pages to skip and put the
2045 	 * system at risk of premature OOM.
2046 	 */
2047 	if (!list_empty(&pages_skipped)) {
2048 		int zid;
2049 
2050 		list_splice(&pages_skipped, src);
2051 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2052 			if (!nr_skipped[zid])
2053 				continue;
2054 
2055 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
2056 			skipped += nr_skipped[zid];
2057 		}
2058 	}
2059 	*nr_scanned = total_scan;
2060 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2061 				    total_scan, skipped, nr_taken,
2062 				    sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2063 	update_lru_sizes(lruvec, lru, nr_zone_taken);
2064 	return nr_taken;
2065 }
2066 
2067 /**
2068  * isolate_lru_page - tries to isolate a page from its LRU list
2069  * @page: page to isolate from its LRU list
2070  *
2071  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2072  * vmstat statistic corresponding to whatever LRU list the page was on.
2073  *
2074  * Returns 0 if the page was removed from an LRU list.
2075  * Returns -EBUSY if the page was not on an LRU list.
2076  *
2077  * The returned page will have PageLRU() cleared.  If it was found on
2078  * the active list, it will have PageActive set.  If it was found on
2079  * the unevictable list, it will have the PageUnevictable bit set. That flag
2080  * may need to be cleared by the caller before letting the page go.
2081  *
2082  * The vmstat statistic corresponding to the list on which the page was
2083  * found will be decremented.
2084  *
2085  * Restrictions:
2086  *
2087  * (1) Must be called with an elevated refcount on the page. This is a
2088  *     fundamental difference from isolate_lru_pages (which is called
2089  *     without a stable reference).
2090  * (2) the lru_lock must not be held.
2091  * (3) interrupts must be enabled.
2092  */
isolate_lru_page(struct page * page)2093 int isolate_lru_page(struct page *page)
2094 {
2095 	int ret = -EBUSY;
2096 
2097 	VM_BUG_ON_PAGE(!page_count(page), page);
2098 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
2099 
2100 	if (TestClearPageLRU(page)) {
2101 		struct lruvec *lruvec;
2102 
2103 		get_page(page);
2104 		lruvec = lock_page_lruvec_irq(page);
2105 		del_page_from_lru_list(page, lruvec);
2106 		unlock_page_lruvec_irq(lruvec);
2107 		ret = 0;
2108 	}
2109 
2110 	return ret;
2111 }
2112 
2113 /*
2114  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2115  * then get rescheduled. When there are massive number of tasks doing page
2116  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2117  * the LRU list will go small and be scanned faster than necessary, leading to
2118  * unnecessary swapping, thrashing and OOM.
2119  */
too_many_isolated(struct pglist_data * pgdat,int file,struct scan_control * sc)2120 static int too_many_isolated(struct pglist_data *pgdat, int file,
2121 		struct scan_control *sc)
2122 {
2123 	unsigned long inactive, isolated;
2124 
2125 	if (current_is_kswapd())
2126 		return 0;
2127 
2128 	if (!writeback_throttling_sane(sc))
2129 		return 0;
2130 
2131 	if (file) {
2132 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2133 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
2134 	} else {
2135 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2136 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2137 	}
2138 
2139 	/*
2140 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2141 	 * won't get blocked by normal direct-reclaimers, forming a circular
2142 	 * deadlock.
2143 	 */
2144 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2145 		inactive >>= 3;
2146 
2147 	return isolated > inactive;
2148 }
2149 
2150 /*
2151  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2152  * On return, @list is reused as a list of pages to be freed by the caller.
2153  *
2154  * Returns the number of pages moved to the given lruvec.
2155  */
move_pages_to_lru(struct lruvec * lruvec,struct list_head * list)2156 static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2157 				      struct list_head *list)
2158 {
2159 	int nr_pages, nr_moved = 0;
2160 	LIST_HEAD(pages_to_free);
2161 	struct page *page;
2162 
2163 	while (!list_empty(list)) {
2164 		page = lru_to_page(list);
2165 		VM_BUG_ON_PAGE(PageLRU(page), page);
2166 		list_del(&page->lru);
2167 		if (unlikely(!page_evictable(page))) {
2168 			spin_unlock_irq(&lruvec->lru_lock);
2169 			putback_lru_page(page);
2170 			spin_lock_irq(&lruvec->lru_lock);
2171 			continue;
2172 		}
2173 
2174 		/*
2175 		 * The SetPageLRU needs to be kept here for list integrity.
2176 		 * Otherwise:
2177 		 *   #0 move_pages_to_lru             #1 release_pages
2178 		 *   if !put_page_testzero
2179 		 *				      if (put_page_testzero())
2180 		 *				        !PageLRU //skip lru_lock
2181 		 *     SetPageLRU()
2182 		 *     list_add(&page->lru,)
2183 		 *                                        list_add(&page->lru,)
2184 		 */
2185 		SetPageLRU(page);
2186 
2187 		if (unlikely(put_page_testzero(page))) {
2188 			__clear_page_lru_flags(page);
2189 
2190 			if (unlikely(PageCompound(page))) {
2191 				spin_unlock_irq(&lruvec->lru_lock);
2192 				destroy_compound_page(page);
2193 				spin_lock_irq(&lruvec->lru_lock);
2194 			} else
2195 				list_add(&page->lru, &pages_to_free);
2196 
2197 			continue;
2198 		}
2199 
2200 		/*
2201 		 * All pages were isolated from the same lruvec (and isolation
2202 		 * inhibits memcg migration).
2203 		 */
2204 		VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
2205 		add_page_to_lru_list(page, lruvec);
2206 		nr_pages = thp_nr_pages(page);
2207 		nr_moved += nr_pages;
2208 		if (PageActive(page))
2209 			workingset_age_nonresident(lruvec, nr_pages);
2210 	}
2211 
2212 	/*
2213 	 * To save our caller's stack, now use input list for pages to free.
2214 	 */
2215 	list_splice(&pages_to_free, list);
2216 
2217 	return nr_moved;
2218 }
2219 
2220 /*
2221  * If a kernel thread (such as nfsd for loop-back mounts) services
2222  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2223  * In that case we should only throttle if the backing device it is
2224  * writing to is congested.  In other cases it is safe to throttle.
2225  */
current_may_throttle(void)2226 static int current_may_throttle(void)
2227 {
2228 	return !(current->flags & PF_LOCAL_THROTTLE) ||
2229 		current->backing_dev_info == NULL ||
2230 		bdi_write_congested(current->backing_dev_info);
2231 }
2232 
2233 /*
2234  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
2235  * of reclaimed pages
2236  */
2237 static unsigned long
shrink_inactive_list(unsigned long nr_to_scan,struct lruvec * lruvec,struct scan_control * sc,enum lru_list lru)2238 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
2239 		     struct scan_control *sc, enum lru_list lru)
2240 {
2241 	LIST_HEAD(page_list);
2242 	unsigned long nr_scanned;
2243 	unsigned int nr_reclaimed = 0;
2244 	unsigned long nr_taken;
2245 	struct reclaim_stat stat;
2246 	bool file = is_file_lru(lru);
2247 	enum vm_event_item item;
2248 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2249 	bool stalled = false;
2250 	struct blk_plug plug;
2251 	bool do_plug = false;
2252 
2253 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2254 		if (stalled)
2255 			return 0;
2256 
2257 		/* wait a bit for the reclaimer. */
2258 		msleep(100);
2259 		stalled = true;
2260 
2261 		/* We are about to die and free our memory. Return now. */
2262 		if (fatal_signal_pending(current))
2263 			return SWAP_CLUSTER_MAX;
2264 	}
2265 
2266 	lru_add_drain();
2267 
2268 	spin_lock_irq(&lruvec->lru_lock);
2269 
2270 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2271 				     &nr_scanned, sc, lru);
2272 
2273 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2274 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2275 	if (!cgroup_reclaim(sc))
2276 		__count_vm_events(item, nr_scanned);
2277 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2278 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2279 
2280 	spin_unlock_irq(&lruvec->lru_lock);
2281 
2282 	if (nr_taken == 0)
2283 		return 0;
2284 
2285 	trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2286 	if (do_plug)
2287 		blk_start_plug(&plug);
2288 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2289 
2290 	spin_lock_irq(&lruvec->lru_lock);
2291 	move_pages_to_lru(lruvec, &page_list);
2292 
2293 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2294 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2295 	if (!cgroup_reclaim(sc))
2296 		__count_vm_events(item, nr_reclaimed);
2297 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2298 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2299 	spin_unlock_irq(&lruvec->lru_lock);
2300 
2301 	if (do_plug)
2302 		blk_finish_plug(&plug);
2303 
2304 	lru_note_cost(lruvec, file, stat.nr_pageout);
2305 	mem_cgroup_uncharge_list(&page_list);
2306 	free_unref_page_list(&page_list);
2307 
2308 	/*
2309 	 * If dirty pages are scanned that are not queued for IO, it
2310 	 * implies that flushers are not doing their job. This can
2311 	 * happen when memory pressure pushes dirty pages to the end of
2312 	 * the LRU before the dirty limits are breached and the dirty
2313 	 * data has expired. It can also happen when the proportion of
2314 	 * dirty pages grows not through writes but through memory
2315 	 * pressure reclaiming all the clean cache. And in some cases,
2316 	 * the flushers simply cannot keep up with the allocation
2317 	 * rate. Nudge the flusher threads in case they are asleep.
2318 	 */
2319 	if (stat.nr_unqueued_dirty == nr_taken)
2320 		wakeup_flusher_threads(WB_REASON_VMSCAN);
2321 
2322 	sc->nr.dirty += stat.nr_dirty;
2323 	sc->nr.congested += stat.nr_congested;
2324 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2325 	sc->nr.writeback += stat.nr_writeback;
2326 	sc->nr.immediate += stat.nr_immediate;
2327 	sc->nr.taken += nr_taken;
2328 	if (file)
2329 		sc->nr.file_taken += nr_taken;
2330 
2331 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2332 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2333 	return nr_reclaimed;
2334 }
2335 
2336 /*
2337  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2338  *
2339  * We move them the other way if the page is referenced by one or more
2340  * processes.
2341  *
2342  * If the pages are mostly unmapped, the processing is fast and it is
2343  * appropriate to hold lru_lock across the whole operation.  But if
2344  * the pages are mapped, the processing is slow (page_referenced()), so
2345  * we should drop lru_lock around each page.  It's impossible to balance
2346  * this, so instead we remove the pages from the LRU while processing them.
2347  * It is safe to rely on PG_active against the non-LRU pages in here because
2348  * nobody will play with that bit on a non-LRU page.
2349  *
2350  * The downside is that we have to touch page->_refcount against each page.
2351  * But we had to alter page->flags anyway.
2352  */
shrink_active_list(unsigned long nr_to_scan,struct lruvec * lruvec,struct scan_control * sc,enum lru_list lru)2353 static void shrink_active_list(unsigned long nr_to_scan,
2354 			       struct lruvec *lruvec,
2355 			       struct scan_control *sc,
2356 			       enum lru_list lru)
2357 {
2358 	unsigned long nr_taken;
2359 	unsigned long nr_scanned;
2360 	unsigned long vm_flags;
2361 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
2362 	LIST_HEAD(l_active);
2363 	LIST_HEAD(l_inactive);
2364 	struct page *page;
2365 	unsigned nr_deactivate, nr_activate;
2366 	unsigned nr_rotated = 0;
2367 	int file = is_file_lru(lru);
2368 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2369 	bool bypass = false;
2370 
2371 	lru_add_drain();
2372 
2373 	spin_lock_irq(&lruvec->lru_lock);
2374 
2375 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2376 				     &nr_scanned, sc, lru);
2377 
2378 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2379 
2380 	if (!cgroup_reclaim(sc))
2381 		__count_vm_events(PGREFILL, nr_scanned);
2382 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2383 
2384 	spin_unlock_irq(&lruvec->lru_lock);
2385 
2386 	while (!list_empty(&l_hold)) {
2387 		cond_resched();
2388 		page = lru_to_page(&l_hold);
2389 		list_del(&page->lru);
2390 
2391 		if (unlikely(!page_evictable(page))) {
2392 			putback_lru_page(page);
2393 			continue;
2394 		}
2395 
2396 		if (unlikely(buffer_heads_over_limit)) {
2397 			if (page_has_private(page) && trylock_page(page)) {
2398 				if (page_has_private(page))
2399 					try_to_release_page(page, 0);
2400 				unlock_page(page);
2401 			}
2402 		}
2403 
2404 		trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2405 		if (bypass)
2406 			goto skip_page_referenced;
2407 
2408 		/* Referenced or rmap lock contention: rotate */
2409 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2410 				    &vm_flags) != 0) {
2411 			/*
2412 			 * Identify referenced, file-backed active pages and
2413 			 * give them one more trip around the active list. So
2414 			 * that executable code get better chances to stay in
2415 			 * memory under moderate memory pressure.  Anon pages
2416 			 * are not likely to be evicted by use-once streaming
2417 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
2418 			 * so we ignore them here.
2419 			 */
2420 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
2421 				nr_rotated += thp_nr_pages(page);
2422 				list_add(&page->lru, &l_active);
2423 				continue;
2424 			}
2425 		}
2426 skip_page_referenced:
2427 		ClearPageActive(page);	/* we are de-activating */
2428 		SetPageWorkingset(page);
2429 		list_add(&page->lru, &l_inactive);
2430 	}
2431 
2432 	/*
2433 	 * Move pages back to the lru list.
2434 	 */
2435 	spin_lock_irq(&lruvec->lru_lock);
2436 
2437 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2438 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2439 	/* Keep all free pages in l_active list */
2440 	list_splice(&l_inactive, &l_active);
2441 
2442 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
2443 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2444 
2445 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2446 	spin_unlock_irq(&lruvec->lru_lock);
2447 
2448 	mem_cgroup_uncharge_list(&l_active);
2449 	free_unref_page_list(&l_active);
2450 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2451 			nr_deactivate, nr_rotated, sc->priority, file);
2452 }
2453 
reclaim_pages(struct list_head * page_list)2454 unsigned long reclaim_pages(struct list_head *page_list)
2455 {
2456 	int nid = NUMA_NO_NODE;
2457 	unsigned int nr_reclaimed = 0;
2458 	LIST_HEAD(node_page_list);
2459 	struct reclaim_stat dummy_stat;
2460 	struct page *page;
2461 	struct blk_plug plug;
2462 	bool do_plug = false;
2463 	unsigned int noreclaim_flag;
2464 	struct scan_control sc = {
2465 		.gfp_mask = GFP_KERNEL,
2466 		.may_writepage = 1,
2467 		.may_unmap = 1,
2468 		.may_swap = 1,
2469 		.no_demotion = 1,
2470 	};
2471 
2472 	noreclaim_flag = memalloc_noreclaim_save();
2473 
2474 	trace_android_vh_reclaim_pages_plug(&do_plug);
2475 	if (do_plug)
2476 		blk_start_plug(&plug);
2477 
2478 	while (!list_empty(page_list)) {
2479 		page = lru_to_page(page_list);
2480 		if (nid == NUMA_NO_NODE) {
2481 			nid = page_to_nid(page);
2482 			INIT_LIST_HEAD(&node_page_list);
2483 		}
2484 
2485 		if (nid == page_to_nid(page)) {
2486 			ClearPageActive(page);
2487 			list_move(&page->lru, &node_page_list);
2488 			continue;
2489 		}
2490 
2491 		nr_reclaimed += shrink_page_list(&node_page_list,
2492 						NODE_DATA(nid),
2493 						&sc, &dummy_stat, false);
2494 		while (!list_empty(&node_page_list)) {
2495 			page = lru_to_page(&node_page_list);
2496 			list_del(&page->lru);
2497 			putback_lru_page(page);
2498 		}
2499 
2500 		nid = NUMA_NO_NODE;
2501 	}
2502 
2503 	if (!list_empty(&node_page_list)) {
2504 		nr_reclaimed += shrink_page_list(&node_page_list,
2505 						NODE_DATA(nid),
2506 						&sc, &dummy_stat, false);
2507 		while (!list_empty(&node_page_list)) {
2508 			page = lru_to_page(&node_page_list);
2509 			list_del(&page->lru);
2510 			putback_lru_page(page);
2511 		}
2512 	}
2513 
2514 	memalloc_noreclaim_restore(noreclaim_flag);
2515 
2516 	if (do_plug)
2517 		blk_finish_plug(&plug);
2518 
2519 	return nr_reclaimed;
2520 }
2521 
shrink_list(enum lru_list lru,unsigned long nr_to_scan,struct lruvec * lruvec,struct scan_control * sc)2522 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2523 				 struct lruvec *lruvec, struct scan_control *sc)
2524 {
2525 	if (is_active_lru(lru)) {
2526 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2527 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2528 		else
2529 			sc->skipped_deactivate = 1;
2530 		return 0;
2531 	}
2532 
2533 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2534 }
2535 
2536 /*
2537  * The inactive anon list should be small enough that the VM never has
2538  * to do too much work.
2539  *
2540  * The inactive file list should be small enough to leave most memory
2541  * to the established workingset on the scan-resistant active list,
2542  * but large enough to avoid thrashing the aggregate readahead window.
2543  *
2544  * Both inactive lists should also be large enough that each inactive
2545  * page has a chance to be referenced again before it is reclaimed.
2546  *
2547  * If that fails and refaulting is observed, the inactive list grows.
2548  *
2549  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2550  * on this LRU, maintained by the pageout code. An inactive_ratio
2551  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2552  *
2553  * total     target    max
2554  * memory    ratio     inactive
2555  * -------------------------------------
2556  *   10MB       1         5MB
2557  *  100MB       1        50MB
2558  *    1GB       3       250MB
2559  *   10GB      10       0.9GB
2560  *  100GB      31         3GB
2561  *    1TB     101        10GB
2562  *   10TB     320        32GB
2563  */
inactive_is_low(struct lruvec * lruvec,enum lru_list inactive_lru)2564 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2565 {
2566 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2567 	unsigned long inactive, active;
2568 	unsigned long inactive_ratio;
2569 	unsigned long gb;
2570 
2571 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2572 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2573 
2574 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
2575 	if (gb)
2576 		inactive_ratio = int_sqrt(10 * gb);
2577 	else
2578 		inactive_ratio = 1;
2579 
2580 	return inactive * inactive_ratio < active;
2581 }
2582 
2583 enum scan_balance {
2584 	SCAN_EQUAL,
2585 	SCAN_FRACT,
2586 	SCAN_ANON,
2587 	SCAN_FILE,
2588 };
2589 
prepare_scan_count(pg_data_t * pgdat,struct scan_control * sc)2590 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2591 {
2592 	unsigned long file;
2593 	struct lruvec *target_lruvec;
2594 
2595 	if (lru_gen_enabled())
2596 		return;
2597 
2598 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2599 
2600 	/*
2601 	 * Flush the memory cgroup stats, so that we read accurate per-memcg
2602 	 * lruvec stats for heuristics.
2603 	 */
2604 	mem_cgroup_flush_stats();
2605 
2606 	/*
2607 	 * Determine the scan balance between anon and file LRUs.
2608 	 */
2609 	spin_lock_irq(&target_lruvec->lru_lock);
2610 	sc->anon_cost = target_lruvec->anon_cost;
2611 	sc->file_cost = target_lruvec->file_cost;
2612 	spin_unlock_irq(&target_lruvec->lru_lock);
2613 
2614 	/*
2615 	 * Target desirable inactive:active list ratios for the anon
2616 	 * and file LRU lists.
2617 	 */
2618 	if (!sc->force_deactivate) {
2619 		unsigned long refaults;
2620 
2621 		refaults = lruvec_page_state(target_lruvec,
2622 				WORKINGSET_ACTIVATE_ANON);
2623 		if (refaults != target_lruvec->refaults[0] ||
2624 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2625 			sc->may_deactivate |= DEACTIVATE_ANON;
2626 		else
2627 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2628 
2629 		/*
2630 		 * When refaults are being observed, it means a new
2631 		 * workingset is being established. Deactivate to get
2632 		 * rid of any stale active pages quickly.
2633 		 */
2634 		refaults = lruvec_page_state(target_lruvec,
2635 				WORKINGSET_ACTIVATE_FILE);
2636 		if (refaults != target_lruvec->refaults[1] ||
2637 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2638 			sc->may_deactivate |= DEACTIVATE_FILE;
2639 		else
2640 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2641 	} else
2642 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2643 
2644 	/*
2645 	 * If we have plenty of inactive file pages that aren't
2646 	 * thrashing, try to reclaim those first before touching
2647 	 * anonymous pages.
2648 	 */
2649 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2650 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2651 		sc->cache_trim_mode = 1;
2652 	else
2653 		sc->cache_trim_mode = 0;
2654 
2655 	/*
2656 	 * Prevent the reclaimer from falling into the cache trap: as
2657 	 * cache pages start out inactive, every cache fault will tip
2658 	 * the scan balance towards the file LRU.  And as the file LRU
2659 	 * shrinks, so does the window for rotation from references.
2660 	 * This means we have a runaway feedback loop where a tiny
2661 	 * thrashing file LRU becomes infinitely more attractive than
2662 	 * anon pages.  Try to detect this based on file LRU size.
2663 	 */
2664 	if (!cgroup_reclaim(sc)) {
2665 		unsigned long total_high_wmark = 0;
2666 		unsigned long free, anon;
2667 		int z;
2668 
2669 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2670 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2671 			   node_page_state(pgdat, NR_INACTIVE_FILE);
2672 
2673 		for (z = 0; z < MAX_NR_ZONES; z++) {
2674 			struct zone *zone = &pgdat->node_zones[z];
2675 
2676 			if (!managed_zone(zone))
2677 				continue;
2678 
2679 			total_high_wmark += high_wmark_pages(zone);
2680 		}
2681 
2682 		/*
2683 		 * Consider anon: if that's low too, this isn't a
2684 		 * runaway file reclaim problem, but rather just
2685 		 * extreme pressure. Reclaim as per usual then.
2686 		 */
2687 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2688 
2689 		sc->file_is_tiny =
2690 			file + free <= total_high_wmark &&
2691 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2692 			anon >> sc->priority;
2693 	}
2694 }
2695 
2696 /*
2697  * Determine how aggressively the anon and file LRU lists should be
2698  * scanned.  The relative value of each set of LRU lists is determined
2699  * by looking at the fraction of the pages scanned we did rotate back
2700  * onto the active list instead of evict.
2701  *
2702  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2703  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2704  */
get_scan_count(struct lruvec * lruvec,struct scan_control * sc,unsigned long * nr)2705 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2706 			   unsigned long *nr)
2707 {
2708 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2709 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2710 	unsigned long anon_cost, file_cost, total_cost;
2711 	int swappiness = mem_cgroup_swappiness(memcg);
2712 	u64 fraction[ANON_AND_FILE];
2713 	u64 denominator = 0;	/* gcc */
2714 	enum scan_balance scan_balance;
2715 	unsigned long ap, fp;
2716 	enum lru_list lru;
2717 	bool balance_anon_file_reclaim = false;
2718 
2719 	/* If we have no swap space, do not bother scanning anon pages. */
2720 	if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2721 		scan_balance = SCAN_FILE;
2722 		goto out;
2723 	}
2724 
2725 	/*
2726 	 * Global reclaim will swap to prevent OOM even with no
2727 	 * swappiness, but memcg users want to use this knob to
2728 	 * disable swapping for individual groups completely when
2729 	 * using the memory controller's swap limit feature would be
2730 	 * too expensive.
2731 	 */
2732 	if (cgroup_reclaim(sc) && !swappiness) {
2733 		scan_balance = SCAN_FILE;
2734 		goto out;
2735 	}
2736 
2737 	/*
2738 	 * Do not apply any pressure balancing cleverness when the
2739 	 * system is close to OOM, scan both anon and file equally
2740 	 * (unless the swappiness setting disagrees with swapping).
2741 	 */
2742 	if (!sc->priority && swappiness) {
2743 		scan_balance = SCAN_EQUAL;
2744 		goto out;
2745 	}
2746 
2747 	/*
2748 	 * If the system is almost out of file pages, force-scan anon.
2749 	 */
2750 	if (sc->file_is_tiny) {
2751 		scan_balance = SCAN_ANON;
2752 		goto out;
2753 	}
2754 
2755 	trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2756 
2757 	/*
2758 	 * If there is enough inactive page cache, we do not reclaim
2759 	 * anything from the anonymous working right now. But when balancing
2760 	 * anon and page cache files for reclaim, allow swapping of anon pages
2761 	 * even if there are a number of inactive file cache pages.
2762 	 */
2763 	if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
2764 		scan_balance = SCAN_FILE;
2765 		goto out;
2766 	}
2767 
2768 	scan_balance = SCAN_FRACT;
2769 	/*
2770 	 * Calculate the pressure balance between anon and file pages.
2771 	 *
2772 	 * The amount of pressure we put on each LRU is inversely
2773 	 * proportional to the cost of reclaiming each list, as
2774 	 * determined by the share of pages that are refaulting, times
2775 	 * the relative IO cost of bringing back a swapped out
2776 	 * anonymous page vs reloading a filesystem page (swappiness).
2777 	 *
2778 	 * Although we limit that influence to ensure no list gets
2779 	 * left behind completely: at least a third of the pressure is
2780 	 * applied, before swappiness.
2781 	 *
2782 	 * With swappiness at 100, anon and file have equal IO cost.
2783 	 */
2784 	total_cost = sc->anon_cost + sc->file_cost;
2785 	anon_cost = total_cost + sc->anon_cost;
2786 	file_cost = total_cost + sc->file_cost;
2787 	total_cost = anon_cost + file_cost;
2788 
2789 	ap = swappiness * (total_cost + 1);
2790 	ap /= anon_cost + 1;
2791 
2792 	fp = (200 - swappiness) * (total_cost + 1);
2793 	fp /= file_cost + 1;
2794 
2795 	fraction[0] = ap;
2796 	fraction[1] = fp;
2797 	denominator = ap + fp;
2798 out:
2799 	for_each_evictable_lru(lru) {
2800 		int file = is_file_lru(lru);
2801 		unsigned long lruvec_size;
2802 		unsigned long low, min;
2803 		unsigned long scan;
2804 
2805 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2806 		mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2807 				      &min, &low);
2808 
2809 		if (min || low) {
2810 			/*
2811 			 * Scale a cgroup's reclaim pressure by proportioning
2812 			 * its current usage to its memory.low or memory.min
2813 			 * setting.
2814 			 *
2815 			 * This is important, as otherwise scanning aggression
2816 			 * becomes extremely binary -- from nothing as we
2817 			 * approach the memory protection threshold, to totally
2818 			 * nominal as we exceed it.  This results in requiring
2819 			 * setting extremely liberal protection thresholds. It
2820 			 * also means we simply get no protection at all if we
2821 			 * set it too low, which is not ideal.
2822 			 *
2823 			 * If there is any protection in place, we reduce scan
2824 			 * pressure by how much of the total memory used is
2825 			 * within protection thresholds.
2826 			 *
2827 			 * There is one special case: in the first reclaim pass,
2828 			 * we skip over all groups that are within their low
2829 			 * protection. If that fails to reclaim enough pages to
2830 			 * satisfy the reclaim goal, we come back and override
2831 			 * the best-effort low protection. However, we still
2832 			 * ideally want to honor how well-behaved groups are in
2833 			 * that case instead of simply punishing them all
2834 			 * equally. As such, we reclaim them based on how much
2835 			 * memory they are using, reducing the scan pressure
2836 			 * again by how much of the total memory used is under
2837 			 * hard protection.
2838 			 */
2839 			unsigned long cgroup_size = mem_cgroup_size(memcg);
2840 			unsigned long protection;
2841 
2842 			/* memory.low scaling, make sure we retry before OOM */
2843 			if (!sc->memcg_low_reclaim && low > min) {
2844 				protection = low;
2845 				sc->memcg_low_skipped = 1;
2846 			} else {
2847 				protection = min;
2848 			}
2849 
2850 			/* Avoid TOCTOU with earlier protection check */
2851 			cgroup_size = max(cgroup_size, protection);
2852 
2853 			scan = lruvec_size - lruvec_size * protection /
2854 				(cgroup_size + 1);
2855 
2856 			/*
2857 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
2858 			 * reclaim moving forwards, avoiding decrementing
2859 			 * sc->priority further than desirable.
2860 			 */
2861 			scan = max(scan, SWAP_CLUSTER_MAX);
2862 		} else {
2863 			scan = lruvec_size;
2864 		}
2865 
2866 		scan >>= sc->priority;
2867 
2868 		/*
2869 		 * If the cgroup's already been deleted, make sure to
2870 		 * scrape out the remaining cache.
2871 		 */
2872 		if (!scan && !mem_cgroup_online(memcg))
2873 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2874 
2875 		switch (scan_balance) {
2876 		case SCAN_EQUAL:
2877 			/* Scan lists relative to size */
2878 			break;
2879 		case SCAN_FRACT:
2880 			/*
2881 			 * Scan types proportional to swappiness and
2882 			 * their relative recent reclaim efficiency.
2883 			 * Make sure we don't miss the last page on
2884 			 * the offlined memory cgroups because of a
2885 			 * round-off error.
2886 			 */
2887 			scan = mem_cgroup_online(memcg) ?
2888 			       div64_u64(scan * fraction[file], denominator) :
2889 			       DIV64_U64_ROUND_UP(scan * fraction[file],
2890 						  denominator);
2891 			break;
2892 		case SCAN_FILE:
2893 		case SCAN_ANON:
2894 			/* Scan one type exclusively */
2895 			if ((scan_balance == SCAN_FILE) != file)
2896 				scan = 0;
2897 			break;
2898 		default:
2899 			/* Look ma, no brain */
2900 			BUG();
2901 		}
2902 
2903 		nr[lru] = scan;
2904 	}
2905 }
2906 
2907 /*
2908  * Anonymous LRU management is a waste if there is
2909  * ultimately no way to reclaim the memory.
2910  */
can_age_anon_pages(struct pglist_data * pgdat,struct scan_control * sc)2911 static bool can_age_anon_pages(struct pglist_data *pgdat,
2912 			       struct scan_control *sc)
2913 {
2914 	/* Aging the anon LRU is valuable if swap is present: */
2915 	if (total_swap_pages > 0)
2916 		return true;
2917 
2918 	/* Also valuable if anon pages can be demoted: */
2919 	return can_demote(pgdat->node_id, sc);
2920 }
2921 
2922 #ifdef CONFIG_LRU_GEN
2923 
2924 #ifdef CONFIG_LRU_GEN_ENABLED
2925 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2926 #define get_cap(cap)	static_branch_likely(&lru_gen_caps[cap])
2927 #else
2928 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2929 #define get_cap(cap)	static_branch_unlikely(&lru_gen_caps[cap])
2930 #endif
2931 
2932 /******************************************************************************
2933  *                          shorthand helpers
2934  ******************************************************************************/
2935 
2936 #define LRU_REFS_FLAGS	(BIT(PG_referenced) | BIT(PG_workingset))
2937 
2938 #define DEFINE_MAX_SEQ(lruvec)						\
2939 	unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2940 
2941 #define DEFINE_MIN_SEQ(lruvec)						\
2942 	unsigned long min_seq[ANON_AND_FILE] = {			\
2943 		READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]),	\
2944 		READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]),	\
2945 	}
2946 
2947 #define for_each_gen_type_zone(gen, type, zone)				\
2948 	for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++)			\
2949 		for ((type) = 0; (type) < ANON_AND_FILE; (type)++)	\
2950 			for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2951 
2952 #define get_memcg_gen(seq)	((seq) % MEMCG_NR_GENS)
2953 #define get_memcg_bin(bin)	((bin) % MEMCG_NR_BINS)
2954 
get_lruvec(struct mem_cgroup * memcg,int nid)2955 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2956 {
2957 	struct pglist_data *pgdat = NODE_DATA(nid);
2958 
2959 #ifdef CONFIG_MEMCG
2960 	if (memcg) {
2961 		struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2962 
2963 		/* for hotadd_new_pgdat() */
2964 		if (!lruvec->pgdat)
2965 			lruvec->pgdat = pgdat;
2966 
2967 		return lruvec;
2968 	}
2969 #endif
2970 	VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2971 
2972 	return pgdat ? &pgdat->__lruvec : NULL;
2973 }
2974 
get_swappiness(struct lruvec * lruvec,struct scan_control * sc)2975 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2976 {
2977 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2978 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2979 
2980 	if (!sc->may_swap)
2981 		return 0;
2982 
2983 	if (!can_demote(pgdat->node_id, sc) &&
2984 		mem_cgroup_get_nr_swap_pages(memcg) <= 0)
2985 		return 0;
2986 
2987 	return mem_cgroup_swappiness(memcg);
2988 }
2989 
get_nr_gens(struct lruvec * lruvec,int type)2990 static int get_nr_gens(struct lruvec *lruvec, int type)
2991 {
2992 	return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2993 }
2994 
seq_is_valid(struct lruvec * lruvec)2995 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2996 {
2997 	/* see the comment on lru_gen_page */
2998 	return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2999 	       get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3000 	       get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3001 }
3002 
3003 /******************************************************************************
3004  *                          mm_struct list
3005  ******************************************************************************/
3006 
get_mm_list(struct mem_cgroup * memcg)3007 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3008 {
3009 	static struct lru_gen_mm_list mm_list = {
3010 		.fifo = LIST_HEAD_INIT(mm_list.fifo),
3011 		.lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3012 	};
3013 
3014 #ifdef CONFIG_MEMCG
3015 	if (memcg)
3016 		return &memcg->mm_list;
3017 #endif
3018 	VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3019 
3020 	return &mm_list;
3021 }
3022 
lru_gen_add_mm(struct mm_struct * mm)3023 void lru_gen_add_mm(struct mm_struct *mm)
3024 {
3025 	int nid;
3026 	struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3027 	struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3028 
3029 	VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3030 #ifdef CONFIG_MEMCG
3031 	VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3032 	mm->lru_gen.memcg = memcg;
3033 #endif
3034 	spin_lock(&mm_list->lock);
3035 
3036 	for_each_node_state(nid, N_MEMORY) {
3037 		struct lruvec *lruvec = get_lruvec(memcg, nid);
3038 
3039 		if (!lruvec)
3040 			continue;
3041 
3042 		/* the first addition since the last iteration */
3043 		if (lruvec->mm_state.tail == &mm_list->fifo)
3044 			lruvec->mm_state.tail = &mm->lru_gen.list;
3045 	}
3046 
3047 	list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3048 
3049 	spin_unlock(&mm_list->lock);
3050 }
3051 
lru_gen_del_mm(struct mm_struct * mm)3052 void lru_gen_del_mm(struct mm_struct *mm)
3053 {
3054 	int nid;
3055 	struct lru_gen_mm_list *mm_list;
3056 	struct mem_cgroup *memcg = NULL;
3057 
3058 	if (list_empty(&mm->lru_gen.list))
3059 		return;
3060 
3061 #ifdef CONFIG_MEMCG
3062 	memcg = mm->lru_gen.memcg;
3063 #endif
3064 	mm_list = get_mm_list(memcg);
3065 
3066 	spin_lock(&mm_list->lock);
3067 
3068 	for_each_node(nid) {
3069 		struct lruvec *lruvec = get_lruvec(memcg, nid);
3070 
3071 		if (!lruvec)
3072 			continue;
3073 
3074 		/* where the current iteration continues after */
3075 		if (lruvec->mm_state.head == &mm->lru_gen.list)
3076 			lruvec->mm_state.head = lruvec->mm_state.head->prev;
3077 
3078 		/* where the last iteration ended before */
3079 		if (lruvec->mm_state.tail == &mm->lru_gen.list)
3080 			lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3081 	}
3082 
3083 	list_del_init(&mm->lru_gen.list);
3084 
3085 	spin_unlock(&mm_list->lock);
3086 
3087 #ifdef CONFIG_MEMCG
3088 	mem_cgroup_put(mm->lru_gen.memcg);
3089 	mm->lru_gen.memcg = NULL;
3090 #endif
3091 }
3092 
3093 #ifdef CONFIG_MEMCG
lru_gen_migrate_mm(struct mm_struct * mm)3094 void lru_gen_migrate_mm(struct mm_struct *mm)
3095 {
3096 	struct mem_cgroup *memcg;
3097 	struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3098 
3099 	VM_WARN_ON_ONCE(task->mm != mm);
3100 	lockdep_assert_held(&task->alloc_lock);
3101 
3102 	/* for mm_update_next_owner() */
3103 	if (mem_cgroup_disabled())
3104 		return;
3105 
3106 	/* migration can happen before addition */
3107 	if (!mm->lru_gen.memcg)
3108 		return;
3109 
3110 	rcu_read_lock();
3111 	memcg = mem_cgroup_from_task(task);
3112 	rcu_read_unlock();
3113 	if (memcg == mm->lru_gen.memcg)
3114 		return;
3115 
3116 	VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3117 
3118 	lru_gen_del_mm(mm);
3119 	lru_gen_add_mm(mm);
3120 }
3121 #endif
3122 
3123 /*
3124  * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3125  * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3126  * bits in a bitmap, k is the number of hash functions and n is the number of
3127  * inserted items.
3128  *
3129  * Page table walkers use one of the two filters to reduce their search space.
3130  * To get rid of non-leaf entries that no longer have enough leaf entries, the
3131  * aging uses the double-buffering technique to flip to the other filter each
3132  * time it produces a new generation. For non-leaf entries that have enough
3133  * leaf entries, the aging carries them over to the next generation in
3134  * walk_pmd_range(); the eviction also report them when walking the rmap
3135  * in lru_gen_look_around().
3136  *
3137  * For future optimizations:
3138  * 1. It's not necessary to keep both filters all the time. The spare one can be
3139  *    freed after the RCU grace period and reallocated if needed again.
3140  * 2. And when reallocating, it's worth scaling its size according to the number
3141  *    of inserted entries in the other filter, to reduce the memory overhead on
3142  *    small systems and false positives on large systems.
3143  * 3. Jenkins' hash function is an alternative to Knuth's.
3144  */
3145 #define BLOOM_FILTER_SHIFT	15
3146 
filter_gen_from_seq(unsigned long seq)3147 static inline int filter_gen_from_seq(unsigned long seq)
3148 {
3149 	return seq % NR_BLOOM_FILTERS;
3150 }
3151 
get_item_key(void * item,int * key)3152 static void get_item_key(void *item, int *key)
3153 {
3154 	u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3155 
3156 	BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3157 
3158 	key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3159 	key[1] = hash >> BLOOM_FILTER_SHIFT;
3160 }
3161 
reset_bloom_filter(struct lruvec * lruvec,unsigned long seq)3162 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3163 {
3164 	unsigned long *filter;
3165 	int gen = filter_gen_from_seq(seq);
3166 
3167 	filter = lruvec->mm_state.filters[gen];
3168 	if (filter) {
3169 		bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3170 		return;
3171 	}
3172 
3173 	filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3174 			       __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3175 	WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3176 }
3177 
update_bloom_filter(struct lruvec * lruvec,unsigned long seq,void * item)3178 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3179 {
3180 	int key[2];
3181 	unsigned long *filter;
3182 	int gen = filter_gen_from_seq(seq);
3183 
3184 	filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3185 	if (!filter)
3186 		return;
3187 
3188 	get_item_key(item, key);
3189 
3190 	if (!test_bit(key[0], filter))
3191 		set_bit(key[0], filter);
3192 	if (!test_bit(key[1], filter))
3193 		set_bit(key[1], filter);
3194 }
3195 
test_bloom_filter(struct lruvec * lruvec,unsigned long seq,void * item)3196 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3197 {
3198 	int key[2];
3199 	unsigned long *filter;
3200 	int gen = filter_gen_from_seq(seq);
3201 
3202 	filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3203 	if (!filter)
3204 		return true;
3205 
3206 	get_item_key(item, key);
3207 
3208 	return test_bit(key[0], filter) && test_bit(key[1], filter);
3209 }
3210 
reset_mm_stats(struct lruvec * lruvec,struct lru_gen_mm_walk * walk,bool last)3211 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3212 {
3213 	int i;
3214 	int hist;
3215 
3216 	lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3217 
3218 	if (walk) {
3219 		hist = lru_hist_from_seq(walk->max_seq);
3220 
3221 		for (i = 0; i < NR_MM_STATS; i++) {
3222 			WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3223 				   lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3224 			walk->mm_stats[i] = 0;
3225 		}
3226 	}
3227 
3228 	if (NR_HIST_GENS > 1 && last) {
3229 		hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3230 
3231 		for (i = 0; i < NR_MM_STATS; i++)
3232 			WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3233 	}
3234 }
3235 
should_skip_mm(struct mm_struct * mm,struct lru_gen_mm_walk * walk)3236 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3237 {
3238 	int type;
3239 	unsigned long size = 0;
3240 	struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3241 	int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3242 
3243 	if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3244 		return true;
3245 
3246 	clear_bit(key, &mm->lru_gen.bitmap);
3247 
3248 	for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3249 		size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3250 			       get_mm_counter(mm, MM_ANONPAGES) +
3251 			       get_mm_counter(mm, MM_SHMEMPAGES);
3252 	}
3253 
3254 	if (size < MIN_LRU_BATCH)
3255 		return true;
3256 
3257 	return !mmget_not_zero(mm);
3258 }
3259 
iterate_mm_list(struct lruvec * lruvec,struct lru_gen_mm_walk * walk,struct mm_struct ** iter)3260 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3261 			    struct mm_struct **iter)
3262 {
3263 	bool first = false;
3264 	bool last = false;
3265 	struct mm_struct *mm = NULL;
3266 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3267 	struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3268 	struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3269 
3270 	/*
3271 	 * mm_state->seq is incremented after each iteration of mm_list. There
3272 	 * are three interesting cases for this page table walker:
3273 	 * 1. It tries to start a new iteration with a stale max_seq: there is
3274 	 *    nothing left to do.
3275 	 * 2. It started the next iteration: it needs to reset the Bloom filter
3276 	 *    so that a fresh set of PTE tables can be recorded.
3277 	 * 3. It ended the current iteration: it needs to reset the mm stats
3278 	 *    counters and tell its caller to increment max_seq.
3279 	 */
3280 	spin_lock(&mm_list->lock);
3281 
3282 	VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3283 
3284 	if (walk->max_seq <= mm_state->seq)
3285 		goto done;
3286 
3287 	if (!mm_state->head)
3288 		mm_state->head = &mm_list->fifo;
3289 
3290 	if (mm_state->head == &mm_list->fifo)
3291 		first = true;
3292 
3293 	do {
3294 		mm_state->head = mm_state->head->next;
3295 		if (mm_state->head == &mm_list->fifo) {
3296 			WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3297 			last = true;
3298 			break;
3299 		}
3300 
3301 		/* force scan for those added after the last iteration */
3302 		if (!mm_state->tail || mm_state->tail == mm_state->head) {
3303 			mm_state->tail = mm_state->head->next;
3304 			walk->force_scan = true;
3305 		}
3306 
3307 		mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3308 		if (should_skip_mm(mm, walk))
3309 			mm = NULL;
3310 	} while (!mm);
3311 done:
3312 	if (*iter || last)
3313 		reset_mm_stats(lruvec, walk, last);
3314 
3315 	spin_unlock(&mm_list->lock);
3316 
3317 	if (mm && first)
3318 		reset_bloom_filter(lruvec, walk->max_seq + 1);
3319 
3320 	if (*iter)
3321 		mmput_async(*iter);
3322 
3323 	*iter = mm;
3324 
3325 	return last;
3326 }
3327 
iterate_mm_list_nowalk(struct lruvec * lruvec,unsigned long max_seq)3328 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3329 {
3330 	bool success = false;
3331 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3332 	struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3333 	struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3334 
3335 	spin_lock(&mm_list->lock);
3336 
3337 	VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3338 
3339 	if (max_seq > mm_state->seq) {
3340 		mm_state->head = NULL;
3341 		mm_state->tail = NULL;
3342 		WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3343 		reset_mm_stats(lruvec, NULL, true);
3344 		success = true;
3345 	}
3346 
3347 	spin_unlock(&mm_list->lock);
3348 
3349 	return success;
3350 }
3351 
3352 /******************************************************************************
3353  *                          refault feedback loop
3354  ******************************************************************************/
3355 
3356 /*
3357  * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3358  *
3359  * The P term is refaulted/(evicted+protected) from a tier in the generation
3360  * currently being evicted; the I term is the exponential moving average of the
3361  * P term over the generations previously evicted, using the smoothing factor
3362  * 1/2; the D term isn't supported.
3363  *
3364  * The setpoint (SP) is always the first tier of one type; the process variable
3365  * (PV) is either any tier of the other type or any other tier of the same
3366  * type.
3367  *
3368  * The error is the difference between the SP and the PV; the correction is to
3369  * turn off protection when SP>PV or turn on protection when SP<PV.
3370  *
3371  * For future optimizations:
3372  * 1. The D term may discount the other two terms over time so that long-lived
3373  *    generations can resist stale information.
3374  */
3375 struct ctrl_pos {
3376 	unsigned long refaulted;
3377 	unsigned long total;
3378 	int gain;
3379 };
3380 
read_ctrl_pos(struct lruvec * lruvec,int type,int tier,int gain,struct ctrl_pos * pos)3381 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3382 			  struct ctrl_pos *pos)
3383 {
3384 	struct lru_gen_page *lrugen = &lruvec->lrugen;
3385 	int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3386 
3387 	pos->refaulted = lrugen->avg_refaulted[type][tier] +
3388 			 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3389 	pos->total = lrugen->avg_total[type][tier] +
3390 		     atomic_long_read(&lrugen->evicted[hist][type][tier]);
3391 	if (tier)
3392 		pos->total += lrugen->protected[hist][type][tier - 1];
3393 	pos->gain = gain;
3394 }
3395 
reset_ctrl_pos(struct lruvec * lruvec,int type,bool carryover)3396 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3397 {
3398 	int hist, tier;
3399 	struct lru_gen_page *lrugen = &lruvec->lrugen;
3400 	bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3401 	unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3402 
3403 	lockdep_assert_held(&lruvec->lru_lock);
3404 
3405 	if (!carryover && !clear)
3406 		return;
3407 
3408 	hist = lru_hist_from_seq(seq);
3409 
3410 	for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3411 		if (carryover) {
3412 			unsigned long sum;
3413 
3414 			sum = lrugen->avg_refaulted[type][tier] +
3415 			      atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3416 			WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3417 
3418 			sum = lrugen->avg_total[type][tier] +
3419 			      atomic_long_read(&lrugen->evicted[hist][type][tier]);
3420 			if (tier)
3421 				sum += lrugen->protected[hist][type][tier - 1];
3422 			WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3423 		}
3424 
3425 		if (clear) {
3426 			atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3427 			atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3428 			if (tier)
3429 				WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3430 		}
3431 	}
3432 }
3433 
positive_ctrl_err(struct ctrl_pos * sp,struct ctrl_pos * pv)3434 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3435 {
3436 	/*
3437 	 * Return true if the PV has a limited number of refaults or a lower
3438 	 * refaulted/total than the SP.
3439 	 */
3440 	return pv->refaulted < MIN_LRU_BATCH ||
3441 	       pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3442 	       (sp->refaulted + 1) * pv->total * pv->gain;
3443 }
3444 
3445 /******************************************************************************
3446  *                          the aging
3447  ******************************************************************************/
3448 
3449 /* promote pages accessed through page tables */
page_update_gen(struct page * page,int gen)3450 static int page_update_gen(struct page *page, int gen)
3451 {
3452 	unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3453 
3454 	VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3455 	VM_WARN_ON_ONCE(!rcu_read_lock_held());
3456 
3457 	do {
3458 		/* lru_gen_del_page() has isolated this page? */
3459 		if (!(old_flags & LRU_GEN_MASK)) {
3460 			/* for shrink_page_list() */
3461 			new_flags = old_flags | BIT(PG_referenced);
3462 			continue;
3463 		}
3464 
3465 		new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3466 		new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3467 	} while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3468 
3469 	return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3470 }
3471 
3472 /* protect pages accessed multiple times through file descriptors */
page_inc_gen(struct lruvec * lruvec,struct page * page,bool reclaiming)3473 static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3474 {
3475 	int type = page_is_file_lru(page);
3476 	struct lru_gen_page *lrugen = &lruvec->lrugen;
3477 	int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3478 	unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3479 
3480 	VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3481 
3482 	do {
3483 		new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3484 		/* page_update_gen() has promoted this page? */
3485 		if (new_gen >= 0 && new_gen != old_gen)
3486 			return new_gen;
3487 
3488 		new_gen = (old_gen + 1) % MAX_NR_GENS;
3489 
3490 		new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3491 		new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3492 		/* for end_page_writeback() */
3493 		if (reclaiming)
3494 			new_flags |= BIT(PG_reclaim);
3495 	} while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3496 
3497 	lru_gen_update_size(lruvec, page, old_gen, new_gen);
3498 
3499 	return new_gen;
3500 }
3501 
update_batch_size(struct lru_gen_mm_walk * walk,struct page * page,int old_gen,int new_gen)3502 static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3503 			      int old_gen, int new_gen)
3504 {
3505 	int type = page_is_file_lru(page);
3506 	int zone = page_zonenum(page);
3507 	int delta = thp_nr_pages(page);
3508 
3509 	VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3510 	VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3511 
3512 	walk->batched++;
3513 
3514 	walk->nr_pages[old_gen][type][zone] -= delta;
3515 	walk->nr_pages[new_gen][type][zone] += delta;
3516 }
3517 
reset_batch_size(struct lruvec * lruvec,struct lru_gen_mm_walk * walk)3518 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3519 {
3520 	int gen, type, zone;
3521 	struct lru_gen_page *lrugen = &lruvec->lrugen;
3522 
3523 	walk->batched = 0;
3524 
3525 	for_each_gen_type_zone(gen, type, zone) {
3526 		enum lru_list lru = type * LRU_INACTIVE_FILE;
3527 		int delta = walk->nr_pages[gen][type][zone];
3528 
3529 		if (!delta)
3530 			continue;
3531 
3532 		walk->nr_pages[gen][type][zone] = 0;
3533 		WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3534 			   lrugen->nr_pages[gen][type][zone] + delta);
3535 
3536 		if (lru_gen_is_active(lruvec, gen))
3537 			lru += LRU_ACTIVE;
3538 		__update_lru_size(lruvec, lru, zone, delta);
3539 	}
3540 }
3541 
should_skip_vma(unsigned long start,unsigned long end,struct mm_walk * args)3542 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3543 {
3544 	struct address_space *mapping;
3545 	struct vm_area_struct *vma = args->vma;
3546 	struct lru_gen_mm_walk *walk = args->private;
3547 
3548 	if (!vma_is_accessible(vma))
3549 		return true;
3550 
3551 	if (is_vm_hugetlb_page(vma))
3552 		return true;
3553 
3554 	if (!vma_has_recency(vma))
3555 		return true;
3556 
3557 	if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
3558 		return true;
3559 
3560 	if (vma == get_gate_vma(vma->vm_mm))
3561 		return true;
3562 
3563 	if (vma_is_anonymous(vma))
3564 		return !walk->can_swap;
3565 
3566 	if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3567 		return true;
3568 
3569 	mapping = vma->vm_file->f_mapping;
3570 	if (mapping_unevictable(mapping))
3571 		return true;
3572 
3573 	if (shmem_mapping(mapping))
3574 		return !walk->can_swap;
3575 
3576 	/* to exclude special mappings like dax, etc. */
3577 	return !mapping->a_ops->readpage;
3578 }
3579 
3580 /*
3581  * Some userspace memory allocators map many single-page VMAs. Instead of
3582  * returning back to the PGD table for each of such VMAs, finish an entire PMD
3583  * table to reduce zigzags and improve cache performance.
3584  */
get_next_vma(unsigned long mask,unsigned long size,struct mm_walk * args,unsigned long * vm_start,unsigned long * vm_end)3585 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3586 			 unsigned long *vm_start, unsigned long *vm_end)
3587 {
3588 	unsigned long start = round_up(*vm_end, size);
3589 	unsigned long end = (start | ~mask) + 1;
3590 
3591 	VM_WARN_ON_ONCE(mask & size);
3592 	VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3593 
3594 	while (args->vma) {
3595 		if (start >= args->vma->vm_end) {
3596 			args->vma = args->vma->vm_next;
3597 			continue;
3598 		}
3599 
3600 		if (end && end <= args->vma->vm_start)
3601 			return false;
3602 
3603 		if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3604 			args->vma = args->vma->vm_next;
3605 			continue;
3606 		}
3607 
3608 		*vm_start = max(start, args->vma->vm_start);
3609 		*vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3610 
3611 		return true;
3612 	}
3613 
3614 	return false;
3615 }
3616 
get_pte_pfn(pte_t pte,struct vm_area_struct * vma,unsigned long addr)3617 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3618 {
3619 	unsigned long pfn = pte_pfn(pte);
3620 
3621 	VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3622 
3623 	if (!pte_present(pte) || is_zero_pfn(pfn))
3624 		return -1;
3625 
3626 	if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3627 		return -1;
3628 
3629 	if (WARN_ON_ONCE(!pfn_valid(pfn)))
3630 		return -1;
3631 
3632 	return pfn;
3633 }
3634 
3635 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
get_pmd_pfn(pmd_t pmd,struct vm_area_struct * vma,unsigned long addr)3636 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3637 {
3638 	unsigned long pfn = pmd_pfn(pmd);
3639 
3640 	VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3641 
3642 	if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3643 		return -1;
3644 
3645 	if (WARN_ON_ONCE(pmd_devmap(pmd)))
3646 		return -1;
3647 
3648 	if (WARN_ON_ONCE(!pfn_valid(pfn)))
3649 		return -1;
3650 
3651 	return pfn;
3652 }
3653 #endif
3654 
get_pfn_page(unsigned long pfn,struct mem_cgroup * memcg,struct pglist_data * pgdat,bool can_swap)3655 static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
3656 				 struct pglist_data *pgdat, bool can_swap)
3657 {
3658 	struct page *page;
3659 
3660 	/* try to avoid unnecessary memory loads */
3661 	if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3662 		return NULL;
3663 
3664 	page = compound_head(pfn_to_page(pfn));
3665 	if (page_to_nid(page) != pgdat->node_id)
3666 		return NULL;
3667 
3668 	if (page_memcg_rcu(page) != memcg)
3669 		return NULL;
3670 
3671 	/* file VMAs can contain anon pages from COW */
3672 	if (!page_is_file_lru(page) && !can_swap)
3673 		return NULL;
3674 
3675 	return page;
3676 }
3677 
suitable_to_scan(int total,int young)3678 static bool suitable_to_scan(int total, int young)
3679 {
3680 	int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3681 
3682 	/* suitable if the average number of young PTEs per cacheline is >=1 */
3683 	return young * n >= total;
3684 }
3685 
walk_pte_range(pmd_t * pmd,unsigned long start,unsigned long end,struct mm_walk * args)3686 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3687 			   struct mm_walk *args)
3688 {
3689 	int i;
3690 	pte_t *pte;
3691 	spinlock_t *ptl;
3692 	unsigned long addr;
3693 	int total = 0;
3694 	int young = 0;
3695 	struct lru_gen_mm_walk *walk = args->private;
3696 	struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3697 	struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3698 	int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3699 
3700 	VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3701 
3702 	ptl = pte_lockptr(args->mm, pmd);
3703 	if (!spin_trylock(ptl))
3704 		return false;
3705 
3706 	arch_enter_lazy_mmu_mode();
3707 
3708 	pte = pte_offset_map(pmd, start & PMD_MASK);
3709 restart:
3710 	for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3711 		unsigned long pfn;
3712 		struct page *page;
3713 
3714 		total++;
3715 		walk->mm_stats[MM_LEAF_TOTAL]++;
3716 
3717 		pfn = get_pte_pfn(pte[i], args->vma, addr);
3718 		if (pfn == -1)
3719 			continue;
3720 
3721 		if (!pte_young(pte[i])) {
3722 			walk->mm_stats[MM_LEAF_OLD]++;
3723 			continue;
3724 		}
3725 
3726 		page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3727 		if (!page)
3728 			continue;
3729 
3730 		if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3731 			VM_WARN_ON_ONCE(true);
3732 
3733 		young++;
3734 		walk->mm_stats[MM_LEAF_YOUNG]++;
3735 
3736 		if (pte_dirty(pte[i]) && !PageDirty(page) &&
3737 		    !(PageAnon(page) && PageSwapBacked(page) &&
3738 		      !PageSwapCache(page)))
3739 			set_page_dirty(page);
3740 
3741 		old_gen = page_update_gen(page, new_gen);
3742 		if (old_gen >= 0 && old_gen != new_gen)
3743 			update_batch_size(walk, page, old_gen, new_gen);
3744 	}
3745 
3746 	if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3747 		goto restart;
3748 
3749 	pte_unmap(pte);
3750 
3751 	arch_leave_lazy_mmu_mode();
3752 	spin_unlock(ptl);
3753 
3754 	return suitable_to_scan(total, young);
3755 }
3756 
3757 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
walk_pmd_range_locked(pud_t * pud,unsigned long next,struct vm_area_struct * vma,struct mm_walk * args,unsigned long * bitmap,unsigned long * start)3758 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3759 				  struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3760 {
3761 	int i;
3762 	pmd_t *pmd;
3763 	spinlock_t *ptl;
3764 	struct lru_gen_mm_walk *walk = args->private;
3765 	struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3766 	struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3767 	int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3768 
3769 	VM_WARN_ON_ONCE(pud_leaf(*pud));
3770 
3771 	/* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3772 	if (*start == -1) {
3773 		*start = next;
3774 		return;
3775 	}
3776 
3777 	i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3778 	if (i && i <= MIN_LRU_BATCH) {
3779 		__set_bit(i - 1, bitmap);
3780 		return;
3781 	}
3782 
3783 	pmd = pmd_offset(pud, *start);
3784 
3785 	ptl = pmd_lockptr(args->mm, pmd);
3786 	if (!spin_trylock(ptl))
3787 		goto done;
3788 
3789 	arch_enter_lazy_mmu_mode();
3790 
3791 	do {
3792 		unsigned long pfn;
3793 		struct page *page;
3794 		unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3795 
3796 		pfn = get_pmd_pfn(pmd[i], vma, addr);
3797 		if (pfn == -1)
3798 			goto next;
3799 
3800 		if (!pmd_trans_huge(pmd[i])) {
3801 			if (arch_has_hw_nonleaf_pmd_young() &&
3802 			    get_cap(LRU_GEN_NONLEAF_YOUNG))
3803 				pmdp_test_and_clear_young(vma, addr, pmd + i);
3804 			goto next;
3805 		}
3806 
3807 		page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3808 		if (!page)
3809 			goto next;
3810 
3811 		if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3812 			goto next;
3813 
3814 		walk->mm_stats[MM_LEAF_YOUNG]++;
3815 
3816 		if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3817 		    !(PageAnon(page) && PageSwapBacked(page) &&
3818 		      !PageSwapCache(page)))
3819 			set_page_dirty(page);
3820 
3821 		old_gen = page_update_gen(page, new_gen);
3822 		if (old_gen >= 0 && old_gen != new_gen)
3823 			update_batch_size(walk, page, old_gen, new_gen);
3824 next:
3825 		i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3826 	} while (i <= MIN_LRU_BATCH);
3827 
3828 	arch_leave_lazy_mmu_mode();
3829 	spin_unlock(ptl);
3830 done:
3831 	*start = -1;
3832 	bitmap_zero(bitmap, MIN_LRU_BATCH);
3833 }
3834 #else
walk_pmd_range_locked(pud_t * pud,unsigned long next,struct vm_area_struct * vma,struct mm_walk * args,unsigned long * bitmap,unsigned long * start)3835 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3836 				  struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3837 {
3838 }
3839 #endif
3840 
walk_pmd_range(pud_t * pud,unsigned long start,unsigned long end,struct mm_walk * args)3841 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3842 			   struct mm_walk *args)
3843 {
3844 	int i;
3845 	pmd_t *pmd;
3846 	unsigned long next;
3847 	unsigned long addr;
3848 	struct vm_area_struct *vma;
3849 	unsigned long pos = -1;
3850 	struct lru_gen_mm_walk *walk = args->private;
3851 	unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3852 
3853 	VM_WARN_ON_ONCE(pud_leaf(*pud));
3854 
3855 	/*
3856 	 * Finish an entire PMD in two passes: the first only reaches to PTE
3857 	 * tables to avoid taking the PMD lock; the second, if necessary, takes
3858 	 * the PMD lock to clear the accessed bit in PMD entries.
3859 	 */
3860 	pmd = pmd_offset(pud, start & PUD_MASK);
3861 restart:
3862 	/* walk_pte_range() may call get_next_vma() */
3863 	vma = args->vma;
3864 	for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3865 		pmd_t val = pmd_read_atomic(pmd + i);
3866 
3867 		/* for pmd_read_atomic() */
3868 		barrier();
3869 
3870 		next = pmd_addr_end(addr, end);
3871 
3872 		if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3873 			walk->mm_stats[MM_LEAF_TOTAL]++;
3874 			continue;
3875 		}
3876 
3877 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3878 		if (pmd_trans_huge(val)) {
3879 			unsigned long pfn = pmd_pfn(val);
3880 			struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3881 
3882 			walk->mm_stats[MM_LEAF_TOTAL]++;
3883 
3884 			if (!pmd_young(val)) {
3885 				walk->mm_stats[MM_LEAF_OLD]++;
3886 				continue;
3887 			}
3888 
3889 			/* try to avoid unnecessary memory loads */
3890 			if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3891 				continue;
3892 
3893 			walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3894 			continue;
3895 		}
3896 #endif
3897 		walk->mm_stats[MM_NONLEAF_TOTAL]++;
3898 
3899 		if (arch_has_hw_nonleaf_pmd_young() &&
3900 		    get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3901 			if (!pmd_young(val))
3902 				continue;
3903 
3904 			walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3905 		}
3906 
3907 		if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3908 			continue;
3909 
3910 		walk->mm_stats[MM_NONLEAF_FOUND]++;
3911 
3912 		if (!walk_pte_range(&val, addr, next, args))
3913 			continue;
3914 
3915 		walk->mm_stats[MM_NONLEAF_ADDED]++;
3916 
3917 		/* carry over to the next generation */
3918 		update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3919 	}
3920 
3921 	walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3922 
3923 	if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3924 		goto restart;
3925 }
3926 
walk_pud_range(p4d_t * p4d,unsigned long start,unsigned long end,struct mm_walk * args)3927 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3928 			  struct mm_walk *args)
3929 {
3930 	int i;
3931 	pud_t *pud;
3932 	unsigned long addr;
3933 	unsigned long next;
3934 	struct lru_gen_mm_walk *walk = args->private;
3935 
3936 	VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3937 
3938 	pud = pud_offset(p4d, start & P4D_MASK);
3939 restart:
3940 	for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3941 		pud_t val = READ_ONCE(pud[i]);
3942 
3943 		next = pud_addr_end(addr, end);
3944 
3945 		if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3946 			continue;
3947 
3948 		walk_pmd_range(&val, addr, next, args);
3949 
3950 		if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3951 			end = (addr | ~PUD_MASK) + 1;
3952 			goto done;
3953 		}
3954 	}
3955 
3956 	if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3957 		goto restart;
3958 
3959 	end = round_up(end, P4D_SIZE);
3960 done:
3961 	if (!end || !args->vma)
3962 		return 1;
3963 
3964 	walk->next_addr = max(end, args->vma->vm_start);
3965 
3966 	return -EAGAIN;
3967 }
3968 
walk_mm(struct lruvec * lruvec,struct mm_struct * mm,struct lru_gen_mm_walk * walk)3969 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3970 {
3971 	static const struct mm_walk_ops mm_walk_ops = {
3972 		.test_walk = should_skip_vma,
3973 		.p4d_entry = walk_pud_range,
3974 	};
3975 
3976 	int err;
3977 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3978 
3979 	walk->next_addr = FIRST_USER_ADDRESS;
3980 
3981 	do {
3982 		DEFINE_MAX_SEQ(lruvec);
3983 
3984 		err = -EBUSY;
3985 
3986 		/* another thread might have called inc_max_seq() */
3987 		if (walk->max_seq != max_seq)
3988 			break;
3989 
3990 		/* page_update_gen() requires stable page_memcg() */
3991 		if (!mem_cgroup_trylock_pages(memcg))
3992 			break;
3993 
3994 		/* the caller might be holding the lock for write */
3995 		if (mmap_read_trylock(mm)) {
3996 			err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3997 
3998 			mmap_read_unlock(mm);
3999 		}
4000 
4001 		mem_cgroup_unlock_pages();
4002 
4003 		if (walk->batched) {
4004 			spin_lock_irq(&lruvec->lru_lock);
4005 			reset_batch_size(lruvec, walk);
4006 			spin_unlock_irq(&lruvec->lru_lock);
4007 		}
4008 
4009 		cond_resched();
4010 	} while (err == -EAGAIN);
4011 }
4012 
set_mm_walk(struct pglist_data * pgdat,bool force_alloc)4013 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
4014 {
4015 	struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4016 
4017 	if (pgdat && current_is_kswapd()) {
4018 		VM_WARN_ON_ONCE(walk);
4019 
4020 		walk = &pgdat->mm_walk;
4021 	} else if (!walk && force_alloc) {
4022 		VM_WARN_ON_ONCE(current_is_kswapd());
4023 
4024 		walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4025 	}
4026 
4027 	current->reclaim_state->mm_walk = walk;
4028 
4029 	return walk;
4030 }
4031 
clear_mm_walk(void)4032 static void clear_mm_walk(void)
4033 {
4034 	struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4035 
4036 	VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4037 	VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4038 
4039 	current->reclaim_state->mm_walk = NULL;
4040 
4041 	if (!current_is_kswapd())
4042 		kfree(walk);
4043 }
4044 
inc_min_seq(struct lruvec * lruvec,int type,bool can_swap)4045 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
4046 {
4047 	int zone;
4048 	int remaining = MAX_LRU_BATCH;
4049 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4050 	int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4051 
4052 	if (type == LRU_GEN_ANON && !can_swap)
4053 		goto done;
4054 
4055 	/* prevent cold/hot inversion if force_scan is true */
4056 	for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4057 		struct list_head *head = &lrugen->pages[old_gen][type][zone];
4058 
4059 		while (!list_empty(head)) {
4060 			struct page *page = lru_to_page(head);
4061 
4062 			VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4063 			VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4064 			VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4065 			VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4066 
4067 			new_gen = page_inc_gen(lruvec, page, false);
4068 			list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
4069 
4070 			if (!--remaining)
4071 				return false;
4072 		}
4073 	}
4074 done:
4075 	reset_ctrl_pos(lruvec, type, true);
4076 	WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4077 
4078 	return true;
4079 }
4080 
try_to_inc_min_seq(struct lruvec * lruvec,bool can_swap)4081 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4082 {
4083 	int gen, type, zone;
4084 	bool success = false;
4085 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4086 	DEFINE_MIN_SEQ(lruvec);
4087 
4088 	VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4089 
4090 	/* find the oldest populated generation */
4091 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4092 		while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4093 			gen = lru_gen_from_seq(min_seq[type]);
4094 
4095 			for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4096 				if (!list_empty(&lrugen->pages[gen][type][zone]))
4097 					goto next;
4098 			}
4099 
4100 			min_seq[type]++;
4101 		}
4102 next:
4103 		;
4104 	}
4105 
4106 	/* see the comment on lru_gen_page */
4107 	if (can_swap) {
4108 		min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4109 		min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4110 	}
4111 
4112 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4113 		if (min_seq[type] == lrugen->min_seq[type])
4114 			continue;
4115 
4116 		reset_ctrl_pos(lruvec, type, true);
4117 		WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4118 		success = true;
4119 	}
4120 
4121 	return success;
4122 }
4123 
inc_max_seq(struct lruvec * lruvec,bool can_swap,bool force_scan)4124 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
4125 {
4126 	int prev, next;
4127 	int type, zone;
4128 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4129 restart:
4130 	spin_lock_irq(&lruvec->lru_lock);
4131 
4132 	VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4133 
4134 	for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4135 		if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4136 			continue;
4137 
4138 		VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
4139 
4140 		if (inc_min_seq(lruvec, type, can_swap))
4141 			continue;
4142 
4143 		spin_unlock_irq(&lruvec->lru_lock);
4144 		cond_resched();
4145 		goto restart;
4146 	}
4147 
4148 	/*
4149 	 * Update the active/inactive LRU sizes for compatibility. Both sides of
4150 	 * the current max_seq need to be covered, since max_seq+1 can overlap
4151 	 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4152 	 * overlap, cold/hot inversion happens.
4153 	 */
4154 	prev = lru_gen_from_seq(lrugen->max_seq - 1);
4155 	next = lru_gen_from_seq(lrugen->max_seq + 1);
4156 
4157 	for (type = 0; type < ANON_AND_FILE; type++) {
4158 		for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4159 			enum lru_list lru = type * LRU_INACTIVE_FILE;
4160 			long delta = lrugen->nr_pages[prev][type][zone] -
4161 				     lrugen->nr_pages[next][type][zone];
4162 
4163 			if (!delta)
4164 				continue;
4165 
4166 			__update_lru_size(lruvec, lru, zone, delta);
4167 			__update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4168 		}
4169 	}
4170 
4171 	for (type = 0; type < ANON_AND_FILE; type++)
4172 		reset_ctrl_pos(lruvec, type, false);
4173 
4174 	WRITE_ONCE(lrugen->timestamps[next], jiffies);
4175 	/* make sure preceding modifications appear */
4176 	smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4177 
4178 	spin_unlock_irq(&lruvec->lru_lock);
4179 }
4180 
try_to_inc_max_seq(struct lruvec * lruvec,unsigned long max_seq,struct scan_control * sc,bool can_swap,bool force_scan)4181 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4182 			       struct scan_control *sc, bool can_swap, bool force_scan)
4183 {
4184 	bool success;
4185 	struct lru_gen_mm_walk *walk;
4186 	struct mm_struct *mm = NULL;
4187 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4188 
4189 	VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4190 
4191 	/* see the comment in iterate_mm_list() */
4192 	if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4193 		success = false;
4194 		goto done;
4195 	}
4196 
4197 	/*
4198 	 * If the hardware doesn't automatically set the accessed bit, fallback
4199 	 * to lru_gen_look_around(), which only clears the accessed bit in a
4200 	 * handful of PTEs. Spreading the work out over a period of time usually
4201 	 * is less efficient, but it avoids bursty page faults.
4202 	 */
4203 	if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
4204 		success = iterate_mm_list_nowalk(lruvec, max_seq);
4205 		goto done;
4206 	}
4207 
4208 	walk = set_mm_walk(NULL, true);
4209 	if (!walk) {
4210 		success = iterate_mm_list_nowalk(lruvec, max_seq);
4211 		goto done;
4212 	}
4213 
4214 	walk->lruvec = lruvec;
4215 	walk->max_seq = max_seq;
4216 	walk->can_swap = can_swap;
4217 	walk->force_scan = force_scan;
4218 
4219 	do {
4220 		success = iterate_mm_list(lruvec, walk, &mm);
4221 		if (mm)
4222 			walk_mm(lruvec, mm, walk);
4223 	} while (mm);
4224 done:
4225 	if (success)
4226 		inc_max_seq(lruvec, can_swap, force_scan);
4227 
4228 	return success;
4229 }
4230 
lruvec_is_sizable(struct lruvec * lruvec,struct scan_control * sc)4231 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
4232 {
4233 	int gen, type, zone;
4234 	unsigned long total = 0;
4235 	bool can_swap = get_swappiness(lruvec, sc);
4236 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4237 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4238 	DEFINE_MAX_SEQ(lruvec);
4239 	DEFINE_MIN_SEQ(lruvec);
4240 
4241 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4242 		unsigned long seq;
4243 
4244 		for (seq = min_seq[type]; seq <= max_seq; seq++) {
4245 			gen = lru_gen_from_seq(seq);
4246 
4247 			for (zone = 0; zone < MAX_NR_ZONES; zone++)
4248 				total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4249 		}
4250 	}
4251 
4252 	/* whether the size is big enough to be helpful */
4253 	return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4254 }
4255 
lruvec_is_reclaimable(struct lruvec * lruvec,struct scan_control * sc,unsigned long min_ttl)4256 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4257 				  unsigned long min_ttl)
4258 {
4259 	int gen;
4260 	unsigned long birth;
4261 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4262 	DEFINE_MIN_SEQ(lruvec);
4263 
4264 	/* see the comment on lru_gen_page */
4265 	gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4266 	birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4267 
4268 	if (time_is_after_jiffies(birth + min_ttl))
4269 		return false;
4270 
4271 	if (!lruvec_is_sizable(lruvec, sc))
4272 		return false;
4273 
4274 	mem_cgroup_calculate_protection(NULL, memcg);
4275 
4276 	return !mem_cgroup_below_min(memcg);
4277 }
4278 
4279 /* to protect the working set of the last N jiffies */
4280 static unsigned long lru_gen_min_ttl __read_mostly;
4281 
lru_gen_age_node(struct pglist_data * pgdat,struct scan_control * sc)4282 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4283 {
4284 	struct mem_cgroup *memcg;
4285 	unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4286 
4287 	VM_WARN_ON_ONCE(!current_is_kswapd());
4288 
4289 	/* check the order to exclude compaction-induced reclaim */
4290 	if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
4291 		return;
4292 
4293 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
4294 	do {
4295 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4296 
4297 		if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4298 			mem_cgroup_iter_break(NULL, memcg);
4299 			return;
4300 		}
4301 
4302 		cond_resched();
4303 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4304 
4305 	/*
4306 	 * The main goal is to OOM kill if every generation from all memcgs is
4307 	 * younger than min_ttl. However, another possibility is all memcgs are
4308 	 * either too small or below min.
4309 	 */
4310 	if (mutex_trylock(&oom_lock)) {
4311 		struct oom_control oc = {
4312 			.gfp_mask = sc->gfp_mask,
4313 		};
4314 
4315 		out_of_memory(&oc);
4316 
4317 		mutex_unlock(&oom_lock);
4318 	}
4319 }
4320 
4321 /*
4322  * This function exploits spatial locality when shrink_page_list() walks the
4323  * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4324  * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4325  * the PTE table to the Bloom filter. This forms a feedback loop between the
4326  * eviction and the aging.
4327  */
lru_gen_look_around(struct page_vma_mapped_walk * pvmw)4328 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4329 {
4330 	int i;
4331 	pte_t *pte;
4332 	unsigned long start;
4333 	unsigned long end;
4334 	unsigned long addr;
4335 	struct lru_gen_mm_walk *walk;
4336 	int young = 0;
4337 	unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4338 	struct page *page = pvmw->page;
4339 	bool can_swap = !page_is_file_lru(page);
4340 	struct mem_cgroup *memcg = page_memcg(page);
4341 	struct pglist_data *pgdat = page_pgdat(page);
4342 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4343 	DEFINE_MAX_SEQ(lruvec);
4344 	int old_gen, new_gen = lru_gen_from_seq(max_seq);
4345 
4346 	lockdep_assert_held(pvmw->ptl);
4347 	VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4348 
4349 	if (spin_is_contended(pvmw->ptl))
4350 		return;
4351 
4352 	/* avoid taking the LRU lock under the PTL when possible */
4353 	walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4354 
4355 	start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4356 	end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4357 
4358 	if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4359 		if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4360 			end = start + MIN_LRU_BATCH * PAGE_SIZE;
4361 		else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4362 			start = end - MIN_LRU_BATCH * PAGE_SIZE;
4363 		else {
4364 			start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4365 			end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4366 		}
4367 	}
4368 
4369 	pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4370 
4371 	rcu_read_lock();
4372 	arch_enter_lazy_mmu_mode();
4373 
4374 	for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4375 		unsigned long pfn;
4376 
4377 		pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4378 		if (pfn == -1)
4379 			continue;
4380 
4381 		if (!pte_young(pte[i]))
4382 			continue;
4383 
4384 		page = get_pfn_page(pfn, memcg, pgdat, can_swap);
4385 		if (!page)
4386 			continue;
4387 
4388 		if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4389 			VM_WARN_ON_ONCE(true);
4390 
4391 		young++;
4392 
4393 		if (pte_dirty(pte[i]) && !PageDirty(page) &&
4394 		    !(PageAnon(page) && PageSwapBacked(page) &&
4395 		      !PageSwapCache(page)))
4396 			set_page_dirty(page);
4397 
4398 		old_gen = page_lru_gen(page);
4399 		if (old_gen < 0)
4400 			SetPageReferenced(page);
4401 		else if (old_gen != new_gen)
4402 			__set_bit(i, bitmap);
4403 	}
4404 
4405 	arch_leave_lazy_mmu_mode();
4406 	rcu_read_unlock();
4407 
4408 	/* feedback from rmap walkers to page table walkers */
4409 	if (suitable_to_scan(i, young))
4410 		update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4411 
4412 	if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
4413 		for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4414 			page = pte_page(pte[i]);
4415 			activate_page(page);
4416 		}
4417 		return;
4418 	}
4419 
4420 	/* page_update_gen() requires stable page_memcg() */
4421 	if (!mem_cgroup_trylock_pages(memcg))
4422 		return;
4423 
4424 	if (!walk) {
4425 		spin_lock_irq(&lruvec->lru_lock);
4426 		new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4427 	}
4428 
4429 	for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4430 		page = compound_head(pte_page(pte[i]));
4431 		if (page_memcg_rcu(page) != memcg)
4432 			continue;
4433 
4434 		old_gen = page_update_gen(page, new_gen);
4435 		if (old_gen < 0 || old_gen == new_gen)
4436 			continue;
4437 
4438 		if (walk)
4439 			update_batch_size(walk, page, old_gen, new_gen);
4440 		else
4441 			lru_gen_update_size(lruvec, page, old_gen, new_gen);
4442 	}
4443 
4444 	if (!walk)
4445 		spin_unlock_irq(&lruvec->lru_lock);
4446 
4447 	mem_cgroup_unlock_pages();
4448 }
4449 
4450 /******************************************************************************
4451  *                          the eviction
4452  ******************************************************************************/
4453 
sort_page(struct lruvec * lruvec,struct page * page,struct scan_control * sc,int tier_idx)4454 static bool sort_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc,
4455 		       int tier_idx)
4456 {
4457 	bool success;
4458 	int gen = page_lru_gen(page);
4459 	int type = page_is_file_lru(page);
4460 	int zone = page_zonenum(page);
4461 	int delta = thp_nr_pages(page);
4462 	int refs = page_lru_refs(page);
4463 	int tier = lru_tier_from_refs(refs);
4464 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4465 
4466 	VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4467 
4468 	/* unevictable */
4469 	if (!page_evictable(page)) {
4470 		success = lru_gen_del_page(lruvec, page, true);
4471 		VM_WARN_ON_ONCE_PAGE(!success, page);
4472 		SetPageUnevictable(page);
4473 		add_page_to_lru_list(page, lruvec);
4474 		__count_vm_events(UNEVICTABLE_PGCULLED, delta);
4475 		return true;
4476 	}
4477 
4478 	/* dirty lazyfree */
4479 	if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4480 		success = lru_gen_del_page(lruvec, page, true);
4481 		VM_WARN_ON_ONCE_PAGE(!success, page);
4482 		SetPageSwapBacked(page);
4483 		add_page_to_lru_list_tail(page, lruvec);
4484 		return true;
4485 	}
4486 
4487 	/* promoted */
4488 	if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4489 		list_move(&page->lru, &lrugen->pages[gen][type][zone]);
4490 		return true;
4491 	}
4492 
4493 	/* protected */
4494 	if (tier > tier_idx) {
4495 		int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4496 
4497 		gen = page_inc_gen(lruvec, page, false);
4498 		list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
4499 
4500 		WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4501 			   lrugen->protected[hist][type][tier - 1] + delta);
4502 		return true;
4503 	}
4504 
4505 	/* ineligible */
4506 	if (zone > sc->reclaim_idx || skip_cma(page, sc)) {
4507 		gen = page_inc_gen(lruvec, page, false);
4508 		list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
4509 		return true;
4510 	}
4511 
4512 	/* waiting for writeback */
4513 	if (PageLocked(page) || PageWriteback(page) ||
4514 	    (type == LRU_GEN_FILE && PageDirty(page))) {
4515 		gen = page_inc_gen(lruvec, page, true);
4516 		list_move(&page->lru, &lrugen->pages[gen][type][zone]);
4517 		return true;
4518 	}
4519 
4520 	return false;
4521 }
4522 
isolate_page(struct lruvec * lruvec,struct page * page,struct scan_control * sc)4523 static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4524 {
4525 	bool success;
4526 
4527 	/* swapping inhibited */
4528 	if (!(sc->gfp_mask & __GFP_IO) &&
4529 	    (PageDirty(page) ||
4530 	     (PageAnon(page) && !PageSwapCache(page))))
4531 		return false;
4532 
4533 	/* raced with release_pages() */
4534 	if (!get_page_unless_zero(page))
4535 		return false;
4536 
4537 	/* raced with another isolation */
4538 	if (!TestClearPageLRU(page)) {
4539 		put_page(page);
4540 		return false;
4541 	}
4542 
4543 	/* see the comment on MAX_NR_TIERS */
4544 	if (!PageReferenced(page))
4545 		set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4546 
4547 	/* for shrink_page_list() */
4548 	ClearPageReclaim(page);
4549 	ClearPageReferenced(page);
4550 
4551 	success = lru_gen_del_page(lruvec, page, true);
4552 	VM_WARN_ON_ONCE_PAGE(!success, page);
4553 
4554 	return true;
4555 }
4556 
scan_pages(struct lruvec * lruvec,struct scan_control * sc,int type,int tier,struct list_head * list)4557 static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4558 		      int type, int tier, struct list_head *list)
4559 {
4560 	int i;
4561 	int gen;
4562 	enum vm_event_item item;
4563 	int sorted = 0;
4564 	int scanned = 0;
4565 	int isolated = 0;
4566 	int remaining = MAX_LRU_BATCH;
4567 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4568 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4569 
4570 	VM_WARN_ON_ONCE(!list_empty(list));
4571 
4572 	if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4573 		return 0;
4574 
4575 	gen = lru_gen_from_seq(lrugen->min_seq[type]);
4576 
4577 	for (i = MAX_NR_ZONES; i > 0; i--) {
4578 		LIST_HEAD(moved);
4579 		int skipped = 0;
4580 		int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
4581 		struct list_head *head = &lrugen->pages[gen][type][zone];
4582 
4583 		while (!list_empty(head)) {
4584 			struct page *page = lru_to_page(head);
4585 			int delta = thp_nr_pages(page);
4586 
4587 			VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4588 			VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4589 			VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4590 			VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4591 
4592 			scanned += delta;
4593 
4594 			if (sort_page(lruvec, page, sc, tier))
4595 				sorted += delta;
4596 			else if (isolate_page(lruvec, page, sc)) {
4597 				list_add(&page->lru, list);
4598 				isolated += delta;
4599 			} else {
4600 				list_move(&page->lru, &moved);
4601 				skipped += delta;
4602 			}
4603 
4604 			if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4605 				break;
4606 		}
4607 
4608 		if (skipped) {
4609 			list_splice(&moved, head);
4610 			__count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4611 		}
4612 
4613 		if (!remaining || isolated >= MIN_LRU_BATCH)
4614 			break;
4615 	}
4616 
4617 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4618 	if (!cgroup_reclaim(sc)) {
4619 		__count_vm_events(item, isolated);
4620 		__count_vm_events(PGREFILL, sorted);
4621 	}
4622 	__count_memcg_events(memcg, item, isolated);
4623 	__count_memcg_events(memcg, PGREFILL, sorted);
4624 	__count_vm_events(PGSCAN_ANON + type, isolated);
4625 
4626 	/*
4627 	 * There might not be eligible pages due to reclaim_idx. Check the
4628 	 * remaining to prevent livelock if it's not making progress.
4629 	 */
4630 	return isolated || !remaining ? scanned : 0;
4631 }
4632 
get_tier_idx(struct lruvec * lruvec,int type)4633 static int get_tier_idx(struct lruvec *lruvec, int type)
4634 {
4635 	int tier;
4636 	struct ctrl_pos sp, pv;
4637 
4638 	/*
4639 	 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4640 	 * This value is chosen because any other tier would have at least twice
4641 	 * as many refaults as the first tier.
4642 	 */
4643 	read_ctrl_pos(lruvec, type, 0, 1, &sp);
4644 	for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4645 		read_ctrl_pos(lruvec, type, tier, 2, &pv);
4646 		if (!positive_ctrl_err(&sp, &pv))
4647 			break;
4648 	}
4649 
4650 	return tier - 1;
4651 }
4652 
get_type_to_scan(struct lruvec * lruvec,int swappiness,int * tier_idx)4653 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4654 {
4655 	int type, tier;
4656 	struct ctrl_pos sp, pv;
4657 	int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4658 
4659 	/*
4660 	 * Compare the first tier of anon with that of file to determine which
4661 	 * type to scan. Also need to compare other tiers of the selected type
4662 	 * with the first tier of the other type to determine the last tier (of
4663 	 * the selected type) to evict.
4664 	 */
4665 	read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4666 	read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4667 	type = positive_ctrl_err(&sp, &pv);
4668 
4669 	read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4670 	for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4671 		read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4672 		if (!positive_ctrl_err(&sp, &pv))
4673 			break;
4674 	}
4675 
4676 	*tier_idx = tier - 1;
4677 
4678 	return type;
4679 }
4680 
isolate_pages(struct lruvec * lruvec,struct scan_control * sc,int swappiness,int * type_scanned,struct list_head * list)4681 static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4682 			 int *type_scanned, struct list_head *list)
4683 {
4684 	int i;
4685 	int type;
4686 	int scanned;
4687 	int tier = -1;
4688 	DEFINE_MIN_SEQ(lruvec);
4689 
4690 	/*
4691 	 * Try to make the obvious choice first. When anon and file are both
4692 	 * available from the same generation, interpret swappiness 1 as file
4693 	 * first and 200 as anon first.
4694 	 */
4695 	if (!swappiness)
4696 		type = LRU_GEN_FILE;
4697 	else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4698 		type = LRU_GEN_ANON;
4699 	else if (swappiness == 1)
4700 		type = LRU_GEN_FILE;
4701 	else if (swappiness == 200)
4702 		type = LRU_GEN_ANON;
4703 	else
4704 		type = get_type_to_scan(lruvec, swappiness, &tier);
4705 
4706 	for (i = !swappiness; i < ANON_AND_FILE; i++) {
4707 		if (tier < 0)
4708 			tier = get_tier_idx(lruvec, type);
4709 
4710 		scanned = scan_pages(lruvec, sc, type, tier, list);
4711 		if (scanned)
4712 			break;
4713 
4714 		type = !type;
4715 		tier = -1;
4716 	}
4717 
4718 	*type_scanned = type;
4719 
4720 	return scanned;
4721 }
4722 
evict_pages(struct lruvec * lruvec,struct scan_control * sc,int swappiness)4723 static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
4724 {
4725 	int type;
4726 	int scanned;
4727 	int reclaimed;
4728 	LIST_HEAD(list);
4729 	LIST_HEAD(clean);
4730 	struct page *page;
4731 	struct page *next;
4732 	enum vm_event_item item;
4733 	struct reclaim_stat stat;
4734 	struct lru_gen_mm_walk *walk;
4735 	bool skip_retry = false;
4736 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4737 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4738 
4739 	spin_lock_irq(&lruvec->lru_lock);
4740 
4741 	scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4742 
4743 	scanned += try_to_inc_min_seq(lruvec, swappiness);
4744 
4745 	if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4746 		scanned = 0;
4747 
4748 	spin_unlock_irq(&lruvec->lru_lock);
4749 
4750 	if (list_empty(&list))
4751 		return scanned;
4752 retry:
4753 	reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4754 	sc->nr_reclaimed += reclaimed;
4755 
4756 	list_for_each_entry_safe_reverse(page, next, &list, lru) {
4757 		if (!page_evictable(page)) {
4758 			list_del(&page->lru);
4759 			putback_lru_page(page);
4760 			continue;
4761 		}
4762 
4763 		if (PageReclaim(page) &&
4764 		    (PageDirty(page) || PageWriteback(page))) {
4765 			/* restore LRU_REFS_FLAGS cleared by isolate_page() */
4766 			if (PageWorkingset(page))
4767 				SetPageReferenced(page);
4768 			continue;
4769 		}
4770 
4771 		if (skip_retry || PageActive(page) || PageReferenced(page) ||
4772 		    page_mapped(page) || PageLocked(page) ||
4773 		    PageDirty(page) || PageWriteback(page)) {
4774 			/* don't add rejected pages to the oldest generation */
4775 			set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4776 				      BIT(PG_active));
4777 			continue;
4778 		}
4779 
4780 		/* retry pages that may have missed rotate_reclaimable_page() */
4781 		list_move(&page->lru, &clean);
4782 		sc->nr_scanned -= thp_nr_pages(page);
4783 	}
4784 
4785 	spin_lock_irq(&lruvec->lru_lock);
4786 
4787 	move_pages_to_lru(lruvec, &list);
4788 
4789 	walk = current->reclaim_state->mm_walk;
4790 	if (walk && walk->batched)
4791 		reset_batch_size(lruvec, walk);
4792 
4793 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4794 	if (!cgroup_reclaim(sc))
4795 		__count_vm_events(item, reclaimed);
4796 	__count_memcg_events(memcg, item, reclaimed);
4797 	__count_vm_events(PGSTEAL_ANON + type, reclaimed);
4798 
4799 	spin_unlock_irq(&lruvec->lru_lock);
4800 
4801 	mem_cgroup_uncharge_list(&list);
4802 	free_unref_page_list(&list);
4803 
4804 	INIT_LIST_HEAD(&list);
4805 	list_splice_init(&clean, &list);
4806 
4807 	if (!list_empty(&list)) {
4808 		skip_retry = true;
4809 		goto retry;
4810 	}
4811 
4812 	return scanned;
4813 }
4814 
should_run_aging(struct lruvec * lruvec,unsigned long max_seq,struct scan_control * sc,bool can_swap,unsigned long * nr_to_scan)4815 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4816 			     struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4817 {
4818 	int gen, type, zone;
4819 	unsigned long old = 0;
4820 	unsigned long young = 0;
4821 	unsigned long total = 0;
4822 	struct lru_gen_page *lrugen = &lruvec->lrugen;
4823 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4824 	DEFINE_MIN_SEQ(lruvec);
4825 
4826 	/* whether this lruvec is completely out of cold pages */
4827 	if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4828 		*nr_to_scan = 0;
4829 		return true;
4830 	}
4831 
4832 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4833 		unsigned long seq;
4834 
4835 		for (seq = min_seq[type]; seq <= max_seq; seq++) {
4836 			unsigned long size = 0;
4837 
4838 			gen = lru_gen_from_seq(seq);
4839 
4840 			for (zone = 0; zone < MAX_NR_ZONES; zone++)
4841 				size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4842 
4843 			total += size;
4844 			if (seq == max_seq)
4845 				young += size;
4846 			else if (seq + MIN_NR_GENS == max_seq)
4847 				old += size;
4848 		}
4849 	}
4850 
4851 	/* try to scrape all its memory if this memcg was deleted */
4852 	*nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4853 
4854 	/*
4855 	 * The aging tries to be lazy to reduce the overhead, while the eviction
4856 	 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4857 	 * ideal number of generations is MIN_NR_GENS+1.
4858 	 */
4859 	if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4860 		return false;
4861 
4862 	/*
4863 	 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4864 	 * of the total number of pages for each generation. A reasonable range
4865 	 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4866 	 * aging cares about the upper bound of hot pages, while the eviction
4867 	 * cares about the lower bound of cold pages.
4868 	 */
4869 	if (young * MIN_NR_GENS > total)
4870 		return true;
4871 	if (old * (MIN_NR_GENS + 2) < total)
4872 		return true;
4873 
4874 	return false;
4875 }
4876 
4877 /*
4878  * For future optimizations:
4879  * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4880  *    reclaim.
4881  */
get_nr_to_scan(struct lruvec * lruvec,struct scan_control * sc,bool can_swap)4882 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4883 {
4884 	unsigned long nr_to_scan;
4885 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4886 	DEFINE_MAX_SEQ(lruvec);
4887 
4888 	if (mem_cgroup_below_min(memcg))
4889 		return 0;
4890 
4891 	if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
4892 		return nr_to_scan;
4893 
4894 	/* skip the aging path at the default priority */
4895 	if (sc->priority == DEF_PRIORITY)
4896 		return nr_to_scan;
4897 
4898 	/* skip this lruvec as it's low on cold pages */
4899 	return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
4900 }
4901 
get_nr_to_reclaim(struct scan_control * sc)4902 static unsigned long get_nr_to_reclaim(struct scan_control *sc)
4903 {
4904 	/* don't abort memcg reclaim to ensure fairness */
4905 	if (!global_reclaim(sc))
4906 		return -1;
4907 
4908 	return max(sc->nr_to_reclaim, compact_gap(sc->order));
4909 }
4910 
try_to_shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)4911 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4912 {
4913 	long nr_to_scan;
4914 	unsigned long scanned = 0;
4915 	unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
4916 	int swappiness = get_swappiness(lruvec, sc);
4917 
4918 	/* clean file pages are more likely to exist */
4919 	if (swappiness && !(sc->gfp_mask & __GFP_IO))
4920 		swappiness = 1;
4921 
4922 	while (true) {
4923 		int delta;
4924 
4925 		nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4926 		if (nr_to_scan <= 0)
4927 			break;
4928 
4929 		delta = evict_pages(lruvec, sc, swappiness);
4930 		if (!delta)
4931 			break;
4932 
4933 		scanned += delta;
4934 		if (scanned >= nr_to_scan)
4935 			break;
4936 
4937 		if (sc->nr_reclaimed >= nr_to_reclaim)
4938 			break;
4939 
4940 		cond_resched();
4941 	}
4942 
4943 	/* whether try_to_inc_max_seq() was successful */
4944 	return nr_to_scan < 0;
4945 }
4946 
shrink_one(struct lruvec * lruvec,struct scan_control * sc)4947 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4948 {
4949 	bool success;
4950 	unsigned long scanned = sc->nr_scanned;
4951 	unsigned long reclaimed = sc->nr_reclaimed;
4952 	int seg = lru_gen_memcg_seg(lruvec);
4953 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4954 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4955 
4956 	/* see the comment on MEMCG_NR_GENS */
4957 	if (!lruvec_is_sizable(lruvec, sc))
4958 		return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
4959 
4960 	mem_cgroup_calculate_protection(NULL, memcg);
4961 
4962 	if (mem_cgroup_below_min(memcg))
4963 		return MEMCG_LRU_YOUNG;
4964 
4965 	if (mem_cgroup_below_low(memcg)) {
4966 		/* see the comment on MEMCG_NR_GENS */
4967 		if (seg != MEMCG_LRU_TAIL)
4968 			return MEMCG_LRU_TAIL;
4969 
4970 		memcg_memory_event(memcg, MEMCG_LOW);
4971 	}
4972 
4973 	success = try_to_shrink_lruvec(lruvec, sc);
4974 
4975 	shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
4976 
4977 	vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
4978 		   sc->nr_reclaimed - reclaimed);
4979 
4980 	sc->nr_reclaimed += current->reclaim_state->reclaimed_slab;
4981 	current->reclaim_state->reclaimed_slab = 0;
4982 
4983 	return success ? MEMCG_LRU_YOUNG : 0;
4984 }
4985 
4986 #ifdef CONFIG_MEMCG
4987 
shrink_many(struct pglist_data * pgdat,struct scan_control * sc)4988 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
4989 {
4990 	int op;
4991 	int gen;
4992 	int bin;
4993 	int first_bin;
4994 	struct lruvec *lruvec;
4995 	struct lru_gen_page *lrugen;
4996 	struct mem_cgroup *memcg;
4997 	const struct hlist_nulls_node *pos;
4998 	unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
4999 
5000 	bin = first_bin = prandom_u32_max(MEMCG_NR_BINS);
5001 restart:
5002 	op = 0;
5003 	memcg = NULL;
5004 	gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5005 
5006 	rcu_read_lock();
5007 
5008 	hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5009 		if (op)
5010 			lru_gen_rotate_memcg(lruvec, op);
5011 
5012 		mem_cgroup_put(memcg);
5013 
5014 		lruvec = container_of(lrugen, struct lruvec, lrugen);
5015 		memcg = lruvec_memcg(lruvec);
5016 
5017 		if (!mem_cgroup_tryget(memcg)) {
5018 			op = 0;
5019 			memcg = NULL;
5020 			continue;
5021 		}
5022 
5023 		rcu_read_unlock();
5024 
5025 		op = shrink_one(lruvec, sc);
5026 
5027 		rcu_read_lock();
5028 
5029 		if (sc->nr_reclaimed >= nr_to_reclaim)
5030 			break;
5031 	}
5032 
5033 	rcu_read_unlock();
5034 
5035 	if (op)
5036 		lru_gen_rotate_memcg(lruvec, op);
5037 
5038 	mem_cgroup_put(memcg);
5039 
5040 	if (sc->nr_reclaimed >= nr_to_reclaim)
5041 		return;
5042 
5043 	/* restart if raced with lru_gen_rotate_memcg() */
5044 	if (gen != get_nulls_value(pos))
5045 		goto restart;
5046 
5047 	/* try the rest of the bins of the current generation */
5048 	bin = get_memcg_bin(bin + 1);
5049 	if (bin != first_bin)
5050 		goto restart;
5051 }
5052 
lru_gen_shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)5053 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5054 {
5055 	struct blk_plug plug;
5056 
5057 	VM_WARN_ON_ONCE(global_reclaim(sc));
5058 	VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
5059 
5060 	lru_add_drain();
5061 
5062 	blk_start_plug(&plug);
5063 
5064 	set_mm_walk(NULL, false);
5065 
5066 	if (try_to_shrink_lruvec(lruvec, sc))
5067 		lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5068 
5069 	clear_mm_walk();
5070 
5071 	blk_finish_plug(&plug);
5072 }
5073 
5074 #else /* !CONFIG_MEMCG */
5075 
shrink_many(struct pglist_data * pgdat,struct scan_control * sc)5076 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5077 {
5078 	BUILD_BUG();
5079 }
5080 
lru_gen_shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)5081 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5082 {
5083 	BUILD_BUG();
5084 }
5085 
5086 #endif
5087 
set_initial_priority(struct pglist_data * pgdat,struct scan_control * sc)5088 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5089 {
5090 	int priority;
5091 	unsigned long reclaimable;
5092 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5093 
5094 	if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5095 		return;
5096 	/*
5097 	 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5098 	 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5099 	 * estimated reclaimed_to_scanned_ratio = inactive / total.
5100 	 */
5101 	reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5102 	if (get_swappiness(lruvec, sc))
5103 		reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5104 
5105 	reclaimable /= MEMCG_NR_GENS;
5106 
5107 	/* round down reclaimable and round up sc->nr_to_reclaim */
5108 	priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5109 
5110 	sc->priority = clamp(priority, 0, DEF_PRIORITY);
5111 }
5112 
lru_gen_shrink_node(struct pglist_data * pgdat,struct scan_control * sc)5113 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5114 {
5115 	struct blk_plug plug;
5116 	unsigned long reclaimed = sc->nr_reclaimed;
5117 
5118 	VM_WARN_ON_ONCE(!global_reclaim(sc));
5119 
5120 	/*
5121 	 * Unmapped clean pages are already prioritized. Scanning for more of
5122 	 * them is likely futile and can cause high reclaim latency when there
5123 	 * is a large number of memcgs.
5124 	 */
5125 	if (!sc->may_writepage || !sc->may_unmap)
5126 		goto done;
5127 
5128 	lru_add_drain();
5129 
5130 	blk_start_plug(&plug);
5131 
5132 	set_mm_walk(pgdat, false);
5133 
5134 	set_initial_priority(pgdat, sc);
5135 
5136 	if (current_is_kswapd())
5137 		sc->nr_reclaimed = 0;
5138 
5139 	if (mem_cgroup_disabled())
5140 		shrink_one(&pgdat->__lruvec, sc);
5141 	else
5142 		shrink_many(pgdat, sc);
5143 
5144 	if (current_is_kswapd())
5145 		sc->nr_reclaimed += reclaimed;
5146 
5147 	clear_mm_walk();
5148 
5149 	blk_finish_plug(&plug);
5150 done:
5151 	/* kswapd should never fail */
5152 	pgdat->kswapd_failures = 0;
5153 }
5154 
5155 #ifdef CONFIG_MEMCG
lru_gen_rotate_memcg(struct lruvec * lruvec,int op)5156 void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
5157 {
5158 	int seg;
5159 	int old, new;
5160 	int bin = prandom_u32_max(MEMCG_NR_BINS);
5161 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5162 
5163 	spin_lock(&pgdat->memcg_lru.lock);
5164 
5165 	VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5166 
5167 	seg = 0;
5168 	new = old = lruvec->lrugen.gen;
5169 
5170 	/* see the comment on MEMCG_NR_GENS */
5171 	if (op == MEMCG_LRU_HEAD)
5172 		seg = MEMCG_LRU_HEAD;
5173 	else if (op == MEMCG_LRU_TAIL)
5174 		seg = MEMCG_LRU_TAIL;
5175 	else if (op == MEMCG_LRU_OLD)
5176 		new = get_memcg_gen(pgdat->memcg_lru.seq);
5177 	else if (op == MEMCG_LRU_YOUNG)
5178 		new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
5179 	else
5180 		VM_WARN_ON_ONCE(true);
5181 
5182 	hlist_nulls_del_rcu(&lruvec->lrugen.list);
5183 
5184 	if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
5185 		hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5186 	else
5187 		hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5188 
5189 	pgdat->memcg_lru.nr_memcgs[old]--;
5190 	pgdat->memcg_lru.nr_memcgs[new]++;
5191 
5192 	lruvec->lrugen.gen = new;
5193 	WRITE_ONCE(lruvec->lrugen.seg, seg);
5194 
5195 	if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
5196 		WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5197 
5198 	spin_unlock(&pgdat->memcg_lru.lock);
5199 }
5200 #endif
5201 
5202 /******************************************************************************
5203  *                          state change
5204  ******************************************************************************/
5205 
state_is_valid(struct lruvec * lruvec)5206 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5207 {
5208 	struct lru_gen_page *lrugen = &lruvec->lrugen;
5209 
5210 	if (lrugen->enabled) {
5211 		enum lru_list lru;
5212 
5213 		for_each_evictable_lru(lru) {
5214 			if (!list_empty(&lruvec->lists[lru]))
5215 				return false;
5216 		}
5217 	} else {
5218 		int gen, type, zone;
5219 
5220 		for_each_gen_type_zone(gen, type, zone) {
5221 			if (!list_empty(&lrugen->pages[gen][type][zone]))
5222 				return false;
5223 		}
5224 	}
5225 
5226 	return true;
5227 }
5228 
fill_evictable(struct lruvec * lruvec)5229 static bool fill_evictable(struct lruvec *lruvec)
5230 {
5231 	enum lru_list lru;
5232 	int remaining = MAX_LRU_BATCH;
5233 
5234 	for_each_evictable_lru(lru) {
5235 		int type = is_file_lru(lru);
5236 		bool active = is_active_lru(lru);
5237 		struct list_head *head = &lruvec->lists[lru];
5238 
5239 		while (!list_empty(head)) {
5240 			bool success;
5241 			struct page *page = lru_to_page(head);
5242 
5243 			VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5244 			VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5245 			VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5246 			VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5247 
5248 			del_page_from_lru_list(page, lruvec);
5249 			success = lru_gen_add_page(lruvec, page, false);
5250 			VM_WARN_ON_ONCE(!success);
5251 
5252 			if (!--remaining)
5253 				return false;
5254 		}
5255 	}
5256 
5257 	return true;
5258 }
5259 
drain_evictable(struct lruvec * lruvec)5260 static bool drain_evictable(struct lruvec *lruvec)
5261 {
5262 	int gen, type, zone;
5263 	int remaining = MAX_LRU_BATCH;
5264 
5265 	for_each_gen_type_zone(gen, type, zone) {
5266 		struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
5267 
5268 		while (!list_empty(head)) {
5269 			bool success;
5270 			struct page *page = lru_to_page(head);
5271 
5272 			VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5273 			VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5274 			VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5275 			VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5276 
5277 			success = lru_gen_del_page(lruvec, page, false);
5278 			VM_WARN_ON_ONCE(!success);
5279 			add_page_to_lru_list(page, lruvec);
5280 
5281 			if (!--remaining)
5282 				return false;
5283 		}
5284 	}
5285 
5286 	return true;
5287 }
5288 
lru_gen_change_state(bool enabled)5289 static void lru_gen_change_state(bool enabled)
5290 {
5291 	static DEFINE_MUTEX(state_mutex);
5292 
5293 	struct mem_cgroup *memcg;
5294 
5295 	cgroup_lock();
5296 	cpus_read_lock();
5297 	get_online_mems();
5298 	mutex_lock(&state_mutex);
5299 
5300 	if (enabled == lru_gen_enabled())
5301 		goto unlock;
5302 
5303 	if (enabled)
5304 		static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5305 	else
5306 		static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5307 
5308 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
5309 	do {
5310 		int nid;
5311 
5312 		for_each_node(nid) {
5313 			struct lruvec *lruvec = get_lruvec(memcg, nid);
5314 
5315 			if (!lruvec)
5316 				continue;
5317 
5318 			spin_lock_irq(&lruvec->lru_lock);
5319 
5320 			VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5321 			VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5322 
5323 			lruvec->lrugen.enabled = enabled;
5324 
5325 			while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5326 				spin_unlock_irq(&lruvec->lru_lock);
5327 				cond_resched();
5328 				spin_lock_irq(&lruvec->lru_lock);
5329 			}
5330 
5331 			spin_unlock_irq(&lruvec->lru_lock);
5332 		}
5333 
5334 		cond_resched();
5335 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5336 unlock:
5337 	mutex_unlock(&state_mutex);
5338 	put_online_mems();
5339 	cpus_read_unlock();
5340 	cgroup_unlock();
5341 }
5342 
5343 /******************************************************************************
5344  *                          sysfs interface
5345  ******************************************************************************/
5346 
show_min_ttl(struct kobject * kobj,struct kobj_attribute * attr,char * buf)5347 static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5348 {
5349 	return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5350 }
5351 
5352 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
store_min_ttl(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)5353 static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5354 			     const char *buf, size_t len)
5355 {
5356 	unsigned int msecs;
5357 
5358 	if (kstrtouint(buf, 0, &msecs))
5359 		return -EINVAL;
5360 
5361 	WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5362 
5363 	return len;
5364 }
5365 
5366 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5367 	min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5368 );
5369 
show_enabled(struct kobject * kobj,struct kobj_attribute * attr,char * buf)5370 static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5371 {
5372 	unsigned int caps = 0;
5373 
5374 	if (get_cap(LRU_GEN_CORE))
5375 		caps |= BIT(LRU_GEN_CORE);
5376 
5377 	if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5378 		caps |= BIT(LRU_GEN_MM_WALK);
5379 
5380 	if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
5381 		caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5382 
5383 	return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5384 }
5385 
5386 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
store_enabled(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)5387 static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5388 			     const char *buf, size_t len)
5389 {
5390 	int i;
5391 	unsigned int caps;
5392 
5393 	if (tolower(*buf) == 'n')
5394 		caps = 0;
5395 	else if (tolower(*buf) == 'y')
5396 		caps = -1;
5397 	else if (kstrtouint(buf, 0, &caps))
5398 		return -EINVAL;
5399 
5400 	for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5401 		bool enabled = caps & BIT(i);
5402 
5403 		if (i == LRU_GEN_CORE)
5404 			lru_gen_change_state(enabled);
5405 		else if (enabled)
5406 			static_branch_enable(&lru_gen_caps[i]);
5407 		else
5408 			static_branch_disable(&lru_gen_caps[i]);
5409 	}
5410 
5411 	return len;
5412 }
5413 
5414 static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5415 	enabled, 0644, show_enabled, store_enabled
5416 );
5417 
5418 static struct attribute *lru_gen_attrs[] = {
5419 	&lru_gen_min_ttl_attr.attr,
5420 	&lru_gen_enabled_attr.attr,
5421 	NULL
5422 };
5423 
5424 static struct attribute_group lru_gen_attr_group = {
5425 	.name = "lru_gen",
5426 	.attrs = lru_gen_attrs,
5427 };
5428 
5429 /******************************************************************************
5430  *                          debugfs interface
5431  ******************************************************************************/
5432 
lru_gen_seq_start(struct seq_file * m,loff_t * pos)5433 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5434 {
5435 	struct mem_cgroup *memcg;
5436 	loff_t nr_to_skip = *pos;
5437 
5438 	m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5439 	if (!m->private)
5440 		return ERR_PTR(-ENOMEM);
5441 
5442 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
5443 	do {
5444 		int nid;
5445 
5446 		for_each_node_state(nid, N_MEMORY) {
5447 			if (!nr_to_skip--)
5448 				return get_lruvec(memcg, nid);
5449 		}
5450 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5451 
5452 	return NULL;
5453 }
5454 
lru_gen_seq_stop(struct seq_file * m,void * v)5455 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5456 {
5457 	if (!IS_ERR_OR_NULL(v))
5458 		mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5459 
5460 	kvfree(m->private);
5461 	m->private = NULL;
5462 }
5463 
lru_gen_seq_next(struct seq_file * m,void * v,loff_t * pos)5464 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5465 {
5466 	int nid = lruvec_pgdat(v)->node_id;
5467 	struct mem_cgroup *memcg = lruvec_memcg(v);
5468 
5469 	++*pos;
5470 
5471 	nid = next_memory_node(nid);
5472 	if (nid == MAX_NUMNODES) {
5473 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
5474 		if (!memcg)
5475 			return NULL;
5476 
5477 		nid = first_memory_node;
5478 	}
5479 
5480 	return get_lruvec(memcg, nid);
5481 }
5482 
lru_gen_seq_show_full(struct seq_file * m,struct lruvec * lruvec,unsigned long max_seq,unsigned long * min_seq,unsigned long seq)5483 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5484 				  unsigned long max_seq, unsigned long *min_seq,
5485 				  unsigned long seq)
5486 {
5487 	int i;
5488 	int type, tier;
5489 	int hist = lru_hist_from_seq(seq);
5490 	struct lru_gen_page *lrugen = &lruvec->lrugen;
5491 
5492 	for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5493 		seq_printf(m, "            %10d", tier);
5494 		for (type = 0; type < ANON_AND_FILE; type++) {
5495 			const char *s = "   ";
5496 			unsigned long n[3] = {};
5497 
5498 			if (seq == max_seq) {
5499 				s = "RT ";
5500 				n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5501 				n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5502 			} else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5503 				s = "rep";
5504 				n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5505 				n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5506 				if (tier)
5507 					n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5508 			}
5509 
5510 			for (i = 0; i < 3; i++)
5511 				seq_printf(m, " %10lu%c", n[i], s[i]);
5512 		}
5513 		seq_putc(m, '\n');
5514 	}
5515 
5516 	seq_puts(m, "                      ");
5517 	for (i = 0; i < NR_MM_STATS; i++) {
5518 		const char *s = "      ";
5519 		unsigned long n = 0;
5520 
5521 		if (seq == max_seq && NR_HIST_GENS == 1) {
5522 			s = "LOYNFA";
5523 			n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5524 		} else if (seq != max_seq && NR_HIST_GENS > 1) {
5525 			s = "loynfa";
5526 			n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5527 		}
5528 
5529 		seq_printf(m, " %10lu%c", n, s[i]);
5530 	}
5531 	seq_putc(m, '\n');
5532 }
5533 
5534 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
lru_gen_seq_show(struct seq_file * m,void * v)5535 static int lru_gen_seq_show(struct seq_file *m, void *v)
5536 {
5537 	unsigned long seq;
5538 	bool full = !debugfs_real_fops(m->file)->write;
5539 	struct lruvec *lruvec = v;
5540 	struct lru_gen_page *lrugen = &lruvec->lrugen;
5541 	int nid = lruvec_pgdat(lruvec)->node_id;
5542 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5543 	DEFINE_MAX_SEQ(lruvec);
5544 	DEFINE_MIN_SEQ(lruvec);
5545 
5546 	if (nid == first_memory_node) {
5547 		const char *path = memcg ? m->private : "";
5548 
5549 #ifdef CONFIG_MEMCG
5550 		if (memcg)
5551 			cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5552 #endif
5553 		seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5554 	}
5555 
5556 	seq_printf(m, " node %5d\n", nid);
5557 
5558 	if (!full)
5559 		seq = min_seq[LRU_GEN_ANON];
5560 	else if (max_seq >= MAX_NR_GENS)
5561 		seq = max_seq - MAX_NR_GENS + 1;
5562 	else
5563 		seq = 0;
5564 
5565 	for (; seq <= max_seq; seq++) {
5566 		int type, zone;
5567 		int gen = lru_gen_from_seq(seq);
5568 		unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5569 
5570 		seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5571 
5572 		for (type = 0; type < ANON_AND_FILE; type++) {
5573 			unsigned long size = 0;
5574 			char mark = full && seq < min_seq[type] ? 'x' : ' ';
5575 
5576 			for (zone = 0; zone < MAX_NR_ZONES; zone++)
5577 				size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5578 
5579 			seq_printf(m, " %10lu%c", size, mark);
5580 		}
5581 
5582 		seq_putc(m, '\n');
5583 
5584 		if (full)
5585 			lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5586 	}
5587 
5588 	return 0;
5589 }
5590 
5591 static const struct seq_operations lru_gen_seq_ops = {
5592 	.start = lru_gen_seq_start,
5593 	.stop = lru_gen_seq_stop,
5594 	.next = lru_gen_seq_next,
5595 	.show = lru_gen_seq_show,
5596 };
5597 
run_aging(struct lruvec * lruvec,unsigned long seq,struct scan_control * sc,bool can_swap,bool force_scan)5598 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5599 		     bool can_swap, bool force_scan)
5600 {
5601 	DEFINE_MAX_SEQ(lruvec);
5602 	DEFINE_MIN_SEQ(lruvec);
5603 
5604 	if (seq < max_seq)
5605 		return 0;
5606 
5607 	if (seq > max_seq)
5608 		return -EINVAL;
5609 
5610 	if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5611 		return -ERANGE;
5612 
5613 	try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5614 
5615 	return 0;
5616 }
5617 
run_eviction(struct lruvec * lruvec,unsigned long seq,struct scan_control * sc,int swappiness,unsigned long nr_to_reclaim)5618 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5619 			int swappiness, unsigned long nr_to_reclaim)
5620 {
5621 	DEFINE_MAX_SEQ(lruvec);
5622 
5623 	if (seq + MIN_NR_GENS > max_seq)
5624 		return -EINVAL;
5625 
5626 	sc->nr_reclaimed = 0;
5627 
5628 	while (!signal_pending(current)) {
5629 		DEFINE_MIN_SEQ(lruvec);
5630 
5631 		if (seq < min_seq[!swappiness])
5632 			return 0;
5633 
5634 		if (sc->nr_reclaimed >= nr_to_reclaim)
5635 			return 0;
5636 
5637 		if (!evict_pages(lruvec, sc, swappiness))
5638 			return 0;
5639 
5640 		cond_resched();
5641 	}
5642 
5643 	return -EINTR;
5644 }
5645 
run_cmd(char cmd,int memcg_id,int nid,unsigned long seq,struct scan_control * sc,int swappiness,unsigned long opt)5646 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5647 		   struct scan_control *sc, int swappiness, unsigned long opt)
5648 {
5649 	struct lruvec *lruvec;
5650 	int err = -EINVAL;
5651 	struct mem_cgroup *memcg = NULL;
5652 
5653 	if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5654 		return -EINVAL;
5655 
5656 	if (!mem_cgroup_disabled()) {
5657 		rcu_read_lock();
5658 
5659 		memcg = mem_cgroup_from_id(memcg_id);
5660 		if (!mem_cgroup_tryget(memcg))
5661 			memcg = NULL;
5662 
5663 		rcu_read_unlock();
5664 
5665 		if (!memcg)
5666 			return -EINVAL;
5667 	}
5668 
5669 	if (memcg_id != mem_cgroup_id(memcg))
5670 		goto done;
5671 
5672 	lruvec = get_lruvec(memcg, nid);
5673 
5674 	if (swappiness < 0)
5675 		swappiness = get_swappiness(lruvec, sc);
5676 	else if (swappiness > 200)
5677 		goto done;
5678 
5679 	switch (cmd) {
5680 	case '+':
5681 		err = run_aging(lruvec, seq, sc, swappiness, opt);
5682 		break;
5683 	case '-':
5684 		err = run_eviction(lruvec, seq, sc, swappiness, opt);
5685 		break;
5686 	}
5687 done:
5688 	mem_cgroup_put(memcg);
5689 
5690 	return err;
5691 }
5692 
5693 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
lru_gen_seq_write(struct file * file,const char __user * src,size_t len,loff_t * pos)5694 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5695 				 size_t len, loff_t *pos)
5696 {
5697 	void *buf;
5698 	char *cur, *next;
5699 	unsigned int flags;
5700 	struct blk_plug plug;
5701 	int err = -EINVAL;
5702 	struct scan_control sc = {
5703 		.may_writepage = true,
5704 		.may_unmap = true,
5705 		.may_swap = true,
5706 		.reclaim_idx = MAX_NR_ZONES - 1,
5707 		.gfp_mask = GFP_KERNEL,
5708 	};
5709 
5710 	buf = kvmalloc(len + 1, GFP_KERNEL);
5711 	if (!buf)
5712 		return -ENOMEM;
5713 
5714 	if (copy_from_user(buf, src, len)) {
5715 		kvfree(buf);
5716 		return -EFAULT;
5717 	}
5718 
5719 	set_task_reclaim_state(current, &sc.reclaim_state);
5720 	flags = memalloc_noreclaim_save();
5721 	blk_start_plug(&plug);
5722 	if (!set_mm_walk(NULL, true)) {
5723 		err = -ENOMEM;
5724 		goto done;
5725 	}
5726 
5727 	next = buf;
5728 	next[len] = '\0';
5729 
5730 	while ((cur = strsep(&next, ",;\n"))) {
5731 		int n;
5732 		int end;
5733 		char cmd;
5734 		unsigned int memcg_id;
5735 		unsigned int nid;
5736 		unsigned long seq;
5737 		unsigned int swappiness = -1;
5738 		unsigned long opt = -1;
5739 
5740 		cur = skip_spaces(cur);
5741 		if (!*cur)
5742 			continue;
5743 
5744 		n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5745 			   &seq, &end, &swappiness, &end, &opt, &end);
5746 		if (n < 4 || cur[end]) {
5747 			err = -EINVAL;
5748 			break;
5749 		}
5750 
5751 		err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5752 		if (err)
5753 			break;
5754 	}
5755 done:
5756 	clear_mm_walk();
5757 	blk_finish_plug(&plug);
5758 	memalloc_noreclaim_restore(flags);
5759 	set_task_reclaim_state(current, NULL);
5760 
5761 	kvfree(buf);
5762 
5763 	return err ? : len;
5764 }
5765 
lru_gen_seq_open(struct inode * inode,struct file * file)5766 static int lru_gen_seq_open(struct inode *inode, struct file *file)
5767 {
5768 	return seq_open(file, &lru_gen_seq_ops);
5769 }
5770 
5771 static const struct file_operations lru_gen_rw_fops = {
5772 	.open = lru_gen_seq_open,
5773 	.read = seq_read,
5774 	.write = lru_gen_seq_write,
5775 	.llseek = seq_lseek,
5776 	.release = seq_release,
5777 };
5778 
5779 static const struct file_operations lru_gen_ro_fops = {
5780 	.open = lru_gen_seq_open,
5781 	.read = seq_read,
5782 	.llseek = seq_lseek,
5783 	.release = seq_release,
5784 };
5785 
5786 /******************************************************************************
5787  *                          initialization
5788  ******************************************************************************/
5789 
lru_gen_init_lruvec(struct lruvec * lruvec)5790 void lru_gen_init_lruvec(struct lruvec *lruvec)
5791 {
5792 	int i;
5793 	int gen, type, zone;
5794 	struct lru_gen_page *lrugen = &lruvec->lrugen;
5795 
5796 	lrugen->max_seq = MIN_NR_GENS + 1;
5797 	lrugen->enabled = lru_gen_enabled();
5798 
5799 	for (i = 0; i <= MIN_NR_GENS + 1; i++)
5800 		lrugen->timestamps[i] = jiffies;
5801 
5802 	for_each_gen_type_zone(gen, type, zone)
5803 		INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
5804 
5805 	lruvec->mm_state.seq = MIN_NR_GENS;
5806 }
5807 
5808 #ifdef CONFIG_MEMCG
5809 
lru_gen_init_pgdat(struct pglist_data * pgdat)5810 void lru_gen_init_pgdat(struct pglist_data *pgdat)
5811 {
5812 	int i, j;
5813 
5814 	spin_lock_init(&pgdat->memcg_lru.lock);
5815 
5816 	for (i = 0; i < MEMCG_NR_GENS; i++) {
5817 		for (j = 0; j < MEMCG_NR_BINS; j++)
5818 			INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5819 	}
5820 }
5821 
lru_gen_init_memcg(struct mem_cgroup * memcg)5822 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5823 {
5824 	INIT_LIST_HEAD(&memcg->mm_list.fifo);
5825 	spin_lock_init(&memcg->mm_list.lock);
5826 }
5827 
lru_gen_exit_memcg(struct mem_cgroup * memcg)5828 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5829 {
5830 	int i;
5831 	int nid;
5832 
5833 	for_each_node(nid) {
5834 		struct lruvec *lruvec = get_lruvec(memcg, nid);
5835 
5836 		VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5837 					   sizeof(lruvec->lrugen.nr_pages)));
5838 
5839 		for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5840 			bitmap_free(lruvec->mm_state.filters[i]);
5841 			lruvec->mm_state.filters[i] = NULL;
5842 		}
5843 	}
5844 }
5845 
lru_gen_online_memcg(struct mem_cgroup * memcg)5846 void lru_gen_online_memcg(struct mem_cgroup *memcg)
5847 {
5848 	int gen;
5849 	int nid;
5850 	int bin = prandom_u32_max(MEMCG_NR_BINS);
5851 
5852 	for_each_node(nid) {
5853 		struct pglist_data *pgdat = NODE_DATA(nid);
5854 		struct lruvec *lruvec = get_lruvec(memcg, nid);
5855 
5856 		spin_lock(&pgdat->memcg_lru.lock);
5857 
5858 		VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
5859 
5860 		gen = get_memcg_gen(pgdat->memcg_lru.seq);
5861 
5862 		hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
5863 		pgdat->memcg_lru.nr_memcgs[gen]++;
5864 
5865 		lruvec->lrugen.gen = gen;
5866 
5867 		spin_unlock(&pgdat->memcg_lru.lock);
5868 	}
5869 }
5870 
lru_gen_offline_memcg(struct mem_cgroup * memcg)5871 void lru_gen_offline_memcg(struct mem_cgroup *memcg)
5872 {
5873 	int nid;
5874 
5875 	for_each_node(nid) {
5876 		struct lruvec *lruvec = get_lruvec(memcg, nid);
5877 
5878 		lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
5879 	}
5880 }
5881 
lru_gen_release_memcg(struct mem_cgroup * memcg)5882 void lru_gen_release_memcg(struct mem_cgroup *memcg)
5883 {
5884 	int gen;
5885 	int nid;
5886 
5887 	for_each_node(nid) {
5888 		struct pglist_data *pgdat = NODE_DATA(nid);
5889 		struct lruvec *lruvec = get_lruvec(memcg, nid);
5890 
5891 		spin_lock(&pgdat->memcg_lru.lock);
5892 
5893 		VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5894 
5895 		gen = lruvec->lrugen.gen;
5896 
5897 		hlist_nulls_del_rcu(&lruvec->lrugen.list);
5898 		pgdat->memcg_lru.nr_memcgs[gen]--;
5899 
5900 		if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
5901 			WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5902 
5903 		spin_unlock(&pgdat->memcg_lru.lock);
5904 	}
5905 }
5906 
5907 #endif /* CONFIG_MEMCG */
5908 
init_lru_gen(void)5909 static int __init init_lru_gen(void)
5910 {
5911 	BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5912 	BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5913 
5914 	if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5915 		pr_err("lru_gen: failed to create sysfs group\n");
5916 
5917 	debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5918 	debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5919 
5920 	return 0;
5921 };
5922 late_initcall(init_lru_gen);
5923 
5924 #else /* !CONFIG_LRU_GEN */
5925 
lru_gen_age_node(struct pglist_data * pgdat,struct scan_control * sc)5926 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5927 {
5928 }
5929 
lru_gen_shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)5930 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5931 {
5932 }
5933 
lru_gen_shrink_node(struct pglist_data * pgdat,struct scan_control * sc)5934 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5935 {
5936 }
5937 
5938 #endif /* CONFIG_LRU_GEN */
5939 
shrink_lruvec(struct lruvec * lruvec,struct scan_control * sc)5940 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5941 {
5942 	unsigned long nr[NR_LRU_LISTS];
5943 	unsigned long targets[NR_LRU_LISTS];
5944 	unsigned long nr_to_scan;
5945 	enum lru_list lru;
5946 	unsigned long nr_reclaimed = 0;
5947 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5948 	bool proportional_reclaim;
5949 	struct blk_plug plug;
5950 	bool do_plug = true;
5951 
5952 	if (lru_gen_enabled() && !global_reclaim(sc)) {
5953 		lru_gen_shrink_lruvec(lruvec, sc);
5954 		return;
5955 	}
5956 
5957 	get_scan_count(lruvec, sc, nr);
5958 
5959 	/* Record the original scan target for proportional adjustments later */
5960 	memcpy(targets, nr, sizeof(nr));
5961 
5962 	/*
5963 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5964 	 * event that can occur when there is little memory pressure e.g.
5965 	 * multiple streaming readers/writers. Hence, we do not abort scanning
5966 	 * when the requested number of pages are reclaimed when scanning at
5967 	 * DEF_PRIORITY on the assumption that the fact we are direct
5968 	 * reclaiming implies that kswapd is not keeping up and it is best to
5969 	 * do a batch of work at once. For memcg reclaim one check is made to
5970 	 * abort proportional reclaim if either the file or anon lru has already
5971 	 * dropped to zero at the first pass.
5972 	 */
5973 	proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5974 				sc->priority == DEF_PRIORITY);
5975 
5976 	trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
5977 	if (do_plug)
5978 		blk_start_plug(&plug);
5979 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5980 					nr[LRU_INACTIVE_FILE]) {
5981 		unsigned long nr_anon, nr_file, percentage;
5982 		unsigned long nr_scanned;
5983 
5984 		for_each_evictable_lru(lru) {
5985 			if (nr[lru]) {
5986 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5987 				nr[lru] -= nr_to_scan;
5988 
5989 				nr_reclaimed += shrink_list(lru, nr_to_scan,
5990 							    lruvec, sc);
5991 			}
5992 		}
5993 
5994 		cond_resched();
5995 
5996 		if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
5997 			continue;
5998 
5999 		/*
6000 		 * For kswapd and memcg, reclaim at least the number of pages
6001 		 * requested. Ensure that the anon and file LRUs are scanned
6002 		 * proportionally what was requested by get_scan_count(). We
6003 		 * stop reclaiming one LRU and reduce the amount scanning
6004 		 * proportional to the original scan target.
6005 		 */
6006 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6007 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6008 
6009 		/*
6010 		 * It's just vindictive to attack the larger once the smaller
6011 		 * has gone to zero.  And given the way we stop scanning the
6012 		 * smaller below, this makes sure that we only make one nudge
6013 		 * towards proportionality once we've got nr_to_reclaim.
6014 		 */
6015 		if (!nr_file || !nr_anon)
6016 			break;
6017 
6018 		if (nr_file > nr_anon) {
6019 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6020 						targets[LRU_ACTIVE_ANON] + 1;
6021 			lru = LRU_BASE;
6022 			percentage = nr_anon * 100 / scan_target;
6023 		} else {
6024 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6025 						targets[LRU_ACTIVE_FILE] + 1;
6026 			lru = LRU_FILE;
6027 			percentage = nr_file * 100 / scan_target;
6028 		}
6029 
6030 		/* Stop scanning the smaller of the LRU */
6031 		nr[lru] = 0;
6032 		nr[lru + LRU_ACTIVE] = 0;
6033 
6034 		/*
6035 		 * Recalculate the other LRU scan count based on its original
6036 		 * scan target and the percentage scanning already complete
6037 		 */
6038 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6039 		nr_scanned = targets[lru] - nr[lru];
6040 		nr[lru] = targets[lru] * (100 - percentage) / 100;
6041 		nr[lru] -= min(nr[lru], nr_scanned);
6042 
6043 		lru += LRU_ACTIVE;
6044 		nr_scanned = targets[lru] - nr[lru];
6045 		nr[lru] = targets[lru] * (100 - percentage) / 100;
6046 		nr[lru] -= min(nr[lru], nr_scanned);
6047 	}
6048 	if (do_plug)
6049 		blk_finish_plug(&plug);
6050 	sc->nr_reclaimed += nr_reclaimed;
6051 
6052 	/*
6053 	 * Even if we did not try to evict anon pages at all, we want to
6054 	 * rebalance the anon lru active/inactive ratio.
6055 	 */
6056 	if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6057 	    inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6058 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6059 				   sc, LRU_ACTIVE_ANON);
6060 }
6061 
6062 /* Use reclaim/compaction for costly allocs or under memory pressure */
in_reclaim_compaction(struct scan_control * sc)6063 static bool in_reclaim_compaction(struct scan_control *sc)
6064 {
6065 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
6066 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
6067 			 sc->priority < DEF_PRIORITY - 2))
6068 		return true;
6069 
6070 	return false;
6071 }
6072 
6073 /*
6074  * Reclaim/compaction is used for high-order allocation requests. It reclaims
6075  * order-0 pages before compacting the zone. should_continue_reclaim() returns
6076  * true if more pages should be reclaimed such that when the page allocator
6077  * calls try_to_compact_pages() that it will have enough free pages to succeed.
6078  * It will give up earlier than that if there is difficulty reclaiming pages.
6079  */
should_continue_reclaim(struct pglist_data * pgdat,unsigned long nr_reclaimed,struct scan_control * sc)6080 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
6081 					unsigned long nr_reclaimed,
6082 					struct scan_control *sc)
6083 {
6084 	unsigned long pages_for_compaction;
6085 	unsigned long inactive_lru_pages;
6086 	int z;
6087 
6088 	/* If not in reclaim/compaction mode, stop */
6089 	if (!in_reclaim_compaction(sc))
6090 		return false;
6091 
6092 	/*
6093 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6094 	 * number of pages that were scanned. This will return to the caller
6095 	 * with the risk reclaim/compaction and the resulting allocation attempt
6096 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6097 	 * allocations through requiring that the full LRU list has been scanned
6098 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6099 	 * scan, but that approximation was wrong, and there were corner cases
6100 	 * where always a non-zero amount of pages were scanned.
6101 	 */
6102 	if (!nr_reclaimed)
6103 		return false;
6104 
6105 	/* If compaction would go ahead or the allocation would succeed, stop */
6106 	for (z = 0; z <= sc->reclaim_idx; z++) {
6107 		struct zone *zone = &pgdat->node_zones[z];
6108 		if (!managed_zone(zone))
6109 			continue;
6110 
6111 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
6112 		case COMPACT_SUCCESS:
6113 		case COMPACT_CONTINUE:
6114 			return false;
6115 		default:
6116 			/* check next zone */
6117 			;
6118 		}
6119 	}
6120 
6121 	/*
6122 	 * If we have not reclaimed enough pages for compaction and the
6123 	 * inactive lists are large enough, continue reclaiming
6124 	 */
6125 	pages_for_compaction = compact_gap(sc->order);
6126 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
6127 	if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
6128 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6129 
6130 	return inactive_lru_pages > pages_for_compaction;
6131 }
6132 
shrink_node_memcgs(pg_data_t * pgdat,struct scan_control * sc)6133 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
6134 {
6135 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
6136 	struct mem_cgroup *memcg;
6137 
6138 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
6139 	do {
6140 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6141 		unsigned long reclaimed;
6142 		unsigned long scanned;
6143 		bool skip = false;
6144 
6145 		/*
6146 		 * This loop can become CPU-bound when target memcgs
6147 		 * aren't eligible for reclaim - either because they
6148 		 * don't have any reclaimable pages, or because their
6149 		 * memory is explicitly protected. Avoid soft lockups.
6150 		 */
6151 		cond_resched();
6152 
6153 		trace_android_vh_shrink_node_memcgs(memcg, &skip);
6154 		if (skip)
6155 			continue;
6156 
6157 		mem_cgroup_calculate_protection(target_memcg, memcg);
6158 
6159 		if (mem_cgroup_below_min(memcg)) {
6160 			/*
6161 			 * Hard protection.
6162 			 * If there is no reclaimable memory, OOM.
6163 			 */
6164 			continue;
6165 		} else if (mem_cgroup_below_low(memcg)) {
6166 			/*
6167 			 * Soft protection.
6168 			 * Respect the protection only as long as
6169 			 * there is an unprotected supply
6170 			 * of reclaimable memory from other cgroups.
6171 			 */
6172 			if (!sc->memcg_low_reclaim) {
6173 				sc->memcg_low_skipped = 1;
6174 				continue;
6175 			}
6176 			memcg_memory_event(memcg, MEMCG_LOW);
6177 		}
6178 
6179 		reclaimed = sc->nr_reclaimed;
6180 		scanned = sc->nr_scanned;
6181 
6182 		shrink_lruvec(lruvec, sc);
6183 
6184 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6185 			    sc->priority);
6186 
6187 		/* Record the group's reclaim efficiency */
6188 		if (!sc->proactive)
6189 			vmpressure(sc->gfp_mask, memcg, false,
6190 				   sc->nr_scanned - scanned,
6191 				   sc->nr_reclaimed - reclaimed);
6192 
6193 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6194 }
6195 
shrink_node(pg_data_t * pgdat,struct scan_control * sc)6196 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
6197 {
6198 	struct reclaim_state *reclaim_state = current->reclaim_state;
6199 	unsigned long nr_reclaimed, nr_scanned;
6200 	struct lruvec *target_lruvec;
6201 	bool reclaimable = false;
6202 
6203 	if (lru_gen_enabled() && global_reclaim(sc)) {
6204 		lru_gen_shrink_node(pgdat, sc);
6205 		return;
6206 	}
6207 
6208 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6209 
6210 again:
6211 	memset(&sc->nr, 0, sizeof(sc->nr));
6212 
6213 	nr_reclaimed = sc->nr_reclaimed;
6214 	nr_scanned = sc->nr_scanned;
6215 
6216 	prepare_scan_count(pgdat, sc);
6217 
6218 	shrink_node_memcgs(pgdat, sc);
6219 
6220 	if (reclaim_state) {
6221 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6222 		reclaim_state->reclaimed_slab = 0;
6223 	}
6224 
6225 	/* Record the subtree's reclaim efficiency */
6226 	if (!sc->proactive)
6227 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6228 			   sc->nr_scanned - nr_scanned,
6229 			   sc->nr_reclaimed - nr_reclaimed);
6230 
6231 	if (sc->nr_reclaimed - nr_reclaimed)
6232 		reclaimable = true;
6233 
6234 	if (current_is_kswapd()) {
6235 		/*
6236 		 * If reclaim is isolating dirty pages under writeback,
6237 		 * it implies that the long-lived page allocation rate
6238 		 * is exceeding the page laundering rate. Either the
6239 		 * global limits are not being effective at throttling
6240 		 * processes due to the page distribution throughout
6241 		 * zones or there is heavy usage of a slow backing
6242 		 * device. The only option is to throttle from reclaim
6243 		 * context which is not ideal as there is no guarantee
6244 		 * the dirtying process is throttled in the same way
6245 		 * balance_dirty_pages() manages.
6246 		 *
6247 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6248 		 * count the number of pages under pages flagged for
6249 		 * immediate reclaim and stall if any are encountered
6250 		 * in the nr_immediate check below.
6251 		 */
6252 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6253 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
6254 
6255 		/* Allow kswapd to start writing pages during reclaim.*/
6256 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6257 			set_bit(PGDAT_DIRTY, &pgdat->flags);
6258 
6259 		/*
6260 		 * If kswapd scans pages marked for immediate
6261 		 * reclaim and under writeback (nr_immediate), it
6262 		 * implies that pages are cycling through the LRU
6263 		 * faster than they are written so also forcibly stall.
6264 		 */
6265 		if (sc->nr.immediate)
6266 			congestion_wait(BLK_RW_ASYNC, HZ/10);
6267 	}
6268 
6269 	/*
6270 	 * Tag a node/memcg as congested if all the dirty pages
6271 	 * scanned were backed by a congested BDI and
6272 	 * wait_iff_congested will stall.
6273 	 *
6274 	 * Legacy memcg will stall in page writeback so avoid forcibly
6275 	 * stalling in wait_iff_congested().
6276 	 */
6277 	if ((current_is_kswapd() ||
6278 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
6279 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
6280 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
6281 
6282 	/*
6283 	 * Stall direct reclaim for IO completions if underlying BDIs
6284 	 * and node is congested. Allow kswapd to continue until it
6285 	 * starts encountering unqueued dirty pages or cycling through
6286 	 * the LRU too quickly.
6287 	 */
6288 	if (!current_is_kswapd() && current_may_throttle() &&
6289 	    !sc->hibernation_mode &&
6290 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
6291 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6292 
6293 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6294 				    sc))
6295 		goto again;
6296 
6297 	/*
6298 	 * Kswapd gives up on balancing particular nodes after too
6299 	 * many failures to reclaim anything from them and goes to
6300 	 * sleep. On reclaim progress, reset the failure counter. A
6301 	 * successful direct reclaim run will revive a dormant kswapd.
6302 	 */
6303 	if (reclaimable)
6304 		pgdat->kswapd_failures = 0;
6305 }
6306 
6307 /*
6308  * Returns true if compaction should go ahead for a costly-order request, or
6309  * the allocation would already succeed without compaction. Return false if we
6310  * should reclaim first.
6311  */
compaction_ready(struct zone * zone,struct scan_control * sc)6312 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6313 {
6314 	unsigned long watermark;
6315 	enum compact_result suitable;
6316 
6317 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6318 	if (suitable == COMPACT_SUCCESS)
6319 		/* Allocation should succeed already. Don't reclaim. */
6320 		return true;
6321 	if (suitable == COMPACT_SKIPPED)
6322 		/* Compaction cannot yet proceed. Do reclaim. */
6323 		return false;
6324 
6325 	/*
6326 	 * Compaction is already possible, but it takes time to run and there
6327 	 * are potentially other callers using the pages just freed. So proceed
6328 	 * with reclaim to make a buffer of free pages available to give
6329 	 * compaction a reasonable chance of completing and allocating the page.
6330 	 * Note that we won't actually reclaim the whole buffer in one attempt
6331 	 * as the target watermark in should_continue_reclaim() is lower. But if
6332 	 * we are already above the high+gap watermark, don't reclaim at all.
6333 	 */
6334 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6335 
6336 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6337 }
6338 
6339 /*
6340  * This is the direct reclaim path, for page-allocating processes.  We only
6341  * try to reclaim pages from zones which will satisfy the caller's allocation
6342  * request.
6343  *
6344  * If a zone is deemed to be full of pinned pages then just give it a light
6345  * scan then give up on it.
6346  */
shrink_zones(struct zonelist * zonelist,struct scan_control * sc)6347 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6348 {
6349 	struct zoneref *z;
6350 	struct zone *zone;
6351 	unsigned long nr_soft_reclaimed;
6352 	unsigned long nr_soft_scanned;
6353 	gfp_t orig_mask;
6354 	pg_data_t *last_pgdat = NULL;
6355 
6356 	/*
6357 	 * If the number of buffer_heads in the machine exceeds the maximum
6358 	 * allowed level, force direct reclaim to scan the highmem zone as
6359 	 * highmem pages could be pinning lowmem pages storing buffer_heads
6360 	 */
6361 	orig_mask = sc->gfp_mask;
6362 	if (buffer_heads_over_limit) {
6363 		sc->gfp_mask |= __GFP_HIGHMEM;
6364 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6365 	}
6366 
6367 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
6368 					sc->reclaim_idx, sc->nodemask) {
6369 		/*
6370 		 * Take care memory controller reclaiming has small influence
6371 		 * to global LRU.
6372 		 */
6373 		if (!cgroup_reclaim(sc)) {
6374 			if (!cpuset_zone_allowed(zone,
6375 						 GFP_KERNEL | __GFP_HARDWALL))
6376 				continue;
6377 
6378 			/*
6379 			 * If we already have plenty of memory free for
6380 			 * compaction in this zone, don't free any more.
6381 			 * Even though compaction is invoked for any
6382 			 * non-zero order, only frequent costly order
6383 			 * reclamation is disruptive enough to become a
6384 			 * noticeable problem, like transparent huge
6385 			 * page allocations.
6386 			 */
6387 			if (IS_ENABLED(CONFIG_COMPACTION) &&
6388 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6389 			    compaction_ready(zone, sc)) {
6390 				sc->compaction_ready = true;
6391 				continue;
6392 			}
6393 
6394 			/*
6395 			 * Shrink each node in the zonelist once. If the
6396 			 * zonelist is ordered by zone (not the default) then a
6397 			 * node may be shrunk multiple times but in that case
6398 			 * the user prefers lower zones being preserved.
6399 			 */
6400 			if (zone->zone_pgdat == last_pgdat)
6401 				continue;
6402 
6403 			/*
6404 			 * This steals pages from memory cgroups over softlimit
6405 			 * and returns the number of reclaimed pages and
6406 			 * scanned pages. This works for global memory pressure
6407 			 * and balancing, not for a memcg's limit.
6408 			 */
6409 			nr_soft_scanned = 0;
6410 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
6411 						sc->order, sc->gfp_mask,
6412 						&nr_soft_scanned);
6413 			sc->nr_reclaimed += nr_soft_reclaimed;
6414 			sc->nr_scanned += nr_soft_scanned;
6415 			/* need some check for avoid more shrink_zone() */
6416 		}
6417 
6418 		/* See comment about same check for global reclaim above */
6419 		if (zone->zone_pgdat == last_pgdat)
6420 			continue;
6421 		last_pgdat = zone->zone_pgdat;
6422 		shrink_node(zone->zone_pgdat, sc);
6423 	}
6424 
6425 	/*
6426 	 * Restore to original mask to avoid the impact on the caller if we
6427 	 * promoted it to __GFP_HIGHMEM.
6428 	 */
6429 	sc->gfp_mask = orig_mask;
6430 }
6431 
snapshot_refaults(struct mem_cgroup * target_memcg,pg_data_t * pgdat)6432 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6433 {
6434 	struct lruvec *target_lruvec;
6435 	unsigned long refaults;
6436 
6437 	if (lru_gen_enabled())
6438 		return;
6439 
6440 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6441 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6442 	target_lruvec->refaults[0] = refaults;
6443 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6444 	target_lruvec->refaults[1] = refaults;
6445 }
6446 
6447 /*
6448  * This is the main entry point to direct page reclaim.
6449  *
6450  * If a full scan of the inactive list fails to free enough memory then we
6451  * are "out of memory" and something needs to be killed.
6452  *
6453  * If the caller is !__GFP_FS then the probability of a failure is reasonably
6454  * high - the zone may be full of dirty or under-writeback pages, which this
6455  * caller can't do much about.  We kick the writeback threads and take explicit
6456  * naps in the hope that some of these pages can be written.  But if the
6457  * allocating task holds filesystem locks which prevent writeout this might not
6458  * work, and the allocation attempt will fail.
6459  *
6460  * returns:	0, if no pages reclaimed
6461  * 		else, the number of pages reclaimed
6462  */
do_try_to_free_pages(struct zonelist * zonelist,struct scan_control * sc)6463 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6464 					  struct scan_control *sc)
6465 {
6466 	int initial_priority = sc->priority;
6467 	pg_data_t *last_pgdat;
6468 	struct zoneref *z;
6469 	struct zone *zone;
6470 retry:
6471 	delayacct_freepages_start();
6472 
6473 	if (!cgroup_reclaim(sc))
6474 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6475 
6476 	do {
6477 		if (!sc->proactive)
6478 			vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6479 					sc->priority);
6480 		sc->nr_scanned = 0;
6481 		shrink_zones(zonelist, sc);
6482 
6483 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6484 			break;
6485 
6486 		if (sc->compaction_ready)
6487 			break;
6488 
6489 		/*
6490 		 * If we're getting trouble reclaiming, start doing
6491 		 * writepage even in laptop mode.
6492 		 */
6493 		if (sc->priority < DEF_PRIORITY - 2)
6494 			sc->may_writepage = 1;
6495 	} while (--sc->priority >= 0);
6496 
6497 	last_pgdat = NULL;
6498 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6499 					sc->nodemask) {
6500 		if (zone->zone_pgdat == last_pgdat)
6501 			continue;
6502 		last_pgdat = zone->zone_pgdat;
6503 
6504 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6505 
6506 		if (cgroup_reclaim(sc)) {
6507 			struct lruvec *lruvec;
6508 
6509 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6510 						   zone->zone_pgdat);
6511 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6512 		}
6513 	}
6514 
6515 	delayacct_freepages_end();
6516 
6517 	if (sc->nr_reclaimed)
6518 		return sc->nr_reclaimed;
6519 
6520 	/* Aborted reclaim to try compaction? don't OOM, then */
6521 	if (sc->compaction_ready)
6522 		return 1;
6523 
6524 	/*
6525 	 * We make inactive:active ratio decisions based on the node's
6526 	 * composition of memory, but a restrictive reclaim_idx or a
6527 	 * memory.low cgroup setting can exempt large amounts of
6528 	 * memory from reclaim. Neither of which are very common, so
6529 	 * instead of doing costly eligibility calculations of the
6530 	 * entire cgroup subtree up front, we assume the estimates are
6531 	 * good, and retry with forcible deactivation if that fails.
6532 	 */
6533 	if (sc->skipped_deactivate) {
6534 		sc->priority = initial_priority;
6535 		sc->force_deactivate = 1;
6536 		sc->skipped_deactivate = 0;
6537 		goto retry;
6538 	}
6539 
6540 	/* Untapped cgroup reserves?  Don't OOM, retry. */
6541 	if (sc->memcg_low_skipped) {
6542 		sc->priority = initial_priority;
6543 		sc->force_deactivate = 0;
6544 		sc->memcg_low_reclaim = 1;
6545 		sc->memcg_low_skipped = 0;
6546 		goto retry;
6547 	}
6548 
6549 	return 0;
6550 }
6551 
allow_direct_reclaim(pg_data_t * pgdat)6552 static bool allow_direct_reclaim(pg_data_t *pgdat)
6553 {
6554 	struct zone *zone;
6555 	unsigned long pfmemalloc_reserve = 0;
6556 	unsigned long free_pages = 0;
6557 	int i;
6558 	bool wmark_ok;
6559 
6560 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6561 		return true;
6562 
6563 	for (i = 0; i <= ZONE_NORMAL; i++) {
6564 		zone = &pgdat->node_zones[i];
6565 		if (!managed_zone(zone))
6566 			continue;
6567 
6568 		if (!zone_reclaimable_pages(zone))
6569 			continue;
6570 
6571 		pfmemalloc_reserve += min_wmark_pages(zone);
6572 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
6573 	}
6574 
6575 	/* If there are no reserves (unexpected config) then do not throttle */
6576 	if (!pfmemalloc_reserve)
6577 		return true;
6578 
6579 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
6580 
6581 	/* kswapd must be awake if processes are being throttled */
6582 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6583 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6584 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6585 
6586 		wake_up_interruptible(&pgdat->kswapd_wait);
6587 	}
6588 
6589 	return wmark_ok;
6590 }
6591 
6592 /*
6593  * Throttle direct reclaimers if backing storage is backed by the network
6594  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6595  * depleted. kswapd will continue to make progress and wake the processes
6596  * when the low watermark is reached.
6597  *
6598  * Returns true if a fatal signal was delivered during throttling. If this
6599  * happens, the page allocator should not consider triggering the OOM killer.
6600  */
throttle_direct_reclaim(gfp_t gfp_mask,struct zonelist * zonelist,nodemask_t * nodemask)6601 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6602 					nodemask_t *nodemask)
6603 {
6604 	struct zoneref *z;
6605 	struct zone *zone;
6606 	pg_data_t *pgdat = NULL;
6607 
6608 	/*
6609 	 * Kernel threads should not be throttled as they may be indirectly
6610 	 * responsible for cleaning pages necessary for reclaim to make forward
6611 	 * progress. kjournald for example may enter direct reclaim while
6612 	 * committing a transaction where throttling it could forcing other
6613 	 * processes to block on log_wait_commit().
6614 	 */
6615 	if (current->flags & PF_KTHREAD)
6616 		goto out;
6617 
6618 	/*
6619 	 * If a fatal signal is pending, this process should not throttle.
6620 	 * It should return quickly so it can exit and free its memory
6621 	 */
6622 	if (fatal_signal_pending(current))
6623 		goto out;
6624 
6625 	/*
6626 	 * Check if the pfmemalloc reserves are ok by finding the first node
6627 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6628 	 * GFP_KERNEL will be required for allocating network buffers when
6629 	 * swapping over the network so ZONE_HIGHMEM is unusable.
6630 	 *
6631 	 * Throttling is based on the first usable node and throttled processes
6632 	 * wait on a queue until kswapd makes progress and wakes them. There
6633 	 * is an affinity then between processes waking up and where reclaim
6634 	 * progress has been made assuming the process wakes on the same node.
6635 	 * More importantly, processes running on remote nodes will not compete
6636 	 * for remote pfmemalloc reserves and processes on different nodes
6637 	 * should make reasonable progress.
6638 	 */
6639 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
6640 					gfp_zone(gfp_mask), nodemask) {
6641 		if (zone_idx(zone) > ZONE_NORMAL)
6642 			continue;
6643 
6644 		/* Throttle based on the first usable node */
6645 		pgdat = zone->zone_pgdat;
6646 		if (allow_direct_reclaim(pgdat))
6647 			goto out;
6648 		break;
6649 	}
6650 
6651 	/* If no zone was usable by the allocation flags then do not throttle */
6652 	if (!pgdat)
6653 		goto out;
6654 
6655 	/* Account for the throttling */
6656 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
6657 
6658 	/*
6659 	 * If the caller cannot enter the filesystem, it's possible that it
6660 	 * is due to the caller holding an FS lock or performing a journal
6661 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
6662 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
6663 	 * blocked waiting on the same lock. Instead, throttle for up to a
6664 	 * second before continuing.
6665 	 */
6666 	if (!(gfp_mask & __GFP_FS))
6667 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6668 			allow_direct_reclaim(pgdat), HZ);
6669 	else
6670 		/* Throttle until kswapd wakes the process */
6671 		wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6672 			allow_direct_reclaim(pgdat));
6673 
6674 	if (fatal_signal_pending(current))
6675 		return true;
6676 
6677 out:
6678 	return false;
6679 }
6680 
try_to_free_pages(struct zonelist * zonelist,int order,gfp_t gfp_mask,nodemask_t * nodemask)6681 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6682 				gfp_t gfp_mask, nodemask_t *nodemask)
6683 {
6684 	unsigned long nr_reclaimed;
6685 	struct scan_control sc = {
6686 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
6687 		.gfp_mask = current_gfp_context(gfp_mask),
6688 		.reclaim_idx = gfp_zone(gfp_mask),
6689 		.order = order,
6690 		.nodemask = nodemask,
6691 		.priority = DEF_PRIORITY,
6692 		.may_writepage = !laptop_mode,
6693 		.may_unmap = 1,
6694 		.may_swap = 1,
6695 	};
6696 
6697 	/*
6698 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6699 	 * Confirm they are large enough for max values.
6700 	 */
6701 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6702 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6703 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6704 
6705 	/*
6706 	 * Do not enter reclaim if fatal signal was delivered while throttled.
6707 	 * 1 is returned so that the page allocator does not OOM kill at this
6708 	 * point.
6709 	 */
6710 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6711 		return 1;
6712 
6713 	set_task_reclaim_state(current, &sc.reclaim_state);
6714 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6715 
6716 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6717 
6718 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6719 	set_task_reclaim_state(current, NULL);
6720 
6721 	return nr_reclaimed;
6722 }
6723 
6724 #ifdef CONFIG_MEMCG
6725 
6726 /* Only used by soft limit reclaim. Do not reuse for anything else. */
mem_cgroup_shrink_node(struct mem_cgroup * memcg,gfp_t gfp_mask,bool noswap,pg_data_t * pgdat,unsigned long * nr_scanned)6727 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6728 						gfp_t gfp_mask, bool noswap,
6729 						pg_data_t *pgdat,
6730 						unsigned long *nr_scanned)
6731 {
6732 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6733 	struct scan_control sc = {
6734 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
6735 		.target_mem_cgroup = memcg,
6736 		.may_writepage = !laptop_mode,
6737 		.may_unmap = 1,
6738 		.reclaim_idx = MAX_NR_ZONES - 1,
6739 		.may_swap = !noswap,
6740 	};
6741 
6742 	WARN_ON_ONCE(!current->reclaim_state);
6743 
6744 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6745 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6746 
6747 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6748 						      sc.gfp_mask);
6749 
6750 	/*
6751 	 * NOTE: Although we can get the priority field, using it
6752 	 * here is not a good idea, since it limits the pages we can scan.
6753 	 * if we don't reclaim here, the shrink_node from balance_pgdat
6754 	 * will pick up pages from other mem cgroup's as well. We hack
6755 	 * the priority and make it zero.
6756 	 */
6757 	shrink_lruvec(lruvec, &sc);
6758 
6759 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6760 
6761 	*nr_scanned = sc.nr_scanned;
6762 
6763 	return sc.nr_reclaimed;
6764 }
6765 
try_to_free_mem_cgroup_pages(struct mem_cgroup * memcg,unsigned long nr_pages,gfp_t gfp_mask,unsigned int reclaim_options)6766 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6767 					   unsigned long nr_pages,
6768 					   gfp_t gfp_mask,
6769 					   unsigned int reclaim_options)
6770 {
6771 	unsigned long nr_reclaimed;
6772 	unsigned int noreclaim_flag;
6773 	struct scan_control sc = {
6774 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6775 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6776 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6777 		.reclaim_idx = MAX_NR_ZONES - 1,
6778 		.target_mem_cgroup = memcg,
6779 		.priority = DEF_PRIORITY,
6780 		.may_writepage = !laptop_mode,
6781 		.may_unmap = 1,
6782 		.may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6783 		.proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
6784 	};
6785 	/*
6786 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6787 	 * equal pressure on all the nodes. This is based on the assumption that
6788 	 * the reclaim does not bail out early.
6789 	 */
6790 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6791 
6792 	set_task_reclaim_state(current, &sc.reclaim_state);
6793 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6794 	noreclaim_flag = memalloc_noreclaim_save();
6795 
6796 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6797 
6798 	memalloc_noreclaim_restore(noreclaim_flag);
6799 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6800 	set_task_reclaim_state(current, NULL);
6801 
6802 	return nr_reclaimed;
6803 }
6804 EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
6805 #endif
6806 
kswapd_age_node(struct pglist_data * pgdat,struct scan_control * sc)6807 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6808 {
6809 	struct mem_cgroup *memcg;
6810 	struct lruvec *lruvec;
6811 
6812 	if (lru_gen_enabled()) {
6813 		lru_gen_age_node(pgdat, sc);
6814 		return;
6815 	}
6816 
6817 	if (!can_age_anon_pages(pgdat, sc))
6818 		return;
6819 
6820 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
6821 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6822 		return;
6823 
6824 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
6825 	do {
6826 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
6827 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6828 				   sc, LRU_ACTIVE_ANON);
6829 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
6830 	} while (memcg);
6831 }
6832 
pgdat_watermark_boosted(pg_data_t * pgdat,int highest_zoneidx)6833 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
6834 {
6835 	int i;
6836 	struct zone *zone;
6837 
6838 	/*
6839 	 * Check for watermark boosts top-down as the higher zones
6840 	 * are more likely to be boosted. Both watermarks and boosts
6841 	 * should not be checked at the same time as reclaim would
6842 	 * start prematurely when there is no boosting and a lower
6843 	 * zone is balanced.
6844 	 */
6845 	for (i = highest_zoneidx; i >= 0; i--) {
6846 		zone = pgdat->node_zones + i;
6847 		if (!managed_zone(zone))
6848 			continue;
6849 
6850 		if (zone->watermark_boost)
6851 			return true;
6852 	}
6853 
6854 	return false;
6855 }
6856 
6857 /*
6858  * Returns true if there is an eligible zone balanced for the request order
6859  * and highest_zoneidx
6860  */
pgdat_balanced(pg_data_t * pgdat,int order,int highest_zoneidx)6861 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
6862 {
6863 	int i;
6864 	unsigned long mark = -1;
6865 	struct zone *zone;
6866 
6867 	/*
6868 	 * Check watermarks bottom-up as lower zones are more likely to
6869 	 * meet watermarks.
6870 	 */
6871 	for (i = 0; i <= highest_zoneidx; i++) {
6872 		zone = pgdat->node_zones + i;
6873 
6874 		if (!managed_zone(zone))
6875 			continue;
6876 
6877 		mark = high_wmark_pages(zone);
6878 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
6879 			return true;
6880 	}
6881 
6882 	/*
6883 	 * If a node has no populated zone within highest_zoneidx, it does not
6884 	 * need balancing by definition. This can happen if a zone-restricted
6885 	 * allocation tries to wake a remote kswapd.
6886 	 */
6887 	if (mark == -1)
6888 		return true;
6889 
6890 	return false;
6891 }
6892 
6893 /* Clear pgdat state for congested, dirty or under writeback. */
clear_pgdat_congested(pg_data_t * pgdat)6894 static void clear_pgdat_congested(pg_data_t *pgdat)
6895 {
6896 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6897 
6898 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6899 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
6900 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6901 }
6902 
6903 /*
6904  * Prepare kswapd for sleeping. This verifies that there are no processes
6905  * waiting in throttle_direct_reclaim() and that watermarks have been met.
6906  *
6907  * Returns true if kswapd is ready to sleep
6908  */
prepare_kswapd_sleep(pg_data_t * pgdat,int order,int highest_zoneidx)6909 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6910 				int highest_zoneidx)
6911 {
6912 	/*
6913 	 * The throttled processes are normally woken up in balance_pgdat() as
6914 	 * soon as allow_direct_reclaim() is true. But there is a potential
6915 	 * race between when kswapd checks the watermarks and a process gets
6916 	 * throttled. There is also a potential race if processes get
6917 	 * throttled, kswapd wakes, a large process exits thereby balancing the
6918 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
6919 	 * the wake up checks. If kswapd is going to sleep, no process should
6920 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6921 	 * the wake up is premature, processes will wake kswapd and get
6922 	 * throttled again. The difference from wake ups in balance_pgdat() is
6923 	 * that here we are under prepare_to_wait().
6924 	 */
6925 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
6926 		wake_up_all(&pgdat->pfmemalloc_wait);
6927 
6928 	/* Hopeless node, leave it to direct reclaim */
6929 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6930 		return true;
6931 
6932 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
6933 		clear_pgdat_congested(pgdat);
6934 		return true;
6935 	}
6936 
6937 	return false;
6938 }
6939 
6940 /*
6941  * kswapd shrinks a node of pages that are at or below the highest usable
6942  * zone that is currently unbalanced.
6943  *
6944  * Returns true if kswapd scanned at least the requested number of pages to
6945  * reclaim or if the lack of progress was due to pages under writeback.
6946  * This is used to determine if the scanning priority needs to be raised.
6947  */
kswapd_shrink_node(pg_data_t * pgdat,struct scan_control * sc)6948 static bool kswapd_shrink_node(pg_data_t *pgdat,
6949 			       struct scan_control *sc)
6950 {
6951 	struct zone *zone;
6952 	int z;
6953 
6954 	/* Reclaim a number of pages proportional to the number of zones */
6955 	sc->nr_to_reclaim = 0;
6956 	for (z = 0; z <= sc->reclaim_idx; z++) {
6957 		zone = pgdat->node_zones + z;
6958 		if (!managed_zone(zone))
6959 			continue;
6960 
6961 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6962 	}
6963 
6964 	/*
6965 	 * Historically care was taken to put equal pressure on all zones but
6966 	 * now pressure is applied based on node LRU order.
6967 	 */
6968 	shrink_node(pgdat, sc);
6969 
6970 	/*
6971 	 * Fragmentation may mean that the system cannot be rebalanced for
6972 	 * high-order allocations. If twice the allocation size has been
6973 	 * reclaimed then recheck watermarks only at order-0 to prevent
6974 	 * excessive reclaim. Assume that a process requested a high-order
6975 	 * can direct reclaim/compact.
6976 	 */
6977 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6978 		sc->order = 0;
6979 
6980 	return sc->nr_scanned >= sc->nr_to_reclaim;
6981 }
6982 
6983 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6984 static inline void
update_reclaim_active(pg_data_t * pgdat,int highest_zoneidx,bool active)6985 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6986 {
6987 	int i;
6988 	struct zone *zone;
6989 
6990 	for (i = 0; i <= highest_zoneidx; i++) {
6991 		zone = pgdat->node_zones + i;
6992 
6993 		if (!managed_zone(zone))
6994 			continue;
6995 
6996 		if (active)
6997 			set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6998 		else
6999 			clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7000 	}
7001 }
7002 
7003 static inline void
set_reclaim_active(pg_data_t * pgdat,int highest_zoneidx)7004 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7005 {
7006 	update_reclaim_active(pgdat, highest_zoneidx, true);
7007 }
7008 
7009 static inline void
clear_reclaim_active(pg_data_t * pgdat,int highest_zoneidx)7010 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7011 {
7012 	update_reclaim_active(pgdat, highest_zoneidx, false);
7013 }
7014 
7015 /*
7016  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7017  * that are eligible for use by the caller until at least one zone is
7018  * balanced.
7019  *
7020  * Returns the order kswapd finished reclaiming at.
7021  *
7022  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
7023  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
7024  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
7025  * or lower is eligible for reclaim until at least one usable zone is
7026  * balanced.
7027  */
balance_pgdat(pg_data_t * pgdat,int order,int highest_zoneidx)7028 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
7029 {
7030 	int i;
7031 	unsigned long nr_soft_reclaimed;
7032 	unsigned long nr_soft_scanned;
7033 	unsigned long pflags;
7034 	unsigned long nr_boost_reclaim;
7035 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7036 	bool boosted;
7037 	struct zone *zone;
7038 	struct scan_control sc = {
7039 		.gfp_mask = GFP_KERNEL,
7040 		.order = order,
7041 		.may_unmap = 1,
7042 	};
7043 
7044 	set_task_reclaim_state(current, &sc.reclaim_state);
7045 	psi_memstall_enter(&pflags);
7046 	__fs_reclaim_acquire(_THIS_IP_);
7047 
7048 	count_vm_event(PAGEOUTRUN);
7049 
7050 	/*
7051 	 * Account for the reclaim boost. Note that the zone boost is left in
7052 	 * place so that parallel allocations that are near the watermark will
7053 	 * stall or direct reclaim until kswapd is finished.
7054 	 */
7055 	nr_boost_reclaim = 0;
7056 	for (i = 0; i <= highest_zoneidx; i++) {
7057 		zone = pgdat->node_zones + i;
7058 		if (!managed_zone(zone))
7059 			continue;
7060 
7061 		nr_boost_reclaim += zone->watermark_boost;
7062 		zone_boosts[i] = zone->watermark_boost;
7063 	}
7064 	boosted = nr_boost_reclaim;
7065 
7066 restart:
7067 	set_reclaim_active(pgdat, highest_zoneidx);
7068 	sc.priority = DEF_PRIORITY;
7069 	do {
7070 		unsigned long nr_reclaimed = sc.nr_reclaimed;
7071 		bool raise_priority = true;
7072 		bool balanced;
7073 		bool ret;
7074 
7075 		sc.reclaim_idx = highest_zoneidx;
7076 
7077 		/*
7078 		 * If the number of buffer_heads exceeds the maximum allowed
7079 		 * then consider reclaiming from all zones. This has a dual
7080 		 * purpose -- on 64-bit systems it is expected that
7081 		 * buffer_heads are stripped during active rotation. On 32-bit
7082 		 * systems, highmem pages can pin lowmem memory and shrinking
7083 		 * buffers can relieve lowmem pressure. Reclaim may still not
7084 		 * go ahead if all eligible zones for the original allocation
7085 		 * request are balanced to avoid excessive reclaim from kswapd.
7086 		 */
7087 		if (buffer_heads_over_limit) {
7088 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7089 				zone = pgdat->node_zones + i;
7090 				if (!managed_zone(zone))
7091 					continue;
7092 
7093 				sc.reclaim_idx = i;
7094 				break;
7095 			}
7096 		}
7097 
7098 		/*
7099 		 * If the pgdat is imbalanced then ignore boosting and preserve
7100 		 * the watermarks for a later time and restart. Note that the
7101 		 * zone watermarks will be still reset at the end of balancing
7102 		 * on the grounds that the normal reclaim should be enough to
7103 		 * re-evaluate if boosting is required when kswapd next wakes.
7104 		 */
7105 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
7106 		if (!balanced && nr_boost_reclaim) {
7107 			nr_boost_reclaim = 0;
7108 			goto restart;
7109 		}
7110 
7111 		/*
7112 		 * If boosting is not active then only reclaim if there are no
7113 		 * eligible zones. Note that sc.reclaim_idx is not used as
7114 		 * buffer_heads_over_limit may have adjusted it.
7115 		 */
7116 		if (!nr_boost_reclaim && balanced)
7117 			goto out;
7118 
7119 		/* Limit the priority of boosting to avoid reclaim writeback */
7120 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7121 			raise_priority = false;
7122 
7123 		/*
7124 		 * Do not writeback or swap pages for boosted reclaim. The
7125 		 * intent is to relieve pressure not issue sub-optimal IO
7126 		 * from reclaim context. If no pages are reclaimed, the
7127 		 * reclaim will be aborted.
7128 		 */
7129 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7130 		sc.may_swap = !nr_boost_reclaim;
7131 
7132 		/*
7133 		 * Do some background aging, to give pages a chance to be
7134 		 * referenced before reclaiming. All pages are rotated
7135 		 * regardless of classzone as this is about consistent aging.
7136 		 */
7137 		kswapd_age_node(pgdat, &sc);
7138 
7139 		/*
7140 		 * If we're getting trouble reclaiming, start doing writepage
7141 		 * even in laptop mode.
7142 		 */
7143 		if (sc.priority < DEF_PRIORITY - 2)
7144 			sc.may_writepage = 1;
7145 
7146 		/* Call soft limit reclaim before calling shrink_node. */
7147 		sc.nr_scanned = 0;
7148 		nr_soft_scanned = 0;
7149 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
7150 						sc.gfp_mask, &nr_soft_scanned);
7151 		sc.nr_reclaimed += nr_soft_reclaimed;
7152 
7153 		/*
7154 		 * There should be no need to raise the scanning priority if
7155 		 * enough pages are already being scanned that that high
7156 		 * watermark would be met at 100% efficiency.
7157 		 */
7158 		if (kswapd_shrink_node(pgdat, &sc))
7159 			raise_priority = false;
7160 
7161 		/*
7162 		 * If the low watermark is met there is no need for processes
7163 		 * to be throttled on pfmemalloc_wait as they should not be
7164 		 * able to safely make forward progress. Wake them
7165 		 */
7166 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
7167 				allow_direct_reclaim(pgdat))
7168 			wake_up_all(&pgdat->pfmemalloc_wait);
7169 
7170 		/* Check if kswapd should be suspending */
7171 		__fs_reclaim_release(_THIS_IP_);
7172 		ret = try_to_freeze();
7173 		__fs_reclaim_acquire(_THIS_IP_);
7174 		if (ret || kthread_should_stop())
7175 			break;
7176 
7177 		/*
7178 		 * Raise priority if scanning rate is too low or there was no
7179 		 * progress in reclaiming pages
7180 		 */
7181 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
7182 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7183 
7184 		/*
7185 		 * If reclaim made no progress for a boost, stop reclaim as
7186 		 * IO cannot be queued and it could be an infinite loop in
7187 		 * extreme circumstances.
7188 		 */
7189 		if (nr_boost_reclaim && !nr_reclaimed)
7190 			break;
7191 
7192 		if (raise_priority || !nr_reclaimed)
7193 			sc.priority--;
7194 	} while (sc.priority >= 1);
7195 
7196 	if (!sc.nr_reclaimed)
7197 		pgdat->kswapd_failures++;
7198 
7199 out:
7200 	clear_reclaim_active(pgdat, highest_zoneidx);
7201 
7202 	/* If reclaim was boosted, account for the reclaim done in this pass */
7203 	if (boosted) {
7204 		unsigned long flags;
7205 
7206 		for (i = 0; i <= highest_zoneidx; i++) {
7207 			if (!zone_boosts[i])
7208 				continue;
7209 
7210 			/* Increments are under the zone lock */
7211 			zone = pgdat->node_zones + i;
7212 			spin_lock_irqsave(&zone->lock, flags);
7213 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7214 			spin_unlock_irqrestore(&zone->lock, flags);
7215 		}
7216 
7217 		/*
7218 		 * As there is now likely space, wakeup kcompact to defragment
7219 		 * pageblocks.
7220 		 */
7221 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7222 	}
7223 
7224 	snapshot_refaults(NULL, pgdat);
7225 	__fs_reclaim_release(_THIS_IP_);
7226 	psi_memstall_leave(&pflags);
7227 	set_task_reclaim_state(current, NULL);
7228 
7229 	/*
7230 	 * Return the order kswapd stopped reclaiming at as
7231 	 * prepare_kswapd_sleep() takes it into account. If another caller
7232 	 * entered the allocator slow path while kswapd was awake, order will
7233 	 * remain at the higher level.
7234 	 */
7235 	return sc.order;
7236 }
7237 
7238 /*
7239  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7240  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7241  * not a valid index then either kswapd runs for first time or kswapd couldn't
7242  * sleep after previous reclaim attempt (node is still unbalanced). In that
7243  * case return the zone index of the previous kswapd reclaim cycle.
7244  */
kswapd_highest_zoneidx(pg_data_t * pgdat,enum zone_type prev_highest_zoneidx)7245 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7246 					   enum zone_type prev_highest_zoneidx)
7247 {
7248 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7249 
7250 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7251 }
7252 
kswapd_try_to_sleep(pg_data_t * pgdat,int alloc_order,int reclaim_order,unsigned int highest_zoneidx)7253 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7254 				unsigned int highest_zoneidx)
7255 {
7256 	long remaining = 0;
7257 	DEFINE_WAIT(wait);
7258 
7259 	if (freezing(current) || kthread_should_stop())
7260 		return;
7261 
7262 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7263 
7264 	/*
7265 	 * Try to sleep for a short interval. Note that kcompactd will only be
7266 	 * woken if it is possible to sleep for a short interval. This is
7267 	 * deliberate on the assumption that if reclaim cannot keep an
7268 	 * eligible zone balanced that it's also unlikely that compaction will
7269 	 * succeed.
7270 	 */
7271 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7272 		/*
7273 		 * Compaction records what page blocks it recently failed to
7274 		 * isolate pages from and skips them in the future scanning.
7275 		 * When kswapd is going to sleep, it is reasonable to assume
7276 		 * that pages and compaction may succeed so reset the cache.
7277 		 */
7278 		reset_isolation_suitable(pgdat);
7279 
7280 		/*
7281 		 * We have freed the memory, now we should compact it to make
7282 		 * allocation of the requested order possible.
7283 		 */
7284 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7285 
7286 		remaining = schedule_timeout(HZ/10);
7287 
7288 		/*
7289 		 * If woken prematurely then reset kswapd_highest_zoneidx and
7290 		 * order. The values will either be from a wakeup request or
7291 		 * the previous request that slept prematurely.
7292 		 */
7293 		if (remaining) {
7294 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7295 					kswapd_highest_zoneidx(pgdat,
7296 							highest_zoneidx));
7297 
7298 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7299 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7300 		}
7301 
7302 		finish_wait(&pgdat->kswapd_wait, &wait);
7303 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7304 	}
7305 
7306 	/*
7307 	 * After a short sleep, check if it was a premature sleep. If not, then
7308 	 * go fully to sleep until explicitly woken up.
7309 	 */
7310 	if (!remaining &&
7311 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7312 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7313 
7314 		/*
7315 		 * vmstat counters are not perfectly accurate and the estimated
7316 		 * value for counters such as NR_FREE_PAGES can deviate from the
7317 		 * true value by nr_online_cpus * threshold. To avoid the zone
7318 		 * watermarks being breached while under pressure, we reduce the
7319 		 * per-cpu vmstat threshold while kswapd is awake and restore
7320 		 * them before going back to sleep.
7321 		 */
7322 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7323 
7324 		if (!kthread_should_stop())
7325 			schedule();
7326 
7327 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7328 	} else {
7329 		if (remaining)
7330 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7331 		else
7332 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7333 	}
7334 	finish_wait(&pgdat->kswapd_wait, &wait);
7335 }
7336 
7337 /*
7338  * The background pageout daemon, started as a kernel thread
7339  * from the init process.
7340  *
7341  * This basically trickles out pages so that we have _some_
7342  * free memory available even if there is no other activity
7343  * that frees anything up. This is needed for things like routing
7344  * etc, where we otherwise might have all activity going on in
7345  * asynchronous contexts that cannot page things out.
7346  *
7347  * If there are applications that are active memory-allocators
7348  * (most normal use), this basically shouldn't matter.
7349  */
kswapd(void * p)7350 int kswapd(void *p)
7351 {
7352 	unsigned int alloc_order, reclaim_order;
7353 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7354 	pg_data_t *pgdat = (pg_data_t *)p;
7355 	struct task_struct *tsk = current;
7356 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7357 
7358 	if (!cpumask_empty(cpumask))
7359 		set_cpus_allowed_ptr(tsk, cpumask);
7360 
7361 	/*
7362 	 * Tell the memory management that we're a "memory allocator",
7363 	 * and that if we need more memory we should get access to it
7364 	 * regardless (see "__alloc_pages()"). "kswapd" should
7365 	 * never get caught in the normal page freeing logic.
7366 	 *
7367 	 * (Kswapd normally doesn't need memory anyway, but sometimes
7368 	 * you need a small amount of memory in order to be able to
7369 	 * page out something else, and this flag essentially protects
7370 	 * us from recursively trying to free more memory as we're
7371 	 * trying to free the first piece of memory in the first place).
7372 	 */
7373 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
7374 	set_freezable();
7375 
7376 	WRITE_ONCE(pgdat->kswapd_order, 0);
7377 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7378 	for ( ; ; ) {
7379 		bool ret;
7380 
7381 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7382 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7383 							highest_zoneidx);
7384 
7385 kswapd_try_sleep:
7386 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7387 					highest_zoneidx);
7388 
7389 		/* Read the new order and highest_zoneidx */
7390 		alloc_order = READ_ONCE(pgdat->kswapd_order);
7391 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7392 							highest_zoneidx);
7393 		WRITE_ONCE(pgdat->kswapd_order, 0);
7394 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7395 
7396 		ret = try_to_freeze();
7397 		if (kthread_should_stop())
7398 			break;
7399 
7400 		/*
7401 		 * We can speed up thawing tasks if we don't call balance_pgdat
7402 		 * after returning from the refrigerator
7403 		 */
7404 		if (ret)
7405 			continue;
7406 
7407 		/*
7408 		 * Reclaim begins at the requested order but if a high-order
7409 		 * reclaim fails then kswapd falls back to reclaiming for
7410 		 * order-0. If that happens, kswapd will consider sleeping
7411 		 * for the order it finished reclaiming at (reclaim_order)
7412 		 * but kcompactd is woken to compact for the original
7413 		 * request (alloc_order).
7414 		 */
7415 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7416 						alloc_order);
7417 		reclaim_order = balance_pgdat(pgdat, alloc_order,
7418 						highest_zoneidx);
7419 		if (reclaim_order < alloc_order)
7420 			goto kswapd_try_sleep;
7421 	}
7422 
7423 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
7424 
7425 	return 0;
7426 }
7427 EXPORT_SYMBOL_GPL(kswapd);
7428 
7429 /*
7430  * A zone is low on free memory or too fragmented for high-order memory.  If
7431  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7432  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
7433  * has failed or is not needed, still wake up kcompactd if only compaction is
7434  * needed.
7435  */
wakeup_kswapd(struct zone * zone,gfp_t gfp_flags,int order,enum zone_type highest_zoneidx)7436 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7437 		   enum zone_type highest_zoneidx)
7438 {
7439 	pg_data_t *pgdat;
7440 	enum zone_type curr_idx;
7441 
7442 	if (!managed_zone(zone))
7443 		return;
7444 
7445 	if (!cpuset_zone_allowed(zone, gfp_flags))
7446 		return;
7447 
7448 	pgdat = zone->zone_pgdat;
7449 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7450 
7451 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7452 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7453 
7454 	if (READ_ONCE(pgdat->kswapd_order) < order)
7455 		WRITE_ONCE(pgdat->kswapd_order, order);
7456 
7457 	if (!waitqueue_active(&pgdat->kswapd_wait))
7458 		return;
7459 
7460 	/* Hopeless node, leave it to direct reclaim if possible */
7461 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7462 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7463 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7464 		/*
7465 		 * There may be plenty of free memory available, but it's too
7466 		 * fragmented for high-order allocations.  Wake up kcompactd
7467 		 * and rely on compaction_suitable() to determine if it's
7468 		 * needed.  If it fails, it will defer subsequent attempts to
7469 		 * ratelimit its work.
7470 		 */
7471 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7472 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
7473 		return;
7474 	}
7475 
7476 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7477 				      gfp_flags);
7478 	wake_up_interruptible(&pgdat->kswapd_wait);
7479 }
7480 
7481 #ifdef CONFIG_HIBERNATION
7482 /*
7483  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7484  * freed pages.
7485  *
7486  * Rather than trying to age LRUs the aim is to preserve the overall
7487  * LRU order by reclaiming preferentially
7488  * inactive > active > active referenced > active mapped
7489  */
shrink_all_memory(unsigned long nr_to_reclaim)7490 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7491 {
7492 	struct scan_control sc = {
7493 		.nr_to_reclaim = nr_to_reclaim,
7494 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
7495 		.reclaim_idx = MAX_NR_ZONES - 1,
7496 		.priority = DEF_PRIORITY,
7497 		.may_writepage = 1,
7498 		.may_unmap = 1,
7499 		.may_swap = 1,
7500 		.hibernation_mode = 1,
7501 	};
7502 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7503 	unsigned long nr_reclaimed;
7504 	unsigned int noreclaim_flag;
7505 
7506 	fs_reclaim_acquire(sc.gfp_mask);
7507 	noreclaim_flag = memalloc_noreclaim_save();
7508 	set_task_reclaim_state(current, &sc.reclaim_state);
7509 
7510 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7511 
7512 	set_task_reclaim_state(current, NULL);
7513 	memalloc_noreclaim_restore(noreclaim_flag);
7514 	fs_reclaim_release(sc.gfp_mask);
7515 
7516 	return nr_reclaimed;
7517 }
7518 #endif /* CONFIG_HIBERNATION */
7519 
7520 /*
7521  * This kswapd start function will be called by init and node-hot-add.
7522  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7523  */
kswapd_run(int nid)7524 void kswapd_run(int nid)
7525 {
7526 	pg_data_t *pgdat = NODE_DATA(nid);
7527 	bool skip = false;
7528 
7529 	if (pgdat->kswapd)
7530 		return;
7531 
7532 	trace_android_vh_kswapd_per_node(nid, &skip, true);
7533 	if (skip)
7534 		return;
7535 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7536 	if (IS_ERR(pgdat->kswapd)) {
7537 		/* failure at boot is fatal */
7538 		BUG_ON(system_state < SYSTEM_RUNNING);
7539 		pr_err("Failed to start kswapd on node %d\n", nid);
7540 		pgdat->kswapd = NULL;
7541 	}
7542 }
7543 
7544 /*
7545  * Called by memory hotplug when all memory in a node is offlined.  Caller must
7546  * hold mem_hotplug_begin/end().
7547  */
kswapd_stop(int nid)7548 void kswapd_stop(int nid)
7549 {
7550 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
7551 	bool skip = false;
7552 
7553 	trace_android_vh_kswapd_per_node(nid, &skip, false);
7554 	if (skip)
7555 		return;
7556 	if (kswapd) {
7557 		kthread_stop(kswapd);
7558 		NODE_DATA(nid)->kswapd = NULL;
7559 	}
7560 }
7561 
kswapd_init(void)7562 static int __init kswapd_init(void)
7563 {
7564 	int nid;
7565 
7566 	swap_setup();
7567 	for_each_node_state(nid, N_MEMORY)
7568  		kswapd_run(nid);
7569 	return 0;
7570 }
7571 
7572 module_init(kswapd_init)
7573 
7574 #ifdef CONFIG_NUMA
7575 /*
7576  * Node reclaim mode
7577  *
7578  * If non-zero call node_reclaim when the number of free pages falls below
7579  * the watermarks.
7580  */
7581 int node_reclaim_mode __read_mostly;
7582 
7583 /*
7584  * Priority for NODE_RECLAIM. This determines the fraction of pages
7585  * of a node considered for each zone_reclaim. 4 scans 1/16th of
7586  * a zone.
7587  */
7588 #define NODE_RECLAIM_PRIORITY 4
7589 
7590 /*
7591  * Percentage of pages in a zone that must be unmapped for node_reclaim to
7592  * occur.
7593  */
7594 int sysctl_min_unmapped_ratio = 1;
7595 
7596 /*
7597  * If the number of slab pages in a zone grows beyond this percentage then
7598  * slab reclaim needs to occur.
7599  */
7600 int sysctl_min_slab_ratio = 5;
7601 
node_unmapped_file_pages(struct pglist_data * pgdat)7602 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7603 {
7604 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7605 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7606 		node_page_state(pgdat, NR_ACTIVE_FILE);
7607 
7608 	/*
7609 	 * It's possible for there to be more file mapped pages than
7610 	 * accounted for by the pages on the file LRU lists because
7611 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7612 	 */
7613 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7614 }
7615 
7616 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
node_pagecache_reclaimable(struct pglist_data * pgdat)7617 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7618 {
7619 	unsigned long nr_pagecache_reclaimable;
7620 	unsigned long delta = 0;
7621 
7622 	/*
7623 	 * If RECLAIM_UNMAP is set, then all file pages are considered
7624 	 * potentially reclaimable. Otherwise, we have to worry about
7625 	 * pages like swapcache and node_unmapped_file_pages() provides
7626 	 * a better estimate
7627 	 */
7628 	if (node_reclaim_mode & RECLAIM_UNMAP)
7629 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7630 	else
7631 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7632 
7633 	/* If we can't clean pages, remove dirty pages from consideration */
7634 	if (!(node_reclaim_mode & RECLAIM_WRITE))
7635 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
7636 
7637 	/* Watch for any possible underflows due to delta */
7638 	if (unlikely(delta > nr_pagecache_reclaimable))
7639 		delta = nr_pagecache_reclaimable;
7640 
7641 	return nr_pagecache_reclaimable - delta;
7642 }
7643 
7644 /*
7645  * Try to free up some pages from this node through reclaim.
7646  */
__node_reclaim(struct pglist_data * pgdat,gfp_t gfp_mask,unsigned int order)7647 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7648 {
7649 	/* Minimum pages needed in order to stay on node */
7650 	const unsigned long nr_pages = 1 << order;
7651 	struct task_struct *p = current;
7652 	unsigned int noreclaim_flag;
7653 	struct scan_control sc = {
7654 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7655 		.gfp_mask = current_gfp_context(gfp_mask),
7656 		.order = order,
7657 		.priority = NODE_RECLAIM_PRIORITY,
7658 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7659 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7660 		.may_swap = 1,
7661 		.reclaim_idx = gfp_zone(gfp_mask),
7662 	};
7663 	unsigned long pflags;
7664 
7665 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7666 					   sc.gfp_mask);
7667 
7668 	cond_resched();
7669 	psi_memstall_enter(&pflags);
7670 	fs_reclaim_acquire(sc.gfp_mask);
7671 	/*
7672 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7673 	 * and we also need to be able to write out pages for RECLAIM_WRITE
7674 	 * and RECLAIM_UNMAP.
7675 	 */
7676 	noreclaim_flag = memalloc_noreclaim_save();
7677 	p->flags |= PF_SWAPWRITE;
7678 	set_task_reclaim_state(p, &sc.reclaim_state);
7679 
7680 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
7681 		/*
7682 		 * Free memory by calling shrink node with increasing
7683 		 * priorities until we have enough memory freed.
7684 		 */
7685 		do {
7686 			shrink_node(pgdat, &sc);
7687 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7688 	}
7689 
7690 	set_task_reclaim_state(p, NULL);
7691 	current->flags &= ~PF_SWAPWRITE;
7692 	memalloc_noreclaim_restore(noreclaim_flag);
7693 	fs_reclaim_release(sc.gfp_mask);
7694 	psi_memstall_leave(&pflags);
7695 
7696 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7697 
7698 	return sc.nr_reclaimed >= nr_pages;
7699 }
7700 
node_reclaim(struct pglist_data * pgdat,gfp_t gfp_mask,unsigned int order)7701 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7702 {
7703 	int ret;
7704 
7705 	/*
7706 	 * Node reclaim reclaims unmapped file backed pages and
7707 	 * slab pages if we are over the defined limits.
7708 	 *
7709 	 * A small portion of unmapped file backed pages is needed for
7710 	 * file I/O otherwise pages read by file I/O will be immediately
7711 	 * thrown out if the node is overallocated. So we do not reclaim
7712 	 * if less than a specified percentage of the node is used by
7713 	 * unmapped file backed pages.
7714 	 */
7715 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7716 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7717 	    pgdat->min_slab_pages)
7718 		return NODE_RECLAIM_FULL;
7719 
7720 	/*
7721 	 * Do not scan if the allocation should not be delayed.
7722 	 */
7723 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7724 		return NODE_RECLAIM_NOSCAN;
7725 
7726 	/*
7727 	 * Only run node reclaim on the local node or on nodes that do not
7728 	 * have associated processors. This will favor the local processor
7729 	 * over remote processors and spread off node memory allocations
7730 	 * as wide as possible.
7731 	 */
7732 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7733 		return NODE_RECLAIM_NOSCAN;
7734 
7735 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7736 		return NODE_RECLAIM_NOSCAN;
7737 
7738 	ret = __node_reclaim(pgdat, gfp_mask, order);
7739 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7740 
7741 	if (!ret)
7742 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7743 
7744 	return ret;
7745 }
7746 #endif
7747 
7748 /**
7749  * check_move_unevictable_pages - check pages for evictability and move to
7750  * appropriate zone lru list
7751  * @pvec: pagevec with lru pages to check
7752  *
7753  * Checks pages for evictability, if an evictable page is in the unevictable
7754  * lru list, moves it to the appropriate evictable lru list. This function
7755  * should be only used for lru pages.
7756  */
check_move_unevictable_pages(struct pagevec * pvec)7757 void check_move_unevictable_pages(struct pagevec *pvec)
7758 {
7759 	struct lruvec *lruvec = NULL;
7760 	int pgscanned = 0;
7761 	int pgrescued = 0;
7762 	int i;
7763 
7764 	for (i = 0; i < pvec->nr; i++) {
7765 		struct page *page = pvec->pages[i];
7766 		int nr_pages;
7767 
7768 		if (PageTransTail(page))
7769 			continue;
7770 
7771 		nr_pages = thp_nr_pages(page);
7772 		pgscanned += nr_pages;
7773 
7774 		/* block memcg migration during page moving between lru */
7775 		if (!TestClearPageLRU(page))
7776 			continue;
7777 
7778 		lruvec = relock_page_lruvec_irq(page, lruvec);
7779 		if (page_evictable(page) && PageUnevictable(page)) {
7780 			del_page_from_lru_list(page, lruvec);
7781 			ClearPageUnevictable(page);
7782 			add_page_to_lru_list(page, lruvec);
7783 			pgrescued += nr_pages;
7784 		}
7785 		SetPageLRU(page);
7786 	}
7787 
7788 	if (lruvec) {
7789 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7790 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7791 		unlock_page_lruvec_irq(lruvec);
7792 	} else if (pgscanned) {
7793 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7794 	}
7795 }
7796 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
7797