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