Home | History | Annotate | Line # | Download | only in x86
x86_xpmap.c revision 1.83
      1 /*	$NetBSD: x86_xpmap.c,v 1.83 2019/03/07 13:26:24 maxv Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2017 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Maxime Villard.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 2006 Mathieu Ropert <mro (at) adviseo.fr>
     34  *
     35  * Permission to use, copy, modify, and distribute this software for any
     36  * purpose with or without fee is hereby granted, provided that the above
     37  * copyright notice and this permission notice appear in all copies.
     38  *
     39  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     40  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     41  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     42  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     43  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     44  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     45  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     46  */
     47 
     48 /*
     49  * Copyright (c) 2006, 2007 Manuel Bouyer.
     50  *
     51  * Redistribution and use in source and binary forms, with or without
     52  * modification, are permitted provided that the following conditions
     53  * are met:
     54  * 1. Redistributions of source code must retain the above copyright
     55  *    notice, this list of conditions and the following disclaimer.
     56  * 2. Redistributions in binary form must reproduce the above copyright
     57  *    notice, this list of conditions and the following disclaimer in the
     58  *    documentation and/or other materials provided with the distribution.
     59  *
     60  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     61  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     62  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     63  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     64  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     65  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     66  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     67  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     68  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     69  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     70  */
     71 
     72 /*
     73  * Copyright (c) 2004 Christian Limpach.
     74  * All rights reserved.
     75  *
     76  * Redistribution and use in source and binary forms, with or without
     77  * modification, are permitted provided that the following conditions
     78  * are met:
     79  * 1. Redistributions of source code must retain the above copyright
     80  *    notice, this list of conditions and the following disclaimer.
     81  * 2. Redistributions in binary form must reproduce the above copyright
     82  *    notice, this list of conditions and the following disclaimer in the
     83  *    documentation and/or other materials provided with the distribution.
     84  *
     85  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     86  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     87  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     88  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     89  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     90  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     91  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     92  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     93  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     94  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     95  */
     96 
     97 #include <sys/cdefs.h>
     98 __KERNEL_RCSID(0, "$NetBSD: x86_xpmap.c,v 1.83 2019/03/07 13:26:24 maxv Exp $");
     99 
    100 #include "opt_xen.h"
    101 #include "opt_ddb.h"
    102 #include "ksyms.h"
    103 
    104 #include <sys/param.h>
    105 #include <sys/systm.h>
    106 #include <sys/mutex.h>
    107 #include <sys/cpu.h>
    108 
    109 #include <uvm/uvm.h>
    110 
    111 #include <x86/pmap.h>
    112 #include <machine/gdt.h>
    113 #include <xen/xenfunc.h>
    114 
    115 #include <dev/isa/isareg.h>
    116 #include <machine/isa_machdep.h>
    117 
    118 #ifdef XENDEBUG
    119 #define	__PRINTK(x) printk x
    120 #else
    121 #define	__PRINTK(x)
    122 #endif
    123 
    124 /* Xen requires the start_info struct to be page aligned */
    125 union start_info_union start_info_union __aligned(PAGE_SIZE);
    126 
    127 volatile shared_info_t *HYPERVISOR_shared_info __read_mostly;
    128 unsigned long *xpmap_phys_to_machine_mapping __read_mostly;
    129 kmutex_t pte_lock __cacheline_aligned;
    130 vaddr_t xen_dummy_page;
    131 pt_entry_t xpmap_pg_nx __read_mostly;
    132 
    133 #define XPQUEUE_SIZE 2048
    134 static mmu_update_t xpq_queue_array[MAXCPUS][XPQUEUE_SIZE];
    135 
    136 void xen_failsafe_handler(void);
    137 
    138 extern volatile struct xencons_interface *xencons_interface; /* XXX */
    139 extern struct xenstore_domain_interface *xenstore_interface; /* XXX */
    140 
    141 static void xen_bt_set_readonly(vaddr_t);
    142 static void xen_bootstrap_tables(vaddr_t, vaddr_t, size_t, size_t, bool);
    143 
    144 vaddr_t xen_locore(void);
    145 
    146 /*
    147  * kcpuset internally uses an array of uint32_t while xen uses an array of
    148  * u_long. As we're little-endian we can cast one to the other.
    149  */
    150 typedef union {
    151 #ifdef _LP64
    152 	uint32_t xcpum_km[2];
    153 #else
    154 	uint32_t xcpum_km[1];
    155 #endif
    156 	u_long xcpum_xm;
    157 } xcpumask_t;
    158 
    159 void
    160 xen_failsafe_handler(void)
    161 {
    162 
    163 	panic("xen_failsafe_handler called!\n");
    164 }
    165 
    166 void
    167 xen_set_ldt(vaddr_t base, uint32_t entries)
    168 {
    169 	vaddr_t va;
    170 	vaddr_t end;
    171 	pt_entry_t *ptp;
    172 	int s;
    173 
    174 #ifdef __x86_64__
    175 	end = base + (entries << 3);
    176 #else
    177 	end = base + entries * sizeof(union descriptor);
    178 #endif
    179 
    180 	for (va = base; va < end; va += PAGE_SIZE) {
    181 		KASSERT(va >= VM_MIN_KERNEL_ADDRESS);
    182 		ptp = kvtopte(va);
    183 		pmap_pte_clearbits(ptp, PG_RW);
    184 	}
    185 	s = splvm(); /* XXXSMP */
    186 	xpq_queue_set_ldt(base, entries);
    187 	splx(s);
    188 }
    189 
    190 void
    191 xpq_flush_queue(void)
    192 {
    193 	mmu_update_t *xpq_queue;
    194 	int done = 0, ret;
    195 	size_t xpq_idx;
    196 
    197 	xpq_idx = curcpu()->ci_xpq_idx;
    198 	xpq_queue = xpq_queue_array[curcpu()->ci_cpuid];
    199 
    200 retry:
    201 	ret = HYPERVISOR_mmu_update(xpq_queue, xpq_idx, &done, DOMID_SELF);
    202 
    203 	if (ret < 0 && xpq_idx != 0) {
    204 		printf("xpq_flush_queue: %zu entries (%d successful) on "
    205 		    "cpu%d (%ld)\n",
    206 		    xpq_idx, done, curcpu()->ci_index, curcpu()->ci_cpuid);
    207 
    208 		if (done != 0) {
    209 			xpq_queue += done;
    210 			xpq_idx -= done;
    211 			done = 0;
    212 			goto retry;
    213 		}
    214 
    215 		panic("HYPERVISOR_mmu_update failed, ret: %d\n", ret);
    216 	}
    217 	curcpu()->ci_xpq_idx = 0;
    218 }
    219 
    220 static inline void
    221 xpq_increment_idx(void)
    222 {
    223 
    224 	if (__predict_false(++curcpu()->ci_xpq_idx == XPQUEUE_SIZE))
    225 		xpq_flush_queue();
    226 }
    227 
    228 void
    229 xpq_queue_machphys_update(paddr_t ma, paddr_t pa)
    230 {
    231 	mmu_update_t *xpq_queue = xpq_queue_array[curcpu()->ci_cpuid];
    232 	size_t xpq_idx = curcpu()->ci_xpq_idx;
    233 
    234 	xpq_queue[xpq_idx].ptr = ma | MMU_MACHPHYS_UPDATE;
    235 	xpq_queue[xpq_idx].val = pa >> PAGE_SHIFT;
    236 	xpq_increment_idx();
    237 }
    238 
    239 void
    240 xpq_queue_pte_update(paddr_t ptr, pt_entry_t val)
    241 {
    242 	mmu_update_t *xpq_queue = xpq_queue_array[curcpu()->ci_cpuid];
    243 	size_t xpq_idx = curcpu()->ci_xpq_idx;
    244 
    245 	xpq_queue[xpq_idx].ptr = ptr | MMU_NORMAL_PT_UPDATE;
    246 	xpq_queue[xpq_idx].val = val;
    247 	xpq_increment_idx();
    248 }
    249 
    250 void
    251 xpq_queue_pt_switch(paddr_t pa)
    252 {
    253 	struct mmuext_op op;
    254 
    255 	xpq_flush_queue();
    256 
    257 	op.cmd = MMUEXT_NEW_BASEPTR;
    258 	op.arg1.mfn = pa >> PAGE_SHIFT;
    259 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    260 		panic(__func__);
    261 }
    262 
    263 void
    264 xpq_queue_pin_table(paddr_t pa, int lvl)
    265 {
    266 	struct mmuext_op op;
    267 
    268 	xpq_flush_queue();
    269 
    270 	op.cmd = lvl;
    271 	op.arg1.mfn = pa >> PAGE_SHIFT;
    272 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    273 		panic(__func__);
    274 }
    275 
    276 void
    277 xpq_queue_unpin_table(paddr_t pa)
    278 {
    279 	struct mmuext_op op;
    280 
    281 	xpq_flush_queue();
    282 
    283 	op.cmd = MMUEXT_UNPIN_TABLE;
    284 	op.arg1.mfn = pa >> PAGE_SHIFT;
    285 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    286 		panic(__func__);
    287 }
    288 
    289 void
    290 xpq_queue_set_ldt(vaddr_t va, uint32_t entries)
    291 {
    292 	struct mmuext_op op;
    293 
    294 	xpq_flush_queue();
    295 
    296 	KASSERT(va == (va & ~PAGE_MASK));
    297 	op.cmd = MMUEXT_SET_LDT;
    298 	op.arg1.linear_addr = va;
    299 	op.arg2.nr_ents = entries;
    300 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    301 		panic(__func__);
    302 }
    303 
    304 void
    305 xpq_queue_tlb_flush(void)
    306 {
    307 	struct mmuext_op op;
    308 
    309 	xpq_flush_queue();
    310 
    311 	op.cmd = MMUEXT_TLB_FLUSH_LOCAL;
    312 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    313 		panic(__func__);
    314 }
    315 
    316 void
    317 xpq_flush_cache(void)
    318 {
    319 	int s = splvm(); /* XXXSMP */
    320 
    321 	xpq_flush_queue();
    322 
    323 	asm("wbinvd":::"memory");
    324 	splx(s); /* XXX: removeme */
    325 }
    326 
    327 void
    328 xpq_queue_invlpg(vaddr_t va)
    329 {
    330 	struct mmuext_op op;
    331 
    332 	xpq_flush_queue();
    333 
    334 	op.cmd = MMUEXT_INVLPG_LOCAL;
    335 	op.arg1.linear_addr = (va & ~PAGE_MASK);
    336 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    337 		panic(__func__);
    338 }
    339 
    340 void
    341 xen_mcast_invlpg(vaddr_t va, kcpuset_t *kc)
    342 {
    343 	xcpumask_t xcpumask;
    344 	mmuext_op_t op;
    345 
    346 	kcpuset_export_u32(kc, &xcpumask.xcpum_km[0], sizeof(xcpumask));
    347 
    348 	xpq_flush_queue();
    349 
    350 	op.cmd = MMUEXT_INVLPG_MULTI;
    351 	op.arg1.linear_addr = va;
    352 	set_xen_guest_handle(op.arg2.vcpumask, &xcpumask.xcpum_xm);
    353 
    354 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    355 		panic(__func__);
    356 }
    357 
    358 void
    359 xen_bcast_invlpg(vaddr_t va)
    360 {
    361 	mmuext_op_t op;
    362 
    363 	xpq_flush_queue();
    364 
    365 	op.cmd = MMUEXT_INVLPG_ALL;
    366 	op.arg1.linear_addr = va;
    367 
    368 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    369 		panic(__func__);
    370 }
    371 
    372 /* This is a synchronous call. */
    373 void
    374 xen_mcast_tlbflush(kcpuset_t *kc)
    375 {
    376 	xcpumask_t xcpumask;
    377 	mmuext_op_t op;
    378 
    379 	kcpuset_export_u32(kc, &xcpumask.xcpum_km[0], sizeof(xcpumask));
    380 
    381 	xpq_flush_queue();
    382 
    383 	op.cmd = MMUEXT_TLB_FLUSH_MULTI;
    384 	set_xen_guest_handle(op.arg2.vcpumask, &xcpumask.xcpum_xm);
    385 
    386 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    387 		panic(__func__);
    388 }
    389 
    390 /* This is a synchronous call. */
    391 void
    392 xen_bcast_tlbflush(void)
    393 {
    394 	mmuext_op_t op;
    395 
    396 	xpq_flush_queue();
    397 
    398 	op.cmd = MMUEXT_TLB_FLUSH_ALL;
    399 
    400 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    401 		panic(__func__);
    402 }
    403 
    404 void
    405 xen_copy_page(paddr_t srcpa, paddr_t dstpa)
    406 {
    407 	mmuext_op_t op;
    408 
    409 	op.cmd = MMUEXT_COPY_PAGE;
    410 	op.arg1.mfn = xpmap_ptom(dstpa) >> PAGE_SHIFT;
    411 	op.arg2.src_mfn = xpmap_ptom(srcpa) >> PAGE_SHIFT;
    412 
    413 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    414 		panic(__func__);
    415 }
    416 
    417 void
    418 xen_pagezero(paddr_t pa)
    419 {
    420 	mmuext_op_t op;
    421 
    422 	op.cmd = MMUEXT_CLEAR_PAGE;
    423 	op.arg1.mfn = xpmap_ptom(pa) >> PAGE_SHIFT;
    424 
    425 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    426 		panic(__func__);
    427 }
    428 
    429 int
    430 xpq_update_foreign(paddr_t ptr, pt_entry_t val, int dom)
    431 {
    432 	mmu_update_t op;
    433 	int ok;
    434 
    435 	xpq_flush_queue();
    436 
    437 	op.ptr = ptr;
    438 	op.val = val;
    439 	if (HYPERVISOR_mmu_update(&op, 1, &ok, dom) < 0)
    440 		return EFAULT;
    441 	return 0;
    442 }
    443 
    444 #if L2_SLOT_KERNBASE > 0
    445 #define TABLE_L2_ENTRIES (2 * (NKL2_KIMG_ENTRIES + 1))
    446 #else
    447 #define TABLE_L2_ENTRIES (NKL2_KIMG_ENTRIES + 1)
    448 #endif
    449 
    450 #ifdef __x86_64__
    451 #define PDIRSZ	PTP_LEVELS
    452 #else
    453 /*
    454  * For PAE, we need an L3 page, a single contiguous L2 "superpage" of 4 pages
    455  * (all of them mapped by the L3 page), and a shadow page for L3[3].
    456  */
    457 #define PDIRSZ	(1 + 4 + 1)
    458 #endif
    459 
    460 /*
    461  * Xen locore: get rid of the Xen bootstrap tables. Build and switch to new page
    462  * tables.
    463  *
    464  * Virtual address space of the kernel when leaving this function:
    465  * +--------------+------------------+-------------+------------+---------------
    466  * | KERNEL IMAGE | BOOTSTRAP TABLES | PROC0 UAREA | DUMMY PAGE | HYPER. SHARED
    467  * +--------------+------------------+-------------+------------+---------------
    468  *
    469  * ------+-----------------+-------------+
    470  *  INFO | EARLY ZERO PAGE | ISA I/O MEM |
    471  * ------+-----------------+-------------+
    472  *
    473  * DUMMY PAGE is either a PDG for amd64 or a GDT for i386.
    474  *
    475  * (HYPER. SHARED INFO + EARLY ZERO PAGE + ISA I/O MEM) have no physical
    476  * addresses preallocated.
    477  */
    478 vaddr_t
    479 xen_locore(void)
    480 {
    481 	size_t nL2, oldcount, mapsize;
    482 	vaddr_t our_tables, xen_tables;
    483 	u_int descs[4];
    484 
    485 	xen_init_features();
    486 
    487 	xpmap_phys_to_machine_mapping =
    488 	    (unsigned long *)xen_start_info.mfn_list;
    489 
    490 	/* Set the NX/XD bit, if available. descs[3] = %edx. */
    491 	x86_cpuid(0x80000001, descs);
    492 	xpmap_pg_nx = (descs[3] & CPUID_NOX) ? PG_NX : 0;
    493 
    494 	/* Space after Xen boostrap tables should be free */
    495 	xen_tables = xen_start_info.pt_base;
    496 	our_tables = xen_tables + (xen_start_info.nr_pt_frames * PAGE_SIZE);
    497 
    498 	/*
    499 	 * Calculate how much space we need. First, everything mapped before
    500 	 * the Xen bootstrap tables.
    501 	 */
    502 	mapsize = xen_tables - KERNTEXTOFF;
    503 
    504 	/* After the tables we'll have:
    505 	 *  - UAREA
    506 	 *  - dummy user PGD (x86_64)
    507 	 *  - HYPERVISOR_shared_info
    508 	 *  - early_zerop
    509 	 *  - ISA I/O mem (if needed)
    510 	 */
    511 	mapsize += UPAGES * PAGE_SIZE;
    512 #ifdef __x86_64__
    513 	mapsize += PAGE_SIZE;
    514 #endif
    515 	mapsize += PAGE_SIZE;
    516 	mapsize += PAGE_SIZE;
    517 #ifdef DOM0OPS
    518 	if (xendomain_is_dom0()) {
    519 		mapsize += IOM_SIZE;
    520 	}
    521 #endif
    522 
    523 	/*
    524 	 * At this point, mapsize doesn't include the table size.
    525 	 */
    526 #ifdef __x86_64__
    527 	nL2 = TABLE_L2_ENTRIES;
    528 #else
    529 	nL2 = (mapsize + (NBPD_L2 - 1)) >> L2_SHIFT;
    530 #endif
    531 
    532 	/*
    533 	 * Now compute how many L2 pages we need exactly. This is useful only
    534 	 * on i386, since the initial count for amd64 is already enough.
    535 	 */
    536 	while (KERNTEXTOFF + mapsize + (nL2 + PDIRSZ) * PAGE_SIZE >
    537 	    KERNBASE + (nL2 << L2_SHIFT)) {
    538 		nL2++;
    539 	}
    540 
    541 #ifdef i386
    542 	/*
    543 	 * One more L2 page: we'll allocate several pages after kva_start
    544 	 * in pmap_bootstrap() before pmap_growkernel(), which have not been
    545 	 * counted here. It's not a big issue to allocate one more L2 as
    546 	 * pmap_growkernel() will be called anyway.
    547 	 */
    548 	nL2++;
    549 	nkptp[1] = nL2;
    550 #endif
    551 
    552 	/*
    553 	 * Install bootstrap pages. We may need more L2 pages than will
    554 	 * have the final table here, as it's installed after the final table.
    555 	 */
    556 	oldcount = nL2;
    557 
    558 bootstrap_again:
    559 
    560 	/*
    561 	 * Xen space we'll reclaim may not be enough for our new page tables,
    562 	 * move bootstrap tables if necessary.
    563 	 */
    564 	if (our_tables < xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE))
    565 		our_tables = xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE);
    566 
    567 	/*
    568 	 * Make sure the number of L2 pages we have is enough to map everything
    569 	 * from KERNBASE to the bootstrap tables themselves.
    570 	 */
    571 	if (our_tables + ((oldcount + PDIRSZ) * PAGE_SIZE) >
    572 	    KERNBASE + (oldcount << L2_SHIFT)) {
    573 		oldcount++;
    574 		goto bootstrap_again;
    575 	}
    576 
    577 	/* Create temporary tables */
    578 	xen_bootstrap_tables(xen_tables, our_tables,
    579 	    xen_start_info.nr_pt_frames, oldcount, false);
    580 
    581 	/* Create final tables */
    582 	xen_bootstrap_tables(our_tables, xen_tables,
    583 	    oldcount + PDIRSZ, nL2, true);
    584 
    585 	/* Zero out PROC0 UAREA and DUMMY PAGE. */
    586 	memset((void *)(xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE)), 0,
    587 	    (UPAGES + 1) * PAGE_SIZE);
    588 
    589 	/* Finally, flush TLB. */
    590 	xpq_queue_tlb_flush();
    591 
    592 	return (xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE));
    593 }
    594 
    595 /*
    596  * Build a new table and switch to it.
    597  * old_count is # of old tables (including L4, L3 and L2).
    598  * new_count is # of new tables (PTE only).
    599  * We assume the areas don't overlap.
    600  */
    601 static void
    602 xen_bootstrap_tables(vaddr_t old_pgd, vaddr_t new_pgd, size_t old_count,
    603     size_t new_count, bool final)
    604 {
    605 	pd_entry_t *L4cpu, *L4, *L3, *L2, *pte;
    606 	paddr_t addr;
    607 	vaddr_t page, avail, map_end;
    608 	int i;
    609 	extern char __rodata_start;
    610 	extern char __data_start;
    611 	extern char __kernel_end;
    612 	extern char *early_zerop; /* from pmap.c */
    613 #ifdef i386
    614 	extern union descriptor tmpgdt[];
    615 #endif
    616 
    617 	/*
    618 	 * Layout of RW area after the kernel image:
    619 	 *     xencons_interface (if present)
    620 	 *     xenstore_interface (if present)
    621 	 *     table pages (new_count + PDIRSZ entries)
    622 	 * Extra mappings (only when final is true):
    623 	 *     UAREA
    624 	 *     dummy user PGD (x86_64 only) / GDT page (i386 only)
    625 	 *     HYPERVISOR_shared_info
    626 	 *     early_zerop
    627 	 *     ISA I/O mem (if needed)
    628 	 */
    629 	map_end = new_pgd + ((new_count + PDIRSZ) * PAGE_SIZE);
    630 	if (final) {
    631 		map_end += UPAGES * PAGE_SIZE;
    632 		xen_dummy_page = (vaddr_t)map_end;
    633 		map_end += PAGE_SIZE;
    634 		HYPERVISOR_shared_info = (shared_info_t *)map_end;
    635 		map_end += PAGE_SIZE;
    636 		early_zerop = (char *)map_end;
    637 		map_end += PAGE_SIZE;
    638 	}
    639 
    640 	/*
    641 	 * We always set atdevbase, as it's used by init386 to find the first
    642 	 * available VA. map_end is updated only if we are dom0, so
    643 	 * atdevbase -> atdevbase + IOM_SIZE will be mapped only in
    644 	 * this case.
    645 	 */
    646 	if (final) {
    647 		atdevbase = map_end;
    648 #ifdef DOM0OPS
    649 		if (xendomain_is_dom0()) {
    650 			/* ISA I/O mem */
    651 			map_end += IOM_SIZE;
    652 		}
    653 #endif
    654 	}
    655 
    656 	__PRINTK(("xen_bootstrap_tables map_end 0x%lx\n", map_end));
    657 	__PRINTK(("console %#lx ", xen_start_info.console_mfn));
    658 	__PRINTK(("xenstore %#" PRIx32 "\n", xen_start_info.store_mfn));
    659 
    660 	avail = new_pgd;
    661 
    662 	/*
    663 	 * Create our page tables.
    664 	 */
    665 
    666 #ifdef __x86_64__
    667 	/* per-cpu L4 */
    668 	L4cpu = (pd_entry_t *)avail;
    669 	memset(L4cpu, 0, PAGE_SIZE);
    670 	avail += PAGE_SIZE;
    671 
    672 	/* pmap_kernel L4 */
    673 	L4 = (pd_entry_t *)avail;
    674 	memset(L4, 0, PAGE_SIZE);
    675 	avail += PAGE_SIZE;
    676 
    677 	/* L3 */
    678 	L3 = (pd_entry_t *)avail;
    679 	memset(L3, 0, PAGE_SIZE);
    680 	avail += PAGE_SIZE;
    681 
    682 	/* link L4->L3 */
    683 	addr = ((u_long)L3) - KERNBASE;
    684 	L4cpu[pl4_pi(KERNTEXTOFF)] = xpmap_ptom_masked(addr) | PG_V | PG_RW;
    685 	L4[pl4_pi(KERNTEXTOFF)] = xpmap_ptom_masked(addr) | PG_V | PG_RW;
    686 
    687 	/* L2 */
    688 	L2 = (pd_entry_t *)avail;
    689 	memset(L2, 0, PAGE_SIZE);
    690 	avail += PAGE_SIZE;
    691 
    692 	/* link L3->L2 */
    693 	addr = ((u_long)L2) - KERNBASE;
    694 	L3[pl3_pi(KERNTEXTOFF)] = xpmap_ptom_masked(addr) | PG_V | PG_RW;
    695 #else
    696 	/* no L4 on i386PAE */
    697 	__USE(L4cpu);
    698 	__USE(L4);
    699 
    700 	/* L3 */
    701 	L3 = (pd_entry_t *)avail;
    702 	memset(L3, 0, PAGE_SIZE);
    703 	avail += PAGE_SIZE;
    704 
    705 	/*
    706 	 * Our PAE-style level 2, 5 contiguous pages (4 L2 + 1 shadow).
    707 	 *                  +-----------------+----------------+---------+
    708 	 * Physical layout: | 3 * USERLAND L2 | L2 KERN SHADOW | L2 KERN |
    709 	 *                  +-----------------+----------------+---------+
    710 	 * However, we enter L3[3] into L2 KERN, and not L2 KERN SHADOW.
    711 	 * This way, L2[L2_SLOT_KERN] always points to the shadow.
    712 	 */
    713 	L2 = (pd_entry_t *)avail;
    714 	memset(L2, 0, PAGE_SIZE * 5);
    715 	avail += PAGE_SIZE * 5;
    716 
    717 	/*
    718 	 * Link L2 pages in L3, with a special case for L2 KERN. Xen doesn't
    719 	 * want RW permissions in L3 entries, it'll add them itself.
    720 	 */
    721 	addr = ((u_long)L2) - KERNBASE;
    722 	for (i = 0; i < 3; i++, addr += PAGE_SIZE) {
    723 		L3[i] = xpmap_ptom_masked(addr) | PG_V;
    724 	}
    725 	addr += PAGE_SIZE;
    726 	L3[3] = xpmap_ptom_masked(addr) | PG_V;
    727 #endif
    728 
    729 	/* Level 1 */
    730 	page = KERNTEXTOFF;
    731 	for (i = 0; i < new_count; i ++) {
    732 		vaddr_t cur_page = page;
    733 
    734 		pte = (pd_entry_t *)avail;
    735 		memset(pte, 0, PAGE_SIZE);
    736 		avail += PAGE_SIZE;
    737 
    738 		while (pl2_pi(page) == pl2_pi(cur_page)) {
    739 			if (page >= map_end) {
    740 				/* not mapped at all */
    741 				pte[pl1_pi(page)] = 0;
    742 				page += PAGE_SIZE;
    743 				continue;
    744 			}
    745 			pte[pl1_pi(page)] = xpmap_ptom_masked(page - KERNBASE);
    746 			if (page == (vaddr_t)HYPERVISOR_shared_info) {
    747 				pte[pl1_pi(page)] = xen_start_info.shared_info;
    748 			}
    749 			if ((xpmap_ptom_masked(page - KERNBASE) >> PAGE_SHIFT)
    750 			    == xen_start_info.console.domU.mfn) {
    751 				xencons_interface = (void *)page;
    752 				pte[pl1_pi(page)] = xen_start_info.console_mfn;
    753 				pte[pl1_pi(page)] <<= PAGE_SHIFT;
    754 			}
    755 			if ((xpmap_ptom_masked(page - KERNBASE) >> PAGE_SHIFT)
    756 			    == xen_start_info.store_mfn) {
    757 				xenstore_interface = (void *)page;
    758 				pte[pl1_pi(page)] = xen_start_info.store_mfn;
    759 				pte[pl1_pi(page)] <<= PAGE_SHIFT;
    760 			}
    761 #ifdef DOM0OPS
    762 			if (page >= (vaddr_t)atdevbase &&
    763 			    page < (vaddr_t)atdevbase + IOM_SIZE) {
    764 				pte[pl1_pi(page)] =
    765 				    IOM_BEGIN + (page - (vaddr_t)atdevbase);
    766 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    767 			}
    768 #endif
    769 
    770 			pte[pl1_pi(page)] |= PG_V;
    771 			if (page < (vaddr_t)&__rodata_start) {
    772 				/* Map the kernel text RX. Nothing to do. */
    773 			} else if (page >= (vaddr_t)&__rodata_start &&
    774 			    page < (vaddr_t)&__data_start) {
    775 				/* Map the kernel rodata R. */
    776 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    777 			} else if (page >= old_pgd &&
    778 			    page < old_pgd + (old_count * PAGE_SIZE)) {
    779 				/* Map the old page tables R. */
    780 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    781 			} else if (page >= new_pgd &&
    782 			    page < new_pgd + ((new_count + PDIRSZ) * PAGE_SIZE)) {
    783 				/* Map the new page tables R. */
    784 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    785 #ifdef i386
    786 			} else if (page == (vaddr_t)tmpgdt) {
    787 				/*
    788 				 * Map bootstrap gdt R/O. Later, we will re-add
    789 				 * this page to uvm after making it writable.
    790 				 */
    791 				pte[pl1_pi(page)] = 0;
    792 				page += PAGE_SIZE;
    793 				continue;
    794 #endif
    795 			} else if (page >= (vaddr_t)&__data_start &&
    796 			    page < (vaddr_t)&__kernel_end) {
    797 				/* Map the kernel data+bss RW. */
    798 				pte[pl1_pi(page)] |= PG_RW | xpmap_pg_nx;
    799 			} else {
    800 				/* Map the page RW. */
    801 				pte[pl1_pi(page)] |= PG_RW | xpmap_pg_nx;
    802 			}
    803 
    804 			page += PAGE_SIZE;
    805 		}
    806 
    807 		addr = ((u_long)pte) - KERNBASE;
    808 		L2[pl2_pi(cur_page)] = xpmap_ptom_masked(addr) | PG_RW | PG_V;
    809 
    810 		/* Mark readonly */
    811 		xen_bt_set_readonly((vaddr_t)pte);
    812 	}
    813 
    814 	/* Install recursive page tables mapping */
    815 #ifdef __x86_64__
    816 	/* Recursive entry in pmap_kernel(). */
    817 	L4[PDIR_SLOT_PTE] = xpmap_ptom_masked((paddr_t)L4 - KERNBASE)
    818 	    | PG_V | xpmap_pg_nx;
    819 	/* Recursive entry in higher-level per-cpu PD. */
    820 	L4cpu[PDIR_SLOT_PTE] = xpmap_ptom_masked((paddr_t)L4cpu - KERNBASE)
    821 	    | PG_V | xpmap_pg_nx;
    822 
    823 	/* Mark tables RO */
    824 	xen_bt_set_readonly((vaddr_t)L2);
    825 #else
    826 	/* Copy L2 KERN into L2 KERN SHADOW, and reference the latter in cpu0. */
    827 	memcpy(&L2[L2_SLOT_KERN + NPDPG], &L2[L2_SLOT_KERN], PAGE_SIZE);
    828 	cpu_info_primary.ci_kpm_pdir = &L2[L2_SLOT_KERN + NPDPG];
    829 	cpu_info_primary.ci_kpm_pdirpa =
    830 	    (vaddr_t)cpu_info_primary.ci_kpm_pdir - KERNBASE;
    831 
    832 	/*
    833 	 * We don't enter a recursive entry from the L3 PD. Instead, we enter
    834 	 * the first 4 L2 pages, which includes the kernel's L2 shadow. But we
    835 	 * have to enter the shadow after switching %cr3, or Xen will refcount
    836 	 * some PTEs with the wrong type.
    837 	 */
    838 	addr = (u_long)L2 - KERNBASE;
    839 	for (i = 0; i < 3; i++, addr += PAGE_SIZE) {
    840 		L2[PDIR_SLOT_PTE + i] = xpmap_ptom_masked(addr) | PG_V |
    841 		    xpmap_pg_nx;
    842 	}
    843 
    844 	/* Mark tables RO, and pin L2 KERN SHADOW. */
    845 	addr = (u_long)L2 - KERNBASE;
    846 	for (i = 0; i < 5; i++, addr += PAGE_SIZE) {
    847 		xen_bt_set_readonly(((vaddr_t)L2) + PAGE_SIZE * i);
    848 	}
    849 	if (final) {
    850 		addr = (u_long)L2 - KERNBASE + 3 * PAGE_SIZE;
    851 		xpq_queue_pin_l2_table(xpmap_ptom_masked(addr));
    852 	}
    853 #endif
    854 
    855 	xen_bt_set_readonly((vaddr_t)L3);
    856 #ifdef __x86_64__
    857 	xen_bt_set_readonly((vaddr_t)L4cpu);
    858 #endif
    859 
    860 	/* Pin the PGD */
    861 #ifdef __x86_64__
    862 	xpq_queue_pin_l4_table(xpmap_ptom_masked(new_pgd - KERNBASE));
    863 #else
    864 	xpq_queue_pin_l3_table(xpmap_ptom_masked(new_pgd - KERNBASE));
    865 #endif
    866 
    867 	/* Save phys. addr of PDP, for libkvm. */
    868 #ifdef __x86_64__
    869 	PDPpaddr = (u_long)L4 - KERNBASE;
    870 #else
    871 	PDPpaddr = (u_long)L2 - KERNBASE; /* PDP is the L2 with PAE */
    872 #endif
    873 
    874 	/* Switch to new tables */
    875 	xpq_queue_pt_switch(xpmap_ptom_masked(new_pgd - KERNBASE));
    876 
    877 	if (final) {
    878 #ifdef __x86_64__
    879 		/* Save the address of the real per-cpu L4 page. */
    880 		cpu_info_primary.ci_kpm_pdir = L4cpu;
    881 		cpu_info_primary.ci_kpm_pdirpa = ((paddr_t)L4cpu - KERNBASE);
    882 #else
    883 		/* Save the address of the L3 page */
    884 		cpu_info_primary.ci_pae_l3_pdir = L3;
    885 		cpu_info_primary.ci_pae_l3_pdirpa = (new_pgd - KERNBASE);
    886 
    887 		/* Now enter the kernel's PTE mappings */
    888 		addr = (u_long)L2 - KERNBASE + PAGE_SIZE * 3;
    889 		xpq_queue_pte_update(
    890 		    xpmap_ptom(((vaddr_t)&L2[PDIR_SLOT_PTE + 3]) - KERNBASE),
    891 		    xpmap_ptom_masked(addr) | PG_V);
    892 		xpq_flush_queue();
    893 #endif
    894 	}
    895 
    896 	/*
    897 	 * Now we can safely reclaim the space taken by the old tables.
    898 	 */
    899 
    900 	/* Unpin old PGD */
    901 	xpq_queue_unpin_table(xpmap_ptom_masked(old_pgd - KERNBASE));
    902 
    903 	/* Mark old tables RW */
    904 	page = old_pgd;
    905 	addr = xpmap_mtop((paddr_t)L2[pl2_pi(page)] & PG_FRAME);
    906 	pte = (pd_entry_t *)((u_long)addr + KERNBASE);
    907 	pte += pl1_pi(page);
    908 	while (page < old_pgd + (old_count * PAGE_SIZE) && page < map_end) {
    909 		addr = xpmap_ptom(((u_long)pte) - KERNBASE);
    910 		xpq_queue_pte_update(addr, *pte | PG_RW);
    911 		page += PAGE_SIZE;
    912 		/*
    913 		 * Our PTEs are contiguous so it's safe to just "++" here.
    914 		 */
    915 		pte++;
    916 	}
    917 	xpq_flush_queue();
    918 }
    919 
    920 /*
    921  * Mark a page read-only, assuming vaddr = paddr + KERNBASE.
    922  */
    923 static void
    924 xen_bt_set_readonly(vaddr_t page)
    925 {
    926 	pt_entry_t entry;
    927 
    928 	entry = xpmap_ptom_masked(page - KERNBASE);
    929 	entry |= PG_V | xpmap_pg_nx;
    930 
    931 	HYPERVISOR_update_va_mapping(page, entry, UVMF_INVLPG);
    932 }
    933 
    934 #ifdef __x86_64__
    935 void
    936 xen_set_user_pgd(paddr_t page)
    937 {
    938 	struct mmuext_op op;
    939 	int s = splvm(); /* XXXSMP */
    940 
    941 	xpq_flush_queue();
    942 	op.cmd = MMUEXT_NEW_USER_BASEPTR;
    943 	op.arg1.mfn = xpmap_ptom_masked(page) >> PAGE_SHIFT;
    944 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    945 		panic("xen_set_user_pgd: failed to install new user page"
    946 			" directory %#" PRIxPADDR, page);
    947 	splx(s);
    948 }
    949 #endif /* __x86_64__ */
    950