xref: /linux/arch/x86/xen/p2m.c (revision 9c5968db9e625019a0ee5226c7eebef5519d366a)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Xen leaves the responsibility for maintaining p2m mappings to the
5  * guests themselves, but it must also access and update the p2m array
6  * during suspend/resume when all the pages are reallocated.
7  *
8  * The logical flat p2m table is mapped to a linear kernel memory area.
9  * For accesses by Xen a three-level tree linked via mfns only is set up to
10  * allow the address space to be sparse.
11  *
12  *               Xen
13  *                |
14  *          p2m_top_mfn
15  *              /   \
16  * p2m_mid_mfn p2m_mid_mfn
17  *         /           /
18  *  p2m p2m p2m ...
19  *
20  * The p2m_mid_mfn pages are mapped by p2m_top_mfn_p.
21  *
22  * The p2m_top_mfn level is limited to 1 page, so the maximum representable
23  * pseudo-physical address space is:
24  *  P2M_TOP_PER_PAGE * P2M_MID_PER_PAGE * P2M_PER_PAGE pages
25  *
26  * P2M_PER_PAGE depends on the architecture, as a mfn is always
27  * unsigned long (8 bytes on 64-bit, 4 bytes on 32), leading to
28  * 512 and 1024 entries respectively.
29  *
30  * In short, these structures contain the Machine Frame Number (MFN) of the PFN.
31  *
32  * However not all entries are filled with MFNs. Specifically for all other
33  * leaf entries, or for the top  root, or middle one, for which there is a void
34  * entry, we assume it is  "missing". So (for example)
35  *  pfn_to_mfn(0x90909090)=INVALID_P2M_ENTRY.
36  * We have a dedicated page p2m_missing with all entries being
37  * INVALID_P2M_ENTRY. This page may be referenced multiple times in the p2m
38  * list/tree in case there are multiple areas with P2M_PER_PAGE invalid pfns.
39  *
40  * We also have the possibility of setting 1-1 mappings on certain regions, so
41  * that:
42  *  pfn_to_mfn(0xc0000)=0xc0000
43  *
44  * The benefit of this is, that we can assume for non-RAM regions (think
45  * PCI BARs, or ACPI spaces), we can create mappings easily because we
46  * get the PFN value to match the MFN.
47  *
48  * For this to work efficiently we have one new page p2m_identity. All entries
49  * in p2m_identity are set to INVALID_P2M_ENTRY type (Xen toolstack only
50  * recognizes that and MFNs, no other fancy value).
51  *
52  * On lookup we spot that the entry points to p2m_identity and return the
53  * identity value instead of dereferencing and returning INVALID_P2M_ENTRY.
54  * If the entry points to an allocated page, we just proceed as before and
55  * return the PFN. If the PFN has IDENTITY_FRAME_BIT set we unmask that in
56  * appropriate functions (pfn_to_mfn).
57  *
58  * The reason for having the IDENTITY_FRAME_BIT instead of just returning the
59  * PFN is that we could find ourselves where pfn_to_mfn(pfn)==pfn for a
60  * non-identity pfn. To protect ourselves against we elect to set (and get) the
61  * IDENTITY_FRAME_BIT on all identity mapped PFNs.
62  */
63 
64 #include <linux/init.h>
65 #include <linux/export.h>
66 #include <linux/list.h>
67 #include <linux/hash.h>
68 #include <linux/sched.h>
69 #include <linux/seq_file.h>
70 #include <linux/memblock.h>
71 #include <linux/slab.h>
72 #include <linux/vmalloc.h>
73 #include <linux/acpi.h>
74 
75 #include <asm/cache.h>
76 #include <asm/setup.h>
77 #include <linux/uaccess.h>
78 
79 #include <asm/xen/page.h>
80 #include <asm/xen/hypercall.h>
81 #include <asm/xen/hypervisor.h>
82 #include <xen/balloon.h>
83 #include <xen/grant_table.h>
84 #include <xen/hvc-console.h>
85 
86 #include "xen-ops.h"
87 
88 #define P2M_MID_PER_PAGE	(PAGE_SIZE / sizeof(unsigned long *))
89 #define P2M_TOP_PER_PAGE	(PAGE_SIZE / sizeof(unsigned long **))
90 
91 #define MAX_P2M_PFN	(P2M_TOP_PER_PAGE * P2M_MID_PER_PAGE * P2M_PER_PAGE)
92 
93 #define PMDS_PER_MID_PAGE	(P2M_MID_PER_PAGE / PTRS_PER_PTE)
94 
95 unsigned long *xen_p2m_addr __read_mostly;
96 EXPORT_SYMBOL_GPL(xen_p2m_addr);
97 unsigned long xen_p2m_size __read_mostly;
98 EXPORT_SYMBOL_GPL(xen_p2m_size);
99 unsigned long xen_max_p2m_pfn __read_mostly;
100 EXPORT_SYMBOL_GPL(xen_max_p2m_pfn);
101 
102 #ifdef CONFIG_XEN_MEMORY_HOTPLUG_LIMIT
103 #define P2M_LIMIT CONFIG_XEN_MEMORY_HOTPLUG_LIMIT
104 #else
105 #define P2M_LIMIT 0
106 #endif
107 
108 static DEFINE_SPINLOCK(p2m_update_lock);
109 
110 static unsigned long *p2m_mid_missing_mfn;
111 static unsigned long *p2m_top_mfn;
112 static unsigned long **p2m_top_mfn_p;
113 static unsigned long *p2m_missing;
114 static unsigned long *p2m_identity;
115 static pte_t *p2m_missing_pte;
116 static pte_t *p2m_identity_pte;
117 
118 /*
119  * Hint at last populated PFN.
120  *
121  * Used to set HYPERVISOR_shared_info->arch.max_pfn so the toolstack
122  * can avoid scanning the whole P2M (which may be sized to account for
123  * hotplugged memory).
124  */
125 static unsigned long xen_p2m_last_pfn;
126 
127 static inline unsigned p2m_top_index(unsigned long pfn)
128 {
129 	BUG_ON(pfn >= MAX_P2M_PFN);
130 	return pfn / (P2M_MID_PER_PAGE * P2M_PER_PAGE);
131 }
132 
133 static inline unsigned p2m_mid_index(unsigned long pfn)
134 {
135 	return (pfn / P2M_PER_PAGE) % P2M_MID_PER_PAGE;
136 }
137 
138 static void p2m_top_mfn_init(unsigned long *top)
139 {
140 	unsigned i;
141 
142 	for (i = 0; i < P2M_TOP_PER_PAGE; i++)
143 		top[i] = virt_to_mfn(p2m_mid_missing_mfn);
144 }
145 
146 static void p2m_top_mfn_p_init(unsigned long **top)
147 {
148 	unsigned i;
149 
150 	for (i = 0; i < P2M_TOP_PER_PAGE; i++)
151 		top[i] = p2m_mid_missing_mfn;
152 }
153 
154 static void p2m_mid_mfn_init(unsigned long *mid, unsigned long *leaf)
155 {
156 	unsigned i;
157 
158 	for (i = 0; i < P2M_MID_PER_PAGE; i++)
159 		mid[i] = virt_to_mfn(leaf);
160 }
161 
162 static void p2m_init(unsigned long *p2m)
163 {
164 	unsigned i;
165 
166 	for (i = 0; i < P2M_PER_PAGE; i++)
167 		p2m[i] = INVALID_P2M_ENTRY;
168 }
169 
170 static void p2m_init_identity(unsigned long *p2m, unsigned long pfn)
171 {
172 	unsigned i;
173 
174 	for (i = 0; i < P2M_PER_PAGE; i++)
175 		p2m[i] = IDENTITY_FRAME(pfn + i);
176 }
177 
178 static void * __ref alloc_p2m_page(void)
179 {
180 	if (unlikely(!slab_is_available())) {
181 		return memblock_alloc_or_panic(PAGE_SIZE, PAGE_SIZE);
182 	}
183 
184 	return (void *)__get_free_page(GFP_KERNEL);
185 }
186 
187 static void __ref free_p2m_page(void *p)
188 {
189 	if (unlikely(!slab_is_available())) {
190 		memblock_free(p, PAGE_SIZE);
191 		return;
192 	}
193 
194 	free_page((unsigned long)p);
195 }
196 
197 /*
198  * Build the parallel p2m_top_mfn and p2m_mid_mfn structures
199  *
200  * This is called both at boot time, and after resuming from suspend:
201  * - At boot time we're called rather early, and must use alloc_bootmem*()
202  *   to allocate memory.
203  *
204  * - After resume we're called from within stop_machine, but the mfn
205  *   tree should already be completely allocated.
206  */
207 void __ref xen_build_mfn_list_list(void)
208 {
209 	unsigned long pfn, mfn;
210 	pte_t *ptep;
211 	unsigned int level, topidx, mididx;
212 	unsigned long *mid_mfn_p;
213 
214 	if (xen_start_info->flags & SIF_VIRT_P2M_4TOOLS)
215 		return;
216 
217 	/* Pre-initialize p2m_top_mfn to be completely missing */
218 	if (p2m_top_mfn == NULL) {
219 		p2m_mid_missing_mfn = alloc_p2m_page();
220 		p2m_mid_mfn_init(p2m_mid_missing_mfn, p2m_missing);
221 
222 		p2m_top_mfn_p = alloc_p2m_page();
223 		p2m_top_mfn_p_init(p2m_top_mfn_p);
224 
225 		p2m_top_mfn = alloc_p2m_page();
226 		p2m_top_mfn_init(p2m_top_mfn);
227 	} else {
228 		/* Reinitialise, mfn's all change after migration */
229 		p2m_mid_mfn_init(p2m_mid_missing_mfn, p2m_missing);
230 	}
231 
232 	for (pfn = 0; pfn < xen_max_p2m_pfn && pfn < MAX_P2M_PFN;
233 	     pfn += P2M_PER_PAGE) {
234 		topidx = p2m_top_index(pfn);
235 		mididx = p2m_mid_index(pfn);
236 
237 		mid_mfn_p = p2m_top_mfn_p[topidx];
238 		ptep = lookup_address((unsigned long)(xen_p2m_addr + pfn),
239 				      &level);
240 		BUG_ON(!ptep || level != PG_LEVEL_4K);
241 		mfn = pte_mfn(*ptep);
242 		ptep = (pte_t *)((unsigned long)ptep & ~(PAGE_SIZE - 1));
243 
244 		/* Don't bother allocating any mfn mid levels if
245 		 * they're just missing, just update the stored mfn,
246 		 * since all could have changed over a migrate.
247 		 */
248 		if (ptep == p2m_missing_pte || ptep == p2m_identity_pte) {
249 			BUG_ON(mididx);
250 			BUG_ON(mid_mfn_p != p2m_mid_missing_mfn);
251 			p2m_top_mfn[topidx] = virt_to_mfn(p2m_mid_missing_mfn);
252 			pfn += (P2M_MID_PER_PAGE - 1) * P2M_PER_PAGE;
253 			continue;
254 		}
255 
256 		if (mid_mfn_p == p2m_mid_missing_mfn) {
257 			mid_mfn_p = alloc_p2m_page();
258 			p2m_mid_mfn_init(mid_mfn_p, p2m_missing);
259 
260 			p2m_top_mfn_p[topidx] = mid_mfn_p;
261 		}
262 
263 		p2m_top_mfn[topidx] = virt_to_mfn(mid_mfn_p);
264 		mid_mfn_p[mididx] = mfn;
265 	}
266 }
267 
268 void xen_setup_mfn_list_list(void)
269 {
270 	BUG_ON(HYPERVISOR_shared_info == &xen_dummy_shared_info);
271 
272 	if (xen_start_info->flags & SIF_VIRT_P2M_4TOOLS)
273 		HYPERVISOR_shared_info->arch.pfn_to_mfn_frame_list_list = ~0UL;
274 	else
275 		HYPERVISOR_shared_info->arch.pfn_to_mfn_frame_list_list =
276 			virt_to_mfn(p2m_top_mfn);
277 	HYPERVISOR_shared_info->arch.max_pfn = xen_p2m_last_pfn;
278 	HYPERVISOR_shared_info->arch.p2m_generation = 0;
279 	HYPERVISOR_shared_info->arch.p2m_vaddr = (unsigned long)xen_p2m_addr;
280 	HYPERVISOR_shared_info->arch.p2m_cr3 =
281 		xen_pfn_to_cr3(virt_to_mfn(swapper_pg_dir));
282 }
283 
284 /* Set up p2m_top to point to the domain-builder provided p2m pages */
285 void __init xen_build_dynamic_phys_to_machine(void)
286 {
287 	unsigned long pfn;
288 
289 	xen_p2m_addr = (unsigned long *)xen_start_info->mfn_list;
290 	xen_p2m_size = ALIGN(xen_start_info->nr_pages, P2M_PER_PAGE);
291 
292 	for (pfn = xen_start_info->nr_pages; pfn < xen_p2m_size; pfn++)
293 		xen_p2m_addr[pfn] = INVALID_P2M_ENTRY;
294 
295 	xen_max_p2m_pfn = xen_p2m_size;
296 }
297 
298 #define P2M_TYPE_IDENTITY	0
299 #define P2M_TYPE_MISSING	1
300 #define P2M_TYPE_PFN		2
301 #define P2M_TYPE_UNKNOWN	3
302 
303 static int xen_p2m_elem_type(unsigned long pfn)
304 {
305 	unsigned long mfn;
306 
307 	if (pfn >= xen_p2m_size)
308 		return P2M_TYPE_IDENTITY;
309 
310 	mfn = xen_p2m_addr[pfn];
311 
312 	if (mfn == INVALID_P2M_ENTRY)
313 		return P2M_TYPE_MISSING;
314 
315 	if (mfn & IDENTITY_FRAME_BIT)
316 		return P2M_TYPE_IDENTITY;
317 
318 	return P2M_TYPE_PFN;
319 }
320 
321 static void __init xen_rebuild_p2m_list(unsigned long *p2m)
322 {
323 	unsigned int i, chunk;
324 	unsigned long pfn;
325 	unsigned long *mfns;
326 	pte_t *ptep;
327 	pmd_t *pmdp;
328 	int type;
329 
330 	p2m_missing = alloc_p2m_page();
331 	p2m_init(p2m_missing);
332 	p2m_identity = alloc_p2m_page();
333 	p2m_init(p2m_identity);
334 
335 	p2m_missing_pte = alloc_p2m_page();
336 	paravirt_alloc_pte(&init_mm, __pa(p2m_missing_pte) >> PAGE_SHIFT);
337 	p2m_identity_pte = alloc_p2m_page();
338 	paravirt_alloc_pte(&init_mm, __pa(p2m_identity_pte) >> PAGE_SHIFT);
339 	for (i = 0; i < PTRS_PER_PTE; i++) {
340 		set_pte(p2m_missing_pte + i,
341 			pfn_pte(PFN_DOWN(__pa(p2m_missing)), PAGE_KERNEL_RO));
342 		set_pte(p2m_identity_pte + i,
343 			pfn_pte(PFN_DOWN(__pa(p2m_identity)), PAGE_KERNEL_RO));
344 	}
345 
346 	for (pfn = 0; pfn < xen_max_p2m_pfn; pfn += chunk) {
347 		/*
348 		 * Try to map missing/identity PMDs or p2m-pages if possible.
349 		 * We have to respect the structure of the mfn_list_list
350 		 * which will be built just afterwards.
351 		 * Chunk size to test is one p2m page if we are in the middle
352 		 * of a mfn_list_list mid page and the complete mid page area
353 		 * if we are at index 0 of the mid page. Please note that a
354 		 * mid page might cover more than one PMD, e.g. on 32 bit PAE
355 		 * kernels.
356 		 */
357 		chunk = (pfn & (P2M_PER_PAGE * P2M_MID_PER_PAGE - 1)) ?
358 			P2M_PER_PAGE : P2M_PER_PAGE * P2M_MID_PER_PAGE;
359 
360 		type = xen_p2m_elem_type(pfn);
361 		i = 0;
362 		if (type != P2M_TYPE_PFN)
363 			for (i = 1; i < chunk; i++)
364 				if (xen_p2m_elem_type(pfn + i) != type)
365 					break;
366 		if (i < chunk)
367 			/* Reset to minimal chunk size. */
368 			chunk = P2M_PER_PAGE;
369 
370 		if (type == P2M_TYPE_PFN || i < chunk) {
371 			/* Use initial p2m page contents. */
372 			mfns = alloc_p2m_page();
373 			copy_page(mfns, xen_p2m_addr + pfn);
374 			ptep = populate_extra_pte((unsigned long)(p2m + pfn));
375 			set_pte(ptep,
376 				pfn_pte(PFN_DOWN(__pa(mfns)), PAGE_KERNEL));
377 			continue;
378 		}
379 
380 		if (chunk == P2M_PER_PAGE) {
381 			/* Map complete missing or identity p2m-page. */
382 			mfns = (type == P2M_TYPE_MISSING) ?
383 				p2m_missing : p2m_identity;
384 			ptep = populate_extra_pte((unsigned long)(p2m + pfn));
385 			set_pte(ptep,
386 				pfn_pte(PFN_DOWN(__pa(mfns)), PAGE_KERNEL_RO));
387 			continue;
388 		}
389 
390 		/* Complete missing or identity PMD(s) can be mapped. */
391 		ptep = (type == P2M_TYPE_MISSING) ?
392 			p2m_missing_pte : p2m_identity_pte;
393 		for (i = 0; i < PMDS_PER_MID_PAGE; i++) {
394 			pmdp = populate_extra_pmd(
395 				(unsigned long)(p2m + pfn) + i * PMD_SIZE);
396 			set_pmd(pmdp, __pmd(__pa(ptep) | _KERNPG_TABLE));
397 		}
398 	}
399 }
400 
401 void __init xen_vmalloc_p2m_tree(void)
402 {
403 	static struct vm_struct vm;
404 	unsigned long p2m_limit;
405 
406 	xen_p2m_last_pfn = xen_max_p2m_pfn;
407 
408 	p2m_limit = (phys_addr_t)P2M_LIMIT * 1024 * 1024 * 1024 / PAGE_SIZE;
409 	vm.flags = VM_ALLOC;
410 	vm.size = ALIGN(sizeof(unsigned long) * max(xen_max_p2m_pfn, p2m_limit),
411 			PMD_SIZE * PMDS_PER_MID_PAGE);
412 	vm_area_register_early(&vm, PMD_SIZE * PMDS_PER_MID_PAGE);
413 	pr_notice("p2m virtual area at %p, size is %lx\n", vm.addr, vm.size);
414 
415 	xen_max_p2m_pfn = vm.size / sizeof(unsigned long);
416 
417 	xen_rebuild_p2m_list(vm.addr);
418 
419 	xen_p2m_addr = vm.addr;
420 	xen_p2m_size = xen_max_p2m_pfn;
421 
422 	xen_inv_extra_mem();
423 }
424 
425 unsigned long get_phys_to_machine(unsigned long pfn)
426 {
427 	pte_t *ptep;
428 	unsigned int level;
429 
430 	if (unlikely(pfn >= xen_p2m_size)) {
431 		if (pfn < xen_max_p2m_pfn)
432 			return xen_chk_extra_mem(pfn);
433 
434 		return IDENTITY_FRAME(pfn);
435 	}
436 
437 	ptep = lookup_address((unsigned long)(xen_p2m_addr + pfn), &level);
438 	BUG_ON(!ptep || level != PG_LEVEL_4K);
439 
440 	/*
441 	 * The INVALID_P2M_ENTRY is filled in both p2m_*identity
442 	 * and in p2m_*missing, so returning the INVALID_P2M_ENTRY
443 	 * would be wrong.
444 	 */
445 	if (pte_pfn(*ptep) == PFN_DOWN(__pa(p2m_identity)))
446 		return IDENTITY_FRAME(pfn);
447 
448 	return xen_p2m_addr[pfn];
449 }
450 EXPORT_SYMBOL_GPL(get_phys_to_machine);
451 
452 /*
453  * Allocate new pmd(s). It is checked whether the old pmd is still in place.
454  * If not, nothing is changed. This is okay as the only reason for allocating
455  * a new pmd is to replace p2m_missing_pte or p2m_identity_pte by a individual
456  * pmd.
457  */
458 static pte_t *alloc_p2m_pmd(unsigned long addr, pte_t *pte_pg)
459 {
460 	pte_t *ptechk;
461 	pte_t *pte_newpg[PMDS_PER_MID_PAGE];
462 	pmd_t *pmdp;
463 	unsigned int level;
464 	unsigned long flags;
465 	unsigned long vaddr;
466 	int i;
467 
468 	/* Do all allocations first to bail out in error case. */
469 	for (i = 0; i < PMDS_PER_MID_PAGE; i++) {
470 		pte_newpg[i] = alloc_p2m_page();
471 		if (!pte_newpg[i]) {
472 			for (i--; i >= 0; i--)
473 				free_p2m_page(pte_newpg[i]);
474 
475 			return NULL;
476 		}
477 	}
478 
479 	vaddr = addr & ~(PMD_SIZE * PMDS_PER_MID_PAGE - 1);
480 
481 	for (i = 0; i < PMDS_PER_MID_PAGE; i++) {
482 		copy_page(pte_newpg[i], pte_pg);
483 		paravirt_alloc_pte(&init_mm, __pa(pte_newpg[i]) >> PAGE_SHIFT);
484 
485 		pmdp = lookup_pmd_address(vaddr);
486 		BUG_ON(!pmdp);
487 
488 		spin_lock_irqsave(&p2m_update_lock, flags);
489 
490 		ptechk = lookup_address(vaddr, &level);
491 		if (ptechk == pte_pg) {
492 			HYPERVISOR_shared_info->arch.p2m_generation++;
493 			wmb(); /* Tools are synchronizing via p2m_generation. */
494 			set_pmd(pmdp,
495 				__pmd(__pa(pte_newpg[i]) | _KERNPG_TABLE));
496 			wmb(); /* Tools are synchronizing via p2m_generation. */
497 			HYPERVISOR_shared_info->arch.p2m_generation++;
498 			pte_newpg[i] = NULL;
499 		}
500 
501 		spin_unlock_irqrestore(&p2m_update_lock, flags);
502 
503 		if (pte_newpg[i]) {
504 			paravirt_release_pte(__pa(pte_newpg[i]) >> PAGE_SHIFT);
505 			free_p2m_page(pte_newpg[i]);
506 		}
507 
508 		vaddr += PMD_SIZE;
509 	}
510 
511 	return lookup_address(addr, &level);
512 }
513 
514 /*
515  * Fully allocate the p2m structure for a given pfn.  We need to check
516  * that both the top and mid levels are allocated, and make sure the
517  * parallel mfn tree is kept in sync.  We may race with other cpus, so
518  * the new pages are installed with cmpxchg; if we lose the race then
519  * simply free the page we allocated and use the one that's there.
520  */
521 int xen_alloc_p2m_entry(unsigned long pfn)
522 {
523 	unsigned topidx;
524 	unsigned long *top_mfn_p, *mid_mfn;
525 	pte_t *ptep, *pte_pg;
526 	unsigned int level;
527 	unsigned long flags;
528 	unsigned long addr = (unsigned long)(xen_p2m_addr + pfn);
529 	unsigned long p2m_pfn;
530 
531 	ptep = lookup_address(addr, &level);
532 	BUG_ON(!ptep || level != PG_LEVEL_4K);
533 	pte_pg = (pte_t *)((unsigned long)ptep & ~(PAGE_SIZE - 1));
534 
535 	if (pte_pg == p2m_missing_pte || pte_pg == p2m_identity_pte) {
536 		/* PMD level is missing, allocate a new one */
537 		ptep = alloc_p2m_pmd(addr, pte_pg);
538 		if (!ptep)
539 			return -ENOMEM;
540 	}
541 
542 	if (p2m_top_mfn && pfn < MAX_P2M_PFN) {
543 		topidx = p2m_top_index(pfn);
544 		top_mfn_p = &p2m_top_mfn[topidx];
545 		mid_mfn = READ_ONCE(p2m_top_mfn_p[topidx]);
546 
547 		BUG_ON(virt_to_mfn(mid_mfn) != *top_mfn_p);
548 
549 		if (mid_mfn == p2m_mid_missing_mfn) {
550 			/* Separately check the mid mfn level */
551 			unsigned long missing_mfn;
552 			unsigned long mid_mfn_mfn;
553 
554 			mid_mfn = alloc_p2m_page();
555 			if (!mid_mfn)
556 				return -ENOMEM;
557 
558 			p2m_mid_mfn_init(mid_mfn, p2m_missing);
559 
560 			missing_mfn = virt_to_mfn(p2m_mid_missing_mfn);
561 			mid_mfn_mfn = virt_to_mfn(mid_mfn);
562 			/* try_cmpxchg() updates missing_mfn on failure. */
563 			if (try_cmpxchg(top_mfn_p, &missing_mfn, mid_mfn_mfn)) {
564 				p2m_top_mfn_p[topidx] = mid_mfn;
565 			} else {
566 				free_p2m_page(mid_mfn);
567 				mid_mfn = mfn_to_virt(missing_mfn);
568 			}
569 		}
570 	} else {
571 		mid_mfn = NULL;
572 	}
573 
574 	p2m_pfn = pte_pfn(READ_ONCE(*ptep));
575 	if (p2m_pfn == PFN_DOWN(__pa(p2m_identity)) ||
576 	    p2m_pfn == PFN_DOWN(__pa(p2m_missing))) {
577 		/* p2m leaf page is missing */
578 		unsigned long *p2m;
579 
580 		p2m = alloc_p2m_page();
581 		if (!p2m)
582 			return -ENOMEM;
583 
584 		if (p2m_pfn == PFN_DOWN(__pa(p2m_missing)))
585 			p2m_init(p2m);
586 		else
587 			p2m_init_identity(p2m, pfn & ~(P2M_PER_PAGE - 1));
588 
589 		spin_lock_irqsave(&p2m_update_lock, flags);
590 
591 		if (pte_pfn(*ptep) == p2m_pfn) {
592 			HYPERVISOR_shared_info->arch.p2m_generation++;
593 			wmb(); /* Tools are synchronizing via p2m_generation. */
594 			set_pte(ptep,
595 				pfn_pte(PFN_DOWN(__pa(p2m)), PAGE_KERNEL));
596 			wmb(); /* Tools are synchronizing via p2m_generation. */
597 			HYPERVISOR_shared_info->arch.p2m_generation++;
598 			if (mid_mfn)
599 				mid_mfn[p2m_mid_index(pfn)] = virt_to_mfn(p2m);
600 			p2m = NULL;
601 		}
602 
603 		spin_unlock_irqrestore(&p2m_update_lock, flags);
604 
605 		if (p2m)
606 			free_p2m_page(p2m);
607 	}
608 
609 	/* Expanded the p2m? */
610 	if (pfn >= xen_p2m_last_pfn) {
611 		xen_p2m_last_pfn = ALIGN(pfn + 1, P2M_PER_PAGE);
612 		HYPERVISOR_shared_info->arch.max_pfn = xen_p2m_last_pfn;
613 	}
614 
615 	return 0;
616 }
617 EXPORT_SYMBOL(xen_alloc_p2m_entry);
618 
619 unsigned long __init set_phys_range_identity(unsigned long pfn_s,
620 				      unsigned long pfn_e)
621 {
622 	unsigned long pfn;
623 
624 	if (unlikely(pfn_s >= xen_p2m_size))
625 		return 0;
626 
627 	if (pfn_s > pfn_e)
628 		return 0;
629 
630 	if (pfn_e > xen_p2m_size)
631 		pfn_e = xen_p2m_size;
632 
633 	for (pfn = pfn_s; pfn < pfn_e; pfn++)
634 		xen_p2m_addr[pfn] = IDENTITY_FRAME(pfn);
635 
636 	return pfn - pfn_s;
637 }
638 
639 bool __set_phys_to_machine(unsigned long pfn, unsigned long mfn)
640 {
641 	pte_t *ptep;
642 	unsigned int level;
643 
644 	/* Only invalid entries allowed above the highest p2m covered frame. */
645 	if (unlikely(pfn >= xen_p2m_size))
646 		return mfn == INVALID_P2M_ENTRY;
647 
648 	/*
649 	 * The interface requires atomic updates on p2m elements.
650 	 * xen_safe_write_ulong() is using an atomic store via asm().
651 	 */
652 	if (likely(!xen_safe_write_ulong(xen_p2m_addr + pfn, mfn)))
653 		return true;
654 
655 	ptep = lookup_address((unsigned long)(xen_p2m_addr + pfn), &level);
656 	BUG_ON(!ptep || level != PG_LEVEL_4K);
657 
658 	if (pte_pfn(*ptep) == PFN_DOWN(__pa(p2m_missing)))
659 		return mfn == INVALID_P2M_ENTRY;
660 
661 	if (pte_pfn(*ptep) == PFN_DOWN(__pa(p2m_identity)))
662 		return mfn == IDENTITY_FRAME(pfn);
663 
664 	return false;
665 }
666 
667 bool set_phys_to_machine(unsigned long pfn, unsigned long mfn)
668 {
669 	if (unlikely(!__set_phys_to_machine(pfn, mfn))) {
670 		int ret;
671 
672 		ret = xen_alloc_p2m_entry(pfn);
673 		if (ret < 0)
674 			return false;
675 
676 		return __set_phys_to_machine(pfn, mfn);
677 	}
678 
679 	return true;
680 }
681 
682 int set_foreign_p2m_mapping(struct gnttab_map_grant_ref *map_ops,
683 			    struct gnttab_map_grant_ref *kmap_ops,
684 			    struct page **pages, unsigned int count)
685 {
686 	int i, ret = 0;
687 	pte_t *pte;
688 
689 	if (xen_feature(XENFEAT_auto_translated_physmap))
690 		return 0;
691 
692 	if (kmap_ops) {
693 		ret = HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref,
694 						kmap_ops, count);
695 		if (ret)
696 			goto out;
697 	}
698 
699 	for (i = 0; i < count; i++) {
700 		unsigned long mfn, pfn;
701 		struct gnttab_unmap_grant_ref unmap[2];
702 		int rc;
703 
704 		/* Do not add to override if the map failed. */
705 		if (map_ops[i].status != GNTST_okay ||
706 		    (kmap_ops && kmap_ops[i].status != GNTST_okay))
707 			continue;
708 
709 		if (map_ops[i].flags & GNTMAP_contains_pte) {
710 			pte = (pte_t *)(mfn_to_virt(PFN_DOWN(map_ops[i].host_addr)) +
711 				(map_ops[i].host_addr & ~PAGE_MASK));
712 			mfn = pte_mfn(*pte);
713 		} else {
714 			mfn = PFN_DOWN(map_ops[i].dev_bus_addr);
715 		}
716 		pfn = page_to_pfn(pages[i]);
717 
718 		WARN(pfn_to_mfn(pfn) != INVALID_P2M_ENTRY, "page must be ballooned");
719 
720 		if (likely(set_phys_to_machine(pfn, FOREIGN_FRAME(mfn))))
721 			continue;
722 
723 		/*
724 		 * Signal an error for this slot. This in turn requires
725 		 * immediate unmapping.
726 		 */
727 		map_ops[i].status = GNTST_general_error;
728 		unmap[0].host_addr = map_ops[i].host_addr;
729 		unmap[0].handle = map_ops[i].handle;
730 		map_ops[i].handle = INVALID_GRANT_HANDLE;
731 		if (map_ops[i].flags & GNTMAP_device_map)
732 			unmap[0].dev_bus_addr = map_ops[i].dev_bus_addr;
733 		else
734 			unmap[0].dev_bus_addr = 0;
735 
736 		if (kmap_ops) {
737 			kmap_ops[i].status = GNTST_general_error;
738 			unmap[1].host_addr = kmap_ops[i].host_addr;
739 			unmap[1].handle = kmap_ops[i].handle;
740 			kmap_ops[i].handle = INVALID_GRANT_HANDLE;
741 			if (kmap_ops[i].flags & GNTMAP_device_map)
742 				unmap[1].dev_bus_addr = kmap_ops[i].dev_bus_addr;
743 			else
744 				unmap[1].dev_bus_addr = 0;
745 		}
746 
747 		/*
748 		 * Pre-populate both status fields, to be recognizable in
749 		 * the log message below.
750 		 */
751 		unmap[0].status = 1;
752 		unmap[1].status = 1;
753 
754 		rc = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref,
755 					       unmap, 1 + !!kmap_ops);
756 		if (rc || unmap[0].status != GNTST_okay ||
757 		    unmap[1].status != GNTST_okay)
758 			pr_err_once("gnttab unmap failed: rc=%d st0=%d st1=%d\n",
759 				    rc, unmap[0].status, unmap[1].status);
760 	}
761 
762 out:
763 	return ret;
764 }
765 
766 int clear_foreign_p2m_mapping(struct gnttab_unmap_grant_ref *unmap_ops,
767 			      struct gnttab_unmap_grant_ref *kunmap_ops,
768 			      struct page **pages, unsigned int count)
769 {
770 	int i, ret = 0;
771 
772 	if (xen_feature(XENFEAT_auto_translated_physmap))
773 		return 0;
774 
775 	for (i = 0; i < count; i++) {
776 		unsigned long mfn = __pfn_to_mfn(page_to_pfn(pages[i]));
777 		unsigned long pfn = page_to_pfn(pages[i]);
778 
779 		if (mfn != INVALID_P2M_ENTRY && (mfn & FOREIGN_FRAME_BIT))
780 			set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
781 		else
782 			ret = -EINVAL;
783 	}
784 	if (kunmap_ops)
785 		ret = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref,
786 						kunmap_ops, count) ?: ret;
787 
788 	return ret;
789 }
790 
791 /* Remapped non-RAM areas */
792 #define NR_NONRAM_REMAP 4
793 static struct nonram_remap {
794 	phys_addr_t maddr;
795 	phys_addr_t paddr;
796 	size_t size;
797 } xen_nonram_remap[NR_NONRAM_REMAP] __ro_after_init;
798 static unsigned int nr_nonram_remap __ro_after_init;
799 
800 /*
801  * Do the real remapping of non-RAM regions as specified in the
802  * xen_nonram_remap[] array.
803  * In case of an error just crash the system.
804  */
805 void __init xen_do_remap_nonram(void)
806 {
807 	unsigned int i;
808 	unsigned int remapped = 0;
809 	const struct nonram_remap *remap = xen_nonram_remap;
810 	unsigned long pfn, mfn, end_pfn;
811 
812 	for (i = 0; i < nr_nonram_remap; i++) {
813 		end_pfn = PFN_UP(remap->paddr + remap->size);
814 		pfn = PFN_DOWN(remap->paddr);
815 		mfn = PFN_DOWN(remap->maddr);
816 		while (pfn < end_pfn) {
817 			if (!set_phys_to_machine(pfn, mfn))
818 				panic("Failed to set p2m mapping for pfn=%lx mfn=%lx\n",
819 				       pfn, mfn);
820 
821 			pfn++;
822 			mfn++;
823 			remapped++;
824 		}
825 
826 		remap++;
827 	}
828 
829 	pr_info("Remapped %u non-RAM page(s)\n", remapped);
830 }
831 
832 #ifdef CONFIG_ACPI
833 /*
834  * Xen variant of acpi_os_ioremap() taking potentially remapped non-RAM
835  * regions into account.
836  * Any attempt to map an area crossing a remap boundary will produce a
837  * WARN() splat.
838  * phys is related to remap->maddr on input and will be rebased to remap->paddr.
839  */
840 static void __iomem *xen_acpi_os_ioremap(acpi_physical_address phys,
841 					 acpi_size size)
842 {
843 	unsigned int i;
844 	const struct nonram_remap *remap = xen_nonram_remap;
845 
846 	for (i = 0; i < nr_nonram_remap; i++) {
847 		if (phys + size > remap->maddr &&
848 		    phys < remap->maddr + remap->size) {
849 			WARN_ON(phys < remap->maddr ||
850 				phys + size > remap->maddr + remap->size);
851 			phys += remap->paddr - remap->maddr;
852 			break;
853 		}
854 	}
855 
856 	return x86_acpi_os_ioremap(phys, size);
857 }
858 #endif /* CONFIG_ACPI */
859 
860 /*
861  * Add a new non-RAM remap entry.
862  * In case of no free entry found, just crash the system.
863  */
864 void __init xen_add_remap_nonram(phys_addr_t maddr, phys_addr_t paddr,
865 				 unsigned long size)
866 {
867 	BUG_ON((maddr & ~PAGE_MASK) != (paddr & ~PAGE_MASK));
868 
869 	if (nr_nonram_remap == NR_NONRAM_REMAP) {
870 		xen_raw_console_write("Number of required E820 entry remapping actions exceed maximum value\n");
871 		BUG();
872 	}
873 
874 #ifdef CONFIG_ACPI
875 	/* Switch to the Xen acpi_os_ioremap() variant. */
876 	if (nr_nonram_remap == 0)
877 		acpi_os_ioremap = xen_acpi_os_ioremap;
878 #endif
879 
880 	xen_nonram_remap[nr_nonram_remap].maddr = maddr;
881 	xen_nonram_remap[nr_nonram_remap].paddr = paddr;
882 	xen_nonram_remap[nr_nonram_remap].size = size;
883 
884 	nr_nonram_remap++;
885 }
886 
887 #ifdef CONFIG_XEN_DEBUG_FS
888 #include <linux/debugfs.h>
889 static int p2m_dump_show(struct seq_file *m, void *v)
890 {
891 	static const char * const type_name[] = {
892 				[P2M_TYPE_IDENTITY] = "identity",
893 				[P2M_TYPE_MISSING] = "missing",
894 				[P2M_TYPE_PFN] = "pfn",
895 				[P2M_TYPE_UNKNOWN] = "abnormal"};
896 	unsigned long pfn, first_pfn;
897 	int type, prev_type;
898 
899 	prev_type = xen_p2m_elem_type(0);
900 	first_pfn = 0;
901 
902 	for (pfn = 0; pfn < xen_p2m_size; pfn++) {
903 		type = xen_p2m_elem_type(pfn);
904 		if (type != prev_type) {
905 			seq_printf(m, " [0x%lx->0x%lx] %s\n", first_pfn, pfn,
906 				   type_name[prev_type]);
907 			prev_type = type;
908 			first_pfn = pfn;
909 		}
910 	}
911 	seq_printf(m, " [0x%lx->0x%lx] %s\n", first_pfn, pfn,
912 		   type_name[prev_type]);
913 	return 0;
914 }
915 
916 DEFINE_SHOW_ATTRIBUTE(p2m_dump);
917 
918 static struct dentry *d_mmu_debug;
919 
920 static int __init xen_p2m_debugfs(void)
921 {
922 	struct dentry *d_xen = xen_init_debugfs();
923 
924 	d_mmu_debug = debugfs_create_dir("mmu", d_xen);
925 
926 	debugfs_create_file("p2m", 0600, d_mmu_debug, NULL, &p2m_dump_fops);
927 	return 0;
928 }
929 fs_initcall(xen_p2m_debugfs);
930 #endif /* CONFIG_XEN_DEBUG_FS */
931