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