xref: /xnu-8019.80.24/osfmk/arm/pmap/pmap_data.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
1 /*
2  * Copyright (c) 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 #include <arm/cpu_data_internal.h>
29 #include <kern/queue.h>
30 #include <libkern/OSAtomic.h>
31 #include <libkern/section_keywords.h>
32 #include <pexpert/device_tree.h>
33 #include <os/atomic_private.h>
34 #include <vm/cpm.h>
35 #include <vm/vm_kern.h>
36 #include <vm/vm_protos.h>
37 #include <vm/vm_object.h>
38 #include <vm/vm_page.h>
39 #include <vm/vm_pageout.h>
40 
41 #include <arm/pmap/pmap_internal.h>
42 
43 /**
44  * Physical Page Attribute Table.
45  *
46  * Array that contains a set of flags for each kernel-managed physical VM page.
47  *
48  * @note There can be a disparity between the VM page size and the underlying
49  *       hardware page size for a specific address space. In those cases, it's
50  *       possible that multiple hardware pages will share the same set of
51  *       attributes. The VM operates on regions of memory by the VM page size
52  *       and is aware that all hardware pages within each VM page share
53  *       attributes.
54  */
55 SECURITY_READ_ONLY_LATE(volatile pp_attr_t*) pp_attr_table = (volatile pp_attr_t*)NULL;
56 
57 /**
58  * Physical to Virtual Table.
59  *
60  * Data structure that contains a list of virtual mappings for each kernel-
61  * managed physical page. Other flags and metadata are also stored in this
62  * structure on a per-physical-page basis.
63  *
64  * This structure is arranged as an array of pointers, where each pointer can
65  * point to one of three different types of data (single mapping, multiple
66  * mappings, or page table descriptor). Metadata about each page (including the
67  * type of pointer) are located in the lower and upper bits of the pointer.
68  * These bits need to be set/masked out to be able to dereference the pointer,
69  * so it's recommended to use the provided API in pmap_data.h to access the
70  * pv_head_table since it handles these details for you.
71  */
72 SECURITY_READ_ONLY_LATE(pv_entry_t * *) pv_head_table = (pv_entry_t**)NULL;
73 
74 /**
75  * Queue chain of userspace page table pages that can be quickly reclaimed by
76  * pmap_page_reclaim() in cases where the a page can't easily be allocated
77  * the normal way, but the caller needs a page quickly.
78  */
79 static queue_head_t pt_page_list MARK_AS_PMAP_DATA;
80 
81 /* Lock for pt_page_list. */
82 static MARK_AS_PMAP_DATA SIMPLE_LOCK_DECLARE(pt_pages_lock, 0);
83 
84 /* Simple linked-list structure used in various page free lists. */
85 typedef struct page_free_entry {
86 	/**
87 	 * The first word in an empty page on a free list is used as a pointer to
88 	 * the next free page in the list.
89 	 */
90 	struct page_free_entry *next;
91 } page_free_entry_t;
92 
93 /* Represents a NULL entry in various page free lists. */
94 #define PAGE_FREE_ENTRY_NULL ((page_free_entry_t *) 0)
95 
96 /**
97  * pmap_page_reclaim() is called in critical, latency-sensitive code paths when
98  * either the VM doesn't have any pages available (on non-PPL systems), or the
99  * PPL page free lists are empty (on PPL systems). Before it attempts to reclaim
100  * a userspace page table page (which will have performance penalties), it will
101  * first try allocating a page from this high-priority free list.
102  *
103  * When the pmap is starved for memory and starts relying on
104  * pmap_page_reclaim() to allocate memory, then the next page being freed will
105  * be placed onto this list for usage only by pmap_page_reclaim(). Typically
106  * that page will be a userspace page table that was just reclaimed.
107  */
108 static page_free_entry_t *pmap_page_reclaim_list MARK_AS_PMAP_DATA = PAGE_FREE_ENTRY_NULL;
109 
110 /**
111  * Current number of pending requests to reclaim a page table page. This is used
112  * as an indicator to pmap_pages_free() to place any freed pages into the high
113  * priority pmap_page_reclaim() free list so that the next invocations of
114  * pmap_page_reclaim() can use them. Typically this will be a userspace page
115  * table that was just reclaimed.
116  */
117 static unsigned int pmap_pages_request_count MARK_AS_PMAP_DATA = 0;
118 
119 /**
120  * Total number of pages that have been requested from pmap_page_reclaim() since
121  * cold boot.
122  */
123 static unsigned long long pmap_pages_request_acum MARK_AS_PMAP_DATA = 0;
124 
125 /* Lock for the pmap_page_reclaim() high-priority free list. */
126 static MARK_AS_PMAP_DATA SIMPLE_LOCK_DECLARE(pmap_page_reclaim_lock, 0);
127 
128 #if XNU_MONITOR
129 /**
130  * The PPL cannot invoke the VM in order to allocate memory, so we must maintain
131  * a list of free pages that the PPL owns. The kernel can give the PPL
132  * additional pages by grabbing pages from the VM and marking them as PPL-owned.
133  * See pmap_alloc_page_for_ppl() for more information.
134  */
135 static page_free_entry_t *pmap_ppl_free_page_list MARK_AS_PMAP_DATA = PAGE_FREE_ENTRY_NULL;
136 
137 /* The current number of pages in the PPL page free list. */
138 uint64_t pmap_ppl_free_page_count MARK_AS_PMAP_DATA = 0;
139 
140 /* Lock for the PPL page free list. */
141 static MARK_AS_PMAP_DATA SIMPLE_LOCK_DECLARE(pmap_ppl_free_page_lock, 0);
142 #endif /* XNU_MONITOR */
143 
144 /**
145  * This VM object will contain every VM page being used by the pmap. This acts
146  * as a convenient place to put pmap pages to keep the VM from reusing them, as
147  * well as providing a way for looping over every page being used by the pmap.
148  */
149 struct vm_object pmap_object_store VM_PAGE_PACKED_ALIGNED;
150 
151 /* Pointer to the pmap's VM object that can't be modified after machine_lockdown(). */
152 SECURITY_READ_ONLY_LATE(vm_object_t) pmap_object = &pmap_object_store;
153 
154 /**
155  * Global variables strictly used for debugging purposes. These variables keep
156  * track of the total number of pages that have been allocated from the VM for
157  * pmap usage since cold boot, as well as how many are currently in use by the
158  * pmap. Once a page is given back to the VM, then the inuse_pmap_pages_count
159  * will be decremented.
160  *
161  * Even if a page is sitting in one of the pmap's various free lists and hasn't
162  * been allocated for usage, these are still considered "used" by the pmap, from
163  * the perspective of the VM.
164  */
165 static uint64_t alloc_pmap_pages_count __attribute__((aligned(8))) = 0LL;
166 unsigned int inuse_pmap_pages_count = 0;
167 
168 /**
169  * Default watermark values used to keep a healthy supply of physical-to-virtual
170  * entries (PVEs) always available. These values can be overriden by the device
171  * tree (see pmap_compute_pv_targets() for more info).
172  */
173 #if XNU_MONITOR
174 /*
175  * Increase the padding for PPL devices to accommodate increased mapping
176  * pressure from IOMMUs. This isn't strictly necessary, but will reduce the need
177  * to retry mappings due to PV allocation failure.
178  */
179 #define PV_KERN_LOW_WATER_MARK_DEFAULT (0x400)
180 #define PV_ALLOC_CHUNK_INITIAL         (0x400)
181 #define PV_KERN_ALLOC_CHUNK_INITIAL    (0x400)
182 #else /* XNU_MONITOR */
183 #define PV_KERN_LOW_WATER_MARK_DEFAULT (0x200)
184 #define PV_ALLOC_CHUNK_INITIAL         (0x200)
185 #define PV_KERN_ALLOC_CHUNK_INITIAL    (0x200)
186 #endif /* XNU_MONITOR */
187 
188 /**
189  * The pv_free array acts as a ring buffer where each entry points to a linked
190  * list of PVEs that have a length set by this define.
191  */
192 #define PV_BATCH_SIZE (PAGE_SIZE / sizeof(pv_entry_t))
193 
194 /* The batch allocation code assumes that a batch can fit within a single page. */
195 #if defined(__arm__) || (defined(__arm64__) && __ARM_16K_PG__)
196 /**
197  * PAGE_SIZE is a variable on arm64 systems with 4K VM pages, so no static
198  * assert on those systems.
199  */
200 static_assert((PV_BATCH_SIZE * sizeof(pv_entry_t)) <= PAGE_SIZE);
201 #endif /* defined(__arm__) || (defined(__arm64__) && __ARM_16K_PG__) */
202 
203 /**
204  * The number of PVEs to attempt to keep in the kernel-dedicated free list. If
205  * the number of entries is below this value, then allocate more.
206  */
207 static uint32_t pv_kern_low_water_mark MARK_AS_PMAP_DATA = PV_KERN_LOW_WATER_MARK_DEFAULT;
208 
209 /**
210  * The initial number of PVEs to allocate during bootstrap (can be overriden in
211  * the device tree, see pmap_compute_pv_targets() for more info).
212  */
213 uint32_t pv_alloc_initial_target MARK_AS_PMAP_DATA = PV_ALLOC_CHUNK_INITIAL * MAX_CPUS;
214 uint32_t pv_kern_alloc_initial_target MARK_AS_PMAP_DATA = PV_KERN_ALLOC_CHUNK_INITIAL;
215 
216 /**
217  * Global variables strictly used for debugging purposes. These variables keep
218  * track of the number of pages being used for PVE objects, and the total number
219  * of PVEs that have been added to the global or kernel-dedicated free lists
220  * respectively.
221  */
222 static uint32_t pv_page_count MARK_AS_PMAP_DATA = 0;
223 static unsigned pmap_reserve_replenish_stat MARK_AS_PMAP_DATA = 0;
224 static unsigned pmap_kern_reserve_alloc_stat MARK_AS_PMAP_DATA = 0;
225 
226 /**
227  * Number of linked lists of PVEs ("batches") in the global PV free ring buffer.
228  * This must be a power of two for the pv_free_array_n_elems() logic to work.
229  */
230 #define PV_FREE_ARRAY_SIZE (256U)
231 
232 /**
233  * A ring buffer where each entry in the buffer is a linked list of PV entries
234  * (called "batches"). Allocations out of this array will always operate on
235  * a PV_BATCH_SIZE amount of entries at a time.
236  */
237 static pv_free_list_t pv_free_ring[PV_FREE_ARRAY_SIZE] MARK_AS_PMAP_DATA = {0};
238 
239 /* Read and write indices for the pv_free ring buffer. */
240 static uint16_t pv_free_read_idx MARK_AS_PMAP_DATA = 0;
241 static uint16_t pv_free_write_idx MARK_AS_PMAP_DATA = 0;
242 
243 /**
244  * Make sure the PV free array is small enough so that all elements can be
245  * properly indexed by pv_free_[read/write]_idx.
246  */
247 static_assert(PV_FREE_ARRAY_SIZE <= (1 << (sizeof(pv_free_read_idx) * 8)));
248 
249 /**
250  * Return the number of free batches available for allocation out of the PV free
251  * ring buffer. Each batch is a linked list of PVEs with length PV_BATCH_SIZE.
252  *
253  * @note This function requires that PV_FREE_ARRAY_SIZE is a power of two.
254  */
255 static inline uint16_t
pv_free_array_n_elems(void)256 pv_free_array_n_elems(void)
257 {
258 	return (pv_free_write_idx - pv_free_read_idx) & (PV_FREE_ARRAY_SIZE - 1);
259 }
260 
261 /* Free list of PV entries dedicated for usage by the kernel. */
262 static pv_free_list_t pv_kern_free MARK_AS_PMAP_DATA = {0};
263 
264 /* Locks for the global and kernel-dedicated PV free lists. */
265 static MARK_AS_PMAP_DATA SIMPLE_LOCK_DECLARE(pv_free_array_lock, 0);
266 static MARK_AS_PMAP_DATA SIMPLE_LOCK_DECLARE(pv_kern_free_list_lock, 0);
267 
268 /* Represents a null page table descriptor (PTD). */
269 #define PTD_ENTRY_NULL ((pt_desc_t *) 0)
270 
271 /* Running free list of PTD nodes. */
272 static pt_desc_t *ptd_free_list MARK_AS_PMAP_DATA = PTD_ENTRY_NULL;
273 
274 /* The number of free PTD nodes available in the free list. */
275 static unsigned int ptd_free_count MARK_AS_PMAP_DATA = 0;
276 
277 /**
278  * The number of PTD objects located in each page being used by the PTD
279  * allocator. The PTD objects share each page with their associated ptd_info_t
280  * objects (with cache-line alignment padding between them). The maximum number
281  * of PTDs that can be placed into a single page is calculated once at boot.
282  */
283 static SECURITY_READ_ONLY_LATE(unsigned) ptd_per_page = 0;
284 
285 /**
286  * The offset in bytes from the beginning of a page of PTD objects where you
287  * start seeing the associated ptd_info_t objects. This is calculated once
288  * during boot to maximize the number of PTD and ptd_info_t objects that can
289  * reside within a page without sharing a cache-line.
290  */
291 static SECURITY_READ_ONLY_LATE(unsigned) ptd_info_offset = 0;
292 
293 /* Lock to protect accesses to the PTD free list. */
294 static decl_simple_lock_data(, ptd_free_list_lock MARK_AS_PMAP_DATA);
295 
296 /**
297  * Dummy _internal() prototypes so Clang doesn't complain about missing
298  * prototypes on a non-static function. These functions can't be marked as
299  * static because they need to be called from pmap_ppl_interface.c where the
300  * PMAP_SUPPORT_PROTOYPES() macro will auto-generate the prototype implicitly.
301  */
302 kern_return_t mapping_free_prime_internal(void);
303 
304 #if XNU_MONITOR
305 
306 /**
307  * These types and variables only exist on PPL-enabled systems because those are
308  * the only systems that need to allocate and manage ledger/pmap objects
309  * themselves. On non-PPL systems, those objects are allocated using a standard
310  * zone allocator.
311  */
312 
313 /**
314  * Specify that the maximum number of ledgers and pmap objects are to be
315  * correlated to the maximum number of tasks allowed on the system (at most,
316  * we'll have one pmap object per task). For ledger objects, give a small amount
317  * of extra padding to account for allocation differences between pmap objects
318  * and ledgers (i.e. ~10% of total number of iOS tasks = 200).
319  *
320  * These defines are only valid once `pmap_max_asids` is initialized in
321  * pmap_bootstrap() (the value can change depending on the device tree).
322  */
323 #define LEDGER_PTR_ARRAY_SIZE (pmap_max_asids + 200)
324 #define PMAP_PTR_ARRAY_SIZE (pmap_max_asids)
325 
326 /**
327  * Each ledger object consists of a variable number of ledger entries that is
328  * determined by the template it's based on. The template used for pmap ledger
329  * objects is the task_ledgers template.
330  *
331  * This define attempts to calculate how large each pmap ledger needs to be
332  * based on how many ledger entries exist in the task_ledgers template. This is
333  * found by counting how many integers exist in the task_ledgers structure (each
334  * integer represents the index for a ledger_entry) and multiplying by the size
335  * of a single ledger entry. That value is then added to the other fields in a
336  * ledger structure to get the total size of a single pmap ledger.
337  *
338  * Some of the task ledger's entries use a smaller struct format. TASK_LEDGER_NUM_SMALL_INDICES
339  * is used to determine how much memory we need for those entries.
340  *
341  * This assumed size will get validated when the task_ledgers template is
342  * created and the system will panic if this calculation wasn't correct.
343  *
344  */
345 #define PMAP_LEDGER_DATA_BYTES \
346 	(((sizeof(task_ledgers) / sizeof(int) - TASK_LEDGER_NUM_SMALL_INDICES) * sizeof(struct ledger_entry) \
347 	  + TASK_LEDGER_NUM_SMALL_INDICES * sizeof(struct ledger_entry_small)) \
348 	  + sizeof(struct ledger))
349 
350 /**
351  * Opaque data structure that contains the exact number of bytes required to
352  * hold a single ledger object based off of the task_ledgers template.
353  */
354 typedef struct pmap_ledger_data {
355 	uint8_t pld_data[PMAP_LEDGER_DATA_BYTES];
356 } pmap_ledger_data_t;
357 
358 /**
359  * This struct contains the memory needed to hold a single ledger object used by
360  * the pmap as well as an index into the pmap_ledger_ptr_array used for
361  * validating ledger objects passed into the PPL.
362  */
363 typedef struct pmap_ledger {
364 	/**
365 	 * Either contain the memory needed for a ledger object based on the
366 	 * task_ledgers template (if already allocated) or a pointer to the next
367 	 * ledger object in the free list if the object hasn't been allocated yet.
368 	 *
369 	 * This union has to be the first member of this struct so that the memory
370 	 * used by this struct can be correctly cast to a ledger_t and used
371 	 * as a normal ledger object by the standard ledger API.
372 	 */
373 	union {
374 		struct pmap_ledger_data pld_data;
375 		struct pmap_ledger *next;
376 	};
377 
378 	/**
379 	 * This extra piece of information (not normally associated with generic
380 	 * ledger_t objects) is used to validate that a ledger passed into the PPL
381 	 * is indeed a ledger that was allocated by the PPL, and not just random
382 	 * memory being passed off as a ledger object. See pmap_ledger_validate()
383 	 * for more information on validating ledger objects.
384 	 */
385 	unsigned long array_index;
386 } pmap_ledger_t;
387 
388 /**
389  * This variable is used to ensure that the size of the ledger objects being
390  * allocated by the PPL match up with the actual size of the ledger objects
391  * before objects start being allocated.
392  */
393 static SECURITY_READ_ONLY_LATE(bool) pmap_ledger_size_verified = false;
394 
395 /* Ledger free list lock. */
396 static MARK_AS_PMAP_DATA SIMPLE_LOCK_DECLARE(pmap_ledger_lock, 0);
397 
398 /*
399  * The pmap_ledger_t contents are allowed to be written outside the PPL,
400  * so refcounts must be in a separate PPL-controlled array.
401  */
402 static SECURITY_READ_ONLY_LATE(os_refcnt_t *) pmap_ledger_refcnt = NULL;
403 
404 /**
405  * The number of entries in the pmap ledger pointer and ledger refcnt arrays.
406  * This determines the maximum number of pmap ledger objects that can be
407  * allocated.
408  *
409  * This value might be slightly higher than LEDGER_PTR_ARRAY_SIZE because the
410  * memory used for the array is rounded up to the nearest page boundary.
411  */
412 static SECURITY_READ_ONLY_LATE(unsigned long) pmap_ledger_ptr_array_count = 0;
413 
414 /**
415  * This array is used to validate that ledger objects passed into the PPL were
416  * allocated by the PPL and aren't just random memory being passed off as a
417  * ledger object. It does this by associating each ledger object allocated by
418  * the PPL with an index into this array. The value at that index will be a
419  * pointer to the ledger object itself.
420  *
421  * Even though the ledger object is kernel-writable, this array is only
422  * modifiable by the PPL. If a ledger object is passed into the PPL that has an
423  * index into this array that doesn't match up, then the validation will fail.
424  */
425 static SECURITY_READ_ONLY_LATE(pmap_ledger_t * *) pmap_ledger_ptr_array = NULL;
426 
427 /**
428  * The next free index into pmap_ledger_ptr_array to be given to the next
429  * allocated ledger object.
430  */
431 static uint64_t pmap_ledger_ptr_array_free_index MARK_AS_PMAP_DATA = 0;
432 
433 /* Free list of pmap ledger objects. */
434 static pmap_ledger_t *pmap_ledger_free_list MARK_AS_PMAP_DATA = NULL;
435 
436 /**
437  * This struct contains the memory needed to hold a single pmap object as well
438  * as an index into the pmap_ptr_array used for validating pmap objects passed
439  * into the PPL.
440  */
441 typedef struct pmap_list_entry {
442 	/**
443 	 * Either contain the memory needed for a single pmap object or a pointer to
444 	 * the next pmap object in the free list if the object hasn't been allocated
445 	 * yet.
446 	 *
447 	 * This union has to be the first member of this struct so that the memory
448 	 * used by this struct can be correctly cast as either a pmap_list_entry_t
449 	 * or a pmap_t (depending on whether the array_index is needed).
450 	 */
451 	union {
452 		struct pmap pmap;
453 		struct pmap_list_entry *next;
454 	};
455 
456 	/**
457 	 * This extra piece of information (not normally associated with generic
458 	 * pmap objects) is used to validate that a pmap object passed into the PPL
459 	 * is indeed a pmap object that was allocated by the PPL, and not just random
460 	 * memory being passed off as a pmap object. See validate_pmap()
461 	 * for more information on validating pmap objects.
462 	 */
463 	unsigned long array_index;
464 } pmap_list_entry_t;
465 
466 /* Lock for the pmap free list. */
467 static MARK_AS_PMAP_DATA SIMPLE_LOCK_DECLARE(pmap_free_list_lock, 0);
468 
469 /**
470  * The number of entries in the pmap pointer array. This determines the maximum
471  * number of pmap objects that can be allocated.
472  *
473  * This value might be slightly higher than PMAP_PTR_ARRAY_SIZE because the
474  * memory used for the array is rounded up to the nearest page boundary.
475  */
476 static SECURITY_READ_ONLY_LATE(unsigned long) pmap_ptr_array_count = 0;
477 
478 /**
479  * This array is used to validate that pmap objects passed into the PPL were
480  * allocated by the PPL and aren't just random memory being passed off as a pmap
481  * object. It does this by associating each pmap object allocated by the PPL
482  * with an index into this array. The value at that index will be a pointer to
483  * the pmap object itself.
484  *
485  * If a pmap object is passed into the PPL that has an index into this array
486  * that doesn't match up, then the validation will fail.
487  */
488 static SECURITY_READ_ONLY_LATE(pmap_list_entry_t * *) pmap_ptr_array = NULL;
489 
490 /**
491  * The next free index into pmap_ptr_array to be given to the next
492  * allocated pmap object.
493  */
494 static unsigned long pmap_ptr_array_free_index MARK_AS_PMAP_DATA = 0;
495 
496 /* Free list of pmap objects. */
497 static pmap_list_entry_t *pmap_free_list MARK_AS_PMAP_DATA = NULL;
498 
499 #endif /* XNU_MONITOR */
500 
501 /**
502  * Sorted representation of the pmap-io-ranges nodes in the device tree. These
503  * nodes describe all of the PPL-owned I/O ranges.
504  */
505 SECURITY_READ_ONLY_LATE(pmap_io_range_t*) io_attr_table = (pmap_io_range_t*)0;
506 
507 /* The number of ranges described by io_attr_table. */
508 SECURITY_READ_ONLY_LATE(unsigned int) num_io_rgns = 0;
509 
510 #if XNU_MONITOR
511 
512 /**
513  * Per-cpu pmap data. On PPL-enabled systems, this memory is only modifiable by
514  * the PPL itself and because of that, needs to be managed separately from the
515  * generic per-cpu data. The per-cpu pmap data exists on non-PPL systems as
516  * well, it's just located within the general machine-specific per-cpu data.
517  */
518 struct pmap_cpu_data_array_entry pmap_cpu_data_array[MAX_CPUS] MARK_AS_PMAP_DATA;
519 
520 /**
521  * The physical address spaces being used for the PPL stacks and PPL register
522  * save area are stored in global variables so that their permissions can be
523  * updated in pmap_static_allocations_done(). These regions are initialized by
524  * pmap_cpu_data_array_init().
525  */
526 SECURITY_READ_ONLY_LATE(pmap_paddr_t) pmap_stacks_start_pa = 0;
527 SECURITY_READ_ONLY_LATE(pmap_paddr_t) pmap_stacks_end_pa = 0;
528 SECURITY_READ_ONLY_LATE(pmap_paddr_t) ppl_cpu_save_area_start = 0;
529 SECURITY_READ_ONLY_LATE(pmap_paddr_t) ppl_cpu_save_area_end = 0;
530 
531 #endif /* XNU_MONITOR */
532 
533 /* Prototypes used by pmap_data_bootstrap(). */
534 vm_size_t pmap_compute_io_rgns(void);
535 void pmap_load_io_rgns(void);
536 void pmap_cpu_data_array_init(void);
537 
538 /**
539  * This function is called once during pmap_bootstrap() to allocate and
540  * initialize many of the core data structures that are implemented in this
541  * file.
542  *
543  * Memory for these data structures is carved out of `avail_start` which is a
544  * global setup by arm_vm_init() that points to a physically contiguous region
545  * used for bootstrap allocations.
546  *
547  * @note There is no guaranteed alignment of `avail_start` when this function
548  *       returns. If avail_start needs to be aligned to a specific value then it
549  *       must be done so by the caller before they use it for more allocations.
550  */
551 void
pmap_data_bootstrap(void)552 pmap_data_bootstrap(void)
553 {
554 	/**
555 	 * Set ptd_per_page to the maximum number of (pt_desc_t + ptd_info_t) we can
556 	 * fit in a single page. We need to allow for some padding between the two,
557 	 * so that no ptd_info_t shares a cache line with a pt_desc_t.
558 	 */
559 	const unsigned ptd_info_size = sizeof(ptd_info_t) * PT_INDEX_MAX;
560 	const unsigned l2_cline_bytes = 1 << MAX_L2_CLINE;
561 	ptd_per_page = (PAGE_SIZE - (l2_cline_bytes - 1)) / (sizeof(pt_desc_t) + ptd_info_size);
562 	unsigned increment = 0;
563 	bool try_next = true;
564 
565 	/**
566 	 * The current ptd_per_page calculation was done assuming the worst-case
567 	 * scenario in terms of padding between the two object arrays that reside in
568 	 * the same page. The following loop attempts to optimize this further by
569 	 * finding the smallest possible amount of padding while still ensuring that
570 	 * the two object arrays don't share a cache line.
571 	 */
572 	while (try_next) {
573 		increment++;
574 		const unsigned pt_desc_total_size =
575 		    PMAP_ALIGN((ptd_per_page + increment) * sizeof(pt_desc_t), l2_cline_bytes);
576 		const unsigned ptd_info_total_size = (ptd_per_page + increment) * ptd_info_size;
577 		try_next = (pt_desc_total_size + ptd_info_total_size) <= PAGE_SIZE;
578 	}
579 	ptd_per_page += increment - 1;
580 	assert(ptd_per_page > 0);
581 
582 	/**
583 	 * ptd_info objects reside after the ptd descriptor objects, with some
584 	 * padding in between if necessary to ensure that they don't co-exist in the
585 	 * same cache line.
586 	 */
587 	const unsigned pt_desc_bytes = ptd_per_page * sizeof(pt_desc_t);
588 	ptd_info_offset = PMAP_ALIGN(pt_desc_bytes, l2_cline_bytes);
589 
590 	/* The maximum amount of padding should be (l2_cline_bytes - 1). */
591 	assert((ptd_info_offset - pt_desc_bytes) < l2_cline_bytes);
592 
593 	/**
594 	 * Allocate enough initial PTDs to map twice the available physical memory.
595 	 *
596 	 * To do this, start by calculating the number of leaf page tables that are
597 	 * needed to cover all of kernel-managed physical memory.
598 	 */
599 	const uint32_t num_leaf_page_tables =
600 	    (uint32_t)(mem_size / ((PAGE_SIZE / sizeof(pt_entry_t)) * ARM_PGBYTES));
601 
602 	/**
603 	 * There should be one PTD per page table (times 2 since we want twice the
604 	 * number of required PTDs), plus round the number of PTDs up to the next
605 	 * `ptd_per_page` value so there's no wasted space.
606 	 */
607 	const uint32_t ptd_root_table_n_ptds =
608 	    (ptd_per_page * ((num_leaf_page_tables * 2) / ptd_per_page)) + ptd_per_page;
609 
610 	/* Lastly, calculate the number of VM pages and bytes these PTDs take up. */
611 	const uint32_t num_ptd_pages = ptd_root_table_n_ptds / ptd_per_page;
612 	vm_size_t ptd_root_table_size = num_ptd_pages * PAGE_SIZE;
613 
614 	/* Number of VM pages that span all of kernel-managed memory. */
615 	const unsigned int npages = (unsigned int)atop(mem_size);
616 
617 	/* The pv_head_table and pp_attr_table both have one entry per VM page. */
618 	const vm_size_t pp_attr_table_size = npages * sizeof(pp_attr_t);
619 	const vm_size_t pv_head_size = round_page(npages * sizeof(pv_entry_t *));
620 
621 	/* Scan the device tree and override heuristics in the PV entry management code. */
622 	pmap_compute_pv_targets();
623 
624 	/* Scan the device tree and figure out how many PPL-owned I/O regions there are. */
625 	const vm_size_t io_attr_table_size = pmap_compute_io_rgns();
626 
627 	/**
628 	 * Don't make any assumptions about the alignment of avail_start before
629 	 * execution of this function. Always re-align it to ensure the first
630 	 * allocated data structure is aligned correctly.
631 	 */
632 	avail_start = PMAP_ALIGN(avail_start, __alignof(pp_attr_t));
633 
634 	/**
635 	 * Keep track of where the data structures start so we can clear this memory
636 	 * later.
637 	 */
638 	const pmap_paddr_t pmap_struct_start = avail_start;
639 
640 	pp_attr_table = (pp_attr_t *)phystokv(avail_start);
641 	avail_start = PMAP_ALIGN(avail_start + pp_attr_table_size, __alignof(pmap_io_range_t));
642 
643 	io_attr_table = (pmap_io_range_t *)phystokv(avail_start);
644 	avail_start = PMAP_ALIGN(avail_start + io_attr_table_size, __alignof(pv_entry_t *));
645 
646 	pv_head_table = (pv_entry_t **)phystokv(avail_start);
647 
648 	/**
649 	 * ptd_root_table must start on a page boundary because all of the math for
650 	 * associating pt_desc_t objects with ptd_info objects assumes the first
651 	 * pt_desc_t in a page starts at the beginning of the page it resides in.
652 	 */
653 	avail_start = round_page(avail_start + pv_head_size);
654 
655 	pt_desc_t *ptd_root_table = (pt_desc_t *)phystokv(avail_start);
656 	avail_start = round_page(avail_start + ptd_root_table_size);
657 
658 	memset((char *)phystokv(pmap_struct_start), 0, avail_start - pmap_struct_start);
659 
660 	/* This function assumes that ptd_root_table has been zeroed out already. */
661 	ptd_bootstrap(ptd_root_table, num_ptd_pages);
662 
663 	/* Load data about the PPL-owned I/O regions into io_attr_table and sort it. */
664 	pmap_load_io_rgns();
665 
666 #if XNU_MONITOR
667 	/**
668 	 * Each of these PPL-only data structures are rounded to the nearest page
669 	 * beyond their predefined size so as to provide a small extra buffer of
670 	 * objects and to make it easy to perform page-sized operations on them if
671 	 * the need ever arises.
672 	 */
673 	const vm_map_address_t pmap_ptr_array_begin = phystokv(avail_start);
674 	pmap_ptr_array = (pmap_list_entry_t**)pmap_ptr_array_begin;
675 	avail_start += round_page(PMAP_PTR_ARRAY_SIZE * sizeof(*pmap_ptr_array));
676 	const vm_map_address_t pmap_ptr_array_end = phystokv(avail_start);
677 
678 	pmap_ptr_array_count = ((pmap_ptr_array_end - pmap_ptr_array_begin) / sizeof(*pmap_ptr_array));
679 
680 	const vm_map_address_t pmap_ledger_ptr_array_begin = phystokv(avail_start);
681 	pmap_ledger_ptr_array = (pmap_ledger_t**)pmap_ledger_ptr_array_begin;
682 	avail_start += round_page(LEDGER_PTR_ARRAY_SIZE * sizeof(*pmap_ledger_ptr_array));
683 	const vm_map_address_t pmap_ledger_ptr_array_end = phystokv(avail_start);
684 	pmap_ledger_ptr_array_count = ((pmap_ledger_ptr_array_end - pmap_ledger_ptr_array_begin) / sizeof(*pmap_ledger_ptr_array));
685 
686 	pmap_ledger_refcnt = (os_refcnt_t*)phystokv(avail_start);
687 	avail_start += round_page(pmap_ledger_ptr_array_count * sizeof(*pmap_ledger_refcnt));
688 #endif /* XNU_MONITOR */
689 
690 	/**
691 	 * Setup the pmap per-cpu data structures (includes the PPL stacks, and PPL
692 	 * register save area). The pmap per-cpu data is managed separately from the
693 	 * general machine-specific per-cpu data on PPL systems so it can be made
694 	 * only writable by the PPL.
695 	 */
696 	pmap_cpu_data_array_init();
697 }
698 
699 /**
700  * Helper function for pmap_page_reclaim (hereby shortened to "ppr") which scans
701  * the list of userspace page table pages for one(s) that can be reclaimed. To
702  * be eligible, a page table must not have any wired PTEs, must contain at least
703  * one valid PTE, can't be nested, and the pmap that owns that page table must
704  * not already be locked.
705  *
706  * @note This should only be called from pmap_page_reclaim().
707  *
708  * @note If an eligible page table was found, then the pmap which contains that
709  *       page table will be locked exclusively.
710  *
711  * @note On systems where multiple page tables exist within one page, all page
712  *       tables within a page have to be eligible for that page to be considered
713  *       reclaimable.
714  *
715  * @param ptdpp Output parameter which will contain a pointer to the page table
716  *              descriptor for the page table(s) that can be reclaimed (if any
717  *              were found). If no page table was found, this will be set to
718  *              NULL.
719  *
720  * @return True if an eligible table was found, false otherwise. In the case
721  *         that a page table was found, ptdpp will be a pointer to the page
722  *         table descriptor for the table(s) that can be reclaimed. Otherwise
723  *         it'll be set to NULL.
724  */
725 MARK_AS_PMAP_TEXT static bool
ppr_find_eligible_pt_page(pt_desc_t ** ptdpp)726 ppr_find_eligible_pt_page(pt_desc_t **ptdpp)
727 {
728 	assert(ptdpp != NULL);
729 
730 	pmap_simple_lock(&pt_pages_lock);
731 	pt_desc_t *ptdp = (pt_desc_t *)queue_first(&pt_page_list);
732 
733 	while (!queue_end(&pt_page_list, (queue_entry_t)ptdp)) {
734 		/* Skip this pmap if it's nested or already locked. */
735 		if ((ptdp->pmap->type != PMAP_TYPE_USER) ||
736 		    (!pmap_try_lock(ptdp->pmap, PMAP_LOCK_EXCLUSIVE))) {
737 			ptdp = (pt_desc_t *)queue_next((queue_t)ptdp);
738 			continue;
739 		}
740 
741 		assert(ptdp->pmap != kernel_pmap);
742 
743 		unsigned refcnt_acc = 0;
744 		unsigned wiredcnt_acc = 0;
745 		const pt_attr_t * const pt_attr = pmap_get_pt_attr(ptdp->pmap);
746 
747 		/**
748 		 * On systems where the VM page size differs from the hardware
749 		 * page size, then multiple page tables can exist within one VM page.
750 		 */
751 		for (unsigned i = 0; i < (PAGE_SIZE / pt_attr_page_size(pt_attr)); i++) {
752 			/* Do not attempt to free a page that contains an L2 table. */
753 			if (ptdp->ptd_info[i].refcnt == PT_DESC_REFCOUNT) {
754 				refcnt_acc = 0;
755 				break;
756 			}
757 
758 			refcnt_acc += ptdp->ptd_info[i].refcnt;
759 			wiredcnt_acc += ptdp->ptd_info[i].wiredcnt;
760 		}
761 
762 		/**
763 		 * If we've found a page with no wired entries, but valid PTEs then
764 		 * choose it for reclamation.
765 		 */
766 		if ((wiredcnt_acc == 0) && (refcnt_acc != 0)) {
767 			*ptdpp = ptdp;
768 			pmap_simple_unlock(&pt_pages_lock);
769 
770 			/**
771 			 * Leave ptdp->pmap locked here. We're about to reclaim a page table
772 			 * from it, so we don't want anyone else messing with it while we do
773 			 * that.
774 			 */
775 			return true;
776 		}
777 
778 		/**
779 		 * This page table/PTD wasn't eligible, unlock its pmap and move to the
780 		 * next one in the queue.
781 		 */
782 		pmap_unlock(ptdp->pmap, PMAP_LOCK_EXCLUSIVE);
783 		ptdp = (pt_desc_t *)queue_next((queue_t)ptdp);
784 	}
785 
786 	pmap_simple_unlock(&pt_pages_lock);
787 	*ptdpp = NULL;
788 
789 	return false;
790 }
791 
792 /**
793  * Helper function for pmap_page_reclaim (hereby shortened to "ppr") which frees
794  * every page table within a page so that that page can get reclaimed.
795  *
796  * @note This should only be called from pmap_page_reclaim() and is only meant
797  *       to delete page tables deemed eligible for reclaiming by
798  *       ppr_find_eligible_pt_page().
799  *
800  * @param ptdp The page table descriptor whose page table(s) will get freed.
801  */
802 MARK_AS_PMAP_TEXT static void
ppr_remove_pt_page(pt_desc_t * ptdp)803 ppr_remove_pt_page(pt_desc_t *ptdp)
804 {
805 	assert(ptdp != NULL);
806 
807 	bool need_strong_sync = false;
808 	tt_entry_t *ttep = TT_ENTRY_NULL;
809 	pt_entry_t *ptep = PT_ENTRY_NULL;
810 	pt_entry_t *begin_pte = PT_ENTRY_NULL;
811 	pt_entry_t *end_pte = PT_ENTRY_NULL;
812 	pmap_t pmap = ptdp->pmap;
813 
814 	/**
815 	 * The pmap exclusive lock should have gotten locked when the eligible page
816 	 * table was found in ppr_find_eligible_pt_page().
817 	 */
818 	pmap_assert_locked(pmap, PMAP_LOCK_EXCLUSIVE);
819 
820 	const pt_attr_t * const pt_attr = pmap_get_pt_attr(pmap);
821 	const uint64_t hw_page_size = pt_attr_page_size(pt_attr);
822 
823 	/**
824 	 * On some systems, one page table descriptor can represent multiple page
825 	 * tables. In that case, remove every table within the wanted page so we
826 	 * can reclaim it.
827 	 */
828 	for (unsigned i = 0; i < (PAGE_SIZE / hw_page_size); i++) {
829 		const vm_map_address_t va = ptdp->va[i];
830 
831 		/**
832 		 * If the VA is bogus, this may represent an unallocated region or one
833 		 * which is in transition (already being freed or expanded). Don't try
834 		 * to remove mappings here.
835 		 */
836 		if (va == (vm_offset_t)-1) {
837 			continue;
838 		}
839 
840 		/* Get the twig table entry that points to the table to reclaim. */
841 		ttep = pmap_tte(pmap, va);
842 
843 		/* If the twig entry is either invalid or a block mapping, skip it. */
844 		if ((ttep == TT_ENTRY_NULL) ||
845 		    ((*ttep & ARM_TTE_TYPE_MASK) != ARM_TTE_TYPE_TABLE)) {
846 			continue;
847 		}
848 
849 		ptep = (pt_entry_t *)ttetokv(*ttep);
850 		begin_pte = &ptep[pte_index(pt_attr, va)];
851 		end_pte = begin_pte + (hw_page_size / sizeof(pt_entry_t));
852 
853 		/**
854 		 * Remove all mappings in the page table being reclaimed.
855 		 *
856 		 * Use PMAP_OPTIONS_REMOVE to clear any "compressed" markers and
857 		 * update the "compressed" counter in the ledger. This means that
858 		 * we lose accounting for any compressed pages in this range but the
859 		 * alternative is to not be able to account for their future
860 		 * decompression, which could cause the counter to drift more and
861 		 * more.
862 		 */
863 		pmap_remove_range_options(
864 			pmap, va, begin_pte, end_pte, NULL, &need_strong_sync, PMAP_OPTIONS_REMOVE);
865 
866 		/**
867 		 * Free the page table now that all of its mappings have been removed.
868 		 * Once all page tables within a page have been deallocated, then the
869 		 * page that contains the table(s) will be freed and made available for
870 		 * reuse.
871 		 */
872 		const vm_offset_t va_end = va + (size_t)pt_attr_leaf_table_size(pt_attr);
873 		pmap_tte_deallocate(pmap, va, va_end, need_strong_sync, ttep, pt_attr_twig_level(pt_attr));
874 	}
875 
876 	/**
877 	 * We're done modifying page tables, so undo the lock that was grabbed when
878 	 * we found the table(s) to reclaim in ppr_find_eligible_pt_page().
879 	 */
880 	pmap_unlock(pmap, PMAP_LOCK_EXCLUSIVE);
881 }
882 
883 /**
884  * Attempt to return a page by freeing an active page-table page. To be eligible
885  * for reclaiming, a page-table page must be assigned to a non-kernel pmap, it
886  * must not have any wired PTEs and must contain at least one valid PTE.
887  *
888  * @note This function is potentially invoked when PMAP_PAGE_RECLAIM_NOWAIT is
889  *       passed as an option to pmap_pages_alloc_zeroed().
890  *
891  * @note Invocations of this function are only meant to occur in critical paths
892  *       that absolutely can't take the latency hit of waiting for the VM or
893  *       jumping out of the PPL to allocate more pages. Reclaiming a page table
894  *       page can cause a performance hit when one of the removed mappings is
895  *       next accessed (forcing the VM to fault and re-insert the mapping).
896  *
897  * @return The physical address of the page that was allocated, or zero if no
898  *         suitable page was found on the page-table list.
899  */
900 MARK_AS_PMAP_TEXT static pmap_paddr_t
pmap_page_reclaim(void)901 pmap_page_reclaim(void)
902 {
903 	pmap_simple_lock(&pmap_page_reclaim_lock);
904 	pmap_pages_request_count++;
905 	pmap_pages_request_acum++;
906 
907 	/* This loop will never break out, the function will just return. */
908 	while (1) {
909 		/**
910 		 * Attempt to allocate a page from the page free list reserved for this
911 		 * function. This free list is managed in tandem with pmap_pages_free()
912 		 * which will add a page to this list for each call to
913 		 * pmap_page_reclaim(). Most likely that page will come from a reclaimed
914 		 * userspace page table, but if there aren't any page tables to reclaim,
915 		 * then whatever the next freed page is will show up on this list for
916 		 * the next invocation of pmap_page_reclaim() to use.
917 		 */
918 		if (pmap_page_reclaim_list != PAGE_FREE_ENTRY_NULL) {
919 			page_free_entry_t *page_entry = pmap_page_reclaim_list;
920 			pmap_page_reclaim_list = pmap_page_reclaim_list->next;
921 			pmap_simple_unlock(&pmap_page_reclaim_lock);
922 
923 			return ml_static_vtop((vm_offset_t)page_entry);
924 		}
925 
926 		/* Drop the lock to allow pmap_pages_free() to add pages to the list. */
927 		pmap_simple_unlock(&pmap_page_reclaim_lock);
928 
929 		/* Attempt to find an elegible page table page to reclaim. */
930 		pt_desc_t *ptdp = NULL;
931 		bool found_page = ppr_find_eligible_pt_page(&ptdp);
932 
933 		if (!found_page) {
934 			/**
935 			 * No eligible page table was found. pmap_pages_free() will still
936 			 * add the next freed page to the reclaim free list, so the next
937 			 * invocation of this function should have better luck.
938 			 */
939 			return (pmap_paddr_t)0;
940 		}
941 
942 		/**
943 		 * If we found a page table to reclaim, then ptdp should point to the
944 		 * descriptor for that table. Go ahead and remove it.
945 		 */
946 		ppr_remove_pt_page(ptdp);
947 
948 		/**
949 		 * Now that a page has hopefully been freed (and added to the reclaim
950 		 * page list), the next iteration of the loop will re-check the reclaim
951 		 * free list.
952 		 */
953 		pmap_simple_lock(&pmap_page_reclaim_lock);
954 	}
955 }
956 
957 #if XNU_MONITOR
958 /**
959  * Helper function for returning a PPL page back to the PPL page free list.
960  *
961  * @param pa Physical address of the page to add to the PPL page free list.
962  *           This address must be aligned to the VM page size.
963  */
964 MARK_AS_PMAP_TEXT static void
pmap_give_free_ppl_page(pmap_paddr_t pa)965 pmap_give_free_ppl_page(pmap_paddr_t pa)
966 {
967 	assert((pa & PAGE_MASK) == 0);
968 
969 	page_free_entry_t *page_entry = (page_free_entry_t *)phystokv(pa);
970 	pmap_simple_lock(&pmap_ppl_free_page_lock);
971 
972 	/* Prepend the passed in page to the PPL page free list. */
973 	page_entry->next = pmap_ppl_free_page_list;
974 	pmap_ppl_free_page_list = page_entry;
975 	pmap_ppl_free_page_count++;
976 
977 	pmap_simple_unlock(&pmap_ppl_free_page_lock);
978 }
979 
980 /**
981  * Helper function for getting a PPL page from the PPL page free list.
982  *
983  * @return The physical address of the page taken from the PPL page free list,
984  *         or zero if there are no pages left in the free list.
985  */
986 MARK_AS_PMAP_TEXT static pmap_paddr_t
pmap_get_free_ppl_page(void)987 pmap_get_free_ppl_page(void)
988 {
989 	pmap_paddr_t pa = 0;
990 
991 	pmap_simple_lock(&pmap_ppl_free_page_lock);
992 
993 	if (pmap_ppl_free_page_list != PAGE_FREE_ENTRY_NULL) {
994 		/**
995 		 * Pop a page off the front of the list. The second item in the list
996 		 * will become the new head.
997 		 */
998 		page_free_entry_t *page_entry = pmap_ppl_free_page_list;
999 		pmap_ppl_free_page_list = pmap_ppl_free_page_list->next;
1000 		pa = kvtophys_nofail((vm_offset_t)page_entry);
1001 		pmap_ppl_free_page_count--;
1002 	} else {
1003 		pa = 0L;
1004 	}
1005 
1006 	pmap_simple_unlock(&pmap_ppl_free_page_lock);
1007 	assert((pa & PAGE_MASK) == 0);
1008 
1009 	return pa;
1010 }
1011 
1012 /**
1013  * Claim a page on behalf of the PPL by marking it as PPL-owned and only
1014  * allowing the PPL to write to it. Also can potentially add the page to the
1015  * PPL page free list (see initially_free parameter).
1016  *
1017  * @note The page cannot have any mappings outside of the physical aperture.
1018  *
1019  * @param pa The physical address of the page to mark as PPL-owned.
1020  * @param initially_free Should the page be added to the PPL page free list.
1021  *                       This is typically "true" if a brand new page was just
1022  *                       allocated for the PPL's usage, and "false" if this is a
1023  *                       page already being used by other agents (e.g., IOMMUs).
1024  */
1025 MARK_AS_PMAP_TEXT void
pmap_mark_page_as_ppl_page_internal(pmap_paddr_t pa,bool initially_free)1026 pmap_mark_page_as_ppl_page_internal(pmap_paddr_t pa, bool initially_free)
1027 {
1028 	pp_attr_t attr = 0;
1029 
1030 	if (!pa_valid(pa)) {
1031 		panic("%s: Non-kernel-managed (maybe I/O) address passed in, pa=0x%llx",
1032 		    __func__, pa);
1033 	}
1034 
1035 	const unsigned int pai = pa_index(pa);
1036 	pvh_lock(pai);
1037 
1038 	/* A page that the PPL already owns can't be given to the PPL. */
1039 	if (ppattr_pa_test_monitor(pa)) {
1040 		panic("%s: page already belongs to PPL, pa=0x%llx", __func__, pa);
1041 	}
1042 
1043 	/* The page cannot be mapped outside of the physical aperture. */
1044 	if (!pmap_verify_free((ppnum_t)atop(pa))) {
1045 		panic("%s: page still has mappings, pa=0x%llx", __func__, pa);
1046 	}
1047 
1048 	do {
1049 		attr = pp_attr_table[pai];
1050 		if (attr & PP_ATTR_NO_MONITOR) {
1051 			panic("%s: page excluded from PPL, pa=0x%llx", __func__, pa);
1052 		}
1053 	} while (!OSCompareAndSwap16(attr, attr | PP_ATTR_MONITOR, &pp_attr_table[pai]));
1054 
1055 	/* Ensure only the PPL has write access to the physical aperture mapping. */
1056 	pmap_set_xprr_perm(pai, XPRR_KERN_RW_PERM, XPRR_PPL_RW_PERM);
1057 
1058 	pvh_unlock(pai);
1059 
1060 	if (initially_free) {
1061 		pmap_give_free_ppl_page(pa);
1062 	}
1063 }
1064 
1065 /**
1066  * Helper function for converting a PPL page back into a kernel-writable page.
1067  * This removes the PPL-ownership for that page and updates the physical
1068  * aperture mapping of that page so it's kernel-writable again.
1069  *
1070  * @param pa The physical address of the PPL page to be made kernel-writable.
1071  */
1072 MARK_AS_PMAP_TEXT void
pmap_mark_page_as_kernel_page(pmap_paddr_t pa)1073 pmap_mark_page_as_kernel_page(pmap_paddr_t pa)
1074 {
1075 	const unsigned int pai = pa_index(pa);
1076 	pvh_lock(pai);
1077 
1078 	if (!ppattr_pa_test_monitor(pa)) {
1079 		panic("%s: page is not a PPL page, pa=%p", __func__, (void *)pa);
1080 	}
1081 
1082 	ppattr_pa_clear_monitor(pa);
1083 
1084 	/* Ensure the kernel has write access to the physical aperture mapping. */
1085 	pmap_set_xprr_perm(pai, XPRR_PPL_RW_PERM, XPRR_KERN_RW_PERM);
1086 
1087 	pvh_unlock(pai);
1088 }
1089 
1090 /**
1091  * PPL Helper function for giving a single page on the PPL page free list back
1092  * to the kernel.
1093  *
1094  * @note This function implements the logic that HAS to run within the PPL for
1095  *       the pmap_release_ppl_pages_to_kernel() call. This helper function
1096  *       shouldn't be called directly.
1097  *
1098  * @note A minimum amount of pages (set by PMAP_MIN_FREE_PPL_PAGES) will always
1099  *       be kept on the PPL page free list to ensure that core operations can
1100  *       occur without having to refill the free list.
1101  *
1102  * @return The physical address of the page that's been returned to the kernel,
1103  *         or zero if no page was returned.
1104  */
1105 MARK_AS_PMAP_TEXT pmap_paddr_t
pmap_release_ppl_pages_to_kernel_internal(void)1106 pmap_release_ppl_pages_to_kernel_internal(void)
1107 {
1108 	pmap_paddr_t pa = 0;
1109 
1110 	if (pmap_ppl_free_page_count <= PMAP_MIN_FREE_PPL_PAGES) {
1111 		return 0;
1112 	}
1113 
1114 	pa = pmap_get_free_ppl_page();
1115 
1116 	if (!pa) {
1117 		return 0;
1118 	}
1119 
1120 	pmap_mark_page_as_kernel_page(pa);
1121 
1122 	return pa;
1123 }
1124 #endif /* XNU_MONITOR */
1125 
1126 /**
1127  * Add a queue of VM pages to the pmap's VM object. This informs the VM that
1128  * these pages are being used by the pmap and shouldn't be reused.
1129  *
1130  * This also means that the pmap_object can be used as a convenient way to loop
1131  * through every page currently being used by the pmap. For instance, this queue
1132  * of pages is exposed to the debugger through the Low Globals, where it's used
1133  * to ensure that all pmap data is saved in an active core dump.
1134  *
1135  * @param mem The head of the queue of VM pages to add to the pmap's VM object.
1136  */
1137 void
pmap_enqueue_pages(vm_page_t mem)1138 pmap_enqueue_pages(vm_page_t mem)
1139 {
1140 	vm_page_t m_prev;
1141 	vm_object_lock(pmap_object);
1142 	while (mem != VM_PAGE_NULL) {
1143 		const vm_object_offset_t offset =
1144 		    (vm_object_offset_t) ((ptoa(VM_PAGE_GET_PHYS_PAGE(mem))) - gPhysBase);
1145 
1146 		vm_page_insert_wired(mem, pmap_object, offset, VM_KERN_MEMORY_PTE);
1147 		m_prev = mem;
1148 		mem = NEXT_PAGE(m_prev);
1149 		*(NEXT_PAGE_PTR(m_prev)) = VM_PAGE_NULL;
1150 	}
1151 	vm_object_unlock(pmap_object);
1152 }
1153 
1154 /**
1155  * Allocate a page for usage within the pmap and zero it out. If running on a
1156  * PPL-enabled system, this will allocate pages from the PPL page free list.
1157  * Otherwise pages are grabbed directly from the VM.
1158  *
1159  * @note On PPL-enabled systems, this function can ONLY be called from within
1160  *       the PPL. If a page needs to be allocated from outside of the PPL on
1161  *       these systems, then use pmap_alloc_page_for_kern().
1162  *
1163  * @param pa Output parameter to store the physical address of the allocated
1164  *           page if one was able to be allocated (NULL otherwise).
1165  * @param size The amount of memory to allocate. This has to be PAGE_SIZE on
1166  *             PPL-enabled systems. On other systems it can be either PAGE_SIZE
1167  *             or 2*PAGE_SIZE, in which case the two pages are allocated
1168  *             physically contiguous.
1169  * @param options The following options can be specified:
1170  *     - PMAP_PAGES_ALLOCATE_NOWAIT: If the VM or PPL page free list don't have
1171  *       any free pages available then don't wait for one, just return
1172  *       immediately without allocating a page. PPL-enabled systems must ALWAYS
1173  *       pass this flag since allocating memory from within the PPL can't spin
1174  *       or block due to preemption being disabled (would be a perf hit).
1175  *
1176  *     - PMAP_PAGE_RECLAIM_NOWAIT: If memory failed to get allocated the normal
1177  *       way (either by the PPL page free list on PPL-enabled systems, or
1178  *       through the VM on other systems), then fall back to attempting to
1179  *       reclaim a userspace page table. This should only be specified in paths
1180  *       that absolutely can't take the latency hit of waiting for the VM or
1181  *       jumping out of the PPL to allocate more pages.
1182  *
1183  * @return KERN_SUCCESS if a page was successfully allocated, or
1184  *         KERN_RESOURCE_SHORTAGE if a page failed to get allocated.
1185  */
1186 MARK_AS_PMAP_TEXT kern_return_t
pmap_pages_alloc_zeroed(pmap_paddr_t * pa,unsigned size,unsigned options)1187 pmap_pages_alloc_zeroed(pmap_paddr_t *pa, unsigned size, unsigned options)
1188 {
1189 	assert(pa != NULL);
1190 
1191 #if XNU_MONITOR
1192 	ASSERT_NOT_HIBERNATING();
1193 
1194 	/* The PPL page free list always operates on PAGE_SIZE chunks of memory. */
1195 	if (size != PAGE_SIZE) {
1196 		panic("%s: size != PAGE_SIZE, pa=%p, size=%u, options=%u",
1197 		    __func__, pa, size, options);
1198 	}
1199 
1200 	/* Allocating memory in the PPL can't wait since preemption is disabled. */
1201 	assert(options & PMAP_PAGES_ALLOCATE_NOWAIT);
1202 
1203 	*pa = pmap_get_free_ppl_page();
1204 
1205 	if ((*pa == 0) && (options & PMAP_PAGE_RECLAIM_NOWAIT)) {
1206 		*pa = pmap_page_reclaim();
1207 	}
1208 
1209 	if (*pa == 0) {
1210 		return KERN_RESOURCE_SHORTAGE;
1211 	} else {
1212 		bzero((void*)phystokv(*pa), size);
1213 		return KERN_SUCCESS;
1214 	}
1215 #else /* XNU_MONITOR */
1216 	vm_page_t mem = VM_PAGE_NULL;
1217 	thread_t self = current_thread();
1218 
1219 	/**
1220 	 * We qualify for allocating reserved memory so set TH_OPT_VMPRIV to inform
1221 	 * the VM of this.
1222 	 *
1223 	 * This field should only be modified by the local thread itself, so no lock
1224 	 * needs to be taken.
1225 	 */
1226 	uint16_t thread_options = self->options;
1227 	self->options |= TH_OPT_VMPRIV;
1228 
1229 	if (__probable(size == PAGE_SIZE)) {
1230 		/**
1231 		 * If we're only allocating a single page, just grab one off the VM's
1232 		 * global page free list.
1233 		 */
1234 		while ((mem = vm_page_grab()) == VM_PAGE_NULL) {
1235 			if (options & PMAP_PAGES_ALLOCATE_NOWAIT) {
1236 				break;
1237 			}
1238 
1239 			VM_PAGE_WAIT();
1240 		}
1241 
1242 		if (mem != VM_PAGE_NULL) {
1243 			vm_page_lock_queues();
1244 			vm_page_wire(mem, VM_KERN_MEMORY_PTE, TRUE);
1245 			vm_page_unlock_queues();
1246 		}
1247 	} else if (size == (2 * PAGE_SIZE)) {
1248 		/**
1249 		 * Allocate two physically contiguous pages. Any random two pages
1250 		 * obtained from the VM's global page free list aren't guaranteed to be
1251 		 * contiguous so we need to use the cpm_allocate() API.
1252 		 */
1253 		while (cpm_allocate(size, &mem, 0, 1, TRUE, 0) != KERN_SUCCESS) {
1254 			if (options & PMAP_PAGES_ALLOCATE_NOWAIT) {
1255 				break;
1256 			}
1257 
1258 			VM_PAGE_WAIT();
1259 		}
1260 	} else {
1261 		panic("%s: invalid size %u", __func__, size);
1262 	}
1263 
1264 	self->options = thread_options;
1265 
1266 	/**
1267 	 * If the normal method of allocating pages failed, then potentially fall
1268 	 * back to attempting to reclaim a userspace page table.
1269 	 */
1270 	if ((mem == VM_PAGE_NULL) && (options & PMAP_PAGE_RECLAIM_NOWAIT)) {
1271 		assert(size == PAGE_SIZE);
1272 		*pa = pmap_page_reclaim();
1273 		if (*pa != 0) {
1274 			bzero((void*)phystokv(*pa), size);
1275 			return KERN_SUCCESS;
1276 		}
1277 	}
1278 
1279 	if (mem == VM_PAGE_NULL) {
1280 		return KERN_RESOURCE_SHORTAGE;
1281 	}
1282 
1283 	*pa = (pmap_paddr_t)ptoa(VM_PAGE_GET_PHYS_PAGE(mem));
1284 
1285 	/* Add the allocated VM page(s) to the pmap's VM object. */
1286 	pmap_enqueue_pages(mem);
1287 
1288 	/* Pages are considered "in use" by the pmap until returned to the VM. */
1289 	OSAddAtomic(size >> PAGE_SHIFT, &inuse_pmap_pages_count);
1290 	OSAddAtomic64(size >> PAGE_SHIFT, &alloc_pmap_pages_count);
1291 
1292 	bzero((void*)phystokv(*pa), size);
1293 	return KERN_SUCCESS;
1294 #endif /* XNU_MONITOR */
1295 }
1296 
1297 #if XNU_MONITOR
1298 /**
1299  * Allocate a page from the VM. If no pages are available, this function can
1300  * potentially spin until a page is available (see the `options` parameter).
1301  *
1302  * @note This function CANNOT be called from the PPL since it calls into the VM.
1303  *       If the PPL needs memory, then it'll need to exit the PPL before
1304  *       allocating more (usually by returning KERN_RESOURCE_SHORTAGE, and then
1305  *       calling pmap_alloc_page_for_ppl() from outside of the PPL).
1306  *
1307  * @param options The following options can be specified:
1308  *     - PMAP_PAGES_ALLOCATE_NOWAIT: If the VM doesn't have any free pages
1309  *       available then don't wait for one, just return immediately without
1310  *       allocating a page.
1311  *
1312  * @return The physical address of the page, if one was allocated. Zero,
1313  *         otherwise.
1314  */
1315 pmap_paddr_t
pmap_alloc_page_for_kern(unsigned int options)1316 pmap_alloc_page_for_kern(unsigned int options)
1317 {
1318 	pmap_paddr_t pa = 0;
1319 	vm_page_t mem = VM_PAGE_NULL;
1320 
1321 	while ((mem = vm_page_grab()) == VM_PAGE_NULL) {
1322 		if (options & PMAP_PAGES_ALLOCATE_NOWAIT) {
1323 			return 0;
1324 		}
1325 		VM_PAGE_WAIT();
1326 	}
1327 
1328 	/* Automatically wire any pages used by the pmap. */
1329 	vm_page_lock_queues();
1330 	vm_page_wire(mem, VM_KERN_MEMORY_PTE, TRUE);
1331 	vm_page_unlock_queues();
1332 
1333 	pa = (pmap_paddr_t)ptoa(VM_PAGE_GET_PHYS_PAGE(mem));
1334 
1335 	if (__improbable(pa == 0)) {
1336 		panic("%s: physical address is 0", __func__);
1337 	}
1338 
1339 	/**
1340 	 * Add the acquired VM page to the pmap's VM object to notify the VM that
1341 	 * this page is being used.
1342 	 */
1343 	pmap_enqueue_pages(mem);
1344 
1345 	/* Pages are considered "in use" by the pmap until returned to the VM. */
1346 	OSAddAtomic(1, &inuse_pmap_pages_count);
1347 	OSAddAtomic64(1, &alloc_pmap_pages_count);
1348 
1349 	return pa;
1350 }
1351 
1352 /**
1353  * Allocate a page from the VM, mark it as being PPL-owned, and add it to the
1354  * PPL page free list.
1355  *
1356  * @note This function CANNOT be called from the PPL since it calls into the VM.
1357  *       If the PPL needs memory, then it'll need to exit the PPL before calling
1358  *       this function (usually by returning KERN_RESOURCE_SHORTAGE).
1359  *
1360  * @param options The following options can be specified:
1361  *     - PMAP_PAGES_ALLOCATE_NOWAIT: If the VM doesn't have any free pages
1362  *       available then don't wait for one, just return immediately without
1363  *       allocating a page.
1364  */
1365 void
pmap_alloc_page_for_ppl(unsigned int options)1366 pmap_alloc_page_for_ppl(unsigned int options)
1367 {
1368 	thread_t self = current_thread();
1369 
1370 	/**
1371 	 * We qualify for allocating reserved memory so set TH_OPT_VMPRIV to inform
1372 	 * the VM of this.
1373 	 *
1374 	 * This field should only be modified by the local thread itself, so no lock
1375 	 * needs to be taken.
1376 	 */
1377 	uint16_t thread_options = self->options;
1378 	self->options |= TH_OPT_VMPRIV;
1379 	pmap_paddr_t pa = pmap_alloc_page_for_kern(options);
1380 	self->options = thread_options;
1381 
1382 	if (pa != 0) {
1383 		pmap_mark_page_as_ppl_page(pa);
1384 	}
1385 }
1386 #endif /* XNU_MONITOR */
1387 
1388 /**
1389  * Free memory previously allocated through pmap_pages_alloc_zeroed() or
1390  * pmap_alloc_page_for_kern().
1391  *
1392  * On PPL-enabled systems, this just adds the page back to the PPL page free
1393  * list. On other systems, this returns the page(s) back to the VM.
1394  *
1395  * @param pa Physical address of the page(s) to free.
1396  * @param size The size in bytes of the memory region being freed (must be
1397  *             PAGE_SIZE on PPL-enabled systems).
1398  */
1399 void
pmap_pages_free(pmap_paddr_t pa,__assert_only unsigned size)1400 pmap_pages_free(pmap_paddr_t pa, __assert_only unsigned size)
1401 {
1402 	/**
1403 	 * If the pmap is starved for memory to the point that pmap_page_reclaim()
1404 	 * starts getting invoked to allocate memory, then let's take the page being
1405 	 * freed and add it directly to pmap_page_reclaim()'s dedicated free list.
1406 	 * In that case, the page being freed is most likely a userspace page table
1407 	 * that was reclaimed.
1408 	 */
1409 	if (__improbable(pmap_pages_request_count != 0)) {
1410 		pmap_simple_lock(&pmap_page_reclaim_lock);
1411 
1412 		if (pmap_pages_request_count != 0) {
1413 			pmap_pages_request_count--;
1414 
1415 			/* Prepend the freed page to the pmap_page_reclaim() free list. */
1416 			page_free_entry_t *page_entry = (page_free_entry_t *)phystokv(pa);
1417 			page_entry->next = pmap_page_reclaim_list;
1418 			pmap_page_reclaim_list = page_entry;
1419 			pmap_simple_unlock(&pmap_page_reclaim_lock);
1420 
1421 			return;
1422 		}
1423 		pmap_simple_unlock(&pmap_page_reclaim_lock);
1424 	}
1425 
1426 #if XNU_MONITOR
1427 	/* The PPL page free list always operates on PAGE_SIZE chunks of memory. */
1428 	assert(size == PAGE_SIZE);
1429 
1430 	/* On PPL-enabled systems, just add the page back to the PPL page free list. */
1431 	pmap_give_free_ppl_page(pa);
1432 #else /* XNU_MONITOR */
1433 	vm_page_t mem = VM_PAGE_NULL;
1434 	const pmap_paddr_t pa_max = pa + size;
1435 
1436 	/* Pages are considered "in use" until given back to the VM. */
1437 	OSAddAtomic(-(size >> PAGE_SHIFT), &inuse_pmap_pages_count);
1438 
1439 	for (; pa < pa_max; pa += PAGE_SIZE) {
1440 		vm_object_lock(pmap_object);
1441 
1442 		/**
1443 		 * Remove the page from the pmap's VM object and return it back to the
1444 		 * VM's global free list of pages.
1445 		 */
1446 		mem = vm_page_lookup(pmap_object, (pa - gPhysBase));
1447 		assert(mem != VM_PAGE_NULL);
1448 		assert(VM_PAGE_WIRED(mem));
1449 		vm_page_lock_queues();
1450 		vm_page_free(mem);
1451 		vm_page_unlock_queues();
1452 		vm_object_unlock(pmap_object);
1453 	}
1454 #endif /* XNU_MONITOR */
1455 }
1456 
1457 /**
1458  * Called by the VM to reclaim pages that we can reclaim quickly and cheaply.
1459  * This will take pages in the pmap's VM object and add them back to the VM's
1460  * global list of free pages.
1461  *
1462  * @return The number of pages returned to the VM.
1463  */
1464 uint64_t
pmap_release_pages_fast(void)1465 pmap_release_pages_fast(void)
1466 {
1467 #if XNU_MONITOR
1468 	return pmap_release_ppl_pages_to_kernel();
1469 #else /* XNU_MONITOR */
1470 	return 0;
1471 #endif
1472 }
1473 
1474 /**
1475  * Allocates a batch (list) of pv_entry_t's from the global PV free array.
1476  *
1477  * @return A pointer to the head of the newly-allocated batch, or PV_ENTRY_NULL
1478  *         if empty.
1479  */
1480 MARK_AS_PMAP_TEXT static pv_entry_t *
pv_free_array_get_batch(void)1481 pv_free_array_get_batch(void)
1482 {
1483 	pv_entry_t *new_batch = PV_ENTRY_NULL;
1484 
1485 	pmap_simple_lock(&pv_free_array_lock);
1486 	if (pv_free_array_n_elems() > 0) {
1487 		/**
1488 		 * The global PV array acts as a ring buffer where each entry points to
1489 		 * a linked list of PVEs of length PV_BATCH_SIZE. Get the next free
1490 		 * batch.
1491 		 */
1492 		const size_t index = pv_free_read_idx++ & (PV_FREE_ARRAY_SIZE - 1);
1493 		pv_free_list_t *free_list = &pv_free_ring[index];
1494 
1495 		assert((free_list->count == PV_BATCH_SIZE) && (free_list->list != PV_ENTRY_NULL));
1496 		new_batch = free_list->list;
1497 	}
1498 	pmap_simple_unlock(&pv_free_array_lock);
1499 
1500 	return new_batch;
1501 }
1502 
1503 /**
1504  * Frees a batch (list) of pv_entry_t's into the global PV free array.
1505  *
1506  * @param batch_head Pointer to the first entry in the batch to be returned to
1507  *                   the array. This must be a linked list of pv_entry_t's of
1508  *                   length PV_BATCH_SIZE.
1509  *
1510  * @return KERN_SUCCESS, or KERN_FAILURE if the global array is full.
1511  */
1512 MARK_AS_PMAP_TEXT static kern_return_t
pv_free_array_give_batch(pv_entry_t * batch_head)1513 pv_free_array_give_batch(pv_entry_t *batch_head)
1514 {
1515 	assert(batch_head != NULL);
1516 
1517 	pmap_simple_lock(&pv_free_array_lock);
1518 	if (pv_free_array_n_elems() == (PV_FREE_ARRAY_SIZE - 1)) {
1519 		pmap_simple_unlock(&pv_free_array_lock);
1520 		return KERN_FAILURE;
1521 	}
1522 
1523 	const size_t index = pv_free_write_idx++ & (PV_FREE_ARRAY_SIZE - 1);
1524 	pv_free_list_t *free_list = &pv_free_ring[index];
1525 	free_list->list = batch_head;
1526 	free_list->count = PV_BATCH_SIZE;
1527 	pmap_simple_unlock(&pv_free_array_lock);
1528 
1529 	return KERN_SUCCESS;
1530 }
1531 
1532 /**
1533  * Helper function for allocating a single PVE from an arbitrary free list.
1534  *
1535  * @param free_list The free list to allocate a node from.
1536  * @param pvepp Output parameter that will get updated with a pointer to the
1537  *              allocated node if the free list isn't empty, or a pointer to
1538  *              NULL if the list is empty.
1539  */
1540 MARK_AS_PMAP_TEXT static void
pv_free_list_alloc(pv_free_list_t * free_list,pv_entry_t ** pvepp)1541 pv_free_list_alloc(pv_free_list_t *free_list, pv_entry_t **pvepp)
1542 {
1543 	assert(pvepp != NULL);
1544 	assert(((free_list->list != NULL) && (free_list->count > 0)) ||
1545 	    ((free_list->list == NULL) && (free_list->count == 0)));
1546 
1547 	if ((*pvepp = free_list->list) != NULL) {
1548 		pv_entry_t *pvep = *pvepp;
1549 		free_list->list = pvep->pve_next;
1550 		pvep->pve_next = PV_ENTRY_NULL;
1551 		free_list->count--;
1552 	}
1553 }
1554 
1555 /**
1556  * Allocates a PVE from the kernel-dedicated list.
1557  *
1558  * @note This is only called when the global free list is empty, so don't bother
1559  *       trying to allocate more nodes from that list.
1560  *
1561  * @param pvepp Output parameter that will get updated with a pointer to the
1562  *              allocated node if the free list isn't empty, or a pointer to
1563  *              NULL if the list is empty. This pointer can't already be
1564  *              pointing to a valid entry before allocation.
1565  */
1566 MARK_AS_PMAP_TEXT static void
pv_list_kern_alloc(pv_entry_t ** pvepp)1567 pv_list_kern_alloc(pv_entry_t **pvepp)
1568 {
1569 	assert((pvepp != NULL) && (*pvepp == PV_ENTRY_NULL));
1570 	pmap_simple_lock(&pv_kern_free_list_lock);
1571 	if (pv_kern_free.count > 0) {
1572 		pmap_kern_reserve_alloc_stat++;
1573 	}
1574 	pv_free_list_alloc(&pv_kern_free, pvepp);
1575 	pmap_simple_unlock(&pv_kern_free_list_lock);
1576 }
1577 
1578 /**
1579  * Returns a list of PVEs to the kernel-dedicated free list.
1580  *
1581  * @param pve_head Head of the list to be returned.
1582  * @param pve_tail Tail of the list to be returned.
1583  * @param pv_cnt Number of elements in the list to be returned.
1584  */
1585 MARK_AS_PMAP_TEXT static void
pv_list_kern_free(pv_entry_t * pve_head,pv_entry_t * pve_tail,int pv_cnt)1586 pv_list_kern_free(pv_entry_t *pve_head, pv_entry_t *pve_tail, int pv_cnt)
1587 {
1588 	assert((pve_head != PV_ENTRY_NULL) && (pve_tail != PV_ENTRY_NULL));
1589 
1590 	pmap_simple_lock(&pv_kern_free_list_lock);
1591 	pve_tail->pve_next = pv_kern_free.list;
1592 	pv_kern_free.list = pve_head;
1593 	pv_kern_free.count += pv_cnt;
1594 	pmap_simple_unlock(&pv_kern_free_list_lock);
1595 }
1596 
1597 /**
1598  * Attempts to allocate from the per-cpu free list of PVEs, and if that fails,
1599  * then replenish the per-cpu free list with a batch of PVEs from the global
1600  * PVE free list.
1601  *
1602  * @param pvepp Output parameter that will get updated with a pointer to the
1603  *              allocated node if the free lists aren't empty, or a pointer to
1604  *              NULL if both the per-cpu and global lists are empty. This
1605  *              pointer can't already be pointing to a valid entry before
1606  *              allocation.
1607  */
1608 MARK_AS_PMAP_TEXT static void
pv_list_alloc(pv_entry_t ** pvepp)1609 pv_list_alloc(pv_entry_t **pvepp)
1610 {
1611 	assert((pvepp != NULL) && (*pvepp == PV_ENTRY_NULL));
1612 
1613 #if !XNU_MONITOR
1614 	/**
1615 	 * Preemption is always disabled in the PPL so it only needs to get disabled
1616 	 * on non-PPL systems. This needs to be disabled while working with per-cpu
1617 	 * data to prevent getting rescheduled onto a different CPU.
1618 	 */
1619 	mp_disable_preemption();
1620 #endif /* !XNU_MONITOR */
1621 
1622 	pmap_cpu_data_t *pmap_cpu_data = pmap_get_cpu_data();
1623 	pv_free_list_alloc(&pmap_cpu_data->pv_free, pvepp);
1624 
1625 	if (*pvepp != PV_ENTRY_NULL) {
1626 		goto pv_list_alloc_done;
1627 	}
1628 
1629 #if !XNU_MONITOR
1630 	if (pv_kern_free.count < pv_kern_low_water_mark) {
1631 		/**
1632 		 * If the kernel reserved pool is low, let non-kernel mappings wait for
1633 		 * a page from the VM.
1634 		 */
1635 		goto pv_list_alloc_done;
1636 	}
1637 #endif /* !XNU_MONITOR */
1638 
1639 	/**
1640 	 * Attempt to replenish the local list off the global one, and return the
1641 	 * first element. If the global list is empty, then the allocation failed.
1642 	 */
1643 	pv_entry_t *new_batch = pv_free_array_get_batch();
1644 
1645 	if (new_batch != PV_ENTRY_NULL) {
1646 		pmap_cpu_data->pv_free.count = PV_BATCH_SIZE - 1;
1647 		pmap_cpu_data->pv_free.list = new_batch->pve_next;
1648 		assert(pmap_cpu_data->pv_free.list != NULL);
1649 
1650 		new_batch->pve_next = PV_ENTRY_NULL;
1651 		*pvepp = new_batch;
1652 	}
1653 
1654 pv_list_alloc_done:
1655 #if !XNU_MONITOR
1656 	mp_enable_preemption();
1657 #endif /* !XNU_MONITOR */
1658 
1659 	return;
1660 }
1661 
1662 /**
1663  * Adds a list of PVEs to the per-CPU PVE free list. May spill out some entries
1664  * to the global or the kernel PVE free lists if the per-CPU list contains too
1665  * many PVEs.
1666  *
1667  * @param pve_head Head of the list to be returned.
1668  * @param pve_tail Tail of the list to be returned.
1669  * @param pv_cnt Number of elements in the list to be returned.
1670  */
1671 MARK_AS_PMAP_TEXT void
pv_list_free(pv_entry_t * pve_head,pv_entry_t * pve_tail,int pv_cnt)1672 pv_list_free(pv_entry_t *pve_head, pv_entry_t *pve_tail, int pv_cnt)
1673 {
1674 	assert((pve_head != PV_ENTRY_NULL) && (pve_tail != PV_ENTRY_NULL));
1675 
1676 #if !XNU_MONITOR
1677 	/**
1678 	 * Preemption is always disabled in the PPL so it only needs to get disabled
1679 	 * on non-PPL systems. This needs to be disabled while working with per-cpu
1680 	 * data to prevent getting rescheduled onto a different CPU.
1681 	 */
1682 	mp_disable_preemption();
1683 #endif /* !XNU_MONITOR */
1684 
1685 	pmap_cpu_data_t *pmap_cpu_data = pmap_get_cpu_data();
1686 
1687 	/**
1688 	 * How many more PVEs need to be added to the last allocated batch to get it
1689 	 * back up to a PV_BATCH_SIZE number of objects.
1690 	 */
1691 	const uint32_t available = PV_BATCH_SIZE - (pmap_cpu_data->pv_free.count % PV_BATCH_SIZE);
1692 
1693 	/**
1694 	 * The common case is that the number of PVEs to be freed fit in the current
1695 	 * PV_BATCH_SIZE boundary. If that is the case, quickly prepend the whole
1696 	 * list and return.
1697 	 */
1698 	if (__probable((pv_cnt <= available) &&
1699 	    ((pmap_cpu_data->pv_free.count % PV_BATCH_SIZE != 0) || (pmap_cpu_data->pv_free.count == 0)))) {
1700 		pve_tail->pve_next = pmap_cpu_data->pv_free.list;
1701 		pmap_cpu_data->pv_free.list = pve_head;
1702 		pmap_cpu_data->pv_free.count += pv_cnt;
1703 		goto pv_list_free_done;
1704 	}
1705 
1706 	/**
1707 	 * In the degenerate case, we need to process PVEs one by one, to make sure
1708 	 * we spill out to the global list, or update the spill marker as
1709 	 * appropriate.
1710 	 */
1711 	while (pv_cnt) {
1712 		/**
1713 		 * Take the node off the top of the passed in list and prepend it to the
1714 		 * per-cpu list.
1715 		 */
1716 		pv_entry_t *pv_next = pve_head->pve_next;
1717 		pve_head->pve_next = pmap_cpu_data->pv_free.list;
1718 		pmap_cpu_data->pv_free.list = pve_head;
1719 		pve_head = pv_next;
1720 		pmap_cpu_data->pv_free.count++;
1721 		pv_cnt--;
1722 
1723 		if (__improbable(pmap_cpu_data->pv_free.count == (PV_BATCH_SIZE + 1))) {
1724 			/**
1725 			 * A full batch of entries have been freed to the per-cpu list.
1726 			 * Update the spill marker which is used to remember the end of a
1727 			 * batch (remember, we prepend nodes) to eventually return back to
1728 			 * the global list (we try to only keep one PV_BATCH_SIZE worth of
1729 			 * nodes in any single per-cpu list).
1730 			 */
1731 			pmap_cpu_data->pv_free_spill_marker = pmap_cpu_data->pv_free.list;
1732 		} else if (__improbable(pmap_cpu_data->pv_free.count == (PV_BATCH_SIZE * 2) + 1)) {
1733 			/* Spill out excess PVEs to the global PVE array */
1734 			pv_entry_t *spill_head = pmap_cpu_data->pv_free.list->pve_next;
1735 			pv_entry_t *spill_tail = pmap_cpu_data->pv_free_spill_marker;
1736 			pmap_cpu_data->pv_free.list->pve_next = pmap_cpu_data->pv_free_spill_marker->pve_next;
1737 			spill_tail->pve_next = PV_ENTRY_NULL;
1738 			pmap_cpu_data->pv_free.count -= PV_BATCH_SIZE;
1739 			pmap_cpu_data->pv_free_spill_marker = pmap_cpu_data->pv_free.list;
1740 
1741 			if (__improbable(pv_free_array_give_batch(spill_head) != KERN_SUCCESS)) {
1742 				/**
1743 				 * This is extremely unlikely to happen, as it would imply that
1744 				 * we have (PV_FREE_ARRAY_SIZE * PV_BATCH_SIZE) PVEs sitting in
1745 				 * the global array. Just in case, push the excess down to the
1746 				 * kernel PVE free list.
1747 				 */
1748 				pv_list_kern_free(spill_head, spill_tail, PV_BATCH_SIZE);
1749 			}
1750 		}
1751 	}
1752 
1753 pv_list_free_done:
1754 #if !XNU_MONITOR
1755 	mp_enable_preemption();
1756 #endif /* !XNU_MONITOR */
1757 
1758 	return;
1759 }
1760 
1761 /**
1762  * Adds a single page to the PVE allocation subsystem.
1763  *
1764  * @note This function operates under the assumption that a PV_BATCH_SIZE amount
1765  *       of PVEs can fit within a single page. One page is always allocated for
1766  *       one batch, so if there's empty space in the page after the batch of
1767  *       PVEs, it'll go unused (so it's best to keep the batch size at an amount
1768  *       that utilizes a whole page).
1769  *
1770  * @param alloc_flags Allocation flags passed to pmap_pages_alloc_zeroed(). See
1771  *                    the definition of that function for a detailed description
1772  *                    of the available flags.
1773  *
1774  * @return KERN_SUCCESS, or the value returned by pmap_pages_alloc_zeroed() upon
1775  *         failure.
1776  */
1777 MARK_AS_PMAP_TEXT static kern_return_t
pve_feed_page(unsigned alloc_flags)1778 pve_feed_page(unsigned alloc_flags)
1779 {
1780 	kern_return_t kr = KERN_FAILURE;
1781 
1782 	pv_entry_t *pve_head = PV_ENTRY_NULL;
1783 	pv_entry_t *pve_tail = PV_ENTRY_NULL;
1784 	pmap_paddr_t pa = 0;
1785 
1786 	kr = pmap_pages_alloc_zeroed(&pa, PAGE_SIZE, alloc_flags);
1787 
1788 	if (kr != KERN_SUCCESS) {
1789 		return kr;
1790 	}
1791 
1792 	/* Update statistics globals. See the variables' definitions for more info. */
1793 	pv_page_count++;
1794 	pmap_reserve_replenish_stat += PV_BATCH_SIZE;
1795 
1796 	/* Prepare a new list by linking all of the entries in advance. */
1797 	pve_head = (pv_entry_t *)phystokv(pa);
1798 	pve_tail = &pve_head[PV_BATCH_SIZE - 1];
1799 
1800 	for (int i = 0; i < PV_BATCH_SIZE; i++) {
1801 		pve_head[i].pve_next = &pve_head[i + 1];
1802 	}
1803 	pve_head[PV_BATCH_SIZE - 1].pve_next = PV_ENTRY_NULL;
1804 
1805 	/**
1806 	 * Add the new list to the kernel PVE free list if we are running low on
1807 	 * kernel-dedicated entries or the global free array is full.
1808 	 */
1809 	if ((pv_kern_free.count < pv_kern_low_water_mark) ||
1810 	    (pv_free_array_give_batch(pve_head) != KERN_SUCCESS)) {
1811 		pv_list_kern_free(pve_head, pve_tail, PV_BATCH_SIZE);
1812 	}
1813 
1814 	return KERN_SUCCESS;
1815 }
1816 
1817 /**
1818  * Allocate a PV node from one of many different free lists (per-cpu, global, or
1819  * kernel-specific).
1820  *
1821  * @note This function is very tightly coupled with pmap_enter_pv(). If
1822  *       modifying this code, please ensure that pmap_enter_pv() doesn't break.
1823  *
1824  * @note The pmap lock must already be held if the new mapping is a CPU mapping.
1825  *
1826  * @note The PVH lock for the physical page that is getting a new mapping
1827  *       registered must already be held.
1828  *
1829  * @param pmap The pmap that owns the new mapping, or NULL if this is tracking
1830  *             an IOMMU translation.
1831  * @param pai The physical address index of the page that's getting a new
1832  *            mapping.
1833  * @param lock_mode Which state the pmap lock is being held in if the mapping is
1834  *                  owned by a pmap, otherwise this is a don't care.
1835  * @param pvepp Output parameter that will get updated with a pointer to the
1836  *              allocated node if none of the free lists are empty, or a pointer
1837  *              to NULL otherwise. This pointer can't already be pointing to a
1838  *              valid entry before allocation.
1839  *
1840  * @return These are the possible return values:
1841  *     PV_ALLOC_SUCCESS: A PVE object was successfully allocated.
1842  *     PV_ALLOC_FAILURE: No objects were available for allocation, and
1843  *                       allocating a new page failed. On PPL-enabled systems,
1844  *                       a fresh page needs to be added to the PPL page list
1845  *                       before retrying this operaton.
1846  *     PV_ALLOC_RETRY: No objects were available on the free lists, so a new
1847  *                     page of PVE objects needed to be allocated. To do that,
1848  *                     the pmap and PVH locks were dropped. The caller may have
1849  *                     depended on these locks for consistency, so return and
1850  *                     let the caller retry the PVE allocation with the locks
1851  *                     held. Note that the locks have already been re-acquired
1852  *                     before this function exits.
1853  */
1854 MARK_AS_PMAP_TEXT pv_alloc_return_t
pv_alloc(pmap_t pmap,unsigned int pai,pmap_lock_mode_t lock_mode,pv_entry_t ** pvepp)1855 pv_alloc(
1856 	pmap_t pmap,
1857 	unsigned int pai,
1858 	pmap_lock_mode_t lock_mode,
1859 	pv_entry_t **pvepp)
1860 {
1861 	assert((pvepp != NULL) && (*pvepp == PV_ENTRY_NULL));
1862 
1863 	if (pmap != NULL) {
1864 		pmap_assert_locked(pmap, lock_mode);
1865 	}
1866 	pvh_assert_locked(pai);
1867 
1868 	pv_list_alloc(pvepp);
1869 	if (PV_ENTRY_NULL != *pvepp) {
1870 		return PV_ALLOC_SUCCESS;
1871 	}
1872 
1873 #if XNU_MONITOR
1874 	/* PPL can't block so this flag is always required. */
1875 	unsigned alloc_flags = PMAP_PAGES_ALLOCATE_NOWAIT;
1876 #else /* XNU_MONITOR */
1877 	unsigned alloc_flags = 0;
1878 #endif /* XNU_MONITOR */
1879 
1880 	/**
1881 	 * We got here because both the per-CPU and the global lists are empty. If
1882 	 * this allocation is for the kernel, we try to get an entry from the kernel
1883 	 * list next.
1884 	 */
1885 	if ((pmap == NULL) || (kernel_pmap == pmap)) {
1886 		pv_list_kern_alloc(pvepp);
1887 		if (PV_ENTRY_NULL != *pvepp) {
1888 			return PV_ALLOC_SUCCESS;
1889 		}
1890 		alloc_flags = PMAP_PAGES_ALLOCATE_NOWAIT | PMAP_PAGE_RECLAIM_NOWAIT;
1891 	}
1892 
1893 	/**
1894 	 * We ran out of PV entries all across the board, or this allocation is not
1895 	 * for the kernel. Let's make sure that the kernel list is not too full
1896 	 * (very unlikely), in which case we can rebalance here.
1897 	 */
1898 	if (__improbable(pv_kern_free.count > (PV_BATCH_SIZE * 2))) {
1899 		pmap_simple_lock(&pv_kern_free_list_lock);
1900 		/* Re-check, now that the lock is held. */
1901 		if (pv_kern_free.count > (PV_BATCH_SIZE * 2)) {
1902 			pv_entry_t *pve_head = pv_kern_free.list;
1903 			pv_entry_t *pve_tail = pve_head;
1904 
1905 			for (int i = 0; i < (PV_BATCH_SIZE - 1); i++) {
1906 				pve_tail = pve_tail->pve_next;
1907 			}
1908 
1909 			pv_kern_free.list = pve_tail->pve_next;
1910 			pv_kern_free.count -= PV_BATCH_SIZE;
1911 			pve_tail->pve_next = PV_ENTRY_NULL;
1912 			pmap_simple_unlock(&pv_kern_free_list_lock);
1913 
1914 			/* Return back every node except the first one to the free lists. */
1915 			pv_list_free(pve_head->pve_next, pve_tail, PV_BATCH_SIZE - 1);
1916 			pve_head->pve_next = PV_ENTRY_NULL;
1917 			*pvepp = pve_head;
1918 			return PV_ALLOC_SUCCESS;
1919 		}
1920 		pmap_simple_unlock(&pv_kern_free_list_lock);
1921 	}
1922 
1923 	/**
1924 	 * If all else fails, try to get a new pmap page so that the allocation
1925 	 * succeeds once the caller retries it.
1926 	 */
1927 	kern_return_t kr = KERN_FAILURE;
1928 	pv_alloc_return_t pv_status = PV_ALLOC_FAIL;
1929 
1930 	/* Drop the lock during page allocation since that can take a while. */
1931 	pvh_unlock(pai);
1932 	if (pmap != NULL) {
1933 		pmap_unlock(pmap, lock_mode);
1934 	}
1935 
1936 	if ((kr = pve_feed_page(alloc_flags)) == KERN_SUCCESS) {
1937 		/**
1938 		 * Since the lock was dropped, even though we successfully allocated a
1939 		 * new page to be used for PVE nodes, the code that relies on this
1940 		 * function might have depended on the lock being held for consistency,
1941 		 * so return out early and let them retry the allocation with the lock
1942 		 * re-held.
1943 		 */
1944 		pv_status = PV_ALLOC_RETRY;
1945 	} else {
1946 		pv_status = PV_ALLOC_FAIL;
1947 	}
1948 
1949 	if (pmap != NULL) {
1950 		pmap_lock(pmap, lock_mode);
1951 	}
1952 	pvh_lock(pai);
1953 
1954 	/* Ensure that no node was created if we're not returning successfully. */
1955 	assert(*pvepp == PV_ENTRY_NULL);
1956 
1957 	return pv_status;
1958 }
1959 
1960 /**
1961  * Utility function for freeing a single PVE object back to the free lists.
1962  *
1963  * @param pvep Pointer to the PVE object to free.
1964  */
1965 MARK_AS_PMAP_TEXT void
pv_free(pv_entry_t * pvep)1966 pv_free(pv_entry_t *pvep)
1967 {
1968 	assert(pvep != PV_ENTRY_NULL);
1969 
1970 	pv_list_free(pvep, pvep, 1);
1971 }
1972 
1973 /**
1974  * This function provides a mechanism for the device tree to override the
1975  * default PV allocation amounts and the watermark level which determines how
1976  * many PVE objects are kept in the kernel-dedicated free list.
1977  */
1978 MARK_AS_PMAP_TEXT void
pmap_compute_pv_targets(void)1979 pmap_compute_pv_targets(void)
1980 {
1981 	DTEntry entry = NULL;
1982 	void const *prop = NULL;
1983 	int err = 0;
1984 	unsigned int prop_size = 0;
1985 
1986 	err = SecureDTLookupEntry(NULL, "/defaults", &entry);
1987 	assert(err == kSuccess);
1988 
1989 	if (kSuccess == SecureDTGetProperty(entry, "pmap-pv-count", &prop, &prop_size)) {
1990 		if (prop_size != sizeof(pv_alloc_initial_target)) {
1991 			panic("pmap-pv-count property is not a 32-bit integer");
1992 		}
1993 		pv_alloc_initial_target = *((uint32_t const *)prop);
1994 	}
1995 
1996 	if (kSuccess == SecureDTGetProperty(entry, "pmap-kern-pv-count", &prop, &prop_size)) {
1997 		if (prop_size != sizeof(pv_kern_alloc_initial_target)) {
1998 			panic("pmap-kern-pv-count property is not a 32-bit integer");
1999 		}
2000 		pv_kern_alloc_initial_target = *((uint32_t const *)prop);
2001 	}
2002 
2003 	if (kSuccess == SecureDTGetProperty(entry, "pmap-kern-pv-min", &prop, &prop_size)) {
2004 		if (prop_size != sizeof(pv_kern_low_water_mark)) {
2005 			panic("pmap-kern-pv-min property is not a 32-bit integer");
2006 		}
2007 		pv_kern_low_water_mark = *((uint32_t const *)prop);
2008 	}
2009 }
2010 
2011 /**
2012  * This would normally be used to adjust the amount of PVE objects available in
2013  * the system, but we do that dynamically at runtime anyway so this is unneeded.
2014  */
2015 void
mapping_adjust(void)2016 mapping_adjust(void)
2017 {
2018 	/* Not implemented for arm/arm64. */
2019 }
2020 
2021 /**
2022  * Creates a target number of free pv_entry_t objects for the kernel free list
2023  * and the general free list.
2024  *
2025  * @note This function is called once during early boot, in kernel_bootstrap().
2026  *
2027  * @return KERN_SUCCESS if the objects were successfully allocated, or the
2028  *         return value from pve_feed_page() on failure (could be caused by not
2029  *         being able to allocate a page).
2030  */
2031 MARK_AS_PMAP_TEXT kern_return_t
mapping_free_prime_internal(void)2032 mapping_free_prime_internal(void)
2033 {
2034 	kern_return_t kr = KERN_FAILURE;
2035 
2036 #if XNU_MONITOR
2037 	/* PPL can't block so this flag is always required. */
2038 	unsigned alloc_flags = PMAP_PAGES_ALLOCATE_NOWAIT;
2039 #else /* XNU_MONITOR */
2040 	unsigned alloc_flags = 0;
2041 #endif /* XNU_MONITOR */
2042 
2043 	/*
2044 	 * We do not need to hold the pv_free_array lock to calculate the number of
2045 	 * elements in it because no other core is running at this point.
2046 	 */
2047 	while (((pv_free_array_n_elems() * PV_BATCH_SIZE) < pv_alloc_initial_target) ||
2048 	    (pv_kern_free.count < pv_kern_alloc_initial_target)) {
2049 		if ((kr = pve_feed_page(alloc_flags)) != KERN_SUCCESS) {
2050 			return kr;
2051 		}
2052 	}
2053 
2054 	return KERN_SUCCESS;
2055 }
2056 
2057 /**
2058  * Helper function for pmap_enter_pv (hereby shortened to "pepv") which converts
2059  * a PVH entry from PVH_TYPE_PTEP to PVH_TYPE_PVEP which will transform the
2060  * entry into a linked list of mappings.
2061  *
2062  * @note This should only be called from pmap_enter_pv().
2063  *
2064  * @note The PVH lock for the passed in page must already be held and the type
2065  *       must be PVH_TYPE_PTEP (wouldn't make sense to call this otherwise).
2066  *
2067  * @param pmap Either the pmap that owns the mapping being registered in
2068  *             pmap_enter_pv(), or NULL if this is an IOMMU mapping.
2069  * @param pai The physical address index of the page that's getting a second
2070  *            mapping and needs to be converted from PVH_TYPE_PTEP to
2071  *            PVH_TYPE_PVEP.
2072  * @param lock_mode Which state the pmap lock is being held in if the mapping is
2073  *                  owned by a pmap, otherwise this is a don't care.
2074  *
2075  * @return PV_ALLOC_SUCCESS if the entry at `pai` was successfully converted
2076  *         into PVH_TYPE_PVEP, or the return value of pv_alloc() otherwise. See
2077  *         pv_alloc()'s function header for a detailed explanation of the
2078  *         possible return values.
2079  */
2080 MARK_AS_PMAP_TEXT static pv_alloc_return_t
pepv_convert_ptep_to_pvep(pmap_t pmap,unsigned int pai,pmap_lock_mode_t lock_mode)2081 pepv_convert_ptep_to_pvep(
2082 	pmap_t pmap,
2083 	unsigned int pai,
2084 	pmap_lock_mode_t lock_mode)
2085 {
2086 	pvh_assert_locked(pai);
2087 
2088 	pv_entry_t **pvh = pai_to_pvh(pai);
2089 	assert(pvh_test_type(pvh, PVH_TYPE_PTEP));
2090 
2091 	pv_entry_t *pvep = PV_ENTRY_NULL;
2092 	pv_alloc_return_t ret = pv_alloc(pmap, pai, lock_mode, &pvep);
2093 	if (ret != PV_ALLOC_SUCCESS) {
2094 		return ret;
2095 	}
2096 
2097 	/* If we've gotten this far then a node should've been allocated. */
2098 	assert(pvep != PV_ENTRY_NULL);
2099 
2100 	/* The new PVE should have the same PTE pointer as the previous PVH entry. */
2101 	pve_init(pvep);
2102 	pve_set_ptep(pvep, 0, pvh_ptep(pvh));
2103 
2104 	if (ppattr_is_altacct(pai)) {
2105 		/**
2106 		 * Transfer "altacct" status from pp_attr to this pve. See the comment
2107 		 * above PP_ATTR_ALTACCT for more information on this.
2108 		 */
2109 		ppattr_clear_altacct(pai);
2110 		pve_set_altacct(pvep, 0);
2111 	}
2112 
2113 	pvh_update_head(pvh, pvep, PVH_TYPE_PVEP);
2114 
2115 	return PV_ALLOC_SUCCESS;
2116 }
2117 
2118 /**
2119  * Register a new mapping into the pv_head_table. This is the main data
2120  * structure used for performing a reverse physical to virtual translation and
2121  * finding all mappings to a physical page. Whenever a new page table mapping is
2122  * created (regardless of whether it's for a CPU or an IOMMU), it should be
2123  * registered with a call to this function.
2124  *
2125  * @note The pmap lock must already be held if the new mapping is a CPU mapping.
2126  *
2127  * @note The PVH lock for the physical page that is getting a new mapping
2128  *       registered must already be held.
2129  *
2130  * @note This function cannot be called during the hibernation process because
2131  *       it modifies critical pmap data structures that need to be dumped into
2132  *       the hibernation image in a consistent state.
2133  *
2134  * @param pmap The pmap that owns the new mapping, or NULL if this is tracking
2135  *             an IOMMU translation.
2136  * @param ptep The new mapping to register.
2137  * @param pai The physical address index of the physical page being mapped by
2138  *            `ptep`.
2139  * @param options Flags that can potentially be set on a per-page basis:
2140  *                PMAP_OPTIONS_INTERNAL: If this is the first CPU mapping, then
2141  *                    mark the page as being "internal". See the definition of
2142  *                    PP_ATTR_INTERNAL for more info.
2143  *                PMAP_OPTIONS_REUSABLE: If this is the first CPU mapping, and
2144  *                    this page is also marked internal, then mark the page as
2145  *                    being "reusable". See the definition of PP_ATTR_REUSABLE
2146  *                    for more info.
2147  * @param lock_mode Which state the pmap lock is being held in if the mapping is
2148  *                  owned by a pmap, otherwise this is a don't care.
2149  * @param new_pvepp An output parameter that is updated with a pointer to the
2150  *                  PVE object where the PTEP was allocated into. In the event
2151  *                  of failure, or if the pointer passed in is NULL,
2152  *                  it's not modified.
2153  * @param new_pve_ptep_idx An output parameter that is updated with the index
2154  *                  into the PVE object where the PTEP was allocated into.
2155  *                  In the event of failure, or if new_pvepp in is NULL,
2156  *                  it's not modified.
2157  *
2158  * @return PV_ALLOC_SUCCESS if the entry at `pai` was successfully updated with
2159  *         the new mapping, or the return value of pv_alloc() otherwise. See
2160  *         pv_alloc()'s function header for a detailed explanation of the
2161  *         possible return values.
2162  */
2163 MARK_AS_PMAP_TEXT pv_alloc_return_t
pmap_enter_pv(pmap_t pmap,pt_entry_t * ptep,int pai,unsigned int options,pmap_lock_mode_t lock_mode,pv_entry_t ** new_pvepp,int * new_pve_ptep_idx)2164 pmap_enter_pv(
2165 	pmap_t pmap,
2166 	pt_entry_t *ptep,
2167 	int pai,
2168 	unsigned int options,
2169 	pmap_lock_mode_t lock_mode,
2170 	pv_entry_t **new_pvepp,
2171 	int *new_pve_ptep_idx)
2172 {
2173 	assert(ptep != PT_ENTRY_NULL);
2174 
2175 	pv_entry_t **pvh = pai_to_pvh(pai);
2176 	bool first_cpu_mapping = false;
2177 
2178 	ASSERT_NOT_HIBERNATING();
2179 	pvh_assert_locked(pai);
2180 
2181 	if (pmap != NULL) {
2182 		pmap_assert_locked(pmap, lock_mode);
2183 	}
2184 
2185 	vm_offset_t pvh_flags = pvh_get_flags(pvh);
2186 
2187 #if XNU_MONITOR
2188 	if (__improbable(pvh_flags & PVH_FLAG_LOCKDOWN_MASK)) {
2189 		panic("%d is locked down (%#lx), cannot enter", pai, pvh_flags);
2190 	}
2191 #endif /* XNU_MONITOR */
2192 
2193 #ifdef PVH_FLAG_CPU
2194 	/**
2195 	 * An IOMMU mapping may already be present for a page that hasn't yet had a
2196 	 * CPU mapping established, so we use PVH_FLAG_CPU to determine if this is
2197 	 * the first CPU mapping. We base internal/reusable accounting on the
2198 	 * options specified for the first CPU mapping. PVH_FLAG_CPU, and thus this
2199 	 * accounting, will then persist as long as there are *any* mappings of the
2200 	 * page. The accounting for a page should not need to change until the page
2201 	 * is recycled by the VM layer, and we assert that there are no mappings
2202 	 * when a page is recycled. An IOMMU mapping of a freed/recycled page is
2203 	 * considered a security violation & potential DMA corruption path.
2204 	 */
2205 	first_cpu_mapping = ((pmap != NULL) && !(pvh_flags & PVH_FLAG_CPU));
2206 	if (first_cpu_mapping) {
2207 		pvh_flags |= PVH_FLAG_CPU;
2208 	}
2209 #else /* PVH_FLAG_CPU */
2210 	first_cpu_mapping = pvh_test_type(pvh, PVH_TYPE_NULL);
2211 #endif /* PVH_FLAG_CPU */
2212 
2213 	/**
2214 	 * Internal/reusable flags are based on the first CPU mapping made to a
2215 	 * page. These will persist until all mappings to the page are removed.
2216 	 */
2217 	if (first_cpu_mapping) {
2218 		if (options & PMAP_OPTIONS_INTERNAL) {
2219 			ppattr_set_internal(pai);
2220 		} else {
2221 			ppattr_clear_internal(pai);
2222 		}
2223 		if ((options & PMAP_OPTIONS_INTERNAL) &&
2224 		    (options & PMAP_OPTIONS_REUSABLE)) {
2225 			ppattr_set_reusable(pai);
2226 		} else {
2227 			ppattr_clear_reusable(pai);
2228 		}
2229 	}
2230 
2231 	/* Visit the definitions for the PVH_TYPEs to learn more about each one. */
2232 	if (pvh_test_type(pvh, PVH_TYPE_NULL)) {
2233 		/* If this is the first mapping, upgrade the type to store a single PTEP. */
2234 		pvh_update_head(pvh, ptep, PVH_TYPE_PTEP);
2235 	} else {
2236 		pv_alloc_return_t ret = PV_ALLOC_FAIL;
2237 
2238 		if (pvh_test_type(pvh, PVH_TYPE_PTEP)) {
2239 			/**
2240 			 * There was already a single mapping to the page. Convert the PVH
2241 			 * entry from PVH_TYPE_PTEP to PVH_TYPE_PVEP so that multiple
2242 			 * mappings can be tracked. If PVEs cannot hold more than a single
2243 			 * mapping, a second PVE will be added farther down.
2244 			 *
2245 			 * Also, ensure that the PVH flags (which can possibly contain
2246 			 * PVH_FLAG_CPU) are set before potentially returning or dropping
2247 			 * the locks. We use that flag to lock in the internal/reusable
2248 			 * attributes and we don't want another mapping to jump in while the
2249 			 * locks are dropped, think it's the first CPU mapping, and decide
2250 			 * to clobber those attributes.
2251 			 */
2252 			pvh_set_flags(pvh, pvh_flags);
2253 			if ((ret = pepv_convert_ptep_to_pvep(pmap, pai, lock_mode)) != PV_ALLOC_SUCCESS) {
2254 				return ret;
2255 			}
2256 
2257 			/**
2258 			 * At this point, the PVH flags have been clobbered due to updating
2259 			 * PTEP->PVEP, but that's ok because the locks are being held and
2260 			 * the flags will get set again below before pv_alloc() is called
2261 			 * and the locks are potentially dropped again.
2262 			 */
2263 		} else if (!pvh_test_type(pvh, PVH_TYPE_PVEP)) {
2264 			panic("%s: unexpected PV head %p, ptep=%p pmap=%p pvh=%p",
2265 			    __func__, *pvh, ptep, pmap, pvh);
2266 		}
2267 
2268 		/**
2269 		 * Check if we have room for one more mapping in this PVE
2270 		 */
2271 		pv_entry_t *pvep = pvh_pve_list(pvh);
2272 		assert(pvep != PV_ENTRY_NULL);
2273 
2274 		int pve_ptep_idx = pve_find_ptep_index(pvep, PT_ENTRY_NULL);
2275 
2276 		if (pve_ptep_idx == -1) {
2277 			/**
2278 			 * Set up the pv_entry for this new mapping and then add it to the list
2279 			 * for this physical page.
2280 			 */
2281 			pve_ptep_idx = 0;
2282 			pvh_set_flags(pvh, pvh_flags);
2283 			pvep = PV_ENTRY_NULL;
2284 			if ((ret = pv_alloc(pmap, pai, lock_mode, &pvep)) != PV_ALLOC_SUCCESS) {
2285 				return ret;
2286 			}
2287 
2288 			/* If we've gotten this far then a node should've been allocated. */
2289 			assert(pvep != PV_ENTRY_NULL);
2290 			pve_init(pvep);
2291 			pve_add(pvh, pvep);
2292 		}
2293 
2294 		pve_set_ptep(pvep, pve_ptep_idx, ptep);
2295 
2296 		/*
2297 		 * The PTEP was successfully entered into the PVE object.
2298 		 * If the caller requests it, set new_pvepp and new_pve_ptep_idx
2299 		 * appropriately.
2300 		 */
2301 		if (new_pvepp != NULL) {
2302 			*new_pvepp = pvep;
2303 			*new_pve_ptep_idx = pve_ptep_idx;
2304 		}
2305 	}
2306 
2307 	pvh_set_flags(pvh, pvh_flags);
2308 
2309 	return PV_ALLOC_SUCCESS;
2310 }
2311 
2312 /**
2313  * Remove a mapping that was registered with the pv_head_table. This needs to be
2314  * done for every mapping that was previously registered using pmap_enter_pv()
2315  * when the mapping is removed.
2316  *
2317  * @note The PVH lock for the physical page that is getting a new mapping
2318  *       registered must already be held.
2319  *
2320  * @note This function cannot be called during the hibernation process because
2321  *       it modifies critical pmap data structures that need to be dumped into
2322  *       the hibernation image in a consistent state.
2323  *
2324  * @param pmap The pmap that owns the new mapping, or NULL if this is tracking
2325  *             an IOMMU translation.
2326  * @param ptep The mapping that's getting removed.
2327  * @param pai The physical address index of the physical page being mapped by
2328  *            `ptep`.
2329  * @param flush_tlb_async On some systems, removing the last mapping to a page
2330  *                        that used to be mapped executable will require
2331  *                        updating the physical aperture mapping of the page.
2332  *                        This parameter specifies whether the TLB invalidate
2333  *                        should be synchronized or not if that update occurs.
2334  * @return The altacct bit of the PTE that was removed.
2335  */
2336 bool
pmap_remove_pv(pmap_t pmap,pt_entry_t * ptep,int pai,bool flush_tlb_async __unused)2337 pmap_remove_pv(
2338 	pmap_t pmap,
2339 	pt_entry_t *ptep,
2340 	int pai,
2341 	bool flush_tlb_async __unused)
2342 {
2343 	ASSERT_NOT_HIBERNATING();
2344 	pvh_assert_locked(pai);
2345 
2346 	bool is_altacct = false;
2347 	pv_entry_t **pvh = pai_to_pvh(pai);
2348 	const vm_offset_t pvh_flags = pvh_get_flags(pvh);
2349 
2350 #if XNU_MONITOR
2351 	if (__improbable(pvh_flags & PVH_FLAG_LOCKDOWN_MASK)) {
2352 		panic("%s: PVH entry at pai %d is locked down (%#lx), cannot remove",
2353 		    __func__, pai, pvh_flags);
2354 	}
2355 #endif /* XNU_MONITOR */
2356 
2357 	if (pvh_test_type(pvh, PVH_TYPE_PTEP)) {
2358 		if (__improbable((ptep != pvh_ptep(pvh)))) {
2359 			/**
2360 			 * The only mapping that exists for this page isn't the one we're
2361 			 * unmapping, weird.
2362 			 */
2363 			panic("%s: ptep=%p does not match pvh=%p (%p), pai=0x%x",
2364 			    __func__, ptep, pvh, pvh_ptep(pvh), pai);
2365 		}
2366 
2367 		pvh_update_head(pvh, PV_ENTRY_NULL, PVH_TYPE_NULL);
2368 		is_altacct = ppattr_is_altacct(pai);
2369 	} else if (pvh_test_type(pvh, PVH_TYPE_PVEP)) {
2370 		pv_entry_t **pvepp = pvh;
2371 		pv_entry_t *pvep = pvh_pve_list(pvh);
2372 		assert(pvep != PV_ENTRY_NULL);
2373 		int pve_pte_idx = 0;
2374 		/* Find the PVE that represents the mapping we're removing. */
2375 		while ((pvep != PV_ENTRY_NULL) && ((pve_pte_idx = pve_find_ptep_index(pvep, ptep)) == -1)) {
2376 			pvepp = pve_next_ptr(pvep);
2377 			pvep = pve_next(pvep);
2378 		}
2379 
2380 		if (__improbable((pvep == PV_ENTRY_NULL))) {
2381 			panic("%s: ptep=%p (pai=0x%x) not in pvh=%p", __func__, ptep, pai, pvh);
2382 		}
2383 
2384 		is_altacct = pve_get_altacct(pvep, pve_pte_idx);
2385 		pve_set_ptep(pvep, pve_pte_idx, PT_ENTRY_NULL);
2386 
2387 #if MACH_ASSERT
2388 		/**
2389 		 * Ensure that the mapping didn't accidentally have multiple PVEs
2390 		 * associated with it (there should only be one PVE per mapping). This
2391 		 * checking only occurs on configurations that can accept the perf hit
2392 		 * that walking the PVE chain on every unmap entails.
2393 		 *
2394 		 * This is skipped for IOMMU mappings because some IOMMUs don't use
2395 		 * normal page tables (e.g., NVMe) to map pages, so the `ptep` field in
2396 		 * the associated PVE won't actually point to a real page table (see the
2397 		 * definition of PVH_FLAG_IOMMU_TABLE for more info). Because of that,
2398 		 * it's perfectly possible for duplicate IOMMU PVEs to exist.
2399 		 */
2400 		if ((pmap != NULL) && (kern_feature_override(KF_PMAPV_OVRD) == FALSE)) {
2401 			pv_entry_t *check_pvep = pvep;
2402 
2403 			do {
2404 				if (pve_find_ptep_index(check_pvep, ptep) != -1) {
2405 					panic_plain("%s: duplicate pve entry ptep=%p pmap=%p, pvh=%p, "
2406 					    "pvep=%p, pai=0x%x", __func__, ptep, pmap, pvh, pvep, pai);
2407 				}
2408 			} while ((check_pvep = pve_next(check_pvep)) != PV_ENTRY_NULL);
2409 		}
2410 #endif /* MACH_ASSERT */
2411 
2412 		const bool pve_is_first = (pvepp == pvh);
2413 		const bool pve_is_last = (pve_next(pvep) == PV_ENTRY_NULL);
2414 		const int other_pte_idx = !pve_pte_idx;
2415 
2416 		if (pve_is_empty(pvep)) {
2417 			/*
2418 			 * This PVE doesn't contain any mappings. We can get rid of it.
2419 			 */
2420 			pve_remove(pvh, pvepp, pvep);
2421 			pv_free(pvep);
2422 		} else if (!pve_is_first) {
2423 			/*
2424 			 * This PVE contains a single mapping. See if we can coalesce it with the one
2425 			 * at the top of the list.
2426 			 */
2427 			pv_entry_t *head_pvep = pvh_pve_list(pvh);
2428 			int head_pve_pte_empty_idx;
2429 			if ((head_pve_pte_empty_idx = pve_find_ptep_index(head_pvep, PT_ENTRY_NULL)) != -1) {
2430 				pve_set_ptep(head_pvep, head_pve_pte_empty_idx, pve_get_ptep(pvep, other_pte_idx));
2431 				if (pve_get_altacct(pvep, other_pte_idx)) {
2432 					pve_set_altacct(head_pvep, head_pve_pte_empty_idx);
2433 				}
2434 				pve_remove(pvh, pvepp, pvep);
2435 				pv_free(pvep);
2436 			} else {
2437 				/*
2438 				 * We could not coalesce it. Move it to the start of the list, so that it
2439 				 * can be coalesced against in the future.
2440 				 */
2441 				*pvepp = pve_next(pvep);
2442 				pve_add(pvh, pvep);
2443 			}
2444 		} else if (pve_is_first && pve_is_last) {
2445 			/*
2446 			 * This PVE contains a single mapping, and it's the last mapping for this PAI.
2447 			 * Collapse this list back into the head, turning it into a PVH_TYPE_PTEP entry.
2448 			 */
2449 			pve_remove(pvh, pvepp, pvep);
2450 			pvh_update_head(pvh, pve_get_ptep(pvep, other_pte_idx), PVH_TYPE_PTEP);
2451 			if (pve_get_altacct(pvep, other_pte_idx)) {
2452 				ppattr_set_altacct(pai);
2453 			}
2454 			pv_free(pvep);
2455 		}
2456 
2457 		/**
2458 		 * Removing a PVE entry can clobber the PVH flags if the head itself is
2459 		 * updated (when removing the first PVE in the list) so let's re-set the
2460 		 * flags back to what they should be.
2461 		 */
2462 		if (!pvh_test_type(pvh, PVH_TYPE_NULL)) {
2463 			pvh_set_flags(pvh, pvh_flags);
2464 		}
2465 	} else {
2466 		panic("%s: unexpected PV head %p, ptep=%p pmap=%p pvh=%p pai=0x%x",
2467 		    __func__, *pvh, ptep, pmap, pvh, pai);
2468 	}
2469 
2470 #ifdef PVH_FLAG_EXEC
2471 	/**
2472 	 * If we're on a system that has extra protections around executable pages,
2473 	 * then removing the last mapping to an executable page means we need to
2474 	 * give write-access back to the physical aperture mapping of this page
2475 	 * (write access is removed when a page is executable for security reasons).
2476 	 */
2477 	if ((pvh_flags & PVH_FLAG_EXEC) && pvh_test_type(pvh, PVH_TYPE_NULL)) {
2478 		pmap_set_ptov_ap(pai, AP_RWNA, flush_tlb_async);
2479 	}
2480 #endif /* PVH_FLAG_EXEC */
2481 
2482 	return is_altacct;
2483 }
2484 
2485 /**
2486  * Bootstrap the initial Page Table Descriptor (PTD) node free list.
2487  *
2488  * @note It's not safe to allocate PTD nodes until after this function is
2489  *       invoked.
2490  *
2491  * @note The maximum number of PTD objects that can reside within one page
2492  *       (`ptd_per_page`) must have already been calculated before calling this
2493  *       function.
2494  *
2495  * @param ptdp Pointer to the virtually-contiguous memory used for the initial
2496  *             free list.
2497  * @param num_pages The number of virtually-contiguous pages pointed to by
2498  *                  `ptdp` that will be used to prime the PTD allocator.
2499  */
2500 MARK_AS_PMAP_TEXT void
ptd_bootstrap(pt_desc_t * ptdp,unsigned int num_pages)2501 ptd_bootstrap(pt_desc_t *ptdp, unsigned int num_pages)
2502 {
2503 	assert(ptd_per_page > 0);
2504 	assert((ptdp != NULL) && (((uintptr_t)ptdp & PAGE_MASK) == 0) && (num_pages > 0));
2505 
2506 	queue_init(&pt_page_list);
2507 
2508 	/**
2509 	 * Region represented by ptdp should be cleared by pmap_bootstrap().
2510 	 *
2511 	 * Only part of each page is being used for PTD objects (the rest is used
2512 	 * for each PTD's associated ptd_info_t object) so link together the last
2513 	 * PTD element of each page to the first element of the previous page.
2514 	 */
2515 	for (int i = 0; i < num_pages; i++) {
2516 		*((void**)(&ptdp[ptd_per_page - 1])) = (void*)ptd_free_list;
2517 		ptd_free_list = ptdp;
2518 		ptdp = (void *)(((uint8_t *)ptdp) + PAGE_SIZE);
2519 	}
2520 
2521 	ptd_free_count = num_pages * ptd_per_page;
2522 	simple_lock_init(&ptd_free_list_lock, 0);
2523 }
2524 
2525 /**
2526  * Allocate a page table descriptor (PTD) object from the PTD free list, but
2527  * don't add it to the list of reclaimable userspace page table pages just yet
2528  * and don't associate the PTD with a specific pmap (that's what "unlinked"
2529  * means here).
2530  *
2531  * @note Until a page table's descriptor object is added to the page table list,
2532  *       that table won't be eligible for reclaiming by pmap_page_reclaim().
2533  *
2534  * @return The page table descriptor object if the allocation was successful, or
2535  *         NULL otherwise (which indicates that a page failed to be allocated
2536  *         for new nodes).
2537  */
2538 MARK_AS_PMAP_TEXT pt_desc_t*
ptd_alloc_unlinked(void)2539 ptd_alloc_unlinked(void)
2540 {
2541 	pt_desc_t *ptdp = PTD_ENTRY_NULL;
2542 
2543 	pmap_simple_lock(&ptd_free_list_lock);
2544 
2545 	assert(ptd_per_page != 0);
2546 
2547 	/**
2548 	 * Ensure that we either have a free list with nodes available, or a
2549 	 * completely empty list to allocate and prepend new nodes to.
2550 	 */
2551 	assert(((ptd_free_list != NULL) && (ptd_free_count > 0)) ||
2552 	    ((ptd_free_list == NULL) && (ptd_free_count == 0)));
2553 
2554 	if (__improbable(ptd_free_count == 0)) {
2555 		pmap_paddr_t pa = 0;
2556 
2557 		/* Drop the lock while allocating pages since that can take a while. */
2558 		pmap_simple_unlock(&ptd_free_list_lock);
2559 
2560 		if (pmap_pages_alloc_zeroed(&pa, PAGE_SIZE, PMAP_PAGES_ALLOCATE_NOWAIT) != KERN_SUCCESS) {
2561 			return NULL;
2562 		}
2563 		ptdp = (pt_desc_t *)phystokv(pa);
2564 
2565 		pmap_simple_lock(&ptd_free_list_lock);
2566 
2567 		/**
2568 		 * Since the lock was dropped while allocating, it's possible another
2569 		 * CPU already allocated a page. To be safe, prepend the current free
2570 		 * list (which may or may not be empty now) to the page of nodes just
2571 		 * allocated and update the head to point to these new nodes.
2572 		 */
2573 		*((void**)(&ptdp[ptd_per_page - 1])) = (void*)ptd_free_list;
2574 		ptd_free_list = ptdp;
2575 		ptd_free_count += ptd_per_page;
2576 	}
2577 
2578 	/* There should be available nodes at this point. */
2579 	if (__improbable((ptd_free_count == 0) || (ptd_free_list == PTD_ENTRY_NULL))) {
2580 		panic_plain("%s: out of PTD entries and for some reason didn't "
2581 		    "allocate more %d %p", __func__, ptd_free_count, ptd_free_list);
2582 	}
2583 
2584 	/* Grab the top node off of the free list to return later. */
2585 	ptdp = ptd_free_list;
2586 
2587 	/**
2588 	 * Advance the free list to the next node.
2589 	 *
2590 	 * Each free pt_desc_t-sized object in this free list uses the first few
2591 	 * bytes of the object to point to the next object in the list. When an
2592 	 * object is deallocated (in ptd_deallocate()) the object is prepended onto
2593 	 * the free list by setting its first few bytes to point to the current free
2594 	 * list head. Then the head is updated to point to that object.
2595 	 *
2596 	 * When a new page is allocated for PTD nodes, it's left zeroed out. Once we
2597 	 * use up all of the previously deallocated nodes, the list will point
2598 	 * somewhere into the last allocated, empty page. We know we're pointing at
2599 	 * this page because the first few bytes of the object will be NULL. In
2600 	 * that case just set the head to this empty object.
2601 	 *
2602 	 * This empty page can be thought of as a "reserve" of empty nodes for the
2603 	 * case where more nodes are being allocated than there are nodes being
2604 	 * deallocated.
2605 	 */
2606 	pt_desc_t *const next_node = (pt_desc_t *)(*(void **)ptd_free_list);
2607 
2608 	/**
2609 	 * If the next node in the list is NULL but there are supposed to still be
2610 	 * nodes left, then we've hit the previously allocated empty page of nodes.
2611 	 * Go ahead and advance the free list to the next free node in that page.
2612 	 */
2613 	if ((next_node == PTD_ENTRY_NULL) && (ptd_free_count > 1)) {
2614 		ptd_free_list = ptd_free_list + 1;
2615 	} else {
2616 		ptd_free_list = next_node;
2617 	}
2618 
2619 	ptd_free_count--;
2620 
2621 	pmap_simple_unlock(&ptd_free_list_lock);
2622 
2623 	ptdp->pt_page.next = NULL;
2624 	ptdp->pt_page.prev = NULL;
2625 	ptdp->pmap = NULL;
2626 
2627 	/**
2628 	 * Calculate and stash the address of the ptd_info_t associated with this
2629 	 * PTD. This can be done easily because both structures co-exist in the same
2630 	 * page, with ptd_info_t's starting at a given offset from the start of the
2631 	 * page.
2632 	 *
2633 	 * Each PTD is associated with a ptd_info_t of the same index. For example,
2634 	 * the 15th PTD will use the 15th ptd_info_t in the same page.
2635 	 */
2636 	const unsigned ptd_index = ((uintptr_t)ptdp & PAGE_MASK) / sizeof(pt_desc_t);
2637 	assert(ptd_index < ptd_per_page);
2638 
2639 	const uintptr_t start_of_page = (uintptr_t)ptdp & ~PAGE_MASK;
2640 	ptd_info_t *first_ptd_info = (ptd_info_t *)(start_of_page + ptd_info_offset);
2641 	ptdp->ptd_info = &first_ptd_info[ptd_index * PT_INDEX_MAX];
2642 
2643 	/**
2644 	 * On systems where the VM page size doesn't match the hardware page size,
2645 	 * one PTD might have to manage multiple page tables.
2646 	 */
2647 	for (unsigned int i = 0; i < PT_INDEX_MAX; i++) {
2648 		ptdp->va[i] = (vm_offset_t)-1;
2649 		ptdp->ptd_info[i].refcnt = 0;
2650 		ptdp->ptd_info[i].wiredcnt = 0;
2651 	}
2652 
2653 	return ptdp;
2654 }
2655 
2656 /**
2657  * Allocate a single page table descriptor (PTD) object, and if it's meant to
2658  * keep track of a userspace page table, then add that descriptor object to the
2659  * list of PTDs that can be reclaimed in pmap_page_reclaim().
2660  *
2661  * @param pmap The pmap object that will be owning the page table(s) that this
2662  *             descriptor object represents.
2663  *
2664  * @return The allocated PTD object, or NULL if one failed to get allocated
2665  *         (which indicates that memory wasn't able to get allocated).
2666  */
2667 MARK_AS_PMAP_TEXT pt_desc_t*
ptd_alloc(pmap_t pmap)2668 ptd_alloc(pmap_t pmap)
2669 {
2670 	pt_desc_t *ptdp = ptd_alloc_unlinked();
2671 
2672 	if (ptdp == NULL) {
2673 		return NULL;
2674 	}
2675 
2676 	ptdp->pmap = pmap;
2677 	if (pmap != kernel_pmap) {
2678 		/**
2679 		 * We should never try to reclaim kernel pagetable pages in
2680 		 * pmap_page_reclaim(), so don't enter them into the list.
2681 		 */
2682 		pmap_simple_lock(&pt_pages_lock);
2683 		queue_enter(&pt_page_list, ptdp, pt_desc_t *, pt_page);
2684 		pmap_simple_unlock(&pt_pages_lock);
2685 	}
2686 
2687 	pmap_tt_ledger_credit(pmap, sizeof(*ptdp));
2688 	return ptdp;
2689 }
2690 
2691 /**
2692  * Deallocate a single page table descriptor (PTD) object.
2693  *
2694  * @note Ledger statistics are tracked on a per-pmap basis, so for those pages
2695  *       which are not associated with any specific pmap (e.g., IOMMU pages),
2696  *       the caller must ensure that the pmap/iommu field in the PTD object is
2697  *       NULL before calling this function.
2698  *
2699  * @param ptdp Pointer to the PTD object to deallocate.
2700  */
2701 MARK_AS_PMAP_TEXT void
ptd_deallocate(pt_desc_t * ptdp)2702 ptd_deallocate(pt_desc_t *ptdp)
2703 {
2704 	pmap_t pmap = ptdp->pmap;
2705 
2706 	/**
2707 	 * If this PTD was put onto the reclaimable page table list, then remove it
2708 	 * from that list before deallocating.
2709 	 */
2710 	if (ptdp->pt_page.next != NULL) {
2711 		pmap_simple_lock(&pt_pages_lock);
2712 		queue_remove(&pt_page_list, ptdp, pt_desc_t *, pt_page);
2713 		pmap_simple_unlock(&pt_pages_lock);
2714 	}
2715 
2716 	/* Prepend the deallocated node to the free list. */
2717 	pmap_simple_lock(&ptd_free_list_lock);
2718 	(*(void **)ptdp) = (void *)ptd_free_list;
2719 	ptd_free_list = (pt_desc_t *)ptdp;
2720 	ptd_free_count++;
2721 	pmap_simple_unlock(&ptd_free_list_lock);
2722 
2723 	/**
2724 	 * If this PTD was being used to represent an IOMMU page then there won't be
2725 	 * an associated pmap, and therefore no ledger statistics to update.
2726 	 */
2727 	if (pmap != NULL) {
2728 		pmap_tt_ledger_debit(pmap, sizeof(*ptdp));
2729 	}
2730 }
2731 
2732 /**
2733  * In address spaces where the VM page size is larger than the underlying
2734  * hardware page size, one page table descriptor (PTD) object can represent
2735  * multiple page tables. Some fields (like the reference counts) still need to
2736  * be tracked on a per-page-table basis. Because of this, those values are
2737  * stored in a separate array of ptd_info_t objects within the PTD where there's
2738  * one ptd_info_t for every page table a single PTD can manage.
2739  *
2740  * This function initializes the correct ptd_info_t field within a PTD based on
2741  * the page table it's representing.
2742  *
2743  * @param ptdp Pointer to the PTD object which contains the ptd_info_t field to
2744  *             update. Must match up with the `pmap` and `ptep` parameters.
2745  * @param pmap The pmap that owns the page table managed by the passed in PTD.
2746  * @param va Any virtual address that resides within the virtual address space
2747  *           being mapped by the page table pointed to by `ptep`.
2748  * @param level The level in the page table hierarchy that the table resides.
2749  * @param ptep A pointer into a page table that the passed in PTD manages. This
2750  *             page table must be owned by `pmap` and be the PTE that maps `va`.
2751  */
2752 MARK_AS_PMAP_TEXT void
ptd_info_init(pt_desc_t * ptdp,pmap_t pmap,vm_map_address_t va,unsigned int level,pt_entry_t * ptep)2753 ptd_info_init(
2754 	pt_desc_t *ptdp,
2755 	pmap_t pmap,
2756 	vm_map_address_t va,
2757 	unsigned int level,
2758 	pt_entry_t *ptep)
2759 {
2760 	const pt_attr_t * const pt_attr = pmap_get_pt_attr(pmap);
2761 
2762 	if (ptdp->pmap != pmap) {
2763 		panic("%s: pmap mismatch, ptdp=%p, pmap=%p, va=%p, level=%u, ptep=%p",
2764 		    __func__, ptdp, pmap, (void*)va, level, ptep);
2765 	}
2766 
2767 	/**
2768 	 * Root tables are managed separately, and can be accessed through the
2769 	 * pmap structure itself (there's only one root table per address space).
2770 	 */
2771 	assert(level > pt_attr_root_level(pt_attr));
2772 
2773 	/**
2774 	 * Each PTD can represent multiple page tables. Get the correct index to use
2775 	 * with the per-page-table properties.
2776 	 */
2777 	const unsigned pt_index = ptd_get_index(ptdp, ptep);
2778 
2779 	/**
2780 	 * The "va" field represents the first virtual address that this page table
2781 	 * is translating for. Naturally, this is dependent on the level the page
2782 	 * table resides at since more VA space is mapped the closer the page
2783 	 * table's level is to the root.
2784 	 */
2785 	ptdp->va[pt_index] = (vm_offset_t) va & ~pt_attr_ln_pt_offmask(pt_attr, level - 1);
2786 
2787 	/**
2788 	 * Reference counts are only tracked on CPU leaf tables because those are
2789 	 * the only tables that can be opportunistically deallocated.
2790 	 */
2791 	if (level < pt_attr_leaf_level(pt_attr)) {
2792 		ptdp->ptd_info[pt_index].refcnt = PT_DESC_REFCOUNT;
2793 	}
2794 }
2795 
2796 #if XNU_MONITOR
2797 
2798 /**
2799  * Validate that a pointer passed into the PPL is indeed an actual ledger object
2800  * that was allocated from within the PPL.
2801  *
2802  * If this is truly a real PPL-allocated ledger object then the object will have
2803  * an index into the ledger pointer array located right after it. That index
2804  * into the ledger pointer array should contain the exact same pointer that
2805  * we're validating. This works because the ledger array is PPL-owned data, so
2806  * even if the index was fabricated to try and point to a different ledger
2807  * object, the pointer inside the array won't match up with the passed in
2808  * pointer and validation will fail.
2809  *
2810  * @note This validation does not need to occur on non-PPL systems because on
2811  *       those systems the ledger objects are allocated using a zone allocator.
2812  *
2813  * @param ledger Pointer to the supposed ledger object that we need to validate.
2814  *
2815  * @return The index into the ledger pointer array used to validate the passed
2816  *         in ledger pointer. If the pointer failed to validate, then the system
2817  *         will panic.
2818  */
2819 MARK_AS_PMAP_TEXT uint64_t
pmap_ledger_validate(const volatile void * ledger)2820 pmap_ledger_validate(const volatile void *ledger)
2821 {
2822 	assert(ledger != NULL);
2823 
2824 	uint64_t array_index = ((const volatile pmap_ledger_t*)ledger)->array_index;
2825 
2826 	if (__improbable(array_index >= pmap_ledger_ptr_array_count)) {
2827 		panic("%s: ledger %p array index invalid, index was %#llx", __func__,
2828 		    ledger, array_index);
2829 	}
2830 
2831 	if (__improbable(pmap_ledger_ptr_array[array_index] != ledger)) {
2832 		panic("%s: ledger pointer mismatch, %p != %p", __func__, ledger,
2833 		    pmap_ledger_ptr_array[array_index]);
2834 	}
2835 
2836 	return array_index;
2837 }
2838 
2839 /**
2840  * The size of the ledgers being allocated by the PPL need to be large enough
2841  * to handle ledgers produced by the task_ledgers ledger template. That template
2842  * is dynamically created at runtime so this function is used to verify that the
2843  * real size of a ledger based on the task_ledgers template matches up with the
2844  * amount of space the PPL calculated is required for a single ledger.
2845  *
2846  * @note See the definition of PMAP_LEDGER_DATA_BYTES for more information.
2847  *
2848  * @note This function needs to be called before any ledgers can be allocated.
2849  *
2850  * @param size The actual size that each pmap ledger should be. This is
2851  *             calculated based on the task_ledgers template which should match
2852  *             up with PMAP_LEDGER_DATA_BYTES.
2853  */
2854 MARK_AS_PMAP_TEXT void
pmap_ledger_verify_size_internal(size_t size)2855 pmap_ledger_verify_size_internal(size_t size)
2856 {
2857 	pmap_simple_lock(&pmap_ledger_lock);
2858 
2859 	if (pmap_ledger_size_verified) {
2860 		panic("%s: ledger size already verified, size=%lu", __func__, size);
2861 	}
2862 
2863 	if ((size == 0) || (size > sizeof(pmap_ledger_data_t)) ||
2864 	    ((sizeof(pmap_ledger_data_t) - size) % sizeof(struct ledger_entry))) {
2865 		panic("%s: size mismatch, expected %lu, size=%lu", __func__,
2866 		    PMAP_LEDGER_DATA_BYTES, size);
2867 	}
2868 
2869 	pmap_ledger_size_verified = true;
2870 
2871 	pmap_simple_unlock(&pmap_ledger_lock);
2872 }
2873 
2874 /**
2875  * Allocate a ledger object from the pmap ledger free list and associate it with
2876  * the ledger pointer array so it can be validated when passed into the PPL.
2877  *
2878  * @return Pointer to the successfully allocated ledger object, or NULL if we're
2879  *         out of PPL pages.
2880  */
2881 MARK_AS_PMAP_TEXT ledger_t
pmap_ledger_alloc_internal(void)2882 pmap_ledger_alloc_internal(void)
2883 {
2884 	/**
2885 	 * Ensure that we've double checked the size of the ledger objects we're
2886 	 * allocating before we allocate anything.
2887 	 */
2888 	if (!pmap_ledger_size_verified) {
2889 		panic_plain("%s: Attempted to allocate a pmap ledger before verifying "
2890 		    "the ledger size", __func__);
2891 	}
2892 
2893 	pmap_simple_lock(&pmap_ledger_lock);
2894 	if (pmap_ledger_free_list == NULL) {
2895 		/* The free list is empty, so allocate a page's worth of objects. */
2896 		const pmap_paddr_t paddr = pmap_get_free_ppl_page();
2897 
2898 		if (paddr == 0) {
2899 			pmap_simple_unlock(&pmap_ledger_lock);
2900 			return NULL;
2901 		}
2902 
2903 		const vm_map_address_t vstart = phystokv(paddr);
2904 		const uint32_t ledgers_per_page = PAGE_SIZE / sizeof(pmap_ledger_t);
2905 		const vm_map_address_t vend = vstart + (ledgers_per_page * sizeof(pmap_ledger_t));
2906 		assert(vend > vstart);
2907 
2908 		/**
2909 		 * Loop through every pmap ledger object within the recently allocated
2910 		 * page and add it to both the ledger free list and the ledger pointer
2911 		 * array (which will be used to validate these objects in the future).
2912 		 */
2913 		for (vm_map_address_t vaddr = vstart; vaddr < vend; vaddr += sizeof(pmap_ledger_t)) {
2914 			/* Get the next free entry in the ledger pointer array. */
2915 			const uint64_t index = pmap_ledger_ptr_array_free_index++;
2916 
2917 			if (index >= pmap_ledger_ptr_array_count) {
2918 				panic("%s: pmap_ledger_ptr_array is full, index=%llu",
2919 				    __func__, index);
2920 			}
2921 
2922 			pmap_ledger_t *free_ledger = (pmap_ledger_t*)vaddr;
2923 
2924 			/**
2925 			 * This association between the just allocated ledger and the
2926 			 * pointer array is what allows this object to be validated in the
2927 			 * future that it's indeed a ledger allocated by this code.
2928 			 */
2929 			pmap_ledger_ptr_array[index] = free_ledger;
2930 			free_ledger->array_index = index;
2931 
2932 			/* Prepend this new ledger object to the free list. */
2933 			free_ledger->next = pmap_ledger_free_list;
2934 			pmap_ledger_free_list = free_ledger;
2935 		}
2936 
2937 		/**
2938 		 * In an effort to reduce the amount of ledger code that needs to be
2939 		 * called from within the PPL, the ledger objects themselves are made
2940 		 * kernel writable. This way, all of the initialization and checking of
2941 		 * the ledgers can occur outside of the PPL.
2942 		 *
2943 		 * The only modification to these ledger objects that should occur from
2944 		 * within the PPL is when debiting/crediting the ledgers. And those
2945 		 * operations should only occur on validated ledger objects that are
2946 		 * validated using the ledger pointer array (which is wholly contained
2947 		 * in PPL-owned memory).
2948 		 */
2949 		pa_set_range_xprr_perm(paddr, paddr + PAGE_SIZE, XPRR_PPL_RW_PERM, XPRR_KERN_RW_PERM);
2950 	}
2951 
2952 	ledger_t new_ledger = (ledger_t)pmap_ledger_free_list;
2953 	pmap_ledger_free_list = pmap_ledger_free_list->next;
2954 
2955 	/**
2956 	 * Double check that the array index of the recently allocated object wasn't
2957 	 * tampered with while the object was sitting on the free list.
2958 	 */
2959 	const uint64_t array_index = pmap_ledger_validate(new_ledger);
2960 	os_ref_init(&pmap_ledger_refcnt[array_index], NULL);
2961 
2962 	pmap_simple_unlock(&pmap_ledger_lock);
2963 
2964 	return new_ledger;
2965 }
2966 
2967 /**
2968  * Free a ledger that was previously allocated by the PPL.
2969  *
2970  * @param ledger The ledger to put back onto the pmap ledger free list.
2971  */
2972 MARK_AS_PMAP_TEXT void
pmap_ledger_free_internal(ledger_t ledger)2973 pmap_ledger_free_internal(ledger_t ledger)
2974 {
2975 	/**
2976 	 * A pmap_ledger_t wholly contains a ledger_t as its first member, but also
2977 	 * includes an index into the ledger pointer array used for validation
2978 	 * purposes.
2979 	 */
2980 	pmap_ledger_t *free_ledger = (pmap_ledger_t*)ledger;
2981 
2982 	pmap_simple_lock(&pmap_ledger_lock);
2983 
2984 	/* Ensure that what we're putting onto the free list is a real ledger. */
2985 	const uint64_t array_index = pmap_ledger_validate(ledger);
2986 
2987 	/* Ensure no pmap objects are still using this ledger. */
2988 	if (os_ref_release(&pmap_ledger_refcnt[array_index]) != 0) {
2989 		panic("%s: ledger still referenced, ledger=%p", __func__, ledger);
2990 	}
2991 
2992 	/* Prepend the ledger to the free list. */
2993 	free_ledger->next = pmap_ledger_free_list;
2994 	pmap_ledger_free_list = free_ledger;
2995 
2996 	pmap_simple_unlock(&pmap_ledger_lock);
2997 }
2998 
2999 /**
3000  * Bump the reference count on a ledger object to denote that is currently in
3001  * use by a pmap object.
3002  *
3003  * @param ledger The ledger whose refcnt to increment.
3004  */
3005 MARK_AS_PMAP_TEXT void
pmap_ledger_retain(ledger_t ledger)3006 pmap_ledger_retain(ledger_t ledger)
3007 {
3008 	pmap_simple_lock(&pmap_ledger_lock);
3009 	const uint64_t array_index = pmap_ledger_validate(ledger);
3010 	os_ref_retain(&pmap_ledger_refcnt[array_index]);
3011 	pmap_simple_unlock(&pmap_ledger_lock);
3012 }
3013 
3014 /**
3015  * Decrement the reference count on a ledger object to denote that a pmap object
3016  * that used to use it now isn't.
3017  *
3018  * @param ledger The ledger whose refcnt to decrement.
3019  */
3020 MARK_AS_PMAP_TEXT void
pmap_ledger_release(ledger_t ledger)3021 pmap_ledger_release(ledger_t ledger)
3022 {
3023 	pmap_simple_lock(&pmap_ledger_lock);
3024 	const uint64_t array_index = pmap_ledger_validate(ledger);
3025 	os_ref_release_live(&pmap_ledger_refcnt[array_index]);
3026 	pmap_simple_unlock(&pmap_ledger_lock);
3027 }
3028 
3029 /**
3030  * This function is used to check a ledger that was recently updated (usually
3031  * from within the PPL) and potentially take actions based on the new ledger
3032  * balances (e.g., set an AST).
3033  *
3034  * @note On non-PPL systems this checking occurs automatically every time a
3035  *       ledger is credited/debited. Due to that, this function only needs to
3036  *       get called on PPL-enabled systems.
3037  *
3038  * @note This function can ONLY be called from *outside* of the PPL due to its
3039  *       usage of current_thread(). The TPIDR register is kernel-modifiable, and
3040  *       hence can't be trusted. This also means we don't need to pull all of
3041  *       the logic used to check ledger balances into the PPL.
3042  *
3043  * @param pmap The pmap whose ledger should be checked.
3044  */
3045 void
pmap_ledger_check_balance(pmap_t pmap)3046 pmap_ledger_check_balance(pmap_t pmap)
3047 {
3048 	/* This function should only be called from outside of the PPL. */
3049 	assert((pmap != NULL) && !pmap_in_ppl());
3050 
3051 	ledger_t ledger = pmap->ledger;
3052 
3053 	if (ledger == NULL) {
3054 		return;
3055 	}
3056 
3057 	thread_t cur_thread = current_thread();
3058 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.alternate_accounting);
3059 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.alternate_accounting_compressed);
3060 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.internal);
3061 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.internal_compressed);
3062 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.page_table);
3063 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.phys_footprint);
3064 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.phys_mem);
3065 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.tkm_private);
3066 	ledger_check_new_balance(cur_thread, ledger, task_ledgers.wired_mem);
3067 }
3068 
3069 #endif /* XNU_MONITOR */
3070 
3071 /**
3072  * Credit a specific ledger entry within the passed in pmap's ledger object.
3073  *
3074  * @note On PPL-enabled systems this operation will not automatically check the
3075  *       ledger balances after updating. A call to pmap_ledger_check_balance()
3076  *       will need to occur outside of the PPL to handle this.
3077  *
3078  * @param pmap The pmap whose ledger should be updated.
3079  * @param entry The specifc ledger entry to update. This needs to be one of the
3080  *              task_ledger entries.
3081  * @param amount The amount to credit from the ledger.
3082  *
3083  * @return The return value from the credit operation.
3084  */
3085 kern_return_t
pmap_ledger_credit(pmap_t pmap,int entry,ledger_amount_t amount)3086 pmap_ledger_credit(pmap_t pmap, int entry, ledger_amount_t amount)
3087 {
3088 	assert(pmap != NULL);
3089 
3090 #if XNU_MONITOR
3091 	/**
3092 	 * On PPL-enabled systems the "nocheck" variant MUST be called to ensure
3093 	 * that the ledger balance doesn't automatically get checked after being
3094 	 * updated.
3095 	 *
3096 	 * That checking process is unsafe to perform within the PPL due to its
3097 	 * reliance on current_thread().
3098 	 */
3099 	return ledger_credit_nocheck(pmap->ledger, entry, amount);
3100 #else /* XNU_MONITOR */
3101 	return ledger_credit(pmap->ledger, entry, amount);
3102 #endif /* XNU_MONITOR */
3103 }
3104 
3105 /**
3106  * Debit a specific ledger entry within the passed in pmap's ledger object.
3107  *
3108  * @note On PPL-enabled systems this operation will not automatically check the
3109  *       ledger balances after updating. A call to pmap_ledger_check_balance()
3110  *       will need to occur outside of the PPL to handle this.
3111  *
3112  * @param pmap The pmap whose ledger should be updated.
3113  * @param entry The specifc ledger entry to update. This needs to be one of the
3114  *              task_ledger entries.
3115  * @param amount The amount to debit from the ledger.
3116  *
3117  * @return The return value from the debit operation.
3118  */
3119 kern_return_t
pmap_ledger_debit(pmap_t pmap,int entry,ledger_amount_t amount)3120 pmap_ledger_debit(pmap_t pmap, int entry, ledger_amount_t amount)
3121 {
3122 	assert(pmap != NULL);
3123 
3124 #if XNU_MONITOR
3125 	/**
3126 	 * On PPL-enabled systems the "nocheck" variant MUST be called to ensure
3127 	 * that the ledger balance doesn't automatically get checked after being
3128 	 * updated.
3129 	 *
3130 	 * That checking process is unsafe to perform within the PPL due to its
3131 	 * reliance on current_thread().
3132 	 */
3133 	return ledger_debit_nocheck(pmap->ledger, entry, amount);
3134 #else /* XNU_MONITOR */
3135 	return ledger_debit(pmap->ledger, entry, amount);
3136 #endif /* XNU_MONITOR */
3137 }
3138 
3139 #if XNU_MONITOR
3140 
3141 /**
3142  * Allocate a pmap object from the pmap object free list and associate it with
3143  * the pmap pointer array so it can be validated when passed into the PPL.
3144  *
3145  * @param pmap Output parameter that holds the newly allocated pmap object if
3146  *             the operation was successful, or NULL otherwise. The return value
3147  *             must be checked to know what this parameter should return.
3148  *
3149  * @return KERN_SUCCESS if the allocation was successful, KERN_RESOURCE_SHORTAGE
3150  *         if out of free PPL pages, or KERN_NO_SPACE if more pmap objects were
3151  *         trying to be allocated than the pmap pointer array could manage. On
3152  *         KERN_SUCCESS, the `pmap` output parameter will point to the newly
3153  *         allocated object.
3154  */
3155 MARK_AS_PMAP_TEXT kern_return_t
pmap_alloc_pmap(pmap_t * pmap)3156 pmap_alloc_pmap(pmap_t *pmap)
3157 {
3158 	pmap_t new_pmap = PMAP_NULL;
3159 	kern_return_t kr = KERN_SUCCESS;
3160 
3161 	pmap_simple_lock(&pmap_free_list_lock);
3162 
3163 	if (pmap_free_list == NULL) {
3164 		/* If the pmap pointer array is full, then no more objects can be allocated. */
3165 		if (__improbable(pmap_ptr_array_free_index == pmap_ptr_array_count)) {
3166 			kr = KERN_NO_SPACE;
3167 			goto pmap_alloc_cleanup;
3168 		}
3169 
3170 		/* The free list is empty, so allocate a page's worth of objects. */
3171 		const pmap_paddr_t paddr = pmap_get_free_ppl_page();
3172 
3173 		if (paddr == 0) {
3174 			kr = KERN_RESOURCE_SHORTAGE;
3175 			goto pmap_alloc_cleanup;
3176 		}
3177 
3178 		const vm_map_address_t vstart = phystokv(paddr);
3179 		const uint32_t pmaps_per_page = PAGE_SIZE / sizeof(pmap_list_entry_t);
3180 		const vm_map_address_t vend = vstart + (pmaps_per_page * sizeof(pmap_list_entry_t));
3181 		assert(vend > vstart);
3182 
3183 		/**
3184 		 * Loop through every pmap object within the recently allocated page and
3185 		 * add it to both the pmap free list and the pmap pointer array (which
3186 		 * will be used to validate these objects in the future).
3187 		 */
3188 		for (vm_map_address_t vaddr = vstart; vaddr < vend; vaddr += sizeof(pmap_list_entry_t)) {
3189 			/* Get the next free entry in the pmap pointer array. */
3190 			const unsigned long index = pmap_ptr_array_free_index++;
3191 
3192 			if (__improbable(index >= pmap_ptr_array_count)) {
3193 				panic("%s: pmap array index %lu >= limit %lu; corruption?",
3194 				    __func__, index, pmap_ptr_array_count);
3195 			}
3196 			pmap_list_entry_t *free_pmap = (pmap_list_entry_t*)vaddr;
3197 			os_atomic_init(&free_pmap->pmap.ref_count, 0);
3198 
3199 			/**
3200 			 * This association between the just allocated pmap object and the
3201 			 * pointer array is what allows this object to be validated in the
3202 			 * future that it's indeed a pmap object allocated by this code.
3203 			 */
3204 			pmap_ptr_array[index] = free_pmap;
3205 			free_pmap->array_index = index;
3206 
3207 			/* Prepend this new pmap object to the free list. */
3208 			free_pmap->next = pmap_free_list;
3209 			pmap_free_list = free_pmap;
3210 
3211 			/* Check if we've reached the maximum number of pmap objects. */
3212 			if (__improbable(pmap_ptr_array_free_index == pmap_ptr_array_count)) {
3213 				break;
3214 			}
3215 		}
3216 	}
3217 
3218 	new_pmap = &pmap_free_list->pmap;
3219 	pmap_free_list = pmap_free_list->next;
3220 
3221 pmap_alloc_cleanup:
3222 	pmap_simple_unlock(&pmap_free_list_lock);
3223 	*pmap = new_pmap;
3224 	return kr;
3225 }
3226 
3227 /**
3228  * Free a pmap object that was previously allocated by the PPL.
3229  *
3230  * @note This should only be called on pmap objects that have already been
3231  *       validated to be real pmap objects.
3232  *
3233  * @param pmap The pmap object to put back onto the pmap free.
3234  */
3235 MARK_AS_PMAP_TEXT void
pmap_free_pmap(pmap_t pmap)3236 pmap_free_pmap(pmap_t pmap)
3237 {
3238 	/**
3239 	 * A pmap_list_entry_t wholly contains a struct pmap as its first member,
3240 	 * but also includes an index into the pmap pointer array used for
3241 	 * validation purposes.
3242 	 */
3243 	pmap_list_entry_t *free_pmap = (pmap_list_entry_t*)pmap;
3244 	if (__improbable(free_pmap->array_index >= pmap_ptr_array_count)) {
3245 		panic("%s: pmap %p has index %lu >= limit %lu", __func__, pmap,
3246 		    free_pmap->array_index, pmap_ptr_array_count);
3247 	}
3248 
3249 	pmap_simple_lock(&pmap_free_list_lock);
3250 
3251 	/* Prepend the pmap object to the free list. */
3252 	free_pmap->next = pmap_free_list;
3253 	pmap_free_list = free_pmap;
3254 
3255 	pmap_simple_unlock(&pmap_free_list_lock);
3256 }
3257 
3258 #endif /* XNU_MONITOR */
3259 
3260 #if XNU_MONITOR
3261 
3262 /**
3263  * Helper function to validate that the pointer passed into this method is truly
3264  * a userspace pmap object that was allocated through the pmap_alloc_pmap() API.
3265  * This function will panic if the validation fails.
3266  *
3267  * @param pmap The pointer to validate.
3268  * @param func The stringized function name of the caller that will be printed
3269  *             in the case that the validation fails.
3270  */
3271 static void
validate_user_pmap(const volatile struct pmap * pmap,const char * func)3272 validate_user_pmap(const volatile struct pmap *pmap, const char *func)
3273 {
3274 	/**
3275 	 * Ensure the array index isn't corrupted. This could happen if an attacker
3276 	 * is trying to pass off random memory as a pmap object.
3277 	 */
3278 	const unsigned long array_index = ((const volatile pmap_list_entry_t*)pmap)->array_index;
3279 	if (__improbable(array_index >= pmap_ptr_array_count)) {
3280 		panic("%s: pmap array index %lu >= limit %lu", func, array_index, pmap_ptr_array_count);
3281 	}
3282 
3283 	/**
3284 	 * If the array index is valid, then ensure that the passed in object
3285 	 * matches up with the object in the pmap pointer array for this index. Even
3286 	 * if an attacker passed in random memory with a valid index, there's no way
3287 	 * the pmap pointer array will ever point to anything but the objects
3288 	 * allocated by the pmap free list (it's PPL-owned memory).
3289 	 */
3290 	if (__improbable(pmap_ptr_array[array_index] != (const volatile pmap_list_entry_t*)pmap)) {
3291 		panic("%s: pmap %p does not match array element %p at index %lu", func, pmap,
3292 		    pmap_ptr_array[array_index], array_index);
3293 	}
3294 
3295 	/**
3296 	 * Ensure that this isn't just an object sitting on the free list waiting to
3297 	 * be allocated. This also helps protect against a race between validating
3298 	 * and deleting a pmap object.
3299 	 */
3300 	if (__improbable(os_atomic_load(&pmap->ref_count, seq_cst) <= 0)) {
3301 		panic("%s: pmap %p is not in use", func, pmap);
3302 	}
3303 }
3304 
3305 #endif /* XNU_MONITOR */
3306 
3307 /**
3308  * Validate that the pointer passed into this method is a valid pmap object and
3309  * is safe to read from and base PPL decisions off of. This function will panic
3310  * if the validation fails.
3311  *
3312  * @note On non-PPL systems this only checks that the pmap object isn't NULL.
3313  *
3314  * @note This validation should only be used on objects that won't be written to
3315  *       for the duration of the PPL call. If the object is going to be modified
3316  *       then you must use validate_pmap_mutable().
3317  *
3318  * @param pmap The pointer to validate.
3319  * @param func The stringized function name of the caller that will be printed
3320  *             in the case that the validation fails.
3321  */
3322 void
validate_pmap_internal(const volatile struct pmap * pmap,const char * func)3323 validate_pmap_internal(const volatile struct pmap *pmap, const char *func)
3324 {
3325 #if !XNU_MONITOR
3326 	#pragma unused(pmap, func)
3327 	assert(pmap != NULL);
3328 #else /* !XNU_MONITOR */
3329 	if (pmap != kernel_pmap) {
3330 		validate_user_pmap(pmap, func);
3331 	}
3332 #endif /* !XNU_MONITOR */
3333 }
3334 
3335 /**
3336  * Validate that the pointer passed into this method is a valid pmap object and
3337  * is safe to both read and write to from within the PPL. This function will
3338  * panic if the validation fails.
3339  *
3340  * @note On non-PPL systems this only checks that the pmap object isn't NULL.
3341  *
3342  * @note If you're only going to be reading from the pmap object for the
3343  *       duration of the PPL call, it'll be faster to use the immutable version
3344  *       of this validation: validate_pmap().
3345  *
3346  * @param pmap The pointer to validate.
3347  * @param func The stringized function name of the caller that will be printed
3348  *             in the case that the validation fails.
3349  */
3350 void
validate_pmap_mutable_internal(const volatile struct pmap * pmap,const char * func)3351 validate_pmap_mutable_internal(const volatile struct pmap *pmap, const char *func)
3352 {
3353 #if !XNU_MONITOR
3354 	#pragma unused(pmap, func)
3355 	assert(pmap != NULL);
3356 #else /* !XNU_MONITOR */
3357 	if (pmap != kernel_pmap) {
3358 		/**
3359 		 * Every time a pmap object is validated to be mutable, we mark it down
3360 		 * as an "inflight" pmap on this CPU. The inflight pmap for this CPU
3361 		 * will be set to NULL automatically when the PPL is exited. The
3362 		 * pmap_destroy() path will ensure that no "inflight" pmaps (on any CPU)
3363 		 * are ever destroyed so as to prevent racy use-after-free attacks.
3364 		 */
3365 		pmap_cpu_data_t *cpu_data = pmap_get_cpu_data();
3366 
3367 		/**
3368 		 * As a sanity check (since the inflight pmap should be cleared when
3369 		 * exiting the PPL), ensure that the previous inflight pmap is NULL, or
3370 		 * is the same as the one being validated here (which allows for
3371 		 * validating the same object twice).
3372 		 */
3373 		__assert_only const volatile struct pmap *prev_inflight_pmap =
3374 		    os_atomic_load(&cpu_data->inflight_pmap, relaxed);
3375 		assert((prev_inflight_pmap == NULL) || (prev_inflight_pmap == pmap));
3376 
3377 		/**
3378 		 * The release barrier here is intended to pair with the seq_cst load of
3379 		 * ref_count in validate_user_pmap() to ensure that if a pmap is
3380 		 * concurrently destroyed, either this path will observe that it was
3381 		 * destroyed after marking it in-flight and panic, or pmap_destroy will
3382 		 * observe the pmap as in-flight after decrementing ref_count and panic.
3383 		 */
3384 		os_atomic_store(&cpu_data->inflight_pmap, pmap, release);
3385 
3386 		validate_user_pmap(pmap, func);
3387 	}
3388 #endif /* !XNU_MONITOR */
3389 }
3390 
3391 /**
3392  * Validate that the passed in pmap pointer is a pmap object that was allocated
3393  * by the pmap and not just random memory. On PPL-enabled systems, the
3394  * allocation is done through the pmap_alloc_pmap() API. On all other systems
3395  * it's allocated through a zone allocator.
3396  *
3397  * This function will panic if the validation fails.
3398  *
3399  * @param pmap The object to validate.
3400  */
3401 void
pmap_require(pmap_t pmap)3402 pmap_require(pmap_t pmap)
3403 {
3404 #if XNU_MONITOR
3405 	validate_pmap(pmap);
3406 #else /* XNU_MONITOR */
3407 	if (pmap != kernel_pmap) {
3408 		zone_id_require(ZONE_ID_PMAP, sizeof(struct pmap), pmap);
3409 	}
3410 #endif /* XNU_MONITOR */
3411 }
3412 
3413 /**
3414  * Parse the device tree and determine how many pmap-io-ranges there are and
3415  * how much memory is needed to store all of that data.
3416  *
3417  * @note See the definition of pmap_io_range_t for more information on what a
3418  *       "pmap-io-range" actually represents.
3419  *
3420  * @return The number of bytes needed to store metadata for all PPL-owned I/O
3421  *         regions.
3422  */
3423 vm_size_t
pmap_compute_io_rgns(void)3424 pmap_compute_io_rgns(void)
3425 {
3426 	DTEntry entry = NULL;
3427 	__assert_only int err = SecureDTLookupEntry(NULL, "/defaults", &entry);
3428 	assert(err == kSuccess);
3429 
3430 	void const *prop = NULL;
3431 	unsigned int prop_size = 0;
3432 	if (kSuccess != SecureDTGetProperty(entry, "pmap-io-ranges", &prop, &prop_size)) {
3433 		return 0;
3434 	}
3435 
3436 	/**
3437 	 * The device tree node for pmap-io-ranges maps directly onto an array of
3438 	 * pmap_io_range_t structures.
3439 	 */
3440 	pmap_io_range_t const *ranges = prop;
3441 
3442 	/* Determine the number of regions and validate the fields. */
3443 	for (unsigned int i = 0; i < (prop_size / sizeof(*ranges)); ++i) {
3444 		if (ranges[i].addr & PAGE_MASK) {
3445 			panic("%s: %u addr 0x%llx is not page-aligned",
3446 			    __func__, i, ranges[i].addr);
3447 		}
3448 
3449 		if (ranges[i].len & PAGE_MASK) {
3450 			panic("%s: %u length 0x%llx is not page-aligned",
3451 			    __func__, i, ranges[i].len);
3452 		}
3453 
3454 		uint64_t rgn_end = 0;
3455 		if (os_add_overflow(ranges[i].addr, ranges[i].len, &rgn_end)) {
3456 			panic("%s: %u addr 0x%llx length 0x%llx wraps around",
3457 			    __func__, i, ranges[i].addr, ranges[i].len);
3458 		}
3459 
3460 		if (((ranges[i].addr <= gPhysBase) && (rgn_end > gPhysBase)) ||
3461 		    ((ranges[i].addr < avail_end) && (rgn_end >= avail_end)) ||
3462 		    ((ranges[i].addr > gPhysBase) && (rgn_end < avail_end))) {
3463 			panic("%s: %u addr 0x%llx length 0x%llx overlaps physical memory",
3464 			    __func__, i, ranges[i].addr, ranges[i].len);
3465 		}
3466 
3467 		++num_io_rgns;
3468 	}
3469 
3470 	return num_io_rgns * sizeof(*ranges);
3471 }
3472 
3473 /**
3474  * Helper function used when sorting and searching PPL I/O ranges.
3475  *
3476  * @param a The first PPL I/O range to compare.
3477  * @param b The second PPL I/O range to compare.
3478  *
3479  * @return < 0 for a < b
3480  *           0 for a == b
3481  *         > 0 for a > b
3482  */
3483 static int
cmp_io_rgns(const void * a,const void * b)3484 cmp_io_rgns(const void *a, const void *b)
3485 {
3486 	const pmap_io_range_t *range_a = a;
3487 	const pmap_io_range_t *range_b = b;
3488 
3489 	if ((range_b->addr + range_b->len) <= range_a->addr) {
3490 		return 1;
3491 	} else if ((range_a->addr + range_a->len) <= range_b->addr) {
3492 		return -1;
3493 	} else {
3494 		return 0;
3495 	}
3496 }
3497 
3498 /**
3499  * Now that enough memory has been allocated to store all of the pmap-io-ranges
3500  * device tree nodes in memory, go ahead and do that copy and then sort the
3501  * resulting array by address for quicker lookup later.
3502  *
3503  * @note This function assumes that the amount of memory required to store the
3504  *       entire pmap-io-ranges device tree node has already been calculated (via
3505  *       pmap_compute_io_rgns()) and allocated in io_attr_table.
3506  *
3507  * @note This function will leave io_attr_table sorted by address to allow for
3508  *       performing a binary search when doing future range lookups.
3509  */
3510 void
pmap_load_io_rgns(void)3511 pmap_load_io_rgns(void)
3512 {
3513 	if (num_io_rgns == 0) {
3514 		return;
3515 	}
3516 
3517 	DTEntry entry = NULL;
3518 	int err = SecureDTLookupEntry(NULL, "/defaults", &entry);
3519 	assert(err == kSuccess);
3520 
3521 	void const *prop = NULL;
3522 	unsigned int prop_size;
3523 	err = SecureDTGetProperty(entry, "pmap-io-ranges", &prop, &prop_size);
3524 	assert(err == kSuccess);
3525 
3526 	pmap_io_range_t const *ranges = prop;
3527 	for (unsigned int i = 0; i < (prop_size / sizeof(*ranges)); ++i) {
3528 		io_attr_table[i] = ranges[i];
3529 	}
3530 
3531 	qsort(io_attr_table, num_io_rgns, sizeof(*ranges), cmp_io_rgns);
3532 }
3533 
3534 /**
3535  * Find and return the PPL I/O range that contains the passed in physical
3536  * address.
3537  *
3538  * @note This function performs a binary search on the already sorted
3539  *       io_attr_table, so it should be reasonably fast.
3540  *
3541  * @param paddr The physical address to query a specific I/O range for.
3542  *
3543  * @return A pointer to the pmap_io_range_t structure if one of the ranges
3544  *         contains the passed in physical address. Otherwise, NULL.
3545  */
3546 pmap_io_range_t*
pmap_find_io_attr(pmap_paddr_t paddr)3547 pmap_find_io_attr(pmap_paddr_t paddr)
3548 {
3549 	unsigned int begin = 0;
3550 	unsigned int end = num_io_rgns - 1;
3551 
3552 	/**
3553 	 * If there are no I/O ranges, or the wanted address is below the lowest
3554 	 * range or above the highest range, then there's no point in searching
3555 	 * since it won't be here.
3556 	 */
3557 	if ((num_io_rgns == 0) || (paddr < io_attr_table[begin].addr) ||
3558 	    (paddr >= (io_attr_table[end].addr + io_attr_table[end].len))) {
3559 		return NULL;
3560 	}
3561 
3562 	/**
3563 	 * A dummy I/O range to compare against when searching for a range that
3564 	 * includes `paddr`.
3565 	 */
3566 	const pmap_io_range_t wanted_range = {
3567 		.addr = paddr & ~PAGE_MASK,
3568 		.len = PAGE_SIZE
3569 	};
3570 
3571 	/* Perform a binary search to find the wanted I/O range. */
3572 	for (;;) {
3573 		const unsigned int middle = (begin + end) / 2;
3574 		const int cmp = cmp_io_rgns(&wanted_range, &io_attr_table[middle]);
3575 
3576 		if (cmp == 0) {
3577 			/* Success! Found the wanted I/O range. */
3578 			return &io_attr_table[middle];
3579 		} else if (begin == end) {
3580 			/* We've checked every range and didn't find a match. */
3581 			break;
3582 		} else if (cmp > 0) {
3583 			/* The wanted range is above the middle. */
3584 			begin = middle + 1;
3585 		} else {
3586 			/* The wanted range is below the middle. */
3587 			end = middle;
3588 		}
3589 	}
3590 
3591 	return NULL;
3592 }
3593 
3594 /**
3595  * Initialize the pmap per-CPU data structure for a single CPU. This is called
3596  * once for each CPU in the system, on the CPU whose per-cpu data needs to be
3597  * initialized.
3598  *
3599  * In reality, many of the per-cpu data fields will have either already been
3600  * initialized or will rely on the fact that the per-cpu data is either zeroed
3601  * out during allocation (on non-PPL systems), or the data itself is a global
3602  * variable which will be zeroed by default (on PPL systems).
3603  *
3604  * @param cpu_number The number of the CPU whose pmap per-cpu data should be
3605  *                   initialized. This number should correspond to the CPU
3606  *                   executing this code.
3607  */
3608 MARK_AS_PMAP_TEXT void
pmap_cpu_data_init_internal(unsigned int cpu_number)3609 pmap_cpu_data_init_internal(unsigned int cpu_number)
3610 {
3611 	pmap_cpu_data_t *pmap_cpu_data = pmap_get_cpu_data();
3612 
3613 #if XNU_MONITOR
3614 	/* Verify the per-cpu data is cacheline-aligned. */
3615 	assert(((vm_offset_t)pmap_cpu_data & (MAX_L2_CLINE_BYTES - 1)) == 0);
3616 
3617 	/**
3618 	 * The CPU number should already have been initialized to
3619 	 * PMAP_INVALID_CPU_NUM when initializing the boot CPU data.
3620 	 */
3621 	if (pmap_cpu_data->cpu_number != PMAP_INVALID_CPU_NUM) {
3622 		panic("%s: pmap_cpu_data->cpu_number=%u, cpu_number=%u",
3623 		    __func__, pmap_cpu_data->cpu_number, cpu_number);
3624 	}
3625 #endif /* XNU_MONITOR */
3626 
3627 	/**
3628 	 * At least when operating in the PPL, it's important to duplicate the CPU
3629 	 * number into a PPL-owned location. If we relied strictly on the CPU number
3630 	 * located in the general machine-specific per-cpu data, it could be
3631 	 * modified in a way to affect PPL operation.
3632 	 */
3633 	pmap_cpu_data->cpu_number = cpu_number;
3634 #if __ARM_MIXED_PAGE_SIZE__
3635 	pmap_cpu_data->commpage_page_shift = PAGE_SHIFT;
3636 #endif
3637 }
3638 
3639 /**
3640  * Initialize the pmap per-cpu data for the bootstrap CPU (the other CPUs should
3641  * just call pmap_cpu_data_init() directly). This code does one of two things
3642  * depending on whether this is a PPL-enabled system.
3643  *
3644  * PPL-enabled: This function will setup the PPL-specific per-cpu data like the
3645  *              PPL stacks and register save area. This performs the
3646  *              functionality usually done by cpu_data_init() to setup the pmap
3647  *              per-cpu data fields. In reality, most fields are not initialized
3648  *              and are assumed to be zero thanks to this data being global.
3649  *
3650  * Non-PPL: Just calls pmap_cpu_data_init() to initialize the bootstrap CPU's
3651  *          pmap per-cpu data (non-boot CPUs will call that function once they
3652  *          come out of reset).
3653  *
3654  * @note This function will carve out physical pages for the PPL stacks and PPL
3655  *       register save area from avail_start. It's assumed that avail_start is
3656  *       on a page boundary before executing this function on PPL-enabled
3657  *       systems.
3658  */
3659 void
pmap_cpu_data_array_init(void)3660 pmap_cpu_data_array_init(void)
3661 {
3662 #if XNU_MONITOR
3663 	/**
3664 	 * Enough virtual address space to cover all PPL stacks for every CPU should
3665 	 * have already been allocated by arm_vm_init() before pmap_boostrap() is
3666 	 * called.
3667 	 */
3668 	assert((pmap_stacks_start != NULL) && (pmap_stacks_end != NULL));
3669 	assert(((uintptr_t)pmap_stacks_end - (uintptr_t)pmap_stacks_start) == PPL_STACK_REGION_SIZE);
3670 
3671 	/**
3672 	 * Ensure avail_start is aligned to a page boundary before allocating the
3673 	 * stacks and register save area.
3674 	 */
3675 	assert(avail_start == round_page(avail_start));
3676 
3677 	/* Each PPL stack contains guard pages before and after. */
3678 	vm_offset_t stack_va = (vm_offset_t)pmap_stacks_start + ARM_PGBYTES;
3679 
3680 	/**
3681 	 * Globally save off the beginning of the PPL stacks physical space so that
3682 	 * we can update its physical aperture mappings in later in the bootstrap
3683 	 * process.
3684 	 */
3685 	pmap_stacks_start_pa = avail_start;
3686 
3687 	/* Map the PPL stacks for each CPU. */
3688 	for (unsigned int cpu_num = 0; cpu_num < MAX_CPUS; cpu_num++) {
3689 		/**
3690 		 * The PPL stack size is based off of the VM page size, which may differ
3691 		 * from the underlying hardware page size.
3692 		 *
3693 		 * Map all of the PPL stack into the kernel's address space.
3694 		 */
3695 		for (vm_offset_t cur_va = stack_va; cur_va < (stack_va + PPL_STACK_SIZE); cur_va += ARM_PGBYTES) {
3696 			assert(cur_va < (vm_offset_t)pmap_stacks_end);
3697 
3698 			pt_entry_t *ptep = pmap_pte(kernel_pmap, cur_va);
3699 			assert(*ptep == ARM_PTE_EMPTY);
3700 
3701 			pt_entry_t template = pa_to_pte(avail_start) | ARM_PTE_AF | ARM_PTE_SH(SH_OUTER_MEMORY) |
3702 			    ARM_PTE_TYPE | ARM_PTE_ATTRINDX(CACHE_ATTRINDX_DEFAULT) | xprr_perm_to_pte(XPRR_PPL_RW_PERM);
3703 
3704 #if __ARM_KERNEL_PROTECT__
3705 			/**
3706 			 * On systems with software based spectre/meltdown mitigations,
3707 			 * kernel mappings are explicitly not made global because the kernel
3708 			 * is unmapped when executing in EL0 (this ensures that kernel TLB
3709 			 * entries won't accidentally be valid in EL0).
3710 			 */
3711 			template |= ARM_PTE_NG;
3712 #endif /* __ARM_KERNEL_PROTECT__ */
3713 
3714 			write_pte(ptep, template);
3715 			__builtin_arm_isb(ISB_SY);
3716 
3717 			avail_start += ARM_PGBYTES;
3718 		}
3719 
3720 #if KASAN
3721 		kasan_map_shadow(stack_va, PPL_STACK_SIZE, false);
3722 #endif /* KASAN */
3723 
3724 		/**
3725 		 * Setup non-zero pmap per-cpu data fields. If the default value should
3726 		 * be zero, then you can assume the field is already set to that.
3727 		 */
3728 		pmap_cpu_data_array[cpu_num].cpu_data.cpu_number = PMAP_INVALID_CPU_NUM;
3729 		pmap_cpu_data_array[cpu_num].cpu_data.ppl_state = PPL_STATE_KERNEL;
3730 		pmap_cpu_data_array[cpu_num].cpu_data.ppl_stack = (void*)(stack_va + PPL_STACK_SIZE);
3731 
3732 		/**
3733 		 * Get the first VA of the next CPU's PPL stack. Need to skip the guard
3734 		 * page after the stack.
3735 		 */
3736 		stack_va += (PPL_STACK_SIZE + ARM_PGBYTES);
3737 	}
3738 
3739 	pmap_stacks_end_pa = avail_start;
3740 
3741 	/**
3742 	 * The PPL register save area location is saved into global variables so
3743 	 * that they can be made writable if DTrace support is needed. This is
3744 	 * needed because DTrace will try to update the register state.
3745 	 */
3746 	ppl_cpu_save_area_start = avail_start;
3747 	ppl_cpu_save_area_end = ppl_cpu_save_area_start;
3748 	pmap_paddr_t ppl_cpu_save_area_cur = ppl_cpu_save_area_start;
3749 
3750 	/* Carve out space for the PPL register save area for each CPU. */
3751 	for (unsigned int cpu_num = 0; cpu_num < MAX_CPUS; cpu_num++) {
3752 		/* Allocate enough space to cover at least one arm_context_t object. */
3753 		while ((ppl_cpu_save_area_end - ppl_cpu_save_area_cur) < sizeof(arm_context_t)) {
3754 			avail_start += PAGE_SIZE;
3755 			ppl_cpu_save_area_end = avail_start;
3756 		}
3757 
3758 		pmap_cpu_data_array[cpu_num].cpu_data.save_area = (arm_context_t *)phystokv(ppl_cpu_save_area_cur);
3759 		ppl_cpu_save_area_cur += sizeof(arm_context_t);
3760 	}
3761 #endif /* XNU_MONITOR */
3762 
3763 	pmap_cpu_data_init();
3764 }
3765 
3766 /**
3767  * Retrieve the pmap per-cpu data for the current CPU. On PPL-enabled systems
3768  * this data is managed separately from the general machine-specific per-cpu
3769  * data to handle the requirement that it must only be PPL-writable.
3770  *
3771  * @return The per-cpu pmap data for the current CPU.
3772  */
3773 pmap_cpu_data_t *
pmap_get_cpu_data(void)3774 pmap_get_cpu_data(void)
3775 {
3776 	pmap_cpu_data_t *pmap_cpu_data = NULL;
3777 
3778 #if XNU_MONITOR
3779 	extern pmap_cpu_data_t* ml_get_ppl_cpu_data(void);
3780 	pmap_cpu_data = ml_get_ppl_cpu_data();
3781 #else /* XNU_MONITOR */
3782 	/**
3783 	 * On non-PPL systems, the pmap per-cpu data is stored in the general
3784 	 * machine-specific per-cpu data.
3785 	 */
3786 	pmap_cpu_data = &getCpuDatap()->cpu_pmap_cpu_data;
3787 #endif /* XNU_MONITOR */
3788 
3789 	return pmap_cpu_data;
3790 }
3791 
3792 /**
3793  * Retrieve the pmap per-cpu data for the specified cpu index.
3794  *
3795  * @return The per-cpu pmap data for the CPU
3796  */
3797 pmap_cpu_data_t *
pmap_get_remote_cpu_data(unsigned int cpu)3798 pmap_get_remote_cpu_data(unsigned int cpu)
3799 {
3800 #if XNU_MONITOR
3801 	assert(cpu < MAX_CPUS);
3802 	return &pmap_cpu_data_array[cpu].cpu_data;
3803 #else
3804 	cpu_data_t *cpu_data = cpu_datap((int)cpu);
3805 	if (cpu_data == NULL) {
3806 		return NULL;
3807 	} else {
3808 		return &cpu_data->cpu_pmap_cpu_data;
3809 	}
3810 #endif
3811 }
3812