xref: /linux/mm/memory.c (revision 977fbdcd5986c9ff700bf276644d2b1973a53348)
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>
436e84f315SIngo Molnar #include <linux/sched/mm.h>
44f7ccbae4SIngo Molnar #include <linux/sched/coredump.h>
456a3827d7SIngo Molnar #include <linux/sched/numa_balancing.h>
4629930025SIngo Molnar #include <linux/sched/task.h>
471da177e4SLinus Torvalds #include <linux/hugetlb.h>
481da177e4SLinus Torvalds #include <linux/mman.h>
491da177e4SLinus Torvalds #include <linux/swap.h>
501da177e4SLinus Torvalds #include <linux/highmem.h>
511da177e4SLinus Torvalds #include <linux/pagemap.h>
525042db43SJérôme Glisse #include <linux/memremap.h>
539a840895SHugh Dickins #include <linux/ksm.h>
541da177e4SLinus Torvalds #include <linux/rmap.h>
55b95f1b31SPaul Gortmaker #include <linux/export.h>
560ff92245SShailabh Nagar #include <linux/delayacct.h>
571da177e4SLinus Torvalds #include <linux/init.h>
5801c8f1c4SDan Williams #include <linux/pfn_t.h>
59edc79b2aSPeter Zijlstra #include <linux/writeback.h>
608a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
61cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
623dc14741SHugh Dickins #include <linux/kallsyms.h>
633dc14741SHugh Dickins #include <linux/swapops.h>
643dc14741SHugh Dickins #include <linux/elf.h>
655a0e3ad6STejun Heo #include <linux/gfp.h>
664daae3b4SMel Gorman #include <linux/migrate.h>
672fbc57c5SAndy Shevchenko #include <linux/string.h>
680abdd7a8SDan Williams #include <linux/dma-debug.h>
691592eef0SKirill A. Shutemov #include <linux/debugfs.h>
706b251fc9SAndrea Arcangeli #include <linux/userfaultfd_k.h>
71bc2466e4SJan Kara #include <linux/dax.h>
726b31d595SMichal Hocko #include <linux/oom.h>
731da177e4SLinus Torvalds 
746952b61dSAlexey Dobriyan #include <asm/io.h>
7533a709b2SDave Hansen #include <asm/mmu_context.h>
761da177e4SLinus Torvalds #include <asm/pgalloc.h>
777c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
781da177e4SLinus Torvalds #include <asm/tlb.h>
791da177e4SLinus Torvalds #include <asm/tlbflush.h>
801da177e4SLinus Torvalds #include <asm/pgtable.h>
811da177e4SLinus Torvalds 
8242b77728SJan Beulich #include "internal.h"
8342b77728SJan Beulich 
8490572890SPeter Zijlstra #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
8590572890SPeter Zijlstra #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
8675980e97SPeter Zijlstra #endif
8775980e97SPeter Zijlstra 
88d41dee36SAndy Whitcroft #ifndef CONFIG_NEED_MULTIPLE_NODES
891da177e4SLinus Torvalds /* use the per-pgdat data instead for discontigmem - mbligh */
901da177e4SLinus Torvalds unsigned long max_mapnr;
911da177e4SLinus Torvalds EXPORT_SYMBOL(max_mapnr);
92166f61b9STobin C Harding 
93166f61b9STobin C Harding struct page *mem_map;
941da177e4SLinus Torvalds EXPORT_SYMBOL(mem_map);
951da177e4SLinus Torvalds #endif
961da177e4SLinus Torvalds 
971da177e4SLinus Torvalds /*
981da177e4SLinus Torvalds  * A number of key systems in x86 including ioremap() rely on the assumption
991da177e4SLinus Torvalds  * that high_memory defines the upper bound on direct map memory, then end
1001da177e4SLinus Torvalds  * of ZONE_NORMAL.  Under CONFIG_DISCONTIG this means that max_low_pfn and
1011da177e4SLinus Torvalds  * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
1021da177e4SLinus Torvalds  * and ZONE_HIGHMEM.
1031da177e4SLinus Torvalds  */
1041da177e4SLinus Torvalds void *high_memory;
1051da177e4SLinus Torvalds EXPORT_SYMBOL(high_memory);
1061da177e4SLinus Torvalds 
10732a93233SIngo Molnar /*
10832a93233SIngo Molnar  * Randomize the address space (stacks, mmaps, brk, etc.).
10932a93233SIngo Molnar  *
11032a93233SIngo Molnar  * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
11132a93233SIngo Molnar  *   as ancient (libc5 based) binaries can segfault. )
11232a93233SIngo Molnar  */
11332a93233SIngo Molnar int randomize_va_space __read_mostly =
11432a93233SIngo Molnar #ifdef CONFIG_COMPAT_BRK
11532a93233SIngo Molnar 					1;
11632a93233SIngo Molnar #else
11732a93233SIngo Molnar 					2;
11832a93233SIngo Molnar #endif
119a62eaf15SAndi Kleen 
120a62eaf15SAndi Kleen static int __init disable_randmaps(char *s)
121a62eaf15SAndi Kleen {
122a62eaf15SAndi Kleen 	randomize_va_space = 0;
1239b41046cSOGAWA Hirofumi 	return 1;
124a62eaf15SAndi Kleen }
125a62eaf15SAndi Kleen __setup("norandmaps", disable_randmaps);
126a62eaf15SAndi Kleen 
12762eede62SHugh Dickins unsigned long zero_pfn __read_mostly;
1280b70068eSArd Biesheuvel EXPORT_SYMBOL(zero_pfn);
1290b70068eSArd Biesheuvel 
130166f61b9STobin C Harding unsigned long highest_memmap_pfn __read_mostly;
131166f61b9STobin C Harding 
132a13ea5b7SHugh Dickins /*
133a13ea5b7SHugh Dickins  * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
134a13ea5b7SHugh Dickins  */
135a13ea5b7SHugh Dickins static int __init init_zero_pfn(void)
136a13ea5b7SHugh Dickins {
137a13ea5b7SHugh Dickins 	zero_pfn = page_to_pfn(ZERO_PAGE(0));
138a13ea5b7SHugh Dickins 	return 0;
139a13ea5b7SHugh Dickins }
140a13ea5b7SHugh Dickins core_initcall(init_zero_pfn);
141a62eaf15SAndi Kleen 
142d559db08SKAMEZAWA Hiroyuki 
14334e55232SKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
14434e55232SKAMEZAWA Hiroyuki 
145ea48cf78SDavid Rientjes void sync_mm_rss(struct mm_struct *mm)
14634e55232SKAMEZAWA Hiroyuki {
14734e55232SKAMEZAWA Hiroyuki 	int i;
14834e55232SKAMEZAWA Hiroyuki 
14934e55232SKAMEZAWA Hiroyuki 	for (i = 0; i < NR_MM_COUNTERS; i++) {
15005af2e10SDavid Rientjes 		if (current->rss_stat.count[i]) {
15105af2e10SDavid Rientjes 			add_mm_counter(mm, i, current->rss_stat.count[i]);
15205af2e10SDavid Rientjes 			current->rss_stat.count[i] = 0;
15334e55232SKAMEZAWA Hiroyuki 		}
15434e55232SKAMEZAWA Hiroyuki 	}
15505af2e10SDavid Rientjes 	current->rss_stat.events = 0;
15634e55232SKAMEZAWA Hiroyuki }
15734e55232SKAMEZAWA Hiroyuki 
15834e55232SKAMEZAWA Hiroyuki static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
15934e55232SKAMEZAWA Hiroyuki {
16034e55232SKAMEZAWA Hiroyuki 	struct task_struct *task = current;
16134e55232SKAMEZAWA Hiroyuki 
16234e55232SKAMEZAWA Hiroyuki 	if (likely(task->mm == mm))
16334e55232SKAMEZAWA Hiroyuki 		task->rss_stat.count[member] += val;
16434e55232SKAMEZAWA Hiroyuki 	else
16534e55232SKAMEZAWA Hiroyuki 		add_mm_counter(mm, member, val);
16634e55232SKAMEZAWA Hiroyuki }
16734e55232SKAMEZAWA Hiroyuki #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
16834e55232SKAMEZAWA Hiroyuki #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
16934e55232SKAMEZAWA Hiroyuki 
17034e55232SKAMEZAWA Hiroyuki /* sync counter once per 64 page faults */
17134e55232SKAMEZAWA Hiroyuki #define TASK_RSS_EVENTS_THRESH	(64)
17234e55232SKAMEZAWA Hiroyuki static void check_sync_rss_stat(struct task_struct *task)
17334e55232SKAMEZAWA Hiroyuki {
17434e55232SKAMEZAWA Hiroyuki 	if (unlikely(task != current))
17534e55232SKAMEZAWA Hiroyuki 		return;
17634e55232SKAMEZAWA Hiroyuki 	if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
177ea48cf78SDavid Rientjes 		sync_mm_rss(task->mm);
17834e55232SKAMEZAWA Hiroyuki }
1799547d01bSPeter Zijlstra #else /* SPLIT_RSS_COUNTING */
18034e55232SKAMEZAWA Hiroyuki 
18134e55232SKAMEZAWA Hiroyuki #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
18234e55232SKAMEZAWA Hiroyuki #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
18334e55232SKAMEZAWA Hiroyuki 
18434e55232SKAMEZAWA Hiroyuki static void check_sync_rss_stat(struct task_struct *task)
18534e55232SKAMEZAWA Hiroyuki {
18634e55232SKAMEZAWA Hiroyuki }
18734e55232SKAMEZAWA Hiroyuki 
1889547d01bSPeter Zijlstra #endif /* SPLIT_RSS_COUNTING */
1899547d01bSPeter Zijlstra 
1909547d01bSPeter Zijlstra #ifdef HAVE_GENERIC_MMU_GATHER
1919547d01bSPeter Zijlstra 
192ca1d6c7dSNicholas Krause static bool tlb_next_batch(struct mmu_gather *tlb)
1939547d01bSPeter Zijlstra {
1949547d01bSPeter Zijlstra 	struct mmu_gather_batch *batch;
1959547d01bSPeter Zijlstra 
1969547d01bSPeter Zijlstra 	batch = tlb->active;
1979547d01bSPeter Zijlstra 	if (batch->next) {
1989547d01bSPeter Zijlstra 		tlb->active = batch->next;
199ca1d6c7dSNicholas Krause 		return true;
2009547d01bSPeter Zijlstra 	}
2019547d01bSPeter Zijlstra 
20253a59fc6SMichal Hocko 	if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
203ca1d6c7dSNicholas Krause 		return false;
20453a59fc6SMichal Hocko 
2059547d01bSPeter Zijlstra 	batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
2069547d01bSPeter Zijlstra 	if (!batch)
207ca1d6c7dSNicholas Krause 		return false;
2089547d01bSPeter Zijlstra 
20953a59fc6SMichal Hocko 	tlb->batch_count++;
2109547d01bSPeter Zijlstra 	batch->next = NULL;
2119547d01bSPeter Zijlstra 	batch->nr   = 0;
2129547d01bSPeter Zijlstra 	batch->max  = MAX_GATHER_BATCH;
2139547d01bSPeter Zijlstra 
2149547d01bSPeter Zijlstra 	tlb->active->next = batch;
2159547d01bSPeter Zijlstra 	tlb->active = batch;
2169547d01bSPeter Zijlstra 
217ca1d6c7dSNicholas Krause 	return true;
2189547d01bSPeter Zijlstra }
2199547d01bSPeter Zijlstra 
22056236a59SMinchan Kim void arch_tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm,
22156236a59SMinchan Kim 				unsigned long start, unsigned long end)
2229547d01bSPeter Zijlstra {
2239547d01bSPeter Zijlstra 	tlb->mm = mm;
2249547d01bSPeter Zijlstra 
2252b047252SLinus Torvalds 	/* Is it from 0 to ~0? */
2262b047252SLinus Torvalds 	tlb->fullmm     = !(start | (end+1));
2271de14c3cSDave Hansen 	tlb->need_flush_all = 0;
2289547d01bSPeter Zijlstra 	tlb->local.next = NULL;
2299547d01bSPeter Zijlstra 	tlb->local.nr   = 0;
2309547d01bSPeter Zijlstra 	tlb->local.max  = ARRAY_SIZE(tlb->__pages);
2319547d01bSPeter Zijlstra 	tlb->active     = &tlb->local;
23253a59fc6SMichal Hocko 	tlb->batch_count = 0;
2339547d01bSPeter Zijlstra 
2349547d01bSPeter Zijlstra #ifdef CONFIG_HAVE_RCU_TABLE_FREE
2359547d01bSPeter Zijlstra 	tlb->batch = NULL;
23634e55232SKAMEZAWA Hiroyuki #endif
237e77b0852SAneesh Kumar K.V 	tlb->page_size = 0;
238fb7332a9SWill Deacon 
239fb7332a9SWill Deacon 	__tlb_reset_range(tlb);
2409547d01bSPeter Zijlstra }
2419547d01bSPeter Zijlstra 
2421cf35d47SLinus Torvalds static void tlb_flush_mmu_tlbonly(struct mmu_gather *tlb)
2439547d01bSPeter Zijlstra {
244721c21c1SWill Deacon 	if (!tlb->end)
245721c21c1SWill Deacon 		return;
246721c21c1SWill Deacon 
2479547d01bSPeter Zijlstra 	tlb_flush(tlb);
24834ee645eSJoerg Roedel 	mmu_notifier_invalidate_range(tlb->mm, tlb->start, tlb->end);
2499547d01bSPeter Zijlstra #ifdef CONFIG_HAVE_RCU_TABLE_FREE
2509547d01bSPeter Zijlstra 	tlb_table_flush(tlb);
2519547d01bSPeter Zijlstra #endif
252fb7332a9SWill Deacon 	__tlb_reset_range(tlb);
2531cf35d47SLinus Torvalds }
2541cf35d47SLinus Torvalds 
2551cf35d47SLinus Torvalds static void tlb_flush_mmu_free(struct mmu_gather *tlb)
2561cf35d47SLinus Torvalds {
2571cf35d47SLinus Torvalds 	struct mmu_gather_batch *batch;
2589547d01bSPeter Zijlstra 
259721c21c1SWill Deacon 	for (batch = &tlb->local; batch && batch->nr; batch = batch->next) {
2609547d01bSPeter Zijlstra 		free_pages_and_swap_cache(batch->pages, batch->nr);
2619547d01bSPeter Zijlstra 		batch->nr = 0;
2629547d01bSPeter Zijlstra 	}
2639547d01bSPeter Zijlstra 	tlb->active = &tlb->local;
2649547d01bSPeter Zijlstra }
2659547d01bSPeter Zijlstra 
2661cf35d47SLinus Torvalds void tlb_flush_mmu(struct mmu_gather *tlb)
2671cf35d47SLinus Torvalds {
2681cf35d47SLinus Torvalds 	tlb_flush_mmu_tlbonly(tlb);
2691cf35d47SLinus Torvalds 	tlb_flush_mmu_free(tlb);
2701cf35d47SLinus Torvalds }
2711cf35d47SLinus Torvalds 
2729547d01bSPeter Zijlstra /* tlb_finish_mmu
2739547d01bSPeter Zijlstra  *	Called at the end of the shootdown operation to free up any resources
2749547d01bSPeter Zijlstra  *	that were required.
2759547d01bSPeter Zijlstra  */
27656236a59SMinchan Kim void arch_tlb_finish_mmu(struct mmu_gather *tlb,
27799baac21SMinchan Kim 		unsigned long start, unsigned long end, bool force)
2789547d01bSPeter Zijlstra {
2799547d01bSPeter Zijlstra 	struct mmu_gather_batch *batch, *next;
2809547d01bSPeter Zijlstra 
28199baac21SMinchan Kim 	if (force)
28299baac21SMinchan Kim 		__tlb_adjust_range(tlb, start, end - start);
28399baac21SMinchan Kim 
2849547d01bSPeter Zijlstra 	tlb_flush_mmu(tlb);
2859547d01bSPeter Zijlstra 
2869547d01bSPeter Zijlstra 	/* keep the page table cache within bounds */
2879547d01bSPeter Zijlstra 	check_pgt_cache();
2889547d01bSPeter Zijlstra 
2899547d01bSPeter Zijlstra 	for (batch = tlb->local.next; batch; batch = next) {
2909547d01bSPeter Zijlstra 		next = batch->next;
2919547d01bSPeter Zijlstra 		free_pages((unsigned long)batch, 0);
2929547d01bSPeter Zijlstra 	}
2939547d01bSPeter Zijlstra 	tlb->local.next = NULL;
2949547d01bSPeter Zijlstra }
2959547d01bSPeter Zijlstra 
2969547d01bSPeter Zijlstra /* __tlb_remove_page
2979547d01bSPeter Zijlstra  *	Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while
2989547d01bSPeter Zijlstra  *	handling the additional races in SMP caused by other CPUs caching valid
2999547d01bSPeter Zijlstra  *	mappings in their TLBs. Returns the number of free page slots left.
3009547d01bSPeter Zijlstra  *	When out of page slots we must call tlb_flush_mmu().
301e9d55e15SAneesh Kumar K.V  *returns true if the caller should flush.
3029547d01bSPeter Zijlstra  */
303e77b0852SAneesh Kumar K.V bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size)
3049547d01bSPeter Zijlstra {
3059547d01bSPeter Zijlstra 	struct mmu_gather_batch *batch;
3069547d01bSPeter Zijlstra 
307fb7332a9SWill Deacon 	VM_BUG_ON(!tlb->end);
308692a68c1SAneesh Kumar K.V 	VM_WARN_ON(tlb->page_size != page_size);
309e77b0852SAneesh Kumar K.V 
3109547d01bSPeter Zijlstra 	batch = tlb->active;
311692a68c1SAneesh Kumar K.V 	/*
312692a68c1SAneesh Kumar K.V 	 * Add the page and check if we are full. If so
313692a68c1SAneesh Kumar K.V 	 * force a flush.
314692a68c1SAneesh Kumar K.V 	 */
315692a68c1SAneesh Kumar K.V 	batch->pages[batch->nr++] = page;
3169547d01bSPeter Zijlstra 	if (batch->nr == batch->max) {
3179547d01bSPeter Zijlstra 		if (!tlb_next_batch(tlb))
318e9d55e15SAneesh Kumar K.V 			return true;
3190b43c3aaSShaohua Li 		batch = tlb->active;
3209547d01bSPeter Zijlstra 	}
321309381feSSasha Levin 	VM_BUG_ON_PAGE(batch->nr > batch->max, page);
3229547d01bSPeter Zijlstra 
323e9d55e15SAneesh Kumar K.V 	return false;
3249547d01bSPeter Zijlstra }
3259547d01bSPeter Zijlstra 
3269547d01bSPeter Zijlstra #endif /* HAVE_GENERIC_MMU_GATHER */
32734e55232SKAMEZAWA Hiroyuki 
32826723911SPeter Zijlstra #ifdef CONFIG_HAVE_RCU_TABLE_FREE
32926723911SPeter Zijlstra 
33026723911SPeter Zijlstra /*
33126723911SPeter Zijlstra  * See the comment near struct mmu_table_batch.
33226723911SPeter Zijlstra  */
33326723911SPeter Zijlstra 
33426723911SPeter Zijlstra static void tlb_remove_table_smp_sync(void *arg)
33526723911SPeter Zijlstra {
33626723911SPeter Zijlstra 	/* Simply deliver the interrupt */
33726723911SPeter Zijlstra }
33826723911SPeter Zijlstra 
33926723911SPeter Zijlstra static void tlb_remove_table_one(void *table)
34026723911SPeter Zijlstra {
34126723911SPeter Zijlstra 	/*
34226723911SPeter Zijlstra 	 * This isn't an RCU grace period and hence the page-tables cannot be
34326723911SPeter Zijlstra 	 * assumed to be actually RCU-freed.
34426723911SPeter Zijlstra 	 *
34526723911SPeter Zijlstra 	 * It is however sufficient for software page-table walkers that rely on
34626723911SPeter Zijlstra 	 * IRQ disabling. See the comment near struct mmu_table_batch.
34726723911SPeter Zijlstra 	 */
34826723911SPeter Zijlstra 	smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
34926723911SPeter Zijlstra 	__tlb_remove_table(table);
35026723911SPeter Zijlstra }
35126723911SPeter Zijlstra 
35226723911SPeter Zijlstra static void tlb_remove_table_rcu(struct rcu_head *head)
35326723911SPeter Zijlstra {
35426723911SPeter Zijlstra 	struct mmu_table_batch *batch;
35526723911SPeter Zijlstra 	int i;
35626723911SPeter Zijlstra 
35726723911SPeter Zijlstra 	batch = container_of(head, struct mmu_table_batch, rcu);
35826723911SPeter Zijlstra 
35926723911SPeter Zijlstra 	for (i = 0; i < batch->nr; i++)
36026723911SPeter Zijlstra 		__tlb_remove_table(batch->tables[i]);
36126723911SPeter Zijlstra 
36226723911SPeter Zijlstra 	free_page((unsigned long)batch);
36326723911SPeter Zijlstra }
36426723911SPeter Zijlstra 
36526723911SPeter Zijlstra void tlb_table_flush(struct mmu_gather *tlb)
36626723911SPeter Zijlstra {
36726723911SPeter Zijlstra 	struct mmu_table_batch **batch = &tlb->batch;
36826723911SPeter Zijlstra 
36926723911SPeter Zijlstra 	if (*batch) {
37026723911SPeter Zijlstra 		call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
37126723911SPeter Zijlstra 		*batch = NULL;
37226723911SPeter Zijlstra 	}
37326723911SPeter Zijlstra }
37426723911SPeter Zijlstra 
37526723911SPeter Zijlstra void tlb_remove_table(struct mmu_gather *tlb, void *table)
37626723911SPeter Zijlstra {
37726723911SPeter Zijlstra 	struct mmu_table_batch **batch = &tlb->batch;
37826723911SPeter Zijlstra 
37926723911SPeter Zijlstra 	/*
38026723911SPeter Zijlstra 	 * When there's less then two users of this mm there cannot be a
38126723911SPeter Zijlstra 	 * concurrent page-table walk.
38226723911SPeter Zijlstra 	 */
38326723911SPeter Zijlstra 	if (atomic_read(&tlb->mm->mm_users) < 2) {
38426723911SPeter Zijlstra 		__tlb_remove_table(table);
38526723911SPeter Zijlstra 		return;
38626723911SPeter Zijlstra 	}
38726723911SPeter Zijlstra 
38826723911SPeter Zijlstra 	if (*batch == NULL) {
38926723911SPeter Zijlstra 		*batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
39026723911SPeter Zijlstra 		if (*batch == NULL) {
39126723911SPeter Zijlstra 			tlb_remove_table_one(table);
39226723911SPeter Zijlstra 			return;
39326723911SPeter Zijlstra 		}
39426723911SPeter Zijlstra 		(*batch)->nr = 0;
39526723911SPeter Zijlstra 	}
39626723911SPeter Zijlstra 	(*batch)->tables[(*batch)->nr++] = table;
39726723911SPeter Zijlstra 	if ((*batch)->nr == MAX_TABLE_BATCH)
39826723911SPeter Zijlstra 		tlb_table_flush(tlb);
39926723911SPeter Zijlstra }
40026723911SPeter Zijlstra 
4019547d01bSPeter Zijlstra #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
40226723911SPeter Zijlstra 
403ef549e13SMike Rapoport /**
404ef549e13SMike Rapoport  * tlb_gather_mmu - initialize an mmu_gather structure for page-table tear-down
405ef549e13SMike Rapoport  * @tlb: the mmu_gather structure to initialize
406ef549e13SMike Rapoport  * @mm: the mm_struct of the target address space
407ef549e13SMike Rapoport  * @start: start of the region that will be removed from the page-table
408ef549e13SMike Rapoport  * @end: end of the region that will be removed from the page-table
409ef549e13SMike Rapoport  *
41056236a59SMinchan Kim  * Called to initialize an (on-stack) mmu_gather structure for page-table
411ef549e13SMike Rapoport  * tear-down from @mm. The @start and @end are set to 0 and -1
412ef549e13SMike Rapoport  * respectively when @mm is without users and we're going to destroy
413ef549e13SMike Rapoport  * the full address space (exit/execve).
41456236a59SMinchan Kim  */
41556236a59SMinchan Kim void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm,
41656236a59SMinchan Kim 			unsigned long start, unsigned long end)
41756236a59SMinchan Kim {
41856236a59SMinchan Kim 	arch_tlb_gather_mmu(tlb, mm, start, end);
41999baac21SMinchan Kim 	inc_tlb_flush_pending(tlb->mm);
42056236a59SMinchan Kim }
42156236a59SMinchan Kim 
42256236a59SMinchan Kim void tlb_finish_mmu(struct mmu_gather *tlb,
42356236a59SMinchan Kim 		unsigned long start, unsigned long end)
42456236a59SMinchan Kim {
42599baac21SMinchan Kim 	/*
42699baac21SMinchan Kim 	 * If there are parallel threads are doing PTE changes on same range
42799baac21SMinchan Kim 	 * under non-exclusive lock(e.g., mmap_sem read-side) but defer TLB
42899baac21SMinchan Kim 	 * flush by batching, a thread has stable TLB entry can fail to flush
42999baac21SMinchan Kim 	 * the TLB by observing pte_none|!pte_dirty, for example so flush TLB
43099baac21SMinchan Kim 	 * forcefully if we detect parallel PTE batching threads.
43199baac21SMinchan Kim 	 */
43299baac21SMinchan Kim 	bool force = mm_tlb_flush_nested(tlb->mm);
43399baac21SMinchan Kim 
43499baac21SMinchan Kim 	arch_tlb_finish_mmu(tlb, start, end, force);
43599baac21SMinchan Kim 	dec_tlb_flush_pending(tlb->mm);
43656236a59SMinchan Kim }
43756236a59SMinchan Kim 
4381da177e4SLinus Torvalds /*
4391da177e4SLinus Torvalds  * Note: this doesn't free the actual pages themselves. That
4401da177e4SLinus Torvalds  * has been handled earlier when unmapping all the memory regions.
4411da177e4SLinus Torvalds  */
4429e1b32caSBenjamin Herrenschmidt static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
4439e1b32caSBenjamin Herrenschmidt 			   unsigned long addr)
4441da177e4SLinus Torvalds {
4452f569afdSMartin Schwidefsky 	pgtable_t token = pmd_pgtable(*pmd);
4461da177e4SLinus Torvalds 	pmd_clear(pmd);
4479e1b32caSBenjamin Herrenschmidt 	pte_free_tlb(tlb, token, addr);
448c4812909SKirill A. Shutemov 	mm_dec_nr_ptes(tlb->mm);
4491da177e4SLinus Torvalds }
4501da177e4SLinus Torvalds 
451e0da382cSHugh Dickins static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
452e0da382cSHugh Dickins 				unsigned long addr, unsigned long end,
453e0da382cSHugh Dickins 				unsigned long floor, unsigned long ceiling)
4541da177e4SLinus Torvalds {
4551da177e4SLinus Torvalds 	pmd_t *pmd;
4561da177e4SLinus Torvalds 	unsigned long next;
457e0da382cSHugh Dickins 	unsigned long start;
4581da177e4SLinus Torvalds 
459e0da382cSHugh Dickins 	start = addr;
4601da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
4611da177e4SLinus Torvalds 	do {
4621da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
4631da177e4SLinus Torvalds 		if (pmd_none_or_clear_bad(pmd))
4641da177e4SLinus Torvalds 			continue;
4659e1b32caSBenjamin Herrenschmidt 		free_pte_range(tlb, pmd, addr);
4661da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
4671da177e4SLinus Torvalds 
468e0da382cSHugh Dickins 	start &= PUD_MASK;
469e0da382cSHugh Dickins 	if (start < floor)
470e0da382cSHugh Dickins 		return;
471e0da382cSHugh Dickins 	if (ceiling) {
472e0da382cSHugh Dickins 		ceiling &= PUD_MASK;
473e0da382cSHugh Dickins 		if (!ceiling)
474e0da382cSHugh Dickins 			return;
4751da177e4SLinus Torvalds 	}
476e0da382cSHugh Dickins 	if (end - 1 > ceiling - 1)
477e0da382cSHugh Dickins 		return;
478e0da382cSHugh Dickins 
479e0da382cSHugh Dickins 	pmd = pmd_offset(pud, start);
480e0da382cSHugh Dickins 	pud_clear(pud);
4819e1b32caSBenjamin Herrenschmidt 	pmd_free_tlb(tlb, pmd, start);
482dc6c9a35SKirill A. Shutemov 	mm_dec_nr_pmds(tlb->mm);
4831da177e4SLinus Torvalds }
4841da177e4SLinus Torvalds 
485c2febafcSKirill A. Shutemov static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
486e0da382cSHugh Dickins 				unsigned long addr, unsigned long end,
487e0da382cSHugh Dickins 				unsigned long floor, unsigned long ceiling)
4881da177e4SLinus Torvalds {
4891da177e4SLinus Torvalds 	pud_t *pud;
4901da177e4SLinus Torvalds 	unsigned long next;
491e0da382cSHugh Dickins 	unsigned long start;
4921da177e4SLinus Torvalds 
493e0da382cSHugh Dickins 	start = addr;
494c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
4951da177e4SLinus Torvalds 	do {
4961da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
4971da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
4981da177e4SLinus Torvalds 			continue;
499e0da382cSHugh Dickins 		free_pmd_range(tlb, pud, addr, next, floor, ceiling);
5001da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
5011da177e4SLinus Torvalds 
502c2febafcSKirill A. Shutemov 	start &= P4D_MASK;
503c2febafcSKirill A. Shutemov 	if (start < floor)
504c2febafcSKirill A. Shutemov 		return;
505c2febafcSKirill A. Shutemov 	if (ceiling) {
506c2febafcSKirill A. Shutemov 		ceiling &= P4D_MASK;
507c2febafcSKirill A. Shutemov 		if (!ceiling)
508c2febafcSKirill A. Shutemov 			return;
509c2febafcSKirill A. Shutemov 	}
510c2febafcSKirill A. Shutemov 	if (end - 1 > ceiling - 1)
511c2febafcSKirill A. Shutemov 		return;
512c2febafcSKirill A. Shutemov 
513c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, start);
514c2febafcSKirill A. Shutemov 	p4d_clear(p4d);
515c2febafcSKirill A. Shutemov 	pud_free_tlb(tlb, pud, start);
516b4e98d9aSKirill A. Shutemov 	mm_dec_nr_puds(tlb->mm);
517c2febafcSKirill A. Shutemov }
518c2febafcSKirill A. Shutemov 
519c2febafcSKirill A. Shutemov static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
520c2febafcSKirill A. Shutemov 				unsigned long addr, unsigned long end,
521c2febafcSKirill A. Shutemov 				unsigned long floor, unsigned long ceiling)
522c2febafcSKirill A. Shutemov {
523c2febafcSKirill A. Shutemov 	p4d_t *p4d;
524c2febafcSKirill A. Shutemov 	unsigned long next;
525c2febafcSKirill A. Shutemov 	unsigned long start;
526c2febafcSKirill A. Shutemov 
527c2febafcSKirill A. Shutemov 	start = addr;
528c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
529c2febafcSKirill A. Shutemov 	do {
530c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
531c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(p4d))
532c2febafcSKirill A. Shutemov 			continue;
533c2febafcSKirill A. Shutemov 		free_pud_range(tlb, p4d, addr, next, floor, ceiling);
534c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
535c2febafcSKirill A. Shutemov 
536e0da382cSHugh Dickins 	start &= PGDIR_MASK;
537e0da382cSHugh Dickins 	if (start < floor)
538e0da382cSHugh Dickins 		return;
539e0da382cSHugh Dickins 	if (ceiling) {
540e0da382cSHugh Dickins 		ceiling &= PGDIR_MASK;
541e0da382cSHugh Dickins 		if (!ceiling)
542e0da382cSHugh Dickins 			return;
5431da177e4SLinus Torvalds 	}
544e0da382cSHugh Dickins 	if (end - 1 > ceiling - 1)
545e0da382cSHugh Dickins 		return;
546e0da382cSHugh Dickins 
547c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, start);
548e0da382cSHugh Dickins 	pgd_clear(pgd);
549c2febafcSKirill A. Shutemov 	p4d_free_tlb(tlb, p4d, start);
5501da177e4SLinus Torvalds }
5511da177e4SLinus Torvalds 
5521da177e4SLinus Torvalds /*
553e0da382cSHugh Dickins  * This function frees user-level page tables of a process.
5541da177e4SLinus Torvalds  */
55542b77728SJan Beulich void free_pgd_range(struct mmu_gather *tlb,
556e0da382cSHugh Dickins 			unsigned long addr, unsigned long end,
557e0da382cSHugh Dickins 			unsigned long floor, unsigned long ceiling)
5581da177e4SLinus Torvalds {
5591da177e4SLinus Torvalds 	pgd_t *pgd;
5601da177e4SLinus Torvalds 	unsigned long next;
5611da177e4SLinus Torvalds 
562e0da382cSHugh Dickins 	/*
563e0da382cSHugh Dickins 	 * The next few lines have given us lots of grief...
564e0da382cSHugh Dickins 	 *
565e0da382cSHugh Dickins 	 * Why are we testing PMD* at this top level?  Because often
566e0da382cSHugh Dickins 	 * there will be no work to do at all, and we'd prefer not to
567e0da382cSHugh Dickins 	 * go all the way down to the bottom just to discover that.
568e0da382cSHugh Dickins 	 *
569e0da382cSHugh Dickins 	 * Why all these "- 1"s?  Because 0 represents both the bottom
570e0da382cSHugh Dickins 	 * of the address space and the top of it (using -1 for the
571e0da382cSHugh Dickins 	 * top wouldn't help much: the masks would do the wrong thing).
572e0da382cSHugh Dickins 	 * The rule is that addr 0 and floor 0 refer to the bottom of
573e0da382cSHugh Dickins 	 * the address space, but end 0 and ceiling 0 refer to the top
574e0da382cSHugh Dickins 	 * Comparisons need to use "end - 1" and "ceiling - 1" (though
575e0da382cSHugh Dickins 	 * that end 0 case should be mythical).
576e0da382cSHugh Dickins 	 *
577e0da382cSHugh Dickins 	 * Wherever addr is brought up or ceiling brought down, we must
578e0da382cSHugh Dickins 	 * be careful to reject "the opposite 0" before it confuses the
579e0da382cSHugh Dickins 	 * subsequent tests.  But what about where end is brought down
580e0da382cSHugh Dickins 	 * by PMD_SIZE below? no, end can't go down to 0 there.
581e0da382cSHugh Dickins 	 *
582e0da382cSHugh Dickins 	 * Whereas we round start (addr) and ceiling down, by different
583e0da382cSHugh Dickins 	 * masks at different levels, in order to test whether a table
584e0da382cSHugh Dickins 	 * now has no other vmas using it, so can be freed, we don't
585e0da382cSHugh Dickins 	 * bother to round floor or end up - the tests don't need that.
586e0da382cSHugh Dickins 	 */
587e0da382cSHugh Dickins 
588e0da382cSHugh Dickins 	addr &= PMD_MASK;
589e0da382cSHugh Dickins 	if (addr < floor) {
590e0da382cSHugh Dickins 		addr += PMD_SIZE;
591e0da382cSHugh Dickins 		if (!addr)
592e0da382cSHugh Dickins 			return;
593e0da382cSHugh Dickins 	}
594e0da382cSHugh Dickins 	if (ceiling) {
595e0da382cSHugh Dickins 		ceiling &= PMD_MASK;
596e0da382cSHugh Dickins 		if (!ceiling)
597e0da382cSHugh Dickins 			return;
598e0da382cSHugh Dickins 	}
599e0da382cSHugh Dickins 	if (end - 1 > ceiling - 1)
600e0da382cSHugh Dickins 		end -= PMD_SIZE;
601e0da382cSHugh Dickins 	if (addr > end - 1)
602e0da382cSHugh Dickins 		return;
60307e32661SAneesh Kumar K.V 	/*
60407e32661SAneesh Kumar K.V 	 * We add page table cache pages with PAGE_SIZE,
60507e32661SAneesh Kumar K.V 	 * (see pte_free_tlb()), flush the tlb if we need
60607e32661SAneesh Kumar K.V 	 */
60707e32661SAneesh Kumar K.V 	tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
60842b77728SJan Beulich 	pgd = pgd_offset(tlb->mm, addr);
6091da177e4SLinus Torvalds 	do {
6101da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
6111da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
6121da177e4SLinus Torvalds 			continue;
613c2febafcSKirill A. Shutemov 		free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
6141da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
615e0da382cSHugh Dickins }
616e0da382cSHugh Dickins 
61742b77728SJan Beulich void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
618e0da382cSHugh Dickins 		unsigned long floor, unsigned long ceiling)
619e0da382cSHugh Dickins {
620e0da382cSHugh Dickins 	while (vma) {
621e0da382cSHugh Dickins 		struct vm_area_struct *next = vma->vm_next;
622e0da382cSHugh Dickins 		unsigned long addr = vma->vm_start;
623e0da382cSHugh Dickins 
6248f4f8c16SHugh Dickins 		/*
62525d9e2d1Snpiggin@suse.de 		 * Hide vma from rmap and truncate_pagecache before freeing
62625d9e2d1Snpiggin@suse.de 		 * pgtables
6278f4f8c16SHugh Dickins 		 */
6285beb4930SRik van Riel 		unlink_anon_vmas(vma);
6298f4f8c16SHugh Dickins 		unlink_file_vma(vma);
6308f4f8c16SHugh Dickins 
6319da61aefSDavid Gibson 		if (is_vm_hugetlb_page(vma)) {
6323bf5ee95SHugh Dickins 			hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
6333bf5ee95SHugh Dickins 				floor, next ? next->vm_start : ceiling);
6343bf5ee95SHugh Dickins 		} else {
6353bf5ee95SHugh Dickins 			/*
6363bf5ee95SHugh Dickins 			 * Optimization: gather nearby vmas into one call down
6373bf5ee95SHugh Dickins 			 */
6383bf5ee95SHugh Dickins 			while (next && next->vm_start <= vma->vm_end + PMD_SIZE
6394866920bSDavid Gibson 			       && !is_vm_hugetlb_page(next)) {
640e0da382cSHugh Dickins 				vma = next;
641e0da382cSHugh Dickins 				next = vma->vm_next;
6425beb4930SRik van Riel 				unlink_anon_vmas(vma);
6438f4f8c16SHugh Dickins 				unlink_file_vma(vma);
644e0da382cSHugh Dickins 			}
6453bf5ee95SHugh Dickins 			free_pgd_range(tlb, addr, vma->vm_end,
646e0da382cSHugh Dickins 				floor, next ? next->vm_start : ceiling);
6473bf5ee95SHugh Dickins 		}
648e0da382cSHugh Dickins 		vma = next;
649e0da382cSHugh Dickins 	}
6501da177e4SLinus Torvalds }
6511da177e4SLinus Torvalds 
6523ed3a4f0SKirill A. Shutemov int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
6531da177e4SLinus Torvalds {
654c4088ebdSKirill A. Shutemov 	spinlock_t *ptl;
6552f569afdSMartin Schwidefsky 	pgtable_t new = pte_alloc_one(mm, address);
6561da177e4SLinus Torvalds 	if (!new)
6571bb3630eSHugh Dickins 		return -ENOMEM;
6581bb3630eSHugh Dickins 
659362a61adSNick Piggin 	/*
660362a61adSNick Piggin 	 * Ensure all pte setup (eg. pte page lock and page clearing) are
661362a61adSNick Piggin 	 * visible before the pte is made visible to other CPUs by being
662362a61adSNick Piggin 	 * put into page tables.
663362a61adSNick Piggin 	 *
664362a61adSNick Piggin 	 * The other side of the story is the pointer chasing in the page
665362a61adSNick Piggin 	 * table walking code (when walking the page table without locking;
666362a61adSNick Piggin 	 * ie. most of the time). Fortunately, these data accesses consist
667362a61adSNick Piggin 	 * of a chain of data-dependent loads, meaning most CPUs (alpha
668362a61adSNick Piggin 	 * being the notable exception) will already guarantee loads are
669362a61adSNick Piggin 	 * seen in-order. See the alpha page table accessors for the
670362a61adSNick Piggin 	 * smp_read_barrier_depends() barriers in page table walking code.
671362a61adSNick Piggin 	 */
672362a61adSNick Piggin 	smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
673362a61adSNick Piggin 
674c4088ebdSKirill A. Shutemov 	ptl = pmd_lock(mm, pmd);
6758ac1f832SAndrea Arcangeli 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
676c4812909SKirill A. Shutemov 		mm_inc_nr_ptes(mm);
6771da177e4SLinus Torvalds 		pmd_populate(mm, pmd, new);
6782f569afdSMartin Schwidefsky 		new = NULL;
6794b471e88SKirill A. Shutemov 	}
680c4088ebdSKirill A. Shutemov 	spin_unlock(ptl);
6812f569afdSMartin Schwidefsky 	if (new)
6822f569afdSMartin Schwidefsky 		pte_free(mm, new);
6831bb3630eSHugh Dickins 	return 0;
6841da177e4SLinus Torvalds }
6851da177e4SLinus Torvalds 
6861bb3630eSHugh Dickins int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
6871da177e4SLinus Torvalds {
6881bb3630eSHugh Dickins 	pte_t *new = pte_alloc_one_kernel(&init_mm, address);
6891da177e4SLinus Torvalds 	if (!new)
6901bb3630eSHugh Dickins 		return -ENOMEM;
6911da177e4SLinus Torvalds 
692362a61adSNick Piggin 	smp_wmb(); /* See comment in __pte_alloc */
693362a61adSNick Piggin 
694872fec16SHugh Dickins 	spin_lock(&init_mm.page_table_lock);
6958ac1f832SAndrea Arcangeli 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
696872fec16SHugh Dickins 		pmd_populate_kernel(&init_mm, pmd, new);
6972f569afdSMartin Schwidefsky 		new = NULL;
6984b471e88SKirill A. Shutemov 	}
699872fec16SHugh Dickins 	spin_unlock(&init_mm.page_table_lock);
7002f569afdSMartin Schwidefsky 	if (new)
7012f569afdSMartin Schwidefsky 		pte_free_kernel(&init_mm, new);
7021bb3630eSHugh Dickins 	return 0;
7031da177e4SLinus Torvalds }
7041da177e4SLinus Torvalds 
705d559db08SKAMEZAWA Hiroyuki static inline void init_rss_vec(int *rss)
706ae859762SHugh Dickins {
707d559db08SKAMEZAWA Hiroyuki 	memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
708d559db08SKAMEZAWA Hiroyuki }
709d559db08SKAMEZAWA Hiroyuki 
710d559db08SKAMEZAWA Hiroyuki static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
711d559db08SKAMEZAWA Hiroyuki {
712d559db08SKAMEZAWA Hiroyuki 	int i;
713d559db08SKAMEZAWA Hiroyuki 
71434e55232SKAMEZAWA Hiroyuki 	if (current->mm == mm)
71505af2e10SDavid Rientjes 		sync_mm_rss(mm);
716d559db08SKAMEZAWA Hiroyuki 	for (i = 0; i < NR_MM_COUNTERS; i++)
717d559db08SKAMEZAWA Hiroyuki 		if (rss[i])
718d559db08SKAMEZAWA Hiroyuki 			add_mm_counter(mm, i, rss[i]);
719ae859762SHugh Dickins }
720ae859762SHugh Dickins 
7211da177e4SLinus Torvalds /*
7226aab341eSLinus Torvalds  * This function is called to print an error when a bad pte
7236aab341eSLinus Torvalds  * is found. For example, we might have a PFN-mapped pte in
7246aab341eSLinus Torvalds  * a region that doesn't allow it.
725b5810039SNick Piggin  *
726b5810039SNick Piggin  * The calling function must still handle the error.
727b5810039SNick Piggin  */
7283dc14741SHugh Dickins static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
7293dc14741SHugh Dickins 			  pte_t pte, struct page *page)
730b5810039SNick Piggin {
7313dc14741SHugh Dickins 	pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
732c2febafcSKirill A. Shutemov 	p4d_t *p4d = p4d_offset(pgd, addr);
733c2febafcSKirill A. Shutemov 	pud_t *pud = pud_offset(p4d, addr);
7343dc14741SHugh Dickins 	pmd_t *pmd = pmd_offset(pud, addr);
7353dc14741SHugh Dickins 	struct address_space *mapping;
7363dc14741SHugh Dickins 	pgoff_t index;
737d936cf9bSHugh Dickins 	static unsigned long resume;
738d936cf9bSHugh Dickins 	static unsigned long nr_shown;
739d936cf9bSHugh Dickins 	static unsigned long nr_unshown;
740d936cf9bSHugh Dickins 
741d936cf9bSHugh Dickins 	/*
742d936cf9bSHugh Dickins 	 * Allow a burst of 60 reports, then keep quiet for that minute;
743d936cf9bSHugh Dickins 	 * or allow a steady drip of one report per second.
744d936cf9bSHugh Dickins 	 */
745d936cf9bSHugh Dickins 	if (nr_shown == 60) {
746d936cf9bSHugh Dickins 		if (time_before(jiffies, resume)) {
747d936cf9bSHugh Dickins 			nr_unshown++;
748d936cf9bSHugh Dickins 			return;
749d936cf9bSHugh Dickins 		}
750d936cf9bSHugh Dickins 		if (nr_unshown) {
7511170532bSJoe Perches 			pr_alert("BUG: Bad page map: %lu messages suppressed\n",
752d936cf9bSHugh Dickins 				 nr_unshown);
753d936cf9bSHugh Dickins 			nr_unshown = 0;
754d936cf9bSHugh Dickins 		}
755d936cf9bSHugh Dickins 		nr_shown = 0;
756d936cf9bSHugh Dickins 	}
757d936cf9bSHugh Dickins 	if (nr_shown++ == 0)
758d936cf9bSHugh Dickins 		resume = jiffies + 60 * HZ;
7593dc14741SHugh Dickins 
7603dc14741SHugh Dickins 	mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
7613dc14741SHugh Dickins 	index = linear_page_index(vma, addr);
7623dc14741SHugh Dickins 
7631170532bSJoe Perches 	pr_alert("BUG: Bad page map in process %s  pte:%08llx pmd:%08llx\n",
7643dc14741SHugh Dickins 		 current->comm,
7653dc14741SHugh Dickins 		 (long long)pte_val(pte), (long long)pmd_val(*pmd));
766718a3821SWu Fengguang 	if (page)
767f0b791a3SDave Hansen 		dump_page(page, "bad pte");
7681170532bSJoe Perches 	pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
7693dc14741SHugh Dickins 		 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
7703dc14741SHugh Dickins 	/*
7713dc14741SHugh Dickins 	 * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
7723dc14741SHugh Dickins 	 */
7732682582aSKonstantin Khlebnikov 	pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n",
7742682582aSKonstantin Khlebnikov 		 vma->vm_file,
7752682582aSKonstantin Khlebnikov 		 vma->vm_ops ? vma->vm_ops->fault : NULL,
7762682582aSKonstantin Khlebnikov 		 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
7772682582aSKonstantin Khlebnikov 		 mapping ? mapping->a_ops->readpage : NULL);
778b5810039SNick Piggin 	dump_stack();
779373d4d09SRusty Russell 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
780b5810039SNick Piggin }
781b5810039SNick Piggin 
782b5810039SNick Piggin /*
7837e675137SNick Piggin  * vm_normal_page -- This function gets the "struct page" associated with a pte.
7846aab341eSLinus Torvalds  *
7857e675137SNick Piggin  * "Special" mappings do not wish to be associated with a "struct page" (either
7867e675137SNick Piggin  * it doesn't exist, or it exists but they don't want to touch it). In this
7877e675137SNick Piggin  * case, NULL is returned here. "Normal" mappings do have a struct page.
788b379d790SJared Hulbert  *
7897e675137SNick Piggin  * There are 2 broad cases. Firstly, an architecture may define a pte_special()
7907e675137SNick Piggin  * pte bit, in which case this function is trivial. Secondly, an architecture
7917e675137SNick Piggin  * may not have a spare pte bit, which requires a more complicated scheme,
7927e675137SNick Piggin  * described below.
7937e675137SNick Piggin  *
7947e675137SNick Piggin  * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
7957e675137SNick Piggin  * special mapping (even if there are underlying and valid "struct pages").
7967e675137SNick Piggin  * COWed pages of a VM_PFNMAP are always normal.
7976aab341eSLinus Torvalds  *
798b379d790SJared Hulbert  * The way we recognize COWed pages within VM_PFNMAP mappings is through the
799b379d790SJared Hulbert  * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
8007e675137SNick Piggin  * set, and the vm_pgoff will point to the first PFN mapped: thus every special
8017e675137SNick Piggin  * mapping will always honor the rule
8026aab341eSLinus Torvalds  *
8036aab341eSLinus Torvalds  *	pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
8046aab341eSLinus Torvalds  *
8057e675137SNick Piggin  * And for normal mappings this is false.
806b379d790SJared Hulbert  *
8077e675137SNick Piggin  * This restricts such mappings to be a linear translation from virtual address
8087e675137SNick Piggin  * to pfn. To get around this restriction, we allow arbitrary mappings so long
8097e675137SNick Piggin  * as the vma is not a COW mapping; in that case, we know that all ptes are
8107e675137SNick Piggin  * special (because none can have been COWed).
811b379d790SJared Hulbert  *
812b379d790SJared Hulbert  *
8137e675137SNick Piggin  * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
8147e675137SNick Piggin  *
815b379d790SJared Hulbert  * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
816b379d790SJared Hulbert  * page" backing, however the difference is that _all_ pages with a struct
817b379d790SJared Hulbert  * page (that is, those where pfn_valid is true) are refcounted and considered
818b379d790SJared Hulbert  * normal pages by the VM. The disadvantage is that pages are refcounted
819b379d790SJared Hulbert  * (which can be slower and simply not an option for some PFNMAP users). The
820b379d790SJared Hulbert  * advantage is that we don't have to follow the strict linearity rule of
821b379d790SJared Hulbert  * PFNMAP mappings in order to support COWable mappings.
822b379d790SJared Hulbert  *
823ee498ed7SHugh Dickins  */
8247e675137SNick Piggin #ifdef __HAVE_ARCH_PTE_SPECIAL
8257e675137SNick Piggin # define HAVE_PTE_SPECIAL 1
8267e675137SNick Piggin #else
8277e675137SNick Piggin # define HAVE_PTE_SPECIAL 0
8287e675137SNick Piggin #endif
829df6ad698SJérôme Glisse struct page *_vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
830df6ad698SJérôme Glisse 			     pte_t pte, bool with_public_device)
831ee498ed7SHugh Dickins {
83222b31eecSHugh Dickins 	unsigned long pfn = pte_pfn(pte);
8337e675137SNick Piggin 
8347e675137SNick Piggin 	if (HAVE_PTE_SPECIAL) {
835b38af472SHugh Dickins 		if (likely(!pte_special(pte)))
83622b31eecSHugh Dickins 			goto check_pfn;
837667a0a06SDavid Vrabel 		if (vma->vm_ops && vma->vm_ops->find_special_page)
838667a0a06SDavid Vrabel 			return vma->vm_ops->find_special_page(vma, addr);
839a13ea5b7SHugh Dickins 		if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
840a13ea5b7SHugh Dickins 			return NULL;
841df6ad698SJérôme Glisse 		if (is_zero_pfn(pfn))
842df6ad698SJérôme Glisse 			return NULL;
843df6ad698SJérôme Glisse 
844df6ad698SJérôme Glisse 		/*
845df6ad698SJérôme Glisse 		 * Device public pages are special pages (they are ZONE_DEVICE
846df6ad698SJérôme Glisse 		 * pages but different from persistent memory). They behave
847df6ad698SJérôme Glisse 		 * allmost like normal pages. The difference is that they are
848df6ad698SJérôme Glisse 		 * not on the lru and thus should never be involve with any-
849df6ad698SJérôme Glisse 		 * thing that involve lru manipulation (mlock, numa balancing,
850df6ad698SJérôme Glisse 		 * ...).
851df6ad698SJérôme Glisse 		 *
852df6ad698SJérôme Glisse 		 * This is why we still want to return NULL for such page from
853df6ad698SJérôme Glisse 		 * vm_normal_page() so that we do not have to special case all
854df6ad698SJérôme Glisse 		 * call site of vm_normal_page().
855df6ad698SJérôme Glisse 		 */
8567d790d2dSReza Arbab 		if (likely(pfn <= highest_memmap_pfn)) {
857df6ad698SJérôme Glisse 			struct page *page = pfn_to_page(pfn);
858df6ad698SJérôme Glisse 
859df6ad698SJérôme Glisse 			if (is_device_public_page(page)) {
860df6ad698SJérôme Glisse 				if (with_public_device)
861df6ad698SJérôme Glisse 					return page;
862df6ad698SJérôme Glisse 				return NULL;
863df6ad698SJérôme Glisse 			}
864df6ad698SJérôme Glisse 		}
86522b31eecSHugh Dickins 		print_bad_pte(vma, addr, pte, NULL);
8667e675137SNick Piggin 		return NULL;
8677e675137SNick Piggin 	}
8687e675137SNick Piggin 
8697e675137SNick Piggin 	/* !HAVE_PTE_SPECIAL case follows: */
8707e675137SNick Piggin 
871b379d790SJared Hulbert 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
872b379d790SJared Hulbert 		if (vma->vm_flags & VM_MIXEDMAP) {
873b379d790SJared Hulbert 			if (!pfn_valid(pfn))
874b379d790SJared Hulbert 				return NULL;
875b379d790SJared Hulbert 			goto out;
876b379d790SJared Hulbert 		} else {
8777e675137SNick Piggin 			unsigned long off;
8787e675137SNick Piggin 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
8796aab341eSLinus Torvalds 			if (pfn == vma->vm_pgoff + off)
8806aab341eSLinus Torvalds 				return NULL;
88167121172SLinus Torvalds 			if (!is_cow_mapping(vma->vm_flags))
882fb155c16SLinus Torvalds 				return NULL;
8836aab341eSLinus Torvalds 		}
884b379d790SJared Hulbert 	}
8856aab341eSLinus Torvalds 
886b38af472SHugh Dickins 	if (is_zero_pfn(pfn))
887b38af472SHugh Dickins 		return NULL;
88822b31eecSHugh Dickins check_pfn:
88922b31eecSHugh Dickins 	if (unlikely(pfn > highest_memmap_pfn)) {
89022b31eecSHugh Dickins 		print_bad_pte(vma, addr, pte, NULL);
89122b31eecSHugh Dickins 		return NULL;
89222b31eecSHugh Dickins 	}
8936aab341eSLinus Torvalds 
8946aab341eSLinus Torvalds 	/*
8957e675137SNick Piggin 	 * NOTE! We still have PageReserved() pages in the page tables.
8967e675137SNick Piggin 	 * eg. VDSO mappings can cause them to exist.
8976aab341eSLinus Torvalds 	 */
898b379d790SJared Hulbert out:
8996aab341eSLinus Torvalds 	return pfn_to_page(pfn);
900ee498ed7SHugh Dickins }
901ee498ed7SHugh Dickins 
90228093f9fSGerald Schaefer #ifdef CONFIG_TRANSPARENT_HUGEPAGE
90328093f9fSGerald Schaefer struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
90428093f9fSGerald Schaefer 				pmd_t pmd)
90528093f9fSGerald Schaefer {
90628093f9fSGerald Schaefer 	unsigned long pfn = pmd_pfn(pmd);
90728093f9fSGerald Schaefer 
90828093f9fSGerald Schaefer 	/*
90928093f9fSGerald Schaefer 	 * There is no pmd_special() but there may be special pmds, e.g.
91028093f9fSGerald Schaefer 	 * in a direct-access (dax) mapping, so let's just replicate the
91128093f9fSGerald Schaefer 	 * !HAVE_PTE_SPECIAL case from vm_normal_page() here.
91228093f9fSGerald Schaefer 	 */
91328093f9fSGerald Schaefer 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
91428093f9fSGerald Schaefer 		if (vma->vm_flags & VM_MIXEDMAP) {
91528093f9fSGerald Schaefer 			if (!pfn_valid(pfn))
91628093f9fSGerald Schaefer 				return NULL;
91728093f9fSGerald Schaefer 			goto out;
91828093f9fSGerald Schaefer 		} else {
91928093f9fSGerald Schaefer 			unsigned long off;
92028093f9fSGerald Schaefer 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
92128093f9fSGerald Schaefer 			if (pfn == vma->vm_pgoff + off)
92228093f9fSGerald Schaefer 				return NULL;
92328093f9fSGerald Schaefer 			if (!is_cow_mapping(vma->vm_flags))
92428093f9fSGerald Schaefer 				return NULL;
92528093f9fSGerald Schaefer 		}
92628093f9fSGerald Schaefer 	}
92728093f9fSGerald Schaefer 
92828093f9fSGerald Schaefer 	if (is_zero_pfn(pfn))
92928093f9fSGerald Schaefer 		return NULL;
93028093f9fSGerald Schaefer 	if (unlikely(pfn > highest_memmap_pfn))
93128093f9fSGerald Schaefer 		return NULL;
93228093f9fSGerald Schaefer 
93328093f9fSGerald Schaefer 	/*
93428093f9fSGerald Schaefer 	 * NOTE! We still have PageReserved() pages in the page tables.
93528093f9fSGerald Schaefer 	 * eg. VDSO mappings can cause them to exist.
93628093f9fSGerald Schaefer 	 */
93728093f9fSGerald Schaefer out:
93828093f9fSGerald Schaefer 	return pfn_to_page(pfn);
93928093f9fSGerald Schaefer }
94028093f9fSGerald Schaefer #endif
94128093f9fSGerald Schaefer 
942ee498ed7SHugh Dickins /*
9431da177e4SLinus Torvalds  * copy one vm_area from one task to the other. Assumes the page tables
9441da177e4SLinus Torvalds  * already present in the new task to be cleared in the whole range
9451da177e4SLinus Torvalds  * covered by this vma.
9461da177e4SLinus Torvalds  */
9471da177e4SLinus Torvalds 
948570a335bSHugh Dickins static inline unsigned long
9491da177e4SLinus Torvalds copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
950b5810039SNick Piggin 		pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
9518c103762SHugh Dickins 		unsigned long addr, int *rss)
9521da177e4SLinus Torvalds {
953b5810039SNick Piggin 	unsigned long vm_flags = vma->vm_flags;
9541da177e4SLinus Torvalds 	pte_t pte = *src_pte;
9551da177e4SLinus Torvalds 	struct page *page;
9561da177e4SLinus Torvalds 
9571da177e4SLinus Torvalds 	/* pte contains position in swap or file, so copy. */
9581da177e4SLinus Torvalds 	if (unlikely(!pte_present(pte))) {
9590697212aSChristoph Lameter 		swp_entry_t entry = pte_to_swp_entry(pte);
9600697212aSChristoph Lameter 
9612022b4d1SHugh Dickins 		if (likely(!non_swap_entry(entry))) {
962570a335bSHugh Dickins 			if (swap_duplicate(entry) < 0)
963570a335bSHugh Dickins 				return entry.val;
964570a335bSHugh Dickins 
9651da177e4SLinus Torvalds 			/* make sure dst_mm is on swapoff's mmlist. */
9661da177e4SLinus Torvalds 			if (unlikely(list_empty(&dst_mm->mmlist))) {
9671da177e4SLinus Torvalds 				spin_lock(&mmlist_lock);
968f412ac08SHugh Dickins 				if (list_empty(&dst_mm->mmlist))
969f412ac08SHugh Dickins 					list_add(&dst_mm->mmlist,
970f412ac08SHugh Dickins 							&src_mm->mmlist);
9711da177e4SLinus Torvalds 				spin_unlock(&mmlist_lock);
9721da177e4SLinus Torvalds 			}
973b084d435SKAMEZAWA Hiroyuki 			rss[MM_SWAPENTS]++;
9742022b4d1SHugh Dickins 		} else if (is_migration_entry(entry)) {
9759f9f1acdSKonstantin Khlebnikov 			page = migration_entry_to_page(entry);
9769f9f1acdSKonstantin Khlebnikov 
977eca56ff9SJerome Marchand 			rss[mm_counter(page)]++;
9789f9f1acdSKonstantin Khlebnikov 
9799f9f1acdSKonstantin Khlebnikov 			if (is_write_migration_entry(entry) &&
9800697212aSChristoph Lameter 					is_cow_mapping(vm_flags)) {
9810697212aSChristoph Lameter 				/*
9829f9f1acdSKonstantin Khlebnikov 				 * COW mappings require pages in both
9839f9f1acdSKonstantin Khlebnikov 				 * parent and child to be set to read.
9840697212aSChristoph Lameter 				 */
9850697212aSChristoph Lameter 				make_migration_entry_read(&entry);
9860697212aSChristoph Lameter 				pte = swp_entry_to_pte(entry);
987c3d16e16SCyrill Gorcunov 				if (pte_swp_soft_dirty(*src_pte))
988c3d16e16SCyrill Gorcunov 					pte = pte_swp_mksoft_dirty(pte);
9890697212aSChristoph Lameter 				set_pte_at(src_mm, addr, src_pte, pte);
9900697212aSChristoph Lameter 			}
9915042db43SJérôme Glisse 		} else if (is_device_private_entry(entry)) {
9925042db43SJérôme Glisse 			page = device_private_entry_to_page(entry);
9935042db43SJérôme Glisse 
9945042db43SJérôme Glisse 			/*
9955042db43SJérôme Glisse 			 * Update rss count even for unaddressable pages, as
9965042db43SJérôme Glisse 			 * they should treated just like normal pages in this
9975042db43SJérôme Glisse 			 * respect.
9985042db43SJérôme Glisse 			 *
9995042db43SJérôme Glisse 			 * We will likely want to have some new rss counters
10005042db43SJérôme Glisse 			 * for unaddressable pages, at some point. But for now
10015042db43SJérôme Glisse 			 * keep things as they are.
10025042db43SJérôme Glisse 			 */
10035042db43SJérôme Glisse 			get_page(page);
10045042db43SJérôme Glisse 			rss[mm_counter(page)]++;
10055042db43SJérôme Glisse 			page_dup_rmap(page, false);
10065042db43SJérôme Glisse 
10075042db43SJérôme Glisse 			/*
10085042db43SJérôme Glisse 			 * We do not preserve soft-dirty information, because so
10095042db43SJérôme Glisse 			 * far, checkpoint/restore is the only feature that
10105042db43SJérôme Glisse 			 * requires that. And checkpoint/restore does not work
10115042db43SJérôme Glisse 			 * when a device driver is involved (you cannot easily
10125042db43SJérôme Glisse 			 * save and restore device driver state).
10135042db43SJérôme Glisse 			 */
10145042db43SJérôme Glisse 			if (is_write_device_private_entry(entry) &&
10155042db43SJérôme Glisse 			    is_cow_mapping(vm_flags)) {
10165042db43SJérôme Glisse 				make_device_private_entry_read(&entry);
10175042db43SJérôme Glisse 				pte = swp_entry_to_pte(entry);
10185042db43SJérôme Glisse 				set_pte_at(src_mm, addr, src_pte, pte);
10195042db43SJérôme Glisse 			}
10201da177e4SLinus Torvalds 		}
1021ae859762SHugh Dickins 		goto out_set_pte;
10221da177e4SLinus Torvalds 	}
10231da177e4SLinus Torvalds 
10241da177e4SLinus Torvalds 	/*
10251da177e4SLinus Torvalds 	 * If it's a COW mapping, write protect it both
10261da177e4SLinus Torvalds 	 * in the parent and the child
10271da177e4SLinus Torvalds 	 */
102867121172SLinus Torvalds 	if (is_cow_mapping(vm_flags)) {
10291da177e4SLinus Torvalds 		ptep_set_wrprotect(src_mm, addr, src_pte);
10303dc90795SZachary Amsden 		pte = pte_wrprotect(pte);
10311da177e4SLinus Torvalds 	}
10321da177e4SLinus Torvalds 
10331da177e4SLinus Torvalds 	/*
10341da177e4SLinus Torvalds 	 * If it's a shared mapping, mark it clean in
10351da177e4SLinus Torvalds 	 * the child
10361da177e4SLinus Torvalds 	 */
10371da177e4SLinus Torvalds 	if (vm_flags & VM_SHARED)
10381da177e4SLinus Torvalds 		pte = pte_mkclean(pte);
10391da177e4SLinus Torvalds 	pte = pte_mkold(pte);
10406aab341eSLinus Torvalds 
10416aab341eSLinus Torvalds 	page = vm_normal_page(vma, addr, pte);
10426aab341eSLinus Torvalds 	if (page) {
10431da177e4SLinus Torvalds 		get_page(page);
104453f9263bSKirill A. Shutemov 		page_dup_rmap(page, false);
1045eca56ff9SJerome Marchand 		rss[mm_counter(page)]++;
1046df6ad698SJérôme Glisse 	} else if (pte_devmap(pte)) {
1047df6ad698SJérôme Glisse 		page = pte_page(pte);
1048df6ad698SJérôme Glisse 
1049df6ad698SJérôme Glisse 		/*
1050df6ad698SJérôme Glisse 		 * Cache coherent device memory behave like regular page and
1051df6ad698SJérôme Glisse 		 * not like persistent memory page. For more informations see
1052df6ad698SJérôme Glisse 		 * MEMORY_DEVICE_CACHE_COHERENT in memory_hotplug.h
1053df6ad698SJérôme Glisse 		 */
1054df6ad698SJérôme Glisse 		if (is_device_public_page(page)) {
1055df6ad698SJérôme Glisse 			get_page(page);
1056df6ad698SJérôme Glisse 			page_dup_rmap(page, false);
1057df6ad698SJérôme Glisse 			rss[mm_counter(page)]++;
1058df6ad698SJérôme Glisse 		}
10596aab341eSLinus Torvalds 	}
1060ae859762SHugh Dickins 
1061ae859762SHugh Dickins out_set_pte:
1062ae859762SHugh Dickins 	set_pte_at(dst_mm, addr, dst_pte, pte);
1063570a335bSHugh Dickins 	return 0;
10641da177e4SLinus Torvalds }
10651da177e4SLinus Torvalds 
106621bda264SJerome Marchand static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
10671da177e4SLinus Torvalds 		   pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
10681da177e4SLinus Torvalds 		   unsigned long addr, unsigned long end)
10691da177e4SLinus Torvalds {
1070c36987e2SDaisuke Nishimura 	pte_t *orig_src_pte, *orig_dst_pte;
10711da177e4SLinus Torvalds 	pte_t *src_pte, *dst_pte;
1072c74df32cSHugh Dickins 	spinlock_t *src_ptl, *dst_ptl;
1073e040f218SHugh Dickins 	int progress = 0;
1074d559db08SKAMEZAWA Hiroyuki 	int rss[NR_MM_COUNTERS];
1075570a335bSHugh Dickins 	swp_entry_t entry = (swp_entry_t){0};
10761da177e4SLinus Torvalds 
10771da177e4SLinus Torvalds again:
1078d559db08SKAMEZAWA Hiroyuki 	init_rss_vec(rss);
1079d559db08SKAMEZAWA Hiroyuki 
1080c74df32cSHugh Dickins 	dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
10811da177e4SLinus Torvalds 	if (!dst_pte)
10821da177e4SLinus Torvalds 		return -ENOMEM;
1083ece0e2b6SPeter Zijlstra 	src_pte = pte_offset_map(src_pmd, addr);
10844c21e2f2SHugh Dickins 	src_ptl = pte_lockptr(src_mm, src_pmd);
1085f20dc5f7SIngo Molnar 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1086c36987e2SDaisuke Nishimura 	orig_src_pte = src_pte;
1087c36987e2SDaisuke Nishimura 	orig_dst_pte = dst_pte;
10886606c3e0SZachary Amsden 	arch_enter_lazy_mmu_mode();
10891da177e4SLinus Torvalds 
10901da177e4SLinus Torvalds 	do {
10911da177e4SLinus Torvalds 		/*
10921da177e4SLinus Torvalds 		 * We are holding two locks at this point - either of them
10931da177e4SLinus Torvalds 		 * could generate latencies in another task on another CPU.
10941da177e4SLinus Torvalds 		 */
1095e040f218SHugh Dickins 		if (progress >= 32) {
1096e040f218SHugh Dickins 			progress = 0;
1097e040f218SHugh Dickins 			if (need_resched() ||
109895c354feSNick Piggin 			    spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
10991da177e4SLinus Torvalds 				break;
1100e040f218SHugh Dickins 		}
11011da177e4SLinus Torvalds 		if (pte_none(*src_pte)) {
11021da177e4SLinus Torvalds 			progress++;
11031da177e4SLinus Torvalds 			continue;
11041da177e4SLinus Torvalds 		}
1105570a335bSHugh Dickins 		entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
1106570a335bSHugh Dickins 							vma, addr, rss);
1107570a335bSHugh Dickins 		if (entry.val)
1108570a335bSHugh Dickins 			break;
11091da177e4SLinus Torvalds 		progress += 8;
11101da177e4SLinus Torvalds 	} while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
11111da177e4SLinus Torvalds 
11126606c3e0SZachary Amsden 	arch_leave_lazy_mmu_mode();
1113c74df32cSHugh Dickins 	spin_unlock(src_ptl);
1114ece0e2b6SPeter Zijlstra 	pte_unmap(orig_src_pte);
1115d559db08SKAMEZAWA Hiroyuki 	add_mm_rss_vec(dst_mm, rss);
1116c36987e2SDaisuke Nishimura 	pte_unmap_unlock(orig_dst_pte, dst_ptl);
1117c74df32cSHugh Dickins 	cond_resched();
1118570a335bSHugh Dickins 
1119570a335bSHugh Dickins 	if (entry.val) {
1120570a335bSHugh Dickins 		if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
1121570a335bSHugh Dickins 			return -ENOMEM;
1122570a335bSHugh Dickins 		progress = 0;
1123570a335bSHugh Dickins 	}
11241da177e4SLinus Torvalds 	if (addr != end)
11251da177e4SLinus Torvalds 		goto again;
11261da177e4SLinus Torvalds 	return 0;
11271da177e4SLinus Torvalds }
11281da177e4SLinus Torvalds 
11291da177e4SLinus Torvalds static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
11301da177e4SLinus Torvalds 		pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
11311da177e4SLinus Torvalds 		unsigned long addr, unsigned long end)
11321da177e4SLinus Torvalds {
11331da177e4SLinus Torvalds 	pmd_t *src_pmd, *dst_pmd;
11341da177e4SLinus Torvalds 	unsigned long next;
11351da177e4SLinus Torvalds 
11361da177e4SLinus Torvalds 	dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
11371da177e4SLinus Torvalds 	if (!dst_pmd)
11381da177e4SLinus Torvalds 		return -ENOMEM;
11391da177e4SLinus Torvalds 	src_pmd = pmd_offset(src_pud, addr);
11401da177e4SLinus Torvalds 	do {
11411da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
114284c3fc4eSZi Yan 		if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
114384c3fc4eSZi Yan 			|| pmd_devmap(*src_pmd)) {
114471e3aac0SAndrea Arcangeli 			int err;
1145a00cc7d9SMatthew Wilcox 			VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, vma);
114671e3aac0SAndrea Arcangeli 			err = copy_huge_pmd(dst_mm, src_mm,
114771e3aac0SAndrea Arcangeli 					    dst_pmd, src_pmd, addr, vma);
114871e3aac0SAndrea Arcangeli 			if (err == -ENOMEM)
114971e3aac0SAndrea Arcangeli 				return -ENOMEM;
115071e3aac0SAndrea Arcangeli 			if (!err)
115171e3aac0SAndrea Arcangeli 				continue;
115271e3aac0SAndrea Arcangeli 			/* fall through */
115371e3aac0SAndrea Arcangeli 		}
11541da177e4SLinus Torvalds 		if (pmd_none_or_clear_bad(src_pmd))
11551da177e4SLinus Torvalds 			continue;
11561da177e4SLinus Torvalds 		if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
11571da177e4SLinus Torvalds 						vma, addr, next))
11581da177e4SLinus Torvalds 			return -ENOMEM;
11591da177e4SLinus Torvalds 	} while (dst_pmd++, src_pmd++, addr = next, addr != end);
11601da177e4SLinus Torvalds 	return 0;
11611da177e4SLinus Torvalds }
11621da177e4SLinus Torvalds 
11631da177e4SLinus Torvalds static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1164c2febafcSKirill A. Shutemov 		p4d_t *dst_p4d, p4d_t *src_p4d, struct vm_area_struct *vma,
11651da177e4SLinus Torvalds 		unsigned long addr, unsigned long end)
11661da177e4SLinus Torvalds {
11671da177e4SLinus Torvalds 	pud_t *src_pud, *dst_pud;
11681da177e4SLinus Torvalds 	unsigned long next;
11691da177e4SLinus Torvalds 
1170c2febafcSKirill A. Shutemov 	dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
11711da177e4SLinus Torvalds 	if (!dst_pud)
11721da177e4SLinus Torvalds 		return -ENOMEM;
1173c2febafcSKirill A. Shutemov 	src_pud = pud_offset(src_p4d, addr);
11741da177e4SLinus Torvalds 	do {
11751da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
1176a00cc7d9SMatthew Wilcox 		if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1177a00cc7d9SMatthew Wilcox 			int err;
1178a00cc7d9SMatthew Wilcox 
1179a00cc7d9SMatthew Wilcox 			VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, vma);
1180a00cc7d9SMatthew Wilcox 			err = copy_huge_pud(dst_mm, src_mm,
1181a00cc7d9SMatthew Wilcox 					    dst_pud, src_pud, addr, vma);
1182a00cc7d9SMatthew Wilcox 			if (err == -ENOMEM)
1183a00cc7d9SMatthew Wilcox 				return -ENOMEM;
1184a00cc7d9SMatthew Wilcox 			if (!err)
1185a00cc7d9SMatthew Wilcox 				continue;
1186a00cc7d9SMatthew Wilcox 			/* fall through */
1187a00cc7d9SMatthew Wilcox 		}
11881da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(src_pud))
11891da177e4SLinus Torvalds 			continue;
11901da177e4SLinus Torvalds 		if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
11911da177e4SLinus Torvalds 						vma, addr, next))
11921da177e4SLinus Torvalds 			return -ENOMEM;
11931da177e4SLinus Torvalds 	} while (dst_pud++, src_pud++, addr = next, addr != end);
11941da177e4SLinus Torvalds 	return 0;
11951da177e4SLinus Torvalds }
11961da177e4SLinus Torvalds 
1197c2febafcSKirill A. Shutemov static inline int copy_p4d_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1198c2febafcSKirill A. Shutemov 		pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
1199c2febafcSKirill A. Shutemov 		unsigned long addr, unsigned long end)
1200c2febafcSKirill A. Shutemov {
1201c2febafcSKirill A. Shutemov 	p4d_t *src_p4d, *dst_p4d;
1202c2febafcSKirill A. Shutemov 	unsigned long next;
1203c2febafcSKirill A. Shutemov 
1204c2febafcSKirill A. Shutemov 	dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1205c2febafcSKirill A. Shutemov 	if (!dst_p4d)
1206c2febafcSKirill A. Shutemov 		return -ENOMEM;
1207c2febafcSKirill A. Shutemov 	src_p4d = p4d_offset(src_pgd, addr);
1208c2febafcSKirill A. Shutemov 	do {
1209c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
1210c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(src_p4d))
1211c2febafcSKirill A. Shutemov 			continue;
1212c2febafcSKirill A. Shutemov 		if (copy_pud_range(dst_mm, src_mm, dst_p4d, src_p4d,
1213c2febafcSKirill A. Shutemov 						vma, addr, next))
1214c2febafcSKirill A. Shutemov 			return -ENOMEM;
1215c2febafcSKirill A. Shutemov 	} while (dst_p4d++, src_p4d++, addr = next, addr != end);
1216c2febafcSKirill A. Shutemov 	return 0;
1217c2febafcSKirill A. Shutemov }
1218c2febafcSKirill A. Shutemov 
12191da177e4SLinus Torvalds int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
12201da177e4SLinus Torvalds 		struct vm_area_struct *vma)
12211da177e4SLinus Torvalds {
12221da177e4SLinus Torvalds 	pgd_t *src_pgd, *dst_pgd;
12231da177e4SLinus Torvalds 	unsigned long next;
12241da177e4SLinus Torvalds 	unsigned long addr = vma->vm_start;
12251da177e4SLinus Torvalds 	unsigned long end = vma->vm_end;
12262ec74c3eSSagi Grimberg 	unsigned long mmun_start;	/* For mmu_notifiers */
12272ec74c3eSSagi Grimberg 	unsigned long mmun_end;		/* For mmu_notifiers */
12282ec74c3eSSagi Grimberg 	bool is_cow;
1229cddb8a5cSAndrea Arcangeli 	int ret;
12301da177e4SLinus Torvalds 
1231d992895bSNick Piggin 	/*
1232d992895bSNick Piggin 	 * Don't copy ptes where a page fault will fill them correctly.
1233d992895bSNick Piggin 	 * Fork becomes much lighter when there are big shared or private
1234d992895bSNick Piggin 	 * readonly mappings. The tradeoff is that copy_page_range is more
1235d992895bSNick Piggin 	 * efficient than faulting.
1236d992895bSNick Piggin 	 */
12370661a336SKirill A. Shutemov 	if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
12380661a336SKirill A. Shutemov 			!vma->anon_vma)
1239d992895bSNick Piggin 		return 0;
1240d992895bSNick Piggin 
12411da177e4SLinus Torvalds 	if (is_vm_hugetlb_page(vma))
12421da177e4SLinus Torvalds 		return copy_hugetlb_page_range(dst_mm, src_mm, vma);
12431da177e4SLinus Torvalds 
1244b3b9c293SKonstantin Khlebnikov 	if (unlikely(vma->vm_flags & VM_PFNMAP)) {
12452ab64037Svenkatesh.pallipadi@intel.com 		/*
12462ab64037Svenkatesh.pallipadi@intel.com 		 * We do not free on error cases below as remove_vma
12472ab64037Svenkatesh.pallipadi@intel.com 		 * gets called on error from higher level routine
12482ab64037Svenkatesh.pallipadi@intel.com 		 */
12495180da41SSuresh Siddha 		ret = track_pfn_copy(vma);
12502ab64037Svenkatesh.pallipadi@intel.com 		if (ret)
12512ab64037Svenkatesh.pallipadi@intel.com 			return ret;
12522ab64037Svenkatesh.pallipadi@intel.com 	}
12532ab64037Svenkatesh.pallipadi@intel.com 
1254cddb8a5cSAndrea Arcangeli 	/*
1255cddb8a5cSAndrea Arcangeli 	 * We need to invalidate the secondary MMU mappings only when
1256cddb8a5cSAndrea Arcangeli 	 * there could be a permission downgrade on the ptes of the
1257cddb8a5cSAndrea Arcangeli 	 * parent mm. And a permission downgrade will only happen if
1258cddb8a5cSAndrea Arcangeli 	 * is_cow_mapping() returns true.
1259cddb8a5cSAndrea Arcangeli 	 */
12602ec74c3eSSagi Grimberg 	is_cow = is_cow_mapping(vma->vm_flags);
12612ec74c3eSSagi Grimberg 	mmun_start = addr;
12622ec74c3eSSagi Grimberg 	mmun_end   = end;
12632ec74c3eSSagi Grimberg 	if (is_cow)
12642ec74c3eSSagi Grimberg 		mmu_notifier_invalidate_range_start(src_mm, mmun_start,
12652ec74c3eSSagi Grimberg 						    mmun_end);
1266cddb8a5cSAndrea Arcangeli 
1267cddb8a5cSAndrea Arcangeli 	ret = 0;
12681da177e4SLinus Torvalds 	dst_pgd = pgd_offset(dst_mm, addr);
12691da177e4SLinus Torvalds 	src_pgd = pgd_offset(src_mm, addr);
12701da177e4SLinus Torvalds 	do {
12711da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
12721da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(src_pgd))
12731da177e4SLinus Torvalds 			continue;
1274c2febafcSKirill A. Shutemov 		if (unlikely(copy_p4d_range(dst_mm, src_mm, dst_pgd, src_pgd,
1275cddb8a5cSAndrea Arcangeli 					    vma, addr, next))) {
1276cddb8a5cSAndrea Arcangeli 			ret = -ENOMEM;
1277cddb8a5cSAndrea Arcangeli 			break;
1278cddb8a5cSAndrea Arcangeli 		}
12791da177e4SLinus Torvalds 	} while (dst_pgd++, src_pgd++, addr = next, addr != end);
1280cddb8a5cSAndrea Arcangeli 
12812ec74c3eSSagi Grimberg 	if (is_cow)
12822ec74c3eSSagi Grimberg 		mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end);
1283cddb8a5cSAndrea Arcangeli 	return ret;
12841da177e4SLinus Torvalds }
12851da177e4SLinus Torvalds 
128651c6f666SRobin Holt static unsigned long zap_pte_range(struct mmu_gather *tlb,
1287b5810039SNick Piggin 				struct vm_area_struct *vma, pmd_t *pmd,
12881da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
128997a89413SPeter Zijlstra 				struct zap_details *details)
12901da177e4SLinus Torvalds {
1291b5810039SNick Piggin 	struct mm_struct *mm = tlb->mm;
1292d16dfc55SPeter Zijlstra 	int force_flush = 0;
1293d559db08SKAMEZAWA Hiroyuki 	int rss[NR_MM_COUNTERS];
129497a89413SPeter Zijlstra 	spinlock_t *ptl;
12955f1a1907SSteven Rostedt 	pte_t *start_pte;
129697a89413SPeter Zijlstra 	pte_t *pte;
12978a5f14a2SKirill A. Shutemov 	swp_entry_t entry;
1298d559db08SKAMEZAWA Hiroyuki 
129907e32661SAneesh Kumar K.V 	tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
1300d16dfc55SPeter Zijlstra again:
1301e303297eSPeter Zijlstra 	init_rss_vec(rss);
13025f1a1907SSteven Rostedt 	start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
13035f1a1907SSteven Rostedt 	pte = start_pte;
13043ea27719SMel Gorman 	flush_tlb_batched_pending(mm);
13056606c3e0SZachary Amsden 	arch_enter_lazy_mmu_mode();
13061da177e4SLinus Torvalds 	do {
13071da177e4SLinus Torvalds 		pte_t ptent = *pte;
1308166f61b9STobin C Harding 		if (pte_none(ptent))
13091da177e4SLinus Torvalds 			continue;
131051c6f666SRobin Holt 
13116f5e6b9eSHugh Dickins 		if (pte_present(ptent)) {
13126f5e6b9eSHugh Dickins 			struct page *page;
13136f5e6b9eSHugh Dickins 
1314df6ad698SJérôme Glisse 			page = _vm_normal_page(vma, addr, ptent, true);
13151da177e4SLinus Torvalds 			if (unlikely(details) && page) {
13161da177e4SLinus Torvalds 				/*
13171da177e4SLinus Torvalds 				 * unmap_shared_mapping_pages() wants to
13181da177e4SLinus Torvalds 				 * invalidate cache without truncating:
13191da177e4SLinus Torvalds 				 * unmap shared but keep private pages.
13201da177e4SLinus Torvalds 				 */
13211da177e4SLinus Torvalds 				if (details->check_mapping &&
1322800d8c63SKirill A. Shutemov 				    details->check_mapping != page_rmapping(page))
13231da177e4SLinus Torvalds 					continue;
13241da177e4SLinus Torvalds 			}
1325b5810039SNick Piggin 			ptent = ptep_get_and_clear_full(mm, addr, pte,
1326a600388dSZachary Amsden 							tlb->fullmm);
13271da177e4SLinus Torvalds 			tlb_remove_tlb_entry(tlb, pte, addr);
13281da177e4SLinus Torvalds 			if (unlikely(!page))
13291da177e4SLinus Torvalds 				continue;
1330eca56ff9SJerome Marchand 
1331eca56ff9SJerome Marchand 			if (!PageAnon(page)) {
13321cf35d47SLinus Torvalds 				if (pte_dirty(ptent)) {
13331cf35d47SLinus Torvalds 					force_flush = 1;
13346237bcd9SHugh Dickins 					set_page_dirty(page);
13351cf35d47SLinus Torvalds 				}
13364917e5d0SJohannes Weiner 				if (pte_young(ptent) &&
133764363aadSJoe Perches 				    likely(!(vma->vm_flags & VM_SEQ_READ)))
1338bf3f3bc5SNick Piggin 					mark_page_accessed(page);
13396237bcd9SHugh Dickins 			}
1340eca56ff9SJerome Marchand 			rss[mm_counter(page)]--;
1341d281ee61SKirill A. Shutemov 			page_remove_rmap(page, false);
13423dc14741SHugh Dickins 			if (unlikely(page_mapcount(page) < 0))
13433dc14741SHugh Dickins 				print_bad_pte(vma, addr, ptent, page);
1344e9d55e15SAneesh Kumar K.V 			if (unlikely(__tlb_remove_page(tlb, page))) {
13451cf35d47SLinus Torvalds 				force_flush = 1;
1346ce9ec37bSWill Deacon 				addr += PAGE_SIZE;
1347d16dfc55SPeter Zijlstra 				break;
13481cf35d47SLinus Torvalds 			}
13491da177e4SLinus Torvalds 			continue;
13501da177e4SLinus Torvalds 		}
13515042db43SJérôme Glisse 
13525042db43SJérôme Glisse 		entry = pte_to_swp_entry(ptent);
13535042db43SJérôme Glisse 		if (non_swap_entry(entry) && is_device_private_entry(entry)) {
13545042db43SJérôme Glisse 			struct page *page = device_private_entry_to_page(entry);
13555042db43SJérôme Glisse 
13565042db43SJérôme Glisse 			if (unlikely(details && details->check_mapping)) {
13575042db43SJérôme Glisse 				/*
13585042db43SJérôme Glisse 				 * unmap_shared_mapping_pages() wants to
13595042db43SJérôme Glisse 				 * invalidate cache without truncating:
13605042db43SJérôme Glisse 				 * unmap shared but keep private pages.
13615042db43SJérôme Glisse 				 */
13625042db43SJérôme Glisse 				if (details->check_mapping !=
13635042db43SJérôme Glisse 				    page_rmapping(page))
13645042db43SJérôme Glisse 					continue;
13655042db43SJérôme Glisse 			}
13665042db43SJérôme Glisse 
13675042db43SJérôme Glisse 			pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
13685042db43SJérôme Glisse 			rss[mm_counter(page)]--;
13695042db43SJérôme Glisse 			page_remove_rmap(page, false);
13705042db43SJérôme Glisse 			put_page(page);
13715042db43SJérôme Glisse 			continue;
13725042db43SJérôme Glisse 		}
13735042db43SJérôme Glisse 
13743e8715fdSKirill A. Shutemov 		/* If details->check_mapping, we leave swap entries. */
13753e8715fdSKirill A. Shutemov 		if (unlikely(details))
13761da177e4SLinus Torvalds 			continue;
1377b084d435SKAMEZAWA Hiroyuki 
13788a5f14a2SKirill A. Shutemov 		entry = pte_to_swp_entry(ptent);
1379b084d435SKAMEZAWA Hiroyuki 		if (!non_swap_entry(entry))
1380b084d435SKAMEZAWA Hiroyuki 			rss[MM_SWAPENTS]--;
13819f9f1acdSKonstantin Khlebnikov 		else if (is_migration_entry(entry)) {
13829f9f1acdSKonstantin Khlebnikov 			struct page *page;
13839f9f1acdSKonstantin Khlebnikov 
13849f9f1acdSKonstantin Khlebnikov 			page = migration_entry_to_page(entry);
1385eca56ff9SJerome Marchand 			rss[mm_counter(page)]--;
13869f9f1acdSKonstantin Khlebnikov 		}
1387b084d435SKAMEZAWA Hiroyuki 		if (unlikely(!free_swap_and_cache(entry)))
13882509ef26SHugh Dickins 			print_bad_pte(vma, addr, ptent, NULL);
13899888a1caSZachary Amsden 		pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
139097a89413SPeter Zijlstra 	} while (pte++, addr += PAGE_SIZE, addr != end);
1391ae859762SHugh Dickins 
1392d559db08SKAMEZAWA Hiroyuki 	add_mm_rss_vec(mm, rss);
13936606c3e0SZachary Amsden 	arch_leave_lazy_mmu_mode();
139451c6f666SRobin Holt 
13951cf35d47SLinus Torvalds 	/* Do the actual TLB flush before dropping ptl */
1396fb7332a9SWill Deacon 	if (force_flush)
13971cf35d47SLinus Torvalds 		tlb_flush_mmu_tlbonly(tlb);
13981cf35d47SLinus Torvalds 	pte_unmap_unlock(start_pte, ptl);
13991cf35d47SLinus Torvalds 
14001cf35d47SLinus Torvalds 	/*
14011cf35d47SLinus Torvalds 	 * If we forced a TLB flush (either due to running out of
14021cf35d47SLinus Torvalds 	 * batch buffers or because we needed to flush dirty TLB
14031cf35d47SLinus Torvalds 	 * entries before releasing the ptl), free the batched
14041cf35d47SLinus Torvalds 	 * memory too. Restart if we didn't do everything.
14051cf35d47SLinus Torvalds 	 */
14061cf35d47SLinus Torvalds 	if (force_flush) {
14071cf35d47SLinus Torvalds 		force_flush = 0;
14081cf35d47SLinus Torvalds 		tlb_flush_mmu_free(tlb);
14092b047252SLinus Torvalds 		if (addr != end)
1410d16dfc55SPeter Zijlstra 			goto again;
1411d16dfc55SPeter Zijlstra 	}
1412d16dfc55SPeter Zijlstra 
141351c6f666SRobin Holt 	return addr;
14141da177e4SLinus Torvalds }
14151da177e4SLinus Torvalds 
141651c6f666SRobin Holt static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1417b5810039SNick Piggin 				struct vm_area_struct *vma, pud_t *pud,
14181da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
141997a89413SPeter Zijlstra 				struct zap_details *details)
14201da177e4SLinus Torvalds {
14211da177e4SLinus Torvalds 	pmd_t *pmd;
14221da177e4SLinus Torvalds 	unsigned long next;
14231da177e4SLinus Torvalds 
14241da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
14251da177e4SLinus Torvalds 	do {
14261da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
142784c3fc4eSZi Yan 		if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
142814d1a55cSAndrea Arcangeli 			if (next - addr != HPAGE_PMD_SIZE) {
142968428398SHugh Dickins 				VM_BUG_ON_VMA(vma_is_anonymous(vma) &&
143068428398SHugh Dickins 				    !rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1431fd60775aSDavid Rientjes 				__split_huge_pmd(vma, pmd, addr, false, NULL);
1432f21760b1SShaohua Li 			} else if (zap_huge_pmd(tlb, vma, pmd, addr))
14331a5a9906SAndrea Arcangeli 				goto next;
143471e3aac0SAndrea Arcangeli 			/* fall through */
143571e3aac0SAndrea Arcangeli 		}
14361a5a9906SAndrea Arcangeli 		/*
14371a5a9906SAndrea Arcangeli 		 * Here there can be other concurrent MADV_DONTNEED or
14381a5a9906SAndrea Arcangeli 		 * trans huge page faults running, and if the pmd is
14391a5a9906SAndrea Arcangeli 		 * none or trans huge it can change under us. This is
14401a5a9906SAndrea Arcangeli 		 * because MADV_DONTNEED holds the mmap_sem in read
14411a5a9906SAndrea Arcangeli 		 * mode.
14421a5a9906SAndrea Arcangeli 		 */
14431a5a9906SAndrea Arcangeli 		if (pmd_none_or_trans_huge_or_clear_bad(pmd))
14441a5a9906SAndrea Arcangeli 			goto next;
144597a89413SPeter Zijlstra 		next = zap_pte_range(tlb, vma, pmd, addr, next, details);
14461a5a9906SAndrea Arcangeli next:
144797a89413SPeter Zijlstra 		cond_resched();
144897a89413SPeter Zijlstra 	} while (pmd++, addr = next, addr != end);
144951c6f666SRobin Holt 
145051c6f666SRobin Holt 	return addr;
14511da177e4SLinus Torvalds }
14521da177e4SLinus Torvalds 
145351c6f666SRobin Holt static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1454c2febafcSKirill A. Shutemov 				struct vm_area_struct *vma, p4d_t *p4d,
14551da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
145697a89413SPeter Zijlstra 				struct zap_details *details)
14571da177e4SLinus Torvalds {
14581da177e4SLinus Torvalds 	pud_t *pud;
14591da177e4SLinus Torvalds 	unsigned long next;
14601da177e4SLinus Torvalds 
1461c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
14621da177e4SLinus Torvalds 	do {
14631da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
1464a00cc7d9SMatthew Wilcox 		if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1465a00cc7d9SMatthew Wilcox 			if (next - addr != HPAGE_PUD_SIZE) {
1466a00cc7d9SMatthew Wilcox 				VM_BUG_ON_VMA(!rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1467a00cc7d9SMatthew Wilcox 				split_huge_pud(vma, pud, addr);
1468a00cc7d9SMatthew Wilcox 			} else if (zap_huge_pud(tlb, vma, pud, addr))
1469a00cc7d9SMatthew Wilcox 				goto next;
1470a00cc7d9SMatthew Wilcox 			/* fall through */
1471a00cc7d9SMatthew Wilcox 		}
147297a89413SPeter Zijlstra 		if (pud_none_or_clear_bad(pud))
14731da177e4SLinus Torvalds 			continue;
147497a89413SPeter Zijlstra 		next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1475a00cc7d9SMatthew Wilcox next:
1476a00cc7d9SMatthew Wilcox 		cond_resched();
147797a89413SPeter Zijlstra 	} while (pud++, addr = next, addr != end);
147851c6f666SRobin Holt 
147951c6f666SRobin Holt 	return addr;
14801da177e4SLinus Torvalds }
14811da177e4SLinus Torvalds 
1482c2febafcSKirill A. Shutemov static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1483c2febafcSKirill A. Shutemov 				struct vm_area_struct *vma, pgd_t *pgd,
1484c2febafcSKirill A. Shutemov 				unsigned long addr, unsigned long end,
1485c2febafcSKirill A. Shutemov 				struct zap_details *details)
1486c2febafcSKirill A. Shutemov {
1487c2febafcSKirill A. Shutemov 	p4d_t *p4d;
1488c2febafcSKirill A. Shutemov 	unsigned long next;
1489c2febafcSKirill A. Shutemov 
1490c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
1491c2febafcSKirill A. Shutemov 	do {
1492c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
1493c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(p4d))
1494c2febafcSKirill A. Shutemov 			continue;
1495c2febafcSKirill A. Shutemov 		next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1496c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
1497c2febafcSKirill A. Shutemov 
1498c2febafcSKirill A. Shutemov 	return addr;
1499c2febafcSKirill A. Shutemov }
1500c2febafcSKirill A. Shutemov 
1501aac45363SMichal Hocko void unmap_page_range(struct mmu_gather *tlb,
150251c6f666SRobin Holt 			     struct vm_area_struct *vma,
15031da177e4SLinus Torvalds 			     unsigned long addr, unsigned long end,
150497a89413SPeter Zijlstra 			     struct zap_details *details)
15051da177e4SLinus Torvalds {
15061da177e4SLinus Torvalds 	pgd_t *pgd;
15071da177e4SLinus Torvalds 	unsigned long next;
15081da177e4SLinus Torvalds 
15091da177e4SLinus Torvalds 	BUG_ON(addr >= end);
15101da177e4SLinus Torvalds 	tlb_start_vma(tlb, vma);
15111da177e4SLinus Torvalds 	pgd = pgd_offset(vma->vm_mm, addr);
15121da177e4SLinus Torvalds 	do {
15131da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
151497a89413SPeter Zijlstra 		if (pgd_none_or_clear_bad(pgd))
15151da177e4SLinus Torvalds 			continue;
1516c2febafcSKirill A. Shutemov 		next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
151797a89413SPeter Zijlstra 	} while (pgd++, addr = next, addr != end);
15181da177e4SLinus Torvalds 	tlb_end_vma(tlb, vma);
15191da177e4SLinus Torvalds }
15201da177e4SLinus Torvalds 
1521f5cc4eefSAl Viro 
1522f5cc4eefSAl Viro static void unmap_single_vma(struct mmu_gather *tlb,
15231da177e4SLinus Torvalds 		struct vm_area_struct *vma, unsigned long start_addr,
15244f74d2c8SLinus Torvalds 		unsigned long end_addr,
15251da177e4SLinus Torvalds 		struct zap_details *details)
15261da177e4SLinus Torvalds {
1527f5cc4eefSAl Viro 	unsigned long start = max(vma->vm_start, start_addr);
15281da177e4SLinus Torvalds 	unsigned long end;
15291da177e4SLinus Torvalds 
15301da177e4SLinus Torvalds 	if (start >= vma->vm_end)
1531f5cc4eefSAl Viro 		return;
15321da177e4SLinus Torvalds 	end = min(vma->vm_end, end_addr);
15331da177e4SLinus Torvalds 	if (end <= vma->vm_start)
1534f5cc4eefSAl Viro 		return;
15351da177e4SLinus Torvalds 
1536cbc91f71SSrikar Dronamraju 	if (vma->vm_file)
1537cbc91f71SSrikar Dronamraju 		uprobe_munmap(vma, start, end);
1538cbc91f71SSrikar Dronamraju 
1539b3b9c293SKonstantin Khlebnikov 	if (unlikely(vma->vm_flags & VM_PFNMAP))
15405180da41SSuresh Siddha 		untrack_pfn(vma, 0, 0);
15412ab64037Svenkatesh.pallipadi@intel.com 
15428b2a1238SAl Viro 	if (start != end) {
154351c6f666SRobin Holt 		if (unlikely(is_vm_hugetlb_page(vma))) {
1544a137e1ccSAndi Kleen 			/*
1545a137e1ccSAndi Kleen 			 * It is undesirable to test vma->vm_file as it
1546a137e1ccSAndi Kleen 			 * should be non-null for valid hugetlb area.
1547a137e1ccSAndi Kleen 			 * However, vm_file will be NULL in the error
15487aa6b4adSDavidlohr Bueso 			 * cleanup path of mmap_region. When
1549a137e1ccSAndi Kleen 			 * hugetlbfs ->mmap method fails,
15507aa6b4adSDavidlohr Bueso 			 * mmap_region() nullifies vma->vm_file
1551a137e1ccSAndi Kleen 			 * before calling this function to clean up.
1552a137e1ccSAndi Kleen 			 * Since no pte has actually been setup, it is
1553a137e1ccSAndi Kleen 			 * safe to do nothing in this case.
1554a137e1ccSAndi Kleen 			 */
155524669e58SAneesh Kumar K.V 			if (vma->vm_file) {
155683cde9e8SDavidlohr Bueso 				i_mmap_lock_write(vma->vm_file->f_mapping);
1557d833352aSMel Gorman 				__unmap_hugepage_range_final(tlb, vma, start, end, NULL);
155883cde9e8SDavidlohr Bueso 				i_mmap_unlock_write(vma->vm_file->f_mapping);
155924669e58SAneesh Kumar K.V 			}
156051c6f666SRobin Holt 		} else
1561038c7aa1SAl Viro 			unmap_page_range(tlb, vma, start, end, details);
156297a89413SPeter Zijlstra 	}
156351c6f666SRobin Holt }
15641da177e4SLinus Torvalds 
1565f5cc4eefSAl Viro /**
1566f5cc4eefSAl Viro  * unmap_vmas - unmap a range of memory covered by a list of vma's
1567f5cc4eefSAl Viro  * @tlb: address of the caller's struct mmu_gather
1568f5cc4eefSAl Viro  * @vma: the starting vma
1569f5cc4eefSAl Viro  * @start_addr: virtual address at which to start unmapping
1570f5cc4eefSAl Viro  * @end_addr: virtual address at which to end unmapping
1571f5cc4eefSAl Viro  *
1572f5cc4eefSAl Viro  * Unmap all pages in the vma list.
1573f5cc4eefSAl Viro  *
1574f5cc4eefSAl Viro  * Only addresses between `start' and `end' will be unmapped.
1575f5cc4eefSAl Viro  *
1576f5cc4eefSAl Viro  * The VMA list must be sorted in ascending virtual address order.
1577f5cc4eefSAl Viro  *
1578f5cc4eefSAl Viro  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1579f5cc4eefSAl Viro  * range after unmap_vmas() returns.  So the only responsibility here is to
1580f5cc4eefSAl Viro  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1581f5cc4eefSAl Viro  * drops the lock and schedules.
1582f5cc4eefSAl Viro  */
1583f5cc4eefSAl Viro void unmap_vmas(struct mmu_gather *tlb,
1584f5cc4eefSAl Viro 		struct vm_area_struct *vma, unsigned long start_addr,
15854f74d2c8SLinus Torvalds 		unsigned long end_addr)
1586f5cc4eefSAl Viro {
1587f5cc4eefSAl Viro 	struct mm_struct *mm = vma->vm_mm;
1588f5cc4eefSAl Viro 
1589f5cc4eefSAl Viro 	mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1590f5cc4eefSAl Viro 	for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
15914f74d2c8SLinus Torvalds 		unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1592cddb8a5cSAndrea Arcangeli 	mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
15931da177e4SLinus Torvalds }
15941da177e4SLinus Torvalds 
15951da177e4SLinus Torvalds /**
15961da177e4SLinus Torvalds  * zap_page_range - remove user pages in a given range
15971da177e4SLinus Torvalds  * @vma: vm_area_struct holding the applicable pages
1598eb4546bbSRandy Dunlap  * @start: starting address of pages to zap
15991da177e4SLinus Torvalds  * @size: number of bytes to zap
1600f5cc4eefSAl Viro  *
1601f5cc4eefSAl Viro  * Caller must protect the VMA list
16021da177e4SLinus Torvalds  */
16037e027b14SLinus Torvalds void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1604ecf1385dSKirill A. Shutemov 		unsigned long size)
16051da177e4SLinus Torvalds {
16061da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
1607d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
16087e027b14SLinus Torvalds 	unsigned long end = start + size;
16091da177e4SLinus Torvalds 
16101da177e4SLinus Torvalds 	lru_add_drain();
16112b047252SLinus Torvalds 	tlb_gather_mmu(&tlb, mm, start, end);
1612365e9c87SHugh Dickins 	update_hiwater_rss(mm);
16137e027b14SLinus Torvalds 	mmu_notifier_invalidate_range_start(mm, start, end);
16144647706eSMel Gorman 	for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
1615ecf1385dSKirill A. Shutemov 		unmap_single_vma(&tlb, vma, start, end, NULL);
16164647706eSMel Gorman 
16174647706eSMel Gorman 		/*
16184647706eSMel Gorman 		 * zap_page_range does not specify whether mmap_sem should be
16194647706eSMel Gorman 		 * held for read or write. That allows parallel zap_page_range
16204647706eSMel Gorman 		 * operations to unmap a PTE and defer a flush meaning that
16214647706eSMel Gorman 		 * this call observes pte_none and fails to flush the TLB.
16224647706eSMel Gorman 		 * Rather than adding a complex API, ensure that no stale
16234647706eSMel Gorman 		 * TLB entries exist when this call returns.
16244647706eSMel Gorman 		 */
16254647706eSMel Gorman 		flush_tlb_range(vma, start, end);
16264647706eSMel Gorman 	}
16274647706eSMel Gorman 
16287e027b14SLinus Torvalds 	mmu_notifier_invalidate_range_end(mm, start, end);
16297e027b14SLinus Torvalds 	tlb_finish_mmu(&tlb, start, end);
16301da177e4SLinus Torvalds }
16311da177e4SLinus Torvalds 
1632c627f9ccSJack Steiner /**
1633f5cc4eefSAl Viro  * zap_page_range_single - remove user pages in a given range
1634f5cc4eefSAl Viro  * @vma: vm_area_struct holding the applicable pages
1635f5cc4eefSAl Viro  * @address: starting address of pages to zap
1636f5cc4eefSAl Viro  * @size: number of bytes to zap
16378a5f14a2SKirill A. Shutemov  * @details: details of shared cache invalidation
1638f5cc4eefSAl Viro  *
1639f5cc4eefSAl Viro  * The range must fit into one VMA.
1640f5cc4eefSAl Viro  */
1641f5cc4eefSAl Viro static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1642f5cc4eefSAl Viro 		unsigned long size, struct zap_details *details)
1643f5cc4eefSAl Viro {
1644f5cc4eefSAl Viro 	struct mm_struct *mm = vma->vm_mm;
1645f5cc4eefSAl Viro 	struct mmu_gather tlb;
1646f5cc4eefSAl Viro 	unsigned long end = address + size;
1647f5cc4eefSAl Viro 
1648f5cc4eefSAl Viro 	lru_add_drain();
16492b047252SLinus Torvalds 	tlb_gather_mmu(&tlb, mm, address, end);
1650f5cc4eefSAl Viro 	update_hiwater_rss(mm);
1651f5cc4eefSAl Viro 	mmu_notifier_invalidate_range_start(mm, address, end);
16524f74d2c8SLinus Torvalds 	unmap_single_vma(&tlb, vma, address, end, details);
1653f5cc4eefSAl Viro 	mmu_notifier_invalidate_range_end(mm, address, end);
1654f5cc4eefSAl Viro 	tlb_finish_mmu(&tlb, address, end);
16551da177e4SLinus Torvalds }
16561da177e4SLinus Torvalds 
1657c627f9ccSJack Steiner /**
1658c627f9ccSJack Steiner  * zap_vma_ptes - remove ptes mapping the vma
1659c627f9ccSJack Steiner  * @vma: vm_area_struct holding ptes to be zapped
1660c627f9ccSJack Steiner  * @address: starting address of pages to zap
1661c627f9ccSJack Steiner  * @size: number of bytes to zap
1662c627f9ccSJack Steiner  *
1663c627f9ccSJack Steiner  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1664c627f9ccSJack Steiner  *
1665c627f9ccSJack Steiner  * The entire address range must be fully contained within the vma.
1666c627f9ccSJack Steiner  *
1667c627f9ccSJack Steiner  * Returns 0 if successful.
1668c627f9ccSJack Steiner  */
1669c627f9ccSJack Steiner int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1670c627f9ccSJack Steiner 		unsigned long size)
1671c627f9ccSJack Steiner {
1672c627f9ccSJack Steiner 	if (address < vma->vm_start || address + size > vma->vm_end ||
1673c627f9ccSJack Steiner 	    		!(vma->vm_flags & VM_PFNMAP))
1674c627f9ccSJack Steiner 		return -1;
1675f5cc4eefSAl Viro 	zap_page_range_single(vma, address, size, NULL);
1676c627f9ccSJack Steiner 	return 0;
1677c627f9ccSJack Steiner }
1678c627f9ccSJack Steiner EXPORT_SYMBOL_GPL(zap_vma_ptes);
1679c627f9ccSJack Steiner 
168025ca1d6cSNamhyung Kim pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1681920c7a5dSHarvey Harrison 			spinlock_t **ptl)
1682c9cfcddfSLinus Torvalds {
1683c2febafcSKirill A. Shutemov 	pgd_t *pgd;
1684c2febafcSKirill A. Shutemov 	p4d_t *p4d;
1685c2febafcSKirill A. Shutemov 	pud_t *pud;
1686c2febafcSKirill A. Shutemov 	pmd_t *pmd;
1687c2febafcSKirill A. Shutemov 
1688c2febafcSKirill A. Shutemov 	pgd = pgd_offset(mm, addr);
1689c2febafcSKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, addr);
1690c2febafcSKirill A. Shutemov 	if (!p4d)
1691c2febafcSKirill A. Shutemov 		return NULL;
1692c2febafcSKirill A. Shutemov 	pud = pud_alloc(mm, p4d, addr);
1693c2febafcSKirill A. Shutemov 	if (!pud)
1694c2febafcSKirill A. Shutemov 		return NULL;
1695c2febafcSKirill A. Shutemov 	pmd = pmd_alloc(mm, pud, addr);
1696c2febafcSKirill A. Shutemov 	if (!pmd)
1697c2febafcSKirill A. Shutemov 		return NULL;
1698c2febafcSKirill A. Shutemov 
1699f66055abSAndrea Arcangeli 	VM_BUG_ON(pmd_trans_huge(*pmd));
1700c9cfcddfSLinus Torvalds 	return pte_alloc_map_lock(mm, pmd, addr, ptl);
1701c9cfcddfSLinus Torvalds }
1702c9cfcddfSLinus Torvalds 
17031da177e4SLinus Torvalds /*
1704238f58d8SLinus Torvalds  * This is the old fallback for page remapping.
1705238f58d8SLinus Torvalds  *
1706238f58d8SLinus Torvalds  * For historical reasons, it only allows reserved pages. Only
1707238f58d8SLinus Torvalds  * old drivers should use this, and they needed to mark their
1708238f58d8SLinus Torvalds  * pages reserved for the old functions anyway.
1709238f58d8SLinus Torvalds  */
1710423bad60SNick Piggin static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1711423bad60SNick Piggin 			struct page *page, pgprot_t prot)
1712238f58d8SLinus Torvalds {
1713423bad60SNick Piggin 	struct mm_struct *mm = vma->vm_mm;
1714238f58d8SLinus Torvalds 	int retval;
1715238f58d8SLinus Torvalds 	pte_t *pte;
1716238f58d8SLinus Torvalds 	spinlock_t *ptl;
1717238f58d8SLinus Torvalds 
1718238f58d8SLinus Torvalds 	retval = -EINVAL;
1719a145dd41SLinus Torvalds 	if (PageAnon(page))
17205b4e655eSKAMEZAWA Hiroyuki 		goto out;
1721238f58d8SLinus Torvalds 	retval = -ENOMEM;
1722238f58d8SLinus Torvalds 	flush_dcache_page(page);
1723c9cfcddfSLinus Torvalds 	pte = get_locked_pte(mm, addr, &ptl);
1724238f58d8SLinus Torvalds 	if (!pte)
17255b4e655eSKAMEZAWA Hiroyuki 		goto out;
1726238f58d8SLinus Torvalds 	retval = -EBUSY;
1727238f58d8SLinus Torvalds 	if (!pte_none(*pte))
1728238f58d8SLinus Torvalds 		goto out_unlock;
1729238f58d8SLinus Torvalds 
1730238f58d8SLinus Torvalds 	/* Ok, finally just insert the thing.. */
1731238f58d8SLinus Torvalds 	get_page(page);
1732eca56ff9SJerome Marchand 	inc_mm_counter_fast(mm, mm_counter_file(page));
1733dd78feddSKirill A. Shutemov 	page_add_file_rmap(page, false);
1734238f58d8SLinus Torvalds 	set_pte_at(mm, addr, pte, mk_pte(page, prot));
1735238f58d8SLinus Torvalds 
1736238f58d8SLinus Torvalds 	retval = 0;
17378a9f3ccdSBalbir Singh 	pte_unmap_unlock(pte, ptl);
17388a9f3ccdSBalbir Singh 	return retval;
1739238f58d8SLinus Torvalds out_unlock:
1740238f58d8SLinus Torvalds 	pte_unmap_unlock(pte, ptl);
1741238f58d8SLinus Torvalds out:
1742238f58d8SLinus Torvalds 	return retval;
1743238f58d8SLinus Torvalds }
1744238f58d8SLinus Torvalds 
1745bfa5bf6dSRolf Eike Beer /**
1746bfa5bf6dSRolf Eike Beer  * vm_insert_page - insert single page into user vma
1747bfa5bf6dSRolf Eike Beer  * @vma: user vma to map to
1748bfa5bf6dSRolf Eike Beer  * @addr: target user address of this page
1749bfa5bf6dSRolf Eike Beer  * @page: source kernel page
1750bfa5bf6dSRolf Eike Beer  *
1751a145dd41SLinus Torvalds  * This allows drivers to insert individual pages they've allocated
1752a145dd41SLinus Torvalds  * into a user vma.
1753a145dd41SLinus Torvalds  *
1754a145dd41SLinus Torvalds  * The page has to be a nice clean _individual_ kernel allocation.
1755a145dd41SLinus Torvalds  * If you allocate a compound page, you need to have marked it as
1756a145dd41SLinus Torvalds  * such (__GFP_COMP), or manually just split the page up yourself
17578dfcc9baSNick Piggin  * (see split_page()).
1758a145dd41SLinus Torvalds  *
1759a145dd41SLinus Torvalds  * NOTE! Traditionally this was done with "remap_pfn_range()" which
1760a145dd41SLinus Torvalds  * took an arbitrary page protection parameter. This doesn't allow
1761a145dd41SLinus Torvalds  * that. Your vma protection will have to be set up correctly, which
1762a145dd41SLinus Torvalds  * means that if you want a shared writable mapping, you'd better
1763a145dd41SLinus Torvalds  * ask for a shared writable mapping!
1764a145dd41SLinus Torvalds  *
1765a145dd41SLinus Torvalds  * The page does not need to be reserved.
17664b6e1e37SKonstantin Khlebnikov  *
17674b6e1e37SKonstantin Khlebnikov  * Usually this function is called from f_op->mmap() handler
17684b6e1e37SKonstantin Khlebnikov  * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
17694b6e1e37SKonstantin Khlebnikov  * Caller must set VM_MIXEDMAP on vma if it wants to call this
17704b6e1e37SKonstantin Khlebnikov  * function from other places, for example from page-fault handler.
1771a145dd41SLinus Torvalds  */
1772423bad60SNick Piggin int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1773423bad60SNick Piggin 			struct page *page)
1774a145dd41SLinus Torvalds {
1775a145dd41SLinus Torvalds 	if (addr < vma->vm_start || addr >= vma->vm_end)
1776a145dd41SLinus Torvalds 		return -EFAULT;
1777a145dd41SLinus Torvalds 	if (!page_count(page))
1778a145dd41SLinus Torvalds 		return -EINVAL;
17794b6e1e37SKonstantin Khlebnikov 	if (!(vma->vm_flags & VM_MIXEDMAP)) {
17804b6e1e37SKonstantin Khlebnikov 		BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
17814b6e1e37SKonstantin Khlebnikov 		BUG_ON(vma->vm_flags & VM_PFNMAP);
17824b6e1e37SKonstantin Khlebnikov 		vma->vm_flags |= VM_MIXEDMAP;
17834b6e1e37SKonstantin Khlebnikov 	}
1784423bad60SNick Piggin 	return insert_page(vma, addr, page, vma->vm_page_prot);
1785a145dd41SLinus Torvalds }
1786e3c3374fSLinus Torvalds EXPORT_SYMBOL(vm_insert_page);
1787a145dd41SLinus Torvalds 
1788423bad60SNick Piggin static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1789b2770da6SRoss Zwisler 			pfn_t pfn, pgprot_t prot, bool mkwrite)
1790423bad60SNick Piggin {
1791423bad60SNick Piggin 	struct mm_struct *mm = vma->vm_mm;
1792423bad60SNick Piggin 	int retval;
1793423bad60SNick Piggin 	pte_t *pte, entry;
1794423bad60SNick Piggin 	spinlock_t *ptl;
1795423bad60SNick Piggin 
1796423bad60SNick Piggin 	retval = -ENOMEM;
1797423bad60SNick Piggin 	pte = get_locked_pte(mm, addr, &ptl);
1798423bad60SNick Piggin 	if (!pte)
1799423bad60SNick Piggin 		goto out;
1800423bad60SNick Piggin 	retval = -EBUSY;
1801b2770da6SRoss Zwisler 	if (!pte_none(*pte)) {
1802b2770da6SRoss Zwisler 		if (mkwrite) {
1803b2770da6SRoss Zwisler 			/*
1804b2770da6SRoss Zwisler 			 * For read faults on private mappings the PFN passed
1805b2770da6SRoss Zwisler 			 * in may not match the PFN we have mapped if the
1806b2770da6SRoss Zwisler 			 * mapped PFN is a writeable COW page.  In the mkwrite
1807b2770da6SRoss Zwisler 			 * case we are creating a writable PTE for a shared
1808b2770da6SRoss Zwisler 			 * mapping and we expect the PFNs to match.
1809b2770da6SRoss Zwisler 			 */
1810b2770da6SRoss Zwisler 			if (WARN_ON_ONCE(pte_pfn(*pte) != pfn_t_to_pfn(pfn)))
1811423bad60SNick Piggin 				goto out_unlock;
1812b2770da6SRoss Zwisler 			entry = *pte;
1813b2770da6SRoss Zwisler 			goto out_mkwrite;
1814b2770da6SRoss Zwisler 		} else
1815b2770da6SRoss Zwisler 			goto out_unlock;
1816b2770da6SRoss Zwisler 	}
1817423bad60SNick Piggin 
1818423bad60SNick Piggin 	/* Ok, finally just insert the thing.. */
181901c8f1c4SDan Williams 	if (pfn_t_devmap(pfn))
182001c8f1c4SDan Williams 		entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
182101c8f1c4SDan Williams 	else
182201c8f1c4SDan Williams 		entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1823b2770da6SRoss Zwisler 
1824b2770da6SRoss Zwisler out_mkwrite:
1825b2770da6SRoss Zwisler 	if (mkwrite) {
1826b2770da6SRoss Zwisler 		entry = pte_mkyoung(entry);
1827b2770da6SRoss Zwisler 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1828b2770da6SRoss Zwisler 	}
1829b2770da6SRoss Zwisler 
1830423bad60SNick Piggin 	set_pte_at(mm, addr, pte, entry);
18314b3073e1SRussell King 	update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1832423bad60SNick Piggin 
1833423bad60SNick Piggin 	retval = 0;
1834423bad60SNick Piggin out_unlock:
1835423bad60SNick Piggin 	pte_unmap_unlock(pte, ptl);
1836423bad60SNick Piggin out:
1837423bad60SNick Piggin 	return retval;
1838423bad60SNick Piggin }
1839423bad60SNick Piggin 
1840e0dc0d8fSNick Piggin /**
1841e0dc0d8fSNick Piggin  * vm_insert_pfn - insert single pfn into user vma
1842e0dc0d8fSNick Piggin  * @vma: user vma to map to
1843e0dc0d8fSNick Piggin  * @addr: target user address of this page
1844e0dc0d8fSNick Piggin  * @pfn: source kernel pfn
1845e0dc0d8fSNick Piggin  *
1846c462f179SRobert P. J. Day  * Similar to vm_insert_page, this allows drivers to insert individual pages
1847e0dc0d8fSNick Piggin  * they've allocated into a user vma. Same comments apply.
1848e0dc0d8fSNick Piggin  *
1849e0dc0d8fSNick Piggin  * This function should only be called from a vm_ops->fault handler, and
1850e0dc0d8fSNick Piggin  * in that case the handler should return NULL.
18510d71d10aSNick Piggin  *
18520d71d10aSNick Piggin  * vma cannot be a COW mapping.
18530d71d10aSNick Piggin  *
18540d71d10aSNick Piggin  * As this is called only for pages that do not currently exist, we
18550d71d10aSNick Piggin  * do not need to flush old virtual caches or the TLB.
1856e0dc0d8fSNick Piggin  */
1857e0dc0d8fSNick Piggin int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1858e0dc0d8fSNick Piggin 			unsigned long pfn)
1859e0dc0d8fSNick Piggin {
18601745cbc5SAndy Lutomirski 	return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
18611745cbc5SAndy Lutomirski }
18621745cbc5SAndy Lutomirski EXPORT_SYMBOL(vm_insert_pfn);
18631745cbc5SAndy Lutomirski 
18641745cbc5SAndy Lutomirski /**
18651745cbc5SAndy Lutomirski  * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
18661745cbc5SAndy Lutomirski  * @vma: user vma to map to
18671745cbc5SAndy Lutomirski  * @addr: target user address of this page
18681745cbc5SAndy Lutomirski  * @pfn: source kernel pfn
18691745cbc5SAndy Lutomirski  * @pgprot: pgprot flags for the inserted page
18701745cbc5SAndy Lutomirski  *
18711745cbc5SAndy Lutomirski  * This is exactly like vm_insert_pfn, except that it allows drivers to
18721745cbc5SAndy Lutomirski  * to override pgprot on a per-page basis.
18731745cbc5SAndy Lutomirski  *
18741745cbc5SAndy Lutomirski  * This only makes sense for IO mappings, and it makes no sense for
18751745cbc5SAndy Lutomirski  * cow mappings.  In general, using multiple vmas is preferable;
18761745cbc5SAndy Lutomirski  * vm_insert_pfn_prot should only be used if using multiple VMAs is
18771745cbc5SAndy Lutomirski  * impractical.
18781745cbc5SAndy Lutomirski  */
18791745cbc5SAndy Lutomirski int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
18801745cbc5SAndy Lutomirski 			unsigned long pfn, pgprot_t pgprot)
18811745cbc5SAndy Lutomirski {
18822ab64037Svenkatesh.pallipadi@intel.com 	int ret;
18837e675137SNick Piggin 	/*
18847e675137SNick Piggin 	 * Technically, architectures with pte_special can avoid all these
18857e675137SNick Piggin 	 * restrictions (same for remap_pfn_range).  However we would like
18867e675137SNick Piggin 	 * consistency in testing and feature parity among all, so we should
18877e675137SNick Piggin 	 * try to keep these invariants in place for everybody.
18887e675137SNick Piggin 	 */
1889b379d790SJared Hulbert 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1890b379d790SJared Hulbert 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1891b379d790SJared Hulbert 						(VM_PFNMAP|VM_MIXEDMAP));
1892b379d790SJared Hulbert 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1893b379d790SJared Hulbert 	BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1894e0dc0d8fSNick Piggin 
1895423bad60SNick Piggin 	if (addr < vma->vm_start || addr >= vma->vm_end)
1896423bad60SNick Piggin 		return -EFAULT;
1897308a047cSBorislav Petkov 
1898308a047cSBorislav Petkov 	track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
18992ab64037Svenkatesh.pallipadi@intel.com 
1900b2770da6SRoss Zwisler 	ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
1901b2770da6SRoss Zwisler 			false);
19022ab64037Svenkatesh.pallipadi@intel.com 
19032ab64037Svenkatesh.pallipadi@intel.com 	return ret;
1904e0dc0d8fSNick Piggin }
19051745cbc5SAndy Lutomirski EXPORT_SYMBOL(vm_insert_pfn_prot);
1906e0dc0d8fSNick Piggin 
1907b2770da6SRoss Zwisler static int __vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1908b2770da6SRoss Zwisler 			pfn_t pfn, bool mkwrite)
1909423bad60SNick Piggin {
191087744ab3SDan Williams 	pgprot_t pgprot = vma->vm_page_prot;
191187744ab3SDan Williams 
1912423bad60SNick Piggin 	BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1913423bad60SNick Piggin 
1914423bad60SNick Piggin 	if (addr < vma->vm_start || addr >= vma->vm_end)
1915423bad60SNick Piggin 		return -EFAULT;
1916308a047cSBorislav Petkov 
1917308a047cSBorislav Petkov 	track_pfn_insert(vma, &pgprot, pfn);
1918423bad60SNick Piggin 
1919423bad60SNick Piggin 	/*
1920423bad60SNick Piggin 	 * If we don't have pte special, then we have to use the pfn_valid()
1921423bad60SNick Piggin 	 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1922423bad60SNick Piggin 	 * refcount the page if pfn_valid is true (hence insert_page rather
192362eede62SHugh Dickins 	 * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
192462eede62SHugh Dickins 	 * without pte special, it would there be refcounted as a normal page.
1925423bad60SNick Piggin 	 */
192603fc2da6SDan Williams 	if (!HAVE_PTE_SPECIAL && !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1927423bad60SNick Piggin 		struct page *page;
1928423bad60SNick Piggin 
192903fc2da6SDan Williams 		/*
193003fc2da6SDan Williams 		 * At this point we are committed to insert_page()
193103fc2da6SDan Williams 		 * regardless of whether the caller specified flags that
193203fc2da6SDan Williams 		 * result in pfn_t_has_page() == false.
193303fc2da6SDan Williams 		 */
193403fc2da6SDan Williams 		page = pfn_to_page(pfn_t_to_pfn(pfn));
193587744ab3SDan Williams 		return insert_page(vma, addr, page, pgprot);
1936423bad60SNick Piggin 	}
1937b2770da6SRoss Zwisler 	return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
1938b2770da6SRoss Zwisler }
1939b2770da6SRoss Zwisler 
1940b2770da6SRoss Zwisler int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1941b2770da6SRoss Zwisler 			pfn_t pfn)
1942b2770da6SRoss Zwisler {
1943b2770da6SRoss Zwisler 	return __vm_insert_mixed(vma, addr, pfn, false);
1944b2770da6SRoss Zwisler 
1945423bad60SNick Piggin }
1946423bad60SNick Piggin EXPORT_SYMBOL(vm_insert_mixed);
1947423bad60SNick Piggin 
1948b2770da6SRoss Zwisler int vm_insert_mixed_mkwrite(struct vm_area_struct *vma, unsigned long addr,
1949b2770da6SRoss Zwisler 			pfn_t pfn)
1950b2770da6SRoss Zwisler {
1951b2770da6SRoss Zwisler 	return __vm_insert_mixed(vma, addr, pfn, true);
1952b2770da6SRoss Zwisler }
1953b2770da6SRoss Zwisler EXPORT_SYMBOL(vm_insert_mixed_mkwrite);
1954b2770da6SRoss Zwisler 
1955a145dd41SLinus Torvalds /*
19561da177e4SLinus Torvalds  * maps a range of physical memory into the requested pages. the old
19571da177e4SLinus Torvalds  * mappings are removed. any references to nonexistent pages results
19581da177e4SLinus Torvalds  * in null mappings (currently treated as "copy-on-access")
19591da177e4SLinus Torvalds  */
19601da177e4SLinus Torvalds static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
19611da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
19621da177e4SLinus Torvalds 			unsigned long pfn, pgprot_t prot)
19631da177e4SLinus Torvalds {
19641da177e4SLinus Torvalds 	pte_t *pte;
1965c74df32cSHugh Dickins 	spinlock_t *ptl;
19661da177e4SLinus Torvalds 
1967c74df32cSHugh Dickins 	pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
19681da177e4SLinus Torvalds 	if (!pte)
19691da177e4SLinus Torvalds 		return -ENOMEM;
19706606c3e0SZachary Amsden 	arch_enter_lazy_mmu_mode();
19711da177e4SLinus Torvalds 	do {
19721da177e4SLinus Torvalds 		BUG_ON(!pte_none(*pte));
19737e675137SNick Piggin 		set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
19741da177e4SLinus Torvalds 		pfn++;
19751da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
19766606c3e0SZachary Amsden 	arch_leave_lazy_mmu_mode();
1977c74df32cSHugh Dickins 	pte_unmap_unlock(pte - 1, ptl);
19781da177e4SLinus Torvalds 	return 0;
19791da177e4SLinus Torvalds }
19801da177e4SLinus Torvalds 
19811da177e4SLinus Torvalds static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
19821da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
19831da177e4SLinus Torvalds 			unsigned long pfn, pgprot_t prot)
19841da177e4SLinus Torvalds {
19851da177e4SLinus Torvalds 	pmd_t *pmd;
19861da177e4SLinus Torvalds 	unsigned long next;
19871da177e4SLinus Torvalds 
19881da177e4SLinus Torvalds 	pfn -= addr >> PAGE_SHIFT;
19891da177e4SLinus Torvalds 	pmd = pmd_alloc(mm, pud, addr);
19901da177e4SLinus Torvalds 	if (!pmd)
19911da177e4SLinus Torvalds 		return -ENOMEM;
1992f66055abSAndrea Arcangeli 	VM_BUG_ON(pmd_trans_huge(*pmd));
19931da177e4SLinus Torvalds 	do {
19941da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
19951da177e4SLinus Torvalds 		if (remap_pte_range(mm, pmd, addr, next,
19961da177e4SLinus Torvalds 				pfn + (addr >> PAGE_SHIFT), prot))
19971da177e4SLinus Torvalds 			return -ENOMEM;
19981da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
19991da177e4SLinus Torvalds 	return 0;
20001da177e4SLinus Torvalds }
20011da177e4SLinus Torvalds 
2002c2febafcSKirill A. Shutemov static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
20031da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
20041da177e4SLinus Torvalds 			unsigned long pfn, pgprot_t prot)
20051da177e4SLinus Torvalds {
20061da177e4SLinus Torvalds 	pud_t *pud;
20071da177e4SLinus Torvalds 	unsigned long next;
20081da177e4SLinus Torvalds 
20091da177e4SLinus Torvalds 	pfn -= addr >> PAGE_SHIFT;
2010c2febafcSKirill A. Shutemov 	pud = pud_alloc(mm, p4d, addr);
20111da177e4SLinus Torvalds 	if (!pud)
20121da177e4SLinus Torvalds 		return -ENOMEM;
20131da177e4SLinus Torvalds 	do {
20141da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
20151da177e4SLinus Torvalds 		if (remap_pmd_range(mm, pud, addr, next,
20161da177e4SLinus Torvalds 				pfn + (addr >> PAGE_SHIFT), prot))
20171da177e4SLinus Torvalds 			return -ENOMEM;
20181da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
20191da177e4SLinus Torvalds 	return 0;
20201da177e4SLinus Torvalds }
20211da177e4SLinus Torvalds 
2022c2febafcSKirill A. Shutemov static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2023c2febafcSKirill A. Shutemov 			unsigned long addr, unsigned long end,
2024c2febafcSKirill A. Shutemov 			unsigned long pfn, pgprot_t prot)
2025c2febafcSKirill A. Shutemov {
2026c2febafcSKirill A. Shutemov 	p4d_t *p4d;
2027c2febafcSKirill A. Shutemov 	unsigned long next;
2028c2febafcSKirill A. Shutemov 
2029c2febafcSKirill A. Shutemov 	pfn -= addr >> PAGE_SHIFT;
2030c2febafcSKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, addr);
2031c2febafcSKirill A. Shutemov 	if (!p4d)
2032c2febafcSKirill A. Shutemov 		return -ENOMEM;
2033c2febafcSKirill A. Shutemov 	do {
2034c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
2035c2febafcSKirill A. Shutemov 		if (remap_pud_range(mm, p4d, addr, next,
2036c2febafcSKirill A. Shutemov 				pfn + (addr >> PAGE_SHIFT), prot))
2037c2febafcSKirill A. Shutemov 			return -ENOMEM;
2038c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
2039c2febafcSKirill A. Shutemov 	return 0;
2040c2febafcSKirill A. Shutemov }
2041c2febafcSKirill A. Shutemov 
2042bfa5bf6dSRolf Eike Beer /**
2043bfa5bf6dSRolf Eike Beer  * remap_pfn_range - remap kernel memory to userspace
2044bfa5bf6dSRolf Eike Beer  * @vma: user vma to map to
2045bfa5bf6dSRolf Eike Beer  * @addr: target user address to start at
2046bfa5bf6dSRolf Eike Beer  * @pfn: physical address of kernel memory
2047bfa5bf6dSRolf Eike Beer  * @size: size of map area
2048bfa5bf6dSRolf Eike Beer  * @prot: page protection flags for this mapping
2049bfa5bf6dSRolf Eike Beer  *
2050bfa5bf6dSRolf Eike Beer  *  Note: this is only safe if the mm semaphore is held when called.
2051bfa5bf6dSRolf Eike Beer  */
20521da177e4SLinus Torvalds int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
20531da177e4SLinus Torvalds 		    unsigned long pfn, unsigned long size, pgprot_t prot)
20541da177e4SLinus Torvalds {
20551da177e4SLinus Torvalds 	pgd_t *pgd;
20561da177e4SLinus Torvalds 	unsigned long next;
20572d15cab8SHugh Dickins 	unsigned long end = addr + PAGE_ALIGN(size);
20581da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
2059d5957d2fSYongji Xie 	unsigned long remap_pfn = pfn;
20601da177e4SLinus Torvalds 	int err;
20611da177e4SLinus Torvalds 
20621da177e4SLinus Torvalds 	/*
20631da177e4SLinus Torvalds 	 * Physically remapped pages are special. Tell the
20641da177e4SLinus Torvalds 	 * rest of the world about it:
20651da177e4SLinus Torvalds 	 *   VM_IO tells people not to look at these pages
20661da177e4SLinus Torvalds 	 *	(accesses can have side effects).
20676aab341eSLinus Torvalds 	 *   VM_PFNMAP tells the core MM that the base pages are just
20686aab341eSLinus Torvalds 	 *	raw PFN mappings, and do not have a "struct page" associated
20696aab341eSLinus Torvalds 	 *	with them.
2070314e51b9SKonstantin Khlebnikov 	 *   VM_DONTEXPAND
2071314e51b9SKonstantin Khlebnikov 	 *      Disable vma merging and expanding with mremap().
2072314e51b9SKonstantin Khlebnikov 	 *   VM_DONTDUMP
2073314e51b9SKonstantin Khlebnikov 	 *      Omit vma from core dump, even when VM_IO turned off.
2074fb155c16SLinus Torvalds 	 *
2075fb155c16SLinus Torvalds 	 * There's a horrible special case to handle copy-on-write
2076fb155c16SLinus Torvalds 	 * behaviour that some programs depend on. We mark the "original"
2077fb155c16SLinus Torvalds 	 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2078b3b9c293SKonstantin Khlebnikov 	 * See vm_normal_page() for details.
20791da177e4SLinus Torvalds 	 */
2080b3b9c293SKonstantin Khlebnikov 	if (is_cow_mapping(vma->vm_flags)) {
2081b3b9c293SKonstantin Khlebnikov 		if (addr != vma->vm_start || end != vma->vm_end)
2082b3b9c293SKonstantin Khlebnikov 			return -EINVAL;
20836aab341eSLinus Torvalds 		vma->vm_pgoff = pfn;
2084b3b9c293SKonstantin Khlebnikov 	}
2085b3b9c293SKonstantin Khlebnikov 
2086d5957d2fSYongji Xie 	err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2087b3b9c293SKonstantin Khlebnikov 	if (err)
20883c8bb73aSvenkatesh.pallipadi@intel.com 		return -EINVAL;
2089fb155c16SLinus Torvalds 
2090314e51b9SKonstantin Khlebnikov 	vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
20911da177e4SLinus Torvalds 
20921da177e4SLinus Torvalds 	BUG_ON(addr >= end);
20931da177e4SLinus Torvalds 	pfn -= addr >> PAGE_SHIFT;
20941da177e4SLinus Torvalds 	pgd = pgd_offset(mm, addr);
20951da177e4SLinus Torvalds 	flush_cache_range(vma, addr, end);
20961da177e4SLinus Torvalds 	do {
20971da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
2098c2febafcSKirill A. Shutemov 		err = remap_p4d_range(mm, pgd, addr, next,
20991da177e4SLinus Torvalds 				pfn + (addr >> PAGE_SHIFT), prot);
21001da177e4SLinus Torvalds 		if (err)
21011da177e4SLinus Torvalds 			break;
21021da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
21032ab64037Svenkatesh.pallipadi@intel.com 
21042ab64037Svenkatesh.pallipadi@intel.com 	if (err)
2105d5957d2fSYongji Xie 		untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
21062ab64037Svenkatesh.pallipadi@intel.com 
21071da177e4SLinus Torvalds 	return err;
21081da177e4SLinus Torvalds }
21091da177e4SLinus Torvalds EXPORT_SYMBOL(remap_pfn_range);
21101da177e4SLinus Torvalds 
2111b4cbb197SLinus Torvalds /**
2112b4cbb197SLinus Torvalds  * vm_iomap_memory - remap memory to userspace
2113b4cbb197SLinus Torvalds  * @vma: user vma to map to
2114b4cbb197SLinus Torvalds  * @start: start of area
2115b4cbb197SLinus Torvalds  * @len: size of area
2116b4cbb197SLinus Torvalds  *
2117b4cbb197SLinus Torvalds  * This is a simplified io_remap_pfn_range() for common driver use. The
2118b4cbb197SLinus Torvalds  * driver just needs to give us the physical memory range to be mapped,
2119b4cbb197SLinus Torvalds  * we'll figure out the rest from the vma information.
2120b4cbb197SLinus Torvalds  *
2121b4cbb197SLinus Torvalds  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2122b4cbb197SLinus Torvalds  * whatever write-combining details or similar.
2123b4cbb197SLinus Torvalds  */
2124b4cbb197SLinus Torvalds int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2125b4cbb197SLinus Torvalds {
2126b4cbb197SLinus Torvalds 	unsigned long vm_len, pfn, pages;
2127b4cbb197SLinus Torvalds 
2128b4cbb197SLinus Torvalds 	/* Check that the physical memory area passed in looks valid */
2129b4cbb197SLinus Torvalds 	if (start + len < start)
2130b4cbb197SLinus Torvalds 		return -EINVAL;
2131b4cbb197SLinus Torvalds 	/*
2132b4cbb197SLinus Torvalds 	 * You *really* shouldn't map things that aren't page-aligned,
2133b4cbb197SLinus Torvalds 	 * but we've historically allowed it because IO memory might
2134b4cbb197SLinus Torvalds 	 * just have smaller alignment.
2135b4cbb197SLinus Torvalds 	 */
2136b4cbb197SLinus Torvalds 	len += start & ~PAGE_MASK;
2137b4cbb197SLinus Torvalds 	pfn = start >> PAGE_SHIFT;
2138b4cbb197SLinus Torvalds 	pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2139b4cbb197SLinus Torvalds 	if (pfn + pages < pfn)
2140b4cbb197SLinus Torvalds 		return -EINVAL;
2141b4cbb197SLinus Torvalds 
2142b4cbb197SLinus Torvalds 	/* We start the mapping 'vm_pgoff' pages into the area */
2143b4cbb197SLinus Torvalds 	if (vma->vm_pgoff > pages)
2144b4cbb197SLinus Torvalds 		return -EINVAL;
2145b4cbb197SLinus Torvalds 	pfn += vma->vm_pgoff;
2146b4cbb197SLinus Torvalds 	pages -= vma->vm_pgoff;
2147b4cbb197SLinus Torvalds 
2148b4cbb197SLinus Torvalds 	/* Can we fit all of the mapping? */
2149b4cbb197SLinus Torvalds 	vm_len = vma->vm_end - vma->vm_start;
2150b4cbb197SLinus Torvalds 	if (vm_len >> PAGE_SHIFT > pages)
2151b4cbb197SLinus Torvalds 		return -EINVAL;
2152b4cbb197SLinus Torvalds 
2153b4cbb197SLinus Torvalds 	/* Ok, let it rip */
2154b4cbb197SLinus Torvalds 	return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2155b4cbb197SLinus Torvalds }
2156b4cbb197SLinus Torvalds EXPORT_SYMBOL(vm_iomap_memory);
2157b4cbb197SLinus Torvalds 
2158aee16b3cSJeremy Fitzhardinge static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2159aee16b3cSJeremy Fitzhardinge 				     unsigned long addr, unsigned long end,
2160aee16b3cSJeremy Fitzhardinge 				     pte_fn_t fn, void *data)
2161aee16b3cSJeremy Fitzhardinge {
2162aee16b3cSJeremy Fitzhardinge 	pte_t *pte;
2163aee16b3cSJeremy Fitzhardinge 	int err;
21642f569afdSMartin Schwidefsky 	pgtable_t token;
216594909914SBorislav Petkov 	spinlock_t *uninitialized_var(ptl);
2166aee16b3cSJeremy Fitzhardinge 
2167aee16b3cSJeremy Fitzhardinge 	pte = (mm == &init_mm) ?
2168aee16b3cSJeremy Fitzhardinge 		pte_alloc_kernel(pmd, addr) :
2169aee16b3cSJeremy Fitzhardinge 		pte_alloc_map_lock(mm, pmd, addr, &ptl);
2170aee16b3cSJeremy Fitzhardinge 	if (!pte)
2171aee16b3cSJeremy Fitzhardinge 		return -ENOMEM;
2172aee16b3cSJeremy Fitzhardinge 
2173aee16b3cSJeremy Fitzhardinge 	BUG_ON(pmd_huge(*pmd));
2174aee16b3cSJeremy Fitzhardinge 
217538e0edb1SJeremy Fitzhardinge 	arch_enter_lazy_mmu_mode();
217638e0edb1SJeremy Fitzhardinge 
21772f569afdSMartin Schwidefsky 	token = pmd_pgtable(*pmd);
2178aee16b3cSJeremy Fitzhardinge 
2179aee16b3cSJeremy Fitzhardinge 	do {
2180c36987e2SDaisuke Nishimura 		err = fn(pte++, token, addr, data);
2181aee16b3cSJeremy Fitzhardinge 		if (err)
2182aee16b3cSJeremy Fitzhardinge 			break;
2183c36987e2SDaisuke Nishimura 	} while (addr += PAGE_SIZE, addr != end);
2184aee16b3cSJeremy Fitzhardinge 
218538e0edb1SJeremy Fitzhardinge 	arch_leave_lazy_mmu_mode();
218638e0edb1SJeremy Fitzhardinge 
2187aee16b3cSJeremy Fitzhardinge 	if (mm != &init_mm)
2188aee16b3cSJeremy Fitzhardinge 		pte_unmap_unlock(pte-1, ptl);
2189aee16b3cSJeremy Fitzhardinge 	return err;
2190aee16b3cSJeremy Fitzhardinge }
2191aee16b3cSJeremy Fitzhardinge 
2192aee16b3cSJeremy Fitzhardinge static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2193aee16b3cSJeremy Fitzhardinge 				     unsigned long addr, unsigned long end,
2194aee16b3cSJeremy Fitzhardinge 				     pte_fn_t fn, void *data)
2195aee16b3cSJeremy Fitzhardinge {
2196aee16b3cSJeremy Fitzhardinge 	pmd_t *pmd;
2197aee16b3cSJeremy Fitzhardinge 	unsigned long next;
2198aee16b3cSJeremy Fitzhardinge 	int err;
2199aee16b3cSJeremy Fitzhardinge 
2200ceb86879SAndi Kleen 	BUG_ON(pud_huge(*pud));
2201ceb86879SAndi Kleen 
2202aee16b3cSJeremy Fitzhardinge 	pmd = pmd_alloc(mm, pud, addr);
2203aee16b3cSJeremy Fitzhardinge 	if (!pmd)
2204aee16b3cSJeremy Fitzhardinge 		return -ENOMEM;
2205aee16b3cSJeremy Fitzhardinge 	do {
2206aee16b3cSJeremy Fitzhardinge 		next = pmd_addr_end(addr, end);
2207aee16b3cSJeremy Fitzhardinge 		err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2208aee16b3cSJeremy Fitzhardinge 		if (err)
2209aee16b3cSJeremy Fitzhardinge 			break;
2210aee16b3cSJeremy Fitzhardinge 	} while (pmd++, addr = next, addr != end);
2211aee16b3cSJeremy Fitzhardinge 	return err;
2212aee16b3cSJeremy Fitzhardinge }
2213aee16b3cSJeremy Fitzhardinge 
2214c2febafcSKirill A. Shutemov static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2215aee16b3cSJeremy Fitzhardinge 				     unsigned long addr, unsigned long end,
2216aee16b3cSJeremy Fitzhardinge 				     pte_fn_t fn, void *data)
2217aee16b3cSJeremy Fitzhardinge {
2218aee16b3cSJeremy Fitzhardinge 	pud_t *pud;
2219aee16b3cSJeremy Fitzhardinge 	unsigned long next;
2220aee16b3cSJeremy Fitzhardinge 	int err;
2221aee16b3cSJeremy Fitzhardinge 
2222c2febafcSKirill A. Shutemov 	pud = pud_alloc(mm, p4d, addr);
2223aee16b3cSJeremy Fitzhardinge 	if (!pud)
2224aee16b3cSJeremy Fitzhardinge 		return -ENOMEM;
2225aee16b3cSJeremy Fitzhardinge 	do {
2226aee16b3cSJeremy Fitzhardinge 		next = pud_addr_end(addr, end);
2227aee16b3cSJeremy Fitzhardinge 		err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2228aee16b3cSJeremy Fitzhardinge 		if (err)
2229aee16b3cSJeremy Fitzhardinge 			break;
2230aee16b3cSJeremy Fitzhardinge 	} while (pud++, addr = next, addr != end);
2231aee16b3cSJeremy Fitzhardinge 	return err;
2232aee16b3cSJeremy Fitzhardinge }
2233aee16b3cSJeremy Fitzhardinge 
2234c2febafcSKirill A. Shutemov static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2235c2febafcSKirill A. Shutemov 				     unsigned long addr, unsigned long end,
2236c2febafcSKirill A. Shutemov 				     pte_fn_t fn, void *data)
2237c2febafcSKirill A. Shutemov {
2238c2febafcSKirill A. Shutemov 	p4d_t *p4d;
2239c2febafcSKirill A. Shutemov 	unsigned long next;
2240c2febafcSKirill A. Shutemov 	int err;
2241c2febafcSKirill A. Shutemov 
2242c2febafcSKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, addr);
2243c2febafcSKirill A. Shutemov 	if (!p4d)
2244c2febafcSKirill A. Shutemov 		return -ENOMEM;
2245c2febafcSKirill A. Shutemov 	do {
2246c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
2247c2febafcSKirill A. Shutemov 		err = apply_to_pud_range(mm, p4d, addr, next, fn, data);
2248c2febafcSKirill A. Shutemov 		if (err)
2249c2febafcSKirill A. Shutemov 			break;
2250c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
2251c2febafcSKirill A. Shutemov 	return err;
2252c2febafcSKirill A. Shutemov }
2253c2febafcSKirill A. Shutemov 
2254aee16b3cSJeremy Fitzhardinge /*
2255aee16b3cSJeremy Fitzhardinge  * Scan a region of virtual memory, filling in page tables as necessary
2256aee16b3cSJeremy Fitzhardinge  * and calling a provided function on each leaf page table.
2257aee16b3cSJeremy Fitzhardinge  */
2258aee16b3cSJeremy Fitzhardinge int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2259aee16b3cSJeremy Fitzhardinge 			unsigned long size, pte_fn_t fn, void *data)
2260aee16b3cSJeremy Fitzhardinge {
2261aee16b3cSJeremy Fitzhardinge 	pgd_t *pgd;
2262aee16b3cSJeremy Fitzhardinge 	unsigned long next;
226357250a5bSJeremy Fitzhardinge 	unsigned long end = addr + size;
2264aee16b3cSJeremy Fitzhardinge 	int err;
2265aee16b3cSJeremy Fitzhardinge 
22669cb65bc3SMika Penttilä 	if (WARN_ON(addr >= end))
22679cb65bc3SMika Penttilä 		return -EINVAL;
22689cb65bc3SMika Penttilä 
2269aee16b3cSJeremy Fitzhardinge 	pgd = pgd_offset(mm, addr);
2270aee16b3cSJeremy Fitzhardinge 	do {
2271aee16b3cSJeremy Fitzhardinge 		next = pgd_addr_end(addr, end);
2272c2febafcSKirill A. Shutemov 		err = apply_to_p4d_range(mm, pgd, addr, next, fn, data);
2273aee16b3cSJeremy Fitzhardinge 		if (err)
2274aee16b3cSJeremy Fitzhardinge 			break;
2275aee16b3cSJeremy Fitzhardinge 	} while (pgd++, addr = next, addr != end);
227657250a5bSJeremy Fitzhardinge 
2277aee16b3cSJeremy Fitzhardinge 	return err;
2278aee16b3cSJeremy Fitzhardinge }
2279aee16b3cSJeremy Fitzhardinge EXPORT_SYMBOL_GPL(apply_to_page_range);
2280aee16b3cSJeremy Fitzhardinge 
22811da177e4SLinus Torvalds /*
22829b4bdd2fSKirill A. Shutemov  * handle_pte_fault chooses page fault handler according to an entry which was
22839b4bdd2fSKirill A. Shutemov  * read non-atomically.  Before making any commitment, on those architectures
22849b4bdd2fSKirill A. Shutemov  * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
22859b4bdd2fSKirill A. Shutemov  * parts, do_swap_page must check under lock before unmapping the pte and
22869b4bdd2fSKirill A. Shutemov  * proceeding (but do_wp_page is only called after already making such a check;
2287a335b2e1SRyota Ozaki  * and do_anonymous_page can safely check later on).
22888f4e2101SHugh Dickins  */
22894c21e2f2SHugh Dickins static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
22908f4e2101SHugh Dickins 				pte_t *page_table, pte_t orig_pte)
22918f4e2101SHugh Dickins {
22928f4e2101SHugh Dickins 	int same = 1;
22938f4e2101SHugh Dickins #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
22948f4e2101SHugh Dickins 	if (sizeof(pte_t) > sizeof(unsigned long)) {
22954c21e2f2SHugh Dickins 		spinlock_t *ptl = pte_lockptr(mm, pmd);
22964c21e2f2SHugh Dickins 		spin_lock(ptl);
22978f4e2101SHugh Dickins 		same = pte_same(*page_table, orig_pte);
22984c21e2f2SHugh Dickins 		spin_unlock(ptl);
22998f4e2101SHugh Dickins 	}
23008f4e2101SHugh Dickins #endif
23018f4e2101SHugh Dickins 	pte_unmap(page_table);
23028f4e2101SHugh Dickins 	return same;
23038f4e2101SHugh Dickins }
23048f4e2101SHugh Dickins 
23059de455b2SAtsushi Nemoto static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
23066aab341eSLinus Torvalds {
23070abdd7a8SDan Williams 	debug_dma_assert_idle(src);
23080abdd7a8SDan Williams 
23096aab341eSLinus Torvalds 	/*
23106aab341eSLinus Torvalds 	 * If the source page was a PFN mapping, we don't have
23116aab341eSLinus Torvalds 	 * a "struct page" for it. We do a best-effort copy by
23126aab341eSLinus Torvalds 	 * just copying from the original user address. If that
23136aab341eSLinus Torvalds 	 * fails, we just zero-fill it. Live with it.
23146aab341eSLinus Torvalds 	 */
23156aab341eSLinus Torvalds 	if (unlikely(!src)) {
23169b04c5feSCong Wang 		void *kaddr = kmap_atomic(dst);
23175d2a2dbbSLinus Torvalds 		void __user *uaddr = (void __user *)(va & PAGE_MASK);
23185d2a2dbbSLinus Torvalds 
23195d2a2dbbSLinus Torvalds 		/*
23205d2a2dbbSLinus Torvalds 		 * This really shouldn't fail, because the page is there
23215d2a2dbbSLinus Torvalds 		 * in the page tables. But it might just be unreadable,
23225d2a2dbbSLinus Torvalds 		 * in which case we just give up and fill the result with
23235d2a2dbbSLinus Torvalds 		 * zeroes.
23245d2a2dbbSLinus Torvalds 		 */
23255d2a2dbbSLinus Torvalds 		if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
23263ecb01dfSJan Beulich 			clear_page(kaddr);
23279b04c5feSCong Wang 		kunmap_atomic(kaddr);
2328c4ec7b0dSDmitriy Monakhov 		flush_dcache_page(dst);
23290ed361deSNick Piggin 	} else
23309de455b2SAtsushi Nemoto 		copy_user_highpage(dst, src, va, vma);
23316aab341eSLinus Torvalds }
23326aab341eSLinus Torvalds 
2333c20cd45eSMichal Hocko static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2334c20cd45eSMichal Hocko {
2335c20cd45eSMichal Hocko 	struct file *vm_file = vma->vm_file;
2336c20cd45eSMichal Hocko 
2337c20cd45eSMichal Hocko 	if (vm_file)
2338c20cd45eSMichal Hocko 		return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2339c20cd45eSMichal Hocko 
2340c20cd45eSMichal Hocko 	/*
2341c20cd45eSMichal Hocko 	 * Special mappings (e.g. VDSO) do not have any file so fake
2342c20cd45eSMichal Hocko 	 * a default GFP_KERNEL for them.
2343c20cd45eSMichal Hocko 	 */
2344c20cd45eSMichal Hocko 	return GFP_KERNEL;
2345c20cd45eSMichal Hocko }
2346c20cd45eSMichal Hocko 
23471da177e4SLinus Torvalds /*
2348fb09a464SKirill A. Shutemov  * Notify the address space that the page is about to become writable so that
2349fb09a464SKirill A. Shutemov  * it can prohibit this or wait for the page to get into an appropriate state.
2350fb09a464SKirill A. Shutemov  *
2351fb09a464SKirill A. Shutemov  * We do this without the lock held, so that it can sleep if it needs to.
2352fb09a464SKirill A. Shutemov  */
235338b8cb7fSJan Kara static int do_page_mkwrite(struct vm_fault *vmf)
2354fb09a464SKirill A. Shutemov {
2355fb09a464SKirill A. Shutemov 	int ret;
235638b8cb7fSJan Kara 	struct page *page = vmf->page;
235738b8cb7fSJan Kara 	unsigned int old_flags = vmf->flags;
2358fb09a464SKirill A. Shutemov 
235938b8cb7fSJan Kara 	vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2360fb09a464SKirill A. Shutemov 
236111bac800SDave Jiang 	ret = vmf->vma->vm_ops->page_mkwrite(vmf);
236238b8cb7fSJan Kara 	/* Restore original flags so that caller is not surprised */
236338b8cb7fSJan Kara 	vmf->flags = old_flags;
2364fb09a464SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2365fb09a464SKirill A. Shutemov 		return ret;
2366fb09a464SKirill A. Shutemov 	if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2367fb09a464SKirill A. Shutemov 		lock_page(page);
2368fb09a464SKirill A. Shutemov 		if (!page->mapping) {
2369fb09a464SKirill A. Shutemov 			unlock_page(page);
2370fb09a464SKirill A. Shutemov 			return 0; /* retry */
2371fb09a464SKirill A. Shutemov 		}
2372fb09a464SKirill A. Shutemov 		ret |= VM_FAULT_LOCKED;
2373fb09a464SKirill A. Shutemov 	} else
2374fb09a464SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
2375fb09a464SKirill A. Shutemov 	return ret;
2376fb09a464SKirill A. Shutemov }
2377fb09a464SKirill A. Shutemov 
2378fb09a464SKirill A. Shutemov /*
237997ba0c2bSJan Kara  * Handle dirtying of a page in shared file mapping on a write fault.
23804e047f89SShachar Raindel  *
238197ba0c2bSJan Kara  * The function expects the page to be locked and unlocks it.
23824e047f89SShachar Raindel  */
238397ba0c2bSJan Kara static void fault_dirty_shared_page(struct vm_area_struct *vma,
238497ba0c2bSJan Kara 				    struct page *page)
23854e047f89SShachar Raindel {
23864e047f89SShachar Raindel 	struct address_space *mapping;
238797ba0c2bSJan Kara 	bool dirtied;
238897ba0c2bSJan Kara 	bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
23894e047f89SShachar Raindel 
23904e047f89SShachar Raindel 	dirtied = set_page_dirty(page);
23914e047f89SShachar Raindel 	VM_BUG_ON_PAGE(PageAnon(page), page);
239297ba0c2bSJan Kara 	/*
239397ba0c2bSJan Kara 	 * Take a local copy of the address_space - page.mapping may be zeroed
239497ba0c2bSJan Kara 	 * by truncate after unlock_page().   The address_space itself remains
239597ba0c2bSJan Kara 	 * pinned by vma->vm_file's reference.  We rely on unlock_page()'s
239697ba0c2bSJan Kara 	 * release semantics to prevent the compiler from undoing this copying.
239797ba0c2bSJan Kara 	 */
239897ba0c2bSJan Kara 	mapping = page_rmapping(page);
23994e047f89SShachar Raindel 	unlock_page(page);
24004e047f89SShachar Raindel 
24014e047f89SShachar Raindel 	if ((dirtied || page_mkwrite) && mapping) {
24024e047f89SShachar Raindel 		/*
24034e047f89SShachar Raindel 		 * Some device drivers do not set page.mapping
24044e047f89SShachar Raindel 		 * but still dirty their pages
24054e047f89SShachar Raindel 		 */
24064e047f89SShachar Raindel 		balance_dirty_pages_ratelimited(mapping);
24074e047f89SShachar Raindel 	}
24084e047f89SShachar Raindel 
24094e047f89SShachar Raindel 	if (!page_mkwrite)
24104e047f89SShachar Raindel 		file_update_time(vma->vm_file);
24114e047f89SShachar Raindel }
24124e047f89SShachar Raindel 
241397ba0c2bSJan Kara /*
24144e047f89SShachar Raindel  * Handle write page faults for pages that can be reused in the current vma
24154e047f89SShachar Raindel  *
24164e047f89SShachar Raindel  * This can happen either due to the mapping being with the VM_SHARED flag,
24174e047f89SShachar Raindel  * or due to us being the last reference standing to the page. In either
24184e047f89SShachar Raindel  * case, all we need to do here is to mark the page as writable and update
24194e047f89SShachar Raindel  * any related book-keeping.
24204e047f89SShachar Raindel  */
2421997dd98dSJan Kara static inline void wp_page_reuse(struct vm_fault *vmf)
242282b0f8c3SJan Kara 	__releases(vmf->ptl)
24234e047f89SShachar Raindel {
242482b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
2425a41b70d6SJan Kara 	struct page *page = vmf->page;
24264e047f89SShachar Raindel 	pte_t entry;
24274e047f89SShachar Raindel 	/*
24284e047f89SShachar Raindel 	 * Clear the pages cpupid information as the existing
24294e047f89SShachar Raindel 	 * information potentially belongs to a now completely
24304e047f89SShachar Raindel 	 * unrelated process.
24314e047f89SShachar Raindel 	 */
24324e047f89SShachar Raindel 	if (page)
24334e047f89SShachar Raindel 		page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
24344e047f89SShachar Raindel 
24352994302bSJan Kara 	flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
24362994302bSJan Kara 	entry = pte_mkyoung(vmf->orig_pte);
24374e047f89SShachar Raindel 	entry = maybe_mkwrite(pte_mkdirty(entry), vma);
243882b0f8c3SJan Kara 	if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
243982b0f8c3SJan Kara 		update_mmu_cache(vma, vmf->address, vmf->pte);
244082b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
24414e047f89SShachar Raindel }
24424e047f89SShachar Raindel 
24434e047f89SShachar Raindel /*
24442f38ab2cSShachar Raindel  * Handle the case of a page which we actually need to copy to a new page.
24452f38ab2cSShachar Raindel  *
24462f38ab2cSShachar Raindel  * Called with mmap_sem locked and the old page referenced, but
24472f38ab2cSShachar Raindel  * without the ptl held.
24482f38ab2cSShachar Raindel  *
24492f38ab2cSShachar Raindel  * High level logic flow:
24502f38ab2cSShachar Raindel  *
24512f38ab2cSShachar Raindel  * - Allocate a page, copy the content of the old page to the new one.
24522f38ab2cSShachar Raindel  * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
24532f38ab2cSShachar Raindel  * - Take the PTL. If the pte changed, bail out and release the allocated page
24542f38ab2cSShachar Raindel  * - If the pte is still the way we remember it, update the page table and all
24552f38ab2cSShachar Raindel  *   relevant references. This includes dropping the reference the page-table
24562f38ab2cSShachar Raindel  *   held to the old page, as well as updating the rmap.
24572f38ab2cSShachar Raindel  * - In any case, unlock the PTL and drop the reference we took to the old page.
24582f38ab2cSShachar Raindel  */
2459a41b70d6SJan Kara static int wp_page_copy(struct vm_fault *vmf)
24602f38ab2cSShachar Raindel {
246182b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
2462bae473a4SKirill A. Shutemov 	struct mm_struct *mm = vma->vm_mm;
2463a41b70d6SJan Kara 	struct page *old_page = vmf->page;
24642f38ab2cSShachar Raindel 	struct page *new_page = NULL;
24652f38ab2cSShachar Raindel 	pte_t entry;
24662f38ab2cSShachar Raindel 	int page_copied = 0;
246782b0f8c3SJan Kara 	const unsigned long mmun_start = vmf->address & PAGE_MASK;
2468bae473a4SKirill A. Shutemov 	const unsigned long mmun_end = mmun_start + PAGE_SIZE;
24692f38ab2cSShachar Raindel 	struct mem_cgroup *memcg;
24702f38ab2cSShachar Raindel 
24712f38ab2cSShachar Raindel 	if (unlikely(anon_vma_prepare(vma)))
24722f38ab2cSShachar Raindel 		goto oom;
24732f38ab2cSShachar Raindel 
24742994302bSJan Kara 	if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
247582b0f8c3SJan Kara 		new_page = alloc_zeroed_user_highpage_movable(vma,
247682b0f8c3SJan Kara 							      vmf->address);
24772f38ab2cSShachar Raindel 		if (!new_page)
24782f38ab2cSShachar Raindel 			goto oom;
24792f38ab2cSShachar Raindel 	} else {
2480bae473a4SKirill A. Shutemov 		new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
248182b0f8c3SJan Kara 				vmf->address);
24822f38ab2cSShachar Raindel 		if (!new_page)
24832f38ab2cSShachar Raindel 			goto oom;
248482b0f8c3SJan Kara 		cow_user_page(new_page, old_page, vmf->address, vma);
24852f38ab2cSShachar Raindel 	}
24862f38ab2cSShachar Raindel 
2487f627c2f5SKirill A. Shutemov 	if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg, false))
24882f38ab2cSShachar Raindel 		goto oom_free_new;
24892f38ab2cSShachar Raindel 
2490eb3c24f3SMel Gorman 	__SetPageUptodate(new_page);
2491eb3c24f3SMel Gorman 
24922f38ab2cSShachar Raindel 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
24932f38ab2cSShachar Raindel 
24942f38ab2cSShachar Raindel 	/*
24952f38ab2cSShachar Raindel 	 * Re-check the pte - we dropped the lock
24962f38ab2cSShachar Raindel 	 */
249782b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
24982994302bSJan Kara 	if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
24992f38ab2cSShachar Raindel 		if (old_page) {
25002f38ab2cSShachar Raindel 			if (!PageAnon(old_page)) {
2501eca56ff9SJerome Marchand 				dec_mm_counter_fast(mm,
2502eca56ff9SJerome Marchand 						mm_counter_file(old_page));
25032f38ab2cSShachar Raindel 				inc_mm_counter_fast(mm, MM_ANONPAGES);
25042f38ab2cSShachar Raindel 			}
25052f38ab2cSShachar Raindel 		} else {
25062f38ab2cSShachar Raindel 			inc_mm_counter_fast(mm, MM_ANONPAGES);
25072f38ab2cSShachar Raindel 		}
25082994302bSJan Kara 		flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
25092f38ab2cSShachar Raindel 		entry = mk_pte(new_page, vma->vm_page_prot);
25102f38ab2cSShachar Raindel 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
25112f38ab2cSShachar Raindel 		/*
25122f38ab2cSShachar Raindel 		 * Clear the pte entry and flush it first, before updating the
25132f38ab2cSShachar Raindel 		 * pte with the new entry. This will avoid a race condition
25142f38ab2cSShachar Raindel 		 * seen in the presence of one thread doing SMC and another
25152f38ab2cSShachar Raindel 		 * thread doing COW.
25162f38ab2cSShachar Raindel 		 */
251782b0f8c3SJan Kara 		ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
251882b0f8c3SJan Kara 		page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2519f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(new_page, memcg, false, false);
25202f38ab2cSShachar Raindel 		lru_cache_add_active_or_unevictable(new_page, vma);
25212f38ab2cSShachar Raindel 		/*
25222f38ab2cSShachar Raindel 		 * We call the notify macro here because, when using secondary
25232f38ab2cSShachar Raindel 		 * mmu page tables (such as kvm shadow page tables), we want the
25242f38ab2cSShachar Raindel 		 * new page to be mapped directly into the secondary page table.
25252f38ab2cSShachar Raindel 		 */
252682b0f8c3SJan Kara 		set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
252782b0f8c3SJan Kara 		update_mmu_cache(vma, vmf->address, vmf->pte);
25282f38ab2cSShachar Raindel 		if (old_page) {
25292f38ab2cSShachar Raindel 			/*
25302f38ab2cSShachar Raindel 			 * Only after switching the pte to the new page may
25312f38ab2cSShachar Raindel 			 * we remove the mapcount here. Otherwise another
25322f38ab2cSShachar Raindel 			 * process may come and find the rmap count decremented
25332f38ab2cSShachar Raindel 			 * before the pte is switched to the new page, and
25342f38ab2cSShachar Raindel 			 * "reuse" the old page writing into it while our pte
25352f38ab2cSShachar Raindel 			 * here still points into it and can be read by other
25362f38ab2cSShachar Raindel 			 * threads.
25372f38ab2cSShachar Raindel 			 *
25382f38ab2cSShachar Raindel 			 * The critical issue is to order this
25392f38ab2cSShachar Raindel 			 * page_remove_rmap with the ptp_clear_flush above.
25402f38ab2cSShachar Raindel 			 * Those stores are ordered by (if nothing else,)
25412f38ab2cSShachar Raindel 			 * the barrier present in the atomic_add_negative
25422f38ab2cSShachar Raindel 			 * in page_remove_rmap.
25432f38ab2cSShachar Raindel 			 *
25442f38ab2cSShachar Raindel 			 * Then the TLB flush in ptep_clear_flush ensures that
25452f38ab2cSShachar Raindel 			 * no process can access the old page before the
25462f38ab2cSShachar Raindel 			 * decremented mapcount is visible. And the old page
25472f38ab2cSShachar Raindel 			 * cannot be reused until after the decremented
25482f38ab2cSShachar Raindel 			 * mapcount is visible. So transitively, TLBs to
25492f38ab2cSShachar Raindel 			 * old page will be flushed before it can be reused.
25502f38ab2cSShachar Raindel 			 */
2551d281ee61SKirill A. Shutemov 			page_remove_rmap(old_page, false);
25522f38ab2cSShachar Raindel 		}
25532f38ab2cSShachar Raindel 
25542f38ab2cSShachar Raindel 		/* Free the old page.. */
25552f38ab2cSShachar Raindel 		new_page = old_page;
25562f38ab2cSShachar Raindel 		page_copied = 1;
25572f38ab2cSShachar Raindel 	} else {
2558f627c2f5SKirill A. Shutemov 		mem_cgroup_cancel_charge(new_page, memcg, false);
25592f38ab2cSShachar Raindel 	}
25602f38ab2cSShachar Raindel 
25612f38ab2cSShachar Raindel 	if (new_page)
256209cbfeafSKirill A. Shutemov 		put_page(new_page);
25632f38ab2cSShachar Raindel 
256482b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
25654645b9feSJérôme Glisse 	/*
25664645b9feSJérôme Glisse 	 * No need to double call mmu_notifier->invalidate_range() callback as
25674645b9feSJérôme Glisse 	 * the above ptep_clear_flush_notify() did already call it.
25684645b9feSJérôme Glisse 	 */
25694645b9feSJérôme Glisse 	mmu_notifier_invalidate_range_only_end(mm, mmun_start, mmun_end);
25702f38ab2cSShachar Raindel 	if (old_page) {
25712f38ab2cSShachar Raindel 		/*
25722f38ab2cSShachar Raindel 		 * Don't let another task, with possibly unlocked vma,
25732f38ab2cSShachar Raindel 		 * keep the mlocked page.
25742f38ab2cSShachar Raindel 		 */
25752f38ab2cSShachar Raindel 		if (page_copied && (vma->vm_flags & VM_LOCKED)) {
25762f38ab2cSShachar Raindel 			lock_page(old_page);	/* LRU manipulation */
2577e90309c9SKirill A. Shutemov 			if (PageMlocked(old_page))
25782f38ab2cSShachar Raindel 				munlock_vma_page(old_page);
25792f38ab2cSShachar Raindel 			unlock_page(old_page);
25802f38ab2cSShachar Raindel 		}
258109cbfeafSKirill A. Shutemov 		put_page(old_page);
25822f38ab2cSShachar Raindel 	}
25832f38ab2cSShachar Raindel 	return page_copied ? VM_FAULT_WRITE : 0;
25842f38ab2cSShachar Raindel oom_free_new:
258509cbfeafSKirill A. Shutemov 	put_page(new_page);
25862f38ab2cSShachar Raindel oom:
25872f38ab2cSShachar Raindel 	if (old_page)
258809cbfeafSKirill A. Shutemov 		put_page(old_page);
25892f38ab2cSShachar Raindel 	return VM_FAULT_OOM;
25902f38ab2cSShachar Raindel }
25912f38ab2cSShachar Raindel 
259266a6197cSJan Kara /**
259366a6197cSJan Kara  * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
259466a6197cSJan Kara  *			  writeable once the page is prepared
259566a6197cSJan Kara  *
259666a6197cSJan Kara  * @vmf: structure describing the fault
259766a6197cSJan Kara  *
259866a6197cSJan Kara  * This function handles all that is needed to finish a write page fault in a
259966a6197cSJan Kara  * shared mapping due to PTE being read-only once the mapped page is prepared.
260066a6197cSJan Kara  * It handles locking of PTE and modifying it. The function returns
260166a6197cSJan Kara  * VM_FAULT_WRITE on success, 0 when PTE got changed before we acquired PTE
260266a6197cSJan Kara  * lock.
260366a6197cSJan Kara  *
260466a6197cSJan Kara  * The function expects the page to be locked or other protection against
260566a6197cSJan Kara  * concurrent faults / writeback (such as DAX radix tree locks).
260666a6197cSJan Kara  */
260766a6197cSJan Kara int finish_mkwrite_fault(struct vm_fault *vmf)
260866a6197cSJan Kara {
260966a6197cSJan Kara 	WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
261066a6197cSJan Kara 	vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
261166a6197cSJan Kara 				       &vmf->ptl);
261266a6197cSJan Kara 	/*
261366a6197cSJan Kara 	 * We might have raced with another page fault while we released the
261466a6197cSJan Kara 	 * pte_offset_map_lock.
261566a6197cSJan Kara 	 */
261666a6197cSJan Kara 	if (!pte_same(*vmf->pte, vmf->orig_pte)) {
261766a6197cSJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
2618a19e2553SJan Kara 		return VM_FAULT_NOPAGE;
261966a6197cSJan Kara 	}
262066a6197cSJan Kara 	wp_page_reuse(vmf);
2621a19e2553SJan Kara 	return 0;
262266a6197cSJan Kara }
262366a6197cSJan Kara 
2624dd906184SBoaz Harrosh /*
2625dd906184SBoaz Harrosh  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2626dd906184SBoaz Harrosh  * mapping
2627dd906184SBoaz Harrosh  */
26282994302bSJan Kara static int wp_pfn_shared(struct vm_fault *vmf)
2629dd906184SBoaz Harrosh {
263082b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
2631bae473a4SKirill A. Shutemov 
2632dd906184SBoaz Harrosh 	if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2633dd906184SBoaz Harrosh 		int ret;
2634dd906184SBoaz Harrosh 
263582b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
2636fe82221fSJan Kara 		vmf->flags |= FAULT_FLAG_MKWRITE;
263711bac800SDave Jiang 		ret = vma->vm_ops->pfn_mkwrite(vmf);
26382f89dc12SJan Kara 		if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
2639dd906184SBoaz Harrosh 			return ret;
264066a6197cSJan Kara 		return finish_mkwrite_fault(vmf);
2641dd906184SBoaz Harrosh 	}
2642997dd98dSJan Kara 	wp_page_reuse(vmf);
2643997dd98dSJan Kara 	return VM_FAULT_WRITE;
2644dd906184SBoaz Harrosh }
2645dd906184SBoaz Harrosh 
2646a41b70d6SJan Kara static int wp_page_shared(struct vm_fault *vmf)
264782b0f8c3SJan Kara 	__releases(vmf->ptl)
264893e478d4SShachar Raindel {
264982b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
265093e478d4SShachar Raindel 
2651a41b70d6SJan Kara 	get_page(vmf->page);
265293e478d4SShachar Raindel 
265393e478d4SShachar Raindel 	if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
265493e478d4SShachar Raindel 		int tmp;
265593e478d4SShachar Raindel 
265682b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
265738b8cb7fSJan Kara 		tmp = do_page_mkwrite(vmf);
265893e478d4SShachar Raindel 		if (unlikely(!tmp || (tmp &
265993e478d4SShachar Raindel 				      (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2660a41b70d6SJan Kara 			put_page(vmf->page);
266193e478d4SShachar Raindel 			return tmp;
266293e478d4SShachar Raindel 		}
266366a6197cSJan Kara 		tmp = finish_mkwrite_fault(vmf);
2664a19e2553SJan Kara 		if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2665a41b70d6SJan Kara 			unlock_page(vmf->page);
2666a41b70d6SJan Kara 			put_page(vmf->page);
266766a6197cSJan Kara 			return tmp;
266893e478d4SShachar Raindel 		}
266966a6197cSJan Kara 	} else {
2670997dd98dSJan Kara 		wp_page_reuse(vmf);
2671997dd98dSJan Kara 		lock_page(vmf->page);
267293e478d4SShachar Raindel 	}
2673997dd98dSJan Kara 	fault_dirty_shared_page(vma, vmf->page);
2674997dd98dSJan Kara 	put_page(vmf->page);
267593e478d4SShachar Raindel 
2676997dd98dSJan Kara 	return VM_FAULT_WRITE;
267793e478d4SShachar Raindel }
267893e478d4SShachar Raindel 
26792f38ab2cSShachar Raindel /*
26801da177e4SLinus Torvalds  * This routine handles present pages, when users try to write
26811da177e4SLinus Torvalds  * to a shared page. It is done by copying the page to a new address
26821da177e4SLinus Torvalds  * and decrementing the shared-page counter for the old page.
26831da177e4SLinus Torvalds  *
26841da177e4SLinus Torvalds  * Note that this routine assumes that the protection checks have been
26851da177e4SLinus Torvalds  * done by the caller (the low-level page fault routine in most cases).
26861da177e4SLinus Torvalds  * Thus we can safely just mark it writable once we've done any necessary
26871da177e4SLinus Torvalds  * COW.
26881da177e4SLinus Torvalds  *
26891da177e4SLinus Torvalds  * We also mark the page dirty at this point even though the page will
26901da177e4SLinus Torvalds  * change only once the write actually happens. This avoids a few races,
26911da177e4SLinus Torvalds  * and potentially makes it more efficient.
26921da177e4SLinus Torvalds  *
26938f4e2101SHugh Dickins  * We enter with non-exclusive mmap_sem (to exclude vma changes,
26948f4e2101SHugh Dickins  * but allow concurrent faults), with pte both mapped and locked.
26958f4e2101SHugh Dickins  * We return with mmap_sem still held, but pte unmapped and unlocked.
26961da177e4SLinus Torvalds  */
26972994302bSJan Kara static int do_wp_page(struct vm_fault *vmf)
269882b0f8c3SJan Kara 	__releases(vmf->ptl)
26991da177e4SLinus Torvalds {
270082b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
27011da177e4SLinus Torvalds 
2702a41b70d6SJan Kara 	vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
2703a41b70d6SJan Kara 	if (!vmf->page) {
2704251b97f5SPeter Zijlstra 		/*
270564e45507SPeter Feiner 		 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
270664e45507SPeter Feiner 		 * VM_PFNMAP VMA.
2707251b97f5SPeter Zijlstra 		 *
2708251b97f5SPeter Zijlstra 		 * We should not cow pages in a shared writeable mapping.
2709dd906184SBoaz Harrosh 		 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2710251b97f5SPeter Zijlstra 		 */
2711251b97f5SPeter Zijlstra 		if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2712251b97f5SPeter Zijlstra 				     (VM_WRITE|VM_SHARED))
27132994302bSJan Kara 			return wp_pfn_shared(vmf);
27142f38ab2cSShachar Raindel 
271582b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
2716a41b70d6SJan Kara 		return wp_page_copy(vmf);
2717251b97f5SPeter Zijlstra 	}
27181da177e4SLinus Torvalds 
2719d08b3851SPeter Zijlstra 	/*
2720ee6a6457SPeter Zijlstra 	 * Take out anonymous pages first, anonymous shared vmas are
2721ee6a6457SPeter Zijlstra 	 * not dirty accountable.
2722d08b3851SPeter Zijlstra 	 */
2723a41b70d6SJan Kara 	if (PageAnon(vmf->page) && !PageKsm(vmf->page)) {
2724ba3c4ce6SHuang Ying 		int total_map_swapcount;
2725a41b70d6SJan Kara 		if (!trylock_page(vmf->page)) {
2726a41b70d6SJan Kara 			get_page(vmf->page);
272782b0f8c3SJan Kara 			pte_unmap_unlock(vmf->pte, vmf->ptl);
2728a41b70d6SJan Kara 			lock_page(vmf->page);
272982b0f8c3SJan Kara 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
273082b0f8c3SJan Kara 					vmf->address, &vmf->ptl);
27312994302bSJan Kara 			if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2732a41b70d6SJan Kara 				unlock_page(vmf->page);
273382b0f8c3SJan Kara 				pte_unmap_unlock(vmf->pte, vmf->ptl);
2734a41b70d6SJan Kara 				put_page(vmf->page);
273528766805SShachar Raindel 				return 0;
2736ab967d86SHugh Dickins 			}
2737a41b70d6SJan Kara 			put_page(vmf->page);
2738ab967d86SHugh Dickins 		}
2739ba3c4ce6SHuang Ying 		if (reuse_swap_page(vmf->page, &total_map_swapcount)) {
2740ba3c4ce6SHuang Ying 			if (total_map_swapcount == 1) {
2741c44b6743SRik van Riel 				/*
27426d0a07edSAndrea Arcangeli 				 * The page is all ours. Move it to
27436d0a07edSAndrea Arcangeli 				 * our anon_vma so the rmap code will
27446d0a07edSAndrea Arcangeli 				 * not search our parent or siblings.
27456d0a07edSAndrea Arcangeli 				 * Protected against the rmap code by
27466d0a07edSAndrea Arcangeli 				 * the page lock.
2747c44b6743SRik van Riel 				 */
2748a41b70d6SJan Kara 				page_move_anon_rmap(vmf->page, vma);
27496d0a07edSAndrea Arcangeli 			}
2750a41b70d6SJan Kara 			unlock_page(vmf->page);
2751997dd98dSJan Kara 			wp_page_reuse(vmf);
2752997dd98dSJan Kara 			return VM_FAULT_WRITE;
2753b009c024SMichel Lespinasse 		}
2754a41b70d6SJan Kara 		unlock_page(vmf->page);
2755ee6a6457SPeter Zijlstra 	} else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2756d08b3851SPeter Zijlstra 					(VM_WRITE|VM_SHARED))) {
2757a41b70d6SJan Kara 		return wp_page_shared(vmf);
27581da177e4SLinus Torvalds 	}
27591da177e4SLinus Torvalds 
27601da177e4SLinus Torvalds 	/*
27611da177e4SLinus Torvalds 	 * Ok, we need to copy. Oh, well..
27621da177e4SLinus Torvalds 	 */
2763a41b70d6SJan Kara 	get_page(vmf->page);
276428766805SShachar Raindel 
276582b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
2766a41b70d6SJan Kara 	return wp_page_copy(vmf);
27671da177e4SLinus Torvalds }
27681da177e4SLinus Torvalds 
276997a89413SPeter Zijlstra static void unmap_mapping_range_vma(struct vm_area_struct *vma,
27701da177e4SLinus Torvalds 		unsigned long start_addr, unsigned long end_addr,
27711da177e4SLinus Torvalds 		struct zap_details *details)
27721da177e4SLinus Torvalds {
2773f5cc4eefSAl Viro 	zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
27741da177e4SLinus Torvalds }
27751da177e4SLinus Torvalds 
2776f808c13fSDavidlohr Bueso static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
27771da177e4SLinus Torvalds 					    struct zap_details *details)
27781da177e4SLinus Torvalds {
27791da177e4SLinus Torvalds 	struct vm_area_struct *vma;
27801da177e4SLinus Torvalds 	pgoff_t vba, vea, zba, zea;
27811da177e4SLinus Torvalds 
27826b2dbba8SMichel Lespinasse 	vma_interval_tree_foreach(vma, root,
27831da177e4SLinus Torvalds 			details->first_index, details->last_index) {
27841da177e4SLinus Torvalds 
27851da177e4SLinus Torvalds 		vba = vma->vm_pgoff;
2786d6e93217SLibin 		vea = vba + vma_pages(vma) - 1;
27871da177e4SLinus Torvalds 		zba = details->first_index;
27881da177e4SLinus Torvalds 		if (zba < vba)
27891da177e4SLinus Torvalds 			zba = vba;
27901da177e4SLinus Torvalds 		zea = details->last_index;
27911da177e4SLinus Torvalds 		if (zea > vea)
27921da177e4SLinus Torvalds 			zea = vea;
27931da177e4SLinus Torvalds 
279497a89413SPeter Zijlstra 		unmap_mapping_range_vma(vma,
27951da177e4SLinus Torvalds 			((zba - vba) << PAGE_SHIFT) + vma->vm_start,
27961da177e4SLinus Torvalds 			((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
279797a89413SPeter Zijlstra 				details);
27981da177e4SLinus Torvalds 	}
27991da177e4SLinus Torvalds }
28001da177e4SLinus Torvalds 
28011da177e4SLinus Torvalds /**
2802*977fbdcdSMatthew Wilcox  * unmap_mapping_pages() - Unmap pages from processes.
2803*977fbdcdSMatthew Wilcox  * @mapping: The address space containing pages to be unmapped.
2804*977fbdcdSMatthew Wilcox  * @start: Index of first page to be unmapped.
2805*977fbdcdSMatthew Wilcox  * @nr: Number of pages to be unmapped.  0 to unmap to end of file.
2806*977fbdcdSMatthew Wilcox  * @even_cows: Whether to unmap even private COWed pages.
2807*977fbdcdSMatthew Wilcox  *
2808*977fbdcdSMatthew Wilcox  * Unmap the pages in this address space from any userspace process which
2809*977fbdcdSMatthew Wilcox  * has them mmaped.  Generally, you want to remove COWed pages as well when
2810*977fbdcdSMatthew Wilcox  * a file is being truncated, but not when invalidating pages from the page
2811*977fbdcdSMatthew Wilcox  * cache.
2812*977fbdcdSMatthew Wilcox  */
2813*977fbdcdSMatthew Wilcox void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
2814*977fbdcdSMatthew Wilcox 		pgoff_t nr, bool even_cows)
2815*977fbdcdSMatthew Wilcox {
2816*977fbdcdSMatthew Wilcox 	struct zap_details details = { };
2817*977fbdcdSMatthew Wilcox 
2818*977fbdcdSMatthew Wilcox 	details.check_mapping = even_cows ? NULL : mapping;
2819*977fbdcdSMatthew Wilcox 	details.first_index = start;
2820*977fbdcdSMatthew Wilcox 	details.last_index = start + nr - 1;
2821*977fbdcdSMatthew Wilcox 	if (details.last_index < details.first_index)
2822*977fbdcdSMatthew Wilcox 		details.last_index = ULONG_MAX;
2823*977fbdcdSMatthew Wilcox 
2824*977fbdcdSMatthew Wilcox 	i_mmap_lock_write(mapping);
2825*977fbdcdSMatthew Wilcox 	if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
2826*977fbdcdSMatthew Wilcox 		unmap_mapping_range_tree(&mapping->i_mmap, &details);
2827*977fbdcdSMatthew Wilcox 	i_mmap_unlock_write(mapping);
2828*977fbdcdSMatthew Wilcox }
2829*977fbdcdSMatthew Wilcox 
2830*977fbdcdSMatthew Wilcox /**
28318a5f14a2SKirill A. Shutemov  * unmap_mapping_range - unmap the portion of all mmaps in the specified
2832*977fbdcdSMatthew Wilcox  * address_space corresponding to the specified byte range in the underlying
28338a5f14a2SKirill A. Shutemov  * file.
28348a5f14a2SKirill A. Shutemov  *
28353d41088fSMartin Waitz  * @mapping: the address space containing mmaps to be unmapped.
28361da177e4SLinus Torvalds  * @holebegin: byte in first page to unmap, relative to the start of
28371da177e4SLinus Torvalds  * the underlying file.  This will be rounded down to a PAGE_SIZE
283825d9e2d1Snpiggin@suse.de  * boundary.  Note that this is different from truncate_pagecache(), which
28391da177e4SLinus Torvalds  * must keep the partial page.  In contrast, we must get rid of
28401da177e4SLinus Torvalds  * partial pages.
28411da177e4SLinus Torvalds  * @holelen: size of prospective hole in bytes.  This will be rounded
28421da177e4SLinus Torvalds  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
28431da177e4SLinus Torvalds  * end of the file.
28441da177e4SLinus Torvalds  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
28451da177e4SLinus Torvalds  * but 0 when invalidating pagecache, don't throw away private data.
28461da177e4SLinus Torvalds  */
28471da177e4SLinus Torvalds void unmap_mapping_range(struct address_space *mapping,
28481da177e4SLinus Torvalds 		loff_t const holebegin, loff_t const holelen, int even_cows)
28491da177e4SLinus Torvalds {
28501da177e4SLinus Torvalds 	pgoff_t hba = holebegin >> PAGE_SHIFT;
28511da177e4SLinus Torvalds 	pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
28521da177e4SLinus Torvalds 
28531da177e4SLinus Torvalds 	/* Check for overflow. */
28541da177e4SLinus Torvalds 	if (sizeof(holelen) > sizeof(hlen)) {
28551da177e4SLinus Torvalds 		long long holeend =
28561da177e4SLinus Torvalds 			(holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
28571da177e4SLinus Torvalds 		if (holeend & ~(long long)ULONG_MAX)
28581da177e4SLinus Torvalds 			hlen = ULONG_MAX - hba + 1;
28591da177e4SLinus Torvalds 	}
28601da177e4SLinus Torvalds 
2861*977fbdcdSMatthew Wilcox 	unmap_mapping_pages(mapping, hba, hlen, even_cows);
28621da177e4SLinus Torvalds }
28631da177e4SLinus Torvalds EXPORT_SYMBOL(unmap_mapping_range);
28641da177e4SLinus Torvalds 
28651da177e4SLinus Torvalds /*
28668f4e2101SHugh Dickins  * We enter with non-exclusive mmap_sem (to exclude vma changes,
28678f4e2101SHugh Dickins  * but allow concurrent faults), and pte mapped but not yet locked.
28689a95f3cfSPaul Cassella  * We return with pte unmapped and unlocked.
28699a95f3cfSPaul Cassella  *
28709a95f3cfSPaul Cassella  * We return with the mmap_sem locked or unlocked in the same cases
28719a95f3cfSPaul Cassella  * as does filemap_fault().
28721da177e4SLinus Torvalds  */
28732994302bSJan Kara int do_swap_page(struct vm_fault *vmf)
28741da177e4SLinus Torvalds {
287582b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
28760bcac06fSMinchan Kim 	struct page *page = NULL, *swapcache = NULL;
287700501b53SJohannes Weiner 	struct mem_cgroup *memcg;
2878ec560175SHuang Ying 	struct vma_swap_readahead swap_ra;
287965500d23SHugh Dickins 	swp_entry_t entry;
28801da177e4SLinus Torvalds 	pte_t pte;
2881d065bd81SMichel Lespinasse 	int locked;
2882ad8c2ee8SRik van Riel 	int exclusive = 0;
288383c54070SNick Piggin 	int ret = 0;
2884ec560175SHuang Ying 	bool vma_readahead = swap_use_vma_readahead();
28851da177e4SLinus Torvalds 
2886f8020772SMinchan Kim 	if (vma_readahead) {
2887ec560175SHuang Ying 		page = swap_readahead_detect(vmf, &swap_ra);
2888f8020772SMinchan Kim 		swapcache = page;
2889f8020772SMinchan Kim 	}
2890f8020772SMinchan Kim 
2891ec560175SHuang Ying 	if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte)) {
2892ec560175SHuang Ying 		if (page)
2893ec560175SHuang Ying 			put_page(page);
28948f4e2101SHugh Dickins 		goto out;
2895ec560175SHuang Ying 	}
289665500d23SHugh Dickins 
28972994302bSJan Kara 	entry = pte_to_swp_entry(vmf->orig_pte);
2898d1737fdbSAndi Kleen 	if (unlikely(non_swap_entry(entry))) {
28990697212aSChristoph Lameter 		if (is_migration_entry(entry)) {
290082b0f8c3SJan Kara 			migration_entry_wait(vma->vm_mm, vmf->pmd,
290182b0f8c3SJan Kara 					     vmf->address);
29025042db43SJérôme Glisse 		} else if (is_device_private_entry(entry)) {
29035042db43SJérôme Glisse 			/*
29045042db43SJérôme Glisse 			 * For un-addressable device memory we call the pgmap
29055042db43SJérôme Glisse 			 * fault handler callback. The callback must migrate
29065042db43SJérôme Glisse 			 * the page back to some CPU accessible page.
29075042db43SJérôme Glisse 			 */
29085042db43SJérôme Glisse 			ret = device_private_entry_fault(vma, vmf->address, entry,
29095042db43SJérôme Glisse 						 vmf->flags, vmf->pmd);
2910d1737fdbSAndi Kleen 		} else if (is_hwpoison_entry(entry)) {
2911d1737fdbSAndi Kleen 			ret = VM_FAULT_HWPOISON;
2912d1737fdbSAndi Kleen 		} else {
29132994302bSJan Kara 			print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
2914d99be1a8SHugh Dickins 			ret = VM_FAULT_SIGBUS;
2915d1737fdbSAndi Kleen 		}
29160697212aSChristoph Lameter 		goto out;
29170697212aSChristoph Lameter 	}
29180bcac06fSMinchan Kim 
29190bcac06fSMinchan Kim 
29200ff92245SShailabh Nagar 	delayacct_set_flag(DELAYACCT_PF_SWAPIN);
2921f8020772SMinchan Kim 	if (!page) {
2922ec560175SHuang Ying 		page = lookup_swap_cache(entry, vma_readahead ? vma : NULL,
292382b0f8c3SJan Kara 					 vmf->address);
2924f8020772SMinchan Kim 		swapcache = page;
2925f8020772SMinchan Kim 	}
2926f8020772SMinchan Kim 
29271da177e4SLinus Torvalds 	if (!page) {
29280bcac06fSMinchan Kim 		struct swap_info_struct *si = swp_swap_info(entry);
29290bcac06fSMinchan Kim 
2930aa8d22a1SMinchan Kim 		if (si->flags & SWP_SYNCHRONOUS_IO &&
2931aa8d22a1SMinchan Kim 				__swap_count(si, entry) == 1) {
29320bcac06fSMinchan Kim 			/* skip swapcache */
29330bcac06fSMinchan Kim 			page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
29340bcac06fSMinchan Kim 			if (page) {
29350bcac06fSMinchan Kim 				__SetPageLocked(page);
29360bcac06fSMinchan Kim 				__SetPageSwapBacked(page);
29370bcac06fSMinchan Kim 				set_page_private(page, entry.val);
29380bcac06fSMinchan Kim 				lru_cache_add_anon(page);
29390bcac06fSMinchan Kim 				swap_readpage(page, true);
29400bcac06fSMinchan Kim 			}
2941aa8d22a1SMinchan Kim 		} else {
2942aa8d22a1SMinchan Kim 			if (vma_readahead)
2943aa8d22a1SMinchan Kim 				page = do_swap_page_readahead(entry,
2944aa8d22a1SMinchan Kim 					GFP_HIGHUSER_MOVABLE, vmf, &swap_ra);
2945aa8d22a1SMinchan Kim 			else
2946aa8d22a1SMinchan Kim 				page = swapin_readahead(entry,
2947aa8d22a1SMinchan Kim 				       GFP_HIGHUSER_MOVABLE, vma, vmf->address);
2948aa8d22a1SMinchan Kim 			swapcache = page;
29490bcac06fSMinchan Kim 		}
29500bcac06fSMinchan Kim 
2951ec560175SHuang Ying 		if (!page) {
29521da177e4SLinus Torvalds 			/*
29538f4e2101SHugh Dickins 			 * Back out if somebody else faulted in this pte
29548f4e2101SHugh Dickins 			 * while we released the pte lock.
29551da177e4SLinus Torvalds 			 */
295682b0f8c3SJan Kara 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
295782b0f8c3SJan Kara 					vmf->address, &vmf->ptl);
29582994302bSJan Kara 			if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
29591da177e4SLinus Torvalds 				ret = VM_FAULT_OOM;
29600ff92245SShailabh Nagar 			delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
296165500d23SHugh Dickins 			goto unlock;
29621da177e4SLinus Torvalds 		}
29631da177e4SLinus Torvalds 
29641da177e4SLinus Torvalds 		/* Had to read the page from swap area: Major fault */
29651da177e4SLinus Torvalds 		ret = VM_FAULT_MAJOR;
2966f8891e5eSChristoph Lameter 		count_vm_event(PGMAJFAULT);
29672262185cSRoman Gushchin 		count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
2968d1737fdbSAndi Kleen 	} else if (PageHWPoison(page)) {
296971f72525SWu Fengguang 		/*
297071f72525SWu Fengguang 		 * hwpoisoned dirty swapcache pages are kept for killing
297171f72525SWu Fengguang 		 * owner processes (which may be unknown at hwpoison time)
297271f72525SWu Fengguang 		 */
2973d1737fdbSAndi Kleen 		ret = VM_FAULT_HWPOISON;
2974d1737fdbSAndi Kleen 		delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
297556f31801SHugh Dickins 		swapcache = page;
29764779cb31SAndi Kleen 		goto out_release;
29771da177e4SLinus Torvalds 	}
29781da177e4SLinus Torvalds 
297982b0f8c3SJan Kara 	locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
2980e709ffd6SRik van Riel 
298120a1022dSBalbir Singh 	delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2982d065bd81SMichel Lespinasse 	if (!locked) {
2983d065bd81SMichel Lespinasse 		ret |= VM_FAULT_RETRY;
2984d065bd81SMichel Lespinasse 		goto out_release;
2985d065bd81SMichel Lespinasse 	}
29861da177e4SLinus Torvalds 
29874969c119SAndrea Arcangeli 	/*
298831c4a3d3SHugh Dickins 	 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
298931c4a3d3SHugh Dickins 	 * release the swapcache from under us.  The page pin, and pte_same
299031c4a3d3SHugh Dickins 	 * test below, are not enough to exclude that.  Even if it is still
299131c4a3d3SHugh Dickins 	 * swapcache, we need to check that the page's swap has not changed.
29924969c119SAndrea Arcangeli 	 */
29930bcac06fSMinchan Kim 	if (unlikely((!PageSwapCache(page) ||
29940bcac06fSMinchan Kim 			page_private(page) != entry.val)) && swapcache)
29954969c119SAndrea Arcangeli 		goto out_page;
29964969c119SAndrea Arcangeli 
299782b0f8c3SJan Kara 	page = ksm_might_need_to_copy(page, vma, vmf->address);
29984969c119SAndrea Arcangeli 	if (unlikely(!page)) {
29995ad64688SHugh Dickins 		ret = VM_FAULT_OOM;
30004969c119SAndrea Arcangeli 		page = swapcache;
30014969c119SAndrea Arcangeli 		goto out_page;
30024969c119SAndrea Arcangeli 	}
30035ad64688SHugh Dickins 
3004bae473a4SKirill A. Shutemov 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
3005bae473a4SKirill A. Shutemov 				&memcg, false)) {
3006073e587eSKAMEZAWA Hiroyuki 		ret = VM_FAULT_OOM;
3007bc43f75cSJohannes Weiner 		goto out_page;
3008073e587eSKAMEZAWA Hiroyuki 	}
3009073e587eSKAMEZAWA Hiroyuki 
30101da177e4SLinus Torvalds 	/*
30118f4e2101SHugh Dickins 	 * Back out if somebody else already faulted in this pte.
30121da177e4SLinus Torvalds 	 */
301382b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
301482b0f8c3SJan Kara 			&vmf->ptl);
30152994302bSJan Kara 	if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3016b8107480SKirill Korotaev 		goto out_nomap;
3017b8107480SKirill Korotaev 
3018b8107480SKirill Korotaev 	if (unlikely(!PageUptodate(page))) {
3019b8107480SKirill Korotaev 		ret = VM_FAULT_SIGBUS;
3020b8107480SKirill Korotaev 		goto out_nomap;
30211da177e4SLinus Torvalds 	}
30221da177e4SLinus Torvalds 
30238c7c6e34SKAMEZAWA Hiroyuki 	/*
30248c7c6e34SKAMEZAWA Hiroyuki 	 * The page isn't present yet, go ahead with the fault.
30258c7c6e34SKAMEZAWA Hiroyuki 	 *
30268c7c6e34SKAMEZAWA Hiroyuki 	 * Be careful about the sequence of operations here.
30278c7c6e34SKAMEZAWA Hiroyuki 	 * To get its accounting right, reuse_swap_page() must be called
30288c7c6e34SKAMEZAWA Hiroyuki 	 * while the page is counted on swap but not yet in mapcount i.e.
30298c7c6e34SKAMEZAWA Hiroyuki 	 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
30308c7c6e34SKAMEZAWA Hiroyuki 	 * must be called after the swap_free(), or it will never succeed.
30318c7c6e34SKAMEZAWA Hiroyuki 	 */
30321da177e4SLinus Torvalds 
3033bae473a4SKirill A. Shutemov 	inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3034bae473a4SKirill A. Shutemov 	dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
30351da177e4SLinus Torvalds 	pte = mk_pte(page, vma->vm_page_prot);
303682b0f8c3SJan Kara 	if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
30371da177e4SLinus Torvalds 		pte = maybe_mkwrite(pte_mkdirty(pte), vma);
303882b0f8c3SJan Kara 		vmf->flags &= ~FAULT_FLAG_WRITE;
30399a5b489bSAndrea Arcangeli 		ret |= VM_FAULT_WRITE;
3040d281ee61SKirill A. Shutemov 		exclusive = RMAP_EXCLUSIVE;
30411da177e4SLinus Torvalds 	}
30421da177e4SLinus Torvalds 	flush_icache_page(vma, page);
30432994302bSJan Kara 	if (pte_swp_soft_dirty(vmf->orig_pte))
3044179ef71cSCyrill Gorcunov 		pte = pte_mksoft_dirty(pte);
304582b0f8c3SJan Kara 	set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
30462994302bSJan Kara 	vmf->orig_pte = pte;
30470bcac06fSMinchan Kim 
30480bcac06fSMinchan Kim 	/* ksm created a completely new copy */
30490bcac06fSMinchan Kim 	if (unlikely(page != swapcache && swapcache)) {
305082b0f8c3SJan Kara 		page_add_new_anon_rmap(page, vma, vmf->address, false);
3051f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, false, false);
305200501b53SJohannes Weiner 		lru_cache_add_active_or_unevictable(page, vma);
30530bcac06fSMinchan Kim 	} else {
30540bcac06fSMinchan Kim 		do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
30550bcac06fSMinchan Kim 		mem_cgroup_commit_charge(page, memcg, true, false);
30560bcac06fSMinchan Kim 		activate_page(page);
305700501b53SJohannes Weiner 	}
30581da177e4SLinus Torvalds 
3059c475a8abSHugh Dickins 	swap_free(entry);
30605ccc5abaSVladimir Davydov 	if (mem_cgroup_swap_full(page) ||
30615ccc5abaSVladimir Davydov 	    (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3062a2c43eedSHugh Dickins 		try_to_free_swap(page);
3063c475a8abSHugh Dickins 	unlock_page(page);
30640bcac06fSMinchan Kim 	if (page != swapcache && swapcache) {
30654969c119SAndrea Arcangeli 		/*
30664969c119SAndrea Arcangeli 		 * Hold the lock to avoid the swap entry to be reused
30674969c119SAndrea Arcangeli 		 * until we take the PT lock for the pte_same() check
30684969c119SAndrea Arcangeli 		 * (to avoid false positives from pte_same). For
30694969c119SAndrea Arcangeli 		 * further safety release the lock after the swap_free
30704969c119SAndrea Arcangeli 		 * so that the swap count won't change under a
30714969c119SAndrea Arcangeli 		 * parallel locked swapcache.
30724969c119SAndrea Arcangeli 		 */
30734969c119SAndrea Arcangeli 		unlock_page(swapcache);
307409cbfeafSKirill A. Shutemov 		put_page(swapcache);
30754969c119SAndrea Arcangeli 	}
3076c475a8abSHugh Dickins 
307782b0f8c3SJan Kara 	if (vmf->flags & FAULT_FLAG_WRITE) {
30782994302bSJan Kara 		ret |= do_wp_page(vmf);
307961469f1dSHugh Dickins 		if (ret & VM_FAULT_ERROR)
308061469f1dSHugh Dickins 			ret &= VM_FAULT_ERROR;
30811da177e4SLinus Torvalds 		goto out;
30821da177e4SLinus Torvalds 	}
30831da177e4SLinus Torvalds 
30841da177e4SLinus Torvalds 	/* No need to invalidate - it was non-present before */
308582b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
308665500d23SHugh Dickins unlock:
308782b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
30881da177e4SLinus Torvalds out:
30891da177e4SLinus Torvalds 	return ret;
3090b8107480SKirill Korotaev out_nomap:
3091f627c2f5SKirill A. Shutemov 	mem_cgroup_cancel_charge(page, memcg, false);
309282b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
3093bc43f75cSJohannes Weiner out_page:
3094b8107480SKirill Korotaev 	unlock_page(page);
30954779cb31SAndi Kleen out_release:
309609cbfeafSKirill A. Shutemov 	put_page(page);
30970bcac06fSMinchan Kim 	if (page != swapcache && swapcache) {
30984969c119SAndrea Arcangeli 		unlock_page(swapcache);
309909cbfeafSKirill A. Shutemov 		put_page(swapcache);
31004969c119SAndrea Arcangeli 	}
310165500d23SHugh Dickins 	return ret;
31021da177e4SLinus Torvalds }
31031da177e4SLinus Torvalds 
31041da177e4SLinus Torvalds /*
31058f4e2101SHugh Dickins  * We enter with non-exclusive mmap_sem (to exclude vma changes,
31068f4e2101SHugh Dickins  * but allow concurrent faults), and pte mapped but not yet locked.
31078f4e2101SHugh Dickins  * We return with mmap_sem still held, but pte unmapped and unlocked.
31081da177e4SLinus Torvalds  */
310982b0f8c3SJan Kara static int do_anonymous_page(struct vm_fault *vmf)
31101da177e4SLinus Torvalds {
311182b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
311200501b53SJohannes Weiner 	struct mem_cgroup *memcg;
31138f4e2101SHugh Dickins 	struct page *page;
31146b31d595SMichal Hocko 	int ret = 0;
31151da177e4SLinus Torvalds 	pte_t entry;
31161da177e4SLinus Torvalds 
31176b7339f4SKirill A. Shutemov 	/* File mapping without ->vm_ops ? */
31186b7339f4SKirill A. Shutemov 	if (vma->vm_flags & VM_SHARED)
31196b7339f4SKirill A. Shutemov 		return VM_FAULT_SIGBUS;
31206b7339f4SKirill A. Shutemov 
31217267ec00SKirill A. Shutemov 	/*
31227267ec00SKirill A. Shutemov 	 * Use pte_alloc() instead of pte_alloc_map().  We can't run
31237267ec00SKirill A. Shutemov 	 * pte_offset_map() on pmds where a huge pmd might be created
31247267ec00SKirill A. Shutemov 	 * from a different thread.
31257267ec00SKirill A. Shutemov 	 *
31267267ec00SKirill A. Shutemov 	 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
31277267ec00SKirill A. Shutemov 	 * parallel threads are excluded by other means.
31287267ec00SKirill A. Shutemov 	 *
31297267ec00SKirill A. Shutemov 	 * Here we only have down_read(mmap_sem).
31307267ec00SKirill A. Shutemov 	 */
313182b0f8c3SJan Kara 	if (pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))
31327267ec00SKirill A. Shutemov 		return VM_FAULT_OOM;
31337267ec00SKirill A. Shutemov 
31347267ec00SKirill A. Shutemov 	/* See the comment in pte_alloc_one_map() */
313582b0f8c3SJan Kara 	if (unlikely(pmd_trans_unstable(vmf->pmd)))
31367267ec00SKirill A. Shutemov 		return 0;
31377267ec00SKirill A. Shutemov 
313811ac5524SLinus Torvalds 	/* Use the zero-page for reads */
313982b0f8c3SJan Kara 	if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3140bae473a4SKirill A. Shutemov 			!mm_forbids_zeropage(vma->vm_mm)) {
314182b0f8c3SJan Kara 		entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
314262eede62SHugh Dickins 						vma->vm_page_prot));
314382b0f8c3SJan Kara 		vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
314482b0f8c3SJan Kara 				vmf->address, &vmf->ptl);
314582b0f8c3SJan Kara 		if (!pte_none(*vmf->pte))
3146a13ea5b7SHugh Dickins 			goto unlock;
31476b31d595SMichal Hocko 		ret = check_stable_address_space(vma->vm_mm);
31486b31d595SMichal Hocko 		if (ret)
31496b31d595SMichal Hocko 			goto unlock;
31506b251fc9SAndrea Arcangeli 		/* Deliver the page fault to userland, check inside PT lock */
31516b251fc9SAndrea Arcangeli 		if (userfaultfd_missing(vma)) {
315282b0f8c3SJan Kara 			pte_unmap_unlock(vmf->pte, vmf->ptl);
315382b0f8c3SJan Kara 			return handle_userfault(vmf, VM_UFFD_MISSING);
31546b251fc9SAndrea Arcangeli 		}
3155a13ea5b7SHugh Dickins 		goto setpte;
3156a13ea5b7SHugh Dickins 	}
3157a13ea5b7SHugh Dickins 
31581da177e4SLinus Torvalds 	/* Allocate our own private page. */
31591da177e4SLinus Torvalds 	if (unlikely(anon_vma_prepare(vma)))
316065500d23SHugh Dickins 		goto oom;
316182b0f8c3SJan Kara 	page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
31621da177e4SLinus Torvalds 	if (!page)
316365500d23SHugh Dickins 		goto oom;
3164eb3c24f3SMel Gorman 
3165bae473a4SKirill A. Shutemov 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
3166eb3c24f3SMel Gorman 		goto oom_free_page;
3167eb3c24f3SMel Gorman 
316852f37629SMinchan Kim 	/*
316952f37629SMinchan Kim 	 * The memory barrier inside __SetPageUptodate makes sure that
317052f37629SMinchan Kim 	 * preceeding stores to the page contents become visible before
317152f37629SMinchan Kim 	 * the set_pte_at() write.
317252f37629SMinchan Kim 	 */
31730ed361deSNick Piggin 	__SetPageUptodate(page);
31741da177e4SLinus Torvalds 
317565500d23SHugh Dickins 	entry = mk_pte(page, vma->vm_page_prot);
31761ac0cb5dSHugh Dickins 	if (vma->vm_flags & VM_WRITE)
31771ac0cb5dSHugh Dickins 		entry = pte_mkwrite(pte_mkdirty(entry));
31788f4e2101SHugh Dickins 
317982b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
318082b0f8c3SJan Kara 			&vmf->ptl);
318182b0f8c3SJan Kara 	if (!pte_none(*vmf->pte))
31828f4e2101SHugh Dickins 		goto release;
31839ba69294SHugh Dickins 
31846b31d595SMichal Hocko 	ret = check_stable_address_space(vma->vm_mm);
31856b31d595SMichal Hocko 	if (ret)
31866b31d595SMichal Hocko 		goto release;
31876b31d595SMichal Hocko 
31886b251fc9SAndrea Arcangeli 	/* Deliver the page fault to userland, check inside PT lock */
31896b251fc9SAndrea Arcangeli 	if (userfaultfd_missing(vma)) {
319082b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3191f627c2f5SKirill A. Shutemov 		mem_cgroup_cancel_charge(page, memcg, false);
319209cbfeafSKirill A. Shutemov 		put_page(page);
319382b0f8c3SJan Kara 		return handle_userfault(vmf, VM_UFFD_MISSING);
31946b251fc9SAndrea Arcangeli 	}
31956b251fc9SAndrea Arcangeli 
3196bae473a4SKirill A. Shutemov 	inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
319782b0f8c3SJan Kara 	page_add_new_anon_rmap(page, vma, vmf->address, false);
3198f627c2f5SKirill A. Shutemov 	mem_cgroup_commit_charge(page, memcg, false, false);
319900501b53SJohannes Weiner 	lru_cache_add_active_or_unevictable(page, vma);
3200a13ea5b7SHugh Dickins setpte:
320182b0f8c3SJan Kara 	set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
32021da177e4SLinus Torvalds 
32031da177e4SLinus Torvalds 	/* No need to invalidate - it was non-present before */
320482b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
320565500d23SHugh Dickins unlock:
320682b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
32076b31d595SMichal Hocko 	return ret;
32088f4e2101SHugh Dickins release:
3209f627c2f5SKirill A. Shutemov 	mem_cgroup_cancel_charge(page, memcg, false);
321009cbfeafSKirill A. Shutemov 	put_page(page);
32118f4e2101SHugh Dickins 	goto unlock;
32128a9f3ccdSBalbir Singh oom_free_page:
321309cbfeafSKirill A. Shutemov 	put_page(page);
321465500d23SHugh Dickins oom:
32151da177e4SLinus Torvalds 	return VM_FAULT_OOM;
32161da177e4SLinus Torvalds }
32171da177e4SLinus Torvalds 
32189a95f3cfSPaul Cassella /*
32199a95f3cfSPaul Cassella  * The mmap_sem must have been held on entry, and may have been
32209a95f3cfSPaul Cassella  * released depending on flags and vma->vm_ops->fault() return value.
32219a95f3cfSPaul Cassella  * See filemap_fault() and __lock_page_retry().
32229a95f3cfSPaul Cassella  */
3223936ca80dSJan Kara static int __do_fault(struct vm_fault *vmf)
32247eae74afSKirill A. Shutemov {
322582b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
32267eae74afSKirill A. Shutemov 	int ret;
32277eae74afSKirill A. Shutemov 
322811bac800SDave Jiang 	ret = vma->vm_ops->fault(vmf);
32293917048dSJan Kara 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3230b1aa812bSJan Kara 			    VM_FAULT_DONE_COW)))
32317eae74afSKirill A. Shutemov 		return ret;
32327eae74afSKirill A. Shutemov 
3233667240e0SJan Kara 	if (unlikely(PageHWPoison(vmf->page))) {
32347eae74afSKirill A. Shutemov 		if (ret & VM_FAULT_LOCKED)
3235667240e0SJan Kara 			unlock_page(vmf->page);
3236667240e0SJan Kara 		put_page(vmf->page);
3237936ca80dSJan Kara 		vmf->page = NULL;
32387eae74afSKirill A. Shutemov 		return VM_FAULT_HWPOISON;
32397eae74afSKirill A. Shutemov 	}
32407eae74afSKirill A. Shutemov 
32417eae74afSKirill A. Shutemov 	if (unlikely(!(ret & VM_FAULT_LOCKED)))
3242667240e0SJan Kara 		lock_page(vmf->page);
32437eae74afSKirill A. Shutemov 	else
3244667240e0SJan Kara 		VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
32457eae74afSKirill A. Shutemov 
32467eae74afSKirill A. Shutemov 	return ret;
32477eae74afSKirill A. Shutemov }
32487eae74afSKirill A. Shutemov 
3249d0f0931dSRoss Zwisler /*
3250d0f0931dSRoss Zwisler  * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3251d0f0931dSRoss Zwisler  * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3252d0f0931dSRoss Zwisler  * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3253d0f0931dSRoss Zwisler  * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3254d0f0931dSRoss Zwisler  */
3255d0f0931dSRoss Zwisler static int pmd_devmap_trans_unstable(pmd_t *pmd)
3256d0f0931dSRoss Zwisler {
3257d0f0931dSRoss Zwisler 	return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3258d0f0931dSRoss Zwisler }
3259d0f0931dSRoss Zwisler 
326082b0f8c3SJan Kara static int pte_alloc_one_map(struct vm_fault *vmf)
32617267ec00SKirill A. Shutemov {
326282b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
32637267ec00SKirill A. Shutemov 
326482b0f8c3SJan Kara 	if (!pmd_none(*vmf->pmd))
32657267ec00SKirill A. Shutemov 		goto map_pte;
326682b0f8c3SJan Kara 	if (vmf->prealloc_pte) {
326782b0f8c3SJan Kara 		vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
326882b0f8c3SJan Kara 		if (unlikely(!pmd_none(*vmf->pmd))) {
326982b0f8c3SJan Kara 			spin_unlock(vmf->ptl);
32707267ec00SKirill A. Shutemov 			goto map_pte;
32717267ec00SKirill A. Shutemov 		}
32727267ec00SKirill A. Shutemov 
3273c4812909SKirill A. Shutemov 		mm_inc_nr_ptes(vma->vm_mm);
327482b0f8c3SJan Kara 		pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
327582b0f8c3SJan Kara 		spin_unlock(vmf->ptl);
32767f2b6ce8STobin C Harding 		vmf->prealloc_pte = NULL;
327782b0f8c3SJan Kara 	} else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))) {
32787267ec00SKirill A. Shutemov 		return VM_FAULT_OOM;
32797267ec00SKirill A. Shutemov 	}
32807267ec00SKirill A. Shutemov map_pte:
32817267ec00SKirill A. Shutemov 	/*
32827267ec00SKirill A. Shutemov 	 * If a huge pmd materialized under us just retry later.  Use
3283d0f0931dSRoss Zwisler 	 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3284d0f0931dSRoss Zwisler 	 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3285d0f0931dSRoss Zwisler 	 * under us and then back to pmd_none, as a result of MADV_DONTNEED
3286d0f0931dSRoss Zwisler 	 * running immediately after a huge pmd fault in a different thread of
3287d0f0931dSRoss Zwisler 	 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3288d0f0931dSRoss Zwisler 	 * All we have to ensure is that it is a regular pmd that we can walk
3289d0f0931dSRoss Zwisler 	 * with pte_offset_map() and we can do that through an atomic read in
3290d0f0931dSRoss Zwisler 	 * C, which is what pmd_trans_unstable() provides.
32917267ec00SKirill A. Shutemov 	 */
3292d0f0931dSRoss Zwisler 	if (pmd_devmap_trans_unstable(vmf->pmd))
32937267ec00SKirill A. Shutemov 		return VM_FAULT_NOPAGE;
32947267ec00SKirill A. Shutemov 
3295d0f0931dSRoss Zwisler 	/*
3296d0f0931dSRoss Zwisler 	 * At this point we know that our vmf->pmd points to a page of ptes
3297d0f0931dSRoss Zwisler 	 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3298d0f0931dSRoss Zwisler 	 * for the duration of the fault.  If a racing MADV_DONTNEED runs and
3299d0f0931dSRoss Zwisler 	 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3300d0f0931dSRoss Zwisler 	 * be valid and we will re-check to make sure the vmf->pte isn't
3301d0f0931dSRoss Zwisler 	 * pte_none() under vmf->ptl protection when we return to
3302d0f0931dSRoss Zwisler 	 * alloc_set_pte().
3303d0f0931dSRoss Zwisler 	 */
330482b0f8c3SJan Kara 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
330582b0f8c3SJan Kara 			&vmf->ptl);
33067267ec00SKirill A. Shutemov 	return 0;
33077267ec00SKirill A. Shutemov }
33087267ec00SKirill A. Shutemov 
3309e496cf3dSKirill A. Shutemov #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
331010102459SKirill A. Shutemov 
331110102459SKirill A. Shutemov #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
331210102459SKirill A. Shutemov static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
331310102459SKirill A. Shutemov 		unsigned long haddr)
331410102459SKirill A. Shutemov {
331510102459SKirill A. Shutemov 	if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
331610102459SKirill A. Shutemov 			(vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
331710102459SKirill A. Shutemov 		return false;
331810102459SKirill A. Shutemov 	if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
331910102459SKirill A. Shutemov 		return false;
332010102459SKirill A. Shutemov 	return true;
332110102459SKirill A. Shutemov }
332210102459SKirill A. Shutemov 
332382b0f8c3SJan Kara static void deposit_prealloc_pte(struct vm_fault *vmf)
3324953c66c2SAneesh Kumar K.V {
332582b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
3326953c66c2SAneesh Kumar K.V 
332782b0f8c3SJan Kara 	pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3328953c66c2SAneesh Kumar K.V 	/*
3329953c66c2SAneesh Kumar K.V 	 * We are going to consume the prealloc table,
3330953c66c2SAneesh Kumar K.V 	 * count that as nr_ptes.
3331953c66c2SAneesh Kumar K.V 	 */
3332c4812909SKirill A. Shutemov 	mm_inc_nr_ptes(vma->vm_mm);
33337f2b6ce8STobin C Harding 	vmf->prealloc_pte = NULL;
3334953c66c2SAneesh Kumar K.V }
3335953c66c2SAneesh Kumar K.V 
333682b0f8c3SJan Kara static int do_set_pmd(struct vm_fault *vmf, struct page *page)
333710102459SKirill A. Shutemov {
333882b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
333982b0f8c3SJan Kara 	bool write = vmf->flags & FAULT_FLAG_WRITE;
334082b0f8c3SJan Kara 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
334110102459SKirill A. Shutemov 	pmd_t entry;
334210102459SKirill A. Shutemov 	int i, ret;
334310102459SKirill A. Shutemov 
334410102459SKirill A. Shutemov 	if (!transhuge_vma_suitable(vma, haddr))
334510102459SKirill A. Shutemov 		return VM_FAULT_FALLBACK;
334610102459SKirill A. Shutemov 
334710102459SKirill A. Shutemov 	ret = VM_FAULT_FALLBACK;
334810102459SKirill A. Shutemov 	page = compound_head(page);
334910102459SKirill A. Shutemov 
3350953c66c2SAneesh Kumar K.V 	/*
3351953c66c2SAneesh Kumar K.V 	 * Archs like ppc64 need additonal space to store information
3352953c66c2SAneesh Kumar K.V 	 * related to pte entry. Use the preallocated table for that.
3353953c66c2SAneesh Kumar K.V 	 */
335482b0f8c3SJan Kara 	if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
335582b0f8c3SJan Kara 		vmf->prealloc_pte = pte_alloc_one(vma->vm_mm, vmf->address);
335682b0f8c3SJan Kara 		if (!vmf->prealloc_pte)
3357953c66c2SAneesh Kumar K.V 			return VM_FAULT_OOM;
3358953c66c2SAneesh Kumar K.V 		smp_wmb(); /* See comment in __pte_alloc() */
3359953c66c2SAneesh Kumar K.V 	}
3360953c66c2SAneesh Kumar K.V 
336182b0f8c3SJan Kara 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
336282b0f8c3SJan Kara 	if (unlikely(!pmd_none(*vmf->pmd)))
336310102459SKirill A. Shutemov 		goto out;
336410102459SKirill A. Shutemov 
336510102459SKirill A. Shutemov 	for (i = 0; i < HPAGE_PMD_NR; i++)
336610102459SKirill A. Shutemov 		flush_icache_page(vma, page + i);
336710102459SKirill A. Shutemov 
336810102459SKirill A. Shutemov 	entry = mk_huge_pmd(page, vma->vm_page_prot);
336910102459SKirill A. Shutemov 	if (write)
3370f55e1014SLinus Torvalds 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
337110102459SKirill A. Shutemov 
337210102459SKirill A. Shutemov 	add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);
337310102459SKirill A. Shutemov 	page_add_file_rmap(page, true);
3374953c66c2SAneesh Kumar K.V 	/*
3375953c66c2SAneesh Kumar K.V 	 * deposit and withdraw with pmd lock held
3376953c66c2SAneesh Kumar K.V 	 */
3377953c66c2SAneesh Kumar K.V 	if (arch_needs_pgtable_deposit())
337882b0f8c3SJan Kara 		deposit_prealloc_pte(vmf);
337910102459SKirill A. Shutemov 
338082b0f8c3SJan Kara 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
338110102459SKirill A. Shutemov 
338282b0f8c3SJan Kara 	update_mmu_cache_pmd(vma, haddr, vmf->pmd);
338310102459SKirill A. Shutemov 
338410102459SKirill A. Shutemov 	/* fault is handled */
338510102459SKirill A. Shutemov 	ret = 0;
338695ecedcdSKirill A. Shutemov 	count_vm_event(THP_FILE_MAPPED);
338710102459SKirill A. Shutemov out:
338882b0f8c3SJan Kara 	spin_unlock(vmf->ptl);
338910102459SKirill A. Shutemov 	return ret;
339010102459SKirill A. Shutemov }
339110102459SKirill A. Shutemov #else
339282b0f8c3SJan Kara static int do_set_pmd(struct vm_fault *vmf, struct page *page)
339310102459SKirill A. Shutemov {
339410102459SKirill A. Shutemov 	BUILD_BUG();
339510102459SKirill A. Shutemov 	return 0;
339610102459SKirill A. Shutemov }
339710102459SKirill A. Shutemov #endif
339810102459SKirill A. Shutemov 
33998c6e50b0SKirill A. Shutemov /**
34007267ec00SKirill A. Shutemov  * alloc_set_pte - setup new PTE entry for given page and add reverse page
34017267ec00SKirill A. Shutemov  * mapping. If needed, the fucntion allocates page table or use pre-allocated.
34028c6e50b0SKirill A. Shutemov  *
340382b0f8c3SJan Kara  * @vmf: fault environment
34047267ec00SKirill A. Shutemov  * @memcg: memcg to charge page (only for private mappings)
34058c6e50b0SKirill A. Shutemov  * @page: page to map
34068c6e50b0SKirill A. Shutemov  *
340782b0f8c3SJan Kara  * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
340882b0f8c3SJan Kara  * return.
34098c6e50b0SKirill A. Shutemov  *
34108c6e50b0SKirill A. Shutemov  * Target users are page handler itself and implementations of
34118c6e50b0SKirill A. Shutemov  * vm_ops->map_pages.
34128c6e50b0SKirill A. Shutemov  */
341382b0f8c3SJan Kara int alloc_set_pte(struct vm_fault *vmf, struct mem_cgroup *memcg,
34147267ec00SKirill A. Shutemov 		struct page *page)
34153bb97794SKirill A. Shutemov {
341682b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
341782b0f8c3SJan Kara 	bool write = vmf->flags & FAULT_FLAG_WRITE;
34183bb97794SKirill A. Shutemov 	pte_t entry;
341910102459SKirill A. Shutemov 	int ret;
342010102459SKirill A. Shutemov 
342182b0f8c3SJan Kara 	if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3422e496cf3dSKirill A. Shutemov 			IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
342310102459SKirill A. Shutemov 		/* THP on COW? */
342410102459SKirill A. Shutemov 		VM_BUG_ON_PAGE(memcg, page);
342510102459SKirill A. Shutemov 
342682b0f8c3SJan Kara 		ret = do_set_pmd(vmf, page);
342710102459SKirill A. Shutemov 		if (ret != VM_FAULT_FALLBACK)
3428b0b9b3dfSHugh Dickins 			return ret;
342910102459SKirill A. Shutemov 	}
34303bb97794SKirill A. Shutemov 
343182b0f8c3SJan Kara 	if (!vmf->pte) {
343282b0f8c3SJan Kara 		ret = pte_alloc_one_map(vmf);
34337267ec00SKirill A. Shutemov 		if (ret)
3434b0b9b3dfSHugh Dickins 			return ret;
34357267ec00SKirill A. Shutemov 	}
34367267ec00SKirill A. Shutemov 
34377267ec00SKirill A. Shutemov 	/* Re-check under ptl */
3438b0b9b3dfSHugh Dickins 	if (unlikely(!pte_none(*vmf->pte)))
3439b0b9b3dfSHugh Dickins 		return VM_FAULT_NOPAGE;
34407267ec00SKirill A. Shutemov 
34413bb97794SKirill A. Shutemov 	flush_icache_page(vma, page);
34423bb97794SKirill A. Shutemov 	entry = mk_pte(page, vma->vm_page_prot);
34433bb97794SKirill A. Shutemov 	if (write)
34443bb97794SKirill A. Shutemov 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3445bae473a4SKirill A. Shutemov 	/* copy-on-write page */
3446bae473a4SKirill A. Shutemov 	if (write && !(vma->vm_flags & VM_SHARED)) {
34473bb97794SKirill A. Shutemov 		inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
344882b0f8c3SJan Kara 		page_add_new_anon_rmap(page, vma, vmf->address, false);
34497267ec00SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, false, false);
34507267ec00SKirill A. Shutemov 		lru_cache_add_active_or_unevictable(page, vma);
34513bb97794SKirill A. Shutemov 	} else {
3452eca56ff9SJerome Marchand 		inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3453dd78feddSKirill A. Shutemov 		page_add_file_rmap(page, false);
34543bb97794SKirill A. Shutemov 	}
345582b0f8c3SJan Kara 	set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
34563bb97794SKirill A. Shutemov 
34573bb97794SKirill A. Shutemov 	/* no need to invalidate: a not-present page won't be cached */
345882b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
34597267ec00SKirill A. Shutemov 
3460b0b9b3dfSHugh Dickins 	return 0;
34613bb97794SKirill A. Shutemov }
34623bb97794SKirill A. Shutemov 
34639118c0cbSJan Kara 
34649118c0cbSJan Kara /**
34659118c0cbSJan Kara  * finish_fault - finish page fault once we have prepared the page to fault
34669118c0cbSJan Kara  *
34679118c0cbSJan Kara  * @vmf: structure describing the fault
34689118c0cbSJan Kara  *
34699118c0cbSJan Kara  * This function handles all that is needed to finish a page fault once the
34709118c0cbSJan Kara  * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
34719118c0cbSJan Kara  * given page, adds reverse page mapping, handles memcg charges and LRU
34729118c0cbSJan Kara  * addition. The function returns 0 on success, VM_FAULT_ code in case of
34739118c0cbSJan Kara  * error.
34749118c0cbSJan Kara  *
34759118c0cbSJan Kara  * The function expects the page to be locked and on success it consumes a
34769118c0cbSJan Kara  * reference of a page being mapped (for the PTE which maps it).
34779118c0cbSJan Kara  */
34789118c0cbSJan Kara int finish_fault(struct vm_fault *vmf)
34799118c0cbSJan Kara {
34809118c0cbSJan Kara 	struct page *page;
34816b31d595SMichal Hocko 	int ret = 0;
34829118c0cbSJan Kara 
34839118c0cbSJan Kara 	/* Did we COW the page? */
34849118c0cbSJan Kara 	if ((vmf->flags & FAULT_FLAG_WRITE) &&
34859118c0cbSJan Kara 	    !(vmf->vma->vm_flags & VM_SHARED))
34869118c0cbSJan Kara 		page = vmf->cow_page;
34879118c0cbSJan Kara 	else
34889118c0cbSJan Kara 		page = vmf->page;
34896b31d595SMichal Hocko 
34906b31d595SMichal Hocko 	/*
34916b31d595SMichal Hocko 	 * check even for read faults because we might have lost our CoWed
34926b31d595SMichal Hocko 	 * page
34936b31d595SMichal Hocko 	 */
34946b31d595SMichal Hocko 	if (!(vmf->vma->vm_flags & VM_SHARED))
34956b31d595SMichal Hocko 		ret = check_stable_address_space(vmf->vma->vm_mm);
34966b31d595SMichal Hocko 	if (!ret)
34979118c0cbSJan Kara 		ret = alloc_set_pte(vmf, vmf->memcg, page);
34989118c0cbSJan Kara 	if (vmf->pte)
34999118c0cbSJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
35009118c0cbSJan Kara 	return ret;
35019118c0cbSJan Kara }
35029118c0cbSJan Kara 
35033a91053aSKirill A. Shutemov static unsigned long fault_around_bytes __read_mostly =
35043a91053aSKirill A. Shutemov 	rounddown_pow_of_two(65536);
3505a9b0f861SKirill A. Shutemov 
35061592eef0SKirill A. Shutemov #ifdef CONFIG_DEBUG_FS
3507a9b0f861SKirill A. Shutemov static int fault_around_bytes_get(void *data, u64 *val)
35081592eef0SKirill A. Shutemov {
3509a9b0f861SKirill A. Shutemov 	*val = fault_around_bytes;
35101592eef0SKirill A. Shutemov 	return 0;
35111592eef0SKirill A. Shutemov }
35121592eef0SKirill A. Shutemov 
3513b4903d6eSAndrey Ryabinin /*
3514b4903d6eSAndrey Ryabinin  * fault_around_pages() and fault_around_mask() expects fault_around_bytes
3515b4903d6eSAndrey Ryabinin  * rounded down to nearest page order. It's what do_fault_around() expects to
3516b4903d6eSAndrey Ryabinin  * see.
3517b4903d6eSAndrey Ryabinin  */
3518a9b0f861SKirill A. Shutemov static int fault_around_bytes_set(void *data, u64 val)
35191592eef0SKirill A. Shutemov {
3520a9b0f861SKirill A. Shutemov 	if (val / PAGE_SIZE > PTRS_PER_PTE)
35211592eef0SKirill A. Shutemov 		return -EINVAL;
3522b4903d6eSAndrey Ryabinin 	if (val > PAGE_SIZE)
3523b4903d6eSAndrey Ryabinin 		fault_around_bytes = rounddown_pow_of_two(val);
3524b4903d6eSAndrey Ryabinin 	else
3525b4903d6eSAndrey Ryabinin 		fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
35261592eef0SKirill A. Shutemov 	return 0;
35271592eef0SKirill A. Shutemov }
35280a1345f8SYevgen Pronenko DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
3529a9b0f861SKirill A. Shutemov 		fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
35301592eef0SKirill A. Shutemov 
35311592eef0SKirill A. Shutemov static int __init fault_around_debugfs(void)
35321592eef0SKirill A. Shutemov {
35331592eef0SKirill A. Shutemov 	void *ret;
35341592eef0SKirill A. Shutemov 
35350a1345f8SYevgen Pronenko 	ret = debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
3536a9b0f861SKirill A. Shutemov 			&fault_around_bytes_fops);
35371592eef0SKirill A. Shutemov 	if (!ret)
3538a9b0f861SKirill A. Shutemov 		pr_warn("Failed to create fault_around_bytes in debugfs");
35391592eef0SKirill A. Shutemov 	return 0;
35401592eef0SKirill A. Shutemov }
35411592eef0SKirill A. Shutemov late_initcall(fault_around_debugfs);
35421592eef0SKirill A. Shutemov #endif
35438c6e50b0SKirill A. Shutemov 
35441fdb412bSKirill A. Shutemov /*
35451fdb412bSKirill A. Shutemov  * do_fault_around() tries to map few pages around the fault address. The hope
35461fdb412bSKirill A. Shutemov  * is that the pages will be needed soon and this will lower the number of
35471fdb412bSKirill A. Shutemov  * faults to handle.
35481fdb412bSKirill A. Shutemov  *
35491fdb412bSKirill A. Shutemov  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
35501fdb412bSKirill A. Shutemov  * not ready to be mapped: not up-to-date, locked, etc.
35511fdb412bSKirill A. Shutemov  *
35521fdb412bSKirill A. Shutemov  * This function is called with the page table lock taken. In the split ptlock
35531fdb412bSKirill A. Shutemov  * case the page table lock only protects only those entries which belong to
35541fdb412bSKirill A. Shutemov  * the page table corresponding to the fault address.
35551fdb412bSKirill A. Shutemov  *
35561fdb412bSKirill A. Shutemov  * This function doesn't cross the VMA boundaries, in order to call map_pages()
35571fdb412bSKirill A. Shutemov  * only once.
35581fdb412bSKirill A. Shutemov  *
35591fdb412bSKirill A. Shutemov  * fault_around_pages() defines how many pages we'll try to map.
35601fdb412bSKirill A. Shutemov  * do_fault_around() expects it to return a power of two less than or equal to
35611fdb412bSKirill A. Shutemov  * PTRS_PER_PTE.
35621fdb412bSKirill A. Shutemov  *
35631fdb412bSKirill A. Shutemov  * The virtual address of the area that we map is naturally aligned to the
35641fdb412bSKirill A. Shutemov  * fault_around_pages() value (and therefore to page order).  This way it's
35651fdb412bSKirill A. Shutemov  * easier to guarantee that we don't cross page table boundaries.
35661fdb412bSKirill A. Shutemov  */
35670721ec8bSJan Kara static int do_fault_around(struct vm_fault *vmf)
35688c6e50b0SKirill A. Shutemov {
356982b0f8c3SJan Kara 	unsigned long address = vmf->address, nr_pages, mask;
35700721ec8bSJan Kara 	pgoff_t start_pgoff = vmf->pgoff;
3571bae473a4SKirill A. Shutemov 	pgoff_t end_pgoff;
35727267ec00SKirill A. Shutemov 	int off, ret = 0;
35738c6e50b0SKirill A. Shutemov 
35744db0c3c2SJason Low 	nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3575aecd6f44SKirill A. Shutemov 	mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3576aecd6f44SKirill A. Shutemov 
357782b0f8c3SJan Kara 	vmf->address = max(address & mask, vmf->vma->vm_start);
357882b0f8c3SJan Kara 	off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3579bae473a4SKirill A. Shutemov 	start_pgoff -= off;
35808c6e50b0SKirill A. Shutemov 
35818c6e50b0SKirill A. Shutemov 	/*
3582bae473a4SKirill A. Shutemov 	 *  end_pgoff is either end of page table or end of vma
3583bae473a4SKirill A. Shutemov 	 *  or fault_around_pages() from start_pgoff, depending what is nearest.
35848c6e50b0SKirill A. Shutemov 	 */
3585bae473a4SKirill A. Shutemov 	end_pgoff = start_pgoff -
358682b0f8c3SJan Kara 		((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
35878c6e50b0SKirill A. Shutemov 		PTRS_PER_PTE - 1;
358882b0f8c3SJan Kara 	end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
3589bae473a4SKirill A. Shutemov 			start_pgoff + nr_pages - 1);
35908c6e50b0SKirill A. Shutemov 
359182b0f8c3SJan Kara 	if (pmd_none(*vmf->pmd)) {
359282b0f8c3SJan Kara 		vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
359382b0f8c3SJan Kara 						  vmf->address);
359482b0f8c3SJan Kara 		if (!vmf->prealloc_pte)
3595c5f88bd2SVegard Nossum 			goto out;
35967267ec00SKirill A. Shutemov 		smp_wmb(); /* See comment in __pte_alloc() */
35978c6e50b0SKirill A. Shutemov 	}
35988c6e50b0SKirill A. Shutemov 
359982b0f8c3SJan Kara 	vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
36007267ec00SKirill A. Shutemov 
36017267ec00SKirill A. Shutemov 	/* Huge page is mapped? Page fault is solved */
360282b0f8c3SJan Kara 	if (pmd_trans_huge(*vmf->pmd)) {
36037267ec00SKirill A. Shutemov 		ret = VM_FAULT_NOPAGE;
36047267ec00SKirill A. Shutemov 		goto out;
36058c6e50b0SKirill A. Shutemov 	}
36068c6e50b0SKirill A. Shutemov 
36077267ec00SKirill A. Shutemov 	/* ->map_pages() haven't done anything useful. Cold page cache? */
360882b0f8c3SJan Kara 	if (!vmf->pte)
36097267ec00SKirill A. Shutemov 		goto out;
36107267ec00SKirill A. Shutemov 
36117267ec00SKirill A. Shutemov 	/* check if the page fault is solved */
361282b0f8c3SJan Kara 	vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
361382b0f8c3SJan Kara 	if (!pte_none(*vmf->pte))
36147267ec00SKirill A. Shutemov 		ret = VM_FAULT_NOPAGE;
361582b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
36167267ec00SKirill A. Shutemov out:
361782b0f8c3SJan Kara 	vmf->address = address;
361882b0f8c3SJan Kara 	vmf->pte = NULL;
36197267ec00SKirill A. Shutemov 	return ret;
36207267ec00SKirill A. Shutemov }
36217267ec00SKirill A. Shutemov 
36220721ec8bSJan Kara static int do_read_fault(struct vm_fault *vmf)
3623e655fb29SKirill A. Shutemov {
362482b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
36258c6e50b0SKirill A. Shutemov 	int ret = 0;
36268c6e50b0SKirill A. Shutemov 
36278c6e50b0SKirill A. Shutemov 	/*
36288c6e50b0SKirill A. Shutemov 	 * Let's call ->map_pages() first and use ->fault() as fallback
36298c6e50b0SKirill A. Shutemov 	 * if page by the offset is not ready to be mapped (cold cache or
36308c6e50b0SKirill A. Shutemov 	 * something).
36318c6e50b0SKirill A. Shutemov 	 */
36329b4bdd2fSKirill A. Shutemov 	if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
36330721ec8bSJan Kara 		ret = do_fault_around(vmf);
36347267ec00SKirill A. Shutemov 		if (ret)
36357267ec00SKirill A. Shutemov 			return ret;
36368c6e50b0SKirill A. Shutemov 	}
3637e655fb29SKirill A. Shutemov 
3638936ca80dSJan Kara 	ret = __do_fault(vmf);
3639e655fb29SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3640e655fb29SKirill A. Shutemov 		return ret;
3641e655fb29SKirill A. Shutemov 
36429118c0cbSJan Kara 	ret |= finish_fault(vmf);
3643936ca80dSJan Kara 	unlock_page(vmf->page);
36447267ec00SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3645936ca80dSJan Kara 		put_page(vmf->page);
3646e655fb29SKirill A. Shutemov 	return ret;
3647e655fb29SKirill A. Shutemov }
3648e655fb29SKirill A. Shutemov 
36490721ec8bSJan Kara static int do_cow_fault(struct vm_fault *vmf)
3650ec47c3b9SKirill A. Shutemov {
365182b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
3652ec47c3b9SKirill A. Shutemov 	int ret;
3653ec47c3b9SKirill A. Shutemov 
3654ec47c3b9SKirill A. Shutemov 	if (unlikely(anon_vma_prepare(vma)))
3655ec47c3b9SKirill A. Shutemov 		return VM_FAULT_OOM;
3656ec47c3b9SKirill A. Shutemov 
3657936ca80dSJan Kara 	vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3658936ca80dSJan Kara 	if (!vmf->cow_page)
3659ec47c3b9SKirill A. Shutemov 		return VM_FAULT_OOM;
3660ec47c3b9SKirill A. Shutemov 
3661936ca80dSJan Kara 	if (mem_cgroup_try_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL,
36623917048dSJan Kara 				&vmf->memcg, false)) {
3663936ca80dSJan Kara 		put_page(vmf->cow_page);
3664ec47c3b9SKirill A. Shutemov 		return VM_FAULT_OOM;
3665ec47c3b9SKirill A. Shutemov 	}
3666ec47c3b9SKirill A. Shutemov 
3667936ca80dSJan Kara 	ret = __do_fault(vmf);
3668ec47c3b9SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3669ec47c3b9SKirill A. Shutemov 		goto uncharge_out;
36703917048dSJan Kara 	if (ret & VM_FAULT_DONE_COW)
36713917048dSJan Kara 		return ret;
3672ec47c3b9SKirill A. Shutemov 
3673936ca80dSJan Kara 	copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
3674936ca80dSJan Kara 	__SetPageUptodate(vmf->cow_page);
3675ec47c3b9SKirill A. Shutemov 
36769118c0cbSJan Kara 	ret |= finish_fault(vmf);
3677936ca80dSJan Kara 	unlock_page(vmf->page);
3678936ca80dSJan Kara 	put_page(vmf->page);
36797267ec00SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
36807267ec00SKirill A. Shutemov 		goto uncharge_out;
3681ec47c3b9SKirill A. Shutemov 	return ret;
3682ec47c3b9SKirill A. Shutemov uncharge_out:
36833917048dSJan Kara 	mem_cgroup_cancel_charge(vmf->cow_page, vmf->memcg, false);
3684936ca80dSJan Kara 	put_page(vmf->cow_page);
3685ec47c3b9SKirill A. Shutemov 	return ret;
3686ec47c3b9SKirill A. Shutemov }
3687ec47c3b9SKirill A. Shutemov 
36880721ec8bSJan Kara static int do_shared_fault(struct vm_fault *vmf)
36891da177e4SLinus Torvalds {
369082b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
3691f0c6d4d2SKirill A. Shutemov 	int ret, tmp;
36921d65f86dSKAMEZAWA Hiroyuki 
3693936ca80dSJan Kara 	ret = __do_fault(vmf);
36947eae74afSKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3695f0c6d4d2SKirill A. Shutemov 		return ret;
36961da177e4SLinus Torvalds 
36971da177e4SLinus Torvalds 	/*
3698f0c6d4d2SKirill A. Shutemov 	 * Check if the backing address space wants to know that the page is
3699f0c6d4d2SKirill A. Shutemov 	 * about to become writable
37001da177e4SLinus Torvalds 	 */
3701fb09a464SKirill A. Shutemov 	if (vma->vm_ops->page_mkwrite) {
3702936ca80dSJan Kara 		unlock_page(vmf->page);
370338b8cb7fSJan Kara 		tmp = do_page_mkwrite(vmf);
3704fb09a464SKirill A. Shutemov 		if (unlikely(!tmp ||
3705fb09a464SKirill A. Shutemov 				(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3706936ca80dSJan Kara 			put_page(vmf->page);
3707f0c6d4d2SKirill A. Shutemov 			return tmp;
370869676147SMark Fasheh 		}
3709d0217ac0SNick Piggin 	}
3710fb09a464SKirill A. Shutemov 
37119118c0cbSJan Kara 	ret |= finish_fault(vmf);
37127267ec00SKirill A. Shutemov 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
37137267ec00SKirill A. Shutemov 					VM_FAULT_RETRY))) {
3714936ca80dSJan Kara 		unlock_page(vmf->page);
3715936ca80dSJan Kara 		put_page(vmf->page);
3716f0c6d4d2SKirill A. Shutemov 		return ret;
37179637a5efSDavid Howells 	}
3718d00806b1SNick Piggin 
371997ba0c2bSJan Kara 	fault_dirty_shared_page(vma, vmf->page);
3720b827e496SNick Piggin 	return ret;
372154cb8821SNick Piggin }
3722d00806b1SNick Piggin 
37239a95f3cfSPaul Cassella /*
37249a95f3cfSPaul Cassella  * We enter with non-exclusive mmap_sem (to exclude vma changes,
37259a95f3cfSPaul Cassella  * but allow concurrent faults).
37269a95f3cfSPaul Cassella  * The mmap_sem may have been released depending on flags and our
37279a95f3cfSPaul Cassella  * return value.  See filemap_fault() and __lock_page_or_retry().
37289a95f3cfSPaul Cassella  */
372982b0f8c3SJan Kara static int do_fault(struct vm_fault *vmf)
373054cb8821SNick Piggin {
373182b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
3732b0b9b3dfSHugh Dickins 	int ret;
373354cb8821SNick Piggin 
37346b7339f4SKirill A. Shutemov 	/* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
37356b7339f4SKirill A. Shutemov 	if (!vma->vm_ops->fault)
3736b0b9b3dfSHugh Dickins 		ret = VM_FAULT_SIGBUS;
3737b0b9b3dfSHugh Dickins 	else if (!(vmf->flags & FAULT_FLAG_WRITE))
3738b0b9b3dfSHugh Dickins 		ret = do_read_fault(vmf);
3739b0b9b3dfSHugh Dickins 	else if (!(vma->vm_flags & VM_SHARED))
3740b0b9b3dfSHugh Dickins 		ret = do_cow_fault(vmf);
3741b0b9b3dfSHugh Dickins 	else
3742b0b9b3dfSHugh Dickins 		ret = do_shared_fault(vmf);
3743b0b9b3dfSHugh Dickins 
3744b0b9b3dfSHugh Dickins 	/* preallocated pagetable is unused: free it */
3745b0b9b3dfSHugh Dickins 	if (vmf->prealloc_pte) {
3746b0b9b3dfSHugh Dickins 		pte_free(vma->vm_mm, vmf->prealloc_pte);
37477f2b6ce8STobin C Harding 		vmf->prealloc_pte = NULL;
3748b0b9b3dfSHugh Dickins 	}
3749b0b9b3dfSHugh Dickins 	return ret;
375054cb8821SNick Piggin }
375154cb8821SNick Piggin 
3752b19a9939SRashika Kheria static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
375304bb2f94SRik van Riel 				unsigned long addr, int page_nid,
375404bb2f94SRik van Riel 				int *flags)
37559532fec1SMel Gorman {
37569532fec1SMel Gorman 	get_page(page);
37579532fec1SMel Gorman 
37589532fec1SMel Gorman 	count_vm_numa_event(NUMA_HINT_FAULTS);
375904bb2f94SRik van Riel 	if (page_nid == numa_node_id()) {
37609532fec1SMel Gorman 		count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
376104bb2f94SRik van Riel 		*flags |= TNF_FAULT_LOCAL;
376204bb2f94SRik van Riel 	}
37639532fec1SMel Gorman 
37649532fec1SMel Gorman 	return mpol_misplaced(page, vma, addr);
37659532fec1SMel Gorman }
37669532fec1SMel Gorman 
37672994302bSJan Kara static int do_numa_page(struct vm_fault *vmf)
3768d10e63f2SMel Gorman {
376982b0f8c3SJan Kara 	struct vm_area_struct *vma = vmf->vma;
37704daae3b4SMel Gorman 	struct page *page = NULL;
37718191acbdSMel Gorman 	int page_nid = -1;
377290572890SPeter Zijlstra 	int last_cpupid;
3773cbee9f88SPeter Zijlstra 	int target_nid;
3774b8593bfdSMel Gorman 	bool migrated = false;
3775cee216a6SAneesh Kumar K.V 	pte_t pte;
3776288bc549SAneesh Kumar K.V 	bool was_writable = pte_savedwrite(vmf->orig_pte);
37776688cc05SPeter Zijlstra 	int flags = 0;
3778d10e63f2SMel Gorman 
3779d10e63f2SMel Gorman 	/*
3780d10e63f2SMel Gorman 	 * The "pte" at this point cannot be used safely without
3781d10e63f2SMel Gorman 	 * validation through pte_unmap_same(). It's of NUMA type but
3782d10e63f2SMel Gorman 	 * the pfn may be screwed if the read is non atomic.
3783d10e63f2SMel Gorman 	 */
378482b0f8c3SJan Kara 	vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
378582b0f8c3SJan Kara 	spin_lock(vmf->ptl);
3786cee216a6SAneesh Kumar K.V 	if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
378782b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
37884daae3b4SMel Gorman 		goto out;
37894daae3b4SMel Gorman 	}
37904daae3b4SMel Gorman 
3791cee216a6SAneesh Kumar K.V 	/*
3792cee216a6SAneesh Kumar K.V 	 * Make it present again, Depending on how arch implementes non
3793cee216a6SAneesh Kumar K.V 	 * accessible ptes, some can allow access by kernel mode.
3794cee216a6SAneesh Kumar K.V 	 */
3795cee216a6SAneesh Kumar K.V 	pte = ptep_modify_prot_start(vma->vm_mm, vmf->address, vmf->pte);
37964d942466SMel Gorman 	pte = pte_modify(pte, vma->vm_page_prot);
37974d942466SMel Gorman 	pte = pte_mkyoung(pte);
3798b191f9b1SMel Gorman 	if (was_writable)
3799b191f9b1SMel Gorman 		pte = pte_mkwrite(pte);
3800cee216a6SAneesh Kumar K.V 	ptep_modify_prot_commit(vma->vm_mm, vmf->address, vmf->pte, pte);
380182b0f8c3SJan Kara 	update_mmu_cache(vma, vmf->address, vmf->pte);
3802d10e63f2SMel Gorman 
380382b0f8c3SJan Kara 	page = vm_normal_page(vma, vmf->address, pte);
3804d10e63f2SMel Gorman 	if (!page) {
380582b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3806d10e63f2SMel Gorman 		return 0;
3807d10e63f2SMel Gorman 	}
3808d10e63f2SMel Gorman 
3809e81c4802SKirill A. Shutemov 	/* TODO: handle PTE-mapped THP */
3810e81c4802SKirill A. Shutemov 	if (PageCompound(page)) {
381182b0f8c3SJan Kara 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3812e81c4802SKirill A. Shutemov 		return 0;
3813e81c4802SKirill A. Shutemov 	}
3814e81c4802SKirill A. Shutemov 
38156688cc05SPeter Zijlstra 	/*
3816bea66fbdSMel Gorman 	 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3817bea66fbdSMel Gorman 	 * much anyway since they can be in shared cache state. This misses
3818bea66fbdSMel Gorman 	 * the case where a mapping is writable but the process never writes
3819bea66fbdSMel Gorman 	 * to it but pte_write gets cleared during protection updates and
3820bea66fbdSMel Gorman 	 * pte_dirty has unpredictable behaviour between PTE scan updates,
3821bea66fbdSMel Gorman 	 * background writeback, dirty balancing and application behaviour.
38226688cc05SPeter Zijlstra 	 */
3823d59dc7bcSRik van Riel 	if (!pte_write(pte))
38246688cc05SPeter Zijlstra 		flags |= TNF_NO_GROUP;
38256688cc05SPeter Zijlstra 
3826dabe1d99SRik van Riel 	/*
3827dabe1d99SRik van Riel 	 * Flag if the page is shared between multiple address spaces. This
3828dabe1d99SRik van Riel 	 * is later used when determining whether to group tasks together
3829dabe1d99SRik van Riel 	 */
3830dabe1d99SRik van Riel 	if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3831dabe1d99SRik van Riel 		flags |= TNF_SHARED;
3832dabe1d99SRik van Riel 
383390572890SPeter Zijlstra 	last_cpupid = page_cpupid_last(page);
38348191acbdSMel Gorman 	page_nid = page_to_nid(page);
383582b0f8c3SJan Kara 	target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
3836bae473a4SKirill A. Shutemov 			&flags);
383782b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
38384daae3b4SMel Gorman 	if (target_nid == -1) {
38394daae3b4SMel Gorman 		put_page(page);
38404daae3b4SMel Gorman 		goto out;
38414daae3b4SMel Gorman 	}
38424daae3b4SMel Gorman 
38434daae3b4SMel Gorman 	/* Migrate to the requested node */
38441bc115d8SMel Gorman 	migrated = migrate_misplaced_page(page, vma, target_nid);
38456688cc05SPeter Zijlstra 	if (migrated) {
38468191acbdSMel Gorman 		page_nid = target_nid;
38476688cc05SPeter Zijlstra 		flags |= TNF_MIGRATED;
3848074c2381SMel Gorman 	} else
3849074c2381SMel Gorman 		flags |= TNF_MIGRATE_FAIL;
38504daae3b4SMel Gorman 
38514daae3b4SMel Gorman out:
38528191acbdSMel Gorman 	if (page_nid != -1)
38536688cc05SPeter Zijlstra 		task_numa_fault(last_cpupid, page_nid, 1, flags);
3854d10e63f2SMel Gorman 	return 0;
3855d10e63f2SMel Gorman }
3856d10e63f2SMel Gorman 
385791a90140SGeert Uytterhoeven static inline int create_huge_pmd(struct vm_fault *vmf)
3858b96375f7SMatthew Wilcox {
3859f4200391SDave Jiang 	if (vma_is_anonymous(vmf->vma))
386082b0f8c3SJan Kara 		return do_huge_pmd_anonymous_page(vmf);
3861a2d58167SDave Jiang 	if (vmf->vma->vm_ops->huge_fault)
3862c791ace1SDave Jiang 		return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3863b96375f7SMatthew Wilcox 	return VM_FAULT_FALLBACK;
3864b96375f7SMatthew Wilcox }
3865b96375f7SMatthew Wilcox 
3866183f24aaSGeert Uytterhoeven /* `inline' is required to avoid gcc 4.1.2 build error */
3867183f24aaSGeert Uytterhoeven static inline int wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
3868b96375f7SMatthew Wilcox {
386982b0f8c3SJan Kara 	if (vma_is_anonymous(vmf->vma))
387082b0f8c3SJan Kara 		return do_huge_pmd_wp_page(vmf, orig_pmd);
3871a2d58167SDave Jiang 	if (vmf->vma->vm_ops->huge_fault)
3872c791ace1SDave Jiang 		return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3873af9e4d5fSKirill A. Shutemov 
3874af9e4d5fSKirill A. Shutemov 	/* COW handled on pte level: split pmd */
387582b0f8c3SJan Kara 	VM_BUG_ON_VMA(vmf->vma->vm_flags & VM_SHARED, vmf->vma);
387682b0f8c3SJan Kara 	__split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
3877af9e4d5fSKirill A. Shutemov 
3878b96375f7SMatthew Wilcox 	return VM_FAULT_FALLBACK;
3879b96375f7SMatthew Wilcox }
3880b96375f7SMatthew Wilcox 
388138e08854SLorenzo Stoakes static inline bool vma_is_accessible(struct vm_area_struct *vma)
388238e08854SLorenzo Stoakes {
388338e08854SLorenzo Stoakes 	return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
388438e08854SLorenzo Stoakes }
388538e08854SLorenzo Stoakes 
3886a00cc7d9SMatthew Wilcox static int create_huge_pud(struct vm_fault *vmf)
3887a00cc7d9SMatthew Wilcox {
3888a00cc7d9SMatthew Wilcox #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3889a00cc7d9SMatthew Wilcox 	/* No support for anonymous transparent PUD pages yet */
3890a00cc7d9SMatthew Wilcox 	if (vma_is_anonymous(vmf->vma))
3891a00cc7d9SMatthew Wilcox 		return VM_FAULT_FALLBACK;
3892a00cc7d9SMatthew Wilcox 	if (vmf->vma->vm_ops->huge_fault)
3893c791ace1SDave Jiang 		return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
3894a00cc7d9SMatthew Wilcox #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3895a00cc7d9SMatthew Wilcox 	return VM_FAULT_FALLBACK;
3896a00cc7d9SMatthew Wilcox }
3897a00cc7d9SMatthew Wilcox 
3898a00cc7d9SMatthew Wilcox static int wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
3899a00cc7d9SMatthew Wilcox {
3900a00cc7d9SMatthew Wilcox #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3901a00cc7d9SMatthew Wilcox 	/* No support for anonymous transparent PUD pages yet */
3902a00cc7d9SMatthew Wilcox 	if (vma_is_anonymous(vmf->vma))
3903a00cc7d9SMatthew Wilcox 		return VM_FAULT_FALLBACK;
3904a00cc7d9SMatthew Wilcox 	if (vmf->vma->vm_ops->huge_fault)
3905c791ace1SDave Jiang 		return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
3906a00cc7d9SMatthew Wilcox #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3907a00cc7d9SMatthew Wilcox 	return VM_FAULT_FALLBACK;
3908a00cc7d9SMatthew Wilcox }
3909a00cc7d9SMatthew Wilcox 
39101da177e4SLinus Torvalds /*
39111da177e4SLinus Torvalds  * These routines also need to handle stuff like marking pages dirty
39121da177e4SLinus Torvalds  * and/or accessed for architectures that don't do it in hardware (most
39131da177e4SLinus Torvalds  * RISC architectures).  The early dirtying is also good on the i386.
39141da177e4SLinus Torvalds  *
39151da177e4SLinus Torvalds  * There is also a hook called "update_mmu_cache()" that architectures
39161da177e4SLinus Torvalds  * with external mmu caches can use to update those (ie the Sparc or
39171da177e4SLinus Torvalds  * PowerPC hashed page tables that act as extended TLBs).
39181da177e4SLinus Torvalds  *
39197267ec00SKirill A. Shutemov  * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
39207267ec00SKirill A. Shutemov  * concurrent faults).
39219a95f3cfSPaul Cassella  *
39227267ec00SKirill A. Shutemov  * The mmap_sem may have been released depending on flags and our return value.
39237267ec00SKirill A. Shutemov  * See filemap_fault() and __lock_page_or_retry().
39241da177e4SLinus Torvalds  */
392582b0f8c3SJan Kara static int handle_pte_fault(struct vm_fault *vmf)
39261da177e4SLinus Torvalds {
39271da177e4SLinus Torvalds 	pte_t entry;
39281da177e4SLinus Torvalds 
392982b0f8c3SJan Kara 	if (unlikely(pmd_none(*vmf->pmd))) {
39307267ec00SKirill A. Shutemov 		/*
39317267ec00SKirill A. Shutemov 		 * Leave __pte_alloc() until later: because vm_ops->fault may
39327267ec00SKirill A. Shutemov 		 * want to allocate huge page, and if we expose page table
39337267ec00SKirill A. Shutemov 		 * for an instant, it will be difficult to retract from
39347267ec00SKirill A. Shutemov 		 * concurrent faults and from rmap lookups.
39357267ec00SKirill A. Shutemov 		 */
393682b0f8c3SJan Kara 		vmf->pte = NULL;
39377267ec00SKirill A. Shutemov 	} else {
39387267ec00SKirill A. Shutemov 		/* See comment in pte_alloc_one_map() */
3939d0f0931dSRoss Zwisler 		if (pmd_devmap_trans_unstable(vmf->pmd))
39407267ec00SKirill A. Shutemov 			return 0;
39417267ec00SKirill A. Shutemov 		/*
39427267ec00SKirill A. Shutemov 		 * A regular pmd is established and it can't morph into a huge
39437267ec00SKirill A. Shutemov 		 * pmd from under us anymore at this point because we hold the
39447267ec00SKirill A. Shutemov 		 * mmap_sem read mode and khugepaged takes it in write mode.
39457267ec00SKirill A. Shutemov 		 * So now it's safe to run pte_offset_map().
39467267ec00SKirill A. Shutemov 		 */
394782b0f8c3SJan Kara 		vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
39482994302bSJan Kara 		vmf->orig_pte = *vmf->pte;
39497267ec00SKirill A. Shutemov 
3950e37c6982SChristian Borntraeger 		/*
3951e37c6982SChristian Borntraeger 		 * some architectures can have larger ptes than wordsize,
39527267ec00SKirill A. Shutemov 		 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
3953b03a0fe0SPaul E. McKenney 		 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
3954b03a0fe0SPaul E. McKenney 		 * accesses.  The code below just needs a consistent view
3955b03a0fe0SPaul E. McKenney 		 * for the ifs and we later double check anyway with the
39567267ec00SKirill A. Shutemov 		 * ptl lock held. So here a barrier will do.
3957e37c6982SChristian Borntraeger 		 */
3958e37c6982SChristian Borntraeger 		barrier();
39592994302bSJan Kara 		if (pte_none(vmf->orig_pte)) {
396082b0f8c3SJan Kara 			pte_unmap(vmf->pte);
396182b0f8c3SJan Kara 			vmf->pte = NULL;
39627267ec00SKirill A. Shutemov 		}
39637267ec00SKirill A. Shutemov 	}
39647267ec00SKirill A. Shutemov 
396582b0f8c3SJan Kara 	if (!vmf->pte) {
396682b0f8c3SJan Kara 		if (vma_is_anonymous(vmf->vma))
396782b0f8c3SJan Kara 			return do_anonymous_page(vmf);
3968b5330628SOleg Nesterov 		else
396982b0f8c3SJan Kara 			return do_fault(vmf);
397065500d23SHugh Dickins 	}
39717267ec00SKirill A. Shutemov 
39722994302bSJan Kara 	if (!pte_present(vmf->orig_pte))
39732994302bSJan Kara 		return do_swap_page(vmf);
39741da177e4SLinus Torvalds 
39752994302bSJan Kara 	if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
39762994302bSJan Kara 		return do_numa_page(vmf);
3977d10e63f2SMel Gorman 
397882b0f8c3SJan Kara 	vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
397982b0f8c3SJan Kara 	spin_lock(vmf->ptl);
39802994302bSJan Kara 	entry = vmf->orig_pte;
398182b0f8c3SJan Kara 	if (unlikely(!pte_same(*vmf->pte, entry)))
39828f4e2101SHugh Dickins 		goto unlock;
398382b0f8c3SJan Kara 	if (vmf->flags & FAULT_FLAG_WRITE) {
3984f6f37321SLinus Torvalds 		if (!pte_write(entry))
39852994302bSJan Kara 			return do_wp_page(vmf);
39861da177e4SLinus Torvalds 		entry = pte_mkdirty(entry);
39871da177e4SLinus Torvalds 	}
39881da177e4SLinus Torvalds 	entry = pte_mkyoung(entry);
398982b0f8c3SJan Kara 	if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
399082b0f8c3SJan Kara 				vmf->flags & FAULT_FLAG_WRITE)) {
399182b0f8c3SJan Kara 		update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
39921a44e149SAndrea Arcangeli 	} else {
39931a44e149SAndrea Arcangeli 		/*
39941a44e149SAndrea Arcangeli 		 * This is needed only for protection faults but the arch code
39951a44e149SAndrea Arcangeli 		 * is not yet telling us if this is a protection fault or not.
39961a44e149SAndrea Arcangeli 		 * This still avoids useless tlb flushes for .text page faults
39971a44e149SAndrea Arcangeli 		 * with threads.
39981a44e149SAndrea Arcangeli 		 */
399982b0f8c3SJan Kara 		if (vmf->flags & FAULT_FLAG_WRITE)
400082b0f8c3SJan Kara 			flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
40011a44e149SAndrea Arcangeli 	}
40028f4e2101SHugh Dickins unlock:
400382b0f8c3SJan Kara 	pte_unmap_unlock(vmf->pte, vmf->ptl);
400483c54070SNick Piggin 	return 0;
40051da177e4SLinus Torvalds }
40061da177e4SLinus Torvalds 
40071da177e4SLinus Torvalds /*
40081da177e4SLinus Torvalds  * By the time we get here, we already hold the mm semaphore
40099a95f3cfSPaul Cassella  *
40109a95f3cfSPaul Cassella  * The mmap_sem may have been released depending on flags and our
40119a95f3cfSPaul Cassella  * return value.  See filemap_fault() and __lock_page_or_retry().
40121da177e4SLinus Torvalds  */
4013dcddffd4SKirill A. Shutemov static int __handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4014dcddffd4SKirill A. Shutemov 		unsigned int flags)
40151da177e4SLinus Torvalds {
401682b0f8c3SJan Kara 	struct vm_fault vmf = {
4017bae473a4SKirill A. Shutemov 		.vma = vma,
40181a29d85eSJan Kara 		.address = address & PAGE_MASK,
4019bae473a4SKirill A. Shutemov 		.flags = flags,
40200721ec8bSJan Kara 		.pgoff = linear_page_index(vma, address),
4021667240e0SJan Kara 		.gfp_mask = __get_fault_gfp_mask(vma),
4022bae473a4SKirill A. Shutemov 	};
4023fde26bedSAnshuman Khandual 	unsigned int dirty = flags & FAULT_FLAG_WRITE;
4024dcddffd4SKirill A. Shutemov 	struct mm_struct *mm = vma->vm_mm;
40251da177e4SLinus Torvalds 	pgd_t *pgd;
4026c2febafcSKirill A. Shutemov 	p4d_t *p4d;
4027a2d58167SDave Jiang 	int ret;
40281da177e4SLinus Torvalds 
40291da177e4SLinus Torvalds 	pgd = pgd_offset(mm, address);
4030c2febafcSKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, address);
4031c2febafcSKirill A. Shutemov 	if (!p4d)
4032c2febafcSKirill A. Shutemov 		return VM_FAULT_OOM;
4033a00cc7d9SMatthew Wilcox 
4034c2febafcSKirill A. Shutemov 	vmf.pud = pud_alloc(mm, p4d, address);
4035a00cc7d9SMatthew Wilcox 	if (!vmf.pud)
4036c74df32cSHugh Dickins 		return VM_FAULT_OOM;
4037a00cc7d9SMatthew Wilcox 	if (pud_none(*vmf.pud) && transparent_hugepage_enabled(vma)) {
4038a00cc7d9SMatthew Wilcox 		ret = create_huge_pud(&vmf);
4039a00cc7d9SMatthew Wilcox 		if (!(ret & VM_FAULT_FALLBACK))
4040a00cc7d9SMatthew Wilcox 			return ret;
4041a00cc7d9SMatthew Wilcox 	} else {
4042a00cc7d9SMatthew Wilcox 		pud_t orig_pud = *vmf.pud;
4043a00cc7d9SMatthew Wilcox 
4044a00cc7d9SMatthew Wilcox 		barrier();
4045a00cc7d9SMatthew Wilcox 		if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4046a00cc7d9SMatthew Wilcox 
4047a00cc7d9SMatthew Wilcox 			/* NUMA case for anonymous PUDs would go here */
4048a00cc7d9SMatthew Wilcox 
4049f6f37321SLinus Torvalds 			if (dirty && !pud_write(orig_pud)) {
4050a00cc7d9SMatthew Wilcox 				ret = wp_huge_pud(&vmf, orig_pud);
4051a00cc7d9SMatthew Wilcox 				if (!(ret & VM_FAULT_FALLBACK))
4052a00cc7d9SMatthew Wilcox 					return ret;
4053a00cc7d9SMatthew Wilcox 			} else {
4054a00cc7d9SMatthew Wilcox 				huge_pud_set_accessed(&vmf, orig_pud);
4055a00cc7d9SMatthew Wilcox 				return 0;
4056a00cc7d9SMatthew Wilcox 			}
4057a00cc7d9SMatthew Wilcox 		}
4058a00cc7d9SMatthew Wilcox 	}
4059a00cc7d9SMatthew Wilcox 
4060a00cc7d9SMatthew Wilcox 	vmf.pmd = pmd_alloc(mm, vmf.pud, address);
406182b0f8c3SJan Kara 	if (!vmf.pmd)
4062c74df32cSHugh Dickins 		return VM_FAULT_OOM;
406382b0f8c3SJan Kara 	if (pmd_none(*vmf.pmd) && transparent_hugepage_enabled(vma)) {
4064a2d58167SDave Jiang 		ret = create_huge_pmd(&vmf);
4065c0292554SKirill A. Shutemov 		if (!(ret & VM_FAULT_FALLBACK))
4066c0292554SKirill A. Shutemov 			return ret;
406771e3aac0SAndrea Arcangeli 	} else {
406882b0f8c3SJan Kara 		pmd_t orig_pmd = *vmf.pmd;
40691f1d06c3SDavid Rientjes 
407071e3aac0SAndrea Arcangeli 		barrier();
407184c3fc4eSZi Yan 		if (unlikely(is_swap_pmd(orig_pmd))) {
407284c3fc4eSZi Yan 			VM_BUG_ON(thp_migration_supported() &&
407384c3fc4eSZi Yan 					  !is_pmd_migration_entry(orig_pmd));
407484c3fc4eSZi Yan 			if (is_pmd_migration_entry(orig_pmd))
407584c3fc4eSZi Yan 				pmd_migration_entry_wait(mm, vmf.pmd);
407684c3fc4eSZi Yan 			return 0;
407784c3fc4eSZi Yan 		}
40785c7fb56eSDan Williams 		if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
407938e08854SLorenzo Stoakes 			if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
408082b0f8c3SJan Kara 				return do_huge_pmd_numa_page(&vmf, orig_pmd);
4081d10e63f2SMel Gorman 
4082f6f37321SLinus Torvalds 			if (dirty && !pmd_write(orig_pmd)) {
408382b0f8c3SJan Kara 				ret = wp_huge_pmd(&vmf, orig_pmd);
40849845cbbdSKirill A. Shutemov 				if (!(ret & VM_FAULT_FALLBACK))
40851f1d06c3SDavid Rientjes 					return ret;
4086a1dd450bSWill Deacon 			} else {
408782b0f8c3SJan Kara 				huge_pmd_set_accessed(&vmf, orig_pmd);
408871e3aac0SAndrea Arcangeli 				return 0;
408971e3aac0SAndrea Arcangeli 			}
409071e3aac0SAndrea Arcangeli 		}
40919845cbbdSKirill A. Shutemov 	}
409271e3aac0SAndrea Arcangeli 
409382b0f8c3SJan Kara 	return handle_pte_fault(&vmf);
40941da177e4SLinus Torvalds }
40951da177e4SLinus Torvalds 
40969a95f3cfSPaul Cassella /*
40979a95f3cfSPaul Cassella  * By the time we get here, we already hold the mm semaphore
40989a95f3cfSPaul Cassella  *
40999a95f3cfSPaul Cassella  * The mmap_sem may have been released depending on flags and our
41009a95f3cfSPaul Cassella  * return value.  See filemap_fault() and __lock_page_or_retry().
41019a95f3cfSPaul Cassella  */
4102dcddffd4SKirill A. Shutemov int handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4103dcddffd4SKirill A. Shutemov 		unsigned int flags)
4104519e5247SJohannes Weiner {
4105519e5247SJohannes Weiner 	int ret;
4106519e5247SJohannes Weiner 
4107519e5247SJohannes Weiner 	__set_current_state(TASK_RUNNING);
4108519e5247SJohannes Weiner 
4109519e5247SJohannes Weiner 	count_vm_event(PGFAULT);
41102262185cSRoman Gushchin 	count_memcg_event_mm(vma->vm_mm, PGFAULT);
4111519e5247SJohannes Weiner 
4112519e5247SJohannes Weiner 	/* do counter updates before entering really critical section. */
4113519e5247SJohannes Weiner 	check_sync_rss_stat(current);
4114519e5247SJohannes Weiner 
4115de0c799bSLaurent Dufour 	if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4116de0c799bSLaurent Dufour 					    flags & FAULT_FLAG_INSTRUCTION,
4117de0c799bSLaurent Dufour 					    flags & FAULT_FLAG_REMOTE))
4118de0c799bSLaurent Dufour 		return VM_FAULT_SIGSEGV;
4119de0c799bSLaurent Dufour 
4120519e5247SJohannes Weiner 	/*
4121519e5247SJohannes Weiner 	 * Enable the memcg OOM handling for faults triggered in user
4122519e5247SJohannes Weiner 	 * space.  Kernel faults are handled more gracefully.
4123519e5247SJohannes Weiner 	 */
4124519e5247SJohannes Weiner 	if (flags & FAULT_FLAG_USER)
412549426420SJohannes Weiner 		mem_cgroup_oom_enable();
4126519e5247SJohannes Weiner 
4127bae473a4SKirill A. Shutemov 	if (unlikely(is_vm_hugetlb_page(vma)))
4128bae473a4SKirill A. Shutemov 		ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4129bae473a4SKirill A. Shutemov 	else
4130dcddffd4SKirill A. Shutemov 		ret = __handle_mm_fault(vma, address, flags);
4131519e5247SJohannes Weiner 
413249426420SJohannes Weiner 	if (flags & FAULT_FLAG_USER) {
413349426420SJohannes Weiner 		mem_cgroup_oom_disable();
413449426420SJohannes Weiner 		/*
413549426420SJohannes Weiner 		 * The task may have entered a memcg OOM situation but
413649426420SJohannes Weiner 		 * if the allocation error was handled gracefully (no
413749426420SJohannes Weiner 		 * VM_FAULT_OOM), there is no need to kill anything.
413849426420SJohannes Weiner 		 * Just clean up the OOM state peacefully.
413949426420SJohannes Weiner 		 */
414049426420SJohannes Weiner 		if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
414149426420SJohannes Weiner 			mem_cgroup_oom_synchronize(false);
414249426420SJohannes Weiner 	}
41433812c8c8SJohannes Weiner 
4144519e5247SJohannes Weiner 	return ret;
4145519e5247SJohannes Weiner }
4146e1d6d01aSJesse Barnes EXPORT_SYMBOL_GPL(handle_mm_fault);
4147519e5247SJohannes Weiner 
414890eceff1SKirill A. Shutemov #ifndef __PAGETABLE_P4D_FOLDED
414990eceff1SKirill A. Shutemov /*
415090eceff1SKirill A. Shutemov  * Allocate p4d page table.
415190eceff1SKirill A. Shutemov  * We've already handled the fast-path in-line.
415290eceff1SKirill A. Shutemov  */
415390eceff1SKirill A. Shutemov int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
415490eceff1SKirill A. Shutemov {
415590eceff1SKirill A. Shutemov 	p4d_t *new = p4d_alloc_one(mm, address);
415690eceff1SKirill A. Shutemov 	if (!new)
415790eceff1SKirill A. Shutemov 		return -ENOMEM;
415890eceff1SKirill A. Shutemov 
415990eceff1SKirill A. Shutemov 	smp_wmb(); /* See comment in __pte_alloc */
416090eceff1SKirill A. Shutemov 
416190eceff1SKirill A. Shutemov 	spin_lock(&mm->page_table_lock);
416290eceff1SKirill A. Shutemov 	if (pgd_present(*pgd))		/* Another has populated it */
416390eceff1SKirill A. Shutemov 		p4d_free(mm, new);
416490eceff1SKirill A. Shutemov 	else
416590eceff1SKirill A. Shutemov 		pgd_populate(mm, pgd, new);
416690eceff1SKirill A. Shutemov 	spin_unlock(&mm->page_table_lock);
416790eceff1SKirill A. Shutemov 	return 0;
416890eceff1SKirill A. Shutemov }
416990eceff1SKirill A. Shutemov #endif /* __PAGETABLE_P4D_FOLDED */
417090eceff1SKirill A. Shutemov 
41711da177e4SLinus Torvalds #ifndef __PAGETABLE_PUD_FOLDED
41721da177e4SLinus Torvalds /*
41731da177e4SLinus Torvalds  * Allocate page upper directory.
4174872fec16SHugh Dickins  * We've already handled the fast-path in-line.
41751da177e4SLinus Torvalds  */
4176c2febafcSKirill A. Shutemov int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
41771da177e4SLinus Torvalds {
4178c74df32cSHugh Dickins 	pud_t *new = pud_alloc_one(mm, address);
4179c74df32cSHugh Dickins 	if (!new)
41801bb3630eSHugh Dickins 		return -ENOMEM;
41811da177e4SLinus Torvalds 
4182362a61adSNick Piggin 	smp_wmb(); /* See comment in __pte_alloc */
4183362a61adSNick Piggin 
4184872fec16SHugh Dickins 	spin_lock(&mm->page_table_lock);
4185c2febafcSKirill A. Shutemov #ifndef __ARCH_HAS_5LEVEL_HACK
4186b4e98d9aSKirill A. Shutemov 	if (!p4d_present(*p4d)) {
4187b4e98d9aSKirill A. Shutemov 		mm_inc_nr_puds(mm);
4188c2febafcSKirill A. Shutemov 		p4d_populate(mm, p4d, new);
4189b4e98d9aSKirill A. Shutemov 	} else	/* Another has populated it */
4190c2febafcSKirill A. Shutemov 		pud_free(mm, new);
4191b4e98d9aSKirill A. Shutemov #else
4192b4e98d9aSKirill A. Shutemov 	if (!pgd_present(*p4d)) {
4193b4e98d9aSKirill A. Shutemov 		mm_inc_nr_puds(mm);
4194c2febafcSKirill A. Shutemov 		pgd_populate(mm, p4d, new);
4195b4e98d9aSKirill A. Shutemov 	} else	/* Another has populated it */
4196b4e98d9aSKirill A. Shutemov 		pud_free(mm, new);
4197c2febafcSKirill A. Shutemov #endif /* __ARCH_HAS_5LEVEL_HACK */
4198872fec16SHugh Dickins 	spin_unlock(&mm->page_table_lock);
41991bb3630eSHugh Dickins 	return 0;
42001da177e4SLinus Torvalds }
42011da177e4SLinus Torvalds #endif /* __PAGETABLE_PUD_FOLDED */
42021da177e4SLinus Torvalds 
42031da177e4SLinus Torvalds #ifndef __PAGETABLE_PMD_FOLDED
42041da177e4SLinus Torvalds /*
42051da177e4SLinus Torvalds  * Allocate page middle directory.
4206872fec16SHugh Dickins  * We've already handled the fast-path in-line.
42071da177e4SLinus Torvalds  */
42081bb3630eSHugh Dickins int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
42091da177e4SLinus Torvalds {
4210a00cc7d9SMatthew Wilcox 	spinlock_t *ptl;
4211c74df32cSHugh Dickins 	pmd_t *new = pmd_alloc_one(mm, address);
4212c74df32cSHugh Dickins 	if (!new)
42131bb3630eSHugh Dickins 		return -ENOMEM;
42141da177e4SLinus Torvalds 
4215362a61adSNick Piggin 	smp_wmb(); /* See comment in __pte_alloc */
4216362a61adSNick Piggin 
4217a00cc7d9SMatthew Wilcox 	ptl = pud_lock(mm, pud);
42181da177e4SLinus Torvalds #ifndef __ARCH_HAS_4LEVEL_HACK
4219dc6c9a35SKirill A. Shutemov 	if (!pud_present(*pud)) {
4220dc6c9a35SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
42211da177e4SLinus Torvalds 		pud_populate(mm, pud, new);
4222dc6c9a35SKirill A. Shutemov 	} else	/* Another has populated it */
42235e541973SBenjamin Herrenschmidt 		pmd_free(mm, new);
4224dc6c9a35SKirill A. Shutemov #else
4225dc6c9a35SKirill A. Shutemov 	if (!pgd_present(*pud)) {
4226dc6c9a35SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
42271da177e4SLinus Torvalds 		pgd_populate(mm, pud, new);
4228dc6c9a35SKirill A. Shutemov 	} else /* Another has populated it */
4229dc6c9a35SKirill A. Shutemov 		pmd_free(mm, new);
42301da177e4SLinus Torvalds #endif /* __ARCH_HAS_4LEVEL_HACK */
4231a00cc7d9SMatthew Wilcox 	spin_unlock(ptl);
42321bb3630eSHugh Dickins 	return 0;
42331da177e4SLinus Torvalds }
42341da177e4SLinus Torvalds #endif /* __PAGETABLE_PMD_FOLDED */
42351da177e4SLinus Torvalds 
423609796395SRoss Zwisler static int __follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4237a4d1a885SJérôme Glisse 			    unsigned long *start, unsigned long *end,
423809796395SRoss Zwisler 			    pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4239f8ad0f49SJohannes Weiner {
4240f8ad0f49SJohannes Weiner 	pgd_t *pgd;
4241c2febafcSKirill A. Shutemov 	p4d_t *p4d;
4242f8ad0f49SJohannes Weiner 	pud_t *pud;
4243f8ad0f49SJohannes Weiner 	pmd_t *pmd;
4244f8ad0f49SJohannes Weiner 	pte_t *ptep;
4245f8ad0f49SJohannes Weiner 
4246f8ad0f49SJohannes Weiner 	pgd = pgd_offset(mm, address);
4247f8ad0f49SJohannes Weiner 	if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4248f8ad0f49SJohannes Weiner 		goto out;
4249f8ad0f49SJohannes Weiner 
4250c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, address);
4251c2febafcSKirill A. Shutemov 	if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4252c2febafcSKirill A. Shutemov 		goto out;
4253c2febafcSKirill A. Shutemov 
4254c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, address);
4255f8ad0f49SJohannes Weiner 	if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4256f8ad0f49SJohannes Weiner 		goto out;
4257f8ad0f49SJohannes Weiner 
4258f8ad0f49SJohannes Weiner 	pmd = pmd_offset(pud, address);
4259f66055abSAndrea Arcangeli 	VM_BUG_ON(pmd_trans_huge(*pmd));
426009796395SRoss Zwisler 
426109796395SRoss Zwisler 	if (pmd_huge(*pmd)) {
426209796395SRoss Zwisler 		if (!pmdpp)
4263f8ad0f49SJohannes Weiner 			goto out;
4264f8ad0f49SJohannes Weiner 
4265a4d1a885SJérôme Glisse 		if (start && end) {
4266a4d1a885SJérôme Glisse 			*start = address & PMD_MASK;
4267a4d1a885SJérôme Glisse 			*end = *start + PMD_SIZE;
4268a4d1a885SJérôme Glisse 			mmu_notifier_invalidate_range_start(mm, *start, *end);
4269a4d1a885SJérôme Glisse 		}
427009796395SRoss Zwisler 		*ptlp = pmd_lock(mm, pmd);
427109796395SRoss Zwisler 		if (pmd_huge(*pmd)) {
427209796395SRoss Zwisler 			*pmdpp = pmd;
427309796395SRoss Zwisler 			return 0;
427409796395SRoss Zwisler 		}
427509796395SRoss Zwisler 		spin_unlock(*ptlp);
4276a4d1a885SJérôme Glisse 		if (start && end)
4277a4d1a885SJérôme Glisse 			mmu_notifier_invalidate_range_end(mm, *start, *end);
427809796395SRoss Zwisler 	}
427909796395SRoss Zwisler 
428009796395SRoss Zwisler 	if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4281f8ad0f49SJohannes Weiner 		goto out;
4282f8ad0f49SJohannes Weiner 
4283a4d1a885SJérôme Glisse 	if (start && end) {
4284a4d1a885SJérôme Glisse 		*start = address & PAGE_MASK;
4285a4d1a885SJérôme Glisse 		*end = *start + PAGE_SIZE;
4286a4d1a885SJérôme Glisse 		mmu_notifier_invalidate_range_start(mm, *start, *end);
4287a4d1a885SJérôme Glisse 	}
4288f8ad0f49SJohannes Weiner 	ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4289f8ad0f49SJohannes Weiner 	if (!pte_present(*ptep))
4290f8ad0f49SJohannes Weiner 		goto unlock;
4291f8ad0f49SJohannes Weiner 	*ptepp = ptep;
4292f8ad0f49SJohannes Weiner 	return 0;
4293f8ad0f49SJohannes Weiner unlock:
4294f8ad0f49SJohannes Weiner 	pte_unmap_unlock(ptep, *ptlp);
4295a4d1a885SJérôme Glisse 	if (start && end)
4296a4d1a885SJérôme Glisse 		mmu_notifier_invalidate_range_end(mm, *start, *end);
4297f8ad0f49SJohannes Weiner out:
4298f8ad0f49SJohannes Weiner 	return -EINVAL;
4299f8ad0f49SJohannes Weiner }
4300f8ad0f49SJohannes Weiner 
4301f729c8c9SRoss Zwisler static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4302f729c8c9SRoss Zwisler 			     pte_t **ptepp, spinlock_t **ptlp)
43031b36ba81SNamhyung Kim {
43041b36ba81SNamhyung Kim 	int res;
43051b36ba81SNamhyung Kim 
43061b36ba81SNamhyung Kim 	/* (void) is needed to make gcc happy */
43071b36ba81SNamhyung Kim 	(void) __cond_lock(*ptlp,
4308a4d1a885SJérôme Glisse 			   !(res = __follow_pte_pmd(mm, address, NULL, NULL,
4309a4d1a885SJérôme Glisse 						    ptepp, NULL, ptlp)));
43101b36ba81SNamhyung Kim 	return res;
43111b36ba81SNamhyung Kim }
43121b36ba81SNamhyung Kim 
431309796395SRoss Zwisler int follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4314a4d1a885SJérôme Glisse 			     unsigned long *start, unsigned long *end,
431509796395SRoss Zwisler 			     pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
431609796395SRoss Zwisler {
431709796395SRoss Zwisler 	int res;
431809796395SRoss Zwisler 
431909796395SRoss Zwisler 	/* (void) is needed to make gcc happy */
432009796395SRoss Zwisler 	(void) __cond_lock(*ptlp,
4321a4d1a885SJérôme Glisse 			   !(res = __follow_pte_pmd(mm, address, start, end,
4322a4d1a885SJérôme Glisse 						    ptepp, pmdpp, ptlp)));
432309796395SRoss Zwisler 	return res;
432409796395SRoss Zwisler }
432509796395SRoss Zwisler EXPORT_SYMBOL(follow_pte_pmd);
432609796395SRoss Zwisler 
43273b6748e2SJohannes Weiner /**
43283b6748e2SJohannes Weiner  * follow_pfn - look up PFN at a user virtual address
43293b6748e2SJohannes Weiner  * @vma: memory mapping
43303b6748e2SJohannes Weiner  * @address: user virtual address
43313b6748e2SJohannes Weiner  * @pfn: location to store found PFN
43323b6748e2SJohannes Weiner  *
43333b6748e2SJohannes Weiner  * Only IO mappings and raw PFN mappings are allowed.
43343b6748e2SJohannes Weiner  *
43353b6748e2SJohannes Weiner  * Returns zero and the pfn at @pfn on success, -ve otherwise.
43363b6748e2SJohannes Weiner  */
43373b6748e2SJohannes Weiner int follow_pfn(struct vm_area_struct *vma, unsigned long address,
43383b6748e2SJohannes Weiner 	unsigned long *pfn)
43393b6748e2SJohannes Weiner {
43403b6748e2SJohannes Weiner 	int ret = -EINVAL;
43413b6748e2SJohannes Weiner 	spinlock_t *ptl;
43423b6748e2SJohannes Weiner 	pte_t *ptep;
43433b6748e2SJohannes Weiner 
43443b6748e2SJohannes Weiner 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
43453b6748e2SJohannes Weiner 		return ret;
43463b6748e2SJohannes Weiner 
43473b6748e2SJohannes Weiner 	ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
43483b6748e2SJohannes Weiner 	if (ret)
43493b6748e2SJohannes Weiner 		return ret;
43503b6748e2SJohannes Weiner 	*pfn = pte_pfn(*ptep);
43513b6748e2SJohannes Weiner 	pte_unmap_unlock(ptep, ptl);
43523b6748e2SJohannes Weiner 	return 0;
43533b6748e2SJohannes Weiner }
43543b6748e2SJohannes Weiner EXPORT_SYMBOL(follow_pfn);
43553b6748e2SJohannes Weiner 
435628b2ee20SRik van Riel #ifdef CONFIG_HAVE_IOREMAP_PROT
4357d87fe660Svenkatesh.pallipadi@intel.com int follow_phys(struct vm_area_struct *vma,
435828b2ee20SRik van Riel 		unsigned long address, unsigned int flags,
4359d87fe660Svenkatesh.pallipadi@intel.com 		unsigned long *prot, resource_size_t *phys)
436028b2ee20SRik van Riel {
436103668a4dSJohannes Weiner 	int ret = -EINVAL;
436228b2ee20SRik van Riel 	pte_t *ptep, pte;
436328b2ee20SRik van Riel 	spinlock_t *ptl;
436428b2ee20SRik van Riel 
4365d87fe660Svenkatesh.pallipadi@intel.com 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4366d87fe660Svenkatesh.pallipadi@intel.com 		goto out;
436728b2ee20SRik van Riel 
436803668a4dSJohannes Weiner 	if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4369d87fe660Svenkatesh.pallipadi@intel.com 		goto out;
437028b2ee20SRik van Riel 	pte = *ptep;
437103668a4dSJohannes Weiner 
4372f6f37321SLinus Torvalds 	if ((flags & FOLL_WRITE) && !pte_write(pte))
437328b2ee20SRik van Riel 		goto unlock;
437428b2ee20SRik van Riel 
437528b2ee20SRik van Riel 	*prot = pgprot_val(pte_pgprot(pte));
437603668a4dSJohannes Weiner 	*phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
437728b2ee20SRik van Riel 
437803668a4dSJohannes Weiner 	ret = 0;
437928b2ee20SRik van Riel unlock:
438028b2ee20SRik van Riel 	pte_unmap_unlock(ptep, ptl);
438128b2ee20SRik van Riel out:
4382d87fe660Svenkatesh.pallipadi@intel.com 	return ret;
438328b2ee20SRik van Riel }
438428b2ee20SRik van Riel 
438528b2ee20SRik van Riel int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
438628b2ee20SRik van Riel 			void *buf, int len, int write)
438728b2ee20SRik van Riel {
438828b2ee20SRik van Riel 	resource_size_t phys_addr;
438928b2ee20SRik van Riel 	unsigned long prot = 0;
43902bc7273bSKOSAKI Motohiro 	void __iomem *maddr;
439128b2ee20SRik van Riel 	int offset = addr & (PAGE_SIZE-1);
439228b2ee20SRik van Riel 
4393d87fe660Svenkatesh.pallipadi@intel.com 	if (follow_phys(vma, addr, write, &prot, &phys_addr))
439428b2ee20SRik van Riel 		return -EINVAL;
439528b2ee20SRik van Riel 
43969cb12d7bSGrazvydas Ignotas 	maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
439728b2ee20SRik van Riel 	if (write)
439828b2ee20SRik van Riel 		memcpy_toio(maddr + offset, buf, len);
439928b2ee20SRik van Riel 	else
440028b2ee20SRik van Riel 		memcpy_fromio(buf, maddr + offset, len);
440128b2ee20SRik van Riel 	iounmap(maddr);
440228b2ee20SRik van Riel 
440328b2ee20SRik van Riel 	return len;
440428b2ee20SRik van Riel }
44055a73633eSUwe Kleine-König EXPORT_SYMBOL_GPL(generic_access_phys);
440628b2ee20SRik van Riel #endif
440728b2ee20SRik van Riel 
44080ec76a11SDavid Howells /*
4409206cb636SStephen Wilson  * Access another process' address space as given in mm.  If non-NULL, use the
4410206cb636SStephen Wilson  * given task for page fault accounting.
44110ec76a11SDavid Howells  */
441284d77d3fSEric W. Biederman int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4413442486ecSLorenzo Stoakes 		unsigned long addr, void *buf, int len, unsigned int gup_flags)
44140ec76a11SDavid Howells {
44150ec76a11SDavid Howells 	struct vm_area_struct *vma;
44160ec76a11SDavid Howells 	void *old_buf = buf;
4417442486ecSLorenzo Stoakes 	int write = gup_flags & FOLL_WRITE;
44180ec76a11SDavid Howells 
44190ec76a11SDavid Howells 	down_read(&mm->mmap_sem);
4420183ff22bSSimon Arlott 	/* ignore errors, just check how much was successfully transferred */
44210ec76a11SDavid Howells 	while (len) {
44220ec76a11SDavid Howells 		int bytes, ret, offset;
44230ec76a11SDavid Howells 		void *maddr;
442428b2ee20SRik van Riel 		struct page *page = NULL;
44250ec76a11SDavid Howells 
44261e987790SDave Hansen 		ret = get_user_pages_remote(tsk, mm, addr, 1,
44275b56d49fSLorenzo Stoakes 				gup_flags, &page, &vma, NULL);
442828b2ee20SRik van Riel 		if (ret <= 0) {
4429dbffcd03SRik van Riel #ifndef CONFIG_HAVE_IOREMAP_PROT
4430dbffcd03SRik van Riel 			break;
4431dbffcd03SRik van Riel #else
443228b2ee20SRik van Riel 			/*
443328b2ee20SRik van Riel 			 * Check if this is a VM_IO | VM_PFNMAP VMA, which
443428b2ee20SRik van Riel 			 * we can access using slightly different code.
443528b2ee20SRik van Riel 			 */
443628b2ee20SRik van Riel 			vma = find_vma(mm, addr);
4437fe936dfcSMichael Ellerman 			if (!vma || vma->vm_start > addr)
44380ec76a11SDavid Howells 				break;
443928b2ee20SRik van Riel 			if (vma->vm_ops && vma->vm_ops->access)
444028b2ee20SRik van Riel 				ret = vma->vm_ops->access(vma, addr, buf,
444128b2ee20SRik van Riel 							  len, write);
444228b2ee20SRik van Riel 			if (ret <= 0)
444328b2ee20SRik van Riel 				break;
444428b2ee20SRik van Riel 			bytes = ret;
4445dbffcd03SRik van Riel #endif
444628b2ee20SRik van Riel 		} else {
44470ec76a11SDavid Howells 			bytes = len;
44480ec76a11SDavid Howells 			offset = addr & (PAGE_SIZE-1);
44490ec76a11SDavid Howells 			if (bytes > PAGE_SIZE-offset)
44500ec76a11SDavid Howells 				bytes = PAGE_SIZE-offset;
44510ec76a11SDavid Howells 
44520ec76a11SDavid Howells 			maddr = kmap(page);
44530ec76a11SDavid Howells 			if (write) {
44540ec76a11SDavid Howells 				copy_to_user_page(vma, page, addr,
44550ec76a11SDavid Howells 						  maddr + offset, buf, bytes);
44560ec76a11SDavid Howells 				set_page_dirty_lock(page);
44570ec76a11SDavid Howells 			} else {
44580ec76a11SDavid Howells 				copy_from_user_page(vma, page, addr,
44590ec76a11SDavid Howells 						    buf, maddr + offset, bytes);
44600ec76a11SDavid Howells 			}
44610ec76a11SDavid Howells 			kunmap(page);
446209cbfeafSKirill A. Shutemov 			put_page(page);
446328b2ee20SRik van Riel 		}
44640ec76a11SDavid Howells 		len -= bytes;
44650ec76a11SDavid Howells 		buf += bytes;
44660ec76a11SDavid Howells 		addr += bytes;
44670ec76a11SDavid Howells 	}
44680ec76a11SDavid Howells 	up_read(&mm->mmap_sem);
44690ec76a11SDavid Howells 
44700ec76a11SDavid Howells 	return buf - old_buf;
44710ec76a11SDavid Howells }
447203252919SAndi Kleen 
44735ddd36b9SStephen Wilson /**
4474ae91dbfcSRandy Dunlap  * access_remote_vm - access another process' address space
44755ddd36b9SStephen Wilson  * @mm:		the mm_struct of the target address space
44765ddd36b9SStephen Wilson  * @addr:	start address to access
44775ddd36b9SStephen Wilson  * @buf:	source or destination buffer
44785ddd36b9SStephen Wilson  * @len:	number of bytes to transfer
44796347e8d5SLorenzo Stoakes  * @gup_flags:	flags modifying lookup behaviour
44805ddd36b9SStephen Wilson  *
44815ddd36b9SStephen Wilson  * The caller must hold a reference on @mm.
44825ddd36b9SStephen Wilson  */
44835ddd36b9SStephen Wilson int access_remote_vm(struct mm_struct *mm, unsigned long addr,
44846347e8d5SLorenzo Stoakes 		void *buf, int len, unsigned int gup_flags)
44855ddd36b9SStephen Wilson {
44866347e8d5SLorenzo Stoakes 	return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
44875ddd36b9SStephen Wilson }
44885ddd36b9SStephen Wilson 
448903252919SAndi Kleen /*
4490206cb636SStephen Wilson  * Access another process' address space.
4491206cb636SStephen Wilson  * Source/target buffer must be kernel space,
4492206cb636SStephen Wilson  * Do not walk the page table directly, use get_user_pages
4493206cb636SStephen Wilson  */
4494206cb636SStephen Wilson int access_process_vm(struct task_struct *tsk, unsigned long addr,
4495f307ab6dSLorenzo Stoakes 		void *buf, int len, unsigned int gup_flags)
4496206cb636SStephen Wilson {
4497206cb636SStephen Wilson 	struct mm_struct *mm;
4498206cb636SStephen Wilson 	int ret;
4499206cb636SStephen Wilson 
4500206cb636SStephen Wilson 	mm = get_task_mm(tsk);
4501206cb636SStephen Wilson 	if (!mm)
4502206cb636SStephen Wilson 		return 0;
4503206cb636SStephen Wilson 
4504f307ab6dSLorenzo Stoakes 	ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
4505442486ecSLorenzo Stoakes 
4506206cb636SStephen Wilson 	mmput(mm);
4507206cb636SStephen Wilson 
4508206cb636SStephen Wilson 	return ret;
4509206cb636SStephen Wilson }
4510fcd35857SCatalin Marinas EXPORT_SYMBOL_GPL(access_process_vm);
4511206cb636SStephen Wilson 
451203252919SAndi Kleen /*
451303252919SAndi Kleen  * Print the name of a VMA.
451403252919SAndi Kleen  */
451503252919SAndi Kleen void print_vma_addr(char *prefix, unsigned long ip)
451603252919SAndi Kleen {
451703252919SAndi Kleen 	struct mm_struct *mm = current->mm;
451803252919SAndi Kleen 	struct vm_area_struct *vma;
451903252919SAndi Kleen 
4520e8bff74aSIngo Molnar 	/*
45210a7f682dSMichal Hocko 	 * we might be running from an atomic context so we cannot sleep
4522e8bff74aSIngo Molnar 	 */
45230a7f682dSMichal Hocko 	if (!down_read_trylock(&mm->mmap_sem))
4524e8bff74aSIngo Molnar 		return;
4525e8bff74aSIngo Molnar 
452603252919SAndi Kleen 	vma = find_vma(mm, ip);
452703252919SAndi Kleen 	if (vma && vma->vm_file) {
452803252919SAndi Kleen 		struct file *f = vma->vm_file;
45290a7f682dSMichal Hocko 		char *buf = (char *)__get_free_page(GFP_NOWAIT);
453003252919SAndi Kleen 		if (buf) {
45312fbc57c5SAndy Shevchenko 			char *p;
453203252919SAndi Kleen 
45339bf39ab2SMiklos Szeredi 			p = file_path(f, buf, PAGE_SIZE);
453403252919SAndi Kleen 			if (IS_ERR(p))
453503252919SAndi Kleen 				p = "?";
45362fbc57c5SAndy Shevchenko 			printk("%s%s[%lx+%lx]", prefix, kbasename(p),
453703252919SAndi Kleen 					vma->vm_start,
453803252919SAndi Kleen 					vma->vm_end - vma->vm_start);
453903252919SAndi Kleen 			free_page((unsigned long)buf);
454003252919SAndi Kleen 		}
454103252919SAndi Kleen 	}
454251a07e50SJeff Liu 	up_read(&mm->mmap_sem);
454303252919SAndi Kleen }
45443ee1afa3SNick Piggin 
4545662bbcb2SMichael S. Tsirkin #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
45469ec23531SDavid Hildenbrand void __might_fault(const char *file, int line)
45473ee1afa3SNick Piggin {
454895156f00SPeter Zijlstra 	/*
454995156f00SPeter Zijlstra 	 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
455095156f00SPeter Zijlstra 	 * holding the mmap_sem, this is safe because kernel memory doesn't
455195156f00SPeter Zijlstra 	 * get paged out, therefore we'll never actually fault, and the
455295156f00SPeter Zijlstra 	 * below annotations will generate false positives.
455395156f00SPeter Zijlstra 	 */
4554db68ce10SAl Viro 	if (uaccess_kernel())
455595156f00SPeter Zijlstra 		return;
45569ec23531SDavid Hildenbrand 	if (pagefault_disabled())
4557662bbcb2SMichael S. Tsirkin 		return;
45589ec23531SDavid Hildenbrand 	__might_sleep(file, line, 0);
45599ec23531SDavid Hildenbrand #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4560662bbcb2SMichael S. Tsirkin 	if (current->mm)
45613ee1afa3SNick Piggin 		might_lock_read(&current->mm->mmap_sem);
45629ec23531SDavid Hildenbrand #endif
45633ee1afa3SNick Piggin }
45649ec23531SDavid Hildenbrand EXPORT_SYMBOL(__might_fault);
45653ee1afa3SNick Piggin #endif
456647ad8475SAndrea Arcangeli 
456747ad8475SAndrea Arcangeli #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
456847ad8475SAndrea Arcangeli static void clear_gigantic_page(struct page *page,
456947ad8475SAndrea Arcangeli 				unsigned long addr,
457047ad8475SAndrea Arcangeli 				unsigned int pages_per_huge_page)
457147ad8475SAndrea Arcangeli {
457247ad8475SAndrea Arcangeli 	int i;
457347ad8475SAndrea Arcangeli 	struct page *p = page;
457447ad8475SAndrea Arcangeli 
457547ad8475SAndrea Arcangeli 	might_sleep();
457647ad8475SAndrea Arcangeli 	for (i = 0; i < pages_per_huge_page;
457747ad8475SAndrea Arcangeli 	     i++, p = mem_map_next(p, page, i)) {
457847ad8475SAndrea Arcangeli 		cond_resched();
457947ad8475SAndrea Arcangeli 		clear_user_highpage(p, addr + i * PAGE_SIZE);
458047ad8475SAndrea Arcangeli 	}
458147ad8475SAndrea Arcangeli }
458247ad8475SAndrea Arcangeli void clear_huge_page(struct page *page,
4583c79b57e4SHuang Ying 		     unsigned long addr_hint, unsigned int pages_per_huge_page)
458447ad8475SAndrea Arcangeli {
4585c79b57e4SHuang Ying 	int i, n, base, l;
4586c79b57e4SHuang Ying 	unsigned long addr = addr_hint &
4587c79b57e4SHuang Ying 		~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
458847ad8475SAndrea Arcangeli 
458947ad8475SAndrea Arcangeli 	if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
459047ad8475SAndrea Arcangeli 		clear_gigantic_page(page, addr, pages_per_huge_page);
459147ad8475SAndrea Arcangeli 		return;
459247ad8475SAndrea Arcangeli 	}
459347ad8475SAndrea Arcangeli 
4594c79b57e4SHuang Ying 	/* Clear sub-page to access last to keep its cache lines hot */
459547ad8475SAndrea Arcangeli 	might_sleep();
4596c79b57e4SHuang Ying 	n = (addr_hint - addr) / PAGE_SIZE;
4597c79b57e4SHuang Ying 	if (2 * n <= pages_per_huge_page) {
4598c79b57e4SHuang Ying 		/* If sub-page to access in first half of huge page */
4599c79b57e4SHuang Ying 		base = 0;
4600c79b57e4SHuang Ying 		l = n;
4601c79b57e4SHuang Ying 		/* Clear sub-pages at the end of huge page */
4602c79b57e4SHuang Ying 		for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
460347ad8475SAndrea Arcangeli 			cond_resched();
460447ad8475SAndrea Arcangeli 			clear_user_highpage(page + i, addr + i * PAGE_SIZE);
460547ad8475SAndrea Arcangeli 		}
4606c79b57e4SHuang Ying 	} else {
4607c79b57e4SHuang Ying 		/* If sub-page to access in second half of huge page */
4608c79b57e4SHuang Ying 		base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
4609c79b57e4SHuang Ying 		l = pages_per_huge_page - n;
4610c79b57e4SHuang Ying 		/* Clear sub-pages at the begin of huge page */
4611c79b57e4SHuang Ying 		for (i = 0; i < base; i++) {
4612c79b57e4SHuang Ying 			cond_resched();
4613c79b57e4SHuang Ying 			clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4614c79b57e4SHuang Ying 		}
4615c79b57e4SHuang Ying 	}
4616c79b57e4SHuang Ying 	/*
4617c79b57e4SHuang Ying 	 * Clear remaining sub-pages in left-right-left-right pattern
4618c79b57e4SHuang Ying 	 * towards the sub-page to access
4619c79b57e4SHuang Ying 	 */
4620c79b57e4SHuang Ying 	for (i = 0; i < l; i++) {
4621c79b57e4SHuang Ying 		int left_idx = base + i;
4622c79b57e4SHuang Ying 		int right_idx = base + 2 * l - 1 - i;
4623c79b57e4SHuang Ying 
4624c79b57e4SHuang Ying 		cond_resched();
4625c79b57e4SHuang Ying 		clear_user_highpage(page + left_idx,
4626c79b57e4SHuang Ying 				    addr + left_idx * PAGE_SIZE);
4627c79b57e4SHuang Ying 		cond_resched();
4628c79b57e4SHuang Ying 		clear_user_highpage(page + right_idx,
4629c79b57e4SHuang Ying 				    addr + right_idx * PAGE_SIZE);
4630c79b57e4SHuang Ying 	}
463147ad8475SAndrea Arcangeli }
463247ad8475SAndrea Arcangeli 
463347ad8475SAndrea Arcangeli static void copy_user_gigantic_page(struct page *dst, struct page *src,
463447ad8475SAndrea Arcangeli 				    unsigned long addr,
463547ad8475SAndrea Arcangeli 				    struct vm_area_struct *vma,
463647ad8475SAndrea Arcangeli 				    unsigned int pages_per_huge_page)
463747ad8475SAndrea Arcangeli {
463847ad8475SAndrea Arcangeli 	int i;
463947ad8475SAndrea Arcangeli 	struct page *dst_base = dst;
464047ad8475SAndrea Arcangeli 	struct page *src_base = src;
464147ad8475SAndrea Arcangeli 
464247ad8475SAndrea Arcangeli 	for (i = 0; i < pages_per_huge_page; ) {
464347ad8475SAndrea Arcangeli 		cond_resched();
464447ad8475SAndrea Arcangeli 		copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
464547ad8475SAndrea Arcangeli 
464647ad8475SAndrea Arcangeli 		i++;
464747ad8475SAndrea Arcangeli 		dst = mem_map_next(dst, dst_base, i);
464847ad8475SAndrea Arcangeli 		src = mem_map_next(src, src_base, i);
464947ad8475SAndrea Arcangeli 	}
465047ad8475SAndrea Arcangeli }
465147ad8475SAndrea Arcangeli 
465247ad8475SAndrea Arcangeli void copy_user_huge_page(struct page *dst, struct page *src,
465347ad8475SAndrea Arcangeli 			 unsigned long addr, struct vm_area_struct *vma,
465447ad8475SAndrea Arcangeli 			 unsigned int pages_per_huge_page)
465547ad8475SAndrea Arcangeli {
465647ad8475SAndrea Arcangeli 	int i;
465747ad8475SAndrea Arcangeli 
465847ad8475SAndrea Arcangeli 	if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
465947ad8475SAndrea Arcangeli 		copy_user_gigantic_page(dst, src, addr, vma,
466047ad8475SAndrea Arcangeli 					pages_per_huge_page);
466147ad8475SAndrea Arcangeli 		return;
466247ad8475SAndrea Arcangeli 	}
466347ad8475SAndrea Arcangeli 
466447ad8475SAndrea Arcangeli 	might_sleep();
466547ad8475SAndrea Arcangeli 	for (i = 0; i < pages_per_huge_page; i++) {
466647ad8475SAndrea Arcangeli 		cond_resched();
466747ad8475SAndrea Arcangeli 		copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
466847ad8475SAndrea Arcangeli 	}
466947ad8475SAndrea Arcangeli }
4670fa4d75c1SMike Kravetz 
4671fa4d75c1SMike Kravetz long copy_huge_page_from_user(struct page *dst_page,
4672fa4d75c1SMike Kravetz 				const void __user *usr_src,
4673810a56b9SMike Kravetz 				unsigned int pages_per_huge_page,
4674810a56b9SMike Kravetz 				bool allow_pagefault)
4675fa4d75c1SMike Kravetz {
4676fa4d75c1SMike Kravetz 	void *src = (void *)usr_src;
4677fa4d75c1SMike Kravetz 	void *page_kaddr;
4678fa4d75c1SMike Kravetz 	unsigned long i, rc = 0;
4679fa4d75c1SMike Kravetz 	unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
4680fa4d75c1SMike Kravetz 
4681fa4d75c1SMike Kravetz 	for (i = 0; i < pages_per_huge_page; i++) {
4682810a56b9SMike Kravetz 		if (allow_pagefault)
4683810a56b9SMike Kravetz 			page_kaddr = kmap(dst_page + i);
4684810a56b9SMike Kravetz 		else
4685fa4d75c1SMike Kravetz 			page_kaddr = kmap_atomic(dst_page + i);
4686fa4d75c1SMike Kravetz 		rc = copy_from_user(page_kaddr,
4687fa4d75c1SMike Kravetz 				(const void __user *)(src + i * PAGE_SIZE),
4688fa4d75c1SMike Kravetz 				PAGE_SIZE);
4689810a56b9SMike Kravetz 		if (allow_pagefault)
4690810a56b9SMike Kravetz 			kunmap(dst_page + i);
4691810a56b9SMike Kravetz 		else
4692fa4d75c1SMike Kravetz 			kunmap_atomic(page_kaddr);
4693fa4d75c1SMike Kravetz 
4694fa4d75c1SMike Kravetz 		ret_val -= (PAGE_SIZE - rc);
4695fa4d75c1SMike Kravetz 		if (rc)
4696fa4d75c1SMike Kravetz 			break;
4697fa4d75c1SMike Kravetz 
4698fa4d75c1SMike Kravetz 		cond_resched();
4699fa4d75c1SMike Kravetz 	}
4700fa4d75c1SMike Kravetz 	return ret_val;
4701fa4d75c1SMike Kravetz }
470247ad8475SAndrea Arcangeli #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
470349076ec2SKirill A. Shutemov 
470440b64acdSOlof Johansson #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4705b35f1819SKirill A. Shutemov 
4706b35f1819SKirill A. Shutemov static struct kmem_cache *page_ptl_cachep;
4707b35f1819SKirill A. Shutemov 
4708b35f1819SKirill A. Shutemov void __init ptlock_cache_init(void)
4709b35f1819SKirill A. Shutemov {
4710b35f1819SKirill A. Shutemov 	page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4711b35f1819SKirill A. Shutemov 			SLAB_PANIC, NULL);
4712b35f1819SKirill A. Shutemov }
4713b35f1819SKirill A. Shutemov 
4714539edb58SPeter Zijlstra bool ptlock_alloc(struct page *page)
471549076ec2SKirill A. Shutemov {
471649076ec2SKirill A. Shutemov 	spinlock_t *ptl;
471749076ec2SKirill A. Shutemov 
4718b35f1819SKirill A. Shutemov 	ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
471949076ec2SKirill A. Shutemov 	if (!ptl)
472049076ec2SKirill A. Shutemov 		return false;
4721539edb58SPeter Zijlstra 	page->ptl = ptl;
472249076ec2SKirill A. Shutemov 	return true;
472349076ec2SKirill A. Shutemov }
472449076ec2SKirill A. Shutemov 
4725539edb58SPeter Zijlstra void ptlock_free(struct page *page)
472649076ec2SKirill A. Shutemov {
4727b35f1819SKirill A. Shutemov 	kmem_cache_free(page_ptl_cachep, page->ptl);
472849076ec2SKirill A. Shutemov }
472949076ec2SKirill A. Shutemov #endif
4730