xref: /linux/mm/memory.c (revision 38b8cb7fbb892503fe9fcf748ebbed8c9fde7bf8)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/mm/memory.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
51da177e4SLinus Torvalds  */
61da177e4SLinus Torvalds 
71da177e4SLinus Torvalds /*
81da177e4SLinus Torvalds  * demand-loading started 01.12.91 - seems it is high on the list of
91da177e4SLinus Torvalds  * things wanted, and it should be easy to implement. - Linus
101da177e4SLinus Torvalds  */
111da177e4SLinus Torvalds 
121da177e4SLinus Torvalds /*
131da177e4SLinus Torvalds  * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
141da177e4SLinus Torvalds  * pages started 02.12.91, seems to work. - Linus.
151da177e4SLinus Torvalds  *
161da177e4SLinus Torvalds  * Tested sharing by executing about 30 /bin/sh: under the old kernel it
171da177e4SLinus Torvalds  * would have taken more than the 6M I have free, but it worked well as
181da177e4SLinus Torvalds  * far as I could see.
191da177e4SLinus Torvalds  *
201da177e4SLinus Torvalds  * Also corrected some "invalidate()"s - I wasn't doing enough of them.
211da177e4SLinus Torvalds  */
221da177e4SLinus Torvalds 
231da177e4SLinus Torvalds /*
241da177e4SLinus Torvalds  * Real VM (paging to/from disk) started 18.12.91. Much more work and
251da177e4SLinus Torvalds  * thought has to go into this. Oh, well..
261da177e4SLinus Torvalds  * 19.12.91  -  works, somewhat. Sometimes I get faults, don't know why.
271da177e4SLinus Torvalds  *		Found it. Everything seems to work now.
281da177e4SLinus Torvalds  * 20.12.91  -  Ok, making the swap-device changeable like the root.
291da177e4SLinus Torvalds  */
301da177e4SLinus Torvalds 
311da177e4SLinus Torvalds /*
321da177e4SLinus Torvalds  * 05.04.94  -  Multi-page memory management added for v1.1.
331da177e4SLinus Torvalds  * 		Idea by Alex Bligh (alex@cconcepts.co.uk)
341da177e4SLinus Torvalds  *
351da177e4SLinus Torvalds  * 16.07.99  -  Support of BIGMEM added by Gerhard Wichert, Siemens AG
361da177e4SLinus Torvalds  *		(Gerhard.Wichert@pdb.siemens.de)
371da177e4SLinus Torvalds  *
381da177e4SLinus Torvalds  * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
391da177e4SLinus Torvalds  */
401da177e4SLinus Torvalds 
411da177e4SLinus Torvalds #include <linux/kernel_stat.h>
421da177e4SLinus Torvalds #include <linux/mm.h>
431da177e4SLinus Torvalds #include <linux/hugetlb.h>
441da177e4SLinus Torvalds #include <linux/mman.h>
451da177e4SLinus Torvalds #include <linux/swap.h>
461da177e4SLinus Torvalds #include <linux/highmem.h>
471da177e4SLinus Torvalds #include <linux/pagemap.h>
489a840895SHugh Dickins #include <linux/ksm.h>
491da177e4SLinus Torvalds #include <linux/rmap.h>
50b95f1b31SPaul Gortmaker #include <linux/export.h>
510ff92245SShailabh Nagar #include <linux/delayacct.h>
521da177e4SLinus Torvalds #include <linux/init.h>
5301c8f1c4SDan Williams #include <linux/pfn_t.h>
54edc79b2aSPeter Zijlstra #include <linux/writeback.h>
558a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
56cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
573dc14741SHugh Dickins #include <linux/kallsyms.h>
583dc14741SHugh Dickins #include <linux/swapops.h>
593dc14741SHugh Dickins #include <linux/elf.h>
605a0e3ad6STejun Heo #include <linux/gfp.h>
614daae3b4SMel Gorman #include <linux/migrate.h>
622fbc57c5SAndy Shevchenko #include <linux/string.h>
630abdd7a8SDan Williams #include <linux/dma-debug.h>
641592eef0SKirill A. Shutemov #include <linux/debugfs.h>
656b251fc9SAndrea Arcangeli #include <linux/userfaultfd_k.h>
66bc2466e4SJan Kara #include <linux/dax.h>
671da177e4SLinus Torvalds 
686952b61dSAlexey Dobriyan #include <asm/io.h>
6933a709b2SDave Hansen #include <asm/mmu_context.h>
701da177e4SLinus Torvalds #include <asm/pgalloc.h>
711da177e4SLinus Torvalds #include <asm/uaccess.h>
721da177e4SLinus Torvalds #include <asm/tlb.h>
731da177e4SLinus Torvalds #include <asm/tlbflush.h>
741da177e4SLinus Torvalds #include <asm/pgtable.h>
751da177e4SLinus Torvalds 
7642b77728SJan Beulich #include "internal.h"
7742b77728SJan Beulich 
7890572890SPeter Zijlstra #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
7990572890SPeter Zijlstra #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
8075980e97SPeter Zijlstra #endif
8175980e97SPeter Zijlstra 
82d41dee36SAndy Whitcroft #ifndef CONFIG_NEED_MULTIPLE_NODES
831da177e4SLinus Torvalds /* use the per-pgdat data instead for discontigmem - mbligh */
841da177e4SLinus Torvalds unsigned long max_mapnr;
851da177e4SLinus Torvalds struct page *mem_map;
861da177e4SLinus Torvalds 
871da177e4SLinus Torvalds EXPORT_SYMBOL(max_mapnr);
881da177e4SLinus Torvalds EXPORT_SYMBOL(mem_map);
891da177e4SLinus Torvalds #endif
901da177e4SLinus Torvalds 
911da177e4SLinus Torvalds /*
921da177e4SLinus Torvalds  * A number of key systems in x86 including ioremap() rely on the assumption
931da177e4SLinus Torvalds  * that high_memory defines the upper bound on direct map memory, then end
941da177e4SLinus Torvalds  * of ZONE_NORMAL.  Under CONFIG_DISCONTIG this means that max_low_pfn and
951da177e4SLinus Torvalds  * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
961da177e4SLinus Torvalds  * and ZONE_HIGHMEM.
971da177e4SLinus Torvalds  */
981da177e4SLinus Torvalds void * high_memory;
991da177e4SLinus Torvalds 
1001da177e4SLinus Torvalds EXPORT_SYMBOL(high_memory);
1011da177e4SLinus Torvalds 
10232a93233SIngo Molnar /*
10332a93233SIngo Molnar  * Randomize the address space (stacks, mmaps, brk, etc.).
10432a93233SIngo Molnar  *
10532a93233SIngo Molnar  * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
10632a93233SIngo Molnar  *   as ancient (libc5 based) binaries can segfault. )
10732a93233SIngo Molnar  */
10832a93233SIngo Molnar int randomize_va_space __read_mostly =
10932a93233SIngo Molnar #ifdef CONFIG_COMPAT_BRK
11032a93233SIngo Molnar 					1;
11132a93233SIngo Molnar #else
11232a93233SIngo Molnar 					2;
11332a93233SIngo Molnar #endif
114a62eaf15SAndi Kleen 
115a62eaf15SAndi Kleen static int __init disable_randmaps(char *s)
116a62eaf15SAndi Kleen {
117a62eaf15SAndi Kleen 	randomize_va_space = 0;
1189b41046cSOGAWA Hirofumi 	return 1;
119a62eaf15SAndi Kleen }
120a62eaf15SAndi Kleen __setup("norandmaps", disable_randmaps);
121a62eaf15SAndi Kleen 
12262eede62SHugh Dickins unsigned long zero_pfn __read_mostly;
12303f6462aSHugh Dickins unsigned long highest_memmap_pfn __read_mostly;
124a13ea5b7SHugh Dickins 
1250b70068eSArd Biesheuvel EXPORT_SYMBOL(zero_pfn);
1260b70068eSArd Biesheuvel 
127a13ea5b7SHugh Dickins /*
128a13ea5b7SHugh Dickins  * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
129a13ea5b7SHugh Dickins  */
130a13ea5b7SHugh Dickins static int __init init_zero_pfn(void)
131a13ea5b7SHugh Dickins {
132a13ea5b7SHugh Dickins 	zero_pfn = page_to_pfn(ZERO_PAGE(0));
133a13ea5b7SHugh Dickins 	return 0;
134a13ea5b7SHugh Dickins }
135a13ea5b7SHugh Dickins core_initcall(init_zero_pfn);
136a62eaf15SAndi Kleen 
137d559db08SKAMEZAWA Hiroyuki 
13834e55232SKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
13934e55232SKAMEZAWA Hiroyuki 
140ea48cf78SDavid Rientjes void sync_mm_rss(struct mm_struct *mm)
14134e55232SKAMEZAWA Hiroyuki {
14234e55232SKAMEZAWA Hiroyuki 	int i;
14334e55232SKAMEZAWA Hiroyuki 
14434e55232SKAMEZAWA Hiroyuki 	for (i = 0; i < NR_MM_COUNTERS; i++) {
14505af2e10SDavid Rientjes 		if (current->rss_stat.count[i]) {
14605af2e10SDavid Rientjes 			add_mm_counter(mm, i, current->rss_stat.count[i]);
14705af2e10SDavid Rientjes 			current->rss_stat.count[i] = 0;
14834e55232SKAMEZAWA Hiroyuki 		}
14934e55232SKAMEZAWA Hiroyuki 	}
15005af2e10SDavid Rientjes 	current->rss_stat.events = 0;
15134e55232SKAMEZAWA Hiroyuki }
15234e55232SKAMEZAWA Hiroyuki 
15334e55232SKAMEZAWA Hiroyuki static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
15434e55232SKAMEZAWA Hiroyuki {
15534e55232SKAMEZAWA Hiroyuki 	struct task_struct *task = current;
15634e55232SKAMEZAWA Hiroyuki 
15734e55232SKAMEZAWA Hiroyuki 	if (likely(task->mm == mm))
15834e55232SKAMEZAWA Hiroyuki 		task->rss_stat.count[member] += val;
15934e55232SKAMEZAWA Hiroyuki 	else
16034e55232SKAMEZAWA Hiroyuki 		add_mm_counter(mm, member, val);
16134e55232SKAMEZAWA Hiroyuki }
16234e55232SKAMEZAWA Hiroyuki #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
16334e55232SKAMEZAWA Hiroyuki #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
16434e55232SKAMEZAWA Hiroyuki 
16534e55232SKAMEZAWA Hiroyuki /* sync counter once per 64 page faults */
16634e55232SKAMEZAWA Hiroyuki #define TASK_RSS_EVENTS_THRESH	(64)
16734e55232SKAMEZAWA Hiroyuki static void check_sync_rss_stat(struct task_struct *task)
16834e55232SKAMEZAWA Hiroyuki {
16934e55232SKAMEZAWA Hiroyuki 	if (unlikely(task != current))
17034e55232SKAMEZAWA Hiroyuki 		return;
17134e55232SKAMEZAWA Hiroyuki 	if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
172ea48cf78SDavid Rientjes 		sync_mm_rss(task->mm);
17334e55232SKAMEZAWA Hiroyuki }
1749547d01bSPeter Zijlstra #else /* SPLIT_RSS_COUNTING */
17534e55232SKAMEZAWA Hiroyuki 
17634e55232SKAMEZAWA Hiroyuki #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
17734e55232SKAMEZAWA Hiroyuki #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
17834e55232SKAMEZAWA Hiroyuki 
17934e55232SKAMEZAWA Hiroyuki static void check_sync_rss_stat(struct task_struct *task)
18034e55232SKAMEZAWA Hiroyuki {
18134e55232SKAMEZAWA Hiroyuki }
18234e55232SKAMEZAWA Hiroyuki 
1839547d01bSPeter Zijlstra #endif /* SPLIT_RSS_COUNTING */
1849547d01bSPeter Zijlstra 
1859547d01bSPeter Zijlstra #ifdef HAVE_GENERIC_MMU_GATHER
1869547d01bSPeter Zijlstra 
187ca1d6c7dSNicholas Krause static bool tlb_next_batch(struct mmu_gather *tlb)
1889547d01bSPeter Zijlstra {
1899547d01bSPeter Zijlstra 	struct mmu_gather_batch *batch;
1909547d01bSPeter Zijlstra 
1919547d01bSPeter Zijlstra 	batch = tlb->active;
1929547d01bSPeter Zijlstra 	if (batch->next) {
1939547d01bSPeter Zijlstra 		tlb->active = batch->next;
194ca1d6c7dSNicholas Krause 		return true;
1959547d01bSPeter Zijlstra 	}
1969547d01bSPeter Zijlstra 
19753a59fc6SMichal Hocko 	if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
198ca1d6c7dSNicholas Krause 		return false;
19953a59fc6SMichal Hocko 
2009547d01bSPeter Zijlstra 	batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
2019547d01bSPeter Zijlstra 	if (!batch)
202ca1d6c7dSNicholas Krause 		return false;
2039547d01bSPeter Zijlstra 
20453a59fc6SMichal Hocko 	tlb->batch_count++;
2059547d01bSPeter Zijlstra 	batch->next = NULL;
2069547d01bSPeter Zijlstra 	batch->nr   = 0;
2079547d01bSPeter Zijlstra 	batch->max  = MAX_GATHER_BATCH;
2089547d01bSPeter Zijlstra 
2099547d01bSPeter Zijlstra 	tlb->active->next = batch;
2109547d01bSPeter Zijlstra 	tlb->active = batch;
2119547d01bSPeter Zijlstra 
212ca1d6c7dSNicholas Krause 	return true;
2139547d01bSPeter Zijlstra }
2149547d01bSPeter Zijlstra 
2159547d01bSPeter Zijlstra /* tlb_gather_mmu
2169547d01bSPeter Zijlstra  *	Called to initialize an (on-stack) mmu_gather structure for page-table
2179547d01bSPeter Zijlstra  *	tear-down from @mm. The @fullmm argument is used when @mm is without
2189547d01bSPeter Zijlstra  *	users and we're going to destroy the full address space (exit/execve).
2199547d01bSPeter Zijlstra  */
2202b047252SLinus Torvalds void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, unsigned long start, unsigned long end)
2219547d01bSPeter Zijlstra {
2229547d01bSPeter Zijlstra 	tlb->mm = mm;
2239547d01bSPeter Zijlstra 
2242b047252SLinus Torvalds 	/* Is it from 0 to ~0? */
2252b047252SLinus Torvalds 	tlb->fullmm     = !(start | (end+1));
2261de14c3cSDave Hansen 	tlb->need_flush_all = 0;
2279547d01bSPeter Zijlstra 	tlb->local.next = NULL;
2289547d01bSPeter Zijlstra 	tlb->local.nr   = 0;
2299547d01bSPeter Zijlstra 	tlb->local.max  = ARRAY_SIZE(tlb->__pages);
2309547d01bSPeter Zijlstra 	tlb->active     = &tlb->local;
23153a59fc6SMichal Hocko 	tlb->batch_count = 0;
2329547d01bSPeter Zijlstra 
2339547d01bSPeter Zijlstra #ifdef CONFIG_HAVE_RCU_TABLE_FREE
2349547d01bSPeter Zijlstra 	tlb->batch = NULL;
23534e55232SKAMEZAWA Hiroyuki #endif
236e77b0852SAneesh Kumar K.V 	tlb->page_size = 0;
237fb7332a9SWill Deacon 
238fb7332a9SWill Deacon 	__tlb_reset_range(tlb);
2399547d01bSPeter Zijlstra }
2409547d01bSPeter Zijlstra 
2411cf35d47SLinus Torvalds static void tlb_flush_mmu_tlbonly(struct mmu_gather *tlb)
2429547d01bSPeter Zijlstra {
243721c21c1SWill Deacon 	if (!tlb->end)
244721c21c1SWill Deacon 		return;
245721c21c1SWill Deacon 
2469547d01bSPeter Zijlstra 	tlb_flush(tlb);
24734ee645eSJoerg Roedel 	mmu_notifier_invalidate_range(tlb->mm, tlb->start, tlb->end);
2489547d01bSPeter Zijlstra #ifdef CONFIG_HAVE_RCU_TABLE_FREE
2499547d01bSPeter Zijlstra 	tlb_table_flush(tlb);
2509547d01bSPeter Zijlstra #endif
251fb7332a9SWill Deacon 	__tlb_reset_range(tlb);
2521cf35d47SLinus Torvalds }
2531cf35d47SLinus Torvalds 
2541cf35d47SLinus Torvalds static void tlb_flush_mmu_free(struct mmu_gather *tlb)
2551cf35d47SLinus Torvalds {
2561cf35d47SLinus Torvalds 	struct mmu_gather_batch *batch;
2579547d01bSPeter Zijlstra 
258721c21c1SWill Deacon 	for (batch = &tlb->local; batch && batch->nr; batch = batch->next) {
2599547d01bSPeter Zijlstra 		free_pages_and_swap_cache(batch->pages, batch->nr);
2609547d01bSPeter Zijlstra 		batch->nr = 0;
2619547d01bSPeter Zijlstra 	}
2629547d01bSPeter Zijlstra 	tlb->active = &tlb->local;
2639547d01bSPeter Zijlstra }
2649547d01bSPeter Zijlstra 
2651cf35d47SLinus Torvalds void tlb_flush_mmu(struct mmu_gather *tlb)
2661cf35d47SLinus Torvalds {
2671cf35d47SLinus Torvalds 	tlb_flush_mmu_tlbonly(tlb);
2681cf35d47SLinus Torvalds 	tlb_flush_mmu_free(tlb);
2691cf35d47SLinus Torvalds }
2701cf35d47SLinus Torvalds 
2719547d01bSPeter Zijlstra /* tlb_finish_mmu
2729547d01bSPeter Zijlstra  *	Called at the end of the shootdown operation to free up any resources
2739547d01bSPeter Zijlstra  *	that were required.
2749547d01bSPeter Zijlstra  */
2759547d01bSPeter Zijlstra void tlb_finish_mmu(struct mmu_gather *tlb, unsigned long start, unsigned long end)
2769547d01bSPeter Zijlstra {
2779547d01bSPeter Zijlstra 	struct mmu_gather_batch *batch, *next;
2789547d01bSPeter Zijlstra 
2799547d01bSPeter Zijlstra 	tlb_flush_mmu(tlb);
2809547d01bSPeter Zijlstra 
2819547d01bSPeter Zijlstra 	/* keep the page table cache within bounds */
2829547d01bSPeter Zijlstra 	check_pgt_cache();
2839547d01bSPeter Zijlstra 
2849547d01bSPeter Zijlstra 	for (batch = tlb->local.next; batch; batch = next) {
2859547d01bSPeter Zijlstra 		next = batch->next;
2869547d01bSPeter Zijlstra 		free_pages((unsigned long)batch, 0);
2879547d01bSPeter Zijlstra 	}
2889547d01bSPeter Zijlstra 	tlb->local.next = NULL;
2899547d01bSPeter Zijlstra }
2909547d01bSPeter Zijlstra 
2919547d01bSPeter Zijlstra /* __tlb_remove_page
2929547d01bSPeter Zijlstra  *	Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while
2939547d01bSPeter Zijlstra  *	handling the additional races in SMP caused by other CPUs caching valid
2949547d01bSPeter Zijlstra  *	mappings in their TLBs. Returns the number of free page slots left.
2959547d01bSPeter Zijlstra  *	When out of page slots we must call tlb_flush_mmu().
296e9d55e15SAneesh Kumar K.V  *returns true if the caller should flush.
2979547d01bSPeter Zijlstra  */
298e77b0852SAneesh Kumar K.V bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size)
2999547d01bSPeter Zijlstra {
3009547d01bSPeter Zijlstra 	struct mmu_gather_batch *batch;
3019547d01bSPeter Zijlstra 
302fb7332a9SWill Deacon 	VM_BUG_ON(!tlb->end);
303692a68c1SAneesh Kumar K.V 	VM_WARN_ON(tlb->page_size != page_size);
304e77b0852SAneesh Kumar K.V 
3059547d01bSPeter Zijlstra 	batch = tlb->active;
306692a68c1SAneesh Kumar K.V 	/*
307692a68c1SAneesh Kumar K.V 	 * Add the page and check if we are full. If so
308692a68c1SAneesh Kumar K.V 	 * force a flush.
309692a68c1SAneesh Kumar K.V 	 */
310692a68c1SAneesh Kumar K.V 	batch->pages[batch->nr++] = page;
3119547d01bSPeter Zijlstra 	if (batch->nr == batch->max) {
3129547d01bSPeter Zijlstra 		if (!tlb_next_batch(tlb))
313e9d55e15SAneesh Kumar K.V 			return true;
3140b43c3aaSShaohua Li 		batch = tlb->active;
3159547d01bSPeter Zijlstra 	}
316309381feSSasha Levin 	VM_BUG_ON_PAGE(batch->nr > batch->max, page);
3179547d01bSPeter Zijlstra 
318e9d55e15SAneesh Kumar K.V 	return false;
3199547d01bSPeter Zijlstra }
3209547d01bSPeter Zijlstra 
3219547d01bSPeter Zijlstra #endif /* HAVE_GENERIC_MMU_GATHER */
32234e55232SKAMEZAWA Hiroyuki 
32326723911SPeter Zijlstra #ifdef CONFIG_HAVE_RCU_TABLE_FREE
32426723911SPeter Zijlstra 
32526723911SPeter Zijlstra /*
32626723911SPeter Zijlstra  * See the comment near struct mmu_table_batch.
32726723911SPeter Zijlstra  */
32826723911SPeter Zijlstra 
32926723911SPeter Zijlstra static void tlb_remove_table_smp_sync(void *arg)
33026723911SPeter Zijlstra {
33126723911SPeter Zijlstra 	/* Simply deliver the interrupt */
33226723911SPeter Zijlstra }
33326723911SPeter Zijlstra 
33426723911SPeter Zijlstra static void tlb_remove_table_one(void *table)
33526723911SPeter Zijlstra {
33626723911SPeter Zijlstra 	/*
33726723911SPeter Zijlstra 	 * This isn't an RCU grace period and hence the page-tables cannot be
33826723911SPeter Zijlstra 	 * assumed to be actually RCU-freed.
33926723911SPeter Zijlstra 	 *
34026723911SPeter Zijlstra 	 * It is however sufficient for software page-table walkers that rely on
34126723911SPeter Zijlstra 	 * IRQ disabling. See the comment near struct mmu_table_batch.
34226723911SPeter Zijlstra 	 */
34326723911SPeter Zijlstra 	smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
34426723911SPeter Zijlstra 	__tlb_remove_table(table);
34526723911SPeter Zijlstra }
34626723911SPeter Zijlstra 
34726723911SPeter Zijlstra static void tlb_remove_table_rcu(struct rcu_head *head)
34826723911SPeter Zijlstra {
34926723911SPeter Zijlstra 	struct mmu_table_batch *batch;
35026723911SPeter Zijlstra 	int i;
35126723911SPeter Zijlstra 
35226723911SPeter Zijlstra 	batch = container_of(head, struct mmu_table_batch, rcu);
35326723911SPeter Zijlstra 
35426723911SPeter Zijlstra 	for (i = 0; i < batch->nr; i++)
35526723911SPeter Zijlstra 		__tlb_remove_table(batch->tables[i]);
35626723911SPeter Zijlstra 
35726723911SPeter Zijlstra 	free_page((unsigned long)batch);
35826723911SPeter Zijlstra }
35926723911SPeter Zijlstra 
36026723911SPeter Zijlstra void tlb_table_flush(struct mmu_gather *tlb)
36126723911SPeter Zijlstra {
36226723911SPeter Zijlstra 	struct mmu_table_batch **batch = &tlb->batch;
36326723911SPeter Zijlstra 
36426723911SPeter Zijlstra 	if (*batch) {
36526723911SPeter Zijlstra 		call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
36626723911SPeter Zijlstra 		*batch = NULL;
36726723911SPeter Zijlstra 	}
36826723911SPeter Zijlstra }
36926723911SPeter Zijlstra 
37026723911SPeter Zijlstra void tlb_remove_table(struct mmu_gather *tlb, void *table)
37126723911SPeter Zijlstra {
37226723911SPeter Zijlstra 	struct mmu_table_batch **batch = &tlb->batch;
37326723911SPeter Zijlstra 
37426723911SPeter Zijlstra 	/*
37526723911SPeter Zijlstra 	 * When there's less then two users of this mm there cannot be a
37626723911SPeter Zijlstra 	 * concurrent page-table walk.
37726723911SPeter Zijlstra 	 */
37826723911SPeter Zijlstra 	if (atomic_read(&tlb->mm->mm_users) < 2) {
37926723911SPeter Zijlstra 		__tlb_remove_table(table);
38026723911SPeter Zijlstra 		return;
38126723911SPeter Zijlstra 	}
38226723911SPeter Zijlstra 
38326723911SPeter Zijlstra 	if (*batch == NULL) {
38426723911SPeter Zijlstra 		*batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
38526723911SPeter Zijlstra 		if (*batch == NULL) {
38626723911SPeter Zijlstra 			tlb_remove_table_one(table);
38726723911SPeter Zijlstra 			return;
38826723911SPeter Zijlstra 		}
38926723911SPeter Zijlstra 		(*batch)->nr = 0;
39026723911SPeter Zijlstra 	}
39126723911SPeter Zijlstra 	(*batch)->tables[(*batch)->nr++] = table;
39226723911SPeter Zijlstra 	if ((*batch)->nr == MAX_TABLE_BATCH)
39326723911SPeter Zijlstra 		tlb_table_flush(tlb);
39426723911SPeter Zijlstra }
39526723911SPeter Zijlstra 
3969547d01bSPeter Zijlstra #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
39726723911SPeter Zijlstra 
3981da177e4SLinus Torvalds /*
3991da177e4SLinus Torvalds  * Note: this doesn't free the actual pages themselves. That
4001da177e4SLinus Torvalds  * has been handled earlier when unmapping all the memory regions.
4011da177e4SLinus Torvalds  */
4029e1b32caSBenjamin Herrenschmidt static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
4039e1b32caSBenjamin Herrenschmidt 			   unsigned long addr)
4041da177e4SLinus Torvalds {
4052f569afdSMartin Schwidefsky 	pgtable_t token = pmd_pgtable(*pmd);
4061da177e4SLinus Torvalds 	pmd_clear(pmd);
4079e1b32caSBenjamin Herrenschmidt 	pte_free_tlb(tlb, token, addr);
408e1f56c89SKirill A. Shutemov 	atomic_long_dec(&tlb->mm->nr_ptes);
4091da177e4SLinus Torvalds }
4101da177e4SLinus Torvalds 
411e0da382cSHugh Dickins static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
412e0da382cSHugh Dickins 				unsigned long addr, unsigned long end,
413e0da382cSHugh Dickins 				unsigned long floor, unsigned long ceiling)
4141da177e4SLinus Torvalds {
4151da177e4SLinus Torvalds 	pmd_t *pmd;
4161da177e4SLinus Torvalds 	unsigned long next;
417e0da382cSHugh Dickins 	unsigned long start;
4181da177e4SLinus Torvalds 
419e0da382cSHugh Dickins 	start = addr;
4201da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
4211da177e4SLinus Torvalds 	do {
4221da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
4231da177e4SLinus Torvalds 		if (pmd_none_or_clear_bad(pmd))
4241da177e4SLinus Torvalds 			continue;
4259e1b32caSBenjamin Herrenschmidt 		free_pte_range(tlb, pmd, addr);
4261da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
4271da177e4SLinus Torvalds 
428e0da382cSHugh Dickins 	start &= PUD_MASK;
429e0da382cSHugh Dickins 	if (start < floor)
430e0da382cSHugh Dickins 		return;
431e0da382cSHugh Dickins 	if (ceiling) {
432e0da382cSHugh Dickins 		ceiling &= PUD_MASK;
433e0da382cSHugh Dickins 		if (!ceiling)
434e0da382cSHugh Dickins 			return;
4351da177e4SLinus Torvalds 	}
436e0da382cSHugh Dickins 	if (end - 1 > ceiling - 1)
437e0da382cSHugh Dickins 		return;
438e0da382cSHugh Dickins 
439e0da382cSHugh Dickins 	pmd = pmd_offset(pud, start);
440e0da382cSHugh Dickins 	pud_clear(pud);
4419e1b32caSBenjamin Herrenschmidt 	pmd_free_tlb(tlb, pmd, start);
442dc6c9a35SKirill A. Shutemov 	mm_dec_nr_pmds(tlb->mm);
4431da177e4SLinus Torvalds }
4441da177e4SLinus Torvalds 
445e0da382cSHugh Dickins static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd,
446e0da382cSHugh Dickins 				unsigned long addr, unsigned long end,
447e0da382cSHugh Dickins 				unsigned long floor, unsigned long ceiling)
4481da177e4SLinus Torvalds {
4491da177e4SLinus Torvalds 	pud_t *pud;
4501da177e4SLinus Torvalds 	unsigned long next;
451e0da382cSHugh Dickins 	unsigned long start;
4521da177e4SLinus Torvalds 
453e0da382cSHugh Dickins 	start = addr;
4541da177e4SLinus Torvalds 	pud = pud_offset(pgd, addr);
4551da177e4SLinus Torvalds 	do {
4561da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
4571da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
4581da177e4SLinus Torvalds 			continue;
459e0da382cSHugh Dickins 		free_pmd_range(tlb, pud, addr, next, floor, ceiling);
4601da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
4611da177e4SLinus Torvalds 
462e0da382cSHugh Dickins 	start &= PGDIR_MASK;
463e0da382cSHugh Dickins 	if (start < floor)
464e0da382cSHugh Dickins 		return;
465e0da382cSHugh Dickins 	if (ceiling) {
466e0da382cSHugh Dickins 		ceiling &= PGDIR_MASK;
467e0da382cSHugh Dickins 		if (!ceiling)
468e0da382cSHugh Dickins 			return;
4691da177e4SLinus Torvalds 	}
470e0da382cSHugh Dickins 	if (end - 1 > ceiling - 1)
471e0da382cSHugh Dickins 		return;
472e0da382cSHugh Dickins 
473e0da382cSHugh Dickins 	pud = pud_offset(pgd, start);
474e0da382cSHugh Dickins 	pgd_clear(pgd);
4759e1b32caSBenjamin Herrenschmidt 	pud_free_tlb(tlb, pud, start);
4761da177e4SLinus Torvalds }
4771da177e4SLinus Torvalds 
4781da177e4SLinus Torvalds /*
479e0da382cSHugh Dickins  * This function frees user-level page tables of a process.
4801da177e4SLinus Torvalds  */
48142b77728SJan Beulich void free_pgd_range(struct mmu_gather *tlb,
482e0da382cSHugh Dickins 			unsigned long addr, unsigned long end,
483e0da382cSHugh Dickins 			unsigned long floor, unsigned long ceiling)
4841da177e4SLinus Torvalds {
4851da177e4SLinus Torvalds 	pgd_t *pgd;
4861da177e4SLinus Torvalds 	unsigned long next;
4871da177e4SLinus Torvalds 
488e0da382cSHugh Dickins 	/*
489e0da382cSHugh Dickins 	 * The next few lines have given us lots of grief...
490e0da382cSHugh Dickins 	 *
491e0da382cSHugh Dickins 	 * Why are we testing PMD* at this top level?  Because often
492e0da382cSHugh Dickins 	 * there will be no work to do at all, and we'd prefer not to
493e0da382cSHugh Dickins 	 * go all the way down to the bottom just to discover that.
494e0da382cSHugh Dickins 	 *
495e0da382cSHugh Dickins 	 * Why all these "- 1"s?  Because 0 represents both the bottom
496e0da382cSHugh Dickins 	 * of the address space and the top of it (using -1 for the
497e0da382cSHugh Dickins 	 * top wouldn't help much: the masks would do the wrong thing).
498e0da382cSHugh Dickins 	 * The rule is that addr 0 and floor 0 refer to the bottom of
499e0da382cSHugh Dickins 	 * the address space, but end 0 and ceiling 0 refer to the top
500e0da382cSHugh Dickins 	 * Comparisons need to use "end - 1" and "ceiling - 1" (though
501e0da382cSHugh Dickins 	 * that end 0 case should be mythical).
502e0da382cSHugh Dickins 	 *
503e0da382cSHugh Dickins 	 * Wherever addr is brought up or ceiling brought down, we must
504e0da382cSHugh Dickins 	 * be careful to reject "the opposite 0" before it confuses the
505e0da382cSHugh Dickins 	 * subsequent tests.  But what about where end is brought down
506e0da382cSHugh Dickins 	 * by PMD_SIZE below? no, end can't go down to 0 there.
507e0da382cSHugh Dickins 	 *
508e0da382cSHugh Dickins 	 * Whereas we round start (addr) and ceiling down, by different
509e0da382cSHugh Dickins 	 * masks at different levels, in order to test whether a table
510e0da382cSHugh Dickins 	 * now has no other vmas using it, so can be freed, we don't
511e0da382cSHugh Dickins 	 * bother to round floor or end up - the tests don't need that.
512e0da382cSHugh Dickins 	 */
513e0da382cSHugh Dickins 
514e0da382cSHugh Dickins 	addr &= PMD_MASK;
515e0da382cSHugh Dickins 	if (addr < floor) {
516e0da382cSHugh Dickins 		addr += PMD_SIZE;
517e0da382cSHugh Dickins 		if (!addr)
518e0da382cSHugh Dickins 			return;
519e0da382cSHugh Dickins 	}
520e0da382cSHugh Dickins 	if (ceiling) {
521e0da382cSHugh Dickins 		ceiling &= PMD_MASK;
522e0da382cSHugh Dickins 		if (!ceiling)
523e0da382cSHugh Dickins 			return;
524e0da382cSHugh Dickins 	}
525e0da382cSHugh Dickins 	if (end - 1 > ceiling - 1)
526e0da382cSHugh Dickins 		end -= PMD_SIZE;
527e0da382cSHugh Dickins 	if (addr > end - 1)
528e0da382cSHugh Dickins 		return;
52907e32661SAneesh Kumar K.V 	/*
53007e32661SAneesh Kumar K.V 	 * We add page table cache pages with PAGE_SIZE,
53107e32661SAneesh Kumar K.V 	 * (see pte_free_tlb()), flush the tlb if we need
53207e32661SAneesh Kumar K.V 	 */
53307e32661SAneesh Kumar K.V 	tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
53442b77728SJan Beulich 	pgd = pgd_offset(tlb->mm, addr);
5351da177e4SLinus Torvalds 	do {
5361da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
5371da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
5381da177e4SLinus Torvalds 			continue;
53942b77728SJan Beulich 		free_pud_range(tlb, pgd, addr, next, floor, ceiling);
5401da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
541e0da382cSHugh Dickins }
542e0da382cSHugh Dickins 
54342b77728SJan Beulich void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
544e0da382cSHugh Dickins 		unsigned long floor, unsigned long ceiling)
545e0da382cSHugh Dickins {
546e0da382cSHugh Dickins 	while (vma) {
547e0da382cSHugh Dickins 		struct vm_area_struct *next = vma->vm_next;
548e0da382cSHugh Dickins 		unsigned long addr = vma->vm_start;
549e0da382cSHugh Dickins 
5508f4f8c16SHugh Dickins 		/*
55125d9e2d1Snpiggin@suse.de 		 * Hide vma from rmap and truncate_pagecache before freeing
55225d9e2d1Snpiggin@suse.de 		 * pgtables
5538f4f8c16SHugh Dickins 		 */
5545beb4930SRik van Riel 		unlink_anon_vmas(vma);
5558f4f8c16SHugh Dickins 		unlink_file_vma(vma);
5568f4f8c16SHugh Dickins 
5579da61aefSDavid Gibson 		if (is_vm_hugetlb_page(vma)) {
5583bf5ee95SHugh Dickins 			hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
5593bf5ee95SHugh Dickins 				floor, next? next->vm_start: ceiling);
5603bf5ee95SHugh Dickins 		} else {
5613bf5ee95SHugh Dickins 			/*
5623bf5ee95SHugh Dickins 			 * Optimization: gather nearby vmas into one call down
5633bf5ee95SHugh Dickins 			 */
5643bf5ee95SHugh Dickins 			while (next && next->vm_start <= vma->vm_end + PMD_SIZE
5654866920bSDavid Gibson 			       && !is_vm_hugetlb_page(next)) {
566e0da382cSHugh Dickins 				vma = next;
567e0da382cSHugh Dickins 				next = vma->vm_next;
5685beb4930SRik van Riel 				unlink_anon_vmas(vma);
5698f4f8c16SHugh Dickins 				unlink_file_vma(vma);
570e0da382cSHugh Dickins 			}
5713bf5ee95SHugh Dickins 			free_pgd_range(tlb, addr, vma->vm_end,
572e0da382cSHugh Dickins 				floor, next? next->vm_start: ceiling);
5733bf5ee95SHugh Dickins 		}
574e0da382cSHugh Dickins 		vma = next;
575e0da382cSHugh Dickins 	}
5761da177e4SLinus Torvalds }
5771da177e4SLinus Torvalds 
5783ed3a4f0SKirill A. Shutemov int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
5791da177e4SLinus Torvalds {
580c4088ebdSKirill A. Shutemov 	spinlock_t *ptl;
5812f569afdSMartin Schwidefsky 	pgtable_t new = pte_alloc_one(mm, address);
5821da177e4SLinus Torvalds 	if (!new)
5831bb3630eSHugh Dickins 		return -ENOMEM;
5841bb3630eSHugh Dickins 
585362a61adSNick Piggin 	/*
586362a61adSNick Piggin 	 * Ensure all pte setup (eg. pte page lock and page clearing) are
587362a61adSNick Piggin 	 * visible before the pte is made visible to other CPUs by being
588362a61adSNick Piggin 	 * put into page tables.
589362a61adSNick Piggin 	 *
590362a61adSNick Piggin 	 * The other side of the story is the pointer chasing in the page
591362a61adSNick Piggin 	 * table walking code (when walking the page table without locking;
592362a61adSNick Piggin 	 * ie. most of the time). Fortunately, these data accesses consist
593362a61adSNick Piggin 	 * of a chain of data-dependent loads, meaning most CPUs (alpha
594362a61adSNick Piggin 	 * being the notable exception) will already guarantee loads are
595362a61adSNick Piggin 	 * seen in-order. See the alpha page table accessors for the
596362a61adSNick Piggin 	 * smp_read_barrier_depends() barriers in page table walking code.
597362a61adSNick Piggin 	 */
598362a61adSNick Piggin 	smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
599362a61adSNick Piggin 
600c4088ebdSKirill A. Shutemov 	ptl = pmd_lock(mm, pmd);
6018ac1f832SAndrea Arcangeli 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
602e1f56c89SKirill A. Shutemov 		atomic_long_inc(&mm->nr_ptes);
6031da177e4SLinus Torvalds 		pmd_populate(mm, pmd, new);
6042f569afdSMartin Schwidefsky 		new = NULL;
6054b471e88SKirill A. Shutemov 	}
606c4088ebdSKirill A. Shutemov 	spin_unlock(ptl);
6072f569afdSMartin Schwidefsky 	if (new)
6082f569afdSMartin Schwidefsky 		pte_free(mm, new);
6091bb3630eSHugh Dickins 	return 0;
6101da177e4SLinus Torvalds }
6111da177e4SLinus Torvalds 
6121bb3630eSHugh Dickins int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
6131da177e4SLinus Torvalds {
6141bb3630eSHugh Dickins 	pte_t *new = pte_alloc_one_kernel(&init_mm, address);
6151da177e4SLinus Torvalds 	if (!new)
6161bb3630eSHugh Dickins 		return -ENOMEM;
6171da177e4SLinus Torvalds 
618362a61adSNick Piggin 	smp_wmb(); /* See comment in __pte_alloc */
619362a61adSNick Piggin 
620872fec16SHugh Dickins 	spin_lock(&init_mm.page_table_lock);
6218ac1f832SAndrea Arcangeli 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
622872fec16SHugh Dickins 		pmd_populate_kernel(&init_mm, pmd, new);
6232f569afdSMartin Schwidefsky 		new = NULL;
6244b471e88SKirill A. Shutemov 	}
625872fec16SHugh Dickins 	spin_unlock(&init_mm.page_table_lock);
6262f569afdSMartin Schwidefsky 	if (new)
6272f569afdSMartin Schwidefsky 		pte_free_kernel(&init_mm, new);
6281bb3630eSHugh Dickins 	return 0;
6291da177e4SLinus Torvalds }
6301da177e4SLinus Torvalds 
631d559db08SKAMEZAWA Hiroyuki static inline void init_rss_vec(int *rss)
632ae859762SHugh Dickins {
633d559db08SKAMEZAWA Hiroyuki 	memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
634d559db08SKAMEZAWA Hiroyuki }
635d559db08SKAMEZAWA Hiroyuki 
636d559db08SKAMEZAWA Hiroyuki static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
637d559db08SKAMEZAWA Hiroyuki {
638d559db08SKAMEZAWA Hiroyuki 	int i;
639d559db08SKAMEZAWA Hiroyuki 
64034e55232SKAMEZAWA Hiroyuki 	if (current->mm == mm)
64105af2e10SDavid Rientjes 		sync_mm_rss(mm);
642d559db08SKAMEZAWA Hiroyuki 	for (i = 0; i < NR_MM_COUNTERS; i++)
643d559db08SKAMEZAWA Hiroyuki 		if (rss[i])
644d559db08SKAMEZAWA Hiroyuki 			add_mm_counter(mm, i, rss[i]);
645ae859762SHugh Dickins }
646ae859762SHugh Dickins 
6471da177e4SLinus Torvalds /*
6486aab341eSLinus Torvalds  * This function is called to print an error when a bad pte
6496aab341eSLinus Torvalds  * is found. For example, we might have a PFN-mapped pte in
6506aab341eSLinus Torvalds  * a region that doesn't allow it.
651b5810039SNick Piggin  *
652b5810039SNick Piggin  * The calling function must still handle the error.
653b5810039SNick Piggin  */
6543dc14741SHugh Dickins static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
6553dc14741SHugh Dickins 			  pte_t pte, struct page *page)
656b5810039SNick Piggin {
6573dc14741SHugh Dickins 	pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
6583dc14741SHugh Dickins 	pud_t *pud = pud_offset(pgd, addr);
6593dc14741SHugh Dickins 	pmd_t *pmd = pmd_offset(pud, addr);
6603dc14741SHugh Dickins 	struct address_space *mapping;
6613dc14741SHugh Dickins 	pgoff_t index;
662d936cf9bSHugh Dickins 	static unsigned long resume;
663d936cf9bSHugh Dickins 	static unsigned long nr_shown;
664d936cf9bSHugh Dickins 	static unsigned long nr_unshown;
665d936cf9bSHugh Dickins 
666d936cf9bSHugh Dickins 	/*
667d936cf9bSHugh Dickins 	 * Allow a burst of 60 reports, then keep quiet for that minute;
668d936cf9bSHugh Dickins 	 * or allow a steady drip of one report per second.
669d936cf9bSHugh Dickins 	 */
670d936cf9bSHugh Dickins 	if (nr_shown == 60) {
671d936cf9bSHugh Dickins 		if (time_before(jiffies, resume)) {
672d936cf9bSHugh Dickins 			nr_unshown++;
673d936cf9bSHugh Dickins 			return;
674d936cf9bSHugh Dickins 		}
675d936cf9bSHugh Dickins 		if (nr_unshown) {
6761170532bSJoe Perches 			pr_alert("BUG: Bad page map: %lu messages suppressed\n",
677d936cf9bSHugh Dickins 				 nr_unshown);
678d936cf9bSHugh Dickins 			nr_unshown = 0;
679d936cf9bSHugh Dickins 		}
680d936cf9bSHugh Dickins 		nr_shown = 0;
681d936cf9bSHugh Dickins 	}
682d936cf9bSHugh Dickins 	if (nr_shown++ == 0)
683d936cf9bSHugh Dickins 		resume = jiffies + 60 * HZ;
6843dc14741SHugh Dickins 
6853dc14741SHugh Dickins 	mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
6863dc14741SHugh Dickins 	index = linear_page_index(vma, addr);
6873dc14741SHugh Dickins 
6881170532bSJoe Perches 	pr_alert("BUG: Bad page map in process %s  pte:%08llx pmd:%08llx\n",
6893dc14741SHugh Dickins 		 current->comm,
6903dc14741SHugh Dickins 		 (long long)pte_val(pte), (long long)pmd_val(*pmd));
691718a3821SWu Fengguang 	if (page)
692f0b791a3SDave Hansen 		dump_page(page, "bad pte");
6931170532bSJoe Perches 	pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
6943dc14741SHugh Dickins 		 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
6953dc14741SHugh Dickins 	/*
6963dc14741SHugh Dickins 	 * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
6973dc14741SHugh Dickins 	 */
6982682582aSKonstantin Khlebnikov 	pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n",
6992682582aSKonstantin Khlebnikov 		 vma->vm_file,
7002682582aSKonstantin Khlebnikov 		 vma->vm_ops ? vma->vm_ops->fault : NULL,
7012682582aSKonstantin Khlebnikov 		 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
7022682582aSKonstantin Khlebnikov 		 mapping ? mapping->a_ops->readpage : NULL);
703b5810039SNick Piggin 	dump_stack();
704373d4d09SRusty Russell 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
705b5810039SNick Piggin }
706b5810039SNick Piggin 
707b5810039SNick Piggin /*
7087e675137SNick Piggin  * vm_normal_page -- This function gets the "struct page" associated with a pte.
7096aab341eSLinus Torvalds  *
7107e675137SNick Piggin  * "Special" mappings do not wish to be associated with a "struct page" (either
7117e675137SNick Piggin  * it doesn't exist, or it exists but they don't want to touch it). In this
7127e675137SNick Piggin  * case, NULL is returned here. "Normal" mappings do have a struct page.
713b379d790SJared Hulbert  *
7147e675137SNick Piggin  * There are 2 broad cases. Firstly, an architecture may define a pte_special()
7157e675137SNick Piggin  * pte bit, in which case this function is trivial. Secondly, an architecture
7167e675137SNick Piggin  * may not have a spare pte bit, which requires a more complicated scheme,
7177e675137SNick Piggin  * described below.
7187e675137SNick Piggin  *
7197e675137SNick Piggin  * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
7207e675137SNick Piggin  * special mapping (even if there are underlying and valid "struct pages").
7217e675137SNick Piggin  * COWed pages of a VM_PFNMAP are always normal.
7226aab341eSLinus Torvalds  *
723b379d790SJared Hulbert  * The way we recognize COWed pages within VM_PFNMAP mappings is through the
724b379d790SJared Hulbert  * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
7257e675137SNick Piggin  * set, and the vm_pgoff will point to the first PFN mapped: thus every special
7267e675137SNick Piggin  * mapping will always honor the rule
7276aab341eSLinus Torvalds  *
7286aab341eSLinus Torvalds  *	pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
7296aab341eSLinus Torvalds  *
7307e675137SNick Piggin  * And for normal mappings this is false.
731b379d790SJared Hulbert  *
7327e675137SNick Piggin  * This restricts such mappings to be a linear translation from virtual address
7337e675137SNick Piggin  * to pfn. To get around this restriction, we allow arbitrary mappings so long
7347e675137SNick Piggin  * as the vma is not a COW mapping; in that case, we know that all ptes are
7357e675137SNick Piggin  * special (because none can have been COWed).
736b379d790SJared Hulbert  *
737b379d790SJared Hulbert  *
7387e675137SNick Piggin  * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
7397e675137SNick Piggin  *
740b379d790SJared Hulbert  * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
741b379d790SJared Hulbert  * page" backing, however the difference is that _all_ pages with a struct
742b379d790SJared Hulbert  * page (that is, those where pfn_valid is true) are refcounted and considered
743b379d790SJared Hulbert  * normal pages by the VM. The disadvantage is that pages are refcounted
744b379d790SJared Hulbert  * (which can be slower and simply not an option for some PFNMAP users). The
745b379d790SJared Hulbert  * advantage is that we don't have to follow the strict linearity rule of
746b379d790SJared Hulbert  * PFNMAP mappings in order to support COWable mappings.
747b379d790SJared Hulbert  *
748ee498ed7SHugh Dickins  */
7497e675137SNick Piggin #ifdef __HAVE_ARCH_PTE_SPECIAL
7507e675137SNick Piggin # define HAVE_PTE_SPECIAL 1
7517e675137SNick Piggin #else
7527e675137SNick Piggin # define HAVE_PTE_SPECIAL 0
7537e675137SNick Piggin #endif
7547e675137SNick Piggin struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
7557e675137SNick Piggin 				pte_t pte)
756ee498ed7SHugh Dickins {
75722b31eecSHugh Dickins 	unsigned long pfn = pte_pfn(pte);
7587e675137SNick Piggin 
7597e675137SNick Piggin 	if (HAVE_PTE_SPECIAL) {
760b38af472SHugh Dickins 		if (likely(!pte_special(pte)))
76122b31eecSHugh Dickins 			goto check_pfn;
762667a0a06SDavid Vrabel 		if (vma->vm_ops && vma->vm_ops->find_special_page)
763667a0a06SDavid Vrabel 			return vma->vm_ops->find_special_page(vma, addr);
764a13ea5b7SHugh Dickins 		if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
765a13ea5b7SHugh Dickins 			return NULL;
76662eede62SHugh Dickins 		if (!is_zero_pfn(pfn))
76722b31eecSHugh Dickins 			print_bad_pte(vma, addr, pte, NULL);
7687e675137SNick Piggin 		return NULL;
7697e675137SNick Piggin 	}
7707e675137SNick Piggin 
7717e675137SNick Piggin 	/* !HAVE_PTE_SPECIAL case follows: */
7727e675137SNick Piggin 
773b379d790SJared Hulbert 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
774b379d790SJared Hulbert 		if (vma->vm_flags & VM_MIXEDMAP) {
775b379d790SJared Hulbert 			if (!pfn_valid(pfn))
776b379d790SJared Hulbert 				return NULL;
777b379d790SJared Hulbert 			goto out;
778b379d790SJared Hulbert 		} else {
7797e675137SNick Piggin 			unsigned long off;
7807e675137SNick Piggin 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
7816aab341eSLinus Torvalds 			if (pfn == vma->vm_pgoff + off)
7826aab341eSLinus Torvalds 				return NULL;
78367121172SLinus Torvalds 			if (!is_cow_mapping(vma->vm_flags))
784fb155c16SLinus Torvalds 				return NULL;
7856aab341eSLinus Torvalds 		}
786b379d790SJared Hulbert 	}
7876aab341eSLinus Torvalds 
788b38af472SHugh Dickins 	if (is_zero_pfn(pfn))
789b38af472SHugh Dickins 		return NULL;
79022b31eecSHugh Dickins check_pfn:
79122b31eecSHugh Dickins 	if (unlikely(pfn > highest_memmap_pfn)) {
79222b31eecSHugh Dickins 		print_bad_pte(vma, addr, pte, NULL);
79322b31eecSHugh Dickins 		return NULL;
79422b31eecSHugh Dickins 	}
7956aab341eSLinus Torvalds 
7966aab341eSLinus Torvalds 	/*
7977e675137SNick Piggin 	 * NOTE! We still have PageReserved() pages in the page tables.
7987e675137SNick Piggin 	 * eg. VDSO mappings can cause them to exist.
7996aab341eSLinus Torvalds 	 */
800b379d790SJared Hulbert out:
8016aab341eSLinus Torvalds 	return pfn_to_page(pfn);
802ee498ed7SHugh Dickins }
803ee498ed7SHugh Dickins 
80428093f9fSGerald Schaefer #ifdef CONFIG_TRANSPARENT_HUGEPAGE
80528093f9fSGerald Schaefer struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
80628093f9fSGerald Schaefer 				pmd_t pmd)
80728093f9fSGerald Schaefer {
80828093f9fSGerald Schaefer 	unsigned long pfn = pmd_pfn(pmd);
80928093f9fSGerald Schaefer 
81028093f9fSGerald Schaefer 	/*
81128093f9fSGerald Schaefer 	 * There is no pmd_special() but there may be special pmds, e.g.
81228093f9fSGerald Schaefer 	 * in a direct-access (dax) mapping, so let's just replicate the
81328093f9fSGerald Schaefer 	 * !HAVE_PTE_SPECIAL case from vm_normal_page() here.
81428093f9fSGerald Schaefer 	 */
81528093f9fSGerald Schaefer 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
81628093f9fSGerald Schaefer 		if (vma->vm_flags & VM_MIXEDMAP) {
81728093f9fSGerald Schaefer 			if (!pfn_valid(pfn))
81828093f9fSGerald Schaefer 				return NULL;
81928093f9fSGerald Schaefer 			goto out;
82028093f9fSGerald Schaefer 		} else {
82128093f9fSGerald Schaefer 			unsigned long off;
82228093f9fSGerald Schaefer 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
82328093f9fSGerald Schaefer 			if (pfn == vma->vm_pgoff + off)
82428093f9fSGerald Schaefer 				return NULL;
82528093f9fSGerald Schaefer 			if (!is_cow_mapping(vma->vm_flags))
82628093f9fSGerald Schaefer 				return NULL;
82728093f9fSGerald Schaefer 		}
82828093f9fSGerald Schaefer 	}
82928093f9fSGerald Schaefer 
83028093f9fSGerald Schaefer 	if (is_zero_pfn(pfn))
83128093f9fSGerald Schaefer 		return NULL;
83228093f9fSGerald Schaefer 	if (unlikely(pfn > highest_memmap_pfn))
83328093f9fSGerald Schaefer 		return NULL;
83428093f9fSGerald Schaefer 
83528093f9fSGerald Schaefer 	/*
83628093f9fSGerald Schaefer 	 * NOTE! We still have PageReserved() pages in the page tables.
83728093f9fSGerald Schaefer 	 * eg. VDSO mappings can cause them to exist.
83828093f9fSGerald Schaefer 	 */
83928093f9fSGerald Schaefer out:
84028093f9fSGerald Schaefer 	return pfn_to_page(pfn);
84128093f9fSGerald Schaefer }
84228093f9fSGerald Schaefer #endif
84328093f9fSGerald Schaefer 
844ee498ed7SHugh Dickins /*
8451da177e4SLinus Torvalds  * copy one vm_area from one task to the other. Assumes the page tables
8461da177e4SLinus Torvalds  * already present in the new task to be cleared in the whole range
8471da177e4SLinus Torvalds  * covered by this vma.
8481da177e4SLinus Torvalds  */
8491da177e4SLinus Torvalds 
850570a335bSHugh Dickins static inline unsigned long
8511da177e4SLinus Torvalds copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
852b5810039SNick Piggin 		pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
8538c103762SHugh Dickins 		unsigned long addr, int *rss)
8541da177e4SLinus Torvalds {
855b5810039SNick Piggin 	unsigned long vm_flags = vma->vm_flags;
8561da177e4SLinus Torvalds 	pte_t pte = *src_pte;
8571da177e4SLinus Torvalds 	struct page *page;
8581da177e4SLinus Torvalds 
8591da177e4SLinus Torvalds 	/* pte contains position in swap or file, so copy. */
8601da177e4SLinus Torvalds 	if (unlikely(!pte_present(pte))) {
8610697212aSChristoph Lameter 		swp_entry_t entry = pte_to_swp_entry(pte);
8620697212aSChristoph Lameter 
8632022b4d1SHugh Dickins 		if (likely(!non_swap_entry(entry))) {
864570a335bSHugh Dickins 			if (swap_duplicate(entry) < 0)
865570a335bSHugh Dickins 				return entry.val;
866570a335bSHugh Dickins 
8671da177e4SLinus Torvalds 			/* make sure dst_mm is on swapoff's mmlist. */
8681da177e4SLinus Torvalds 			if (unlikely(list_empty(&dst_mm->mmlist))) {
8691da177e4SLinus Torvalds 				spin_lock(&mmlist_lock);
870f412ac08SHugh Dickins 				if (list_empty(&dst_mm->mmlist))
871f412ac08SHugh Dickins 					list_add(&dst_mm->mmlist,
872f412ac08SHugh Dickins 							&src_mm->mmlist);
8731da177e4SLinus Torvalds 				spin_unlock(&mmlist_lock);
8741da177e4SLinus Torvalds 			}
875b084d435SKAMEZAWA Hiroyuki 			rss[MM_SWAPENTS]++;
8762022b4d1SHugh Dickins 		} else if (is_migration_entry(entry)) {
8779f9f1acdSKonstantin Khlebnikov 			page = migration_entry_to_page(entry);
8789f9f1acdSKonstantin Khlebnikov 
879eca56ff9SJerome Marchand 			rss[mm_counter(page)]++;
8809f9f1acdSKonstantin Khlebnikov 
8819f9f1acdSKonstantin Khlebnikov 			if (is_write_migration_entry(entry) &&
8820697212aSChristoph Lameter 					is_cow_mapping(vm_flags)) {
8830697212aSChristoph Lameter 				/*
8849f9f1acdSKonstantin Khlebnikov 				 * COW mappings require pages in both
8859f9f1acdSKonstantin Khlebnikov 				 * parent and child to be set to read.
8860697212aSChristoph Lameter 				 */
8870697212aSChristoph Lameter 				make_migration_entry_read(&entry);
8880697212aSChristoph Lameter 				pte = swp_entry_to_pte(entry);
889c3d16e16SCyrill Gorcunov 				if (pte_swp_soft_dirty(*src_pte))
890c3d16e16SCyrill Gorcunov 					pte = pte_swp_mksoft_dirty(pte);
8910697212aSChristoph Lameter 				set_pte_at(src_mm, addr, src_pte, pte);
8920697212aSChristoph Lameter 			}
8931da177e4SLinus Torvalds 		}
894ae859762SHugh Dickins 		goto out_set_pte;
8951da177e4SLinus Torvalds 	}
8961da177e4SLinus Torvalds 
8971da177e4SLinus Torvalds 	/*
8981da177e4SLinus Torvalds 	 * If it's a COW mapping, write protect it both
8991da177e4SLinus Torvalds 	 * in the parent and the child
9001da177e4SLinus Torvalds 	 */
90167121172SLinus Torvalds 	if (is_cow_mapping(vm_flags)) {
9021da177e4SLinus Torvalds 		ptep_set_wrprotect(src_mm, addr, src_pte);
9033dc90795SZachary Amsden 		pte = pte_wrprotect(pte);
9041da177e4SLinus Torvalds 	}
9051da177e4SLinus Torvalds 
9061da177e4SLinus Torvalds 	/*
9071da177e4SLinus Torvalds 	 * If it's a shared mapping, mark it clean in
9081da177e4SLinus Torvalds 	 * the child
9091da177e4SLinus Torvalds 	 */
9101da177e4SLinus Torvalds 	if (vm_flags & VM_SHARED)
9111da177e4SLinus Torvalds 		pte = pte_mkclean(pte);
9121da177e4SLinus Torvalds 	pte = pte_mkold(pte);
9136aab341eSLinus Torvalds 
9146aab341eSLinus Torvalds 	page = vm_normal_page(vma, addr, pte);
9156aab341eSLinus Torvalds 	if (page) {
9161da177e4SLinus Torvalds 		get_page(page);
91753f9263bSKirill A. Shutemov 		page_dup_rmap(page, false);
918eca56ff9SJerome Marchand 		rss[mm_counter(page)]++;
9196aab341eSLinus Torvalds 	}
920ae859762SHugh Dickins 
921ae859762SHugh Dickins out_set_pte:
922ae859762SHugh Dickins 	set_pte_at(dst_mm, addr, dst_pte, pte);
923570a335bSHugh Dickins 	return 0;
9241da177e4SLinus Torvalds }
9251da177e4SLinus Torvalds 
92621bda264SJerome Marchand static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
9271da177e4SLinus Torvalds 		   pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
9281da177e4SLinus Torvalds 		   unsigned long addr, unsigned long end)
9291da177e4SLinus Torvalds {
930c36987e2SDaisuke Nishimura 	pte_t *orig_src_pte, *orig_dst_pte;
9311da177e4SLinus Torvalds 	pte_t *src_pte, *dst_pte;
932c74df32cSHugh Dickins 	spinlock_t *src_ptl, *dst_ptl;
933e040f218SHugh Dickins 	int progress = 0;
934d559db08SKAMEZAWA Hiroyuki 	int rss[NR_MM_COUNTERS];
935570a335bSHugh Dickins 	swp_entry_t entry = (swp_entry_t){0};
9361da177e4SLinus Torvalds 
9371da177e4SLinus Torvalds again:
938d559db08SKAMEZAWA Hiroyuki 	init_rss_vec(rss);
939d559db08SKAMEZAWA Hiroyuki 
940c74df32cSHugh Dickins 	dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
9411da177e4SLinus Torvalds 	if (!dst_pte)
9421da177e4SLinus Torvalds 		return -ENOMEM;
943ece0e2b6SPeter Zijlstra 	src_pte = pte_offset_map(src_pmd, addr);
9444c21e2f2SHugh Dickins 	src_ptl = pte_lockptr(src_mm, src_pmd);
945f20dc5f7SIngo Molnar 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
946c36987e2SDaisuke Nishimura 	orig_src_pte = src_pte;
947c36987e2SDaisuke Nishimura 	orig_dst_pte = dst_pte;
9486606c3e0SZachary Amsden 	arch_enter_lazy_mmu_mode();
9491da177e4SLinus Torvalds 
9501da177e4SLinus Torvalds 	do {
9511da177e4SLinus Torvalds 		/*
9521da177e4SLinus Torvalds 		 * We are holding two locks at this point - either of them
9531da177e4SLinus Torvalds 		 * could generate latencies in another task on another CPU.
9541da177e4SLinus Torvalds 		 */
955e040f218SHugh Dickins 		if (progress >= 32) {
956e040f218SHugh Dickins 			progress = 0;
957e040f218SHugh Dickins 			if (need_resched() ||
95895c354feSNick Piggin 			    spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
9591da177e4SLinus Torvalds 				break;
960e040f218SHugh Dickins 		}
9611da177e4SLinus Torvalds 		if (pte_none(*src_pte)) {
9621da177e4SLinus Torvalds 			progress++;
9631da177e4SLinus Torvalds 			continue;
9641da177e4SLinus Torvalds 		}
965570a335bSHugh Dickins 		entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
966570a335bSHugh Dickins 							vma, addr, rss);
967570a335bSHugh Dickins 		if (entry.val)
968570a335bSHugh Dickins 			break;
9691da177e4SLinus Torvalds 		progress += 8;
9701da177e4SLinus Torvalds 	} while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
9711da177e4SLinus Torvalds 
9726606c3e0SZachary Amsden 	arch_leave_lazy_mmu_mode();
973c74df32cSHugh Dickins 	spin_unlock(src_ptl);
974ece0e2b6SPeter Zijlstra 	pte_unmap(orig_src_pte);
975d559db08SKAMEZAWA Hiroyuki 	add_mm_rss_vec(dst_mm, rss);
976c36987e2SDaisuke Nishimura 	pte_unmap_unlock(orig_dst_pte, dst_ptl);
977c74df32cSHugh Dickins 	cond_resched();
978570a335bSHugh Dickins 
979570a335bSHugh Dickins 	if (entry.val) {
980570a335bSHugh Dickins 		if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
981570a335bSHugh Dickins 			return -ENOMEM;
982570a335bSHugh Dickins 		progress = 0;
983570a335bSHugh Dickins 	}
9841da177e4SLinus Torvalds 	if (addr != end)
9851da177e4SLinus Torvalds 		goto again;
9861da177e4SLinus Torvalds 	return 0;
9871da177e4SLinus Torvalds }
9881da177e4SLinus Torvalds 
9891da177e4SLinus Torvalds static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
9901da177e4SLinus Torvalds 		pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
9911da177e4SLinus Torvalds 		unsigned long addr, unsigned long end)
9921da177e4SLinus Torvalds {
9931da177e4SLinus Torvalds 	pmd_t *src_pmd, *dst_pmd;
9941da177e4SLinus Torvalds 	unsigned long next;
9951da177e4SLinus Torvalds 
9961da177e4SLinus Torvalds 	dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
9971da177e4SLinus Torvalds 	if (!dst_pmd)
9981da177e4SLinus Torvalds 		return -ENOMEM;
9991da177e4SLinus Torvalds 	src_pmd = pmd_offset(src_pud, addr);
10001da177e4SLinus Torvalds 	do {
10011da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
10025c7fb56eSDan Williams 		if (pmd_trans_huge(*src_pmd) || pmd_devmap(*src_pmd)) {
100371e3aac0SAndrea Arcangeli 			int err;
100414d1a55cSAndrea Arcangeli 			VM_BUG_ON(next-addr != HPAGE_PMD_SIZE);
100571e3aac0SAndrea Arcangeli 			err = copy_huge_pmd(dst_mm, src_mm,
100671e3aac0SAndrea Arcangeli 					    dst_pmd, src_pmd, addr, vma);
100771e3aac0SAndrea Arcangeli 			if (err == -ENOMEM)
100871e3aac0SAndrea Arcangeli 				return -ENOMEM;
100971e3aac0SAndrea Arcangeli 			if (!err)
101071e3aac0SAndrea Arcangeli 				continue;
101171e3aac0SAndrea Arcangeli 			/* fall through */
101271e3aac0SAndrea Arcangeli 		}
10131da177e4SLinus Torvalds 		if (pmd_none_or_clear_bad(src_pmd))
10141da177e4SLinus Torvalds 			continue;
10151da177e4SLinus Torvalds 		if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
10161da177e4SLinus Torvalds 						vma, addr, next))
10171da177e4SLinus Torvalds 			return -ENOMEM;
10181da177e4SLinus Torvalds 	} while (dst_pmd++, src_pmd++, addr = next, addr != end);
10191da177e4SLinus Torvalds 	return 0;
10201da177e4SLinus Torvalds }
10211da177e4SLinus Torvalds 
10221da177e4SLinus Torvalds static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
10231da177e4SLinus Torvalds 		pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
10241da177e4SLinus Torvalds 		unsigned long addr, unsigned long end)
10251da177e4SLinus Torvalds {
10261da177e4SLinus Torvalds 	pud_t *src_pud, *dst_pud;
10271da177e4SLinus Torvalds 	unsigned long next;
10281da177e4SLinus Torvalds 
10291da177e4SLinus Torvalds 	dst_pud = pud_alloc(dst_mm, dst_pgd, addr);
10301da177e4SLinus Torvalds 	if (!dst_pud)
10311da177e4SLinus Torvalds 		return -ENOMEM;
10321da177e4SLinus Torvalds 	src_pud = pud_offset(src_pgd, addr);
10331da177e4SLinus Torvalds 	do {
10341da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
10351da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(src_pud))
10361da177e4SLinus Torvalds 			continue;
10371da177e4SLinus Torvalds 		if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
10381da177e4SLinus Torvalds 						vma, addr, next))
10391da177e4SLinus Torvalds 			return -ENOMEM;
10401da177e4SLinus Torvalds 	} while (dst_pud++, src_pud++, addr = next, addr != end);
10411da177e4SLinus Torvalds 	return 0;
10421da177e4SLinus Torvalds }
10431da177e4SLinus Torvalds 
10441da177e4SLinus Torvalds int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
10451da177e4SLinus Torvalds 		struct vm_area_struct *vma)
10461da177e4SLinus Torvalds {
10471da177e4SLinus Torvalds 	pgd_t *src_pgd, *dst_pgd;
10481da177e4SLinus Torvalds 	unsigned long next;
10491da177e4SLinus Torvalds 	unsigned long addr = vma->vm_start;
10501da177e4SLinus Torvalds 	unsigned long end = vma->vm_end;
10512ec74c3eSSagi Grimberg 	unsigned long mmun_start;	/* For mmu_notifiers */
10522ec74c3eSSagi Grimberg 	unsigned long mmun_end;		/* For mmu_notifiers */
10532ec74c3eSSagi Grimberg 	bool is_cow;
1054cddb8a5cSAndrea Arcangeli 	int ret;
10551da177e4SLinus Torvalds 
1056d992895bSNick Piggin 	/*
1057d992895bSNick Piggin 	 * Don't copy ptes where a page fault will fill them correctly.
1058d992895bSNick Piggin 	 * Fork becomes much lighter when there are big shared or private
1059d992895bSNick Piggin 	 * readonly mappings. The tradeoff is that copy_page_range is more
1060d992895bSNick Piggin 	 * efficient than faulting.
1061d992895bSNick Piggin 	 */
10620661a336SKirill A. Shutemov 	if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
10630661a336SKirill A. Shutemov 			!vma->anon_vma)
1064d992895bSNick Piggin 		return 0;
1065d992895bSNick Piggin 
10661da177e4SLinus Torvalds 	if (is_vm_hugetlb_page(vma))
10671da177e4SLinus Torvalds 		return copy_hugetlb_page_range(dst_mm, src_mm, vma);
10681da177e4SLinus Torvalds 
1069b3b9c293SKonstantin Khlebnikov 	if (unlikely(vma->vm_flags & VM_PFNMAP)) {
10702ab64037Svenkatesh.pallipadi@intel.com 		/*
10712ab64037Svenkatesh.pallipadi@intel.com 		 * We do not free on error cases below as remove_vma
10722ab64037Svenkatesh.pallipadi@intel.com 		 * gets called on error from higher level routine
10732ab64037Svenkatesh.pallipadi@intel.com 		 */
10745180da41SSuresh Siddha 		ret = track_pfn_copy(vma);
10752ab64037Svenkatesh.pallipadi@intel.com 		if (ret)
10762ab64037Svenkatesh.pallipadi@intel.com 			return ret;
10772ab64037Svenkatesh.pallipadi@intel.com 	}
10782ab64037Svenkatesh.pallipadi@intel.com 
1079cddb8a5cSAndrea Arcangeli 	/*
1080cddb8a5cSAndrea Arcangeli 	 * We need to invalidate the secondary MMU mappings only when
1081cddb8a5cSAndrea Arcangeli 	 * there could be a permission downgrade on the ptes of the
1082cddb8a5cSAndrea Arcangeli 	 * parent mm. And a permission downgrade will only happen if
1083cddb8a5cSAndrea Arcangeli 	 * is_cow_mapping() returns true.
1084cddb8a5cSAndrea Arcangeli 	 */
10852ec74c3eSSagi Grimberg 	is_cow = is_cow_mapping(vma->vm_flags);
10862ec74c3eSSagi Grimberg 	mmun_start = addr;
10872ec74c3eSSagi Grimberg 	mmun_end   = end;
10882ec74c3eSSagi Grimberg 	if (is_cow)
10892ec74c3eSSagi Grimberg 		mmu_notifier_invalidate_range_start(src_mm, mmun_start,
10902ec74c3eSSagi Grimberg 						    mmun_end);
1091cddb8a5cSAndrea Arcangeli 
1092cddb8a5cSAndrea Arcangeli 	ret = 0;
10931da177e4SLinus Torvalds 	dst_pgd = pgd_offset(dst_mm, addr);
10941da177e4SLinus Torvalds 	src_pgd = pgd_offset(src_mm, addr);
10951da177e4SLinus Torvalds 	do {
10961da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
10971da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(src_pgd))
10981da177e4SLinus Torvalds 			continue;
1099cddb8a5cSAndrea Arcangeli 		if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd,
1100cddb8a5cSAndrea Arcangeli 					    vma, addr, next))) {
1101cddb8a5cSAndrea Arcangeli 			ret = -ENOMEM;
1102cddb8a5cSAndrea Arcangeli 			break;
1103cddb8a5cSAndrea Arcangeli 		}
11041da177e4SLinus Torvalds 	} while (dst_pgd++, src_pgd++, addr = next, addr != end);
1105cddb8a5cSAndrea Arcangeli 
11062ec74c3eSSagi Grimberg 	if (is_cow)
11072ec74c3eSSagi Grimberg 		mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end);
1108cddb8a5cSAndrea Arcangeli 	return ret;
11091da177e4SLinus Torvalds }
11101da177e4SLinus Torvalds 
111151c6f666SRobin Holt static unsigned long zap_pte_range(struct mmu_gather *tlb,
1112b5810039SNick Piggin 				struct vm_area_struct *vma, pmd_t *pmd,
11131da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
111497a89413SPeter Zijlstra 				struct zap_details *details)
11151da177e4SLinus Torvalds {
1116b5810039SNick Piggin 	struct mm_struct *mm = tlb->mm;
1117d16dfc55SPeter Zijlstra 	int force_flush = 0;
1118d559db08SKAMEZAWA Hiroyuki 	int rss[NR_MM_COUNTERS];
111997a89413SPeter Zijlstra 	spinlock_t *ptl;
11205f1a1907SSteven Rostedt 	pte_t *start_pte;
112197a89413SPeter Zijlstra 	pte_t *pte;
11228a5f14a2SKirill A. Shutemov 	swp_entry_t entry;
1123d559db08SKAMEZAWA Hiroyuki 
112407e32661SAneesh Kumar K.V 	tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
1125d16dfc55SPeter Zijlstra again:
1126e303297eSPeter Zijlstra 	init_rss_vec(rss);
11275f1a1907SSteven Rostedt 	start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
11285f1a1907SSteven Rostedt 	pte = start_pte;
11296606c3e0SZachary Amsden 	arch_enter_lazy_mmu_mode();
11301da177e4SLinus Torvalds 	do {
11311da177e4SLinus Torvalds 		pte_t ptent = *pte;
113251c6f666SRobin Holt 		if (pte_none(ptent)) {
11331da177e4SLinus Torvalds 			continue;
113451c6f666SRobin Holt 		}
113551c6f666SRobin Holt 
11366f5e6b9eSHugh Dickins 		if (pte_present(ptent)) {
11376f5e6b9eSHugh Dickins 			struct page *page;
11386f5e6b9eSHugh Dickins 
11396aab341eSLinus Torvalds 			page = vm_normal_page(vma, addr, ptent);
11401da177e4SLinus Torvalds 			if (unlikely(details) && page) {
11411da177e4SLinus Torvalds 				/*
11421da177e4SLinus Torvalds 				 * unmap_shared_mapping_pages() wants to
11431da177e4SLinus Torvalds 				 * invalidate cache without truncating:
11441da177e4SLinus Torvalds 				 * unmap shared but keep private pages.
11451da177e4SLinus Torvalds 				 */
11461da177e4SLinus Torvalds 				if (details->check_mapping &&
1147800d8c63SKirill A. Shutemov 				    details->check_mapping != page_rmapping(page))
11481da177e4SLinus Torvalds 					continue;
11491da177e4SLinus Torvalds 			}
1150b5810039SNick Piggin 			ptent = ptep_get_and_clear_full(mm, addr, pte,
1151a600388dSZachary Amsden 							tlb->fullmm);
11521da177e4SLinus Torvalds 			tlb_remove_tlb_entry(tlb, pte, addr);
11531da177e4SLinus Torvalds 			if (unlikely(!page))
11541da177e4SLinus Torvalds 				continue;
1155eca56ff9SJerome Marchand 
1156eca56ff9SJerome Marchand 			if (!PageAnon(page)) {
11571cf35d47SLinus Torvalds 				if (pte_dirty(ptent)) {
1158aac45363SMichal Hocko 					/*
1159aac45363SMichal Hocko 					 * oom_reaper cannot tear down dirty
1160aac45363SMichal Hocko 					 * pages
1161aac45363SMichal Hocko 					 */
1162aac45363SMichal Hocko 					if (unlikely(details && details->ignore_dirty))
1163aac45363SMichal Hocko 						continue;
11641cf35d47SLinus Torvalds 					force_flush = 1;
11656237bcd9SHugh Dickins 					set_page_dirty(page);
11661cf35d47SLinus Torvalds 				}
11674917e5d0SJohannes Weiner 				if (pte_young(ptent) &&
116864363aadSJoe Perches 				    likely(!(vma->vm_flags & VM_SEQ_READ)))
1169bf3f3bc5SNick Piggin 					mark_page_accessed(page);
11706237bcd9SHugh Dickins 			}
1171eca56ff9SJerome Marchand 			rss[mm_counter(page)]--;
1172d281ee61SKirill A. Shutemov 			page_remove_rmap(page, false);
11733dc14741SHugh Dickins 			if (unlikely(page_mapcount(page) < 0))
11743dc14741SHugh Dickins 				print_bad_pte(vma, addr, ptent, page);
1175e9d55e15SAneesh Kumar K.V 			if (unlikely(__tlb_remove_page(tlb, page))) {
11761cf35d47SLinus Torvalds 				force_flush = 1;
1177ce9ec37bSWill Deacon 				addr += PAGE_SIZE;
1178d16dfc55SPeter Zijlstra 				break;
11791cf35d47SLinus Torvalds 			}
11801da177e4SLinus Torvalds 			continue;
11811da177e4SLinus Torvalds 		}
1182aac45363SMichal Hocko 		/* only check swap_entries if explicitly asked for in details */
1183aac45363SMichal Hocko 		if (unlikely(details && !details->check_swap_entries))
11841da177e4SLinus Torvalds 			continue;
1185b084d435SKAMEZAWA Hiroyuki 
11868a5f14a2SKirill A. Shutemov 		entry = pte_to_swp_entry(ptent);
1187b084d435SKAMEZAWA Hiroyuki 		if (!non_swap_entry(entry))
1188b084d435SKAMEZAWA Hiroyuki 			rss[MM_SWAPENTS]--;
11899f9f1acdSKonstantin Khlebnikov 		else if (is_migration_entry(entry)) {
11909f9f1acdSKonstantin Khlebnikov 			struct page *page;
11919f9f1acdSKonstantin Khlebnikov 
11929f9f1acdSKonstantin Khlebnikov 			page = migration_entry_to_page(entry);
1193eca56ff9SJerome Marchand 			rss[mm_counter(page)]--;
11949f9f1acdSKonstantin Khlebnikov 		}
1195b084d435SKAMEZAWA Hiroyuki 		if (unlikely(!free_swap_and_cache(entry)))
11962509ef26SHugh Dickins 			print_bad_pte(vma, addr, ptent, NULL);
11979888a1caSZachary Amsden 		pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
119897a89413SPeter Zijlstra 	} while (pte++, addr += PAGE_SIZE, addr != end);
1199ae859762SHugh Dickins 
1200d559db08SKAMEZAWA Hiroyuki 	add_mm_rss_vec(mm, rss);
12016606c3e0SZachary Amsden 	arch_leave_lazy_mmu_mode();
120251c6f666SRobin Holt 
12031cf35d47SLinus Torvalds 	/* Do the actual TLB flush before dropping ptl */
1204fb7332a9SWill Deacon 	if (force_flush)
12051cf35d47SLinus Torvalds 		tlb_flush_mmu_tlbonly(tlb);
12061cf35d47SLinus Torvalds 	pte_unmap_unlock(start_pte, ptl);
12071cf35d47SLinus Torvalds 
12081cf35d47SLinus Torvalds 	/*
12091cf35d47SLinus Torvalds 	 * If we forced a TLB flush (either due to running out of
12101cf35d47SLinus Torvalds 	 * batch buffers or because we needed to flush dirty TLB
12111cf35d47SLinus Torvalds 	 * entries before releasing the ptl), free the batched
12121cf35d47SLinus Torvalds 	 * memory too. Restart if we didn't do everything.
12131cf35d47SLinus Torvalds 	 */
12141cf35d47SLinus Torvalds 	if (force_flush) {
12151cf35d47SLinus Torvalds 		force_flush = 0;
12161cf35d47SLinus Torvalds 		tlb_flush_mmu_free(tlb);
12172b047252SLinus Torvalds 		if (addr != end)
1218d16dfc55SPeter Zijlstra 			goto again;
1219d16dfc55SPeter Zijlstra 	}
1220d16dfc55SPeter Zijlstra 
122151c6f666SRobin Holt 	return addr;
12221da177e4SLinus Torvalds }
12231da177e4SLinus Torvalds 
122451c6f666SRobin Holt static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1225b5810039SNick Piggin 				struct vm_area_struct *vma, pud_t *pud,
12261da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
122797a89413SPeter Zijlstra 				struct zap_details *details)
12281da177e4SLinus Torvalds {
12291da177e4SLinus Torvalds 	pmd_t *pmd;
12301da177e4SLinus Torvalds 	unsigned long next;
12311da177e4SLinus Torvalds 
12321da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
12331da177e4SLinus Torvalds 	do {
12341da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
12355c7fb56eSDan Williams 		if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
123614d1a55cSAndrea Arcangeli 			if (next - addr != HPAGE_PMD_SIZE) {
123768428398SHugh Dickins 				VM_BUG_ON_VMA(vma_is_anonymous(vma) &&
123868428398SHugh Dickins 				    !rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1239fd60775aSDavid Rientjes 				__split_huge_pmd(vma, pmd, addr, false, NULL);
1240f21760b1SShaohua Li 			} else if (zap_huge_pmd(tlb, vma, pmd, addr))
12411a5a9906SAndrea Arcangeli 				goto next;
124271e3aac0SAndrea Arcangeli 			/* fall through */
124371e3aac0SAndrea Arcangeli 		}
12441a5a9906SAndrea Arcangeli 		/*
12451a5a9906SAndrea Arcangeli 		 * Here there can be other concurrent MADV_DONTNEED or
12461a5a9906SAndrea Arcangeli 		 * trans huge page faults running, and if the pmd is
12471a5a9906SAndrea Arcangeli 		 * none or trans huge it can change under us. This is
12481a5a9906SAndrea Arcangeli 		 * because MADV_DONTNEED holds the mmap_sem in read
12491a5a9906SAndrea Arcangeli 		 * mode.
12501a5a9906SAndrea Arcangeli 		 */
12511a5a9906SAndrea Arcangeli 		if (pmd_none_or_trans_huge_or_clear_bad(pmd))
12521a5a9906SAndrea Arcangeli 			goto next;
125397a89413SPeter Zijlstra 		next = zap_pte_range(tlb, vma, pmd, addr, next, details);
12541a5a9906SAndrea Arcangeli next:
125597a89413SPeter Zijlstra 		cond_resched();
125697a89413SPeter Zijlstra 	} while (pmd++, addr = next, addr != end);
125751c6f666SRobin Holt 
125851c6f666SRobin Holt 	return addr;
12591da177e4SLinus Torvalds }
12601da177e4SLinus Torvalds 
126151c6f666SRobin Holt static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1262b5810039SNick Piggin 				struct vm_area_struct *vma, pgd_t *pgd,
12631da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
126497a89413SPeter Zijlstra 				struct zap_details *details)
12651da177e4SLinus Torvalds {
12661da177e4SLinus Torvalds 	pud_t *pud;
12671da177e4SLinus Torvalds 	unsigned long next;
12681da177e4SLinus Torvalds 
12691da177e4SLinus Torvalds 	pud = pud_offset(pgd, addr);
12701da177e4SLinus Torvalds 	do {
12711da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
127297a89413SPeter Zijlstra 		if (pud_none_or_clear_bad(pud))
12731da177e4SLinus Torvalds 			continue;
127497a89413SPeter Zijlstra 		next = zap_pmd_range(tlb, vma, pud, addr, next, details);
127597a89413SPeter Zijlstra 	} while (pud++, addr = next, addr != end);
127651c6f666SRobin Holt 
127751c6f666SRobin Holt 	return addr;
12781da177e4SLinus Torvalds }
12791da177e4SLinus Torvalds 
1280aac45363SMichal Hocko void unmap_page_range(struct mmu_gather *tlb,
128151c6f666SRobin Holt 			     struct vm_area_struct *vma,
12821da177e4SLinus Torvalds 			     unsigned long addr, unsigned long end,
128397a89413SPeter Zijlstra 			     struct zap_details *details)
12841da177e4SLinus Torvalds {
12851da177e4SLinus Torvalds 	pgd_t *pgd;
12861da177e4SLinus Torvalds 	unsigned long next;
12871da177e4SLinus Torvalds 
12881da177e4SLinus Torvalds 	BUG_ON(addr >= end);
12891da177e4SLinus Torvalds 	tlb_start_vma(tlb, vma);
12901da177e4SLinus Torvalds 	pgd = pgd_offset(vma->vm_mm, addr);
12911da177e4SLinus Torvalds 	do {
12921da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
129397a89413SPeter Zijlstra 		if (pgd_none_or_clear_bad(pgd))
12941da177e4SLinus Torvalds 			continue;
129597a89413SPeter Zijlstra 		next = zap_pud_range(tlb, vma, pgd, addr, next, details);
129697a89413SPeter Zijlstra 	} while (pgd++, addr = next, addr != end);
12971da177e4SLinus Torvalds 	tlb_end_vma(tlb, vma);
12981da177e4SLinus Torvalds }
12991da177e4SLinus Torvalds 
1300f5cc4eefSAl Viro 
1301f5cc4eefSAl Viro static void unmap_single_vma(struct mmu_gather *tlb,
13021da177e4SLinus Torvalds 		struct vm_area_struct *vma, unsigned long start_addr,
13034f74d2c8SLinus Torvalds 		unsigned long end_addr,
13041da177e4SLinus Torvalds 		struct zap_details *details)
13051da177e4SLinus Torvalds {
1306f5cc4eefSAl Viro 	unsigned long start = max(vma->vm_start, start_addr);
13071da177e4SLinus Torvalds 	unsigned long end;
13081da177e4SLinus Torvalds 
13091da177e4SLinus Torvalds 	if (start >= vma->vm_end)
1310f5cc4eefSAl Viro 		return;
13111da177e4SLinus Torvalds 	end = min(vma->vm_end, end_addr);
13121da177e4SLinus Torvalds 	if (end <= vma->vm_start)
1313f5cc4eefSAl Viro 		return;
13141da177e4SLinus Torvalds 
1315cbc91f71SSrikar Dronamraju 	if (vma->vm_file)
1316cbc91f71SSrikar Dronamraju 		uprobe_munmap(vma, start, end);
1317cbc91f71SSrikar Dronamraju 
1318b3b9c293SKonstantin Khlebnikov 	if (unlikely(vma->vm_flags & VM_PFNMAP))
13195180da41SSuresh Siddha 		untrack_pfn(vma, 0, 0);
13202ab64037Svenkatesh.pallipadi@intel.com 
13218b2a1238SAl Viro 	if (start != end) {
132251c6f666SRobin Holt 		if (unlikely(is_vm_hugetlb_page(vma))) {
1323a137e1ccSAndi Kleen 			/*
1324a137e1ccSAndi Kleen 			 * It is undesirable to test vma->vm_file as it
1325a137e1ccSAndi Kleen 			 * should be non-null for valid hugetlb area.
1326a137e1ccSAndi Kleen 			 * However, vm_file will be NULL in the error
13277aa6b4adSDavidlohr Bueso 			 * cleanup path of mmap_region. When
1328a137e1ccSAndi Kleen 			 * hugetlbfs ->mmap method fails,
13297aa6b4adSDavidlohr Bueso 			 * mmap_region() nullifies vma->vm_file
1330a137e1ccSAndi Kleen 			 * before calling this function to clean up.
1331a137e1ccSAndi Kleen 			 * Since no pte has actually been setup, it is
1332a137e1ccSAndi Kleen 			 * safe to do nothing in this case.
1333a137e1ccSAndi Kleen 			 */
133424669e58SAneesh Kumar K.V 			if (vma->vm_file) {
133583cde9e8SDavidlohr Bueso 				i_mmap_lock_write(vma->vm_file->f_mapping);
1336d833352aSMel Gorman 				__unmap_hugepage_range_final(tlb, vma, start, end, NULL);
133783cde9e8SDavidlohr Bueso 				i_mmap_unlock_write(vma->vm_file->f_mapping);
133824669e58SAneesh Kumar K.V 			}
133951c6f666SRobin Holt 		} else
1340038c7aa1SAl Viro 			unmap_page_range(tlb, vma, start, end, details);
134197a89413SPeter Zijlstra 	}
134251c6f666SRobin Holt }
13431da177e4SLinus Torvalds 
1344f5cc4eefSAl Viro /**
1345f5cc4eefSAl Viro  * unmap_vmas - unmap a range of memory covered by a list of vma's
1346f5cc4eefSAl Viro  * @tlb: address of the caller's struct mmu_gather
1347f5cc4eefSAl Viro  * @vma: the starting vma
1348f5cc4eefSAl Viro  * @start_addr: virtual address at which to start unmapping
1349f5cc4eefSAl Viro  * @end_addr: virtual address at which to end unmapping
1350f5cc4eefSAl Viro  *
1351f5cc4eefSAl Viro  * Unmap all pages in the vma list.
1352f5cc4eefSAl Viro  *
1353f5cc4eefSAl Viro  * Only addresses between `start' and `end' will be unmapped.
1354f5cc4eefSAl Viro  *
1355f5cc4eefSAl Viro  * The VMA list must be sorted in ascending virtual address order.
1356f5cc4eefSAl Viro  *
1357f5cc4eefSAl Viro  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1358f5cc4eefSAl Viro  * range after unmap_vmas() returns.  So the only responsibility here is to
1359f5cc4eefSAl Viro  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1360f5cc4eefSAl Viro  * drops the lock and schedules.
1361f5cc4eefSAl Viro  */
1362f5cc4eefSAl Viro void unmap_vmas(struct mmu_gather *tlb,
1363f5cc4eefSAl Viro 		struct vm_area_struct *vma, unsigned long start_addr,
13644f74d2c8SLinus Torvalds 		unsigned long end_addr)
1365f5cc4eefSAl Viro {
1366f5cc4eefSAl Viro 	struct mm_struct *mm = vma->vm_mm;
1367f5cc4eefSAl Viro 
1368f5cc4eefSAl Viro 	mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1369f5cc4eefSAl Viro 	for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
13704f74d2c8SLinus Torvalds 		unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1371cddb8a5cSAndrea Arcangeli 	mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
13721da177e4SLinus Torvalds }
13731da177e4SLinus Torvalds 
13741da177e4SLinus Torvalds /**
13751da177e4SLinus Torvalds  * zap_page_range - remove user pages in a given range
13761da177e4SLinus Torvalds  * @vma: vm_area_struct holding the applicable pages
1377eb4546bbSRandy Dunlap  * @start: starting address of pages to zap
13781da177e4SLinus Torvalds  * @size: number of bytes to zap
13798a5f14a2SKirill A. Shutemov  * @details: details of shared cache invalidation
1380f5cc4eefSAl Viro  *
1381f5cc4eefSAl Viro  * Caller must protect the VMA list
13821da177e4SLinus Torvalds  */
13837e027b14SLinus Torvalds void zap_page_range(struct vm_area_struct *vma, unsigned long start,
13841da177e4SLinus Torvalds 		unsigned long size, struct zap_details *details)
13851da177e4SLinus Torvalds {
13861da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
1387d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
13887e027b14SLinus Torvalds 	unsigned long end = start + size;
13891da177e4SLinus Torvalds 
13901da177e4SLinus Torvalds 	lru_add_drain();
13912b047252SLinus Torvalds 	tlb_gather_mmu(&tlb, mm, start, end);
1392365e9c87SHugh Dickins 	update_hiwater_rss(mm);
13937e027b14SLinus Torvalds 	mmu_notifier_invalidate_range_start(mm, start, end);
13947e027b14SLinus Torvalds 	for ( ; vma && vma->vm_start < end; vma = vma->vm_next)
13954f74d2c8SLinus Torvalds 		unmap_single_vma(&tlb, vma, start, end, details);
13967e027b14SLinus Torvalds 	mmu_notifier_invalidate_range_end(mm, start, end);
13977e027b14SLinus Torvalds 	tlb_finish_mmu(&tlb, start, end);
13981da177e4SLinus Torvalds }
13991da177e4SLinus Torvalds 
1400c627f9ccSJack Steiner /**
1401f5cc4eefSAl Viro  * zap_page_range_single - remove user pages in a given range
1402f5cc4eefSAl Viro  * @vma: vm_area_struct holding the applicable pages
1403f5cc4eefSAl Viro  * @address: starting address of pages to zap
1404f5cc4eefSAl Viro  * @size: number of bytes to zap
14058a5f14a2SKirill A. Shutemov  * @details: details of shared cache invalidation
1406f5cc4eefSAl Viro  *
1407f5cc4eefSAl Viro  * The range must fit into one VMA.
1408f5cc4eefSAl Viro  */
1409f5cc4eefSAl Viro static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1410f5cc4eefSAl Viro 		unsigned long size, struct zap_details *details)
1411f5cc4eefSAl Viro {
1412f5cc4eefSAl Viro 	struct mm_struct *mm = vma->vm_mm;
1413f5cc4eefSAl Viro 	struct mmu_gather tlb;
1414f5cc4eefSAl Viro 	unsigned long end = address + size;
1415f5cc4eefSAl Viro 
1416f5cc4eefSAl Viro 	lru_add_drain();
14172b047252SLinus Torvalds 	tlb_gather_mmu(&tlb, mm, address, end);
1418f5cc4eefSAl Viro 	update_hiwater_rss(mm);
1419f5cc4eefSAl Viro 	mmu_notifier_invalidate_range_start(mm, address, end);
14204f74d2c8SLinus Torvalds 	unmap_single_vma(&tlb, vma, address, end, details);
1421f5cc4eefSAl Viro 	mmu_notifier_invalidate_range_end(mm, address, end);
1422f5cc4eefSAl Viro 	tlb_finish_mmu(&tlb, address, end);
14231da177e4SLinus Torvalds }
14241da177e4SLinus Torvalds 
1425c627f9ccSJack Steiner /**
1426c627f9ccSJack Steiner  * zap_vma_ptes - remove ptes mapping the vma
1427c627f9ccSJack Steiner  * @vma: vm_area_struct holding ptes to be zapped
1428c627f9ccSJack Steiner  * @address: starting address of pages to zap
1429c627f9ccSJack Steiner  * @size: number of bytes to zap
1430c627f9ccSJack Steiner  *
1431c627f9ccSJack Steiner  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1432c627f9ccSJack Steiner  *
1433c627f9ccSJack Steiner  * The entire address range must be fully contained within the vma.
1434c627f9ccSJack Steiner  *
1435c627f9ccSJack Steiner  * Returns 0 if successful.
1436c627f9ccSJack Steiner  */
1437c627f9ccSJack Steiner int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1438c627f9ccSJack Steiner 		unsigned long size)
1439c627f9ccSJack Steiner {
1440c627f9ccSJack Steiner 	if (address < vma->vm_start || address + size > vma->vm_end ||
1441c627f9ccSJack Steiner 	    		!(vma->vm_flags & VM_PFNMAP))
1442c627f9ccSJack Steiner 		return -1;
1443f5cc4eefSAl Viro 	zap_page_range_single(vma, address, size, NULL);
1444c627f9ccSJack Steiner 	return 0;
1445c627f9ccSJack Steiner }
1446c627f9ccSJack Steiner EXPORT_SYMBOL_GPL(zap_vma_ptes);
1447c627f9ccSJack Steiner 
144825ca1d6cSNamhyung Kim pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1449920c7a5dSHarvey Harrison 			spinlock_t **ptl)
1450c9cfcddfSLinus Torvalds {
1451c9cfcddfSLinus Torvalds 	pgd_t * pgd = pgd_offset(mm, addr);
1452c9cfcddfSLinus Torvalds 	pud_t * pud = pud_alloc(mm, pgd, addr);
1453c9cfcddfSLinus Torvalds 	if (pud) {
145449c91fb0STrond Myklebust 		pmd_t * pmd = pmd_alloc(mm, pud, addr);
1455f66055abSAndrea Arcangeli 		if (pmd) {
1456f66055abSAndrea Arcangeli 			VM_BUG_ON(pmd_trans_huge(*pmd));
1457c9cfcddfSLinus Torvalds 			return pte_alloc_map_lock(mm, pmd, addr, ptl);
1458c9cfcddfSLinus Torvalds 		}
1459f66055abSAndrea Arcangeli 	}
1460c9cfcddfSLinus Torvalds 	return NULL;
1461c9cfcddfSLinus Torvalds }
1462c9cfcddfSLinus Torvalds 
14631da177e4SLinus Torvalds /*
1464238f58d8SLinus Torvalds  * This is the old fallback for page remapping.
1465238f58d8SLinus Torvalds  *
1466238f58d8SLinus Torvalds  * For historical reasons, it only allows reserved pages. Only
1467238f58d8SLinus Torvalds  * old drivers should use this, and they needed to mark their
1468238f58d8SLinus Torvalds  * pages reserved for the old functions anyway.
1469238f58d8SLinus Torvalds  */
1470423bad60SNick Piggin static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1471423bad60SNick Piggin 			struct page *page, pgprot_t prot)
1472238f58d8SLinus Torvalds {
1473423bad60SNick Piggin 	struct mm_struct *mm = vma->vm_mm;
1474238f58d8SLinus Torvalds 	int retval;
1475238f58d8SLinus Torvalds 	pte_t *pte;
1476238f58d8SLinus Torvalds 	spinlock_t *ptl;
1477238f58d8SLinus Torvalds 
1478238f58d8SLinus Torvalds 	retval = -EINVAL;
1479a145dd41SLinus Torvalds 	if (PageAnon(page))
14805b4e655eSKAMEZAWA Hiroyuki 		goto out;
1481238f58d8SLinus Torvalds 	retval = -ENOMEM;
1482238f58d8SLinus Torvalds 	flush_dcache_page(page);
1483c9cfcddfSLinus Torvalds 	pte = get_locked_pte(mm, addr, &ptl);
1484238f58d8SLinus Torvalds 	if (!pte)
14855b4e655eSKAMEZAWA Hiroyuki 		goto out;
1486238f58d8SLinus Torvalds 	retval = -EBUSY;
1487238f58d8SLinus Torvalds 	if (!pte_none(*pte))
1488238f58d8SLinus Torvalds 		goto out_unlock;
1489238f58d8SLinus Torvalds 
1490238f58d8SLinus Torvalds 	/* Ok, finally just insert the thing.. */
1491238f58d8SLinus Torvalds 	get_page(page);
1492eca56ff9SJerome Marchand 	inc_mm_counter_fast(mm, mm_counter_file(page));
1493dd78feddSKirill A. Shutemov 	page_add_file_rmap(page, false);
1494238f58d8SLinus Torvalds 	set_pte_at(mm, addr, pte, mk_pte(page, prot));
1495238f58d8SLinus Torvalds 
1496238f58d8SLinus Torvalds 	retval = 0;
14978a9f3ccdSBalbir Singh 	pte_unmap_unlock(pte, ptl);
14988a9f3ccdSBalbir Singh 	return retval;
1499238f58d8SLinus Torvalds out_unlock:
1500238f58d8SLinus Torvalds 	pte_unmap_unlock(pte, ptl);
1501238f58d8SLinus Torvalds out:
1502238f58d8SLinus Torvalds 	return retval;
1503238f58d8SLinus Torvalds }
1504238f58d8SLinus Torvalds 
1505bfa5bf6dSRolf Eike Beer /**
1506bfa5bf6dSRolf Eike Beer  * vm_insert_page - insert single page into user vma
1507bfa5bf6dSRolf Eike Beer  * @vma: user vma to map to
1508bfa5bf6dSRolf Eike Beer  * @addr: target user address of this page
1509bfa5bf6dSRolf Eike Beer  * @page: source kernel page
1510bfa5bf6dSRolf Eike Beer  *
1511a145dd41SLinus Torvalds  * This allows drivers to insert individual pages they've allocated
1512a145dd41SLinus Torvalds  * into a user vma.
1513a145dd41SLinus Torvalds  *
1514a145dd41SLinus Torvalds  * The page has to be a nice clean _individual_ kernel allocation.
1515a145dd41SLinus Torvalds  * If you allocate a compound page, you need to have marked it as
1516a145dd41SLinus Torvalds  * such (__GFP_COMP), or manually just split the page up yourself
15178dfcc9baSNick Piggin  * (see split_page()).
1518a145dd41SLinus Torvalds  *
1519a145dd41SLinus Torvalds  * NOTE! Traditionally this was done with "remap_pfn_range()" which
1520a145dd41SLinus Torvalds  * took an arbitrary page protection parameter. This doesn't allow
1521a145dd41SLinus Torvalds  * that. Your vma protection will have to be set up correctly, which
1522a145dd41SLinus Torvalds  * means that if you want a shared writable mapping, you'd better
1523a145dd41SLinus Torvalds  * ask for a shared writable mapping!
1524a145dd41SLinus Torvalds  *
1525a145dd41SLinus Torvalds  * The page does not need to be reserved.
15264b6e1e37SKonstantin Khlebnikov  *
15274b6e1e37SKonstantin Khlebnikov  * Usually this function is called from f_op->mmap() handler
15284b6e1e37SKonstantin Khlebnikov  * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
15294b6e1e37SKonstantin Khlebnikov  * Caller must set VM_MIXEDMAP on vma if it wants to call this
15304b6e1e37SKonstantin Khlebnikov  * function from other places, for example from page-fault handler.
1531a145dd41SLinus Torvalds  */
1532423bad60SNick Piggin int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1533423bad60SNick Piggin 			struct page *page)
1534a145dd41SLinus Torvalds {
1535a145dd41SLinus Torvalds 	if (addr < vma->vm_start || addr >= vma->vm_end)
1536a145dd41SLinus Torvalds 		return -EFAULT;
1537a145dd41SLinus Torvalds 	if (!page_count(page))
1538a145dd41SLinus Torvalds 		return -EINVAL;
15394b6e1e37SKonstantin Khlebnikov 	if (!(vma->vm_flags & VM_MIXEDMAP)) {
15404b6e1e37SKonstantin Khlebnikov 		BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
15414b6e1e37SKonstantin Khlebnikov 		BUG_ON(vma->vm_flags & VM_PFNMAP);
15424b6e1e37SKonstantin Khlebnikov 		vma->vm_flags |= VM_MIXEDMAP;
15434b6e1e37SKonstantin Khlebnikov 	}
1544423bad60SNick Piggin 	return insert_page(vma, addr, page, vma->vm_page_prot);
1545a145dd41SLinus Torvalds }
1546e3c3374fSLinus Torvalds EXPORT_SYMBOL(vm_insert_page);
1547a145dd41SLinus Torvalds 
1548423bad60SNick Piggin static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
154901c8f1c4SDan Williams 			pfn_t pfn, pgprot_t prot)
1550423bad60SNick Piggin {
1551423bad60SNick Piggin 	struct mm_struct *mm = vma->vm_mm;
1552423bad60SNick Piggin 	int retval;
1553423bad60SNick Piggin 	pte_t *pte, entry;
1554423bad60SNick Piggin 	spinlock_t *ptl;
1555423bad60SNick Piggin 
1556423bad60SNick Piggin 	retval = -ENOMEM;
1557423bad60SNick Piggin 	pte = get_locked_pte(mm, addr, &ptl);
1558423bad60SNick Piggin 	if (!pte)
1559423bad60SNick Piggin 		goto out;
1560423bad60SNick Piggin 	retval = -EBUSY;
1561423bad60SNick Piggin 	if (!pte_none(*pte))
1562423bad60SNick Piggin 		goto out_unlock;
1563423bad60SNick Piggin 
1564423bad60SNick Piggin 	/* Ok, finally just insert the thing.. */
156501c8f1c4SDan Williams 	if (pfn_t_devmap(pfn))
156601c8f1c4SDan Williams 		entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
156701c8f1c4SDan Williams 	else
156801c8f1c4SDan Williams 		entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1569423bad60SNick Piggin 	set_pte_at(mm, addr, pte, entry);
15704b3073e1SRussell King 	update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1571423bad60SNick Piggin 
1572423bad60SNick Piggin 	retval = 0;
1573423bad60SNick Piggin out_unlock:
1574423bad60SNick Piggin 	pte_unmap_unlock(pte, ptl);
1575423bad60SNick Piggin out:
1576423bad60SNick Piggin 	return retval;
1577423bad60SNick Piggin }
1578423bad60SNick Piggin 
1579e0dc0d8fSNick Piggin /**
1580e0dc0d8fSNick Piggin  * vm_insert_pfn - insert single pfn into user vma
1581e0dc0d8fSNick Piggin  * @vma: user vma to map to
1582e0dc0d8fSNick Piggin  * @addr: target user address of this page
1583e0dc0d8fSNick Piggin  * @pfn: source kernel pfn
1584e0dc0d8fSNick Piggin  *
1585c462f179SRobert P. J. Day  * Similar to vm_insert_page, this allows drivers to insert individual pages
1586e0dc0d8fSNick Piggin  * they've allocated into a user vma. Same comments apply.
1587e0dc0d8fSNick Piggin  *
1588e0dc0d8fSNick Piggin  * This function should only be called from a vm_ops->fault handler, and
1589e0dc0d8fSNick Piggin  * in that case the handler should return NULL.
15900d71d10aSNick Piggin  *
15910d71d10aSNick Piggin  * vma cannot be a COW mapping.
15920d71d10aSNick Piggin  *
15930d71d10aSNick Piggin  * As this is called only for pages that do not currently exist, we
15940d71d10aSNick Piggin  * do not need to flush old virtual caches or the TLB.
1595e0dc0d8fSNick Piggin  */
1596e0dc0d8fSNick Piggin int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1597e0dc0d8fSNick Piggin 			unsigned long pfn)
1598e0dc0d8fSNick Piggin {
15991745cbc5SAndy Lutomirski 	return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
16001745cbc5SAndy Lutomirski }
16011745cbc5SAndy Lutomirski EXPORT_SYMBOL(vm_insert_pfn);
16021745cbc5SAndy Lutomirski 
16031745cbc5SAndy Lutomirski /**
16041745cbc5SAndy Lutomirski  * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
16051745cbc5SAndy Lutomirski  * @vma: user vma to map to
16061745cbc5SAndy Lutomirski  * @addr: target user address of this page
16071745cbc5SAndy Lutomirski  * @pfn: source kernel pfn
16081745cbc5SAndy Lutomirski  * @pgprot: pgprot flags for the inserted page
16091745cbc5SAndy Lutomirski  *
16101745cbc5SAndy Lutomirski  * This is exactly like vm_insert_pfn, except that it allows drivers to
16111745cbc5SAndy Lutomirski  * to override pgprot on a per-page basis.
16121745cbc5SAndy Lutomirski  *
16131745cbc5SAndy Lutomirski  * This only makes sense for IO mappings, and it makes no sense for
16141745cbc5SAndy Lutomirski  * cow mappings.  In general, using multiple vmas is preferable;
16151745cbc5SAndy Lutomirski  * vm_insert_pfn_prot should only be used if using multiple VMAs is
16161745cbc5SAndy Lutomirski  * impractical.
16171745cbc5SAndy Lutomirski  */
16181745cbc5SAndy Lutomirski int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
16191745cbc5SAndy Lutomirski 			unsigned long pfn, pgprot_t pgprot)
16201745cbc5SAndy Lutomirski {
16212ab64037Svenkatesh.pallipadi@intel.com 	int ret;
16227e675137SNick Piggin 	/*
16237e675137SNick Piggin 	 * Technically, architectures with pte_special can avoid all these
16247e675137SNick Piggin 	 * restrictions (same for remap_pfn_range).  However we would like
16257e675137SNick Piggin 	 * consistency in testing and feature parity among all, so we should
16267e675137SNick Piggin 	 * try to keep these invariants in place for everybody.
16277e675137SNick Piggin 	 */
1628b379d790SJared Hulbert 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1629b379d790SJared Hulbert 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1630b379d790SJared Hulbert 						(VM_PFNMAP|VM_MIXEDMAP));
1631b379d790SJared Hulbert 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1632b379d790SJared Hulbert 	BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1633e0dc0d8fSNick Piggin 
1634423bad60SNick Piggin 	if (addr < vma->vm_start || addr >= vma->vm_end)
1635423bad60SNick Piggin 		return -EFAULT;
1636308a047cSBorislav Petkov 
1637308a047cSBorislav Petkov 	track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
16382ab64037Svenkatesh.pallipadi@intel.com 
163901c8f1c4SDan Williams 	ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot);
16402ab64037Svenkatesh.pallipadi@intel.com 
16412ab64037Svenkatesh.pallipadi@intel.com 	return ret;
1642e0dc0d8fSNick Piggin }
16431745cbc5SAndy Lutomirski EXPORT_SYMBOL(vm_insert_pfn_prot);
1644e0dc0d8fSNick Piggin 
1645423bad60SNick Piggin int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
164601c8f1c4SDan Williams 			pfn_t pfn)
1647423bad60SNick Piggin {
164887744ab3SDan Williams 	pgprot_t pgprot = vma->vm_page_prot;
164987744ab3SDan Williams 
1650423bad60SNick Piggin 	BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1651423bad60SNick Piggin 
1652423bad60SNick Piggin 	if (addr < vma->vm_start || addr >= vma->vm_end)
1653423bad60SNick Piggin 		return -EFAULT;
1654308a047cSBorislav Petkov 
1655308a047cSBorislav Petkov 	track_pfn_insert(vma, &pgprot, pfn);
1656423bad60SNick Piggin 
1657423bad60SNick Piggin 	/*
1658423bad60SNick Piggin 	 * If we don't have pte special, then we have to use the pfn_valid()
1659423bad60SNick Piggin 	 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1660423bad60SNick Piggin 	 * refcount the page if pfn_valid is true (hence insert_page rather
166162eede62SHugh Dickins 	 * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
166262eede62SHugh Dickins 	 * without pte special, it would there be refcounted as a normal page.
1663423bad60SNick Piggin 	 */
166403fc2da6SDan Williams 	if (!HAVE_PTE_SPECIAL && !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1665423bad60SNick Piggin 		struct page *page;
1666423bad60SNick Piggin 
166703fc2da6SDan Williams 		/*
166803fc2da6SDan Williams 		 * At this point we are committed to insert_page()
166903fc2da6SDan Williams 		 * regardless of whether the caller specified flags that
167003fc2da6SDan Williams 		 * result in pfn_t_has_page() == false.
167103fc2da6SDan Williams 		 */
167203fc2da6SDan Williams 		page = pfn_to_page(pfn_t_to_pfn(pfn));
167387744ab3SDan Williams 		return insert_page(vma, addr, page, pgprot);
1674423bad60SNick Piggin 	}
167587744ab3SDan Williams 	return insert_pfn(vma, addr, pfn, pgprot);
1676423bad60SNick Piggin }
1677423bad60SNick Piggin EXPORT_SYMBOL(vm_insert_mixed);
1678423bad60SNick Piggin 
1679a145dd41SLinus Torvalds /*
16801da177e4SLinus Torvalds  * maps a range of physical memory into the requested pages. the old
16811da177e4SLinus Torvalds  * mappings are removed. any references to nonexistent pages results
16821da177e4SLinus Torvalds  * in null mappings (currently treated as "copy-on-access")
16831da177e4SLinus Torvalds  */
16841da177e4SLinus Torvalds static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
16851da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
16861da177e4SLinus Torvalds 			unsigned long pfn, pgprot_t prot)
16871da177e4SLinus Torvalds {
16881da177e4SLinus Torvalds 	pte_t *pte;
1689c74df32cSHugh Dickins 	spinlock_t *ptl;
16901da177e4SLinus Torvalds 
1691c74df32cSHugh Dickins 	pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
16921da177e4SLinus Torvalds 	if (!pte)
16931da177e4SLinus Torvalds 		return -ENOMEM;
16946606c3e0SZachary Amsden 	arch_enter_lazy_mmu_mode();
16951da177e4SLinus Torvalds 	do {
16961da177e4SLinus Torvalds 		BUG_ON(!pte_none(*pte));
16977e675137SNick Piggin 		set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
16981da177e4SLinus Torvalds 		pfn++;
16991da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
17006606c3e0SZachary Amsden 	arch_leave_lazy_mmu_mode();
1701c74df32cSHugh Dickins 	pte_unmap_unlock(pte - 1, ptl);
17021da177e4SLinus Torvalds 	return 0;
17031da177e4SLinus Torvalds }
17041da177e4SLinus Torvalds 
17051da177e4SLinus Torvalds static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
17061da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
17071da177e4SLinus Torvalds 			unsigned long pfn, pgprot_t prot)
17081da177e4SLinus Torvalds {
17091da177e4SLinus Torvalds 	pmd_t *pmd;
17101da177e4SLinus Torvalds 	unsigned long next;
17111da177e4SLinus Torvalds 
17121da177e4SLinus Torvalds 	pfn -= addr >> PAGE_SHIFT;
17131da177e4SLinus Torvalds 	pmd = pmd_alloc(mm, pud, addr);
17141da177e4SLinus Torvalds 	if (!pmd)
17151da177e4SLinus Torvalds 		return -ENOMEM;
1716f66055abSAndrea Arcangeli 	VM_BUG_ON(pmd_trans_huge(*pmd));
17171da177e4SLinus Torvalds 	do {
17181da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
17191da177e4SLinus Torvalds 		if (remap_pte_range(mm, pmd, addr, next,
17201da177e4SLinus Torvalds 				pfn + (addr >> PAGE_SHIFT), prot))
17211da177e4SLinus Torvalds 			return -ENOMEM;
17221da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
17231da177e4SLinus Torvalds 	return 0;
17241da177e4SLinus Torvalds }
17251da177e4SLinus Torvalds 
17261da177e4SLinus Torvalds static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd,
17271da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
17281da177e4SLinus Torvalds 			unsigned long pfn, pgprot_t prot)
17291da177e4SLinus Torvalds {
17301da177e4SLinus Torvalds 	pud_t *pud;
17311da177e4SLinus Torvalds 	unsigned long next;
17321da177e4SLinus Torvalds 
17331da177e4SLinus Torvalds 	pfn -= addr >> PAGE_SHIFT;
17341da177e4SLinus Torvalds 	pud = pud_alloc(mm, pgd, addr);
17351da177e4SLinus Torvalds 	if (!pud)
17361da177e4SLinus Torvalds 		return -ENOMEM;
17371da177e4SLinus Torvalds 	do {
17381da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
17391da177e4SLinus Torvalds 		if (remap_pmd_range(mm, pud, addr, next,
17401da177e4SLinus Torvalds 				pfn + (addr >> PAGE_SHIFT), prot))
17411da177e4SLinus Torvalds 			return -ENOMEM;
17421da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
17431da177e4SLinus Torvalds 	return 0;
17441da177e4SLinus Torvalds }
17451da177e4SLinus Torvalds 
1746bfa5bf6dSRolf Eike Beer /**
1747bfa5bf6dSRolf Eike Beer  * remap_pfn_range - remap kernel memory to userspace
1748bfa5bf6dSRolf Eike Beer  * @vma: user vma to map to
1749bfa5bf6dSRolf Eike Beer  * @addr: target user address to start at
1750bfa5bf6dSRolf Eike Beer  * @pfn: physical address of kernel memory
1751bfa5bf6dSRolf Eike Beer  * @size: size of map area
1752bfa5bf6dSRolf Eike Beer  * @prot: page protection flags for this mapping
1753bfa5bf6dSRolf Eike Beer  *
1754bfa5bf6dSRolf Eike Beer  *  Note: this is only safe if the mm semaphore is held when called.
1755bfa5bf6dSRolf Eike Beer  */
17561da177e4SLinus Torvalds int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
17571da177e4SLinus Torvalds 		    unsigned long pfn, unsigned long size, pgprot_t prot)
17581da177e4SLinus Torvalds {
17591da177e4SLinus Torvalds 	pgd_t *pgd;
17601da177e4SLinus Torvalds 	unsigned long next;
17612d15cab8SHugh Dickins 	unsigned long end = addr + PAGE_ALIGN(size);
17621da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
1763d5957d2fSYongji Xie 	unsigned long remap_pfn = pfn;
17641da177e4SLinus Torvalds 	int err;
17651da177e4SLinus Torvalds 
17661da177e4SLinus Torvalds 	/*
17671da177e4SLinus Torvalds 	 * Physically remapped pages are special. Tell the
17681da177e4SLinus Torvalds 	 * rest of the world about it:
17691da177e4SLinus Torvalds 	 *   VM_IO tells people not to look at these pages
17701da177e4SLinus Torvalds 	 *	(accesses can have side effects).
17716aab341eSLinus Torvalds 	 *   VM_PFNMAP tells the core MM that the base pages are just
17726aab341eSLinus Torvalds 	 *	raw PFN mappings, and do not have a "struct page" associated
17736aab341eSLinus Torvalds 	 *	with them.
1774314e51b9SKonstantin Khlebnikov 	 *   VM_DONTEXPAND
1775314e51b9SKonstantin Khlebnikov 	 *      Disable vma merging and expanding with mremap().
1776314e51b9SKonstantin Khlebnikov 	 *   VM_DONTDUMP
1777314e51b9SKonstantin Khlebnikov 	 *      Omit vma from core dump, even when VM_IO turned off.
1778fb155c16SLinus Torvalds 	 *
1779fb155c16SLinus Torvalds 	 * There's a horrible special case to handle copy-on-write
1780fb155c16SLinus Torvalds 	 * behaviour that some programs depend on. We mark the "original"
1781fb155c16SLinus Torvalds 	 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
1782b3b9c293SKonstantin Khlebnikov 	 * See vm_normal_page() for details.
17831da177e4SLinus Torvalds 	 */
1784b3b9c293SKonstantin Khlebnikov 	if (is_cow_mapping(vma->vm_flags)) {
1785b3b9c293SKonstantin Khlebnikov 		if (addr != vma->vm_start || end != vma->vm_end)
1786b3b9c293SKonstantin Khlebnikov 			return -EINVAL;
17876aab341eSLinus Torvalds 		vma->vm_pgoff = pfn;
1788b3b9c293SKonstantin Khlebnikov 	}
1789b3b9c293SKonstantin Khlebnikov 
1790d5957d2fSYongji Xie 	err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
1791b3b9c293SKonstantin Khlebnikov 	if (err)
17923c8bb73aSvenkatesh.pallipadi@intel.com 		return -EINVAL;
1793fb155c16SLinus Torvalds 
1794314e51b9SKonstantin Khlebnikov 	vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
17951da177e4SLinus Torvalds 
17961da177e4SLinus Torvalds 	BUG_ON(addr >= end);
17971da177e4SLinus Torvalds 	pfn -= addr >> PAGE_SHIFT;
17981da177e4SLinus Torvalds 	pgd = pgd_offset(mm, addr);
17991da177e4SLinus Torvalds 	flush_cache_range(vma, addr, end);
18001da177e4SLinus Torvalds 	do {
18011da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
18021da177e4SLinus Torvalds 		err = remap_pud_range(mm, pgd, addr, next,
18031da177e4SLinus Torvalds 				pfn + (addr >> PAGE_SHIFT), prot);
18041da177e4SLinus Torvalds 		if (err)
18051da177e4SLinus Torvalds 			break;
18061da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
18072ab64037Svenkatesh.pallipadi@intel.com 
18082ab64037Svenkatesh.pallipadi@intel.com 	if (err)
1809d5957d2fSYongji Xie 		untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
18102ab64037Svenkatesh.pallipadi@intel.com 
18111da177e4SLinus Torvalds 	return err;
18121da177e4SLinus Torvalds }
18131da177e4SLinus Torvalds EXPORT_SYMBOL(remap_pfn_range);
18141da177e4SLinus Torvalds 
1815b4cbb197SLinus Torvalds /**
1816b4cbb197SLinus Torvalds  * vm_iomap_memory - remap memory to userspace
1817b4cbb197SLinus Torvalds  * @vma: user vma to map to
1818b4cbb197SLinus Torvalds  * @start: start of area
1819b4cbb197SLinus Torvalds  * @len: size of area
1820b4cbb197SLinus Torvalds  *
1821b4cbb197SLinus Torvalds  * This is a simplified io_remap_pfn_range() for common driver use. The
1822b4cbb197SLinus Torvalds  * driver just needs to give us the physical memory range to be mapped,
1823b4cbb197SLinus Torvalds  * we'll figure out the rest from the vma information.
1824b4cbb197SLinus Torvalds  *
1825b4cbb197SLinus Torvalds  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
1826b4cbb197SLinus Torvalds  * whatever write-combining details or similar.
1827b4cbb197SLinus Torvalds  */
1828b4cbb197SLinus Torvalds int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
1829b4cbb197SLinus Torvalds {
1830b4cbb197SLinus Torvalds 	unsigned long vm_len, pfn, pages;
1831b4cbb197SLinus Torvalds 
1832b4cbb197SLinus Torvalds 	/* Check that the physical memory area passed in looks valid */
1833b4cbb197SLinus Torvalds 	if (start + len < start)
1834b4cbb197SLinus Torvalds 		return -EINVAL;
1835b4cbb197SLinus Torvalds 	/*
1836b4cbb197SLinus Torvalds 	 * You *really* shouldn't map things that aren't page-aligned,
1837b4cbb197SLinus Torvalds 	 * but we've historically allowed it because IO memory might
1838b4cbb197SLinus Torvalds 	 * just have smaller alignment.
1839b4cbb197SLinus Torvalds 	 */
1840b4cbb197SLinus Torvalds 	len += start & ~PAGE_MASK;
1841b4cbb197SLinus Torvalds 	pfn = start >> PAGE_SHIFT;
1842b4cbb197SLinus Torvalds 	pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
1843b4cbb197SLinus Torvalds 	if (pfn + pages < pfn)
1844b4cbb197SLinus Torvalds 		return -EINVAL;
1845b4cbb197SLinus Torvalds 
1846b4cbb197SLinus Torvalds 	/* We start the mapping 'vm_pgoff' pages into the area */
1847b4cbb197SLinus Torvalds 	if (vma->vm_pgoff > pages)
1848b4cbb197SLinus Torvalds 		return -EINVAL;
1849b4cbb197SLinus Torvalds 	pfn += vma->vm_pgoff;
1850b4cbb197SLinus Torvalds 	pages -= vma->vm_pgoff;
1851b4cbb197SLinus Torvalds 
1852b4cbb197SLinus Torvalds 	/* Can we fit all of the mapping? */
1853b4cbb197SLinus Torvalds 	vm_len = vma->vm_end - vma->vm_start;
1854b4cbb197SLinus Torvalds 	if (vm_len >> PAGE_SHIFT > pages)
1855b4cbb197SLinus Torvalds 		return -EINVAL;
1856b4cbb197SLinus Torvalds 
1857b4cbb197SLinus Torvalds 	/* Ok, let it rip */
1858b4cbb197SLinus Torvalds 	return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
1859b4cbb197SLinus Torvalds }
1860b4cbb197SLinus Torvalds EXPORT_SYMBOL(vm_iomap_memory);
1861b4cbb197SLinus Torvalds 
1862aee16b3cSJeremy Fitzhardinge static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
1863aee16b3cSJeremy Fitzhardinge 				     unsigned long addr, unsigned long end,
1864aee16b3cSJeremy Fitzhardinge 				     pte_fn_t fn, void *data)
1865aee16b3cSJeremy Fitzhardinge {
1866aee16b3cSJeremy Fitzhardinge 	pte_t *pte;
1867aee16b3cSJeremy Fitzhardinge 	int err;
18682f569afdSMartin Schwidefsky 	pgtable_t token;
186994909914SBorislav Petkov 	spinlock_t *uninitialized_var(ptl);
1870aee16b3cSJeremy Fitzhardinge 
1871aee16b3cSJeremy Fitzhardinge 	pte = (mm == &init_mm) ?
1872aee16b3cSJeremy Fitzhardinge 		pte_alloc_kernel(pmd, addr) :
1873aee16b3cSJeremy Fitzhardinge 		pte_alloc_map_lock(mm, pmd, addr, &ptl);
1874aee16b3cSJeremy Fitzhardinge 	if (!pte)
1875aee16b3cSJeremy Fitzhardinge 		return -ENOMEM;
1876aee16b3cSJeremy Fitzhardinge 
1877aee16b3cSJeremy Fitzhardinge 	BUG_ON(pmd_huge(*pmd));
1878aee16b3cSJeremy Fitzhardinge 
187938e0edb1SJeremy Fitzhardinge 	arch_enter_lazy_mmu_mode();
188038e0edb1SJeremy Fitzhardinge 
18812f569afdSMartin Schwidefsky 	token = pmd_pgtable(*pmd);
1882aee16b3cSJeremy Fitzhardinge 
1883aee16b3cSJeremy Fitzhardinge 	do {
1884c36987e2SDaisuke Nishimura 		err = fn(pte++, token, addr, data);
1885aee16b3cSJeremy Fitzhardinge 		if (err)
1886aee16b3cSJeremy Fitzhardinge 			break;
1887c36987e2SDaisuke Nishimura 	} while (addr += PAGE_SIZE, addr != end);
1888aee16b3cSJeremy Fitzhardinge 
188938e0edb1SJeremy Fitzhardinge 	arch_leave_lazy_mmu_mode();
189038e0edb1SJeremy Fitzhardinge 
1891aee16b3cSJeremy Fitzhardinge 	if (mm != &init_mm)
1892aee16b3cSJeremy Fitzhardinge 		pte_unmap_unlock(pte-1, ptl);
1893aee16b3cSJeremy Fitzhardinge 	return err;
1894aee16b3cSJeremy Fitzhardinge }
1895aee16b3cSJeremy Fitzhardinge 
1896aee16b3cSJeremy Fitzhardinge static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
1897aee16b3cSJeremy Fitzhardinge 				     unsigned long addr, unsigned long end,
1898aee16b3cSJeremy Fitzhardinge 				     pte_fn_t fn, void *data)
1899aee16b3cSJeremy Fitzhardinge {
1900aee16b3cSJeremy Fitzhardinge 	pmd_t *pmd;
1901aee16b3cSJeremy Fitzhardinge 	unsigned long next;
1902aee16b3cSJeremy Fitzhardinge 	int err;
1903aee16b3cSJeremy Fitzhardinge 
1904ceb86879SAndi Kleen 	BUG_ON(pud_huge(*pud));
1905ceb86879SAndi Kleen 
1906aee16b3cSJeremy Fitzhardinge 	pmd = pmd_alloc(mm, pud, addr);
1907aee16b3cSJeremy Fitzhardinge 	if (!pmd)
1908aee16b3cSJeremy Fitzhardinge 		return -ENOMEM;
1909aee16b3cSJeremy Fitzhardinge 	do {
1910aee16b3cSJeremy Fitzhardinge 		next = pmd_addr_end(addr, end);
1911aee16b3cSJeremy Fitzhardinge 		err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
1912aee16b3cSJeremy Fitzhardinge 		if (err)
1913aee16b3cSJeremy Fitzhardinge 			break;
1914aee16b3cSJeremy Fitzhardinge 	} while (pmd++, addr = next, addr != end);
1915aee16b3cSJeremy Fitzhardinge 	return err;
1916aee16b3cSJeremy Fitzhardinge }
1917aee16b3cSJeremy Fitzhardinge 
1918aee16b3cSJeremy Fitzhardinge static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd,
1919aee16b3cSJeremy Fitzhardinge 				     unsigned long addr, unsigned long end,
1920aee16b3cSJeremy Fitzhardinge 				     pte_fn_t fn, void *data)
1921aee16b3cSJeremy Fitzhardinge {
1922aee16b3cSJeremy Fitzhardinge 	pud_t *pud;
1923aee16b3cSJeremy Fitzhardinge 	unsigned long next;
1924aee16b3cSJeremy Fitzhardinge 	int err;
1925aee16b3cSJeremy Fitzhardinge 
1926aee16b3cSJeremy Fitzhardinge 	pud = pud_alloc(mm, pgd, addr);
1927aee16b3cSJeremy Fitzhardinge 	if (!pud)
1928aee16b3cSJeremy Fitzhardinge 		return -ENOMEM;
1929aee16b3cSJeremy Fitzhardinge 	do {
1930aee16b3cSJeremy Fitzhardinge 		next = pud_addr_end(addr, end);
1931aee16b3cSJeremy Fitzhardinge 		err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
1932aee16b3cSJeremy Fitzhardinge 		if (err)
1933aee16b3cSJeremy Fitzhardinge 			break;
1934aee16b3cSJeremy Fitzhardinge 	} while (pud++, addr = next, addr != end);
1935aee16b3cSJeremy Fitzhardinge 	return err;
1936aee16b3cSJeremy Fitzhardinge }
1937aee16b3cSJeremy Fitzhardinge 
1938aee16b3cSJeremy Fitzhardinge /*
1939aee16b3cSJeremy Fitzhardinge  * Scan a region of virtual memory, filling in page tables as necessary
1940aee16b3cSJeremy Fitzhardinge  * and calling a provided function on each leaf page table.
1941aee16b3cSJeremy Fitzhardinge  */
1942aee16b3cSJeremy Fitzhardinge int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
1943aee16b3cSJeremy Fitzhardinge 			unsigned long size, pte_fn_t fn, void *data)
1944aee16b3cSJeremy Fitzhardinge {
1945aee16b3cSJeremy Fitzhardinge 	pgd_t *pgd;
1946aee16b3cSJeremy Fitzhardinge 	unsigned long next;
194757250a5bSJeremy Fitzhardinge 	unsigned long end = addr + size;
1948aee16b3cSJeremy Fitzhardinge 	int err;
1949aee16b3cSJeremy Fitzhardinge 
19509cb65bc3SMika Penttilä 	if (WARN_ON(addr >= end))
19519cb65bc3SMika Penttilä 		return -EINVAL;
19529cb65bc3SMika Penttilä 
1953aee16b3cSJeremy Fitzhardinge 	pgd = pgd_offset(mm, addr);
1954aee16b3cSJeremy Fitzhardinge 	do {
1955aee16b3cSJeremy Fitzhardinge 		next = pgd_addr_end(addr, end);
1956aee16b3cSJeremy Fitzhardinge 		err = apply_to_pud_range(mm, pgd, addr, next, fn, data);
1957aee16b3cSJeremy Fitzhardinge 		if (err)
1958aee16b3cSJeremy Fitzhardinge 			break;
1959aee16b3cSJeremy Fitzhardinge 	} while (pgd++, addr = next, addr != end);
196057250a5bSJeremy Fitzhardinge 
1961aee16b3cSJeremy Fitzhardinge 	return err;
1962aee16b3cSJeremy Fitzhardinge }
1963aee16b3cSJeremy Fitzhardinge EXPORT_SYMBOL_GPL(apply_to_page_range);
1964aee16b3cSJeremy Fitzhardinge 
19651da177e4SLinus Torvalds /*
19669b4bdd2fSKirill A. Shutemov  * handle_pte_fault chooses page fault handler according to an entry which was
19679b4bdd2fSKirill A. Shutemov  * read non-atomically.  Before making any commitment, on those architectures
19689b4bdd2fSKirill A. Shutemov  * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
19699b4bdd2fSKirill A. Shutemov  * parts, do_swap_page must check under lock before unmapping the pte and
19709b4bdd2fSKirill A. Shutemov  * proceeding (but do_wp_page is only called after already making such a check;
1971a335b2e1SRyota Ozaki  * and do_anonymous_page can safely check later on).
19728f4e2101SHugh Dickins  */
19734c21e2f2SHugh Dickins static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
19748f4e2101SHugh Dickins 				pte_t *page_table, pte_t orig_pte)
19758f4e2101SHugh Dickins {
19768f4e2101SHugh Dickins 	int same = 1;
19778f4e2101SHugh Dickins #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
19788f4e2101SHugh Dickins 	if (sizeof(pte_t) > sizeof(unsigned long)) {
19794c21e2f2SHugh Dickins 		spinlock_t *ptl = pte_lockptr(mm, pmd);
19804c21e2f2SHugh Dickins 		spin_lock(ptl);
19818f4e2101SHugh Dickins 		same = pte_same(*page_table, orig_pte);
19824c21e2f2SHugh Dickins 		spin_unlock(ptl);
19838f4e2101SHugh Dickins 	}
19848f4e2101SHugh Dickins #endif
19858f4e2101SHugh Dickins 	pte_unmap(page_table);
19868f4e2101SHugh Dickins 	return same;
19878f4e2101SHugh Dickins }
19888f4e2101SHugh Dickins 
19899de455b2SAtsushi Nemoto static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
19906aab341eSLinus Torvalds {
19910abdd7a8SDan Williams 	debug_dma_assert_idle(src);
19920abdd7a8SDan Williams 
19936aab341eSLinus Torvalds 	/*
19946aab341eSLinus Torvalds 	 * If the source page was a PFN mapping, we don't have
19956aab341eSLinus Torvalds 	 * a "struct page" for it. We do a best-effort copy by
19966aab341eSLinus Torvalds 	 * just copying from the original user address. If that
19976aab341eSLinus Torvalds 	 * fails, we just zero-fill it. Live with it.
19986aab341eSLinus Torvalds 	 */
19996aab341eSLinus Torvalds 	if (unlikely(!src)) {
20009b04c5feSCong Wang 		void *kaddr = kmap_atomic(dst);
20015d2a2dbbSLinus Torvalds 		void __user *uaddr = (void __user *)(va & PAGE_MASK);
20025d2a2dbbSLinus Torvalds 
20035d2a2dbbSLinus Torvalds 		/*
20045d2a2dbbSLinus Torvalds 		 * This really shouldn't fail, because the page is there
20055d2a2dbbSLinus Torvalds 		 * in the page tables. But it might just be unreadable,
20065d2a2dbbSLinus Torvalds 		 * in which case we just give up and fill the result with
20075d2a2dbbSLinus Torvalds 		 * zeroes.
20085d2a2dbbSLinus Torvalds 		 */
20095d2a2dbbSLinus Torvalds 		if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
20103ecb01dfSJan Beulich 			clear_page(kaddr);
20119b04c5feSCong Wang 		kunmap_atomic(kaddr);
2012c4ec7b0dSDmitriy Monakhov 		flush_dcache_page(dst);
20130ed361deSNick Piggin 	} else
20149de455b2SAtsushi Nemoto 		copy_user_highpage(dst, src, va, vma);
20156aab341eSLinus Torvalds }
20166aab341eSLinus Torvalds 
2017c20cd45eSMichal Hocko static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2018c20cd45eSMichal Hocko {
2019c20cd45eSMichal Hocko 	struct file *vm_file = vma->vm_file;
2020c20cd45eSMichal Hocko 
2021c20cd45eSMichal Hocko 	if (vm_file)
2022c20cd45eSMichal Hocko 		return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2023c20cd45eSMichal Hocko 
2024c20cd45eSMichal Hocko 	/*
2025c20cd45eSMichal Hocko 	 * Special mappings (e.g. VDSO) do not have any file so fake
2026c20cd45eSMichal Hocko 	 * a default GFP_KERNEL for them.
2027c20cd45eSMichal Hocko 	 */
2028c20cd45eSMichal Hocko 	return GFP_KERNEL;
2029c20cd45eSMichal Hocko }
2030c20cd45eSMichal Hocko 
20311da177e4SLinus Torvalds /*
2032fb09a464SKirill A. Shutemov  * Notify the address space that the page is about to become writable so that
2033fb09a464SKirill A. Shutemov  * it can prohibit this or wait for the page to get into an appropriate state.
2034fb09a464SKirill A. Shutemov  *
2035fb09a464SKirill A. Shutemov  * We do this without the lock held, so that it can sleep if it needs to.
2036fb09a464SKirill A. Shutemov  */
2037*38b8cb7fSJan Kara static int do_page_mkwrite(struct vm_fault *vmf)
2038fb09a464SKirill A. Shutemov {
2039fb09a464SKirill A. Shutemov 	int ret;
2040*38b8cb7fSJan Kara 	struct page *page = vmf->page;
2041*38b8cb7fSJan Kara 	unsigned int old_flags = vmf->flags;
2042fb09a464SKirill A. Shutemov 
2043*38b8cb7fSJan Kara 	vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2044fb09a464SKirill A. Shutemov 
2045*38b8cb7fSJan Kara 	ret = vmf->vma->vm_ops->page_mkwrite(vmf->vma, vmf);
2046*38b8cb7fSJan Kara 	/* Restore original flags so that caller is not surprised */
2047*38b8cb7fSJan Kara 	vmf->flags = old_flags;
2048fb09a464SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2049fb09a464SKirill A. Shutemov 		return ret;
2050fb09a464SKirill A. Shutemov 	if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2051fb09a464SKirill A. Shutemov 		lock_page(page);
2052fb09a464SKirill A. Shutemov 		if (!page->mapping) {
2053fb09a464SKirill A. Shutemov 			unlock_page(page);
2054fb09a464SKirill A. Shutemov 			return 0; /* retry */
2055fb09a464SKirill A. Shutemov 		}
2056fb09a464SKirill A. Shutemov 		ret |= VM_FAULT_LOCKED;
2057fb09a464SKirill A. Shutemov 	} else
2058fb09a464SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
2059fb09a464SKirill A. Shutemov 	return ret;
2060fb09a464SKirill A. Shutemov }
2061fb09a464SKirill A. Shutemov 
2062fb09a464SKirill A. Shutemov /*
206397ba0c2bSJan Kara  * Handle dirtying of a page in shared file mapping on a write fault.
206497ba0c2bSJan Kara  *
206597ba0c2bSJan Kara  * The function expects the page to be locked and unlocks it.
206697ba0c2bSJan Kara  */
206797ba0c2bSJan Kara static void fault_dirty_shared_page(struct vm_area_struct *vma,
206897ba0c2bSJan Kara 				    struct page *page)
206997ba0c2bSJan Kara {
207097ba0c2bSJan Kara 	struct address_space *mapping;
207197ba0c2bSJan Kara 	bool dirtied;
207297ba0c2bSJan Kara 	bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
207397ba0c2bSJan Kara 
207497ba0c2bSJan Kara 	dirtied = set_page_dirty(page);
207597ba0c2bSJan Kara 	VM_BUG_ON_PAGE(PageAnon(page), page);
207697ba0c2bSJan Kara 	/*
207797ba0c2bSJan Kara 	 * Take a local copy of the address_space - page.mapping may be zeroed
207897ba0c2bSJan Kara 	 * by truncate after unlock_page().   The address_space itself remains
207997ba0c2bSJan Kara 	 * pinned by vma->vm_file's reference.  We rely on unlock_page()'s
208097ba0c2bSJan Kara 	 * release semantics to prevent the compiler from undoing this copying.
208197ba0c2bSJan Kara 	 */
208297ba0c2bSJan Kara 	mapping = page_rmapping(page);
208397ba0c2bSJan Kara 	unlock_page(page);
208497ba0c2bSJan Kara 
208597ba0c2bSJan Kara 	if ((dirtied || page_mkwrite) && mapping) {
208697ba0c2bSJan Kara 		/*
208797ba0c2bSJan Kara 		 * Some device drivers do not set page.mapping
208897ba0c2bSJan Kara 		 * but still dirty their pages
208997ba0c2bSJan Kara 		 */
209097ba0c2bSJan Kara 		balance_dirty_pages_ratelimited(mapping);
209197ba0c2bSJan Kara 	}
209297ba0c2bSJan Kara 
209397ba0c2bSJan Kara 	if (!page_mkwrite)
209497ba0c2bSJan Kara 		file_update_time(vma->vm_file);
209597ba0c2bSJan Kara }
209697ba0c2bSJan Kara 
209797ba0c2bSJan Kara /*
20984e047f89SShachar Raindel  * Handle write page faults for pages that can be reused in the current vma
20994e047f89SShachar Raindel  *
21004e047f89SShachar Raindel  * This can happen either due to the mapping being with the VM_SHARED flag,
21014e047f89SShachar Raindel  * or due to us being the last reference standing to the page. In either
21024e047f89SShachar Raindel  * case, all we need to do here is to mark the page as writable and update
21034e047f89SShachar Raindel  * any related book-keeping.
21044e047f89SShachar Raindel  */
21052994302bSJan Kara static inline int wp_page_reuse(struct vm_fault *vmf, struct page *page,
21062994302bSJan Kara 				int page_mkwrite, int dirty_shared)
210782b0f8c3SJan Kara 	__releases(vmf->ptl)
21084e047f89SShachar Raindel {
210982b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
21104e047f89SShachar Raindel 	pte_t entry;
21114e047f89SShachar Raindel 	/*
21124e047f89SShachar Raindel 	 * Clear the pages cpupid information as the existing
21134e047f89SShachar Raindel 	 * information potentially belongs to a now completely
21144e047f89SShachar Raindel 	 * unrelated process.
21154e047f89SShachar Raindel 	 */
21164e047f89SShachar Raindel 	if (page)
21174e047f89SShachar Raindel 		page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
21184e047f89SShachar Raindel 
21192994302bSJan Kara 	flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
21202994302bSJan Kara 	entry = pte_mkyoung(vmf->orig_pte);
21214e047f89SShachar Raindel 	entry = maybe_mkwrite(pte_mkdirty(entry), vma);
212282b0f8c3SJan Kara 	if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
212382b0f8c3SJan Kara 		update_mmu_cache(vma, vmf->address, vmf->pte);
212482b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
21254e047f89SShachar Raindel 
21264e047f89SShachar Raindel 	if (dirty_shared) {
21274e047f89SShachar Raindel 		if (!page_mkwrite)
21284e047f89SShachar Raindel 			lock_page(page);
21294e047f89SShachar Raindel 
213097ba0c2bSJan Kara 		fault_dirty_shared_page(vma, page);
213109cbfeafSKirill A. Shutemov 		put_page(page);
21324e047f89SShachar Raindel 	}
21334e047f89SShachar Raindel 
21344e047f89SShachar Raindel 	return VM_FAULT_WRITE;
21354e047f89SShachar Raindel }
21364e047f89SShachar Raindel 
21374e047f89SShachar Raindel /*
21382f38ab2cSShachar Raindel  * Handle the case of a page which we actually need to copy to a new page.
21392f38ab2cSShachar Raindel  *
21402f38ab2cSShachar Raindel  * Called with mmap_sem locked and the old page referenced, but
21412f38ab2cSShachar Raindel  * without the ptl held.
21422f38ab2cSShachar Raindel  *
21432f38ab2cSShachar Raindel  * High level logic flow:
21442f38ab2cSShachar Raindel  *
21452f38ab2cSShachar Raindel  * - Allocate a page, copy the content of the old page to the new one.
21462f38ab2cSShachar Raindel  * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
21472f38ab2cSShachar Raindel  * - Take the PTL. If the pte changed, bail out and release the allocated page
21482f38ab2cSShachar Raindel  * - If the pte is still the way we remember it, update the page table and all
21492f38ab2cSShachar Raindel  *   relevant references. This includes dropping the reference the page-table
21502f38ab2cSShachar Raindel  *   held to the old page, as well as updating the rmap.
21512f38ab2cSShachar Raindel  * - In any case, unlock the PTL and drop the reference we took to the old page.
21522f38ab2cSShachar Raindel  */
21532994302bSJan Kara static int wp_page_copy(struct vm_fault *vmf, struct page *old_page)
21542f38ab2cSShachar Raindel {
215582b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
2156bae473a4SKirill A. Shutemov 	struct mm_struct *mm = vma->vm_mm;
21572f38ab2cSShachar Raindel 	struct page *new_page = NULL;
21582f38ab2cSShachar Raindel 	pte_t entry;
21592f38ab2cSShachar Raindel 	int page_copied = 0;
216082b0f8c3SJan Kara 	const unsigned long mmun_start = vmf->address & PAGE_MASK;
2161bae473a4SKirill A. Shutemov 	const unsigned long mmun_end = mmun_start + PAGE_SIZE;
21622f38ab2cSShachar Raindel 	struct mem_cgroup *memcg;
21632f38ab2cSShachar Raindel 
21642f38ab2cSShachar Raindel 	if (unlikely(anon_vma_prepare(vma)))
21652f38ab2cSShachar Raindel 		goto oom;
21662f38ab2cSShachar Raindel 
21672994302bSJan Kara 	if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
216882b0f8c3SJan Kara 		new_page = alloc_zeroed_user_highpage_movable(vma,
216982b0f8c3SJan Kara 							      vmf->address);
21702f38ab2cSShachar Raindel 		if (!new_page)
21712f38ab2cSShachar Raindel 			goto oom;
21722f38ab2cSShachar Raindel 	} else {
2173bae473a4SKirill A. Shutemov 		new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
217482b0f8c3SJan Kara 				vmf->address);
21752f38ab2cSShachar Raindel 		if (!new_page)
21762f38ab2cSShachar Raindel 			goto oom;
217782b0f8c3SJan Kara 		cow_user_page(new_page, old_page, vmf->address, vma);
21782f38ab2cSShachar Raindel 	}
21792f38ab2cSShachar Raindel 
2180f627c2f5SKirill A. Shutemov 	if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg, false))
21812f38ab2cSShachar Raindel 		goto oom_free_new;
21822f38ab2cSShachar Raindel 
2183eb3c24f3SMel Gorman 	__SetPageUptodate(new_page);
2184eb3c24f3SMel Gorman 
21852f38ab2cSShachar Raindel 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
21862f38ab2cSShachar Raindel 
21872f38ab2cSShachar Raindel 	/*
21882f38ab2cSShachar Raindel 	 * Re-check the pte - we dropped the lock
21892f38ab2cSShachar Raindel 	 */
219082b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
21912994302bSJan Kara 	if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
21922f38ab2cSShachar Raindel 		if (old_page) {
21932f38ab2cSShachar Raindel 			if (!PageAnon(old_page)) {
2194eca56ff9SJerome Marchand 				dec_mm_counter_fast(mm,
2195eca56ff9SJerome Marchand 						mm_counter_file(old_page));
21962f38ab2cSShachar Raindel 				inc_mm_counter_fast(mm, MM_ANONPAGES);
21972f38ab2cSShachar Raindel 			}
21982f38ab2cSShachar Raindel 		} else {
21992f38ab2cSShachar Raindel 			inc_mm_counter_fast(mm, MM_ANONPAGES);
22002f38ab2cSShachar Raindel 		}
22012994302bSJan Kara 		flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
22022f38ab2cSShachar Raindel 		entry = mk_pte(new_page, vma->vm_page_prot);
22032f38ab2cSShachar Raindel 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
22042f38ab2cSShachar Raindel 		/*
22052f38ab2cSShachar Raindel 		 * Clear the pte entry and flush it first, before updating the
22062f38ab2cSShachar Raindel 		 * pte with the new entry. This will avoid a race condition
22072f38ab2cSShachar Raindel 		 * seen in the presence of one thread doing SMC and another
22082f38ab2cSShachar Raindel 		 * thread doing COW.
22092f38ab2cSShachar Raindel 		 */
221082b0f8c3SJan Kara 		ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
221182b0f8c3SJan Kara 		page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2212f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(new_page, memcg, false, false);
22132f38ab2cSShachar Raindel 		lru_cache_add_active_or_unevictable(new_page, vma);
22142f38ab2cSShachar Raindel 		/*
22152f38ab2cSShachar Raindel 		 * We call the notify macro here because, when using secondary
22162f38ab2cSShachar Raindel 		 * mmu page tables (such as kvm shadow page tables), we want the
22172f38ab2cSShachar Raindel 		 * new page to be mapped directly into the secondary page table.
22182f38ab2cSShachar Raindel 		 */
221982b0f8c3SJan Kara 		set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
222082b0f8c3SJan Kara 		update_mmu_cache(vma, vmf->address, vmf->pte);
22212f38ab2cSShachar Raindel 		if (old_page) {
22222f38ab2cSShachar Raindel 			/*
22232f38ab2cSShachar Raindel 			 * Only after switching the pte to the new page may
22242f38ab2cSShachar Raindel 			 * we remove the mapcount here. Otherwise another
22252f38ab2cSShachar Raindel 			 * process may come and find the rmap count decremented
22262f38ab2cSShachar Raindel 			 * before the pte is switched to the new page, and
22272f38ab2cSShachar Raindel 			 * "reuse" the old page writing into it while our pte
22282f38ab2cSShachar Raindel 			 * here still points into it and can be read by other
22292f38ab2cSShachar Raindel 			 * threads.
22302f38ab2cSShachar Raindel 			 *
22312f38ab2cSShachar Raindel 			 * The critical issue is to order this
22322f38ab2cSShachar Raindel 			 * page_remove_rmap with the ptp_clear_flush above.
22332f38ab2cSShachar Raindel 			 * Those stores are ordered by (if nothing else,)
22342f38ab2cSShachar Raindel 			 * the barrier present in the atomic_add_negative
22352f38ab2cSShachar Raindel 			 * in page_remove_rmap.
22362f38ab2cSShachar Raindel 			 *
22372f38ab2cSShachar Raindel 			 * Then the TLB flush in ptep_clear_flush ensures that
22382f38ab2cSShachar Raindel 			 * no process can access the old page before the
22392f38ab2cSShachar Raindel 			 * decremented mapcount is visible. And the old page
22402f38ab2cSShachar Raindel 			 * cannot be reused until after the decremented
22412f38ab2cSShachar Raindel 			 * mapcount is visible. So transitively, TLBs to
22422f38ab2cSShachar Raindel 			 * old page will be flushed before it can be reused.
22432f38ab2cSShachar Raindel 			 */
2244d281ee61SKirill A. Shutemov 			page_remove_rmap(old_page, false);
22452f38ab2cSShachar Raindel 		}
22462f38ab2cSShachar Raindel 
22472f38ab2cSShachar Raindel 		/* Free the old page.. */
22482f38ab2cSShachar Raindel 		new_page = old_page;
22492f38ab2cSShachar Raindel 		page_copied = 1;
22502f38ab2cSShachar Raindel 	} else {
2251f627c2f5SKirill A. Shutemov 		mem_cgroup_cancel_charge(new_page, memcg, false);
22522f38ab2cSShachar Raindel 	}
22532f38ab2cSShachar Raindel 
22542f38ab2cSShachar Raindel 	if (new_page)
225509cbfeafSKirill A. Shutemov 		put_page(new_page);
22562f38ab2cSShachar Raindel 
225782b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
22582f38ab2cSShachar Raindel 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
22592f38ab2cSShachar Raindel 	if (old_page) {
22602f38ab2cSShachar Raindel 		/*
22612f38ab2cSShachar Raindel 		 * Don't let another task, with possibly unlocked vma,
22622f38ab2cSShachar Raindel 		 * keep the mlocked page.
22632f38ab2cSShachar Raindel 		 */
22642f38ab2cSShachar Raindel 		if (page_copied && (vma->vm_flags & VM_LOCKED)) {
22652f38ab2cSShachar Raindel 			lock_page(old_page);	/* LRU manipulation */
2266e90309c9SKirill A. Shutemov 			if (PageMlocked(old_page))
22672f38ab2cSShachar Raindel 				munlock_vma_page(old_page);
22682f38ab2cSShachar Raindel 			unlock_page(old_page);
22692f38ab2cSShachar Raindel 		}
227009cbfeafSKirill A. Shutemov 		put_page(old_page);
22712f38ab2cSShachar Raindel 	}
22722f38ab2cSShachar Raindel 	return page_copied ? VM_FAULT_WRITE : 0;
22732f38ab2cSShachar Raindel oom_free_new:
227409cbfeafSKirill A. Shutemov 	put_page(new_page);
22752f38ab2cSShachar Raindel oom:
22762f38ab2cSShachar Raindel 	if (old_page)
227709cbfeafSKirill A. Shutemov 		put_page(old_page);
22782f38ab2cSShachar Raindel 	return VM_FAULT_OOM;
22792f38ab2cSShachar Raindel }
22802f38ab2cSShachar Raindel 
2281dd906184SBoaz Harrosh /*
2282dd906184SBoaz Harrosh  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2283dd906184SBoaz Harrosh  * mapping
2284dd906184SBoaz Harrosh  */
22852994302bSJan Kara static int wp_pfn_shared(struct vm_fault *vmf)
2286dd906184SBoaz Harrosh {
228782b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
2288bae473a4SKirill A. Shutemov 
2289dd906184SBoaz Harrosh 	if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2290dd906184SBoaz Harrosh 		int ret;
2291dd906184SBoaz Harrosh 
229282b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
2293fe82221fSJan Kara 		vmf->flags |= FAULT_FLAG_MKWRITE;
2294fe82221fSJan Kara 		ret = vma->vm_ops->pfn_mkwrite(vma, vmf);
2295dd906184SBoaz Harrosh 		if (ret & VM_FAULT_ERROR)
2296dd906184SBoaz Harrosh 			return ret;
229782b0f8c3SJan Kara 		vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
229882b0f8c3SJan Kara 				vmf->address, &vmf->ptl);
2299dd906184SBoaz Harrosh 		/*
2300dd906184SBoaz Harrosh 		 * We might have raced with another page fault while we
2301dd906184SBoaz Harrosh 		 * released the pte_offset_map_lock.
2302dd906184SBoaz Harrosh 		 */
23032994302bSJan Kara 		if (!pte_same(*vmf->pte, vmf->orig_pte)) {
230482b0f8c3SJan Kara 			pte_unmap_unlock(vmf->pte, vmf->ptl);
2305dd906184SBoaz Harrosh 			return 0;
2306dd906184SBoaz Harrosh 		}
2307dd906184SBoaz Harrosh 	}
23082994302bSJan Kara 	return wp_page_reuse(vmf, NULL, 0, 0);
2309dd906184SBoaz Harrosh }
2310dd906184SBoaz Harrosh 
23112994302bSJan Kara static int wp_page_shared(struct vm_fault *vmf, struct page *old_page)
231282b0f8c3SJan Kara 	__releases(vmf->ptl)
231393e478d4SShachar Raindel {
231482b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
231593e478d4SShachar Raindel 	int page_mkwrite = 0;
231693e478d4SShachar Raindel 
231709cbfeafSKirill A. Shutemov 	get_page(old_page);
231893e478d4SShachar Raindel 
231993e478d4SShachar Raindel 	if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
232093e478d4SShachar Raindel 		int tmp;
232193e478d4SShachar Raindel 
232282b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
2323*38b8cb7fSJan Kara 		vmf->page = old_page;
2324*38b8cb7fSJan Kara 		tmp = do_page_mkwrite(vmf);
232593e478d4SShachar Raindel 		if (unlikely(!tmp || (tmp &
232693e478d4SShachar Raindel 				      (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
232709cbfeafSKirill A. Shutemov 			put_page(old_page);
232893e478d4SShachar Raindel 			return tmp;
232993e478d4SShachar Raindel 		}
233093e478d4SShachar Raindel 		/*
233193e478d4SShachar Raindel 		 * Since we dropped the lock we need to revalidate
233293e478d4SShachar Raindel 		 * the PTE as someone else may have changed it.  If
233393e478d4SShachar Raindel 		 * they did, we just return, as we can count on the
233493e478d4SShachar Raindel 		 * MMU to tell us if they didn't also make it writable.
233593e478d4SShachar Raindel 		 */
233682b0f8c3SJan Kara 		vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
233782b0f8c3SJan Kara 						vmf->address, &vmf->ptl);
23382994302bSJan Kara 		if (!pte_same(*vmf->pte, vmf->orig_pte)) {
233993e478d4SShachar Raindel 			unlock_page(old_page);
234082b0f8c3SJan Kara 			pte_unmap_unlock(vmf->pte, vmf->ptl);
234109cbfeafSKirill A. Shutemov 			put_page(old_page);
234293e478d4SShachar Raindel 			return 0;
234393e478d4SShachar Raindel 		}
234493e478d4SShachar Raindel 		page_mkwrite = 1;
234593e478d4SShachar Raindel 	}
234693e478d4SShachar Raindel 
23472994302bSJan Kara 	return wp_page_reuse(vmf, old_page, page_mkwrite, 1);
234893e478d4SShachar Raindel }
234993e478d4SShachar Raindel 
23502f38ab2cSShachar Raindel /*
23511da177e4SLinus Torvalds  * This routine handles present pages, when users try to write
23521da177e4SLinus Torvalds  * to a shared page. It is done by copying the page to a new address
23531da177e4SLinus Torvalds  * and decrementing the shared-page counter for the old page.
23541da177e4SLinus Torvalds  *
23551da177e4SLinus Torvalds  * Note that this routine assumes that the protection checks have been
23561da177e4SLinus Torvalds  * done by the caller (the low-level page fault routine in most cases).
23571da177e4SLinus Torvalds  * Thus we can safely just mark it writable once we've done any necessary
23581da177e4SLinus Torvalds  * COW.
23591da177e4SLinus Torvalds  *
23601da177e4SLinus Torvalds  * We also mark the page dirty at this point even though the page will
23611da177e4SLinus Torvalds  * change only once the write actually happens. This avoids a few races,
23621da177e4SLinus Torvalds  * and potentially makes it more efficient.
23631da177e4SLinus Torvalds  *
23648f4e2101SHugh Dickins  * We enter with non-exclusive mmap_sem (to exclude vma changes,
23658f4e2101SHugh Dickins  * but allow concurrent faults), with pte both mapped and locked.
23668f4e2101SHugh Dickins  * We return with mmap_sem still held, but pte unmapped and unlocked.
23671da177e4SLinus Torvalds  */
23682994302bSJan Kara static int do_wp_page(struct vm_fault *vmf)
236982b0f8c3SJan Kara 	__releases(vmf->ptl)
23701da177e4SLinus Torvalds {
237182b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
23722f38ab2cSShachar Raindel 	struct page *old_page;
23731da177e4SLinus Torvalds 
23742994302bSJan Kara 	old_page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
2375251b97f5SPeter Zijlstra 	if (!old_page) {
2376251b97f5SPeter Zijlstra 		/*
237764e45507SPeter Feiner 		 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
237864e45507SPeter Feiner 		 * VM_PFNMAP VMA.
2379251b97f5SPeter Zijlstra 		 *
2380251b97f5SPeter Zijlstra 		 * We should not cow pages in a shared writeable mapping.
2381dd906184SBoaz Harrosh 		 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2382251b97f5SPeter Zijlstra 		 */
2383251b97f5SPeter Zijlstra 		if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2384251b97f5SPeter Zijlstra 				     (VM_WRITE|VM_SHARED))
23852994302bSJan Kara 			return wp_pfn_shared(vmf);
23862f38ab2cSShachar Raindel 
238782b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
23882994302bSJan Kara 		return wp_page_copy(vmf, old_page);
2389251b97f5SPeter Zijlstra 	}
23901da177e4SLinus Torvalds 
2391d08b3851SPeter Zijlstra 	/*
2392ee6a6457SPeter Zijlstra 	 * Take out anonymous pages first, anonymous shared vmas are
2393ee6a6457SPeter Zijlstra 	 * not dirty accountable.
2394d08b3851SPeter Zijlstra 	 */
23959a840895SHugh Dickins 	if (PageAnon(old_page) && !PageKsm(old_page)) {
23966d0a07edSAndrea Arcangeli 		int total_mapcount;
2397ab967d86SHugh Dickins 		if (!trylock_page(old_page)) {
239809cbfeafSKirill A. Shutemov 			get_page(old_page);
239982b0f8c3SJan Kara 			pte_unmap_unlock(vmf->pte, vmf->ptl);
2400ab967d86SHugh Dickins 			lock_page(old_page);
240182b0f8c3SJan Kara 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
240282b0f8c3SJan Kara 					vmf->address, &vmf->ptl);
24032994302bSJan Kara 			if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2404ab967d86SHugh Dickins 				unlock_page(old_page);
240582b0f8c3SJan Kara 				pte_unmap_unlock(vmf->pte, vmf->ptl);
240609cbfeafSKirill A. Shutemov 				put_page(old_page);
240728766805SShachar Raindel 				return 0;
2408ab967d86SHugh Dickins 			}
240909cbfeafSKirill A. Shutemov 			put_page(old_page);
2410ab967d86SHugh Dickins 		}
24116d0a07edSAndrea Arcangeli 		if (reuse_swap_page(old_page, &total_mapcount)) {
24126d0a07edSAndrea Arcangeli 			if (total_mapcount == 1) {
2413c44b6743SRik van Riel 				/*
24146d0a07edSAndrea Arcangeli 				 * The page is all ours. Move it to
24156d0a07edSAndrea Arcangeli 				 * our anon_vma so the rmap code will
24166d0a07edSAndrea Arcangeli 				 * not search our parent or siblings.
24176d0a07edSAndrea Arcangeli 				 * Protected against the rmap code by
24186d0a07edSAndrea Arcangeli 				 * the page lock.
2419c44b6743SRik van Riel 				 */
24205a49973dSHugh Dickins 				page_move_anon_rmap(old_page, vma);
24216d0a07edSAndrea Arcangeli 			}
2422ee6a6457SPeter Zijlstra 			unlock_page(old_page);
24232994302bSJan Kara 			return wp_page_reuse(vmf, old_page, 0, 0);
2424b009c024SMichel Lespinasse 		}
2425b009c024SMichel Lespinasse 		unlock_page(old_page);
2426ee6a6457SPeter Zijlstra 	} else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2427d08b3851SPeter Zijlstra 					(VM_WRITE|VM_SHARED))) {
24282994302bSJan Kara 		return wp_page_shared(vmf, old_page);
24291da177e4SLinus Torvalds 	}
24301da177e4SLinus Torvalds 
24311da177e4SLinus Torvalds 	/*
24321da177e4SLinus Torvalds 	 * Ok, we need to copy. Oh, well..
24331da177e4SLinus Torvalds 	 */
243409cbfeafSKirill A. Shutemov 	get_page(old_page);
243528766805SShachar Raindel 
243682b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
24372994302bSJan Kara 	return wp_page_copy(vmf, old_page);
24381da177e4SLinus Torvalds }
24391da177e4SLinus Torvalds 
244097a89413SPeter Zijlstra static void unmap_mapping_range_vma(struct vm_area_struct *vma,
24411da177e4SLinus Torvalds 		unsigned long start_addr, unsigned long end_addr,
24421da177e4SLinus Torvalds 		struct zap_details *details)
24431da177e4SLinus Torvalds {
2444f5cc4eefSAl Viro 	zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
24451da177e4SLinus Torvalds }
24461da177e4SLinus Torvalds 
24476b2dbba8SMichel Lespinasse static inline void unmap_mapping_range_tree(struct rb_root *root,
24481da177e4SLinus Torvalds 					    struct zap_details *details)
24491da177e4SLinus Torvalds {
24501da177e4SLinus Torvalds 	struct vm_area_struct *vma;
24511da177e4SLinus Torvalds 	pgoff_t vba, vea, zba, zea;
24521da177e4SLinus Torvalds 
24536b2dbba8SMichel Lespinasse 	vma_interval_tree_foreach(vma, root,
24541da177e4SLinus Torvalds 			details->first_index, details->last_index) {
24551da177e4SLinus Torvalds 
24561da177e4SLinus Torvalds 		vba = vma->vm_pgoff;
2457d6e93217SLibin 		vea = vba + vma_pages(vma) - 1;
24581da177e4SLinus Torvalds 		zba = details->first_index;
24591da177e4SLinus Torvalds 		if (zba < vba)
24601da177e4SLinus Torvalds 			zba = vba;
24611da177e4SLinus Torvalds 		zea = details->last_index;
24621da177e4SLinus Torvalds 		if (zea > vea)
24631da177e4SLinus Torvalds 			zea = vea;
24641da177e4SLinus Torvalds 
246597a89413SPeter Zijlstra 		unmap_mapping_range_vma(vma,
24661da177e4SLinus Torvalds 			((zba - vba) << PAGE_SHIFT) + vma->vm_start,
24671da177e4SLinus Torvalds 			((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
246897a89413SPeter Zijlstra 				details);
24691da177e4SLinus Torvalds 	}
24701da177e4SLinus Torvalds }
24711da177e4SLinus Torvalds 
24721da177e4SLinus Torvalds /**
24738a5f14a2SKirill A. Shutemov  * unmap_mapping_range - unmap the portion of all mmaps in the specified
24748a5f14a2SKirill A. Shutemov  * address_space corresponding to the specified page range in the underlying
24758a5f14a2SKirill A. Shutemov  * file.
24768a5f14a2SKirill A. Shutemov  *
24773d41088fSMartin Waitz  * @mapping: the address space containing mmaps to be unmapped.
24781da177e4SLinus Torvalds  * @holebegin: byte in first page to unmap, relative to the start of
24791da177e4SLinus Torvalds  * the underlying file.  This will be rounded down to a PAGE_SIZE
248025d9e2d1Snpiggin@suse.de  * boundary.  Note that this is different from truncate_pagecache(), which
24811da177e4SLinus Torvalds  * must keep the partial page.  In contrast, we must get rid of
24821da177e4SLinus Torvalds  * partial pages.
24831da177e4SLinus Torvalds  * @holelen: size of prospective hole in bytes.  This will be rounded
24841da177e4SLinus Torvalds  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
24851da177e4SLinus Torvalds  * end of the file.
24861da177e4SLinus Torvalds  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
24871da177e4SLinus Torvalds  * but 0 when invalidating pagecache, don't throw away private data.
24881da177e4SLinus Torvalds  */
24891da177e4SLinus Torvalds void unmap_mapping_range(struct address_space *mapping,
24901da177e4SLinus Torvalds 		loff_t const holebegin, loff_t const holelen, int even_cows)
24911da177e4SLinus Torvalds {
2492aac45363SMichal Hocko 	struct zap_details details = { };
24931da177e4SLinus Torvalds 	pgoff_t hba = holebegin >> PAGE_SHIFT;
24941da177e4SLinus Torvalds 	pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
24951da177e4SLinus Torvalds 
24961da177e4SLinus Torvalds 	/* Check for overflow. */
24971da177e4SLinus Torvalds 	if (sizeof(holelen) > sizeof(hlen)) {
24981da177e4SLinus Torvalds 		long long holeend =
24991da177e4SLinus Torvalds 			(holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
25001da177e4SLinus Torvalds 		if (holeend & ~(long long)ULONG_MAX)
25011da177e4SLinus Torvalds 			hlen = ULONG_MAX - hba + 1;
25021da177e4SLinus Torvalds 	}
25031da177e4SLinus Torvalds 
25041da177e4SLinus Torvalds 	details.check_mapping = even_cows? NULL: mapping;
25051da177e4SLinus Torvalds 	details.first_index = hba;
25061da177e4SLinus Torvalds 	details.last_index = hba + hlen - 1;
25071da177e4SLinus Torvalds 	if (details.last_index < details.first_index)
25081da177e4SLinus Torvalds 		details.last_index = ULONG_MAX;
25091da177e4SLinus Torvalds 
251048ec833bSKirill A. Shutemov 	i_mmap_lock_write(mapping);
25116b2dbba8SMichel Lespinasse 	if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap)))
25121da177e4SLinus Torvalds 		unmap_mapping_range_tree(&mapping->i_mmap, &details);
251348ec833bSKirill A. Shutemov 	i_mmap_unlock_write(mapping);
25141da177e4SLinus Torvalds }
25151da177e4SLinus Torvalds EXPORT_SYMBOL(unmap_mapping_range);
25161da177e4SLinus Torvalds 
25171da177e4SLinus Torvalds /*
25188f4e2101SHugh Dickins  * We enter with non-exclusive mmap_sem (to exclude vma changes,
25198f4e2101SHugh Dickins  * but allow concurrent faults), and pte mapped but not yet locked.
25209a95f3cfSPaul Cassella  * We return with pte unmapped and unlocked.
25219a95f3cfSPaul Cassella  *
25229a95f3cfSPaul Cassella  * We return with the mmap_sem locked or unlocked in the same cases
25239a95f3cfSPaul Cassella  * as does filemap_fault().
25241da177e4SLinus Torvalds  */
25252994302bSJan Kara int do_swap_page(struct vm_fault *vmf)
25261da177e4SLinus Torvalds {
252782b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
252856f31801SHugh Dickins 	struct page *page, *swapcache;
252900501b53SJohannes Weiner 	struct mem_cgroup *memcg;
253065500d23SHugh Dickins 	swp_entry_t entry;
25311da177e4SLinus Torvalds 	pte_t pte;
2532d065bd81SMichel Lespinasse 	int locked;
2533ad8c2ee8SRik van Riel 	int exclusive = 0;
253483c54070SNick Piggin 	int ret = 0;
25351da177e4SLinus Torvalds 
25362994302bSJan Kara 	if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte))
25378f4e2101SHugh Dickins 		goto out;
253865500d23SHugh Dickins 
25392994302bSJan Kara 	entry = pte_to_swp_entry(vmf->orig_pte);
2540d1737fdbSAndi Kleen 	if (unlikely(non_swap_entry(entry))) {
25410697212aSChristoph Lameter 		if (is_migration_entry(entry)) {
254282b0f8c3SJan Kara 			migration_entry_wait(vma->vm_mm, vmf->pmd,
254382b0f8c3SJan Kara 					     vmf->address);
2544d1737fdbSAndi Kleen 		} else if (is_hwpoison_entry(entry)) {
2545d1737fdbSAndi Kleen 			ret = VM_FAULT_HWPOISON;
2546d1737fdbSAndi Kleen 		} else {
25472994302bSJan Kara 			print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
2548d99be1a8SHugh Dickins 			ret = VM_FAULT_SIGBUS;
2549d1737fdbSAndi Kleen 		}
25500697212aSChristoph Lameter 		goto out;
25510697212aSChristoph Lameter 	}
25520ff92245SShailabh Nagar 	delayacct_set_flag(DELAYACCT_PF_SWAPIN);
25531da177e4SLinus Torvalds 	page = lookup_swap_cache(entry);
25541da177e4SLinus Torvalds 	if (!page) {
255582b0f8c3SJan Kara 		page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vma,
255682b0f8c3SJan Kara 					vmf->address);
25571da177e4SLinus Torvalds 		if (!page) {
25581da177e4SLinus Torvalds 			/*
25598f4e2101SHugh Dickins 			 * Back out if somebody else faulted in this pte
25608f4e2101SHugh Dickins 			 * while we released the pte lock.
25611da177e4SLinus Torvalds 			 */
256282b0f8c3SJan Kara 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
256382b0f8c3SJan Kara 					vmf->address, &vmf->ptl);
25642994302bSJan Kara 			if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
25651da177e4SLinus Torvalds 				ret = VM_FAULT_OOM;
25660ff92245SShailabh Nagar 			delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
256765500d23SHugh Dickins 			goto unlock;
25681da177e4SLinus Torvalds 		}
25691da177e4SLinus Torvalds 
25701da177e4SLinus Torvalds 		/* Had to read the page from swap area: Major fault */
25711da177e4SLinus Torvalds 		ret = VM_FAULT_MAJOR;
2572f8891e5eSChristoph Lameter 		count_vm_event(PGMAJFAULT);
2573bae473a4SKirill A. Shutemov 		mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
2574d1737fdbSAndi Kleen 	} else if (PageHWPoison(page)) {
257571f72525SWu Fengguang 		/*
257671f72525SWu Fengguang 		 * hwpoisoned dirty swapcache pages are kept for killing
257771f72525SWu Fengguang 		 * owner processes (which may be unknown at hwpoison time)
257871f72525SWu Fengguang 		 */
2579d1737fdbSAndi Kleen 		ret = VM_FAULT_HWPOISON;
2580d1737fdbSAndi Kleen 		delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
258156f31801SHugh Dickins 		swapcache = page;
25824779cb31SAndi Kleen 		goto out_release;
25831da177e4SLinus Torvalds 	}
25841da177e4SLinus Torvalds 
258556f31801SHugh Dickins 	swapcache = page;
258682b0f8c3SJan Kara 	locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
2587e709ffd6SRik van Riel 
258820a1022dSBalbir Singh 	delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2589d065bd81SMichel Lespinasse 	if (!locked) {
2590d065bd81SMichel Lespinasse 		ret |= VM_FAULT_RETRY;
2591d065bd81SMichel Lespinasse 		goto out_release;
2592d065bd81SMichel Lespinasse 	}
25931da177e4SLinus Torvalds 
25944969c119SAndrea Arcangeli 	/*
259531c4a3d3SHugh Dickins 	 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
259631c4a3d3SHugh Dickins 	 * release the swapcache from under us.  The page pin, and pte_same
259731c4a3d3SHugh Dickins 	 * test below, are not enough to exclude that.  Even if it is still
259831c4a3d3SHugh Dickins 	 * swapcache, we need to check that the page's swap has not changed.
25994969c119SAndrea Arcangeli 	 */
260031c4a3d3SHugh Dickins 	if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
26014969c119SAndrea Arcangeli 		goto out_page;
26024969c119SAndrea Arcangeli 
260382b0f8c3SJan Kara 	page = ksm_might_need_to_copy(page, vma, vmf->address);
26044969c119SAndrea Arcangeli 	if (unlikely(!page)) {
26055ad64688SHugh Dickins 		ret = VM_FAULT_OOM;
26064969c119SAndrea Arcangeli 		page = swapcache;
26074969c119SAndrea Arcangeli 		goto out_page;
26084969c119SAndrea Arcangeli 	}
26095ad64688SHugh Dickins 
2610bae473a4SKirill A. Shutemov 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
2611bae473a4SKirill A. Shutemov 				&memcg, false)) {
2612073e587eSKAMEZAWA Hiroyuki 		ret = VM_FAULT_OOM;
2613bc43f75cSJohannes Weiner 		goto out_page;
2614073e587eSKAMEZAWA Hiroyuki 	}
2615073e587eSKAMEZAWA Hiroyuki 
26161da177e4SLinus Torvalds 	/*
26178f4e2101SHugh Dickins 	 * Back out if somebody else already faulted in this pte.
26181da177e4SLinus Torvalds 	 */
261982b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
262082b0f8c3SJan Kara 			&vmf->ptl);
26212994302bSJan Kara 	if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
2622b8107480SKirill Korotaev 		goto out_nomap;
2623b8107480SKirill Korotaev 
2624b8107480SKirill Korotaev 	if (unlikely(!PageUptodate(page))) {
2625b8107480SKirill Korotaev 		ret = VM_FAULT_SIGBUS;
2626b8107480SKirill Korotaev 		goto out_nomap;
26271da177e4SLinus Torvalds 	}
26281da177e4SLinus Torvalds 
26298c7c6e34SKAMEZAWA Hiroyuki 	/*
26308c7c6e34SKAMEZAWA Hiroyuki 	 * The page isn't present yet, go ahead with the fault.
26318c7c6e34SKAMEZAWA Hiroyuki 	 *
26328c7c6e34SKAMEZAWA Hiroyuki 	 * Be careful about the sequence of operations here.
26338c7c6e34SKAMEZAWA Hiroyuki 	 * To get its accounting right, reuse_swap_page() must be called
26348c7c6e34SKAMEZAWA Hiroyuki 	 * while the page is counted on swap but not yet in mapcount i.e.
26358c7c6e34SKAMEZAWA Hiroyuki 	 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
26368c7c6e34SKAMEZAWA Hiroyuki 	 * must be called after the swap_free(), or it will never succeed.
26378c7c6e34SKAMEZAWA Hiroyuki 	 */
26381da177e4SLinus Torvalds 
2639bae473a4SKirill A. Shutemov 	inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
2640bae473a4SKirill A. Shutemov 	dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
26411da177e4SLinus Torvalds 	pte = mk_pte(page, vma->vm_page_prot);
264282b0f8c3SJan Kara 	if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
26431da177e4SLinus Torvalds 		pte = maybe_mkwrite(pte_mkdirty(pte), vma);
264482b0f8c3SJan Kara 		vmf->flags &= ~FAULT_FLAG_WRITE;
26459a5b489bSAndrea Arcangeli 		ret |= VM_FAULT_WRITE;
2646d281ee61SKirill A. Shutemov 		exclusive = RMAP_EXCLUSIVE;
26471da177e4SLinus Torvalds 	}
26481da177e4SLinus Torvalds 	flush_icache_page(vma, page);
26492994302bSJan Kara 	if (pte_swp_soft_dirty(vmf->orig_pte))
2650179ef71cSCyrill Gorcunov 		pte = pte_mksoft_dirty(pte);
265182b0f8c3SJan Kara 	set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
26522994302bSJan Kara 	vmf->orig_pte = pte;
265300501b53SJohannes Weiner 	if (page == swapcache) {
265482b0f8c3SJan Kara 		do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
2655f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, true, false);
26561a8018fbSMinchan Kim 		activate_page(page);
265700501b53SJohannes Weiner 	} else { /* ksm created a completely new copy */
265882b0f8c3SJan Kara 		page_add_new_anon_rmap(page, vma, vmf->address, false);
2659f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, false, false);
266000501b53SJohannes Weiner 		lru_cache_add_active_or_unevictable(page, vma);
266100501b53SJohannes Weiner 	}
26621da177e4SLinus Torvalds 
2663c475a8abSHugh Dickins 	swap_free(entry);
26645ccc5abaSVladimir Davydov 	if (mem_cgroup_swap_full(page) ||
26655ccc5abaSVladimir Davydov 	    (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
2666a2c43eedSHugh Dickins 		try_to_free_swap(page);
2667c475a8abSHugh Dickins 	unlock_page(page);
266856f31801SHugh Dickins 	if (page != swapcache) {
26694969c119SAndrea Arcangeli 		/*
26704969c119SAndrea Arcangeli 		 * Hold the lock to avoid the swap entry to be reused
26714969c119SAndrea Arcangeli 		 * until we take the PT lock for the pte_same() check
26724969c119SAndrea Arcangeli 		 * (to avoid false positives from pte_same). For
26734969c119SAndrea Arcangeli 		 * further safety release the lock after the swap_free
26744969c119SAndrea Arcangeli 		 * so that the swap count won't change under a
26754969c119SAndrea Arcangeli 		 * parallel locked swapcache.
26764969c119SAndrea Arcangeli 		 */
26774969c119SAndrea Arcangeli 		unlock_page(swapcache);
267809cbfeafSKirill A. Shutemov 		put_page(swapcache);
26794969c119SAndrea Arcangeli 	}
2680c475a8abSHugh Dickins 
268182b0f8c3SJan Kara 	if (vmf->flags & FAULT_FLAG_WRITE) {
26822994302bSJan Kara 		ret |= do_wp_page(vmf);
268361469f1dSHugh Dickins 		if (ret & VM_FAULT_ERROR)
268461469f1dSHugh Dickins 			ret &= VM_FAULT_ERROR;
26851da177e4SLinus Torvalds 		goto out;
26861da177e4SLinus Torvalds 	}
26871da177e4SLinus Torvalds 
26881da177e4SLinus Torvalds 	/* No need to invalidate - it was non-present before */
268982b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
269065500d23SHugh Dickins unlock:
269182b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
26921da177e4SLinus Torvalds out:
26931da177e4SLinus Torvalds 	return ret;
2694b8107480SKirill Korotaev out_nomap:
2695f627c2f5SKirill A. Shutemov 	mem_cgroup_cancel_charge(page, memcg, false);
269682b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
2697bc43f75cSJohannes Weiner out_page:
2698b8107480SKirill Korotaev 	unlock_page(page);
26994779cb31SAndi Kleen out_release:
270009cbfeafSKirill A. Shutemov 	put_page(page);
270156f31801SHugh Dickins 	if (page != swapcache) {
27024969c119SAndrea Arcangeli 		unlock_page(swapcache);
270309cbfeafSKirill A. Shutemov 		put_page(swapcache);
27044969c119SAndrea Arcangeli 	}
270565500d23SHugh Dickins 	return ret;
27061da177e4SLinus Torvalds }
27071da177e4SLinus Torvalds 
27081da177e4SLinus Torvalds /*
27098ca3eb08SLuck, Tony  * This is like a special single-page "expand_{down|up}wards()",
27108ca3eb08SLuck, Tony  * except we must first make sure that 'address{-|+}PAGE_SIZE'
2711320b2b8dSLinus Torvalds  * doesn't hit another vma.
2712320b2b8dSLinus Torvalds  */
2713320b2b8dSLinus Torvalds static inline int check_stack_guard_page(struct vm_area_struct *vma, unsigned long address)
2714320b2b8dSLinus Torvalds {
2715320b2b8dSLinus Torvalds 	address &= PAGE_MASK;
2716320b2b8dSLinus Torvalds 	if ((vma->vm_flags & VM_GROWSDOWN) && address == vma->vm_start) {
27170e8e50e2SLinus Torvalds 		struct vm_area_struct *prev = vma->vm_prev;
2718320b2b8dSLinus Torvalds 
27190e8e50e2SLinus Torvalds 		/*
27200e8e50e2SLinus Torvalds 		 * Is there a mapping abutting this one below?
27210e8e50e2SLinus Torvalds 		 *
27220e8e50e2SLinus Torvalds 		 * That's only ok if it's the same stack mapping
27230e8e50e2SLinus Torvalds 		 * that has gotten split..
27240e8e50e2SLinus Torvalds 		 */
27250e8e50e2SLinus Torvalds 		if (prev && prev->vm_end == address)
27260e8e50e2SLinus Torvalds 			return prev->vm_flags & VM_GROWSDOWN ? 0 : -ENOMEM;
27270e8e50e2SLinus Torvalds 
2728fee7e49dSLinus Torvalds 		return expand_downwards(vma, address - PAGE_SIZE);
2729320b2b8dSLinus Torvalds 	}
27308ca3eb08SLuck, Tony 	if ((vma->vm_flags & VM_GROWSUP) && address + PAGE_SIZE == vma->vm_end) {
27318ca3eb08SLuck, Tony 		struct vm_area_struct *next = vma->vm_next;
27328ca3eb08SLuck, Tony 
27338ca3eb08SLuck, Tony 		/* As VM_GROWSDOWN but s/below/above/ */
27348ca3eb08SLuck, Tony 		if (next && next->vm_start == address + PAGE_SIZE)
27358ca3eb08SLuck, Tony 			return next->vm_flags & VM_GROWSUP ? 0 : -ENOMEM;
27368ca3eb08SLuck, Tony 
2737fee7e49dSLinus Torvalds 		return expand_upwards(vma, address + PAGE_SIZE);
27388ca3eb08SLuck, Tony 	}
2739320b2b8dSLinus Torvalds 	return 0;
2740320b2b8dSLinus Torvalds }
2741320b2b8dSLinus Torvalds 
2742320b2b8dSLinus Torvalds /*
27438f4e2101SHugh Dickins  * We enter with non-exclusive mmap_sem (to exclude vma changes,
27448f4e2101SHugh Dickins  * but allow concurrent faults), and pte mapped but not yet locked.
27458f4e2101SHugh Dickins  * We return with mmap_sem still held, but pte unmapped and unlocked.
27461da177e4SLinus Torvalds  */
274782b0f8c3SJan Kara static int do_anonymous_page(struct vm_fault *vmf)
27481da177e4SLinus Torvalds {
274982b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
275000501b53SJohannes Weiner 	struct mem_cgroup *memcg;
27518f4e2101SHugh Dickins 	struct page *page;
27521da177e4SLinus Torvalds 	pte_t entry;
27531da177e4SLinus Torvalds 
27546b7339f4SKirill A. Shutemov 	/* File mapping without ->vm_ops ? */
27556b7339f4SKirill A. Shutemov 	if (vma->vm_flags & VM_SHARED)
27566b7339f4SKirill A. Shutemov 		return VM_FAULT_SIGBUS;
27576b7339f4SKirill A. Shutemov 
275811ac5524SLinus Torvalds 	/* Check if we need to add a guard page to the stack */
275982b0f8c3SJan Kara 	if (check_stack_guard_page(vma, vmf->address) < 0)
27609c145c56SLinus Torvalds 		return VM_FAULT_SIGSEGV;
276111ac5524SLinus Torvalds 
27627267ec00SKirill A. Shutemov 	/*
27637267ec00SKirill A. Shutemov 	 * Use pte_alloc() instead of pte_alloc_map().  We can't run
27647267ec00SKirill A. Shutemov 	 * pte_offset_map() on pmds where a huge pmd might be created
27657267ec00SKirill A. Shutemov 	 * from a different thread.
27667267ec00SKirill A. Shutemov 	 *
27677267ec00SKirill A. Shutemov 	 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
27687267ec00SKirill A. Shutemov 	 * parallel threads are excluded by other means.
27697267ec00SKirill A. Shutemov 	 *
27707267ec00SKirill A. Shutemov 	 * Here we only have down_read(mmap_sem).
27717267ec00SKirill A. Shutemov 	 */
277282b0f8c3SJan Kara 	if (pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))
27737267ec00SKirill A. Shutemov 		return VM_FAULT_OOM;
27747267ec00SKirill A. Shutemov 
27757267ec00SKirill A. Shutemov 	/* See the comment in pte_alloc_one_map() */
277682b0f8c3SJan Kara 	if (unlikely(pmd_trans_unstable(vmf->pmd)))
27777267ec00SKirill A. Shutemov 		return 0;
27787267ec00SKirill A. Shutemov 
277911ac5524SLinus Torvalds 	/* Use the zero-page for reads */
278082b0f8c3SJan Kara 	if (!(vmf->flags & FAULT_FLAG_WRITE) &&
2781bae473a4SKirill A. Shutemov 			!mm_forbids_zeropage(vma->vm_mm)) {
278282b0f8c3SJan Kara 		entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
278362eede62SHugh Dickins 						vma->vm_page_prot));
278482b0f8c3SJan Kara 		vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
278582b0f8c3SJan Kara 				vmf->address, &vmf->ptl);
278682b0f8c3SJan Kara 		if (!pte_none(*vmf->pte))
2787a13ea5b7SHugh Dickins 			goto unlock;
27886b251fc9SAndrea Arcangeli 		/* Deliver the page fault to userland, check inside PT lock */
27896b251fc9SAndrea Arcangeli 		if (userfaultfd_missing(vma)) {
279082b0f8c3SJan Kara 			pte_unmap_unlock(vmf->pte, vmf->ptl);
279182b0f8c3SJan Kara 			return handle_userfault(vmf, VM_UFFD_MISSING);
27926b251fc9SAndrea Arcangeli 		}
2793a13ea5b7SHugh Dickins 		goto setpte;
2794a13ea5b7SHugh Dickins 	}
2795a13ea5b7SHugh Dickins 
27961da177e4SLinus Torvalds 	/* Allocate our own private page. */
27971da177e4SLinus Torvalds 	if (unlikely(anon_vma_prepare(vma)))
279865500d23SHugh Dickins 		goto oom;
279982b0f8c3SJan Kara 	page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
28001da177e4SLinus Torvalds 	if (!page)
280165500d23SHugh Dickins 		goto oom;
2802eb3c24f3SMel Gorman 
2803bae473a4SKirill A. Shutemov 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
2804eb3c24f3SMel Gorman 		goto oom_free_page;
2805eb3c24f3SMel Gorman 
280652f37629SMinchan Kim 	/*
280752f37629SMinchan Kim 	 * The memory barrier inside __SetPageUptodate makes sure that
280852f37629SMinchan Kim 	 * preceeding stores to the page contents become visible before
280952f37629SMinchan Kim 	 * the set_pte_at() write.
281052f37629SMinchan Kim 	 */
28110ed361deSNick Piggin 	__SetPageUptodate(page);
28121da177e4SLinus Torvalds 
281365500d23SHugh Dickins 	entry = mk_pte(page, vma->vm_page_prot);
28141ac0cb5dSHugh Dickins 	if (vma->vm_flags & VM_WRITE)
28151ac0cb5dSHugh Dickins 		entry = pte_mkwrite(pte_mkdirty(entry));
28168f4e2101SHugh Dickins 
281782b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
281882b0f8c3SJan Kara 			&vmf->ptl);
281982b0f8c3SJan Kara 	if (!pte_none(*vmf->pte))
28208f4e2101SHugh Dickins 		goto release;
28219ba69294SHugh Dickins 
28226b251fc9SAndrea Arcangeli 	/* Deliver the page fault to userland, check inside PT lock */
28236b251fc9SAndrea Arcangeli 	if (userfaultfd_missing(vma)) {
282482b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
2825f627c2f5SKirill A. Shutemov 		mem_cgroup_cancel_charge(page, memcg, false);
282609cbfeafSKirill A. Shutemov 		put_page(page);
282782b0f8c3SJan Kara 		return handle_userfault(vmf, VM_UFFD_MISSING);
28286b251fc9SAndrea Arcangeli 	}
28296b251fc9SAndrea Arcangeli 
2830bae473a4SKirill A. Shutemov 	inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
283182b0f8c3SJan Kara 	page_add_new_anon_rmap(page, vma, vmf->address, false);
2832f627c2f5SKirill A. Shutemov 	mem_cgroup_commit_charge(page, memcg, false, false);
283300501b53SJohannes Weiner 	lru_cache_add_active_or_unevictable(page, vma);
2834a13ea5b7SHugh Dickins setpte:
283582b0f8c3SJan Kara 	set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
28361da177e4SLinus Torvalds 
28371da177e4SLinus Torvalds 	/* No need to invalidate - it was non-present before */
283882b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
283965500d23SHugh Dickins unlock:
284082b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
284183c54070SNick Piggin 	return 0;
28428f4e2101SHugh Dickins release:
2843f627c2f5SKirill A. Shutemov 	mem_cgroup_cancel_charge(page, memcg, false);
284409cbfeafSKirill A. Shutemov 	put_page(page);
28458f4e2101SHugh Dickins 	goto unlock;
28468a9f3ccdSBalbir Singh oom_free_page:
284709cbfeafSKirill A. Shutemov 	put_page(page);
284865500d23SHugh Dickins oom:
28491da177e4SLinus Torvalds 	return VM_FAULT_OOM;
28501da177e4SLinus Torvalds }
28511da177e4SLinus Torvalds 
28529a95f3cfSPaul Cassella /*
28539a95f3cfSPaul Cassella  * The mmap_sem must have been held on entry, and may have been
28549a95f3cfSPaul Cassella  * released depending on flags and vma->vm_ops->fault() return value.
28559a95f3cfSPaul Cassella  * See filemap_fault() and __lock_page_retry().
28569a95f3cfSPaul Cassella  */
2857936ca80dSJan Kara static int __do_fault(struct vm_fault *vmf)
28587eae74afSKirill A. Shutemov {
285982b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
28607eae74afSKirill A. Shutemov 	int ret;
28617eae74afSKirill A. Shutemov 
2862667240e0SJan Kara 	ret = vma->vm_ops->fault(vma, vmf);
28633917048dSJan Kara 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
2864b1aa812bSJan Kara 			    VM_FAULT_DONE_COW)))
2865bc2466e4SJan Kara 		return ret;
28667eae74afSKirill A. Shutemov 
2867667240e0SJan Kara 	if (unlikely(PageHWPoison(vmf->page))) {
28687eae74afSKirill A. Shutemov 		if (ret & VM_FAULT_LOCKED)
2869667240e0SJan Kara 			unlock_page(vmf->page);
2870667240e0SJan Kara 		put_page(vmf->page);
2871936ca80dSJan Kara 		vmf->page = NULL;
28727eae74afSKirill A. Shutemov 		return VM_FAULT_HWPOISON;
28737eae74afSKirill A. Shutemov 	}
28747eae74afSKirill A. Shutemov 
28757eae74afSKirill A. Shutemov 	if (unlikely(!(ret & VM_FAULT_LOCKED)))
2876667240e0SJan Kara 		lock_page(vmf->page);
28777eae74afSKirill A. Shutemov 	else
2878667240e0SJan Kara 		VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
28797eae74afSKirill A. Shutemov 
28807eae74afSKirill A. Shutemov 	return ret;
28817eae74afSKirill A. Shutemov }
28827eae74afSKirill A. Shutemov 
288382b0f8c3SJan Kara static int pte_alloc_one_map(struct vm_fault *vmf)
28847267ec00SKirill A. Shutemov {
288582b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
28867267ec00SKirill A. Shutemov 
288782b0f8c3SJan Kara 	if (!pmd_none(*vmf->pmd))
28887267ec00SKirill A. Shutemov 		goto map_pte;
288982b0f8c3SJan Kara 	if (vmf->prealloc_pte) {
289082b0f8c3SJan Kara 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
289182b0f8c3SJan Kara 		if (unlikely(!pmd_none(*vmf->pmd))) {
289282b0f8c3SJan Kara 			spin_unlock(vmf->ptl);
28937267ec00SKirill A. Shutemov 			goto map_pte;
28947267ec00SKirill A. Shutemov 		}
28957267ec00SKirill A. Shutemov 
28967267ec00SKirill A. Shutemov 		atomic_long_inc(&vma->vm_mm->nr_ptes);
289782b0f8c3SJan Kara 		pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
289882b0f8c3SJan Kara 		spin_unlock(vmf->ptl);
289982b0f8c3SJan Kara 		vmf->prealloc_pte = 0;
290082b0f8c3SJan Kara 	} else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))) {
29017267ec00SKirill A. Shutemov 		return VM_FAULT_OOM;
29027267ec00SKirill A. Shutemov 	}
29037267ec00SKirill A. Shutemov map_pte:
29047267ec00SKirill A. Shutemov 	/*
29057267ec00SKirill A. Shutemov 	 * If a huge pmd materialized under us just retry later.  Use
29067267ec00SKirill A. Shutemov 	 * pmd_trans_unstable() instead of pmd_trans_huge() to ensure the pmd
29077267ec00SKirill A. Shutemov 	 * didn't become pmd_trans_huge under us and then back to pmd_none, as
29087267ec00SKirill A. Shutemov 	 * a result of MADV_DONTNEED running immediately after a huge pmd fault
29097267ec00SKirill A. Shutemov 	 * in a different thread of this mm, in turn leading to a misleading
29107267ec00SKirill A. Shutemov 	 * pmd_trans_huge() retval.  All we have to ensure is that it is a
29117267ec00SKirill A. Shutemov 	 * regular pmd that we can walk with pte_offset_map() and we can do that
29127267ec00SKirill A. Shutemov 	 * through an atomic read in C, which is what pmd_trans_unstable()
29137267ec00SKirill A. Shutemov 	 * provides.
29147267ec00SKirill A. Shutemov 	 */
291582b0f8c3SJan Kara 	if (pmd_trans_unstable(vmf->pmd) || pmd_devmap(*vmf->pmd))
29167267ec00SKirill A. Shutemov 		return VM_FAULT_NOPAGE;
29177267ec00SKirill A. Shutemov 
291882b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
291982b0f8c3SJan Kara 			&vmf->ptl);
29207267ec00SKirill A. Shutemov 	return 0;
29217267ec00SKirill A. Shutemov }
29227267ec00SKirill A. Shutemov 
2923e496cf3dSKirill A. Shutemov #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
292410102459SKirill A. Shutemov 
292510102459SKirill A. Shutemov #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
292610102459SKirill A. Shutemov static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
292710102459SKirill A. Shutemov 		unsigned long haddr)
292810102459SKirill A. Shutemov {
292910102459SKirill A. Shutemov 	if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
293010102459SKirill A. Shutemov 			(vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
293110102459SKirill A. Shutemov 		return false;
293210102459SKirill A. Shutemov 	if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
293310102459SKirill A. Shutemov 		return false;
293410102459SKirill A. Shutemov 	return true;
293510102459SKirill A. Shutemov }
293610102459SKirill A. Shutemov 
293782b0f8c3SJan Kara static void deposit_prealloc_pte(struct vm_fault *vmf)
2938953c66c2SAneesh Kumar K.V {
293982b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
2940953c66c2SAneesh Kumar K.V 
294182b0f8c3SJan Kara 	pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
2942953c66c2SAneesh Kumar K.V 	/*
2943953c66c2SAneesh Kumar K.V 	 * We are going to consume the prealloc table,
2944953c66c2SAneesh Kumar K.V 	 * count that as nr_ptes.
2945953c66c2SAneesh Kumar K.V 	 */
2946953c66c2SAneesh Kumar K.V 	atomic_long_inc(&vma->vm_mm->nr_ptes);
294782b0f8c3SJan Kara 	vmf->prealloc_pte = 0;
2948953c66c2SAneesh Kumar K.V }
2949953c66c2SAneesh Kumar K.V 
295082b0f8c3SJan Kara static int do_set_pmd(struct vm_fault *vmf, struct page *page)
295110102459SKirill A. Shutemov {
295282b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
295382b0f8c3SJan Kara 	bool write = vmf->flags & FAULT_FLAG_WRITE;
295482b0f8c3SJan Kara 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
295510102459SKirill A. Shutemov 	pmd_t entry;
295610102459SKirill A. Shutemov 	int i, ret;
295710102459SKirill A. Shutemov 
295810102459SKirill A. Shutemov 	if (!transhuge_vma_suitable(vma, haddr))
295910102459SKirill A. Shutemov 		return VM_FAULT_FALLBACK;
296010102459SKirill A. Shutemov 
296110102459SKirill A. Shutemov 	ret = VM_FAULT_FALLBACK;
296210102459SKirill A. Shutemov 	page = compound_head(page);
296310102459SKirill A. Shutemov 
2964953c66c2SAneesh Kumar K.V 	/*
2965953c66c2SAneesh Kumar K.V 	 * Archs like ppc64 need additonal space to store information
2966953c66c2SAneesh Kumar K.V 	 * related to pte entry. Use the preallocated table for that.
2967953c66c2SAneesh Kumar K.V 	 */
296882b0f8c3SJan Kara 	if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
296982b0f8c3SJan Kara 		vmf->prealloc_pte = pte_alloc_one(vma->vm_mm, vmf->address);
297082b0f8c3SJan Kara 		if (!vmf->prealloc_pte)
2971953c66c2SAneesh Kumar K.V 			return VM_FAULT_OOM;
2972953c66c2SAneesh Kumar K.V 		smp_wmb(); /* See comment in __pte_alloc() */
2973953c66c2SAneesh Kumar K.V 	}
2974953c66c2SAneesh Kumar K.V 
297582b0f8c3SJan Kara 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
297682b0f8c3SJan Kara 	if (unlikely(!pmd_none(*vmf->pmd)))
297710102459SKirill A. Shutemov 		goto out;
297810102459SKirill A. Shutemov 
297910102459SKirill A. Shutemov 	for (i = 0; i < HPAGE_PMD_NR; i++)
298010102459SKirill A. Shutemov 		flush_icache_page(vma, page + i);
298110102459SKirill A. Shutemov 
298210102459SKirill A. Shutemov 	entry = mk_huge_pmd(page, vma->vm_page_prot);
298310102459SKirill A. Shutemov 	if (write)
298410102459SKirill A. Shutemov 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
298510102459SKirill A. Shutemov 
298610102459SKirill A. Shutemov 	add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);
298710102459SKirill A. Shutemov 	page_add_file_rmap(page, true);
2988953c66c2SAneesh Kumar K.V 	/*
2989953c66c2SAneesh Kumar K.V 	 * deposit and withdraw with pmd lock held
2990953c66c2SAneesh Kumar K.V 	 */
2991953c66c2SAneesh Kumar K.V 	if (arch_needs_pgtable_deposit())
299282b0f8c3SJan Kara 		deposit_prealloc_pte(vmf);
299310102459SKirill A. Shutemov 
299482b0f8c3SJan Kara 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
299510102459SKirill A. Shutemov 
299682b0f8c3SJan Kara 	update_mmu_cache_pmd(vma, haddr, vmf->pmd);
299710102459SKirill A. Shutemov 
299810102459SKirill A. Shutemov 	/* fault is handled */
299910102459SKirill A. Shutemov 	ret = 0;
300095ecedcdSKirill A. Shutemov 	count_vm_event(THP_FILE_MAPPED);
300110102459SKirill A. Shutemov out:
3002953c66c2SAneesh Kumar K.V 	/*
3003953c66c2SAneesh Kumar K.V 	 * If we are going to fallback to pte mapping, do a
3004953c66c2SAneesh Kumar K.V 	 * withdraw with pmd lock held.
3005953c66c2SAneesh Kumar K.V 	 */
3006953c66c2SAneesh Kumar K.V 	if (arch_needs_pgtable_deposit() && ret == VM_FAULT_FALLBACK)
300782b0f8c3SJan Kara 		vmf->prealloc_pte = pgtable_trans_huge_withdraw(vma->vm_mm,
300882b0f8c3SJan Kara 								vmf->pmd);
300982b0f8c3SJan Kara 	spin_unlock(vmf->ptl);
301010102459SKirill A. Shutemov 	return ret;
301110102459SKirill A. Shutemov }
301210102459SKirill A. Shutemov #else
301382b0f8c3SJan Kara static int do_set_pmd(struct vm_fault *vmf, struct page *page)
301410102459SKirill A. Shutemov {
301510102459SKirill A. Shutemov 	BUILD_BUG();
301610102459SKirill A. Shutemov 	return 0;
301710102459SKirill A. Shutemov }
301810102459SKirill A. Shutemov #endif
301910102459SKirill A. Shutemov 
30208c6e50b0SKirill A. Shutemov /**
30217267ec00SKirill A. Shutemov  * alloc_set_pte - setup new PTE entry for given page and add reverse page
30227267ec00SKirill A. Shutemov  * mapping. If needed, the fucntion allocates page table or use pre-allocated.
30238c6e50b0SKirill A. Shutemov  *
302482b0f8c3SJan Kara  * @vmf: fault environment
30257267ec00SKirill A. Shutemov  * @memcg: memcg to charge page (only for private mappings)
30268c6e50b0SKirill A. Shutemov  * @page: page to map
30278c6e50b0SKirill A. Shutemov  *
302882b0f8c3SJan Kara  * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
302982b0f8c3SJan Kara  * return.
30308c6e50b0SKirill A. Shutemov  *
30318c6e50b0SKirill A. Shutemov  * Target users are page handler itself and implementations of
30328c6e50b0SKirill A. Shutemov  * vm_ops->map_pages.
30338c6e50b0SKirill A. Shutemov  */
303482b0f8c3SJan Kara int alloc_set_pte(struct vm_fault *vmf, struct mem_cgroup *memcg,
30357267ec00SKirill A. Shutemov 		struct page *page)
30363bb97794SKirill A. Shutemov {
303782b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
303882b0f8c3SJan Kara 	bool write = vmf->flags & FAULT_FLAG_WRITE;
30393bb97794SKirill A. Shutemov 	pte_t entry;
304010102459SKirill A. Shutemov 	int ret;
304110102459SKirill A. Shutemov 
304282b0f8c3SJan Kara 	if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3043e496cf3dSKirill A. Shutemov 			IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
304410102459SKirill A. Shutemov 		/* THP on COW? */
304510102459SKirill A. Shutemov 		VM_BUG_ON_PAGE(memcg, page);
304610102459SKirill A. Shutemov 
304782b0f8c3SJan Kara 		ret = do_set_pmd(vmf, page);
304810102459SKirill A. Shutemov 		if (ret != VM_FAULT_FALLBACK)
3049953c66c2SAneesh Kumar K.V 			goto fault_handled;
305010102459SKirill A. Shutemov 	}
30513bb97794SKirill A. Shutemov 
305282b0f8c3SJan Kara 	if (!vmf->pte) {
305382b0f8c3SJan Kara 		ret = pte_alloc_one_map(vmf);
30547267ec00SKirill A. Shutemov 		if (ret)
3055953c66c2SAneesh Kumar K.V 			goto fault_handled;
30567267ec00SKirill A. Shutemov 	}
30577267ec00SKirill A. Shutemov 
30587267ec00SKirill A. Shutemov 	/* Re-check under ptl */
305982b0f8c3SJan Kara 	if (unlikely(!pte_none(*vmf->pte))) {
3060953c66c2SAneesh Kumar K.V 		ret = VM_FAULT_NOPAGE;
3061953c66c2SAneesh Kumar K.V 		goto fault_handled;
3062953c66c2SAneesh Kumar K.V 	}
30637267ec00SKirill A. Shutemov 
30643bb97794SKirill A. Shutemov 	flush_icache_page(vma, page);
30653bb97794SKirill A. Shutemov 	entry = mk_pte(page, vma->vm_page_prot);
30663bb97794SKirill A. Shutemov 	if (write)
30673bb97794SKirill A. Shutemov 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3068bae473a4SKirill A. Shutemov 	/* copy-on-write page */
3069bae473a4SKirill A. Shutemov 	if (write && !(vma->vm_flags & VM_SHARED)) {
30703bb97794SKirill A. Shutemov 		inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
307182b0f8c3SJan Kara 		page_add_new_anon_rmap(page, vma, vmf->address, false);
30727267ec00SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, false, false);
30737267ec00SKirill A. Shutemov 		lru_cache_add_active_or_unevictable(page, vma);
30743bb97794SKirill A. Shutemov 	} else {
3075eca56ff9SJerome Marchand 		inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3076dd78feddSKirill A. Shutemov 		page_add_file_rmap(page, false);
30773bb97794SKirill A. Shutemov 	}
307882b0f8c3SJan Kara 	set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
30793bb97794SKirill A. Shutemov 
30803bb97794SKirill A. Shutemov 	/* no need to invalidate: a not-present page won't be cached */
308182b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
3082953c66c2SAneesh Kumar K.V 	ret = 0;
30837267ec00SKirill A. Shutemov 
3084953c66c2SAneesh Kumar K.V fault_handled:
3085953c66c2SAneesh Kumar K.V 	/* preallocated pagetable is unused: free it */
308682b0f8c3SJan Kara 	if (vmf->prealloc_pte) {
308782b0f8c3SJan Kara 		pte_free(vmf->vma->vm_mm, vmf->prealloc_pte);
308882b0f8c3SJan Kara 		vmf->prealloc_pte = 0;
3089953c66c2SAneesh Kumar K.V 	}
3090953c66c2SAneesh Kumar K.V 	return ret;
30913bb97794SKirill A. Shutemov }
30923bb97794SKirill A. Shutemov 
30939118c0cbSJan Kara 
30949118c0cbSJan Kara /**
30959118c0cbSJan Kara  * finish_fault - finish page fault once we have prepared the page to fault
30969118c0cbSJan Kara  *
30979118c0cbSJan Kara  * @vmf: structure describing the fault
30989118c0cbSJan Kara  *
30999118c0cbSJan Kara  * This function handles all that is needed to finish a page fault once the
31009118c0cbSJan Kara  * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
31019118c0cbSJan Kara  * given page, adds reverse page mapping, handles memcg charges and LRU
31029118c0cbSJan Kara  * addition. The function returns 0 on success, VM_FAULT_ code in case of
31039118c0cbSJan Kara  * error.
31049118c0cbSJan Kara  *
31059118c0cbSJan Kara  * The function expects the page to be locked and on success it consumes a
31069118c0cbSJan Kara  * reference of a page being mapped (for the PTE which maps it).
31079118c0cbSJan Kara  */
31089118c0cbSJan Kara int finish_fault(struct vm_fault *vmf)
31099118c0cbSJan Kara {
31109118c0cbSJan Kara 	struct page *page;
31119118c0cbSJan Kara 	int ret;
31129118c0cbSJan Kara 
31139118c0cbSJan Kara 	/* Did we COW the page? */
31149118c0cbSJan Kara 	if ((vmf->flags & FAULT_FLAG_WRITE) &&
31159118c0cbSJan Kara 	    !(vmf->vma->vm_flags & VM_SHARED))
31169118c0cbSJan Kara 		page = vmf->cow_page;
31179118c0cbSJan Kara 	else
31189118c0cbSJan Kara 		page = vmf->page;
31199118c0cbSJan Kara 	ret = alloc_set_pte(vmf, vmf->memcg, page);
31209118c0cbSJan Kara 	if (vmf->pte)
31219118c0cbSJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
31229118c0cbSJan Kara 	return ret;
31239118c0cbSJan Kara }
31249118c0cbSJan Kara 
31253a91053aSKirill A. Shutemov static unsigned long fault_around_bytes __read_mostly =
31263a91053aSKirill A. Shutemov 	rounddown_pow_of_two(65536);
3127a9b0f861SKirill A. Shutemov 
31281592eef0SKirill A. Shutemov #ifdef CONFIG_DEBUG_FS
3129a9b0f861SKirill A. Shutemov static int fault_around_bytes_get(void *data, u64 *val)
31301592eef0SKirill A. Shutemov {
3131a9b0f861SKirill A. Shutemov 	*val = fault_around_bytes;
31321592eef0SKirill A. Shutemov 	return 0;
31331592eef0SKirill A. Shutemov }
31341592eef0SKirill A. Shutemov 
3135b4903d6eSAndrey Ryabinin /*
3136b4903d6eSAndrey Ryabinin  * fault_around_pages() and fault_around_mask() expects fault_around_bytes
3137b4903d6eSAndrey Ryabinin  * rounded down to nearest page order. It's what do_fault_around() expects to
3138b4903d6eSAndrey Ryabinin  * see.
3139b4903d6eSAndrey Ryabinin  */
3140a9b0f861SKirill A. Shutemov static int fault_around_bytes_set(void *data, u64 val)
31411592eef0SKirill A. Shutemov {
3142a9b0f861SKirill A. Shutemov 	if (val / PAGE_SIZE > PTRS_PER_PTE)
31431592eef0SKirill A. Shutemov 		return -EINVAL;
3144b4903d6eSAndrey Ryabinin 	if (val > PAGE_SIZE)
3145b4903d6eSAndrey Ryabinin 		fault_around_bytes = rounddown_pow_of_two(val);
3146b4903d6eSAndrey Ryabinin 	else
3147b4903d6eSAndrey Ryabinin 		fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
31481592eef0SKirill A. Shutemov 	return 0;
31491592eef0SKirill A. Shutemov }
3150a9b0f861SKirill A. Shutemov DEFINE_SIMPLE_ATTRIBUTE(fault_around_bytes_fops,
3151a9b0f861SKirill A. Shutemov 		fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
31521592eef0SKirill A. Shutemov 
31531592eef0SKirill A. Shutemov static int __init fault_around_debugfs(void)
31541592eef0SKirill A. Shutemov {
31551592eef0SKirill A. Shutemov 	void *ret;
31561592eef0SKirill A. Shutemov 
3157a9b0f861SKirill A. Shutemov 	ret = debugfs_create_file("fault_around_bytes", 0644, NULL, NULL,
3158a9b0f861SKirill A. Shutemov 			&fault_around_bytes_fops);
31591592eef0SKirill A. Shutemov 	if (!ret)
3160a9b0f861SKirill A. Shutemov 		pr_warn("Failed to create fault_around_bytes in debugfs");
31611592eef0SKirill A. Shutemov 	return 0;
31621592eef0SKirill A. Shutemov }
31631592eef0SKirill A. Shutemov late_initcall(fault_around_debugfs);
31641592eef0SKirill A. Shutemov #endif
31658c6e50b0SKirill A. Shutemov 
31661fdb412bSKirill A. Shutemov /*
31671fdb412bSKirill A. Shutemov  * do_fault_around() tries to map few pages around the fault address. The hope
31681fdb412bSKirill A. Shutemov  * is that the pages will be needed soon and this will lower the number of
31691fdb412bSKirill A. Shutemov  * faults to handle.
31701fdb412bSKirill A. Shutemov  *
31711fdb412bSKirill A. Shutemov  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
31721fdb412bSKirill A. Shutemov  * not ready to be mapped: not up-to-date, locked, etc.
31731fdb412bSKirill A. Shutemov  *
31741fdb412bSKirill A. Shutemov  * This function is called with the page table lock taken. In the split ptlock
31751fdb412bSKirill A. Shutemov  * case the page table lock only protects only those entries which belong to
31761fdb412bSKirill A. Shutemov  * the page table corresponding to the fault address.
31771fdb412bSKirill A. Shutemov  *
31781fdb412bSKirill A. Shutemov  * This function doesn't cross the VMA boundaries, in order to call map_pages()
31791fdb412bSKirill A. Shutemov  * only once.
31801fdb412bSKirill A. Shutemov  *
31811fdb412bSKirill A. Shutemov  * fault_around_pages() defines how many pages we'll try to map.
31821fdb412bSKirill A. Shutemov  * do_fault_around() expects it to return a power of two less than or equal to
31831fdb412bSKirill A. Shutemov  * PTRS_PER_PTE.
31841fdb412bSKirill A. Shutemov  *
31851fdb412bSKirill A. Shutemov  * The virtual address of the area that we map is naturally aligned to the
31861fdb412bSKirill A. Shutemov  * fault_around_pages() value (and therefore to page order).  This way it's
31871fdb412bSKirill A. Shutemov  * easier to guarantee that we don't cross page table boundaries.
31881fdb412bSKirill A. Shutemov  */
31890721ec8bSJan Kara static int do_fault_around(struct vm_fault *vmf)
31908c6e50b0SKirill A. Shutemov {
319182b0f8c3SJan Kara 	unsigned long address = vmf->address, nr_pages, mask;
31920721ec8bSJan Kara 	pgoff_t start_pgoff = vmf->pgoff;
3193bae473a4SKirill A. Shutemov 	pgoff_t end_pgoff;
31947267ec00SKirill A. Shutemov 	int off, ret = 0;
31958c6e50b0SKirill A. Shutemov 
31964db0c3c2SJason Low 	nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3197aecd6f44SKirill A. Shutemov 	mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3198aecd6f44SKirill A. Shutemov 
319982b0f8c3SJan Kara 	vmf->address = max(address & mask, vmf->vma->vm_start);
320082b0f8c3SJan Kara 	off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3201bae473a4SKirill A. Shutemov 	start_pgoff -= off;
32028c6e50b0SKirill A. Shutemov 
32038c6e50b0SKirill A. Shutemov 	/*
3204bae473a4SKirill A. Shutemov 	 *  end_pgoff is either end of page table or end of vma
3205bae473a4SKirill A. Shutemov 	 *  or fault_around_pages() from start_pgoff, depending what is nearest.
32068c6e50b0SKirill A. Shutemov 	 */
3207bae473a4SKirill A. Shutemov 	end_pgoff = start_pgoff -
320882b0f8c3SJan Kara 		((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
32098c6e50b0SKirill A. Shutemov 		PTRS_PER_PTE - 1;
321082b0f8c3SJan Kara 	end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
3211bae473a4SKirill A. Shutemov 			start_pgoff + nr_pages - 1);
32128c6e50b0SKirill A. Shutemov 
321382b0f8c3SJan Kara 	if (pmd_none(*vmf->pmd)) {
321482b0f8c3SJan Kara 		vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
321582b0f8c3SJan Kara 						  vmf->address);
321682b0f8c3SJan Kara 		if (!vmf->prealloc_pte)
3217c5f88bd2SVegard Nossum 			goto out;
32187267ec00SKirill A. Shutemov 		smp_wmb(); /* See comment in __pte_alloc() */
32198c6e50b0SKirill A. Shutemov 	}
32208c6e50b0SKirill A. Shutemov 
322182b0f8c3SJan Kara 	vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
32227267ec00SKirill A. Shutemov 
32237267ec00SKirill A. Shutemov 	/* Huge page is mapped? Page fault is solved */
322482b0f8c3SJan Kara 	if (pmd_trans_huge(*vmf->pmd)) {
32257267ec00SKirill A. Shutemov 		ret = VM_FAULT_NOPAGE;
32267267ec00SKirill A. Shutemov 		goto out;
32278c6e50b0SKirill A. Shutemov 	}
32288c6e50b0SKirill A. Shutemov 
32297267ec00SKirill A. Shutemov 	/* ->map_pages() haven't done anything useful. Cold page cache? */
323082b0f8c3SJan Kara 	if (!vmf->pte)
32317267ec00SKirill A. Shutemov 		goto out;
32327267ec00SKirill A. Shutemov 
32337267ec00SKirill A. Shutemov 	/* check if the page fault is solved */
323482b0f8c3SJan Kara 	vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
323582b0f8c3SJan Kara 	if (!pte_none(*vmf->pte))
32367267ec00SKirill A. Shutemov 		ret = VM_FAULT_NOPAGE;
323782b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
32387267ec00SKirill A. Shutemov out:
323982b0f8c3SJan Kara 	vmf->address = address;
324082b0f8c3SJan Kara 	vmf->pte = NULL;
32417267ec00SKirill A. Shutemov 	return ret;
32427267ec00SKirill A. Shutemov }
32437267ec00SKirill A. Shutemov 
32440721ec8bSJan Kara static int do_read_fault(struct vm_fault *vmf)
3245e655fb29SKirill A. Shutemov {
324682b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
32478c6e50b0SKirill A. Shutemov 	int ret = 0;
32488c6e50b0SKirill A. Shutemov 
32498c6e50b0SKirill A. Shutemov 	/*
32508c6e50b0SKirill A. Shutemov 	 * Let's call ->map_pages() first and use ->fault() as fallback
32518c6e50b0SKirill A. Shutemov 	 * if page by the offset is not ready to be mapped (cold cache or
32528c6e50b0SKirill A. Shutemov 	 * something).
32538c6e50b0SKirill A. Shutemov 	 */
32549b4bdd2fSKirill A. Shutemov 	if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
32550721ec8bSJan Kara 		ret = do_fault_around(vmf);
32567267ec00SKirill A. Shutemov 		if (ret)
32577267ec00SKirill A. Shutemov 			return ret;
32588c6e50b0SKirill A. Shutemov 	}
3259e655fb29SKirill A. Shutemov 
3260936ca80dSJan Kara 	ret = __do_fault(vmf);
3261e655fb29SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3262e655fb29SKirill A. Shutemov 		return ret;
3263e655fb29SKirill A. Shutemov 
32649118c0cbSJan Kara 	ret |= finish_fault(vmf);
3265936ca80dSJan Kara 	unlock_page(vmf->page);
32667267ec00SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3267936ca80dSJan Kara 		put_page(vmf->page);
3268e655fb29SKirill A. Shutemov 	return ret;
3269e655fb29SKirill A. Shutemov }
3270e655fb29SKirill A. Shutemov 
32710721ec8bSJan Kara static int do_cow_fault(struct vm_fault *vmf)
3272ec47c3b9SKirill A. Shutemov {
327382b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
3274ec47c3b9SKirill A. Shutemov 	int ret;
3275ec47c3b9SKirill A. Shutemov 
3276ec47c3b9SKirill A. Shutemov 	if (unlikely(anon_vma_prepare(vma)))
3277ec47c3b9SKirill A. Shutemov 		return VM_FAULT_OOM;
3278ec47c3b9SKirill A. Shutemov 
3279936ca80dSJan Kara 	vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3280936ca80dSJan Kara 	if (!vmf->cow_page)
3281ec47c3b9SKirill A. Shutemov 		return VM_FAULT_OOM;
3282ec47c3b9SKirill A. Shutemov 
3283936ca80dSJan Kara 	if (mem_cgroup_try_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL,
32843917048dSJan Kara 				&vmf->memcg, false)) {
3285936ca80dSJan Kara 		put_page(vmf->cow_page);
3286ec47c3b9SKirill A. Shutemov 		return VM_FAULT_OOM;
3287ec47c3b9SKirill A. Shutemov 	}
3288ec47c3b9SKirill A. Shutemov 
3289936ca80dSJan Kara 	ret = __do_fault(vmf);
3290ec47c3b9SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3291ec47c3b9SKirill A. Shutemov 		goto uncharge_out;
32923917048dSJan Kara 	if (ret & VM_FAULT_DONE_COW)
32933917048dSJan Kara 		return ret;
3294ec47c3b9SKirill A. Shutemov 
3295936ca80dSJan Kara 	copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
3296936ca80dSJan Kara 	__SetPageUptodate(vmf->cow_page);
3297ec47c3b9SKirill A. Shutemov 
32989118c0cbSJan Kara 	ret |= finish_fault(vmf);
3299936ca80dSJan Kara 	unlock_page(vmf->page);
3300936ca80dSJan Kara 	put_page(vmf->page);
33017267ec00SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
33027267ec00SKirill A. Shutemov 		goto uncharge_out;
3303ec47c3b9SKirill A. Shutemov 	return ret;
3304ec47c3b9SKirill A. Shutemov uncharge_out:
33053917048dSJan Kara 	mem_cgroup_cancel_charge(vmf->cow_page, vmf->memcg, false);
3306936ca80dSJan Kara 	put_page(vmf->cow_page);
3307ec47c3b9SKirill A. Shutemov 	return ret;
3308ec47c3b9SKirill A. Shutemov }
3309ec47c3b9SKirill A. Shutemov 
33100721ec8bSJan Kara static int do_shared_fault(struct vm_fault *vmf)
33111da177e4SLinus Torvalds {
331282b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
3313f0c6d4d2SKirill A. Shutemov 	int ret, tmp;
33141d65f86dSKAMEZAWA Hiroyuki 
3315936ca80dSJan Kara 	ret = __do_fault(vmf);
33167eae74afSKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3317f0c6d4d2SKirill A. Shutemov 		return ret;
33181da177e4SLinus Torvalds 
33191da177e4SLinus Torvalds 	/*
3320f0c6d4d2SKirill A. Shutemov 	 * Check if the backing address space wants to know that the page is
3321f0c6d4d2SKirill A. Shutemov 	 * about to become writable
33221da177e4SLinus Torvalds 	 */
3323fb09a464SKirill A. Shutemov 	if (vma->vm_ops->page_mkwrite) {
3324936ca80dSJan Kara 		unlock_page(vmf->page);
3325*38b8cb7fSJan Kara 		tmp = do_page_mkwrite(vmf);
3326fb09a464SKirill A. Shutemov 		if (unlikely(!tmp ||
3327fb09a464SKirill A. Shutemov 				(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3328936ca80dSJan Kara 			put_page(vmf->page);
3329f0c6d4d2SKirill A. Shutemov 			return tmp;
333069676147SMark Fasheh 		}
3331d0217ac0SNick Piggin 	}
3332fb09a464SKirill A. Shutemov 
33339118c0cbSJan Kara 	ret |= finish_fault(vmf);
33347267ec00SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
33357267ec00SKirill A. Shutemov 					VM_FAULT_RETRY))) {
3336936ca80dSJan Kara 		unlock_page(vmf->page);
3337936ca80dSJan Kara 		put_page(vmf->page);
3338f0c6d4d2SKirill A. Shutemov 		return ret;
33399637a5efSDavid Howells 	}
3340d00806b1SNick Piggin 
334197ba0c2bSJan Kara 	fault_dirty_shared_page(vma, vmf->page);
3342b827e496SNick Piggin 	return ret;
334354cb8821SNick Piggin }
3344d00806b1SNick Piggin 
33459a95f3cfSPaul Cassella /*
33469a95f3cfSPaul Cassella  * We enter with non-exclusive mmap_sem (to exclude vma changes,
33479a95f3cfSPaul Cassella  * but allow concurrent faults).
33489a95f3cfSPaul Cassella  * The mmap_sem may have been released depending on flags and our
33499a95f3cfSPaul Cassella  * return value.  See filemap_fault() and __lock_page_or_retry().
33509a95f3cfSPaul Cassella  */
335182b0f8c3SJan Kara static int do_fault(struct vm_fault *vmf)
335254cb8821SNick Piggin {
335382b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
335454cb8821SNick Piggin 
33556b7339f4SKirill A. Shutemov 	/* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
33566b7339f4SKirill A. Shutemov 	if (!vma->vm_ops->fault)
33576b7339f4SKirill A. Shutemov 		return VM_FAULT_SIGBUS;
335882b0f8c3SJan Kara 	if (!(vmf->flags & FAULT_FLAG_WRITE))
33590721ec8bSJan Kara 		return do_read_fault(vmf);
3360ec47c3b9SKirill A. Shutemov 	if (!(vma->vm_flags & VM_SHARED))
33610721ec8bSJan Kara 		return do_cow_fault(vmf);
33620721ec8bSJan Kara 	return do_shared_fault(vmf);
336354cb8821SNick Piggin }
336454cb8821SNick Piggin 
3365b19a9939SRashika Kheria static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
336604bb2f94SRik van Riel 				unsigned long addr, int page_nid,
336704bb2f94SRik van Riel 				int *flags)
33689532fec1SMel Gorman {
33699532fec1SMel Gorman 	get_page(page);
33709532fec1SMel Gorman 
33719532fec1SMel Gorman 	count_vm_numa_event(NUMA_HINT_FAULTS);
337204bb2f94SRik van Riel 	if (page_nid == numa_node_id()) {
33739532fec1SMel Gorman 		count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
337404bb2f94SRik van Riel 		*flags |= TNF_FAULT_LOCAL;
337504bb2f94SRik van Riel 	}
33769532fec1SMel Gorman 
33779532fec1SMel Gorman 	return mpol_misplaced(page, vma, addr);
33789532fec1SMel Gorman }
33799532fec1SMel Gorman 
33802994302bSJan Kara static int do_numa_page(struct vm_fault *vmf)
3381d10e63f2SMel Gorman {
338282b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
33834daae3b4SMel Gorman 	struct page *page = NULL;
33848191acbdSMel Gorman 	int page_nid = -1;
338590572890SPeter Zijlstra 	int last_cpupid;
3386cbee9f88SPeter Zijlstra 	int target_nid;
3387b8593bfdSMel Gorman 	bool migrated = false;
33882994302bSJan Kara 	pte_t pte = vmf->orig_pte;
3389b191f9b1SMel Gorman 	bool was_writable = pte_write(pte);
33906688cc05SPeter Zijlstra 	int flags = 0;
3391d10e63f2SMel Gorman 
3392d10e63f2SMel Gorman 	/*
3393d10e63f2SMel Gorman 	* The "pte" at this point cannot be used safely without
3394d10e63f2SMel Gorman 	* validation through pte_unmap_same(). It's of NUMA type but
3395d10e63f2SMel Gorman 	* the pfn may be screwed if the read is non atomic.
3396d10e63f2SMel Gorman 	*
33974d942466SMel Gorman 	* We can safely just do a "set_pte_at()", because the old
33984d942466SMel Gorman 	* page table entry is not accessible, so there would be no
33994d942466SMel Gorman 	* concurrent hardware modifications to the PTE.
3400d10e63f2SMel Gorman 	*/
340182b0f8c3SJan Kara 	vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
340282b0f8c3SJan Kara 	spin_lock(vmf->ptl);
340382b0f8c3SJan Kara 	if (unlikely(!pte_same(*vmf->pte, pte))) {
340482b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
34054daae3b4SMel Gorman 		goto out;
34064daae3b4SMel Gorman 	}
34074daae3b4SMel Gorman 
34084d942466SMel Gorman 	/* Make it present again */
34094d942466SMel Gorman 	pte = pte_modify(pte, vma->vm_page_prot);
34104d942466SMel Gorman 	pte = pte_mkyoung(pte);
3411b191f9b1SMel Gorman 	if (was_writable)
3412b191f9b1SMel Gorman 		pte = pte_mkwrite(pte);
341382b0f8c3SJan Kara 	set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
341482b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
3415d10e63f2SMel Gorman 
341682b0f8c3SJan Kara 	page = vm_normal_page(vma, vmf->address, pte);
3417d10e63f2SMel Gorman 	if (!page) {
341882b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3419d10e63f2SMel Gorman 		return 0;
3420d10e63f2SMel Gorman 	}
3421d10e63f2SMel Gorman 
3422e81c4802SKirill A. Shutemov 	/* TODO: handle PTE-mapped THP */
3423e81c4802SKirill A. Shutemov 	if (PageCompound(page)) {
342482b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3425e81c4802SKirill A. Shutemov 		return 0;
3426e81c4802SKirill A. Shutemov 	}
3427e81c4802SKirill A. Shutemov 
34286688cc05SPeter Zijlstra 	/*
3429bea66fbdSMel Gorman 	 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3430bea66fbdSMel Gorman 	 * much anyway since they can be in shared cache state. This misses
3431bea66fbdSMel Gorman 	 * the case where a mapping is writable but the process never writes
3432bea66fbdSMel Gorman 	 * to it but pte_write gets cleared during protection updates and
3433bea66fbdSMel Gorman 	 * pte_dirty has unpredictable behaviour between PTE scan updates,
3434bea66fbdSMel Gorman 	 * background writeback, dirty balancing and application behaviour.
34356688cc05SPeter Zijlstra 	 */
3436d59dc7bcSRik van Riel 	if (!pte_write(pte))
34376688cc05SPeter Zijlstra 		flags |= TNF_NO_GROUP;
34386688cc05SPeter Zijlstra 
3439dabe1d99SRik van Riel 	/*
3440dabe1d99SRik van Riel 	 * Flag if the page is shared between multiple address spaces. This
3441dabe1d99SRik van Riel 	 * is later used when determining whether to group tasks together
3442dabe1d99SRik van Riel 	 */
3443dabe1d99SRik van Riel 	if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3444dabe1d99SRik van Riel 		flags |= TNF_SHARED;
3445dabe1d99SRik van Riel 
344690572890SPeter Zijlstra 	last_cpupid = page_cpupid_last(page);
34478191acbdSMel Gorman 	page_nid = page_to_nid(page);
344882b0f8c3SJan Kara 	target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
3449bae473a4SKirill A. Shutemov 			&flags);
345082b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
34514daae3b4SMel Gorman 	if (target_nid == -1) {
34524daae3b4SMel Gorman 		put_page(page);
34534daae3b4SMel Gorman 		goto out;
34544daae3b4SMel Gorman 	}
34554daae3b4SMel Gorman 
34564daae3b4SMel Gorman 	/* Migrate to the requested node */
34571bc115d8SMel Gorman 	migrated = migrate_misplaced_page(page, vma, target_nid);
34586688cc05SPeter Zijlstra 	if (migrated) {
34598191acbdSMel Gorman 		page_nid = target_nid;
34606688cc05SPeter Zijlstra 		flags |= TNF_MIGRATED;
3461074c2381SMel Gorman 	} else
3462074c2381SMel Gorman 		flags |= TNF_MIGRATE_FAIL;
34634daae3b4SMel Gorman 
34644daae3b4SMel Gorman out:
34658191acbdSMel Gorman 	if (page_nid != -1)
34666688cc05SPeter Zijlstra 		task_numa_fault(last_cpupid, page_nid, 1, flags);
3467d10e63f2SMel Gorman 	return 0;
3468d10e63f2SMel Gorman }
3469d10e63f2SMel Gorman 
347082b0f8c3SJan Kara static int create_huge_pmd(struct vm_fault *vmf)
3471b96375f7SMatthew Wilcox {
347282b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
3473fb6dd5faSKirill A. Shutemov 	if (vma_is_anonymous(vma))
347482b0f8c3SJan Kara 		return do_huge_pmd_anonymous_page(vmf);
3475b96375f7SMatthew Wilcox 	if (vma->vm_ops->pmd_fault)
347682b0f8c3SJan Kara 		return vma->vm_ops->pmd_fault(vma, vmf->address, vmf->pmd,
347782b0f8c3SJan Kara 				vmf->flags);
3478b96375f7SMatthew Wilcox 	return VM_FAULT_FALLBACK;
3479b96375f7SMatthew Wilcox }
3480b96375f7SMatthew Wilcox 
348182b0f8c3SJan Kara static int wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
3482b96375f7SMatthew Wilcox {
348382b0f8c3SJan Kara 	if (vma_is_anonymous(vmf->vma))
348482b0f8c3SJan Kara 		return do_huge_pmd_wp_page(vmf, orig_pmd);
348582b0f8c3SJan Kara 	if (vmf->vma->vm_ops->pmd_fault)
348682b0f8c3SJan Kara 		return vmf->vma->vm_ops->pmd_fault(vmf->vma, vmf->address,
348782b0f8c3SJan Kara 						   vmf->pmd, vmf->flags);
3488af9e4d5fSKirill A. Shutemov 
3489af9e4d5fSKirill A. Shutemov 	/* COW handled on pte level: split pmd */
349082b0f8c3SJan Kara 	VM_BUG_ON_VMA(vmf->vma->vm_flags & VM_SHARED, vmf->vma);
349182b0f8c3SJan Kara 	__split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
3492af9e4d5fSKirill A. Shutemov 
3493b96375f7SMatthew Wilcox 	return VM_FAULT_FALLBACK;
3494b96375f7SMatthew Wilcox }
3495b96375f7SMatthew Wilcox 
349638e08854SLorenzo Stoakes static inline bool vma_is_accessible(struct vm_area_struct *vma)
349738e08854SLorenzo Stoakes {
349838e08854SLorenzo Stoakes 	return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
349938e08854SLorenzo Stoakes }
350038e08854SLorenzo Stoakes 
35011da177e4SLinus Torvalds /*
35021da177e4SLinus Torvalds  * These routines also need to handle stuff like marking pages dirty
35031da177e4SLinus Torvalds  * and/or accessed for architectures that don't do it in hardware (most
35041da177e4SLinus Torvalds  * RISC architectures).  The early dirtying is also good on the i386.
35051da177e4SLinus Torvalds  *
35061da177e4SLinus Torvalds  * There is also a hook called "update_mmu_cache()" that architectures
35071da177e4SLinus Torvalds  * with external mmu caches can use to update those (ie the Sparc or
35081da177e4SLinus Torvalds  * PowerPC hashed page tables that act as extended TLBs).
35091da177e4SLinus Torvalds  *
35107267ec00SKirill A. Shutemov  * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
35117267ec00SKirill A. Shutemov  * concurrent faults).
35129a95f3cfSPaul Cassella  *
35137267ec00SKirill A. Shutemov  * The mmap_sem may have been released depending on flags and our return value.
35147267ec00SKirill A. Shutemov  * See filemap_fault() and __lock_page_or_retry().
35151da177e4SLinus Torvalds  */
351682b0f8c3SJan Kara static int handle_pte_fault(struct vm_fault *vmf)
35171da177e4SLinus Torvalds {
35181da177e4SLinus Torvalds 	pte_t entry;
35191da177e4SLinus Torvalds 
352082b0f8c3SJan Kara 	if (unlikely(pmd_none(*vmf->pmd))) {
35217267ec00SKirill A. Shutemov 		/*
35227267ec00SKirill A. Shutemov 		 * Leave __pte_alloc() until later: because vm_ops->fault may
35237267ec00SKirill A. Shutemov 		 * want to allocate huge page, and if we expose page table
35247267ec00SKirill A. Shutemov 		 * for an instant, it will be difficult to retract from
35257267ec00SKirill A. Shutemov 		 * concurrent faults and from rmap lookups.
35267267ec00SKirill A. Shutemov 		 */
352782b0f8c3SJan Kara 		vmf->pte = NULL;
35287267ec00SKirill A. Shutemov 	} else {
35297267ec00SKirill A. Shutemov 		/* See comment in pte_alloc_one_map() */
353082b0f8c3SJan Kara 		if (pmd_trans_unstable(vmf->pmd) || pmd_devmap(*vmf->pmd))
35317267ec00SKirill A. Shutemov 			return 0;
35327267ec00SKirill A. Shutemov 		/*
35337267ec00SKirill A. Shutemov 		 * A regular pmd is established and it can't morph into a huge
35347267ec00SKirill A. Shutemov 		 * pmd from under us anymore at this point because we hold the
35357267ec00SKirill A. Shutemov 		 * mmap_sem read mode and khugepaged takes it in write mode.
35367267ec00SKirill A. Shutemov 		 * So now it's safe to run pte_offset_map().
35377267ec00SKirill A. Shutemov 		 */
353882b0f8c3SJan Kara 		vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
35392994302bSJan Kara 		vmf->orig_pte = *vmf->pte;
35407267ec00SKirill A. Shutemov 
3541e37c6982SChristian Borntraeger 		/*
3542e37c6982SChristian Borntraeger 		 * some architectures can have larger ptes than wordsize,
35437267ec00SKirill A. Shutemov 		 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
35447267ec00SKirill A. Shutemov 		 * CONFIG_32BIT=y, so READ_ONCE or ACCESS_ONCE cannot guarantee
35457267ec00SKirill A. Shutemov 		 * atomic accesses.  The code below just needs a consistent
35467267ec00SKirill A. Shutemov 		 * view for the ifs and we later double check anyway with the
35477267ec00SKirill A. Shutemov 		 * ptl lock held. So here a barrier will do.
3548e37c6982SChristian Borntraeger 		 */
3549e37c6982SChristian Borntraeger 		barrier();
35502994302bSJan Kara 		if (pte_none(vmf->orig_pte)) {
355182b0f8c3SJan Kara 			pte_unmap(vmf->pte);
355282b0f8c3SJan Kara 			vmf->pte = NULL;
35537267ec00SKirill A. Shutemov 		}
35547267ec00SKirill A. Shutemov 	}
35557267ec00SKirill A. Shutemov 
355682b0f8c3SJan Kara 	if (!vmf->pte) {
355782b0f8c3SJan Kara 		if (vma_is_anonymous(vmf->vma))
355882b0f8c3SJan Kara 			return do_anonymous_page(vmf);
3559b5330628SOleg Nesterov 		else
356082b0f8c3SJan Kara 			return do_fault(vmf);
356165500d23SHugh Dickins 	}
35627267ec00SKirill A. Shutemov 
35632994302bSJan Kara 	if (!pte_present(vmf->orig_pte))
35642994302bSJan Kara 		return do_swap_page(vmf);
35651da177e4SLinus Torvalds 
35662994302bSJan Kara 	if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
35672994302bSJan Kara 		return do_numa_page(vmf);
3568d10e63f2SMel Gorman 
356982b0f8c3SJan Kara 	vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
357082b0f8c3SJan Kara 	spin_lock(vmf->ptl);
35712994302bSJan Kara 	entry = vmf->orig_pte;
357282b0f8c3SJan Kara 	if (unlikely(!pte_same(*vmf->pte, entry)))
35738f4e2101SHugh Dickins 		goto unlock;
357482b0f8c3SJan Kara 	if (vmf->flags & FAULT_FLAG_WRITE) {
35751da177e4SLinus Torvalds 		if (!pte_write(entry))
35762994302bSJan Kara 			return do_wp_page(vmf);
35771da177e4SLinus Torvalds 		entry = pte_mkdirty(entry);
35781da177e4SLinus Torvalds 	}
35791da177e4SLinus Torvalds 	entry = pte_mkyoung(entry);
358082b0f8c3SJan Kara 	if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
358182b0f8c3SJan Kara 				vmf->flags & FAULT_FLAG_WRITE)) {
358282b0f8c3SJan Kara 		update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
35831a44e149SAndrea Arcangeli 	} else {
35841a44e149SAndrea Arcangeli 		/*
35851a44e149SAndrea Arcangeli 		 * This is needed only for protection faults but the arch code
35861a44e149SAndrea Arcangeli 		 * is not yet telling us if this is a protection fault or not.
35871a44e149SAndrea Arcangeli 		 * This still avoids useless tlb flushes for .text page faults
35881a44e149SAndrea Arcangeli 		 * with threads.
35891a44e149SAndrea Arcangeli 		 */
359082b0f8c3SJan Kara 		if (vmf->flags & FAULT_FLAG_WRITE)
359182b0f8c3SJan Kara 			flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
35921a44e149SAndrea Arcangeli 	}
35938f4e2101SHugh Dickins unlock:
359482b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
359583c54070SNick Piggin 	return 0;
35961da177e4SLinus Torvalds }
35971da177e4SLinus Torvalds 
35981da177e4SLinus Torvalds /*
35991da177e4SLinus Torvalds  * By the time we get here, we already hold the mm semaphore
36009a95f3cfSPaul Cassella  *
36019a95f3cfSPaul Cassella  * The mmap_sem may have been released depending on flags and our
36029a95f3cfSPaul Cassella  * return value.  See filemap_fault() and __lock_page_or_retry().
36031da177e4SLinus Torvalds  */
3604dcddffd4SKirill A. Shutemov static int __handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
3605dcddffd4SKirill A. Shutemov 		unsigned int flags)
36061da177e4SLinus Torvalds {
360782b0f8c3SJan Kara 	struct vm_fault vmf = {
3608bae473a4SKirill A. Shutemov 		.vma = vma,
36091a29d85eSJan Kara 		.address = address & PAGE_MASK,
3610bae473a4SKirill A. Shutemov 		.flags = flags,
36110721ec8bSJan Kara 		.pgoff = linear_page_index(vma, address),
3612667240e0SJan Kara 		.gfp_mask = __get_fault_gfp_mask(vma),
3613bae473a4SKirill A. Shutemov 	};
3614dcddffd4SKirill A. Shutemov 	struct mm_struct *mm = vma->vm_mm;
36151da177e4SLinus Torvalds 	pgd_t *pgd;
36161da177e4SLinus Torvalds 	pud_t *pud;
36171da177e4SLinus Torvalds 
36181da177e4SLinus Torvalds 	pgd = pgd_offset(mm, address);
36191da177e4SLinus Torvalds 	pud = pud_alloc(mm, pgd, address);
36201da177e4SLinus Torvalds 	if (!pud)
3621c74df32cSHugh Dickins 		return VM_FAULT_OOM;
362282b0f8c3SJan Kara 	vmf.pmd = pmd_alloc(mm, pud, address);
362382b0f8c3SJan Kara 	if (!vmf.pmd)
3624c74df32cSHugh Dickins 		return VM_FAULT_OOM;
362582b0f8c3SJan Kara 	if (pmd_none(*vmf.pmd) && transparent_hugepage_enabled(vma)) {
362682b0f8c3SJan Kara 		int ret = create_huge_pmd(&vmf);
3627c0292554SKirill A. Shutemov 		if (!(ret & VM_FAULT_FALLBACK))
3628c0292554SKirill A. Shutemov 			return ret;
362971e3aac0SAndrea Arcangeli 	} else {
363082b0f8c3SJan Kara 		pmd_t orig_pmd = *vmf.pmd;
36311f1d06c3SDavid Rientjes 		int ret;
36321f1d06c3SDavid Rientjes 
363371e3aac0SAndrea Arcangeli 		barrier();
36345c7fb56eSDan Williams 		if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
363538e08854SLorenzo Stoakes 			if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
363682b0f8c3SJan Kara 				return do_huge_pmd_numa_page(&vmf, orig_pmd);
3637d10e63f2SMel Gorman 
363882b0f8c3SJan Kara 			if ((vmf.flags & FAULT_FLAG_WRITE) &&
3639bae473a4SKirill A. Shutemov 					!pmd_write(orig_pmd)) {
364082b0f8c3SJan Kara 				ret = wp_huge_pmd(&vmf, orig_pmd);
36419845cbbdSKirill A. Shutemov 				if (!(ret & VM_FAULT_FALLBACK))
36421f1d06c3SDavid Rientjes 					return ret;
3643a1dd450bSWill Deacon 			} else {
364482b0f8c3SJan Kara 				huge_pmd_set_accessed(&vmf, orig_pmd);
364571e3aac0SAndrea Arcangeli 				return 0;
364671e3aac0SAndrea Arcangeli 			}
364771e3aac0SAndrea Arcangeli 		}
36489845cbbdSKirill A. Shutemov 	}
364971e3aac0SAndrea Arcangeli 
365082b0f8c3SJan Kara 	return handle_pte_fault(&vmf);
36511da177e4SLinus Torvalds }
36521da177e4SLinus Torvalds 
36539a95f3cfSPaul Cassella /*
36549a95f3cfSPaul Cassella  * By the time we get here, we already hold the mm semaphore
36559a95f3cfSPaul Cassella  *
36569a95f3cfSPaul Cassella  * The mmap_sem may have been released depending on flags and our
36579a95f3cfSPaul Cassella  * return value.  See filemap_fault() and __lock_page_or_retry().
36589a95f3cfSPaul Cassella  */
3659dcddffd4SKirill A. Shutemov int handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
3660dcddffd4SKirill A. Shutemov 		unsigned int flags)
3661519e5247SJohannes Weiner {
3662519e5247SJohannes Weiner 	int ret;
3663519e5247SJohannes Weiner 
3664519e5247SJohannes Weiner 	__set_current_state(TASK_RUNNING);
3665519e5247SJohannes Weiner 
3666519e5247SJohannes Weiner 	count_vm_event(PGFAULT);
3667dcddffd4SKirill A. Shutemov 	mem_cgroup_count_vm_event(vma->vm_mm, PGFAULT);
3668519e5247SJohannes Weiner 
3669519e5247SJohannes Weiner 	/* do counter updates before entering really critical section. */
3670519e5247SJohannes Weiner 	check_sync_rss_stat(current);
3671519e5247SJohannes Weiner 
3672519e5247SJohannes Weiner 	/*
3673519e5247SJohannes Weiner 	 * Enable the memcg OOM handling for faults triggered in user
3674519e5247SJohannes Weiner 	 * space.  Kernel faults are handled more gracefully.
3675519e5247SJohannes Weiner 	 */
3676519e5247SJohannes Weiner 	if (flags & FAULT_FLAG_USER)
367749426420SJohannes Weiner 		mem_cgroup_oom_enable();
3678519e5247SJohannes Weiner 
3679bae473a4SKirill A. Shutemov 	if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
3680bae473a4SKirill A. Shutemov 					    flags & FAULT_FLAG_INSTRUCTION,
3681bae473a4SKirill A. Shutemov 					    flags & FAULT_FLAG_REMOTE))
3682bae473a4SKirill A. Shutemov 		return VM_FAULT_SIGSEGV;
3683bae473a4SKirill A. Shutemov 
3684bae473a4SKirill A. Shutemov 	if (unlikely(is_vm_hugetlb_page(vma)))
3685bae473a4SKirill A. Shutemov 		ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
3686bae473a4SKirill A. Shutemov 	else
3687dcddffd4SKirill A. Shutemov 		ret = __handle_mm_fault(vma, address, flags);
3688519e5247SJohannes Weiner 
368949426420SJohannes Weiner 	if (flags & FAULT_FLAG_USER) {
369049426420SJohannes Weiner 		mem_cgroup_oom_disable();
369149426420SJohannes Weiner                 /*
369249426420SJohannes Weiner                  * The task may have entered a memcg OOM situation but
369349426420SJohannes Weiner                  * if the allocation error was handled gracefully (no
369449426420SJohannes Weiner                  * VM_FAULT_OOM), there is no need to kill anything.
369549426420SJohannes Weiner                  * Just clean up the OOM state peacefully.
369649426420SJohannes Weiner                  */
369749426420SJohannes Weiner                 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
369849426420SJohannes Weiner                         mem_cgroup_oom_synchronize(false);
369949426420SJohannes Weiner 	}
37003812c8c8SJohannes Weiner 
37013f70dc38SMichal Hocko 	/*
37023f70dc38SMichal Hocko 	 * This mm has been already reaped by the oom reaper and so the
37033f70dc38SMichal Hocko 	 * refault cannot be trusted in general. Anonymous refaults would
37043f70dc38SMichal Hocko 	 * lose data and give a zero page instead e.g. This is especially
37053f70dc38SMichal Hocko 	 * problem for use_mm() because regular tasks will just die and
37063f70dc38SMichal Hocko 	 * the corrupted data will not be visible anywhere while kthread
37073f70dc38SMichal Hocko 	 * will outlive the oom victim and potentially propagate the date
37083f70dc38SMichal Hocko 	 * further.
37093f70dc38SMichal Hocko 	 */
37103f70dc38SMichal Hocko 	if (unlikely((current->flags & PF_KTHREAD) && !(ret & VM_FAULT_ERROR)
37113f70dc38SMichal Hocko 				&& test_bit(MMF_UNSTABLE, &vma->vm_mm->flags)))
37123f70dc38SMichal Hocko 		ret = VM_FAULT_SIGBUS;
37133f70dc38SMichal Hocko 
3714519e5247SJohannes Weiner 	return ret;
3715519e5247SJohannes Weiner }
3716e1d6d01aSJesse Barnes EXPORT_SYMBOL_GPL(handle_mm_fault);
3717519e5247SJohannes Weiner 
37181da177e4SLinus Torvalds #ifndef __PAGETABLE_PUD_FOLDED
37191da177e4SLinus Torvalds /*
37201da177e4SLinus Torvalds  * Allocate page upper directory.
3721872fec16SHugh Dickins  * We've already handled the fast-path in-line.
37221da177e4SLinus Torvalds  */
37231bb3630eSHugh Dickins int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
37241da177e4SLinus Torvalds {
3725c74df32cSHugh Dickins 	pud_t *new = pud_alloc_one(mm, address);
3726c74df32cSHugh Dickins 	if (!new)
37271bb3630eSHugh Dickins 		return -ENOMEM;
37281da177e4SLinus Torvalds 
3729362a61adSNick Piggin 	smp_wmb(); /* See comment in __pte_alloc */
3730362a61adSNick Piggin 
3731872fec16SHugh Dickins 	spin_lock(&mm->page_table_lock);
37321bb3630eSHugh Dickins 	if (pgd_present(*pgd))		/* Another has populated it */
37335e541973SBenjamin Herrenschmidt 		pud_free(mm, new);
37341bb3630eSHugh Dickins 	else
37351da177e4SLinus Torvalds 		pgd_populate(mm, pgd, new);
3736872fec16SHugh Dickins 	spin_unlock(&mm->page_table_lock);
37371bb3630eSHugh Dickins 	return 0;
37381da177e4SLinus Torvalds }
37391da177e4SLinus Torvalds #endif /* __PAGETABLE_PUD_FOLDED */
37401da177e4SLinus Torvalds 
37411da177e4SLinus Torvalds #ifndef __PAGETABLE_PMD_FOLDED
37421da177e4SLinus Torvalds /*
37431da177e4SLinus Torvalds  * Allocate page middle directory.
3744872fec16SHugh Dickins  * We've already handled the fast-path in-line.
37451da177e4SLinus Torvalds  */
37461bb3630eSHugh Dickins int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
37471da177e4SLinus Torvalds {
3748c74df32cSHugh Dickins 	pmd_t *new = pmd_alloc_one(mm, address);
3749c74df32cSHugh Dickins 	if (!new)
37501bb3630eSHugh Dickins 		return -ENOMEM;
37511da177e4SLinus Torvalds 
3752362a61adSNick Piggin 	smp_wmb(); /* See comment in __pte_alloc */
3753362a61adSNick Piggin 
3754872fec16SHugh Dickins 	spin_lock(&mm->page_table_lock);
37551da177e4SLinus Torvalds #ifndef __ARCH_HAS_4LEVEL_HACK
3756dc6c9a35SKirill A. Shutemov 	if (!pud_present(*pud)) {
3757dc6c9a35SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
37581da177e4SLinus Torvalds 		pud_populate(mm, pud, new);
3759dc6c9a35SKirill A. Shutemov 	} else	/* Another has populated it */
37605e541973SBenjamin Herrenschmidt 		pmd_free(mm, new);
3761dc6c9a35SKirill A. Shutemov #else
3762dc6c9a35SKirill A. Shutemov 	if (!pgd_present(*pud)) {
3763dc6c9a35SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
37641da177e4SLinus Torvalds 		pgd_populate(mm, pud, new);
3765dc6c9a35SKirill A. Shutemov 	} else /* Another has populated it */
3766dc6c9a35SKirill A. Shutemov 		pmd_free(mm, new);
37671da177e4SLinus Torvalds #endif /* __ARCH_HAS_4LEVEL_HACK */
3768872fec16SHugh Dickins 	spin_unlock(&mm->page_table_lock);
37691bb3630eSHugh Dickins 	return 0;
37701da177e4SLinus Torvalds }
37711da177e4SLinus Torvalds #endif /* __PAGETABLE_PMD_FOLDED */
37721da177e4SLinus Torvalds 
37731b36ba81SNamhyung Kim static int __follow_pte(struct mm_struct *mm, unsigned long address,
3774f8ad0f49SJohannes Weiner 		pte_t **ptepp, spinlock_t **ptlp)
3775f8ad0f49SJohannes Weiner {
3776f8ad0f49SJohannes Weiner 	pgd_t *pgd;
3777f8ad0f49SJohannes Weiner 	pud_t *pud;
3778f8ad0f49SJohannes Weiner 	pmd_t *pmd;
3779f8ad0f49SJohannes Weiner 	pte_t *ptep;
3780f8ad0f49SJohannes Weiner 
3781f8ad0f49SJohannes Weiner 	pgd = pgd_offset(mm, address);
3782f8ad0f49SJohannes Weiner 	if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
3783f8ad0f49SJohannes Weiner 		goto out;
3784f8ad0f49SJohannes Weiner 
3785f8ad0f49SJohannes Weiner 	pud = pud_offset(pgd, address);
3786f8ad0f49SJohannes Weiner 	if (pud_none(*pud) || unlikely(pud_bad(*pud)))
3787f8ad0f49SJohannes Weiner 		goto out;
3788f8ad0f49SJohannes Weiner 
3789f8ad0f49SJohannes Weiner 	pmd = pmd_offset(pud, address);
3790f66055abSAndrea Arcangeli 	VM_BUG_ON(pmd_trans_huge(*pmd));
3791f8ad0f49SJohannes Weiner 	if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
3792f8ad0f49SJohannes Weiner 		goto out;
3793f8ad0f49SJohannes Weiner 
3794f8ad0f49SJohannes Weiner 	/* We cannot handle huge page PFN maps. Luckily they don't exist. */
3795f8ad0f49SJohannes Weiner 	if (pmd_huge(*pmd))
3796f8ad0f49SJohannes Weiner 		goto out;
3797f8ad0f49SJohannes Weiner 
3798f8ad0f49SJohannes Weiner 	ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
3799f8ad0f49SJohannes Weiner 	if (!ptep)
3800f8ad0f49SJohannes Weiner 		goto out;
3801f8ad0f49SJohannes Weiner 	if (!pte_present(*ptep))
3802f8ad0f49SJohannes Weiner 		goto unlock;
3803f8ad0f49SJohannes Weiner 	*ptepp = ptep;
3804f8ad0f49SJohannes Weiner 	return 0;
3805f8ad0f49SJohannes Weiner unlock:
3806f8ad0f49SJohannes Weiner 	pte_unmap_unlock(ptep, *ptlp);
3807f8ad0f49SJohannes Weiner out:
3808f8ad0f49SJohannes Weiner 	return -EINVAL;
3809f8ad0f49SJohannes Weiner }
3810f8ad0f49SJohannes Weiner 
38111b36ba81SNamhyung Kim static inline int follow_pte(struct mm_struct *mm, unsigned long address,
38121b36ba81SNamhyung Kim 			     pte_t **ptepp, spinlock_t **ptlp)
38131b36ba81SNamhyung Kim {
38141b36ba81SNamhyung Kim 	int res;
38151b36ba81SNamhyung Kim 
38161b36ba81SNamhyung Kim 	/* (void) is needed to make gcc happy */
38171b36ba81SNamhyung Kim 	(void) __cond_lock(*ptlp,
38181b36ba81SNamhyung Kim 			   !(res = __follow_pte(mm, address, ptepp, ptlp)));
38191b36ba81SNamhyung Kim 	return res;
38201b36ba81SNamhyung Kim }
38211b36ba81SNamhyung Kim 
38223b6748e2SJohannes Weiner /**
38233b6748e2SJohannes Weiner  * follow_pfn - look up PFN at a user virtual address
38243b6748e2SJohannes Weiner  * @vma: memory mapping
38253b6748e2SJohannes Weiner  * @address: user virtual address
38263b6748e2SJohannes Weiner  * @pfn: location to store found PFN
38273b6748e2SJohannes Weiner  *
38283b6748e2SJohannes Weiner  * Only IO mappings and raw PFN mappings are allowed.
38293b6748e2SJohannes Weiner  *
38303b6748e2SJohannes Weiner  * Returns zero and the pfn at @pfn on success, -ve otherwise.
38313b6748e2SJohannes Weiner  */
38323b6748e2SJohannes Weiner int follow_pfn(struct vm_area_struct *vma, unsigned long address,
38333b6748e2SJohannes Weiner 	unsigned long *pfn)
38343b6748e2SJohannes Weiner {
38353b6748e2SJohannes Weiner 	int ret = -EINVAL;
38363b6748e2SJohannes Weiner 	spinlock_t *ptl;
38373b6748e2SJohannes Weiner 	pte_t *ptep;
38383b6748e2SJohannes Weiner 
38393b6748e2SJohannes Weiner 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
38403b6748e2SJohannes Weiner 		return ret;
38413b6748e2SJohannes Weiner 
38423b6748e2SJohannes Weiner 	ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
38433b6748e2SJohannes Weiner 	if (ret)
38443b6748e2SJohannes Weiner 		return ret;
38453b6748e2SJohannes Weiner 	*pfn = pte_pfn(*ptep);
38463b6748e2SJohannes Weiner 	pte_unmap_unlock(ptep, ptl);
38473b6748e2SJohannes Weiner 	return 0;
38483b6748e2SJohannes Weiner }
38493b6748e2SJohannes Weiner EXPORT_SYMBOL(follow_pfn);
38503b6748e2SJohannes Weiner 
385128b2ee20SRik van Riel #ifdef CONFIG_HAVE_IOREMAP_PROT
3852d87fe660Svenkatesh.pallipadi@intel.com int follow_phys(struct vm_area_struct *vma,
385328b2ee20SRik van Riel 		unsigned long address, unsigned int flags,
3854d87fe660Svenkatesh.pallipadi@intel.com 		unsigned long *prot, resource_size_t *phys)
385528b2ee20SRik van Riel {
385603668a4dSJohannes Weiner 	int ret = -EINVAL;
385728b2ee20SRik van Riel 	pte_t *ptep, pte;
385828b2ee20SRik van Riel 	spinlock_t *ptl;
385928b2ee20SRik van Riel 
3860d87fe660Svenkatesh.pallipadi@intel.com 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
3861d87fe660Svenkatesh.pallipadi@intel.com 		goto out;
386228b2ee20SRik van Riel 
386303668a4dSJohannes Weiner 	if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
3864d87fe660Svenkatesh.pallipadi@intel.com 		goto out;
386528b2ee20SRik van Riel 	pte = *ptep;
386603668a4dSJohannes Weiner 
386728b2ee20SRik van Riel 	if ((flags & FOLL_WRITE) && !pte_write(pte))
386828b2ee20SRik van Riel 		goto unlock;
386928b2ee20SRik van Riel 
387028b2ee20SRik van Riel 	*prot = pgprot_val(pte_pgprot(pte));
387103668a4dSJohannes Weiner 	*phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
387228b2ee20SRik van Riel 
387303668a4dSJohannes Weiner 	ret = 0;
387428b2ee20SRik van Riel unlock:
387528b2ee20SRik van Riel 	pte_unmap_unlock(ptep, ptl);
387628b2ee20SRik van Riel out:
3877d87fe660Svenkatesh.pallipadi@intel.com 	return ret;
387828b2ee20SRik van Riel }
387928b2ee20SRik van Riel 
388028b2ee20SRik van Riel int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
388128b2ee20SRik van Riel 			void *buf, int len, int write)
388228b2ee20SRik van Riel {
388328b2ee20SRik van Riel 	resource_size_t phys_addr;
388428b2ee20SRik van Riel 	unsigned long prot = 0;
38852bc7273bSKOSAKI Motohiro 	void __iomem *maddr;
388628b2ee20SRik van Riel 	int offset = addr & (PAGE_SIZE-1);
388728b2ee20SRik van Riel 
3888d87fe660Svenkatesh.pallipadi@intel.com 	if (follow_phys(vma, addr, write, &prot, &phys_addr))
388928b2ee20SRik van Riel 		return -EINVAL;
389028b2ee20SRik van Riel 
38919cb12d7bSGrazvydas Ignotas 	maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
389228b2ee20SRik van Riel 	if (write)
389328b2ee20SRik van Riel 		memcpy_toio(maddr + offset, buf, len);
389428b2ee20SRik van Riel 	else
389528b2ee20SRik van Riel 		memcpy_fromio(buf, maddr + offset, len);
389628b2ee20SRik van Riel 	iounmap(maddr);
389728b2ee20SRik van Riel 
389828b2ee20SRik van Riel 	return len;
389928b2ee20SRik van Riel }
39005a73633eSUwe Kleine-König EXPORT_SYMBOL_GPL(generic_access_phys);
390128b2ee20SRik van Riel #endif
390228b2ee20SRik van Riel 
39030ec76a11SDavid Howells /*
3904206cb636SStephen Wilson  * Access another process' address space as given in mm.  If non-NULL, use the
3905206cb636SStephen Wilson  * given task for page fault accounting.
39060ec76a11SDavid Howells  */
3907206cb636SStephen Wilson static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
3908442486ecSLorenzo Stoakes 		unsigned long addr, void *buf, int len, unsigned int gup_flags)
39090ec76a11SDavid Howells {
39100ec76a11SDavid Howells 	struct vm_area_struct *vma;
39110ec76a11SDavid Howells 	void *old_buf = buf;
3912442486ecSLorenzo Stoakes 	int write = gup_flags & FOLL_WRITE;
39130ec76a11SDavid Howells 
39140ec76a11SDavid Howells 	down_read(&mm->mmap_sem);
3915183ff22bSSimon Arlott 	/* ignore errors, just check how much was successfully transferred */
39160ec76a11SDavid Howells 	while (len) {
39170ec76a11SDavid Howells 		int bytes, ret, offset;
39180ec76a11SDavid Howells 		void *maddr;
391928b2ee20SRik van Riel 		struct page *page = NULL;
39200ec76a11SDavid Howells 
39211e987790SDave Hansen 		ret = get_user_pages_remote(tsk, mm, addr, 1,
39225b56d49fSLorenzo Stoakes 				gup_flags, &page, &vma, NULL);
392328b2ee20SRik van Riel 		if (ret <= 0) {
3924dbffcd03SRik van Riel #ifndef CONFIG_HAVE_IOREMAP_PROT
3925dbffcd03SRik van Riel 			break;
3926dbffcd03SRik van Riel #else
392728b2ee20SRik van Riel 			/*
392828b2ee20SRik van Riel 			 * Check if this is a VM_IO | VM_PFNMAP VMA, which
392928b2ee20SRik van Riel 			 * we can access using slightly different code.
393028b2ee20SRik van Riel 			 */
393128b2ee20SRik van Riel 			vma = find_vma(mm, addr);
3932fe936dfcSMichael Ellerman 			if (!vma || vma->vm_start > addr)
39330ec76a11SDavid Howells 				break;
393428b2ee20SRik van Riel 			if (vma->vm_ops && vma->vm_ops->access)
393528b2ee20SRik van Riel 				ret = vma->vm_ops->access(vma, addr, buf,
393628b2ee20SRik van Riel 							  len, write);
393728b2ee20SRik van Riel 			if (ret <= 0)
393828b2ee20SRik van Riel 				break;
393928b2ee20SRik van Riel 			bytes = ret;
3940dbffcd03SRik van Riel #endif
394128b2ee20SRik van Riel 		} else {
39420ec76a11SDavid Howells 			bytes = len;
39430ec76a11SDavid Howells 			offset = addr & (PAGE_SIZE-1);
39440ec76a11SDavid Howells 			if (bytes > PAGE_SIZE-offset)
39450ec76a11SDavid Howells 				bytes = PAGE_SIZE-offset;
39460ec76a11SDavid Howells 
39470ec76a11SDavid Howells 			maddr = kmap(page);
39480ec76a11SDavid Howells 			if (write) {
39490ec76a11SDavid Howells 				copy_to_user_page(vma, page, addr,
39500ec76a11SDavid Howells 						  maddr + offset, buf, bytes);
39510ec76a11SDavid Howells 				set_page_dirty_lock(page);
39520ec76a11SDavid Howells 			} else {
39530ec76a11SDavid Howells 				copy_from_user_page(vma, page, addr,
39540ec76a11SDavid Howells 						    buf, maddr + offset, bytes);
39550ec76a11SDavid Howells 			}
39560ec76a11SDavid Howells 			kunmap(page);
395709cbfeafSKirill A. Shutemov 			put_page(page);
395828b2ee20SRik van Riel 		}
39590ec76a11SDavid Howells 		len -= bytes;
39600ec76a11SDavid Howells 		buf += bytes;
39610ec76a11SDavid Howells 		addr += bytes;
39620ec76a11SDavid Howells 	}
39630ec76a11SDavid Howells 	up_read(&mm->mmap_sem);
39640ec76a11SDavid Howells 
39650ec76a11SDavid Howells 	return buf - old_buf;
39660ec76a11SDavid Howells }
396703252919SAndi Kleen 
39685ddd36b9SStephen Wilson /**
3969ae91dbfcSRandy Dunlap  * access_remote_vm - access another process' address space
39705ddd36b9SStephen Wilson  * @mm:		the mm_struct of the target address space
39715ddd36b9SStephen Wilson  * @addr:	start address to access
39725ddd36b9SStephen Wilson  * @buf:	source or destination buffer
39735ddd36b9SStephen Wilson  * @len:	number of bytes to transfer
39746347e8d5SLorenzo Stoakes  * @gup_flags:	flags modifying lookup behaviour
39755ddd36b9SStephen Wilson  *
39765ddd36b9SStephen Wilson  * The caller must hold a reference on @mm.
39775ddd36b9SStephen Wilson  */
39785ddd36b9SStephen Wilson int access_remote_vm(struct mm_struct *mm, unsigned long addr,
39796347e8d5SLorenzo Stoakes 		void *buf, int len, unsigned int gup_flags)
39805ddd36b9SStephen Wilson {
39816347e8d5SLorenzo Stoakes 	return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
39825ddd36b9SStephen Wilson }
39835ddd36b9SStephen Wilson 
398403252919SAndi Kleen /*
3985206cb636SStephen Wilson  * Access another process' address space.
3986206cb636SStephen Wilson  * Source/target buffer must be kernel space,
3987206cb636SStephen Wilson  * Do not walk the page table directly, use get_user_pages
3988206cb636SStephen Wilson  */
3989206cb636SStephen Wilson int access_process_vm(struct task_struct *tsk, unsigned long addr,
3990f307ab6dSLorenzo Stoakes 		void *buf, int len, unsigned int gup_flags)
3991206cb636SStephen Wilson {
3992206cb636SStephen Wilson 	struct mm_struct *mm;
3993206cb636SStephen Wilson 	int ret;
3994206cb636SStephen Wilson 
3995206cb636SStephen Wilson 	mm = get_task_mm(tsk);
3996206cb636SStephen Wilson 	if (!mm)
3997206cb636SStephen Wilson 		return 0;
3998206cb636SStephen Wilson 
3999f307ab6dSLorenzo Stoakes 	ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
4000442486ecSLorenzo Stoakes 
4001206cb636SStephen Wilson 	mmput(mm);
4002206cb636SStephen Wilson 
4003206cb636SStephen Wilson 	return ret;
4004206cb636SStephen Wilson }
4005fcd35857SCatalin Marinas EXPORT_SYMBOL_GPL(access_process_vm);
4006206cb636SStephen Wilson 
400703252919SAndi Kleen /*
400803252919SAndi Kleen  * Print the name of a VMA.
400903252919SAndi Kleen  */
401003252919SAndi Kleen void print_vma_addr(char *prefix, unsigned long ip)
401103252919SAndi Kleen {
401203252919SAndi Kleen 	struct mm_struct *mm = current->mm;
401303252919SAndi Kleen 	struct vm_area_struct *vma;
401403252919SAndi Kleen 
4015e8bff74aSIngo Molnar 	/*
4016e8bff74aSIngo Molnar 	 * Do not print if we are in atomic
4017e8bff74aSIngo Molnar 	 * contexts (in exception stacks, etc.):
4018e8bff74aSIngo Molnar 	 */
4019e8bff74aSIngo Molnar 	if (preempt_count())
4020e8bff74aSIngo Molnar 		return;
4021e8bff74aSIngo Molnar 
402203252919SAndi Kleen 	down_read(&mm->mmap_sem);
402303252919SAndi Kleen 	vma = find_vma(mm, ip);
402403252919SAndi Kleen 	if (vma && vma->vm_file) {
402503252919SAndi Kleen 		struct file *f = vma->vm_file;
402603252919SAndi Kleen 		char *buf = (char *)__get_free_page(GFP_KERNEL);
402703252919SAndi Kleen 		if (buf) {
40282fbc57c5SAndy Shevchenko 			char *p;
402903252919SAndi Kleen 
40309bf39ab2SMiklos Szeredi 			p = file_path(f, buf, PAGE_SIZE);
403103252919SAndi Kleen 			if (IS_ERR(p))
403203252919SAndi Kleen 				p = "?";
40332fbc57c5SAndy Shevchenko 			printk("%s%s[%lx+%lx]", prefix, kbasename(p),
403403252919SAndi Kleen 					vma->vm_start,
403503252919SAndi Kleen 					vma->vm_end - vma->vm_start);
403603252919SAndi Kleen 			free_page((unsigned long)buf);
403703252919SAndi Kleen 		}
403803252919SAndi Kleen 	}
403951a07e50SJeff Liu 	up_read(&mm->mmap_sem);
404003252919SAndi Kleen }
40413ee1afa3SNick Piggin 
4042662bbcb2SMichael S. Tsirkin #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
40439ec23531SDavid Hildenbrand void __might_fault(const char *file, int line)
40443ee1afa3SNick Piggin {
404595156f00SPeter Zijlstra 	/*
404695156f00SPeter Zijlstra 	 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
404795156f00SPeter Zijlstra 	 * holding the mmap_sem, this is safe because kernel memory doesn't
404895156f00SPeter Zijlstra 	 * get paged out, therefore we'll never actually fault, and the
404995156f00SPeter Zijlstra 	 * below annotations will generate false positives.
405095156f00SPeter Zijlstra 	 */
405195156f00SPeter Zijlstra 	if (segment_eq(get_fs(), KERNEL_DS))
405295156f00SPeter Zijlstra 		return;
40539ec23531SDavid Hildenbrand 	if (pagefault_disabled())
4054662bbcb2SMichael S. Tsirkin 		return;
40559ec23531SDavid Hildenbrand 	__might_sleep(file, line, 0);
40569ec23531SDavid Hildenbrand #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4057662bbcb2SMichael S. Tsirkin 	if (current->mm)
40583ee1afa3SNick Piggin 		might_lock_read(&current->mm->mmap_sem);
40599ec23531SDavid Hildenbrand #endif
40603ee1afa3SNick Piggin }
40619ec23531SDavid Hildenbrand EXPORT_SYMBOL(__might_fault);
40623ee1afa3SNick Piggin #endif
406347ad8475SAndrea Arcangeli 
406447ad8475SAndrea Arcangeli #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
406547ad8475SAndrea Arcangeli static void clear_gigantic_page(struct page *page,
406647ad8475SAndrea Arcangeli 				unsigned long addr,
406747ad8475SAndrea Arcangeli 				unsigned int pages_per_huge_page)
406847ad8475SAndrea Arcangeli {
406947ad8475SAndrea Arcangeli 	int i;
407047ad8475SAndrea Arcangeli 	struct page *p = page;
407147ad8475SAndrea Arcangeli 
407247ad8475SAndrea Arcangeli 	might_sleep();
407347ad8475SAndrea Arcangeli 	for (i = 0; i < pages_per_huge_page;
407447ad8475SAndrea Arcangeli 	     i++, p = mem_map_next(p, page, i)) {
407547ad8475SAndrea Arcangeli 		cond_resched();
407647ad8475SAndrea Arcangeli 		clear_user_highpage(p, addr + i * PAGE_SIZE);
407747ad8475SAndrea Arcangeli 	}
407847ad8475SAndrea Arcangeli }
407947ad8475SAndrea Arcangeli void clear_huge_page(struct page *page,
408047ad8475SAndrea Arcangeli 		     unsigned long addr, unsigned int pages_per_huge_page)
408147ad8475SAndrea Arcangeli {
408247ad8475SAndrea Arcangeli 	int i;
408347ad8475SAndrea Arcangeli 
408447ad8475SAndrea Arcangeli 	if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
408547ad8475SAndrea Arcangeli 		clear_gigantic_page(page, addr, pages_per_huge_page);
408647ad8475SAndrea Arcangeli 		return;
408747ad8475SAndrea Arcangeli 	}
408847ad8475SAndrea Arcangeli 
408947ad8475SAndrea Arcangeli 	might_sleep();
409047ad8475SAndrea Arcangeli 	for (i = 0; i < pages_per_huge_page; i++) {
409147ad8475SAndrea Arcangeli 		cond_resched();
409247ad8475SAndrea Arcangeli 		clear_user_highpage(page + i, addr + i * PAGE_SIZE);
409347ad8475SAndrea Arcangeli 	}
409447ad8475SAndrea Arcangeli }
409547ad8475SAndrea Arcangeli 
409647ad8475SAndrea Arcangeli static void copy_user_gigantic_page(struct page *dst, struct page *src,
409747ad8475SAndrea Arcangeli 				    unsigned long addr,
409847ad8475SAndrea Arcangeli 				    struct vm_area_struct *vma,
409947ad8475SAndrea Arcangeli 				    unsigned int pages_per_huge_page)
410047ad8475SAndrea Arcangeli {
410147ad8475SAndrea Arcangeli 	int i;
410247ad8475SAndrea Arcangeli 	struct page *dst_base = dst;
410347ad8475SAndrea Arcangeli 	struct page *src_base = src;
410447ad8475SAndrea Arcangeli 
410547ad8475SAndrea Arcangeli 	for (i = 0; i < pages_per_huge_page; ) {
410647ad8475SAndrea Arcangeli 		cond_resched();
410747ad8475SAndrea Arcangeli 		copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
410847ad8475SAndrea Arcangeli 
410947ad8475SAndrea Arcangeli 		i++;
411047ad8475SAndrea Arcangeli 		dst = mem_map_next(dst, dst_base, i);
411147ad8475SAndrea Arcangeli 		src = mem_map_next(src, src_base, i);
411247ad8475SAndrea Arcangeli 	}
411347ad8475SAndrea Arcangeli }
411447ad8475SAndrea Arcangeli 
411547ad8475SAndrea Arcangeli void copy_user_huge_page(struct page *dst, struct page *src,
411647ad8475SAndrea Arcangeli 			 unsigned long addr, struct vm_area_struct *vma,
411747ad8475SAndrea Arcangeli 			 unsigned int pages_per_huge_page)
411847ad8475SAndrea Arcangeli {
411947ad8475SAndrea Arcangeli 	int i;
412047ad8475SAndrea Arcangeli 
412147ad8475SAndrea Arcangeli 	if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
412247ad8475SAndrea Arcangeli 		copy_user_gigantic_page(dst, src, addr, vma,
412347ad8475SAndrea Arcangeli 					pages_per_huge_page);
412447ad8475SAndrea Arcangeli 		return;
412547ad8475SAndrea Arcangeli 	}
412647ad8475SAndrea Arcangeli 
412747ad8475SAndrea Arcangeli 	might_sleep();
412847ad8475SAndrea Arcangeli 	for (i = 0; i < pages_per_huge_page; i++) {
412947ad8475SAndrea Arcangeli 		cond_resched();
413047ad8475SAndrea Arcangeli 		copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
413147ad8475SAndrea Arcangeli 	}
413247ad8475SAndrea Arcangeli }
413347ad8475SAndrea Arcangeli #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
413449076ec2SKirill A. Shutemov 
413540b64acdSOlof Johansson #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4136b35f1819SKirill A. Shutemov 
4137b35f1819SKirill A. Shutemov static struct kmem_cache *page_ptl_cachep;
4138b35f1819SKirill A. Shutemov 
4139b35f1819SKirill A. Shutemov void __init ptlock_cache_init(void)
4140b35f1819SKirill A. Shutemov {
4141b35f1819SKirill A. Shutemov 	page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4142b35f1819SKirill A. Shutemov 			SLAB_PANIC, NULL);
4143b35f1819SKirill A. Shutemov }
4144b35f1819SKirill A. Shutemov 
4145539edb58SPeter Zijlstra bool ptlock_alloc(struct page *page)
414649076ec2SKirill A. Shutemov {
414749076ec2SKirill A. Shutemov 	spinlock_t *ptl;
414849076ec2SKirill A. Shutemov 
4149b35f1819SKirill A. Shutemov 	ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
415049076ec2SKirill A. Shutemov 	if (!ptl)
415149076ec2SKirill A. Shutemov 		return false;
4152539edb58SPeter Zijlstra 	page->ptl = ptl;
415349076ec2SKirill A. Shutemov 	return true;
415449076ec2SKirill A. Shutemov }
415549076ec2SKirill A. Shutemov 
4156539edb58SPeter Zijlstra void ptlock_free(struct page *page)
415749076ec2SKirill A. Shutemov {
4158b35f1819SKirill A. Shutemov 	kmem_cache_free(page_ptl_cachep, page->ptl);
415949076ec2SKirill A. Shutemov }
416049076ec2SKirill A. Shutemov #endif
4161