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