-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathpmap.c
More file actions
3465 lines (2970 loc) · 91.1 KB
/
pmap.c
File metadata and controls
3465 lines (2970 loc) · 91.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2022 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/*
* @OSF_COPYRIGHT@
*/
/*
* Mach Operating System
* Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
* All Rights Reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
* ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie Mellon
* the rights to redistribute these changes.
*/
/*
*/
/*
* File: pmap.c
* Author: Avadis Tevanian, Jr., Michael Wayne Young
* (These guys wrote the Vax version)
*
* Physical Map management code for Intel i386, i486, and i860.
*
* Manages physical address maps.
*
* In addition to hardware address maps, this
* module is called upon to provide software-use-only
* maps which may or may not be stored in the same
* form as hardware maps. These pseudo-maps are
* used to store intermediate results from copy
* operations to and from address spaces.
*
* Since the information managed by this module is
* also stored by the logical address mapping module,
* this module may throw away valid virtual-to-physical
* mappings at almost any time. However, invalidations
* of virtual-to-physical mappings must be done as
* requested.
*
* In order to cope with hardware architectures which
* make virtual-to-physical map invalidates expensive,
* this module may delay invalidate or reduced protection
* operations until such time as they are actually
* necessary. This module is given full information as
* to which processors are currently using which maps,
* and to when physical maps must be made correct.
*/
#include <string.h>
#include <mach_ldebug.h>
#include <libkern/OSAtomic.h>
#include <mach/machine/vm_types.h>
#include <mach/boolean.h>
#include <kern/thread.h>
#include <kern/zalloc.h>
#include <kern/zalloc_internal.h>
#include <kern/queue.h>
#include <kern/ledger.h>
#include <kern/mach_param.h>
#include <kern/spl.h>
#include <vm/pmap.h>
#include <vm/pmap_cs.h>
#include <vm/vm_map_xnu.h>
#include <vm/vm_kern_xnu.h>
#include <mach/vm_param.h>
#include <mach/vm_prot.h>
#include <vm/vm_object_internal.h>
#include <vm/vm_page_internal.h>
#include <mach/machine/vm_param.h>
#include <machine/thread.h>
#include <kern/misc_protos.h> /* prototyping */
#include <i386/misc_protos.h>
#include <i386/i386_lowmem.h>
#include <x86_64/lowglobals.h>
#include <i386/cpuid.h>
#include <i386/cpu_data.h>
#include <i386/cpu_number.h>
#include <i386/machine_cpu.h>
#include <i386/seg.h>
#include <i386/serial_io.h>
#include <i386/cpu_capabilities.h>
#include <i386/machine_routines.h>
#include <i386/proc_reg.h>
#include <i386/tsc.h>
#include <i386/pmap_internal.h>
#include <i386/pmap_pcid.h>
#if CONFIG_VMX
#include <i386/vmx/vmx_cpu.h>
#endif
#include <vm/vm_protos.h>
#include <san/kasan.h>
#include <i386/mp.h>
#include <i386/mp_desc.h>
#include <libkern/kernel_mach_header.h>
#include <pexpert/i386/efi.h>
#include <libkern/section_keywords.h>
#if MACH_ASSERT
int pmap_stats_assert = 1;
#endif /* MACH_ASSERT */
#ifdef IWANTTODEBUG
#undef DEBUG
#define DEBUG 1
#define POSTCODE_DELAY 1
#include <i386/postcode.h>
#endif /* IWANTTODEBUG */
#ifdef PMAP_DEBUG
#define DBG(x...) kprintf("DBG: " x)
#else
#define DBG(x...)
#endif
/* Compile time assert to ensure adjacency/alignment of per-CPU data fields used
* in the trampolines for kernel/user boundary TLB coherency.
*/
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];
boolean_t pmap_trace = FALSE;
boolean_t no_shared_cr3 = DEBUG; /* TRUE for DEBUG by default */
#if DEVELOPMENT || DEBUG
int nx_enabled = 1; /* enable no-execute protection -- set during boot */
#else
const int nx_enabled = 1;
#endif
#if DEBUG || DEVELOPMENT
int allow_data_exec = VM_ABI_32; /* 32-bit apps may execute data by default, 64-bit apps may not */
int allow_stack_exec = 0; /* No apps may execute from the stack by default */
#else /* DEBUG || DEVELOPMENT */
const int allow_data_exec = VM_ABI_32; /* 32-bit apps may execute data by default, 64-bit apps may not */
const int allow_stack_exec = 0; /* No apps may execute from the stack by default */
#endif /* DEBUG || DEVELOPMENT */
uint64_t max_preemption_latency_tsc = 0;
pv_hashed_entry_t *pv_hash_table; /* hash lists */
uint32_t npvhashmask = 0, npvhashbuckets = 0;
pv_hashed_entry_t pv_hashed_free_list = PV_HASHED_ENTRY_NULL;
pv_hashed_entry_t pv_hashed_kern_free_list = PV_HASHED_ENTRY_NULL;
SIMPLE_LOCK_DECLARE(pv_hashed_free_list_lock, 0);
SIMPLE_LOCK_DECLARE(pv_hashed_kern_free_list_lock, 0);
SIMPLE_LOCK_DECLARE(pv_hash_table_lock, 0);
SIMPLE_LOCK_DECLARE(phys_backup_lock, 0);
SECURITY_READ_ONLY_LATE(zone_t) pv_hashed_list_zone; /* zone of pv_hashed_entry structures */
/*
* First and last physical addresses that we maintain any information
* for. Initialized to zero so that pmap operations done before
* pmap_init won't touch any non-existent structures.
*/
boolean_t pmap_initialized = FALSE;/* Has pmap_init completed? */
static struct vm_object kptobj_object_store VM_PAGE_PACKED_ALIGNED;
static struct vm_object kpml4obj_object_store VM_PAGE_PACKED_ALIGNED;
static struct vm_object kpdptobj_object_store VM_PAGE_PACKED_ALIGNED;
/*
* Array of physical page attribites for managed pages.
* One byte per physical page.
*/
char *pmap_phys_attributes;
ppnum_t last_managed_page = 0;
unsigned pmap_memory_region_count;
unsigned pmap_memory_region_current;
pmap_memory_region_t pmap_memory_regions[PMAP_MEMORY_REGIONS_SIZE];
/*
* Other useful macros.
*/
#define current_pmap() (vm_map_pmap(current_thread()->map))
struct pmap kernel_pmap_store;
const pmap_t kernel_pmap = &kernel_pmap_store;
SECURITY_READ_ONLY_LATE(zone_t) pmap_zone; /* zone of pmap structures */
SECURITY_READ_ONLY_LATE(zone_t) pmap_anchor_zone;
SECURITY_READ_ONLY_LATE(zone_t) pmap_uanchor_zone;
int pmap_debug = 0; /* flag for debugging prints */
unsigned int inuse_ptepages_count = 0;
long long alloc_ptepages_count __attribute__((aligned(8))) = 0; /* aligned for atomic access */
unsigned int bootstrap_wired_pages = 0;
extern long NMIPI_acks;
SECURITY_READ_ONLY_LATE(boolean_t) kernel_text_ps_4K = TRUE;
extern char end;
static int nkpt;
#if DEVELOPMENT || DEBUG
SECURITY_READ_ONLY_LATE(boolean_t) pmap_disable_kheap_nx = FALSE;
SECURITY_READ_ONLY_LATE(boolean_t) pmap_disable_kstack_nx = FALSE;
SECURITY_READ_ONLY_LATE(boolean_t) wpkernel = TRUE;
#else
const boolean_t wpkernel = TRUE;
#endif
extern long __stack_chk_guard[];
static uint64_t pmap_eptp_flags = 0;
boolean_t pmap_ept_support_ad = FALSE;
static void process_pmap_updates(pmap_t, bool, addr64_t, addr64_t);
/*
* Map memory at initialization. The physical addresses being
* mapped are not managed and are never unmapped.
*
* For now, VM is already on, we only need to map the
* specified memory.
*/
vm_offset_t
pmap_map(
vm_offset_t virt,
vm_map_offset_t start_addr,
vm_map_offset_t end_addr,
vm_prot_t prot,
unsigned int flags)
{
kern_return_t kr;
int ps;
ps = PAGE_SIZE;
while (start_addr < end_addr) {
kr = pmap_enter(kernel_pmap, (vm_map_offset_t)virt,
(ppnum_t) i386_btop(start_addr), prot, VM_PROT_NONE, flags, TRUE, PMAP_MAPPING_TYPE_INFER);
if (kr != KERN_SUCCESS) {
panic("%s: failed pmap_enter, "
"virt=%p, start_addr=%p, end_addr=%p, prot=%#x, flags=%#x",
__FUNCTION__,
(void *)virt, (void *)start_addr, (void *)end_addr, prot, flags);
}
virt += ps;
start_addr += ps;
}
return virt;
}
extern char *first_avail;
extern vm_offset_t virtual_avail, virtual_end;
extern pmap_paddr_t avail_start, avail_end;
extern vm_offset_t sHIB;
extern vm_offset_t eHIB;
extern vm_offset_t stext;
extern vm_offset_t etext;
extern vm_offset_t sdata, edata;
extern vm_offset_t sconst, econst;
extern void *KPTphys;
boolean_t pmap_smep_enabled = FALSE;
boolean_t pmap_smap_enabled = FALSE;
void
pmap_cpu_init(void)
{
cpu_data_t *cdp = current_cpu_datap();
set_cr4(get_cr4() | CR4_PGE);
/*
* Initialize the per-cpu, TLB-related fields.
*/
cdp->cpu_kernel_cr3 = kernel_pmap->pm_cr3;
cpu_shadowp(cdp->cpu_number)->cpu_kernel_cr3 = cdp->cpu_kernel_cr3;
cdp->cpu_active_cr3 = kernel_pmap->pm_cr3;
cdp->cpu_tlb_invalid = 0;
cdp->cpu_task_map = TASK_MAP_64BIT;
pmap_pcid_configure();
if (cpuid_leaf7_features() & CPUID_LEAF7_FEATURE_SMEP) {
pmap_smep_enabled = TRUE;
#if DEVELOPMENT || DEBUG
boolean_t nsmep;
if (PE_parse_boot_argn("-pmap_smep_disable", &nsmep, sizeof(nsmep))) {
pmap_smep_enabled = FALSE;
}
#endif
if (pmap_smep_enabled) {
set_cr4(get_cr4() | CR4_SMEP);
}
}
if (cpuid_leaf7_features() & CPUID_LEAF7_FEATURE_SMAP) {
pmap_smap_enabled = TRUE;
#if DEVELOPMENT || DEBUG
boolean_t nsmap;
if (PE_parse_boot_argn("-pmap_smap_disable", &nsmap, sizeof(nsmap))) {
pmap_smap_enabled = FALSE;
}
#endif
if (pmap_smap_enabled) {
set_cr4(get_cr4() | CR4_SMAP);
}
}
#if !CONFIG_CPU_COUNTERS
if (cdp->cpu_fixed_pmcs_enabled) {
boolean_t enable = TRUE;
cpu_pmc_control(&enable);
}
#endif /* !CONFIG_CPU_COUNTERS */
}
static void
pmap_ro_zone_validate_element_dst(
zone_id_t zid,
vm_offset_t va,
vm_offset_t offset,
vm_size_t new_data_size)
{
if (__improbable((zid < ZONE_ID__FIRST_RO) || (zid > ZONE_ID__LAST_RO))) {
panic("%s: ZoneID %u outside RO range %u - %u", __func__, zid,
ZONE_ID__FIRST_RO, ZONE_ID__LAST_RO);
}
vm_size_t elem_size = zone_ro_size_params[zid].z_elem_size;
/* Check element is from correct zone and properly aligned */
zone_require_ro(zid, elem_size, (void*)va);
if (__improbable(new_data_size > (elem_size - offset))) {
panic("%s: New data size %lu too large for elem size %lu at addr %p",
__func__, (uintptr_t)new_data_size, (uintptr_t)elem_size, (void*)va);
}
if (__improbable(offset >= elem_size)) {
panic("%s: Offset %lu too large for elem size %lu at addr %p",
__func__, (uintptr_t)offset, (uintptr_t)elem_size, (void*)va);
}
}
static void
pmap_ro_zone_validate_element(
zone_id_t zid,
vm_offset_t va,
vm_offset_t offset,
const vm_offset_t new_data,
vm_size_t new_data_size)
{
vm_offset_t sum = 0;
if (__improbable(os_add_overflow(new_data, new_data_size, &sum))) {
panic("%s: Integer addition overflow %p + %lu = %lu",
__func__, (void*)new_data, (uintptr_t)new_data_size, (uintptr_t)sum);
}
pmap_ro_zone_validate_element_dst(zid, va, offset, new_data_size);
}
void
pmap_ro_zone_memcpy(
zone_id_t zid,
vm_offset_t va,
vm_offset_t offset,
const vm_offset_t new_data,
vm_size_t new_data_size)
{
const pmap_paddr_t pa = kvtophys(va + offset);
if (!new_data || new_data_size == 0) {
return;
}
pmap_ro_zone_validate_element(zid, va, offset, new_data, new_data_size);
/* Write through Physical Aperture */
memcpy((void*)phystokv(pa), (void*)new_data, new_data_size);
}
uint64_t
pmap_ro_zone_atomic_op(
zone_id_t zid,
vm_offset_t va,
vm_offset_t offset,
zro_atomic_op_t op,
uint64_t value)
{
const pmap_paddr_t pa = kvtophys(va + offset);
vm_size_t value_size = op & 0xf;
pmap_ro_zone_validate_element_dst(zid, va, offset, value_size);
/* Write through Physical Aperture */
return __zalloc_ro_mut_atomic(phystokv(pa), op, value);
}
void
pmap_ro_zone_bzero(
zone_id_t zid,
vm_offset_t va,
vm_offset_t offset,
vm_size_t size)
{
const pmap_paddr_t pa = kvtophys(va + offset);
pmap_ro_zone_validate_element(zid, va, offset, 0, size);
bzero((void*)phystokv(pa), size);
}
static uint32_t
pmap_scale_shift(void)
{
uint32_t scale = 0;
if (sane_size <= 8 * GB) {
scale = (uint32_t)(sane_size / (2 * GB));
} else if (sane_size <= 32 * GB) {
scale = 4 + (uint32_t)((sane_size - (8 * GB)) / (4 * GB));
} else {
scale = 10 + (uint32_t)MIN(4, ((sane_size - (32 * GB)) / (8 * GB)));
}
return scale;
}
LCK_GRP_DECLARE(pmap_lck_grp, "pmap");
LCK_ATTR_DECLARE(pmap_lck_rw_attr, 0, LCK_ATTR_DEBUG);
/*
* Bootstrap the system enough to run with virtual memory.
* Map the kernel's code and data, and allocate the system page table.
* Called with mapping OFF. Page_size must already be set.
*/
void
pmap_bootstrap(
__unused vm_offset_t load_start,
__unused boolean_t IA32e)
{
assert(IA32e);
vm_last_addr = VM_MAX_KERNEL_ADDRESS; /* Set the highest address
* known to VM */
/*
* The kernel's pmap is statically allocated so we don't
* have to use pmap_create, which is unlikely to work
* correctly at this part of the boot sequence.
*/
os_ref_init(&kernel_pmap->ref_count, NULL);
#if DEVELOPMENT || DEBUG
kernel_pmap->nx_enabled = TRUE;
#endif
kernel_pmap->pm_task_map = TASK_MAP_64BIT;
kernel_pmap->pm_obj = (vm_object_t) NULL;
kernel_pmap->pm_pml4 = IdlePML4;
kernel_pmap->pm_upml4 = IdlePML4;
kernel_pmap->pm_cr3 = (uintptr_t)ID_MAP_VTOP(IdlePML4);
kernel_pmap->pm_ucr3 = (uintptr_t)ID_MAP_VTOP(IdlePML4);
kernel_pmap->pm_eptp = 0;
pmap_pcid_initialize_kernel(kernel_pmap);
current_cpu_datap()->cpu_kernel_cr3 = cpu_shadowp(cpu_number())->cpu_kernel_cr3 = (addr64_t) kernel_pmap->pm_cr3;
nkpt = NKPT;
OSAddAtomic(NKPT, &inuse_ptepages_count);
OSAddAtomic64(NKPT, &alloc_ptepages_count);
bootstrap_wired_pages = NKPT;
virtual_avail = (vm_offset_t)(VM_MIN_KERNEL_ADDRESS) + (vm_offset_t)first_avail;
virtual_end = (vm_offset_t)(VM_MAX_KERNEL_ADDRESS);
if (!PE_parse_boot_argn("npvhash", &npvhashmask, sizeof(npvhashmask))) {
npvhashmask = ((NPVHASHBUCKETS) << pmap_scale_shift()) - 1;
}
npvhashbuckets = npvhashmask + 1;
if (0 != ((npvhashbuckets) & npvhashmask)) {
panic("invalid hash %d, must be ((2^N)-1), "
"using default %d\n", npvhashmask, NPVHASHMASK);
}
lck_rw_init(&kernel_pmap->pmap_rwl, &pmap_lck_grp, &pmap_lck_rw_attr);
kernel_pmap->pmap_rwl.lck_rw_can_sleep = FALSE;
pmap_cpu_init();
if (pmap_pcid_ncpus) {
printf("PMAP: PCID enabled\n");
}
if (pmap_smep_enabled) {
printf("PMAP: Supervisor Mode Execute Protection enabled\n");
}
if (pmap_smap_enabled) {
printf("PMAP: Supervisor Mode Access Protection enabled\n");
}
#if DEBUG
printf("Stack canary: 0x%lx\n", __stack_chk_guard[0]);
printf("early_random(): 0x%qx\n", early_random());
#endif
#if DEVELOPMENT || DEBUG
boolean_t ptmp;
/* Check if the user has requested disabling stack or heap no-execute
* enforcement. These are "const" variables; that qualifier is cast away
* when altering them. The TEXT/DATA const sections are marked
* write protected later in the kernel startup sequence, so altering
* them is possible at this point, in pmap_bootstrap().
*/
if (PE_parse_boot_argn("-pmap_disable_kheap_nx", &ptmp, sizeof(ptmp))) {
boolean_t *pdknxp = (boolean_t *) &pmap_disable_kheap_nx;
*pdknxp = TRUE;
}
if (PE_parse_boot_argn("-pmap_disable_kstack_nx", &ptmp, sizeof(ptmp))) {
boolean_t *pdknhp = (boolean_t *) &pmap_disable_kstack_nx;
*pdknhp = TRUE;
}
#endif /* DEVELOPMENT || DEBUG */
boot_args *args = (boot_args *)PE_state.bootArgs;
if (args->efiMode == kBootArgsEfiMode32) {
printf("EFI32: kernel virtual space limited to 4GB\n");
virtual_end = VM_MAX_KERNEL_ADDRESS_EFI32;
}
kprintf("Kernel virtual space from 0x%lx to 0x%lx.\n",
(long)KERNEL_BASE, (long)virtual_end);
kprintf("Available physical space from 0x%llx to 0x%llx\n",
avail_start, avail_end);
/*
* The -no_shared_cr3 boot-arg is a debugging feature (set by default
* in the DEBUG kernel) to force the kernel to switch to its own map
* (and cr3) when control is in kernelspace. The kernel's map does not
* include (i.e. share) userspace so wild references will cause
* a panic. Only copyin and copyout are exempt from this.
*/
(void) PE_parse_boot_argn("-no_shared_cr3",
&no_shared_cr3, sizeof(no_shared_cr3));
if (no_shared_cr3) {
kprintf("Kernel not sharing user map\n");
}
#ifdef PMAP_TRACES
if (PE_parse_boot_argn("-pmap_trace", &pmap_trace, sizeof(pmap_trace))) {
kprintf("Kernel traces for pmap operations enabled\n");
}
#endif /* PMAP_TRACES */
#if MACH_ASSERT
PE_parse_boot_argn("pmap_asserts", &pmap_asserts_enabled, sizeof(pmap_asserts_enabled));
PE_parse_boot_argn("pmap_stats_assert",
&pmap_stats_assert,
sizeof(pmap_stats_assert));
#endif /* MACH_ASSERT */
}
void
pmap_virtual_space(
vm_offset_t *startp,
vm_offset_t *endp)
{
*startp = virtual_avail;
*endp = virtual_end;
}
#if HIBERNATION
#include <IOKit/IOHibernatePrivate.h>
#include <machine/pal_hibernate.h>
int32_t pmap_npages;
int32_t pmap_teardown_last_valid_compact_indx = -1;
void pmap_pack_index(uint32_t);
int32_t pmap_unpack_index(pv_rooted_entry_t);
int32_t
pmap_unpack_index(pv_rooted_entry_t pv_h)
{
int32_t indx = 0;
indx = (int32_t)(*((uint64_t *)(&pv_h->qlink.next)) >> 48);
indx = indx << 16;
indx |= (int32_t)(*((uint64_t *)(&pv_h->qlink.prev)) >> 48);
*((uint64_t *)(&pv_h->qlink.next)) |= ((uint64_t)0xffff << 48);
*((uint64_t *)(&pv_h->qlink.prev)) |= ((uint64_t)0xffff << 48);
return indx;
}
void
pmap_pack_index(uint32_t indx)
{
pv_rooted_entry_t pv_h;
pv_h = &pv_head_table[indx];
*((uint64_t *)(&pv_h->qlink.next)) &= ~((uint64_t)0xffff << 48);
*((uint64_t *)(&pv_h->qlink.prev)) &= ~((uint64_t)0xffff << 48);
*((uint64_t *)(&pv_h->qlink.next)) |= ((uint64_t)(indx >> 16)) << 48;
*((uint64_t *)(&pv_h->qlink.prev)) |= ((uint64_t)(indx & 0xffff)) << 48;
}
void
pal_hib_teardown_pmap_structs(addr64_t *unneeded_start, addr64_t *unneeded_end)
{
int32_t i;
int32_t compact_target_indx;
compact_target_indx = 0;
for (i = 0; i < pmap_npages; i++) {
if (pv_head_table[i].pmap == PMAP_NULL) {
if (pv_head_table[compact_target_indx].pmap != PMAP_NULL) {
compact_target_indx = i;
}
} else {
pmap_pack_index((uint32_t)i);
if (pv_head_table[compact_target_indx].pmap == PMAP_NULL) {
/*
* we've got a hole to fill, so
* move this pv_rooted_entry_t to it's new home
*/
pv_head_table[compact_target_indx] = pv_head_table[i];
pv_head_table[i].pmap = PMAP_NULL;
pmap_teardown_last_valid_compact_indx = compact_target_indx;
compact_target_indx++;
} else {
pmap_teardown_last_valid_compact_indx = i;
}
}
}
*unneeded_start = (addr64_t)&pv_head_table[pmap_teardown_last_valid_compact_indx + 1];
*unneeded_end = (addr64_t)&pv_head_table[pmap_npages - 1];
HIBLOG("pal_hib_teardown_pmap_structs done: last_valid_compact_indx %d\n", pmap_teardown_last_valid_compact_indx);
}
void
pal_hib_rebuild_pmap_structs(void)
{
int32_t cindx, eindx, rindx = 0;
pv_rooted_entry_t pv_h;
eindx = (int32_t)pmap_npages;
for (cindx = pmap_teardown_last_valid_compact_indx; cindx >= 0; cindx--) {
pv_h = &pv_head_table[cindx];
rindx = pmap_unpack_index(pv_h);
assert(rindx < pmap_npages);
if (rindx != cindx) {
/*
* this pv_rooted_entry_t was moved by pal_hib_teardown_pmap_structs,
* so move it back to its real location
*/
pv_head_table[rindx] = pv_head_table[cindx];
}
if (rindx + 1 != eindx) {
/*
* the 'hole' between this vm_rooted_entry_t and the previous
* vm_rooted_entry_t we moved needs to be initialized as
* a range of zero'd vm_rooted_entry_t's
*/
bzero((char *)&pv_head_table[rindx + 1], (eindx - rindx - 1) * sizeof(struct pv_rooted_entry));
}
eindx = rindx;
}
if (rindx) {
bzero((char *)&pv_head_table[0], rindx * sizeof(struct pv_rooted_entry));
}
HIBLOG("pal_hib_rebuild_pmap_structs done: last_valid_compact_indx %d\n", pmap_teardown_last_valid_compact_indx);
}
#endif
/*
* Create pv entries for kernel pages mapped by early startup code.
* These have to exist so we can ml_static_mfree() them later.
*/
static void
pmap_pv_fixup(vm_offset_t start_va, vm_offset_t end_va)
{
ppnum_t ppn;
pv_rooted_entry_t pv_h;
uint32_t pgsz;
start_va = round_page(start_va);
end_va = trunc_page(end_va);
while (start_va < end_va) {
pgsz = PAGE_SIZE;
ppn = pmap_find_phys(kernel_pmap, start_va);
if (ppn != 0 && IS_MANAGED_PAGE(ppn)) {
pv_h = pai_to_pvh(ppn);
assert(pv_h->qlink.next == 0); /* shouldn't be init'd yet */
assert(pv_h->pmap == 0);
pv_h->va_and_flags = start_va;
pv_h->pmap = kernel_pmap;
queue_init(&pv_h->qlink);
/*
* Note that pmap_query_pagesize does not enforce start_va is aligned
* on a 2M boundary if it's within a large page
*/
if (pmap_query_pagesize(kernel_pmap, start_va) == I386_LPGBYTES) {
pgsz = I386_LPGBYTES;
}
}
if (os_add_overflow(start_va, pgsz, &start_va)) {
#if DEVELOPMENT || DEBUG
panic("pmap_pv_fixup: Unexpected address wrap (0x%lx after adding 0x%x)", start_va, pgsz);
#else
start_va = end_va;
#endif
}
}
}
static SECURITY_READ_ONLY_LATE(struct mach_vm_range) pmap_struct_range = {};
static __startup_data vm_map_t pmap_struct_map;
static __startup_data long pmap_npages_early;
static __startup_data vm_map_size_t pmap_struct_size;
KMEM_RANGE_REGISTER_DYNAMIC(pmap_struct, &pmap_struct_range, ^() {
vm_map_size_t s;
pmap_npages_early = i386_btop(avail_end);
s = (vm_map_size_t) (sizeof(struct pv_rooted_entry) * pmap_npages_early +
(sizeof(struct pv_hashed_entry_t *) * (npvhashbuckets)) +
pv_lock_table_size(pmap_npages_early) +
pv_hash_lock_table_size((npvhashbuckets)) +
pmap_npages_early);
pmap_struct_size = round_page(s);
return pmap_struct_size;
});
/*
* Initialize the pmap module.
* Called by vm_init, to initialize any structures that the pmap
* system needs to map virtual memory.
*/
void
pmap_init(void)
{
long npages;
vm_offset_t addr;
vm_size_t vsize;
vm_map_offset_t vaddr;
ppnum_t ppn;
kernel_pmap->pm_obj_pml4 = &kpml4obj_object_store;
_vm_object_allocate((vm_object_size_t)NPML4PGS * PAGE_SIZE, &kpml4obj_object_store);
kernel_pmap->pm_obj_pdpt = &kpdptobj_object_store;
_vm_object_allocate((vm_object_size_t)NPDPTPGS * PAGE_SIZE, &kpdptobj_object_store);
kernel_pmap->pm_obj = &kptobj_object_store;
_vm_object_allocate((vm_object_size_t)NPDEPGS * PAGE_SIZE, &kptobj_object_store);
/*
* Allocate memory for the pv_head_table and its lock bits,
* the modify bit array, and the pte_page table.
*/
/*
* zero bias all these arrays now instead of off avail_start
* so we cover all memory
*/
npages = pmap_npages_early;
assert(npages == i386_btop(avail_end));
#if HIBERNATION
pmap_npages = (uint32_t)npages;
#endif
vm_map_will_allocate_early_map(&pmap_struct_map);
pmap_struct_map = kmem_suballoc(kernel_map, &pmap_struct_range.min_address,
pmap_struct_size, VM_MAP_CREATE_NEVER_FAULTS,
VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, KMS_NOFAIL | KMS_PERMANENT,
VM_KERN_MEMORY_PMAP).kmr_submap;
kmem_alloc(pmap_struct_map, &addr, pmap_struct_size,
KMA_NOFAIL | KMA_ZERO | KMA_KOBJECT | KMA_PERMANENT,
VM_KERN_MEMORY_PMAP);
vaddr = addr;
vsize = pmap_struct_size;
#if PV_DEBUG
if (0 == npvhashmask) {
panic("npvhashmask not initialized");
}
#endif
/*
* Allocate the structures first to preserve word-alignment.
*/
pv_head_table = (pv_rooted_entry_t) addr;
addr = (vm_offset_t) (pv_head_table + npages);
pv_hash_table = (pv_hashed_entry_t *)addr;
addr = (vm_offset_t) (pv_hash_table + (npvhashbuckets));
pv_lock_table = (char *) addr;
addr = (vm_offset_t) (pv_lock_table + pv_lock_table_size(npages));
pv_hash_lock_table = (char *) addr;
addr = (vm_offset_t) (pv_hash_lock_table + pv_hash_lock_table_size((npvhashbuckets)));
pmap_phys_attributes = (char *) addr;
ppnum_t last_pn = i386_btop(avail_end);
unsigned int i;
pmap_memory_region_t *pmptr = pmap_memory_regions;
for (i = 0; i < pmap_memory_region_count; i++, pmptr++) {
if (pmptr->type != kEfiConventionalMemory) {
continue;
}
ppnum_t pn;
for (pn = pmptr->base; pn <= pmptr->end; pn++) {
if (pn < last_pn) {
pmap_phys_attributes[pn] |= PHYS_MANAGED;
if (pn > last_managed_page) {
last_managed_page = pn;
}
if ((pmap_high_used_bottom <= pn && pn <= pmap_high_used_top) ||
(pmap_middle_used_bottom <= pn && pn <= pmap_middle_used_top)) {
pmap_phys_attributes[pn] |= PHYS_NOENCRYPT;
}
}
}
}
while (vsize) {
ppn = pmap_find_phys(kernel_pmap, vaddr);
pmap_phys_attributes[ppn] |= PHYS_NOENCRYPT;
vaddr += PAGE_SIZE;
vsize -= PAGE_SIZE;
}
/*
* Create the zone of physical maps,
* and of the physical-to-virtual entries.
*/
pmap_zone = zone_create_ext("pmap", sizeof(struct pmap),
ZC_NOENCRYPT | ZC_ZFREE_CLEARMEM, ZONE_ID_PMAP, NULL);
/* The anchor is required to be page aligned. Zone debugging adds
* padding which may violate that requirement. Tell the zone
* subsystem that alignment is required.
*/
pmap_anchor_zone = zone_create("pagetable anchors", PAGE_SIZE,
ZC_NOENCRYPT | ZC_ALIGNMENT_REQUIRED);
/* TODO: possible general optimisation...pre-allocate via zones commonly created
* level3/2 pagetables
*/
/* The anchor is required to be page aligned. Zone debugging adds
* padding which may violate that requirement. Tell the zone
* subsystem that alignment is required.
*/
pmap_uanchor_zone = zone_create("pagetable user anchors", PAGE_SIZE,
ZC_NOENCRYPT | ZC_ALIGNMENT_REQUIRED);
pv_hashed_list_zone = zone_create("pv_list", sizeof(struct pv_hashed_entry),
ZC_NOENCRYPT | ZC_ALIGNMENT_REQUIRED);
/*
* Create pv entries for kernel pages that might get pmap_remove()ed.
*
* - very low pages that were identity mapped.
* - vm_pages[] entries that might be unused and reclaimed.
*/
assert((uintptr_t)VM_MIN_KERNEL_ADDRESS + avail_start <= (uintptr_t)vm_page_array_beginning_addr);
pmap_pv_fixup((uintptr_t)VM_MIN_KERNEL_ADDRESS, (uintptr_t)VM_MIN_KERNEL_ADDRESS + avail_start);
pmap_pv_fixup((uintptr_t)vm_page_array_beginning_addr, (uintptr_t)vm_page_array_ending_addr);
pmap_initialized = TRUE;
max_preemption_latency_tsc = tmrCvt((uint64_t)MAX_PREEMPTION_LATENCY_NS, tscFCvtn2t);
/*
* Ensure the kernel's PML4 entry exists for the basement
* before this is shared with any user.
*/
pmap_expand_pml4(kernel_pmap, KERNEL_BASEMENT, PMAP_EXPAND_OPTIONS_NONE);
#if CONFIG_VMX
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);
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);
#endif /* CONFIG_VMX */
}
void
pmap_mark_range(pmap_t npmap, uint64_t sv, uint64_t nxrosz, boolean_t NX, boolean_t ro)
{
uint64_t ev, cv = sv;
pd_entry_t *pdep;
pt_entry_t *ptep = NULL;
if (os_add_overflow(sv, nxrosz, &ev)) {
panic("pmap_mark_range: Unexpected address overflow: start=0x%llx size=0x%llx", sv, nxrosz);
}
/* XXX what if nxrosz is 0? we end up marking the page whose address is passed in via sv -- is that kosher? */
assert(!is_ept_pmap(npmap));
assert(((sv & 0xFFFULL) | (nxrosz & 0xFFFULL)) == 0);
for (pdep = pmap_pde(npmap, cv); pdep != NULL && (cv < ev);) {
uint64_t pdev = (cv & ~((uint64_t)PDEMASK));
if (*pdep & INTEL_PTE_PS) {
#ifdef REMAP_DEBUG
if ((NX ^ !!(*pdep & INTEL_PTE_NX)) || (ro ^ !!!(*pdep & INTEL_PTE_WRITE))) {
kprintf("WARNING: Remapping PDE for %p from %s%s%s to %s%s%s\n", (void *)cv,
(*pdep & INTEL_PTE_VALID) ? "R" : "",
(*pdep & INTEL_PTE_WRITE) ? "W" : "",
(*pdep & INTEL_PTE_NX) ? "" : "X",
"R",
ro ? "" : "W",
NX ? "" : "X");
}
#endif
if (NX) {
*pdep |= INTEL_PTE_NX;
} else {
*pdep &= ~INTEL_PTE_NX;
}
if (ro) {
*pdep &= ~INTEL_PTE_WRITE;
} else {
*pdep |= INTEL_PTE_WRITE;
}
if (os_add_overflow(cv, NBPD, &cv)) {
cv = ev;
} else {
cv &= ~((uint64_t) PDEMASK);