xref: /xnu-8792.41.9/osfmk/i386/commpage/commpage.c (revision 5c2921b07a2480ab43ec66f5b9e41cb872bc554f)
1 /*
2  * Copyright (c) 2003-2020 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 /*
30  *	Here's what to do if you want to add a new routine to the comm page:
31  *
32  *		1. Add a definition for it's address in osfmk/i386/cpu_capabilities.h,
33  *		   being careful to reserve room for future expansion.
34  *
35  *		2. Write one or more versions of the routine, each with it's own
36  *		   commpage_descriptor.  The tricky part is getting the "special",
37  *		   "musthave", and "canthave" fields right, so that exactly one
38  *		   version of the routine is selected for every machine.
39  *		   The source files should be in osfmk/i386/commpage/.
40  *
41  *		3. Add a ptr to your new commpage_descriptor(s) in the "routines"
42  *		   array in osfmk/i386/commpage/commpage_asm.s.  There are two
43  *		   arrays, one for the 32-bit and one for the 64-bit commpage.
44  *
45  *		4. Write the code in Libc to use the new routine.
46  */
47 
48 #include <mach/mach_types.h>
49 #include <mach/machine.h>
50 #include <mach/vm_map.h>
51 #include <mach/mach_vm.h>
52 #include <mach/machine.h>
53 #include <i386/cpuid.h>
54 #include <i386/tsc.h>
55 #include <i386/rtclock_protos.h>
56 #include <i386/cpu_data.h>
57 #include <i386/machine_routines.h>
58 #include <i386/misc_protos.h>
59 #include <i386/cpuid.h>
60 #include <machine/cpu_capabilities.h>
61 #include <machine/commpage.h>
62 #include <machine/pmap.h>
63 #include <vm/vm_kern.h>
64 #include <vm/vm_map.h>
65 #include <stdatomic.h>
66 
67 #include <ipc/ipc_port.h>
68 
69 #include <kern/page_decrypt.h>
70 #include <kern/processor.h>
71 
72 #include <sys/kdebug.h>
73 
74 #if CONFIG_ATM
75 #include <atm/atm_internal.h>
76 #endif
77 
78 /* the lists of commpage routines are in commpage_asm.s  */
79 extern  commpage_descriptor*    commpage_32_routines[];
80 extern  commpage_descriptor*    commpage_64_routines[];
81 
82 extern vm_map_t commpage32_map; // the shared submap, set up in vm init
83 extern vm_map_t commpage64_map; // the shared submap, set up in vm init
84 extern vm_map_t commpage_text32_map;    // the shared submap, set up in vm init
85 extern vm_map_t commpage_text64_map;    // the shared submap, set up in vm init
86 
87 
88 char    *commPagePtr32 = NULL;          // virtual addr in kernel map of 32-bit commpage
89 char    *commPagePtr64 = NULL;          // ...and of 64-bit commpage
90 char    *commPageTextPtr32 = NULL;      // virtual addr in kernel map of 32-bit commpage
91 char    *commPageTextPtr64 = NULL;      // ...and of 64-bit commpage
92 
93 uint64_t     _cpu_capabilities = 0;     // define the capability vector
94 
95 typedef uint32_t commpage_address_t;
96 
97 static commpage_address_t       next;   // next available address in comm page
98 
99 static char    *commPagePtr;            // virtual addr in kernel map of commpage we are working on
100 static commpage_address_t       commPageBaseOffset; // subtract from 32-bit runtime address to get offset in virtual commpage in kernel map
101 
102 static  commpage_time_data      *time_data32 = NULL;
103 static  commpage_time_data      *time_data64 = NULL;
104 static  new_commpage_timeofday_data_t *gtod_time_data32 = NULL;
105 static  new_commpage_timeofday_data_t *gtod_time_data64 = NULL;
106 
107 
108 decl_simple_lock_data(static, commpage_active_cpus_lock);
109 
110 /* Allocate the commpage and add to the shared submap created by vm:
111  *      1. allocate a page in the kernel map (RW)
112  *	2. wire it down
113  *	3. make a memory entry out of it
114  *	4. map that entry into the shared comm region map (R-only)
115  */
116 
117 static  void*
commpage_allocate(vm_map_t submap,size_t area_used,vm_prot_t uperm)118 commpage_allocate(
119 	vm_map_t        submap,                 // commpage32_map or commpage_map64
120 	size_t          area_used,              // _COMM_PAGE32_AREA_USED or _COMM_PAGE64_AREA_USED
121 	vm_prot_t       uperm)
122 {
123 	vm_offset_t     kernel_addr = 0;        // address of commpage in kernel map
124 	vm_offset_t     zero = 0;
125 	vm_size_t       size = area_used;       // size actually populated
126 	vm_map_entry_t  entry;
127 	ipc_port_t      handle;
128 	kern_return_t   kr;
129 	vm_map_kernel_flags_t vmk_flags;
130 
131 	if (submap == NULL) {
132 		panic("commpage submap is null");
133 	}
134 
135 	kr = vm_map_kernel(kernel_map,
136 	    &kernel_addr,
137 	    area_used,
138 	    0,
139 	    VM_FLAGS_ANYWHERE,
140 	    VM_MAP_KERNEL_FLAGS_NONE,
141 	    VM_KERN_MEMORY_OSFMK,
142 	    NULL,
143 	    0,
144 	    FALSE,
145 	    VM_PROT_ALL,
146 	    VM_PROT_ALL,
147 	    VM_INHERIT_NONE);
148 	if (kr != KERN_SUCCESS) {
149 		panic("cannot allocate commpage %d", kr);
150 	}
151 
152 	if ((kr = vm_map_wire_kernel(kernel_map,
153 	    kernel_addr,
154 	    kernel_addr + area_used,
155 	    VM_PROT_DEFAULT, VM_KERN_MEMORY_OSFMK,
156 	    FALSE))) {
157 		panic("cannot wire commpage: %d", kr);
158 	}
159 
160 	/*
161 	 * Now that the object is created and wired into the kernel map, mark it so that no delay
162 	 * copy-on-write will ever be performed on it as a result of mapping it into user-space.
163 	 * If such a delayed copy ever occurred, we could remove the kernel's wired mapping - and
164 	 * that would be a real disaster.
165 	 *
166 	 * JMM - What we really need is a way to create it like this in the first place.
167 	 */
168 	if (!(kr = vm_map_lookup_entry( kernel_map, vm_map_trunc_page(kernel_addr, VM_MAP_PAGE_MASK(kernel_map)), &entry) || entry->is_sub_map)) {
169 		panic("cannot find commpage entry %d", kr);
170 	}
171 	VME_OBJECT(entry)->copy_strategy = MEMORY_OBJECT_COPY_NONE;
172 
173 	if ((kr = mach_make_memory_entry( kernel_map,           // target map
174 	    &size,                                      // size
175 	    kernel_addr,                                // offset (address in kernel map)
176 	    uperm,                              // protections as specified
177 	    &handle,                                    // this is the object handle we get
178 	    NULL ))) {                                  // parent_entry (what is this?)
179 		panic("cannot make entry for commpage %d", kr);
180 	}
181 
182 	vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
183 	if (uperm == (VM_PROT_READ | VM_PROT_EXECUTE)) {
184 		/*
185 		 * Mark this unsigned executable mapping as "jit" to avoid
186 		 * code-signing violations when attempting to execute unsigned
187 		 * code.
188 		 */
189 		vmk_flags.vmkf_map_jit = TRUE;
190 	}
191 
192 	kr = vm_map_64_kernel(
193 		submap,                 // target map (shared submap)
194 		&zero,                  // address (map into 1st page in submap)
195 		area_used,              // size
196 		0,                      // mask
197 		VM_FLAGS_FIXED,         // flags (it must be 1st page in submap)
198 		vmk_flags,
199 		VM_KERN_MEMORY_NONE,
200 		handle,                 // port is the memory entry we just made
201 		0,                      // offset (map 1st page in memory entry)
202 		FALSE,                  // copy
203 		uperm,                  // cur_protection (R-only in user map)
204 		uperm,                  // max_protection
205 		VM_INHERIT_SHARE);      // inheritance
206 	if (kr != KERN_SUCCESS) {
207 		panic("cannot map commpage %d", kr);
208 	}
209 
210 	ipc_port_release(handle);
211 	/* Make the kernel mapping non-executable. This cannot be done
212 	 * at the time of map entry creation as mach_make_memory_entry
213 	 * cannot handle disjoint permissions at this time.
214 	 */
215 	kr = vm_protect(kernel_map, kernel_addr, area_used, FALSE, VM_PROT_READ | VM_PROT_WRITE);
216 	assert(kr == KERN_SUCCESS);
217 
218 	return (void*)(intptr_t)kernel_addr;                     // return address in kernel map
219 }
220 
221 /* Get address (in kernel map) of a commpage field. */
222 
223 static void*
commpage_addr_of(commpage_address_t addr_at_runtime)224 commpage_addr_of(
225 	commpage_address_t     addr_at_runtime )
226 {
227 	return (void*) ((uintptr_t)commPagePtr + (addr_at_runtime - commPageBaseOffset));
228 }
229 
230 /*
231  * Calculate address of data within 32- and 64-bit commpages (not to be used with commpage
232  * text).
233  */
234 static void*
commpage_specific_addr_of(char * commPageBase,commpage_address_t addr_at_runtime)235 commpage_specific_addr_of(char *commPageBase, commpage_address_t addr_at_runtime)
236 {
237 	/*
238 	 * Note that the base address (_COMM_PAGE32_BASE_ADDRESS) is the same for
239 	 * 32- and 64-bit commpages
240 	 */
241 	return (void*) ((uintptr_t)commPageBase + (addr_at_runtime - _COMM_PAGE32_BASE_ADDRESS));
242 }
243 
244 /* Determine number of CPUs on this system.  We cannot rely on
245  * machine_info.max_cpus this early in the boot.
246  */
247 static int
commpage_cpus(void)248 commpage_cpus( void )
249 {
250 	unsigned int cpus;
251 
252 	cpus = ml_wait_max_cpus();                   // NB: this call can block
253 
254 	if (cpus == 0) {
255 		panic("commpage cpus==0");
256 	}
257 	if (cpus > 0xFF) {
258 		cpus = 0xFF;
259 	}
260 
261 	return cpus;
262 }
263 
264 /* Initialize kernel version of _cpu_capabilities vector (used by KEXTs.) */
265 
266 static void
commpage_init_cpu_capabilities(void)267 commpage_init_cpu_capabilities( void )
268 {
269 	uint64_t bits;
270 	int cpus;
271 	ml_cpu_info_t cpu_info;
272 
273 	bits = 0;
274 	ml_cpu_get_info(&cpu_info);
275 
276 	switch (cpu_info.vector_unit) {
277 	case 9:
278 		bits |= kHasAVX1_0;
279 		OS_FALLTHROUGH;
280 	case 8:
281 		bits |= kHasSSE4_2;
282 		OS_FALLTHROUGH;
283 	case 7:
284 		bits |= kHasSSE4_1;
285 		OS_FALLTHROUGH;
286 	case 6:
287 		bits |= kHasSupplementalSSE3;
288 		OS_FALLTHROUGH;
289 	case 5:
290 		bits |= kHasSSE3;
291 		OS_FALLTHROUGH;
292 	case 4:
293 		bits |= kHasSSE2;
294 		OS_FALLTHROUGH;
295 	case 3:
296 		bits |= kHasSSE;
297 		OS_FALLTHROUGH;
298 	case 2:
299 		bits |= kHasMMX;
300 		OS_FALLTHROUGH;
301 	default:
302 		break;
303 	}
304 	switch (cpu_info.cache_line_size) {
305 	case 128:
306 		bits |= kCache128;
307 		break;
308 	case 64:
309 		bits |= kCache64;
310 		break;
311 	case 32:
312 		bits |= kCache32;
313 		break;
314 	default:
315 		break;
316 	}
317 	cpus = commpage_cpus();                 // how many CPUs do we have
318 
319 	bits |= (cpus << kNumCPUsShift);
320 
321 	bits |= kFastThreadLocalStorage;        // we use %gs for TLS
322 
323 #define setif(_bits, _bit, _condition) \
324 	if (_condition) _bits |= _bit
325 
326 	setif(bits, kUP, cpus == 1);
327 	setif(bits, k64Bit, cpu_mode_is64bit());
328 	setif(bits, kSlow, tscFreq <= SLOW_TSC_THRESHOLD);
329 
330 	setif(bits, kHasAES, cpuid_features() &
331 	    CPUID_FEATURE_AES);
332 	setif(bits, kHasF16C, cpuid_features() &
333 	    CPUID_FEATURE_F16C);
334 	setif(bits, kHasRDRAND, cpuid_features() &
335 	    CPUID_FEATURE_RDRAND);
336 	setif(bits, kHasFMA, cpuid_features() &
337 	    CPUID_FEATURE_FMA);
338 
339 	setif(bits, kHasBMI1, cpuid_leaf7_features() &
340 	    CPUID_LEAF7_FEATURE_BMI1);
341 	setif(bits, kHasBMI2, cpuid_leaf7_features() &
342 	    CPUID_LEAF7_FEATURE_BMI2);
343 	/* Do not advertise RTM and HLE if the TSX FORCE ABORT WA is required */
344 	if (cpuid_wa_required(CPU_INTEL_TSXFA) & CWA_OFF) {
345 		setif(bits, kHasRTM, cpuid_leaf7_features() &
346 		    CPUID_LEAF7_FEATURE_RTM);
347 		setif(bits, kHasHLE, cpuid_leaf7_features() &
348 		    CPUID_LEAF7_FEATURE_HLE);
349 	}
350 	setif(bits, kHasAVX2_0, cpuid_leaf7_features() &
351 	    CPUID_LEAF7_FEATURE_AVX2);
352 	setif(bits, kHasRDSEED, cpuid_leaf7_features() &
353 	    CPUID_LEAF7_FEATURE_RDSEED);
354 	setif(bits, kHasADX, cpuid_leaf7_features() &
355 	    CPUID_LEAF7_FEATURE_ADX);
356 
357 #if 0   /* The kernel doesn't support MPX or SGX */
358 	setif(bits, kHasMPX, cpuid_leaf7_features() &
359 	    CPUID_LEAF7_FEATURE_MPX);
360 	setif(bits, kHasSGX, cpuid_leaf7_features() &
361 	    CPUID_LEAF7_FEATURE_SGX);
362 #endif
363 
364 	if (ml_fpu_avx512_enabled()) {
365 		setif(bits, kHasAVX512F, cpuid_leaf7_features() &
366 		    CPUID_LEAF7_FEATURE_AVX512F);
367 		setif(bits, kHasAVX512CD, cpuid_leaf7_features() &
368 		    CPUID_LEAF7_FEATURE_AVX512CD);
369 		setif(bits, kHasAVX512DQ, cpuid_leaf7_features() &
370 		    CPUID_LEAF7_FEATURE_AVX512DQ);
371 		setif(bits, kHasAVX512BW, cpuid_leaf7_features() &
372 		    CPUID_LEAF7_FEATURE_AVX512BW);
373 		setif(bits, kHasAVX512VL, cpuid_leaf7_features() &
374 		    CPUID_LEAF7_FEATURE_AVX512VL);
375 		setif(bits, kHasAVX512IFMA, cpuid_leaf7_features() &
376 		    CPUID_LEAF7_FEATURE_AVX512IFMA);
377 		setif(bits, kHasAVX512VBMI, cpuid_leaf7_features() &
378 		    CPUID_LEAF7_FEATURE_AVX512VBMI);
379 		setif(bits, kHasVAES, cpuid_leaf7_features() &
380 		    CPUID_LEAF7_FEATURE_VAES);
381 		setif(bits, kHasVPCLMULQDQ, cpuid_leaf7_features() &
382 		    CPUID_LEAF7_FEATURE_VPCLMULQDQ);
383 		setif(bits, kHasAVX512VNNI, cpuid_leaf7_features() &
384 		    CPUID_LEAF7_FEATURE_AVX512VNNI);
385 		setif(bits, kHasAVX512BITALG, cpuid_leaf7_features() &
386 		    CPUID_LEAF7_FEATURE_AVX512BITALG);
387 		setif(bits, kHasAVX512VPOPCNTDQ, cpuid_leaf7_features() &
388 		    CPUID_LEAF7_FEATURE_AVX512VPCDQ);
389 	}
390 
391 	uint64_t misc_enable = rdmsr64(MSR_IA32_MISC_ENABLE);
392 	setif(bits, kHasENFSTRG, (misc_enable & 1ULL) &&
393 	    (cpuid_leaf7_features() &
394 	    CPUID_LEAF7_FEATURE_ERMS));
395 
396 	_cpu_capabilities = bits;               // set kernel version for use by drivers etc
397 }
398 
399 /* initialize the approx_time_supported flag and set the approx time to 0.
400  * Called during initial commpage population.
401  */
402 static void
commpage_mach_approximate_time_init(void)403 commpage_mach_approximate_time_init(void)
404 {
405 	char *cp = commPagePtr32;
406 	uint8_t supported;
407 
408 #ifdef CONFIG_MACH_APPROXIMATE_TIME
409 	supported = 1;
410 #else
411 	supported = 0;
412 #endif
413 	if (cp) {
414 		cp += (_COMM_PAGE_APPROX_TIME_SUPPORTED - _COMM_PAGE32_BASE_ADDRESS);
415 		*(boolean_t *)cp = supported;
416 	}
417 
418 	cp = commPagePtr64;
419 	if (cp) {
420 		cp += (_COMM_PAGE_APPROX_TIME_SUPPORTED - _COMM_PAGE32_START_ADDRESS);
421 		*(boolean_t *)cp = supported;
422 	}
423 	commpage_update_mach_approximate_time(0);
424 }
425 
426 static void
commpage_mach_continuous_time_init(void)427 commpage_mach_continuous_time_init(void)
428 {
429 	commpage_update_mach_continuous_time(0);
430 }
431 
432 static void
commpage_boottime_init(void)433 commpage_boottime_init(void)
434 {
435 	clock_sec_t secs;
436 	clock_usec_t microsecs;
437 	clock_get_boottime_microtime(&secs, &microsecs);
438 	commpage_update_boottime(secs * USEC_PER_SEC + microsecs);
439 }
440 
441 uint64_t
_get_cpu_capabilities(void)442 _get_cpu_capabilities(void)
443 {
444 	return _cpu_capabilities;
445 }
446 
447 /* Copy data into commpage. */
448 
449 static void
commpage_stuff(commpage_address_t address,const void * source,int length)450 commpage_stuff(
451 	commpage_address_t  address,
452 	const void  *source,
453 	int         length  )
454 {
455 	void        *dest = commpage_addr_of(address);
456 
457 	if (address < next) {
458 		panic("commpage overlap at address 0x%p, 0x%x < 0x%x", dest, address, next);
459 	}
460 
461 	bcopy(source, dest, length);
462 
463 	next = address + length;
464 }
465 
466 /*
467  * Updates both the 32-bit and 64-bit commpages with the new data.
468  */
469 static void
commpage_update(commpage_address_t address,const void * source,int length)470 commpage_update(commpage_address_t address, const void *source, int length)
471 {
472 	void *dest = commpage_specific_addr_of(commPagePtr32, address);
473 	bcopy(source, dest, length);
474 
475 	dest = commpage_specific_addr_of(commPagePtr64, address);
476 	bcopy(source, dest, length);
477 }
478 
479 void
commpage_post_ucode_update(void)480 commpage_post_ucode_update(void)
481 {
482 	commpage_init_cpu_capabilities();
483 	commpage_update(_COMM_PAGE_CPU_CAPABILITIES64, &_cpu_capabilities, sizeof(_cpu_capabilities));
484 	commpage_update(_COMM_PAGE_CPU_CAPABILITIES, &_cpu_capabilities, sizeof(uint32_t));
485 }
486 
487 /* Copy a routine into comm page if it matches running machine.
488  */
489 static void
commpage_stuff_routine(commpage_descriptor * rd)490 commpage_stuff_routine(
491 	commpage_descriptor *rd     )
492 {
493 	commpage_stuff(rd->commpage_address, rd->code_address, rd->code_length);
494 }
495 
496 
497 /* Fill in the 32- or 64-bit commpage.  Called once for each.
498  */
499 
500 static void
commpage_populate_one(vm_map_t submap,char ** kernAddressPtr,size_t area_used,commpage_address_t base_offset,commpage_time_data ** time_data,new_commpage_timeofday_data_t ** gtod_time_data,const char * signature,vm_prot_t uperm)501 commpage_populate_one(
502 	vm_map_t        submap,         // commpage32_map or compage64_map
503 	char **         kernAddressPtr, // &commPagePtr32 or &commPagePtr64
504 	size_t          area_used,      // _COMM_PAGE32_AREA_USED or _COMM_PAGE64_AREA_USED
505 	commpage_address_t base_offset, // will become commPageBaseOffset
506 	commpage_time_data** time_data, // &time_data32 or &time_data64
507 	new_commpage_timeofday_data_t** gtod_time_data, // &gtod_time_data32 or &gtod_time_data64
508 	const char*     signature,      // "commpage 32-bit" or "commpage 64-bit"
509 	vm_prot_t       uperm)
510 {
511 	uint8_t         c1;
512 	uint16_t        c2;
513 	uint64_t        c8;
514 	uint32_t        cfamily;
515 	short   version = _COMM_PAGE_THIS_VERSION;
516 
517 	next = 0;
518 	commPagePtr = (char *)commpage_allocate( submap, (vm_size_t) area_used, uperm );
519 	*kernAddressPtr = commPagePtr;                          // save address either in commPagePtr32 or 64
520 	commPageBaseOffset = base_offset;
521 
522 	*time_data = commpage_addr_of( _COMM_PAGE_TIME_DATA_START );
523 	*gtod_time_data = commpage_addr_of( _COMM_PAGE_NEWTIMEOFDAY_DATA );
524 
525 	/* Stuff in the constants.  We move things into the comm page in strictly
526 	 * ascending order, so we can check for overlap and panic if so.
527 	 * Note: the 32-bit cpu_capabilities vector is retained in addition to
528 	 * the expanded 64-bit vector.
529 	 */
530 	commpage_stuff(_COMM_PAGE_SIGNATURE, signature, (int)MIN(_COMM_PAGE_SIGNATURELEN, strlen(signature)));
531 	commpage_stuff(_COMM_PAGE_CPU_CAPABILITIES64, &_cpu_capabilities, sizeof(_cpu_capabilities));
532 	commpage_stuff(_COMM_PAGE_VERSION, &version, sizeof(short));
533 	commpage_stuff(_COMM_PAGE_CPU_CAPABILITIES, &_cpu_capabilities, sizeof(uint32_t));
534 
535 	c2 = 32;  // default
536 	if (_cpu_capabilities & kCache64) {
537 		c2 = 64;
538 	} else if (_cpu_capabilities & kCache128) {
539 		c2 = 128;
540 	}
541 	commpage_stuff(_COMM_PAGE_CACHE_LINESIZE, &c2, 2);
542 
543 	/* machine_info valid after ml_wait_max_cpus() */
544 	c1 = machine_info.physical_cpu_max;
545 	commpage_stuff(_COMM_PAGE_PHYSICAL_CPUS, &c1, 1);
546 	c1 = machine_info.logical_cpu_max;
547 	commpage_stuff(_COMM_PAGE_LOGICAL_CPUS, &c1, 1);
548 
549 	c8 = ml_cpu_cache_size(0);
550 	commpage_stuff(_COMM_PAGE_MEMORY_SIZE, &c8, 8);
551 
552 	cfamily = cpuid_info()->cpuid_cpufamily;
553 	commpage_stuff(_COMM_PAGE_CPUFAMILY, &cfamily, 4);
554 	c1 = PAGE_SHIFT;
555 	commpage_stuff(_COMM_PAGE_KERNEL_PAGE_SHIFT, &c1, 1);
556 	commpage_stuff(_COMM_PAGE_USER_PAGE_SHIFT_64, &c1, 1);
557 
558 	if (next > _COMM_PAGE_END) {
559 		panic("commpage overflow: next = 0x%08x, commPagePtr = 0x%p", next, commPagePtr);
560 	}
561 }
562 
563 
564 /* Fill in commpages: called once, during kernel initialization, from the
565  * startup thread before user-mode code is running.
566  *
567  * See the top of this file for a list of what you have to do to add
568  * a new routine to the commpage.
569  */
570 
571 void
commpage_populate(void)572 commpage_populate( void )
573 {
574 	commpage_init_cpu_capabilities();
575 
576 	commpage_populate_one(  commpage32_map,
577 	    &commPagePtr32,
578 	    _COMM_PAGE32_AREA_USED,
579 	    _COMM_PAGE32_BASE_ADDRESS,
580 	    &time_data32,
581 	    &gtod_time_data32,
582 	    _COMM_PAGE32_SIGNATURE_STRING,
583 	    VM_PROT_READ);
584 #ifndef __LP64__
585 	pmap_commpage32_init((vm_offset_t) commPagePtr32, _COMM_PAGE32_BASE_ADDRESS,
586 	    _COMM_PAGE32_AREA_USED / INTEL_PGBYTES);
587 #endif
588 	time_data64 = time_data32;                      /* if no 64-bit commpage, point to 32-bit */
589 	gtod_time_data64 = gtod_time_data32;
590 
591 	if (_cpu_capabilities & k64Bit) {
592 		commpage_populate_one(  commpage64_map,
593 		    &commPagePtr64,
594 		    _COMM_PAGE64_AREA_USED,
595 		    _COMM_PAGE32_START_ADDRESS,                     /* commpage address are relative to 32-bit commpage placement */
596 		    &time_data64,
597 		    &gtod_time_data64,
598 		    _COMM_PAGE64_SIGNATURE_STRING,
599 		    VM_PROT_READ);
600 #ifndef __LP64__
601 		pmap_commpage64_init((vm_offset_t) commPagePtr64, _COMM_PAGE64_BASE_ADDRESS,
602 		    _COMM_PAGE64_AREA_USED / INTEL_PGBYTES);
603 #endif
604 	}
605 
606 	simple_lock_init(&commpage_active_cpus_lock, 0);
607 
608 	commpage_update_active_cpus();
609 	commpage_mach_approximate_time_init();
610 	commpage_mach_continuous_time_init();
611 	commpage_boottime_init();
612 	rtc_nanotime_init_commpage();
613 	commpage_update_kdebug_state();
614 #if CONFIG_ATM
615 	commpage_update_atm_diagnostic_config(atm_get_diagnostic_config());
616 #endif
617 }
618 
619 /* Fill in the common routines during kernel initialization.
620  * This is called before user-mode code is running.
621  */
622 void
commpage_text_populate(void)623 commpage_text_populate( void )
624 {
625 	commpage_descriptor **rd;
626 
627 	next = 0;
628 	commPagePtr = (char *) commpage_allocate(commpage_text32_map, (vm_size_t) _COMM_PAGE_TEXT_AREA_USED, VM_PROT_READ | VM_PROT_EXECUTE);
629 	commPageTextPtr32 = commPagePtr;
630 
631 	char *cptr = commPagePtr;
632 	int i = 0;
633 	for (; i < _COMM_PAGE_TEXT_AREA_USED; i++) {
634 		cptr[i] = 0xCC;
635 	}
636 
637 	commPageBaseOffset = _COMM_PAGE_TEXT_START;
638 	for (rd = commpage_32_routines; *rd != NULL; rd++) {
639 		commpage_stuff_routine(*rd);
640 	}
641 
642 #ifndef __LP64__
643 	pmap_commpage32_init((vm_offset_t) commPageTextPtr32, _COMM_PAGE_TEXT_START,
644 	    _COMM_PAGE_TEXT_AREA_USED / INTEL_PGBYTES);
645 #endif
646 
647 	if (_cpu_capabilities & k64Bit) {
648 		next = 0;
649 		commPagePtr = (char *) commpage_allocate(commpage_text64_map, (vm_size_t) _COMM_PAGE_TEXT_AREA_USED, VM_PROT_READ | VM_PROT_EXECUTE);
650 		commPageTextPtr64 = commPagePtr;
651 
652 		cptr = commPagePtr;
653 		for (i = 0; i < _COMM_PAGE_TEXT_AREA_USED; i++) {
654 			cptr[i] = 0xCC;
655 		}
656 
657 		for (rd = commpage_64_routines; *rd != NULL; rd++) {
658 			commpage_stuff_routine(*rd);
659 		}
660 
661 #ifndef __LP64__
662 		pmap_commpage64_init((vm_offset_t) commPageTextPtr64, _COMM_PAGE_TEXT_START,
663 		    _COMM_PAGE_TEXT_AREA_USED / INTEL_PGBYTES);
664 #endif
665 	}
666 
667 	if (next > _COMM_PAGE_TEXT_END) {
668 		panic("commpage text overflow: next=0x%08x, commPagePtr=%p", next, commPagePtr);
669 	}
670 }
671 
672 /* Update commpage nanotime information.
673  *
674  * This routine must be serialized by some external means, ie a lock.
675  */
676 
677 void
commpage_set_nanotime(uint64_t tsc_base,uint64_t ns_base,uint32_t scale,uint32_t shift)678 commpage_set_nanotime(
679 	uint64_t        tsc_base,
680 	uint64_t        ns_base,
681 	uint32_t        scale,
682 	uint32_t        shift )
683 {
684 	commpage_time_data      *p32 = time_data32;
685 	commpage_time_data      *p64 = time_data64;
686 	static uint32_t generation = 0;
687 	uint32_t        next_gen;
688 
689 	if (p32 == NULL) {              /* have commpages been allocated yet? */
690 		return;
691 	}
692 
693 	if (generation != p32->nt_generation) {
694 		panic("nanotime trouble 1");    /* possibly not serialized */
695 	}
696 	if (ns_base < p32->nt_ns_base) {
697 		panic("nanotime trouble 2");
698 	}
699 	if ((shift != 0) && ((_cpu_capabilities & kSlow) == 0)) {
700 		panic("nanotime trouble 3");
701 	}
702 
703 	next_gen = ++generation;
704 	if (next_gen == 0) {
705 		next_gen = ++generation;
706 	}
707 
708 	p32->nt_generation = 0;         /* mark invalid, so commpage won't try to use it */
709 	p64->nt_generation = 0;
710 
711 	p32->nt_tsc_base = tsc_base;
712 	p64->nt_tsc_base = tsc_base;
713 
714 	p32->nt_ns_base = ns_base;
715 	p64->nt_ns_base = ns_base;
716 
717 	p32->nt_scale = scale;
718 	p64->nt_scale = scale;
719 
720 	p32->nt_shift = shift;
721 	p64->nt_shift = shift;
722 
723 	p32->nt_generation = next_gen;  /* mark data as valid */
724 	p64->nt_generation = next_gen;
725 }
726 
727 /* Update commpage gettimeofday() information.  As with nanotime(), we interleave
728  * updates to the 32- and 64-bit commpage, in order to keep time more nearly in sync
729  * between the two environments.
730  *
731  * This routine must be serializeed by some external means, ie a lock.
732  */
733 
734 void
commpage_set_timestamp(uint64_t abstime,uint64_t sec,uint64_t frac,uint64_t scale,uint64_t tick_per_sec)735 commpage_set_timestamp(
736 	uint64_t        abstime,
737 	uint64_t        sec,
738 	uint64_t        frac,
739 	uint64_t        scale,
740 	uint64_t        tick_per_sec)
741 {
742 	new_commpage_timeofday_data_t   *p32 = gtod_time_data32;
743 	new_commpage_timeofday_data_t   *p64 = gtod_time_data64;
744 
745 	p32->TimeStamp_tick = 0x0ULL;
746 	p64->TimeStamp_tick = 0x0ULL;
747 
748 	p32->TimeStamp_sec = sec;
749 	p64->TimeStamp_sec = sec;
750 
751 	p32->TimeStamp_frac = frac;
752 	p64->TimeStamp_frac = frac;
753 
754 	p32->Ticks_scale = scale;
755 	p64->Ticks_scale = scale;
756 
757 	p32->Ticks_per_sec = tick_per_sec;
758 	p64->Ticks_per_sec = tick_per_sec;
759 
760 	p32->TimeStamp_tick = abstime;
761 	p64->TimeStamp_tick = abstime;
762 }
763 
764 /* Update _COMM_PAGE_MEMORY_PRESSURE.  Called periodically from vm's compute_memory_pressure()  */
765 
766 void
commpage_set_memory_pressure(unsigned int pressure)767 commpage_set_memory_pressure(
768 	unsigned int    pressure )
769 {
770 	char        *cp;
771 	uint32_t    *ip;
772 
773 	cp = commPagePtr32;
774 	if (cp) {
775 		cp += (_COMM_PAGE_MEMORY_PRESSURE - _COMM_PAGE32_BASE_ADDRESS);
776 		ip = (uint32_t*) (void *) cp;
777 		*ip = (uint32_t) pressure;
778 	}
779 
780 	cp = commPagePtr64;
781 	if (cp) {
782 		cp += (_COMM_PAGE_MEMORY_PRESSURE - _COMM_PAGE32_START_ADDRESS);
783 		ip = (uint32_t*) (void *) cp;
784 		*ip = (uint32_t) pressure;
785 	}
786 }
787 
788 /* Updated every time a logical CPU goes offline/online */
789 void
commpage_update_active_cpus(void)790 commpage_update_active_cpus(void)
791 {
792 	char        *cp;
793 	volatile uint8_t    *ip;
794 
795 	/* At least 32-bit commpage must be initialized */
796 	if (!commPagePtr32) {
797 		return;
798 	}
799 
800 	simple_lock(&commpage_active_cpus_lock, LCK_GRP_NULL);
801 
802 	cp = commPagePtr32;
803 	cp += (_COMM_PAGE_ACTIVE_CPUS - _COMM_PAGE32_BASE_ADDRESS);
804 	ip = (volatile uint8_t*) cp;
805 	*ip = (uint8_t) processor_avail_count_user;
806 
807 	cp = commPagePtr64;
808 	if (cp) {
809 		cp += (_COMM_PAGE_ACTIVE_CPUS - _COMM_PAGE32_START_ADDRESS);
810 		ip = (volatile uint8_t*) cp;
811 		*ip = (uint8_t) processor_avail_count_user;
812 	}
813 
814 	simple_unlock(&commpage_active_cpus_lock);
815 }
816 
817 /*
818  * Update the commpage with current kdebug state. This currently has bits for
819  * global trace state, and typefilter enablement. It is likely additional state
820  * will be tracked in the future.
821  *
822  * INVARIANT: This value will always be 0 if global tracing is disabled. This
823  * allows simple guard tests of "if (*_COMM_PAGE_KDEBUG_ENABLE) { ... }"
824  */
825 void
commpage_update_kdebug_state(void)826 commpage_update_kdebug_state(void)
827 {
828 	volatile uint32_t *saved_data_ptr;
829 	char *cp;
830 
831 	cp = commPagePtr32;
832 	if (cp) {
833 		cp += (_COMM_PAGE_KDEBUG_ENABLE - _COMM_PAGE32_BASE_ADDRESS);
834 		saved_data_ptr = (volatile uint32_t *)cp;
835 		*saved_data_ptr = kdebug_commpage_state();
836 	}
837 
838 	cp = commPagePtr64;
839 	if (cp) {
840 		cp += (_COMM_PAGE_KDEBUG_ENABLE - _COMM_PAGE32_START_ADDRESS);
841 		saved_data_ptr = (volatile uint32_t *)cp;
842 		*saved_data_ptr = kdebug_commpage_state();
843 	}
844 }
845 
846 /* Ditto for atm_diagnostic_config */
847 void
commpage_update_atm_diagnostic_config(uint32_t diagnostic_config)848 commpage_update_atm_diagnostic_config(uint32_t diagnostic_config)
849 {
850 	volatile uint32_t *saved_data_ptr;
851 	char *cp;
852 
853 	cp = commPagePtr32;
854 	if (cp) {
855 		cp += (_COMM_PAGE_ATM_DIAGNOSTIC_CONFIG - _COMM_PAGE32_BASE_ADDRESS);
856 		saved_data_ptr = (volatile uint32_t *)cp;
857 		*saved_data_ptr = diagnostic_config;
858 	}
859 
860 	cp = commPagePtr64;
861 	if (cp) {
862 		cp += (_COMM_PAGE_ATM_DIAGNOSTIC_CONFIG - _COMM_PAGE32_START_ADDRESS);
863 		saved_data_ptr = (volatile uint32_t *)cp;
864 		*saved_data_ptr = diagnostic_config;
865 	}
866 }
867 
868 /*
869  * update the commpage with if dtrace user land probes are enabled
870  */
871 void
commpage_update_dof(boolean_t enabled)872 commpage_update_dof(boolean_t enabled)
873 {
874 #if CONFIG_DTRACE
875 	char *cp;
876 
877 	cp = commPagePtr32;
878 	if (cp) {
879 		cp += (_COMM_PAGE_DTRACE_DOF_ENABLED - _COMM_PAGE32_BASE_ADDRESS);
880 		*cp = (enabled ? 1 : 0);
881 	}
882 
883 	cp = commPagePtr64;
884 	if (cp) {
885 		cp += (_COMM_PAGE_DTRACE_DOF_ENABLED - _COMM_PAGE32_START_ADDRESS);
886 		*cp = (enabled ? 1 : 0);
887 	}
888 #else
889 	(void)enabled;
890 #endif
891 }
892 
893 
894 /*
895  * update the dyld global config flags
896  */
897 void
commpage_update_dyld_flags(uint64_t value)898 commpage_update_dyld_flags(uint64_t value)
899 {
900 	char *cp;
901 
902 	cp = commPagePtr32;
903 	if (cp) {
904 		cp += (_COMM_PAGE_DYLD_FLAGS - _COMM_PAGE32_BASE_ADDRESS);
905 		*(uint64_t *)cp = value;
906 	}
907 
908 	cp = commPagePtr64;
909 	if (cp) {
910 		cp += (_COMM_PAGE_DYLD_FLAGS - _COMM_PAGE32_BASE_ADDRESS);
911 		*(uint64_t *)cp = value;
912 	}
913 }
914 
915 
916 /*
917  * update the commpage data for last known value of mach_absolute_time()
918  */
919 
920 void
commpage_update_mach_approximate_time(uint64_t abstime)921 commpage_update_mach_approximate_time(uint64_t abstime)
922 {
923 #ifdef CONFIG_MACH_APPROXIMATE_TIME
924 	uint64_t saved_data;
925 	char *cp;
926 
927 	cp = commPagePtr32;
928 	if (cp) {
929 		cp += (_COMM_PAGE_APPROX_TIME - _COMM_PAGE32_BASE_ADDRESS);
930 		saved_data = atomic_load_explicit((_Atomic uint64_t *)(uintptr_t)cp, memory_order_relaxed);
931 		if (saved_data < abstime) {
932 			/* ignoring the success/fail return value assuming that
933 			 * if the value has been updated since we last read it,
934 			 * "someone" has a newer timestamp than us and ours is
935 			 * now invalid. */
936 			atomic_compare_exchange_strong_explicit((_Atomic uint64_t *)(uintptr_t)cp,
937 			    &saved_data, abstime, memory_order_relaxed, memory_order_relaxed);
938 		}
939 	}
940 	cp = commPagePtr64;
941 	if (cp) {
942 		cp += (_COMM_PAGE_APPROX_TIME - _COMM_PAGE32_START_ADDRESS);
943 		saved_data = atomic_load_explicit((_Atomic uint64_t *)(uintptr_t)cp, memory_order_relaxed);
944 		if (saved_data < abstime) {
945 			/* ignoring the success/fail return value assuming that
946 			 * if the value has been updated since we last read it,
947 			 * "someone" has a newer timestamp than us and ours is
948 			 * now invalid. */
949 			atomic_compare_exchange_strong_explicit((_Atomic uint64_t *)(uintptr_t)cp,
950 			    &saved_data, abstime, memory_order_relaxed, memory_order_relaxed);
951 		}
952 	}
953 #else
954 #pragma unused (abstime)
955 #endif
956 }
957 
958 void
commpage_update_mach_continuous_time(uint64_t sleeptime)959 commpage_update_mach_continuous_time(uint64_t sleeptime)
960 {
961 	char *cp;
962 	cp = commPagePtr32;
963 	if (cp) {
964 		cp += (_COMM_PAGE_CONT_TIMEBASE - _COMM_PAGE32_START_ADDRESS);
965 		*(uint64_t *)cp = sleeptime;
966 	}
967 
968 	cp = commPagePtr64;
969 	if (cp) {
970 		cp += (_COMM_PAGE_CONT_TIMEBASE - _COMM_PAGE32_START_ADDRESS);
971 		*(uint64_t *)cp = sleeptime;
972 	}
973 }
974 
975 void
commpage_update_boottime(uint64_t boottime)976 commpage_update_boottime(uint64_t boottime)
977 {
978 	char *cp;
979 	cp = commPagePtr32;
980 	if (cp) {
981 		cp += (_COMM_PAGE_BOOTTIME_USEC - _COMM_PAGE32_START_ADDRESS);
982 		*(uint64_t *)cp = boottime;
983 	}
984 
985 	cp = commPagePtr64;
986 	if (cp) {
987 		cp += (_COMM_PAGE_BOOTTIME_USEC - _COMM_PAGE32_START_ADDRESS);
988 		*(uint64_t *)cp = boottime;
989 	}
990 }
991 
992 
993 extern user32_addr_t commpage_text32_location;
994 extern user64_addr_t commpage_text64_location;
995 
996 /* Check to see if a given address is in the Preemption Free Zone (PFZ) */
997 
998 uint32_t
commpage_is_in_pfz32(uint32_t addr32)999 commpage_is_in_pfz32(uint32_t addr32)
1000 {
1001 	if ((addr32 >= (commpage_text32_location + _COMM_TEXT_PFZ_START_OFFSET))
1002 	    && (addr32 < (commpage_text32_location + _COMM_TEXT_PFZ_END_OFFSET))) {
1003 		return 1;
1004 	} else {
1005 		return 0;
1006 	}
1007 }
1008 
1009 uint32_t
commpage_is_in_pfz64(addr64_t addr64)1010 commpage_is_in_pfz64(addr64_t addr64)
1011 {
1012 	if ((addr64 >= (commpage_text64_location + _COMM_TEXT_PFZ_START_OFFSET))
1013 	    && (addr64 < (commpage_text64_location + _COMM_TEXT_PFZ_END_OFFSET))) {
1014 		return 1;
1015 	} else {
1016 		return 0;
1017 	}
1018 }
1019