1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/mm/swap.c
4 *
5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
6 */
7
8 /*
9 * This file contains the default values for the operation of the
10 * Linux VM subsystem. Fine-tuning documentation can be found in
11 * Documentation/admin-guide/sysctl/vm.rst.
12 * Started 18.12.91
13 * Swap aging added 23.2.95, Stephen Tweedie.
14 * Buffermem limits added 12.3.98, Rik van Riel.
15 */
16
17 #include <linux/mm.h>
18 #include <linux/sched.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/swap.h>
21 #include <linux/mman.h>
22 #include <linux/pagemap.h>
23 #include <linux/pagevec.h>
24 #include <linux/init.h>
25 #include <linux/export.h>
26 #include <linux/mm_inline.h>
27 #include <linux/percpu_counter.h>
28 #include <linux/memremap.h>
29 #include <linux/percpu.h>
30 #include <linux/cpu.h>
31 #include <linux/notifier.h>
32 #include <linux/backing-dev.h>
33 #include <linux/memcontrol.h>
34 #include <linux/gfp.h>
35 #include <linux/uio.h>
36 #include <linux/hugetlb.h>
37 #include <linux/page_idle.h>
38 #include <linux/local_lock.h>
39 #include <linux/buffer_head.h>
40
41 #include "internal.h"
42
43 #define CREATE_TRACE_POINTS
44 #include <trace/events/pagemap.h>
45
46 /* How many pages do we try to swap or page in/out together? As a power of 2 */
47 int page_cluster;
48 const int page_cluster_max = 31;
49
50 /* Protecting only lru_rotate.fbatch which requires disabling interrupts */
51 struct lru_rotate {
52 local_lock_t lock;
53 struct folio_batch fbatch;
54 };
55 static DEFINE_PER_CPU(struct lru_rotate, lru_rotate) = {
56 .lock = INIT_LOCAL_LOCK(lock),
57 };
58
59 /*
60 * The following folio batches are grouped together because they are protected
61 * by disabling preemption (and interrupts remain enabled).
62 */
63 struct cpu_fbatches {
64 local_lock_t lock;
65 struct folio_batch lru_add;
66 struct folio_batch lru_deactivate_file;
67 struct folio_batch lru_deactivate;
68 struct folio_batch lru_lazyfree;
69 #ifdef CONFIG_SMP
70 struct folio_batch activate;
71 #endif
72 };
73 static DEFINE_PER_CPU(struct cpu_fbatches, cpu_fbatches) = {
74 .lock = INIT_LOCAL_LOCK(lock),
75 };
76
77 /*
78 * This path almost never happens for VM activity - pages are normally freed
79 * in batches. But it gets used by networking - and for compound pages.
80 */
__page_cache_release(struct folio * folio)81 static void __page_cache_release(struct folio *folio)
82 {
83 if (folio_test_lru(folio)) {
84 struct lruvec *lruvec;
85 unsigned long flags;
86
87 lruvec = folio_lruvec_lock_irqsave(folio, &flags);
88 lruvec_del_folio(lruvec, folio);
89 __folio_clear_lru_flags(folio);
90 unlock_page_lruvec_irqrestore(lruvec, flags);
91 }
92 }
93
__folio_put_small(struct folio * folio)94 static void __folio_put_small(struct folio *folio)
95 {
96 __page_cache_release(folio);
97 mem_cgroup_uncharge(folio);
98 free_unref_page(&folio->page, 0);
99 }
100
__folio_put_large(struct folio * folio)101 static void __folio_put_large(struct folio *folio)
102 {
103 /*
104 * __page_cache_release() is supposed to be called for thp, not for
105 * hugetlb. This is because hugetlb page does never have PageLRU set
106 * (it's never listed to any LRU lists) and no memcg routines should
107 * be called for hugetlb (it has a separate hugetlb_cgroup.)
108 */
109 if (!folio_test_hugetlb(folio))
110 __page_cache_release(folio);
111 destroy_large_folio(folio);
112 }
113
__folio_put(struct folio * folio)114 void __folio_put(struct folio *folio)
115 {
116 if (unlikely(folio_is_zone_device(folio)))
117 free_zone_device_page(&folio->page);
118 else if (unlikely(folio_test_large(folio)))
119 __folio_put_large(folio);
120 else
121 __folio_put_small(folio);
122 }
123 EXPORT_SYMBOL(__folio_put);
124
125 /**
126 * put_pages_list() - release a list of pages
127 * @pages: list of pages threaded on page->lru
128 *
129 * Release a list of pages which are strung together on page.lru.
130 */
put_pages_list(struct list_head * pages)131 void put_pages_list(struct list_head *pages)
132 {
133 struct folio *folio, *next;
134
135 list_for_each_entry_safe(folio, next, pages, lru) {
136 if (!folio_put_testzero(folio)) {
137 list_del(&folio->lru);
138 continue;
139 }
140 if (folio_test_large(folio)) {
141 list_del(&folio->lru);
142 __folio_put_large(folio);
143 continue;
144 }
145 /* LRU flag must be clear because it's passed using the lru */
146 }
147
148 free_unref_page_list(pages);
149 INIT_LIST_HEAD(pages);
150 }
151 EXPORT_SYMBOL(put_pages_list);
152
153 typedef void (*move_fn_t)(struct lruvec *lruvec, struct folio *folio);
154
lru_add_fn(struct lruvec * lruvec,struct folio * folio)155 static void lru_add_fn(struct lruvec *lruvec, struct folio *folio)
156 {
157 int was_unevictable = folio_test_clear_unevictable(folio);
158 long nr_pages = folio_nr_pages(folio);
159
160 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
161
162 /*
163 * Is an smp_mb__after_atomic() still required here, before
164 * folio_evictable() tests the mlocked flag, to rule out the possibility
165 * of stranding an evictable folio on an unevictable LRU? I think
166 * not, because __munlock_folio() only clears the mlocked flag
167 * while the LRU lock is held.
168 *
169 * (That is not true of __page_cache_release(), and not necessarily
170 * true of release_pages(): but those only clear the mlocked flag after
171 * folio_put_testzero() has excluded any other users of the folio.)
172 */
173 if (folio_evictable(folio)) {
174 if (was_unevictable)
175 __count_vm_events(UNEVICTABLE_PGRESCUED, nr_pages);
176 } else {
177 folio_clear_active(folio);
178 folio_set_unevictable(folio);
179 /*
180 * folio->mlock_count = !!folio_test_mlocked(folio)?
181 * But that leaves __mlock_folio() in doubt whether another
182 * actor has already counted the mlock or not. Err on the
183 * safe side, underestimate, let page reclaim fix it, rather
184 * than leaving a page on the unevictable LRU indefinitely.
185 */
186 folio->mlock_count = 0;
187 if (!was_unevictable)
188 __count_vm_events(UNEVICTABLE_PGCULLED, nr_pages);
189 }
190
191 lruvec_add_folio(lruvec, folio);
192 trace_mm_lru_insertion(folio);
193 }
194
folio_batch_move_lru(struct folio_batch * fbatch,move_fn_t move_fn)195 static void folio_batch_move_lru(struct folio_batch *fbatch, move_fn_t move_fn)
196 {
197 int i;
198 struct lruvec *lruvec = NULL;
199 unsigned long flags = 0;
200
201 for (i = 0; i < folio_batch_count(fbatch); i++) {
202 struct folio *folio = fbatch->folios[i];
203
204 /* block memcg migration while the folio moves between lru */
205 if (move_fn != lru_add_fn && !folio_test_clear_lru(folio))
206 continue;
207
208 lruvec = folio_lruvec_relock_irqsave(folio, lruvec, &flags);
209 move_fn(lruvec, folio);
210
211 folio_set_lru(folio);
212 }
213
214 if (lruvec)
215 unlock_page_lruvec_irqrestore(lruvec, flags);
216 folios_put(fbatch->folios, folio_batch_count(fbatch));
217 folio_batch_reinit(fbatch);
218 }
219
folio_batch_add_and_move(struct folio_batch * fbatch,struct folio * folio,move_fn_t move_fn)220 static void folio_batch_add_and_move(struct folio_batch *fbatch,
221 struct folio *folio, move_fn_t move_fn)
222 {
223 if (folio_batch_add(fbatch, folio) && !folio_test_large(folio) &&
224 !lru_cache_disabled())
225 return;
226 folio_batch_move_lru(fbatch, move_fn);
227 }
228
lru_move_tail_fn(struct lruvec * lruvec,struct folio * folio)229 static void lru_move_tail_fn(struct lruvec *lruvec, struct folio *folio)
230 {
231 if (!folio_test_unevictable(folio)) {
232 lruvec_del_folio(lruvec, folio);
233 folio_clear_active(folio);
234 lruvec_add_folio_tail(lruvec, folio);
235 __count_vm_events(PGROTATED, folio_nr_pages(folio));
236 }
237 }
238
239 /*
240 * Writeback is about to end against a folio which has been marked for
241 * immediate reclaim. If it still appears to be reclaimable, move it
242 * to the tail of the inactive list.
243 *
244 * folio_rotate_reclaimable() must disable IRQs, to prevent nasty races.
245 */
folio_rotate_reclaimable(struct folio * folio)246 void folio_rotate_reclaimable(struct folio *folio)
247 {
248 if (!folio_test_locked(folio) && !folio_test_dirty(folio) &&
249 !folio_test_unevictable(folio) && folio_test_lru(folio)) {
250 struct folio_batch *fbatch;
251 unsigned long flags;
252
253 folio_get(folio);
254 local_lock_irqsave(&lru_rotate.lock, flags);
255 fbatch = this_cpu_ptr(&lru_rotate.fbatch);
256 folio_batch_add_and_move(fbatch, folio, lru_move_tail_fn);
257 local_unlock_irqrestore(&lru_rotate.lock, flags);
258 }
259 }
260
lru_note_cost(struct lruvec * lruvec,bool file,unsigned int nr_io,unsigned int nr_rotated)261 void lru_note_cost(struct lruvec *lruvec, bool file,
262 unsigned int nr_io, unsigned int nr_rotated)
263 {
264 unsigned long cost;
265
266 /*
267 * Reflect the relative cost of incurring IO and spending CPU
268 * time on rotations. This doesn't attempt to make a precise
269 * comparison, it just says: if reloads are about comparable
270 * between the LRU lists, or rotations are overwhelmingly
271 * different between them, adjust scan balance for CPU work.
272 */
273 cost = nr_io * SWAP_CLUSTER_MAX + nr_rotated;
274
275 do {
276 unsigned long lrusize;
277
278 /*
279 * Hold lruvec->lru_lock is safe here, since
280 * 1) The pinned lruvec in reclaim, or
281 * 2) From a pre-LRU page during refault (which also holds the
282 * rcu lock, so would be safe even if the page was on the LRU
283 * and could move simultaneously to a new lruvec).
284 */
285 spin_lock_irq(&lruvec->lru_lock);
286 /* Record cost event */
287 if (file)
288 lruvec->file_cost += cost;
289 else
290 lruvec->anon_cost += cost;
291
292 /*
293 * Decay previous events
294 *
295 * Because workloads change over time (and to avoid
296 * overflow) we keep these statistics as a floating
297 * average, which ends up weighing recent refaults
298 * more than old ones.
299 */
300 lrusize = lruvec_page_state(lruvec, NR_INACTIVE_ANON) +
301 lruvec_page_state(lruvec, NR_ACTIVE_ANON) +
302 lruvec_page_state(lruvec, NR_INACTIVE_FILE) +
303 lruvec_page_state(lruvec, NR_ACTIVE_FILE);
304
305 if (lruvec->file_cost + lruvec->anon_cost > lrusize / 4) {
306 lruvec->file_cost /= 2;
307 lruvec->anon_cost /= 2;
308 }
309 spin_unlock_irq(&lruvec->lru_lock);
310 } while ((lruvec = parent_lruvec(lruvec)));
311 }
312
lru_note_cost_refault(struct folio * folio)313 void lru_note_cost_refault(struct folio *folio)
314 {
315 #ifdef CONFIG_HYPERHOLD_FILE_LRU
316 if (page_is_file_lru(folio_page(folio, 0))) {
317 lru_note_cost(&(folio_pgdat(folio)->__lruvec), 1, folio_nr_pages(folio), 0);
318 return;
319 }
320 #endif
321
322 lru_note_cost(folio_lruvec(folio), folio_is_file_lru(folio),
323 folio_nr_pages(folio), 0);
324 }
325
folio_activate_fn(struct lruvec * lruvec,struct folio * folio)326 static void folio_activate_fn(struct lruvec *lruvec, struct folio *folio)
327 {
328 if (!folio_test_active(folio) && !folio_test_unevictable(folio)) {
329 long nr_pages = folio_nr_pages(folio);
330
331 lruvec_del_folio(lruvec, folio);
332 folio_set_active(folio);
333 lruvec_add_folio(lruvec, folio);
334 trace_mm_lru_activate(folio);
335
336 __count_vm_events(PGACTIVATE, nr_pages);
337 __count_memcg_events(lruvec_memcg(lruvec), PGACTIVATE,
338 nr_pages);
339 }
340 }
341
342 #ifdef CONFIG_SMP
folio_activate_drain(int cpu)343 static void folio_activate_drain(int cpu)
344 {
345 struct folio_batch *fbatch = &per_cpu(cpu_fbatches.activate, cpu);
346
347 if (folio_batch_count(fbatch))
348 folio_batch_move_lru(fbatch, folio_activate_fn);
349 }
350
folio_activate(struct folio * folio)351 void folio_activate(struct folio *folio)
352 {
353 if (folio_test_lru(folio) && !folio_test_active(folio) &&
354 !folio_test_unevictable(folio)) {
355 struct folio_batch *fbatch;
356
357 folio_get(folio);
358 local_lock(&cpu_fbatches.lock);
359 fbatch = this_cpu_ptr(&cpu_fbatches.activate);
360 folio_batch_add_and_move(fbatch, folio, folio_activate_fn);
361 local_unlock(&cpu_fbatches.lock);
362 }
363 }
364
365 #else
folio_activate_drain(int cpu)366 static inline void folio_activate_drain(int cpu)
367 {
368 }
369
folio_activate(struct folio * folio)370 void folio_activate(struct folio *folio)
371 {
372 struct lruvec *lruvec;
373
374 if (folio_test_clear_lru(folio)) {
375 lruvec = folio_lruvec_lock_irq(folio);
376 folio_activate_fn(lruvec, folio);
377 unlock_page_lruvec_irq(lruvec);
378 folio_set_lru(folio);
379 }
380 }
381 #endif
382
__lru_cache_activate_folio(struct folio * folio)383 static void __lru_cache_activate_folio(struct folio *folio)
384 {
385 struct folio_batch *fbatch;
386 int i;
387
388 local_lock(&cpu_fbatches.lock);
389 fbatch = this_cpu_ptr(&cpu_fbatches.lru_add);
390
391 /*
392 * Search backwards on the optimistic assumption that the folio being
393 * activated has just been added to this batch. Note that only
394 * the local batch is examined as a !LRU folio could be in the
395 * process of being released, reclaimed, migrated or on a remote
396 * batch that is currently being drained. Furthermore, marking
397 * a remote batch's folio active potentially hits a race where
398 * a folio is marked active just after it is added to the inactive
399 * list causing accounting errors and BUG_ON checks to trigger.
400 */
401 for (i = folio_batch_count(fbatch) - 1; i >= 0; i--) {
402 struct folio *batch_folio = fbatch->folios[i];
403
404 if (batch_folio == folio) {
405 folio_set_active(folio);
406 break;
407 }
408 }
409
410 local_unlock(&cpu_fbatches.lock);
411 }
412
413 #ifdef CONFIG_LRU_GEN
folio_inc_refs(struct folio * folio)414 static void folio_inc_refs(struct folio *folio)
415 {
416 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
417
418 if (folio_test_unevictable(folio))
419 return;
420
421 if (!folio_test_referenced(folio)) {
422 folio_set_referenced(folio);
423 return;
424 }
425
426 if (!folio_test_workingset(folio)) {
427 folio_set_workingset(folio);
428 return;
429 }
430
431 /* see the comment on MAX_NR_TIERS */
432 do {
433 new_flags = old_flags & LRU_REFS_MASK;
434 if (new_flags == LRU_REFS_MASK)
435 break;
436
437 new_flags += BIT(LRU_REFS_PGOFF);
438 new_flags |= old_flags & ~LRU_REFS_MASK;
439 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
440 }
441 #else
folio_inc_refs(struct folio * folio)442 static void folio_inc_refs(struct folio *folio)
443 {
444 }
445 #endif /* CONFIG_LRU_GEN */
446
447 /*
448 * Mark a page as having seen activity.
449 *
450 * inactive,unreferenced -> inactive,referenced
451 * inactive,referenced -> active,unreferenced
452 * active,unreferenced -> active,referenced
453 *
454 * When a newly allocated page is not yet visible, so safe for non-atomic ops,
455 * __SetPageReferenced(page) may be substituted for mark_page_accessed(page).
456 */
folio_mark_accessed(struct folio * folio)457 void folio_mark_accessed(struct folio *folio)
458 {
459 if (lru_gen_enabled()) {
460 folio_inc_refs(folio);
461 return;
462 }
463
464 if (!folio_test_referenced(folio)) {
465 folio_set_referenced(folio);
466 } else if (folio_test_unevictable(folio)) {
467 /*
468 * Unevictable pages are on the "LRU_UNEVICTABLE" list. But,
469 * this list is never rotated or maintained, so marking an
470 * unevictable page accessed has no effect.
471 */
472 } else if (!folio_test_active(folio)) {
473 /*
474 * If the folio is on the LRU, queue it for activation via
475 * cpu_fbatches.activate. Otherwise, assume the folio is in a
476 * folio_batch, mark it active and it'll be moved to the active
477 * LRU on the next drain.
478 */
479 if (folio_test_lru(folio))
480 folio_activate(folio);
481 else
482 __lru_cache_activate_folio(folio);
483 folio_clear_referenced(folio);
484 workingset_activation(folio);
485 }
486 if (folio_test_idle(folio))
487 folio_clear_idle(folio);
488 }
489 EXPORT_SYMBOL(folio_mark_accessed);
490
491 /**
492 * folio_add_lru - Add a folio to an LRU list.
493 * @folio: The folio to be added to the LRU.
494 *
495 * Queue the folio for addition to the LRU. The decision on whether
496 * to add the page to the [in]active [file|anon] list is deferred until the
497 * folio_batch is drained. This gives a chance for the caller of folio_add_lru()
498 * have the folio added to the active list using folio_mark_accessed().
499 */
folio_add_lru(struct folio * folio)500 void folio_add_lru(struct folio *folio)
501 {
502 struct folio_batch *fbatch;
503
504 VM_BUG_ON_FOLIO(folio_test_active(folio) &&
505 folio_test_unevictable(folio), folio);
506 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
507
508 /* see the comment in lru_gen_add_folio() */
509 if (lru_gen_enabled() && !folio_test_unevictable(folio) &&
510 lru_gen_in_fault() && !(current->flags & PF_MEMALLOC))
511 folio_set_active(folio);
512
513 folio_get(folio);
514 local_lock(&cpu_fbatches.lock);
515 fbatch = this_cpu_ptr(&cpu_fbatches.lru_add);
516 folio_batch_add_and_move(fbatch, folio, lru_add_fn);
517 local_unlock(&cpu_fbatches.lock);
518 }
519 EXPORT_SYMBOL(folio_add_lru);
520
521 /**
522 * folio_add_lru_vma() - Add a folio to the appropate LRU list for this VMA.
523 * @folio: The folio to be added to the LRU.
524 * @vma: VMA in which the folio is mapped.
525 *
526 * If the VMA is mlocked, @folio is added to the unevictable list.
527 * Otherwise, it is treated the same way as folio_add_lru().
528 */
folio_add_lru_vma(struct folio * folio,struct vm_area_struct * vma)529 void folio_add_lru_vma(struct folio *folio, struct vm_area_struct *vma)
530 {
531 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
532
533 if (unlikely((vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) == VM_LOCKED))
534 mlock_new_folio(folio);
535 else
536 folio_add_lru(folio);
537 }
538
539 /*
540 * If the folio cannot be invalidated, it is moved to the
541 * inactive list to speed up its reclaim. It is moved to the
542 * head of the list, rather than the tail, to give the flusher
543 * threads some time to write it out, as this is much more
544 * effective than the single-page writeout from reclaim.
545 *
546 * If the folio isn't mapped and dirty/writeback, the folio
547 * could be reclaimed asap using the reclaim flag.
548 *
549 * 1. active, mapped folio -> none
550 * 2. active, dirty/writeback folio -> inactive, head, reclaim
551 * 3. inactive, mapped folio -> none
552 * 4. inactive, dirty/writeback folio -> inactive, head, reclaim
553 * 5. inactive, clean -> inactive, tail
554 * 6. Others -> none
555 *
556 * In 4, it moves to the head of the inactive list so the folio is
557 * written out by flusher threads as this is much more efficient
558 * than the single-page writeout from reclaim.
559 */
lru_deactivate_file_fn(struct lruvec * lruvec,struct folio * folio)560 static void lru_deactivate_file_fn(struct lruvec *lruvec, struct folio *folio)
561 {
562 bool active = folio_test_active(folio);
563 long nr_pages = folio_nr_pages(folio);
564
565 if (folio_test_unevictable(folio))
566 return;
567
568 /* Some processes are using the folio */
569 if (folio_mapped(folio))
570 return;
571
572 lruvec_del_folio(lruvec, folio);
573 folio_clear_active(folio);
574 folio_clear_referenced(folio);
575
576 if (folio_test_writeback(folio) || folio_test_dirty(folio)) {
577 /*
578 * Setting the reclaim flag could race with
579 * folio_end_writeback() and confuse readahead. But the
580 * race window is _really_ small and it's not a critical
581 * problem.
582 */
583 lruvec_add_folio(lruvec, folio);
584 folio_set_reclaim(folio);
585 } else {
586 /*
587 * The folio's writeback ended while it was in the batch.
588 * We move that folio to the tail of the inactive list.
589 */
590 lruvec_add_folio_tail(lruvec, folio);
591 __count_vm_events(PGROTATED, nr_pages);
592 }
593
594 if (active) {
595 __count_vm_events(PGDEACTIVATE, nr_pages);
596 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
597 nr_pages);
598 }
599 }
600
lru_deactivate_fn(struct lruvec * lruvec,struct folio * folio)601 static void lru_deactivate_fn(struct lruvec *lruvec, struct folio *folio)
602 {
603 if (!folio_test_unevictable(folio) && (folio_test_active(folio) || lru_gen_enabled())) {
604 long nr_pages = folio_nr_pages(folio);
605
606 lruvec_del_folio(lruvec, folio);
607 folio_clear_active(folio);
608 folio_clear_referenced(folio);
609 lruvec_add_folio(lruvec, folio);
610
611 __count_vm_events(PGDEACTIVATE, nr_pages);
612 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
613 nr_pages);
614 }
615 }
616
lru_lazyfree_fn(struct lruvec * lruvec,struct folio * folio)617 static void lru_lazyfree_fn(struct lruvec *lruvec, struct folio *folio)
618 {
619 if (folio_test_anon(folio) && folio_test_swapbacked(folio) &&
620 !folio_test_swapcache(folio) && !folio_test_unevictable(folio)) {
621 long nr_pages = folio_nr_pages(folio);
622
623 lruvec_del_folio(lruvec, folio);
624 folio_clear_active(folio);
625 folio_clear_referenced(folio);
626 /*
627 * Lazyfree folios are clean anonymous folios. They have
628 * the swapbacked flag cleared, to distinguish them from normal
629 * anonymous folios
630 */
631 folio_clear_swapbacked(folio);
632 lruvec_add_folio(lruvec, folio);
633
634 __count_vm_events(PGLAZYFREE, nr_pages);
635 __count_memcg_events(lruvec_memcg(lruvec), PGLAZYFREE,
636 nr_pages);
637 }
638 }
639
640 /*
641 * Drain pages out of the cpu's folio_batch.
642 * Either "cpu" is the current CPU, and preemption has already been
643 * disabled; or "cpu" is being hot-unplugged, and is already dead.
644 */
lru_add_drain_cpu(int cpu)645 void lru_add_drain_cpu(int cpu)
646 {
647 struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
648 struct folio_batch *fbatch = &fbatches->lru_add;
649
650 if (folio_batch_count(fbatch))
651 folio_batch_move_lru(fbatch, lru_add_fn);
652
653 fbatch = &per_cpu(lru_rotate.fbatch, cpu);
654 /* Disabling interrupts below acts as a compiler barrier. */
655 if (data_race(folio_batch_count(fbatch))) {
656 unsigned long flags;
657
658 /* No harm done if a racing interrupt already did this */
659 local_lock_irqsave(&lru_rotate.lock, flags);
660 folio_batch_move_lru(fbatch, lru_move_tail_fn);
661 local_unlock_irqrestore(&lru_rotate.lock, flags);
662 }
663
664 fbatch = &fbatches->lru_deactivate_file;
665 if (folio_batch_count(fbatch))
666 folio_batch_move_lru(fbatch, lru_deactivate_file_fn);
667
668 fbatch = &fbatches->lru_deactivate;
669 if (folio_batch_count(fbatch))
670 folio_batch_move_lru(fbatch, lru_deactivate_fn);
671
672 fbatch = &fbatches->lru_lazyfree;
673 if (folio_batch_count(fbatch))
674 folio_batch_move_lru(fbatch, lru_lazyfree_fn);
675
676 folio_activate_drain(cpu);
677 }
678
679 /**
680 * deactivate_file_folio() - Deactivate a file folio.
681 * @folio: Folio to deactivate.
682 *
683 * This function hints to the VM that @folio is a good reclaim candidate,
684 * for example if its invalidation fails due to the folio being dirty
685 * or under writeback.
686 *
687 * Context: Caller holds a reference on the folio.
688 */
deactivate_file_folio(struct folio * folio)689 void deactivate_file_folio(struct folio *folio)
690 {
691 struct folio_batch *fbatch;
692
693 /* Deactivating an unevictable folio will not accelerate reclaim */
694 if (folio_test_unevictable(folio))
695 return;
696
697 folio_get(folio);
698 local_lock(&cpu_fbatches.lock);
699 fbatch = this_cpu_ptr(&cpu_fbatches.lru_deactivate_file);
700 folio_batch_add_and_move(fbatch, folio, lru_deactivate_file_fn);
701 local_unlock(&cpu_fbatches.lock);
702 }
703
704 /*
705 * folio_deactivate - deactivate a folio
706 * @folio: folio to deactivate
707 *
708 * folio_deactivate() moves @folio to the inactive list if @folio was on the
709 * active list and was not unevictable. This is done to accelerate the
710 * reclaim of @folio.
711 */
folio_deactivate(struct folio * folio)712 void folio_deactivate(struct folio *folio)
713 {
714 if (folio_test_lru(folio) && !folio_test_unevictable(folio) &&
715 (folio_test_active(folio) || lru_gen_enabled())) {
716 struct folio_batch *fbatch;
717
718 folio_get(folio);
719 local_lock(&cpu_fbatches.lock);
720 fbatch = this_cpu_ptr(&cpu_fbatches.lru_deactivate);
721 folio_batch_add_and_move(fbatch, folio, lru_deactivate_fn);
722 local_unlock(&cpu_fbatches.lock);
723 }
724 }
725
726 /**
727 * folio_mark_lazyfree - make an anon folio lazyfree
728 * @folio: folio to deactivate
729 *
730 * folio_mark_lazyfree() moves @folio to the inactive file list.
731 * This is done to accelerate the reclaim of @folio.
732 */
folio_mark_lazyfree(struct folio * folio)733 void folio_mark_lazyfree(struct folio *folio)
734 {
735 if (folio_test_lru(folio) && folio_test_anon(folio) &&
736 folio_test_swapbacked(folio) && !folio_test_swapcache(folio) &&
737 !folio_test_unevictable(folio)) {
738 struct folio_batch *fbatch;
739
740 folio_get(folio);
741 local_lock(&cpu_fbatches.lock);
742 fbatch = this_cpu_ptr(&cpu_fbatches.lru_lazyfree);
743 folio_batch_add_and_move(fbatch, folio, lru_lazyfree_fn);
744 local_unlock(&cpu_fbatches.lock);
745 }
746 }
747
lru_add_drain(void)748 void lru_add_drain(void)
749 {
750 local_lock(&cpu_fbatches.lock);
751 lru_add_drain_cpu(smp_processor_id());
752 local_unlock(&cpu_fbatches.lock);
753 mlock_drain_local();
754 }
755
756 /*
757 * It's called from per-cpu workqueue context in SMP case so
758 * lru_add_drain_cpu and invalidate_bh_lrus_cpu should run on
759 * the same cpu. It shouldn't be a problem in !SMP case since
760 * the core is only one and the locks will disable preemption.
761 */
lru_add_and_bh_lrus_drain(void)762 static void lru_add_and_bh_lrus_drain(void)
763 {
764 local_lock(&cpu_fbatches.lock);
765 lru_add_drain_cpu(smp_processor_id());
766 local_unlock(&cpu_fbatches.lock);
767 invalidate_bh_lrus_cpu();
768 mlock_drain_local();
769 }
770
lru_add_drain_cpu_zone(struct zone * zone)771 void lru_add_drain_cpu_zone(struct zone *zone)
772 {
773 local_lock(&cpu_fbatches.lock);
774 lru_add_drain_cpu(smp_processor_id());
775 drain_local_pages(zone);
776 local_unlock(&cpu_fbatches.lock);
777 mlock_drain_local();
778 }
779
780 #ifdef CONFIG_SMP
781
782 static DEFINE_PER_CPU(struct work_struct, lru_add_drain_work);
783
lru_add_drain_per_cpu(struct work_struct * dummy)784 static void lru_add_drain_per_cpu(struct work_struct *dummy)
785 {
786 lru_add_and_bh_lrus_drain();
787 }
788
cpu_needs_drain(unsigned int cpu)789 static bool cpu_needs_drain(unsigned int cpu)
790 {
791 struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
792
793 /* Check these in order of likelihood that they're not zero */
794 return folio_batch_count(&fbatches->lru_add) ||
795 data_race(folio_batch_count(&per_cpu(lru_rotate.fbatch, cpu))) ||
796 folio_batch_count(&fbatches->lru_deactivate_file) ||
797 folio_batch_count(&fbatches->lru_deactivate) ||
798 folio_batch_count(&fbatches->lru_lazyfree) ||
799 folio_batch_count(&fbatches->activate) ||
800 need_mlock_drain(cpu) ||
801 has_bh_in_lru(cpu, NULL);
802 }
803
804 /*
805 * Doesn't need any cpu hotplug locking because we do rely on per-cpu
806 * kworkers being shut down before our page_alloc_cpu_dead callback is
807 * executed on the offlined cpu.
808 * Calling this function with cpu hotplug locks held can actually lead
809 * to obscure indirect dependencies via WQ context.
810 */
__lru_add_drain_all(bool force_all_cpus)811 static inline void __lru_add_drain_all(bool force_all_cpus)
812 {
813 /*
814 * lru_drain_gen - Global pages generation number
815 *
816 * (A) Definition: global lru_drain_gen = x implies that all generations
817 * 0 < n <= x are already *scheduled* for draining.
818 *
819 * This is an optimization for the highly-contended use case where a
820 * user space workload keeps constantly generating a flow of pages for
821 * each CPU.
822 */
823 static unsigned int lru_drain_gen;
824 static struct cpumask has_work;
825 static DEFINE_MUTEX(lock);
826 unsigned cpu, this_gen;
827
828 /*
829 * Make sure nobody triggers this path before mm_percpu_wq is fully
830 * initialized.
831 */
832 if (WARN_ON(!mm_percpu_wq))
833 return;
834
835 /*
836 * Guarantee folio_batch counter stores visible by this CPU
837 * are visible to other CPUs before loading the current drain
838 * generation.
839 */
840 smp_mb();
841
842 /*
843 * (B) Locally cache global LRU draining generation number
844 *
845 * The read barrier ensures that the counter is loaded before the mutex
846 * is taken. It pairs with smp_mb() inside the mutex critical section
847 * at (D).
848 */
849 this_gen = smp_load_acquire(&lru_drain_gen);
850
851 mutex_lock(&lock);
852
853 /*
854 * (C) Exit the draining operation if a newer generation, from another
855 * lru_add_drain_all(), was already scheduled for draining. Check (A).
856 */
857 if (unlikely(this_gen != lru_drain_gen && !force_all_cpus))
858 goto done;
859
860 /*
861 * (D) Increment global generation number
862 *
863 * Pairs with smp_load_acquire() at (B), outside of the critical
864 * section. Use a full memory barrier to guarantee that the
865 * new global drain generation number is stored before loading
866 * folio_batch counters.
867 *
868 * This pairing must be done here, before the for_each_online_cpu loop
869 * below which drains the page vectors.
870 *
871 * Let x, y, and z represent some system CPU numbers, where x < y < z.
872 * Assume CPU #z is in the middle of the for_each_online_cpu loop
873 * below and has already reached CPU #y's per-cpu data. CPU #x comes
874 * along, adds some pages to its per-cpu vectors, then calls
875 * lru_add_drain_all().
876 *
877 * If the paired barrier is done at any later step, e.g. after the
878 * loop, CPU #x will just exit at (C) and miss flushing out all of its
879 * added pages.
880 */
881 WRITE_ONCE(lru_drain_gen, lru_drain_gen + 1);
882 smp_mb();
883
884 cpumask_clear(&has_work);
885 for_each_online_cpu(cpu) {
886 struct work_struct *work = &per_cpu(lru_add_drain_work, cpu);
887
888 if (cpu_needs_drain(cpu)) {
889 INIT_WORK(work, lru_add_drain_per_cpu);
890 queue_work_on(cpu, mm_percpu_wq, work);
891 __cpumask_set_cpu(cpu, &has_work);
892 }
893 }
894
895 for_each_cpu(cpu, &has_work)
896 flush_work(&per_cpu(lru_add_drain_work, cpu));
897
898 done:
899 mutex_unlock(&lock);
900 }
901
lru_add_drain_all(void)902 void lru_add_drain_all(void)
903 {
904 __lru_add_drain_all(false);
905 }
906 #else
lru_add_drain_all(void)907 void lru_add_drain_all(void)
908 {
909 lru_add_drain();
910 }
911 #endif /* CONFIG_SMP */
912
913 atomic_t lru_disable_count = ATOMIC_INIT(0);
914
915 /*
916 * lru_cache_disable() needs to be called before we start compiling
917 * a list of pages to be migrated using isolate_lru_page().
918 * It drains pages on LRU cache and then disable on all cpus until
919 * lru_cache_enable is called.
920 *
921 * Must be paired with a call to lru_cache_enable().
922 */
lru_cache_disable(void)923 void lru_cache_disable(void)
924 {
925 atomic_inc(&lru_disable_count);
926 /*
927 * Readers of lru_disable_count are protected by either disabling
928 * preemption or rcu_read_lock:
929 *
930 * preempt_disable, local_irq_disable [bh_lru_lock()]
931 * rcu_read_lock [rt_spin_lock CONFIG_PREEMPT_RT]
932 * preempt_disable [local_lock !CONFIG_PREEMPT_RT]
933 *
934 * Since v5.1 kernel, synchronize_rcu() is guaranteed to wait on
935 * preempt_disable() regions of code. So any CPU which sees
936 * lru_disable_count = 0 will have exited the critical
937 * section when synchronize_rcu() returns.
938 */
939 synchronize_rcu_expedited();
940 #ifdef CONFIG_SMP
941 __lru_add_drain_all(true);
942 #else
943 lru_add_and_bh_lrus_drain();
944 #endif
945 }
946
947 /**
948 * release_pages - batched put_page()
949 * @arg: array of pages to release
950 * @nr: number of pages
951 *
952 * Decrement the reference count on all the pages in @arg. If it
953 * fell to zero, remove the page from the LRU and free it.
954 *
955 * Note that the argument can be an array of pages, encoded pages,
956 * or folio pointers. We ignore any encoded bits, and turn any of
957 * them into just a folio that gets free'd.
958 */
release_pages(release_pages_arg arg,int nr)959 void release_pages(release_pages_arg arg, int nr)
960 {
961 int i;
962 struct encoded_page **encoded = arg.encoded_pages;
963 LIST_HEAD(pages_to_free);
964 struct lruvec *lruvec = NULL;
965 unsigned long flags = 0;
966 unsigned int lock_batch;
967
968 for (i = 0; i < nr; i++) {
969 struct folio *folio;
970
971 /* Turn any of the argument types into a folio */
972 folio = page_folio(encoded_page_ptr(encoded[i]));
973
974 /*
975 * Make sure the IRQ-safe lock-holding time does not get
976 * excessive with a continuous string of pages from the
977 * same lruvec. The lock is held only if lruvec != NULL.
978 */
979 if (lruvec && ++lock_batch == SWAP_CLUSTER_MAX) {
980 unlock_page_lruvec_irqrestore(lruvec, flags);
981 lruvec = NULL;
982 }
983
984 if (is_huge_zero_page(&folio->page))
985 continue;
986
987 if (folio_is_zone_device(folio)) {
988 if (lruvec) {
989 unlock_page_lruvec_irqrestore(lruvec, flags);
990 lruvec = NULL;
991 }
992 if (put_devmap_managed_page(&folio->page))
993 continue;
994 if (folio_put_testzero(folio))
995 free_zone_device_page(&folio->page);
996 continue;
997 }
998
999 if (!folio_put_testzero(folio))
1000 continue;
1001
1002 if (folio_test_large(folio)) {
1003 if (lruvec) {
1004 unlock_page_lruvec_irqrestore(lruvec, flags);
1005 lruvec = NULL;
1006 }
1007 __folio_put_large(folio);
1008 continue;
1009 }
1010
1011 if (folio_test_lru(folio)) {
1012 struct lruvec *prev_lruvec = lruvec;
1013
1014 lruvec = folio_lruvec_relock_irqsave(folio, lruvec,
1015 &flags);
1016 if (prev_lruvec != lruvec)
1017 lock_batch = 0;
1018
1019 lruvec_del_folio(lruvec, folio);
1020 __folio_clear_lru_flags(folio);
1021 }
1022
1023 list_add(&folio->lru, &pages_to_free);
1024 }
1025 if (lruvec)
1026 unlock_page_lruvec_irqrestore(lruvec, flags);
1027
1028 mem_cgroup_uncharge_list(&pages_to_free);
1029 free_unref_page_list(&pages_to_free);
1030 }
1031 EXPORT_SYMBOL(release_pages);
1032
1033 /*
1034 * The folios which we're about to release may be in the deferred lru-addition
1035 * queues. That would prevent them from really being freed right now. That's
1036 * OK from a correctness point of view but is inefficient - those folios may be
1037 * cache-warm and we want to give them back to the page allocator ASAP.
1038 *
1039 * So __folio_batch_release() will drain those queues here.
1040 * folio_batch_move_lru() calls folios_put() directly to avoid
1041 * mutual recursion.
1042 */
__folio_batch_release(struct folio_batch * fbatch)1043 void __folio_batch_release(struct folio_batch *fbatch)
1044 {
1045 if (!fbatch->percpu_pvec_drained) {
1046 lru_add_drain();
1047 fbatch->percpu_pvec_drained = true;
1048 }
1049 release_pages(fbatch->folios, folio_batch_count(fbatch));
1050 folio_batch_reinit(fbatch);
1051 }
1052 EXPORT_SYMBOL(__folio_batch_release);
1053
1054 /**
1055 * folio_batch_remove_exceptionals() - Prune non-folios from a batch.
1056 * @fbatch: The batch to prune
1057 *
1058 * find_get_entries() fills a batch with both folios and shadow/swap/DAX
1059 * entries. This function prunes all the non-folio entries from @fbatch
1060 * without leaving holes, so that it can be passed on to folio-only batch
1061 * operations.
1062 */
folio_batch_remove_exceptionals(struct folio_batch * fbatch)1063 void folio_batch_remove_exceptionals(struct folio_batch *fbatch)
1064 {
1065 unsigned int i, j;
1066
1067 for (i = 0, j = 0; i < folio_batch_count(fbatch); i++) {
1068 struct folio *folio = fbatch->folios[i];
1069 if (!xa_is_value(folio))
1070 fbatch->folios[j++] = folio;
1071 }
1072 fbatch->nr = j;
1073 }
1074
1075 /*
1076 * Perform any setup for the swap system
1077 */
swap_setup(void)1078 void __init swap_setup(void)
1079 {
1080 unsigned long megs = totalram_pages() >> (20 - PAGE_SHIFT);
1081
1082 /* Use a smaller cluster for small-memory machines */
1083 if (megs < 16)
1084 page_cluster = 2;
1085 else
1086 page_cluster = 3;
1087 /*
1088 * Right now other parts of the system means that we
1089 * _really_ don't want to cluster much more
1090 */
1091 }
1092