]> git.saurik.com Git - apple/xnu.git/blob - osfmk/x86_64/pmap.c
9b2a9675eff7faa94360314f2b0313c5d5b6fd5a
[apple/xnu.git] / osfmk / x86_64 / pmap.c
1 /*
2 * Copyright (c) 2000-2010 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * @OSF_COPYRIGHT@
30 */
31 /*
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
34 * All Rights Reserved.
35 *
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
41 *
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45 *
46 * Carnegie Mellon requests users of this software to return to
47 *
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
52 *
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
55 */
56 /*
57 */
58
59 /*
60 * File: pmap.c
61 * Author: Avadis Tevanian, Jr., Michael Wayne Young
62 * (These guys wrote the Vax version)
63 *
64 * Physical Map management code for Intel i386, i486, and i860.
65 *
66 * Manages physical address maps.
67 *
68 * In addition to hardware address maps, this
69 * module is called upon to provide software-use-only
70 * maps which may or may not be stored in the same
71 * form as hardware maps. These pseudo-maps are
72 * used to store intermediate results from copy
73 * operations to and from address spaces.
74 *
75 * Since the information managed by this module is
76 * also stored by the logical address mapping module,
77 * this module may throw away valid virtual-to-physical
78 * mappings at almost any time. However, invalidations
79 * of virtual-to-physical mappings must be done as
80 * requested.
81 *
82 * In order to cope with hardware architectures which
83 * make virtual-to-physical map invalidates expensive,
84 * this module may delay invalidate or reduced protection
85 * operations until such time as they are actually
86 * necessary. This module is given full information as
87 * to which processors are currently using which maps,
88 * and to when physical maps must be made correct.
89 */
90
91 #include <string.h>
92 #include <mach_ldebug.h>
93
94 #include <libkern/OSAtomic.h>
95
96 #include <mach/machine/vm_types.h>
97
98 #include <mach/boolean.h>
99 #include <kern/thread.h>
100 #include <kern/zalloc.h>
101 #include <kern/queue.h>
102 #include <kern/ledger.h>
103 #include <kern/mach_param.h>
104
105 #include <kern/kalloc.h>
106 #include <kern/spl.h>
107
108 #include <vm/pmap.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_kern.h>
111 #include <mach/vm_param.h>
112 #include <mach/vm_prot.h>
113 #include <vm/vm_object.h>
114 #include <vm/vm_page.h>
115
116 #include <mach/machine/vm_param.h>
117 #include <machine/thread.h>
118
119 #include <kern/misc_protos.h> /* prototyping */
120 #include <i386/misc_protos.h>
121 #include <i386/i386_lowmem.h>
122 #include <x86_64/lowglobals.h>
123
124 #include <i386/cpuid.h>
125 #include <i386/cpu_data.h>
126 #include <i386/cpu_number.h>
127 #include <i386/machine_cpu.h>
128 #include <i386/seg.h>
129 #include <i386/serial_io.h>
130 #include <i386/cpu_capabilities.h>
131 #include <i386/machine_routines.h>
132 #include <i386/proc_reg.h>
133 #include <i386/tsc.h>
134 #include <i386/pmap_internal.h>
135 #include <i386/pmap_pcid.h>
136 #if CONFIG_VMX
137 #include <i386/vmx/vmx_cpu.h>
138 #endif
139
140 #include <vm/vm_protos.h>
141 #include <san/kasan.h>
142
143 #include <i386/mp.h>
144 #include <i386/mp_desc.h>
145 #include <libkern/kernel_mach_header.h>
146
147 #include <pexpert/i386/efi.h>
148
149 #if MACH_ASSERT
150 int pmap_stats_assert = 1;
151 #endif /* MACH_ASSERT */
152
153 #ifdef IWANTTODEBUG
154 #undef DEBUG
155 #define DEBUG 1
156 #define POSTCODE_DELAY 1
157 #include <i386/postcode.h>
158 #endif /* IWANTTODEBUG */
159
160 #ifdef PMAP_DEBUG
161 #define DBG(x...) kprintf("DBG: " x)
162 #else
163 #define DBG(x...)
164 #endif
165 /* Compile time assert to ensure adjacency/alignment of per-CPU data fields used
166 * in the trampolines for kernel/user boundary TLB coherency.
167 */
168 char pmap_cpu_data_assert[(((offsetof(cpu_data_t, cpu_tlb_invalid) - offsetof(cpu_data_t, cpu_active_cr3)) == 8) && (offsetof(cpu_data_t, cpu_active_cr3) % 64 == 0)) ? 1 : -1];
169 boolean_t pmap_trace = FALSE;
170
171 boolean_t no_shared_cr3 = DEBUG; /* TRUE for DEBUG by default */
172
173 int nx_enabled = 1; /* enable no-execute protection -- set during boot */
174
175 #if DEBUG || DEVELOPMENT
176 int allow_data_exec = VM_ABI_32; /* 32-bit apps may execute data by default, 64-bit apps may not */
177 int allow_stack_exec = 0; /* No apps may execute from the stack by default */
178 #else /* DEBUG || DEVELOPMENT */
179 const int allow_data_exec = VM_ABI_32; /* 32-bit apps may execute data by default, 64-bit apps may not */
180 const int allow_stack_exec = 0; /* No apps may execute from the stack by default */
181 #endif /* DEBUG || DEVELOPMENT */
182
183 const boolean_t cpu_64bit = TRUE; /* Mais oui! */
184
185 uint64_t max_preemption_latency_tsc = 0;
186
187 pv_hashed_entry_t *pv_hash_table; /* hash lists */
188
189 uint32_t npvhashmask = 0, npvhashbuckets = 0;
190
191 pv_hashed_entry_t pv_hashed_free_list = PV_HASHED_ENTRY_NULL;
192 pv_hashed_entry_t pv_hashed_kern_free_list = PV_HASHED_ENTRY_NULL;
193 decl_simple_lock_data(,pv_hashed_free_list_lock)
194 decl_simple_lock_data(,pv_hashed_kern_free_list_lock)
195 decl_simple_lock_data(,pv_hash_table_lock)
196
197 decl_simple_lock_data(,phys_backup_lock)
198
199 zone_t pv_hashed_list_zone; /* zone of pv_hashed_entry structures */
200
201 /*
202 * First and last physical addresses that we maintain any information
203 * for. Initialized to zero so that pmap operations done before
204 * pmap_init won't touch any non-existent structures.
205 */
206 boolean_t pmap_initialized = FALSE;/* Has pmap_init completed? */
207
208 static struct vm_object kptobj_object_store __attribute__((aligned(VM_PACKED_POINTER_ALIGNMENT)));
209 static struct vm_object kpml4obj_object_store __attribute__((aligned(VM_PACKED_POINTER_ALIGNMENT)));
210 static struct vm_object kpdptobj_object_store __attribute__((aligned(VM_PACKED_POINTER_ALIGNMENT)));
211
212 /*
213 * Array of physical page attribites for managed pages.
214 * One byte per physical page.
215 */
216 char *pmap_phys_attributes;
217 ppnum_t last_managed_page = 0;
218
219 /*
220 * Amount of virtual memory mapped by one
221 * page-directory entry.
222 */
223
224 uint64_t pde_mapped_size = PDE_MAPPED_SIZE;
225
226 unsigned pmap_memory_region_count;
227 unsigned pmap_memory_region_current;
228
229 pmap_memory_region_t pmap_memory_regions[PMAP_MEMORY_REGIONS_SIZE];
230
231 /*
232 * Other useful macros.
233 */
234 #define current_pmap() (vm_map_pmap(current_thread()->map))
235
236 struct pmap kernel_pmap_store;
237 pmap_t kernel_pmap;
238
239 struct zone *pmap_zone; /* zone of pmap structures */
240
241 struct zone *pmap_anchor_zone;
242 int pmap_debug = 0; /* flag for debugging prints */
243
244 unsigned int inuse_ptepages_count = 0;
245 long long alloc_ptepages_count __attribute__((aligned(8))) = 0; /* aligned for atomic access */
246 unsigned int bootstrap_wired_pages = 0;
247 int pt_fake_zone_index = -1;
248
249 extern long NMIPI_acks;
250
251 boolean_t kernel_text_ps_4K = TRUE;
252 boolean_t wpkernel = TRUE;
253
254 extern char end;
255
256 static int nkpt;
257
258 pt_entry_t *DMAP1, *DMAP2;
259 caddr_t DADDR1;
260 caddr_t DADDR2;
261
262 boolean_t pmap_disable_kheap_nx = FALSE;
263 boolean_t pmap_disable_kstack_nx = FALSE;
264
265 extern long __stack_chk_guard[];
266
267 static uint64_t pmap_eptp_flags = 0;
268 boolean_t pmap_ept_support_ad = FALSE;
269
270
271 /*
272 * Map memory at initialization. The physical addresses being
273 * mapped are not managed and are never unmapped.
274 *
275 * For now, VM is already on, we only need to map the
276 * specified memory.
277 */
278 vm_offset_t
279 pmap_map(
280 vm_offset_t virt,
281 vm_map_offset_t start_addr,
282 vm_map_offset_t end_addr,
283 vm_prot_t prot,
284 unsigned int flags)
285 {
286 kern_return_t kr;
287 int ps;
288
289 ps = PAGE_SIZE;
290 while (start_addr < end_addr) {
291 kr = pmap_enter(kernel_pmap, (vm_map_offset_t)virt,
292 (ppnum_t) i386_btop(start_addr), prot, VM_PROT_NONE, flags, TRUE);
293
294 if (kr != KERN_SUCCESS) {
295 panic("%s: failed pmap_enter, "
296 "virt=%p, start_addr=%p, end_addr=%p, prot=%#x, flags=%#x",
297 __FUNCTION__,
298 (void *)virt, (void *)start_addr, (void *)end_addr, prot, flags);
299 }
300
301 virt += ps;
302 start_addr += ps;
303 }
304 return(virt);
305 }
306
307 extern char *first_avail;
308 extern vm_offset_t virtual_avail, virtual_end;
309 extern pmap_paddr_t avail_start, avail_end;
310 extern vm_offset_t sHIB;
311 extern vm_offset_t eHIB;
312 extern vm_offset_t stext;
313 extern vm_offset_t etext;
314 extern vm_offset_t sdata, edata;
315 extern vm_offset_t sconst, econst;
316
317 extern void *KPTphys;
318
319 boolean_t pmap_smep_enabled = FALSE;
320 boolean_t pmap_smap_enabled = FALSE;
321
322 void
323 pmap_cpu_init(void)
324 {
325 cpu_data_t *cdp = current_cpu_datap();
326 /*
327 * Here early in the life of a processor (from cpu_mode_init()).
328 * Ensure global page feature is disabled at this point.
329 */
330
331 set_cr4(get_cr4() &~ CR4_PGE);
332
333 /*
334 * Initialize the per-cpu, TLB-related fields.
335 */
336 cdp->cpu_kernel_cr3 = kernel_pmap->pm_cr3;
337 cdp->cpu_active_cr3 = kernel_pmap->pm_cr3;
338 cdp->cpu_tlb_invalid = FALSE;
339 cdp->cpu_task_map = TASK_MAP_64BIT;
340 pmap_pcid_configure();
341 if (cpuid_leaf7_features() & CPUID_LEAF7_FEATURE_SMEP) {
342 pmap_smep_enabled = TRUE;
343 #if DEVELOPMENT || DEBUG
344 boolean_t nsmep;
345 if (PE_parse_boot_argn("-pmap_smep_disable", &nsmep, sizeof(nsmep))) {
346 pmap_smep_enabled = FALSE;
347 }
348 #endif
349 if (pmap_smep_enabled) {
350 set_cr4(get_cr4() | CR4_SMEP);
351 }
352
353 }
354 if (cpuid_leaf7_features() & CPUID_LEAF7_FEATURE_SMAP) {
355 pmap_smap_enabled = TRUE;
356 #if DEVELOPMENT || DEBUG
357 boolean_t nsmap;
358 if (PE_parse_boot_argn("-pmap_smap_disable", &nsmap, sizeof(nsmap))) {
359 pmap_smap_enabled = FALSE;
360 }
361 #endif
362 if (pmap_smap_enabled) {
363 set_cr4(get_cr4() | CR4_SMAP);
364 }
365 }
366
367 #if !MONOTONIC
368 if (cdp->cpu_fixed_pmcs_enabled) {
369 boolean_t enable = TRUE;
370 cpu_pmc_control(&enable);
371 }
372 #endif /* !MONOTONIC */
373 }
374
375 static uint32_t pmap_scale_shift(void) {
376 uint32_t scale = 0;
377
378 if (sane_size <= 8*GB) {
379 scale = (uint32_t)(sane_size / (2 * GB));
380 } else if (sane_size <= 32*GB) {
381 scale = 4 + (uint32_t)((sane_size - (8 * GB))/ (4 * GB));
382 } else {
383 scale = 10 + (uint32_t)MIN(4, ((sane_size - (32 * GB))/ (8 * GB)));
384 }
385 return scale;
386 }
387
388 /*
389 * Bootstrap the system enough to run with virtual memory.
390 * Map the kernel's code and data, and allocate the system page table.
391 * Called with mapping OFF. Page_size must already be set.
392 */
393
394 void
395 pmap_bootstrap(
396 __unused vm_offset_t load_start,
397 __unused boolean_t IA32e)
398 {
399 #if NCOPY_WINDOWS > 0
400 vm_offset_t va;
401 int i;
402 #endif
403 assert(IA32e);
404
405 vm_last_addr = VM_MAX_KERNEL_ADDRESS; /* Set the highest address
406 * known to VM */
407 /*
408 * The kernel's pmap is statically allocated so we don't
409 * have to use pmap_create, which is unlikely to work
410 * correctly at this part of the boot sequence.
411 */
412
413 kernel_pmap = &kernel_pmap_store;
414 kernel_pmap->ref_count = 1;
415 kernel_pmap->nx_enabled = TRUE;
416 kernel_pmap->pm_task_map = TASK_MAP_64BIT;
417 kernel_pmap->pm_obj = (vm_object_t) NULL;
418 kernel_pmap->dirbase = (pd_entry_t *)((uintptr_t)IdlePTD);
419 kernel_pmap->pm_pdpt = (pd_entry_t *) ((uintptr_t)IdlePDPT);
420 kernel_pmap->pm_pml4 = IdlePML4;
421 kernel_pmap->pm_cr3 = (uintptr_t)ID_MAP_VTOP(IdlePML4);
422 kernel_pmap->pm_eptp = 0;
423 pmap_pcid_initialize_kernel(kernel_pmap);
424
425
426
427 current_cpu_datap()->cpu_kernel_cr3 = (addr64_t) kernel_pmap->pm_cr3;
428
429 nkpt = NKPT;
430 OSAddAtomic(NKPT, &inuse_ptepages_count);
431 OSAddAtomic64(NKPT, &alloc_ptepages_count);
432 bootstrap_wired_pages = NKPT;
433
434 virtual_avail = (vm_offset_t)(VM_MIN_KERNEL_ADDRESS) + (vm_offset_t)first_avail;
435 virtual_end = (vm_offset_t)(VM_MAX_KERNEL_ADDRESS);
436
437 #if NCOPY_WINDOWS > 0
438 /*
439 * Reserve some special page table entries/VA space for temporary
440 * mapping of pages.
441 */
442 #define SYSMAP(c, p, v, n) \
443 v = (c)va; va += ((n)*INTEL_PGBYTES);
444
445 va = virtual_avail;
446
447 for (i=0; i<PMAP_NWINDOWS; i++) {
448 #if 1
449 kprintf("trying to do SYSMAP idx %d %p\n", i,
450 current_cpu_datap());
451 kprintf("cpu_pmap %p\n", current_cpu_datap()->cpu_pmap);
452 kprintf("mapwindow %p\n", current_cpu_datap()->cpu_pmap->mapwindow);
453 kprintf("two stuff %p %p\n",
454 (void *)(current_cpu_datap()->cpu_pmap->mapwindow[i].prv_CMAP),
455 (void *)(current_cpu_datap()->cpu_pmap->mapwindow[i].prv_CADDR));
456 #endif
457 SYSMAP(caddr_t,
458 (current_cpu_datap()->cpu_pmap->mapwindow[i].prv_CMAP),
459 (current_cpu_datap()->cpu_pmap->mapwindow[i].prv_CADDR),
460 1);
461 current_cpu_datap()->cpu_pmap->mapwindow[i].prv_CMAP =
462 &(current_cpu_datap()->cpu_pmap->mapwindow[i].prv_CMAP_store);
463 *current_cpu_datap()->cpu_pmap->mapwindow[i].prv_CMAP = 0;
464 }
465
466 /* DMAP user for debugger */
467 SYSMAP(caddr_t, DMAP1, DADDR1, 1);
468 SYSMAP(caddr_t, DMAP2, DADDR2, 1); /* XXX temporary - can remove */
469
470 virtual_avail = va;
471 #endif
472 if (!PE_parse_boot_argn("npvhash", &npvhashmask, sizeof (npvhashmask))) {
473 npvhashmask = ((NPVHASHBUCKETS) << pmap_scale_shift()) - 1;
474
475 }
476
477 npvhashbuckets = npvhashmask + 1;
478
479 if (0 != ((npvhashbuckets) & npvhashmask)) {
480 panic("invalid hash %d, must be ((2^N)-1), "
481 "using default %d\n", npvhashmask, NPVHASHMASK);
482 }
483
484 simple_lock_init(&kernel_pmap->lock, 0);
485 simple_lock_init(&pv_hashed_free_list_lock, 0);
486 simple_lock_init(&pv_hashed_kern_free_list_lock, 0);
487 simple_lock_init(&pv_hash_table_lock,0);
488 simple_lock_init(&phys_backup_lock, 0);
489
490 pmap_cpu_init();
491
492 if (pmap_pcid_ncpus)
493 printf("PMAP: PCID enabled\n");
494
495 if (pmap_smep_enabled)
496 printf("PMAP: Supervisor Mode Execute Protection enabled\n");
497 if (pmap_smap_enabled)
498 printf("PMAP: Supervisor Mode Access Protection enabled\n");
499
500 #if DEBUG
501 printf("Stack canary: 0x%lx\n", __stack_chk_guard[0]);
502 printf("early_random(): 0x%qx\n", early_random());
503 #endif
504 #if DEVELOPMENT || DEBUG
505 boolean_t ptmp;
506 /* Check if the user has requested disabling stack or heap no-execute
507 * enforcement. These are "const" variables; that qualifier is cast away
508 * when altering them. The TEXT/DATA const sections are marked
509 * write protected later in the kernel startup sequence, so altering
510 * them is possible at this point, in pmap_bootstrap().
511 */
512 if (PE_parse_boot_argn("-pmap_disable_kheap_nx", &ptmp, sizeof(ptmp))) {
513 boolean_t *pdknxp = (boolean_t *) &pmap_disable_kheap_nx;
514 *pdknxp = TRUE;
515 }
516
517 if (PE_parse_boot_argn("-pmap_disable_kstack_nx", &ptmp, sizeof(ptmp))) {
518 boolean_t *pdknhp = (boolean_t *) &pmap_disable_kstack_nx;
519 *pdknhp = TRUE;
520 }
521 #endif /* DEVELOPMENT || DEBUG */
522
523 boot_args *args = (boot_args *)PE_state.bootArgs;
524 if (args->efiMode == kBootArgsEfiMode32) {
525 printf("EFI32: kernel virtual space limited to 4GB\n");
526 virtual_end = VM_MAX_KERNEL_ADDRESS_EFI32;
527 }
528 kprintf("Kernel virtual space from 0x%lx to 0x%lx.\n",
529 (long)KERNEL_BASE, (long)virtual_end);
530 kprintf("Available physical space from 0x%llx to 0x%llx\n",
531 avail_start, avail_end);
532
533 /*
534 * The -no_shared_cr3 boot-arg is a debugging feature (set by default
535 * in the DEBUG kernel) to force the kernel to switch to its own map
536 * (and cr3) when control is in kernelspace. The kernel's map does not
537 * include (i.e. share) userspace so wild references will cause
538 * a panic. Only copyin and copyout are exempt from this.
539 */
540 (void) PE_parse_boot_argn("-no_shared_cr3",
541 &no_shared_cr3, sizeof (no_shared_cr3));
542 if (no_shared_cr3)
543 kprintf("Kernel not sharing user map\n");
544
545 #ifdef PMAP_TRACES
546 if (PE_parse_boot_argn("-pmap_trace", &pmap_trace, sizeof (pmap_trace))) {
547 kprintf("Kernel traces for pmap operations enabled\n");
548 }
549 #endif /* PMAP_TRACES */
550
551 #if MACH_ASSERT
552 PE_parse_boot_argn("pmap_stats_assert",
553 &pmap_stats_assert,
554 sizeof (pmap_stats_assert));
555 #endif /* MACH_ASSERT */
556 }
557
558 void
559 pmap_virtual_space(
560 vm_offset_t *startp,
561 vm_offset_t *endp)
562 {
563 *startp = virtual_avail;
564 *endp = virtual_end;
565 }
566
567
568
569
570 #if HIBERNATION
571
572 #include <IOKit/IOHibernatePrivate.h>
573
574 int32_t pmap_npages;
575 int32_t pmap_teardown_last_valid_compact_indx = -1;
576
577
578 void hibernate_rebuild_pmap_structs(void);
579 void hibernate_teardown_pmap_structs(addr64_t *, addr64_t *);
580 void pmap_pack_index(uint32_t);
581 int32_t pmap_unpack_index(pv_rooted_entry_t);
582
583
584 int32_t
585 pmap_unpack_index(pv_rooted_entry_t pv_h)
586 {
587 int32_t indx = 0;
588
589 indx = (int32_t)(*((uint64_t *)(&pv_h->qlink.next)) >> 48);
590 indx = indx << 16;
591 indx |= (int32_t)(*((uint64_t *)(&pv_h->qlink.prev)) >> 48);
592
593 *((uint64_t *)(&pv_h->qlink.next)) |= ((uint64_t)0xffff << 48);
594 *((uint64_t *)(&pv_h->qlink.prev)) |= ((uint64_t)0xffff << 48);
595
596 return (indx);
597 }
598
599
600 void
601 pmap_pack_index(uint32_t indx)
602 {
603 pv_rooted_entry_t pv_h;
604
605 pv_h = &pv_head_table[indx];
606
607 *((uint64_t *)(&pv_h->qlink.next)) &= ~((uint64_t)0xffff << 48);
608 *((uint64_t *)(&pv_h->qlink.prev)) &= ~((uint64_t)0xffff << 48);
609
610 *((uint64_t *)(&pv_h->qlink.next)) |= ((uint64_t)(indx >> 16)) << 48;
611 *((uint64_t *)(&pv_h->qlink.prev)) |= ((uint64_t)(indx & 0xffff)) << 48;
612 }
613
614
615 void
616 hibernate_teardown_pmap_structs(addr64_t *unneeded_start, addr64_t *unneeded_end)
617 {
618 int32_t i;
619 int32_t compact_target_indx;
620
621 compact_target_indx = 0;
622
623 for (i = 0; i < pmap_npages; i++) {
624 if (pv_head_table[i].pmap == PMAP_NULL) {
625
626 if (pv_head_table[compact_target_indx].pmap != PMAP_NULL)
627 compact_target_indx = i;
628 } else {
629 pmap_pack_index((uint32_t)i);
630
631 if (pv_head_table[compact_target_indx].pmap == PMAP_NULL) {
632 /*
633 * we've got a hole to fill, so
634 * move this pv_rooted_entry_t to it's new home
635 */
636 pv_head_table[compact_target_indx] = pv_head_table[i];
637 pv_head_table[i].pmap = PMAP_NULL;
638
639 pmap_teardown_last_valid_compact_indx = compact_target_indx;
640 compact_target_indx++;
641 } else
642 pmap_teardown_last_valid_compact_indx = i;
643 }
644 }
645 *unneeded_start = (addr64_t)&pv_head_table[pmap_teardown_last_valid_compact_indx+1];
646 *unneeded_end = (addr64_t)&pv_head_table[pmap_npages-1];
647
648 HIBLOG("hibernate_teardown_pmap_structs done: last_valid_compact_indx %d\n", pmap_teardown_last_valid_compact_indx);
649 }
650
651
652 void
653 hibernate_rebuild_pmap_structs(void)
654 {
655 int32_t cindx, eindx, rindx = 0;
656 pv_rooted_entry_t pv_h;
657
658 eindx = (int32_t)pmap_npages;
659
660 for (cindx = pmap_teardown_last_valid_compact_indx; cindx >= 0; cindx--) {
661
662 pv_h = &pv_head_table[cindx];
663
664 rindx = pmap_unpack_index(pv_h);
665 assert(rindx < pmap_npages);
666
667 if (rindx != cindx) {
668 /*
669 * this pv_rooted_entry_t was moved by hibernate_teardown_pmap_structs,
670 * so move it back to its real location
671 */
672 pv_head_table[rindx] = pv_head_table[cindx];
673 }
674 if (rindx+1 != eindx) {
675 /*
676 * the 'hole' between this vm_rooted_entry_t and the previous
677 * vm_rooted_entry_t we moved needs to be initialized as
678 * a range of zero'd vm_rooted_entry_t's
679 */
680 bzero((char *)&pv_head_table[rindx+1], (eindx - rindx - 1) * sizeof (struct pv_rooted_entry));
681 }
682 eindx = rindx;
683 }
684 if (rindx)
685 bzero ((char *)&pv_head_table[0], rindx * sizeof (struct pv_rooted_entry));
686
687 HIBLOG("hibernate_rebuild_pmap_structs done: last_valid_compact_indx %d\n", pmap_teardown_last_valid_compact_indx);
688 }
689
690 #endif
691
692 /*
693 * Initialize the pmap module.
694 * Called by vm_init, to initialize any structures that the pmap
695 * system needs to map virtual memory.
696 */
697 void
698 pmap_init(void)
699 {
700 long npages;
701 vm_offset_t addr;
702 vm_size_t s, vsize;
703 vm_map_offset_t vaddr;
704 ppnum_t ppn;
705
706
707 kernel_pmap->pm_obj_pml4 = &kpml4obj_object_store;
708 _vm_object_allocate((vm_object_size_t)NPML4PGS * PAGE_SIZE, &kpml4obj_object_store);
709
710 kernel_pmap->pm_obj_pdpt = &kpdptobj_object_store;
711 _vm_object_allocate((vm_object_size_t)NPDPTPGS * PAGE_SIZE, &kpdptobj_object_store);
712
713 kernel_pmap->pm_obj = &kptobj_object_store;
714 _vm_object_allocate((vm_object_size_t)NPDEPGS * PAGE_SIZE, &kptobj_object_store);
715
716 /*
717 * Allocate memory for the pv_head_table and its lock bits,
718 * the modify bit array, and the pte_page table.
719 */
720
721 /*
722 * zero bias all these arrays now instead of off avail_start
723 * so we cover all memory
724 */
725
726 npages = i386_btop(avail_end);
727 #if HIBERNATION
728 pmap_npages = (uint32_t)npages;
729 #endif
730 s = (vm_size_t) (sizeof(struct pv_rooted_entry) * npages
731 + (sizeof (struct pv_hashed_entry_t *) * (npvhashbuckets))
732 + pv_lock_table_size(npages)
733 + pv_hash_lock_table_size((npvhashbuckets))
734 + npages);
735 s = round_page(s);
736 if (kernel_memory_allocate(kernel_map, &addr, s, 0,
737 KMA_KOBJECT | KMA_PERMANENT, VM_KERN_MEMORY_PMAP)
738 != KERN_SUCCESS)
739 panic("pmap_init");
740
741 memset((char *)addr, 0, s);
742
743 vaddr = addr;
744 vsize = s;
745
746 #if PV_DEBUG
747 if (0 == npvhashmask) panic("npvhashmask not initialized");
748 #endif
749
750 /*
751 * Allocate the structures first to preserve word-alignment.
752 */
753 pv_head_table = (pv_rooted_entry_t) addr;
754 addr = (vm_offset_t) (pv_head_table + npages);
755
756 pv_hash_table = (pv_hashed_entry_t *)addr;
757 addr = (vm_offset_t) (pv_hash_table + (npvhashbuckets));
758
759 pv_lock_table = (char *) addr;
760 addr = (vm_offset_t) (pv_lock_table + pv_lock_table_size(npages));
761
762 pv_hash_lock_table = (char *) addr;
763 addr = (vm_offset_t) (pv_hash_lock_table + pv_hash_lock_table_size((npvhashbuckets)));
764
765 pmap_phys_attributes = (char *) addr;
766
767 ppnum_t last_pn = i386_btop(avail_end);
768 unsigned int i;
769 pmap_memory_region_t *pmptr = pmap_memory_regions;
770 for (i = 0; i < pmap_memory_region_count; i++, pmptr++) {
771 if (pmptr->type != kEfiConventionalMemory)
772 continue;
773 ppnum_t pn;
774 for (pn = pmptr->base; pn <= pmptr->end; pn++) {
775 if (pn < last_pn) {
776 pmap_phys_attributes[pn] |= PHYS_MANAGED;
777
778 if (pn > last_managed_page)
779 last_managed_page = pn;
780
781 if (pn >= lowest_hi && pn <= highest_hi)
782 pmap_phys_attributes[pn] |= PHYS_NOENCRYPT;
783 }
784 }
785 }
786 while (vsize) {
787 ppn = pmap_find_phys(kernel_pmap, vaddr);
788
789 pmap_phys_attributes[ppn] |= PHYS_NOENCRYPT;
790
791 vaddr += PAGE_SIZE;
792 vsize -= PAGE_SIZE;
793 }
794 /*
795 * Create the zone of physical maps,
796 * and of the physical-to-virtual entries.
797 */
798 s = (vm_size_t) sizeof(struct pmap);
799 pmap_zone = zinit(s, 400*s, 4096, "pmap"); /* XXX */
800 zone_change(pmap_zone, Z_NOENCRYPT, TRUE);
801
802 pmap_anchor_zone = zinit(PAGE_SIZE, task_max, PAGE_SIZE, "pagetable anchors");
803 zone_change(pmap_anchor_zone, Z_NOENCRYPT, TRUE);
804
805 /* The anchor is required to be page aligned. Zone debugging adds
806 * padding which may violate that requirement. Tell the zone
807 * subsystem that alignment is required.
808 */
809
810 zone_change(pmap_anchor_zone, Z_ALIGNMENT_REQUIRED, TRUE);
811
812 s = (vm_size_t) sizeof(struct pv_hashed_entry);
813 pv_hashed_list_zone = zinit(s, 10000*s /* Expandable zone */,
814 4096 * 3 /* LCM x86_64*/, "pv_list");
815 zone_change(pv_hashed_list_zone, Z_NOENCRYPT, TRUE);
816 zone_change(pv_hashed_list_zone, Z_GZALLOC_EXEMPT, TRUE);
817
818 /* create pv entries for kernel pages mapped by low level
819 startup code. these have to exist so we can pmap_remove()
820 e.g. kext pages from the middle of our addr space */
821
822 vaddr = (vm_map_offset_t) VM_MIN_KERNEL_ADDRESS;
823 for (ppn = VM_MIN_KERNEL_PAGE; ppn < i386_btop(avail_start); ppn++) {
824 pv_rooted_entry_t pv_e;
825
826 pv_e = pai_to_pvh(ppn);
827 pv_e->va_and_flags = vaddr;
828 vaddr += PAGE_SIZE;
829 pv_e->pmap = kernel_pmap;
830 queue_init(&pv_e->qlink);
831 }
832 pmap_initialized = TRUE;
833
834 max_preemption_latency_tsc = tmrCvt((uint64_t)MAX_PREEMPTION_LATENCY_NS, tscFCvtn2t);
835
836 /*
837 * Ensure the kernel's PML4 entry exists for the basement
838 * before this is shared with any user.
839 */
840 pmap_expand_pml4(kernel_pmap, KERNEL_BASEMENT, PMAP_EXPAND_OPTIONS_NONE);
841
842 #if CONFIG_VMX
843 pmap_ept_support_ad = vmx_hv_support() && (VMX_CAP(MSR_IA32_VMX_EPT_VPID_CAP, MSR_IA32_VMX_EPT_VPID_CAP_AD_SHIFT, 1) ? TRUE : FALSE);
844 pmap_eptp_flags = HV_VMX_EPTP_MEMORY_TYPE_WB | HV_VMX_EPTP_WALK_LENGTH(4) | (pmap_ept_support_ad ? HV_VMX_EPTP_ENABLE_AD_FLAGS : 0);
845 #endif /* CONFIG_VMX */
846 }
847
848 static
849 void pmap_mark_range(pmap_t npmap, uint64_t sv, uint64_t nxrosz, boolean_t NX, boolean_t ro) {
850 uint64_t ev = sv + nxrosz, cv = sv;
851 pd_entry_t *pdep;
852 pt_entry_t *ptep = NULL;
853
854 assert(!is_ept_pmap(npmap));
855
856 assert(((sv & 0xFFFULL) | (nxrosz & 0xFFFULL)) == 0);
857
858 for (pdep = pmap_pde(npmap, cv); pdep != NULL && (cv < ev);) {
859 uint64_t pdev = (cv & ~((uint64_t)PDEMASK));
860
861 if (*pdep & INTEL_PTE_PS) {
862 if (NX)
863 *pdep |= INTEL_PTE_NX;
864 if (ro)
865 *pdep &= ~INTEL_PTE_WRITE;
866 cv += NBPD;
867 cv &= ~((uint64_t) PDEMASK);
868 pdep = pmap_pde(npmap, cv);
869 continue;
870 }
871
872 for (ptep = pmap_pte(npmap, cv); ptep != NULL && (cv < (pdev + NBPD)) && (cv < ev);) {
873 if (NX)
874 *ptep |= INTEL_PTE_NX;
875 if (ro)
876 *ptep &= ~INTEL_PTE_WRITE;
877 cv += NBPT;
878 ptep = pmap_pte(npmap, cv);
879 }
880 }
881 DPRINTF("%s(0x%llx, 0x%llx, %u, %u): 0x%llx, 0x%llx\n", __FUNCTION__, sv, nxrosz, NX, ro, cv, ptep ? *ptep: 0);
882 }
883
884 /*
885 * Called once VM is fully initialized so that we can release unused
886 * sections of low memory to the general pool.
887 * Also complete the set-up of identity-mapped sections of the kernel:
888 * 1) write-protect kernel text
889 * 2) map kernel text using large pages if possible
890 * 3) read and write-protect page zero (for K32)
891 * 4) map the global page at the appropriate virtual address.
892 *
893 * Use of large pages
894 * ------------------
895 * To effectively map and write-protect all kernel text pages, the text
896 * must be 2M-aligned at the base, and the data section above must also be
897 * 2M-aligned. That is, there's padding below and above. This is achieved
898 * through linker directives. Large pages are used only if this alignment
899 * exists (and not overriden by the -kernel_text_page_4K boot-arg). The
900 * memory layout is:
901 *
902 * : :
903 * | __DATA |
904 * sdata: ================== 2Meg
905 * | |
906 * | zero-padding |
907 * | |
908 * etext: ------------------
909 * | |
910 * : :
911 * | |
912 * | __TEXT |
913 * | |
914 * : :
915 * | |
916 * stext: ================== 2Meg
917 * | |
918 * | zero-padding |
919 * | |
920 * eHIB: ------------------
921 * | __HIB |
922 * : :
923 *
924 * Prior to changing the mapping from 4K to 2M, the zero-padding pages
925 * [eHIB,stext] and [etext,sdata] are ml_static_mfree()'d. Then all the
926 * 4K pages covering [stext,etext] are coalesced as 2M large pages.
927 * The now unused level-1 PTE pages are also freed.
928 */
929 extern ppnum_t vm_kernel_base_page;
930 static uint32_t constptes = 0, dataptes = 0;
931
932 void pmap_lowmem_finalize(void) {
933 spl_t spl;
934 int i;
935
936 /*
937 * Update wired memory statistics for early boot pages
938 */
939 PMAP_ZINFO_PALLOC(kernel_pmap, bootstrap_wired_pages * PAGE_SIZE);
940
941 /*
942 * Free pages in pmap regions below the base:
943 * rdar://6332712
944 * We can't free all the pages to VM that EFI reports available.
945 * Pages in the range 0xc0000-0xff000 aren't safe over sleep/wake.
946 * There's also a size miscalculation here: pend is one page less
947 * than it should be but this is not fixed to be backwards
948 * compatible.
949 * This is important for KASLR because up to 256*2MB = 512MB of space
950 * needs has to be released to VM.
951 */
952 for (i = 0;
953 pmap_memory_regions[i].end < vm_kernel_base_page;
954 i++) {
955 vm_offset_t pbase = i386_ptob(pmap_memory_regions[i].base);
956 vm_offset_t pend = i386_ptob(pmap_memory_regions[i].end+1);
957
958 DBG("pmap region %d [%p..[%p\n",
959 i, (void *) pbase, (void *) pend);
960
961 if (pmap_memory_regions[i].attribute & EFI_MEMORY_KERN_RESERVED)
962 continue;
963 /*
964 * rdar://6332712
965 * Adjust limits not to free pages in range 0xc0000-0xff000.
966 */
967 if (pbase >= 0xc0000 && pend <= 0x100000)
968 continue;
969 if (pbase < 0xc0000 && pend > 0x100000) {
970 /* page range entirely within region, free lower part */
971 DBG("- ml_static_mfree(%p,%p)\n",
972 (void *) ml_static_ptovirt(pbase),
973 (void *) (0xc0000-pbase));
974 ml_static_mfree(ml_static_ptovirt(pbase),0xc0000-pbase);
975 pbase = 0x100000;
976 }
977 if (pbase < 0xc0000)
978 pend = MIN(pend, 0xc0000);
979 if (pend > 0x100000)
980 pbase = MAX(pbase, 0x100000);
981 DBG("- ml_static_mfree(%p,%p)\n",
982 (void *) ml_static_ptovirt(pbase),
983 (void *) (pend - pbase));
984 ml_static_mfree(ml_static_ptovirt(pbase), pend - pbase);
985 }
986
987 /* A final pass to get rid of all initial identity mappings to
988 * low pages.
989 */
990 DPRINTF("%s: Removing mappings from 0->0x%lx\n", __FUNCTION__, vm_kernel_base);
991
992 /*
993 * Remove all mappings past the boot-cpu descriptor aliases and low globals.
994 * Non-boot-cpu GDT aliases will be remapped later as needed.
995 */
996 pmap_remove(kernel_pmap, LOWGLOBAL_ALIAS + PAGE_SIZE, vm_kernel_base);
997
998 /*
999 * If text and data are both 2MB-aligned,
1000 * we can map text with large-pages,
1001 * unless the -kernel_text_ps_4K boot-arg overrides.
1002 */
1003 if ((stext & I386_LPGMASK) == 0 && (sdata & I386_LPGMASK) == 0) {
1004 kprintf("Kernel text is 2MB aligned");
1005 kernel_text_ps_4K = FALSE;
1006 if (PE_parse_boot_argn("-kernel_text_ps_4K",
1007 &kernel_text_ps_4K,
1008 sizeof (kernel_text_ps_4K)))
1009 kprintf(" but will be mapped with 4K pages\n");
1010 else
1011 kprintf(" and will be mapped with 2M pages\n");
1012 }
1013
1014 (void) PE_parse_boot_argn("wpkernel", &wpkernel, sizeof (wpkernel));
1015 if (wpkernel)
1016 kprintf("Kernel text %p-%p to be write-protected\n",
1017 (void *) stext, (void *) etext);
1018
1019 spl = splhigh();
1020
1021 /*
1022 * Scan over text if mappings are to be changed:
1023 * - Remap kernel text readonly unless the "wpkernel" boot-arg is 0
1024 * - Change to large-pages if possible and not overriden.
1025 */
1026 if (kernel_text_ps_4K && wpkernel) {
1027 vm_offset_t myva;
1028 for (myva = stext; myva < etext; myva += PAGE_SIZE) {
1029 pt_entry_t *ptep;
1030
1031 ptep = pmap_pte(kernel_pmap, (vm_map_offset_t)myva);
1032 if (ptep)
1033 pmap_store_pte(ptep, *ptep & ~INTEL_PTE_WRITE);
1034 }
1035 }
1036
1037 if (!kernel_text_ps_4K) {
1038 vm_offset_t myva;
1039
1040 /*
1041 * Release zero-filled page padding used for 2M-alignment.
1042 */
1043 DBG("ml_static_mfree(%p,%p) for padding below text\n",
1044 (void *) eHIB, (void *) (stext - eHIB));
1045 ml_static_mfree(eHIB, stext - eHIB);
1046 DBG("ml_static_mfree(%p,%p) for padding above text\n",
1047 (void *) etext, (void *) (sdata - etext));
1048 ml_static_mfree(etext, sdata - etext);
1049
1050 /*
1051 * Coalesce text pages into large pages.
1052 */
1053 for (myva = stext; myva < sdata; myva += I386_LPGBYTES) {
1054 pt_entry_t *ptep;
1055 vm_offset_t pte_phys;
1056 pt_entry_t *pdep;
1057 pt_entry_t pde;
1058
1059 pdep = pmap_pde(kernel_pmap, (vm_map_offset_t)myva);
1060 ptep = pmap_pte(kernel_pmap, (vm_map_offset_t)myva);
1061 DBG("myva: %p pdep: %p ptep: %p\n",
1062 (void *) myva, (void *) pdep, (void *) ptep);
1063 if ((*ptep & INTEL_PTE_VALID) == 0)
1064 continue;
1065 pte_phys = (vm_offset_t)(*ptep & PG_FRAME);
1066 pde = *pdep & PTMASK; /* page attributes from pde */
1067 pde |= INTEL_PTE_PS; /* make it a 2M entry */
1068 pde |= pte_phys; /* take page frame from pte */
1069
1070 if (wpkernel)
1071 pde &= ~INTEL_PTE_WRITE;
1072 DBG("pmap_store_pte(%p,0x%llx)\n",
1073 (void *)pdep, pde);
1074 pmap_store_pte(pdep, pde);
1075
1076 /*
1077 * Free the now-unused level-1 pte.
1078 * Note: ptep is a virtual address to the pte in the
1079 * recursive map. We can't use this address to free
1080 * the page. Instead we need to compute its address
1081 * in the Idle PTEs in "low memory".
1082 */
1083 vm_offset_t vm_ptep = (vm_offset_t) KPTphys
1084 + (pte_phys >> PTPGSHIFT);
1085 DBG("ml_static_mfree(%p,0x%x) for pte\n",
1086 (void *) vm_ptep, PAGE_SIZE);
1087 ml_static_mfree(vm_ptep, PAGE_SIZE);
1088 }
1089
1090 /* Change variable read by sysctl machdep.pmap */
1091 pmap_kernel_text_ps = I386_LPGBYTES;
1092 }
1093
1094 boolean_t doconstro = TRUE;
1095 #if DEVELOPMENT || DEBUG
1096 (void) PE_parse_boot_argn("dataconstro", &doconstro, sizeof(doconstro));
1097 #endif
1098 if (doconstro) {
1099 if (sconst & PAGE_MASK) {
1100 panic("CONST segment misaligned 0x%lx 0x%lx\n",
1101 sconst, econst);
1102 }
1103 kprintf("Marking const DATA read-only\n");
1104 }
1105
1106 vm_offset_t dva;
1107
1108 for (dva = sdata; dva < edata; dva += I386_PGBYTES) {
1109 assert(((sdata | edata) & PAGE_MASK) == 0);
1110 pt_entry_t dpte, *dptep = pmap_pte(kernel_pmap, dva);
1111
1112 dpte = *dptep;
1113 assert((dpte & INTEL_PTE_VALID));
1114 dpte |= INTEL_PTE_NX;
1115 pmap_store_pte(dptep, dpte);
1116 dataptes++;
1117 }
1118 assert(dataptes > 0);
1119
1120 for (dva = sconst; dva < econst; dva += I386_PGBYTES) {
1121 pt_entry_t dpte, *dptep = pmap_pte(kernel_pmap, dva);
1122
1123 dpte = *dptep;
1124
1125 assert((dpte & INTEL_PTE_VALID));
1126 dpte |= INTEL_PTE_NX;
1127 dpte &= ~INTEL_PTE_WRITE;
1128 constptes++;
1129 pmap_store_pte(dptep, dpte);
1130 }
1131
1132 assert(constptes > 0);
1133
1134 kernel_segment_command_t * seg;
1135 kernel_section_t * sec;
1136
1137 for (seg = firstseg(); seg != NULL; seg = nextsegfromheader(&_mh_execute_header, seg)) {
1138 if (!strcmp(seg->segname, "__TEXT") ||
1139 !strcmp(seg->segname, "__DATA")) {
1140 continue;
1141 }
1142 //XXX
1143 if (!strcmp(seg->segname, "__KLD")) {
1144 continue;
1145 }
1146 if (!strcmp(seg->segname, "__HIB")) {
1147 for (sec = firstsect(seg); sec != NULL; sec = nextsect(seg, sec)) {
1148 if (sec->addr & PAGE_MASK)
1149 panic("__HIB segment's sections misaligned");
1150 if (!strcmp(sec->sectname, "__text")) {
1151 pmap_mark_range(kernel_pmap, sec->addr, round_page(sec->size), FALSE, TRUE);
1152 } else {
1153 pmap_mark_range(kernel_pmap, sec->addr, round_page(sec->size), TRUE, FALSE);
1154 }
1155 }
1156 } else {
1157 pmap_mark_range(kernel_pmap, seg->vmaddr, round_page_64(seg->vmsize), TRUE, FALSE);
1158 }
1159 }
1160
1161 /*
1162 * If we're debugging, map the low global vector page at the fixed
1163 * virtual address. Otherwise, remove the mapping for this.
1164 */
1165 if (debug_boot_arg) {
1166 pt_entry_t *pte = NULL;
1167 if (0 == (pte = pmap_pte(kernel_pmap, LOWGLOBAL_ALIAS)))
1168 panic("lowmem pte");
1169 /* make sure it is defined on page boundary */
1170 assert(0 == ((vm_offset_t) &lowGlo & PAGE_MASK));
1171 pmap_store_pte(pte, kvtophys((vm_offset_t)&lowGlo)
1172 | INTEL_PTE_REF
1173 | INTEL_PTE_MOD
1174 | INTEL_PTE_WIRED
1175 | INTEL_PTE_VALID
1176 | INTEL_PTE_WRITE
1177 | INTEL_PTE_NX);
1178 } else {
1179 pmap_remove(kernel_pmap,
1180 LOWGLOBAL_ALIAS, LOWGLOBAL_ALIAS + PAGE_SIZE);
1181 }
1182
1183 splx(spl);
1184 if (pmap_pcid_ncpus)
1185 tlb_flush_global();
1186 else
1187 flush_tlb_raw();
1188 }
1189
1190 /*
1191 * this function is only used for debugging fron the vm layer
1192 */
1193 boolean_t
1194 pmap_verify_free(
1195 ppnum_t pn)
1196 {
1197 pv_rooted_entry_t pv_h;
1198 int pai;
1199 boolean_t result;
1200
1201 assert(pn != vm_page_fictitious_addr);
1202
1203 if (!pmap_initialized)
1204 return(TRUE);
1205
1206 if (pn == vm_page_guard_addr)
1207 return TRUE;
1208
1209 pai = ppn_to_pai(pn);
1210 if (!IS_MANAGED_PAGE(pai))
1211 return(FALSE);
1212 pv_h = pai_to_pvh(pn);
1213 result = (pv_h->pmap == PMAP_NULL);
1214 return(result);
1215 }
1216
1217 boolean_t
1218 pmap_is_empty(
1219 pmap_t pmap,
1220 vm_map_offset_t va_start,
1221 vm_map_offset_t va_end)
1222 {
1223 vm_map_offset_t offset;
1224 ppnum_t phys_page;
1225
1226 if (pmap == PMAP_NULL) {
1227 return TRUE;
1228 }
1229
1230 /*
1231 * Check the resident page count
1232 * - if it's zero, the pmap is completely empty.
1233 * This short-circuit test prevents a virtual address scan which is
1234 * painfully slow for 64-bit spaces.
1235 * This assumes the count is correct
1236 * .. the debug kernel ought to be checking perhaps by page table walk.
1237 */
1238 if (pmap->stats.resident_count == 0)
1239 return TRUE;
1240
1241 for (offset = va_start;
1242 offset < va_end;
1243 offset += PAGE_SIZE_64) {
1244 phys_page = pmap_find_phys(pmap, offset);
1245 if (phys_page) {
1246 kprintf("pmap_is_empty(%p,0x%llx,0x%llx): "
1247 "page %d at 0x%llx\n",
1248 pmap, va_start, va_end, phys_page, offset);
1249 return FALSE;
1250 }
1251 }
1252
1253 return TRUE;
1254 }
1255
1256 void
1257 hv_ept_pmap_create(void **ept_pmap, void **eptp)
1258 {
1259 pmap_t p;
1260
1261 if ((ept_pmap == NULL) || (eptp == NULL)) {
1262 return;
1263 }
1264
1265 p = pmap_create_options(get_task_ledger(current_task()), 0, (PMAP_CREATE_64BIT | PMAP_CREATE_EPT));
1266 if (p == PMAP_NULL) {
1267 *ept_pmap = NULL;
1268 *eptp = NULL;
1269 return;
1270 }
1271
1272 assert(is_ept_pmap(p));
1273
1274 *ept_pmap = (void*)p;
1275 *eptp = (void*)(p->pm_eptp);
1276 return;
1277 }
1278
1279 /*
1280 * Create and return a physical map.
1281 *
1282 * If the size specified for the map
1283 * is zero, the map is an actual physical
1284 * map, and may be referenced by the
1285 * hardware.
1286 *
1287 * If the size specified is non-zero,
1288 * the map will be used in software only, and
1289 * is bounded by that size.
1290 */
1291 pmap_t
1292 pmap_create_options(
1293 ledger_t ledger,
1294 vm_map_size_t sz,
1295 int flags)
1296 {
1297 pmap_t p;
1298 vm_size_t size;
1299 pml4_entry_t *pml4;
1300 pml4_entry_t *kpml4;
1301
1302 PMAP_TRACE(PMAP_CODE(PMAP__CREATE) | DBG_FUNC_START, sz, flags);
1303
1304 size = (vm_size_t) sz;
1305
1306 /*
1307 * A software use-only map doesn't even need a map.
1308 */
1309
1310 if (size != 0) {
1311 return(PMAP_NULL);
1312 }
1313
1314 /*
1315 * Return error when unrecognized flags are passed.
1316 */
1317 if ((flags & ~(PMAP_CREATE_KNOWN_FLAGS)) != 0) {
1318 return(PMAP_NULL);
1319 }
1320
1321 p = (pmap_t) zalloc(pmap_zone);
1322 if (PMAP_NULL == p)
1323 panic("pmap_create zalloc");
1324 /* Zero all fields */
1325 bzero(p, sizeof(*p));
1326 /* init counts now since we'll be bumping some */
1327 simple_lock_init(&p->lock, 0);
1328 #if 00
1329 p->stats.resident_count = 0;
1330 p->stats.resident_max = 0;
1331 p->stats.wired_count = 0;
1332 #else
1333 bzero(&p->stats, sizeof (p->stats));
1334 #endif
1335 p->ref_count = 1;
1336 p->nx_enabled = 1;
1337 p->pm_shared = FALSE;
1338 ledger_reference(ledger);
1339 p->ledger = ledger;
1340
1341 p->pm_task_map = ((flags & PMAP_CREATE_64BIT) ? TASK_MAP_64BIT : TASK_MAP_32BIT);
1342
1343 p->pagezero_accessible = FALSE;
1344
1345 if (pmap_pcid_ncpus) {
1346 pmap_pcid_initialize(p);
1347 }
1348
1349 p->pm_pml4 = zalloc(pmap_anchor_zone);
1350
1351 pmap_assert((((uintptr_t)p->pm_pml4) & PAGE_MASK) == 0);
1352
1353 memset((char *)p->pm_pml4, 0, PAGE_SIZE);
1354
1355 if (flags & PMAP_CREATE_EPT) {
1356 p->pm_eptp = (pmap_paddr_t)kvtophys((vm_offset_t)p->pm_pml4) | pmap_eptp_flags;
1357 p->pm_cr3 = 0;
1358 } else {
1359 p->pm_eptp = 0;
1360 p->pm_cr3 = (pmap_paddr_t)kvtophys((vm_offset_t)p->pm_pml4);
1361 }
1362
1363 /* allocate the vm_objs to hold the pdpt, pde and pte pages */
1364
1365 p->pm_obj_pml4 = vm_object_allocate((vm_object_size_t)(NPML4PGS) * PAGE_SIZE);
1366 if (NULL == p->pm_obj_pml4)
1367 panic("pmap_create pdpt obj");
1368
1369 p->pm_obj_pdpt = vm_object_allocate((vm_object_size_t)(NPDPTPGS) * PAGE_SIZE);
1370 if (NULL == p->pm_obj_pdpt)
1371 panic("pmap_create pdpt obj");
1372
1373 p->pm_obj = vm_object_allocate((vm_object_size_t)(NPDEPGS) * PAGE_SIZE);
1374 if (NULL == p->pm_obj)
1375 panic("pmap_create pte obj");
1376
1377 if (!(flags & PMAP_CREATE_EPT)) {
1378 /* All host pmaps share the kernel's pml4 */
1379 pml4 = pmap64_pml4(p, 0ULL);
1380 kpml4 = kernel_pmap->pm_pml4;
1381 pml4[KERNEL_PML4_INDEX] = kpml4[KERNEL_PML4_INDEX];
1382 pml4[KERNEL_KEXTS_INDEX] = kpml4[KERNEL_KEXTS_INDEX];
1383 pml4[KERNEL_PHYSMAP_PML4_INDEX] = kpml4[KERNEL_PHYSMAP_PML4_INDEX];
1384
1385 #if KASAN
1386 pml4[KERNEL_KASAN_PML4_INDEX0] = kpml4[KERNEL_KASAN_PML4_INDEX0];
1387 pml4[KERNEL_KASAN_PML4_INDEX1] = kpml4[KERNEL_KASAN_PML4_INDEX1];
1388 #endif
1389 }
1390
1391 #if MACH_ASSERT
1392 p->pmap_pid = 0;
1393 strlcpy(p->pmap_procname, "<nil>", sizeof (p->pmap_procname));
1394 #endif /* MACH_ASSERT */
1395
1396 PMAP_TRACE(PMAP_CODE(PMAP__CREATE) | DBG_FUNC_END,
1397 VM_KERNEL_ADDRHIDE(p));
1398
1399 return(p);
1400 }
1401
1402 pmap_t
1403 pmap_create(
1404 ledger_t ledger,
1405 vm_map_size_t sz,
1406 boolean_t is_64bit)
1407 {
1408 return pmap_create_options(ledger, sz, ((is_64bit) ? PMAP_CREATE_64BIT : 0));
1409 }
1410
1411 /*
1412 * We maintain stats and ledgers so that a task's physical footprint is:
1413 * phys_footprint = ((internal - alternate_accounting)
1414 * + (internal_compressed - alternate_accounting_compressed)
1415 * + iokit_mapped
1416 * + purgeable_nonvolatile
1417 * + purgeable_nonvolatile_compressed
1418 * + page_table)
1419 * where "alternate_accounting" includes "iokit" and "purgeable" memory.
1420 */
1421
1422 #if MACH_ASSERT
1423 struct {
1424 uint64_t num_pmaps_checked;
1425
1426 int phys_footprint_over;
1427 ledger_amount_t phys_footprint_over_total;
1428 ledger_amount_t phys_footprint_over_max;
1429 int phys_footprint_under;
1430 ledger_amount_t phys_footprint_under_total;
1431 ledger_amount_t phys_footprint_under_max;
1432
1433 int internal_over;
1434 ledger_amount_t internal_over_total;
1435 ledger_amount_t internal_over_max;
1436 int internal_under;
1437 ledger_amount_t internal_under_total;
1438 ledger_amount_t internal_under_max;
1439
1440 int internal_compressed_over;
1441 ledger_amount_t internal_compressed_over_total;
1442 ledger_amount_t internal_compressed_over_max;
1443 int internal_compressed_under;
1444 ledger_amount_t internal_compressed_under_total;
1445 ledger_amount_t internal_compressed_under_max;
1446
1447 int iokit_mapped_over;
1448 ledger_amount_t iokit_mapped_over_total;
1449 ledger_amount_t iokit_mapped_over_max;
1450 int iokit_mapped_under;
1451 ledger_amount_t iokit_mapped_under_total;
1452 ledger_amount_t iokit_mapped_under_max;
1453
1454 int alternate_accounting_over;
1455 ledger_amount_t alternate_accounting_over_total;
1456 ledger_amount_t alternate_accounting_over_max;
1457 int alternate_accounting_under;
1458 ledger_amount_t alternate_accounting_under_total;
1459 ledger_amount_t alternate_accounting_under_max;
1460
1461 int alternate_accounting_compressed_over;
1462 ledger_amount_t alternate_accounting_compressed_over_total;
1463 ledger_amount_t alternate_accounting_compressed_over_max;
1464 int alternate_accounting_compressed_under;
1465 ledger_amount_t alternate_accounting_compressed_under_total;
1466 ledger_amount_t alternate_accounting_compressed_under_max;
1467
1468 int page_table_over;
1469 ledger_amount_t page_table_over_total;
1470 ledger_amount_t page_table_over_max;
1471 int page_table_under;
1472 ledger_amount_t page_table_under_total;
1473 ledger_amount_t page_table_under_max;
1474
1475 int purgeable_volatile_over;
1476 ledger_amount_t purgeable_volatile_over_total;
1477 ledger_amount_t purgeable_volatile_over_max;
1478 int purgeable_volatile_under;
1479 ledger_amount_t purgeable_volatile_under_total;
1480 ledger_amount_t purgeable_volatile_under_max;
1481
1482 int purgeable_nonvolatile_over;
1483 ledger_amount_t purgeable_nonvolatile_over_total;
1484 ledger_amount_t purgeable_nonvolatile_over_max;
1485 int purgeable_nonvolatile_under;
1486 ledger_amount_t purgeable_nonvolatile_under_total;
1487 ledger_amount_t purgeable_nonvolatile_under_max;
1488
1489 int purgeable_volatile_compressed_over;
1490 ledger_amount_t purgeable_volatile_compressed_over_total;
1491 ledger_amount_t purgeable_volatile_compressed_over_max;
1492 int purgeable_volatile_compressed_under;
1493 ledger_amount_t purgeable_volatile_compressed_under_total;
1494 ledger_amount_t purgeable_volatile_compressed_under_max;
1495
1496 int purgeable_nonvolatile_compressed_over;
1497 ledger_amount_t purgeable_nonvolatile_compressed_over_total;
1498 ledger_amount_t purgeable_nonvolatile_compressed_over_max;
1499 int purgeable_nonvolatile_compressed_under;
1500 ledger_amount_t purgeable_nonvolatile_compressed_under_total;
1501 ledger_amount_t purgeable_nonvolatile_compressed_under_max;
1502 } pmap_ledgers_drift;
1503 static void pmap_check_ledgers(pmap_t pmap);
1504 #else /* MACH_ASSERT */
1505 static inline void pmap_check_ledgers(__unused pmap_t pmap) {}
1506 #endif /* MACH_ASSERT */
1507
1508 /*
1509 * Retire the given physical map from service.
1510 * Should only be called if the map contains
1511 * no valid mappings.
1512 */
1513 extern int vm_wired_objects_page_count;
1514
1515 void
1516 pmap_destroy(pmap_t p)
1517 {
1518 int c;
1519
1520 if (p == PMAP_NULL)
1521 return;
1522
1523 PMAP_TRACE(PMAP_CODE(PMAP__DESTROY) | DBG_FUNC_START,
1524 VM_KERNEL_ADDRHIDe(p));
1525
1526 PMAP_LOCK(p);
1527
1528 c = --p->ref_count;
1529
1530 pmap_assert((current_thread() && (current_thread()->map)) ? (current_thread()->map->pmap != p) : TRUE);
1531
1532 if (c == 0) {
1533 /*
1534 * If some cpu is not using the physical pmap pointer that it
1535 * is supposed to be (see set_dirbase), we might be using the
1536 * pmap that is being destroyed! Make sure we are
1537 * physically on the right pmap:
1538 */
1539 PMAP_UPDATE_TLBS(p, 0x0ULL, 0xFFFFFFFFFFFFF000ULL);
1540 if (pmap_pcid_ncpus)
1541 pmap_destroy_pcid_sync(p);
1542 }
1543
1544 PMAP_UNLOCK(p);
1545
1546 if (c != 0) {
1547 PMAP_TRACE(PMAP_CODE(PMAP__DESTROY) | DBG_FUNC_END);
1548 pmap_assert(p == kernel_pmap);
1549 return; /* still in use */
1550 }
1551
1552 /*
1553 * Free the memory maps, then the
1554 * pmap structure.
1555 */
1556 int inuse_ptepages = 0;
1557
1558 zfree(pmap_anchor_zone, p->pm_pml4);
1559
1560 inuse_ptepages += p->pm_obj_pml4->resident_page_count;
1561 vm_object_deallocate(p->pm_obj_pml4);
1562
1563 inuse_ptepages += p->pm_obj_pdpt->resident_page_count;
1564 vm_object_deallocate(p->pm_obj_pdpt);
1565
1566 inuse_ptepages += p->pm_obj->resident_page_count;
1567 vm_object_deallocate(p->pm_obj);
1568
1569 OSAddAtomic(-inuse_ptepages, &inuse_ptepages_count);
1570 PMAP_ZINFO_PFREE(p, inuse_ptepages * PAGE_SIZE);
1571
1572 pmap_check_ledgers(p);
1573 ledger_dereference(p->ledger);
1574 zfree(pmap_zone, p);
1575
1576 PMAP_TRACE(PMAP_CODE(PMAP__DESTROY) | DBG_FUNC_END);
1577 }
1578
1579 /*
1580 * Add a reference to the specified pmap.
1581 */
1582
1583 void
1584 pmap_reference(pmap_t p)
1585 {
1586 if (p != PMAP_NULL) {
1587 PMAP_LOCK(p);
1588 p->ref_count++;
1589 PMAP_UNLOCK(p);;
1590 }
1591 }
1592
1593 /*
1594 * Remove phys addr if mapped in specified map
1595 *
1596 */
1597 void
1598 pmap_remove_some_phys(
1599 __unused pmap_t map,
1600 __unused ppnum_t pn)
1601 {
1602
1603 /* Implement to support working set code */
1604
1605 }
1606
1607
1608 void
1609 pmap_protect(
1610 pmap_t map,
1611 vm_map_offset_t sva,
1612 vm_map_offset_t eva,
1613 vm_prot_t prot)
1614 {
1615 pmap_protect_options(map, sva, eva, prot, 0, NULL);
1616 }
1617
1618
1619 /*
1620 * Set the physical protection on the
1621 * specified range of this map as requested.
1622 * Will not increase permissions.
1623 */
1624 void
1625 pmap_protect_options(
1626 pmap_t map,
1627 vm_map_offset_t sva,
1628 vm_map_offset_t eva,
1629 vm_prot_t prot,
1630 unsigned int options,
1631 void *arg)
1632 {
1633 pt_entry_t *pde;
1634 pt_entry_t *spte, *epte;
1635 vm_map_offset_t lva;
1636 vm_map_offset_t orig_sva;
1637 boolean_t set_NX;
1638 int num_found = 0;
1639 boolean_t is_ept;
1640
1641 pmap_intr_assert();
1642
1643 if (map == PMAP_NULL)
1644 return;
1645
1646 if (prot == VM_PROT_NONE) {
1647 pmap_remove_options(map, sva, eva, options);
1648 return;
1649 }
1650
1651 PMAP_TRACE(PMAP_CODE(PMAP__PROTECT) | DBG_FUNC_START,
1652 VM_KERNEL_ADDRHIDE(map), VM_KERNEL_ADDRHIDE(sva),
1653 VM_KERNEL_ADDRHIDE(eva));
1654
1655 if ((prot & VM_PROT_EXECUTE) || !nx_enabled || !map->nx_enabled)
1656 set_NX = FALSE;
1657 else
1658 set_NX = TRUE;
1659
1660 is_ept = is_ept_pmap(map);
1661
1662
1663 PMAP_LOCK(map);
1664
1665 orig_sva = sva;
1666 while (sva < eva) {
1667 lva = (sva + pde_mapped_size) & ~(pde_mapped_size - 1);
1668 if (lva > eva)
1669 lva = eva;
1670 pde = pmap_pde(map, sva);
1671 if (pde && (*pde & PTE_VALID_MASK(is_ept))) {
1672 if (*pde & PTE_PS) {
1673 /* superpage */
1674 spte = pde;
1675 epte = spte+1; /* excluded */
1676 } else {
1677 spte = pmap_pte(map, (sva & ~(pde_mapped_size - 1)));
1678 spte = &spte[ptenum(sva)];
1679 epte = &spte[intel_btop(lva - sva)];
1680 }
1681
1682 for (; spte < epte; spte++) {
1683 if (!(*spte & PTE_VALID_MASK(is_ept)))
1684 continue;
1685
1686 if (is_ept) {
1687 if (prot & VM_PROT_READ)
1688 pmap_update_pte(spte, 0, PTE_READ(is_ept));
1689 else
1690 pmap_update_pte(spte, PTE_READ(is_ept), 0);
1691 }
1692 if (prot & VM_PROT_WRITE)
1693 pmap_update_pte(spte, 0, PTE_WRITE(is_ept));
1694 else
1695 pmap_update_pte(spte, PTE_WRITE(is_ept), 0);
1696
1697 if (set_NX) {
1698 if (!is_ept)
1699 pmap_update_pte(spte, 0, INTEL_PTE_NX);
1700 else
1701 pmap_update_pte(spte, INTEL_EPT_EX, 0);
1702 } else {
1703 if (!is_ept)
1704 pmap_update_pte(spte, INTEL_PTE_NX, 0);
1705 else
1706 pmap_update_pte(spte, 0, INTEL_EPT_EX);
1707 }
1708 num_found++;
1709 }
1710 }
1711 sva = lva;
1712 }
1713 if (num_found) {
1714 if (options & PMAP_OPTIONS_NOFLUSH)
1715 PMAP_UPDATE_TLBS_DELAYED(map, orig_sva, eva, (pmap_flush_context *)arg);
1716 else
1717 PMAP_UPDATE_TLBS(map, orig_sva, eva);
1718 }
1719 PMAP_UNLOCK(map);
1720
1721 PMAP_TRACE(PMAP_CODE(PMAP__PROTECT) | DBG_FUNC_END);
1722
1723 }
1724
1725 /* Map a (possibly) autogenned block */
1726 kern_return_t
1727 pmap_map_block(
1728 pmap_t pmap,
1729 addr64_t va,
1730 ppnum_t pa,
1731 uint32_t size,
1732 vm_prot_t prot,
1733 int attr,
1734 __unused unsigned int flags)
1735 {
1736 kern_return_t kr;
1737 addr64_t original_va = va;
1738 uint32_t page;
1739 int cur_page_size;
1740
1741 if (attr & VM_MEM_SUPERPAGE)
1742 cur_page_size = SUPERPAGE_SIZE;
1743 else
1744 cur_page_size = PAGE_SIZE;
1745
1746 for (page = 0; page < size; page+=cur_page_size/PAGE_SIZE) {
1747 kr = pmap_enter(pmap, va, pa, prot, VM_PROT_NONE, attr, TRUE);
1748
1749 if (kr != KERN_SUCCESS) {
1750 /*
1751 * This will panic for now, as it is unclear that
1752 * removing the mappings is correct.
1753 */
1754 panic("%s: failed pmap_enter, "
1755 "pmap=%p, va=%#llx, pa=%u, size=%u, prot=%#x, flags=%#x",
1756 __FUNCTION__,
1757 pmap, va, pa, size, prot, flags);
1758
1759 pmap_remove(pmap, original_va, va - original_va);
1760 return kr;
1761 }
1762
1763 va += cur_page_size;
1764 pa+=cur_page_size/PAGE_SIZE;
1765 }
1766
1767 return KERN_SUCCESS;
1768 }
1769
1770 kern_return_t
1771 pmap_expand_pml4(
1772 pmap_t map,
1773 vm_map_offset_t vaddr,
1774 unsigned int options)
1775 {
1776 vm_page_t m;
1777 pmap_paddr_t pa;
1778 uint64_t i;
1779 ppnum_t pn;
1780 pml4_entry_t *pml4p;
1781 boolean_t is_ept = is_ept_pmap(map);
1782
1783 DBG("pmap_expand_pml4(%p,%p)\n", map, (void *)vaddr);
1784
1785 /*
1786 * Allocate a VM page for the pml4 page
1787 */
1788 while ((m = vm_page_grab()) == VM_PAGE_NULL) {
1789 if (options & PMAP_EXPAND_OPTIONS_NOWAIT)
1790 return KERN_RESOURCE_SHORTAGE;
1791 VM_PAGE_WAIT();
1792 }
1793 /*
1794 * put the page into the pmap's obj list so it
1795 * can be found later.
1796 */
1797 pn = VM_PAGE_GET_PHYS_PAGE(m);
1798 pa = i386_ptob(pn);
1799 i = pml4idx(map, vaddr);
1800
1801 /*
1802 * Zero the page.
1803 */
1804 pmap_zero_page(pn);
1805
1806 vm_page_lockspin_queues();
1807 vm_page_wire(m, VM_KERN_MEMORY_PTE, TRUE);
1808 vm_page_unlock_queues();
1809
1810 OSAddAtomic(1, &inuse_ptepages_count);
1811 OSAddAtomic64(1, &alloc_ptepages_count);
1812 PMAP_ZINFO_PALLOC(map, PAGE_SIZE);
1813
1814 /* Take the oject lock (mutex) before the PMAP_LOCK (spinlock) */
1815 vm_object_lock(map->pm_obj_pml4);
1816
1817 PMAP_LOCK(map);
1818 /*
1819 * See if someone else expanded us first
1820 */
1821 if (pmap64_pdpt(map, vaddr) != PDPT_ENTRY_NULL) {
1822 PMAP_UNLOCK(map);
1823 vm_object_unlock(map->pm_obj_pml4);
1824
1825 VM_PAGE_FREE(m);
1826
1827 OSAddAtomic(-1, &inuse_ptepages_count);
1828 PMAP_ZINFO_PFREE(map, PAGE_SIZE);
1829 return KERN_SUCCESS;
1830 }
1831
1832 #if 0 /* DEBUG */
1833 if (0 != vm_page_lookup(map->pm_obj_pml4, (vm_object_offset_t)i * PAGE_SIZE)) {
1834 panic("pmap_expand_pml4: obj not empty, pmap %p pm_obj %p vaddr 0x%llx i 0x%llx\n",
1835 map, map->pm_obj_pml4, vaddr, i);
1836 }
1837 #endif
1838 vm_page_insert_wired(m, map->pm_obj_pml4, (vm_object_offset_t)i * PAGE_SIZE, VM_KERN_MEMORY_PTE);
1839 vm_object_unlock(map->pm_obj_pml4);
1840
1841 /*
1842 * Set the page directory entry for this page table.
1843 */
1844 pml4p = pmap64_pml4(map, vaddr); /* refetch under lock */
1845
1846 pmap_store_pte(pml4p, pa_to_pte(pa)
1847 | PTE_READ(is_ept)
1848 | (is_ept ? INTEL_EPT_EX : INTEL_PTE_USER)
1849 | PTE_WRITE(is_ept));
1850
1851 PMAP_UNLOCK(map);
1852
1853 return KERN_SUCCESS;
1854 }
1855
1856 kern_return_t
1857 pmap_expand_pdpt(pmap_t map, vm_map_offset_t vaddr, unsigned int options)
1858 {
1859 vm_page_t m;
1860 pmap_paddr_t pa;
1861 uint64_t i;
1862 ppnum_t pn;
1863 pdpt_entry_t *pdptp;
1864 boolean_t is_ept = is_ept_pmap(map);
1865
1866 DBG("pmap_expand_pdpt(%p,%p)\n", map, (void *)vaddr);
1867
1868 while ((pdptp = pmap64_pdpt(map, vaddr)) == PDPT_ENTRY_NULL) {
1869 kern_return_t pep4kr = pmap_expand_pml4(map, vaddr, options);
1870 if (pep4kr != KERN_SUCCESS)
1871 return pep4kr;
1872 }
1873
1874 /*
1875 * Allocate a VM page for the pdpt page
1876 */
1877 while ((m = vm_page_grab()) == VM_PAGE_NULL) {
1878 if (options & PMAP_EXPAND_OPTIONS_NOWAIT)
1879 return KERN_RESOURCE_SHORTAGE;
1880 VM_PAGE_WAIT();
1881 }
1882
1883 /*
1884 * put the page into the pmap's obj list so it
1885 * can be found later.
1886 */
1887 pn = VM_PAGE_GET_PHYS_PAGE(m);
1888 pa = i386_ptob(pn);
1889 i = pdptidx(map, vaddr);
1890
1891 /*
1892 * Zero the page.
1893 */
1894 pmap_zero_page(pn);
1895
1896 vm_page_lockspin_queues();
1897 vm_page_wire(m, VM_KERN_MEMORY_PTE, TRUE);
1898 vm_page_unlock_queues();
1899
1900 OSAddAtomic(1, &inuse_ptepages_count);
1901 OSAddAtomic64(1, &alloc_ptepages_count);
1902 PMAP_ZINFO_PALLOC(map, PAGE_SIZE);
1903
1904 /* Take the oject lock (mutex) before the PMAP_LOCK (spinlock) */
1905 vm_object_lock(map->pm_obj_pdpt);
1906
1907 PMAP_LOCK(map);
1908 /*
1909 * See if someone else expanded us first
1910 */
1911 if (pmap64_pde(map, vaddr) != PD_ENTRY_NULL) {
1912 PMAP_UNLOCK(map);
1913 vm_object_unlock(map->pm_obj_pdpt);
1914
1915 VM_PAGE_FREE(m);
1916
1917 OSAddAtomic(-1, &inuse_ptepages_count);
1918 PMAP_ZINFO_PFREE(map, PAGE_SIZE);
1919 return KERN_SUCCESS;
1920 }
1921
1922 #if 0 /* DEBUG */
1923 if (0 != vm_page_lookup(map->pm_obj_pdpt, (vm_object_offset_t)i * PAGE_SIZE)) {
1924 panic("pmap_expand_pdpt: obj not empty, pmap %p pm_obj %p vaddr 0x%llx i 0x%llx\n",
1925 map, map->pm_obj_pdpt, vaddr, i);
1926 }
1927 #endif
1928 vm_page_insert_wired(m, map->pm_obj_pdpt, (vm_object_offset_t)i * PAGE_SIZE, VM_KERN_MEMORY_PTE);
1929 vm_object_unlock(map->pm_obj_pdpt);
1930
1931 /*
1932 * Set the page directory entry for this page table.
1933 */
1934 pdptp = pmap64_pdpt(map, vaddr); /* refetch under lock */
1935
1936 pmap_store_pte(pdptp, pa_to_pte(pa)
1937 | PTE_READ(is_ept)
1938 | (is_ept ? INTEL_EPT_EX : INTEL_PTE_USER)
1939 | PTE_WRITE(is_ept));
1940
1941 PMAP_UNLOCK(map);
1942
1943 return KERN_SUCCESS;
1944
1945 }
1946
1947
1948
1949 /*
1950 * Routine: pmap_expand
1951 *
1952 * Expands a pmap to be able to map the specified virtual address.
1953 *
1954 * Allocates new virtual memory for the P0 or P1 portion of the
1955 * pmap, then re-maps the physical pages that were in the old
1956 * pmap to be in the new pmap.
1957 *
1958 * Must be called with the pmap system and the pmap unlocked,
1959 * since these must be unlocked to use vm_allocate or vm_deallocate.
1960 * Thus it must be called in a loop that checks whether the map
1961 * has been expanded enough.
1962 * (We won't loop forever, since page tables aren't shrunk.)
1963 */
1964 kern_return_t
1965 pmap_expand(
1966 pmap_t map,
1967 vm_map_offset_t vaddr,
1968 unsigned int options)
1969 {
1970 pt_entry_t *pdp;
1971 vm_page_t m;
1972 pmap_paddr_t pa;
1973 uint64_t i;
1974 ppnum_t pn;
1975 boolean_t is_ept = is_ept_pmap(map);
1976
1977
1978 /*
1979 * For the kernel, the virtual address must be in or above the basement
1980 * which is for kexts and is in the 512GB immediately below the kernel..
1981 * XXX - should use VM_MIN_KERNEL_AND_KEXT_ADDRESS not KERNEL_BASEMENT
1982 */
1983 if (map == kernel_pmap &&
1984 !(vaddr >= KERNEL_BASEMENT && vaddr <= VM_MAX_KERNEL_ADDRESS))
1985 panic("pmap_expand: bad vaddr 0x%llx for kernel pmap", vaddr);
1986
1987
1988 while ((pdp = pmap64_pde(map, vaddr)) == PD_ENTRY_NULL) {
1989 kern_return_t pepkr = pmap_expand_pdpt(map, vaddr, options);
1990 if (pepkr != KERN_SUCCESS)
1991 return pepkr;
1992 }
1993
1994 /*
1995 * Allocate a VM page for the pde entries.
1996 */
1997 while ((m = vm_page_grab()) == VM_PAGE_NULL) {
1998 if (options & PMAP_EXPAND_OPTIONS_NOWAIT)
1999 return KERN_RESOURCE_SHORTAGE;
2000 VM_PAGE_WAIT();
2001 }
2002
2003 /*
2004 * put the page into the pmap's obj list so it
2005 * can be found later.
2006 */
2007 pn = VM_PAGE_GET_PHYS_PAGE(m);
2008 pa = i386_ptob(pn);
2009 i = pdeidx(map, vaddr);
2010
2011 /*
2012 * Zero the page.
2013 */
2014 pmap_zero_page(pn);
2015
2016 vm_page_lockspin_queues();
2017 vm_page_wire(m, VM_KERN_MEMORY_PTE, TRUE);
2018 vm_page_unlock_queues();
2019
2020 OSAddAtomic(1, &inuse_ptepages_count);
2021 OSAddAtomic64(1, &alloc_ptepages_count);
2022 PMAP_ZINFO_PALLOC(map, PAGE_SIZE);
2023
2024 /* Take the oject lock (mutex) before the PMAP_LOCK (spinlock) */
2025 vm_object_lock(map->pm_obj);
2026
2027 PMAP_LOCK(map);
2028
2029 /*
2030 * See if someone else expanded us first
2031 */
2032 if (pmap_pte(map, vaddr) != PT_ENTRY_NULL) {
2033 PMAP_UNLOCK(map);
2034 vm_object_unlock(map->pm_obj);
2035
2036 VM_PAGE_FREE(m);
2037
2038 OSAddAtomic(-1, &inuse_ptepages_count);
2039 PMAP_ZINFO_PFREE(map, PAGE_SIZE);
2040 return KERN_SUCCESS;
2041 }
2042
2043 #if 0 /* DEBUG */
2044 if (0 != vm_page_lookup(map->pm_obj, (vm_object_offset_t)i * PAGE_SIZE)) {
2045 panic("pmap_expand: obj not empty, pmap 0x%x pm_obj 0x%x vaddr 0x%llx i 0x%llx\n",
2046 map, map->pm_obj, vaddr, i);
2047 }
2048 #endif
2049 vm_page_insert_wired(m, map->pm_obj, (vm_object_offset_t)i * PAGE_SIZE, VM_KERN_MEMORY_PTE);
2050 vm_object_unlock(map->pm_obj);
2051
2052 /*
2053 * Set the page directory entry for this page table.
2054 */
2055 pdp = pmap_pde(map, vaddr);
2056 pmap_store_pte(pdp, pa_to_pte(pa)
2057 | PTE_READ(is_ept)
2058 | (is_ept ? INTEL_EPT_EX : INTEL_PTE_USER)
2059 | PTE_WRITE(is_ept));
2060
2061 PMAP_UNLOCK(map);
2062
2063 return KERN_SUCCESS;
2064 }
2065
2066 /* On K64 machines with more than 32GB of memory, pmap_steal_memory
2067 * will allocate past the 1GB of pre-expanded virtual kernel area. This
2068 * function allocates all the page tables using memory from the same pool
2069 * that pmap_steal_memory uses, rather than calling vm_page_grab (which
2070 * isn't available yet). */
2071 void
2072 pmap_pre_expand(pmap_t pmap, vm_map_offset_t vaddr)
2073 {
2074 ppnum_t pn;
2075 pt_entry_t *pte;
2076 boolean_t is_ept = is_ept_pmap(pmap);
2077
2078 PMAP_LOCK(pmap);
2079
2080 if(pmap64_pdpt(pmap, vaddr) == PDPT_ENTRY_NULL) {
2081 if (!pmap_next_page_hi(&pn))
2082 panic("pmap_pre_expand");
2083
2084 pmap_zero_page(pn);
2085
2086 pte = pmap64_pml4(pmap, vaddr);
2087
2088 pmap_store_pte(pte, pa_to_pte(i386_ptob(pn))
2089 | PTE_READ(is_ept)
2090 | (is_ept ? INTEL_EPT_EX : INTEL_PTE_USER)
2091 | PTE_WRITE(is_ept));
2092 }
2093
2094 if(pmap64_pde(pmap, vaddr) == PD_ENTRY_NULL) {
2095 if (!pmap_next_page_hi(&pn))
2096 panic("pmap_pre_expand");
2097
2098 pmap_zero_page(pn);
2099
2100 pte = pmap64_pdpt(pmap, vaddr);
2101
2102 pmap_store_pte(pte, pa_to_pte(i386_ptob(pn))
2103 | PTE_READ(is_ept)
2104 | (is_ept ? INTEL_EPT_EX : INTEL_PTE_USER)
2105 | PTE_WRITE(is_ept));
2106 }
2107
2108 if(pmap_pte(pmap, vaddr) == PT_ENTRY_NULL) {
2109 if (!pmap_next_page_hi(&pn))
2110 panic("pmap_pre_expand");
2111
2112 pmap_zero_page(pn);
2113
2114 pte = pmap64_pde(pmap, vaddr);
2115
2116 pmap_store_pte(pte, pa_to_pte(i386_ptob(pn))
2117 | PTE_READ(is_ept)
2118 | (is_ept ? INTEL_EPT_EX : INTEL_PTE_USER)
2119 | PTE_WRITE(is_ept));
2120 }
2121
2122 PMAP_UNLOCK(pmap);
2123 }
2124
2125 /*
2126 * pmap_sync_page_data_phys(ppnum_t pa)
2127 *
2128 * Invalidates all of the instruction cache on a physical page and
2129 * pushes any dirty data from the data cache for the same physical page
2130 * Not required in i386.
2131 */
2132 void
2133 pmap_sync_page_data_phys(__unused ppnum_t pa)
2134 {
2135 return;
2136 }
2137
2138 /*
2139 * pmap_sync_page_attributes_phys(ppnum_t pa)
2140 *
2141 * Write back and invalidate all cachelines on a physical page.
2142 */
2143 void
2144 pmap_sync_page_attributes_phys(ppnum_t pa)
2145 {
2146 cache_flush_page_phys(pa);
2147 }
2148
2149
2150
2151 #ifdef CURRENTLY_UNUSED_AND_UNTESTED
2152
2153 int collect_ref;
2154 int collect_unref;
2155
2156 /*
2157 * Routine: pmap_collect
2158 * Function:
2159 * Garbage collects the physical map system for
2160 * pages which are no longer used.
2161 * Success need not be guaranteed -- that is, there
2162 * may well be pages which are not referenced, but
2163 * others may be collected.
2164 * Usage:
2165 * Called by the pageout daemon when pages are scarce.
2166 */
2167 void
2168 pmap_collect(
2169 pmap_t p)
2170 {
2171 pt_entry_t *pdp, *ptp;
2172 pt_entry_t *eptp;
2173 int wired;
2174 boolean_t is_ept;
2175
2176 if (p == PMAP_NULL)
2177 return;
2178
2179 if (p == kernel_pmap)
2180 return;
2181
2182 is_ept = is_ept_pmap(p);
2183
2184 /*
2185 * Garbage collect map.
2186 */
2187 PMAP_LOCK(p);
2188
2189 for (pdp = (pt_entry_t *)p->dirbase;
2190 pdp < (pt_entry_t *)&p->dirbase[(UMAXPTDI+1)];
2191 pdp++)
2192 {
2193 if (*pdp & PTE_VALID_MASK(is_ept)) {
2194 if (*pdp & PTE_REF(is_ept)) {
2195 pmap_store_pte(pdp, *pdp & ~PTE_REF(is_ept));
2196 collect_ref++;
2197 } else {
2198 collect_unref++;
2199 ptp = pmap_pte(p, pdetova(pdp - (pt_entry_t *)p->dirbase));
2200 eptp = ptp + NPTEPG;
2201
2202 /*
2203 * If the pte page has any wired mappings, we cannot
2204 * free it.
2205 */
2206 wired = 0;
2207 {
2208 pt_entry_t *ptep;
2209 for (ptep = ptp; ptep < eptp; ptep++) {
2210 if (iswired(*ptep)) {
2211 wired = 1;
2212 break;
2213 }
2214 }
2215 }
2216 if (!wired) {
2217 /*
2218 * Remove the virtual addresses mapped by this pte page.
2219 */
2220 pmap_remove_range(p,
2221 pdetova(pdp - (pt_entry_t *)p->dirbase),
2222 ptp,
2223 eptp);
2224
2225 /*
2226 * Invalidate the page directory pointer.
2227 */
2228 pmap_store_pte(pdp, 0x0);
2229
2230 PMAP_UNLOCK(p);
2231
2232 /*
2233 * And free the pte page itself.
2234 */
2235 {
2236 vm_page_t m;
2237
2238 vm_object_lock(p->pm_obj);
2239
2240 m = vm_page_lookup(p->pm_obj,(vm_object_offset_t)(pdp - (pt_entry_t *)&p->dirbase[0]) * PAGE_SIZE);
2241 if (m == VM_PAGE_NULL)
2242 panic("pmap_collect: pte page not in object");
2243
2244 vm_object_unlock(p->pm_obj);
2245
2246 VM_PAGE_FREE(m);
2247
2248 OSAddAtomic(-1, &inuse_ptepages_count);
2249 PMAP_ZINFO_PFREE(p, PAGE_SIZE);
2250 }
2251
2252 PMAP_LOCK(p);
2253 }
2254 }
2255 }
2256 }
2257
2258 PMAP_UPDATE_TLBS(p, 0x0, 0xFFFFFFFFFFFFF000ULL);
2259 PMAP_UNLOCK(p);
2260 return;
2261 }
2262 #endif
2263
2264
2265 void
2266 pmap_copy_page(ppnum_t src, ppnum_t dst)
2267 {
2268 bcopy_phys((addr64_t)i386_ptob(src),
2269 (addr64_t)i386_ptob(dst),
2270 PAGE_SIZE);
2271 }
2272
2273
2274 /*
2275 * Routine: pmap_pageable
2276 * Function:
2277 * Make the specified pages (by pmap, offset)
2278 * pageable (or not) as requested.
2279 *
2280 * A page which is not pageable may not take
2281 * a fault; therefore, its page table entry
2282 * must remain valid for the duration.
2283 *
2284 * This routine is merely advisory; pmap_enter
2285 * will specify that these pages are to be wired
2286 * down (or not) as appropriate.
2287 */
2288 void
2289 pmap_pageable(
2290 __unused pmap_t pmap,
2291 __unused vm_map_offset_t start_addr,
2292 __unused vm_map_offset_t end_addr,
2293 __unused boolean_t pageable)
2294 {
2295 #ifdef lint
2296 pmap++; start_addr++; end_addr++; pageable++;
2297 #endif /* lint */
2298 }
2299
2300 void
2301 invalidate_icache(__unused vm_offset_t addr,
2302 __unused unsigned cnt,
2303 __unused int phys)
2304 {
2305 return;
2306 }
2307
2308 void
2309 flush_dcache(__unused vm_offset_t addr,
2310 __unused unsigned count,
2311 __unused int phys)
2312 {
2313 return;
2314 }
2315
2316 #if CONFIG_DTRACE
2317 /*
2318 * Constrain DTrace copyin/copyout actions
2319 */
2320 extern kern_return_t dtrace_copyio_preflight(addr64_t);
2321 extern kern_return_t dtrace_copyio_postflight(addr64_t);
2322
2323 kern_return_t dtrace_copyio_preflight(__unused addr64_t va)
2324 {
2325 thread_t thread = current_thread();
2326 uint64_t ccr3;
2327 if (current_map() == kernel_map)
2328 return KERN_FAILURE;
2329 else if (((ccr3 = get_cr3_base()) != thread->map->pmap->pm_cr3) && (no_shared_cr3 == FALSE))
2330 return KERN_FAILURE;
2331 else if (no_shared_cr3 && (ccr3 != kernel_pmap->pm_cr3))
2332 return KERN_FAILURE;
2333 else
2334 return KERN_SUCCESS;
2335 }
2336
2337 kern_return_t dtrace_copyio_postflight(__unused addr64_t va)
2338 {
2339 return KERN_SUCCESS;
2340 }
2341 #endif /* CONFIG_DTRACE */
2342
2343 #include <mach_vm_debug.h>
2344 #if MACH_VM_DEBUG
2345 #include <vm/vm_debug.h>
2346
2347 int
2348 pmap_list_resident_pages(
2349 __unused pmap_t pmap,
2350 __unused vm_offset_t *listp,
2351 __unused int space)
2352 {
2353 return 0;
2354 }
2355 #endif /* MACH_VM_DEBUG */
2356
2357
2358 #if CONFIG_COREDUMP
2359 /* temporary workaround */
2360 boolean_t
2361 coredumpok(__unused vm_map_t map, __unused vm_offset_t va)
2362 {
2363 #if 0
2364 pt_entry_t *ptep;
2365
2366 ptep = pmap_pte(map->pmap, va);
2367 if (0 == ptep)
2368 return FALSE;
2369 return ((*ptep & (INTEL_PTE_NCACHE | INTEL_PTE_WIRED)) != (INTEL_PTE_NCACHE | INTEL_PTE_WIRED));
2370 #else
2371 return TRUE;
2372 #endif
2373 }
2374 #endif
2375
2376 boolean_t
2377 phys_page_exists(ppnum_t pn)
2378 {
2379 assert(pn != vm_page_fictitious_addr);
2380
2381 if (!pmap_initialized)
2382 return TRUE;
2383
2384 if (pn == vm_page_guard_addr)
2385 return FALSE;
2386
2387 if (!IS_MANAGED_PAGE(ppn_to_pai(pn)))
2388 return FALSE;
2389
2390 return TRUE;
2391 }
2392
2393
2394
2395 void
2396 pmap_switch(pmap_t tpmap)
2397 {
2398 spl_t s;
2399
2400 s = splhigh(); /* Make sure interruptions are disabled */
2401 set_dirbase(tpmap, current_thread(), cpu_number());
2402 splx(s);
2403 }
2404
2405
2406 /*
2407 * disable no-execute capability on
2408 * the specified pmap
2409 */
2410 void
2411 pmap_disable_NX(pmap_t pmap)
2412 {
2413 pmap->nx_enabled = 0;
2414 }
2415
2416 void
2417 pt_fake_zone_init(int zone_index)
2418 {
2419 pt_fake_zone_index = zone_index;
2420 }
2421
2422 void
2423 pt_fake_zone_info(
2424 int *count,
2425 vm_size_t *cur_size,
2426 vm_size_t *max_size,
2427 vm_size_t *elem_size,
2428 vm_size_t *alloc_size,
2429 uint64_t *sum_size,
2430 int *collectable,
2431 int *exhaustable,
2432 int *caller_acct)
2433 {
2434 *count = inuse_ptepages_count;
2435 *cur_size = PAGE_SIZE * inuse_ptepages_count;
2436 *max_size = PAGE_SIZE * (inuse_ptepages_count +
2437 vm_page_inactive_count +
2438 vm_page_active_count +
2439 vm_page_free_count);
2440 *elem_size = PAGE_SIZE;
2441 *alloc_size = PAGE_SIZE;
2442 *sum_size = alloc_ptepages_count * PAGE_SIZE;
2443
2444 *collectable = 1;
2445 *exhaustable = 0;
2446 *caller_acct = 1;
2447 }
2448
2449
2450 void
2451 pmap_flush_context_init(pmap_flush_context *pfc)
2452 {
2453 pfc->pfc_cpus = 0;
2454 pfc->pfc_invalid_global = 0;
2455 }
2456
2457 extern uint64_t TLBTimeOut;
2458 void
2459 pmap_flush(
2460 pmap_flush_context *pfc)
2461 {
2462 unsigned int my_cpu;
2463 unsigned int cpu;
2464 unsigned int cpu_bit;
2465 cpumask_t cpus_to_respond = 0;
2466 cpumask_t cpus_to_signal = 0;
2467 cpumask_t cpus_signaled = 0;
2468 boolean_t flush_self = FALSE;
2469 uint64_t deadline;
2470
2471 mp_disable_preemption();
2472
2473 my_cpu = cpu_number();
2474 cpus_to_signal = pfc->pfc_cpus;
2475
2476 PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_DELAYED_TLBS) | DBG_FUNC_START,
2477 NULL, cpus_to_signal);
2478
2479 for (cpu = 0, cpu_bit = 1; cpu < real_ncpus && cpus_to_signal; cpu++, cpu_bit <<= 1) {
2480
2481 if (cpus_to_signal & cpu_bit) {
2482
2483 cpus_to_signal &= ~cpu_bit;
2484
2485 if (!cpu_datap(cpu)->cpu_running)
2486 continue;
2487
2488 if (pfc->pfc_invalid_global & cpu_bit)
2489 cpu_datap(cpu)->cpu_tlb_invalid_global = TRUE;
2490 else
2491 cpu_datap(cpu)->cpu_tlb_invalid_local = TRUE;
2492 mfence();
2493
2494 if (cpu == my_cpu) {
2495 flush_self = TRUE;
2496 continue;
2497 }
2498 if (CPU_CR3_IS_ACTIVE(cpu)) {
2499 cpus_to_respond |= cpu_bit;
2500 i386_signal_cpu(cpu, MP_TLB_FLUSH, ASYNC);
2501 }
2502 }
2503 }
2504 cpus_signaled = cpus_to_respond;
2505
2506 /*
2507 * Flush local tlb if required.
2508 * Do this now to overlap with other processors responding.
2509 */
2510 if (flush_self && cpu_datap(my_cpu)->cpu_tlb_invalid != FALSE)
2511 process_pmap_updates();
2512
2513 if (cpus_to_respond) {
2514
2515 deadline = mach_absolute_time() +
2516 (TLBTimeOut ? TLBTimeOut : LockTimeOut);
2517 boolean_t is_timeout_traced = FALSE;
2518
2519 /*
2520 * Wait for those other cpus to acknowledge
2521 */
2522 while (cpus_to_respond != 0) {
2523 long orig_acks = 0;
2524
2525 for (cpu = 0, cpu_bit = 1; cpu < real_ncpus; cpu++, cpu_bit <<= 1) {
2526 /* Consider checking local/global invalidity
2527 * as appropriate in the PCID case.
2528 */
2529 if ((cpus_to_respond & cpu_bit) != 0) {
2530 if (!cpu_datap(cpu)->cpu_running ||
2531 cpu_datap(cpu)->cpu_tlb_invalid == FALSE ||
2532 !CPU_CR3_IS_ACTIVE(cpu)) {
2533 cpus_to_respond &= ~cpu_bit;
2534 }
2535 cpu_pause();
2536 }
2537 if (cpus_to_respond == 0)
2538 break;
2539 }
2540 if (cpus_to_respond && (mach_absolute_time() > deadline)) {
2541 if (machine_timeout_suspended())
2542 continue;
2543 if (TLBTimeOut == 0) {
2544 if (is_timeout_traced)
2545 continue;
2546
2547 PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_TLBS_TO),
2548 NULL, cpus_to_signal, cpus_to_respond);
2549
2550 is_timeout_traced = TRUE;
2551 continue;
2552 }
2553 orig_acks = NMIPI_acks;
2554 NMIPI_panic(cpus_to_respond, TLB_FLUSH_TIMEOUT);
2555 panic("TLB invalidation IPI timeout, unresponsive CPU bitmap: 0x%llx, NMIPI acks: 0x%lx, now: 0x%lx, deadline: %llu",
2556 cpus_to_respond, orig_acks, NMIPI_acks, deadline);
2557 }
2558 }
2559 }
2560
2561 PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_DELAYED_TLBS) | DBG_FUNC_END,
2562 NULL, cpus_signaled, flush_self);
2563
2564 mp_enable_preemption();
2565 }
2566
2567
2568 static void
2569 invept(void *eptp)
2570 {
2571 struct {
2572 uint64_t eptp;
2573 uint64_t reserved;
2574 } __attribute__((aligned(16), packed)) invept_descriptor = {(uint64_t)eptp, 0};
2575
2576 __asm__ volatile("invept (%%rax), %%rcx"
2577 : : "c" (PMAP_INVEPT_SINGLE_CONTEXT), "a" (&invept_descriptor)
2578 : "cc", "memory");
2579 }
2580
2581 /*
2582 * Called with pmap locked, we:
2583 * - scan through per-cpu data to see which other cpus need to flush
2584 * - send an IPI to each non-idle cpu to be flushed
2585 * - wait for all to signal back that they are inactive or we see that
2586 * they are at a safe point (idle).
2587 * - flush the local tlb if active for this pmap
2588 * - return ... the caller will unlock the pmap
2589 */
2590
2591 void
2592 pmap_flush_tlbs(pmap_t pmap, vm_map_offset_t startv, vm_map_offset_t endv, int options, pmap_flush_context *pfc)
2593 {
2594 unsigned int cpu;
2595 unsigned int cpu_bit;
2596 cpumask_t cpus_to_signal = 0;
2597 unsigned int my_cpu = cpu_number();
2598 pmap_paddr_t pmap_cr3 = pmap->pm_cr3;
2599 boolean_t flush_self = FALSE;
2600 uint64_t deadline;
2601 boolean_t pmap_is_shared = (pmap->pm_shared || (pmap == kernel_pmap));
2602 boolean_t need_global_flush = FALSE;
2603 uint32_t event_code;
2604 vm_map_offset_t event_startv, event_endv;
2605 boolean_t is_ept = is_ept_pmap(pmap);
2606
2607 assert((processor_avail_count < 2) ||
2608 (ml_get_interrupts_enabled() && get_preemption_level() != 0));
2609
2610 if (pmap == kernel_pmap) {
2611 event_code = PMAP_CODE(PMAP__FLUSH_KERN_TLBS);
2612 event_startv = VM_KERNEL_UNSLIDE_OR_PERM(startv);
2613 event_endv = VM_KERNEL_UNSLIDE_OR_PERM(endv);
2614 } else if (is_ept) {
2615 event_code = PMAP_CODE(PMAP__FLUSH_EPT);
2616 event_startv = startv;
2617 event_endv = endv;
2618 } else {
2619 event_code = PMAP_CODE(PMAP__FLUSH_TLBS);
2620 event_startv = startv;
2621 event_endv = endv;
2622 }
2623
2624 PMAP_TRACE_CONSTANT(event_code | DBG_FUNC_START,
2625 VM_KERNEL_UNSLIDE_OR_PERM(pmap), options,
2626 event_startv, event_endv);
2627
2628 if (is_ept) {
2629 mp_cpus_call(CPUMASK_ALL, ASYNC, invept, (void*)pmap->pm_eptp);
2630 goto out;
2631 }
2632
2633 /*
2634 * Scan other cpus for matching active or task CR3.
2635 * For idle cpus (with no active map) we mark them invalid but
2636 * don't signal -- they'll check as they go busy.
2637 */
2638 if (pmap_pcid_ncpus) {
2639 if (pmap_is_shared)
2640 need_global_flush = TRUE;
2641 pmap_pcid_invalidate_all_cpus(pmap);
2642 mfence();
2643 }
2644 for (cpu = 0, cpu_bit = 1; cpu < real_ncpus; cpu++, cpu_bit <<= 1) {
2645 if (!cpu_datap(cpu)->cpu_running)
2646 continue;
2647 uint64_t cpu_active_cr3 = CPU_GET_ACTIVE_CR3(cpu);
2648 uint64_t cpu_task_cr3 = CPU_GET_TASK_CR3(cpu);
2649
2650 if ((pmap_cr3 == cpu_task_cr3) ||
2651 (pmap_cr3 == cpu_active_cr3) ||
2652 (pmap_is_shared)) {
2653
2654 if (options & PMAP_DELAY_TLB_FLUSH) {
2655 if (need_global_flush == TRUE)
2656 pfc->pfc_invalid_global |= cpu_bit;
2657 pfc->pfc_cpus |= cpu_bit;
2658
2659 continue;
2660 }
2661 if (cpu == my_cpu) {
2662 flush_self = TRUE;
2663 continue;
2664 }
2665 if (need_global_flush == TRUE)
2666 cpu_datap(cpu)->cpu_tlb_invalid_global = TRUE;
2667 else
2668 cpu_datap(cpu)->cpu_tlb_invalid_local = TRUE;
2669 mfence();
2670
2671 /*
2672 * We don't need to signal processors which will flush
2673 * lazily at the idle state or kernel boundary.
2674 * For example, if we're invalidating the kernel pmap,
2675 * processors currently in userspace don't need to flush
2676 * their TLBs until the next time they enter the kernel.
2677 * Alterations to the address space of a task active
2678 * on a remote processor result in a signal, to
2679 * account for copy operations. (There may be room
2680 * for optimization in such cases).
2681 * The order of the loads below with respect
2682 * to the store to the "cpu_tlb_invalid" field above
2683 * is important--hence the barrier.
2684 */
2685 if (CPU_CR3_IS_ACTIVE(cpu) &&
2686 (pmap_cr3 == CPU_GET_ACTIVE_CR3(cpu) ||
2687 pmap->pm_shared ||
2688 (pmap_cr3 == CPU_GET_TASK_CR3(cpu)))) {
2689 cpus_to_signal |= cpu_bit;
2690 i386_signal_cpu(cpu, MP_TLB_FLUSH, ASYNC);
2691 }
2692 }
2693 }
2694 if ((options & PMAP_DELAY_TLB_FLUSH))
2695 goto out;
2696
2697 /*
2698 * Flush local tlb if required.
2699 * Do this now to overlap with other processors responding.
2700 */
2701 if (flush_self) {
2702 if (pmap_pcid_ncpus) {
2703 pmap_pcid_validate_cpu(pmap, my_cpu);
2704 if (pmap_is_shared)
2705 tlb_flush_global();
2706 else
2707 flush_tlb_raw();
2708 }
2709 else
2710 flush_tlb_raw();
2711 }
2712
2713 if (cpus_to_signal) {
2714 cpumask_t cpus_to_respond = cpus_to_signal;
2715
2716 deadline = mach_absolute_time() +
2717 (TLBTimeOut ? TLBTimeOut : LockTimeOut);
2718 boolean_t is_timeout_traced = FALSE;
2719
2720 /*
2721 * Wait for those other cpus to acknowledge
2722 */
2723 while (cpus_to_respond != 0) {
2724 long orig_acks = 0;
2725
2726 for (cpu = 0, cpu_bit = 1; cpu < real_ncpus; cpu++, cpu_bit <<= 1) {
2727 /* Consider checking local/global invalidity
2728 * as appropriate in the PCID case.
2729 */
2730 if ((cpus_to_respond & cpu_bit) != 0) {
2731 if (!cpu_datap(cpu)->cpu_running ||
2732 cpu_datap(cpu)->cpu_tlb_invalid == FALSE ||
2733 !CPU_CR3_IS_ACTIVE(cpu)) {
2734 cpus_to_respond &= ~cpu_bit;
2735 }
2736 cpu_pause();
2737 }
2738 if (cpus_to_respond == 0)
2739 break;
2740 }
2741 if (cpus_to_respond && (mach_absolute_time() > deadline)) {
2742 if (machine_timeout_suspended())
2743 continue;
2744 if (TLBTimeOut == 0) {
2745 /* cut tracepoint but don't panic */
2746 if (is_timeout_traced)
2747 continue;
2748
2749 PMAP_TRACE_CONSTANT(PMAP_CODE(PMAP__FLUSH_TLBS_TO),
2750 VM_KERNEL_UNSLIDE_OR_PERM(pmap),
2751 cpus_to_signal,
2752 cpus_to_respond);
2753
2754 is_timeout_traced = TRUE;
2755 continue;
2756 }
2757 orig_acks = NMIPI_acks;
2758
2759 NMIPI_panic(cpus_to_respond, TLB_FLUSH_TIMEOUT);
2760 panic("TLB invalidation IPI timeout, unresponsive CPU bitmap: 0x%llx, NMIPI acks: 0x%lx, now: 0x%lx, deadline: %llu",
2761 cpus_to_respond, orig_acks, NMIPI_acks, deadline);
2762 }
2763 }
2764 }
2765
2766 if (__improbable((pmap == kernel_pmap) && (flush_self != TRUE))) {
2767 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);
2768 }
2769
2770 out:
2771 PMAP_TRACE_CONSTANT(event_code | DBG_FUNC_END,
2772 VM_KERNEL_UNSLIDE_OR_PERM(pmap), cpus_to_signal,
2773 event_startv, event_endv);
2774
2775 }
2776
2777 void
2778 process_pmap_updates(void)
2779 {
2780 int ccpu = cpu_number();
2781 pmap_assert(ml_get_interrupts_enabled() == 0 || get_preemption_level() != 0);
2782 if (pmap_pcid_ncpus) {
2783 pmap_pcid_validate_current();
2784 if (cpu_datap(ccpu)->cpu_tlb_invalid_global) {
2785 cpu_datap(ccpu)->cpu_tlb_invalid = FALSE;
2786 tlb_flush_global();
2787 }
2788 else {
2789 cpu_datap(ccpu)->cpu_tlb_invalid_local = FALSE;
2790 flush_tlb_raw();
2791 }
2792 }
2793 else {
2794 current_cpu_datap()->cpu_tlb_invalid = FALSE;
2795 flush_tlb_raw();
2796 }
2797
2798 mfence();
2799 }
2800
2801 void
2802 pmap_update_interrupt(void)
2803 {
2804 PMAP_TRACE(PMAP_CODE(PMAP__UPDATE_INTERRUPT) | DBG_FUNC_START);
2805
2806 if (current_cpu_datap()->cpu_tlb_invalid)
2807 process_pmap_updates();
2808
2809 PMAP_TRACE(PMAP_CODE(PMAP__UPDATE_INTERRUPT) | DBG_FUNC_END);
2810 }
2811
2812 #include <mach/mach_vm.h> /* mach_vm_region_recurse() */
2813 /* Scan kernel pmap for W+X PTEs, scan kernel VM map for W+X map entries
2814 * and identify ranges with mismatched VM permissions and PTE permissions
2815 */
2816 kern_return_t
2817 pmap_permissions_verify(pmap_t ipmap, vm_map_t ivmmap, vm_offset_t sv, vm_offset_t ev) {
2818 vm_offset_t cv = sv;
2819 kern_return_t rv = KERN_SUCCESS;
2820 uint64_t skip4 = 0, skip2 = 0;
2821
2822 assert(!is_ept_pmap(ipmap));
2823
2824 sv &= ~PAGE_MASK_64;
2825 ev &= ~PAGE_MASK_64;
2826 while (cv < ev) {
2827 if (__improbable((cv > 0x00007FFFFFFFFFFFULL) &&
2828 (cv < 0xFFFF800000000000ULL))) {
2829 cv = 0xFFFF800000000000ULL;
2830 }
2831 /* Potential inconsistencies from not holding pmap lock
2832 * but harmless for the moment.
2833 */
2834 if (((cv & PML4MASK) == 0) && (pmap64_pml4(ipmap, cv) == 0)) {
2835 if ((cv + NBPML4) > cv)
2836 cv += NBPML4;
2837 else
2838 break;
2839 skip4++;
2840 continue;
2841 }
2842 if (((cv & PDMASK) == 0) && (pmap_pde(ipmap, cv) == 0)) {
2843 if ((cv + NBPD) > cv)
2844 cv += NBPD;
2845 else
2846 break;
2847 skip2++;
2848 continue;
2849 }
2850
2851 pt_entry_t *ptep = pmap_pte(ipmap, cv);
2852 if (ptep && (*ptep & INTEL_PTE_VALID)) {
2853 if (*ptep & INTEL_PTE_WRITE) {
2854 if (!(*ptep & INTEL_PTE_NX)) {
2855 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)))));
2856 rv = KERN_FAILURE;
2857 }
2858 }
2859 }
2860 cv += PAGE_SIZE;
2861 }
2862 kprintf("Completed pmap scan\n");
2863 cv = sv;
2864
2865 struct vm_region_submap_info_64 vbr;
2866 mach_msg_type_number_t vbrcount = 0;
2867 mach_vm_size_t vmsize;
2868 vm_prot_t prot;
2869 uint32_t nesting_depth = 0;
2870 kern_return_t kret;
2871
2872 while (cv < ev) {
2873
2874 for (;;) {
2875 vbrcount = VM_REGION_SUBMAP_INFO_COUNT_64;
2876 if((kret = mach_vm_region_recurse(ivmmap,
2877 (mach_vm_address_t *) &cv, &vmsize, &nesting_depth,
2878 (vm_region_recurse_info_t)&vbr,
2879 &vbrcount)) != KERN_SUCCESS) {
2880 break;
2881 }
2882
2883 if(vbr.is_submap) {
2884 nesting_depth++;
2885 continue;
2886 } else {
2887 break;
2888 }
2889 }
2890
2891 if(kret != KERN_SUCCESS)
2892 break;
2893
2894 prot = vbr.protection;
2895
2896 if ((prot & (VM_PROT_WRITE | VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE)) {
2897 kprintf("W+X map entry at address 0x%lx\n", cv);
2898 rv = KERN_FAILURE;
2899 }
2900
2901 if (prot) {
2902 vm_offset_t pcv;
2903 for (pcv = cv; pcv < cv + vmsize; pcv += PAGE_SIZE) {
2904 pt_entry_t *ptep = pmap_pte(ipmap, pcv);
2905 vm_prot_t tprot;
2906
2907 if ((ptep == NULL) || !(*ptep & INTEL_PTE_VALID))
2908 continue;
2909 tprot = VM_PROT_READ;
2910 if (*ptep & INTEL_PTE_WRITE)
2911 tprot |= VM_PROT_WRITE;
2912 if ((*ptep & INTEL_PTE_NX) == 0)
2913 tprot |= VM_PROT_EXECUTE;
2914 if (tprot != prot) {
2915 kprintf("PTE/map entry permissions mismatch at address 0x%lx, pte: 0x%llx, protection: 0x%x\n", pcv, *ptep, prot);
2916 rv = KERN_FAILURE;
2917 }
2918 }
2919 }
2920 cv += vmsize;
2921 }
2922 return rv;
2923 }
2924
2925 #if MACH_ASSERT
2926 extern int pmap_ledgers_panic;
2927 static void
2928 pmap_check_ledgers(
2929 pmap_t pmap)
2930 {
2931 ledger_amount_t bal;
2932 int pid;
2933 char *procname;
2934 boolean_t do_panic;
2935
2936 if (pmap->pmap_pid == 0) {
2937 /*
2938 * This pmap was not or is no longer fully associated
2939 * with a task (e.g. the old pmap after a fork()/exec() or
2940 * spawn()). Its "ledger" still points at a task that is
2941 * now using a different (and active) address space, so
2942 * we can't check that all the pmap ledgers are balanced here.
2943 *
2944 * If the "pid" is set, that means that we went through
2945 * pmap_set_process() in task_terminate_internal(), so
2946 * this task's ledger should not have been re-used and
2947 * all the pmap ledgers should be back to 0.
2948 */
2949 return;
2950 }
2951
2952 do_panic = FALSE;
2953 pid = pmap->pmap_pid;
2954 procname = pmap->pmap_procname;
2955
2956 pmap_ledgers_drift.num_pmaps_checked++;
2957
2958 ledger_get_balance(pmap->ledger,
2959 task_ledgers.phys_footprint,
2960 &bal);
2961 if (bal != 0) {
2962 do_panic = TRUE;
2963 printf("LEDGER BALANCE proc %d (%s) "
2964 "\"phys_footprint\" = %lld\n",
2965 pid, procname, bal);
2966 if (bal > 0) {
2967 pmap_ledgers_drift.phys_footprint_over++;
2968 pmap_ledgers_drift.phys_footprint_over_total += bal;
2969 if (bal > pmap_ledgers_drift.phys_footprint_over_max) {
2970 pmap_ledgers_drift.phys_footprint_over_max = bal;
2971 }
2972 } else {
2973 pmap_ledgers_drift.phys_footprint_under++;
2974 pmap_ledgers_drift.phys_footprint_under_total += bal;
2975 if (bal < pmap_ledgers_drift.phys_footprint_under_max) {
2976 pmap_ledgers_drift.phys_footprint_under_max = bal;
2977 }
2978 }
2979 }
2980 ledger_get_balance(pmap->ledger,
2981 task_ledgers.internal,
2982 &bal);
2983 if (bal != 0) {
2984 do_panic = TRUE;
2985 printf("LEDGER BALANCE proc %d (%s) "
2986 "\"internal\" = %lld\n",
2987 pid, procname, bal);
2988 if (bal > 0) {
2989 pmap_ledgers_drift.internal_over++;
2990 pmap_ledgers_drift.internal_over_total += bal;
2991 if (bal > pmap_ledgers_drift.internal_over_max) {
2992 pmap_ledgers_drift.internal_over_max = bal;
2993 }
2994 } else {
2995 pmap_ledgers_drift.internal_under++;
2996 pmap_ledgers_drift.internal_under_total += bal;
2997 if (bal < pmap_ledgers_drift.internal_under_max) {
2998 pmap_ledgers_drift.internal_under_max = bal;
2999 }
3000 }
3001 }
3002 ledger_get_balance(pmap->ledger,
3003 task_ledgers.internal_compressed,
3004 &bal);
3005 if (bal != 0) {
3006 do_panic = TRUE;
3007 printf("LEDGER BALANCE proc %d (%s) "
3008 "\"internal_compressed\" = %lld\n",
3009 pid, procname, bal);
3010 if (bal > 0) {
3011 pmap_ledgers_drift.internal_compressed_over++;
3012 pmap_ledgers_drift.internal_compressed_over_total += bal;
3013 if (bal > pmap_ledgers_drift.internal_compressed_over_max) {
3014 pmap_ledgers_drift.internal_compressed_over_max = bal;
3015 }
3016 } else {
3017 pmap_ledgers_drift.internal_compressed_under++;
3018 pmap_ledgers_drift.internal_compressed_under_total += bal;
3019 if (bal < pmap_ledgers_drift.internal_compressed_under_max) {
3020 pmap_ledgers_drift.internal_compressed_under_max = bal;
3021 }
3022 }
3023 }
3024 ledger_get_balance(pmap->ledger,
3025 task_ledgers.iokit_mapped,
3026 &bal);
3027 if (bal != 0) {
3028 do_panic = TRUE;
3029 printf("LEDGER BALANCE proc %d (%s) "
3030 "\"iokit_mapped\" = %lld\n",
3031 pid, procname, bal);
3032 if (bal > 0) {
3033 pmap_ledgers_drift.iokit_mapped_over++;
3034 pmap_ledgers_drift.iokit_mapped_over_total += bal;
3035 if (bal > pmap_ledgers_drift.iokit_mapped_over_max) {
3036 pmap_ledgers_drift.iokit_mapped_over_max = bal;
3037 }
3038 } else {
3039 pmap_ledgers_drift.iokit_mapped_under++;
3040 pmap_ledgers_drift.iokit_mapped_under_total += bal;
3041 if (bal < pmap_ledgers_drift.iokit_mapped_under_max) {
3042 pmap_ledgers_drift.iokit_mapped_under_max = bal;
3043 }
3044 }
3045 }
3046 ledger_get_balance(pmap->ledger,
3047 task_ledgers.alternate_accounting,
3048 &bal);
3049 if (bal != 0) {
3050 do_panic = TRUE;
3051 printf("LEDGER BALANCE proc %d (%s) "
3052 "\"alternate_accounting\" = %lld\n",
3053 pid, procname, bal);
3054 if (bal > 0) {
3055 pmap_ledgers_drift.alternate_accounting_over++;
3056 pmap_ledgers_drift.alternate_accounting_over_total += bal;
3057 if (bal > pmap_ledgers_drift.alternate_accounting_over_max) {
3058 pmap_ledgers_drift.alternate_accounting_over_max = bal;
3059 }
3060 } else {
3061 pmap_ledgers_drift.alternate_accounting_under++;
3062 pmap_ledgers_drift.alternate_accounting_under_total += bal;
3063 if (bal < pmap_ledgers_drift.alternate_accounting_under_max) {
3064 pmap_ledgers_drift.alternate_accounting_under_max = bal;
3065 }
3066 }
3067 }
3068 ledger_get_balance(pmap->ledger,
3069 task_ledgers.alternate_accounting_compressed,
3070 &bal);
3071 if (bal != 0) {
3072 do_panic = TRUE;
3073 printf("LEDGER BALANCE proc %d (%s) "
3074 "\"alternate_accounting_compressed\" = %lld\n",
3075 pid, procname, bal);
3076 if (bal > 0) {
3077 pmap_ledgers_drift.alternate_accounting_compressed_over++;
3078 pmap_ledgers_drift.alternate_accounting_compressed_over_total += bal;
3079 if (bal > pmap_ledgers_drift.alternate_accounting_compressed_over_max) {
3080 pmap_ledgers_drift.alternate_accounting_compressed_over_max = bal;
3081 }
3082 } else {
3083 pmap_ledgers_drift.alternate_accounting_compressed_under++;
3084 pmap_ledgers_drift.alternate_accounting_compressed_under_total += bal;
3085 if (bal < pmap_ledgers_drift.alternate_accounting_compressed_under_max) {
3086 pmap_ledgers_drift.alternate_accounting_compressed_under_max = bal;
3087 }
3088 }
3089 }
3090 ledger_get_balance(pmap->ledger,
3091 task_ledgers.page_table,
3092 &bal);
3093 if (bal != 0) {
3094 do_panic = TRUE;
3095 printf("LEDGER BALANCE proc %d (%s) "
3096 "\"page_table\" = %lld\n",
3097 pid, procname, bal);
3098 if (bal > 0) {
3099 pmap_ledgers_drift.page_table_over++;
3100 pmap_ledgers_drift.page_table_over_total += bal;
3101 if (bal > pmap_ledgers_drift.page_table_over_max) {
3102 pmap_ledgers_drift.page_table_over_max = bal;
3103 }
3104 } else {
3105 pmap_ledgers_drift.page_table_under++;
3106 pmap_ledgers_drift.page_table_under_total += bal;
3107 if (bal < pmap_ledgers_drift.page_table_under_max) {
3108 pmap_ledgers_drift.page_table_under_max = bal;
3109 }
3110 }
3111 }
3112 ledger_get_balance(pmap->ledger,
3113 task_ledgers.purgeable_volatile,
3114 &bal);
3115 if (bal != 0) {
3116 do_panic = TRUE;
3117 printf("LEDGER BALANCE proc %d (%s) "
3118 "\"purgeable_volatile\" = %lld\n",
3119 pid, procname, bal);
3120 if (bal > 0) {
3121 pmap_ledgers_drift.purgeable_volatile_over++;
3122 pmap_ledgers_drift.purgeable_volatile_over_total += bal;
3123 if (bal > pmap_ledgers_drift.purgeable_volatile_over_max) {
3124 pmap_ledgers_drift.purgeable_volatile_over_max = bal;
3125 }
3126 } else {
3127 pmap_ledgers_drift.purgeable_volatile_under++;
3128 pmap_ledgers_drift.purgeable_volatile_under_total += bal;
3129 if (bal < pmap_ledgers_drift.purgeable_volatile_under_max) {
3130 pmap_ledgers_drift.purgeable_volatile_under_max = bal;
3131 }
3132 }
3133 }
3134 ledger_get_balance(pmap->ledger,
3135 task_ledgers.purgeable_nonvolatile,
3136 &bal);
3137 if (bal != 0) {
3138 do_panic = TRUE;
3139 printf("LEDGER BALANCE proc %d (%s) "
3140 "\"purgeable_nonvolatile\" = %lld\n",
3141 pid, procname, bal);
3142 if (bal > 0) {
3143 pmap_ledgers_drift.purgeable_nonvolatile_over++;
3144 pmap_ledgers_drift.purgeable_nonvolatile_over_total += bal;
3145 if (bal > pmap_ledgers_drift.purgeable_nonvolatile_over_max) {
3146 pmap_ledgers_drift.purgeable_nonvolatile_over_max = bal;
3147 }
3148 } else {
3149 pmap_ledgers_drift.purgeable_nonvolatile_under++;
3150 pmap_ledgers_drift.purgeable_nonvolatile_under_total += bal;
3151 if (bal < pmap_ledgers_drift.purgeable_nonvolatile_under_max) {
3152 pmap_ledgers_drift.purgeable_nonvolatile_under_max = bal;
3153 }
3154 }
3155 }
3156 ledger_get_balance(pmap->ledger,
3157 task_ledgers.purgeable_volatile_compressed,
3158 &bal);
3159 if (bal != 0) {
3160 do_panic = TRUE;
3161 printf("LEDGER BALANCE proc %d (%s) "
3162 "\"purgeable_volatile_compressed\" = %lld\n",
3163 pid, procname, bal);
3164 if (bal > 0) {
3165 pmap_ledgers_drift.purgeable_volatile_compressed_over++;
3166 pmap_ledgers_drift.purgeable_volatile_compressed_over_total += bal;
3167 if (bal > pmap_ledgers_drift.purgeable_volatile_compressed_over_max) {
3168 pmap_ledgers_drift.purgeable_volatile_compressed_over_max = bal;
3169 }
3170 } else {
3171 pmap_ledgers_drift.purgeable_volatile_compressed_under++;
3172 pmap_ledgers_drift.purgeable_volatile_compressed_under_total += bal;
3173 if (bal < pmap_ledgers_drift.purgeable_volatile_compressed_under_max) {
3174 pmap_ledgers_drift.purgeable_volatile_compressed_under_max = bal;
3175 }
3176 }
3177 }
3178 ledger_get_balance(pmap->ledger,
3179 task_ledgers.purgeable_nonvolatile_compressed,
3180 &bal);
3181 if (bal != 0) {
3182 do_panic = TRUE;
3183 printf("LEDGER BALANCE proc %d (%s) "
3184 "\"purgeable_nonvolatile_compressed\" = %lld\n",
3185 pid, procname, bal);
3186 if (bal > 0) {
3187 pmap_ledgers_drift.purgeable_nonvolatile_compressed_over++;
3188 pmap_ledgers_drift.purgeable_nonvolatile_compressed_over_total += bal;
3189 if (bal > pmap_ledgers_drift.purgeable_nonvolatile_compressed_over_max) {
3190 pmap_ledgers_drift.purgeable_nonvolatile_compressed_over_max = bal;
3191 }
3192 } else {
3193 pmap_ledgers_drift.purgeable_nonvolatile_compressed_under++;
3194 pmap_ledgers_drift.purgeable_nonvolatile_compressed_under_total += bal;
3195 if (bal < pmap_ledgers_drift.purgeable_nonvolatile_compressed_under_max) {
3196 pmap_ledgers_drift.purgeable_nonvolatile_compressed_under_max = bal;
3197 }
3198 }
3199 }
3200
3201 if (do_panic) {
3202 if (pmap_ledgers_panic) {
3203 panic("pmap_destroy(%p) %d[%s] has imbalanced ledgers\n",
3204 pmap, pid, procname);
3205 } else {
3206 printf("pmap_destroy(%p) %d[%s] has imbalanced ledgers\n",
3207 pmap, pid, procname);
3208 }
3209 }
3210
3211 if (pmap->stats.resident_count != 0 ||
3212 pmap->stats.wired_count != 0 ||
3213 pmap->stats.device != 0 ||
3214 pmap->stats.internal != 0 ||
3215 pmap->stats.external != 0 ||
3216 pmap->stats.reusable != 0 ||
3217 pmap->stats.compressed != 0) {
3218 if (pmap_stats_assert) {
3219 panic("pmap_destroy(%p) %d[%s] imbalanced stats: resident=%d wired=%d device=%d internal=%d external=%d reusable=%d compressed=%lld",
3220 pmap, pid, procname,
3221 pmap->stats.resident_count,
3222 pmap->stats.wired_count,
3223 pmap->stats.device,
3224 pmap->stats.internal,
3225 pmap->stats.external,
3226 pmap->stats.reusable,
3227 pmap->stats.compressed);
3228 } else {
3229 printf("pmap_destroy(%p) %d[%s] imbalanced stats: resident=%d wired=%d device=%d internal=%d external=%d reusable=%d compressed=%lld",
3230 pmap, pid, procname,
3231 pmap->stats.resident_count,
3232 pmap->stats.wired_count,
3233 pmap->stats.device,
3234 pmap->stats.internal,
3235 pmap->stats.external,
3236 pmap->stats.reusable,
3237 pmap->stats.compressed);
3238 }
3239 }
3240 }
3241
3242 void
3243 pmap_set_process(
3244 pmap_t pmap,
3245 int pid,
3246 char *procname)
3247 {
3248 if (pmap == NULL)
3249 return;
3250
3251 pmap->pmap_pid = pid;
3252 strlcpy(pmap->pmap_procname, procname, sizeof (pmap->pmap_procname));
3253 }
3254 #endif /* MACH_ASSERT */
3255
3256
3257 #if DEVELOPMENT || DEBUG
3258 int pmap_pagezero_mitigation = 1;
3259 #endif
3260
3261 void pmap_advise_pagezero_range(pmap_t lpmap, uint64_t low_bound) {
3262 #if DEVELOPMENT || DEBUG
3263 if (pmap_pagezero_mitigation == 0) {
3264 lpmap->pagezero_accessible = FALSE;
3265 return;
3266 }
3267 #endif
3268 lpmap->pagezero_accessible = ((pmap_smap_enabled == FALSE) && (low_bound < 0x1000));
3269 if (lpmap == current_pmap()) {
3270 mp_disable_preemption();
3271 current_cpu_datap()->cpu_pagezero_mapped = lpmap->pagezero_accessible;
3272 mp_enable_preemption();
3273 }
3274 }
3275
3276 void pmap_verify_noncacheable(uintptr_t vaddr) {
3277 pt_entry_t *ptep = NULL;
3278 ptep = pmap_pte(kernel_pmap, vaddr);
3279 if (ptep == NULL) {
3280 panic("pmap_verify_noncacheable: no translation for 0x%lx", vaddr);
3281 }
3282 /* Non-cacheable OK */
3283 if (*ptep & (INTEL_PTE_NCACHE))
3284 return;
3285 /* Write-combined OK */
3286 if (*ptep & (INTEL_PTE_PTA))
3287 return;
3288 panic("pmap_verify_noncacheable: IO read from a cacheable address? address: 0x%lx, PTE: %p, *PTE: 0x%llx", vaddr, ptep, *ptep);
3289 }
3290
3291 #if KASAN
3292 void kasan_map_low_fixed_regions(void) {
3293 kasan_map_shadow(MASTER_GDT_ALIAS, PAGE_SIZE, false);
3294 kasan_map_shadow(MASTER_IDT_ALIAS, PAGE_SIZE, false);
3295 kasan_map_shadow(LOWGLOBAL_ALIAS, PAGE_SIZE, false);
3296 }
3297 #endif