xref: /linux/arch/x86/xen/mmu_pv.c (revision fd31a1bea3c94e01cb7b998485d2d7b14bdc8101)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Xen mmu operations
5  *
6  * This file contains the various mmu fetch and update operations.
7  * The most important job they must perform is the mapping between the
8  * domain's pfn and the overall machine mfns.
9  *
10  * Xen allows guests to directly update the pagetable, in a controlled
11  * fashion.  In other words, the guest modifies the same pagetable
12  * that the CPU actually uses, which eliminates the overhead of having
13  * a separate shadow pagetable.
14  *
15  * In order to allow this, it falls on the guest domain to map its
16  * notion of a "physical" pfn - which is just a domain-local linear
17  * address - into a real "machine address" which the CPU's MMU can
18  * use.
19  *
20  * A pgd_t/pmd_t/pte_t will typically contain an mfn, and so can be
21  * inserted directly into the pagetable.  When creating a new
22  * pte/pmd/pgd, it converts the passed pfn into an mfn.  Conversely,
23  * when reading the content back with __(pgd|pmd|pte)_val, it converts
24  * the mfn back into a pfn.
25  *
26  * The other constraint is that all pages which make up a pagetable
27  * must be mapped read-only in the guest.  This prevents uncontrolled
28  * guest updates to the pagetable.  Xen strictly enforces this, and
29  * will disallow any pagetable update which will end up mapping a
30  * pagetable page RW, and will disallow using any writable page as a
31  * pagetable.
32  *
33  * Naively, when loading %cr3 with the base of a new pagetable, Xen
34  * would need to validate the whole pagetable before going on.
35  * Naturally, this is quite slow.  The solution is to "pin" a
36  * pagetable, which enforces all the constraints on the pagetable even
37  * when it is not actively in use.  This means that Xen can be assured
38  * that it is still valid when you do load it into %cr3, and doesn't
39  * need to revalidate it.
40  *
41  * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
42  */
43 #include <linux/sched/mm.h>
44 #include <linux/debugfs.h>
45 #include <linux/bug.h>
46 #include <linux/vmalloc.h>
47 #include <linux/export.h>
48 #include <linux/init.h>
49 #include <linux/gfp.h>
50 #include <linux/memblock.h>
51 #include <linux/seq_file.h>
52 #include <linux/crash_dump.h>
53 #include <linux/pgtable.h>
54 #ifdef CONFIG_KEXEC_CORE
55 #include <linux/kexec.h>
56 #endif
57 
58 #include <trace/events/xen.h>
59 
60 #include <asm/tlbflush.h>
61 #include <asm/fixmap.h>
62 #include <asm/mmu_context.h>
63 #include <asm/setup.h>
64 #include <asm/paravirt.h>
65 #include <asm/e820/api.h>
66 #include <asm/linkage.h>
67 #include <asm/page.h>
68 #include <asm/init.h>
69 #include <asm/memtype.h>
70 #include <asm/smp.h>
71 #include <asm/tlb.h>
72 
73 #include <asm/xen/hypercall.h>
74 #include <asm/xen/hypervisor.h>
75 
76 #include <xen/xen.h>
77 #include <xen/page.h>
78 #include <xen/interface/xen.h>
79 #include <xen/interface/hvm/hvm_op.h>
80 #include <xen/interface/version.h>
81 #include <xen/interface/memory.h>
82 #include <xen/hvc-console.h>
83 #include <xen/swiotlb-xen.h>
84 
85 #include "xen-ops.h"
86 
87 /*
88  * Prototypes for functions called via PV_CALLEE_SAVE_REGS_THUNK() in order
89  * to avoid warnings with "-Wmissing-prototypes".
90  */
91 pteval_t xen_pte_val(pte_t pte);
92 pgdval_t xen_pgd_val(pgd_t pgd);
93 pmdval_t xen_pmd_val(pmd_t pmd);
94 pudval_t xen_pud_val(pud_t pud);
95 p4dval_t xen_p4d_val(p4d_t p4d);
96 pte_t xen_make_pte(pteval_t pte);
97 pgd_t xen_make_pgd(pgdval_t pgd);
98 pmd_t xen_make_pmd(pmdval_t pmd);
99 pud_t xen_make_pud(pudval_t pud);
100 p4d_t xen_make_p4d(p4dval_t p4d);
101 pte_t xen_make_pte_init(pteval_t pte);
102 
103 #ifdef CONFIG_X86_VSYSCALL_EMULATION
104 /* l3 pud for userspace vsyscall mapping */
105 static pud_t level3_user_vsyscall[PTRS_PER_PUD] __page_aligned_bss;
106 #endif
107 
108 /*
109  * Protects atomic reservation decrease/increase against concurrent increases.
110  * Also protects non-atomic updates of current_pages and balloon lists.
111  */
112 static DEFINE_SPINLOCK(xen_reservation_lock);
113 
114 /* Protected by xen_reservation_lock. */
115 #define MIN_CONTIG_ORDER 9 /* 2MB */
116 static unsigned int discontig_frames_order = MIN_CONTIG_ORDER;
117 static unsigned long discontig_frames_early[1UL << MIN_CONTIG_ORDER] __initdata;
118 static unsigned long *discontig_frames __refdata = discontig_frames_early;
119 static bool discontig_frames_dyn;
120 
alloc_discontig_frames(unsigned int order)121 static int alloc_discontig_frames(unsigned int order)
122 {
123 	unsigned long *new_array, *old_array;
124 	unsigned int old_order;
125 	unsigned long flags;
126 
127 	BUG_ON(order < MIN_CONTIG_ORDER);
128 	BUILD_BUG_ON(sizeof(discontig_frames_early) != PAGE_SIZE);
129 
130 	new_array = (unsigned long *)__get_free_pages(GFP_KERNEL,
131 						      order - MIN_CONTIG_ORDER);
132 	if (!new_array)
133 		return -ENOMEM;
134 
135 	spin_lock_irqsave(&xen_reservation_lock, flags);
136 
137 	old_order = discontig_frames_order;
138 
139 	if (order > discontig_frames_order || !discontig_frames_dyn) {
140 		if (!discontig_frames_dyn)
141 			old_array = NULL;
142 		else
143 			old_array = discontig_frames;
144 
145 		discontig_frames = new_array;
146 		discontig_frames_order = order;
147 		discontig_frames_dyn = true;
148 	} else {
149 		old_array = new_array;
150 	}
151 
152 	spin_unlock_irqrestore(&xen_reservation_lock, flags);
153 
154 	free_pages((unsigned long)old_array, old_order - MIN_CONTIG_ORDER);
155 
156 	return 0;
157 }
158 
159 /*
160  * Note about cr3 (pagetable base) values:
161  *
162  * xen_cr3 contains the current logical cr3 value; it contains the
163  * last set cr3.  This may not be the current effective cr3, because
164  * its update may be being lazily deferred.  However, a vcpu looking
165  * at its own cr3 can use this value knowing that it everything will
166  * be self-consistent.
167  *
168  * xen_current_cr3 contains the actual vcpu cr3; it is set once the
169  * hypercall to set the vcpu cr3 is complete (so it may be a little
170  * out of date, but it will never be set early).  If one vcpu is
171  * looking at another vcpu's cr3 value, it should use this variable.
172  */
173 DEFINE_PER_CPU(unsigned long, xen_cr3);	 /* cr3 stored as physaddr */
174 static DEFINE_PER_CPU(unsigned long, xen_current_cr3);	/* actual vcpu cr3 */
175 
176 static phys_addr_t xen_pt_base, xen_pt_size __initdata;
177 
178 static DEFINE_STATIC_KEY_FALSE(xen_struct_pages_ready);
179 
180 /*
181  * Just beyond the highest usermode address.  STACK_TOP_MAX has a
182  * redzone above it, so round it up to a PGD boundary.
183  */
184 #define USER_LIMIT	((STACK_TOP_MAX + PGDIR_SIZE - 1) & PGDIR_MASK)
185 
make_lowmem_page_readonly(void * vaddr)186 void make_lowmem_page_readonly(void *vaddr)
187 {
188 	pte_t *pte, ptev;
189 	unsigned long address = (unsigned long)vaddr;
190 	unsigned int level;
191 
192 	pte = lookup_address(address, &level);
193 	if (pte == NULL)
194 		return;		/* vaddr missing */
195 
196 	ptev = pte_wrprotect(*pte);
197 
198 	if (HYPERVISOR_update_va_mapping(address, ptev, 0))
199 		BUG();
200 }
201 
make_lowmem_page_readwrite(void * vaddr)202 void make_lowmem_page_readwrite(void *vaddr)
203 {
204 	pte_t *pte, ptev;
205 	unsigned long address = (unsigned long)vaddr;
206 	unsigned int level;
207 
208 	pte = lookup_address(address, &level);
209 	if (pte == NULL)
210 		return;		/* vaddr missing */
211 
212 	ptev = pte_mkwrite_novma(*pte);
213 
214 	if (HYPERVISOR_update_va_mapping(address, ptev, 0))
215 		BUG();
216 }
217 
218 
219 /*
220  * During early boot all page table pages are pinned, but we do not have struct
221  * pages, so return true until struct pages are ready.
222  */
xen_page_pinned(void * ptr)223 static bool xen_page_pinned(void *ptr)
224 {
225 	if (static_branch_likely(&xen_struct_pages_ready)) {
226 		struct page *page = virt_to_page(ptr);
227 
228 		return PagePinned(page);
229 	}
230 	return true;
231 }
232 
xen_extend_mmu_update(const struct mmu_update * update)233 static void xen_extend_mmu_update(const struct mmu_update *update)
234 {
235 	struct multicall_space mcs;
236 	struct mmu_update *u;
237 
238 	mcs = xen_mc_extend_args(__HYPERVISOR_mmu_update, sizeof(*u));
239 
240 	if (mcs.mc != NULL) {
241 		mcs.mc->args[1]++;
242 	} else {
243 		mcs = __xen_mc_entry(sizeof(*u));
244 		MULTI_mmu_update(mcs.mc, mcs.args, 1, NULL, DOMID_SELF);
245 	}
246 
247 	u = mcs.args;
248 	*u = *update;
249 }
250 
xen_extend_mmuext_op(const struct mmuext_op * op)251 static void xen_extend_mmuext_op(const struct mmuext_op *op)
252 {
253 	struct multicall_space mcs;
254 	struct mmuext_op *u;
255 
256 	mcs = xen_mc_extend_args(__HYPERVISOR_mmuext_op, sizeof(*u));
257 
258 	if (mcs.mc != NULL) {
259 		mcs.mc->args[1]++;
260 	} else {
261 		mcs = __xen_mc_entry(sizeof(*u));
262 		MULTI_mmuext_op(mcs.mc, mcs.args, 1, NULL, DOMID_SELF);
263 	}
264 
265 	u = mcs.args;
266 	*u = *op;
267 }
268 
xen_set_pmd_hyper(pmd_t * ptr,pmd_t val)269 static void xen_set_pmd_hyper(pmd_t *ptr, pmd_t val)
270 {
271 	struct mmu_update u;
272 
273 	preempt_disable();
274 
275 	xen_mc_batch();
276 
277 	/* ptr may be ioremapped for 64-bit pagetable setup */
278 	u.ptr = arbitrary_virt_to_machine(ptr).maddr;
279 	u.val = pmd_val_ma(val);
280 	xen_extend_mmu_update(&u);
281 
282 	xen_mc_issue(XEN_LAZY_MMU);
283 
284 	preempt_enable();
285 }
286 
xen_set_pmd(pmd_t * ptr,pmd_t val)287 static void xen_set_pmd(pmd_t *ptr, pmd_t val)
288 {
289 	trace_xen_mmu_set_pmd(ptr, val);
290 
291 	/* If page is not pinned, we can just update the entry
292 	   directly */
293 	if (!xen_page_pinned(ptr)) {
294 		*ptr = val;
295 		return;
296 	}
297 
298 	xen_set_pmd_hyper(ptr, val);
299 }
300 
301 /*
302  * Associate a virtual page frame with a given physical page frame
303  * and protection flags for that frame.
304  */
set_pte_mfn(unsigned long vaddr,unsigned long mfn,pgprot_t flags)305 void __init set_pte_mfn(unsigned long vaddr, unsigned long mfn, pgprot_t flags)
306 {
307 	if (HYPERVISOR_update_va_mapping(vaddr, mfn_pte(mfn, flags),
308 					 UVMF_INVLPG))
309 		BUG();
310 }
311 
xen_batched_set_pte(pte_t * ptep,pte_t pteval)312 static bool xen_batched_set_pte(pte_t *ptep, pte_t pteval)
313 {
314 	struct mmu_update u;
315 
316 	if (xen_get_lazy_mode() != XEN_LAZY_MMU)
317 		return false;
318 
319 	xen_mc_batch();
320 
321 	u.ptr = virt_to_machine(ptep).maddr | MMU_NORMAL_PT_UPDATE;
322 	u.val = pte_val_ma(pteval);
323 	xen_extend_mmu_update(&u);
324 
325 	xen_mc_issue(XEN_LAZY_MMU);
326 
327 	return true;
328 }
329 
__xen_set_pte(pte_t * ptep,pte_t pteval)330 static inline void __xen_set_pte(pte_t *ptep, pte_t pteval)
331 {
332 	if (!xen_batched_set_pte(ptep, pteval)) {
333 		/*
334 		 * Could call native_set_pte() here and trap and
335 		 * emulate the PTE write, but a hypercall is much cheaper.
336 		 */
337 		struct mmu_update u;
338 
339 		u.ptr = virt_to_machine(ptep).maddr | MMU_NORMAL_PT_UPDATE;
340 		u.val = pte_val_ma(pteval);
341 		HYPERVISOR_mmu_update(&u, 1, NULL, DOMID_SELF);
342 	}
343 }
344 
xen_set_pte(pte_t * ptep,pte_t pteval)345 static void xen_set_pte(pte_t *ptep, pte_t pteval)
346 {
347 	trace_xen_mmu_set_pte(ptep, pteval);
348 	__xen_set_pte(ptep, pteval);
349 }
350 
xen_ptep_modify_prot_start(struct vm_area_struct * vma,unsigned long addr,pte_t * ptep)351 static pte_t xen_ptep_modify_prot_start(struct vm_area_struct *vma,
352 					unsigned long addr, pte_t *ptep)
353 {
354 	/* Just return the pte as-is.  We preserve the bits on commit */
355 	trace_xen_mmu_ptep_modify_prot_start(vma->vm_mm, addr, ptep, *ptep);
356 	return *ptep;
357 }
358 
xen_ptep_modify_prot_commit(struct vm_area_struct * vma,unsigned long addr,pte_t * ptep,pte_t pte)359 static void xen_ptep_modify_prot_commit(struct vm_area_struct *vma,
360 					unsigned long addr,
361 					pte_t *ptep, pte_t pte)
362 {
363 	struct mmu_update u;
364 
365 	trace_xen_mmu_ptep_modify_prot_commit(vma->vm_mm, addr, ptep, pte);
366 	xen_mc_batch();
367 
368 	u.ptr = virt_to_machine(ptep).maddr | MMU_PT_UPDATE_PRESERVE_AD;
369 	u.val = pte_val_ma(pte);
370 	xen_extend_mmu_update(&u);
371 
372 	xen_mc_issue(XEN_LAZY_MMU);
373 }
374 
375 /* Assume pteval_t is equivalent to all the other *val_t types. */
pte_mfn_to_pfn(pteval_t val)376 static pteval_t pte_mfn_to_pfn(pteval_t val)
377 {
378 	if (val & _PAGE_PRESENT) {
379 		unsigned long mfn = (val & XEN_PTE_MFN_MASK) >> PAGE_SHIFT;
380 		unsigned long pfn = mfn_to_pfn(mfn);
381 
382 		pteval_t flags = val & PTE_FLAGS_MASK;
383 		if (unlikely(pfn == ~0))
384 			val = flags & ~_PAGE_PRESENT;
385 		else
386 			val = ((pteval_t)pfn << PAGE_SHIFT) | flags;
387 	}
388 
389 	return val;
390 }
391 
pte_pfn_to_mfn(pteval_t val)392 static pteval_t pte_pfn_to_mfn(pteval_t val)
393 {
394 	if (val & _PAGE_PRESENT) {
395 		unsigned long pfn = (val & PTE_PFN_MASK) >> PAGE_SHIFT;
396 		pteval_t flags = val & PTE_FLAGS_MASK;
397 		unsigned long mfn;
398 
399 		mfn = __pfn_to_mfn(pfn);
400 
401 		/*
402 		 * If there's no mfn for the pfn, then just create an
403 		 * empty non-present pte.  Unfortunately this loses
404 		 * information about the original pfn, so
405 		 * pte_mfn_to_pfn is asymmetric.
406 		 */
407 		if (unlikely(mfn == INVALID_P2M_ENTRY)) {
408 			mfn = 0;
409 			flags = 0;
410 		} else
411 			mfn &= ~(FOREIGN_FRAME_BIT | IDENTITY_FRAME_BIT);
412 		val = ((pteval_t)mfn << PAGE_SHIFT) | flags;
413 	}
414 
415 	return val;
416 }
417 
xen_pte_val(pte_t pte)418 __visible pteval_t xen_pte_val(pte_t pte)
419 {
420 	pteval_t pteval = pte.pte;
421 
422 	return pte_mfn_to_pfn(pteval);
423 }
424 PV_CALLEE_SAVE_REGS_THUNK(xen_pte_val);
425 
xen_pgd_val(pgd_t pgd)426 __visible pgdval_t xen_pgd_val(pgd_t pgd)
427 {
428 	return pte_mfn_to_pfn(pgd.pgd);
429 }
430 PV_CALLEE_SAVE_REGS_THUNK(xen_pgd_val);
431 
xen_make_pte(pteval_t pte)432 __visible pte_t xen_make_pte(pteval_t pte)
433 {
434 	pte = pte_pfn_to_mfn(pte);
435 
436 	return native_make_pte(pte);
437 }
438 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pte);
439 
xen_make_pgd(pgdval_t pgd)440 __visible pgd_t xen_make_pgd(pgdval_t pgd)
441 {
442 	pgd = pte_pfn_to_mfn(pgd);
443 	return native_make_pgd(pgd);
444 }
445 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pgd);
446 
xen_pmd_val(pmd_t pmd)447 __visible pmdval_t xen_pmd_val(pmd_t pmd)
448 {
449 	return pte_mfn_to_pfn(pmd.pmd);
450 }
451 PV_CALLEE_SAVE_REGS_THUNK(xen_pmd_val);
452 
xen_set_pud_hyper(pud_t * ptr,pud_t val)453 static void xen_set_pud_hyper(pud_t *ptr, pud_t val)
454 {
455 	struct mmu_update u;
456 
457 	preempt_disable();
458 
459 	xen_mc_batch();
460 
461 	/* ptr may be ioremapped for 64-bit pagetable setup */
462 	u.ptr = arbitrary_virt_to_machine(ptr).maddr;
463 	u.val = pud_val_ma(val);
464 	xen_extend_mmu_update(&u);
465 
466 	xen_mc_issue(XEN_LAZY_MMU);
467 
468 	preempt_enable();
469 }
470 
xen_set_pud(pud_t * ptr,pud_t val)471 static void xen_set_pud(pud_t *ptr, pud_t val)
472 {
473 	trace_xen_mmu_set_pud(ptr, val);
474 
475 	/* If page is not pinned, we can just update the entry
476 	   directly */
477 	if (!xen_page_pinned(ptr)) {
478 		*ptr = val;
479 		return;
480 	}
481 
482 	xen_set_pud_hyper(ptr, val);
483 }
484 
xen_make_pmd(pmdval_t pmd)485 __visible pmd_t xen_make_pmd(pmdval_t pmd)
486 {
487 	pmd = pte_pfn_to_mfn(pmd);
488 	return native_make_pmd(pmd);
489 }
490 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pmd);
491 
xen_pud_val(pud_t pud)492 __visible pudval_t xen_pud_val(pud_t pud)
493 {
494 	return pte_mfn_to_pfn(pud.pud);
495 }
496 PV_CALLEE_SAVE_REGS_THUNK(xen_pud_val);
497 
xen_make_pud(pudval_t pud)498 __visible pud_t xen_make_pud(pudval_t pud)
499 {
500 	pud = pte_pfn_to_mfn(pud);
501 
502 	return native_make_pud(pud);
503 }
504 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pud);
505 
xen_get_user_pgd(pgd_t * pgd)506 static pgd_t *xen_get_user_pgd(pgd_t *pgd)
507 {
508 	pgd_t *pgd_page = (pgd_t *)(((unsigned long)pgd) & PAGE_MASK);
509 	unsigned offset = pgd - pgd_page;
510 	pgd_t *user_ptr = NULL;
511 
512 	if (offset < pgd_index(USER_LIMIT)) {
513 		struct page *page = virt_to_page(pgd_page);
514 		user_ptr = (pgd_t *)page->private;
515 		if (user_ptr)
516 			user_ptr += offset;
517 	}
518 
519 	return user_ptr;
520 }
521 
__xen_set_p4d_hyper(p4d_t * ptr,p4d_t val)522 static void __xen_set_p4d_hyper(p4d_t *ptr, p4d_t val)
523 {
524 	struct mmu_update u;
525 
526 	u.ptr = virt_to_machine(ptr).maddr;
527 	u.val = p4d_val_ma(val);
528 	xen_extend_mmu_update(&u);
529 }
530 
531 /*
532  * Raw hypercall-based set_p4d, intended for in early boot before
533  * there's a page structure.  This implies:
534  *  1. The only existing pagetable is the kernel's
535  *  2. It is always pinned
536  *  3. It has no user pagetable attached to it
537  */
xen_set_p4d_hyper(p4d_t * ptr,p4d_t val)538 static void __init xen_set_p4d_hyper(p4d_t *ptr, p4d_t val)
539 {
540 	preempt_disable();
541 
542 	xen_mc_batch();
543 
544 	__xen_set_p4d_hyper(ptr, val);
545 
546 	xen_mc_issue(XEN_LAZY_MMU);
547 
548 	preempt_enable();
549 }
550 
xen_set_p4d(p4d_t * ptr,p4d_t val)551 static void xen_set_p4d(p4d_t *ptr, p4d_t val)
552 {
553 	pgd_t *user_ptr = xen_get_user_pgd((pgd_t *)ptr);
554 	pgd_t pgd_val;
555 
556 	trace_xen_mmu_set_p4d(ptr, (p4d_t *)user_ptr, val);
557 
558 	/* If page is not pinned, we can just update the entry
559 	   directly */
560 	if (!xen_page_pinned(ptr)) {
561 		*ptr = val;
562 		if (user_ptr) {
563 			WARN_ON(xen_page_pinned(user_ptr));
564 			pgd_val.pgd = p4d_val_ma(val);
565 			*user_ptr = pgd_val;
566 		}
567 		return;
568 	}
569 
570 	/* If it's pinned, then we can at least batch the kernel and
571 	   user updates together. */
572 	xen_mc_batch();
573 
574 	__xen_set_p4d_hyper(ptr, val);
575 	if (user_ptr)
576 		__xen_set_p4d_hyper((p4d_t *)user_ptr, val);
577 
578 	xen_mc_issue(XEN_LAZY_MMU);
579 }
580 
581 #if CONFIG_PGTABLE_LEVELS >= 5
xen_p4d_val(p4d_t p4d)582 __visible p4dval_t xen_p4d_val(p4d_t p4d)
583 {
584 	return pte_mfn_to_pfn(p4d.p4d);
585 }
586 PV_CALLEE_SAVE_REGS_THUNK(xen_p4d_val);
587 
xen_make_p4d(p4dval_t p4d)588 __visible p4d_t xen_make_p4d(p4dval_t p4d)
589 {
590 	p4d = pte_pfn_to_mfn(p4d);
591 
592 	return native_make_p4d(p4d);
593 }
594 PV_CALLEE_SAVE_REGS_THUNK(xen_make_p4d);
595 #endif  /* CONFIG_PGTABLE_LEVELS >= 5 */
596 
xen_pmd_walk(struct mm_struct * mm,pmd_t * pmd,void (* func)(struct mm_struct * mm,struct page *,enum pt_level),bool last,unsigned long limit)597 static void xen_pmd_walk(struct mm_struct *mm, pmd_t *pmd,
598 			 void (*func)(struct mm_struct *mm, struct page *,
599 				      enum pt_level),
600 			 bool last, unsigned long limit)
601 {
602 	int i, nr;
603 
604 	nr = last ? pmd_index(limit) + 1 : PTRS_PER_PMD;
605 	for (i = 0; i < nr; i++) {
606 		if (!pmd_none(pmd[i]))
607 			(*func)(mm, pmd_page(pmd[i]), PT_PTE);
608 	}
609 }
610 
xen_pud_walk(struct mm_struct * mm,pud_t * pud,void (* func)(struct mm_struct * mm,struct page *,enum pt_level),bool last,unsigned long limit)611 static void xen_pud_walk(struct mm_struct *mm, pud_t *pud,
612 			 void (*func)(struct mm_struct *mm, struct page *,
613 				      enum pt_level),
614 			 bool last, unsigned long limit)
615 {
616 	int i, nr;
617 
618 	nr = last ? pud_index(limit) + 1 : PTRS_PER_PUD;
619 	for (i = 0; i < nr; i++) {
620 		pmd_t *pmd;
621 
622 		if (pud_none(pud[i]))
623 			continue;
624 
625 		pmd = pmd_offset(&pud[i], 0);
626 		if (PTRS_PER_PMD > 1)
627 			(*func)(mm, virt_to_page(pmd), PT_PMD);
628 		xen_pmd_walk(mm, pmd, func, last && i == nr - 1, limit);
629 	}
630 }
631 
xen_p4d_walk(struct mm_struct * mm,p4d_t * p4d,void (* func)(struct mm_struct * mm,struct page *,enum pt_level),bool last,unsigned long limit)632 static void xen_p4d_walk(struct mm_struct *mm, p4d_t *p4d,
633 			 void (*func)(struct mm_struct *mm, struct page *,
634 				      enum pt_level),
635 			 bool last, unsigned long limit)
636 {
637 	pud_t *pud;
638 
639 
640 	if (p4d_none(*p4d))
641 		return;
642 
643 	pud = pud_offset(p4d, 0);
644 	if (PTRS_PER_PUD > 1)
645 		(*func)(mm, virt_to_page(pud), PT_PUD);
646 	xen_pud_walk(mm, pud, func, last, limit);
647 }
648 
649 /*
650  * (Yet another) pagetable walker.  This one is intended for pinning a
651  * pagetable.  This means that it walks a pagetable and calls the
652  * callback function on each page it finds making up the page table,
653  * at every level.  It walks the entire pagetable, but it only bothers
654  * pinning pte pages which are below limit.  In the normal case this
655  * will be STACK_TOP_MAX, but at boot we need to pin up to
656  * FIXADDR_TOP.
657  *
658  * We must skip the Xen hole in the middle of the address space, just after
659  * the big x86-64 virtual hole.
660  */
__xen_pgd_walk(struct mm_struct * mm,pgd_t * pgd,void (* func)(struct mm_struct * mm,struct page *,enum pt_level),unsigned long limit)661 static void __xen_pgd_walk(struct mm_struct *mm, pgd_t *pgd,
662 			   void (*func)(struct mm_struct *mm, struct page *,
663 					enum pt_level),
664 			   unsigned long limit)
665 {
666 	int i, nr;
667 	unsigned hole_low = 0, hole_high = 0;
668 
669 	/* The limit is the last byte to be touched */
670 	limit--;
671 	BUG_ON(limit >= FIXADDR_TOP);
672 
673 	/*
674 	 * 64-bit has a great big hole in the middle of the address
675 	 * space, which contains the Xen mappings.
676 	 */
677 	hole_low = pgd_index(GUARD_HOLE_BASE_ADDR);
678 	hole_high = pgd_index(GUARD_HOLE_END_ADDR);
679 
680 	nr = pgd_index(limit) + 1;
681 	for (i = 0; i < nr; i++) {
682 		p4d_t *p4d;
683 
684 		if (i >= hole_low && i < hole_high)
685 			continue;
686 
687 		if (pgd_none(pgd[i]))
688 			continue;
689 
690 		p4d = p4d_offset(&pgd[i], 0);
691 		xen_p4d_walk(mm, p4d, func, i == nr - 1, limit);
692 	}
693 
694 	/* Do the top level last, so that the callbacks can use it as
695 	   a cue to do final things like tlb flushes. */
696 	(*func)(mm, virt_to_page(pgd), PT_PGD);
697 }
698 
xen_pgd_walk(struct mm_struct * mm,void (* func)(struct mm_struct * mm,struct page *,enum pt_level),unsigned long limit)699 static void xen_pgd_walk(struct mm_struct *mm,
700 			 void (*func)(struct mm_struct *mm, struct page *,
701 				      enum pt_level),
702 			 unsigned long limit)
703 {
704 	__xen_pgd_walk(mm, mm->pgd, func, limit);
705 }
706 
707 /* If we're using split pte locks, then take the page's lock and
708    return a pointer to it.  Otherwise return NULL. */
xen_pte_lock(struct page * page,struct mm_struct * mm)709 static spinlock_t *xen_pte_lock(struct page *page, struct mm_struct *mm)
710 {
711 	spinlock_t *ptl = NULL;
712 
713 #if defined(CONFIG_SPLIT_PTE_PTLOCKS)
714 	ptl = ptlock_ptr(page_ptdesc(page));
715 	spin_lock_nest_lock(ptl, &mm->page_table_lock);
716 #endif
717 
718 	return ptl;
719 }
720 
xen_pte_unlock(void * v)721 static void xen_pte_unlock(void *v)
722 {
723 	spinlock_t *ptl = v;
724 	spin_unlock(ptl);
725 }
726 
xen_do_pin(unsigned level,unsigned long pfn)727 static void xen_do_pin(unsigned level, unsigned long pfn)
728 {
729 	struct mmuext_op op;
730 
731 	op.cmd = level;
732 	op.arg1.mfn = pfn_to_mfn(pfn);
733 
734 	xen_extend_mmuext_op(&op);
735 }
736 
xen_pin_page(struct mm_struct * mm,struct page * page,enum pt_level level)737 static void xen_pin_page(struct mm_struct *mm, struct page *page,
738 			 enum pt_level level)
739 {
740 	unsigned pgfl = TestSetPagePinned(page);
741 
742 	if (!pgfl) {
743 		void *pt = lowmem_page_address(page);
744 		unsigned long pfn = page_to_pfn(page);
745 		struct multicall_space mcs = __xen_mc_entry(0);
746 		spinlock_t *ptl;
747 
748 		/*
749 		 * We need to hold the pagetable lock between the time
750 		 * we make the pagetable RO and when we actually pin
751 		 * it.  If we don't, then other users may come in and
752 		 * attempt to update the pagetable by writing it,
753 		 * which will fail because the memory is RO but not
754 		 * pinned, so Xen won't do the trap'n'emulate.
755 		 *
756 		 * If we're using split pte locks, we can't hold the
757 		 * entire pagetable's worth of locks during the
758 		 * traverse, because we may wrap the preempt count (8
759 		 * bits).  The solution is to mark RO and pin each PTE
760 		 * page while holding the lock.  This means the number
761 		 * of locks we end up holding is never more than a
762 		 * batch size (~32 entries, at present).
763 		 *
764 		 * If we're not using split pte locks, we needn't pin
765 		 * the PTE pages independently, because we're
766 		 * protected by the overall pagetable lock.
767 		 */
768 		ptl = NULL;
769 		if (level == PT_PTE)
770 			ptl = xen_pte_lock(page, mm);
771 
772 		MULTI_update_va_mapping(mcs.mc, (unsigned long)pt,
773 					pfn_pte(pfn, PAGE_KERNEL_RO),
774 					level == PT_PGD ? UVMF_TLB_FLUSH : 0);
775 
776 		if (ptl) {
777 			xen_do_pin(MMUEXT_PIN_L1_TABLE, pfn);
778 
779 			/* Queue a deferred unlock for when this batch
780 			   is completed. */
781 			xen_mc_callback(xen_pte_unlock, ptl);
782 		}
783 	}
784 }
785 
786 /* This is called just after a mm has been created, but it has not
787    been used yet.  We need to make sure that its pagetable is all
788    read-only, and can be pinned. */
__xen_pgd_pin(struct mm_struct * mm,pgd_t * pgd)789 static void __xen_pgd_pin(struct mm_struct *mm, pgd_t *pgd)
790 {
791 	pgd_t *user_pgd = xen_get_user_pgd(pgd);
792 
793 	trace_xen_mmu_pgd_pin(mm, pgd);
794 
795 	xen_mc_batch();
796 
797 	__xen_pgd_walk(mm, pgd, xen_pin_page, USER_LIMIT);
798 
799 	xen_do_pin(MMUEXT_PIN_L4_TABLE, PFN_DOWN(__pa(pgd)));
800 
801 	if (user_pgd) {
802 		xen_pin_page(mm, virt_to_page(user_pgd), PT_PGD);
803 		xen_do_pin(MMUEXT_PIN_L4_TABLE,
804 			   PFN_DOWN(__pa(user_pgd)));
805 	}
806 
807 	xen_mc_issue(0);
808 }
809 
xen_pgd_pin(struct mm_struct * mm)810 static void xen_pgd_pin(struct mm_struct *mm)
811 {
812 	__xen_pgd_pin(mm, mm->pgd);
813 }
814 
815 /*
816  * On save, we need to pin all pagetables to make sure they get their
817  * mfns turned into pfns.  Search the list for any unpinned pgds and pin
818  * them (unpinned pgds are not currently in use, probably because the
819  * process is under construction or destruction).
820  *
821  * Expected to be called in stop_machine() ("equivalent to taking
822  * every spinlock in the system"), so the locking doesn't really
823  * matter all that much.
824  */
xen_mm_pin_all(void)825 void xen_mm_pin_all(void)
826 {
827 	struct page *page;
828 
829 	spin_lock(&init_mm.page_table_lock);
830 	spin_lock(&pgd_lock);
831 
832 	list_for_each_entry(page, &pgd_list, lru) {
833 		if (!PagePinned(page)) {
834 			__xen_pgd_pin(&init_mm, (pgd_t *)page_address(page));
835 			SetPageSavePinned(page);
836 		}
837 	}
838 
839 	spin_unlock(&pgd_lock);
840 	spin_unlock(&init_mm.page_table_lock);
841 }
842 
xen_mark_pinned(struct mm_struct * mm,struct page * page,enum pt_level level)843 static void __init xen_mark_pinned(struct mm_struct *mm, struct page *page,
844 				   enum pt_level level)
845 {
846 	SetPagePinned(page);
847 }
848 
849 /*
850  * The init_mm pagetable is really pinned as soon as its created, but
851  * that's before we have page structures to store the bits.  So do all
852  * the book-keeping now once struct pages for allocated pages are
853  * initialized. This happens only after memblock_free_all() is called.
854  */
xen_after_bootmem(void)855 static void __init xen_after_bootmem(void)
856 {
857 	static_branch_enable(&xen_struct_pages_ready);
858 #ifdef CONFIG_X86_VSYSCALL_EMULATION
859 	SetPagePinned(virt_to_page(level3_user_vsyscall));
860 #endif
861 	xen_pgd_walk(&init_mm, xen_mark_pinned, FIXADDR_TOP);
862 
863 	if (alloc_discontig_frames(MIN_CONTIG_ORDER))
864 		BUG();
865 }
866 
xen_unpin_page(struct mm_struct * mm,struct page * page,enum pt_level level)867 static void xen_unpin_page(struct mm_struct *mm, struct page *page,
868 			   enum pt_level level)
869 {
870 	unsigned pgfl = TestClearPagePinned(page);
871 
872 	if (pgfl) {
873 		void *pt = lowmem_page_address(page);
874 		unsigned long pfn = page_to_pfn(page);
875 		spinlock_t *ptl = NULL;
876 		struct multicall_space mcs;
877 
878 		/*
879 		 * Do the converse to pin_page.  If we're using split
880 		 * pte locks, we must be holding the lock for while
881 		 * the pte page is unpinned but still RO to prevent
882 		 * concurrent updates from seeing it in this
883 		 * partially-pinned state.
884 		 */
885 		if (level == PT_PTE) {
886 			ptl = xen_pte_lock(page, mm);
887 
888 			if (ptl)
889 				xen_do_pin(MMUEXT_UNPIN_TABLE, pfn);
890 		}
891 
892 		mcs = __xen_mc_entry(0);
893 
894 		MULTI_update_va_mapping(mcs.mc, (unsigned long)pt,
895 					pfn_pte(pfn, PAGE_KERNEL),
896 					level == PT_PGD ? UVMF_TLB_FLUSH : 0);
897 
898 		if (ptl) {
899 			/* unlock when batch completed */
900 			xen_mc_callback(xen_pte_unlock, ptl);
901 		}
902 	}
903 }
904 
905 /* Release a pagetables pages back as normal RW */
__xen_pgd_unpin(struct mm_struct * mm,pgd_t * pgd)906 static void __xen_pgd_unpin(struct mm_struct *mm, pgd_t *pgd)
907 {
908 	pgd_t *user_pgd = xen_get_user_pgd(pgd);
909 
910 	trace_xen_mmu_pgd_unpin(mm, pgd);
911 
912 	xen_mc_batch();
913 
914 	xen_do_pin(MMUEXT_UNPIN_TABLE, PFN_DOWN(__pa(pgd)));
915 
916 	if (user_pgd) {
917 		xen_do_pin(MMUEXT_UNPIN_TABLE,
918 			   PFN_DOWN(__pa(user_pgd)));
919 		xen_unpin_page(mm, virt_to_page(user_pgd), PT_PGD);
920 	}
921 
922 	__xen_pgd_walk(mm, pgd, xen_unpin_page, USER_LIMIT);
923 
924 	xen_mc_issue(0);
925 }
926 
xen_pgd_unpin(struct mm_struct * mm)927 static void xen_pgd_unpin(struct mm_struct *mm)
928 {
929 	__xen_pgd_unpin(mm, mm->pgd);
930 }
931 
932 /*
933  * On resume, undo any pinning done at save, so that the rest of the
934  * kernel doesn't see any unexpected pinned pagetables.
935  */
xen_mm_unpin_all(void)936 void xen_mm_unpin_all(void)
937 {
938 	struct page *page;
939 
940 	spin_lock(&init_mm.page_table_lock);
941 	spin_lock(&pgd_lock);
942 
943 	list_for_each_entry(page, &pgd_list, lru) {
944 		if (PageSavePinned(page)) {
945 			BUG_ON(!PagePinned(page));
946 			__xen_pgd_unpin(&init_mm, (pgd_t *)page_address(page));
947 			ClearPageSavePinned(page);
948 		}
949 	}
950 
951 	spin_unlock(&pgd_lock);
952 	spin_unlock(&init_mm.page_table_lock);
953 }
954 
xen_enter_mmap(struct mm_struct * mm)955 static void xen_enter_mmap(struct mm_struct *mm)
956 {
957 	spin_lock(&mm->page_table_lock);
958 	xen_pgd_pin(mm);
959 	spin_unlock(&mm->page_table_lock);
960 }
961 
drop_mm_ref_this_cpu(void * info)962 static void drop_mm_ref_this_cpu(void *info)
963 {
964 	struct mm_struct *mm = info;
965 
966 	if (this_cpu_read(cpu_tlbstate.loaded_mm) == mm)
967 		leave_mm();
968 
969 	/*
970 	 * If this cpu still has a stale cr3 reference, then make sure
971 	 * it has been flushed.
972 	 */
973 	if (this_cpu_read(xen_current_cr3) == __pa(mm->pgd))
974 		xen_mc_flush();
975 }
976 
977 #ifdef CONFIG_SMP
978 /*
979  * Another cpu may still have their %cr3 pointing at the pagetable, so
980  * we need to repoint it somewhere else before we can unpin it.
981  */
xen_drop_mm_ref(struct mm_struct * mm)982 static void xen_drop_mm_ref(struct mm_struct *mm)
983 {
984 	cpumask_var_t mask;
985 	unsigned cpu;
986 
987 	drop_mm_ref_this_cpu(mm);
988 
989 	/* Get the "official" set of cpus referring to our pagetable. */
990 	if (!alloc_cpumask_var(&mask, GFP_ATOMIC)) {
991 		for_each_online_cpu(cpu) {
992 			if (per_cpu(xen_current_cr3, cpu) != __pa(mm->pgd))
993 				continue;
994 			smp_call_function_single(cpu, drop_mm_ref_this_cpu, mm, 1);
995 		}
996 		return;
997 	}
998 
999 	/*
1000 	 * It's possible that a vcpu may have a stale reference to our
1001 	 * cr3, because its in lazy mode, and it hasn't yet flushed
1002 	 * its set of pending hypercalls yet.  In this case, we can
1003 	 * look at its actual current cr3 value, and force it to flush
1004 	 * if needed.
1005 	 */
1006 	cpumask_clear(mask);
1007 	for_each_online_cpu(cpu) {
1008 		if (per_cpu(xen_current_cr3, cpu) == __pa(mm->pgd))
1009 			cpumask_set_cpu(cpu, mask);
1010 	}
1011 
1012 	smp_call_function_many(mask, drop_mm_ref_this_cpu, mm, 1);
1013 	free_cpumask_var(mask);
1014 }
1015 #else
xen_drop_mm_ref(struct mm_struct * mm)1016 static void xen_drop_mm_ref(struct mm_struct *mm)
1017 {
1018 	drop_mm_ref_this_cpu(mm);
1019 }
1020 #endif
1021 
1022 /*
1023  * While a process runs, Xen pins its pagetables, which means that the
1024  * hypervisor forces it to be read-only, and it controls all updates
1025  * to it.  This means that all pagetable updates have to go via the
1026  * hypervisor, which is moderately expensive.
1027  *
1028  * Since we're pulling the pagetable down, we switch to use init_mm,
1029  * unpin old process pagetable and mark it all read-write, which
1030  * allows further operations on it to be simple memory accesses.
1031  *
1032  * The only subtle point is that another CPU may be still using the
1033  * pagetable because of lazy tlb flushing.  This means we need need to
1034  * switch all CPUs off this pagetable before we can unpin it.
1035  */
xen_exit_mmap(struct mm_struct * mm)1036 static void xen_exit_mmap(struct mm_struct *mm)
1037 {
1038 	get_cpu();		/* make sure we don't move around */
1039 	xen_drop_mm_ref(mm);
1040 	put_cpu();
1041 
1042 	spin_lock(&mm->page_table_lock);
1043 
1044 	/* pgd may not be pinned in the error exit path of execve */
1045 	if (xen_page_pinned(mm->pgd))
1046 		xen_pgd_unpin(mm);
1047 
1048 	spin_unlock(&mm->page_table_lock);
1049 }
1050 
1051 static void xen_post_allocator_init(void);
1052 
pin_pagetable_pfn(unsigned cmd,unsigned long pfn)1053 static void __init pin_pagetable_pfn(unsigned cmd, unsigned long pfn)
1054 {
1055 	struct mmuext_op op;
1056 
1057 	op.cmd = cmd;
1058 	op.arg1.mfn = pfn_to_mfn(pfn);
1059 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF))
1060 		BUG();
1061 }
1062 
xen_cleanhighmap(unsigned long vaddr,unsigned long vaddr_end)1063 static void __init xen_cleanhighmap(unsigned long vaddr,
1064 				    unsigned long vaddr_end)
1065 {
1066 	unsigned long kernel_end = roundup((unsigned long)_brk_end, PMD_SIZE) - 1;
1067 	pmd_t *pmd = level2_kernel_pgt + pmd_index(vaddr);
1068 
1069 	/* NOTE: The loop is more greedy than the cleanup_highmap variant.
1070 	 * We include the PMD passed in on _both_ boundaries. */
1071 	for (; vaddr <= vaddr_end && (pmd < (level2_kernel_pgt + PTRS_PER_PMD));
1072 			pmd++, vaddr += PMD_SIZE) {
1073 		if (pmd_none(*pmd))
1074 			continue;
1075 		if (vaddr < (unsigned long) _text || vaddr > kernel_end)
1076 			set_pmd(pmd, __pmd(0));
1077 	}
1078 	/* In case we did something silly, we should crash in this function
1079 	 * instead of somewhere later and be confusing. */
1080 	xen_mc_flush();
1081 }
1082 
1083 /*
1084  * Make a page range writeable and free it.
1085  */
xen_free_ro_pages(unsigned long paddr,unsigned long size)1086 static void __init xen_free_ro_pages(unsigned long paddr, unsigned long size)
1087 {
1088 	void *vaddr = __va(paddr);
1089 	void *vaddr_end = vaddr + size;
1090 
1091 	for (; vaddr < vaddr_end; vaddr += PAGE_SIZE)
1092 		make_lowmem_page_readwrite(vaddr);
1093 
1094 	memblock_phys_free(paddr, size);
1095 }
1096 
xen_cleanmfnmap_free_pgtbl(void * pgtbl,bool unpin)1097 static void __init xen_cleanmfnmap_free_pgtbl(void *pgtbl, bool unpin)
1098 {
1099 	unsigned long pa = __pa(pgtbl) & PHYSICAL_PAGE_MASK;
1100 
1101 	if (unpin)
1102 		pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, PFN_DOWN(pa));
1103 	ClearPagePinned(virt_to_page(__va(pa)));
1104 	xen_free_ro_pages(pa, PAGE_SIZE);
1105 }
1106 
xen_cleanmfnmap_pmd(pmd_t * pmd,bool unpin)1107 static void __init xen_cleanmfnmap_pmd(pmd_t *pmd, bool unpin)
1108 {
1109 	unsigned long pa;
1110 	pte_t *pte_tbl;
1111 	int i;
1112 
1113 	if (pmd_leaf(*pmd)) {
1114 		pa = pmd_val(*pmd) & PHYSICAL_PAGE_MASK;
1115 		xen_free_ro_pages(pa, PMD_SIZE);
1116 		return;
1117 	}
1118 
1119 	pte_tbl = pte_offset_kernel(pmd, 0);
1120 	for (i = 0; i < PTRS_PER_PTE; i++) {
1121 		if (pte_none(pte_tbl[i]))
1122 			continue;
1123 		pa = pte_pfn(pte_tbl[i]) << PAGE_SHIFT;
1124 		xen_free_ro_pages(pa, PAGE_SIZE);
1125 	}
1126 	set_pmd(pmd, __pmd(0));
1127 	xen_cleanmfnmap_free_pgtbl(pte_tbl, unpin);
1128 }
1129 
xen_cleanmfnmap_pud(pud_t * pud,bool unpin)1130 static void __init xen_cleanmfnmap_pud(pud_t *pud, bool unpin)
1131 {
1132 	unsigned long pa;
1133 	pmd_t *pmd_tbl;
1134 	int i;
1135 
1136 	if (pud_leaf(*pud)) {
1137 		pa = pud_val(*pud) & PHYSICAL_PAGE_MASK;
1138 		xen_free_ro_pages(pa, PUD_SIZE);
1139 		return;
1140 	}
1141 
1142 	pmd_tbl = pmd_offset(pud, 0);
1143 	for (i = 0; i < PTRS_PER_PMD; i++) {
1144 		if (pmd_none(pmd_tbl[i]))
1145 			continue;
1146 		xen_cleanmfnmap_pmd(pmd_tbl + i, unpin);
1147 	}
1148 	set_pud(pud, __pud(0));
1149 	xen_cleanmfnmap_free_pgtbl(pmd_tbl, unpin);
1150 }
1151 
xen_cleanmfnmap_p4d(p4d_t * p4d,bool unpin)1152 static void __init xen_cleanmfnmap_p4d(p4d_t *p4d, bool unpin)
1153 {
1154 	unsigned long pa;
1155 	pud_t *pud_tbl;
1156 	int i;
1157 
1158 	if (p4d_leaf(*p4d)) {
1159 		pa = p4d_val(*p4d) & PHYSICAL_PAGE_MASK;
1160 		xen_free_ro_pages(pa, P4D_SIZE);
1161 		return;
1162 	}
1163 
1164 	pud_tbl = pud_offset(p4d, 0);
1165 	for (i = 0; i < PTRS_PER_PUD; i++) {
1166 		if (pud_none(pud_tbl[i]))
1167 			continue;
1168 		xen_cleanmfnmap_pud(pud_tbl + i, unpin);
1169 	}
1170 	set_p4d(p4d, __p4d(0));
1171 	xen_cleanmfnmap_free_pgtbl(pud_tbl, unpin);
1172 }
1173 
1174 /*
1175  * Since it is well isolated we can (and since it is perhaps large we should)
1176  * also free the page tables mapping the initial P->M table.
1177  */
xen_cleanmfnmap(unsigned long vaddr)1178 static void __init xen_cleanmfnmap(unsigned long vaddr)
1179 {
1180 	pgd_t *pgd;
1181 	p4d_t *p4d;
1182 	bool unpin;
1183 
1184 	unpin = (vaddr == 2 * PGDIR_SIZE);
1185 	vaddr &= PMD_MASK;
1186 	pgd = pgd_offset_k(vaddr);
1187 	p4d = p4d_offset(pgd, 0);
1188 	if (!p4d_none(*p4d))
1189 		xen_cleanmfnmap_p4d(p4d, unpin);
1190 }
1191 
xen_pagetable_p2m_free(void)1192 static void __init xen_pagetable_p2m_free(void)
1193 {
1194 	unsigned long size;
1195 	unsigned long addr;
1196 
1197 	size = PAGE_ALIGN(xen_start_info->nr_pages * sizeof(unsigned long));
1198 
1199 	/* No memory or already called. */
1200 	if ((unsigned long)xen_p2m_addr == xen_start_info->mfn_list)
1201 		return;
1202 
1203 	/* using __ka address and sticking INVALID_P2M_ENTRY! */
1204 	memset((void *)xen_start_info->mfn_list, 0xff, size);
1205 
1206 	addr = xen_start_info->mfn_list;
1207 	/*
1208 	 * We could be in __ka space.
1209 	 * We roundup to the PMD, which means that if anybody at this stage is
1210 	 * using the __ka address of xen_start_info or
1211 	 * xen_start_info->shared_info they are in going to crash. Fortunately
1212 	 * we have already revectored in xen_setup_kernel_pagetable.
1213 	 */
1214 	size = roundup(size, PMD_SIZE);
1215 
1216 	if (addr >= __START_KERNEL_map) {
1217 		xen_cleanhighmap(addr, addr + size);
1218 		size = PAGE_ALIGN(xen_start_info->nr_pages *
1219 				  sizeof(unsigned long));
1220 		memblock_free((void *)addr, size);
1221 	} else {
1222 		xen_cleanmfnmap(addr);
1223 	}
1224 }
1225 
xen_pagetable_cleanhighmap(void)1226 static void __init xen_pagetable_cleanhighmap(void)
1227 {
1228 	unsigned long size;
1229 	unsigned long addr;
1230 
1231 	/* At this stage, cleanup_highmap has already cleaned __ka space
1232 	 * from _brk_limit way up to the max_pfn_mapped (which is the end of
1233 	 * the ramdisk). We continue on, erasing PMD entries that point to page
1234 	 * tables - do note that they are accessible at this stage via __va.
1235 	 * As Xen is aligning the memory end to a 4MB boundary, for good
1236 	 * measure we also round up to PMD_SIZE * 2 - which means that if
1237 	 * anybody is using __ka address to the initial boot-stack - and try
1238 	 * to use it - they are going to crash. The xen_start_info has been
1239 	 * taken care of already in xen_setup_kernel_pagetable. */
1240 	addr = xen_start_info->pt_base;
1241 	size = xen_start_info->nr_pt_frames * PAGE_SIZE;
1242 
1243 	xen_cleanhighmap(addr, roundup(addr + size, PMD_SIZE * 2));
1244 	xen_start_info->pt_base = (unsigned long)__va(__pa(xen_start_info->pt_base));
1245 }
1246 
xen_pagetable_p2m_setup(void)1247 static void __init xen_pagetable_p2m_setup(void)
1248 {
1249 	xen_vmalloc_p2m_tree();
1250 
1251 	xen_pagetable_p2m_free();
1252 
1253 	xen_pagetable_cleanhighmap();
1254 
1255 	/* And revector! Bye bye old array */
1256 	xen_start_info->mfn_list = (unsigned long)xen_p2m_addr;
1257 }
1258 
xen_pagetable_init(void)1259 static void __init xen_pagetable_init(void)
1260 {
1261 	/*
1262 	 * The majority of further PTE writes is to pagetables already
1263 	 * announced as such to Xen. Hence it is more efficient to use
1264 	 * hypercalls for these updates.
1265 	 */
1266 	pv_ops.mmu.set_pte = __xen_set_pte;
1267 
1268 	paging_init();
1269 	xen_post_allocator_init();
1270 
1271 	xen_pagetable_p2m_setup();
1272 
1273 	/* Allocate and initialize top and mid mfn levels for p2m structure */
1274 	xen_build_mfn_list_list();
1275 
1276 	/* Remap memory freed due to conflicts with E820 map */
1277 	xen_remap_memory();
1278 	xen_setup_mfn_list_list();
1279 }
1280 
xen_write_cr2(unsigned long cr2)1281 static noinstr void xen_write_cr2(unsigned long cr2)
1282 {
1283 	this_cpu_read(xen_vcpu)->arch.cr2 = cr2;
1284 }
1285 
xen_flush_tlb(void)1286 static noinline void xen_flush_tlb(void)
1287 {
1288 	struct mmuext_op *op;
1289 	struct multicall_space mcs;
1290 
1291 	preempt_disable();
1292 
1293 	mcs = xen_mc_entry(sizeof(*op));
1294 
1295 	op = mcs.args;
1296 	op->cmd = MMUEXT_TLB_FLUSH_LOCAL;
1297 	MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
1298 
1299 	xen_mc_issue(XEN_LAZY_MMU);
1300 
1301 	preempt_enable();
1302 }
1303 
xen_flush_tlb_one_user(unsigned long addr)1304 static void xen_flush_tlb_one_user(unsigned long addr)
1305 {
1306 	struct mmuext_op *op;
1307 	struct multicall_space mcs;
1308 
1309 	trace_xen_mmu_flush_tlb_one_user(addr);
1310 
1311 	preempt_disable();
1312 
1313 	mcs = xen_mc_entry(sizeof(*op));
1314 	op = mcs.args;
1315 	op->cmd = MMUEXT_INVLPG_LOCAL;
1316 	op->arg1.linear_addr = addr & PAGE_MASK;
1317 	MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
1318 
1319 	xen_mc_issue(XEN_LAZY_MMU);
1320 
1321 	preempt_enable();
1322 }
1323 
xen_flush_tlb_multi(const struct cpumask * cpus,const struct flush_tlb_info * info)1324 static void xen_flush_tlb_multi(const struct cpumask *cpus,
1325 				const struct flush_tlb_info *info)
1326 {
1327 	struct {
1328 		struct mmuext_op op;
1329 		DECLARE_BITMAP(mask, NR_CPUS);
1330 	} *args;
1331 	struct multicall_space mcs;
1332 	const size_t mc_entry_size = sizeof(args->op) +
1333 		sizeof(args->mask[0]) * BITS_TO_LONGS(num_possible_cpus());
1334 
1335 	trace_xen_mmu_flush_tlb_multi(cpus, info->mm, info->start, info->end);
1336 
1337 	if (cpumask_empty(cpus))
1338 		return;		/* nothing to do */
1339 
1340 	mcs = xen_mc_entry(mc_entry_size);
1341 	args = mcs.args;
1342 	args->op.arg2.vcpumask = to_cpumask(args->mask);
1343 
1344 	/* Remove any offline CPUs */
1345 	cpumask_and(to_cpumask(args->mask), cpus, cpu_online_mask);
1346 
1347 	args->op.cmd = MMUEXT_TLB_FLUSH_MULTI;
1348 	if (info->end != TLB_FLUSH_ALL &&
1349 	    (info->end - info->start) <= PAGE_SIZE) {
1350 		args->op.cmd = MMUEXT_INVLPG_MULTI;
1351 		args->op.arg1.linear_addr = info->start;
1352 	}
1353 
1354 	MULTI_mmuext_op(mcs.mc, &args->op, 1, NULL, DOMID_SELF);
1355 
1356 	xen_mc_issue(XEN_LAZY_MMU);
1357 }
1358 
xen_read_cr3(void)1359 static unsigned long xen_read_cr3(void)
1360 {
1361 	return this_cpu_read(xen_cr3);
1362 }
1363 
set_current_cr3(void * v)1364 static void set_current_cr3(void *v)
1365 {
1366 	this_cpu_write(xen_current_cr3, (unsigned long)v);
1367 }
1368 
__xen_write_cr3(bool kernel,unsigned long cr3)1369 static void __xen_write_cr3(bool kernel, unsigned long cr3)
1370 {
1371 	struct mmuext_op op;
1372 	unsigned long mfn;
1373 
1374 	trace_xen_mmu_write_cr3(kernel, cr3);
1375 
1376 	if (cr3)
1377 		mfn = pfn_to_mfn(PFN_DOWN(cr3));
1378 	else
1379 		mfn = 0;
1380 
1381 	WARN_ON(mfn == 0 && kernel);
1382 
1383 	op.cmd = kernel ? MMUEXT_NEW_BASEPTR : MMUEXT_NEW_USER_BASEPTR;
1384 	op.arg1.mfn = mfn;
1385 
1386 	xen_extend_mmuext_op(&op);
1387 
1388 	if (kernel) {
1389 		this_cpu_write(xen_cr3, cr3);
1390 
1391 		/* Update xen_current_cr3 once the batch has actually
1392 		   been submitted. */
1393 		xen_mc_callback(set_current_cr3, (void *)cr3);
1394 	}
1395 }
xen_write_cr3(unsigned long cr3)1396 static void xen_write_cr3(unsigned long cr3)
1397 {
1398 	pgd_t *user_pgd = xen_get_user_pgd(__va(cr3));
1399 
1400 	BUG_ON(preemptible());
1401 
1402 	xen_mc_batch();  /* disables interrupts */
1403 
1404 	/* Update while interrupts are disabled, so its atomic with
1405 	   respect to ipis */
1406 	this_cpu_write(xen_cr3, cr3);
1407 
1408 	__xen_write_cr3(true, cr3);
1409 
1410 	if (user_pgd)
1411 		__xen_write_cr3(false, __pa(user_pgd));
1412 	else
1413 		__xen_write_cr3(false, 0);
1414 
1415 	xen_mc_issue(XEN_LAZY_CPU);  /* interrupts restored */
1416 }
1417 
1418 /*
1419  * At the start of the day - when Xen launches a guest, it has already
1420  * built pagetables for the guest. We diligently look over them
1421  * in xen_setup_kernel_pagetable and graft as appropriate them in the
1422  * init_top_pgt and its friends. Then when we are happy we load
1423  * the new init_top_pgt - and continue on.
1424  *
1425  * The generic code starts (start_kernel) and 'init_mem_mapping' sets
1426  * up the rest of the pagetables. When it has completed it loads the cr3.
1427  * N.B. that baremetal would start at 'start_kernel' (and the early
1428  * #PF handler would create bootstrap pagetables) - so we are running
1429  * with the same assumptions as what to do when write_cr3 is executed
1430  * at this point.
1431  *
1432  * Since there are no user-page tables at all, we have two variants
1433  * of xen_write_cr3 - the early bootup (this one), and the late one
1434  * (xen_write_cr3). The reason we have to do that is that in 64-bit
1435  * the Linux kernel and user-space are both in ring 3 while the
1436  * hypervisor is in ring 0.
1437  */
xen_write_cr3_init(unsigned long cr3)1438 static void __init xen_write_cr3_init(unsigned long cr3)
1439 {
1440 	BUG_ON(preemptible());
1441 
1442 	xen_mc_batch();  /* disables interrupts */
1443 
1444 	/* Update while interrupts are disabled, so its atomic with
1445 	   respect to ipis */
1446 	this_cpu_write(xen_cr3, cr3);
1447 
1448 	__xen_write_cr3(true, cr3);
1449 
1450 	xen_mc_issue(XEN_LAZY_CPU);  /* interrupts restored */
1451 }
1452 
xen_pgd_alloc(struct mm_struct * mm)1453 static int xen_pgd_alloc(struct mm_struct *mm)
1454 {
1455 	pgd_t *pgd = mm->pgd;
1456 	struct page *page = virt_to_page(pgd);
1457 	pgd_t *user_pgd;
1458 	int ret = -ENOMEM;
1459 
1460 	BUG_ON(PagePinned(virt_to_page(pgd)));
1461 	BUG_ON(page->private != 0);
1462 
1463 	user_pgd = (pgd_t *)__get_free_page(GFP_KERNEL | __GFP_ZERO);
1464 	page->private = (unsigned long)user_pgd;
1465 
1466 	if (user_pgd != NULL) {
1467 #ifdef CONFIG_X86_VSYSCALL_EMULATION
1468 		user_pgd[pgd_index(VSYSCALL_ADDR)] =
1469 			__pgd(__pa(level3_user_vsyscall) | _PAGE_TABLE);
1470 #endif
1471 		ret = 0;
1472 	}
1473 
1474 	BUG_ON(PagePinned(virt_to_page(xen_get_user_pgd(pgd))));
1475 
1476 	return ret;
1477 }
1478 
xen_pgd_free(struct mm_struct * mm,pgd_t * pgd)1479 static void xen_pgd_free(struct mm_struct *mm, pgd_t *pgd)
1480 {
1481 	pgd_t *user_pgd = xen_get_user_pgd(pgd);
1482 
1483 	if (user_pgd)
1484 		free_page((unsigned long)user_pgd);
1485 }
1486 
1487 /*
1488  * Init-time set_pte while constructing initial pagetables, which
1489  * doesn't allow RO page table pages to be remapped RW.
1490  *
1491  * If there is no MFN for this PFN then this page is initially
1492  * ballooned out so clear the PTE (as in decrease_reservation() in
1493  * drivers/xen/balloon.c).
1494  *
1495  * Many of these PTE updates are done on unpinned and writable pages
1496  * and doing a hypercall for these is unnecessary and expensive.  At
1497  * this point it is rarely possible to tell if a page is pinned, so
1498  * mostly write the PTE directly and rely on Xen trapping and
1499  * emulating any updates as necessary.
1500  */
xen_set_pte_init(pte_t * ptep,pte_t pte)1501 static void __init xen_set_pte_init(pte_t *ptep, pte_t pte)
1502 {
1503 	if (unlikely(is_early_ioremap_ptep(ptep)))
1504 		__xen_set_pte(ptep, pte);
1505 	else
1506 		native_set_pte(ptep, pte);
1507 }
1508 
xen_make_pte_init(pteval_t pte)1509 __visible pte_t xen_make_pte_init(pteval_t pte)
1510 {
1511 	unsigned long pfn;
1512 
1513 	/*
1514 	 * Pages belonging to the initial p2m list mapped outside the default
1515 	 * address range must be mapped read-only. This region contains the
1516 	 * page tables for mapping the p2m list, too, and page tables MUST be
1517 	 * mapped read-only.
1518 	 */
1519 	pfn = (pte & PTE_PFN_MASK) >> PAGE_SHIFT;
1520 	if (xen_start_info->mfn_list < __START_KERNEL_map &&
1521 	    pfn >= xen_start_info->first_p2m_pfn &&
1522 	    pfn < xen_start_info->first_p2m_pfn + xen_start_info->nr_p2m_frames)
1523 		pte &= ~_PAGE_RW;
1524 
1525 	pte = pte_pfn_to_mfn(pte);
1526 	return native_make_pte(pte);
1527 }
1528 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pte_init);
1529 
1530 /* Early in boot, while setting up the initial pagetable, assume
1531    everything is pinned. */
xen_alloc_pte_init(struct mm_struct * mm,unsigned long pfn)1532 static void __init xen_alloc_pte_init(struct mm_struct *mm, unsigned long pfn)
1533 {
1534 #ifdef CONFIG_FLATMEM
1535 	BUG_ON(mem_map);	/* should only be used early */
1536 #endif
1537 	make_lowmem_page_readonly(__va(PFN_PHYS(pfn)));
1538 	pin_pagetable_pfn(MMUEXT_PIN_L1_TABLE, pfn);
1539 }
1540 
1541 /* Used for pmd and pud */
xen_alloc_pmd_init(struct mm_struct * mm,unsigned long pfn)1542 static void __init xen_alloc_pmd_init(struct mm_struct *mm, unsigned long pfn)
1543 {
1544 #ifdef CONFIG_FLATMEM
1545 	BUG_ON(mem_map);	/* should only be used early */
1546 #endif
1547 	make_lowmem_page_readonly(__va(PFN_PHYS(pfn)));
1548 }
1549 
1550 /* Early release_pte assumes that all pts are pinned, since there's
1551    only init_mm and anything attached to that is pinned. */
xen_release_pte_init(unsigned long pfn)1552 static void __init xen_release_pte_init(unsigned long pfn)
1553 {
1554 	pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, pfn);
1555 	make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
1556 }
1557 
xen_release_pmd_init(unsigned long pfn)1558 static void __init xen_release_pmd_init(unsigned long pfn)
1559 {
1560 	make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
1561 }
1562 
__pin_pagetable_pfn(unsigned cmd,unsigned long pfn)1563 static inline void __pin_pagetable_pfn(unsigned cmd, unsigned long pfn)
1564 {
1565 	struct multicall_space mcs;
1566 	struct mmuext_op *op;
1567 
1568 	mcs = __xen_mc_entry(sizeof(*op));
1569 	op = mcs.args;
1570 	op->cmd = cmd;
1571 	op->arg1.mfn = pfn_to_mfn(pfn);
1572 
1573 	MULTI_mmuext_op(mcs.mc, mcs.args, 1, NULL, DOMID_SELF);
1574 }
1575 
__set_pfn_prot(unsigned long pfn,pgprot_t prot)1576 static inline void __set_pfn_prot(unsigned long pfn, pgprot_t prot)
1577 {
1578 	struct multicall_space mcs;
1579 	unsigned long addr = (unsigned long)__va(pfn << PAGE_SHIFT);
1580 
1581 	mcs = __xen_mc_entry(0);
1582 	MULTI_update_va_mapping(mcs.mc, (unsigned long)addr,
1583 				pfn_pte(pfn, prot), 0);
1584 }
1585 
1586 /* This needs to make sure the new pte page is pinned iff its being
1587    attached to a pinned pagetable. */
xen_alloc_ptpage(struct mm_struct * mm,unsigned long pfn,unsigned level)1588 static inline void xen_alloc_ptpage(struct mm_struct *mm, unsigned long pfn,
1589 				    unsigned level)
1590 {
1591 	bool pinned = xen_page_pinned(mm->pgd);
1592 
1593 	trace_xen_mmu_alloc_ptpage(mm, pfn, level, pinned);
1594 
1595 	if (pinned) {
1596 		struct page *page = pfn_to_page(pfn);
1597 
1598 		pinned = false;
1599 		if (static_branch_likely(&xen_struct_pages_ready)) {
1600 			pinned = PagePinned(page);
1601 			SetPagePinned(page);
1602 		}
1603 
1604 		xen_mc_batch();
1605 
1606 		__set_pfn_prot(pfn, PAGE_KERNEL_RO);
1607 
1608 		if (level == PT_PTE && IS_ENABLED(CONFIG_SPLIT_PTE_PTLOCKS) &&
1609 		    !pinned)
1610 			__pin_pagetable_pfn(MMUEXT_PIN_L1_TABLE, pfn);
1611 
1612 		xen_mc_issue(XEN_LAZY_MMU);
1613 	}
1614 }
1615 
xen_alloc_pte(struct mm_struct * mm,unsigned long pfn)1616 static void xen_alloc_pte(struct mm_struct *mm, unsigned long pfn)
1617 {
1618 	xen_alloc_ptpage(mm, pfn, PT_PTE);
1619 }
1620 
xen_alloc_pmd(struct mm_struct * mm,unsigned long pfn)1621 static void xen_alloc_pmd(struct mm_struct *mm, unsigned long pfn)
1622 {
1623 	xen_alloc_ptpage(mm, pfn, PT_PMD);
1624 }
1625 
1626 /* This should never happen until we're OK to use struct page */
xen_release_ptpage(unsigned long pfn,unsigned level)1627 static inline void xen_release_ptpage(unsigned long pfn, unsigned level)
1628 {
1629 	struct page *page = pfn_to_page(pfn);
1630 	bool pinned = PagePinned(page);
1631 
1632 	trace_xen_mmu_release_ptpage(pfn, level, pinned);
1633 
1634 	if (pinned) {
1635 		xen_mc_batch();
1636 
1637 		if (level == PT_PTE && IS_ENABLED(CONFIG_SPLIT_PTE_PTLOCKS))
1638 			__pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, pfn);
1639 
1640 		__set_pfn_prot(pfn, PAGE_KERNEL);
1641 
1642 		xen_mc_issue(XEN_LAZY_MMU);
1643 
1644 		ClearPagePinned(page);
1645 	}
1646 }
1647 
xen_release_pte(unsigned long pfn)1648 static void xen_release_pte(unsigned long pfn)
1649 {
1650 	xen_release_ptpage(pfn, PT_PTE);
1651 }
1652 
xen_release_pmd(unsigned long pfn)1653 static void xen_release_pmd(unsigned long pfn)
1654 {
1655 	xen_release_ptpage(pfn, PT_PMD);
1656 }
1657 
xen_alloc_pud(struct mm_struct * mm,unsigned long pfn)1658 static void xen_alloc_pud(struct mm_struct *mm, unsigned long pfn)
1659 {
1660 	xen_alloc_ptpage(mm, pfn, PT_PUD);
1661 }
1662 
xen_release_pud(unsigned long pfn)1663 static void xen_release_pud(unsigned long pfn)
1664 {
1665 	xen_release_ptpage(pfn, PT_PUD);
1666 }
1667 
1668 /*
1669  * Like __va(), but returns address in the kernel mapping (which is
1670  * all we have until the physical memory mapping has been set up.
1671  */
__ka(phys_addr_t paddr)1672 static void * __init __ka(phys_addr_t paddr)
1673 {
1674 	return (void *)(paddr + __START_KERNEL_map);
1675 }
1676 
1677 /* Convert a machine address to physical address */
m2p(phys_addr_t maddr)1678 static unsigned long __init m2p(phys_addr_t maddr)
1679 {
1680 	phys_addr_t paddr;
1681 
1682 	maddr &= XEN_PTE_MFN_MASK;
1683 	paddr = mfn_to_pfn(maddr >> PAGE_SHIFT) << PAGE_SHIFT;
1684 
1685 	return paddr;
1686 }
1687 
1688 /* Convert a machine address to kernel virtual */
m2v(phys_addr_t maddr)1689 static void * __init m2v(phys_addr_t maddr)
1690 {
1691 	return __ka(m2p(maddr));
1692 }
1693 
1694 /* Set the page permissions on an identity-mapped pages */
set_page_prot_flags(void * addr,pgprot_t prot,unsigned long flags)1695 static void __init set_page_prot_flags(void *addr, pgprot_t prot,
1696 				       unsigned long flags)
1697 {
1698 	unsigned long pfn = __pa(addr) >> PAGE_SHIFT;
1699 	pte_t pte = pfn_pte(pfn, prot);
1700 
1701 	if (HYPERVISOR_update_va_mapping((unsigned long)addr, pte, flags))
1702 		BUG();
1703 }
set_page_prot(void * addr,pgprot_t prot)1704 static void __init set_page_prot(void *addr, pgprot_t prot)
1705 {
1706 	return set_page_prot_flags(addr, prot, UVMF_NONE);
1707 }
1708 
xen_setup_machphys_mapping(void)1709 void __init xen_setup_machphys_mapping(void)
1710 {
1711 	struct xen_machphys_mapping mapping;
1712 
1713 	if (HYPERVISOR_memory_op(XENMEM_machphys_mapping, &mapping) == 0) {
1714 		machine_to_phys_mapping = (unsigned long *)mapping.v_start;
1715 		machine_to_phys_nr = mapping.max_mfn + 1;
1716 	} else {
1717 		machine_to_phys_nr = MACH2PHYS_NR_ENTRIES;
1718 	}
1719 }
1720 
convert_pfn_mfn(void * v)1721 static void __init convert_pfn_mfn(void *v)
1722 {
1723 	pte_t *pte = v;
1724 	int i;
1725 
1726 	/* All levels are converted the same way, so just treat them
1727 	   as ptes. */
1728 	for (i = 0; i < PTRS_PER_PTE; i++)
1729 		pte[i] = xen_make_pte(pte[i].pte);
1730 }
check_pt_base(unsigned long * pt_base,unsigned long * pt_end,unsigned long addr)1731 static void __init check_pt_base(unsigned long *pt_base, unsigned long *pt_end,
1732 				 unsigned long addr)
1733 {
1734 	if (*pt_base == PFN_DOWN(__pa(addr))) {
1735 		set_page_prot_flags((void *)addr, PAGE_KERNEL, UVMF_INVLPG);
1736 		clear_page((void *)addr);
1737 		(*pt_base)++;
1738 	}
1739 	if (*pt_end == PFN_DOWN(__pa(addr))) {
1740 		set_page_prot_flags((void *)addr, PAGE_KERNEL, UVMF_INVLPG);
1741 		clear_page((void *)addr);
1742 		(*pt_end)--;
1743 	}
1744 }
1745 /*
1746  * Set up the initial kernel pagetable.
1747  *
1748  * We can construct this by grafting the Xen provided pagetable into
1749  * head_64.S's preconstructed pagetables.  We copy the Xen L2's into
1750  * level2_ident_pgt, and level2_kernel_pgt.  This means that only the
1751  * kernel has a physical mapping to start with - but that's enough to
1752  * get __va working.  We need to fill in the rest of the physical
1753  * mapping once some sort of allocator has been set up.
1754  */
xen_setup_kernel_pagetable(pgd_t * pgd,unsigned long max_pfn)1755 void __init xen_setup_kernel_pagetable(pgd_t *pgd, unsigned long max_pfn)
1756 {
1757 	pud_t *l3;
1758 	pmd_t *l2;
1759 	unsigned long addr[3];
1760 	unsigned long pt_base, pt_end;
1761 	unsigned i;
1762 
1763 	/* max_pfn_mapped is the last pfn mapped in the initial memory
1764 	 * mappings. Considering that on Xen after the kernel mappings we
1765 	 * have the mappings of some pages that don't exist in pfn space, we
1766 	 * set max_pfn_mapped to the last real pfn mapped. */
1767 	if (xen_start_info->mfn_list < __START_KERNEL_map)
1768 		max_pfn_mapped = xen_start_info->first_p2m_pfn;
1769 	else
1770 		max_pfn_mapped = PFN_DOWN(__pa(xen_start_info->mfn_list));
1771 
1772 	pt_base = PFN_DOWN(__pa(xen_start_info->pt_base));
1773 	pt_end = pt_base + xen_start_info->nr_pt_frames;
1774 
1775 	/* Zap identity mapping */
1776 	init_top_pgt[0] = __pgd(0);
1777 
1778 	/* Pre-constructed entries are in pfn, so convert to mfn */
1779 	/* L4[273] -> level3_ident_pgt  */
1780 	/* L4[511] -> level3_kernel_pgt */
1781 	convert_pfn_mfn(init_top_pgt);
1782 
1783 	/* L3_i[0] -> level2_ident_pgt */
1784 	convert_pfn_mfn(level3_ident_pgt);
1785 	/* L3_k[510] -> level2_kernel_pgt */
1786 	/* L3_k[511] -> level2_fixmap_pgt */
1787 	convert_pfn_mfn(level3_kernel_pgt);
1788 
1789 	/* L3_k[511][508-FIXMAP_PMD_NUM ... 507] -> level1_fixmap_pgt */
1790 	convert_pfn_mfn(level2_fixmap_pgt);
1791 
1792 	/* We get [511][511] and have Xen's version of level2_kernel_pgt */
1793 	l3 = m2v(pgd[pgd_index(__START_KERNEL_map)].pgd);
1794 	l2 = m2v(l3[pud_index(__START_KERNEL_map)].pud);
1795 
1796 	addr[0] = (unsigned long)pgd;
1797 	addr[1] = (unsigned long)l3;
1798 	addr[2] = (unsigned long)l2;
1799 	/* Graft it onto L4[273][0]. Note that we creating an aliasing problem:
1800 	 * Both L4[273][0] and L4[511][510] have entries that point to the same
1801 	 * L2 (PMD) tables. Meaning that if you modify it in __va space
1802 	 * it will be also modified in the __ka space! (But if you just
1803 	 * modify the PMD table to point to other PTE's or none, then you
1804 	 * are OK - which is what cleanup_highmap does) */
1805 	copy_page(level2_ident_pgt, l2);
1806 	/* Graft it onto L4[511][510] */
1807 	copy_page(level2_kernel_pgt, l2);
1808 
1809 	/*
1810 	 * Zap execute permission from the ident map. Due to the sharing of
1811 	 * L1 entries we need to do this in the L2.
1812 	 */
1813 	if (__supported_pte_mask & _PAGE_NX) {
1814 		for (i = 0; i < PTRS_PER_PMD; ++i) {
1815 			if (pmd_none(level2_ident_pgt[i]))
1816 				continue;
1817 			level2_ident_pgt[i] = pmd_set_flags(level2_ident_pgt[i], _PAGE_NX);
1818 		}
1819 	}
1820 
1821 	/* Copy the initial P->M table mappings if necessary. */
1822 	i = pgd_index(xen_start_info->mfn_list);
1823 	if (i && i < pgd_index(__START_KERNEL_map))
1824 		init_top_pgt[i] = ((pgd_t *)xen_start_info->pt_base)[i];
1825 
1826 	/* Make pagetable pieces RO */
1827 	set_page_prot(init_top_pgt, PAGE_KERNEL_RO);
1828 	set_page_prot(level3_ident_pgt, PAGE_KERNEL_RO);
1829 	set_page_prot(level3_kernel_pgt, PAGE_KERNEL_RO);
1830 	set_page_prot(level2_ident_pgt, PAGE_KERNEL_RO);
1831 	set_page_prot(level2_kernel_pgt, PAGE_KERNEL_RO);
1832 	set_page_prot(level2_fixmap_pgt, PAGE_KERNEL_RO);
1833 
1834 	for (i = 0; i < FIXMAP_PMD_NUM; i++) {
1835 		set_page_prot(level1_fixmap_pgt + i * PTRS_PER_PTE,
1836 			      PAGE_KERNEL_RO);
1837 	}
1838 
1839 	/* Pin down new L4 */
1840 	pin_pagetable_pfn(MMUEXT_PIN_L4_TABLE,
1841 			  PFN_DOWN(__pa_symbol(init_top_pgt)));
1842 
1843 	/* Unpin Xen-provided one */
1844 	pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, PFN_DOWN(__pa(pgd)));
1845 
1846 #ifdef CONFIG_X86_VSYSCALL_EMULATION
1847 	/* Pin user vsyscall L3 */
1848 	set_page_prot(level3_user_vsyscall, PAGE_KERNEL_RO);
1849 	pin_pagetable_pfn(MMUEXT_PIN_L3_TABLE,
1850 			  PFN_DOWN(__pa_symbol(level3_user_vsyscall)));
1851 #endif
1852 
1853 	/*
1854 	 * At this stage there can be no user pgd, and no page structure to
1855 	 * attach it to, so make sure we just set kernel pgd.
1856 	 */
1857 	xen_mc_batch();
1858 	__xen_write_cr3(true, __pa(init_top_pgt));
1859 	xen_mc_issue(XEN_LAZY_CPU);
1860 
1861 	/* We can't that easily rip out L3 and L2, as the Xen pagetables are
1862 	 * set out this way: [L4], [L1], [L2], [L3], [L1], [L1] ...  for
1863 	 * the initial domain. For guests using the toolstack, they are in:
1864 	 * [L4], [L3], [L2], [L1], [L1], order .. So for dom0 we can only
1865 	 * rip out the [L4] (pgd), but for guests we shave off three pages.
1866 	 */
1867 	for (i = 0; i < ARRAY_SIZE(addr); i++)
1868 		check_pt_base(&pt_base, &pt_end, addr[i]);
1869 
1870 	/* Our (by three pages) smaller Xen pagetable that we are using */
1871 	xen_pt_base = PFN_PHYS(pt_base);
1872 	xen_pt_size = (pt_end - pt_base) * PAGE_SIZE;
1873 	memblock_reserve(xen_pt_base, xen_pt_size);
1874 
1875 	/* Revector the xen_start_info */
1876 	xen_start_info = (struct start_info *)__va(__pa(xen_start_info));
1877 }
1878 
1879 /*
1880  * Read a value from a physical address.
1881  */
xen_read_phys_ulong(phys_addr_t addr)1882 static unsigned long __init xen_read_phys_ulong(phys_addr_t addr)
1883 {
1884 	unsigned long *vaddr;
1885 	unsigned long val;
1886 
1887 	vaddr = early_memremap_ro(addr, sizeof(val));
1888 	val = *vaddr;
1889 	early_memunmap(vaddr, sizeof(val));
1890 	return val;
1891 }
1892 
1893 /*
1894  * Translate a virtual address to a physical one without relying on mapped
1895  * page tables. Don't rely on big pages being aligned in (guest) physical
1896  * space!
1897  */
xen_early_virt_to_phys(unsigned long vaddr)1898 static phys_addr_t __init xen_early_virt_to_phys(unsigned long vaddr)
1899 {
1900 	phys_addr_t pa;
1901 	pgd_t pgd;
1902 	pud_t pud;
1903 	pmd_t pmd;
1904 	pte_t pte;
1905 
1906 	pa = read_cr3_pa();
1907 	pgd = native_make_pgd(xen_read_phys_ulong(pa + pgd_index(vaddr) *
1908 						       sizeof(pgd)));
1909 	if (!pgd_present(pgd))
1910 		return 0;
1911 
1912 	pa = pgd_val(pgd) & PTE_PFN_MASK;
1913 	pud = native_make_pud(xen_read_phys_ulong(pa + pud_index(vaddr) *
1914 						       sizeof(pud)));
1915 	if (!pud_present(pud))
1916 		return 0;
1917 	pa = pud_val(pud) & PTE_PFN_MASK;
1918 	if (pud_leaf(pud))
1919 		return pa + (vaddr & ~PUD_MASK);
1920 
1921 	pmd = native_make_pmd(xen_read_phys_ulong(pa + pmd_index(vaddr) *
1922 						       sizeof(pmd)));
1923 	if (!pmd_present(pmd))
1924 		return 0;
1925 	pa = pmd_val(pmd) & PTE_PFN_MASK;
1926 	if (pmd_leaf(pmd))
1927 		return pa + (vaddr & ~PMD_MASK);
1928 
1929 	pte = native_make_pte(xen_read_phys_ulong(pa + pte_index(vaddr) *
1930 						       sizeof(pte)));
1931 	if (!pte_present(pte))
1932 		return 0;
1933 	pa = pte_pfn(pte) << PAGE_SHIFT;
1934 
1935 	return pa | (vaddr & ~PAGE_MASK);
1936 }
1937 
1938 /*
1939  * Find a new area for the hypervisor supplied p2m list and relocate the p2m to
1940  * this area.
1941  */
xen_relocate_p2m(void)1942 void __init xen_relocate_p2m(void)
1943 {
1944 	phys_addr_t size, new_area, pt_phys, pmd_phys, pud_phys;
1945 	unsigned long p2m_pfn, p2m_pfn_end, n_frames, pfn, pfn_end;
1946 	int n_pte, n_pt, n_pmd, n_pud, idx_pte, idx_pt, idx_pmd, idx_pud;
1947 	pte_t *pt;
1948 	pmd_t *pmd;
1949 	pud_t *pud;
1950 	pgd_t *pgd;
1951 	unsigned long *new_p2m;
1952 
1953 	size = PAGE_ALIGN(xen_start_info->nr_pages * sizeof(unsigned long));
1954 	n_pte = roundup(size, PAGE_SIZE) >> PAGE_SHIFT;
1955 	n_pt = roundup(size, PMD_SIZE) >> PMD_SHIFT;
1956 	n_pmd = roundup(size, PUD_SIZE) >> PUD_SHIFT;
1957 	n_pud = roundup(size, P4D_SIZE) >> P4D_SHIFT;
1958 	n_frames = n_pte + n_pt + n_pmd + n_pud;
1959 
1960 	new_area = xen_find_free_area(PFN_PHYS(n_frames));
1961 	if (!new_area) {
1962 		xen_raw_console_write("Can't find new memory area for p2m needed due to E820 map conflict\n");
1963 		BUG();
1964 	}
1965 
1966 	/*
1967 	 * Setup the page tables for addressing the new p2m list.
1968 	 * We have asked the hypervisor to map the p2m list at the user address
1969 	 * PUD_SIZE. It may have done so, or it may have used a kernel space
1970 	 * address depending on the Xen version.
1971 	 * To avoid any possible virtual address collision, just use
1972 	 * 2 * PUD_SIZE for the new area.
1973 	 */
1974 	pud_phys = new_area;
1975 	pmd_phys = pud_phys + PFN_PHYS(n_pud);
1976 	pt_phys = pmd_phys + PFN_PHYS(n_pmd);
1977 	p2m_pfn = PFN_DOWN(pt_phys) + n_pt;
1978 
1979 	pgd = __va(read_cr3_pa());
1980 	new_p2m = (unsigned long *)(2 * PGDIR_SIZE);
1981 	for (idx_pud = 0; idx_pud < n_pud; idx_pud++) {
1982 		pud = early_memremap(pud_phys, PAGE_SIZE);
1983 		clear_page(pud);
1984 		for (idx_pmd = 0; idx_pmd < min(n_pmd, PTRS_PER_PUD);
1985 				idx_pmd++) {
1986 			pmd = early_memremap(pmd_phys, PAGE_SIZE);
1987 			clear_page(pmd);
1988 			for (idx_pt = 0; idx_pt < min(n_pt, PTRS_PER_PMD);
1989 					idx_pt++) {
1990 				pt = early_memremap(pt_phys, PAGE_SIZE);
1991 				clear_page(pt);
1992 				for (idx_pte = 0;
1993 				     idx_pte < min(n_pte, PTRS_PER_PTE);
1994 				     idx_pte++) {
1995 					pt[idx_pte] = pfn_pte(p2m_pfn,
1996 							      PAGE_KERNEL);
1997 					p2m_pfn++;
1998 				}
1999 				n_pte -= PTRS_PER_PTE;
2000 				early_memunmap(pt, PAGE_SIZE);
2001 				make_lowmem_page_readonly(__va(pt_phys));
2002 				pin_pagetable_pfn(MMUEXT_PIN_L1_TABLE,
2003 						PFN_DOWN(pt_phys));
2004 				pmd[idx_pt] = __pmd(_PAGE_TABLE | pt_phys);
2005 				pt_phys += PAGE_SIZE;
2006 			}
2007 			n_pt -= PTRS_PER_PMD;
2008 			early_memunmap(pmd, PAGE_SIZE);
2009 			make_lowmem_page_readonly(__va(pmd_phys));
2010 			pin_pagetable_pfn(MMUEXT_PIN_L2_TABLE,
2011 					PFN_DOWN(pmd_phys));
2012 			pud[idx_pmd] = __pud(_PAGE_TABLE | pmd_phys);
2013 			pmd_phys += PAGE_SIZE;
2014 		}
2015 		n_pmd -= PTRS_PER_PUD;
2016 		early_memunmap(pud, PAGE_SIZE);
2017 		make_lowmem_page_readonly(__va(pud_phys));
2018 		pin_pagetable_pfn(MMUEXT_PIN_L3_TABLE, PFN_DOWN(pud_phys));
2019 		set_pgd(pgd + 2 + idx_pud, __pgd(_PAGE_TABLE | pud_phys));
2020 		pud_phys += PAGE_SIZE;
2021 	}
2022 
2023 	/* Now copy the old p2m info to the new area. */
2024 	memcpy(new_p2m, xen_p2m_addr, size);
2025 	xen_p2m_addr = new_p2m;
2026 
2027 	/* Release the old p2m list and set new list info. */
2028 	p2m_pfn = PFN_DOWN(xen_early_virt_to_phys(xen_start_info->mfn_list));
2029 	BUG_ON(!p2m_pfn);
2030 	p2m_pfn_end = p2m_pfn + PFN_DOWN(size);
2031 
2032 	if (xen_start_info->mfn_list < __START_KERNEL_map) {
2033 		pfn = xen_start_info->first_p2m_pfn;
2034 		pfn_end = xen_start_info->first_p2m_pfn +
2035 			  xen_start_info->nr_p2m_frames;
2036 		set_pgd(pgd + 1, __pgd(0));
2037 	} else {
2038 		pfn = p2m_pfn;
2039 		pfn_end = p2m_pfn_end;
2040 	}
2041 
2042 	memblock_phys_free(PFN_PHYS(pfn), PAGE_SIZE * (pfn_end - pfn));
2043 	while (pfn < pfn_end) {
2044 		if (pfn == p2m_pfn) {
2045 			pfn = p2m_pfn_end;
2046 			continue;
2047 		}
2048 		make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
2049 		pfn++;
2050 	}
2051 
2052 	xen_start_info->mfn_list = (unsigned long)xen_p2m_addr;
2053 	xen_start_info->first_p2m_pfn =  PFN_DOWN(new_area);
2054 	xen_start_info->nr_p2m_frames = n_frames;
2055 }
2056 
xen_reserve_special_pages(void)2057 void __init xen_reserve_special_pages(void)
2058 {
2059 	phys_addr_t paddr;
2060 
2061 	memblock_reserve(__pa(xen_start_info), PAGE_SIZE);
2062 	if (xen_start_info->store_mfn) {
2063 		paddr = PFN_PHYS(mfn_to_pfn(xen_start_info->store_mfn));
2064 		memblock_reserve(paddr, PAGE_SIZE);
2065 	}
2066 	if (!xen_initial_domain()) {
2067 		paddr = PFN_PHYS(mfn_to_pfn(xen_start_info->console.domU.mfn));
2068 		memblock_reserve(paddr, PAGE_SIZE);
2069 	}
2070 }
2071 
xen_pt_check_e820(void)2072 void __init xen_pt_check_e820(void)
2073 {
2074 	xen_chk_is_e820_usable(xen_pt_base, xen_pt_size, "page table");
2075 }
2076 
2077 static unsigned char dummy_mapping[PAGE_SIZE] __page_aligned_bss;
2078 
xen_set_fixmap(unsigned idx,phys_addr_t phys,pgprot_t prot)2079 static void xen_set_fixmap(unsigned idx, phys_addr_t phys, pgprot_t prot)
2080 {
2081 	pte_t pte;
2082 	unsigned long vaddr;
2083 
2084 	phys >>= PAGE_SHIFT;
2085 
2086 	switch (idx) {
2087 	case FIX_BTMAP_END ... FIX_BTMAP_BEGIN:
2088 #ifdef CONFIG_X86_VSYSCALL_EMULATION
2089 	case VSYSCALL_PAGE:
2090 #endif
2091 		/* All local page mappings */
2092 		pte = pfn_pte(phys, prot);
2093 		break;
2094 
2095 #ifdef CONFIG_X86_LOCAL_APIC
2096 	case FIX_APIC_BASE:	/* maps dummy local APIC */
2097 		pte = pfn_pte(PFN_DOWN(__pa(dummy_mapping)), PAGE_KERNEL);
2098 		break;
2099 #endif
2100 
2101 #ifdef CONFIG_X86_IO_APIC
2102 	case FIX_IO_APIC_BASE_0 ... FIX_IO_APIC_BASE_END:
2103 		/*
2104 		 * We just don't map the IO APIC - all access is via
2105 		 * hypercalls.  Keep the address in the pte for reference.
2106 		 */
2107 		pte = pfn_pte(PFN_DOWN(__pa(dummy_mapping)), PAGE_KERNEL);
2108 		break;
2109 #endif
2110 
2111 	case FIX_PARAVIRT_BOOTMAP:
2112 		/* This is an MFN, but it isn't an IO mapping from the
2113 		   IO domain */
2114 		pte = mfn_pte(phys, prot);
2115 		break;
2116 
2117 	default:
2118 		/* By default, set_fixmap is used for hardware mappings */
2119 		pte = mfn_pte(phys, prot);
2120 		break;
2121 	}
2122 
2123 	vaddr = __fix_to_virt(idx);
2124 	if (HYPERVISOR_update_va_mapping(vaddr, pte, UVMF_INVLPG))
2125 		BUG();
2126 
2127 #ifdef CONFIG_X86_VSYSCALL_EMULATION
2128 	/* Replicate changes to map the vsyscall page into the user
2129 	   pagetable vsyscall mapping. */
2130 	if (idx == VSYSCALL_PAGE)
2131 		set_pte_vaddr_pud(level3_user_vsyscall, vaddr, pte);
2132 #endif
2133 }
2134 
xen_enter_lazy_mmu(void)2135 static void xen_enter_lazy_mmu(void)
2136 {
2137 	enter_lazy(XEN_LAZY_MMU);
2138 }
2139 
xen_flush_lazy_mmu(void)2140 static void xen_flush_lazy_mmu(void)
2141 {
2142 	preempt_disable();
2143 
2144 	if (xen_get_lazy_mode() == XEN_LAZY_MMU) {
2145 		arch_leave_lazy_mmu_mode();
2146 		arch_enter_lazy_mmu_mode();
2147 	}
2148 
2149 	preempt_enable();
2150 }
2151 
xen_post_allocator_init(void)2152 static void __init xen_post_allocator_init(void)
2153 {
2154 	pv_ops.mmu.set_pte = xen_set_pte;
2155 	pv_ops.mmu.set_pmd = xen_set_pmd;
2156 	pv_ops.mmu.set_pud = xen_set_pud;
2157 	pv_ops.mmu.set_p4d = xen_set_p4d;
2158 
2159 	/* This will work as long as patching hasn't happened yet
2160 	   (which it hasn't) */
2161 	pv_ops.mmu.alloc_pte = xen_alloc_pte;
2162 	pv_ops.mmu.alloc_pmd = xen_alloc_pmd;
2163 	pv_ops.mmu.release_pte = xen_release_pte;
2164 	pv_ops.mmu.release_pmd = xen_release_pmd;
2165 	pv_ops.mmu.alloc_pud = xen_alloc_pud;
2166 	pv_ops.mmu.release_pud = xen_release_pud;
2167 	pv_ops.mmu.make_pte = PV_CALLEE_SAVE(xen_make_pte);
2168 
2169 	pv_ops.mmu.write_cr3 = &xen_write_cr3;
2170 }
2171 
xen_leave_lazy_mmu(void)2172 static void xen_leave_lazy_mmu(void)
2173 {
2174 	preempt_disable();
2175 	xen_mc_flush();
2176 	leave_lazy(XEN_LAZY_MMU);
2177 	preempt_enable();
2178 }
2179 
2180 static const typeof(pv_ops) xen_mmu_ops __initconst = {
2181 	.mmu = {
2182 		.read_cr2 = __PV_IS_CALLEE_SAVE(xen_read_cr2),
2183 		.write_cr2 = xen_write_cr2,
2184 
2185 		.read_cr3 = xen_read_cr3,
2186 		.write_cr3 = xen_write_cr3_init,
2187 
2188 		.flush_tlb_user = xen_flush_tlb,
2189 		.flush_tlb_kernel = xen_flush_tlb,
2190 		.flush_tlb_one_user = xen_flush_tlb_one_user,
2191 		.flush_tlb_multi = xen_flush_tlb_multi,
2192 		.tlb_remove_table = tlb_remove_table,
2193 
2194 		.pgd_alloc = xen_pgd_alloc,
2195 		.pgd_free = xen_pgd_free,
2196 
2197 		.alloc_pte = xen_alloc_pte_init,
2198 		.release_pte = xen_release_pte_init,
2199 		.alloc_pmd = xen_alloc_pmd_init,
2200 		.release_pmd = xen_release_pmd_init,
2201 
2202 		.set_pte = xen_set_pte_init,
2203 		.set_pmd = xen_set_pmd_hyper,
2204 
2205 		.ptep_modify_prot_start = xen_ptep_modify_prot_start,
2206 		.ptep_modify_prot_commit = xen_ptep_modify_prot_commit,
2207 
2208 		.pte_val = PV_CALLEE_SAVE(xen_pte_val),
2209 		.pgd_val = PV_CALLEE_SAVE(xen_pgd_val),
2210 
2211 		.make_pte = PV_CALLEE_SAVE(xen_make_pte_init),
2212 		.make_pgd = PV_CALLEE_SAVE(xen_make_pgd),
2213 
2214 		.set_pud = xen_set_pud_hyper,
2215 
2216 		.make_pmd = PV_CALLEE_SAVE(xen_make_pmd),
2217 		.pmd_val = PV_CALLEE_SAVE(xen_pmd_val),
2218 
2219 		.pud_val = PV_CALLEE_SAVE(xen_pud_val),
2220 		.make_pud = PV_CALLEE_SAVE(xen_make_pud),
2221 		.set_p4d = xen_set_p4d_hyper,
2222 
2223 		.alloc_pud = xen_alloc_pmd_init,
2224 		.release_pud = xen_release_pmd_init,
2225 
2226 #if CONFIG_PGTABLE_LEVELS >= 5
2227 		.p4d_val = PV_CALLEE_SAVE(xen_p4d_val),
2228 		.make_p4d = PV_CALLEE_SAVE(xen_make_p4d),
2229 #endif
2230 
2231 		.enter_mmap = xen_enter_mmap,
2232 		.exit_mmap = xen_exit_mmap,
2233 
2234 		.lazy_mode = {
2235 			.enter = xen_enter_lazy_mmu,
2236 			.leave = xen_leave_lazy_mmu,
2237 			.flush = xen_flush_lazy_mmu,
2238 		},
2239 
2240 		.set_fixmap = xen_set_fixmap,
2241 	},
2242 };
2243 
xen_init_mmu_ops(void)2244 void __init xen_init_mmu_ops(void)
2245 {
2246 	x86_init.paging.pagetable_init = xen_pagetable_init;
2247 	x86_init.hyper.init_after_bootmem = xen_after_bootmem;
2248 
2249 	pv_ops.mmu = xen_mmu_ops.mmu;
2250 
2251 	memset(dummy_mapping, 0xff, PAGE_SIZE);
2252 }
2253 
2254 #define VOID_PTE (mfn_pte(0, __pgprot(0)))
xen_zap_pfn_range(unsigned long vaddr,unsigned int order,unsigned long * in_frames,unsigned long * out_frames)2255 static void xen_zap_pfn_range(unsigned long vaddr, unsigned int order,
2256 				unsigned long *in_frames,
2257 				unsigned long *out_frames)
2258 {
2259 	int i;
2260 	struct multicall_space mcs;
2261 
2262 	xen_mc_batch();
2263 	for (i = 0; i < (1UL<<order); i++, vaddr += PAGE_SIZE) {
2264 		mcs = __xen_mc_entry(0);
2265 
2266 		if (in_frames)
2267 			in_frames[i] = virt_to_mfn((void *)vaddr);
2268 
2269 		MULTI_update_va_mapping(mcs.mc, vaddr, VOID_PTE, 0);
2270 		__set_phys_to_machine(virt_to_pfn((void *)vaddr), INVALID_P2M_ENTRY);
2271 
2272 		if (out_frames)
2273 			out_frames[i] = virt_to_pfn((void *)vaddr);
2274 	}
2275 	xen_mc_issue(0);
2276 }
2277 
2278 /*
2279  * Update the pfn-to-mfn mappings for a virtual address range, either to
2280  * point to an array of mfns, or contiguously from a single starting
2281  * mfn.
2282  */
xen_remap_exchanged_ptes(unsigned long vaddr,int order,unsigned long * mfns,unsigned long first_mfn)2283 static void xen_remap_exchanged_ptes(unsigned long vaddr, int order,
2284 				     unsigned long *mfns,
2285 				     unsigned long first_mfn)
2286 {
2287 	unsigned i, limit;
2288 	unsigned long mfn;
2289 
2290 	xen_mc_batch();
2291 
2292 	limit = 1u << order;
2293 	for (i = 0; i < limit; i++, vaddr += PAGE_SIZE) {
2294 		struct multicall_space mcs;
2295 		unsigned flags;
2296 
2297 		mcs = __xen_mc_entry(0);
2298 		if (mfns)
2299 			mfn = mfns[i];
2300 		else
2301 			mfn = first_mfn + i;
2302 
2303 		if (i < (limit - 1))
2304 			flags = 0;
2305 		else {
2306 			if (order == 0)
2307 				flags = UVMF_INVLPG | UVMF_ALL;
2308 			else
2309 				flags = UVMF_TLB_FLUSH | UVMF_ALL;
2310 		}
2311 
2312 		MULTI_update_va_mapping(mcs.mc, vaddr,
2313 				mfn_pte(mfn, PAGE_KERNEL), flags);
2314 
2315 		set_phys_to_machine(virt_to_pfn((void *)vaddr), mfn);
2316 	}
2317 
2318 	xen_mc_issue(0);
2319 }
2320 
2321 /*
2322  * Perform the hypercall to exchange a region of our pfns to point to
2323  * memory with the required contiguous alignment.  Takes the pfns as
2324  * input, and populates mfns as output.
2325  *
2326  * Returns a success code indicating whether the hypervisor was able to
2327  * satisfy the request or not.
2328  */
xen_exchange_memory(unsigned long extents_in,unsigned int order_in,unsigned long * pfns_in,unsigned long extents_out,unsigned int order_out,unsigned long * mfns_out,unsigned int address_bits)2329 static int xen_exchange_memory(unsigned long extents_in, unsigned int order_in,
2330 			       unsigned long *pfns_in,
2331 			       unsigned long extents_out,
2332 			       unsigned int order_out,
2333 			       unsigned long *mfns_out,
2334 			       unsigned int address_bits)
2335 {
2336 	long rc;
2337 	int success;
2338 
2339 	struct xen_memory_exchange exchange = {
2340 		.in = {
2341 			.nr_extents   = extents_in,
2342 			.extent_order = order_in,
2343 			.extent_start = pfns_in,
2344 			.domid        = DOMID_SELF
2345 		},
2346 		.out = {
2347 			.nr_extents   = extents_out,
2348 			.extent_order = order_out,
2349 			.extent_start = mfns_out,
2350 			.address_bits = address_bits,
2351 			.domid        = DOMID_SELF
2352 		}
2353 	};
2354 
2355 	BUG_ON(extents_in << order_in != extents_out << order_out);
2356 
2357 	rc = HYPERVISOR_memory_op(XENMEM_exchange, &exchange);
2358 	success = (exchange.nr_exchanged == extents_in);
2359 
2360 	BUG_ON(!success && ((exchange.nr_exchanged != 0) || (rc == 0)));
2361 	BUG_ON(success && (rc != 0));
2362 
2363 	return success;
2364 }
2365 
xen_create_contiguous_region(phys_addr_t pstart,unsigned int order,unsigned int address_bits,dma_addr_t * dma_handle)2366 int xen_create_contiguous_region(phys_addr_t pstart, unsigned int order,
2367 				 unsigned int address_bits,
2368 				 dma_addr_t *dma_handle)
2369 {
2370 	unsigned long *in_frames, out_frame;
2371 	unsigned long  flags;
2372 	int            success;
2373 	unsigned long vstart = (unsigned long)phys_to_virt(pstart);
2374 
2375 	if (unlikely(order > discontig_frames_order)) {
2376 		if (!discontig_frames_dyn)
2377 			return -ENOMEM;
2378 
2379 		if (alloc_discontig_frames(order))
2380 			return -ENOMEM;
2381 	}
2382 
2383 	memset((void *) vstart, 0, PAGE_SIZE << order);
2384 
2385 	spin_lock_irqsave(&xen_reservation_lock, flags);
2386 
2387 	in_frames = discontig_frames;
2388 
2389 	/* 1. Zap current PTEs, remembering MFNs. */
2390 	xen_zap_pfn_range(vstart, order, in_frames, NULL);
2391 
2392 	/* 2. Get a new contiguous memory extent. */
2393 	out_frame = virt_to_pfn((void *)vstart);
2394 	success = xen_exchange_memory(1UL << order, 0, in_frames,
2395 				      1, order, &out_frame,
2396 				      address_bits);
2397 
2398 	/* 3. Map the new extent in place of old pages. */
2399 	if (success)
2400 		xen_remap_exchanged_ptes(vstart, order, NULL, out_frame);
2401 	else
2402 		xen_remap_exchanged_ptes(vstart, order, in_frames, 0);
2403 
2404 	spin_unlock_irqrestore(&xen_reservation_lock, flags);
2405 
2406 	*dma_handle = virt_to_machine(vstart).maddr;
2407 	return success ? 0 : -ENOMEM;
2408 }
2409 
xen_destroy_contiguous_region(phys_addr_t pstart,unsigned int order)2410 void xen_destroy_contiguous_region(phys_addr_t pstart, unsigned int order)
2411 {
2412 	unsigned long *out_frames, in_frame;
2413 	unsigned long  flags;
2414 	int success;
2415 	unsigned long vstart;
2416 
2417 	if (unlikely(order > discontig_frames_order))
2418 		return;
2419 
2420 	vstart = (unsigned long)phys_to_virt(pstart);
2421 	memset((void *) vstart, 0, PAGE_SIZE << order);
2422 
2423 	spin_lock_irqsave(&xen_reservation_lock, flags);
2424 
2425 	out_frames = discontig_frames;
2426 
2427 	/* 1. Find start MFN of contiguous extent. */
2428 	in_frame = virt_to_mfn((void *)vstart);
2429 
2430 	/* 2. Zap current PTEs. */
2431 	xen_zap_pfn_range(vstart, order, NULL, out_frames);
2432 
2433 	/* 3. Do the exchange for non-contiguous MFNs. */
2434 	success = xen_exchange_memory(1, order, &in_frame, 1UL << order,
2435 					0, out_frames, 0);
2436 
2437 	/* 4. Map new pages in place of old pages. */
2438 	if (success)
2439 		xen_remap_exchanged_ptes(vstart, order, out_frames, 0);
2440 	else
2441 		xen_remap_exchanged_ptes(vstart, order, NULL, in_frame);
2442 
2443 	spin_unlock_irqrestore(&xen_reservation_lock, flags);
2444 }
2445 
xen_flush_tlb_all(void)2446 static noinline void xen_flush_tlb_all(void)
2447 {
2448 	struct mmuext_op *op;
2449 	struct multicall_space mcs;
2450 
2451 	preempt_disable();
2452 
2453 	mcs = xen_mc_entry(sizeof(*op));
2454 
2455 	op = mcs.args;
2456 	op->cmd = MMUEXT_TLB_FLUSH_ALL;
2457 	MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
2458 
2459 	xen_mc_issue(XEN_LAZY_MMU);
2460 
2461 	preempt_enable();
2462 }
2463 
2464 #define REMAP_BATCH_SIZE 16
2465 
2466 struct remap_data {
2467 	xen_pfn_t *pfn;
2468 	bool contiguous;
2469 	bool no_translate;
2470 	pgprot_t prot;
2471 	struct mmu_update *mmu_update;
2472 };
2473 
remap_area_pfn_pte_fn(pte_t * ptep,unsigned long addr,void * data)2474 static int remap_area_pfn_pte_fn(pte_t *ptep, unsigned long addr, void *data)
2475 {
2476 	struct remap_data *rmd = data;
2477 	pte_t pte = pte_mkspecial(mfn_pte(*rmd->pfn, rmd->prot));
2478 
2479 	/*
2480 	 * If we have a contiguous range, just update the pfn itself,
2481 	 * else update pointer to be "next pfn".
2482 	 */
2483 	if (rmd->contiguous)
2484 		(*rmd->pfn)++;
2485 	else
2486 		rmd->pfn++;
2487 
2488 	rmd->mmu_update->ptr = virt_to_machine(ptep).maddr;
2489 	rmd->mmu_update->ptr |= rmd->no_translate ?
2490 		MMU_PT_UPDATE_NO_TRANSLATE :
2491 		MMU_NORMAL_PT_UPDATE;
2492 	rmd->mmu_update->val = pte_val_ma(pte);
2493 	rmd->mmu_update++;
2494 
2495 	return 0;
2496 }
2497 
xen_remap_pfn(struct vm_area_struct * vma,unsigned long addr,xen_pfn_t * pfn,int nr,int * err_ptr,pgprot_t prot,unsigned int domid,bool no_translate)2498 int xen_remap_pfn(struct vm_area_struct *vma, unsigned long addr,
2499 		  xen_pfn_t *pfn, int nr, int *err_ptr, pgprot_t prot,
2500 		  unsigned int domid, bool no_translate)
2501 {
2502 	int err = 0;
2503 	struct remap_data rmd;
2504 	struct mmu_update mmu_update[REMAP_BATCH_SIZE];
2505 	unsigned long range;
2506 	int mapped = 0;
2507 
2508 	BUG_ON(!((vma->vm_flags & (VM_PFNMAP | VM_IO)) == (VM_PFNMAP | VM_IO)));
2509 
2510 	rmd.pfn = pfn;
2511 	rmd.prot = prot;
2512 	/*
2513 	 * We use the err_ptr to indicate if there we are doing a contiguous
2514 	 * mapping or a discontiguous mapping.
2515 	 */
2516 	rmd.contiguous = !err_ptr;
2517 	rmd.no_translate = no_translate;
2518 
2519 	while (nr) {
2520 		int index = 0;
2521 		int done = 0;
2522 		int batch = min(REMAP_BATCH_SIZE, nr);
2523 		int batch_left = batch;
2524 
2525 		range = (unsigned long)batch << PAGE_SHIFT;
2526 
2527 		rmd.mmu_update = mmu_update;
2528 		err = apply_to_page_range(vma->vm_mm, addr, range,
2529 					  remap_area_pfn_pte_fn, &rmd);
2530 		if (err)
2531 			goto out;
2532 
2533 		/*
2534 		 * We record the error for each page that gives an error, but
2535 		 * continue mapping until the whole set is done
2536 		 */
2537 		do {
2538 			int i;
2539 
2540 			err = HYPERVISOR_mmu_update(&mmu_update[index],
2541 						    batch_left, &done, domid);
2542 
2543 			/*
2544 			 * @err_ptr may be the same buffer as @gfn, so
2545 			 * only clear it after each chunk of @gfn is
2546 			 * used.
2547 			 */
2548 			if (err_ptr) {
2549 				for (i = index; i < index + done; i++)
2550 					err_ptr[i] = 0;
2551 			}
2552 			if (err < 0) {
2553 				if (!err_ptr)
2554 					goto out;
2555 				err_ptr[i] = err;
2556 				done++; /* Skip failed frame. */
2557 			} else
2558 				mapped += done;
2559 			batch_left -= done;
2560 			index += done;
2561 		} while (batch_left);
2562 
2563 		nr -= batch;
2564 		addr += range;
2565 		if (err_ptr)
2566 			err_ptr += batch;
2567 		cond_resched();
2568 	}
2569 out:
2570 
2571 	xen_flush_tlb_all();
2572 
2573 	return err < 0 ? err : mapped;
2574 }
2575 EXPORT_SYMBOL_GPL(xen_remap_pfn);
2576 
2577 #ifdef CONFIG_VMCORE_INFO
paddr_vmcoreinfo_note(void)2578 phys_addr_t paddr_vmcoreinfo_note(void)
2579 {
2580 	if (xen_pv_domain())
2581 		return virt_to_machine(vmcoreinfo_note).maddr;
2582 	else
2583 		return __pa(vmcoreinfo_note);
2584 }
2585 #endif /* CONFIG_KEXEC_CORE */
2586