Home | History | Annotate | Line # | Download | only in x86
x86_xpmap.c revision 1.84.4.1
      1 /*	$NetBSD: x86_xpmap.c,v 1.84.4.1 2020/05/31 10:39:34 martin 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.84.4.1 2020/05/31 10:39:34 martin 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, PTE_W);
    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, u_int flags)
    431 {
    432 	mmu_update_t op;
    433 	int ok;
    434 	int err;
    435 
    436 	xpq_flush_queue();
    437 
    438 	op.ptr = ptr;
    439 	if (flags & PMAP_MD_XEN_NOTR)
    440 		op.ptr |= MMU_PT_UPDATE_NO_TRANSLATE;
    441 	op.val = val;
    442 	/*
    443 	 * here we return a negative error number as Xen error to
    444 	 * pmap_enter_ma. only calls from privcmd.c should end here, and
    445 	 * it can deal with it.
    446 	 */
    447 	if ((err = HYPERVISOR_mmu_update(&op, 1, &ok, dom)) < 0) {
    448 		return err;
    449 	}
    450 	return 0;
    451 }
    452 
    453 #if L2_SLOT_KERNBASE > 0
    454 #define TABLE_L2_ENTRIES (2 * (NKL2_KIMG_ENTRIES + 1))
    455 #else
    456 #define TABLE_L2_ENTRIES (NKL2_KIMG_ENTRIES + 1)
    457 #endif
    458 
    459 #ifdef __x86_64__
    460 #define PDIRSZ	PTP_LEVELS
    461 #else
    462 /*
    463  * For PAE, we need an L3 page, a single contiguous L2 "superpage" of 4 pages
    464  * (all of them mapped by the L3 page), and a shadow page for L3[3].
    465  */
    466 #define PDIRSZ	(1 + 4 + 1)
    467 #endif
    468 
    469 /*
    470  * Xen locore: get rid of the Xen bootstrap tables. Build and switch to new page
    471  * tables.
    472  *
    473  * Virtual address space of the kernel when leaving this function:
    474  * +--------------+------------------+-------------+------------+---------------
    475  * | KERNEL IMAGE | BOOTSTRAP TABLES | PROC0 UAREA | DUMMY PAGE | HYPER. SHARED
    476  * +--------------+------------------+-------------+------------+---------------
    477  *
    478  * ------+-----------------+-------------+
    479  *  INFO | EARLY ZERO PAGE | ISA I/O MEM |
    480  * ------+-----------------+-------------+
    481  *
    482  * DUMMY PAGE is either a PDG for amd64 or a GDT for i386.
    483  *
    484  * (HYPER. SHARED INFO + EARLY ZERO PAGE + ISA I/O MEM) have no physical
    485  * addresses preallocated.
    486  */
    487 vaddr_t
    488 xen_locore(void)
    489 {
    490 	size_t nL2, oldcount, mapsize;
    491 	vaddr_t our_tables, xen_tables;
    492 	u_int descs[4];
    493 
    494 	xen_init_features();
    495 
    496 	xpmap_phys_to_machine_mapping =
    497 	    (unsigned long *)xen_start_info.mfn_list;
    498 
    499 	/* Set the NX/XD bit, if available. descs[3] = %edx. */
    500 	x86_cpuid(0x80000001, descs);
    501 	xpmap_pg_nx = (descs[3] & CPUID_NOX) ? PG_NX : 0;
    502 
    503 	/* Space after Xen boostrap tables should be free */
    504 	xen_tables = xen_start_info.pt_base;
    505 	our_tables = xen_tables + (xen_start_info.nr_pt_frames * PAGE_SIZE);
    506 
    507 	/*
    508 	 * Calculate how much space we need. First, everything mapped before
    509 	 * the Xen bootstrap tables.
    510 	 */
    511 	mapsize = xen_tables - KERNTEXTOFF;
    512 
    513 	/* After the tables we'll have:
    514 	 *  - UAREA
    515 	 *  - dummy user PGD (x86_64)
    516 	 *  - HYPERVISOR_shared_info
    517 	 *  - early_zerop
    518 	 *  - ISA I/O mem (if needed)
    519 	 */
    520 	mapsize += UPAGES * PAGE_SIZE;
    521 #ifdef __x86_64__
    522 	mapsize += PAGE_SIZE;
    523 #endif
    524 	mapsize += PAGE_SIZE;
    525 	mapsize += PAGE_SIZE;
    526 #ifdef DOM0OPS
    527 	if (xendomain_is_dom0()) {
    528 		mapsize += IOM_SIZE;
    529 	}
    530 #endif
    531 
    532 	/*
    533 	 * At this point, mapsize doesn't include the table size.
    534 	 */
    535 #ifdef __x86_64__
    536 	nL2 = TABLE_L2_ENTRIES;
    537 #else
    538 	nL2 = (mapsize + (NBPD_L2 - 1)) >> L2_SHIFT;
    539 #endif
    540 
    541 	/*
    542 	 * Now compute how many L2 pages we need exactly. This is useful only
    543 	 * on i386, since the initial count for amd64 is already enough.
    544 	 */
    545 	while (KERNTEXTOFF + mapsize + (nL2 + PDIRSZ) * PAGE_SIZE >
    546 	    KERNBASE + (nL2 << L2_SHIFT)) {
    547 		nL2++;
    548 	}
    549 
    550 #ifdef i386
    551 	/*
    552 	 * One more L2 page: we'll allocate several pages after kva_start
    553 	 * in pmap_bootstrap() before pmap_growkernel(), which have not been
    554 	 * counted here. It's not a big issue to allocate one more L2 as
    555 	 * pmap_growkernel() will be called anyway.
    556 	 */
    557 	nL2++;
    558 	nkptp[1] = nL2;
    559 #endif
    560 
    561 	/*
    562 	 * Install bootstrap pages. We may need more L2 pages than will
    563 	 * have the final table here, as it's installed after the final table.
    564 	 */
    565 	oldcount = nL2;
    566 
    567 bootstrap_again:
    568 
    569 	/*
    570 	 * Xen space we'll reclaim may not be enough for our new page tables,
    571 	 * move bootstrap tables if necessary.
    572 	 */
    573 	if (our_tables < xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE))
    574 		our_tables = xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE);
    575 
    576 	/*
    577 	 * Make sure the number of L2 pages we have is enough to map everything
    578 	 * from KERNBASE to the bootstrap tables themselves.
    579 	 */
    580 	if (our_tables + ((oldcount + PDIRSZ) * PAGE_SIZE) >
    581 	    KERNBASE + (oldcount << L2_SHIFT)) {
    582 		oldcount++;
    583 		goto bootstrap_again;
    584 	}
    585 
    586 	/* Create temporary tables */
    587 	xen_bootstrap_tables(xen_tables, our_tables,
    588 	    xen_start_info.nr_pt_frames, oldcount, false);
    589 
    590 	/* Create final tables */
    591 	xen_bootstrap_tables(our_tables, xen_tables,
    592 	    oldcount + PDIRSZ, nL2, true);
    593 
    594 	/* Zero out PROC0 UAREA and DUMMY PAGE. */
    595 	memset((void *)(xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE)), 0,
    596 	    (UPAGES + 1) * PAGE_SIZE);
    597 
    598 	/* Finally, flush TLB. */
    599 	xpq_queue_tlb_flush();
    600 
    601 	return (xen_tables + ((nL2 + PDIRSZ) * PAGE_SIZE));
    602 }
    603 
    604 /*
    605  * Build a new table and switch to it.
    606  * old_count is # of old tables (including L4, L3 and L2).
    607  * new_count is # of new tables (PTE only).
    608  * We assume the areas don't overlap.
    609  */
    610 static void
    611 xen_bootstrap_tables(vaddr_t old_pgd, vaddr_t new_pgd, size_t old_count,
    612     size_t new_count, bool final)
    613 {
    614 	pd_entry_t *L4cpu, *L4, *L3, *L2, *pte;
    615 	paddr_t addr;
    616 	vaddr_t page, avail, map_end;
    617 	int i;
    618 	extern char __rodata_start;
    619 	extern char __data_start;
    620 	extern char __kernel_end;
    621 	extern char *early_zerop; /* from pmap.c */
    622 #ifdef i386
    623 	extern union descriptor tmpgdt[];
    624 #endif
    625 
    626 	/*
    627 	 * Layout of RW area after the kernel image:
    628 	 *     xencons_interface (if present)
    629 	 *     xenstore_interface (if present)
    630 	 *     table pages (new_count + PDIRSZ entries)
    631 	 * Extra mappings (only when final is true):
    632 	 *     UAREA
    633 	 *     dummy user PGD (x86_64 only) / GDT page (i386 only)
    634 	 *     HYPERVISOR_shared_info
    635 	 *     early_zerop
    636 	 *     ISA I/O mem (if needed)
    637 	 */
    638 	map_end = new_pgd + ((new_count + PDIRSZ) * PAGE_SIZE);
    639 	if (final) {
    640 		map_end += UPAGES * PAGE_SIZE;
    641 		xen_dummy_page = (vaddr_t)map_end;
    642 		map_end += PAGE_SIZE;
    643 		HYPERVISOR_shared_info = (shared_info_t *)map_end;
    644 		map_end += PAGE_SIZE;
    645 		early_zerop = (char *)map_end;
    646 		map_end += PAGE_SIZE;
    647 	}
    648 
    649 	/*
    650 	 * We always set atdevbase, as it's used by init386 to find the first
    651 	 * available VA. map_end is updated only if we are dom0, so
    652 	 * atdevbase -> atdevbase + IOM_SIZE will be mapped only in
    653 	 * this case.
    654 	 */
    655 	if (final) {
    656 		atdevbase = map_end;
    657 #ifdef DOM0OPS
    658 		if (xendomain_is_dom0()) {
    659 			/* ISA I/O mem */
    660 			map_end += IOM_SIZE;
    661 		}
    662 #endif
    663 	}
    664 
    665 	__PRINTK(("xen_bootstrap_tables map_end 0x%lx\n", map_end));
    666 	__PRINTK(("console %#lx ", xen_start_info.console_mfn));
    667 	__PRINTK(("xenstore %#" PRIx32 "\n", xen_start_info.store_mfn));
    668 
    669 	avail = new_pgd;
    670 
    671 	/*
    672 	 * Create our page tables.
    673 	 */
    674 
    675 #ifdef __x86_64__
    676 	/* per-cpu L4 */
    677 	L4cpu = (pd_entry_t *)avail;
    678 	memset(L4cpu, 0, PAGE_SIZE);
    679 	avail += PAGE_SIZE;
    680 
    681 	/* pmap_kernel L4 */
    682 	L4 = (pd_entry_t *)avail;
    683 	memset(L4, 0, PAGE_SIZE);
    684 	avail += PAGE_SIZE;
    685 
    686 	/* L3 */
    687 	L3 = (pd_entry_t *)avail;
    688 	memset(L3, 0, PAGE_SIZE);
    689 	avail += PAGE_SIZE;
    690 
    691 	/* link L4->L3 */
    692 	addr = ((u_long)L3) - KERNBASE;
    693 	L4cpu[pl4_pi(KERNTEXTOFF)] = xpmap_ptom_masked(addr) | PTE_P | PTE_W;
    694 	L4[pl4_pi(KERNTEXTOFF)] = xpmap_ptom_masked(addr) | PTE_P | PTE_W;
    695 
    696 	/* L2 */
    697 	L2 = (pd_entry_t *)avail;
    698 	memset(L2, 0, PAGE_SIZE);
    699 	avail += PAGE_SIZE;
    700 
    701 	/* link L3->L2 */
    702 	addr = ((u_long)L2) - KERNBASE;
    703 	L3[pl3_pi(KERNTEXTOFF)] = xpmap_ptom_masked(addr) | PTE_P | PTE_W;
    704 #else
    705 	/* no L4 on i386PAE */
    706 	__USE(L4cpu);
    707 	__USE(L4);
    708 
    709 	/* L3 */
    710 	L3 = (pd_entry_t *)avail;
    711 	memset(L3, 0, PAGE_SIZE);
    712 	avail += PAGE_SIZE;
    713 
    714 	/*
    715 	 * Our PAE-style level 2, 5 contiguous pages (4 L2 + 1 shadow).
    716 	 *                  +-----------------+----------------+---------+
    717 	 * Physical layout: | 3 * USERLAND L2 | L2 KERN SHADOW | L2 KERN |
    718 	 *                  +-----------------+----------------+---------+
    719 	 * However, we enter L3[3] into L2 KERN, and not L2 KERN SHADOW.
    720 	 * This way, L2[L2_SLOT_KERN] always points to the shadow.
    721 	 */
    722 	L2 = (pd_entry_t *)avail;
    723 	memset(L2, 0, PAGE_SIZE * 5);
    724 	avail += PAGE_SIZE * 5;
    725 
    726 	/*
    727 	 * Link L2 pages in L3, with a special case for L2 KERN. Xen doesn't
    728 	 * want RW permissions in L3 entries, it'll add them itself.
    729 	 */
    730 	addr = ((u_long)L2) - KERNBASE;
    731 	for (i = 0; i < 3; i++, addr += PAGE_SIZE) {
    732 		L3[i] = xpmap_ptom_masked(addr) | PTE_P;
    733 	}
    734 	addr += PAGE_SIZE;
    735 	L3[3] = xpmap_ptom_masked(addr) | PTE_P;
    736 #endif
    737 
    738 	/* Level 1 */
    739 	page = KERNTEXTOFF;
    740 	for (i = 0; i < new_count; i ++) {
    741 		vaddr_t cur_page = page;
    742 
    743 		pte = (pd_entry_t *)avail;
    744 		memset(pte, 0, PAGE_SIZE);
    745 		avail += PAGE_SIZE;
    746 
    747 		while (pl2_pi(page) == pl2_pi(cur_page)) {
    748 			if (page >= map_end) {
    749 				/* not mapped at all */
    750 				pte[pl1_pi(page)] = 0;
    751 				page += PAGE_SIZE;
    752 				continue;
    753 			}
    754 			pte[pl1_pi(page)] = xpmap_ptom_masked(page - KERNBASE);
    755 			if (page == (vaddr_t)HYPERVISOR_shared_info) {
    756 				pte[pl1_pi(page)] = xen_start_info.shared_info;
    757 			}
    758 			if ((xpmap_ptom_masked(page - KERNBASE) >> PAGE_SHIFT)
    759 			    == xen_start_info.console.domU.mfn) {
    760 				xencons_interface = (void *)page;
    761 				pte[pl1_pi(page)] = xen_start_info.console_mfn;
    762 				pte[pl1_pi(page)] <<= PAGE_SHIFT;
    763 			}
    764 			if ((xpmap_ptom_masked(page - KERNBASE) >> PAGE_SHIFT)
    765 			    == xen_start_info.store_mfn) {
    766 				xenstore_interface = (void *)page;
    767 				pte[pl1_pi(page)] = xen_start_info.store_mfn;
    768 				pte[pl1_pi(page)] <<= PAGE_SHIFT;
    769 			}
    770 #ifdef DOM0OPS
    771 			if (page >= (vaddr_t)atdevbase &&
    772 			    page < (vaddr_t)atdevbase + IOM_SIZE) {
    773 				pte[pl1_pi(page)] =
    774 				    IOM_BEGIN + (page - (vaddr_t)atdevbase);
    775 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    776 			}
    777 #endif
    778 
    779 			pte[pl1_pi(page)] |= PTE_P;
    780 			if (page < (vaddr_t)&__rodata_start) {
    781 				/* Map the kernel text RX. Nothing to do. */
    782 			} else if (page >= (vaddr_t)&__rodata_start &&
    783 			    page < (vaddr_t)&__data_start) {
    784 				/* Map the kernel rodata R. */
    785 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    786 			} else if (page >= old_pgd &&
    787 			    page < old_pgd + (old_count * PAGE_SIZE)) {
    788 				/* Map the old page tables R. */
    789 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    790 			} else if (page >= new_pgd &&
    791 			    page < new_pgd + ((new_count + PDIRSZ) * PAGE_SIZE)) {
    792 				/* Map the new page tables R. */
    793 				pte[pl1_pi(page)] |= xpmap_pg_nx;
    794 #ifdef i386
    795 			} else if (page == (vaddr_t)tmpgdt) {
    796 				/*
    797 				 * Map bootstrap gdt R/O. Later, we will re-add
    798 				 * this page to uvm after making it writable.
    799 				 */
    800 				pte[pl1_pi(page)] = 0;
    801 				page += PAGE_SIZE;
    802 				continue;
    803 #endif
    804 			} else if (page >= (vaddr_t)&__data_start &&
    805 			    page < (vaddr_t)&__kernel_end) {
    806 				/* Map the kernel data+bss RW. */
    807 				pte[pl1_pi(page)] |= PTE_W | xpmap_pg_nx;
    808 			} else {
    809 				/* Map the page RW. */
    810 				pte[pl1_pi(page)] |= PTE_W | xpmap_pg_nx;
    811 			}
    812 
    813 			page += PAGE_SIZE;
    814 		}
    815 
    816 		addr = ((u_long)pte) - KERNBASE;
    817 		L2[pl2_pi(cur_page)] = xpmap_ptom_masked(addr) | PTE_W | PTE_P;
    818 
    819 		/* Mark readonly */
    820 		xen_bt_set_readonly((vaddr_t)pte);
    821 	}
    822 
    823 	/* Install recursive page tables mapping */
    824 #ifdef __x86_64__
    825 	/* Recursive entry in pmap_kernel(). */
    826 	L4[PDIR_SLOT_PTE] = xpmap_ptom_masked((paddr_t)L4 - KERNBASE)
    827 	    | PTE_P | xpmap_pg_nx;
    828 	/* Recursive entry in higher-level per-cpu PD. */
    829 	L4cpu[PDIR_SLOT_PTE] = xpmap_ptom_masked((paddr_t)L4cpu - KERNBASE)
    830 	    | PTE_P | xpmap_pg_nx;
    831 
    832 	/* Mark tables RO */
    833 	xen_bt_set_readonly((vaddr_t)L2);
    834 #else
    835 	/* Copy L2 KERN into L2 KERN SHADOW, and reference the latter in cpu0. */
    836 	memcpy(&L2[L2_SLOT_KERN + NPDPG], &L2[L2_SLOT_KERN], PAGE_SIZE);
    837 	cpu_info_primary.ci_kpm_pdir = &L2[L2_SLOT_KERN + NPDPG];
    838 	cpu_info_primary.ci_kpm_pdirpa =
    839 	    (vaddr_t)cpu_info_primary.ci_kpm_pdir - KERNBASE;
    840 
    841 	/*
    842 	 * We don't enter a recursive entry from the L3 PD. Instead, we enter
    843 	 * the first 4 L2 pages, which includes the kernel's L2 shadow. But we
    844 	 * have to enter the shadow after switching %cr3, or Xen will refcount
    845 	 * some PTEs with the wrong type.
    846 	 */
    847 	addr = (u_long)L2 - KERNBASE;
    848 	for (i = 0; i < 3; i++, addr += PAGE_SIZE) {
    849 		L2[PDIR_SLOT_PTE + i] = xpmap_ptom_masked(addr) | PTE_P |
    850 		    xpmap_pg_nx;
    851 	}
    852 
    853 	/* Mark tables RO, and pin L2 KERN SHADOW. */
    854 	addr = (u_long)L2 - KERNBASE;
    855 	for (i = 0; i < 5; i++, addr += PAGE_SIZE) {
    856 		xen_bt_set_readonly(((vaddr_t)L2) + PAGE_SIZE * i);
    857 	}
    858 	if (final) {
    859 		addr = (u_long)L2 - KERNBASE + 3 * PAGE_SIZE;
    860 		xpq_queue_pin_l2_table(xpmap_ptom_masked(addr));
    861 	}
    862 #endif
    863 
    864 	xen_bt_set_readonly((vaddr_t)L3);
    865 #ifdef __x86_64__
    866 	xen_bt_set_readonly((vaddr_t)L4cpu);
    867 #endif
    868 
    869 	/* Pin the PGD */
    870 #ifdef __x86_64__
    871 	xpq_queue_pin_l4_table(xpmap_ptom_masked(new_pgd - KERNBASE));
    872 #else
    873 	xpq_queue_pin_l3_table(xpmap_ptom_masked(new_pgd - KERNBASE));
    874 #endif
    875 
    876 	/* Save phys. addr of PDP, for libkvm. */
    877 #ifdef __x86_64__
    878 	PDPpaddr = (u_long)L4 - KERNBASE;
    879 #else
    880 	PDPpaddr = (u_long)L2 - KERNBASE; /* PDP is the L2 with PAE */
    881 #endif
    882 
    883 	/* Switch to new tables */
    884 	xpq_queue_pt_switch(xpmap_ptom_masked(new_pgd - KERNBASE));
    885 
    886 	if (final) {
    887 #ifdef __x86_64__
    888 		/* Save the address of the real per-cpu L4 page. */
    889 		cpu_info_primary.ci_kpm_pdir = L4cpu;
    890 		cpu_info_primary.ci_kpm_pdirpa = ((paddr_t)L4cpu - KERNBASE);
    891 #else
    892 		/* Save the address of the L3 page */
    893 		cpu_info_primary.ci_pae_l3_pdir = L3;
    894 		cpu_info_primary.ci_pae_l3_pdirpa = (new_pgd - KERNBASE);
    895 
    896 		/* Now enter the kernel's PTE mappings */
    897 		addr = (u_long)L2 - KERNBASE + PAGE_SIZE * 3;
    898 		xpq_queue_pte_update(
    899 		    xpmap_ptom(((vaddr_t)&L2[PDIR_SLOT_PTE + 3]) - KERNBASE),
    900 		    xpmap_ptom_masked(addr) | PTE_P);
    901 		xpq_flush_queue();
    902 #endif
    903 	}
    904 
    905 	/*
    906 	 * Now we can safely reclaim the space taken by the old tables.
    907 	 */
    908 
    909 	/* Unpin old PGD */
    910 	xpq_queue_unpin_table(xpmap_ptom_masked(old_pgd - KERNBASE));
    911 
    912 	/* Mark old tables RW */
    913 	page = old_pgd;
    914 	addr = xpmap_mtop((paddr_t)L2[pl2_pi(page)] & PG_FRAME);
    915 	pte = (pd_entry_t *)((u_long)addr + KERNBASE);
    916 	pte += pl1_pi(page);
    917 	while (page < old_pgd + (old_count * PAGE_SIZE) && page < map_end) {
    918 		addr = xpmap_ptom(((u_long)pte) - KERNBASE);
    919 		xpq_queue_pte_update(addr, *pte | PTE_W);
    920 		page += PAGE_SIZE;
    921 		/*
    922 		 * Our PTEs are contiguous so it's safe to just "++" here.
    923 		 */
    924 		pte++;
    925 	}
    926 	xpq_flush_queue();
    927 }
    928 
    929 /*
    930  * Mark a page read-only, assuming vaddr = paddr + KERNBASE.
    931  */
    932 static void
    933 xen_bt_set_readonly(vaddr_t page)
    934 {
    935 	pt_entry_t entry;
    936 
    937 	entry = xpmap_ptom_masked(page - KERNBASE);
    938 	entry |= PTE_P | xpmap_pg_nx;
    939 
    940 	HYPERVISOR_update_va_mapping(page, entry, UVMF_INVLPG);
    941 }
    942 
    943 #ifdef __x86_64__
    944 void
    945 xen_set_user_pgd(paddr_t page)
    946 {
    947 	struct mmuext_op op;
    948 	int s = splvm(); /* XXXSMP */
    949 
    950 	xpq_flush_queue();
    951 	op.cmd = MMUEXT_NEW_USER_BASEPTR;
    952 	op.arg1.mfn = xpmap_ptom_masked(page) >> PAGE_SHIFT;
    953 	if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF) < 0)
    954 		panic("xen_set_user_pgd: failed to install new user page"
    955 			" directory %#" PRIxPADDR, page);
    956 	splx(s);
    957 }
    958 #endif /* __x86_64__ */
    959