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