]> git.saurik.com Git - apple/xnu.git/blobdiff - osfmk/x86_64/pmap.c
xnu-2782.1.97.tar.gz
[apple/xnu.git] / osfmk / x86_64 / pmap.c
index 147372eff5f76acce3817936439816d491451c1e..8e1b559025c4e5ef95448b0070906cd573ad0d51 100644 (file)
@@ -89,7 +89,6 @@
  */
 
 #include <string.h>
-#include <mach_kdb.h>
 #include <mach_ldebug.h>
 
 #include <libkern/OSAtomic.h>
 #include <kern/thread.h>
 #include <kern/zalloc.h>
 #include <kern/queue.h>
+#include <kern/ledger.h>
 #include <kern/mach_param.h>
 
-#include <kern/lock.h>
 #include <kern/kalloc.h>
 #include <kern/spl.h>
 
 #include <i386/pmap_internal.h>
 #include <i386/pmap_pcid.h>
 
-#if    MACH_KDB
-#include <ddb/db_command.h>
-#include <ddb/db_output.h>
-#include <ddb/db_sym.h>
-#include <ddb/db_print.h>
-#endif /* MACH_KDB */
-
 #include <vm/vm_protos.h>
 
 #include <i386/mp.h>
 #include <i386/mp_desc.h>
+#include <libkern/kernel_mach_header.h>
+
+#include <pexpert/i386/efi.h>
 
 
 #ifdef IWANTTODEBUG
@@ -178,7 +173,7 @@ uint64_t max_preemption_latency_tsc = 0;
 
 pv_hashed_entry_t     *pv_hash_table;  /* hash lists */
 
-uint32_t npvhash = 0;
+uint32_t npvhashmask = 0, npvhashbuckets = 0;
 
 pv_hashed_entry_t      pv_hashed_free_list = PV_HASHED_ENTRY_NULL;
 pv_hashed_entry_t      pv_hashed_kern_free_list = PV_HASHED_ENTRY_NULL;
@@ -186,6 +181,8 @@ decl_simple_lock_data(,pv_hashed_free_list_lock)
 decl_simple_lock_data(,pv_hashed_kern_free_list_lock)
 decl_simple_lock_data(,pv_hash_table_lock)
 
+decl_simple_lock_data(,phys_backup_lock)
+
 zone_t         pv_hashed_list_zone;    /* zone of pv_hashed_entry structures */
 
 /*
@@ -204,7 +201,7 @@ static struct vm_object kpdptobj_object_store;
  *     One byte per physical page.
  */
 char           *pmap_phys_attributes;
-unsigned int   last_managed_page = 0;
+ppnum_t                last_managed_page = 0;
 
 /*
  *     Amount of virtual memory mapped by one
@@ -226,9 +223,6 @@ pmap_memory_region_t pmap_memory_regions[PMAP_MEMORY_REGIONS_SIZE];
 struct pmap    kernel_pmap_store;
 pmap_t         kernel_pmap;
 
-pd_entry_t     high_shared_pde;
-pd_entry_t     commpage64_pde;
-
 struct zone    *pmap_zone;             /* zone of pmap structures */
 
 struct zone    *pmap_anchor_zone;
@@ -252,12 +246,11 @@ pt_entry_t     *DMAP1, *DMAP2;
 caddr_t         DADDR1;
 caddr_t         DADDR2;
 
-/*
- * unlinks the pv_hashed_entry_t pvh from the singly linked hash chain.
- * properly deals with the anchor.
- * must be called with the hash locked, does not unlock it
- */
+const boolean_t        pmap_disable_kheap_nx = FALSE;
+const boolean_t        pmap_disable_kstack_nx = FALSE;
+extern boolean_t doconstro_override;
 
+extern long __stack_chk_guard[];
 
 /*
  *     Map memory at initialization.  The physical addresses being
@@ -279,7 +272,7 @@ pmap_map(
        ps = PAGE_SIZE;
        while (start_addr < end_addr) {
                pmap_enter(kernel_pmap, (vm_map_offset_t)virt,
-                          (ppnum_t) i386_btop(start_addr), prot, flags, FALSE);
+                          (ppnum_t) i386_btop(start_addr), prot, VM_PROT_NONE, flags, TRUE);
                virt += ps;
                start_addr += ps;
        }
@@ -293,15 +286,18 @@ extern  vm_offset_t               sHIB;
 extern  vm_offset_t            eHIB;
 extern  vm_offset_t            stext;
 extern  vm_offset_t            etext;
-extern  vm_offset_t            sdata;
+extern  vm_offset_t            sdata, edata;
+extern  vm_offset_t            sconstdata, econstdata;
 
 extern void                    *KPTphys;
 
 boolean_t pmap_smep_enabled = FALSE;
+boolean_t pmap_smap_enabled = FALSE;
 
 void
 pmap_cpu_init(void)
 {
+       cpu_data_t      *cdp = current_cpu_datap();
        /*
         * Here early in the life of a processor (from cpu_mode_init()).
         * Ensure global page feature is disabled at this point.
@@ -312,10 +308,10 @@ pmap_cpu_init(void)
        /*
         * Initialize the per-cpu, TLB-related fields.
         */
-       current_cpu_datap()->cpu_kernel_cr3 = kernel_pmap->pm_cr3;
-       current_cpu_datap()->cpu_active_cr3 = kernel_pmap->pm_cr3;
-       current_cpu_datap()->cpu_tlb_invalid = FALSE;
-       current_cpu_datap()->cpu_task_map = TASK_MAP_64BIT;
+       cdp->cpu_kernel_cr3 = kernel_pmap->pm_cr3;
+       cdp->cpu_active_cr3 = kernel_pmap->pm_cr3;
+       cdp->cpu_tlb_invalid = FALSE;
+       cdp->cpu_task_map = TASK_MAP_64BIT;
        pmap_pcid_configure();
        if (cpuid_leaf7_features() & CPUID_LEAF7_FEATURE_SMEP) {
                boolean_t nsmep;
@@ -324,9 +320,25 @@ pmap_cpu_init(void)
                        pmap_smep_enabled = TRUE;
                }
        }
+
+       if (cdp->cpu_fixed_pmcs_enabled) {
+               boolean_t enable = TRUE;
+               cpu_pmc_control(&enable);
+       }
 }
 
+static uint32_t pmap_scale_shift(void) {
+       uint32_t scale = 0;
 
+       if (sane_size <= 8*GB) {
+               scale = (uint32_t)(sane_size / (2 * GB));
+       } else if (sane_size <= 32*GB) {
+               scale = 4 + (uint32_t)((sane_size - (8 * GB))/ (4 * GB)); 
+       } else {
+               scale = 10 + (uint32_t)MIN(4, ((sane_size - (32 * GB))/ (8 * GB))); 
+       }
+       return scale;
+}
 
 /*
  *     Bootstrap the system enough to run with virtual memory.
@@ -355,7 +367,7 @@ pmap_bootstrap(
 
        kernel_pmap = &kernel_pmap_store;
        kernel_pmap->ref_count = 1;
-       kernel_pmap->nx_enabled = FALSE;
+       kernel_pmap->nx_enabled = TRUE;
        kernel_pmap->pm_task_map = TASK_MAP_64BIT;
        kernel_pmap->pm_obj = (vm_object_t) NULL;
        kernel_pmap->dirbase = (pd_entry_t *)((uintptr_t)IdlePTD);
@@ -411,21 +423,23 @@ pmap_bootstrap(
 
        virtual_avail = va;
 #endif
+       if (!PE_parse_boot_argn("npvhash", &npvhashmask, sizeof (npvhashmask))) {
+               npvhashmask = ((NPVHASHBUCKETS) << pmap_scale_shift()) - 1;
 
-       if (PE_parse_boot_argn("npvhash", &npvhash, sizeof (npvhash))) {
-               if (0 != ((npvhash + 1) & npvhash)) {
-                       kprintf("invalid hash %d, must be ((2^N)-1), "
-                               "using default %d\n", npvhash, NPVHASH);
-                       npvhash = NPVHASH;
-               }
-       } else {
-               npvhash = NPVHASH;
+       }
+
+       npvhashbuckets = npvhashmask + 1;
+
+       if (0 != ((npvhashbuckets) & npvhashmask)) {
+               panic("invalid hash %d, must be ((2^N)-1), "
+                   "using default %d\n", npvhashmask, NPVHASHMASK);
        }
 
        simple_lock_init(&kernel_pmap->lock, 0);
        simple_lock_init(&pv_hashed_free_list_lock, 0);
        simple_lock_init(&pv_hashed_kern_free_list_lock, 0);
        simple_lock_init(&pv_hash_table_lock,0);
+       simple_lock_init(&phys_backup_lock, 0);
 
        pmap_cpu_init();
 
@@ -435,6 +449,27 @@ pmap_bootstrap(
        if (pmap_smep_enabled)
                printf("PMAP: Supervisor Mode Execute Protection enabled\n");
 
+#if    DEBUG
+       printf("Stack canary: 0x%lx\n", __stack_chk_guard[0]);
+       printf("early_random(): 0x%qx\n", early_random());
+#endif
+       boolean_t ptmp;
+       /* Check if the user has requested disabling stack or heap no-execute
+        * enforcement. These are "const" variables; that qualifier is cast away
+        * when altering them. The TEXT/DATA const sections are marked
+        * write protected later in the kernel startup sequence, so altering
+        * them is possible at this point, in pmap_bootstrap().
+        */
+       if (PE_parse_boot_argn("-pmap_disable_kheap_nx", &ptmp, sizeof(ptmp))) {
+               boolean_t *pdknxp = (boolean_t *) &pmap_disable_kheap_nx;
+               *pdknxp = TRUE;
+       }
+
+       if (PE_parse_boot_argn("-pmap_disable_kstack_nx", &ptmp, sizeof(ptmp))) {
+               boolean_t *pdknhp = (boolean_t *) &pmap_disable_kstack_nx;
+               *pdknhp = TRUE;
+       }
+
        boot_args *args = (boot_args *)PE_state.bootArgs;
        if (args->efiMode == kBootArgsEfiMode32) {
                printf("EFI32: kernel virtual space limited to 4GB\n");
@@ -473,6 +508,131 @@ pmap_virtual_space(
        *endp = virtual_end;
 }
 
+
+
+
+#if HIBERNATION
+
+#include <IOKit/IOHibernatePrivate.h>
+
+int32_t                pmap_npages;
+int32_t                pmap_teardown_last_valid_compact_indx = -1;
+
+
+void   hibernate_rebuild_pmap_structs(void);
+void   hibernate_teardown_pmap_structs(addr64_t *, addr64_t *);
+void   pmap_pack_index(uint32_t);
+int32_t        pmap_unpack_index(pv_rooted_entry_t);
+
+
+int32_t
+pmap_unpack_index(pv_rooted_entry_t pv_h)
+{
+       int32_t indx = 0;
+
+       indx = (int32_t)(*((uint64_t *)(&pv_h->qlink.next)) >> 48);
+       indx = indx << 16;
+       indx |= (int32_t)(*((uint64_t *)(&pv_h->qlink.prev)) >> 48);
+       
+       *((uint64_t *)(&pv_h->qlink.next)) |= ((uint64_t)0xffff << 48);
+       *((uint64_t *)(&pv_h->qlink.prev)) |= ((uint64_t)0xffff << 48);
+
+       return (indx);
+}
+
+
+void
+pmap_pack_index(uint32_t indx)
+{
+       pv_rooted_entry_t       pv_h;
+
+       pv_h = &pv_head_table[indx];
+
+       *((uint64_t *)(&pv_h->qlink.next)) &= ~((uint64_t)0xffff << 48);
+       *((uint64_t *)(&pv_h->qlink.prev)) &= ~((uint64_t)0xffff << 48);
+
+       *((uint64_t *)(&pv_h->qlink.next)) |= ((uint64_t)(indx >> 16)) << 48;
+       *((uint64_t *)(&pv_h->qlink.prev)) |= ((uint64_t)(indx & 0xffff)) << 48;
+}
+
+
+void
+hibernate_teardown_pmap_structs(addr64_t *unneeded_start, addr64_t *unneeded_end)
+{
+       int32_t         i;
+       int32_t         compact_target_indx;
+
+       compact_target_indx = 0;
+
+       for (i = 0; i < pmap_npages; i++) {
+               if (pv_head_table[i].pmap == PMAP_NULL) {
+
+                       if (pv_head_table[compact_target_indx].pmap != PMAP_NULL)
+                               compact_target_indx = i;
+               } else {
+                       pmap_pack_index((uint32_t)i);
+
+                       if (pv_head_table[compact_target_indx].pmap == PMAP_NULL) {
+                               /*
+                                 * we've got a hole to fill, so
+                                 * move this pv_rooted_entry_t to it's new home
+                                 */
+                               pv_head_table[compact_target_indx] = pv_head_table[i];
+                               pv_head_table[i].pmap = PMAP_NULL;
+                               
+                               pmap_teardown_last_valid_compact_indx = compact_target_indx;
+                               compact_target_indx++;
+                       } else
+                               pmap_teardown_last_valid_compact_indx = i;
+               }
+       }
+       *unneeded_start = (addr64_t)&pv_head_table[pmap_teardown_last_valid_compact_indx+1];
+       *unneeded_end = (addr64_t)&pv_head_table[pmap_npages-1];
+       
+       HIBLOG("hibernate_teardown_pmap_structs done: last_valid_compact_indx %d\n", pmap_teardown_last_valid_compact_indx);
+}
+
+
+void
+hibernate_rebuild_pmap_structs(void)
+{
+       int32_t                 cindx, eindx, rindx;
+       pv_rooted_entry_t       pv_h;
+
+       eindx = (int32_t)pmap_npages;
+
+       for (cindx = pmap_teardown_last_valid_compact_indx; cindx >= 0; cindx--) {
+
+               pv_h = &pv_head_table[cindx];
+
+               rindx = pmap_unpack_index(pv_h);
+               assert(rindx < pmap_npages);
+
+               if (rindx != cindx) {
+                       /*
+                        * this pv_rooted_entry_t was moved by hibernate_teardown_pmap_structs,
+                        * so move it back to its real location
+                        */
+                       pv_head_table[rindx] = pv_head_table[cindx];
+               }
+               if (rindx+1 != eindx) {
+                       /*
+                        * the 'hole' between this vm_rooted_entry_t and the previous
+                        * vm_rooted_entry_t we moved needs to be initialized as 
+                        * a range of zero'd vm_rooted_entry_t's
+                        */
+                       bzero((char *)&pv_head_table[rindx+1], (eindx - rindx - 1) * sizeof (struct pv_rooted_entry));
+               }
+               eindx = rindx;
+       }
+       if (rindx)
+               bzero ((char *)&pv_head_table[0], rindx * sizeof (struct pv_rooted_entry));
+
+       HIBLOG("hibernate_rebuild_pmap_structs done: last_valid_compact_indx %d\n", pmap_teardown_last_valid_compact_indx);
+}
+
+#endif
+
 /*
  *     Initialize the pmap module.
  *     Called by vm_init, to initialize any structures that the pmap
@@ -489,13 +649,13 @@ pmap_init(void)
 
 
        kernel_pmap->pm_obj_pml4 = &kpml4obj_object_store;
-       _vm_object_allocate((vm_object_size_t)NPML4PGS, &kpml4obj_object_store);
+       _vm_object_allocate((vm_object_size_t)NPML4PGS * PAGE_SIZE, &kpml4obj_object_store);
 
        kernel_pmap->pm_obj_pdpt = &kpdptobj_object_store;
-       _vm_object_allocate((vm_object_size_t)NPDPTPGS, &kpdptobj_object_store);
+       _vm_object_allocate((vm_object_size_t)NPDPTPGS * PAGE_SIZE, &kpdptobj_object_store);
 
        kernel_pmap->pm_obj = &kptobj_object_store;
-       _vm_object_allocate((vm_object_size_t)NPDEPGS, &kptobj_object_store);
+       _vm_object_allocate((vm_object_size_t)NPDEPGS * PAGE_SIZE, &kptobj_object_store);
 
        /*
         *      Allocate memory for the pv_head_table and its lock bits,
@@ -508,10 +668,13 @@ pmap_init(void)
         */
 
        npages = i386_btop(avail_end);
+#if HIBERNATION
+       pmap_npages = (uint32_t)npages;
+#endif 
        s = (vm_size_t) (sizeof(struct pv_rooted_entry) * npages
-                        + (sizeof (struct pv_hashed_entry_t *) * (npvhash+1))
+                        + (sizeof (struct pv_hashed_entry_t *) * (npvhashbuckets))
                         + pv_lock_table_size(npages)
-                        + pv_hash_lock_table_size((npvhash+1))
+                        + pv_hash_lock_table_size((npvhashbuckets))
                                + npages);
 
        s = round_page(s);
@@ -526,7 +689,7 @@ pmap_init(void)
        vsize = s;
 
 #if PV_DEBUG
-       if (0 == npvhash) panic("npvhash not initialized");
+       if (0 == npvhashmask) panic("npvhashmask not initialized");
 #endif
 
        /*
@@ -536,13 +699,13 @@ pmap_init(void)
        addr = (vm_offset_t) (pv_head_table + npages);
 
        pv_hash_table = (pv_hashed_entry_t *)addr;
-       addr = (vm_offset_t) (pv_hash_table + (npvhash + 1));
+       addr = (vm_offset_t) (pv_hash_table + (npvhashbuckets));
 
        pv_lock_table = (char *) addr;
        addr = (vm_offset_t) (pv_lock_table + pv_lock_table_size(npages));
 
        pv_hash_lock_table = (char *) addr;
-       addr = (vm_offset_t) (pv_hash_lock_table + pv_hash_lock_table_size((npvhash+1)));
+       addr = (vm_offset_t) (pv_hash_lock_table + pv_hash_lock_table_size((npvhashbuckets)));
 
        pmap_phys_attributes = (char *) addr;
 
@@ -552,7 +715,7 @@ pmap_init(void)
        for (i = 0; i < pmap_memory_region_count; i++, pmptr++) {
                if (pmptr->type != kEfiConventionalMemory)
                        continue;
-               unsigned int pn;
+               ppnum_t pn;
                for (pn = pmptr->base; pn <= pmptr->end; pn++) {
                        if (pn < last_pn) {
                                pmap_phys_attributes[pn] |= PHYS_MANAGED;
@@ -584,13 +747,12 @@ pmap_init(void)
        pmap_anchor_zone = zinit(PAGE_SIZE, task_max, PAGE_SIZE, "pagetable anchors");
        zone_change(pmap_anchor_zone, Z_NOENCRYPT, TRUE);
 
-#if    ZONE_DEBUG
        /* The anchor is required to be page aligned. Zone debugging adds
-        * padding which may violate that requirement. Disable it
-        * to avoid assumptions.
+        * padding which may violate that requirement. Tell the zone
+        * subsystem that alignment is required.
         */
-       zone_debug_disable(pmap_anchor_zone);
-#endif 
+
+       zone_change(pmap_anchor_zone, Z_ALIGNMENT_REQUIRED, TRUE);
 
        s = (vm_size_t) sizeof(struct pv_hashed_entry);
        pv_hashed_list_zone = zinit(s, 10000*s /* Expandable zone */,
@@ -619,7 +781,41 @@ pmap_init(void)
         * Ensure the kernel's PML4 entry exists for the basement
         * before this is shared with any user.
         */
-       pmap_expand_pml4(kernel_pmap, KERNEL_BASEMENT);
+       pmap_expand_pml4(kernel_pmap, KERNEL_BASEMENT, PMAP_EXPAND_OPTIONS_NONE);
+}
+
+static
+void pmap_mark_range(pmap_t npmap, uint64_t sv, uint64_t nxrosz, boolean_t NX, boolean_t ro) {
+       uint64_t ev = sv + nxrosz, cv = sv;
+       pd_entry_t *pdep;
+       pt_entry_t *ptep = NULL;
+
+       assert(((sv & 0xFFFULL) | (nxrosz & 0xFFFULL)) == 0);
+
+       for (pdep = pmap_pde(npmap, cv); pdep != NULL && (cv < ev);) {
+               uint64_t pdev = (cv & ~((uint64_t)PDEMASK));
+
+               if (*pdep & INTEL_PTE_PS) {
+                       if (NX)
+                               *pdep |= INTEL_PTE_NX;
+                       if (ro)
+                               *pdep &= ~INTEL_PTE_WRITE;
+                       cv += NBPD;
+                       cv &= ~((uint64_t) PDEMASK);
+                       pdep = pmap_pde(npmap, cv);
+                       continue;
+               }
+
+               for (ptep = pmap_pte(npmap, cv); ptep != NULL && (cv < (pdev + NBPD)) && (cv < ev);) {
+                       if (NX)
+                               *ptep |= INTEL_PTE_NX;
+                       if (ro)
+                               *ptep &= ~INTEL_PTE_WRITE;
+                       cv += NBPT;
+                       ptep = pmap_pte(npmap, cv);
+               }
+       }
+       DPRINTF("%s(0x%llx, 0x%llx, %u, %u): 0x%llx, 0x%llx\n", __FUNCTION__, sv, nxrosz, NX, ro, cv, ptep ? *ptep: 0);
 }
 
 /*
@@ -667,50 +863,75 @@ pmap_init(void)
  * 4K pages covering [stext,etext] are coalesced as 2M large pages.
  * The now unused level-1 PTE pages are also freed.
  */
-extern uint32_t pmap_reserved_ranges;
+extern ppnum_t vm_kernel_base_page;
 void
 pmap_lowmem_finalize(void)
 {
        spl_t           spl;
        int             i;
 
-       /* Check the kernel is linked at the expected base address */
-       if (i386_btop(kvtophys((vm_offset_t) &IdlePML4)) !=
-           I386_KERNEL_IMAGE_BASE_PAGE)
-               panic("pmap_lowmem_finalize() unexpected kernel base address");
-
        /*
         * Update wired memory statistics for early boot pages
         */
-       PMAP_ZINFO_PALLOC(bootstrap_wired_pages * PAGE_SIZE);
+       PMAP_ZINFO_PALLOC(kernel_pmap, bootstrap_wired_pages * PAGE_SIZE);
 
        /*
-        * Free all pages in pmap regions below the base:
+        * Free pages in pmap regions below the base:
         * rdar://6332712
         *      We can't free all the pages to VM that EFI reports available.
         *      Pages in the range 0xc0000-0xff000 aren't safe over sleep/wake.
         *      There's also a size miscalculation here: pend is one page less
         *      than it should be but this is not fixed to be backwards
         *      compatible.
-        *      Due to this current EFI limitation, we take only the first
-        *      entry in the memory region table. However, the loop is retained
-        *      (with the intended termination criteria commented out) in the
-        *      hope that some day we can free all low-memory ranges.
+        * This is important for KASLR because up to 256*2MB = 512MB of space
+        * needs has to be released to VM.
         */
        for (i = 0;
-//          pmap_memory_regions[i].end <= I386_KERNEL_IMAGE_BASE_PAGE;
-            i < 1  && (pmap_reserved_ranges == 0);
+            pmap_memory_regions[i].end < vm_kernel_base_page;
             i++) {
-               vm_offset_t     pbase = (vm_offset_t)i386_ptob(pmap_memory_regions[i].base);
-               vm_offset_t     pend  = (vm_offset_t)i386_ptob(pmap_memory_regions[i].end);
-//             vm_offset_t     pend  = i386_ptob(pmap_memory_regions[i].end+1);
+               vm_offset_t     pbase = i386_ptob(pmap_memory_regions[i].base);
+               vm_offset_t     pend  = i386_ptob(pmap_memory_regions[i].end+1);
+
+               DBG("pmap region %d [%p..[%p\n",
+                   i, (void *) pbase, (void *) pend);
 
-               DBG("ml_static_mfree(%p,%p) for pmap region %d\n",
+               if (pmap_memory_regions[i].attribute & EFI_MEMORY_KERN_RESERVED)
+                       continue;
+               /*
+                * rdar://6332712
+                * Adjust limits not to free pages in range 0xc0000-0xff000.
+                */
+               if (pbase >= 0xc0000 && pend <= 0x100000)
+                       continue;
+               if (pbase < 0xc0000 && pend > 0x100000) {
+                       /* page range entirely within region, free lower part */
+                       DBG("- ml_static_mfree(%p,%p)\n",
+                           (void *) ml_static_ptovirt(pbase),
+                           (void *) (0xc0000-pbase));
+                       ml_static_mfree(ml_static_ptovirt(pbase),0xc0000-pbase);
+                       pbase = 0x100000;
+               }
+               if (pbase < 0xc0000)
+                       pend = MIN(pend, 0xc0000);
+               if (pend  > 0x100000)
+                       pbase = MAX(pbase, 0x100000);
+               DBG("- ml_static_mfree(%p,%p)\n",
                    (void *) ml_static_ptovirt(pbase),
-                   (void *) (pend - pbase), i);
+                   (void *) (pend - pbase));
                ml_static_mfree(ml_static_ptovirt(pbase), pend - pbase);
        }
 
+       /* A final pass to get rid of all initial identity mappings to
+        * low pages.
+        */
+       DPRINTF("%s: Removing mappings from 0->0x%lx\n", __FUNCTION__, vm_kernel_base);
+
+       /*
+        * Remove all mappings past the boot-cpu descriptor aliases and low globals.
+        * Non-boot-cpu GDT aliases will be remapped later as needed. 
+        */
+       pmap_remove(kernel_pmap, LOWGLOBAL_ALIAS + PAGE_SIZE, vm_kernel_base);
+
        /*
         * If text and data are both 2MB-aligned,
         * we can map text with large-pages,
@@ -746,7 +967,7 @@ pmap_lowmem_finalize(void)
 
                        ptep = pmap_pte(kernel_pmap, (vm_map_offset_t)myva);
                        if (ptep)
-                               pmap_store_pte(ptep, *ptep & ~INTEL_PTE_RW);
+                               pmap_store_pte(ptep, *ptep & ~INTEL_PTE_WRITE);
                }
        }
 
@@ -784,7 +1005,7 @@ pmap_lowmem_finalize(void)
                        pde |= pte_phys;        /* take page frame from pte */
 
                        if (wpkernel)
-                               pde &= ~INTEL_PTE_RW;
+                               pde &= ~INTEL_PTE_WRITE;
                        DBG("pmap_store_pte(%p,0x%llx)\n",
                                (void *)pdep, pde);
                        pmap_store_pte(pdep, pde);
@@ -807,19 +1028,98 @@ pmap_lowmem_finalize(void)
                pmap_kernel_text_ps = I386_LPGBYTES;
        }
 
-       /* map lowmem global page into fixed addr */
-       pt_entry_t *pte = NULL;
-       if (0 == (pte = pmap_pte(kernel_pmap,
-                                VM_MIN_KERNEL_LOADED_ADDRESS + 0x2000)))
-               panic("lowmem pte");
-       /* make sure it is defined on page boundary */
-       assert(0 == ((vm_offset_t) &lowGlo & PAGE_MASK));
-       pmap_store_pte(pte, kvtophys((vm_offset_t)&lowGlo)
-                               | INTEL_PTE_REF
-                               | INTEL_PTE_MOD
-                               | INTEL_PTE_WIRED
-                               | INTEL_PTE_VALID
-                               | INTEL_PTE_RW);
+       boolean_t doconstro = TRUE;
+
+       (void) PE_parse_boot_argn("dataconstro", &doconstro, sizeof(doconstro));
+
+       if ((sconstdata | econstdata) & PAGE_MASK) {
+               kprintf("Const DATA misaligned 0x%lx 0x%lx\n", sconstdata, econstdata);
+               if ((sconstdata & PAGE_MASK) || (doconstro_override == FALSE))
+                       doconstro = FALSE;
+       }
+
+       if ((sconstdata > edata) || (sconstdata < sdata) || ((econstdata - sconstdata) >= (edata - sdata))) {
+               kprintf("Const DATA incorrect size 0x%lx 0x%lx 0x%lx 0x%lx\n", sconstdata, econstdata, sdata, edata);
+               doconstro = FALSE;
+       }
+
+       if (doconstro)
+               kprintf("Marking const DATA read-only\n");
+
+       vm_offset_t dva;
+
+       for (dva = sdata; dva < edata; dva += I386_PGBYTES) {
+               assert(((sdata | edata) & PAGE_MASK) == 0);
+               if ( (sdata | edata) & PAGE_MASK) {
+                       kprintf("DATA misaligned, 0x%lx, 0x%lx\n", sdata, edata);
+                       break;
+               }
+
+               pt_entry_t dpte, *dptep = pmap_pte(kernel_pmap, dva);
+
+               dpte = *dptep;
+
+               assert((dpte & INTEL_PTE_VALID));
+               if ((dpte & INTEL_PTE_VALID) == 0) {
+                       kprintf("Missing data mapping 0x%lx 0x%lx 0x%lx\n", dva, sdata, edata);
+                       continue;
+               }
+
+               dpte |= INTEL_PTE_NX;
+               if (doconstro && (dva >= sconstdata) && (dva < econstdata)) {
+                       dpte &= ~INTEL_PTE_WRITE;
+               }
+               pmap_store_pte(dptep, dpte);
+       }
+       kernel_segment_command_t * seg;
+       kernel_section_t         * sec;
+
+       for (seg = firstseg(); seg != NULL; seg = nextsegfromheader(&_mh_execute_header, seg)) {
+               if (!strcmp(seg->segname, "__TEXT") ||
+                   !strcmp(seg->segname, "__DATA")) {
+                       continue;
+               }
+               //XXX
+               if (!strcmp(seg->segname, "__KLD")) {
+                       continue;
+               }
+               if (!strcmp(seg->segname, "__HIB")) {
+                       for (sec = firstsect(seg); sec != NULL; sec = nextsect(seg, sec)) {
+                               if (sec->addr & PAGE_MASK)
+                                       panic("__HIB segment's sections misaligned");
+                               if (!strcmp(sec->sectname, "__text")) {
+                                       pmap_mark_range(kernel_pmap, sec->addr, round_page(sec->size), FALSE, TRUE);
+                               } else {
+                                       pmap_mark_range(kernel_pmap, sec->addr, round_page(sec->size), TRUE, FALSE);
+                               }
+                       }
+               } else {
+                       pmap_mark_range(kernel_pmap, seg->vmaddr, round_page_64(seg->vmsize), TRUE, FALSE);
+               }
+       }
+
+       /*
+        * If we're debugging, map the low global vector page at the fixed
+        * virtual address.  Otherwise, remove the mapping for this.
+        */
+       if (debug_boot_arg) {
+               pt_entry_t *pte = NULL;
+               if (0 == (pte = pmap_pte(kernel_pmap, LOWGLOBAL_ALIAS)))
+                       panic("lowmem pte");
+               /* make sure it is defined on page boundary */
+               assert(0 == ((vm_offset_t) &lowGlo & PAGE_MASK));
+               pmap_store_pte(pte, kvtophys((vm_offset_t)&lowGlo)
+                                       | INTEL_PTE_REF
+                                       | INTEL_PTE_MOD
+                                       | INTEL_PTE_WIRED
+                                       | INTEL_PTE_VALID
+                                       | INTEL_PTE_WRITE
+                                       | INTEL_PTE_NX);
+       } else {
+               pmap_remove(kernel_pmap,
+                           LOWGLOBAL_ALIAS, LOWGLOBAL_ALIAS + PAGE_SIZE);
+       }
+       
        splx(spl);
        if (pmap_pcid_ncpus)
                tlb_flush_global();
@@ -908,6 +1208,7 @@ pmap_is_empty(
  */
 pmap_t
 pmap_create(
+       ledger_t                ledger,
            vm_map_size_t       sz,
            boolean_t           is_64bit)
 {
@@ -936,16 +1237,23 @@ pmap_create(
        bzero(p, sizeof(*p));
        /* init counts now since we'll be bumping some */
        simple_lock_init(&p->lock, 0);
+#if 00
        p->stats.resident_count = 0;
        p->stats.resident_max = 0;
        p->stats.wired_count = 0;
+#else
+       bzero(&p->stats, sizeof (p->stats));
+#endif
        p->ref_count = 1;
        p->nx_enabled = 1;
        p->pm_shared = FALSE;
+       ledger_reference(ledger);
+       p->ledger = ledger;
 
        p->pm_task_map = is_64bit ? TASK_MAP_64BIT : TASK_MAP_32BIT;;
        if (pmap_pcid_ncpus)
                pmap_pcid_initialize(p);
+
        p->pm_pml4 = zalloc(pmap_anchor_zone);
 
        pmap_assert((((uintptr_t)p->pm_pml4) & PAGE_MASK) == 0);
@@ -956,15 +1264,15 @@ pmap_create(
 
        /* allocate the vm_objs to hold the pdpt, pde and pte pages */
 
-       p->pm_obj_pml4 = vm_object_allocate((vm_object_size_t)(NPML4PGS));
+       p->pm_obj_pml4 = vm_object_allocate((vm_object_size_t)(NPML4PGS) * PAGE_SIZE);
        if (NULL == p->pm_obj_pml4)
                panic("pmap_create pdpt obj");
 
-       p->pm_obj_pdpt = vm_object_allocate((vm_object_size_t)(NPDPTPGS));
+       p->pm_obj_pdpt = vm_object_allocate((vm_object_size_t)(NPDPTPGS) * PAGE_SIZE);
        if (NULL == p->pm_obj_pdpt)
                panic("pmap_create pdpt obj");
 
-       p->pm_obj = vm_object_allocate((vm_object_size_t)(NPDEPGS));
+       p->pm_obj = vm_object_allocate((vm_object_size_t)(NPDEPGS) * PAGE_SIZE);
        if (NULL == p->pm_obj)
                panic("pmap_create pte obj");
 
@@ -973,7 +1281,7 @@ pmap_create(
        kpml4 = kernel_pmap->pm_pml4;
        pml4[KERNEL_PML4_INDEX]    = kpml4[KERNEL_PML4_INDEX];
        pml4[KERNEL_KEXTS_INDEX]   = kpml4[KERNEL_KEXTS_INDEX];
-       pml4[KERNEL_PHYSMAP_INDEX] = kpml4[KERNEL_PHYSMAP_INDEX];
+       pml4[KERNEL_PHYSMAP_PML4_INDEX] = kpml4[KERNEL_PHYSMAP_PML4_INDEX];
 
        PMAP_TRACE(PMAP_CODE(PMAP__CREATE) | DBG_FUNC_START,
                   p, is_64bit, 0, 0, 0);
@@ -1043,8 +1351,8 @@ pmap_destroy(pmap_t       p)
        vm_object_deallocate(p->pm_obj);
 
        OSAddAtomic(-inuse_ptepages,  &inuse_ptepages_count);
-       PMAP_ZINFO_PFREE(inuse_ptepages * PAGE_SIZE);
-
+       PMAP_ZINFO_PFREE(p, inuse_ptepages * PAGE_SIZE);
+       ledger_dereference(p->ledger);
        zfree(pmap_zone, p);
 
        PMAP_TRACE(PMAP_CODE(PMAP__DESTROY) | DBG_FUNC_END,
@@ -1080,17 +1388,30 @@ pmap_remove_some_phys(
 }
 
 
+void
+pmap_protect(
+       pmap_t          map,
+       vm_map_offset_t sva,
+       vm_map_offset_t eva,
+       vm_prot_t       prot)
+{
+       pmap_protect_options(map, sva, eva, prot, 0, NULL);
+}
+
+
 /*
  *     Set the physical protection on the
  *     specified range of this map as requested.
  *     Will not increase permissions.
  */
 void
-pmap_protect(
+pmap_protect_options(
        pmap_t          map,
        vm_map_offset_t sva,
        vm_map_offset_t eva,
-       vm_prot_t       prot)
+       vm_prot_t       prot,
+       unsigned int    options,
+       void            *arg)
 {
        pt_entry_t      *pde;
        pt_entry_t      *spte, *epte;
@@ -1105,7 +1426,7 @@ pmap_protect(
                return;
 
        if (prot == VM_PROT_NONE) {
-               pmap_remove(map, sva, eva);
+               pmap_remove_options(map, sva, eva, options);
                return;
        }
        PMAP_TRACE(PMAP_CODE(PMAP__PROTECT) | DBG_FUNC_START,
@@ -1142,27 +1463,25 @@ pmap_protect(
                                        continue;
 
                                if (prot & VM_PROT_WRITE)
-                                       pmap_update_pte(spte, *spte,
-                                               *spte | INTEL_PTE_WRITE);
+                                       pmap_update_pte(spte, 0, INTEL_PTE_WRITE);
                                else
-                                       pmap_update_pte(spte, *spte,
-                                               *spte & ~INTEL_PTE_WRITE);
+                                       pmap_update_pte(spte, INTEL_PTE_WRITE, 0);
 
                                if (set_NX)
-                                       pmap_update_pte(spte, *spte,
-                                               *spte | INTEL_PTE_NX);
+                                       pmap_update_pte(spte, 0, INTEL_PTE_NX);
                                else
-                                       pmap_update_pte(spte, *spte,
-                                               *spte & ~INTEL_PTE_NX);
-
+                                       pmap_update_pte(spte, INTEL_PTE_NX, 0);
                                num_found++;
                        }
                }
                sva = lva;
        }
-       if (num_found)
-               PMAP_UPDATE_TLBS(map, orig_sva, eva);
-
+       if (num_found) {
+               if (options & PMAP_OPTIONS_NOFLUSH)
+                       PMAP_UPDATE_TLBS_DELAYED(map, orig_sva, eva, (pmap_flush_context *)arg);
+               else
+                       PMAP_UPDATE_TLBS(map, orig_sva, eva);
+       }
        PMAP_UNLOCK(map);
 
        PMAP_TRACE(PMAP_CODE(PMAP__PROTECT) | DBG_FUNC_END,
@@ -1190,17 +1509,17 @@ pmap_map_block(
                cur_page_size =  PAGE_SIZE;
 
        for (page = 0; page < size; page+=cur_page_size/PAGE_SIZE) {
-               pmap_enter(pmap, va, pa, prot, attr, TRUE);
+               pmap_enter(pmap, va, pa, prot, VM_PROT_NONE, attr, TRUE);
                va += cur_page_size;
                pa+=cur_page_size/PAGE_SIZE;
        }
 }
 
-
-void
+kern_return_t
 pmap_expand_pml4(
        pmap_t          map,
-       vm_map_offset_t vaddr)
+       vm_map_offset_t vaddr,
+       unsigned int options)
 {
        vm_page_t       m;
        pmap_paddr_t    pa;
@@ -1213,9 +1532,11 @@ pmap_expand_pml4(
        /*
         *      Allocate a VM page for the pml4 page
         */
-       while ((m = vm_page_grab()) == VM_PAGE_NULL)
+       while ((m = vm_page_grab()) == VM_PAGE_NULL) {
+               if (options & PMAP_EXPAND_OPTIONS_NOWAIT)
+                       return KERN_RESOURCE_SHORTAGE;
                VM_PAGE_WAIT();
-
+       }
        /*
         *      put the page into the pmap's obj list so it
         *      can be found later.
@@ -1235,7 +1556,7 @@ pmap_expand_pml4(
 
        OSAddAtomic(1,  &inuse_ptepages_count);
        OSAddAtomic64(1,  &alloc_ptepages_count);
-       PMAP_ZINFO_PALLOC(PAGE_SIZE);
+       PMAP_ZINFO_PALLOC(map, PAGE_SIZE);
 
        /* Take the oject lock (mutex) before the PMAP_LOCK (spinlock) */
        vm_object_lock(map->pm_obj_pml4);
@@ -1251,17 +1572,17 @@ pmap_expand_pml4(
                VM_PAGE_FREE(m);
 
                OSAddAtomic(-1,  &inuse_ptepages_count);
-               PMAP_ZINFO_PFREE(PAGE_SIZE);
-               return;
+               PMAP_ZINFO_PFREE(map, PAGE_SIZE);
+               return KERN_SUCCESS;
        }
 
 #if 0 /* DEBUG */
-       if (0 != vm_page_lookup(map->pm_obj_pml4, (vm_object_offset_t)i)) {
+       if (0 != vm_page_lookup(map->pm_obj_pml4, (vm_object_offset_t)i * PAGE_SIZE)) {
               panic("pmap_expand_pml4: obj not empty, pmap %p pm_obj %p vaddr 0x%llx i 0x%llx\n",
                     map, map->pm_obj_pml4, vaddr, i);
        }
 #endif
-       vm_page_insert(m, map->pm_obj_pml4, (vm_object_offset_t)i);
+       vm_page_insert(m, map->pm_obj_pml4, (vm_object_offset_t)i * PAGE_SIZE);
        vm_object_unlock(map->pm_obj_pml4);
 
        /*
@@ -1276,13 +1597,11 @@ pmap_expand_pml4(
 
        PMAP_UNLOCK(map);
 
-       return;
+       return KERN_SUCCESS;
 }
 
-void
-pmap_expand_pdpt(
-                pmap_t map,
-                vm_map_offset_t vaddr)
+kern_return_t
+pmap_expand_pdpt(pmap_t map, vm_map_offset_t vaddr, unsigned int options)
 {
        vm_page_t       m;
        pmap_paddr_t    pa;
@@ -1293,14 +1612,19 @@ pmap_expand_pdpt(
        DBG("pmap_expand_pdpt(%p,%p)\n", map, (void *)vaddr);
 
        while ((pdptp = pmap64_pdpt(map, vaddr)) == PDPT_ENTRY_NULL) {
-               pmap_expand_pml4(map, vaddr);
+               kern_return_t pep4kr = pmap_expand_pml4(map, vaddr, options);
+               if (pep4kr != KERN_SUCCESS)
+                       return pep4kr;
        }
 
        /*
         *      Allocate a VM page for the pdpt page
         */
-       while ((m = vm_page_grab()) == VM_PAGE_NULL)
+       while ((m = vm_page_grab()) == VM_PAGE_NULL) {
+               if (options & PMAP_EXPAND_OPTIONS_NOWAIT)
+                       return KERN_RESOURCE_SHORTAGE;
                VM_PAGE_WAIT();
+       }
 
        /*
         *      put the page into the pmap's obj list so it
@@ -1321,7 +1645,7 @@ pmap_expand_pdpt(
 
        OSAddAtomic(1,  &inuse_ptepages_count);
        OSAddAtomic64(1,  &alloc_ptepages_count);
-       PMAP_ZINFO_PALLOC(PAGE_SIZE);
+       PMAP_ZINFO_PALLOC(map, PAGE_SIZE);
 
        /* Take the oject lock (mutex) before the PMAP_LOCK (spinlock) */
        vm_object_lock(map->pm_obj_pdpt);
@@ -1337,17 +1661,17 @@ pmap_expand_pdpt(
                VM_PAGE_FREE(m);
 
                OSAddAtomic(-1,  &inuse_ptepages_count);
-               PMAP_ZINFO_PFREE(PAGE_SIZE);
-               return;
+               PMAP_ZINFO_PFREE(map, PAGE_SIZE);
+               return KERN_SUCCESS;
        }
 
 #if 0 /* DEBUG */
-       if (0 != vm_page_lookup(map->pm_obj_pdpt, (vm_object_offset_t)i)) {
+       if (0 != vm_page_lookup(map->pm_obj_pdpt, (vm_object_offset_t)i * PAGE_SIZE)) {
               panic("pmap_expand_pdpt: obj not empty, pmap %p pm_obj %p vaddr 0x%llx i 0x%llx\n",
                     map, map->pm_obj_pdpt, vaddr, i);
        }
 #endif
-       vm_page_insert(m, map->pm_obj_pdpt, (vm_object_offset_t)i);
+       vm_page_insert(m, map->pm_obj_pdpt, (vm_object_offset_t)i * PAGE_SIZE);
        vm_object_unlock(map->pm_obj_pdpt);
 
        /*
@@ -1362,7 +1686,7 @@ pmap_expand_pdpt(
 
        PMAP_UNLOCK(map);
 
-       return;
+       return KERN_SUCCESS;
 
 }
 
@@ -1383,10 +1707,11 @@ pmap_expand_pdpt(
  *     has been expanded enough.
  *     (We won't loop forever, since page tables aren't shrunk.)
  */
-void
+kern_return_t
 pmap_expand(
        pmap_t          map,
-       vm_map_offset_t vaddr)
+       vm_map_offset_t vaddr,
+       unsigned int options)
 {
        pt_entry_t              *pdp;
        register vm_page_t      m;
@@ -1406,15 +1731,19 @@ pmap_expand(
 
 
        while ((pdp = pmap64_pde(map, vaddr)) == PD_ENTRY_NULL) {
-               /* need room for another pde entry */
-               pmap_expand_pdpt(map, vaddr);
+               kern_return_t pepkr = pmap_expand_pdpt(map, vaddr, options);
+               if (pepkr != KERN_SUCCESS)
+                       return pepkr;
        }
 
        /*
         *      Allocate a VM page for the pde entries.
         */
-       while ((m = vm_page_grab()) == VM_PAGE_NULL)
+       while ((m = vm_page_grab()) == VM_PAGE_NULL) {
+               if (options & PMAP_EXPAND_OPTIONS_NOWAIT)
+                       return KERN_RESOURCE_SHORTAGE;
                VM_PAGE_WAIT();
+       }
 
        /*
         *      put the page into the pmap's obj list so it
@@ -1435,7 +1764,7 @@ pmap_expand(
 
        OSAddAtomic(1,  &inuse_ptepages_count);
        OSAddAtomic64(1,  &alloc_ptepages_count);
-       PMAP_ZINFO_PALLOC(PAGE_SIZE);
+       PMAP_ZINFO_PALLOC(map, PAGE_SIZE);
 
        /* Take the oject lock (mutex) before the PMAP_LOCK (spinlock) */
        vm_object_lock(map->pm_obj);
@@ -1452,17 +1781,17 @@ pmap_expand(
                VM_PAGE_FREE(m);
 
                OSAddAtomic(-1,  &inuse_ptepages_count);
-               PMAP_ZINFO_PFREE(PAGE_SIZE);
-               return;
+               PMAP_ZINFO_PFREE(map, PAGE_SIZE);
+               return KERN_SUCCESS;
        }
 
 #if 0 /* DEBUG */
-       if (0 != vm_page_lookup(map->pm_obj, (vm_object_offset_t)i)) {
+       if (0 != vm_page_lookup(map->pm_obj, (vm_object_offset_t)i * PAGE_SIZE)) {
               panic("pmap_expand: obj not empty, pmap 0x%x pm_obj 0x%x vaddr 0x%llx i 0x%llx\n",
                     map, map->pm_obj, vaddr, i);
        }
 #endif
-       vm_page_insert(m, map->pm_obj, (vm_object_offset_t)i);
+       vm_page_insert(m, map->pm_obj, (vm_object_offset_t)i * PAGE_SIZE);
        vm_object_unlock(map->pm_obj);
 
        /*
@@ -1476,7 +1805,7 @@ pmap_expand(
 
        PMAP_UNLOCK(map);
 
-       return;
+       return KERN_SUCCESS;
 }
 
 /* On K64 machines with more than 32GB of memory, pmap_steal_memory
@@ -1649,7 +1978,7 @@ pmap_collect(
 
                        vm_object_lock(p->pm_obj);
 
-                       m = vm_page_lookup(p->pm_obj,(vm_object_offset_t)(pdp - (pt_entry_t *)&p->dirbase[0]));
+                       m = vm_page_lookup(p->pm_obj,(vm_object_offset_t)(pdp - (pt_entry_t *)&p->dirbase[0]) * PAGE_SIZE);
                        if (m == VM_PAGE_NULL)
                            panic("pmap_collect: pte page not in object");
 
@@ -1658,7 +1987,7 @@ pmap_collect(
                        VM_PAGE_FREE(m);
 
                        OSAddAtomic(-1,  &inuse_ptepages_count);
-                       PMAP_ZINFO_PFREE(PAGE_SIZE);
+                       PMAP_ZINFO_PFREE(p, PAGE_SIZE);
                    }
 
                    PMAP_LOCK(p);
@@ -1710,7 +2039,6 @@ pmap_pageable(
 #endif /* lint */
 }
 
-
 void 
 invalidate_icache(__unused vm_offset_t addr,
                  __unused unsigned     cnt,
@@ -1738,15 +2066,12 @@ kern_return_t dtrace_copyio_preflight(__unused addr64_t va)
 {
        thread_t thread = current_thread();
        uint64_t ccr3;
-
        if (current_map() == kernel_map)
                return KERN_FAILURE;
        else if (((ccr3 = get_cr3_base()) != thread->map->pmap->pm_cr3) && (no_shared_cr3 == FALSE))
                return KERN_FAILURE;
        else if (no_shared_cr3 && (ccr3 != kernel_pmap->pm_cr3))
                return KERN_FAILURE;
-       else if (thread->machine.specFlags & CopyIOActive)
-               return KERN_FAILURE;
        else
                return KERN_SUCCESS;
 }
@@ -1815,7 +2140,7 @@ pmap_switch(pmap_t tpmap)
         spl_t  s;
 
        s = splhigh();          /* Make sure interruptions are disabled */
-       set_dirbase(tpmap, current_thread());
+       set_dirbase(tpmap, current_thread(), cpu_number());
        splx(s);
 }
 
@@ -1863,20 +2188,125 @@ pt_fake_zone_info(
        *caller_acct = 1;
 }
 
-static inline void
-pmap_cpuset_NMIPI(cpu_set cpu_mask) {
-       unsigned int cpu, cpu_bit;
-       uint64_t deadline;
 
-       for (cpu = 0, cpu_bit = 1; cpu < real_ncpus; cpu++, cpu_bit <<= 1) {
-               if (cpu_mask & cpu_bit)
-                       cpu_NMI_interrupt(cpu);
+void
+pmap_flush_context_init(pmap_flush_context *pfc)
+{
+       pfc->pfc_cpus = 0;
+       pfc->pfc_invalid_global = 0;
+}
+
+extern unsigned TLBTimeOut;
+void
+pmap_flush(
+       pmap_flush_context *pfc)
+{
+       unsigned int    my_cpu;
+       unsigned int    cpu;
+       unsigned int    cpu_bit;
+       cpumask_t       cpus_to_respond = 0;
+       cpumask_t       cpus_to_signal = 0;
+       cpumask_t       cpus_signaled = 0;
+       boolean_t       flush_self = FALSE;
+       uint64_t        deadline;
+
+       mp_disable_preemption();
+
+       my_cpu = cpu_number();
+       cpus_to_signal = pfc->pfc_cpus;
+
+       PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_DELAYED_TLBS) | DBG_FUNC_START,
+                           NULL, cpus_to_signal, 0, 0, 0);
+
+       for (cpu = 0, cpu_bit = 1; cpu < real_ncpus && cpus_to_signal; cpu++, cpu_bit <<= 1) {
+
+               if (cpus_to_signal & cpu_bit) {
+
+                       cpus_to_signal &= ~cpu_bit;
+
+                       if (!cpu_datap(cpu)->cpu_running)
+                               continue;
+
+                       if (pfc->pfc_invalid_global & cpu_bit)
+                               cpu_datap(cpu)->cpu_tlb_invalid_global = TRUE;
+                       else
+                               cpu_datap(cpu)->cpu_tlb_invalid_local = TRUE;
+                       mfence();
+
+                       if (cpu == my_cpu) {
+                               flush_self = TRUE;
+                               continue;
+                       }
+                       if (CPU_CR3_IS_ACTIVE(cpu)) {
+                               cpus_to_respond |= cpu_bit;
+                               i386_signal_cpu(cpu, MP_TLB_FLUSH, ASYNC);
+                       }
+               }
        }
-       deadline = mach_absolute_time() + (LockTimeOut);
-       while (mach_absolute_time() < deadline)
-               cpu_pause();
+       cpus_signaled = cpus_to_respond;
+
+       /*
+        * Flush local tlb if required.
+        * Do this now to overlap with other processors responding.
+        */
+       if (flush_self && cpu_datap(my_cpu)->cpu_tlb_invalid != FALSE)
+               process_pmap_updates();
+
+       if (cpus_to_respond) {
+
+               deadline = mach_absolute_time() +
+                               (TLBTimeOut ? TLBTimeOut : LockTimeOut);
+               boolean_t is_timeout_traced = FALSE;
+               
+               /*
+                * Wait for those other cpus to acknowledge
+                */
+               while (cpus_to_respond != 0) {
+                       long orig_acks = 0;
+
+                       for (cpu = 0, cpu_bit = 1; cpu < real_ncpus; cpu++, cpu_bit <<= 1) {
+                               /* Consider checking local/global invalidity
+                                * as appropriate in the PCID case.
+                                */
+                               if ((cpus_to_respond & cpu_bit) != 0) {
+                                       if (!cpu_datap(cpu)->cpu_running ||
+                                           cpu_datap(cpu)->cpu_tlb_invalid == FALSE ||
+                                           !CPU_CR3_IS_ACTIVE(cpu)) {
+                                               cpus_to_respond &= ~cpu_bit;
+                                       }
+                                       cpu_pause();
+                               }
+                               if (cpus_to_respond == 0)
+                                       break;
+                       }
+                       if (cpus_to_respond && (mach_absolute_time() > deadline)) {
+                               if (machine_timeout_suspended())
+                                       continue;
+                               if (TLBTimeOut == 0) {
+                                       if (is_timeout_traced)
+                                               continue;
+                                       PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_TLBS_TO),
+                                               NULL, cpus_to_signal, cpus_to_respond, 0, 0);
+                                       is_timeout_traced = TRUE;
+                                       continue;
+                               }
+                               pmap_tlb_flush_timeout = TRUE;
+                               orig_acks = NMIPI_acks;
+                               mp_cpus_NMIPI(cpus_to_respond);
+
+                               panic("TLB invalidation IPI timeout: "
+                                   "CPU(s) failed to respond to interrupts, unresponsive CPU bitmap: 0x%lx, NMIPI acks: orig: 0x%lx, now: 0x%lx",
+                                   cpus_to_respond, orig_acks, NMIPI_acks);
+                       }
+               }
+       }
+       PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_DELAYED_TLBS) | DBG_FUNC_END,
+                           NULL, cpus_signaled, flush_self, 0, 0);
+
+       mp_enable_preemption();
 }
 
+
 /*
  * Called with pmap locked, we:
  *  - scan through per-cpu data to see which other cpus need to flush
@@ -1888,20 +2318,27 @@ pmap_cpuset_NMIPI(cpu_set cpu_mask) {
  */
 
 void
-pmap_flush_tlbs(pmap_t pmap, vm_map_offset_t startv, vm_map_offset_t endv)
+pmap_flush_tlbs(pmap_t pmap, vm_map_offset_t startv, vm_map_offset_t endv, int options, pmap_flush_context *pfc)
 {
        unsigned int    cpu;
        unsigned int    cpu_bit;
-       cpu_set         cpus_to_signal;
+       cpumask_t       cpus_to_signal;
        unsigned int    my_cpu = cpu_number();
        pmap_paddr_t    pmap_cr3 = pmap->pm_cr3;
        boolean_t       flush_self = FALSE;
        uint64_t        deadline;
        boolean_t       pmap_is_shared = (pmap->pm_shared || (pmap == kernel_pmap));
+       boolean_t       need_global_flush = FALSE;
+       uint32_t        event_code;
 
        assert((processor_avail_count < 2) ||
               (ml_get_interrupts_enabled() && get_preemption_level() != 0));
 
+       event_code = (pmap == kernel_pmap) ? PMAP_CODE(PMAP__FLUSH_KERN_TLBS)
+                                          : PMAP_CODE(PMAP__FLUSH_TLBS);
+       PMAP_TRACE_CONSTANT(event_code | DBG_FUNC_START,
+                           pmap, options, startv, endv, 0);
+
        /*
         * Scan other cpus for matching active or task CR3.
         * For idle cpus (with no active map) we mark them invalid but
@@ -1910,10 +2347,11 @@ pmap_flush_tlbs(pmap_t  pmap, vm_map_offset_t startv, vm_map_offset_t endv)
        cpus_to_signal = 0;
 
        if (pmap_pcid_ncpus) {
+               if (pmap_is_shared)
+                       need_global_flush = TRUE;
                pmap_pcid_invalidate_all_cpus(pmap);
-               __asm__ volatile("mfence":::"memory");
+               mfence();
        }
-
        for (cpu = 0, cpu_bit = 1; cpu < real_ncpus; cpu++, cpu_bit <<= 1) {
                if (!cpu_datap(cpu)->cpu_running)
                        continue;
@@ -1923,15 +2361,23 @@ pmap_flush_tlbs(pmap_t  pmap, vm_map_offset_t startv, vm_map_offset_t endv)
                if ((pmap_cr3 == cpu_task_cr3) ||
                    (pmap_cr3 == cpu_active_cr3) ||
                    (pmap_is_shared)) {
+
+                       if (options & PMAP_DELAY_TLB_FLUSH) {
+                               if (need_global_flush == TRUE)
+                                       pfc->pfc_invalid_global |= cpu_bit;
+                               pfc->pfc_cpus |= cpu_bit;
+
+                               continue;
+                       }
                        if (cpu == my_cpu) {
                                flush_self = TRUE;
                                continue;
                        }
-                       if (pmap_pcid_ncpus && pmap_is_shared)
+                       if (need_global_flush == TRUE)
                                cpu_datap(cpu)->cpu_tlb_invalid_global = TRUE;
                        else
                                cpu_datap(cpu)->cpu_tlb_invalid_local = TRUE;
-                       __asm__ volatile("mfence":::"memory");
+                       mfence();
 
                        /*
                         * We don't need to signal processors which will flush
@@ -1949,16 +2395,15 @@ pmap_flush_tlbs(pmap_t  pmap, vm_map_offset_t startv, vm_map_offset_t endv)
                         */
                        if (CPU_CR3_IS_ACTIVE(cpu) &&
                            (pmap_cr3 == CPU_GET_ACTIVE_CR3(cpu) ||
-                           pmap->pm_shared ||
-                           (pmap_cr3 == CPU_GET_TASK_CR3(cpu)))) {
+                            pmap->pm_shared ||
+                            (pmap_cr3 == CPU_GET_TASK_CR3(cpu)))) {
                                cpus_to_signal |= cpu_bit;
                                i386_signal_cpu(cpu, MP_TLB_FLUSH, ASYNC);
                        }
                }
        }
-
-       PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_TLBS) | DBG_FUNC_START,
-                  pmap, cpus_to_signal, flush_self, startv, endv);
+       if ((options & PMAP_DELAY_TLB_FLUSH))
+               goto out;
 
        /*
         * Flush local tlb if required.
@@ -1977,9 +2422,12 @@ pmap_flush_tlbs(pmap_t   pmap, vm_map_offset_t startv, vm_map_offset_t endv)
        }
 
        if (cpus_to_signal) {
-               cpu_set cpus_to_respond = cpus_to_signal;
+               cpumask_t       cpus_to_respond = cpus_to_signal;
+
+               deadline = mach_absolute_time() +
+                               (TLBTimeOut ? TLBTimeOut : LockTimeOut);
+               boolean_t is_timeout_traced = FALSE;
 
-               deadline = mach_absolute_time() + LockTimeOut;
                /*
                 * Wait for those other cpus to acknowledge
                 */
@@ -2004,9 +2452,19 @@ pmap_flush_tlbs(pmap_t   pmap, vm_map_offset_t startv, vm_map_offset_t endv)
                        if (cpus_to_respond && (mach_absolute_time() > deadline)) {
                                if (machine_timeout_suspended())
                                        continue;
+                               if (TLBTimeOut == 0) {
+                                       /* cut tracepoint but don't panic */
+                                       if (is_timeout_traced)
+                                               continue;
+                                       PMAP_TRACE_CONSTANT(
+                                               PMAP_CODE(PMAP__FLUSH_TLBS_TO),
+                                               pmap, cpus_to_signal, cpus_to_respond, 0, 0);
+                                       is_timeout_traced = TRUE;
+                                       continue;
+                               }
                                pmap_tlb_flush_timeout = TRUE;
                                orig_acks = NMIPI_acks;
-                               pmap_cpuset_NMIPI(cpus_to_respond);
+                               mp_cpus_NMIPI(cpus_to_respond);
 
                                panic("TLB invalidation IPI timeout: "
                                    "CPU(s) failed to respond to interrupts, unresponsive CPU bitmap: 0x%lx, NMIPI acks: orig: 0x%lx, now: 0x%lx",
@@ -2015,8 +2473,14 @@ pmap_flush_tlbs(pmap_t   pmap, vm_map_offset_t startv, vm_map_offset_t endv)
                }
        }
 
-       PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_TLBS) | DBG_FUNC_END,
-           pmap, cpus_to_signal, startv, endv, 0);
+       if (__improbable((pmap == kernel_pmap) && (flush_self != TRUE))) {
+               panic("pmap_flush_tlbs: pmap == kernel_pmap && flush_self != TRUE; kernel CR3: 0x%llX, pmap_cr3: 0x%llx, CPU active CR3: 0x%llX, CPU Task Map: %d", kernel_pmap->pm_cr3, pmap_cr3, current_cpu_datap()->cpu_active_cr3, current_cpu_datap()->cpu_task_map);
+       }
+
+out:
+       PMAP_TRACE_CONSTANT(event_code | DBG_FUNC_END,
+                           pmap, cpus_to_signal, startv, endv, 0);
+
 }
 
 void
@@ -2040,7 +2504,7 @@ process_pmap_updates(void)
                flush_tlb_raw();
        }
 
-       __asm__ volatile("mfence");
+       mfence();
 }
 
 void
@@ -2049,8 +2513,120 @@ pmap_update_interrupt(void)
         PMAP_TRACE(PMAP_CODE(PMAP__UPDATE_INTERRUPT) | DBG_FUNC_START,
                   0, 0, 0, 0, 0);
 
-       process_pmap_updates();
+       if (current_cpu_datap()->cpu_tlb_invalid)
+               process_pmap_updates();
 
         PMAP_TRACE(PMAP_CODE(PMAP__UPDATE_INTERRUPT) | DBG_FUNC_END,
                   0, 0, 0, 0, 0);
 }
+
+#include <mach/mach_vm.h>      /* mach_vm_region_recurse() */
+/* Scan kernel pmap for W+X PTEs, scan kernel VM map for W+X map entries
+ * and identify ranges with mismatched VM permissions and PTE permissions
+ */
+kern_return_t
+pmap_permissions_verify(pmap_t ipmap, vm_map_t ivmmap, vm_offset_t sv, vm_offset_t ev) {
+       vm_offset_t cv = sv;
+       kern_return_t rv = KERN_SUCCESS;
+       uint64_t skip4 = 0, skip2 = 0;
+
+       sv &= ~PAGE_MASK_64;
+       ev &= ~PAGE_MASK_64;
+       while (cv < ev) {
+               if (__improbable((cv > 0x00007FFFFFFFFFFFULL) &&
+                       (cv < 0xFFFF800000000000ULL))) {
+                       cv = 0xFFFF800000000000ULL;
+               }
+               /* Potential inconsistencies from not holding pmap lock
+                * but harmless for the moment.
+                */
+               if (((cv & PML4MASK) == 0) && (pmap64_pml4(ipmap, cv) == 0)) {
+                       if ((cv + NBPML4) > cv)
+                               cv += NBPML4;
+                       else
+                               break;
+                       skip4++;
+                       continue;
+               }
+               if (((cv & PDMASK) == 0) && (pmap_pde(ipmap, cv) == 0)) {
+                       if ((cv + NBPD) > cv)
+                               cv += NBPD;
+                       else
+                               break;
+                       skip2++;
+                       continue;
+               }
+
+               pt_entry_t *ptep = pmap_pte(ipmap, cv);
+               if (ptep && (*ptep & INTEL_PTE_VALID)) {
+                       if (*ptep & INTEL_PTE_WRITE) {
+                               if (!(*ptep & INTEL_PTE_NX)) {
+                                       kprintf("W+X PTE at 0x%lx, P4: 0x%llx, P3: 0x%llx, P2: 0x%llx, PT: 0x%llx, VP: %u\n", cv, *pmap64_pml4(ipmap, cv), *pmap64_pdpt(ipmap, cv), *pmap64_pde(ipmap, cv), *ptep, pmap_valid_page((ppnum_t)(i386_btop(pte_to_pa(*ptep)))));
+                                       rv = KERN_FAILURE;
+                               }
+                       }
+               }
+               cv += PAGE_SIZE;
+       }
+       kprintf("Completed pmap scan\n");
+       cv = sv;
+
+       struct vm_region_submap_info_64 vbr;
+       mach_msg_type_number_t vbrcount = 0;
+       mach_vm_size_t  vmsize;
+       vm_prot_t       prot;
+       uint32_t nesting_depth = 0;
+       kern_return_t kret;
+       
+       while (cv < ev) {
+               
+               for (;;) {
+                       vbrcount = VM_REGION_SUBMAP_INFO_COUNT_64;
+                       if((kret = mach_vm_region_recurse(ivmmap, 
+                                   (mach_vm_address_t *) &cv, &vmsize, &nesting_depth, 
+                                       (vm_region_recurse_info_t)&vbr,
+                                       &vbrcount)) != KERN_SUCCESS) {
+                               break;
+                       }
+
+                       if(vbr.is_submap) {
+                               nesting_depth++;
+                               continue;
+                       } else {
+                               break;
+                       }
+               }
+
+               if(kret != KERN_SUCCESS)
+                       break;
+
+               prot = vbr.protection;
+
+               if ((prot & (VM_PROT_WRITE | VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE)) {
+                       kprintf("W+X map entry at address 0x%lx\n", cv);
+                       rv = KERN_FAILURE;
+               }
+
+               if (prot) {
+                       vm_offset_t pcv;
+                       for (pcv = cv; pcv < cv + vmsize; pcv += PAGE_SIZE) {
+                               pt_entry_t *ptep = pmap_pte(ipmap, pcv);
+                               vm_prot_t tprot;
+
+                               if ((ptep == NULL) || !(*ptep & INTEL_PTE_VALID))
+                                       continue;
+                               tprot = VM_PROT_READ;
+                               if (*ptep & INTEL_PTE_WRITE)
+                                       tprot |= VM_PROT_WRITE;
+                               if ((*ptep & INTEL_PTE_NX) == 0)
+                                       tprot |= VM_PROT_EXECUTE;
+                               if (tprot != prot) {
+                                       kprintf("PTE/map entry permissions mismatch at address 0x%lx, pte: 0x%llx, protection: 0x%x\n", pcv, *ptep, prot);
+                                       rv = KERN_FAILURE;
+                               }
+                       }
+               }
+               cv += vmsize;
+       }
+       return rv;
+}