• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/mm/memory.c
3  *
4  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
5  */
6 
7 /*
8  * demand-loading started 01.12.91 - seems it is high on the list of
9  * things wanted, and it should be easy to implement. - Linus
10  */
11 
12 /*
13  * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
14  * pages started 02.12.91, seems to work. - Linus.
15  *
16  * Tested sharing by executing about 30 /bin/sh: under the old kernel it
17  * would have taken more than the 6M I have free, but it worked well as
18  * far as I could see.
19  *
20  * Also corrected some "invalidate()"s - I wasn't doing enough of them.
21  */
22 
23 /*
24  * Real VM (paging to/from disk) started 18.12.91. Much more work and
25  * thought has to go into this. Oh, well..
26  * 19.12.91  -  works, somewhat. Sometimes I get faults, don't know why.
27  *		Found it. Everything seems to work now.
28  * 20.12.91  -  Ok, making the swap-device changeable like the root.
29  */
30 
31 /*
32  * 05.04.94  -  Multi-page memory management added for v1.1.
33  * 		Idea by Alex Bligh (alex@cconcepts.co.uk)
34  *
35  * 16.07.99  -  Support of BIGMEM added by Gerhard Wichert, Siemens AG
36  *		(Gerhard.Wichert@pdb.siemens.de)
37  *
38  * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
39  */
40 
41 #include <linux/kernel_stat.h>
42 #include <linux/mm.h>
43 #include <linux/hugetlb.h>
44 #include <linux/mman.h>
45 #include <linux/swap.h>
46 #include <linux/highmem.h>
47 #include <linux/pagemap.h>
48 #include <linux/ksm.h>
49 #include <linux/rmap.h>
50 #include <linux/export.h>
51 #include <linux/delayacct.h>
52 #include <linux/init.h>
53 #include <linux/pfn_t.h>
54 #include <linux/writeback.h>
55 #include <linux/memcontrol.h>
56 #include <linux/mmu_notifier.h>
57 #include <linux/kallsyms.h>
58 #include <linux/swapops.h>
59 #include <linux/elf.h>
60 #include <linux/gfp.h>
61 #include <linux/migrate.h>
62 #include <linux/string.h>
63 #include <linux/dma-debug.h>
64 #include <linux/debugfs.h>
65 #include <linux/userfaultfd_k.h>
66 #include <linux/dax.h>
67 
68 #include <asm/io.h>
69 #include <asm/mmu_context.h>
70 #include <asm/pgalloc.h>
71 #include <asm/uaccess.h>
72 #include <asm/tlb.h>
73 #include <asm/tlbflush.h>
74 #include <asm/pgtable.h>
75 
76 #include "internal.h"
77 
78 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
79 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
80 #endif
81 
82 #ifndef CONFIG_NEED_MULTIPLE_NODES
83 /* use the per-pgdat data instead for discontigmem - mbligh */
84 unsigned long max_mapnr;
85 struct page *mem_map;
86 
87 EXPORT_SYMBOL(max_mapnr);
88 EXPORT_SYMBOL(mem_map);
89 #endif
90 
91 /*
92  * A number of key systems in x86 including ioremap() rely on the assumption
93  * that high_memory defines the upper bound on direct map memory, then end
94  * of ZONE_NORMAL.  Under CONFIG_DISCONTIG this means that max_low_pfn and
95  * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
96  * and ZONE_HIGHMEM.
97  */
98 void * high_memory;
99 
100 EXPORT_SYMBOL(high_memory);
101 
102 /*
103  * Randomize the address space (stacks, mmaps, brk, etc.).
104  *
105  * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
106  *   as ancient (libc5 based) binaries can segfault. )
107  */
108 int randomize_va_space __read_mostly =
109 #ifdef CONFIG_COMPAT_BRK
110 					1;
111 #else
112 					2;
113 #endif
114 
disable_randmaps(char * s)115 static int __init disable_randmaps(char *s)
116 {
117 	randomize_va_space = 0;
118 	return 1;
119 }
120 __setup("norandmaps", disable_randmaps);
121 
122 unsigned long zero_pfn __read_mostly;
123 unsigned long highest_memmap_pfn __read_mostly;
124 
125 EXPORT_SYMBOL(zero_pfn);
126 
127 /*
128  * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
129  */
init_zero_pfn(void)130 static int __init init_zero_pfn(void)
131 {
132 	zero_pfn = page_to_pfn(ZERO_PAGE(0));
133 	return 0;
134 }
135 core_initcall(init_zero_pfn);
136 
137 
138 #if defined(SPLIT_RSS_COUNTING)
139 
sync_mm_rss(struct mm_struct * mm)140 void sync_mm_rss(struct mm_struct *mm)
141 {
142 	int i;
143 
144 	for (i = 0; i < NR_MM_COUNTERS; i++) {
145 		if (current->rss_stat.count[i]) {
146 			add_mm_counter(mm, i, current->rss_stat.count[i]);
147 			current->rss_stat.count[i] = 0;
148 		}
149 	}
150 	current->rss_stat.events = 0;
151 }
152 
add_mm_counter_fast(struct mm_struct * mm,int member,int val)153 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
154 {
155 	struct task_struct *task = current;
156 
157 	if (likely(task->mm == mm))
158 		task->rss_stat.count[member] += val;
159 	else
160 		add_mm_counter(mm, member, val);
161 }
162 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
163 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
164 
165 /* sync counter once per 64 page faults */
166 #define TASK_RSS_EVENTS_THRESH	(64)
check_sync_rss_stat(struct task_struct * task)167 static void check_sync_rss_stat(struct task_struct *task)
168 {
169 	if (unlikely(task != current))
170 		return;
171 	if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
172 		sync_mm_rss(task->mm);
173 }
174 #else /* SPLIT_RSS_COUNTING */
175 
176 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
177 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
178 
check_sync_rss_stat(struct task_struct * task)179 static void check_sync_rss_stat(struct task_struct *task)
180 {
181 }
182 
183 #endif /* SPLIT_RSS_COUNTING */
184 
185 #ifdef HAVE_GENERIC_MMU_GATHER
186 
tlb_next_batch(struct mmu_gather * tlb)187 static bool tlb_next_batch(struct mmu_gather *tlb)
188 {
189 	struct mmu_gather_batch *batch;
190 
191 	batch = tlb->active;
192 	if (batch->next) {
193 		tlb->active = batch->next;
194 		return true;
195 	}
196 
197 	if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
198 		return false;
199 
200 	batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
201 	if (!batch)
202 		return false;
203 
204 	tlb->batch_count++;
205 	batch->next = NULL;
206 	batch->nr   = 0;
207 	batch->max  = MAX_GATHER_BATCH;
208 
209 	tlb->active->next = batch;
210 	tlb->active = batch;
211 
212 	return true;
213 }
214 
215 /* tlb_gather_mmu
216  *	Called to initialize an (on-stack) mmu_gather structure for page-table
217  *	tear-down from @mm. The @fullmm argument is used when @mm is without
218  *	users and we're going to destroy the full address space (exit/execve).
219  */
tlb_gather_mmu(struct mmu_gather * tlb,struct mm_struct * mm,unsigned long start,unsigned long end)220 void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, unsigned long start, unsigned long end)
221 {
222 	tlb->mm = mm;
223 
224 	/* Is it from 0 to ~0? */
225 	tlb->fullmm     = !(start | (end+1));
226 	tlb->need_flush_all = 0;
227 	tlb->local.next = NULL;
228 	tlb->local.nr   = 0;
229 	tlb->local.max  = ARRAY_SIZE(tlb->__pages);
230 	tlb->active     = &tlb->local;
231 	tlb->batch_count = 0;
232 
233 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
234 	tlb->batch = NULL;
235 #endif
236 	tlb->page_size = 0;
237 
238 	__tlb_reset_range(tlb);
239 }
240 
tlb_flush_mmu_tlbonly(struct mmu_gather * tlb)241 static void tlb_flush_mmu_tlbonly(struct mmu_gather *tlb)
242 {
243 	if (!tlb->end)
244 		return;
245 
246 	tlb_flush(tlb);
247 	mmu_notifier_invalidate_range(tlb->mm, tlb->start, tlb->end);
248 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
249 	tlb_table_flush(tlb);
250 #endif
251 	__tlb_reset_range(tlb);
252 }
253 
tlb_flush_mmu_free(struct mmu_gather * tlb)254 static void tlb_flush_mmu_free(struct mmu_gather *tlb)
255 {
256 	struct mmu_gather_batch *batch;
257 
258 	for (batch = &tlb->local; batch && batch->nr; batch = batch->next) {
259 		free_pages_and_swap_cache(batch->pages, batch->nr);
260 		batch->nr = 0;
261 	}
262 	tlb->active = &tlb->local;
263 }
264 
tlb_flush_mmu(struct mmu_gather * tlb)265 void tlb_flush_mmu(struct mmu_gather *tlb)
266 {
267 	tlb_flush_mmu_tlbonly(tlb);
268 	tlb_flush_mmu_free(tlb);
269 }
270 
271 /* tlb_finish_mmu
272  *	Called at the end of the shootdown operation to free up any resources
273  *	that were required.
274  */
tlb_finish_mmu(struct mmu_gather * tlb,unsigned long start,unsigned long end)275 void tlb_finish_mmu(struct mmu_gather *tlb, unsigned long start, unsigned long end)
276 {
277 	struct mmu_gather_batch *batch, *next;
278 
279 	tlb_flush_mmu(tlb);
280 
281 	/* keep the page table cache within bounds */
282 	check_pgt_cache();
283 
284 	for (batch = tlb->local.next; batch; batch = next) {
285 		next = batch->next;
286 		free_pages((unsigned long)batch, 0);
287 	}
288 	tlb->local.next = NULL;
289 }
290 
291 /* __tlb_remove_page
292  *	Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while
293  *	handling the additional races in SMP caused by other CPUs caching valid
294  *	mappings in their TLBs. Returns the number of free page slots left.
295  *	When out of page slots we must call tlb_flush_mmu().
296  *returns true if the caller should flush.
297  */
__tlb_remove_page_size(struct mmu_gather * tlb,struct page * page,int page_size)298 bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size)
299 {
300 	struct mmu_gather_batch *batch;
301 
302 	VM_BUG_ON(!tlb->end);
303 
304 	if (!tlb->page_size)
305 		tlb->page_size = page_size;
306 	else {
307 		if (page_size != tlb->page_size)
308 			return true;
309 	}
310 
311 	batch = tlb->active;
312 	if (batch->nr == batch->max) {
313 		if (!tlb_next_batch(tlb))
314 			return true;
315 		batch = tlb->active;
316 	}
317 	VM_BUG_ON_PAGE(batch->nr > batch->max, page);
318 
319 	batch->pages[batch->nr++] = page;
320 	return false;
321 }
322 
323 #endif /* HAVE_GENERIC_MMU_GATHER */
324 
325 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
326 
327 /*
328  * See the comment near struct mmu_table_batch.
329  */
330 
tlb_remove_table_smp_sync(void * arg)331 static void tlb_remove_table_smp_sync(void *arg)
332 {
333 	/* Simply deliver the interrupt */
334 }
335 
tlb_remove_table_one(void * table)336 static void tlb_remove_table_one(void *table)
337 {
338 	/*
339 	 * This isn't an RCU grace period and hence the page-tables cannot be
340 	 * assumed to be actually RCU-freed.
341 	 *
342 	 * It is however sufficient for software page-table walkers that rely on
343 	 * IRQ disabling. See the comment near struct mmu_table_batch.
344 	 */
345 	smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
346 	__tlb_remove_table(table);
347 }
348 
tlb_remove_table_rcu(struct rcu_head * head)349 static void tlb_remove_table_rcu(struct rcu_head *head)
350 {
351 	struct mmu_table_batch *batch;
352 	int i;
353 
354 	batch = container_of(head, struct mmu_table_batch, rcu);
355 
356 	for (i = 0; i < batch->nr; i++)
357 		__tlb_remove_table(batch->tables[i]);
358 
359 	free_page((unsigned long)batch);
360 }
361 
tlb_table_flush(struct mmu_gather * tlb)362 void tlb_table_flush(struct mmu_gather *tlb)
363 {
364 	struct mmu_table_batch **batch = &tlb->batch;
365 
366 	if (*batch) {
367 		call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
368 		*batch = NULL;
369 	}
370 }
371 
tlb_remove_table(struct mmu_gather * tlb,void * table)372 void tlb_remove_table(struct mmu_gather *tlb, void *table)
373 {
374 	struct mmu_table_batch **batch = &tlb->batch;
375 
376 	/*
377 	 * When there's less then two users of this mm there cannot be a
378 	 * concurrent page-table walk.
379 	 */
380 	if (atomic_read(&tlb->mm->mm_users) < 2) {
381 		__tlb_remove_table(table);
382 		return;
383 	}
384 
385 	if (*batch == NULL) {
386 		*batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
387 		if (*batch == NULL) {
388 			tlb_remove_table_one(table);
389 			return;
390 		}
391 		(*batch)->nr = 0;
392 	}
393 	(*batch)->tables[(*batch)->nr++] = table;
394 	if ((*batch)->nr == MAX_TABLE_BATCH)
395 		tlb_table_flush(tlb);
396 }
397 
398 #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
399 
400 /*
401  * Note: this doesn't free the actual pages themselves. That
402  * has been handled earlier when unmapping all the memory regions.
403  */
free_pte_range(struct mmu_gather * tlb,pmd_t * pmd,unsigned long addr)404 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
405 			   unsigned long addr)
406 {
407 	pgtable_t token = pmd_pgtable(*pmd);
408 	pmd_clear(pmd);
409 	pte_free_tlb(tlb, token, addr);
410 	atomic_long_dec(&tlb->mm->nr_ptes);
411 }
412 
free_pmd_range(struct mmu_gather * tlb,pud_t * pud,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)413 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
414 				unsigned long addr, unsigned long end,
415 				unsigned long floor, unsigned long ceiling)
416 {
417 	pmd_t *pmd;
418 	unsigned long next;
419 	unsigned long start;
420 
421 	start = addr;
422 	pmd = pmd_offset(pud, addr);
423 	do {
424 		next = pmd_addr_end(addr, end);
425 		if (pmd_none_or_clear_bad(pmd))
426 			continue;
427 		free_pte_range(tlb, pmd, addr);
428 	} while (pmd++, addr = next, addr != end);
429 
430 	start &= PUD_MASK;
431 	if (start < floor)
432 		return;
433 	if (ceiling) {
434 		ceiling &= PUD_MASK;
435 		if (!ceiling)
436 			return;
437 	}
438 	if (end - 1 > ceiling - 1)
439 		return;
440 
441 	pmd = pmd_offset(pud, start);
442 	pud_clear(pud);
443 	pmd_free_tlb(tlb, pmd, start);
444 	mm_dec_nr_pmds(tlb->mm);
445 }
446 
free_pud_range(struct mmu_gather * tlb,pgd_t * pgd,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)447 static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd,
448 				unsigned long addr, unsigned long end,
449 				unsigned long floor, unsigned long ceiling)
450 {
451 	pud_t *pud;
452 	unsigned long next;
453 	unsigned long start;
454 
455 	start = addr;
456 	pud = pud_offset(pgd, addr);
457 	do {
458 		next = pud_addr_end(addr, end);
459 		if (pud_none_or_clear_bad(pud))
460 			continue;
461 		free_pmd_range(tlb, pud, addr, next, floor, ceiling);
462 	} while (pud++, addr = next, addr != end);
463 
464 	start &= PGDIR_MASK;
465 	if (start < floor)
466 		return;
467 	if (ceiling) {
468 		ceiling &= PGDIR_MASK;
469 		if (!ceiling)
470 			return;
471 	}
472 	if (end - 1 > ceiling - 1)
473 		return;
474 
475 	pud = pud_offset(pgd, start);
476 	pgd_clear(pgd);
477 	pud_free_tlb(tlb, pud, start);
478 }
479 
480 /*
481  * This function frees user-level page tables of a process.
482  */
free_pgd_range(struct mmu_gather * tlb,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)483 void free_pgd_range(struct mmu_gather *tlb,
484 			unsigned long addr, unsigned long end,
485 			unsigned long floor, unsigned long ceiling)
486 {
487 	pgd_t *pgd;
488 	unsigned long next;
489 
490 	/*
491 	 * The next few lines have given us lots of grief...
492 	 *
493 	 * Why are we testing PMD* at this top level?  Because often
494 	 * there will be no work to do at all, and we'd prefer not to
495 	 * go all the way down to the bottom just to discover that.
496 	 *
497 	 * Why all these "- 1"s?  Because 0 represents both the bottom
498 	 * of the address space and the top of it (using -1 for the
499 	 * top wouldn't help much: the masks would do the wrong thing).
500 	 * The rule is that addr 0 and floor 0 refer to the bottom of
501 	 * the address space, but end 0 and ceiling 0 refer to the top
502 	 * Comparisons need to use "end - 1" and "ceiling - 1" (though
503 	 * that end 0 case should be mythical).
504 	 *
505 	 * Wherever addr is brought up or ceiling brought down, we must
506 	 * be careful to reject "the opposite 0" before it confuses the
507 	 * subsequent tests.  But what about where end is brought down
508 	 * by PMD_SIZE below? no, end can't go down to 0 there.
509 	 *
510 	 * Whereas we round start (addr) and ceiling down, by different
511 	 * masks at different levels, in order to test whether a table
512 	 * now has no other vmas using it, so can be freed, we don't
513 	 * bother to round floor or end up - the tests don't need that.
514 	 */
515 
516 	addr &= PMD_MASK;
517 	if (addr < floor) {
518 		addr += PMD_SIZE;
519 		if (!addr)
520 			return;
521 	}
522 	if (ceiling) {
523 		ceiling &= PMD_MASK;
524 		if (!ceiling)
525 			return;
526 	}
527 	if (end - 1 > ceiling - 1)
528 		end -= PMD_SIZE;
529 	if (addr > end - 1)
530 		return;
531 
532 	pgd = pgd_offset(tlb->mm, addr);
533 	do {
534 		next = pgd_addr_end(addr, end);
535 		if (pgd_none_or_clear_bad(pgd))
536 			continue;
537 		free_pud_range(tlb, pgd, addr, next, floor, ceiling);
538 	} while (pgd++, addr = next, addr != end);
539 }
540 
free_pgtables(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long floor,unsigned long ceiling)541 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
542 		unsigned long floor, unsigned long ceiling)
543 {
544 	while (vma) {
545 		struct vm_area_struct *next = vma->vm_next;
546 		unsigned long addr = vma->vm_start;
547 
548 		/*
549 		 * Hide vma from rmap and truncate_pagecache before freeing
550 		 * pgtables
551 		 */
552 		unlink_anon_vmas(vma);
553 		unlink_file_vma(vma);
554 
555 		if (is_vm_hugetlb_page(vma)) {
556 			hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
557 				floor, next? next->vm_start: ceiling);
558 		} else {
559 			/*
560 			 * Optimization: gather nearby vmas into one call down
561 			 */
562 			while (next && next->vm_start <= vma->vm_end + PMD_SIZE
563 			       && !is_vm_hugetlb_page(next)) {
564 				vma = next;
565 				next = vma->vm_next;
566 				unlink_anon_vmas(vma);
567 				unlink_file_vma(vma);
568 			}
569 			free_pgd_range(tlb, addr, vma->vm_end,
570 				floor, next? next->vm_start: ceiling);
571 		}
572 		vma = next;
573 	}
574 }
575 
__pte_alloc(struct mm_struct * mm,pmd_t * pmd,unsigned long address)576 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
577 {
578 	spinlock_t *ptl;
579 	pgtable_t new = pte_alloc_one(mm, address);
580 	if (!new)
581 		return -ENOMEM;
582 
583 	/*
584 	 * Ensure all pte setup (eg. pte page lock and page clearing) are
585 	 * visible before the pte is made visible to other CPUs by being
586 	 * put into page tables.
587 	 *
588 	 * The other side of the story is the pointer chasing in the page
589 	 * table walking code (when walking the page table without locking;
590 	 * ie. most of the time). Fortunately, these data accesses consist
591 	 * of a chain of data-dependent loads, meaning most CPUs (alpha
592 	 * being the notable exception) will already guarantee loads are
593 	 * seen in-order. See the alpha page table accessors for the
594 	 * smp_read_barrier_depends() barriers in page table walking code.
595 	 */
596 	smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
597 
598 	ptl = pmd_lock(mm, pmd);
599 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
600 		atomic_long_inc(&mm->nr_ptes);
601 		pmd_populate(mm, pmd, new);
602 		new = NULL;
603 	}
604 	spin_unlock(ptl);
605 	if (new)
606 		pte_free(mm, new);
607 	return 0;
608 }
609 
__pte_alloc_kernel(pmd_t * pmd,unsigned long address)610 int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
611 {
612 	pte_t *new = pte_alloc_one_kernel(&init_mm, address);
613 	if (!new)
614 		return -ENOMEM;
615 
616 	smp_wmb(); /* See comment in __pte_alloc */
617 
618 	spin_lock(&init_mm.page_table_lock);
619 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
620 		pmd_populate_kernel(&init_mm, pmd, new);
621 		new = NULL;
622 	}
623 	spin_unlock(&init_mm.page_table_lock);
624 	if (new)
625 		pte_free_kernel(&init_mm, new);
626 	return 0;
627 }
628 
init_rss_vec(int * rss)629 static inline void init_rss_vec(int *rss)
630 {
631 	memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
632 }
633 
add_mm_rss_vec(struct mm_struct * mm,int * rss)634 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
635 {
636 	int i;
637 
638 	if (current->mm == mm)
639 		sync_mm_rss(mm);
640 	for (i = 0; i < NR_MM_COUNTERS; i++)
641 		if (rss[i])
642 			add_mm_counter(mm, i, rss[i]);
643 }
644 
645 /*
646  * This function is called to print an error when a bad pte
647  * is found. For example, we might have a PFN-mapped pte in
648  * a region that doesn't allow it.
649  *
650  * The calling function must still handle the error.
651  */
print_bad_pte(struct vm_area_struct * vma,unsigned long addr,pte_t pte,struct page * page)652 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
653 			  pte_t pte, struct page *page)
654 {
655 	pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
656 	pud_t *pud = pud_offset(pgd, addr);
657 	pmd_t *pmd = pmd_offset(pud, addr);
658 	struct address_space *mapping;
659 	pgoff_t index;
660 	static unsigned long resume;
661 	static unsigned long nr_shown;
662 	static unsigned long nr_unshown;
663 
664 	/*
665 	 * Allow a burst of 60 reports, then keep quiet for that minute;
666 	 * or allow a steady drip of one report per second.
667 	 */
668 	if (nr_shown == 60) {
669 		if (time_before(jiffies, resume)) {
670 			nr_unshown++;
671 			return;
672 		}
673 		if (nr_unshown) {
674 			pr_alert("BUG: Bad page map: %lu messages suppressed\n",
675 				 nr_unshown);
676 			nr_unshown = 0;
677 		}
678 		nr_shown = 0;
679 	}
680 	if (nr_shown++ == 0)
681 		resume = jiffies + 60 * HZ;
682 
683 	mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
684 	index = linear_page_index(vma, addr);
685 
686 	pr_alert("BUG: Bad page map in process %s  pte:%08llx pmd:%08llx\n",
687 		 current->comm,
688 		 (long long)pte_val(pte), (long long)pmd_val(*pmd));
689 	if (page)
690 		dump_page(page, "bad pte");
691 	pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
692 		 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
693 	/*
694 	 * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
695 	 */
696 	pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n",
697 		 vma->vm_file,
698 		 vma->vm_ops ? vma->vm_ops->fault : NULL,
699 		 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
700 		 mapping ? mapping->a_ops->readpage : NULL);
701 	dump_stack();
702 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
703 }
704 
705 /*
706  * vm_normal_page -- This function gets the "struct page" associated with a pte.
707  *
708  * "Special" mappings do not wish to be associated with a "struct page" (either
709  * it doesn't exist, or it exists but they don't want to touch it). In this
710  * case, NULL is returned here. "Normal" mappings do have a struct page.
711  *
712  * There are 2 broad cases. Firstly, an architecture may define a pte_special()
713  * pte bit, in which case this function is trivial. Secondly, an architecture
714  * may not have a spare pte bit, which requires a more complicated scheme,
715  * described below.
716  *
717  * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
718  * special mapping (even if there are underlying and valid "struct pages").
719  * COWed pages of a VM_PFNMAP are always normal.
720  *
721  * The way we recognize COWed pages within VM_PFNMAP mappings is through the
722  * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
723  * set, and the vm_pgoff will point to the first PFN mapped: thus every special
724  * mapping will always honor the rule
725  *
726  *	pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
727  *
728  * And for normal mappings this is false.
729  *
730  * This restricts such mappings to be a linear translation from virtual address
731  * to pfn. To get around this restriction, we allow arbitrary mappings so long
732  * as the vma is not a COW mapping; in that case, we know that all ptes are
733  * special (because none can have been COWed).
734  *
735  *
736  * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
737  *
738  * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
739  * page" backing, however the difference is that _all_ pages with a struct
740  * page (that is, those where pfn_valid is true) are refcounted and considered
741  * normal pages by the VM. The disadvantage is that pages are refcounted
742  * (which can be slower and simply not an option for some PFNMAP users). The
743  * advantage is that we don't have to follow the strict linearity rule of
744  * PFNMAP mappings in order to support COWable mappings.
745  *
746  */
747 #ifdef __HAVE_ARCH_PTE_SPECIAL
748 # define HAVE_PTE_SPECIAL 1
749 #else
750 # define HAVE_PTE_SPECIAL 0
751 #endif
vm_normal_page(struct vm_area_struct * vma,unsigned long addr,pte_t pte)752 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
753 				pte_t pte)
754 {
755 	unsigned long pfn = pte_pfn(pte);
756 
757 	if (HAVE_PTE_SPECIAL) {
758 		if (likely(!pte_special(pte)))
759 			goto check_pfn;
760 		if (vma->vm_ops && vma->vm_ops->find_special_page)
761 			return vma->vm_ops->find_special_page(vma, addr);
762 		if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
763 			return NULL;
764 		if (!is_zero_pfn(pfn))
765 			print_bad_pte(vma, addr, pte, NULL);
766 		return NULL;
767 	}
768 
769 	/* !HAVE_PTE_SPECIAL case follows: */
770 
771 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
772 		if (vma->vm_flags & VM_MIXEDMAP) {
773 			if (!pfn_valid(pfn))
774 				return NULL;
775 			goto out;
776 		} else {
777 			unsigned long off;
778 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
779 			if (pfn == vma->vm_pgoff + off)
780 				return NULL;
781 			if (!is_cow_mapping(vma->vm_flags))
782 				return NULL;
783 		}
784 	}
785 
786 	if (is_zero_pfn(pfn))
787 		return NULL;
788 check_pfn:
789 	if (unlikely(pfn > highest_memmap_pfn)) {
790 		print_bad_pte(vma, addr, pte, NULL);
791 		return NULL;
792 	}
793 
794 	/*
795 	 * NOTE! We still have PageReserved() pages in the page tables.
796 	 * eg. VDSO mappings can cause them to exist.
797 	 */
798 out:
799 	return pfn_to_page(pfn);
800 }
801 
802 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
vm_normal_page_pmd(struct vm_area_struct * vma,unsigned long addr,pmd_t pmd)803 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
804 				pmd_t pmd)
805 {
806 	unsigned long pfn = pmd_pfn(pmd);
807 
808 	/*
809 	 * There is no pmd_special() but there may be special pmds, e.g.
810 	 * in a direct-access (dax) mapping, so let's just replicate the
811 	 * !HAVE_PTE_SPECIAL case from vm_normal_page() here.
812 	 */
813 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
814 		if (vma->vm_flags & VM_MIXEDMAP) {
815 			if (!pfn_valid(pfn))
816 				return NULL;
817 			goto out;
818 		} else {
819 			unsigned long off;
820 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
821 			if (pfn == vma->vm_pgoff + off)
822 				return NULL;
823 			if (!is_cow_mapping(vma->vm_flags))
824 				return NULL;
825 		}
826 	}
827 
828 	if (is_zero_pfn(pfn))
829 		return NULL;
830 	if (unlikely(pfn > highest_memmap_pfn))
831 		return NULL;
832 
833 	/*
834 	 * NOTE! We still have PageReserved() pages in the page tables.
835 	 * eg. VDSO mappings can cause them to exist.
836 	 */
837 out:
838 	return pfn_to_page(pfn);
839 }
840 #endif
841 
842 /*
843  * copy one vm_area from one task to the other. Assumes the page tables
844  * already present in the new task to be cleared in the whole range
845  * covered by this vma.
846  */
847 
848 static inline unsigned long
copy_one_pte(struct mm_struct * dst_mm,struct mm_struct * src_mm,pte_t * dst_pte,pte_t * src_pte,struct vm_area_struct * vma,unsigned long addr,int * rss)849 copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
850 		pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
851 		unsigned long addr, int *rss)
852 {
853 	unsigned long vm_flags = vma->vm_flags;
854 	pte_t pte = *src_pte;
855 	struct page *page;
856 
857 	/* pte contains position in swap or file, so copy. */
858 	if (unlikely(!pte_present(pte))) {
859 		swp_entry_t entry = pte_to_swp_entry(pte);
860 
861 		if (likely(!non_swap_entry(entry))) {
862 			if (swap_duplicate(entry) < 0)
863 				return entry.val;
864 
865 			/* make sure dst_mm is on swapoff's mmlist. */
866 			if (unlikely(list_empty(&dst_mm->mmlist))) {
867 				spin_lock(&mmlist_lock);
868 				if (list_empty(&dst_mm->mmlist))
869 					list_add(&dst_mm->mmlist,
870 							&src_mm->mmlist);
871 				spin_unlock(&mmlist_lock);
872 			}
873 			rss[MM_SWAPENTS]++;
874 		} else if (is_migration_entry(entry)) {
875 			page = migration_entry_to_page(entry);
876 
877 			rss[mm_counter(page)]++;
878 
879 			if (is_write_migration_entry(entry) &&
880 					is_cow_mapping(vm_flags)) {
881 				/*
882 				 * COW mappings require pages in both
883 				 * parent and child to be set to read.
884 				 */
885 				make_migration_entry_read(&entry);
886 				pte = swp_entry_to_pte(entry);
887 				if (pte_swp_soft_dirty(*src_pte))
888 					pte = pte_swp_mksoft_dirty(pte);
889 				set_pte_at(src_mm, addr, src_pte, pte);
890 			}
891 		}
892 		goto out_set_pte;
893 	}
894 
895 	/*
896 	 * If it's a COW mapping, write protect it both
897 	 * in the parent and the child
898 	 */
899 	if (is_cow_mapping(vm_flags)) {
900 		ptep_set_wrprotect(src_mm, addr, src_pte);
901 		pte = pte_wrprotect(pte);
902 	}
903 
904 	/*
905 	 * If it's a shared mapping, mark it clean in
906 	 * the child
907 	 */
908 	if (vm_flags & VM_SHARED)
909 		pte = pte_mkclean(pte);
910 	pte = pte_mkold(pte);
911 
912 	page = vm_normal_page(vma, addr, pte);
913 	if (page) {
914 		get_page(page);
915 		page_dup_rmap(page, false);
916 		rss[mm_counter(page)]++;
917 	}
918 
919 out_set_pte:
920 	set_pte_at(dst_mm, addr, dst_pte, pte);
921 	return 0;
922 }
923 
copy_pte_range(struct mm_struct * dst_mm,struct mm_struct * src_mm,pmd_t * dst_pmd,pmd_t * src_pmd,struct vm_area_struct * vma,unsigned long addr,unsigned long end)924 static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
925 		   pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
926 		   unsigned long addr, unsigned long end)
927 {
928 	pte_t *orig_src_pte, *orig_dst_pte;
929 	pte_t *src_pte, *dst_pte;
930 	spinlock_t *src_ptl, *dst_ptl;
931 	int progress = 0;
932 	int rss[NR_MM_COUNTERS];
933 	swp_entry_t entry = (swp_entry_t){0};
934 
935 again:
936 	init_rss_vec(rss);
937 
938 	dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
939 	if (!dst_pte)
940 		return -ENOMEM;
941 	src_pte = pte_offset_map(src_pmd, addr);
942 	src_ptl = pte_lockptr(src_mm, src_pmd);
943 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
944 	orig_src_pte = src_pte;
945 	orig_dst_pte = dst_pte;
946 	arch_enter_lazy_mmu_mode();
947 
948 	do {
949 		/*
950 		 * We are holding two locks at this point - either of them
951 		 * could generate latencies in another task on another CPU.
952 		 */
953 		if (progress >= 32) {
954 			progress = 0;
955 			if (need_resched() ||
956 			    spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
957 				break;
958 		}
959 		if (pte_none(*src_pte)) {
960 			progress++;
961 			continue;
962 		}
963 		entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
964 							vma, addr, rss);
965 		if (entry.val)
966 			break;
967 		progress += 8;
968 	} while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
969 
970 	arch_leave_lazy_mmu_mode();
971 	spin_unlock(src_ptl);
972 	pte_unmap(orig_src_pte);
973 	add_mm_rss_vec(dst_mm, rss);
974 	pte_unmap_unlock(orig_dst_pte, dst_ptl);
975 	cond_resched();
976 
977 	if (entry.val) {
978 		if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
979 			return -ENOMEM;
980 		progress = 0;
981 	}
982 	if (addr != end)
983 		goto again;
984 	return 0;
985 }
986 
copy_pmd_range(struct mm_struct * dst_mm,struct mm_struct * src_mm,pud_t * dst_pud,pud_t * src_pud,struct vm_area_struct * vma,unsigned long addr,unsigned long end)987 static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
988 		pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
989 		unsigned long addr, unsigned long end)
990 {
991 	pmd_t *src_pmd, *dst_pmd;
992 	unsigned long next;
993 
994 	dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
995 	if (!dst_pmd)
996 		return -ENOMEM;
997 	src_pmd = pmd_offset(src_pud, addr);
998 	do {
999 		next = pmd_addr_end(addr, end);
1000 		if (pmd_trans_huge(*src_pmd) || pmd_devmap(*src_pmd)) {
1001 			int err;
1002 			VM_BUG_ON(next-addr != HPAGE_PMD_SIZE);
1003 			err = copy_huge_pmd(dst_mm, src_mm,
1004 					    dst_pmd, src_pmd, addr, vma);
1005 			if (err == -ENOMEM)
1006 				return -ENOMEM;
1007 			if (!err)
1008 				continue;
1009 			/* fall through */
1010 		}
1011 		if (pmd_none_or_clear_bad(src_pmd))
1012 			continue;
1013 		if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
1014 						vma, addr, next))
1015 			return -ENOMEM;
1016 	} while (dst_pmd++, src_pmd++, addr = next, addr != end);
1017 	return 0;
1018 }
1019 
copy_pud_range(struct mm_struct * dst_mm,struct mm_struct * src_mm,pgd_t * dst_pgd,pgd_t * src_pgd,struct vm_area_struct * vma,unsigned long addr,unsigned long end)1020 static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1021 		pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
1022 		unsigned long addr, unsigned long end)
1023 {
1024 	pud_t *src_pud, *dst_pud;
1025 	unsigned long next;
1026 
1027 	dst_pud = pud_alloc(dst_mm, dst_pgd, addr);
1028 	if (!dst_pud)
1029 		return -ENOMEM;
1030 	src_pud = pud_offset(src_pgd, addr);
1031 	do {
1032 		next = pud_addr_end(addr, end);
1033 		if (pud_none_or_clear_bad(src_pud))
1034 			continue;
1035 		if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
1036 						vma, addr, next))
1037 			return -ENOMEM;
1038 	} while (dst_pud++, src_pud++, addr = next, addr != end);
1039 	return 0;
1040 }
1041 
copy_page_range(struct mm_struct * dst_mm,struct mm_struct * src_mm,struct vm_area_struct * vma)1042 int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1043 		struct vm_area_struct *vma)
1044 {
1045 	pgd_t *src_pgd, *dst_pgd;
1046 	unsigned long next;
1047 	unsigned long addr = vma->vm_start;
1048 	unsigned long end = vma->vm_end;
1049 	unsigned long mmun_start;	/* For mmu_notifiers */
1050 	unsigned long mmun_end;		/* For mmu_notifiers */
1051 	bool is_cow;
1052 	int ret;
1053 
1054 	/*
1055 	 * Don't copy ptes where a page fault will fill them correctly.
1056 	 * Fork becomes much lighter when there are big shared or private
1057 	 * readonly mappings. The tradeoff is that copy_page_range is more
1058 	 * efficient than faulting.
1059 	 */
1060 	if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1061 			!vma->anon_vma)
1062 		return 0;
1063 
1064 	if (is_vm_hugetlb_page(vma))
1065 		return copy_hugetlb_page_range(dst_mm, src_mm, vma);
1066 
1067 	if (unlikely(vma->vm_flags & VM_PFNMAP)) {
1068 		/*
1069 		 * We do not free on error cases below as remove_vma
1070 		 * gets called on error from higher level routine
1071 		 */
1072 		ret = track_pfn_copy(vma);
1073 		if (ret)
1074 			return ret;
1075 	}
1076 
1077 	/*
1078 	 * We need to invalidate the secondary MMU mappings only when
1079 	 * there could be a permission downgrade on the ptes of the
1080 	 * parent mm. And a permission downgrade will only happen if
1081 	 * is_cow_mapping() returns true.
1082 	 */
1083 	is_cow = is_cow_mapping(vma->vm_flags);
1084 	mmun_start = addr;
1085 	mmun_end   = end;
1086 	if (is_cow)
1087 		mmu_notifier_invalidate_range_start(src_mm, mmun_start,
1088 						    mmun_end);
1089 
1090 	ret = 0;
1091 	dst_pgd = pgd_offset(dst_mm, addr);
1092 	src_pgd = pgd_offset(src_mm, addr);
1093 	do {
1094 		next = pgd_addr_end(addr, end);
1095 		if (pgd_none_or_clear_bad(src_pgd))
1096 			continue;
1097 		if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd,
1098 					    vma, addr, next))) {
1099 			ret = -ENOMEM;
1100 			break;
1101 		}
1102 	} while (dst_pgd++, src_pgd++, addr = next, addr != end);
1103 
1104 	if (is_cow)
1105 		mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end);
1106 	return ret;
1107 }
1108 
zap_pte_range(struct mmu_gather * tlb,struct vm_area_struct * vma,pmd_t * pmd,unsigned long addr,unsigned long end,struct zap_details * details)1109 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1110 				struct vm_area_struct *vma, pmd_t *pmd,
1111 				unsigned long addr, unsigned long end,
1112 				struct zap_details *details)
1113 {
1114 	struct mm_struct *mm = tlb->mm;
1115 	int force_flush = 0;
1116 	int rss[NR_MM_COUNTERS];
1117 	spinlock_t *ptl;
1118 	pte_t *start_pte;
1119 	pte_t *pte;
1120 	swp_entry_t entry;
1121 	struct page *pending_page = NULL;
1122 
1123 again:
1124 	init_rss_vec(rss);
1125 	start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1126 	pte = start_pte;
1127 	flush_tlb_batched_pending(mm);
1128 	arch_enter_lazy_mmu_mode();
1129 	do {
1130 		pte_t ptent = *pte;
1131 		if (pte_none(ptent)) {
1132 			continue;
1133 		}
1134 
1135 		if (pte_present(ptent)) {
1136 			struct page *page;
1137 
1138 			page = vm_normal_page(vma, addr, ptent);
1139 			if (unlikely(details) && page) {
1140 				/*
1141 				 * unmap_shared_mapping_pages() wants to
1142 				 * invalidate cache without truncating:
1143 				 * unmap shared but keep private pages.
1144 				 */
1145 				if (details->check_mapping &&
1146 				    details->check_mapping != page_rmapping(page))
1147 					continue;
1148 			}
1149 			ptent = ptep_get_and_clear_full(mm, addr, pte,
1150 							tlb->fullmm);
1151 			tlb_remove_tlb_entry(tlb, pte, addr);
1152 			if (unlikely(!page))
1153 				continue;
1154 
1155 			if (!PageAnon(page)) {
1156 				if (pte_dirty(ptent)) {
1157 					/*
1158 					 * oom_reaper cannot tear down dirty
1159 					 * pages
1160 					 */
1161 					if (unlikely(details && details->ignore_dirty))
1162 						continue;
1163 					force_flush = 1;
1164 					set_page_dirty(page);
1165 				}
1166 				if (pte_young(ptent) &&
1167 				    likely(!(vma->vm_flags & VM_SEQ_READ)))
1168 					mark_page_accessed(page);
1169 			}
1170 			rss[mm_counter(page)]--;
1171 			page_remove_rmap(page, false);
1172 			if (unlikely(page_mapcount(page) < 0))
1173 				print_bad_pte(vma, addr, ptent, page);
1174 			if (unlikely(__tlb_remove_page(tlb, page))) {
1175 				force_flush = 1;
1176 				pending_page = page;
1177 				addr += PAGE_SIZE;
1178 				break;
1179 			}
1180 			continue;
1181 		}
1182 		/* only check swap_entries if explicitly asked for in details */
1183 		if (unlikely(details && !details->check_swap_entries))
1184 			continue;
1185 
1186 		entry = pte_to_swp_entry(ptent);
1187 		if (!non_swap_entry(entry))
1188 			rss[MM_SWAPENTS]--;
1189 		else if (is_migration_entry(entry)) {
1190 			struct page *page;
1191 
1192 			page = migration_entry_to_page(entry);
1193 			rss[mm_counter(page)]--;
1194 		}
1195 		if (unlikely(!free_swap_and_cache(entry)))
1196 			print_bad_pte(vma, addr, ptent, NULL);
1197 		pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1198 	} while (pte++, addr += PAGE_SIZE, addr != end);
1199 
1200 	add_mm_rss_vec(mm, rss);
1201 	arch_leave_lazy_mmu_mode();
1202 
1203 	/* Do the actual TLB flush before dropping ptl */
1204 	if (force_flush)
1205 		tlb_flush_mmu_tlbonly(tlb);
1206 	pte_unmap_unlock(start_pte, ptl);
1207 
1208 	/*
1209 	 * If we forced a TLB flush (either due to running out of
1210 	 * batch buffers or because we needed to flush dirty TLB
1211 	 * entries before releasing the ptl), free the batched
1212 	 * memory too. Restart if we didn't do everything.
1213 	 */
1214 	if (force_flush) {
1215 		force_flush = 0;
1216 		tlb_flush_mmu_free(tlb);
1217 		if (pending_page) {
1218 			/* remove the page with new size */
1219 			__tlb_remove_pte_page(tlb, pending_page);
1220 			pending_page = NULL;
1221 		}
1222 		if (addr != end)
1223 			goto again;
1224 	}
1225 
1226 	return addr;
1227 }
1228 
zap_pmd_range(struct mmu_gather * tlb,struct vm_area_struct * vma,pud_t * pud,unsigned long addr,unsigned long end,struct zap_details * details)1229 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1230 				struct vm_area_struct *vma, pud_t *pud,
1231 				unsigned long addr, unsigned long end,
1232 				struct zap_details *details)
1233 {
1234 	pmd_t *pmd;
1235 	unsigned long next;
1236 
1237 	pmd = pmd_offset(pud, addr);
1238 	do {
1239 		next = pmd_addr_end(addr, end);
1240 		if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1241 			if (next - addr != HPAGE_PMD_SIZE) {
1242 				VM_BUG_ON_VMA(vma_is_anonymous(vma) &&
1243 				    !rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1244 				split_huge_pmd(vma, pmd, addr);
1245 			} else if (zap_huge_pmd(tlb, vma, pmd, addr))
1246 				goto next;
1247 			/* fall through */
1248 		}
1249 		/*
1250 		 * Here there can be other concurrent MADV_DONTNEED or
1251 		 * trans huge page faults running, and if the pmd is
1252 		 * none or trans huge it can change under us. This is
1253 		 * because MADV_DONTNEED holds the mmap_sem in read
1254 		 * mode.
1255 		 */
1256 		if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1257 			goto next;
1258 		next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1259 next:
1260 		cond_resched();
1261 	} while (pmd++, addr = next, addr != end);
1262 
1263 	return addr;
1264 }
1265 
zap_pud_range(struct mmu_gather * tlb,struct vm_area_struct * vma,pgd_t * pgd,unsigned long addr,unsigned long end,struct zap_details * details)1266 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1267 				struct vm_area_struct *vma, pgd_t *pgd,
1268 				unsigned long addr, unsigned long end,
1269 				struct zap_details *details)
1270 {
1271 	pud_t *pud;
1272 	unsigned long next;
1273 
1274 	pud = pud_offset(pgd, addr);
1275 	do {
1276 		next = pud_addr_end(addr, end);
1277 		if (pud_none_or_clear_bad(pud))
1278 			continue;
1279 		next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1280 	} while (pud++, addr = next, addr != end);
1281 
1282 	return addr;
1283 }
1284 
unmap_page_range(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long addr,unsigned long end,struct zap_details * details)1285 void unmap_page_range(struct mmu_gather *tlb,
1286 			     struct vm_area_struct *vma,
1287 			     unsigned long addr, unsigned long end,
1288 			     struct zap_details *details)
1289 {
1290 	pgd_t *pgd;
1291 	unsigned long next;
1292 
1293 	BUG_ON(addr >= end);
1294 	tlb_start_vma(tlb, vma);
1295 	pgd = pgd_offset(vma->vm_mm, addr);
1296 	do {
1297 		next = pgd_addr_end(addr, end);
1298 		if (pgd_none_or_clear_bad(pgd))
1299 			continue;
1300 		next = zap_pud_range(tlb, vma, pgd, addr, next, details);
1301 	} while (pgd++, addr = next, addr != end);
1302 	tlb_end_vma(tlb, vma);
1303 }
1304 
1305 
unmap_single_vma(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long start_addr,unsigned long end_addr,struct zap_details * details)1306 static void unmap_single_vma(struct mmu_gather *tlb,
1307 		struct vm_area_struct *vma, unsigned long start_addr,
1308 		unsigned long end_addr,
1309 		struct zap_details *details)
1310 {
1311 	unsigned long start = max(vma->vm_start, start_addr);
1312 	unsigned long end;
1313 
1314 	if (start >= vma->vm_end)
1315 		return;
1316 	end = min(vma->vm_end, end_addr);
1317 	if (end <= vma->vm_start)
1318 		return;
1319 
1320 	if (vma->vm_file)
1321 		uprobe_munmap(vma, start, end);
1322 
1323 	if (unlikely(vma->vm_flags & VM_PFNMAP))
1324 		untrack_pfn(vma, 0, 0);
1325 
1326 	if (start != end) {
1327 		if (unlikely(is_vm_hugetlb_page(vma))) {
1328 			/*
1329 			 * It is undesirable to test vma->vm_file as it
1330 			 * should be non-null for valid hugetlb area.
1331 			 * However, vm_file will be NULL in the error
1332 			 * cleanup path of mmap_region. When
1333 			 * hugetlbfs ->mmap method fails,
1334 			 * mmap_region() nullifies vma->vm_file
1335 			 * before calling this function to clean up.
1336 			 * Since no pte has actually been setup, it is
1337 			 * safe to do nothing in this case.
1338 			 */
1339 			if (vma->vm_file) {
1340 				i_mmap_lock_write(vma->vm_file->f_mapping);
1341 				__unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1342 				i_mmap_unlock_write(vma->vm_file->f_mapping);
1343 			}
1344 		} else
1345 			unmap_page_range(tlb, vma, start, end, details);
1346 	}
1347 }
1348 
1349 /**
1350  * unmap_vmas - unmap a range of memory covered by a list of vma's
1351  * @tlb: address of the caller's struct mmu_gather
1352  * @vma: the starting vma
1353  * @start_addr: virtual address at which to start unmapping
1354  * @end_addr: virtual address at which to end unmapping
1355  *
1356  * Unmap all pages in the vma list.
1357  *
1358  * Only addresses between `start' and `end' will be unmapped.
1359  *
1360  * The VMA list must be sorted in ascending virtual address order.
1361  *
1362  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1363  * range after unmap_vmas() returns.  So the only responsibility here is to
1364  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1365  * drops the lock and schedules.
1366  */
unmap_vmas(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long start_addr,unsigned long end_addr)1367 void unmap_vmas(struct mmu_gather *tlb,
1368 		struct vm_area_struct *vma, unsigned long start_addr,
1369 		unsigned long end_addr)
1370 {
1371 	struct mm_struct *mm = vma->vm_mm;
1372 
1373 	mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1374 	for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1375 		unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1376 	mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1377 }
1378 
1379 /**
1380  * zap_page_range - remove user pages in a given range
1381  * @vma: vm_area_struct holding the applicable pages
1382  * @start: starting address of pages to zap
1383  * @size: number of bytes to zap
1384  * @details: details of shared cache invalidation
1385  *
1386  * Caller must protect the VMA list
1387  */
zap_page_range(struct vm_area_struct * vma,unsigned long start,unsigned long size,struct zap_details * details)1388 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1389 		unsigned long size, struct zap_details *details)
1390 {
1391 	struct mm_struct *mm = vma->vm_mm;
1392 	struct mmu_gather tlb;
1393 	unsigned long end = start + size;
1394 
1395 	lru_add_drain();
1396 	tlb_gather_mmu(&tlb, mm, start, end);
1397 	update_hiwater_rss(mm);
1398 	mmu_notifier_invalidate_range_start(mm, start, end);
1399 	for ( ; vma && vma->vm_start < end; vma = vma->vm_next)
1400 		unmap_single_vma(&tlb, vma, start, end, details);
1401 	mmu_notifier_invalidate_range_end(mm, start, end);
1402 	tlb_finish_mmu(&tlb, start, end);
1403 }
1404 
1405 /**
1406  * zap_page_range_single - remove user pages in a given range
1407  * @vma: vm_area_struct holding the applicable pages
1408  * @address: starting address of pages to zap
1409  * @size: number of bytes to zap
1410  * @details: details of shared cache invalidation
1411  *
1412  * The range must fit into one VMA.
1413  */
zap_page_range_single(struct vm_area_struct * vma,unsigned long address,unsigned long size,struct zap_details * details)1414 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1415 		unsigned long size, struct zap_details *details)
1416 {
1417 	struct mm_struct *mm = vma->vm_mm;
1418 	struct mmu_gather tlb;
1419 	unsigned long end = address + size;
1420 
1421 	lru_add_drain();
1422 	tlb_gather_mmu(&tlb, mm, address, end);
1423 	update_hiwater_rss(mm);
1424 	mmu_notifier_invalidate_range_start(mm, address, end);
1425 	unmap_single_vma(&tlb, vma, address, end, details);
1426 	mmu_notifier_invalidate_range_end(mm, address, end);
1427 	tlb_finish_mmu(&tlb, address, end);
1428 }
1429 
1430 /**
1431  * zap_vma_ptes - remove ptes mapping the vma
1432  * @vma: vm_area_struct holding ptes to be zapped
1433  * @address: starting address of pages to zap
1434  * @size: number of bytes to zap
1435  *
1436  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1437  *
1438  * The entire address range must be fully contained within the vma.
1439  *
1440  * Returns 0 if successful.
1441  */
zap_vma_ptes(struct vm_area_struct * vma,unsigned long address,unsigned long size)1442 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1443 		unsigned long size)
1444 {
1445 	if (address < vma->vm_start || address + size > vma->vm_end ||
1446 	    		!(vma->vm_flags & VM_PFNMAP))
1447 		return -1;
1448 	zap_page_range_single(vma, address, size, NULL);
1449 	return 0;
1450 }
1451 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1452 
__get_locked_pte(struct mm_struct * mm,unsigned long addr,spinlock_t ** ptl)1453 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1454 			spinlock_t **ptl)
1455 {
1456 	pgd_t * pgd = pgd_offset(mm, addr);
1457 	pud_t * pud = pud_alloc(mm, pgd, addr);
1458 	if (pud) {
1459 		pmd_t * pmd = pmd_alloc(mm, pud, addr);
1460 		if (pmd) {
1461 			VM_BUG_ON(pmd_trans_huge(*pmd));
1462 			return pte_alloc_map_lock(mm, pmd, addr, ptl);
1463 		}
1464 	}
1465 	return NULL;
1466 }
1467 
1468 /*
1469  * This is the old fallback for page remapping.
1470  *
1471  * For historical reasons, it only allows reserved pages. Only
1472  * old drivers should use this, and they needed to mark their
1473  * pages reserved for the old functions anyway.
1474  */
insert_page(struct vm_area_struct * vma,unsigned long addr,struct page * page,pgprot_t prot)1475 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1476 			struct page *page, pgprot_t prot)
1477 {
1478 	struct mm_struct *mm = vma->vm_mm;
1479 	int retval;
1480 	pte_t *pte;
1481 	spinlock_t *ptl;
1482 
1483 	retval = -EINVAL;
1484 	if (PageAnon(page))
1485 		goto out;
1486 	retval = -ENOMEM;
1487 	flush_dcache_page(page);
1488 	pte = get_locked_pte(mm, addr, &ptl);
1489 	if (!pte)
1490 		goto out;
1491 	retval = -EBUSY;
1492 	if (!pte_none(*pte))
1493 		goto out_unlock;
1494 
1495 	/* Ok, finally just insert the thing.. */
1496 	get_page(page);
1497 	inc_mm_counter_fast(mm, mm_counter_file(page));
1498 	page_add_file_rmap(page, false);
1499 	set_pte_at(mm, addr, pte, mk_pte(page, prot));
1500 
1501 	retval = 0;
1502 	pte_unmap_unlock(pte, ptl);
1503 	return retval;
1504 out_unlock:
1505 	pte_unmap_unlock(pte, ptl);
1506 out:
1507 	return retval;
1508 }
1509 
1510 /**
1511  * vm_insert_page - insert single page into user vma
1512  * @vma: user vma to map to
1513  * @addr: target user address of this page
1514  * @page: source kernel page
1515  *
1516  * This allows drivers to insert individual pages they've allocated
1517  * into a user vma.
1518  *
1519  * The page has to be a nice clean _individual_ kernel allocation.
1520  * If you allocate a compound page, you need to have marked it as
1521  * such (__GFP_COMP), or manually just split the page up yourself
1522  * (see split_page()).
1523  *
1524  * NOTE! Traditionally this was done with "remap_pfn_range()" which
1525  * took an arbitrary page protection parameter. This doesn't allow
1526  * that. Your vma protection will have to be set up correctly, which
1527  * means that if you want a shared writable mapping, you'd better
1528  * ask for a shared writable mapping!
1529  *
1530  * The page does not need to be reserved.
1531  *
1532  * Usually this function is called from f_op->mmap() handler
1533  * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
1534  * Caller must set VM_MIXEDMAP on vma if it wants to call this
1535  * function from other places, for example from page-fault handler.
1536  */
vm_insert_page(struct vm_area_struct * vma,unsigned long addr,struct page * page)1537 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1538 			struct page *page)
1539 {
1540 	if (addr < vma->vm_start || addr >= vma->vm_end)
1541 		return -EFAULT;
1542 	if (!page_count(page))
1543 		return -EINVAL;
1544 	if (!(vma->vm_flags & VM_MIXEDMAP)) {
1545 		BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
1546 		BUG_ON(vma->vm_flags & VM_PFNMAP);
1547 		vma->vm_flags |= VM_MIXEDMAP;
1548 	}
1549 	return insert_page(vma, addr, page, vma->vm_page_prot);
1550 }
1551 EXPORT_SYMBOL(vm_insert_page);
1552 
insert_pfn(struct vm_area_struct * vma,unsigned long addr,pfn_t pfn,pgprot_t prot)1553 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1554 			pfn_t pfn, pgprot_t prot)
1555 {
1556 	struct mm_struct *mm = vma->vm_mm;
1557 	int retval;
1558 	pte_t *pte, entry;
1559 	spinlock_t *ptl;
1560 
1561 	retval = -ENOMEM;
1562 	pte = get_locked_pte(mm, addr, &ptl);
1563 	if (!pte)
1564 		goto out;
1565 	retval = -EBUSY;
1566 	if (!pte_none(*pte))
1567 		goto out_unlock;
1568 
1569 	/* Ok, finally just insert the thing.. */
1570 	if (pfn_t_devmap(pfn))
1571 		entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1572 	else
1573 		entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1574 	set_pte_at(mm, addr, pte, entry);
1575 	update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1576 
1577 	retval = 0;
1578 out_unlock:
1579 	pte_unmap_unlock(pte, ptl);
1580 out:
1581 	return retval;
1582 }
1583 
1584 /**
1585  * vm_insert_pfn - insert single pfn into user vma
1586  * @vma: user vma to map to
1587  * @addr: target user address of this page
1588  * @pfn: source kernel pfn
1589  *
1590  * Similar to vm_insert_page, this allows drivers to insert individual pages
1591  * they've allocated into a user vma. Same comments apply.
1592  *
1593  * This function should only be called from a vm_ops->fault handler, and
1594  * in that case the handler should return NULL.
1595  *
1596  * vma cannot be a COW mapping.
1597  *
1598  * As this is called only for pages that do not currently exist, we
1599  * do not need to flush old virtual caches or the TLB.
1600  */
vm_insert_pfn(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn)1601 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1602 			unsigned long pfn)
1603 {
1604 	return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
1605 }
1606 EXPORT_SYMBOL(vm_insert_pfn);
1607 
1608 /**
1609  * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1610  * @vma: user vma to map to
1611  * @addr: target user address of this page
1612  * @pfn: source kernel pfn
1613  * @pgprot: pgprot flags for the inserted page
1614  *
1615  * This is exactly like vm_insert_pfn, except that it allows drivers to
1616  * to override pgprot on a per-page basis.
1617  *
1618  * This only makes sense for IO mappings, and it makes no sense for
1619  * cow mappings.  In general, using multiple vmas is preferable;
1620  * vm_insert_pfn_prot should only be used if using multiple VMAs is
1621  * impractical.
1622  */
vm_insert_pfn_prot(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn,pgprot_t pgprot)1623 int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
1624 			unsigned long pfn, pgprot_t pgprot)
1625 {
1626 	int ret;
1627 	/*
1628 	 * Technically, architectures with pte_special can avoid all these
1629 	 * restrictions (same for remap_pfn_range).  However we would like
1630 	 * consistency in testing and feature parity among all, so we should
1631 	 * try to keep these invariants in place for everybody.
1632 	 */
1633 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1634 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1635 						(VM_PFNMAP|VM_MIXEDMAP));
1636 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1637 	BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1638 
1639 	if (addr < vma->vm_start || addr >= vma->vm_end)
1640 		return -EFAULT;
1641 	if (track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV)))
1642 		return -EINVAL;
1643 
1644 	ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot);
1645 
1646 	return ret;
1647 }
1648 EXPORT_SYMBOL(vm_insert_pfn_prot);
1649 
vm_insert_mixed(struct vm_area_struct * vma,unsigned long addr,pfn_t pfn)1650 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1651 			pfn_t pfn)
1652 {
1653 	pgprot_t pgprot = vma->vm_page_prot;
1654 
1655 	BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1656 
1657 	if (addr < vma->vm_start || addr >= vma->vm_end)
1658 		return -EFAULT;
1659 	if (track_pfn_insert(vma, &pgprot, pfn))
1660 		return -EINVAL;
1661 
1662 	/*
1663 	 * If we don't have pte special, then we have to use the pfn_valid()
1664 	 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1665 	 * refcount the page if pfn_valid is true (hence insert_page rather
1666 	 * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
1667 	 * without pte special, it would there be refcounted as a normal page.
1668 	 */
1669 	if (!HAVE_PTE_SPECIAL && !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1670 		struct page *page;
1671 
1672 		/*
1673 		 * At this point we are committed to insert_page()
1674 		 * regardless of whether the caller specified flags that
1675 		 * result in pfn_t_has_page() == false.
1676 		 */
1677 		page = pfn_to_page(pfn_t_to_pfn(pfn));
1678 		return insert_page(vma, addr, page, pgprot);
1679 	}
1680 	return insert_pfn(vma, addr, pfn, pgprot);
1681 }
1682 EXPORT_SYMBOL(vm_insert_mixed);
1683 
1684 /*
1685  * maps a range of physical memory into the requested pages. the old
1686  * mappings are removed. any references to nonexistent pages results
1687  * in null mappings (currently treated as "copy-on-access")
1688  */
remap_pte_range(struct mm_struct * mm,pmd_t * pmd,unsigned long addr,unsigned long end,unsigned long pfn,pgprot_t prot)1689 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
1690 			unsigned long addr, unsigned long end,
1691 			unsigned long pfn, pgprot_t prot)
1692 {
1693 	pte_t *pte;
1694 	spinlock_t *ptl;
1695 
1696 	pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
1697 	if (!pte)
1698 		return -ENOMEM;
1699 	arch_enter_lazy_mmu_mode();
1700 	do {
1701 		BUG_ON(!pte_none(*pte));
1702 		set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
1703 		pfn++;
1704 	} while (pte++, addr += PAGE_SIZE, addr != end);
1705 	arch_leave_lazy_mmu_mode();
1706 	pte_unmap_unlock(pte - 1, ptl);
1707 	return 0;
1708 }
1709 
remap_pmd_range(struct mm_struct * mm,pud_t * pud,unsigned long addr,unsigned long end,unsigned long pfn,pgprot_t prot)1710 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
1711 			unsigned long addr, unsigned long end,
1712 			unsigned long pfn, pgprot_t prot)
1713 {
1714 	pmd_t *pmd;
1715 	unsigned long next;
1716 
1717 	pfn -= addr >> PAGE_SHIFT;
1718 	pmd = pmd_alloc(mm, pud, addr);
1719 	if (!pmd)
1720 		return -ENOMEM;
1721 	VM_BUG_ON(pmd_trans_huge(*pmd));
1722 	do {
1723 		next = pmd_addr_end(addr, end);
1724 		if (remap_pte_range(mm, pmd, addr, next,
1725 				pfn + (addr >> PAGE_SHIFT), prot))
1726 			return -ENOMEM;
1727 	} while (pmd++, addr = next, addr != end);
1728 	return 0;
1729 }
1730 
remap_pud_range(struct mm_struct * mm,pgd_t * pgd,unsigned long addr,unsigned long end,unsigned long pfn,pgprot_t prot)1731 static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd,
1732 			unsigned long addr, unsigned long end,
1733 			unsigned long pfn, pgprot_t prot)
1734 {
1735 	pud_t *pud;
1736 	unsigned long next;
1737 
1738 	pfn -= addr >> PAGE_SHIFT;
1739 	pud = pud_alloc(mm, pgd, addr);
1740 	if (!pud)
1741 		return -ENOMEM;
1742 	do {
1743 		next = pud_addr_end(addr, end);
1744 		if (remap_pmd_range(mm, pud, addr, next,
1745 				pfn + (addr >> PAGE_SHIFT), prot))
1746 			return -ENOMEM;
1747 	} while (pud++, addr = next, addr != end);
1748 	return 0;
1749 }
1750 
1751 /**
1752  * remap_pfn_range - remap kernel memory to userspace
1753  * @vma: user vma to map to
1754  * @addr: target user address to start at
1755  * @pfn: physical address of kernel memory
1756  * @size: size of map area
1757  * @prot: page protection flags for this mapping
1758  *
1759  *  Note: this is only safe if the mm semaphore is held when called.
1760  */
remap_pfn_range(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn,unsigned long size,pgprot_t prot)1761 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
1762 		    unsigned long pfn, unsigned long size, pgprot_t prot)
1763 {
1764 	pgd_t *pgd;
1765 	unsigned long next;
1766 	unsigned long end = addr + PAGE_ALIGN(size);
1767 	struct mm_struct *mm = vma->vm_mm;
1768 	unsigned long remap_pfn = pfn;
1769 	int err;
1770 
1771 	/*
1772 	 * Physically remapped pages are special. Tell the
1773 	 * rest of the world about it:
1774 	 *   VM_IO tells people not to look at these pages
1775 	 *	(accesses can have side effects).
1776 	 *   VM_PFNMAP tells the core MM that the base pages are just
1777 	 *	raw PFN mappings, and do not have a "struct page" associated
1778 	 *	with them.
1779 	 *   VM_DONTEXPAND
1780 	 *      Disable vma merging and expanding with mremap().
1781 	 *   VM_DONTDUMP
1782 	 *      Omit vma from core dump, even when VM_IO turned off.
1783 	 *
1784 	 * There's a horrible special case to handle copy-on-write
1785 	 * behaviour that some programs depend on. We mark the "original"
1786 	 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
1787 	 * See vm_normal_page() for details.
1788 	 */
1789 	if (is_cow_mapping(vma->vm_flags)) {
1790 		if (addr != vma->vm_start || end != vma->vm_end)
1791 			return -EINVAL;
1792 		vma->vm_pgoff = pfn;
1793 	}
1794 
1795 	err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
1796 	if (err)
1797 		return -EINVAL;
1798 
1799 	vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
1800 
1801 	BUG_ON(addr >= end);
1802 	pfn -= addr >> PAGE_SHIFT;
1803 	pgd = pgd_offset(mm, addr);
1804 	flush_cache_range(vma, addr, end);
1805 	do {
1806 		next = pgd_addr_end(addr, end);
1807 		err = remap_pud_range(mm, pgd, addr, next,
1808 				pfn + (addr >> PAGE_SHIFT), prot);
1809 		if (err)
1810 			break;
1811 	} while (pgd++, addr = next, addr != end);
1812 
1813 	if (err)
1814 		untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
1815 
1816 	return err;
1817 }
1818 EXPORT_SYMBOL(remap_pfn_range);
1819 
1820 /**
1821  * vm_iomap_memory - remap memory to userspace
1822  * @vma: user vma to map to
1823  * @start: start of area
1824  * @len: size of area
1825  *
1826  * This is a simplified io_remap_pfn_range() for common driver use. The
1827  * driver just needs to give us the physical memory range to be mapped,
1828  * we'll figure out the rest from the vma information.
1829  *
1830  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
1831  * whatever write-combining details or similar.
1832  */
vm_iomap_memory(struct vm_area_struct * vma,phys_addr_t start,unsigned long len)1833 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
1834 {
1835 	unsigned long vm_len, pfn, pages;
1836 
1837 	/* Check that the physical memory area passed in looks valid */
1838 	if (start + len < start)
1839 		return -EINVAL;
1840 	/*
1841 	 * You *really* shouldn't map things that aren't page-aligned,
1842 	 * but we've historically allowed it because IO memory might
1843 	 * just have smaller alignment.
1844 	 */
1845 	len += start & ~PAGE_MASK;
1846 	pfn = start >> PAGE_SHIFT;
1847 	pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
1848 	if (pfn + pages < pfn)
1849 		return -EINVAL;
1850 
1851 	/* We start the mapping 'vm_pgoff' pages into the area */
1852 	if (vma->vm_pgoff > pages)
1853 		return -EINVAL;
1854 	pfn += vma->vm_pgoff;
1855 	pages -= vma->vm_pgoff;
1856 
1857 	/* Can we fit all of the mapping? */
1858 	vm_len = vma->vm_end - vma->vm_start;
1859 	if (vm_len >> PAGE_SHIFT > pages)
1860 		return -EINVAL;
1861 
1862 	/* Ok, let it rip */
1863 	return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
1864 }
1865 EXPORT_SYMBOL(vm_iomap_memory);
1866 
apply_to_pte_range(struct mm_struct * mm,pmd_t * pmd,unsigned long addr,unsigned long end,pte_fn_t fn,void * data)1867 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
1868 				     unsigned long addr, unsigned long end,
1869 				     pte_fn_t fn, void *data)
1870 {
1871 	pte_t *pte;
1872 	int err;
1873 	pgtable_t token;
1874 	spinlock_t *uninitialized_var(ptl);
1875 
1876 	pte = (mm == &init_mm) ?
1877 		pte_alloc_kernel(pmd, addr) :
1878 		pte_alloc_map_lock(mm, pmd, addr, &ptl);
1879 	if (!pte)
1880 		return -ENOMEM;
1881 
1882 	BUG_ON(pmd_huge(*pmd));
1883 
1884 	arch_enter_lazy_mmu_mode();
1885 
1886 	token = pmd_pgtable(*pmd);
1887 
1888 	do {
1889 		err = fn(pte++, token, addr, data);
1890 		if (err)
1891 			break;
1892 	} while (addr += PAGE_SIZE, addr != end);
1893 
1894 	arch_leave_lazy_mmu_mode();
1895 
1896 	if (mm != &init_mm)
1897 		pte_unmap_unlock(pte-1, ptl);
1898 	return err;
1899 }
1900 
apply_to_pmd_range(struct mm_struct * mm,pud_t * pud,unsigned long addr,unsigned long end,pte_fn_t fn,void * data)1901 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
1902 				     unsigned long addr, unsigned long end,
1903 				     pte_fn_t fn, void *data)
1904 {
1905 	pmd_t *pmd;
1906 	unsigned long next;
1907 	int err;
1908 
1909 	BUG_ON(pud_huge(*pud));
1910 
1911 	pmd = pmd_alloc(mm, pud, addr);
1912 	if (!pmd)
1913 		return -ENOMEM;
1914 	do {
1915 		next = pmd_addr_end(addr, end);
1916 		err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
1917 		if (err)
1918 			break;
1919 	} while (pmd++, addr = next, addr != end);
1920 	return err;
1921 }
1922 
apply_to_pud_range(struct mm_struct * mm,pgd_t * pgd,unsigned long addr,unsigned long end,pte_fn_t fn,void * data)1923 static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd,
1924 				     unsigned long addr, unsigned long end,
1925 				     pte_fn_t fn, void *data)
1926 {
1927 	pud_t *pud;
1928 	unsigned long next;
1929 	int err;
1930 
1931 	pud = pud_alloc(mm, pgd, addr);
1932 	if (!pud)
1933 		return -ENOMEM;
1934 	do {
1935 		next = pud_addr_end(addr, end);
1936 		err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
1937 		if (err)
1938 			break;
1939 	} while (pud++, addr = next, addr != end);
1940 	return err;
1941 }
1942 
1943 /*
1944  * Scan a region of virtual memory, filling in page tables as necessary
1945  * and calling a provided function on each leaf page table.
1946  */
apply_to_page_range(struct mm_struct * mm,unsigned long addr,unsigned long size,pte_fn_t fn,void * data)1947 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
1948 			unsigned long size, pte_fn_t fn, void *data)
1949 {
1950 	pgd_t *pgd;
1951 	unsigned long next;
1952 	unsigned long end = addr + size;
1953 	int err;
1954 
1955 	if (WARN_ON(addr >= end))
1956 		return -EINVAL;
1957 
1958 	pgd = pgd_offset(mm, addr);
1959 	do {
1960 		next = pgd_addr_end(addr, end);
1961 		err = apply_to_pud_range(mm, pgd, addr, next, fn, data);
1962 		if (err)
1963 			break;
1964 	} while (pgd++, addr = next, addr != end);
1965 
1966 	return err;
1967 }
1968 EXPORT_SYMBOL_GPL(apply_to_page_range);
1969 
1970 /*
1971  * handle_pte_fault chooses page fault handler according to an entry which was
1972  * read non-atomically.  Before making any commitment, on those architectures
1973  * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
1974  * parts, do_swap_page must check under lock before unmapping the pte and
1975  * proceeding (but do_wp_page is only called after already making such a check;
1976  * and do_anonymous_page can safely check later on).
1977  */
pte_unmap_same(struct mm_struct * mm,pmd_t * pmd,pte_t * page_table,pte_t orig_pte)1978 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
1979 				pte_t *page_table, pte_t orig_pte)
1980 {
1981 	int same = 1;
1982 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
1983 	if (sizeof(pte_t) > sizeof(unsigned long)) {
1984 		spinlock_t *ptl = pte_lockptr(mm, pmd);
1985 		spin_lock(ptl);
1986 		same = pte_same(*page_table, orig_pte);
1987 		spin_unlock(ptl);
1988 	}
1989 #endif
1990 	pte_unmap(page_table);
1991 	return same;
1992 }
1993 
cow_user_page(struct page * dst,struct page * src,unsigned long va,struct vm_area_struct * vma)1994 static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
1995 {
1996 	debug_dma_assert_idle(src);
1997 
1998 	/*
1999 	 * If the source page was a PFN mapping, we don't have
2000 	 * a "struct page" for it. We do a best-effort copy by
2001 	 * just copying from the original user address. If that
2002 	 * fails, we just zero-fill it. Live with it.
2003 	 */
2004 	if (unlikely(!src)) {
2005 		void *kaddr = kmap_atomic(dst);
2006 		void __user *uaddr = (void __user *)(va & PAGE_MASK);
2007 
2008 		/*
2009 		 * This really shouldn't fail, because the page is there
2010 		 * in the page tables. But it might just be unreadable,
2011 		 * in which case we just give up and fill the result with
2012 		 * zeroes.
2013 		 */
2014 		if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
2015 			clear_page(kaddr);
2016 		kunmap_atomic(kaddr);
2017 		flush_dcache_page(dst);
2018 	} else
2019 		copy_user_highpage(dst, src, va, vma);
2020 }
2021 
__get_fault_gfp_mask(struct vm_area_struct * vma)2022 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2023 {
2024 	struct file *vm_file = vma->vm_file;
2025 
2026 	if (vm_file)
2027 		return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2028 
2029 	/*
2030 	 * Special mappings (e.g. VDSO) do not have any file so fake
2031 	 * a default GFP_KERNEL for them.
2032 	 */
2033 	return GFP_KERNEL;
2034 }
2035 
2036 /*
2037  * Notify the address space that the page is about to become writable so that
2038  * it can prohibit this or wait for the page to get into an appropriate state.
2039  *
2040  * We do this without the lock held, so that it can sleep if it needs to.
2041  */
do_page_mkwrite(struct vm_area_struct * vma,struct page * page,unsigned long address)2042 static int do_page_mkwrite(struct vm_area_struct *vma, struct page *page,
2043 	       unsigned long address)
2044 {
2045 	struct vm_fault vmf;
2046 	int ret;
2047 
2048 	vmf.virtual_address = (void __user *)(address & PAGE_MASK);
2049 	vmf.pgoff = page->index;
2050 	vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2051 	vmf.gfp_mask = __get_fault_gfp_mask(vma);
2052 	vmf.page = page;
2053 	vmf.cow_page = NULL;
2054 
2055 	ret = vma->vm_ops->page_mkwrite(vma, &vmf);
2056 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2057 		return ret;
2058 	if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2059 		lock_page(page);
2060 		if (!page->mapping) {
2061 			unlock_page(page);
2062 			return 0; /* retry */
2063 		}
2064 		ret |= VM_FAULT_LOCKED;
2065 	} else
2066 		VM_BUG_ON_PAGE(!PageLocked(page), page);
2067 	return ret;
2068 }
2069 
2070 /*
2071  * Handle write page faults for pages that can be reused in the current vma
2072  *
2073  * This can happen either due to the mapping being with the VM_SHARED flag,
2074  * or due to us being the last reference standing to the page. In either
2075  * case, all we need to do here is to mark the page as writable and update
2076  * any related book-keeping.
2077  */
wp_page_reuse(struct fault_env * fe,pte_t orig_pte,struct page * page,int page_mkwrite,int dirty_shared)2078 static inline int wp_page_reuse(struct fault_env *fe, pte_t orig_pte,
2079 			struct page *page, int page_mkwrite, int dirty_shared)
2080 	__releases(fe->ptl)
2081 {
2082 	struct vm_area_struct *vma = fe->vma;
2083 	pte_t entry;
2084 	/*
2085 	 * Clear the pages cpupid information as the existing
2086 	 * information potentially belongs to a now completely
2087 	 * unrelated process.
2088 	 */
2089 	if (page)
2090 		page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2091 
2092 	flush_cache_page(vma, fe->address, pte_pfn(orig_pte));
2093 	entry = pte_mkyoung(orig_pte);
2094 	entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2095 	if (ptep_set_access_flags(vma, fe->address, fe->pte, entry, 1))
2096 		update_mmu_cache(vma, fe->address, fe->pte);
2097 	pte_unmap_unlock(fe->pte, fe->ptl);
2098 
2099 	if (dirty_shared) {
2100 		struct address_space *mapping;
2101 		int dirtied;
2102 
2103 		if (!page_mkwrite)
2104 			lock_page(page);
2105 
2106 		dirtied = set_page_dirty(page);
2107 		VM_BUG_ON_PAGE(PageAnon(page), page);
2108 		mapping = page->mapping;
2109 		unlock_page(page);
2110 		put_page(page);
2111 
2112 		if ((dirtied || page_mkwrite) && mapping) {
2113 			/*
2114 			 * Some device drivers do not set page.mapping
2115 			 * but still dirty their pages
2116 			 */
2117 			balance_dirty_pages_ratelimited(mapping);
2118 		}
2119 
2120 		if (!page_mkwrite)
2121 			file_update_time(vma->vm_file);
2122 	}
2123 
2124 	return VM_FAULT_WRITE;
2125 }
2126 
2127 /*
2128  * Handle the case of a page which we actually need to copy to a new page.
2129  *
2130  * Called with mmap_sem locked and the old page referenced, but
2131  * without the ptl held.
2132  *
2133  * High level logic flow:
2134  *
2135  * - Allocate a page, copy the content of the old page to the new one.
2136  * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2137  * - Take the PTL. If the pte changed, bail out and release the allocated page
2138  * - If the pte is still the way we remember it, update the page table and all
2139  *   relevant references. This includes dropping the reference the page-table
2140  *   held to the old page, as well as updating the rmap.
2141  * - In any case, unlock the PTL and drop the reference we took to the old page.
2142  */
wp_page_copy(struct fault_env * fe,pte_t orig_pte,struct page * old_page)2143 static int wp_page_copy(struct fault_env *fe, pte_t orig_pte,
2144 		struct page *old_page)
2145 {
2146 	struct vm_area_struct *vma = fe->vma;
2147 	struct mm_struct *mm = vma->vm_mm;
2148 	struct page *new_page = NULL;
2149 	pte_t entry;
2150 	int page_copied = 0;
2151 	const unsigned long mmun_start = fe->address & PAGE_MASK;
2152 	const unsigned long mmun_end = mmun_start + PAGE_SIZE;
2153 	struct mem_cgroup *memcg;
2154 
2155 	if (unlikely(anon_vma_prepare(vma)))
2156 		goto oom;
2157 
2158 	if (is_zero_pfn(pte_pfn(orig_pte))) {
2159 		new_page = alloc_zeroed_user_highpage_movable(vma, fe->address);
2160 		if (!new_page)
2161 			goto oom;
2162 	} else {
2163 		new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2164 				fe->address);
2165 		if (!new_page)
2166 			goto oom;
2167 		cow_user_page(new_page, old_page, fe->address, vma);
2168 	}
2169 
2170 	if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg, false))
2171 		goto oom_free_new;
2172 
2173 	__SetPageUptodate(new_page);
2174 
2175 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2176 
2177 	/*
2178 	 * Re-check the pte - we dropped the lock
2179 	 */
2180 	fe->pte = pte_offset_map_lock(mm, fe->pmd, fe->address, &fe->ptl);
2181 	if (likely(pte_same(*fe->pte, orig_pte))) {
2182 		if (old_page) {
2183 			if (!PageAnon(old_page)) {
2184 				dec_mm_counter_fast(mm,
2185 						mm_counter_file(old_page));
2186 				inc_mm_counter_fast(mm, MM_ANONPAGES);
2187 			}
2188 		} else {
2189 			inc_mm_counter_fast(mm, MM_ANONPAGES);
2190 		}
2191 		flush_cache_page(vma, fe->address, pte_pfn(orig_pte));
2192 		entry = mk_pte(new_page, vma->vm_page_prot);
2193 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2194 		/*
2195 		 * Clear the pte entry and flush it first, before updating the
2196 		 * pte with the new entry. This will avoid a race condition
2197 		 * seen in the presence of one thread doing SMC and another
2198 		 * thread doing COW.
2199 		 */
2200 		ptep_clear_flush_notify(vma, fe->address, fe->pte);
2201 		page_add_new_anon_rmap(new_page, vma, fe->address, false);
2202 		mem_cgroup_commit_charge(new_page, memcg, false, false);
2203 		lru_cache_add_active_or_unevictable(new_page, vma);
2204 		/*
2205 		 * We call the notify macro here because, when using secondary
2206 		 * mmu page tables (such as kvm shadow page tables), we want the
2207 		 * new page to be mapped directly into the secondary page table.
2208 		 */
2209 		set_pte_at_notify(mm, fe->address, fe->pte, entry);
2210 		update_mmu_cache(vma, fe->address, fe->pte);
2211 		if (old_page) {
2212 			/*
2213 			 * Only after switching the pte to the new page may
2214 			 * we remove the mapcount here. Otherwise another
2215 			 * process may come and find the rmap count decremented
2216 			 * before the pte is switched to the new page, and
2217 			 * "reuse" the old page writing into it while our pte
2218 			 * here still points into it and can be read by other
2219 			 * threads.
2220 			 *
2221 			 * The critical issue is to order this
2222 			 * page_remove_rmap with the ptp_clear_flush above.
2223 			 * Those stores are ordered by (if nothing else,)
2224 			 * the barrier present in the atomic_add_negative
2225 			 * in page_remove_rmap.
2226 			 *
2227 			 * Then the TLB flush in ptep_clear_flush ensures that
2228 			 * no process can access the old page before the
2229 			 * decremented mapcount is visible. And the old page
2230 			 * cannot be reused until after the decremented
2231 			 * mapcount is visible. So transitively, TLBs to
2232 			 * old page will be flushed before it can be reused.
2233 			 */
2234 			page_remove_rmap(old_page, false);
2235 		}
2236 
2237 		/* Free the old page.. */
2238 		new_page = old_page;
2239 		page_copied = 1;
2240 	} else {
2241 		mem_cgroup_cancel_charge(new_page, memcg, false);
2242 	}
2243 
2244 	if (new_page)
2245 		put_page(new_page);
2246 
2247 	pte_unmap_unlock(fe->pte, fe->ptl);
2248 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2249 	if (old_page) {
2250 		/*
2251 		 * Don't let another task, with possibly unlocked vma,
2252 		 * keep the mlocked page.
2253 		 */
2254 		if (page_copied && (vma->vm_flags & VM_LOCKED)) {
2255 			lock_page(old_page);	/* LRU manipulation */
2256 			if (PageMlocked(old_page))
2257 				munlock_vma_page(old_page);
2258 			unlock_page(old_page);
2259 		}
2260 		put_page(old_page);
2261 	}
2262 	return page_copied ? VM_FAULT_WRITE : 0;
2263 oom_free_new:
2264 	put_page(new_page);
2265 oom:
2266 	if (old_page)
2267 		put_page(old_page);
2268 	return VM_FAULT_OOM;
2269 }
2270 
2271 /*
2272  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2273  * mapping
2274  */
wp_pfn_shared(struct fault_env * fe,pte_t orig_pte)2275 static int wp_pfn_shared(struct fault_env *fe,  pte_t orig_pte)
2276 {
2277 	struct vm_area_struct *vma = fe->vma;
2278 
2279 	if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2280 		struct vm_fault vmf = {
2281 			.page = NULL,
2282 			.pgoff = linear_page_index(vma, fe->address),
2283 			.virtual_address =
2284 				(void __user *)(fe->address & PAGE_MASK),
2285 			.flags = FAULT_FLAG_WRITE | FAULT_FLAG_MKWRITE,
2286 		};
2287 		int ret;
2288 
2289 		pte_unmap_unlock(fe->pte, fe->ptl);
2290 		ret = vma->vm_ops->pfn_mkwrite(vma, &vmf);
2291 		if (ret & VM_FAULT_ERROR)
2292 			return ret;
2293 		fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2294 				&fe->ptl);
2295 		/*
2296 		 * We might have raced with another page fault while we
2297 		 * released the pte_offset_map_lock.
2298 		 */
2299 		if (!pte_same(*fe->pte, orig_pte)) {
2300 			pte_unmap_unlock(fe->pte, fe->ptl);
2301 			return 0;
2302 		}
2303 	}
2304 	return wp_page_reuse(fe, orig_pte, NULL, 0, 0);
2305 }
2306 
wp_page_shared(struct fault_env * fe,pte_t orig_pte,struct page * old_page)2307 static int wp_page_shared(struct fault_env *fe, pte_t orig_pte,
2308 		struct page *old_page)
2309 	__releases(fe->ptl)
2310 {
2311 	struct vm_area_struct *vma = fe->vma;
2312 	int page_mkwrite = 0;
2313 
2314 	get_page(old_page);
2315 
2316 	if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2317 		int tmp;
2318 
2319 		pte_unmap_unlock(fe->pte, fe->ptl);
2320 		tmp = do_page_mkwrite(vma, old_page, fe->address);
2321 		if (unlikely(!tmp || (tmp &
2322 				      (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2323 			put_page(old_page);
2324 			return tmp;
2325 		}
2326 		/*
2327 		 * Since we dropped the lock we need to revalidate
2328 		 * the PTE as someone else may have changed it.  If
2329 		 * they did, we just return, as we can count on the
2330 		 * MMU to tell us if they didn't also make it writable.
2331 		 */
2332 		fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2333 						 &fe->ptl);
2334 		if (!pte_same(*fe->pte, orig_pte)) {
2335 			unlock_page(old_page);
2336 			pte_unmap_unlock(fe->pte, fe->ptl);
2337 			put_page(old_page);
2338 			return 0;
2339 		}
2340 		page_mkwrite = 1;
2341 	}
2342 
2343 	return wp_page_reuse(fe, orig_pte, old_page, page_mkwrite, 1);
2344 }
2345 
2346 /*
2347  * This routine handles present pages, when users try to write
2348  * to a shared page. It is done by copying the page to a new address
2349  * and decrementing the shared-page counter for the old page.
2350  *
2351  * Note that this routine assumes that the protection checks have been
2352  * done by the caller (the low-level page fault routine in most cases).
2353  * Thus we can safely just mark it writable once we've done any necessary
2354  * COW.
2355  *
2356  * We also mark the page dirty at this point even though the page will
2357  * change only once the write actually happens. This avoids a few races,
2358  * and potentially makes it more efficient.
2359  *
2360  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2361  * but allow concurrent faults), with pte both mapped and locked.
2362  * We return with mmap_sem still held, but pte unmapped and unlocked.
2363  */
do_wp_page(struct fault_env * fe,pte_t orig_pte)2364 static int do_wp_page(struct fault_env *fe, pte_t orig_pte)
2365 	__releases(fe->ptl)
2366 {
2367 	struct vm_area_struct *vma = fe->vma;
2368 	struct page *old_page;
2369 
2370 	old_page = vm_normal_page(vma, fe->address, orig_pte);
2371 	if (!old_page) {
2372 		/*
2373 		 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
2374 		 * VM_PFNMAP VMA.
2375 		 *
2376 		 * We should not cow pages in a shared writeable mapping.
2377 		 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2378 		 */
2379 		if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2380 				     (VM_WRITE|VM_SHARED))
2381 			return wp_pfn_shared(fe, orig_pte);
2382 
2383 		pte_unmap_unlock(fe->pte, fe->ptl);
2384 		return wp_page_copy(fe, orig_pte, old_page);
2385 	}
2386 
2387 	/*
2388 	 * Take out anonymous pages first, anonymous shared vmas are
2389 	 * not dirty accountable.
2390 	 */
2391 	if (PageAnon(old_page) && !PageKsm(old_page)) {
2392 		int total_mapcount;
2393 		if (!trylock_page(old_page)) {
2394 			get_page(old_page);
2395 			pte_unmap_unlock(fe->pte, fe->ptl);
2396 			lock_page(old_page);
2397 			fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd,
2398 					fe->address, &fe->ptl);
2399 			if (!pte_same(*fe->pte, orig_pte)) {
2400 				unlock_page(old_page);
2401 				pte_unmap_unlock(fe->pte, fe->ptl);
2402 				put_page(old_page);
2403 				return 0;
2404 			}
2405 			put_page(old_page);
2406 		}
2407 		if (reuse_swap_page(old_page, &total_mapcount)) {
2408 			if (total_mapcount == 1) {
2409 				/*
2410 				 * The page is all ours. Move it to
2411 				 * our anon_vma so the rmap code will
2412 				 * not search our parent or siblings.
2413 				 * Protected against the rmap code by
2414 				 * the page lock.
2415 				 */
2416 				page_move_anon_rmap(old_page, vma);
2417 			}
2418 			unlock_page(old_page);
2419 			return wp_page_reuse(fe, orig_pte, old_page, 0, 0);
2420 		}
2421 		unlock_page(old_page);
2422 	} else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2423 					(VM_WRITE|VM_SHARED))) {
2424 		return wp_page_shared(fe, orig_pte, old_page);
2425 	}
2426 
2427 	/*
2428 	 * Ok, we need to copy. Oh, well..
2429 	 */
2430 	get_page(old_page);
2431 
2432 	pte_unmap_unlock(fe->pte, fe->ptl);
2433 	return wp_page_copy(fe, orig_pte, old_page);
2434 }
2435 
unmap_mapping_range_vma(struct vm_area_struct * vma,unsigned long start_addr,unsigned long end_addr,struct zap_details * details)2436 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2437 		unsigned long start_addr, unsigned long end_addr,
2438 		struct zap_details *details)
2439 {
2440 	zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2441 }
2442 
unmap_mapping_range_tree(struct rb_root * root,struct zap_details * details)2443 static inline void unmap_mapping_range_tree(struct rb_root *root,
2444 					    struct zap_details *details)
2445 {
2446 	struct vm_area_struct *vma;
2447 	pgoff_t vba, vea, zba, zea;
2448 
2449 	vma_interval_tree_foreach(vma, root,
2450 			details->first_index, details->last_index) {
2451 
2452 		vba = vma->vm_pgoff;
2453 		vea = vba + vma_pages(vma) - 1;
2454 		zba = details->first_index;
2455 		if (zba < vba)
2456 			zba = vba;
2457 		zea = details->last_index;
2458 		if (zea > vea)
2459 			zea = vea;
2460 
2461 		unmap_mapping_range_vma(vma,
2462 			((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2463 			((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2464 				details);
2465 	}
2466 }
2467 
2468 /**
2469  * unmap_mapping_range - unmap the portion of all mmaps in the specified
2470  * address_space corresponding to the specified page range in the underlying
2471  * file.
2472  *
2473  * @mapping: the address space containing mmaps to be unmapped.
2474  * @holebegin: byte in first page to unmap, relative to the start of
2475  * the underlying file.  This will be rounded down to a PAGE_SIZE
2476  * boundary.  Note that this is different from truncate_pagecache(), which
2477  * must keep the partial page.  In contrast, we must get rid of
2478  * partial pages.
2479  * @holelen: size of prospective hole in bytes.  This will be rounded
2480  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
2481  * end of the file.
2482  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2483  * but 0 when invalidating pagecache, don't throw away private data.
2484  */
unmap_mapping_range(struct address_space * mapping,loff_t const holebegin,loff_t const holelen,int even_cows)2485 void unmap_mapping_range(struct address_space *mapping,
2486 		loff_t const holebegin, loff_t const holelen, int even_cows)
2487 {
2488 	struct zap_details details = { };
2489 	pgoff_t hba = holebegin >> PAGE_SHIFT;
2490 	pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2491 
2492 	/* Check for overflow. */
2493 	if (sizeof(holelen) > sizeof(hlen)) {
2494 		long long holeend =
2495 			(holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2496 		if (holeend & ~(long long)ULONG_MAX)
2497 			hlen = ULONG_MAX - hba + 1;
2498 	}
2499 
2500 	details.check_mapping = even_cows? NULL: mapping;
2501 	details.first_index = hba;
2502 	details.last_index = hba + hlen - 1;
2503 	if (details.last_index < details.first_index)
2504 		details.last_index = ULONG_MAX;
2505 
2506 	i_mmap_lock_write(mapping);
2507 	if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap)))
2508 		unmap_mapping_range_tree(&mapping->i_mmap, &details);
2509 	i_mmap_unlock_write(mapping);
2510 }
2511 EXPORT_SYMBOL(unmap_mapping_range);
2512 
2513 /*
2514  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2515  * but allow concurrent faults), and pte mapped but not yet locked.
2516  * We return with pte unmapped and unlocked.
2517  *
2518  * We return with the mmap_sem locked or unlocked in the same cases
2519  * as does filemap_fault().
2520  */
do_swap_page(struct fault_env * fe,pte_t orig_pte)2521 int do_swap_page(struct fault_env *fe, pte_t orig_pte)
2522 {
2523 	struct vm_area_struct *vma = fe->vma;
2524 	struct page *page, *swapcache;
2525 	struct mem_cgroup *memcg;
2526 	swp_entry_t entry;
2527 	pte_t pte;
2528 	int locked;
2529 	int exclusive = 0;
2530 	int ret = 0;
2531 
2532 	if (!pte_unmap_same(vma->vm_mm, fe->pmd, fe->pte, orig_pte))
2533 		goto out;
2534 
2535 	entry = pte_to_swp_entry(orig_pte);
2536 	if (unlikely(non_swap_entry(entry))) {
2537 		if (is_migration_entry(entry)) {
2538 			migration_entry_wait(vma->vm_mm, fe->pmd, fe->address);
2539 		} else if (is_hwpoison_entry(entry)) {
2540 			ret = VM_FAULT_HWPOISON;
2541 		} else {
2542 			print_bad_pte(vma, fe->address, orig_pte, NULL);
2543 			ret = VM_FAULT_SIGBUS;
2544 		}
2545 		goto out;
2546 	}
2547 	delayacct_set_flag(DELAYACCT_PF_SWAPIN);
2548 	page = lookup_swap_cache(entry);
2549 	if (!page) {
2550 		page = swapin_readahead(entry,
2551 					GFP_HIGHUSER_MOVABLE, vma, fe->address);
2552 		if (!page) {
2553 			/*
2554 			 * Back out if somebody else faulted in this pte
2555 			 * while we released the pte lock.
2556 			 */
2557 			fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd,
2558 					fe->address, &fe->ptl);
2559 			if (likely(pte_same(*fe->pte, orig_pte)))
2560 				ret = VM_FAULT_OOM;
2561 			delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2562 			goto unlock;
2563 		}
2564 
2565 		/* Had to read the page from swap area: Major fault */
2566 		ret = VM_FAULT_MAJOR;
2567 		count_vm_event(PGMAJFAULT);
2568 		mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
2569 	} else if (PageHWPoison(page)) {
2570 		/*
2571 		 * hwpoisoned dirty swapcache pages are kept for killing
2572 		 * owner processes (which may be unknown at hwpoison time)
2573 		 */
2574 		ret = VM_FAULT_HWPOISON;
2575 		delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2576 		swapcache = page;
2577 		goto out_release;
2578 	}
2579 
2580 	swapcache = page;
2581 	locked = lock_page_or_retry(page, vma->vm_mm, fe->flags);
2582 
2583 	delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2584 	if (!locked) {
2585 		ret |= VM_FAULT_RETRY;
2586 		goto out_release;
2587 	}
2588 
2589 	/*
2590 	 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
2591 	 * release the swapcache from under us.  The page pin, and pte_same
2592 	 * test below, are not enough to exclude that.  Even if it is still
2593 	 * swapcache, we need to check that the page's swap has not changed.
2594 	 */
2595 	if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
2596 		goto out_page;
2597 
2598 	page = ksm_might_need_to_copy(page, vma, fe->address);
2599 	if (unlikely(!page)) {
2600 		ret = VM_FAULT_OOM;
2601 		page = swapcache;
2602 		goto out_page;
2603 	}
2604 
2605 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
2606 				&memcg, false)) {
2607 		ret = VM_FAULT_OOM;
2608 		goto out_page;
2609 	}
2610 
2611 	/*
2612 	 * Back out if somebody else already faulted in this pte.
2613 	 */
2614 	fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2615 			&fe->ptl);
2616 	if (unlikely(!pte_same(*fe->pte, orig_pte)))
2617 		goto out_nomap;
2618 
2619 	if (unlikely(!PageUptodate(page))) {
2620 		ret = VM_FAULT_SIGBUS;
2621 		goto out_nomap;
2622 	}
2623 
2624 	/*
2625 	 * The page isn't present yet, go ahead with the fault.
2626 	 *
2627 	 * Be careful about the sequence of operations here.
2628 	 * To get its accounting right, reuse_swap_page() must be called
2629 	 * while the page is counted on swap but not yet in mapcount i.e.
2630 	 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
2631 	 * must be called after the swap_free(), or it will never succeed.
2632 	 */
2633 
2634 	inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
2635 	dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
2636 	pte = mk_pte(page, vma->vm_page_prot);
2637 	if ((fe->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
2638 		pte = maybe_mkwrite(pte_mkdirty(pte), vma);
2639 		fe->flags &= ~FAULT_FLAG_WRITE;
2640 		ret |= VM_FAULT_WRITE;
2641 		exclusive = RMAP_EXCLUSIVE;
2642 	}
2643 	flush_icache_page(vma, page);
2644 	if (pte_swp_soft_dirty(orig_pte))
2645 		pte = pte_mksoft_dirty(pte);
2646 	set_pte_at(vma->vm_mm, fe->address, fe->pte, pte);
2647 	if (page == swapcache) {
2648 		do_page_add_anon_rmap(page, vma, fe->address, exclusive);
2649 		mem_cgroup_commit_charge(page, memcg, true, false);
2650 		activate_page(page);
2651 	} else { /* ksm created a completely new copy */
2652 		page_add_new_anon_rmap(page, vma, fe->address, false);
2653 		mem_cgroup_commit_charge(page, memcg, false, false);
2654 		lru_cache_add_active_or_unevictable(page, vma);
2655 	}
2656 
2657 	swap_free(entry);
2658 	if (mem_cgroup_swap_full(page) ||
2659 	    (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
2660 		try_to_free_swap(page);
2661 	unlock_page(page);
2662 	if (page != swapcache) {
2663 		/*
2664 		 * Hold the lock to avoid the swap entry to be reused
2665 		 * until we take the PT lock for the pte_same() check
2666 		 * (to avoid false positives from pte_same). For
2667 		 * further safety release the lock after the swap_free
2668 		 * so that the swap count won't change under a
2669 		 * parallel locked swapcache.
2670 		 */
2671 		unlock_page(swapcache);
2672 		put_page(swapcache);
2673 	}
2674 
2675 	if (fe->flags & FAULT_FLAG_WRITE) {
2676 		ret |= do_wp_page(fe, pte);
2677 		if (ret & VM_FAULT_ERROR)
2678 			ret &= VM_FAULT_ERROR;
2679 		goto out;
2680 	}
2681 
2682 	/* No need to invalidate - it was non-present before */
2683 	update_mmu_cache(vma, fe->address, fe->pte);
2684 unlock:
2685 	pte_unmap_unlock(fe->pte, fe->ptl);
2686 out:
2687 	return ret;
2688 out_nomap:
2689 	mem_cgroup_cancel_charge(page, memcg, false);
2690 	pte_unmap_unlock(fe->pte, fe->ptl);
2691 out_page:
2692 	unlock_page(page);
2693 out_release:
2694 	put_page(page);
2695 	if (page != swapcache) {
2696 		unlock_page(swapcache);
2697 		put_page(swapcache);
2698 	}
2699 	return ret;
2700 }
2701 
2702 /*
2703  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2704  * but allow concurrent faults), and pte mapped but not yet locked.
2705  * We return with mmap_sem still held, but pte unmapped and unlocked.
2706  */
do_anonymous_page(struct fault_env * fe)2707 static int do_anonymous_page(struct fault_env *fe)
2708 {
2709 	struct vm_area_struct *vma = fe->vma;
2710 	struct mem_cgroup *memcg;
2711 	struct page *page;
2712 	pte_t entry;
2713 
2714 	/* File mapping without ->vm_ops ? */
2715 	if (vma->vm_flags & VM_SHARED)
2716 		return VM_FAULT_SIGBUS;
2717 
2718 	/*
2719 	 * Use pte_alloc() instead of pte_alloc_map().  We can't run
2720 	 * pte_offset_map() on pmds where a huge pmd might be created
2721 	 * from a different thread.
2722 	 *
2723 	 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
2724 	 * parallel threads are excluded by other means.
2725 	 *
2726 	 * Here we only have down_read(mmap_sem).
2727 	 */
2728 	if (pte_alloc(vma->vm_mm, fe->pmd, fe->address))
2729 		return VM_FAULT_OOM;
2730 
2731 	/* See the comment in pte_alloc_one_map() */
2732 	if (unlikely(pmd_trans_unstable(fe->pmd)))
2733 		return 0;
2734 
2735 	/* Use the zero-page for reads */
2736 	if (!(fe->flags & FAULT_FLAG_WRITE) &&
2737 			!mm_forbids_zeropage(vma->vm_mm)) {
2738 		entry = pte_mkspecial(pfn_pte(my_zero_pfn(fe->address),
2739 						vma->vm_page_prot));
2740 		fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2741 				&fe->ptl);
2742 		if (!pte_none(*fe->pte))
2743 			goto unlock;
2744 		/* Deliver the page fault to userland, check inside PT lock */
2745 		if (userfaultfd_missing(vma)) {
2746 			pte_unmap_unlock(fe->pte, fe->ptl);
2747 			return handle_userfault(fe, VM_UFFD_MISSING);
2748 		}
2749 		goto setpte;
2750 	}
2751 
2752 	/* Allocate our own private page. */
2753 	if (unlikely(anon_vma_prepare(vma)))
2754 		goto oom;
2755 	page = alloc_zeroed_user_highpage_movable(vma, fe->address);
2756 	if (!page)
2757 		goto oom;
2758 
2759 	if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
2760 		goto oom_free_page;
2761 
2762 	/*
2763 	 * The memory barrier inside __SetPageUptodate makes sure that
2764 	 * preceeding stores to the page contents become visible before
2765 	 * the set_pte_at() write.
2766 	 */
2767 	__SetPageUptodate(page);
2768 
2769 	entry = mk_pte(page, vma->vm_page_prot);
2770 	if (vma->vm_flags & VM_WRITE)
2771 		entry = pte_mkwrite(pte_mkdirty(entry));
2772 
2773 	fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2774 			&fe->ptl);
2775 	if (!pte_none(*fe->pte))
2776 		goto release;
2777 
2778 	/* Deliver the page fault to userland, check inside PT lock */
2779 	if (userfaultfd_missing(vma)) {
2780 		pte_unmap_unlock(fe->pte, fe->ptl);
2781 		mem_cgroup_cancel_charge(page, memcg, false);
2782 		put_page(page);
2783 		return handle_userfault(fe, VM_UFFD_MISSING);
2784 	}
2785 
2786 	inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
2787 	page_add_new_anon_rmap(page, vma, fe->address, false);
2788 	mem_cgroup_commit_charge(page, memcg, false, false);
2789 	lru_cache_add_active_or_unevictable(page, vma);
2790 setpte:
2791 	set_pte_at(vma->vm_mm, fe->address, fe->pte, entry);
2792 
2793 	/* No need to invalidate - it was non-present before */
2794 	update_mmu_cache(vma, fe->address, fe->pte);
2795 unlock:
2796 	pte_unmap_unlock(fe->pte, fe->ptl);
2797 	return 0;
2798 release:
2799 	mem_cgroup_cancel_charge(page, memcg, false);
2800 	put_page(page);
2801 	goto unlock;
2802 oom_free_page:
2803 	put_page(page);
2804 oom:
2805 	return VM_FAULT_OOM;
2806 }
2807 
2808 /*
2809  * The mmap_sem must have been held on entry, and may have been
2810  * released depending on flags and vma->vm_ops->fault() return value.
2811  * See filemap_fault() and __lock_page_retry().
2812  */
__do_fault(struct fault_env * fe,pgoff_t pgoff,struct page * cow_page,struct page ** page,void ** entry)2813 static int __do_fault(struct fault_env *fe, pgoff_t pgoff,
2814 		struct page *cow_page, struct page **page, void **entry)
2815 {
2816 	struct vm_area_struct *vma = fe->vma;
2817 	struct vm_fault vmf;
2818 	int ret;
2819 
2820 	vmf.virtual_address = (void __user *)(fe->address & PAGE_MASK);
2821 	vmf.pgoff = pgoff;
2822 	vmf.flags = fe->flags;
2823 	vmf.page = NULL;
2824 	vmf.gfp_mask = __get_fault_gfp_mask(vma);
2825 	vmf.cow_page = cow_page;
2826 
2827 	ret = vma->vm_ops->fault(vma, &vmf);
2828 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
2829 		return ret;
2830 	if (ret & VM_FAULT_DAX_LOCKED) {
2831 		*entry = vmf.entry;
2832 		return ret;
2833 	}
2834 
2835 	if (unlikely(PageHWPoison(vmf.page))) {
2836 		if (ret & VM_FAULT_LOCKED)
2837 			unlock_page(vmf.page);
2838 		put_page(vmf.page);
2839 		return VM_FAULT_HWPOISON;
2840 	}
2841 
2842 	if (unlikely(!(ret & VM_FAULT_LOCKED)))
2843 		lock_page(vmf.page);
2844 	else
2845 		VM_BUG_ON_PAGE(!PageLocked(vmf.page), vmf.page);
2846 
2847 	*page = vmf.page;
2848 	return ret;
2849 }
2850 
2851 /*
2852  * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
2853  * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
2854  * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
2855  * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
2856  */
pmd_devmap_trans_unstable(pmd_t * pmd)2857 static int pmd_devmap_trans_unstable(pmd_t *pmd)
2858 {
2859 	return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
2860 }
2861 
pte_alloc_one_map(struct fault_env * fe)2862 static int pte_alloc_one_map(struct fault_env *fe)
2863 {
2864 	struct vm_area_struct *vma = fe->vma;
2865 
2866 	if (!pmd_none(*fe->pmd))
2867 		goto map_pte;
2868 	if (fe->prealloc_pte) {
2869 		fe->ptl = pmd_lock(vma->vm_mm, fe->pmd);
2870 		if (unlikely(!pmd_none(*fe->pmd))) {
2871 			spin_unlock(fe->ptl);
2872 			goto map_pte;
2873 		}
2874 
2875 		atomic_long_inc(&vma->vm_mm->nr_ptes);
2876 		pmd_populate(vma->vm_mm, fe->pmd, fe->prealloc_pte);
2877 		spin_unlock(fe->ptl);
2878 		fe->prealloc_pte = 0;
2879 	} else if (unlikely(pte_alloc(vma->vm_mm, fe->pmd, fe->address))) {
2880 		return VM_FAULT_OOM;
2881 	}
2882 map_pte:
2883 	/*
2884 	 * If a huge pmd materialized under us just retry later.  Use
2885 	 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
2886 	 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
2887 	 * under us and then back to pmd_none, as a result of MADV_DONTNEED
2888 	 * running immediately after a huge pmd fault in a different thread of
2889 	 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
2890 	 * All we have to ensure is that it is a regular pmd that we can walk
2891 	 * with pte_offset_map() and we can do that through an atomic read in
2892 	 * C, which is what pmd_trans_unstable() provides.
2893 	 */
2894 	if (pmd_devmap_trans_unstable(fe->pmd))
2895 		return VM_FAULT_NOPAGE;
2896 
2897 	/*
2898 	 * At this point we know that our vmf->pmd points to a page of ptes
2899 	 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
2900 	 * for the duration of the fault.  If a racing MADV_DONTNEED runs and
2901 	 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
2902 	 * be valid and we will re-check to make sure the vmf->pte isn't
2903 	 * pte_none() under vmf->ptl protection when we return to
2904 	 * alloc_set_pte().
2905 	 */
2906 	fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2907 			&fe->ptl);
2908 	return 0;
2909 }
2910 
2911 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
2912 
2913 #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
transhuge_vma_suitable(struct vm_area_struct * vma,unsigned long haddr)2914 static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
2915 		unsigned long haddr)
2916 {
2917 	if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
2918 			(vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
2919 		return false;
2920 	if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
2921 		return false;
2922 	return true;
2923 }
2924 
do_set_pmd(struct fault_env * fe,struct page * page)2925 static int do_set_pmd(struct fault_env *fe, struct page *page)
2926 {
2927 	struct vm_area_struct *vma = fe->vma;
2928 	bool write = fe->flags & FAULT_FLAG_WRITE;
2929 	unsigned long haddr = fe->address & HPAGE_PMD_MASK;
2930 	pmd_t entry;
2931 	int i, ret;
2932 
2933 	if (!transhuge_vma_suitable(vma, haddr))
2934 		return VM_FAULT_FALLBACK;
2935 
2936 	ret = VM_FAULT_FALLBACK;
2937 	page = compound_head(page);
2938 
2939 	fe->ptl = pmd_lock(vma->vm_mm, fe->pmd);
2940 	if (unlikely(!pmd_none(*fe->pmd)))
2941 		goto out;
2942 
2943 	for (i = 0; i < HPAGE_PMD_NR; i++)
2944 		flush_icache_page(vma, page + i);
2945 
2946 	entry = mk_huge_pmd(page, vma->vm_page_prot);
2947 	if (write)
2948 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
2949 
2950 	add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);
2951 	page_add_file_rmap(page, true);
2952 
2953 	set_pmd_at(vma->vm_mm, haddr, fe->pmd, entry);
2954 
2955 	update_mmu_cache_pmd(vma, haddr, fe->pmd);
2956 
2957 	/* fault is handled */
2958 	ret = 0;
2959 	count_vm_event(THP_FILE_MAPPED);
2960 out:
2961 	spin_unlock(fe->ptl);
2962 	return ret;
2963 }
2964 #else
do_set_pmd(struct fault_env * fe,struct page * page)2965 static int do_set_pmd(struct fault_env *fe, struct page *page)
2966 {
2967 	BUILD_BUG();
2968 	return 0;
2969 }
2970 #endif
2971 
2972 /**
2973  * alloc_set_pte - setup new PTE entry for given page and add reverse page
2974  * mapping. If needed, the fucntion allocates page table or use pre-allocated.
2975  *
2976  * @fe: fault environment
2977  * @memcg: memcg to charge page (only for private mappings)
2978  * @page: page to map
2979  *
2980  * Caller must take care of unlocking fe->ptl, if fe->pte is non-NULL on return.
2981  *
2982  * Target users are page handler itself and implementations of
2983  * vm_ops->map_pages.
2984  */
alloc_set_pte(struct fault_env * fe,struct mem_cgroup * memcg,struct page * page)2985 int alloc_set_pte(struct fault_env *fe, struct mem_cgroup *memcg,
2986 		struct page *page)
2987 {
2988 	struct vm_area_struct *vma = fe->vma;
2989 	bool write = fe->flags & FAULT_FLAG_WRITE;
2990 	pte_t entry;
2991 	int ret;
2992 
2993 	if (pmd_none(*fe->pmd) && PageTransCompound(page) &&
2994 			IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
2995 		/* THP on COW? */
2996 		VM_BUG_ON_PAGE(memcg, page);
2997 
2998 		ret = do_set_pmd(fe, page);
2999 		if (ret != VM_FAULT_FALLBACK)
3000 			return ret;
3001 	}
3002 
3003 	if (!fe->pte) {
3004 		ret = pte_alloc_one_map(fe);
3005 		if (ret)
3006 			return ret;
3007 	}
3008 
3009 	/* Re-check under ptl */
3010 	if (unlikely(!pte_none(*fe->pte)))
3011 		return VM_FAULT_NOPAGE;
3012 
3013 	flush_icache_page(vma, page);
3014 	entry = mk_pte(page, vma->vm_page_prot);
3015 	if (write)
3016 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3017 	/* copy-on-write page */
3018 	if (write && !(vma->vm_flags & VM_SHARED)) {
3019 		inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3020 		page_add_new_anon_rmap(page, vma, fe->address, false);
3021 		mem_cgroup_commit_charge(page, memcg, false, false);
3022 		lru_cache_add_active_or_unevictable(page, vma);
3023 	} else {
3024 		inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3025 		page_add_file_rmap(page, false);
3026 	}
3027 	set_pte_at(vma->vm_mm, fe->address, fe->pte, entry);
3028 
3029 	/* no need to invalidate: a not-present page won't be cached */
3030 	update_mmu_cache(vma, fe->address, fe->pte);
3031 
3032 	return 0;
3033 }
3034 
3035 static unsigned long fault_around_bytes __read_mostly =
3036 	rounddown_pow_of_two(65536);
3037 
3038 #ifdef CONFIG_DEBUG_FS
fault_around_bytes_get(void * data,u64 * val)3039 static int fault_around_bytes_get(void *data, u64 *val)
3040 {
3041 	*val = fault_around_bytes;
3042 	return 0;
3043 }
3044 
3045 /*
3046  * fault_around_pages() and fault_around_mask() expects fault_around_bytes
3047  * rounded down to nearest page order. It's what do_fault_around() expects to
3048  * see.
3049  */
fault_around_bytes_set(void * data,u64 val)3050 static int fault_around_bytes_set(void *data, u64 val)
3051 {
3052 	if (val / PAGE_SIZE > PTRS_PER_PTE)
3053 		return -EINVAL;
3054 	if (val > PAGE_SIZE)
3055 		fault_around_bytes = rounddown_pow_of_two(val);
3056 	else
3057 		fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3058 	return 0;
3059 }
3060 DEFINE_SIMPLE_ATTRIBUTE(fault_around_bytes_fops,
3061 		fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3062 
fault_around_debugfs(void)3063 static int __init fault_around_debugfs(void)
3064 {
3065 	void *ret;
3066 
3067 	ret = debugfs_create_file("fault_around_bytes", 0644, NULL, NULL,
3068 			&fault_around_bytes_fops);
3069 	if (!ret)
3070 		pr_warn("Failed to create fault_around_bytes in debugfs");
3071 	return 0;
3072 }
3073 late_initcall(fault_around_debugfs);
3074 #endif
3075 
3076 /*
3077  * do_fault_around() tries to map few pages around the fault address. The hope
3078  * is that the pages will be needed soon and this will lower the number of
3079  * faults to handle.
3080  *
3081  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3082  * not ready to be mapped: not up-to-date, locked, etc.
3083  *
3084  * This function is called with the page table lock taken. In the split ptlock
3085  * case the page table lock only protects only those entries which belong to
3086  * the page table corresponding to the fault address.
3087  *
3088  * This function doesn't cross the VMA boundaries, in order to call map_pages()
3089  * only once.
3090  *
3091  * fault_around_pages() defines how many pages we'll try to map.
3092  * do_fault_around() expects it to return a power of two less than or equal to
3093  * PTRS_PER_PTE.
3094  *
3095  * The virtual address of the area that we map is naturally aligned to the
3096  * fault_around_pages() value (and therefore to page order).  This way it's
3097  * easier to guarantee that we don't cross page table boundaries.
3098  */
do_fault_around(struct fault_env * fe,pgoff_t start_pgoff)3099 static int do_fault_around(struct fault_env *fe, pgoff_t start_pgoff)
3100 {
3101 	unsigned long address = fe->address, nr_pages, mask;
3102 	pgoff_t end_pgoff;
3103 	int off, ret = 0;
3104 
3105 	nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3106 	mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3107 
3108 	fe->address = max(address & mask, fe->vma->vm_start);
3109 	off = ((address - fe->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3110 	start_pgoff -= off;
3111 
3112 	/*
3113 	 *  end_pgoff is either end of page table or end of vma
3114 	 *  or fault_around_pages() from start_pgoff, depending what is nearest.
3115 	 */
3116 	end_pgoff = start_pgoff -
3117 		((fe->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
3118 		PTRS_PER_PTE - 1;
3119 	end_pgoff = min3(end_pgoff, vma_pages(fe->vma) + fe->vma->vm_pgoff - 1,
3120 			start_pgoff + nr_pages - 1);
3121 
3122 	if (pmd_none(*fe->pmd)) {
3123 		fe->prealloc_pte = pte_alloc_one(fe->vma->vm_mm, fe->address);
3124 		if (!fe->prealloc_pte)
3125 			goto out;
3126 		smp_wmb(); /* See comment in __pte_alloc() */
3127 	}
3128 
3129 	fe->vma->vm_ops->map_pages(fe, start_pgoff, end_pgoff);
3130 
3131 	/* preallocated pagetable is unused: free it */
3132 	if (fe->prealloc_pte) {
3133 		pte_free(fe->vma->vm_mm, fe->prealloc_pte);
3134 		fe->prealloc_pte = 0;
3135 	}
3136 	/* Huge page is mapped? Page fault is solved */
3137 	if (pmd_trans_huge(*fe->pmd)) {
3138 		ret = VM_FAULT_NOPAGE;
3139 		goto out;
3140 	}
3141 
3142 	/* ->map_pages() haven't done anything useful. Cold page cache? */
3143 	if (!fe->pte)
3144 		goto out;
3145 
3146 	/* check if the page fault is solved */
3147 	fe->pte -= (fe->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
3148 	if (!pte_none(*fe->pte))
3149 		ret = VM_FAULT_NOPAGE;
3150 	pte_unmap_unlock(fe->pte, fe->ptl);
3151 out:
3152 	fe->address = address;
3153 	fe->pte = NULL;
3154 	return ret;
3155 }
3156 
do_read_fault(struct fault_env * fe,pgoff_t pgoff)3157 static int do_read_fault(struct fault_env *fe, pgoff_t pgoff)
3158 {
3159 	struct vm_area_struct *vma = fe->vma;
3160 	struct page *fault_page;
3161 	int ret = 0;
3162 
3163 	/*
3164 	 * Let's call ->map_pages() first and use ->fault() as fallback
3165 	 * if page by the offset is not ready to be mapped (cold cache or
3166 	 * something).
3167 	 */
3168 	if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
3169 		ret = do_fault_around(fe, pgoff);
3170 		if (ret)
3171 			return ret;
3172 	}
3173 
3174 	ret = __do_fault(fe, pgoff, NULL, &fault_page, NULL);
3175 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3176 		return ret;
3177 
3178 	ret |= alloc_set_pte(fe, NULL, fault_page);
3179 	if (fe->pte)
3180 		pte_unmap_unlock(fe->pte, fe->ptl);
3181 	unlock_page(fault_page);
3182 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3183 		put_page(fault_page);
3184 	return ret;
3185 }
3186 
do_cow_fault(struct fault_env * fe,pgoff_t pgoff)3187 static int do_cow_fault(struct fault_env *fe, pgoff_t pgoff)
3188 {
3189 	struct vm_area_struct *vma = fe->vma;
3190 	struct page *fault_page, *new_page;
3191 	void *fault_entry;
3192 	struct mem_cgroup *memcg;
3193 	int ret;
3194 
3195 	if (unlikely(anon_vma_prepare(vma)))
3196 		return VM_FAULT_OOM;
3197 
3198 	new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, fe->address);
3199 	if (!new_page)
3200 		return VM_FAULT_OOM;
3201 
3202 	if (mem_cgroup_try_charge(new_page, vma->vm_mm, GFP_KERNEL,
3203 				&memcg, false)) {
3204 		put_page(new_page);
3205 		return VM_FAULT_OOM;
3206 	}
3207 
3208 	ret = __do_fault(fe, pgoff, new_page, &fault_page, &fault_entry);
3209 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3210 		goto uncharge_out;
3211 
3212 	if (!(ret & VM_FAULT_DAX_LOCKED))
3213 		copy_user_highpage(new_page, fault_page, fe->address, vma);
3214 	__SetPageUptodate(new_page);
3215 
3216 	ret |= alloc_set_pte(fe, memcg, new_page);
3217 	if (fe->pte)
3218 		pte_unmap_unlock(fe->pte, fe->ptl);
3219 	if (!(ret & VM_FAULT_DAX_LOCKED)) {
3220 		unlock_page(fault_page);
3221 		put_page(fault_page);
3222 	} else {
3223 		dax_unlock_mapping_entry(vma->vm_file->f_mapping, pgoff);
3224 	}
3225 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3226 		goto uncharge_out;
3227 	return ret;
3228 uncharge_out:
3229 	mem_cgroup_cancel_charge(new_page, memcg, false);
3230 	put_page(new_page);
3231 	return ret;
3232 }
3233 
do_shared_fault(struct fault_env * fe,pgoff_t pgoff)3234 static int do_shared_fault(struct fault_env *fe, pgoff_t pgoff)
3235 {
3236 	struct vm_area_struct *vma = fe->vma;
3237 	struct page *fault_page;
3238 	struct address_space *mapping;
3239 	int dirtied = 0;
3240 	int ret, tmp;
3241 
3242 	ret = __do_fault(fe, pgoff, NULL, &fault_page, NULL);
3243 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3244 		return ret;
3245 
3246 	/*
3247 	 * Check if the backing address space wants to know that the page is
3248 	 * about to become writable
3249 	 */
3250 	if (vma->vm_ops->page_mkwrite) {
3251 		unlock_page(fault_page);
3252 		tmp = do_page_mkwrite(vma, fault_page, fe->address);
3253 		if (unlikely(!tmp ||
3254 				(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3255 			put_page(fault_page);
3256 			return tmp;
3257 		}
3258 	}
3259 
3260 	ret |= alloc_set_pte(fe, NULL, fault_page);
3261 	if (fe->pte)
3262 		pte_unmap_unlock(fe->pte, fe->ptl);
3263 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3264 					VM_FAULT_RETRY))) {
3265 		unlock_page(fault_page);
3266 		put_page(fault_page);
3267 		return ret;
3268 	}
3269 
3270 	if (set_page_dirty(fault_page))
3271 		dirtied = 1;
3272 	/*
3273 	 * Take a local copy of the address_space - page.mapping may be zeroed
3274 	 * by truncate after unlock_page().   The address_space itself remains
3275 	 * pinned by vma->vm_file's reference.  We rely on unlock_page()'s
3276 	 * release semantics to prevent the compiler from undoing this copying.
3277 	 */
3278 	mapping = page_rmapping(fault_page);
3279 	unlock_page(fault_page);
3280 	if ((dirtied || vma->vm_ops->page_mkwrite) && mapping) {
3281 		/*
3282 		 * Some device drivers do not set page.mapping but still
3283 		 * dirty their pages
3284 		 */
3285 		balance_dirty_pages_ratelimited(mapping);
3286 	}
3287 
3288 	if (!vma->vm_ops->page_mkwrite)
3289 		file_update_time(vma->vm_file);
3290 
3291 	return ret;
3292 }
3293 
3294 /*
3295  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3296  * but allow concurrent faults).
3297  * The mmap_sem may have been released depending on flags and our
3298  * return value.  See filemap_fault() and __lock_page_or_retry().
3299  */
do_fault(struct fault_env * fe)3300 static int do_fault(struct fault_env *fe)
3301 {
3302 	struct vm_area_struct *vma = fe->vma;
3303 	pgoff_t pgoff = linear_page_index(vma, fe->address);
3304 
3305 	/* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
3306 	if (!vma->vm_ops->fault)
3307 		return VM_FAULT_SIGBUS;
3308 	if (!(fe->flags & FAULT_FLAG_WRITE))
3309 		return do_read_fault(fe, pgoff);
3310 	if (!(vma->vm_flags & VM_SHARED))
3311 		return do_cow_fault(fe, pgoff);
3312 	return do_shared_fault(fe, pgoff);
3313 }
3314 
numa_migrate_prep(struct page * page,struct vm_area_struct * vma,unsigned long addr,int page_nid,int * flags)3315 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3316 				unsigned long addr, int page_nid,
3317 				int *flags)
3318 {
3319 	get_page(page);
3320 
3321 	count_vm_numa_event(NUMA_HINT_FAULTS);
3322 	if (page_nid == numa_node_id()) {
3323 		count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3324 		*flags |= TNF_FAULT_LOCAL;
3325 	}
3326 
3327 	return mpol_misplaced(page, vma, addr);
3328 }
3329 
do_numa_page(struct fault_env * fe,pte_t pte)3330 static int do_numa_page(struct fault_env *fe, pte_t pte)
3331 {
3332 	struct vm_area_struct *vma = fe->vma;
3333 	struct page *page = NULL;
3334 	int page_nid = -1;
3335 	int last_cpupid;
3336 	int target_nid;
3337 	bool migrated = false;
3338 	bool was_writable = pte_write(pte);
3339 	int flags = 0;
3340 
3341 	/*
3342 	* The "pte" at this point cannot be used safely without
3343 	* validation through pte_unmap_same(). It's of NUMA type but
3344 	* the pfn may be screwed if the read is non atomic.
3345 	*
3346 	* We can safely just do a "set_pte_at()", because the old
3347 	* page table entry is not accessible, so there would be no
3348 	* concurrent hardware modifications to the PTE.
3349 	*/
3350 	fe->ptl = pte_lockptr(vma->vm_mm, fe->pmd);
3351 	spin_lock(fe->ptl);
3352 	if (unlikely(!pte_same(*fe->pte, pte))) {
3353 		pte_unmap_unlock(fe->pte, fe->ptl);
3354 		goto out;
3355 	}
3356 
3357 	/* Make it present again */
3358 	pte = pte_modify(pte, vma->vm_page_prot);
3359 	pte = pte_mkyoung(pte);
3360 	if (was_writable)
3361 		pte = pte_mkwrite(pte);
3362 	set_pte_at(vma->vm_mm, fe->address, fe->pte, pte);
3363 	update_mmu_cache(vma, fe->address, fe->pte);
3364 
3365 	page = vm_normal_page(vma, fe->address, pte);
3366 	if (!page) {
3367 		pte_unmap_unlock(fe->pte, fe->ptl);
3368 		return 0;
3369 	}
3370 
3371 	/* TODO: handle PTE-mapped THP */
3372 	if (PageCompound(page)) {
3373 		pte_unmap_unlock(fe->pte, fe->ptl);
3374 		return 0;
3375 	}
3376 
3377 	/*
3378 	 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3379 	 * much anyway since they can be in shared cache state. This misses
3380 	 * the case where a mapping is writable but the process never writes
3381 	 * to it but pte_write gets cleared during protection updates and
3382 	 * pte_dirty has unpredictable behaviour between PTE scan updates,
3383 	 * background writeback, dirty balancing and application behaviour.
3384 	 */
3385 	if (!pte_write(pte))
3386 		flags |= TNF_NO_GROUP;
3387 
3388 	/*
3389 	 * Flag if the page is shared between multiple address spaces. This
3390 	 * is later used when determining whether to group tasks together
3391 	 */
3392 	if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3393 		flags |= TNF_SHARED;
3394 
3395 	last_cpupid = page_cpupid_last(page);
3396 	page_nid = page_to_nid(page);
3397 	target_nid = numa_migrate_prep(page, vma, fe->address, page_nid,
3398 			&flags);
3399 	pte_unmap_unlock(fe->pte, fe->ptl);
3400 	if (target_nid == -1) {
3401 		put_page(page);
3402 		goto out;
3403 	}
3404 
3405 	/* Migrate to the requested node */
3406 	migrated = migrate_misplaced_page(page, vma, target_nid);
3407 	if (migrated) {
3408 		page_nid = target_nid;
3409 		flags |= TNF_MIGRATED;
3410 	} else
3411 		flags |= TNF_MIGRATE_FAIL;
3412 
3413 out:
3414 	if (page_nid != -1)
3415 		task_numa_fault(last_cpupid, page_nid, 1, flags);
3416 	return 0;
3417 }
3418 
create_huge_pmd(struct fault_env * fe)3419 static int create_huge_pmd(struct fault_env *fe)
3420 {
3421 	struct vm_area_struct *vma = fe->vma;
3422 	if (vma_is_anonymous(vma))
3423 		return do_huge_pmd_anonymous_page(fe);
3424 	if (vma->vm_ops->pmd_fault)
3425 		return vma->vm_ops->pmd_fault(vma, fe->address, fe->pmd,
3426 				fe->flags);
3427 	return VM_FAULT_FALLBACK;
3428 }
3429 
wp_huge_pmd(struct fault_env * fe,pmd_t orig_pmd)3430 static int wp_huge_pmd(struct fault_env *fe, pmd_t orig_pmd)
3431 {
3432 	if (vma_is_anonymous(fe->vma))
3433 		return do_huge_pmd_wp_page(fe, orig_pmd);
3434 	if (fe->vma->vm_ops->pmd_fault)
3435 		return fe->vma->vm_ops->pmd_fault(fe->vma, fe->address, fe->pmd,
3436 				fe->flags);
3437 
3438 	/* COW handled on pte level: split pmd */
3439 	VM_BUG_ON_VMA(fe->vma->vm_flags & VM_SHARED, fe->vma);
3440 	split_huge_pmd(fe->vma, fe->pmd, fe->address);
3441 
3442 	return VM_FAULT_FALLBACK;
3443 }
3444 
vma_is_accessible(struct vm_area_struct * vma)3445 static inline bool vma_is_accessible(struct vm_area_struct *vma)
3446 {
3447 	return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
3448 }
3449 
3450 /*
3451  * These routines also need to handle stuff like marking pages dirty
3452  * and/or accessed for architectures that don't do it in hardware (most
3453  * RISC architectures).  The early dirtying is also good on the i386.
3454  *
3455  * There is also a hook called "update_mmu_cache()" that architectures
3456  * with external mmu caches can use to update those (ie the Sparc or
3457  * PowerPC hashed page tables that act as extended TLBs).
3458  *
3459  * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
3460  * concurrent faults).
3461  *
3462  * The mmap_sem may have been released depending on flags and our return value.
3463  * See filemap_fault() and __lock_page_or_retry().
3464  */
handle_pte_fault(struct fault_env * fe)3465 static int handle_pte_fault(struct fault_env *fe)
3466 {
3467 	pte_t entry;
3468 
3469 	if (unlikely(pmd_none(*fe->pmd))) {
3470 		/*
3471 		 * Leave __pte_alloc() until later: because vm_ops->fault may
3472 		 * want to allocate huge page, and if we expose page table
3473 		 * for an instant, it will be difficult to retract from
3474 		 * concurrent faults and from rmap lookups.
3475 		 */
3476 		fe->pte = NULL;
3477 	} else {
3478 		/* See comment in pte_alloc_one_map() */
3479 		if (pmd_devmap_trans_unstable(fe->pmd))
3480 			return 0;
3481 		/*
3482 		 * A regular pmd is established and it can't morph into a huge
3483 		 * pmd from under us anymore at this point because we hold the
3484 		 * mmap_sem read mode and khugepaged takes it in write mode.
3485 		 * So now it's safe to run pte_offset_map().
3486 		 */
3487 		fe->pte = pte_offset_map(fe->pmd, fe->address);
3488 
3489 		entry = *fe->pte;
3490 
3491 		/*
3492 		 * some architectures can have larger ptes than wordsize,
3493 		 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
3494 		 * CONFIG_32BIT=y, so READ_ONCE or ACCESS_ONCE cannot guarantee
3495 		 * atomic accesses.  The code below just needs a consistent
3496 		 * view for the ifs and we later double check anyway with the
3497 		 * ptl lock held. So here a barrier will do.
3498 		 */
3499 		barrier();
3500 		if (pte_none(entry)) {
3501 			pte_unmap(fe->pte);
3502 			fe->pte = NULL;
3503 		}
3504 	}
3505 
3506 	if (!fe->pte) {
3507 		if (vma_is_anonymous(fe->vma))
3508 			return do_anonymous_page(fe);
3509 		else
3510 			return do_fault(fe);
3511 	}
3512 
3513 	if (!pte_present(entry))
3514 		return do_swap_page(fe, entry);
3515 
3516 	if (pte_protnone(entry) && vma_is_accessible(fe->vma))
3517 		return do_numa_page(fe, entry);
3518 
3519 	fe->ptl = pte_lockptr(fe->vma->vm_mm, fe->pmd);
3520 	spin_lock(fe->ptl);
3521 	if (unlikely(!pte_same(*fe->pte, entry)))
3522 		goto unlock;
3523 	if (fe->flags & FAULT_FLAG_WRITE) {
3524 		if (!pte_write(entry))
3525 			return do_wp_page(fe, entry);
3526 		entry = pte_mkdirty(entry);
3527 	}
3528 	entry = pte_mkyoung(entry);
3529 	if (ptep_set_access_flags(fe->vma, fe->address, fe->pte, entry,
3530 				fe->flags & FAULT_FLAG_WRITE)) {
3531 		update_mmu_cache(fe->vma, fe->address, fe->pte);
3532 	} else {
3533 		/*
3534 		 * This is needed only for protection faults but the arch code
3535 		 * is not yet telling us if this is a protection fault or not.
3536 		 * This still avoids useless tlb flushes for .text page faults
3537 		 * with threads.
3538 		 */
3539 		if (fe->flags & FAULT_FLAG_WRITE)
3540 			flush_tlb_fix_spurious_fault(fe->vma, fe->address);
3541 	}
3542 unlock:
3543 	pte_unmap_unlock(fe->pte, fe->ptl);
3544 	return 0;
3545 }
3546 
3547 /*
3548  * By the time we get here, we already hold the mm semaphore
3549  *
3550  * The mmap_sem may have been released depending on flags and our
3551  * return value.  See filemap_fault() and __lock_page_or_retry().
3552  */
__handle_mm_fault(struct vm_area_struct * vma,unsigned long address,unsigned int flags)3553 static int __handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
3554 		unsigned int flags)
3555 {
3556 	struct fault_env fe = {
3557 		.vma = vma,
3558 		.address = address,
3559 		.flags = flags,
3560 	};
3561 	struct mm_struct *mm = vma->vm_mm;
3562 	pgd_t *pgd;
3563 	pud_t *pud;
3564 
3565 	pgd = pgd_offset(mm, address);
3566 	pud = pud_alloc(mm, pgd, address);
3567 	if (!pud)
3568 		return VM_FAULT_OOM;
3569 	fe.pmd = pmd_alloc(mm, pud, address);
3570 	if (!fe.pmd)
3571 		return VM_FAULT_OOM;
3572 	if (pmd_none(*fe.pmd) && transparent_hugepage_enabled(vma)) {
3573 		int ret = create_huge_pmd(&fe);
3574 		if (!(ret & VM_FAULT_FALLBACK))
3575 			return ret;
3576 	} else {
3577 		pmd_t orig_pmd = *fe.pmd;
3578 		int ret;
3579 
3580 		barrier();
3581 		if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
3582 			if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
3583 				return do_huge_pmd_numa_page(&fe, orig_pmd);
3584 
3585 			if ((fe.flags & FAULT_FLAG_WRITE) &&
3586 					!pmd_write(orig_pmd)) {
3587 				ret = wp_huge_pmd(&fe, orig_pmd);
3588 				if (!(ret & VM_FAULT_FALLBACK))
3589 					return ret;
3590 			} else {
3591 				huge_pmd_set_accessed(&fe, orig_pmd);
3592 				return 0;
3593 			}
3594 		}
3595 	}
3596 
3597 	return handle_pte_fault(&fe);
3598 }
3599 
3600 /*
3601  * By the time we get here, we already hold the mm semaphore
3602  *
3603  * The mmap_sem may have been released depending on flags and our
3604  * return value.  See filemap_fault() and __lock_page_or_retry().
3605  */
handle_mm_fault(struct vm_area_struct * vma,unsigned long address,unsigned int flags)3606 int handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
3607 		unsigned int flags)
3608 {
3609 	int ret;
3610 
3611 	__set_current_state(TASK_RUNNING);
3612 
3613 	count_vm_event(PGFAULT);
3614 	mem_cgroup_count_vm_event(vma->vm_mm, PGFAULT);
3615 
3616 	/* do counter updates before entering really critical section. */
3617 	check_sync_rss_stat(current);
3618 
3619 	if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
3620 					    flags & FAULT_FLAG_INSTRUCTION,
3621 					    flags & FAULT_FLAG_REMOTE))
3622 		return VM_FAULT_SIGSEGV;
3623 
3624 	/*
3625 	 * Enable the memcg OOM handling for faults triggered in user
3626 	 * space.  Kernel faults are handled more gracefully.
3627 	 */
3628 	if (flags & FAULT_FLAG_USER)
3629 		mem_cgroup_oom_enable();
3630 
3631 	if (unlikely(is_vm_hugetlb_page(vma)))
3632 		ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
3633 	else
3634 		ret = __handle_mm_fault(vma, address, flags);
3635 
3636 	if (flags & FAULT_FLAG_USER) {
3637 		mem_cgroup_oom_disable();
3638                 /*
3639                  * The task may have entered a memcg OOM situation but
3640                  * if the allocation error was handled gracefully (no
3641                  * VM_FAULT_OOM), there is no need to kill anything.
3642                  * Just clean up the OOM state peacefully.
3643                  */
3644                 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
3645                         mem_cgroup_oom_synchronize(false);
3646 	}
3647 
3648 	/*
3649 	 * This mm has been already reaped by the oom reaper and so the
3650 	 * refault cannot be trusted in general. Anonymous refaults would
3651 	 * lose data and give a zero page instead e.g. This is especially
3652 	 * problem for use_mm() because regular tasks will just die and
3653 	 * the corrupted data will not be visible anywhere while kthread
3654 	 * will outlive the oom victim and potentially propagate the date
3655 	 * further.
3656 	 */
3657 	if (unlikely((current->flags & PF_KTHREAD) && !(ret & VM_FAULT_ERROR)
3658 				&& test_bit(MMF_UNSTABLE, &vma->vm_mm->flags))) {
3659 
3660 		/*
3661 		 * We are going to enforce SIGBUS but the PF path might have
3662 		 * dropped the mmap_sem already so take it again so that
3663 		 * we do not break expectations of all arch specific PF paths
3664 		 * and g-u-p
3665 		 */
3666 		if (ret & VM_FAULT_RETRY)
3667 			down_read(&vma->vm_mm->mmap_sem);
3668 		ret = VM_FAULT_SIGBUS;
3669 	}
3670 
3671 	return ret;
3672 }
3673 EXPORT_SYMBOL_GPL(handle_mm_fault);
3674 
3675 #ifndef __PAGETABLE_PUD_FOLDED
3676 /*
3677  * Allocate page upper directory.
3678  * We've already handled the fast-path in-line.
3679  */
__pud_alloc(struct mm_struct * mm,pgd_t * pgd,unsigned long address)3680 int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
3681 {
3682 	pud_t *new = pud_alloc_one(mm, address);
3683 	if (!new)
3684 		return -ENOMEM;
3685 
3686 	smp_wmb(); /* See comment in __pte_alloc */
3687 
3688 	spin_lock(&mm->page_table_lock);
3689 	if (pgd_present(*pgd))		/* Another has populated it */
3690 		pud_free(mm, new);
3691 	else
3692 		pgd_populate(mm, pgd, new);
3693 	spin_unlock(&mm->page_table_lock);
3694 	return 0;
3695 }
3696 #endif /* __PAGETABLE_PUD_FOLDED */
3697 
3698 #ifndef __PAGETABLE_PMD_FOLDED
3699 /*
3700  * Allocate page middle directory.
3701  * We've already handled the fast-path in-line.
3702  */
__pmd_alloc(struct mm_struct * mm,pud_t * pud,unsigned long address)3703 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
3704 {
3705 	pmd_t *new = pmd_alloc_one(mm, address);
3706 	if (!new)
3707 		return -ENOMEM;
3708 
3709 	smp_wmb(); /* See comment in __pte_alloc */
3710 
3711 	spin_lock(&mm->page_table_lock);
3712 #ifndef __ARCH_HAS_4LEVEL_HACK
3713 	if (!pud_present(*pud)) {
3714 		mm_inc_nr_pmds(mm);
3715 		pud_populate(mm, pud, new);
3716 	} else	/* Another has populated it */
3717 		pmd_free(mm, new);
3718 #else
3719 	if (!pgd_present(*pud)) {
3720 		mm_inc_nr_pmds(mm);
3721 		pgd_populate(mm, pud, new);
3722 	} else /* Another has populated it */
3723 		pmd_free(mm, new);
3724 #endif /* __ARCH_HAS_4LEVEL_HACK */
3725 	spin_unlock(&mm->page_table_lock);
3726 	return 0;
3727 }
3728 #endif /* __PAGETABLE_PMD_FOLDED */
3729 
__follow_pte(struct mm_struct * mm,unsigned long address,pte_t ** ptepp,spinlock_t ** ptlp)3730 static int __follow_pte(struct mm_struct *mm, unsigned long address,
3731 		pte_t **ptepp, spinlock_t **ptlp)
3732 {
3733 	pgd_t *pgd;
3734 	pud_t *pud;
3735 	pmd_t *pmd;
3736 	pte_t *ptep;
3737 
3738 	pgd = pgd_offset(mm, address);
3739 	if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
3740 		goto out;
3741 
3742 	pud = pud_offset(pgd, address);
3743 	if (pud_none(*pud) || unlikely(pud_bad(*pud)))
3744 		goto out;
3745 
3746 	pmd = pmd_offset(pud, address);
3747 	VM_BUG_ON(pmd_trans_huge(*pmd));
3748 	if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
3749 		goto out;
3750 
3751 	/* We cannot handle huge page PFN maps. Luckily they don't exist. */
3752 	if (pmd_huge(*pmd))
3753 		goto out;
3754 
3755 	ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
3756 	if (!ptep)
3757 		goto out;
3758 	if (!pte_present(*ptep))
3759 		goto unlock;
3760 	*ptepp = ptep;
3761 	return 0;
3762 unlock:
3763 	pte_unmap_unlock(ptep, *ptlp);
3764 out:
3765 	return -EINVAL;
3766 }
3767 
follow_pte(struct mm_struct * mm,unsigned long address,pte_t ** ptepp,spinlock_t ** ptlp)3768 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
3769 			     pte_t **ptepp, spinlock_t **ptlp)
3770 {
3771 	int res;
3772 
3773 	/* (void) is needed to make gcc happy */
3774 	(void) __cond_lock(*ptlp,
3775 			   !(res = __follow_pte(mm, address, ptepp, ptlp)));
3776 	return res;
3777 }
3778 
3779 /**
3780  * follow_pfn - look up PFN at a user virtual address
3781  * @vma: memory mapping
3782  * @address: user virtual address
3783  * @pfn: location to store found PFN
3784  *
3785  * Only IO mappings and raw PFN mappings are allowed.
3786  *
3787  * Returns zero and the pfn at @pfn on success, -ve otherwise.
3788  */
follow_pfn(struct vm_area_struct * vma,unsigned long address,unsigned long * pfn)3789 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
3790 	unsigned long *pfn)
3791 {
3792 	int ret = -EINVAL;
3793 	spinlock_t *ptl;
3794 	pte_t *ptep;
3795 
3796 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
3797 		return ret;
3798 
3799 	ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
3800 	if (ret)
3801 		return ret;
3802 	*pfn = pte_pfn(*ptep);
3803 	pte_unmap_unlock(ptep, ptl);
3804 	return 0;
3805 }
3806 EXPORT_SYMBOL(follow_pfn);
3807 
3808 #ifdef CONFIG_HAVE_IOREMAP_PROT
follow_phys(struct vm_area_struct * vma,unsigned long address,unsigned int flags,unsigned long * prot,resource_size_t * phys)3809 int follow_phys(struct vm_area_struct *vma,
3810 		unsigned long address, unsigned int flags,
3811 		unsigned long *prot, resource_size_t *phys)
3812 {
3813 	int ret = -EINVAL;
3814 	pte_t *ptep, pte;
3815 	spinlock_t *ptl;
3816 
3817 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
3818 		goto out;
3819 
3820 	if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
3821 		goto out;
3822 	pte = *ptep;
3823 
3824 	if ((flags & FOLL_WRITE) && !pte_write(pte))
3825 		goto unlock;
3826 
3827 	*prot = pgprot_val(pte_pgprot(pte));
3828 	*phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
3829 
3830 	ret = 0;
3831 unlock:
3832 	pte_unmap_unlock(ptep, ptl);
3833 out:
3834 	return ret;
3835 }
3836 
generic_access_phys(struct vm_area_struct * vma,unsigned long addr,void * buf,int len,int write)3837 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
3838 			void *buf, int len, int write)
3839 {
3840 	resource_size_t phys_addr;
3841 	unsigned long prot = 0;
3842 	void __iomem *maddr;
3843 	int offset = addr & (PAGE_SIZE-1);
3844 
3845 	if (follow_phys(vma, addr, write, &prot, &phys_addr))
3846 		return -EINVAL;
3847 
3848 	maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
3849 	if (write)
3850 		memcpy_toio(maddr + offset, buf, len);
3851 	else
3852 		memcpy_fromio(buf, maddr + offset, len);
3853 	iounmap(maddr);
3854 
3855 	return len;
3856 }
3857 EXPORT_SYMBOL_GPL(generic_access_phys);
3858 #endif
3859 
3860 /*
3861  * Access another process' address space as given in mm.  If non-NULL, use the
3862  * given task for page fault accounting.
3863  */
__access_remote_vm(struct task_struct * tsk,struct mm_struct * mm,unsigned long addr,void * buf,int len,unsigned int gup_flags)3864 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
3865 		unsigned long addr, void *buf, int len, unsigned int gup_flags)
3866 {
3867 	struct vm_area_struct *vma;
3868 	void *old_buf = buf;
3869 	int write = gup_flags & FOLL_WRITE;
3870 
3871 	down_read(&mm->mmap_sem);
3872 	/* ignore errors, just check how much was successfully transferred */
3873 	while (len) {
3874 		int bytes, ret, offset;
3875 		void *maddr;
3876 		struct page *page = NULL;
3877 
3878 		ret = get_user_pages_remote(tsk, mm, addr, 1,
3879 				gup_flags, &page, &vma);
3880 		if (ret <= 0) {
3881 #ifndef CONFIG_HAVE_IOREMAP_PROT
3882 			break;
3883 #else
3884 			/*
3885 			 * Check if this is a VM_IO | VM_PFNMAP VMA, which
3886 			 * we can access using slightly different code.
3887 			 */
3888 			vma = find_vma(mm, addr);
3889 			if (!vma || vma->vm_start > addr)
3890 				break;
3891 			if (vma->vm_ops && vma->vm_ops->access)
3892 				ret = vma->vm_ops->access(vma, addr, buf,
3893 							  len, write);
3894 			if (ret <= 0)
3895 				break;
3896 			bytes = ret;
3897 #endif
3898 		} else {
3899 			bytes = len;
3900 			offset = addr & (PAGE_SIZE-1);
3901 			if (bytes > PAGE_SIZE-offset)
3902 				bytes = PAGE_SIZE-offset;
3903 
3904 			maddr = kmap(page);
3905 			if (write) {
3906 				copy_to_user_page(vma, page, addr,
3907 						  maddr + offset, buf, bytes);
3908 				set_page_dirty_lock(page);
3909 			} else {
3910 				copy_from_user_page(vma, page, addr,
3911 						    buf, maddr + offset, bytes);
3912 			}
3913 			kunmap(page);
3914 			put_page(page);
3915 		}
3916 		len -= bytes;
3917 		buf += bytes;
3918 		addr += bytes;
3919 	}
3920 	up_read(&mm->mmap_sem);
3921 
3922 	return buf - old_buf;
3923 }
3924 
3925 /**
3926  * access_remote_vm - access another process' address space
3927  * @mm:		the mm_struct of the target address space
3928  * @addr:	start address to access
3929  * @buf:	source or destination buffer
3930  * @len:	number of bytes to transfer
3931  * @gup_flags:	flags modifying lookup behaviour
3932  *
3933  * The caller must hold a reference on @mm.
3934  */
access_remote_vm(struct mm_struct * mm,unsigned long addr,void * buf,int len,unsigned int gup_flags)3935 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
3936 		void *buf, int len, unsigned int gup_flags)
3937 {
3938 	return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
3939 }
3940 
3941 /*
3942  * Access another process' address space.
3943  * Source/target buffer must be kernel space,
3944  * Do not walk the page table directly, use get_user_pages
3945  */
access_process_vm(struct task_struct * tsk,unsigned long addr,void * buf,int len,unsigned int gup_flags)3946 int access_process_vm(struct task_struct *tsk, unsigned long addr,
3947 		void *buf, int len, unsigned int gup_flags)
3948 {
3949 	struct mm_struct *mm;
3950 	int ret;
3951 
3952 	mm = get_task_mm(tsk);
3953 	if (!mm)
3954 		return 0;
3955 
3956 	ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
3957 
3958 	mmput(mm);
3959 
3960 	return ret;
3961 }
3962 
3963 /*
3964  * Print the name of a VMA.
3965  */
print_vma_addr(char * prefix,unsigned long ip)3966 void print_vma_addr(char *prefix, unsigned long ip)
3967 {
3968 	struct mm_struct *mm = current->mm;
3969 	struct vm_area_struct *vma;
3970 
3971 	/*
3972 	 * Do not print if we are in atomic
3973 	 * contexts (in exception stacks, etc.):
3974 	 */
3975 	if (preempt_count())
3976 		return;
3977 
3978 	down_read(&mm->mmap_sem);
3979 	vma = find_vma(mm, ip);
3980 	if (vma && vma->vm_file) {
3981 		struct file *f = vma->vm_file;
3982 		char *buf = (char *)__get_free_page(GFP_KERNEL);
3983 		if (buf) {
3984 			char *p;
3985 
3986 			p = file_path(f, buf, PAGE_SIZE);
3987 			if (IS_ERR(p))
3988 				p = "?";
3989 			printk("%s%s[%lx+%lx]", prefix, kbasename(p),
3990 					vma->vm_start,
3991 					vma->vm_end - vma->vm_start);
3992 			free_page((unsigned long)buf);
3993 		}
3994 	}
3995 	up_read(&mm->mmap_sem);
3996 }
3997 
3998 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
__might_fault(const char * file,int line)3999 void __might_fault(const char *file, int line)
4000 {
4001 	/*
4002 	 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4003 	 * holding the mmap_sem, this is safe because kernel memory doesn't
4004 	 * get paged out, therefore we'll never actually fault, and the
4005 	 * below annotations will generate false positives.
4006 	 */
4007 	if (segment_eq(get_fs(), KERNEL_DS))
4008 		return;
4009 	if (pagefault_disabled())
4010 		return;
4011 	__might_sleep(file, line, 0);
4012 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4013 	if (current->mm)
4014 		might_lock_read(&current->mm->mmap_sem);
4015 #endif
4016 }
4017 EXPORT_SYMBOL(__might_fault);
4018 #endif
4019 
4020 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
clear_gigantic_page(struct page * page,unsigned long addr,unsigned int pages_per_huge_page)4021 static void clear_gigantic_page(struct page *page,
4022 				unsigned long addr,
4023 				unsigned int pages_per_huge_page)
4024 {
4025 	int i;
4026 	struct page *p = page;
4027 
4028 	might_sleep();
4029 	for (i = 0; i < pages_per_huge_page;
4030 	     i++, p = mem_map_next(p, page, i)) {
4031 		cond_resched();
4032 		clear_user_highpage(p, addr + i * PAGE_SIZE);
4033 	}
4034 }
clear_huge_page(struct page * page,unsigned long addr,unsigned int pages_per_huge_page)4035 void clear_huge_page(struct page *page,
4036 		     unsigned long addr, unsigned int pages_per_huge_page)
4037 {
4038 	int i;
4039 
4040 	if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4041 		clear_gigantic_page(page, addr, pages_per_huge_page);
4042 		return;
4043 	}
4044 
4045 	might_sleep();
4046 	for (i = 0; i < pages_per_huge_page; i++) {
4047 		cond_resched();
4048 		clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4049 	}
4050 }
4051 
copy_user_gigantic_page(struct page * dst,struct page * src,unsigned long addr,struct vm_area_struct * vma,unsigned int pages_per_huge_page)4052 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4053 				    unsigned long addr,
4054 				    struct vm_area_struct *vma,
4055 				    unsigned int pages_per_huge_page)
4056 {
4057 	int i;
4058 	struct page *dst_base = dst;
4059 	struct page *src_base = src;
4060 
4061 	for (i = 0; i < pages_per_huge_page; ) {
4062 		cond_resched();
4063 		copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4064 
4065 		i++;
4066 		dst = mem_map_next(dst, dst_base, i);
4067 		src = mem_map_next(src, src_base, i);
4068 	}
4069 }
4070 
copy_user_huge_page(struct page * dst,struct page * src,unsigned long addr,struct vm_area_struct * vma,unsigned int pages_per_huge_page)4071 void copy_user_huge_page(struct page *dst, struct page *src,
4072 			 unsigned long addr, struct vm_area_struct *vma,
4073 			 unsigned int pages_per_huge_page)
4074 {
4075 	int i;
4076 
4077 	if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4078 		copy_user_gigantic_page(dst, src, addr, vma,
4079 					pages_per_huge_page);
4080 		return;
4081 	}
4082 
4083 	might_sleep();
4084 	for (i = 0; i < pages_per_huge_page; i++) {
4085 		cond_resched();
4086 		copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4087 	}
4088 }
4089 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
4090 
4091 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4092 
4093 static struct kmem_cache *page_ptl_cachep;
4094 
ptlock_cache_init(void)4095 void __init ptlock_cache_init(void)
4096 {
4097 	page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4098 			SLAB_PANIC, NULL);
4099 }
4100 
ptlock_alloc(struct page * page)4101 bool ptlock_alloc(struct page *page)
4102 {
4103 	spinlock_t *ptl;
4104 
4105 	ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
4106 	if (!ptl)
4107 		return false;
4108 	page->ptl = ptl;
4109 	return true;
4110 }
4111 
ptlock_free(struct page * page)4112 void ptlock_free(struct page *page)
4113 {
4114 	kmem_cache_free(page_ptl_cachep, page->ptl);
4115 }
4116 #endif
4117