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 #undef CREATE_TRACE_POINTS
47 #include <trace/hooks/mm.h>
48
49 /* How many pages do we try to swap or page in/out together? */
50 int page_cluster;
51
52 /* Protecting only lru_rotate.pvec which requires disabling interrupts */
53 struct lru_rotate {
54 local_lock_t lock;
55 struct pagevec pvec;
56 };
57 static DEFINE_PER_CPU(struct lru_rotate, lru_rotate) = {
58 .lock = INIT_LOCAL_LOCK(lock),
59 };
60
61 /*
62 * The following struct pagevec are grouped together because they are protected
63 * by disabling preemption (and interrupts remain enabled).
64 */
65 struct lru_pvecs {
66 local_lock_t lock;
67 struct pagevec lru_add;
68 struct pagevec lru_deactivate_file;
69 struct pagevec lru_deactivate;
70 struct pagevec lru_lazyfree;
71 #ifdef CONFIG_SMP
72 struct pagevec activate_page;
73 #endif
74 };
75 static DEFINE_PER_CPU(struct lru_pvecs, lru_pvecs) = {
76 .lock = INIT_LOCAL_LOCK(lock),
77 };
78
79 /*
80 * This path almost never happens for VM activity - pages are normally
81 * freed via pagevecs. But it gets used by networking.
82 */
__page_cache_release(struct page * page)83 static void __page_cache_release(struct page *page)
84 {
85 if (PageLRU(page)) {
86 struct lruvec *lruvec;
87 unsigned long flags;
88
89 lruvec = lock_page_lruvec_irqsave(page, &flags);
90 del_page_from_lru_list(page, lruvec);
91 __clear_page_lru_flags(page);
92 unlock_page_lruvec_irqrestore(lruvec, flags);
93 }
94 __ClearPageWaiters(page);
95 }
96
__put_single_page(struct page * page)97 static void __put_single_page(struct page *page)
98 {
99 __page_cache_release(page);
100 mem_cgroup_uncharge(page);
101 free_unref_page(page, 0);
102 }
103
__put_compound_page(struct page * page)104 static void __put_compound_page(struct page *page)
105 {
106 /*
107 * __page_cache_release() is supposed to be called for thp, not for
108 * hugetlb. This is because hugetlb page does never have PageLRU set
109 * (it's never listed to any LRU lists) and no memcg routines should
110 * be called for hugetlb (it has a separate hugetlb_cgroup.)
111 */
112 if (!PageHuge(page))
113 __page_cache_release(page);
114 destroy_compound_page(page);
115 }
116
__put_page(struct page * page)117 void __put_page(struct page *page)
118 {
119 if (is_zone_device_page(page)) {
120 put_dev_pagemap(page->pgmap);
121
122 /*
123 * The page belongs to the device that created pgmap. Do
124 * not return it to page allocator.
125 */
126 return;
127 }
128
129 if (unlikely(PageCompound(page)))
130 __put_compound_page(page);
131 else
132 __put_single_page(page);
133 }
134 EXPORT_SYMBOL(__put_page);
135
136 /**
137 * put_pages_list() - release a list of pages
138 * @pages: list of pages threaded on page->lru
139 *
140 * Release a list of pages which are strung together on page.lru. Currently
141 * used by read_cache_pages() and related error recovery code.
142 */
put_pages_list(struct list_head * pages)143 void put_pages_list(struct list_head *pages)
144 {
145 while (!list_empty(pages)) {
146 struct page *victim;
147
148 victim = lru_to_page(pages);
149 list_del(&victim->lru);
150 put_page(victim);
151 }
152 }
153 EXPORT_SYMBOL(put_pages_list);
154
155 /*
156 * get_kernel_pages() - pin kernel pages in memory
157 * @kiov: An array of struct kvec structures
158 * @nr_segs: number of segments to pin
159 * @write: pinning for read/write, currently ignored
160 * @pages: array that receives pointers to the pages pinned.
161 * Should be at least nr_segs long.
162 *
163 * Returns number of pages pinned. This may be fewer than the number
164 * requested. If nr_pages is 0 or negative, returns 0. If no pages
165 * were pinned, returns -errno. Each page returned must be released
166 * with a put_page() call when it is finished with.
167 */
get_kernel_pages(const struct kvec * kiov,int nr_segs,int write,struct page ** pages)168 int get_kernel_pages(const struct kvec *kiov, int nr_segs, int write,
169 struct page **pages)
170 {
171 int seg;
172
173 for (seg = 0; seg < nr_segs; seg++) {
174 if (WARN_ON(kiov[seg].iov_len != PAGE_SIZE))
175 return seg;
176
177 pages[seg] = kmap_to_page(kiov[seg].iov_base);
178 get_page(pages[seg]);
179 }
180
181 return seg;
182 }
183 EXPORT_SYMBOL_GPL(get_kernel_pages);
184
pagevec_lru_move_fn(struct pagevec * pvec,void (* move_fn)(struct page * page,struct lruvec * lruvec))185 static void pagevec_lru_move_fn(struct pagevec *pvec,
186 void (*move_fn)(struct page *page, struct lruvec *lruvec))
187 {
188 int i;
189 struct lruvec *lruvec = NULL;
190 unsigned long flags = 0;
191
192 for (i = 0; i < pagevec_count(pvec); i++) {
193 struct page *page = pvec->pages[i];
194
195 /* block memcg migration during page moving between lru */
196 if (!TestClearPageLRU(page))
197 continue;
198
199 lruvec = relock_page_lruvec_irqsave(page, lruvec, &flags);
200 (*move_fn)(page, lruvec);
201
202 SetPageLRU(page);
203 }
204 if (lruvec)
205 unlock_page_lruvec_irqrestore(lruvec, flags);
206 release_pages(pvec->pages, pvec->nr);
207 pagevec_reinit(pvec);
208 }
209
pagevec_move_tail_fn(struct page * page,struct lruvec * lruvec)210 static void pagevec_move_tail_fn(struct page *page, struct lruvec *lruvec)
211 {
212 if (!PageUnevictable(page)) {
213 del_page_from_lru_list(page, lruvec);
214 ClearPageActive(page);
215 add_page_to_lru_list_tail(page, lruvec);
216 __count_vm_events(PGROTATED, thp_nr_pages(page));
217 }
218 }
219
220 /* return true if pagevec needs to drain */
pagevec_add_and_need_flush(struct pagevec * pvec,struct page * page)221 static bool pagevec_add_and_need_flush(struct pagevec *pvec, struct page *page)
222 {
223 bool ret = false;
224
225 if (!pagevec_add(pvec, page) || PageCompound(page) ||
226 lru_cache_disabled())
227 ret = true;
228
229 trace_android_vh_pagevec_drain(page, &ret);
230 return ret;
231 }
232
233 /*
234 * Writeback is about to end against a page which has been marked for immediate
235 * reclaim. If it still appears to be reclaimable, move it to the tail of the
236 * inactive list.
237 *
238 * rotate_reclaimable_page() must disable IRQs, to prevent nasty races.
239 */
rotate_reclaimable_page(struct page * page)240 void rotate_reclaimable_page(struct page *page)
241 {
242 if (!PageLocked(page) && !PageDirty(page) &&
243 !PageUnevictable(page) && PageLRU(page)) {
244 struct pagevec *pvec;
245 unsigned long flags;
246
247 get_page(page);
248 local_lock_irqsave(&lru_rotate.lock, flags);
249 pvec = this_cpu_ptr(&lru_rotate.pvec);
250 if (pagevec_add_and_need_flush(pvec, page))
251 pagevec_lru_move_fn(pvec, pagevec_move_tail_fn);
252 local_unlock_irqrestore(&lru_rotate.lock, flags);
253 }
254 }
255
lru_note_cost(struct lruvec * lruvec,bool file,unsigned int nr_pages)256 void lru_note_cost(struct lruvec *lruvec, bool file, unsigned int nr_pages)
257 {
258 do {
259 unsigned long lrusize;
260
261 /*
262 * Hold lruvec->lru_lock is safe here, since
263 * 1) The pinned lruvec in reclaim, or
264 * 2) From a pre-LRU page during refault (which also holds the
265 * rcu lock, so would be safe even if the page was on the LRU
266 * and could move simultaneously to a new lruvec).
267 */
268 spin_lock_irq(&lruvec->lru_lock);
269 /* Record cost event */
270 if (file)
271 lruvec->file_cost += nr_pages;
272 else
273 lruvec->anon_cost += nr_pages;
274
275 /*
276 * Decay previous events
277 *
278 * Because workloads change over time (and to avoid
279 * overflow) we keep these statistics as a floating
280 * average, which ends up weighing recent refaults
281 * more than old ones.
282 */
283 lrusize = lruvec_page_state(lruvec, NR_INACTIVE_ANON) +
284 lruvec_page_state(lruvec, NR_ACTIVE_ANON) +
285 lruvec_page_state(lruvec, NR_INACTIVE_FILE) +
286 lruvec_page_state(lruvec, NR_ACTIVE_FILE);
287
288 if (lruvec->file_cost + lruvec->anon_cost > lrusize / 4) {
289 lruvec->file_cost /= 2;
290 lruvec->anon_cost /= 2;
291 }
292 spin_unlock_irq(&lruvec->lru_lock);
293 } while ((lruvec = parent_lruvec(lruvec)));
294 }
295
lru_note_cost_page(struct page * page)296 void lru_note_cost_page(struct page *page)
297 {
298 lru_note_cost(mem_cgroup_page_lruvec(page),
299 page_is_file_lru(page), thp_nr_pages(page));
300 }
301
__activate_page(struct page * page,struct lruvec * lruvec)302 static void __activate_page(struct page *page, struct lruvec *lruvec)
303 {
304 if (!PageActive(page) && !PageUnevictable(page)) {
305 int nr_pages = thp_nr_pages(page);
306
307 del_page_from_lru_list(page, lruvec);
308 SetPageActive(page);
309 add_page_to_lru_list(page, lruvec);
310 trace_mm_lru_activate(page);
311
312 __count_vm_events(PGACTIVATE, nr_pages);
313 __count_memcg_events(lruvec_memcg(lruvec), PGACTIVATE,
314 nr_pages);
315 }
316 }
317
318 #ifdef CONFIG_SMP
activate_page_drain(int cpu)319 static void activate_page_drain(int cpu)
320 {
321 struct pagevec *pvec = &per_cpu(lru_pvecs.activate_page, cpu);
322
323 if (pagevec_count(pvec))
324 pagevec_lru_move_fn(pvec, __activate_page);
325 }
326
need_activate_page_drain(int cpu)327 static bool need_activate_page_drain(int cpu)
328 {
329 return pagevec_count(&per_cpu(lru_pvecs.activate_page, cpu)) != 0;
330 }
331
activate_page(struct page * page)332 void activate_page(struct page *page)
333 {
334 page = compound_head(page);
335 if (PageLRU(page) && !PageActive(page) && !PageUnevictable(page)) {
336 struct pagevec *pvec;
337
338 local_lock(&lru_pvecs.lock);
339 pvec = this_cpu_ptr(&lru_pvecs.activate_page);
340 get_page(page);
341 if (pagevec_add_and_need_flush(pvec, page))
342 pagevec_lru_move_fn(pvec, __activate_page);
343 local_unlock(&lru_pvecs.lock);
344 }
345 }
346
347 #else
activate_page_drain(int cpu)348 static inline void activate_page_drain(int cpu)
349 {
350 }
351
activate_page(struct page * page)352 void activate_page(struct page *page)
353 {
354 struct lruvec *lruvec;
355
356 page = compound_head(page);
357 if (TestClearPageLRU(page)) {
358 lruvec = lock_page_lruvec_irq(page);
359 __activate_page(page, lruvec);
360 unlock_page_lruvec_irq(lruvec);
361 SetPageLRU(page);
362 }
363 }
364 #endif
365
__lru_cache_activate_page(struct page * page)366 static void __lru_cache_activate_page(struct page *page)
367 {
368 struct pagevec *pvec;
369 int i;
370
371 local_lock(&lru_pvecs.lock);
372 pvec = this_cpu_ptr(&lru_pvecs.lru_add);
373
374 /*
375 * Search backwards on the optimistic assumption that the page being
376 * activated has just been added to this pagevec. Note that only
377 * the local pagevec is examined as a !PageLRU page could be in the
378 * process of being released, reclaimed, migrated or on a remote
379 * pagevec that is currently being drained. Furthermore, marking
380 * a remote pagevec's page PageActive potentially hits a race where
381 * a page is marked PageActive just after it is added to the inactive
382 * list causing accounting errors and BUG_ON checks to trigger.
383 */
384 for (i = pagevec_count(pvec) - 1; i >= 0; i--) {
385 struct page *pagevec_page = pvec->pages[i];
386
387 if (pagevec_page == page) {
388 SetPageActive(page);
389 break;
390 }
391 }
392
393 local_unlock(&lru_pvecs.lock);
394 }
395
396 #ifdef CONFIG_LRU_GEN
page_inc_refs(struct page * page)397 static void page_inc_refs(struct page *page)
398 {
399 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
400
401 if (PageUnevictable(page))
402 return;
403
404 if (!PageReferenced(page)) {
405 SetPageReferenced(page);
406 return;
407 }
408
409 if (!PageWorkingset(page)) {
410 SetPageWorkingset(page);
411 return;
412 }
413
414 /* see the comment on MAX_NR_TIERS */
415 do {
416 new_flags = old_flags & LRU_REFS_MASK;
417 if (new_flags == LRU_REFS_MASK)
418 break;
419
420 new_flags += BIT(LRU_REFS_PGOFF);
421 new_flags |= old_flags & ~LRU_REFS_MASK;
422 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
423 }
424 #else
page_inc_refs(struct page * page)425 static void page_inc_refs(struct page *page)
426 {
427 }
428 #endif /* CONFIG_LRU_GEN */
429
430 /*
431 * Mark a page as having seen activity.
432 *
433 * inactive,unreferenced -> inactive,referenced
434 * inactive,referenced -> active,unreferenced
435 * active,unreferenced -> active,referenced
436 *
437 * When a newly allocated page is not yet visible, so safe for non-atomic ops,
438 * __SetPageReferenced(page) may be substituted for mark_page_accessed(page).
439 */
mark_page_accessed(struct page * page)440 void mark_page_accessed(struct page *page)
441 {
442 page = compound_head(page);
443
444 if (lru_gen_enabled()) {
445 page_inc_refs(page);
446 return;
447 }
448
449 if (!PageReferenced(page)) {
450 SetPageReferenced(page);
451 } else if (PageUnevictable(page)) {
452 /*
453 * Unevictable pages are on the "LRU_UNEVICTABLE" list. But,
454 * this list is never rotated or maintained, so marking an
455 * evictable page accessed has no effect.
456 */
457 } else if (!PageActive(page)) {
458 /*
459 * If the page is on the LRU, queue it for activation via
460 * lru_pvecs.activate_page. Otherwise, assume the page is on a
461 * pagevec, mark it active and it'll be moved to the active
462 * LRU on the next drain.
463 */
464 if (PageLRU(page))
465 activate_page(page);
466 else
467 __lru_cache_activate_page(page);
468 ClearPageReferenced(page);
469 workingset_activation(page);
470 }
471 if (page_is_idle(page))
472 clear_page_idle(page);
473 }
474 EXPORT_SYMBOL(mark_page_accessed);
475
476 /**
477 * lru_cache_add - add a page to a page list
478 * @page: the page to be added to the LRU.
479 *
480 * Queue the page for addition to the LRU via pagevec. The decision on whether
481 * to add the page to the [in]active [file|anon] list is deferred until the
482 * pagevec is drained. This gives a chance for the caller of lru_cache_add()
483 * have the page added to the active list using mark_page_accessed().
484 */
lru_cache_add(struct page * page)485 void lru_cache_add(struct page *page)
486 {
487 struct pagevec *pvec;
488
489 VM_BUG_ON_PAGE(PageActive(page) && PageUnevictable(page), page);
490 VM_BUG_ON_PAGE(PageLRU(page), page);
491
492 /* see the comment in lru_gen_add_page() */
493 if (lru_gen_enabled() && !PageUnevictable(page) &&
494 lru_gen_in_fault() && !(current->flags & PF_MEMALLOC))
495 SetPageActive(page);
496
497 get_page(page);
498 local_lock(&lru_pvecs.lock);
499 pvec = this_cpu_ptr(&lru_pvecs.lru_add);
500 if (pagevec_add_and_need_flush(pvec, page))
501 __pagevec_lru_add(pvec);
502 local_unlock(&lru_pvecs.lock);
503 }
504 EXPORT_SYMBOL(lru_cache_add);
505
506 /**
507 * lru_cache_add_inactive_or_unevictable
508 * @page: the page to be added to LRU
509 * @vma: vma in which page is mapped for determining reclaimability
510 *
511 * Place @page on the inactive or unevictable LRU list, depending on its
512 * evictability.
513 */
lru_cache_add_inactive_or_unevictable(struct page * page,struct vm_area_struct * vma)514 void lru_cache_add_inactive_or_unevictable(struct page *page,
515 struct vm_area_struct *vma)
516 {
517 bool unevictable;
518
519 VM_BUG_ON_PAGE(PageLRU(page), page);
520
521 unevictable = (vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) == VM_LOCKED;
522 if (unlikely(unevictable) && !TestSetPageMlocked(page)) {
523 int nr_pages = thp_nr_pages(page);
524 /*
525 * We use the irq-unsafe __mod_zone_page_state because this
526 * counter is not modified from interrupt context, and the pte
527 * lock is held(spinlock), which implies preemption disabled.
528 */
529 __mod_zone_page_state(page_zone(page), NR_MLOCK, nr_pages);
530 count_vm_events(UNEVICTABLE_PGMLOCKED, nr_pages);
531 }
532 lru_cache_add(page);
533 }
534
535 /*
536 * If the page can not be invalidated, it is moved to the
537 * inactive list to speed up its reclaim. It is moved to the
538 * head of the list, rather than the tail, to give the flusher
539 * threads some time to write it out, as this is much more
540 * effective than the single-page writeout from reclaim.
541 *
542 * If the page isn't page_mapped and dirty/writeback, the page
543 * could reclaim asap using PG_reclaim.
544 *
545 * 1. active, mapped page -> none
546 * 2. active, dirty/writeback page -> inactive, head, PG_reclaim
547 * 3. inactive, mapped page -> none
548 * 4. inactive, dirty/writeback page -> inactive, head, PG_reclaim
549 * 5. inactive, clean -> inactive, tail
550 * 6. Others -> none
551 *
552 * In 4, why it moves inactive's head, the VM expects the page would
553 * be write it out by flusher threads as this is much more effective
554 * than the single-page writeout from reclaim.
555 */
lru_deactivate_file_fn(struct page * page,struct lruvec * lruvec)556 static void lru_deactivate_file_fn(struct page *page, struct lruvec *lruvec)
557 {
558 bool active = PageActive(page);
559 int nr_pages = thp_nr_pages(page);
560
561 if (PageUnevictable(page))
562 return;
563
564 /* Some processes are using the page */
565 if (page_mapped(page))
566 return;
567
568 del_page_from_lru_list(page, lruvec);
569 ClearPageActive(page);
570 ClearPageReferenced(page);
571
572 if (PageWriteback(page) || PageDirty(page)) {
573 /*
574 * PG_reclaim could be raced with end_page_writeback
575 * It can make readahead confusing. But race window
576 * is _really_ small and it's non-critical problem.
577 */
578 add_page_to_lru_list(page, lruvec);
579 SetPageReclaim(page);
580 } else {
581 /*
582 * The page's writeback ends up during pagevec
583 * We move that page into tail of inactive.
584 */
585 add_page_to_lru_list_tail(page, lruvec);
586 __count_vm_events(PGROTATED, nr_pages);
587 }
588
589 if (active) {
590 __count_vm_events(PGDEACTIVATE, nr_pages);
591 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
592 nr_pages);
593 }
594 }
595
lru_deactivate_fn(struct page * page,struct lruvec * lruvec)596 static void lru_deactivate_fn(struct page *page, struct lruvec *lruvec)
597 {
598 if (!PageUnevictable(page) && (PageActive(page) || lru_gen_enabled())) {
599 int nr_pages = thp_nr_pages(page);
600
601 del_page_from_lru_list(page, lruvec);
602 ClearPageActive(page);
603 ClearPageReferenced(page);
604 add_page_to_lru_list(page, lruvec);
605
606 __count_vm_events(PGDEACTIVATE, nr_pages);
607 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
608 nr_pages);
609 }
610 }
611
lru_lazyfree_fn(struct page * page,struct lruvec * lruvec)612 static void lru_lazyfree_fn(struct page *page, struct lruvec *lruvec)
613 {
614 if (PageAnon(page) && PageSwapBacked(page) &&
615 !PageSwapCache(page) && !PageUnevictable(page)) {
616 int nr_pages = thp_nr_pages(page);
617
618 del_page_from_lru_list(page, lruvec);
619 ClearPageActive(page);
620 ClearPageReferenced(page);
621 /*
622 * Lazyfree pages are clean anonymous pages. They have
623 * PG_swapbacked flag cleared, to distinguish them from normal
624 * anonymous pages
625 */
626 ClearPageSwapBacked(page);
627 add_page_to_lru_list(page, lruvec);
628
629 __count_vm_events(PGLAZYFREE, nr_pages);
630 __count_memcg_events(lruvec_memcg(lruvec), PGLAZYFREE,
631 nr_pages);
632 }
633 }
634
635 /*
636 * Drain pages out of the cpu's pagevecs.
637 * Either "cpu" is the current CPU, and preemption has already been
638 * disabled; or "cpu" is being hot-unplugged, and is already dead.
639 */
lru_add_drain_cpu(int cpu)640 void lru_add_drain_cpu(int cpu)
641 {
642 struct pagevec *pvec = &per_cpu(lru_pvecs.lru_add, cpu);
643
644 if (pagevec_count(pvec))
645 __pagevec_lru_add(pvec);
646
647 pvec = &per_cpu(lru_rotate.pvec, cpu);
648 /* Disabling interrupts below acts as a compiler barrier. */
649 if (data_race(pagevec_count(pvec))) {
650 unsigned long flags;
651
652 /* No harm done if a racing interrupt already did this */
653 local_lock_irqsave(&lru_rotate.lock, flags);
654 pagevec_lru_move_fn(pvec, pagevec_move_tail_fn);
655 local_unlock_irqrestore(&lru_rotate.lock, flags);
656 }
657
658 pvec = &per_cpu(lru_pvecs.lru_deactivate_file, cpu);
659 if (pagevec_count(pvec))
660 pagevec_lru_move_fn(pvec, lru_deactivate_file_fn);
661
662 pvec = &per_cpu(lru_pvecs.lru_deactivate, cpu);
663 if (pagevec_count(pvec))
664 pagevec_lru_move_fn(pvec, lru_deactivate_fn);
665
666 pvec = &per_cpu(lru_pvecs.lru_lazyfree, cpu);
667 if (pagevec_count(pvec))
668 pagevec_lru_move_fn(pvec, lru_lazyfree_fn);
669
670 activate_page_drain(cpu);
671 }
672
673 /**
674 * deactivate_file_page - forcefully deactivate a file page
675 * @page: page to deactivate
676 *
677 * This function hints the VM that @page is a good reclaim candidate,
678 * for example if its invalidation fails due to the page being dirty
679 * or under writeback.
680 */
deactivate_file_page(struct page * page)681 void deactivate_file_page(struct page *page)
682 {
683 /*
684 * In a workload with many unevictable page such as mprotect,
685 * unevictable page deactivation for accelerating reclaim is pointless.
686 */
687 if (PageUnevictable(page))
688 return;
689
690 if (likely(get_page_unless_zero(page))) {
691 struct pagevec *pvec;
692
693 local_lock(&lru_pvecs.lock);
694 pvec = this_cpu_ptr(&lru_pvecs.lru_deactivate_file);
695
696 if (pagevec_add_and_need_flush(pvec, page))
697 pagevec_lru_move_fn(pvec, lru_deactivate_file_fn);
698 local_unlock(&lru_pvecs.lock);
699 }
700 }
701
702 /*
703 * deactivate_page - deactivate a page
704 * @page: page to deactivate
705 *
706 * deactivate_page() moves @page to the inactive list if @page was on the active
707 * list and was not an unevictable page. This is done to accelerate the reclaim
708 * of @page.
709 */
deactivate_page(struct page * page)710 void deactivate_page(struct page *page)
711 {
712 if (PageLRU(page) && !PageUnevictable(page) &&
713 (PageActive(page) || lru_gen_enabled())) {
714 struct pagevec *pvec;
715
716 local_lock(&lru_pvecs.lock);
717 pvec = this_cpu_ptr(&lru_pvecs.lru_deactivate);
718 get_page(page);
719 if (pagevec_add_and_need_flush(pvec, page))
720 pagevec_lru_move_fn(pvec, lru_deactivate_fn);
721 local_unlock(&lru_pvecs.lock);
722 }
723 }
724
725 /**
726 * mark_page_lazyfree - make an anon page lazyfree
727 * @page: page to deactivate
728 *
729 * mark_page_lazyfree() moves @page to the inactive file list.
730 * This is done to accelerate the reclaim of @page.
731 */
mark_page_lazyfree(struct page * page)732 void mark_page_lazyfree(struct page *page)
733 {
734 if (PageLRU(page) && PageAnon(page) && PageSwapBacked(page) &&
735 !PageSwapCache(page) && !PageUnevictable(page)) {
736 struct pagevec *pvec;
737
738 local_lock(&lru_pvecs.lock);
739 pvec = this_cpu_ptr(&lru_pvecs.lru_lazyfree);
740 get_page(page);
741 if (pagevec_add_and_need_flush(pvec, page))
742 pagevec_lru_move_fn(pvec, lru_lazyfree_fn);
743 local_unlock(&lru_pvecs.lock);
744 }
745 }
746
lru_add_drain(void)747 void lru_add_drain(void)
748 {
749 local_lock(&lru_pvecs.lock);
750 lru_add_drain_cpu(smp_processor_id());
751 local_unlock(&lru_pvecs.lock);
752 }
753
754 /*
755 * It's called from per-cpu workqueue context in SMP case so
756 * lru_add_drain_cpu and invalidate_bh_lrus_cpu should run on
757 * the same cpu. It shouldn't be a problem in !SMP case since
758 * the core is only one and the locks will disable preemption.
759 */
lru_add_and_bh_lrus_drain(void)760 static void lru_add_and_bh_lrus_drain(void)
761 {
762 local_lock(&lru_pvecs.lock);
763 lru_add_drain_cpu(smp_processor_id());
764 local_unlock(&lru_pvecs.lock);
765 invalidate_bh_lrus_cpu();
766 }
767
lru_add_drain_cpu_zone(struct zone * zone)768 void lru_add_drain_cpu_zone(struct zone *zone)
769 {
770 local_lock(&lru_pvecs.lock);
771 lru_add_drain_cpu(smp_processor_id());
772 drain_local_pages(zone);
773 local_unlock(&lru_pvecs.lock);
774 }
775
776 #ifdef CONFIG_SMP
777
778 static DEFINE_PER_CPU(struct work_struct, lru_add_drain_work);
779
lru_add_drain_per_cpu(struct work_struct * dummy)780 static void lru_add_drain_per_cpu(struct work_struct *dummy)
781 {
782 lru_add_and_bh_lrus_drain();
783 }
784
785 /*
786 * Doesn't need any cpu hotplug locking because we do rely on per-cpu
787 * kworkers being shut down before our page_alloc_cpu_dead callback is
788 * executed on the offlined cpu.
789 * Calling this function with cpu hotplug locks held can actually lead
790 * to obscure indirect dependencies via WQ context.
791 */
__lru_add_drain_all(bool force_all_cpus)792 inline void __lru_add_drain_all(bool force_all_cpus)
793 {
794 /*
795 * lru_drain_gen - Global pages generation number
796 *
797 * (A) Definition: global lru_drain_gen = x implies that all generations
798 * 0 < n <= x are already *scheduled* for draining.
799 *
800 * This is an optimization for the highly-contended use case where a
801 * user space workload keeps constantly generating a flow of pages for
802 * each CPU.
803 */
804 static unsigned int lru_drain_gen;
805 static struct cpumask has_work;
806 static DEFINE_MUTEX(lock);
807 unsigned cpu, this_gen;
808
809 /*
810 * Make sure nobody triggers this path before mm_percpu_wq is fully
811 * initialized.
812 */
813 if (WARN_ON(!mm_percpu_wq))
814 return;
815
816 /*
817 * Guarantee pagevec counter stores visible by this CPU are visible to
818 * other CPUs before loading the current drain generation.
819 */
820 smp_mb();
821
822 /*
823 * (B) Locally cache global LRU draining generation number
824 *
825 * The read barrier ensures that the counter is loaded before the mutex
826 * is taken. It pairs with smp_mb() inside the mutex critical section
827 * at (D).
828 */
829 this_gen = smp_load_acquire(&lru_drain_gen);
830
831 mutex_lock(&lock);
832
833 /*
834 * (C) Exit the draining operation if a newer generation, from another
835 * lru_add_drain_all(), was already scheduled for draining. Check (A).
836 */
837 if (unlikely(this_gen != lru_drain_gen && !force_all_cpus))
838 goto done;
839
840 /*
841 * (D) Increment global generation number
842 *
843 * Pairs with smp_load_acquire() at (B), outside of the critical
844 * section. Use a full memory barrier to guarantee that the new global
845 * drain generation number is stored before loading pagevec counters.
846 *
847 * This pairing must be done here, before the for_each_online_cpu loop
848 * below which drains the page vectors.
849 *
850 * Let x, y, and z represent some system CPU numbers, where x < y < z.
851 * Assume CPU #z is in the middle of the for_each_online_cpu loop
852 * below and has already reached CPU #y's per-cpu data. CPU #x comes
853 * along, adds some pages to its per-cpu vectors, then calls
854 * lru_add_drain_all().
855 *
856 * If the paired barrier is done at any later step, e.g. after the
857 * loop, CPU #x will just exit at (C) and miss flushing out all of its
858 * added pages.
859 */
860 WRITE_ONCE(lru_drain_gen, lru_drain_gen + 1);
861 smp_mb();
862
863 cpumask_clear(&has_work);
864 for_each_online_cpu(cpu) {
865 struct work_struct *work = &per_cpu(lru_add_drain_work, cpu);
866
867 if (force_all_cpus ||
868 pagevec_count(&per_cpu(lru_pvecs.lru_add, cpu)) ||
869 data_race(pagevec_count(&per_cpu(lru_rotate.pvec, cpu))) ||
870 pagevec_count(&per_cpu(lru_pvecs.lru_deactivate_file, cpu)) ||
871 pagevec_count(&per_cpu(lru_pvecs.lru_deactivate, cpu)) ||
872 pagevec_count(&per_cpu(lru_pvecs.lru_lazyfree, cpu)) ||
873 need_activate_page_drain(cpu) ||
874 has_bh_in_lru(cpu, NULL)) {
875 INIT_WORK(work, lru_add_drain_per_cpu);
876 queue_work_on(cpu, mm_percpu_wq, work);
877 __cpumask_set_cpu(cpu, &has_work);
878 }
879 }
880
881 for_each_cpu(cpu, &has_work)
882 flush_work(&per_cpu(lru_add_drain_work, cpu));
883
884 done:
885 mutex_unlock(&lock);
886 }
887
lru_add_drain_all(void)888 void lru_add_drain_all(void)
889 {
890 __lru_add_drain_all(false);
891 }
892 #else
lru_add_drain_all(void)893 void lru_add_drain_all(void)
894 {
895 lru_add_drain();
896 }
897 #endif /* CONFIG_SMP */
898
899 static atomic_t lru_disable_count = ATOMIC_INIT(0);
900
lru_cache_disabled(void)901 bool lru_cache_disabled(void)
902 {
903 return atomic_read(&lru_disable_count) != 0;
904 }
905
lru_cache_enable(void)906 void lru_cache_enable(void)
907 {
908 atomic_dec(&lru_disable_count);
909 }
910 EXPORT_SYMBOL_GPL(lru_cache_enable);
911
912 /*
913 * lru_cache_disable() needs to be called before we start compiling
914 * a list of pages to be migrated using isolate_lru_page().
915 * It drains pages on LRU cache and then disable on all cpus until
916 * lru_cache_enable is called.
917 *
918 * Must be paired with a call to lru_cache_enable().
919 */
lru_cache_disable(void)920 void lru_cache_disable(void)
921 {
922 /*
923 * If someone is already disabled lru_cache, just return with
924 * increasing the lru_disable_count.
925 */
926 if (atomic_inc_not_zero(&lru_disable_count))
927 return;
928 #ifdef CONFIG_SMP
929 /*
930 * lru_add_drain_all in the force mode will schedule draining on
931 * all online CPUs so any calls of lru_cache_disabled wrapped by
932 * local_lock or preemption disabled would be ordered by that.
933 * The atomic operation doesn't need to have stronger ordering
934 * requirements because that is enforeced by the scheduling
935 * guarantees.
936 */
937 __lru_add_drain_all(true);
938 #else
939 lru_add_and_bh_lrus_drain();
940 #endif
941 atomic_inc(&lru_disable_count);
942 }
943 EXPORT_SYMBOL_GPL(lru_cache_disable);
944
945 /**
946 * release_pages - batched put_page()
947 * @pages: array of pages to release
948 * @nr: number of pages
949 *
950 * Decrement the reference count on all the pages in @pages. If it
951 * fell to zero, remove the page from the LRU and free it.
952 */
release_pages(struct page ** pages,int nr)953 void release_pages(struct page **pages, int nr)
954 {
955 int i;
956 LIST_HEAD(pages_to_free);
957 struct lruvec *lruvec = NULL;
958 unsigned long flags;
959 unsigned int lock_batch;
960
961 for (i = 0; i < nr; i++) {
962 struct page *page = pages[i];
963
964 /*
965 * Make sure the IRQ-safe lock-holding time does not get
966 * excessive with a continuous string of pages from the
967 * same lruvec. The lock is held only if lruvec != NULL.
968 */
969 if (lruvec && ++lock_batch == SWAP_CLUSTER_MAX) {
970 unlock_page_lruvec_irqrestore(lruvec, flags);
971 lruvec = NULL;
972 }
973
974 page = compound_head(page);
975 if (is_huge_zero_page(page))
976 continue;
977
978 if (is_zone_device_page(page)) {
979 if (lruvec) {
980 unlock_page_lruvec_irqrestore(lruvec, flags);
981 lruvec = NULL;
982 }
983 /*
984 * ZONE_DEVICE pages that return 'false' from
985 * page_is_devmap_managed() do not require special
986 * processing, and instead, expect a call to
987 * put_page_testzero().
988 */
989 if (page_is_devmap_managed(page)) {
990 put_devmap_managed_page(page);
991 continue;
992 }
993 if (put_page_testzero(page))
994 put_dev_pagemap(page->pgmap);
995 continue;
996 }
997
998 if (!put_page_testzero(page))
999 continue;
1000
1001 if (PageCompound(page)) {
1002 if (lruvec) {
1003 unlock_page_lruvec_irqrestore(lruvec, flags);
1004 lruvec = NULL;
1005 }
1006 __put_compound_page(page);
1007 continue;
1008 }
1009
1010 if (PageLRU(page)) {
1011 struct lruvec *prev_lruvec = lruvec;
1012
1013 lruvec = relock_page_lruvec_irqsave(page, lruvec,
1014 &flags);
1015 if (prev_lruvec != lruvec)
1016 lock_batch = 0;
1017
1018 del_page_from_lru_list(page, lruvec);
1019 __clear_page_lru_flags(page);
1020 }
1021
1022 __ClearPageWaiters(page);
1023
1024 list_add(&page->lru, &pages_to_free);
1025 }
1026 if (lruvec)
1027 unlock_page_lruvec_irqrestore(lruvec, flags);
1028
1029 mem_cgroup_uncharge_list(&pages_to_free);
1030 free_unref_page_list(&pages_to_free);
1031 }
1032 EXPORT_SYMBOL(release_pages);
1033
1034 /*
1035 * The pages which we're about to release may be in the deferred lru-addition
1036 * queues. That would prevent them from really being freed right now. That's
1037 * OK from a correctness point of view but is inefficient - those pages may be
1038 * cache-warm and we want to give them back to the page allocator ASAP.
1039 *
1040 * So __pagevec_release() will drain those queues here. __pagevec_lru_add()
1041 * and __pagevec_lru_add_active() call release_pages() directly to avoid
1042 * mutual recursion.
1043 */
__pagevec_release(struct pagevec * pvec)1044 void __pagevec_release(struct pagevec *pvec)
1045 {
1046 if (!pvec->percpu_pvec_drained) {
1047 lru_add_drain();
1048 pvec->percpu_pvec_drained = true;
1049 }
1050 release_pages(pvec->pages, pagevec_count(pvec));
1051 pagevec_reinit(pvec);
1052 }
1053 EXPORT_SYMBOL(__pagevec_release);
1054
__pagevec_lru_add_fn(struct page * page,struct lruvec * lruvec)1055 static void __pagevec_lru_add_fn(struct page *page, struct lruvec *lruvec)
1056 {
1057 int was_unevictable = TestClearPageUnevictable(page);
1058 int nr_pages = thp_nr_pages(page);
1059
1060 VM_BUG_ON_PAGE(PageLRU(page), page);
1061
1062 /*
1063 * Page becomes evictable in two ways:
1064 * 1) Within LRU lock [munlock_vma_page() and __munlock_pagevec()].
1065 * 2) Before acquiring LRU lock to put the page to correct LRU and then
1066 * a) do PageLRU check with lock [check_move_unevictable_pages]
1067 * b) do PageLRU check before lock [clear_page_mlock]
1068 *
1069 * (1) & (2a) are ok as LRU lock will serialize them. For (2b), we need
1070 * following strict ordering:
1071 *
1072 * #0: __pagevec_lru_add_fn #1: clear_page_mlock
1073 *
1074 * SetPageLRU() TestClearPageMlocked()
1075 * smp_mb() // explicit ordering // above provides strict
1076 * // ordering
1077 * PageMlocked() PageLRU()
1078 *
1079 *
1080 * if '#1' does not observe setting of PG_lru by '#0' and fails
1081 * isolation, the explicit barrier will make sure that page_evictable
1082 * check will put the page in correct LRU. Without smp_mb(), SetPageLRU
1083 * can be reordered after PageMlocked check and can make '#1' to fail
1084 * the isolation of the page whose Mlocked bit is cleared (#0 is also
1085 * looking at the same page) and the evictable page will be stranded
1086 * in an unevictable LRU.
1087 */
1088 SetPageLRU(page);
1089 smp_mb__after_atomic();
1090
1091 if (page_evictable(page)) {
1092 if (was_unevictable)
1093 __count_vm_events(UNEVICTABLE_PGRESCUED, nr_pages);
1094 } else {
1095 ClearPageActive(page);
1096 SetPageUnevictable(page);
1097 if (!was_unevictable)
1098 __count_vm_events(UNEVICTABLE_PGCULLED, nr_pages);
1099 }
1100
1101 add_page_to_lru_list(page, lruvec);
1102 trace_mm_lru_insertion(page);
1103 }
1104
1105 /*
1106 * Add the passed pages to the LRU, then drop the caller's refcount
1107 * on them. Reinitialises the caller's pagevec.
1108 */
__pagevec_lru_add(struct pagevec * pvec)1109 void __pagevec_lru_add(struct pagevec *pvec)
1110 {
1111 int i;
1112 struct lruvec *lruvec = NULL;
1113 unsigned long flags = 0;
1114
1115 for (i = 0; i < pagevec_count(pvec); i++) {
1116 struct page *page = pvec->pages[i];
1117
1118 lruvec = relock_page_lruvec_irqsave(page, lruvec, &flags);
1119 __pagevec_lru_add_fn(page, lruvec);
1120 }
1121 if (lruvec)
1122 unlock_page_lruvec_irqrestore(lruvec, flags);
1123 release_pages(pvec->pages, pvec->nr);
1124 pagevec_reinit(pvec);
1125 }
1126
1127 /**
1128 * pagevec_remove_exceptionals - pagevec exceptionals pruning
1129 * @pvec: The pagevec to prune
1130 *
1131 * find_get_entries() fills both pages and XArray value entries (aka
1132 * exceptional entries) into the pagevec. This function prunes all
1133 * exceptionals from @pvec without leaving holes, so that it can be
1134 * passed on to page-only pagevec operations.
1135 */
pagevec_remove_exceptionals(struct pagevec * pvec)1136 void pagevec_remove_exceptionals(struct pagevec *pvec)
1137 {
1138 int i, j;
1139
1140 for (i = 0, j = 0; i < pagevec_count(pvec); i++) {
1141 struct page *page = pvec->pages[i];
1142 if (!xa_is_value(page))
1143 pvec->pages[j++] = page;
1144 }
1145 pvec->nr = j;
1146 }
1147
1148 /**
1149 * pagevec_lookup_range - gang pagecache lookup
1150 * @pvec: Where the resulting pages are placed
1151 * @mapping: The address_space to search
1152 * @start: The starting page index
1153 * @end: The final page index
1154 *
1155 * pagevec_lookup_range() will search for & return a group of up to PAGEVEC_SIZE
1156 * pages in the mapping starting from index @start and upto index @end
1157 * (inclusive). The pages are placed in @pvec. pagevec_lookup() takes a
1158 * reference against the pages in @pvec.
1159 *
1160 * The search returns a group of mapping-contiguous pages with ascending
1161 * indexes. There may be holes in the indices due to not-present pages. We
1162 * also update @start to index the next page for the traversal.
1163 *
1164 * pagevec_lookup_range() returns the number of pages which were found. If this
1165 * number is smaller than PAGEVEC_SIZE, the end of specified range has been
1166 * reached.
1167 */
pagevec_lookup_range(struct pagevec * pvec,struct address_space * mapping,pgoff_t * start,pgoff_t end)1168 unsigned pagevec_lookup_range(struct pagevec *pvec,
1169 struct address_space *mapping, pgoff_t *start, pgoff_t end)
1170 {
1171 pvec->nr = find_get_pages_range(mapping, start, end, PAGEVEC_SIZE,
1172 pvec->pages);
1173 return pagevec_count(pvec);
1174 }
1175 EXPORT_SYMBOL(pagevec_lookup_range);
1176
pagevec_lookup_range_tag(struct pagevec * pvec,struct address_space * mapping,pgoff_t * index,pgoff_t end,xa_mark_t tag)1177 unsigned pagevec_lookup_range_tag(struct pagevec *pvec,
1178 struct address_space *mapping, pgoff_t *index, pgoff_t end,
1179 xa_mark_t tag)
1180 {
1181 pvec->nr = find_get_pages_range_tag(mapping, index, end, tag,
1182 PAGEVEC_SIZE, pvec->pages);
1183 return pagevec_count(pvec);
1184 }
1185 EXPORT_SYMBOL(pagevec_lookup_range_tag);
1186
1187 /*
1188 * Perform any setup for the swap system
1189 */
swap_setup(void)1190 void __init swap_setup(void)
1191 {
1192 unsigned long megs = totalram_pages() >> (20 - PAGE_SHIFT);
1193
1194 /* Use a smaller cluster for small-memory machines */
1195 if (megs < 16)
1196 page_cluster = 2;
1197 else
1198 page_cluster = 3;
1199 /*
1200 * Right now other parts of the system means that we
1201 * _really_ don't want to cluster much more
1202 */
1203 }
1204
1205 #ifdef CONFIG_DEV_PAGEMAP_OPS
put_devmap_managed_page(struct page * page)1206 void put_devmap_managed_page(struct page *page)
1207 {
1208 int count;
1209
1210 if (WARN_ON_ONCE(!page_is_devmap_managed(page)))
1211 return;
1212
1213 count = page_ref_dec_return(page);
1214
1215 /*
1216 * devmap page refcounts are 1-based, rather than 0-based: if
1217 * refcount is 1, then the page is free and the refcount is
1218 * stable because nobody holds a reference on the page.
1219 */
1220 if (count == 1)
1221 free_devmap_managed_page(page);
1222 else if (!count)
1223 __put_page(page);
1224 }
1225 EXPORT_SYMBOL(put_devmap_managed_page);
1226 #endif
1227