1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * @OSF_COPYRIGHT@
30 */
31 /*
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34 * All Rights Reserved.
35 *
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
41 *
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45 *
46 * Carnegie Mellon requests users of this software to return to
47 *
48 * Software Distribution Coordinator or [email protected]
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
52 *
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
55 */
56 /*
57 */
58 /*
59 * File: kern/zalloc.c
60 * Author: Avadis Tevanian, Jr.
61 *
62 * Zone-based memory allocator. A zone is a collection of fixed size
63 * data blocks for which quick allocation/deallocation is possible.
64 */
65
66 #define ZALLOC_ALLOW_DEPRECATED 1
67 #if !ZALLOC_TEST
68 #include <mach/mach_types.h>
69 #include <mach/vm_param.h>
70 #include <mach/kern_return.h>
71 #include <mach/mach_host_server.h>
72 #include <mach/task_server.h>
73 #include <mach/machine/vm_types.h>
74 #include <machine/machine_routines.h>
75 #include <mach/vm_map.h>
76 #include <mach/sdt.h>
77 #if __x86_64__
78 #include <i386/cpuid.h>
79 #endif
80
81 #include <kern/bits.h>
82 #include <kern/btlog.h>
83 #include <kern/startup.h>
84 #include <kern/kern_types.h>
85 #include <kern/assert.h>
86 #include <kern/backtrace.h>
87 #include <kern/host.h>
88 #include <kern/macro_help.h>
89 #include <kern/sched.h>
90 #include <kern/locks.h>
91 #include <kern/sched_prim.h>
92 #include <kern/misc_protos.h>
93 #include <kern/thread_call.h>
94 #include <kern/zalloc_internal.h>
95 #include <kern/kalloc.h>
96 #include <kern/debug.h>
97
98 #include <prng/random.h>
99
100 #include <vm/pmap.h>
101 #include <vm/vm_map_internal.h>
102 #include <vm/vm_memtag.h>
103 #include <vm/vm_kern_internal.h>
104 #include <vm/vm_page_internal.h>
105 #include <vm/vm_pageout_internal.h>
106 #include <vm/vm_compressor_xnu.h> /* C_SLOT_PACKED_PTR* */
107
108 #include <pexpert/pexpert.h>
109
110 #include <machine/machparam.h>
111 #include <machine/machine_routines.h> /* ml_cpu_get_info */
112
113 #include <os/atomic.h>
114
115 #include <libkern/OSDebug.h>
116 #include <libkern/OSAtomic.h>
117 #include <libkern/section_keywords.h>
118 #include <sys/kdebug.h>
119 #include <sys/code_signing.h>
120
121 #include <san/kasan.h>
122 #include <libsa/stdlib.h>
123 #include <sys/errno.h>
124
125 #include <IOKit/IOBSD.h>
126 #include <arm64/amcc_rorgn.h>
127
128 #if DEBUG
129 #define z_debug_assert(expr) assert(expr)
130 #else
131 #define z_debug_assert(expr) (void)(expr)
132 #endif
133
134 #if CONFIG_PROB_GZALLOC && CONFIG_SPTM
135 #error This is not a supported configuration
136 #endif
137
138 /* Returns pid of the task with the largest number of VM map entries. */
139 extern pid_t find_largest_process_vm_map_entries(void);
140
141 /*
142 * Callout to jetsam. If pid is -1, we wake up the memorystatus thread to do asynchronous kills.
143 * For any other pid we try to kill that process synchronously.
144 */
145 extern boolean_t memorystatus_kill_on_zone_map_exhaustion(pid_t pid);
146
147 extern zone_t vm_object_zone;
148 extern zone_t ipc_service_port_label_zone;
149
150 ZONE_DEFINE_TYPE(percpu_u64_zone, "percpu.64", uint64_t,
151 ZC_PERCPU | ZC_ALIGNMENT_REQUIRED | ZC_KASAN_NOREDZONE);
152
153 #if ZSECURITY_CONFIG(ZONE_TAGGING)
154 #define ZONE_MIN_ELEM_SIZE (sizeof(uint64_t) * 2)
155 #define ZONE_ALIGN_SIZE ZONE_MIN_ELEM_SIZE
156 #else /* ZSECURITY_CONFIG_ZONE_TAGGING */
157 #define ZONE_MIN_ELEM_SIZE sizeof(uint64_t)
158 #define ZONE_ALIGN_SIZE ZONE_MIN_ELEM_SIZE
159 #endif /* ZSECURITY_CONFIG_ZONE_TAGGING */
160
161 #define ZONE_MAX_ALLOC_SIZE (32 * 1024)
162 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
163 #define ZONE_CHUNK_ALLOC_SIZE (256 * 1024)
164 #define ZONE_GUARD_DENSE (32 * 1024)
165 #define ZONE_GUARD_SPARSE (64 * 1024)
166 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
167
168 #if XNU_PLATFORM_MacOSX
169 #define ZONE_MAP_MAX (32ULL << 30)
170 #define ZONE_MAP_VA_SIZE (128ULL << 30)
171 #else /* XNU_PLATFORM_MacOSX */
172 #define ZONE_MAP_MAX (8ULL << 30)
173 #define ZONE_MAP_VA_SIZE (24ULL << 30)
174 #endif /* !XNU_PLATFORM_MacOSX */
175
176 __enum_closed_decl(zm_len_t, uint16_t, {
177 ZM_CHUNK_FREE = 0x0,
178 /* 1 through 8 are valid lengths */
179 ZM_CHUNK_LEN_MAX = 0x8,
180
181 /* PGZ magical values */
182 ZM_PGZ_FREE = 0x0,
183 ZM_PGZ_ALLOCATED = 0xa, /* [a]llocated */
184 ZM_PGZ_GUARD = 0xb, /* oo[b] */
185 ZM_PGZ_DOUBLE_FREE = 0xd, /* [d]ouble_free */
186
187 /* secondary page markers */
188 ZM_SECONDARY_PAGE = 0xe,
189 ZM_SECONDARY_PCPU_PAGE = 0xf,
190 });
191
192 static_assert(MAX_ZONES < (1u << 10), "MAX_ZONES must fit in zm_index");
193
194 struct zone_page_metadata {
195 union {
196 struct {
197 /* The index of the zone this metadata page belongs to */
198 zone_id_t zm_index : 10;
199
200 /*
201 * This chunk ends with a guard page.
202 */
203 uint16_t zm_guarded : 1;
204
205 /*
206 * Whether `zm_bitmap` is an inline bitmap
207 * or a packed bitmap reference
208 */
209 uint16_t zm_inline_bitmap : 1;
210
211 /*
212 * Zones allocate in "chunks" of zone_t::z_chunk_pages
213 * consecutive pages, or zpercpu_count() pages if the
214 * zone is percpu.
215 *
216 * The first page of it has its metadata set with:
217 * - 0 if none of the pages are currently wired
218 * - the number of wired pages in the chunk
219 * (not scaled for percpu).
220 *
221 * Other pages in the chunk have their zm_chunk_len set
222 * to ZM_SECONDARY_PAGE or ZM_SECONDARY_PCPU_PAGE
223 * depending on whether the zone is percpu or not.
224 * For those, zm_page_index holds the index of that page
225 * in the run, and zm_subchunk_len the remaining length
226 * within the chunk.
227 *
228 * Metadata used for PGZ pages can have 3 values:
229 * - ZM_PGZ_FREE: slot is free
230 * - ZM_PGZ_ALLOCATED: slot holds an allocated element
231 * at offset (zm_pgz_orig_addr & PAGE_MASK)
232 * - ZM_PGZ_DOUBLE_FREE: slot detected a double free
233 * (will panic).
234 */
235 zm_len_t zm_chunk_len : 4;
236 };
237 uint16_t zm_bits;
238 };
239
240 union {
241 #define ZM_ALLOC_SIZE_LOCK 1u
242 uint16_t zm_alloc_size; /* first page only */
243 struct {
244 uint8_t zm_page_index; /* secondary pages only */
245 uint8_t zm_subchunk_len; /* secondary pages only */
246 };
247 uint16_t zm_oob_offs; /* in guard pages */
248 };
249 union {
250 uint32_t zm_bitmap; /* most zones */
251 uint32_t zm_bump; /* permanent zones */
252 };
253
254 union {
255 struct {
256 zone_pva_t zm_page_next;
257 zone_pva_t zm_page_prev;
258 };
259 vm_offset_t zm_pgz_orig_addr;
260 struct zone_page_metadata *zm_pgz_slot_next;
261 };
262 };
263 static_assert(sizeof(struct zone_page_metadata) == 16, "validate packing");
264
265 /*!
266 * @typedef zone_magazine_t
267 *
268 * @brief
269 * Magazine of cached allocations.
270 *
271 * @field zm_next linkage used by magazine depots.
272 * @field zm_elems an array of @c zc_mag_size() elements.
273 */
274 struct zone_magazine {
275 zone_magazine_t zm_next;
276 smr_seq_t zm_seq;
277 vm_offset_t zm_elems[0];
278 };
279
280 /*!
281 * @typedef zone_cache_t
282 *
283 * @brief
284 * Magazine of cached allocations.
285 *
286 * @discussion
287 * Below is a diagram of the caching system. This design is inspired by the
288 * paper "Magazines and Vmem: Extending the Slab Allocator to Many CPUs and
289 * Arbitrary Resources" by Jeff Bonwick and Jonathan Adams and the FreeBSD UMA
290 * zone allocator (itself derived from this seminal work).
291 *
292 * It is divided into 3 layers:
293 * - the per-cpu layer,
294 * - the recirculation depot layer,
295 * - the Zone Allocator.
296 *
297 * The per-cpu and recirculation depot layer use magazines (@c zone_magazine_t),
298 * which are stacks of up to @c zc_mag_size() elements.
299 *
300 * <h2>CPU layer</h2>
301 *
302 * The CPU layer (@c zone_cache_t) looks like this:
303 *
304 * ╭─ a ─ f ─┬───────── zm_depot ──────────╮
305 * │ ╭─╮ ╭─╮ │ ╭─╮ ╭─╮ ╭─╮ ╭─╮ ╭─╮ │
306 * │ │#│ │#│ │ │#│ │#│ │#│ │#│ │#│ │
307 * │ │#│ │ │ │ │#│ │#│ │#│ │#│ │#│ │
308 * │ │ │ │ │ │ │#│ │#│ │#│ │#│ │#│ │
309 * │ ╰─╯ ╰─╯ │ ╰─╯ ╰─╯ ╰─╯ ╰─╯ ╰─╯ │
310 * ╰─────────┴─────────────────────────────╯
311 *
312 * It has two pre-loaded magazines (a)lloc and (f)ree which we allocate from,
313 * or free to. Serialization is achieved through disabling preemption, and only
314 * the current CPU can acces those allocations. This is represented on the left
315 * hand side of the diagram above.
316 *
317 * The right hand side is the per-cpu depot. It consists of @c zm_depot_count
318 * full magazines, and is protected by the @c zm_depot_lock for access.
319 * The lock is expected to absolutely never be contended, as only the local CPU
320 * tends to access the local per-cpu depot in regular operation mode.
321 *
322 * However unlike UMA, our implementation allows for the zone GC to reclaim
323 * per-CPU magazines aggresively, which is serialized with the @c zm_depot_lock.
324 *
325 *
326 * <h2>Recirculation Depot</h2>
327 *
328 * The recirculation depot layer is a list similar to the per-cpu depot,
329 * however it is different in two fundamental ways:
330 *
331 * - it is protected by the regular zone lock,
332 * - elements referenced by the magazines in that layer appear free
333 * to the zone layer.
334 *
335 *
336 * <h2>Magazine circulation and sizing</h2>
337 *
338 * The caching system sizes itself dynamically. Operations that allocate/free
339 * a single element call @c zone_lock_nopreempt_check_contention() which records
340 * contention on the lock by doing a trylock and recording its success.
341 *
342 * This information is stored in the @c z_recirc_cont_cur field of the zone,
343 * and a windowed moving average is maintained in @c z_contention_wma.
344 * The periodically run function @c compute_zone_working_set_size() will then
345 * take this into account to decide to grow the number of buckets allowed
346 * in the depot or shrink it based on the @c zc_grow_level and @c zc_shrink_level
347 * thresholds.
348 *
349 * The per-cpu layer will attempt to work with its depot, finding both full and
350 * empty magazines cached there. If it can't get what it needs, then it will
351 * mediate with the zone recirculation layer. Such recirculation is done in
352 * batches in order to amortize lock holds.
353 * (See @c {zalloc,zfree}_cached_depot_recirculate()).
354 *
355 * The recirculation layer keeps a track of what the minimum amount of magazines
356 * it had over time was for each of the full and empty queues. This allows for
357 * @c compute_zone_working_set_size() to return memory to the system when a zone
358 * stops being used as much.
359 *
360 * <h2>Security considerations</h2>
361 *
362 * The zone caching layer has been designed to avoid returning elements in
363 * a strict LIFO behavior: @c zalloc() will allocate from the (a) magazine,
364 * and @c zfree() free to the (f) magazine, and only swap them when the
365 * requested operation cannot be fulfilled.
366 *
367 * The per-cpu overflow depot or the recirculation depots are similarly used
368 * in FIFO order.
369 *
370 * @field zc_depot_lock a lock to access @c zc_depot, @c zc_depot_cur.
371 * @field zc_alloc_cur denormalized number of elements in the (a) magazine
372 * @field zc_free_cur denormalized number of elements in the (f) magazine
373 * @field zc_alloc_elems a pointer to the array of elements in (a)
374 * @field zc_free_elems a pointer to the array of elements in (f)
375 *
376 * @field zc_depot a list of @c zc_depot_cur full magazines
377 */
378 typedef struct zone_cache {
379 hw_lck_ticket_t zc_depot_lock;
380 uint16_t zc_alloc_cur;
381 uint16_t zc_free_cur;
382 vm_offset_t *zc_alloc_elems;
383 vm_offset_t *zc_free_elems;
384 struct zone_depot zc_depot;
385 smr_t zc_smr;
386 zone_smr_free_cb_t XNU_PTRAUTH_SIGNED_FUNCTION_PTR("zc_free") zc_free;
387 } __attribute__((aligned(64))) * zone_cache_t;
388
389 #if !__x86_64__
390 static
391 #endif
392 __security_const_late struct {
393 struct mach_vm_range zi_map_range; /* all zone submaps */
394 struct mach_vm_range zi_ro_range; /* read-only range */
395 struct mach_vm_range zi_meta_range; /* debugging only */
396 struct mach_vm_range zi_bits_range; /* bits buddy allocator */
397 struct mach_vm_range zi_xtra_range; /* vm tracking metadata */
398 struct mach_vm_range zi_pgz_range;
399 struct zone_page_metadata *zi_pgz_meta;
400
401 /*
402 * The metadata lives within the zi_meta_range address range.
403 *
404 * The correct formula to find a metadata index is:
405 * absolute_page_index - page_index(zi_map_range.min_address)
406 *
407 * And then this index is used to dereference zi_meta_range.min_address
408 * as a `struct zone_page_metadata` array.
409 *
410 * To avoid doing that substraction all the time in the various fast-paths,
411 * zi_meta_base are pre-offset with that minimum page index to avoid redoing
412 * that math all the time.
413 */
414 struct zone_page_metadata *zi_meta_base;
415 } zone_info;
416
417 __startup_data static struct mach_vm_range zone_map_range;
418 __startup_data static vm_map_size_t zone_meta_size;
419 __startup_data static vm_map_size_t zone_bits_size;
420 __startup_data static vm_map_size_t zone_xtra_size;
421
422 /*
423 * Initial array of metadata for stolen memory.
424 *
425 * The numbers here have to be kept in sync with vm_map_steal_memory()
426 * so that we have reserved enough metadata.
427 *
428 * After zone_init() has run (which happens while the kernel is still single
429 * threaded), the metadata is moved to its final dynamic location, and
430 * this array is unmapped with the rest of __startup_data at lockdown.
431 */
432 #define ZONE_EARLY_META_INLINE_COUNT 64
433 __startup_data
434 static struct zone_page_metadata
435 zone_early_meta_array_startup[ZONE_EARLY_META_INLINE_COUNT];
436
437
438 __startup_data __attribute__((aligned(PAGE_MAX_SIZE)))
439 static uint8_t zone_early_pages_to_cram[PAGE_MAX_SIZE * 16];
440
441 /*
442 * The zone_locks_grp allows for collecting lock statistics.
443 * All locks are associated to this group in zinit.
444 * Look at tools/lockstat for debugging lock contention.
445 */
446 LCK_GRP_DECLARE(zone_locks_grp, "zone_locks");
447 static LCK_MTX_DECLARE(zone_metadata_region_lck, &zone_locks_grp);
448
449 /*
450 * The zone metadata lock protects:
451 * - metadata faulting,
452 * - VM submap VA allocations,
453 * - early gap page queue list
454 */
455 #define zone_meta_lock() lck_mtx_lock(&zone_metadata_region_lck);
456 #define zone_meta_unlock() lck_mtx_unlock(&zone_metadata_region_lck);
457
458 /*
459 * Exclude more than one concurrent garbage collection
460 */
461 static LCK_GRP_DECLARE(zone_gc_lck_grp, "zone_gc");
462 static LCK_MTX_DECLARE(zone_gc_lock, &zone_gc_lck_grp);
463 static LCK_SPIN_DECLARE(zone_exhausted_lock, &zone_gc_lck_grp);
464
465 /*
466 * Panic logging metadata
467 */
468 bool panic_include_zprint = false;
469 bool panic_include_kalloc_types = false;
470 zone_t kalloc_type_src_zone = ZONE_NULL;
471 zone_t kalloc_type_dst_zone = ZONE_NULL;
472 mach_memory_info_t *panic_kext_memory_info = NULL;
473 vm_size_t panic_kext_memory_size = 0;
474 vm_offset_t panic_fault_address = 0;
475
476 /*
477 * Protects zone_array, num_zones, num_zones_in_use, and
478 * zone_destroyed_bitmap
479 */
480 static SIMPLE_LOCK_DECLARE(all_zones_lock, 0);
481 static zone_id_t num_zones_in_use;
482 zone_id_t _Atomic num_zones;
483 SECURITY_READ_ONLY_LATE(unsigned int) zone_view_count;
484
485 /*
486 * Initial globals for zone stats until we can allocate the real ones.
487 * Those get migrated inside the per-CPU ones during zone_init() and
488 * this array is unmapped with the rest of __startup_data at lockdown.
489 */
490
491 /* zone to allocate zone_magazine structs from */
492 static SECURITY_READ_ONLY_LATE(zone_t) zc_magazine_zone;
493 /*
494 * Until pid1 is made, zone caching is off,
495 * until compute_zone_working_set_size() runs for the firt time.
496 *
497 * -1 represents the "never enabled yet" value.
498 */
499 static int8_t zone_caching_disabled = -1;
500
501 __startup_data
502 static struct zone_stats zone_stats_startup[MAX_ZONES];
503 struct zone zone_array[MAX_ZONES];
504 SECURITY_READ_ONLY_LATE(zone_security_flags_t) zone_security_array[MAX_ZONES] = {
505 [0 ... MAX_ZONES - 1] = {
506 .z_kheap_id = KHEAP_ID_NONE,
507 .z_noencrypt = false,
508 .z_submap_idx = Z_SUBMAP_IDX_GENERAL_0,
509 .z_kalloc_type = false,
510 .z_sig_eq = 0,
511 #if ZSECURITY_CONFIG(ZONE_TAGGING)
512 .z_tag = 1,
513 #else /* ZSECURITY_CONFIG(ZONE_TAGGING) */
514 .z_tag = 0,
515 #endif /* ZSECURITY_CONFIG(ZONE_TAGGING) */
516 },
517 };
518 SECURITY_READ_ONLY_LATE(struct zone_size_params) zone_ro_size_params[ZONE_ID__LAST_RO + 1];
SECURITY_READ_ONLY_LATE(zone_cache_ops_t)519 SECURITY_READ_ONLY_LATE(zone_cache_ops_t) zcache_ops[ZONE_ID__FIRST_DYNAMIC];
520
521 #if DEBUG || DEVELOPMENT
522 unsigned int
523 zone_max_zones(void)
524 {
525 return MAX_ZONES;
526 }
527 #endif
528
529 /* Initialized in zone_bootstrap(), how many "copies" the per-cpu system does */
530 static SECURITY_READ_ONLY_LATE(unsigned) zpercpu_early_count;
531
532 /* Used to keep track of destroyed slots in the zone_array */
533 static bitmap_t zone_destroyed_bitmap[BITMAP_LEN(MAX_ZONES)];
534
535 /* number of zone mapped pages used by all zones */
536 static size_t _Atomic zone_pages_jetsam_threshold = ~0;
537 size_t zone_pages_wired;
538 size_t zone_guard_pages;
539
540 /* Time in (ms) after which we panic for zone exhaustions */
541 TUNABLE(int, zone_exhausted_timeout, "zet", 5000);
542 static bool zone_share_always = true;
543 static TUNABLE_WRITEABLE(uint32_t, zone_early_thres_mul, "zone_early_thres_mul", 5);
544
545 #if VM_TAG_SIZECLASSES
546 /*
547 * Zone tagging allows for per "tag" accounting of allocations for the kalloc
548 * zones only.
549 *
550 * There are 3 kinds of tags that can be used:
551 * - pre-registered VM_KERN_MEMORY_*
552 * - dynamic tags allocated per call sites in core-kernel (using vm_tag_alloc())
553 * - per-kext tags computed by IOKit (using the magic Z_VM_TAG_BT_BIT marker).
554 *
555 * The VM tracks the statistics in lazily allocated structures.
556 * See vm_tag_will_update_zone(), vm_tag_update_zone_size().
557 *
558 * If for some reason the requested tag cannot be accounted for,
559 * the tag is forced to VM_KERN_MEMORY_KALLOC which is pre-allocated.
560 *
561 * Each allocated element also remembers the tag it was assigned,
562 * which lets zalloc/zfree update statistics correctly.
563 */
564
565 /* enable tags for zones that ask for it */
566 static TUNABLE(bool, zone_tagging_on, "-zt", false);
567
568 /*
569 * Array of all sizeclasses used by kalloc variants so that we can
570 * have accounting per size class for each kalloc callsite
571 */
572 static uint16_t zone_tags_sizeclasses[VM_TAG_SIZECLASSES];
573 #endif /* VM_TAG_SIZECLASSES */
574
575 #if DEBUG || DEVELOPMENT
576 static int zalloc_simulate_vm_pressure;
577 #endif /* DEBUG || DEVELOPMENT */
578
579 #define Z_TUNABLE(t, n, d) \
580 TUNABLE(t, _##n, #n, d); \
581 __pure2 static inline t n(void) { return _##n; }
582
583 /*
584 * Zone caching tunables
585 *
586 * zc_mag_size():
587 * size of magazines, larger to reduce contention at the expense of memory
588 *
589 * zc_enable_level
590 * number of contentions per second after which zone caching engages
591 * automatically.
592 *
593 * 0 to disable.
594 *
595 * zc_grow_level
596 * number of contentions per second x cpu after which the number of magazines
597 * allowed in the depot can grow. (in "Z_WMA_UNIT" units).
598 *
599 * zc_shrink_level
600 * number of contentions per second x cpu below which the number of magazines
601 * allowed in the depot will shrink. (in "Z_WMA_UNIT" units).
602 *
603 * zc_pcpu_max
604 * maximum memory size in bytes that can hang from a CPU,
605 * which will affect how many magazines are allowed in the depot.
606 *
607 * The alloc/free magazines are assumed to be on average half-empty
608 * and to count for "1" unit of magazines.
609 *
610 * zc_autotrim_size
611 * Size allowed to hang extra from the recirculation depot before
612 * auto-trim kicks in.
613 *
614 * zc_autotrim_buckets
615 *
616 * How many buckets in excess of the working-set are allowed
617 * before auto-trim kicks in for empty buckets.
618 *
619 * zc_free_batch_size
620 * The size of batches of frees/reclaim that can be done keeping
621 * the zone lock held (and preemption disabled).
622 */
623 Z_TUNABLE(uint16_t, zc_mag_size, 8);
624 static Z_TUNABLE(uint32_t, zc_enable_level, 10);
625 static Z_TUNABLE(uint32_t, zc_grow_level, 5 * Z_WMA_UNIT);
626 static Z_TUNABLE(uint32_t, zc_shrink_level, Z_WMA_UNIT / 2);
627 static Z_TUNABLE(uint32_t, zc_pcpu_max, 128 << 10);
628 static Z_TUNABLE(uint32_t, zc_autotrim_size, 16 << 10);
629 static Z_TUNABLE(uint32_t, zc_autotrim_buckets, 8);
630 static Z_TUNABLE(uint32_t, zc_free_batch_size, 128);
631
632 static SECURITY_READ_ONLY_LATE(size_t) zone_pages_wired_max;
633 static SECURITY_READ_ONLY_LATE(vm_map_t) zone_submaps[Z_SUBMAP_IDX_COUNT];
634 static SECURITY_READ_ONLY_LATE(vm_map_t) zone_meta_map;
635 static char const * const zone_submaps_names[Z_SUBMAP_IDX_COUNT] = {
636 [Z_SUBMAP_IDX_VM] = "VM",
637 [Z_SUBMAP_IDX_READ_ONLY] = "RO",
638 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
639 [Z_SUBMAP_IDX_GENERAL_0] = "GEN0",
640 [Z_SUBMAP_IDX_GENERAL_1] = "GEN1",
641 [Z_SUBMAP_IDX_GENERAL_2] = "GEN2",
642 [Z_SUBMAP_IDX_GENERAL_3] = "GEN3",
643 #else
644 [Z_SUBMAP_IDX_GENERAL_0] = "GEN",
645 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
646 [Z_SUBMAP_IDX_DATA] = "DATA",
647 };
648
649 #if __x86_64__
650 #define ZONE_ENTROPY_CNT 8
651 #else
652 #define ZONE_ENTROPY_CNT 2
653 #endif
654 static struct zone_bool_gen {
655 struct bool_gen zbg_bg;
656 uint32_t zbg_entropy[ZONE_ENTROPY_CNT];
657 } zone_bool_gen[MAX_CPUS];
658
659 #if CONFIG_PROB_GZALLOC
660 /*
661 * Probabilistic gzalloc
662 * =====================
663 *
664 *
665 * Probabilistic guard zalloc samples allocations and will protect them by
666 * double-mapping the page holding them and returning the secondary virtual
667 * address to its callers.
668 *
669 * Its data structures are lazily allocated if the `pgz` or `pgz1` boot-args
670 * are set.
671 *
672 *
673 * Unlike GZalloc, PGZ uses a fixed amount of memory, and is compatible with
674 * most zalloc/kalloc features:
675 * - zone_require is functional
676 * - zone caching or zone tagging is compatible
677 * - non-blocking allocation work (they will always return NULL with gzalloc).
678 *
679 * PGZ limitations:
680 * - VA sequestering isn't respected, as the slots (which are in limited
681 * quantity) will be reused for any type, however the PGZ quarantine
682 * somewhat mitigates the impact.
683 * - zones with elements larger than a page cannot be protected.
684 *
685 *
686 * Tunables:
687 * --------
688 *
689 * pgz=1:
690 * Turn on probabilistic guard malloc for all zones
691 *
692 * (default on for DEVELOPMENT, off for RELEASE, or if pgz1... are specified)
693 *
694 * pgz_sample_rate=0 to 2^31
695 * average sample rate between two guarded allocations.
696 * 0 means every allocation.
697 *
698 * The default is a random number between 1000 and 10,000
699 *
700 * pgz_slots
701 * how many allocations to protect.
702 *
703 * Each costs:
704 * - a PTE in the pmap (when allocated)
705 * - 2 zone page meta's (every other page is a "guard" one, 32B total)
706 * - 64 bytes per backtraces.
707 * On LP64 this is <16K per 100 slots.
708 *
709 * The default is ~200 slots per G of physical ram (32k / G)
710 *
711 * TODO:
712 * - try harder to allocate elements at the "end" to catch OOB more reliably.
713 *
714 * pgz_quarantine
715 * how many slots should be free at any given time.
716 *
717 * PGZ will round robin through free slots to be reused, but free slots are
718 * important to detect use-after-free by acting as a quarantine.
719 *
720 * By default, PGZ will keep 33% of the slots around at all time.
721 *
722 * pgz1=<name>, pgz2=<name>, ..., pgzn=<name>...
723 * Specific zones for which to enable probabilistic guard malloc.
724 * There must be no numbering gap (names after the gap will be ignored).
725 */
726 #if DEBUG || DEVELOPMENT
727 static TUNABLE(bool, pgz_all, "pgz", true);
728 #else
729 static TUNABLE(bool, pgz_all, "pgz", false);
730 #endif
731 static TUNABLE(uint32_t, pgz_sample_rate, "pgz_sample_rate", 0);
732 static TUNABLE(uint32_t, pgz_slots, "pgz_slots", UINT32_MAX);
733 static TUNABLE(uint32_t, pgz_quarantine, "pgz_quarantine", 0);
734 #endif /* CONFIG_PROB_GZALLOC */
735
736 static zone_t zone_find_largest(uint64_t *zone_size);
737
738 #endif /* !ZALLOC_TEST */
739 #pragma mark Zone metadata
740 #if !ZALLOC_TEST
741
742 static inline bool
zone_has_index(zone_t z,zone_id_t zid)743 zone_has_index(zone_t z, zone_id_t zid)
744 {
745 return zone_array + zid == z;
746 }
747
748 __abortlike
749 void
zone_invalid_panic(zone_t zone)750 zone_invalid_panic(zone_t zone)
751 {
752 panic("zone %p isn't in the zone_array", zone);
753 }
754
755 __abortlike
756 static void
zone_metadata_corruption(zone_t zone,struct zone_page_metadata * meta,const char * kind)757 zone_metadata_corruption(zone_t zone, struct zone_page_metadata *meta,
758 const char *kind)
759 {
760 panic("zone metadata corruption: %s (meta %p, zone %s%s)",
761 kind, meta, zone_heap_name(zone), zone->z_name);
762 }
763
764 __abortlike
765 static void
zone_invalid_element_addr_panic(zone_t zone,vm_offset_t addr)766 zone_invalid_element_addr_panic(zone_t zone, vm_offset_t addr)
767 {
768 panic("zone element pointer validation failed (addr: %p, zone %s%s)",
769 (void *)addr, zone_heap_name(zone), zone->z_name);
770 }
771
772 __abortlike
773 static void
zone_page_metadata_index_confusion_panic(zone_t zone,vm_offset_t addr,struct zone_page_metadata * meta)774 zone_page_metadata_index_confusion_panic(zone_t zone, vm_offset_t addr,
775 struct zone_page_metadata *meta)
776 {
777 zone_security_flags_t zsflags = zone_security_config(zone), src_zsflags;
778 zone_id_t zidx;
779 zone_t src_zone;
780
781 if (zsflags.z_kalloc_type) {
782 panic_include_kalloc_types = true;
783 kalloc_type_dst_zone = zone;
784 }
785
786 zidx = meta->zm_index;
787 if (zidx >= os_atomic_load(&num_zones, relaxed)) {
788 panic("%p expected in zone %s%s[%d], but metadata has invalid zidx: %d",
789 (void *)addr, zone_heap_name(zone), zone->z_name, zone_index(zone),
790 zidx);
791 }
792
793 src_zone = &zone_array[zidx];
794 src_zsflags = zone_security_array[zidx];
795 if (src_zsflags.z_kalloc_type) {
796 panic_include_kalloc_types = true;
797 kalloc_type_src_zone = src_zone;
798 }
799
800 panic("%p not in the expected zone %s%s[%d], but found in %s%s[%d]",
801 (void *)addr, zone_heap_name(zone), zone->z_name, zone_index(zone),
802 zone_heap_name(src_zone), src_zone->z_name, zidx);
803 }
804
805 __abortlike
806 static void
zone_page_metadata_list_corruption(zone_t zone,struct zone_page_metadata * meta)807 zone_page_metadata_list_corruption(zone_t zone, struct zone_page_metadata *meta)
808 {
809 panic("metadata list corruption through element %p detected in zone %s%s",
810 meta, zone_heap_name(zone), zone->z_name);
811 }
812
813 __abortlike
814 static void
zone_page_meta_accounting_panic(zone_t zone,struct zone_page_metadata * meta,const char * kind)815 zone_page_meta_accounting_panic(zone_t zone, struct zone_page_metadata *meta,
816 const char *kind)
817 {
818 panic("accounting mismatch (%s) for zone %s%s, meta %p", kind,
819 zone_heap_name(zone), zone->z_name, meta);
820 }
821
822 __abortlike
823 static void
zone_meta_double_free_panic(zone_t zone,vm_offset_t addr,const char * caller)824 zone_meta_double_free_panic(zone_t zone, vm_offset_t addr, const char *caller)
825 {
826 panic("%s: double free of %p to zone %s%s", caller,
827 (void *)addr, zone_heap_name(zone), zone->z_name);
828 }
829
830 __abortlike
831 static void
zone_accounting_panic(zone_t zone,const char * kind)832 zone_accounting_panic(zone_t zone, const char *kind)
833 {
834 panic("accounting mismatch (%s) for zone %s%s", kind,
835 zone_heap_name(zone), zone->z_name);
836 }
837
838 #define zone_counter_sub(z, stat, value) ({ \
839 if (os_sub_overflow((z)->stat, value, &(z)->stat)) { \
840 zone_accounting_panic(z, #stat " wrap-around"); \
841 } \
842 (z)->stat; \
843 })
844
845 static inline uint16_t
zone_meta_alloc_size_add(zone_t z,struct zone_page_metadata * m,vm_offset_t esize)846 zone_meta_alloc_size_add(zone_t z, struct zone_page_metadata *m,
847 vm_offset_t esize)
848 {
849 if (os_add_overflow(m->zm_alloc_size, (uint16_t)esize, &m->zm_alloc_size)) {
850 zone_page_meta_accounting_panic(z, m, "alloc_size wrap-around");
851 }
852 return m->zm_alloc_size;
853 }
854
855 static inline uint16_t
zone_meta_alloc_size_sub(zone_t z,struct zone_page_metadata * m,vm_offset_t esize)856 zone_meta_alloc_size_sub(zone_t z, struct zone_page_metadata *m,
857 vm_offset_t esize)
858 {
859 if (os_sub_overflow(m->zm_alloc_size, esize, &m->zm_alloc_size)) {
860 zone_page_meta_accounting_panic(z, m, "alloc_size wrap-around");
861 }
862 return m->zm_alloc_size;
863 }
864
865 __abortlike
866 static void
zone_nofail_panic(zone_t zone)867 zone_nofail_panic(zone_t zone)
868 {
869 panic("zalloc(Z_NOFAIL) can't be satisfied for zone %s%s (potential leak)",
870 zone_heap_name(zone), zone->z_name);
871 }
872
873 __header_always_inline bool
zone_spans_ro_va(vm_offset_t addr_start,vm_offset_t addr_end)874 zone_spans_ro_va(vm_offset_t addr_start, vm_offset_t addr_end)
875 {
876 const struct mach_vm_range *ro_r = &zone_info.zi_ro_range;
877 struct mach_vm_range r = { addr_start, addr_end };
878
879 return mach_vm_range_intersects(ro_r, &r);
880 }
881
882 #define from_range(r, addr, size) \
883 __builtin_choose_expr(__builtin_constant_p(size) ? (size) == 1 : 0, \
884 mach_vm_range_contains(r, (mach_vm_offset_t)(addr)), \
885 mach_vm_range_contains(r, (mach_vm_offset_t)(addr), size))
886
887 #define from_ro_map(addr, size) \
888 from_range(&zone_info.zi_ro_range, addr, size)
889
890 #define from_zone_map(addr, size) \
891 from_range(&zone_info.zi_map_range, addr, size)
892
893 __header_always_inline bool
zone_pva_is_null(zone_pva_t page)894 zone_pva_is_null(zone_pva_t page)
895 {
896 return page.packed_address == 0;
897 }
898
899 __header_always_inline bool
zone_pva_is_queue(zone_pva_t page)900 zone_pva_is_queue(zone_pva_t page)
901 {
902 // actual kernel pages have the top bit set
903 return (int32_t)page.packed_address > 0;
904 }
905
906 __header_always_inline bool
zone_pva_is_equal(zone_pva_t pva1,zone_pva_t pva2)907 zone_pva_is_equal(zone_pva_t pva1, zone_pva_t pva2)
908 {
909 return pva1.packed_address == pva2.packed_address;
910 }
911
912 __header_always_inline zone_pva_t *
zone_pageq_base(void)913 zone_pageq_base(void)
914 {
915 extern zone_pva_t data_seg_start[] __SEGMENT_START_SYM("__DATA");
916
917 /*
918 * `-1` so that if the first __DATA variable is a page queue,
919 * it gets a non 0 index
920 */
921 return data_seg_start - 1;
922 }
923
924 __header_always_inline void
zone_queue_set_head(zone_t z,zone_pva_t queue,zone_pva_t oldv,struct zone_page_metadata * meta)925 zone_queue_set_head(zone_t z, zone_pva_t queue, zone_pva_t oldv,
926 struct zone_page_metadata *meta)
927 {
928 zone_pva_t *queue_head = &zone_pageq_base()[queue.packed_address];
929
930 if (!zone_pva_is_equal(*queue_head, oldv)) {
931 zone_page_metadata_list_corruption(z, meta);
932 }
933 *queue_head = meta->zm_page_next;
934 }
935
936 __header_always_inline zone_pva_t
zone_queue_encode(zone_pva_t * headp)937 zone_queue_encode(zone_pva_t *headp)
938 {
939 return (zone_pva_t){ (uint32_t)(headp - zone_pageq_base()) };
940 }
941
942 __header_always_inline zone_pva_t
zone_pva_from_addr(vm_address_t addr)943 zone_pva_from_addr(vm_address_t addr)
944 {
945 // cannot use atop() because we want to maintain the sign bit
946 return (zone_pva_t){ (uint32_t)((intptr_t)addr >> PAGE_SHIFT) };
947 }
948
949 __header_always_inline vm_address_t
zone_pva_to_addr(zone_pva_t page)950 zone_pva_to_addr(zone_pva_t page)
951 {
952 // cause sign extension so that we end up with the right address
953 return (vm_offset_t)(int32_t)page.packed_address << PAGE_SHIFT;
954 }
955
956 __header_always_inline struct zone_page_metadata *
zone_pva_to_meta(zone_pva_t page)957 zone_pva_to_meta(zone_pva_t page)
958 {
959 return &zone_info.zi_meta_base[page.packed_address];
960 }
961
962 __header_always_inline zone_pva_t
zone_pva_from_meta(struct zone_page_metadata * meta)963 zone_pva_from_meta(struct zone_page_metadata *meta)
964 {
965 return (zone_pva_t){ (uint32_t)(meta - zone_info.zi_meta_base) };
966 }
967
968 __header_always_inline struct zone_page_metadata *
zone_meta_from_addr(vm_offset_t addr)969 zone_meta_from_addr(vm_offset_t addr)
970 {
971 return zone_pva_to_meta(zone_pva_from_addr(addr));
972 }
973
974 __header_always_inline zone_id_t
zone_index_from_ptr(const void * ptr)975 zone_index_from_ptr(const void *ptr)
976 {
977 return zone_pva_to_meta(zone_pva_from_addr((vm_offset_t)ptr))->zm_index;
978 }
979
980 __header_always_inline vm_offset_t
zone_meta_to_addr(struct zone_page_metadata * meta)981 zone_meta_to_addr(struct zone_page_metadata *meta)
982 {
983 return ptoa((int32_t)(meta - zone_info.zi_meta_base));
984 }
985
986 __attribute__((overloadable))
987 __header_always_inline void
zone_meta_validate(zone_t z,struct zone_page_metadata * meta,vm_address_t addr)988 zone_meta_validate(zone_t z, struct zone_page_metadata *meta, vm_address_t addr)
989 {
990 if (!zone_has_index(z, meta->zm_index)) {
991 zone_page_metadata_index_confusion_panic(z, addr, meta);
992 }
993 }
994
995 __attribute__((overloadable))
996 __header_always_inline void
zone_meta_validate(zone_t z,struct zone_page_metadata * meta)997 zone_meta_validate(zone_t z, struct zone_page_metadata *meta)
998 {
999 zone_meta_validate(z, meta, zone_meta_to_addr(meta));
1000 }
1001
1002 __header_always_inline void
zone_meta_queue_push(zone_t z,zone_pva_t * headp,struct zone_page_metadata * meta)1003 zone_meta_queue_push(zone_t z, zone_pva_t *headp,
1004 struct zone_page_metadata *meta)
1005 {
1006 zone_pva_t head = *headp;
1007 zone_pva_t queue_pva = zone_queue_encode(headp);
1008 struct zone_page_metadata *tmp;
1009
1010 meta->zm_page_next = head;
1011 if (!zone_pva_is_null(head)) {
1012 tmp = zone_pva_to_meta(head);
1013 if (!zone_pva_is_equal(tmp->zm_page_prev, queue_pva)) {
1014 zone_page_metadata_list_corruption(z, meta);
1015 }
1016 tmp->zm_page_prev = zone_pva_from_meta(meta);
1017 }
1018 meta->zm_page_prev = queue_pva;
1019 *headp = zone_pva_from_meta(meta);
1020 }
1021
1022 __header_always_inline struct zone_page_metadata *
zone_meta_queue_pop(zone_t z,zone_pva_t * headp)1023 zone_meta_queue_pop(zone_t z, zone_pva_t *headp)
1024 {
1025 zone_pva_t head = *headp;
1026 struct zone_page_metadata *meta = zone_pva_to_meta(head);
1027 struct zone_page_metadata *tmp;
1028
1029 zone_meta_validate(z, meta);
1030
1031 if (!zone_pva_is_null(meta->zm_page_next)) {
1032 tmp = zone_pva_to_meta(meta->zm_page_next);
1033 if (!zone_pva_is_equal(tmp->zm_page_prev, head)) {
1034 zone_page_metadata_list_corruption(z, meta);
1035 }
1036 tmp->zm_page_prev = meta->zm_page_prev;
1037 }
1038 *headp = meta->zm_page_next;
1039
1040 meta->zm_page_next = meta->zm_page_prev = (zone_pva_t){ 0 };
1041
1042 return meta;
1043 }
1044
1045 __header_always_inline void
zone_meta_remqueue(zone_t z,struct zone_page_metadata * meta)1046 zone_meta_remqueue(zone_t z, struct zone_page_metadata *meta)
1047 {
1048 zone_pva_t meta_pva = zone_pva_from_meta(meta);
1049 struct zone_page_metadata *tmp;
1050
1051 if (!zone_pva_is_null(meta->zm_page_next)) {
1052 tmp = zone_pva_to_meta(meta->zm_page_next);
1053 if (!zone_pva_is_equal(tmp->zm_page_prev, meta_pva)) {
1054 zone_page_metadata_list_corruption(z, meta);
1055 }
1056 tmp->zm_page_prev = meta->zm_page_prev;
1057 }
1058 if (zone_pva_is_queue(meta->zm_page_prev)) {
1059 zone_queue_set_head(z, meta->zm_page_prev, meta_pva, meta);
1060 } else {
1061 tmp = zone_pva_to_meta(meta->zm_page_prev);
1062 if (!zone_pva_is_equal(tmp->zm_page_next, meta_pva)) {
1063 zone_page_metadata_list_corruption(z, meta);
1064 }
1065 tmp->zm_page_next = meta->zm_page_next;
1066 }
1067
1068 meta->zm_page_next = meta->zm_page_prev = (zone_pva_t){ 0 };
1069 }
1070
1071 __header_always_inline void
zone_meta_requeue(zone_t z,zone_pva_t * headp,struct zone_page_metadata * meta)1072 zone_meta_requeue(zone_t z, zone_pva_t *headp,
1073 struct zone_page_metadata *meta)
1074 {
1075 zone_meta_remqueue(z, meta);
1076 zone_meta_queue_push(z, headp, meta);
1077 }
1078
1079 /* prevents a given metadata from ever reaching the z_pageq_empty queue */
1080 static inline void
zone_meta_lock_in_partial(zone_t z,struct zone_page_metadata * m,uint32_t len)1081 zone_meta_lock_in_partial(zone_t z, struct zone_page_metadata *m, uint32_t len)
1082 {
1083 uint16_t new_size = zone_meta_alloc_size_add(z, m, ZM_ALLOC_SIZE_LOCK);
1084
1085 assert(new_size % sizeof(vm_offset_t) == ZM_ALLOC_SIZE_LOCK);
1086 if (new_size == ZM_ALLOC_SIZE_LOCK) {
1087 zone_meta_requeue(z, &z->z_pageq_partial, m);
1088 zone_counter_sub(z, z_wired_empty, len);
1089 }
1090 }
1091
1092 /* allows a given metadata to reach the z_pageq_empty queue again */
1093 static inline void
zone_meta_unlock_from_partial(zone_t z,struct zone_page_metadata * m,uint32_t len)1094 zone_meta_unlock_from_partial(zone_t z, struct zone_page_metadata *m, uint32_t len)
1095 {
1096 uint16_t new_size = zone_meta_alloc_size_sub(z, m, ZM_ALLOC_SIZE_LOCK);
1097
1098 assert(new_size % sizeof(vm_offset_t) == 0);
1099 if (new_size == 0) {
1100 zone_meta_requeue(z, &z->z_pageq_empty, m);
1101 z->z_wired_empty += len;
1102 }
1103 }
1104
1105 /*
1106 * Routine to populate a page backing metadata in the zone_metadata_region.
1107 * Must be called without the zone lock held as it might potentially block.
1108 */
1109 static void
zone_meta_populate(vm_offset_t base,vm_size_t size)1110 zone_meta_populate(vm_offset_t base, vm_size_t size)
1111 {
1112 struct zone_page_metadata *from = zone_meta_from_addr(base);
1113 struct zone_page_metadata *to = from + atop(size);
1114 vm_offset_t page_addr = trunc_page(from);
1115
1116 for (; page_addr < (vm_offset_t)to; page_addr += PAGE_SIZE) {
1117 #if !KASAN
1118 /*
1119 * This can race with another thread doing a populate on the same metadata
1120 * page, where we see an updated pmap but unmapped KASan shadow, causing a
1121 * fault in the shadow when we first access the metadata page. Avoid this
1122 * by always synchronizing on the zone_metadata_region lock with KASan.
1123 */
1124 if (pmap_find_phys(kernel_pmap, page_addr)) {
1125 continue;
1126 }
1127 #endif
1128
1129 for (;;) {
1130 kern_return_t ret = KERN_SUCCESS;
1131
1132 /*
1133 * All updates to the zone_metadata_region are done
1134 * under the zone_metadata_region_lck
1135 */
1136 zone_meta_lock();
1137 if (0 == pmap_find_phys(kernel_pmap, page_addr)) {
1138 ret = kernel_memory_populate(page_addr,
1139 PAGE_SIZE, KMA_NOPAGEWAIT | KMA_KOBJECT | KMA_ZERO,
1140 VM_KERN_MEMORY_OSFMK);
1141 }
1142 zone_meta_unlock();
1143
1144 if (ret == KERN_SUCCESS) {
1145 break;
1146 }
1147
1148 /*
1149 * We can't pass KMA_NOPAGEWAIT under a global lock as it leads
1150 * to bad system deadlocks, so if the allocation failed,
1151 * we need to do the VM_PAGE_WAIT() outside of the lock.
1152 */
1153 VM_PAGE_WAIT();
1154 }
1155 }
1156 }
1157
1158 __abortlike
1159 static void
zone_invalid_element_panic(zone_t zone,vm_offset_t addr)1160 zone_invalid_element_panic(zone_t zone, vm_offset_t addr)
1161 {
1162 struct zone_page_metadata *meta;
1163 const char *from_cache = "";
1164 vm_offset_t page;
1165
1166 if (!from_zone_map(addr, zone_elem_inner_size(zone))) {
1167 panic("addr %p being freed to zone %s%s%s, isn't from zone map",
1168 (void *)addr, zone_heap_name(zone), zone->z_name, from_cache);
1169 }
1170 page = trunc_page(addr);
1171 meta = zone_meta_from_addr(addr);
1172
1173 if (!zone_has_index(zone, meta->zm_index)) {
1174 zone_page_metadata_index_confusion_panic(zone, addr, meta);
1175 }
1176
1177 if (meta->zm_chunk_len == ZM_SECONDARY_PCPU_PAGE) {
1178 panic("metadata %p corresponding to addr %p being freed to "
1179 "zone %s%s%s, is marked as secondary per cpu page",
1180 meta, (void *)addr, zone_heap_name(zone), zone->z_name,
1181 from_cache);
1182 }
1183 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1184 page -= ptoa(meta->zm_page_index);
1185 meta -= meta->zm_page_index;
1186 }
1187
1188 if (meta->zm_chunk_len > ZM_CHUNK_LEN_MAX) {
1189 panic("metadata %p corresponding to addr %p being freed to "
1190 "zone %s%s%s, has chunk len greater than max",
1191 meta, (void *)addr, zone_heap_name(zone), zone->z_name,
1192 from_cache);
1193 }
1194
1195 if ((addr - zone_elem_inner_offs(zone) - page) % zone_elem_outer_size(zone)) {
1196 panic("addr %p being freed to zone %s%s%s, isn't aligned to "
1197 "zone element size", (void *)addr, zone_heap_name(zone),
1198 zone->z_name, from_cache);
1199 }
1200
1201 zone_invalid_element_addr_panic(zone, addr);
1202 }
1203
1204 __attribute__((always_inline))
1205 static struct zone_page_metadata *
zone_element_resolve(zone_t zone,vm_offset_t addr,vm_offset_t * idx)1206 zone_element_resolve(
1207 zone_t zone,
1208 vm_offset_t addr,
1209 vm_offset_t *idx)
1210 {
1211 struct zone_page_metadata *meta;
1212 vm_offset_t offs, eidx;
1213
1214 meta = zone_meta_from_addr(addr);
1215 if (!from_zone_map(addr, 1) || !zone_has_index(zone, meta->zm_index)) {
1216 zone_invalid_element_panic(zone, addr);
1217 }
1218
1219 offs = (addr & PAGE_MASK) - zone_elem_inner_offs(zone);
1220 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1221 offs += ptoa(meta->zm_page_index);
1222 meta -= meta->zm_page_index;
1223 }
1224
1225 eidx = Z_FAST_QUO(offs, zone->z_quo_magic);
1226 if (eidx * zone_elem_outer_size(zone) != offs) {
1227 zone_invalid_element_panic(zone, addr);
1228 }
1229
1230 *idx = eidx;
1231 return meta;
1232 }
1233
1234 #if ZSECURITY_CONFIG(PGZ_OOB_ADJUST)
1235 void *
zone_element_pgz_oob_adjust(void * ptr,vm_size_t req_size,vm_size_t elem_size)1236 zone_element_pgz_oob_adjust(void *ptr, vm_size_t req_size, vm_size_t elem_size)
1237 {
1238 vm_offset_t addr = (vm_offset_t)ptr;
1239 vm_offset_t end = addr + elem_size;
1240 vm_offset_t offs;
1241
1242 /*
1243 * 0-sized allocations in a KALLOC_MINSIZE bucket
1244 * would be offset to the next allocation which is incorrect.
1245 */
1246 req_size = MAX(roundup(req_size, KALLOC_MINALIGN), KALLOC_MINALIGN);
1247
1248 /*
1249 * Given how chunks work, for a zone with PGZ guards on,
1250 * there's a single element which ends precisely
1251 * at the page boundary: the last one.
1252 */
1253 if (req_size == elem_size ||
1254 (end & PAGE_MASK) ||
1255 !zone_meta_from_addr(addr)->zm_guarded) {
1256 return ptr;
1257 }
1258
1259 offs = elem_size - req_size;
1260 zone_meta_from_addr(end)->zm_oob_offs = (uint16_t)offs;
1261
1262 return (char *)addr + offs;
1263 }
1264 #endif /* !ZSECURITY_CONFIG(PGZ_OOB_ADJUST) */
1265
1266 __abortlike
1267 static void
zone_element_bounds_check_panic(vm_address_t addr,vm_size_t len)1268 zone_element_bounds_check_panic(vm_address_t addr, vm_size_t len)
1269 {
1270 struct zone_page_metadata *meta;
1271 vm_offset_t offs, size, page;
1272 zone_t zone;
1273
1274 page = trunc_page(addr);
1275 meta = zone_meta_from_addr(addr);
1276 zone = &zone_array[meta->zm_index];
1277
1278 if (zone->z_percpu) {
1279 panic("zone bound checks: address %p is a per-cpu allocation",
1280 (void *)addr);
1281 }
1282
1283 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1284 page -= ptoa(meta->zm_page_index);
1285 meta -= meta->zm_page_index;
1286 }
1287
1288 size = zone_elem_outer_size(zone);
1289 offs = Z_FAST_MOD(addr - zone_elem_inner_offs(zone) - page + size,
1290 zone->z_quo_magic, size);
1291 panic("zone bound checks: buffer %p of length %zd overflows "
1292 "object %p of size %zd in zone %p[%s%s]",
1293 (void *)addr, len, (void *)(addr - offs - zone_elem_redzone(zone)),
1294 zone_elem_inner_size(zone), zone, zone_heap_name(zone), zone_name(zone));
1295 }
1296
1297 void
zone_element_bounds_check(vm_address_t addr,vm_size_t len)1298 zone_element_bounds_check(vm_address_t addr, vm_size_t len)
1299 {
1300 struct zone_page_metadata *meta;
1301 vm_offset_t offs, size;
1302 zone_t zone;
1303
1304 if (!from_zone_map(addr, 1)) {
1305 return;
1306 }
1307
1308 #if CONFIG_PROB_GZALLOC
1309 if (__improbable(pgz_owned(addr))) {
1310 meta = zone_meta_from_addr(addr);
1311 addr = trunc_page(meta->zm_pgz_orig_addr) + (addr & PAGE_MASK);
1312 }
1313 #endif /* CONFIG_PROB_GZALLOC */
1314 meta = zone_meta_from_addr(addr);
1315 zone = zone_by_id(meta->zm_index);
1316
1317 if (zone->z_percpu) {
1318 zone_element_bounds_check_panic(addr, len);
1319 }
1320
1321 if (zone->z_permanent) {
1322 /* We don't know bounds for those */
1323 return;
1324 }
1325
1326 offs = (addr & PAGE_MASK) - zone_elem_inner_offs(zone);
1327 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1328 offs += ptoa(meta->zm_page_index);
1329 }
1330 size = zone_elem_outer_size(zone);
1331 offs = Z_FAST_MOD(offs + size, zone->z_quo_magic, size);
1332 if (len + zone_elem_redzone(zone) > size - offs) {
1333 zone_element_bounds_check_panic(addr, len);
1334 }
1335 }
1336
1337 /*
1338 * Routine to get the size of a zone allocated address.
1339 * If the address doesnt belong to the zone maps, returns 0.
1340 */
1341 vm_size_t
zone_element_size(void * elem,zone_t * z,bool clear_oob,vm_offset_t * oob_offs)1342 zone_element_size(void *elem, zone_t *z, bool clear_oob, vm_offset_t *oob_offs)
1343 {
1344 vm_address_t addr = (vm_address_t)elem;
1345 struct zone_page_metadata *meta;
1346 vm_size_t esize, offs, end;
1347 zone_t zone;
1348
1349 if (from_zone_map(addr, sizeof(void *))) {
1350 meta = zone_meta_from_addr(addr);
1351 zone = zone_by_id(meta->zm_index);
1352 esize = zone_elem_inner_size(zone);
1353 end = vm_memtag_canonicalize_address(addr + esize);
1354 offs = 0;
1355
1356 #if ZSECURITY_CONFIG(PGZ_OOB_ADJUST)
1357 /*
1358 * If the chunk uses guards, and that (addr + esize)
1359 * either crosses a page boundary or is at the boundary,
1360 * we need to look harder.
1361 */
1362 if (oob_offs && meta->zm_guarded && atop(addr ^ end)) {
1363 /*
1364 * Because in the vast majority of cases the element
1365 * size is sub-page, and that meta[1] must be faulted,
1366 * we can quickly peek at whether it's a guard.
1367 *
1368 * For elements larger than a page, finding the guard
1369 * page requires a little more effort.
1370 */
1371 if (meta[1].zm_chunk_len == ZM_PGZ_GUARD) {
1372 offs = meta[1].zm_oob_offs;
1373 if (clear_oob) {
1374 meta[1].zm_oob_offs = 0;
1375 }
1376 } else if (esize > PAGE_SIZE) {
1377 struct zone_page_metadata *gmeta;
1378
1379 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1380 gmeta = meta + meta->zm_subchunk_len;
1381 } else {
1382 gmeta = meta + zone->z_chunk_pages;
1383 }
1384 assert(gmeta->zm_chunk_len == ZM_PGZ_GUARD);
1385
1386 if (end >= zone_meta_to_addr(gmeta)) {
1387 offs = gmeta->zm_oob_offs;
1388 if (clear_oob) {
1389 gmeta->zm_oob_offs = 0;
1390 }
1391 }
1392 }
1393 }
1394 #else
1395 #pragma unused(end, clear_oob)
1396 #endif /* ZSECURITY_CONFIG(PGZ_OOB_ADJUST) */
1397
1398 if (oob_offs) {
1399 *oob_offs = offs;
1400 }
1401 if (z) {
1402 *z = zone;
1403 }
1404 return esize;
1405 }
1406
1407 if (oob_offs) {
1408 *oob_offs = 0;
1409 }
1410
1411 return 0;
1412 }
1413
1414 zone_id_t
zone_id_for_element(void * addr,vm_size_t esize)1415 zone_id_for_element(void *addr, vm_size_t esize)
1416 {
1417 zone_id_t zid = ZONE_ID_INVALID;
1418 if (from_zone_map(addr, esize)) {
1419 zid = zone_index_from_ptr(addr);
1420 __builtin_assume(zid != ZONE_ID_INVALID);
1421 }
1422 return zid;
1423 }
1424
1425 /* This function just formats the reason for the panics by redoing the checks */
1426 __abortlike
1427 static void
zone_require_panic(zone_t zone,void * addr)1428 zone_require_panic(zone_t zone, void *addr)
1429 {
1430 uint32_t zindex;
1431 zone_t other;
1432
1433 if (!from_zone_map(addr, zone_elem_inner_size(zone))) {
1434 panic("zone_require failed: address not in a zone (addr: %p)", addr);
1435 }
1436
1437 zindex = zone_index_from_ptr(addr);
1438 other = &zone_array[zindex];
1439 if (zindex >= os_atomic_load(&num_zones, relaxed) || !other->z_self) {
1440 panic("zone_require failed: invalid zone index %d "
1441 "(addr: %p, expected: %s%s)", zindex,
1442 addr, zone_heap_name(zone), zone->z_name);
1443 } else {
1444 panic("zone_require failed: address in unexpected zone id %d (%s%s) "
1445 "(addr: %p, expected: %s%s)",
1446 zindex, zone_heap_name(other), other->z_name,
1447 addr, zone_heap_name(zone), zone->z_name);
1448 }
1449 }
1450
1451 __abortlike
1452 static void
zone_id_require_panic(zone_id_t zid,void * addr)1453 zone_id_require_panic(zone_id_t zid, void *addr)
1454 {
1455 zone_require_panic(&zone_array[zid], addr);
1456 }
1457
1458 /*
1459 * Routines to panic if a pointer is not mapped to an expected zone.
1460 * This can be used as a means of pinning an object to the zone it is expected
1461 * to be a part of. Causes a panic if the address does not belong to any
1462 * specified zone, does not belong to any zone, has been freed and therefore
1463 * unmapped from the zone, or the pointer contains an uninitialized value that
1464 * does not belong to any zone.
1465 */
1466 void
zone_require(zone_t zone,void * addr)1467 zone_require(zone_t zone, void *addr)
1468 {
1469 vm_size_t esize = zone_elem_inner_size(zone);
1470
1471 if (from_zone_map(addr, esize) &&
1472 zone_has_index(zone, zone_index_from_ptr(addr))) {
1473 return;
1474 }
1475 zone_require_panic(zone, addr);
1476 }
1477
1478 void
zone_id_require(zone_id_t zid,vm_size_t esize,void * addr)1479 zone_id_require(zone_id_t zid, vm_size_t esize, void *addr)
1480 {
1481 if (from_zone_map(addr, esize) && zid == zone_index_from_ptr(addr)) {
1482 return;
1483 }
1484 zone_id_require_panic(zid, addr);
1485 }
1486
1487 void
zone_id_require_aligned(zone_id_t zid,void * addr)1488 zone_id_require_aligned(zone_id_t zid, void *addr)
1489 {
1490 zone_t zone = zone_by_id(zid);
1491 vm_offset_t elem, offs;
1492
1493 elem = (vm_offset_t)addr;
1494 offs = (elem & PAGE_MASK) - zone_elem_inner_offs(zone);
1495
1496 if (from_zone_map(addr, 1)) {
1497 struct zone_page_metadata *meta;
1498
1499 meta = zone_meta_from_addr(elem);
1500 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1501 offs += ptoa(meta->zm_page_index);
1502 }
1503
1504 if (zid == meta->zm_index &&
1505 Z_FAST_ALIGNED(offs, zone->z_align_magic)) {
1506 return;
1507 }
1508 }
1509
1510 zone_invalid_element_panic(zone, elem);
1511 }
1512
1513 bool
zone_owns(zone_t zone,void * addr)1514 zone_owns(zone_t zone, void *addr)
1515 {
1516 vm_size_t esize = zone_elem_inner_size(zone);
1517
1518 if (from_zone_map(addr, esize)) {
1519 return zone_has_index(zone, zone_index_from_ptr(addr));
1520 }
1521 return false;
1522 }
1523
1524 static inline struct mach_vm_range
zone_kmem_suballoc(mach_vm_offset_t addr,vm_size_t size,int flags,vm_tag_t tag,vm_map_t * new_map)1525 zone_kmem_suballoc(
1526 mach_vm_offset_t addr,
1527 vm_size_t size,
1528 int flags,
1529 vm_tag_t tag,
1530 vm_map_t *new_map)
1531 {
1532 struct mach_vm_range r;
1533
1534 *new_map = kmem_suballoc(kernel_map, &addr, size,
1535 VM_MAP_CREATE_NEVER_FAULTS | VM_MAP_CREATE_DISABLE_HOLELIST,
1536 flags, KMS_PERMANENT | KMS_NOFAIL, tag).kmr_submap;
1537
1538 r.min_address = addr;
1539 r.max_address = addr + size;
1540 return r;
1541 }
1542
1543 #endif /* !ZALLOC_TEST */
1544 #pragma mark Zone bits allocator
1545
1546 /*!
1547 * @defgroup Zone Bitmap allocator
1548 * @{
1549 *
1550 * @brief
1551 * Functions implementing the zone bitmap allocator
1552 *
1553 * @discussion
1554 * The zone allocator maintains which elements are allocated or free in bitmaps.
1555 *
1556 * When the number of elements per page is smaller than 32, it is stored inline
1557 * on the @c zone_page_metadata structure (@c zm_inline_bitmap is set,
1558 * and @c zm_bitmap used for storage).
1559 *
1560 * When the number of elements is larger, then a bitmap is allocated from
1561 * a buddy allocator (impelemented under the @c zba_* namespace). Pointers
1562 * to bitmaps are implemented as a packed 32 bit bitmap reference, stored in
1563 * @c zm_bitmap. The low 3 bits encode the scale (order) of the allocation in
1564 * @c ZBA_GRANULE units, and hence actual allocations encoded with that scheme
1565 * cannot be larger than 1024 bytes (8192 bits).
1566 *
1567 * This buddy allocator can actually accomodate allocations as large
1568 * as 8k on 16k systems and 2k on 4k systems.
1569 *
1570 * Note: @c zba_* functions are implementation details not meant to be used
1571 * outside of the allocation of the allocator itself. Interfaces to the rest of
1572 * the zone allocator are documented and not @c zba_* prefixed.
1573 */
1574
1575 #define ZBA_CHUNK_SIZE PAGE_MAX_SIZE
1576 #define ZBA_GRANULE sizeof(uint64_t)
1577 #define ZBA_GRANULE_BITS (8 * sizeof(uint64_t))
1578 #define ZBA_MAX_ORDER (PAGE_MAX_SHIFT - 4)
1579 #define ZBA_MAX_ALLOC_ORDER 7
1580 #define ZBA_SLOTS (ZBA_CHUNK_SIZE / ZBA_GRANULE)
1581 #define ZBA_HEADS_COUNT (ZBA_MAX_ORDER + 1)
1582 #define ZBA_PTR_MASK 0x0fffffff
1583 #define ZBA_ORDER_SHIFT 29
1584 #define ZBA_HAS_EXTRA_BIT 0x10000000
1585
1586 static_assert(2ul * ZBA_GRANULE << ZBA_MAX_ORDER == ZBA_CHUNK_SIZE, "chunk sizes");
1587 static_assert(ZBA_MAX_ALLOC_ORDER <= ZBA_MAX_ORDER, "ZBA_MAX_ORDER is enough");
1588
1589 struct zone_bits_chain {
1590 uint32_t zbc_next;
1591 uint32_t zbc_prev;
1592 } __attribute__((aligned(ZBA_GRANULE)));
1593
1594 struct zone_bits_head {
1595 uint32_t zbh_next;
1596 uint32_t zbh_unused;
1597 } __attribute__((aligned(ZBA_GRANULE)));
1598
1599 static_assert(sizeof(struct zone_bits_chain) == ZBA_GRANULE, "zbc size");
1600 static_assert(sizeof(struct zone_bits_head) == ZBA_GRANULE, "zbh size");
1601
1602 struct zone_bits_allocator_meta {
1603 uint32_t zbam_left;
1604 uint32_t zbam_right;
1605 struct zone_bits_head zbam_lists[ZBA_HEADS_COUNT];
1606 struct zone_bits_head zbam_lists_with_extra[ZBA_HEADS_COUNT];
1607 };
1608
1609 struct zone_bits_allocator_header {
1610 uint64_t zbah_bits[ZBA_SLOTS / (8 * sizeof(uint64_t))];
1611 };
1612
1613 #if ZALLOC_TEST
1614 static struct zalloc_bits_allocator_test_setup {
1615 vm_offset_t zbats_base;
1616 void (*zbats_populate)(vm_address_t addr, vm_size_t size);
1617 } zba_test_info;
1618
1619 static struct zone_bits_allocator_header *
zba_base_header(void)1620 zba_base_header(void)
1621 {
1622 return (struct zone_bits_allocator_header *)zba_test_info.zbats_base;
1623 }
1624
1625 static kern_return_t
zba_populate(uint32_t n,bool with_extra __unused)1626 zba_populate(uint32_t n, bool with_extra __unused)
1627 {
1628 vm_address_t base = zba_test_info.zbats_base;
1629 zba_test_info.zbats_populate(base + n * ZBA_CHUNK_SIZE, ZBA_CHUNK_SIZE);
1630
1631 return KERN_SUCCESS;
1632 }
1633 #else
1634 __startup_data __attribute__((aligned(ZBA_CHUNK_SIZE)))
1635 static uint8_t zba_chunk_startup[ZBA_CHUNK_SIZE];
1636
1637 static SECURITY_READ_ONLY_LATE(uint8_t) zba_xtra_shift;
1638 static LCK_MTX_DECLARE(zba_mtx, &zone_locks_grp);
1639
1640 static struct zone_bits_allocator_header *
zba_base_header(void)1641 zba_base_header(void)
1642 {
1643 return (struct zone_bits_allocator_header *)zone_info.zi_bits_range.min_address;
1644 }
1645
1646 static void
zba_lock(void)1647 zba_lock(void)
1648 {
1649 lck_mtx_lock(&zba_mtx);
1650 }
1651
1652 static void
zba_unlock(void)1653 zba_unlock(void)
1654 {
1655 lck_mtx_unlock(&zba_mtx);
1656 }
1657
1658 __abortlike
1659 static void
zba_memory_exhausted(void)1660 zba_memory_exhausted(void)
1661 {
1662 uint64_t zsize = 0;
1663 zone_t z = zone_find_largest(&zsize);
1664 panic("zba_populate: out of bitmap space, "
1665 "likely due to memory leak in zone [%s%s] "
1666 "(%u%c, %d elements allocated)",
1667 zone_heap_name(z), zone_name(z),
1668 mach_vm_size_pretty(zsize), mach_vm_size_unit(zsize),
1669 zone_count_allocated(z));
1670 }
1671
1672
1673 static kern_return_t
zba_populate(uint32_t n,bool with_extra)1674 zba_populate(uint32_t n, bool with_extra)
1675 {
1676 vm_size_t bits_size = ZBA_CHUNK_SIZE;
1677 vm_size_t xtra_size = bits_size * CHAR_BIT << zba_xtra_shift;
1678 vm_address_t bits_addr;
1679 vm_address_t xtra_addr;
1680 kern_return_t kr;
1681
1682 bits_addr = zone_info.zi_bits_range.min_address + n * bits_size;
1683 xtra_addr = zone_info.zi_xtra_range.min_address + n * xtra_size;
1684
1685 kr = kernel_memory_populate(bits_addr, bits_size,
1686 KMA_ZERO | KMA_KOBJECT | KMA_NOPAGEWAIT,
1687 VM_KERN_MEMORY_OSFMK);
1688 if (kr != KERN_SUCCESS) {
1689 return kr;
1690 }
1691
1692
1693 if (with_extra) {
1694 kr = kernel_memory_populate(xtra_addr, xtra_size,
1695 KMA_ZERO | KMA_KOBJECT | KMA_NOPAGEWAIT,
1696 VM_KERN_MEMORY_OSFMK);
1697 if (kr != KERN_SUCCESS) {
1698 kernel_memory_depopulate(bits_addr, bits_size,
1699 KMA_ZERO | KMA_KOBJECT | KMA_NOPAGEWAIT,
1700 VM_KERN_MEMORY_OSFMK);
1701 }
1702 }
1703
1704 return kr;
1705 }
1706 #endif
1707
1708 __pure2
1709 static struct zone_bits_allocator_meta *
zba_meta(void)1710 zba_meta(void)
1711 {
1712 return (struct zone_bits_allocator_meta *)&zba_base_header()[1];
1713 }
1714
1715 __pure2
1716 static uint64_t *
zba_slot_base(void)1717 zba_slot_base(void)
1718 {
1719 return (uint64_t *)zba_base_header();
1720 }
1721
1722 __pure2
1723 static struct zone_bits_head *
zba_head(uint32_t order,bool with_extra)1724 zba_head(uint32_t order, bool with_extra)
1725 {
1726 if (with_extra) {
1727 return &zba_meta()->zbam_lists_with_extra[order];
1728 } else {
1729 return &zba_meta()->zbam_lists[order];
1730 }
1731 }
1732
1733 __pure2
1734 static uint32_t
zba_head_index(struct zone_bits_head * hd)1735 zba_head_index(struct zone_bits_head *hd)
1736 {
1737 return (uint32_t)((uint64_t *)hd - zba_slot_base());
1738 }
1739
1740 __pure2
1741 static struct zone_bits_chain *
zba_chain_for_index(uint32_t index)1742 zba_chain_for_index(uint32_t index)
1743 {
1744 return (struct zone_bits_chain *)(zba_slot_base() + index);
1745 }
1746
1747 __pure2
1748 static uint32_t
zba_chain_to_index(const struct zone_bits_chain * zbc)1749 zba_chain_to_index(const struct zone_bits_chain *zbc)
1750 {
1751 return (uint32_t)((const uint64_t *)zbc - zba_slot_base());
1752 }
1753
1754 __abortlike
1755 static void
zba_head_corruption_panic(uint32_t order,bool with_extra)1756 zba_head_corruption_panic(uint32_t order, bool with_extra)
1757 {
1758 panic("zone bits allocator head[%d:%d:%p] is corrupt",
1759 order, with_extra, zba_head(order, with_extra));
1760 }
1761
1762 __abortlike
1763 static void
zba_chain_corruption_panic(struct zone_bits_chain * a,struct zone_bits_chain * b)1764 zba_chain_corruption_panic(struct zone_bits_chain *a, struct zone_bits_chain *b)
1765 {
1766 panic("zone bits allocator freelist is corrupt (%p <-> %p)", a, b);
1767 }
1768
1769 static void
zba_push_block(struct zone_bits_chain * zbc,uint32_t order,bool with_extra)1770 zba_push_block(struct zone_bits_chain *zbc, uint32_t order, bool with_extra)
1771 {
1772 struct zone_bits_head *hd = zba_head(order, with_extra);
1773 uint32_t hd_index = zba_head_index(hd);
1774 uint32_t index = zba_chain_to_index(zbc);
1775 struct zone_bits_chain *next;
1776
1777 if (hd->zbh_next) {
1778 next = zba_chain_for_index(hd->zbh_next);
1779 if (next->zbc_prev != hd_index) {
1780 zba_head_corruption_panic(order, with_extra);
1781 }
1782 next->zbc_prev = index;
1783 }
1784 zbc->zbc_next = hd->zbh_next;
1785 zbc->zbc_prev = hd_index;
1786 hd->zbh_next = index;
1787 }
1788
1789 static void
zba_remove_block(struct zone_bits_chain * zbc)1790 zba_remove_block(struct zone_bits_chain *zbc)
1791 {
1792 struct zone_bits_chain *prev = zba_chain_for_index(zbc->zbc_prev);
1793 uint32_t index = zba_chain_to_index(zbc);
1794
1795 if (prev->zbc_next != index) {
1796 zba_chain_corruption_panic(prev, zbc);
1797 }
1798 if ((prev->zbc_next = zbc->zbc_next)) {
1799 struct zone_bits_chain *next = zba_chain_for_index(zbc->zbc_next);
1800 if (next->zbc_prev != index) {
1801 zba_chain_corruption_panic(zbc, next);
1802 }
1803 next->zbc_prev = zbc->zbc_prev;
1804 }
1805 }
1806
1807 static vm_address_t
zba_try_pop_block(uint32_t order,bool with_extra)1808 zba_try_pop_block(uint32_t order, bool with_extra)
1809 {
1810 struct zone_bits_head *hd = zba_head(order, with_extra);
1811 struct zone_bits_chain *zbc;
1812
1813 if (hd->zbh_next == 0) {
1814 return 0;
1815 }
1816
1817 zbc = zba_chain_for_index(hd->zbh_next);
1818 zba_remove_block(zbc);
1819 return (vm_address_t)zbc;
1820 }
1821
1822 static struct zone_bits_allocator_header *
zba_header(vm_offset_t addr)1823 zba_header(vm_offset_t addr)
1824 {
1825 addr &= -(vm_offset_t)ZBA_CHUNK_SIZE;
1826 return (struct zone_bits_allocator_header *)addr;
1827 }
1828
1829 static size_t
zba_node_parent(size_t node)1830 zba_node_parent(size_t node)
1831 {
1832 return (node - 1) / 2;
1833 }
1834
1835 static size_t
zba_node_left_child(size_t node)1836 zba_node_left_child(size_t node)
1837 {
1838 return node * 2 + 1;
1839 }
1840
1841 static size_t
zba_node_buddy(size_t node)1842 zba_node_buddy(size_t node)
1843 {
1844 return ((node - 1) ^ 1) + 1;
1845 }
1846
1847 static size_t
zba_node(vm_offset_t addr,uint32_t order)1848 zba_node(vm_offset_t addr, uint32_t order)
1849 {
1850 vm_offset_t offs = (addr % ZBA_CHUNK_SIZE) / ZBA_GRANULE;
1851 return (offs >> order) + (1 << (ZBA_MAX_ORDER - order + 1)) - 1;
1852 }
1853
1854 static struct zone_bits_chain *
zba_chain_for_node(struct zone_bits_allocator_header * zbah,size_t node,uint32_t order)1855 zba_chain_for_node(struct zone_bits_allocator_header *zbah, size_t node, uint32_t order)
1856 {
1857 vm_offset_t offs = (node - (1 << (ZBA_MAX_ORDER - order + 1)) + 1) << order;
1858 return (struct zone_bits_chain *)((vm_offset_t)zbah + offs * ZBA_GRANULE);
1859 }
1860
1861 static void
zba_node_flip_split(struct zone_bits_allocator_header * zbah,size_t node)1862 zba_node_flip_split(struct zone_bits_allocator_header *zbah, size_t node)
1863 {
1864 zbah->zbah_bits[node / 64] ^= 1ull << (node % 64);
1865 }
1866
1867 static bool
zba_node_is_split(struct zone_bits_allocator_header * zbah,size_t node)1868 zba_node_is_split(struct zone_bits_allocator_header *zbah, size_t node)
1869 {
1870 return zbah->zbah_bits[node / 64] & (1ull << (node % 64));
1871 }
1872
1873 static void
zba_free(vm_offset_t addr,uint32_t order,bool with_extra)1874 zba_free(vm_offset_t addr, uint32_t order, bool with_extra)
1875 {
1876 struct zone_bits_allocator_header *zbah = zba_header(addr);
1877 struct zone_bits_chain *zbc;
1878 size_t node = zba_node(addr, order);
1879
1880 while (node) {
1881 size_t parent = zba_node_parent(node);
1882
1883 zba_node_flip_split(zbah, parent);
1884 if (zba_node_is_split(zbah, parent)) {
1885 break;
1886 }
1887
1888 zbc = zba_chain_for_node(zbah, zba_node_buddy(node), order);
1889 zba_remove_block(zbc);
1890 order++;
1891 node = parent;
1892 }
1893
1894 zba_push_block(zba_chain_for_node(zbah, node, order), order, with_extra);
1895 }
1896
1897 static vm_size_t
zba_chunk_header_size(uint32_t n)1898 zba_chunk_header_size(uint32_t n)
1899 {
1900 vm_size_t hdr_size = sizeof(struct zone_bits_allocator_header);
1901 if (n == 0) {
1902 hdr_size += sizeof(struct zone_bits_allocator_meta);
1903 }
1904 return hdr_size;
1905 }
1906
1907 static void
zba_init_chunk(uint32_t n,bool with_extra)1908 zba_init_chunk(uint32_t n, bool with_extra)
1909 {
1910 vm_size_t hdr_size = zba_chunk_header_size(n);
1911 vm_offset_t page = (vm_offset_t)zba_base_header() + n * ZBA_CHUNK_SIZE;
1912 struct zone_bits_allocator_header *zbah = zba_header(page);
1913 vm_size_t size = ZBA_CHUNK_SIZE;
1914 size_t node;
1915
1916 for (uint32_t o = ZBA_MAX_ORDER + 1; o-- > 0;) {
1917 if (size < hdr_size + (ZBA_GRANULE << o)) {
1918 continue;
1919 }
1920 size -= ZBA_GRANULE << o;
1921 node = zba_node(page + size, o);
1922 zba_node_flip_split(zbah, zba_node_parent(node));
1923 zba_push_block(zba_chain_for_node(zbah, node, o), o, with_extra);
1924 }
1925 }
1926
1927 __attribute__((noinline))
1928 static void
zba_grow(bool with_extra)1929 zba_grow(bool with_extra)
1930 {
1931 struct zone_bits_allocator_meta *meta = zba_meta();
1932 kern_return_t kr = KERN_SUCCESS;
1933 uint32_t chunk;
1934
1935 #if !ZALLOC_TEST
1936 if (meta->zbam_left >= meta->zbam_right) {
1937 zba_memory_exhausted();
1938 }
1939 #endif
1940
1941 if (with_extra) {
1942 chunk = meta->zbam_right - 1;
1943 } else {
1944 chunk = meta->zbam_left;
1945 }
1946
1947 kr = zba_populate(chunk, with_extra);
1948 if (kr == KERN_SUCCESS) {
1949 if (with_extra) {
1950 meta->zbam_right -= 1;
1951 } else {
1952 meta->zbam_left += 1;
1953 }
1954
1955 zba_init_chunk(chunk, with_extra);
1956 #if !ZALLOC_TEST
1957 } else {
1958 /*
1959 * zba_populate() has to be allowed to fail populating,
1960 * as we are under a global lock, we need to do the
1961 * VM_PAGE_WAIT() outside of the lock.
1962 */
1963 assert(kr == KERN_RESOURCE_SHORTAGE);
1964 zba_unlock();
1965 VM_PAGE_WAIT();
1966 zba_lock();
1967 #endif
1968 }
1969 }
1970
1971 static vm_offset_t
zba_alloc(uint32_t order,bool with_extra)1972 zba_alloc(uint32_t order, bool with_extra)
1973 {
1974 struct zone_bits_allocator_header *zbah;
1975 uint32_t cur = order;
1976 vm_address_t addr;
1977 size_t node;
1978
1979 while ((addr = zba_try_pop_block(cur, with_extra)) == 0) {
1980 if (__improbable(cur++ >= ZBA_MAX_ORDER)) {
1981 zba_grow(with_extra);
1982 cur = order;
1983 }
1984 }
1985
1986 zbah = zba_header(addr);
1987 node = zba_node(addr, cur);
1988 zba_node_flip_split(zbah, zba_node_parent(node));
1989 while (cur > order) {
1990 cur--;
1991 zba_node_flip_split(zbah, node);
1992 node = zba_node_left_child(node);
1993 zba_push_block(zba_chain_for_node(zbah, node + 1, cur),
1994 cur, with_extra);
1995 }
1996
1997 return addr;
1998 }
1999
2000 #define zba_map_index(type, n) (n / (8 * sizeof(type)))
2001 #define zba_map_bit(type, n) ((type)1 << (n % (8 * sizeof(type))))
2002 #define zba_map_mask_lt(type, n) (zba_map_bit(type, n) - 1)
2003 #define zba_map_mask_ge(type, n) ((type)-zba_map_bit(type, n))
2004
2005 #if !ZALLOC_TEST
2006 #if VM_TAG_SIZECLASSES
2007
2008 static void *
zba_extra_ref_ptr(uint32_t bref,vm_offset_t idx)2009 zba_extra_ref_ptr(uint32_t bref, vm_offset_t idx)
2010 {
2011 vm_offset_t base = zone_info.zi_xtra_range.min_address;
2012 vm_offset_t offs = (bref & ZBA_PTR_MASK) * ZBA_GRANULE * CHAR_BIT;
2013
2014 return (void *)(base + ((offs + idx) << zba_xtra_shift));
2015 }
2016
2017 #endif /* VM_TAG_SIZECLASSES */
2018
2019 static uint32_t
zba_bits_ref_order(uint32_t bref)2020 zba_bits_ref_order(uint32_t bref)
2021 {
2022 return bref >> ZBA_ORDER_SHIFT;
2023 }
2024
2025 static bitmap_t *
zba_bits_ref_ptr(uint32_t bref)2026 zba_bits_ref_ptr(uint32_t bref)
2027 {
2028 return zba_slot_base() + (bref & ZBA_PTR_MASK);
2029 }
2030
2031 static vm_offset_t
zba_scan_bitmap_inline(zone_t zone,struct zone_page_metadata * meta,zalloc_flags_t flags,vm_offset_t eidx)2032 zba_scan_bitmap_inline(zone_t zone, struct zone_page_metadata *meta,
2033 zalloc_flags_t flags, vm_offset_t eidx)
2034 {
2035 size_t i = eidx / 32;
2036 uint32_t map;
2037
2038 if (eidx % 32) {
2039 map = meta[i].zm_bitmap & zba_map_mask_ge(uint32_t, eidx);
2040 if (map) {
2041 eidx = __builtin_ctz(map);
2042 meta[i].zm_bitmap ^= 1u << eidx;
2043 return i * 32 + eidx;
2044 }
2045 i++;
2046 }
2047
2048 uint32_t chunk_len = meta->zm_chunk_len;
2049 if (flags & Z_PCPU) {
2050 chunk_len = zpercpu_count();
2051 }
2052 for (int j = 0; j < chunk_len; j++, i++) {
2053 if (i >= chunk_len) {
2054 i = 0;
2055 }
2056 if (__probable(map = meta[i].zm_bitmap)) {
2057 meta[i].zm_bitmap &= map - 1;
2058 return i * 32 + __builtin_ctz(map);
2059 }
2060 }
2061
2062 zone_page_meta_accounting_panic(zone, meta, "zm_bitmap");
2063 }
2064
2065 static vm_offset_t
zba_scan_bitmap_ref(zone_t zone,struct zone_page_metadata * meta,vm_offset_t eidx)2066 zba_scan_bitmap_ref(zone_t zone, struct zone_page_metadata *meta,
2067 vm_offset_t eidx)
2068 {
2069 uint32_t bits_size = 1 << zba_bits_ref_order(meta->zm_bitmap);
2070 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2071 size_t i = eidx / 64;
2072 uint64_t map;
2073
2074 if (eidx % 64) {
2075 map = bits[i] & zba_map_mask_ge(uint64_t, eidx);
2076 if (map) {
2077 eidx = __builtin_ctzll(map);
2078 bits[i] ^= 1ull << eidx;
2079 return i * 64 + eidx;
2080 }
2081 i++;
2082 }
2083
2084 for (int j = 0; j < bits_size; i++, j++) {
2085 if (i >= bits_size) {
2086 i = 0;
2087 }
2088 if (__probable(map = bits[i])) {
2089 bits[i] &= map - 1;
2090 return i * 64 + __builtin_ctzll(map);
2091 }
2092 }
2093
2094 zone_page_meta_accounting_panic(zone, meta, "zm_bitmap");
2095 }
2096
2097 /*!
2098 * @function zone_meta_find_and_clear_bit
2099 *
2100 * @brief
2101 * The core of the bitmap allocator: find a bit set in the bitmaps.
2102 *
2103 * @discussion
2104 * This method will round robin through available allocations,
2105 * with a per-core memory of the last allocated element index allocated.
2106 *
2107 * This is done in order to avoid a fully LIFO behavior which makes exploiting
2108 * double-free bugs way too practical.
2109 *
2110 * @param zone The zone we're allocating from.
2111 * @param meta The main metadata for the chunk being allocated from.
2112 * @param flags the alloc flags (for @c Z_PCPU).
2113 */
2114 static vm_offset_t
zone_meta_find_and_clear_bit(zone_t zone,zone_stats_t zs,struct zone_page_metadata * meta,zalloc_flags_t flags)2115 zone_meta_find_and_clear_bit(
2116 zone_t zone,
2117 zone_stats_t zs,
2118 struct zone_page_metadata *meta,
2119 zalloc_flags_t flags)
2120 {
2121 vm_offset_t eidx = zs->zs_alloc_rr + 1;
2122
2123 if (meta->zm_inline_bitmap) {
2124 eidx = zba_scan_bitmap_inline(zone, meta, flags, eidx);
2125 } else {
2126 eidx = zba_scan_bitmap_ref(zone, meta, eidx);
2127 }
2128 zs->zs_alloc_rr = (uint16_t)eidx;
2129 return eidx;
2130 }
2131
2132 /*!
2133 * @function zone_meta_bits_init_inline
2134 *
2135 * @brief
2136 * Initializes the inline zm_bitmap field(s) for a newly assigned chunk.
2137 *
2138 * @param meta The main metadata for the initialized chunk.
2139 * @param count The number of elements the chunk can hold
2140 * (which might be partial for partially populated chunks).
2141 */
2142 static void
zone_meta_bits_init_inline(struct zone_page_metadata * meta,uint32_t count)2143 zone_meta_bits_init_inline(struct zone_page_metadata *meta, uint32_t count)
2144 {
2145 /*
2146 * We're called with the metadata zm_bitmap fields already zeroed out.
2147 */
2148 for (size_t i = 0; i < count / 32; i++) {
2149 meta[i].zm_bitmap = ~0u;
2150 }
2151 if (count % 32) {
2152 meta[count / 32].zm_bitmap = zba_map_mask_lt(uint32_t, count);
2153 }
2154 }
2155
2156 /*!
2157 * @function zone_meta_bits_alloc_init
2158 *
2159 * @brief
2160 * Allocates a zm_bitmap field for a newly assigned chunk.
2161 *
2162 * @param count The number of elements the chunk can hold
2163 * (which might be partial for partially populated chunks).
2164 * @param nbits The maximum nuber of bits that will be used.
2165 * @param with_extra Whether "VM Tracking" metadata needs to be allocated.
2166 */
2167 static uint32_t
zone_meta_bits_alloc_init(uint32_t count,uint32_t nbits,bool with_extra)2168 zone_meta_bits_alloc_init(uint32_t count, uint32_t nbits, bool with_extra)
2169 {
2170 static_assert(ZONE_MAX_ALLOC_SIZE / ZONE_MIN_ELEM_SIZE <=
2171 ZBA_GRANULE_BITS << ZBA_MAX_ORDER, "bitmaps will be large enough");
2172
2173 uint32_t order = flsll((nbits - 1) / ZBA_GRANULE_BITS);
2174 uint64_t *bits;
2175 size_t i = 0;
2176
2177 assert(order <= ZBA_MAX_ALLOC_ORDER);
2178 assert(count <= ZBA_GRANULE_BITS << order);
2179
2180 zba_lock();
2181 bits = (uint64_t *)zba_alloc(order, with_extra);
2182 zba_unlock();
2183
2184 while (i < count / 64) {
2185 bits[i++] = ~0ull;
2186 }
2187 if (count % 64) {
2188 bits[i++] = zba_map_mask_lt(uint64_t, count);
2189 }
2190 while (i < 1u << order) {
2191 bits[i++] = 0;
2192 }
2193
2194 return (uint32_t)(bits - zba_slot_base()) +
2195 (order << ZBA_ORDER_SHIFT) +
2196 (with_extra ? ZBA_HAS_EXTRA_BIT : 0);
2197 }
2198
2199 /*!
2200 * @function zone_meta_bits_merge
2201 *
2202 * @brief
2203 * Adds elements <code>[start, end)</code> to a chunk being extended.
2204 *
2205 * @param meta The main metadata for the extended chunk.
2206 * @param start The index of the first element to add to the chunk.
2207 * @param end The index of the last (exclusive) element to add.
2208 */
2209 static void
zone_meta_bits_merge(struct zone_page_metadata * meta,uint32_t start,uint32_t end)2210 zone_meta_bits_merge(struct zone_page_metadata *meta,
2211 uint32_t start, uint32_t end)
2212 {
2213 if (meta->zm_inline_bitmap) {
2214 while (start < end) {
2215 size_t s_i = start / 32;
2216 size_t s_e = end / 32;
2217
2218 if (s_i == s_e) {
2219 meta[s_i].zm_bitmap |= zba_map_mask_lt(uint32_t, end) &
2220 zba_map_mask_ge(uint32_t, start);
2221 break;
2222 }
2223
2224 meta[s_i].zm_bitmap |= zba_map_mask_ge(uint32_t, start);
2225 start += 32 - (start % 32);
2226 }
2227 } else {
2228 uint64_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2229
2230 while (start < end) {
2231 size_t s_i = start / 64;
2232 size_t s_e = end / 64;
2233
2234 if (s_i == s_e) {
2235 bits[s_i] |= zba_map_mask_lt(uint64_t, end) &
2236 zba_map_mask_ge(uint64_t, start);
2237 break;
2238 }
2239 bits[s_i] |= zba_map_mask_ge(uint64_t, start);
2240 start += 64 - (start % 64);
2241 }
2242 }
2243 }
2244
2245 /*!
2246 * @function zone_bits_free
2247 *
2248 * @brief
2249 * Frees a bitmap to the zone bitmap allocator.
2250 *
2251 * @param bref
2252 * A bitmap reference set by @c zone_meta_bits_init() in a @c zm_bitmap field.
2253 */
2254 static void
zone_bits_free(uint32_t bref)2255 zone_bits_free(uint32_t bref)
2256 {
2257 zba_lock();
2258 zba_free((vm_offset_t)zba_bits_ref_ptr(bref),
2259 zba_bits_ref_order(bref), (bref & ZBA_HAS_EXTRA_BIT));
2260 zba_unlock();
2261 }
2262
2263 /*!
2264 * @function zone_meta_is_free
2265 *
2266 * @brief
2267 * Returns whether a given element appears free.
2268 */
2269 static bool
zone_meta_is_free(struct zone_page_metadata * meta,vm_offset_t eidx)2270 zone_meta_is_free(struct zone_page_metadata *meta, vm_offset_t eidx)
2271 {
2272 if (meta->zm_inline_bitmap) {
2273 uint32_t bit = zba_map_bit(uint32_t, eidx);
2274 return meta[zba_map_index(uint32_t, eidx)].zm_bitmap & bit;
2275 } else {
2276 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2277 uint64_t bit = zba_map_bit(uint64_t, eidx);
2278 return bits[zba_map_index(uint64_t, eidx)] & bit;
2279 }
2280 }
2281
2282 /*!
2283 * @function zone_meta_mark_free
2284 *
2285 * @brief
2286 * Marks an element as free and returns whether it was marked as used.
2287 */
2288 static bool
zone_meta_mark_free(struct zone_page_metadata * meta,vm_offset_t eidx)2289 zone_meta_mark_free(struct zone_page_metadata *meta, vm_offset_t eidx)
2290 {
2291 if (meta->zm_inline_bitmap) {
2292 uint32_t bit = zba_map_bit(uint32_t, eidx);
2293 if (meta[zba_map_index(uint32_t, eidx)].zm_bitmap & bit) {
2294 return false;
2295 }
2296 meta[zba_map_index(uint32_t, eidx)].zm_bitmap ^= bit;
2297 } else {
2298 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2299 uint64_t bit = zba_map_bit(uint64_t, eidx);
2300 if (bits[zba_map_index(uint64_t, eidx)] & bit) {
2301 return false;
2302 }
2303 bits[zba_map_index(uint64_t, eidx)] ^= bit;
2304 }
2305 return true;
2306 }
2307
2308 #if VM_TAG_SIZECLASSES
2309
2310 __startup_func
2311 void
__zone_site_register(vm_allocation_site_t * site)2312 __zone_site_register(vm_allocation_site_t *site)
2313 {
2314 if (zone_tagging_on) {
2315 vm_tag_alloc(site);
2316 }
2317 }
2318
2319 uint16_t
zone_index_from_tag_index(uint32_t sizeclass_idx)2320 zone_index_from_tag_index(uint32_t sizeclass_idx)
2321 {
2322 return zone_tags_sizeclasses[sizeclass_idx];
2323 }
2324
2325 #endif /* VM_TAG_SIZECLASSES */
2326 #endif /* !ZALLOC_TEST */
2327 /*! @} */
2328 #pragma mark zalloc helpers
2329 #if !ZALLOC_TEST
2330
2331 static inline void *
zstack_tbi_fix(vm_offset_t elem)2332 zstack_tbi_fix(vm_offset_t elem)
2333 {
2334 elem = vm_memtag_fixup_ptr(elem);
2335 return (void *)elem;
2336 }
2337
2338 static inline vm_offset_t
zstack_tbi_fill(void * addr)2339 zstack_tbi_fill(void *addr)
2340 {
2341 vm_offset_t elem = (vm_offset_t)addr;
2342
2343 return vm_memtag_canonicalize_address(elem);
2344 }
2345
2346 __attribute__((always_inline))
2347 static inline void
zstack_push_no_delta(zstack_t * stack,void * addr)2348 zstack_push_no_delta(zstack_t *stack, void *addr)
2349 {
2350 vm_offset_t elem = zstack_tbi_fill(addr);
2351
2352 *(vm_offset_t *)addr = stack->z_head - elem;
2353 stack->z_head = elem;
2354 }
2355
2356 __attribute__((always_inline))
2357 void
zstack_push(zstack_t * stack,void * addr)2358 zstack_push(zstack_t *stack, void *addr)
2359 {
2360 zstack_push_no_delta(stack, addr);
2361 stack->z_count++;
2362 }
2363
2364 __attribute__((always_inline))
2365 static inline void *
zstack_pop_no_delta(zstack_t * stack)2366 zstack_pop_no_delta(zstack_t *stack)
2367 {
2368 void *addr = zstack_tbi_fix(stack->z_head);
2369
2370 stack->z_head += *(vm_offset_t *)addr;
2371 *(vm_offset_t *)addr = 0;
2372
2373 return addr;
2374 }
2375
2376 __attribute__((always_inline))
2377 void *
zstack_pop(zstack_t * stack)2378 zstack_pop(zstack_t *stack)
2379 {
2380 stack->z_count--;
2381 return zstack_pop_no_delta(stack);
2382 }
2383
2384 static inline void
zone_recirc_lock_nopreempt_check_contention(zone_t zone)2385 zone_recirc_lock_nopreempt_check_contention(zone_t zone)
2386 {
2387 uint32_t ticket;
2388
2389 if (__probable(hw_lck_ticket_reserve_nopreempt(&zone->z_recirc_lock,
2390 &ticket, &zone_locks_grp))) {
2391 return;
2392 }
2393
2394 hw_lck_ticket_wait(&zone->z_recirc_lock, ticket, NULL, &zone_locks_grp);
2395
2396 /*
2397 * If zone caching has been disabled due to memory pressure,
2398 * then recording contention is not useful, give the system
2399 * time to recover.
2400 */
2401 if (__probable(!zone_caching_disabled && !zone_exhausted(zone))) {
2402 zone->z_recirc_cont_cur++;
2403 }
2404 }
2405
2406 static inline void
zone_recirc_lock_nopreempt(zone_t zone)2407 zone_recirc_lock_nopreempt(zone_t zone)
2408 {
2409 hw_lck_ticket_lock_nopreempt(&zone->z_recirc_lock, &zone_locks_grp);
2410 }
2411
2412 static inline void
zone_recirc_unlock_nopreempt(zone_t zone)2413 zone_recirc_unlock_nopreempt(zone_t zone)
2414 {
2415 hw_lck_ticket_unlock_nopreempt(&zone->z_recirc_lock);
2416 }
2417
2418 static inline void
zone_lock_nopreempt_check_contention(zone_t zone)2419 zone_lock_nopreempt_check_contention(zone_t zone)
2420 {
2421 uint32_t ticket;
2422 #if KASAN_FAKESTACK
2423 spl_t s = 0;
2424 if (zone->z_kasan_fakestacks) {
2425 s = splsched();
2426 }
2427 #endif /* KASAN_FAKESTACK */
2428
2429 if (__probable(hw_lck_ticket_reserve_nopreempt(&zone->z_lock, &ticket,
2430 &zone_locks_grp))) {
2431 #if KASAN_FAKESTACK
2432 zone->z_kasan_spl = s;
2433 #endif /* KASAN_FAKESTACK */
2434 return;
2435 }
2436
2437 hw_lck_ticket_wait(&zone->z_lock, ticket, NULL, &zone_locks_grp);
2438 #if KASAN_FAKESTACK
2439 zone->z_kasan_spl = s;
2440 #endif /* KASAN_FAKESTACK */
2441
2442 /*
2443 * If zone caching has been disabled due to memory pressure,
2444 * then recording contention is not useful, give the system
2445 * time to recover.
2446 */
2447 if (__probable(!zone_caching_disabled &&
2448 !zone->z_pcpu_cache && !zone_exhausted(zone))) {
2449 zone->z_recirc_cont_cur++;
2450 }
2451 }
2452
2453 static inline void
zone_lock_nopreempt(zone_t zone)2454 zone_lock_nopreempt(zone_t zone)
2455 {
2456 #if KASAN_FAKESTACK
2457 spl_t s = 0;
2458 if (zone->z_kasan_fakestacks) {
2459 s = splsched();
2460 }
2461 #endif /* KASAN_FAKESTACK */
2462 hw_lck_ticket_lock_nopreempt(&zone->z_lock, &zone_locks_grp);
2463 #if KASAN_FAKESTACK
2464 zone->z_kasan_spl = s;
2465 #endif /* KASAN_FAKESTACK */
2466 }
2467
2468 static inline void
zone_unlock_nopreempt(zone_t zone)2469 zone_unlock_nopreempt(zone_t zone)
2470 {
2471 #if KASAN_FAKESTACK
2472 spl_t s = zone->z_kasan_spl;
2473 zone->z_kasan_spl = 0;
2474 #endif /* KASAN_FAKESTACK */
2475 hw_lck_ticket_unlock_nopreempt(&zone->z_lock);
2476 #if KASAN_FAKESTACK
2477 if (zone->z_kasan_fakestacks) {
2478 splx(s);
2479 }
2480 #endif /* KASAN_FAKESTACK */
2481 }
2482
2483 static inline void
zone_depot_lock_nopreempt(zone_cache_t zc)2484 zone_depot_lock_nopreempt(zone_cache_t zc)
2485 {
2486 hw_lck_ticket_lock_nopreempt(&zc->zc_depot_lock, &zone_locks_grp);
2487 }
2488
2489 static inline void
zone_depot_unlock_nopreempt(zone_cache_t zc)2490 zone_depot_unlock_nopreempt(zone_cache_t zc)
2491 {
2492 hw_lck_ticket_unlock_nopreempt(&zc->zc_depot_lock);
2493 }
2494
2495 static inline void
zone_depot_lock(zone_cache_t zc)2496 zone_depot_lock(zone_cache_t zc)
2497 {
2498 hw_lck_ticket_lock(&zc->zc_depot_lock, &zone_locks_grp);
2499 }
2500
2501 static inline void
zone_depot_unlock(zone_cache_t zc)2502 zone_depot_unlock(zone_cache_t zc)
2503 {
2504 hw_lck_ticket_unlock(&zc->zc_depot_lock);
2505 }
2506
2507 zone_t
zone_by_id(size_t zid)2508 zone_by_id(size_t zid)
2509 {
2510 return (zone_t)((uintptr_t)zone_array + zid * sizeof(struct zone));
2511 }
2512
2513 static inline bool
zone_supports_vm(zone_t z)2514 zone_supports_vm(zone_t z)
2515 {
2516 /*
2517 * VM_MAP_ENTRY and VM_MAP_HOLES zones are allowed
2518 * to overcommit because they're used to reclaim memory
2519 * (VM support).
2520 */
2521 return z >= &zone_array[ZONE_ID_VM_MAP_ENTRY] &&
2522 z <= &zone_array[ZONE_ID_VM_MAP_HOLES];
2523 }
2524
2525 const char *
zone_name(zone_t z)2526 zone_name(zone_t z)
2527 {
2528 return z->z_name;
2529 }
2530
2531 const char *
zone_heap_name(zone_t z)2532 zone_heap_name(zone_t z)
2533 {
2534 zone_security_flags_t zsflags = zone_security_config(z);
2535 if (__probable(zsflags.z_kheap_id < KHEAP_ID_COUNT)) {
2536 return kalloc_heap_names[zsflags.z_kheap_id];
2537 }
2538 return "invalid";
2539 }
2540
2541 static uint32_t
zone_alloc_pages_for_nelems(zone_t z,vm_size_t max_elems)2542 zone_alloc_pages_for_nelems(zone_t z, vm_size_t max_elems)
2543 {
2544 vm_size_t elem_count, chunks;
2545
2546 elem_count = ptoa(z->z_percpu ? 1 : z->z_chunk_pages) /
2547 zone_elem_outer_size(z);
2548 chunks = (max_elems + elem_count - 1) / elem_count;
2549
2550 return (uint32_t)MIN(UINT32_MAX, chunks * z->z_chunk_pages);
2551 }
2552
2553 static inline vm_size_t
zone_submaps_approx_size(void)2554 zone_submaps_approx_size(void)
2555 {
2556 vm_size_t size = 0;
2557
2558 for (unsigned idx = 0; idx < Z_SUBMAP_IDX_COUNT; idx++) {
2559 if (zone_submaps[idx] != VM_MAP_NULL) {
2560 size += zone_submaps[idx]->size;
2561 }
2562 }
2563
2564 return size;
2565 }
2566
2567 static inline void
zone_depot_init(struct zone_depot * zd)2568 zone_depot_init(struct zone_depot *zd)
2569 {
2570 *zd = (struct zone_depot){
2571 .zd_tail = &zd->zd_head,
2572 };
2573 }
2574
2575 static inline void
zone_depot_insert_head_full(struct zone_depot * zd,zone_magazine_t mag)2576 zone_depot_insert_head_full(struct zone_depot *zd, zone_magazine_t mag)
2577 {
2578 if (zd->zd_full++ == 0) {
2579 zd->zd_tail = &mag->zm_next;
2580 }
2581 mag->zm_next = zd->zd_head;
2582 zd->zd_head = mag;
2583 }
2584
2585 static inline void
zone_depot_insert_tail_full(struct zone_depot * zd,zone_magazine_t mag)2586 zone_depot_insert_tail_full(struct zone_depot *zd, zone_magazine_t mag)
2587 {
2588 zd->zd_full++;
2589 mag->zm_next = *zd->zd_tail;
2590 *zd->zd_tail = mag;
2591 zd->zd_tail = &mag->zm_next;
2592 }
2593
2594 static inline void
zone_depot_insert_head_empty(struct zone_depot * zd,zone_magazine_t mag)2595 zone_depot_insert_head_empty(struct zone_depot *zd, zone_magazine_t mag)
2596 {
2597 zd->zd_empty++;
2598 mag->zm_next = *zd->zd_tail;
2599 *zd->zd_tail = mag;
2600 }
2601
2602 static inline zone_magazine_t
zone_depot_pop_head_full(struct zone_depot * zd,zone_t z)2603 zone_depot_pop_head_full(struct zone_depot *zd, zone_t z)
2604 {
2605 zone_magazine_t mag = zd->zd_head;
2606
2607 assert(zd->zd_full);
2608
2609 zd->zd_full--;
2610 if (z && z->z_recirc_full_min > zd->zd_full) {
2611 z->z_recirc_full_min = zd->zd_full;
2612 }
2613 zd->zd_head = mag->zm_next;
2614 if (zd->zd_full == 0) {
2615 zd->zd_tail = &zd->zd_head;
2616 }
2617
2618 mag->zm_next = NULL;
2619 return mag;
2620 }
2621
2622 static inline zone_magazine_t
zone_depot_pop_head_empty(struct zone_depot * zd,zone_t z)2623 zone_depot_pop_head_empty(struct zone_depot *zd, zone_t z)
2624 {
2625 zone_magazine_t mag = *zd->zd_tail;
2626
2627 assert(zd->zd_empty);
2628
2629 zd->zd_empty--;
2630 if (z && z->z_recirc_empty_min > zd->zd_empty) {
2631 z->z_recirc_empty_min = zd->zd_empty;
2632 }
2633 *zd->zd_tail = mag->zm_next;
2634
2635 mag->zm_next = NULL;
2636 return mag;
2637 }
2638
2639 static inline smr_seq_t
zone_depot_move_full(struct zone_depot * dst,struct zone_depot * src,uint32_t n,zone_t z)2640 zone_depot_move_full(
2641 struct zone_depot *dst,
2642 struct zone_depot *src,
2643 uint32_t n,
2644 zone_t z)
2645 {
2646 zone_magazine_t head, last;
2647
2648 assert(n);
2649 assert(src->zd_full >= n);
2650
2651 src->zd_full -= n;
2652 if (z && z->z_recirc_full_min > src->zd_full) {
2653 z->z_recirc_full_min = src->zd_full;
2654 }
2655 head = last = src->zd_head;
2656 for (uint32_t i = n; i-- > 1;) {
2657 last = last->zm_next;
2658 }
2659
2660 src->zd_head = last->zm_next;
2661 if (src->zd_full == 0) {
2662 src->zd_tail = &src->zd_head;
2663 }
2664
2665 if (z && zone_security_array[zone_index(z)].z_lifo) {
2666 if (dst->zd_full == 0) {
2667 dst->zd_tail = &last->zm_next;
2668 }
2669 last->zm_next = dst->zd_head;
2670 dst->zd_head = head;
2671 } else {
2672 last->zm_next = *dst->zd_tail;
2673 *dst->zd_tail = head;
2674 dst->zd_tail = &last->zm_next;
2675 }
2676 dst->zd_full += n;
2677
2678 return last->zm_seq;
2679 }
2680
2681 static inline void
zone_depot_move_empty(struct zone_depot * dst,struct zone_depot * src,uint32_t n,zone_t z)2682 zone_depot_move_empty(
2683 struct zone_depot *dst,
2684 struct zone_depot *src,
2685 uint32_t n,
2686 zone_t z)
2687 {
2688 zone_magazine_t head, last;
2689
2690 assert(n);
2691 assert(src->zd_empty >= n);
2692
2693 src->zd_empty -= n;
2694 if (z && z->z_recirc_empty_min > src->zd_empty) {
2695 z->z_recirc_empty_min = src->zd_empty;
2696 }
2697 head = last = *src->zd_tail;
2698 for (uint32_t i = n; i-- > 1;) {
2699 last = last->zm_next;
2700 }
2701
2702 *src->zd_tail = last->zm_next;
2703
2704 dst->zd_empty += n;
2705 last->zm_next = *dst->zd_tail;
2706 *dst->zd_tail = head;
2707 }
2708
2709 static inline bool
zone_depot_poll(struct zone_depot * depot,smr_t smr)2710 zone_depot_poll(struct zone_depot *depot, smr_t smr)
2711 {
2712 if (depot->zd_full == 0) {
2713 return false;
2714 }
2715
2716 return smr == NULL || smr_poll(smr, depot->zd_head->zm_seq);
2717 }
2718
2719 static void
zone_cache_swap_magazines(zone_cache_t cache)2720 zone_cache_swap_magazines(zone_cache_t cache)
2721 {
2722 uint16_t count_a = cache->zc_alloc_cur;
2723 uint16_t count_f = cache->zc_free_cur;
2724 vm_offset_t *elems_a = cache->zc_alloc_elems;
2725 vm_offset_t *elems_f = cache->zc_free_elems;
2726
2727 z_debug_assert(count_a <= zc_mag_size());
2728 z_debug_assert(count_f <= zc_mag_size());
2729
2730 cache->zc_alloc_cur = count_f;
2731 cache->zc_free_cur = count_a;
2732 cache->zc_alloc_elems = elems_f;
2733 cache->zc_free_elems = elems_a;
2734 }
2735
2736 __pure2
2737 static smr_t
zone_cache_smr(zone_cache_t cache)2738 zone_cache_smr(zone_cache_t cache)
2739 {
2740 return cache->zc_smr;
2741 }
2742
2743 /*!
2744 * @function zone_magazine_replace
2745 *
2746 * @brief
2747 * Unlod a magazine and load a new one instead.
2748 */
2749 static zone_magazine_t
zone_magazine_replace(zone_cache_t zc,zone_magazine_t mag,bool empty)2750 zone_magazine_replace(zone_cache_t zc, zone_magazine_t mag, bool empty)
2751 {
2752 zone_magazine_t old;
2753 vm_offset_t **elems;
2754
2755 mag->zm_seq = SMR_SEQ_INVALID;
2756
2757 if (empty) {
2758 elems = &zc->zc_free_elems;
2759 zc->zc_free_cur = 0;
2760 } else {
2761 elems = &zc->zc_alloc_elems;
2762 zc->zc_alloc_cur = zc_mag_size();
2763 }
2764 old = (zone_magazine_t)((uintptr_t)*elems -
2765 offsetof(struct zone_magazine, zm_elems));
2766 *elems = mag->zm_elems;
2767
2768 return old;
2769 }
2770
2771 static zone_magazine_t
zone_magazine_alloc(zalloc_flags_t flags)2772 zone_magazine_alloc(zalloc_flags_t flags)
2773 {
2774 return zalloc_flags(zc_magazine_zone, flags | Z_ZERO);
2775 }
2776
2777 static void
zone_magazine_free(zone_magazine_t mag)2778 zone_magazine_free(zone_magazine_t mag)
2779 {
2780 (zfree)(zc_magazine_zone, mag);
2781 }
2782
2783 static void
zone_magazine_free_list(struct zone_depot * zd)2784 zone_magazine_free_list(struct zone_depot *zd)
2785 {
2786 zone_magazine_t tmp, mag = *zd->zd_tail;
2787
2788 while (mag) {
2789 tmp = mag->zm_next;
2790 zone_magazine_free(mag);
2791 mag = tmp;
2792 }
2793
2794 *zd->zd_tail = NULL;
2795 zd->zd_empty = 0;
2796 }
2797
2798 void
zone_enable_caching(zone_t zone)2799 zone_enable_caching(zone_t zone)
2800 {
2801 size_t size_per_mag = zone_elem_inner_size(zone) * zc_mag_size();
2802 zone_cache_t caches;
2803 size_t depot_limit;
2804
2805 depot_limit = zc_pcpu_max() / size_per_mag;
2806 zone->z_depot_limit = (uint16_t)MIN(depot_limit, INT16_MAX);
2807
2808 caches = zalloc_percpu_permanent_type(struct zone_cache);
2809 zpercpu_foreach(zc, caches) {
2810 zc->zc_alloc_elems = zone_magazine_alloc(Z_WAITOK | Z_NOFAIL)->zm_elems;
2811 zc->zc_free_elems = zone_magazine_alloc(Z_WAITOK | Z_NOFAIL)->zm_elems;
2812 zone_depot_init(&zc->zc_depot);
2813 hw_lck_ticket_init(&zc->zc_depot_lock, &zone_locks_grp);
2814 }
2815
2816 zone_lock(zone);
2817 assert(zone->z_pcpu_cache == NULL);
2818 zone->z_pcpu_cache = caches;
2819 zone->z_recirc_cont_cur = 0;
2820 zone->z_recirc_cont_wma = 0;
2821 zone->z_elems_free_min = 0; /* becomes z_recirc_empty_min */
2822 zone->z_elems_free_wma = 0; /* becomes z_recirc_empty_wma */
2823 zone_unlock(zone);
2824 }
2825
2826 bool
zone_maps_owned(vm_address_t addr,vm_size_t size)2827 zone_maps_owned(vm_address_t addr, vm_size_t size)
2828 {
2829 return from_zone_map(addr, size);
2830 }
2831
2832 #if KASAN_LIGHT
2833 bool
kasan_zone_maps_owned(vm_address_t addr,vm_size_t size)2834 kasan_zone_maps_owned(vm_address_t addr, vm_size_t size)
2835 {
2836 return from_zone_map(addr, size) ||
2837 mach_vm_range_size(&zone_info.zi_map_range) == 0;
2838 }
2839 #endif /* KASAN_LIGHT */
2840
2841 void
zone_map_sizes(vm_map_size_t * psize,vm_map_size_t * pfree,vm_map_size_t * plargest_free)2842 zone_map_sizes(
2843 vm_map_size_t *psize,
2844 vm_map_size_t *pfree,
2845 vm_map_size_t *plargest_free)
2846 {
2847 vm_map_size_t size, free, largest;
2848
2849 vm_map_sizes(zone_submaps[0], psize, pfree, plargest_free);
2850
2851 for (uint32_t i = 1; i < Z_SUBMAP_IDX_COUNT; i++) {
2852 vm_map_sizes(zone_submaps[i], &size, &free, &largest);
2853 *psize += size;
2854 *pfree += free;
2855 *plargest_free = MAX(*plargest_free, largest);
2856 }
2857 }
2858
2859 __attribute__((always_inline))
2860 vm_map_t
zone_submap(zone_security_flags_t zsflags)2861 zone_submap(zone_security_flags_t zsflags)
2862 {
2863 return zone_submaps[zsflags.z_submap_idx];
2864 }
2865
2866 unsigned
zpercpu_count(void)2867 zpercpu_count(void)
2868 {
2869 return zpercpu_early_count;
2870 }
2871
2872 #if ZSECURITY_CONFIG(SAD_FENG_SHUI) || CONFIG_PROB_GZALLOC
2873 /*
2874 * Returns a random number of a given bit-width.
2875 *
2876 * DO NOT COPY THIS CODE OUTSIDE OF ZALLOC
2877 *
2878 * This uses Intel's rdrand because random() uses FP registers
2879 * which causes FP faults and allocations which isn't something
2880 * we can do from zalloc itself due to reentrancy problems.
2881 *
2882 * For pre-rdrand machines (which we no longer support),
2883 * we use a bad biased random generator that doesn't use FP.
2884 * Such HW is no longer supported, but VM of newer OSes on older
2885 * bare metal is made to limp along (with reduced security) this way.
2886 */
2887 static uint64_t
zalloc_random_mask64(uint32_t bits)2888 zalloc_random_mask64(uint32_t bits)
2889 {
2890 uint64_t mask = ~0ull >> (64 - bits);
2891 uint64_t v;
2892
2893 #if __x86_64__
2894 if (__probable(cpuid_features() & CPUID_FEATURE_RDRAND)) {
2895 asm volatile ("1: rdrand %0; jnc 1b\n" : "=r" (v) :: "cc");
2896 v &= mask;
2897 } else {
2898 disable_preemption();
2899 int cpu = cpu_number();
2900 v = random_bool_gen_bits(&zone_bool_gen[cpu].zbg_bg,
2901 zone_bool_gen[cpu].zbg_entropy,
2902 ZONE_ENTROPY_CNT, bits);
2903 enable_preemption();
2904 }
2905 #else
2906 v = early_random() & mask;
2907 #endif
2908
2909 return v;
2910 }
2911
2912 /*
2913 * Returns a random number within [bound_min, bound_max)
2914 *
2915 * This isn't _exactly_ uniform, but the skew is small enough
2916 * not to matter for the consumers of this interface.
2917 *
2918 * Values within [bound_min, 2^64 % (bound_max - bound_min))
2919 * will be returned (bound_max - bound_min) / 2^64 more often
2920 * than values within [2^64 % (bound_max - bound_min), bound_max).
2921 */
2922 static uint32_t
zalloc_random_uniform32(uint32_t bound_min,uint32_t bound_max)2923 zalloc_random_uniform32(uint32_t bound_min, uint32_t bound_max)
2924 {
2925 uint64_t delta = bound_max - bound_min;
2926
2927 return bound_min + (uint32_t)(zalloc_random_mask64(64) % delta);
2928 }
2929
2930 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) || CONFIG_PROB_GZALLOC */
2931 #if ZALLOC_ENABLE_LOGGING || CONFIG_PROB_GZALLOC
2932 /*
2933 * Track all kalloc zones of specified size for zlog name
2934 * kalloc.type.<size> or kalloc.type.var.<size> or kalloc.<size>
2935 *
2936 * Additionally track all shared kalloc zones with shared.kalloc
2937 */
2938 static bool
track_kalloc_zones(zone_t z,const char * logname)2939 track_kalloc_zones(zone_t z, const char *logname)
2940 {
2941 const char *prefix;
2942 size_t len;
2943 zone_security_flags_t zsflags = zone_security_config(z);
2944
2945 prefix = "kalloc.type.var.";
2946 len = strlen(prefix);
2947 if (zsflags.z_kalloc_type && zsflags.z_kheap_id == KHEAP_ID_KT_VAR &&
2948 strncmp(logname, prefix, len) == 0) {
2949 vm_size_t sizeclass = strtoul(logname + len, NULL, 0);
2950
2951 return zone_elem_inner_size(z) == sizeclass;
2952 }
2953
2954 prefix = "kalloc.type.";
2955 len = strlen(prefix);
2956 if (zsflags.z_kalloc_type && zsflags.z_kheap_id != KHEAP_ID_KT_VAR &&
2957 strncmp(logname, prefix, len) == 0) {
2958 vm_size_t sizeclass = strtoul(logname + len, NULL, 0);
2959
2960 return zone_elem_inner_size(z) == sizeclass;
2961 }
2962
2963 prefix = "kalloc.";
2964 len = strlen(prefix);
2965 if ((zsflags.z_kheap_id || zsflags.z_kalloc_type) &&
2966 strncmp(logname, prefix, len) == 0) {
2967 vm_size_t sizeclass = strtoul(logname + len, NULL, 0);
2968
2969 return zone_elem_inner_size(z) == sizeclass;
2970 }
2971
2972 prefix = "shared.kalloc";
2973 if ((zsflags.z_kheap_id == KHEAP_ID_SHARED) &&
2974 (strcmp(logname, prefix) == 0)) {
2975 return true;
2976 }
2977
2978 return false;
2979 }
2980 #endif
2981
2982 int
track_this_zone(const char * zonename,const char * logname)2983 track_this_zone(const char *zonename, const char *logname)
2984 {
2985 unsigned int len;
2986 const char *zc = zonename;
2987 const char *lc = logname;
2988
2989 /*
2990 * Compare the strings. We bound the compare by MAX_ZONE_NAME.
2991 */
2992
2993 for (len = 1; len <= MAX_ZONE_NAME; zc++, lc++, len++) {
2994 /*
2995 * If the current characters don't match, check for a space in
2996 * in the zone name and a corresponding period in the log name.
2997 * If that's not there, then the strings don't match.
2998 */
2999
3000 if (*zc != *lc && !(*zc == ' ' && *lc == '.')) {
3001 break;
3002 }
3003
3004 /*
3005 * The strings are equal so far. If we're at the end, then it's a match.
3006 */
3007
3008 if (*zc == '\0') {
3009 return TRUE;
3010 }
3011 }
3012
3013 return FALSE;
3014 }
3015
3016 #if DEBUG || DEVELOPMENT
3017
3018 vm_size_t
zone_element_info(void * addr,vm_tag_t * ptag)3019 zone_element_info(void *addr, vm_tag_t * ptag)
3020 {
3021 vm_size_t size = 0;
3022 vm_tag_t tag = VM_KERN_MEMORY_NONE;
3023 struct zone *src_zone;
3024
3025 if (from_zone_map(addr, sizeof(void *))) {
3026 src_zone = zone_by_id(zone_index_from_ptr(addr));
3027 size = zone_elem_inner_size(src_zone);
3028 #if VM_TAG_SIZECLASSES
3029 if (__improbable(src_zone->z_uses_tags)) {
3030 struct zone_page_metadata *meta;
3031 vm_offset_t eidx;
3032 vm_tag_t *slot;
3033
3034 meta = zone_element_resolve(src_zone,
3035 (vm_offset_t)addr, &eidx);
3036 slot = zba_extra_ref_ptr(meta->zm_bitmap, eidx);
3037 tag = *slot;
3038 }
3039 #endif /* VM_TAG_SIZECLASSES */
3040 }
3041
3042 *ptag = tag;
3043 return size;
3044 }
3045
3046 #endif /* DEBUG || DEVELOPMENT */
3047 #if KASAN_CLASSIC
3048
3049 vm_size_t
kasan_quarantine_resolve(vm_address_t addr,zone_t * zonep)3050 kasan_quarantine_resolve(vm_address_t addr, zone_t *zonep)
3051 {
3052 zone_t zone = zone_by_id(zone_index_from_ptr((void *)addr));
3053
3054 *zonep = zone;
3055 return zone_elem_inner_size(zone);
3056 }
3057
3058 #endif /* KASAN_CLASSIC */
3059 #endif /* !ZALLOC_TEST */
3060 #pragma mark Zone zeroing and early random
3061 #if !ZALLOC_TEST
3062
3063 /*
3064 * Zone zeroing
3065 *
3066 * All allocations from zones are zeroed on free and are additionally
3067 * check that they are still zero on alloc. The check is
3068 * always on, on embedded devices. Perf regression was detected
3069 * on intel as we cant use the vectorized implementation of
3070 * memcmp_zero_ptr_aligned due to cyclic dependenices between
3071 * initization and allocation. Therefore we perform the check
3072 * on 20% of the allocations.
3073 */
3074 #if ZALLOC_ENABLE_ZERO_CHECK
3075 #if defined(__x86_64__)
3076 /*
3077 * Peform zero validation on every 5th allocation
3078 */
3079 static TUNABLE(uint32_t, zzc_rate, "zzc_rate", 5);
3080 static uint32_t PERCPU_DATA(zzc_decrementer);
3081 #endif /* defined(__x86_64__) */
3082
3083 /*
3084 * Determine if zero validation for allocation should be skipped
3085 */
3086 static bool
zalloc_skip_zero_check(void)3087 zalloc_skip_zero_check(void)
3088 {
3089 #if defined(__x86_64__)
3090 uint32_t *counterp, cnt;
3091
3092 counterp = PERCPU_GET(zzc_decrementer);
3093 cnt = *counterp;
3094 if (__probable(cnt > 0)) {
3095 *counterp = cnt - 1;
3096 return true;
3097 }
3098 *counterp = zzc_rate - 1;
3099 #endif /* !defined(__x86_64__) */
3100 return false;
3101 }
3102
3103 __abortlike
3104 static void
zalloc_uaf_panic(zone_t z,uintptr_t elem,size_t size)3105 zalloc_uaf_panic(zone_t z, uintptr_t elem, size_t size)
3106 {
3107 uint32_t esize = (uint32_t)zone_elem_inner_size(z);
3108 uint32_t first_offs = ~0u;
3109 uintptr_t first_bits = 0, v;
3110 char buf[1024];
3111 int pos = 0;
3112
3113 buf[0] = '\0';
3114
3115 for (uint32_t o = 0; o < size; o += sizeof(v)) {
3116 if ((v = *(uintptr_t *)(elem + o)) == 0) {
3117 continue;
3118 }
3119 pos += scnprintf(buf + pos, sizeof(buf) - pos, "\n"
3120 "%5d: 0x%016lx", o, v);
3121 if (first_offs > o) {
3122 first_offs = o;
3123 first_bits = v;
3124 }
3125 }
3126
3127 (panic)("[%s%s]: element modified after free "
3128 "(off:%d, val:0x%016lx, sz:%d, ptr:%p)%s",
3129 zone_heap_name(z), zone_name(z),
3130 first_offs, first_bits, esize, (void *)elem, buf);
3131 }
3132
3133 static void
zalloc_validate_element(zone_t zone,vm_offset_t elem,vm_size_t size,zalloc_flags_t flags)3134 zalloc_validate_element(
3135 zone_t zone,
3136 vm_offset_t elem,
3137 vm_size_t size,
3138 zalloc_flags_t flags)
3139 {
3140 if (flags & Z_NOZZC) {
3141 return;
3142 }
3143 if (memcmp_zero_ptr_aligned((void *)elem, size)) {
3144 zalloc_uaf_panic(zone, elem, size);
3145 }
3146 if (flags & Z_PCPU) {
3147 for (size_t i = zpercpu_count(); --i > 0;) {
3148 elem += PAGE_SIZE;
3149 if (memcmp_zero_ptr_aligned((void *)elem, size)) {
3150 zalloc_uaf_panic(zone, elem, size);
3151 }
3152 }
3153 }
3154 }
3155
3156 #endif /* ZALLOC_ENABLE_ZERO_CHECK */
3157
3158 __attribute__((noinline))
3159 static void
zone_early_scramble_rr(zone_t zone,int cpu,zone_stats_t zs)3160 zone_early_scramble_rr(zone_t zone, int cpu, zone_stats_t zs)
3161 {
3162 #if KASAN_FAKESTACK
3163 /*
3164 * This can cause re-entrancy with kasan fakestacks
3165 */
3166 #pragma unused(zone, cpu, zs)
3167 #else
3168 uint32_t bits;
3169
3170 bits = random_bool_gen_bits(&zone_bool_gen[cpu].zbg_bg,
3171 zone_bool_gen[cpu].zbg_entropy, ZONE_ENTROPY_CNT, 8);
3172
3173 zs->zs_alloc_rr += bits;
3174 zs->zs_alloc_rr %= zone->z_chunk_elems;
3175 #endif
3176 }
3177
3178 #endif /* !ZALLOC_TEST */
3179 #pragma mark Zone Leak Detection
3180 #if !ZALLOC_TEST
3181 #if ZALLOC_ENABLE_LOGGING || CONFIG_ZLEAKS
3182
3183 /*
3184 * Zone leak debugging code
3185 *
3186 * When enabled, this code keeps a log to track allocations to a particular
3187 * zone that have not yet been freed.
3188 *
3189 * Examining this log will reveal the source of a zone leak.
3190 *
3191 * The log is allocated only when logging is enabled (it is off by default),
3192 * so there is no effect on the system when it's turned off.
3193 *
3194 * Zone logging is enabled with the `zlog<n>=<zone>` boot-arg for each
3195 * zone name to log, with n starting at 1.
3196 *
3197 * Leaks debugging utilizes 2 tunables:
3198 * - zlsize (in kB) which describes how much "size" the record covers
3199 * (zones with smaller elements get more records, default is 4M).
3200 *
3201 * - zlfreq (in bytes) which describes a sample rate in cumulative allocation
3202 * size at which automatic leak detection will sample allocations.
3203 * (default is 8k)
3204 *
3205 *
3206 * Zone corruption logging
3207 *
3208 * Logging can also be used to help identify the source of a zone corruption.
3209 *
3210 * First, identify the zone that is being corrupted,
3211 * then add "-zc zlog<n>=<zone name>" to the boot-args.
3212 *
3213 * When -zc is used in conjunction with zlog,
3214 * it changes the logging style to track both allocations and frees to the zone.
3215 *
3216 * When the corruption is detected, examining the log will show you the stack
3217 * traces of the callers who last allocated and freed any particular element in
3218 * the zone.
3219 *
3220 * Corruption debugging logs will have zrecs records
3221 * (tuned by the zrecs= boot-arg, 16k elements per G of RAM by default).
3222 */
3223
3224 #define ZRECORDS_MAX (256u << 10)
3225 #define ZRECORDS_DEFAULT (16u << 10)
3226 static TUNABLE(uint32_t, zrecs, "zrecs", 0);
3227 static TUNABLE(uint32_t, zlsize, "zlsize", 4 * 1024);
3228 static TUNABLE(uint32_t, zlfreq, "zlfreq", 8 * 1024);
3229
3230 __startup_func
3231 static void
zone_leaks_init_zrecs(void)3232 zone_leaks_init_zrecs(void)
3233 {
3234 /*
3235 * Don't allow more than ZRECORDS_MAX records,
3236 * even if the user asked for more.
3237 *
3238 * This prevents accidentally hogging too much kernel memory
3239 * and making the system unusable.
3240 */
3241 if (zrecs == 0) {
3242 zrecs = ZRECORDS_DEFAULT *
3243 (uint32_t)((max_mem + (1ul << 30)) >> 30);
3244 }
3245 if (zrecs > ZRECORDS_MAX) {
3246 zrecs = ZRECORDS_MAX;
3247 }
3248 }
3249 STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, zone_leaks_init_zrecs);
3250
3251 static uint32_t
zone_leaks_record_count(zone_t z)3252 zone_leaks_record_count(zone_t z)
3253 {
3254 uint32_t recs = (zlsize << 10) / zone_elem_inner_size(z);
3255
3256 return MIN(MAX(recs, ZRECORDS_DEFAULT), ZRECORDS_MAX);
3257 }
3258
3259 static uint32_t
zone_leaks_sample_rate(zone_t z)3260 zone_leaks_sample_rate(zone_t z)
3261 {
3262 return zlfreq / zone_elem_inner_size(z);
3263 }
3264
3265 #if ZALLOC_ENABLE_LOGGING
3266 /* Log allocations and frees to help debug a zone element corruption */
3267 static TUNABLE(bool, corruption_debug_flag, "-zc", false);
3268
3269 /*
3270 * A maximum of 10 zlog<n> boot args can be provided (zlog1 -> zlog10)
3271 */
3272 #define MAX_ZONES_LOG_REQUESTS 10
3273
3274 /**
3275 * @function zone_setup_logging
3276 *
3277 * @abstract
3278 * Optionally sets up a zone for logging.
3279 *
3280 * @discussion
3281 * We recognized two boot-args:
3282 *
3283 * zlog=<zone_to_log>
3284 * zrecs=<num_records_in_log>
3285 * zlsize=<memory to cover for leaks>
3286 *
3287 * The zlog arg is used to specify the zone name that should be logged,
3288 * and zrecs/zlsize is used to control the size of the log.
3289 */
3290 static void
zone_setup_logging(zone_t z)3291 zone_setup_logging(zone_t z)
3292 {
3293 char zone_name[MAX_ZONE_NAME]; /* Temp. buffer for the zone name */
3294 char zlog_name[MAX_ZONE_NAME]; /* Temp. buffer to create the strings zlog1, zlog2 etc... */
3295 char zlog_val[MAX_ZONE_NAME]; /* the zone name we're logging, if any */
3296 bool logging_on = false;
3297
3298 /*
3299 * Append kalloc heap name to zone name (if zone is used by kalloc)
3300 */
3301 snprintf(zone_name, MAX_ZONE_NAME, "%s%s", zone_heap_name(z), z->z_name);
3302
3303 /* zlog0 isn't allowed. */
3304 for (int i = 1; i <= MAX_ZONES_LOG_REQUESTS; i++) {
3305 snprintf(zlog_name, MAX_ZONE_NAME, "zlog%d", i);
3306
3307 if (PE_parse_boot_argn(zlog_name, zlog_val, sizeof(zlog_val))) {
3308 if (track_this_zone(zone_name, zlog_val) ||
3309 track_kalloc_zones(z, zlog_val)) {
3310 logging_on = true;
3311 break;
3312 }
3313 }
3314 }
3315
3316 /*
3317 * Backwards compat. with the old boot-arg used to specify single zone
3318 * logging i.e. zlog Needs to happen after the newer zlogn checks
3319 * because the prefix will match all the zlogn
3320 * boot-args.
3321 */
3322 if (!logging_on &&
3323 PE_parse_boot_argn("zlog", zlog_val, sizeof(zlog_val))) {
3324 if (track_this_zone(zone_name, zlog_val) ||
3325 track_kalloc_zones(z, zlog_val)) {
3326 logging_on = true;
3327 }
3328 }
3329
3330 /*
3331 * If we want to log a zone, see if we need to allocate buffer space for
3332 * the log.
3333 *
3334 * Some vm related zones are zinit'ed before we can do a kmem_alloc, so
3335 * we have to defer allocation in that case.
3336 *
3337 * zone_init() will finish the job.
3338 *
3339 * If we want to log one of the VM related zones that's set up early on,
3340 * we will skip allocation of the log until zinit is called again later
3341 * on some other zone.
3342 */
3343 if (logging_on) {
3344 if (corruption_debug_flag) {
3345 z->z_btlog = btlog_create(BTLOG_LOG, zrecs, 0);
3346 } else {
3347 z->z_btlog = btlog_create(BTLOG_HASH,
3348 zone_leaks_record_count(z), 0);
3349 }
3350 if (z->z_btlog) {
3351 z->z_log_on = true;
3352 printf("zone[%s%s]: logging enabled\n",
3353 zone_heap_name(z), z->z_name);
3354 } else {
3355 printf("zone[%s%s]: failed to enable logging\n",
3356 zone_heap_name(z), z->z_name);
3357 }
3358 }
3359 }
3360
3361 #endif /* ZALLOC_ENABLE_LOGGING */
3362 #if KASAN_TBI
3363 static TUNABLE(uint32_t, kasan_zrecs, "kasan_zrecs", 0);
3364
3365 __startup_func
3366 static void
kasan_tbi_init_zrecs(void)3367 kasan_tbi_init_zrecs(void)
3368 {
3369 /*
3370 * Don't allow more than ZRECORDS_MAX records,
3371 * even if the user asked for more.
3372 *
3373 * This prevents accidentally hogging too much kernel memory
3374 * and making the system unusable.
3375 */
3376 if (kasan_zrecs == 0) {
3377 kasan_zrecs = ZRECORDS_DEFAULT *
3378 (uint32_t)((max_mem + (1ul << 30)) >> 30);
3379 }
3380 if (kasan_zrecs > ZRECORDS_MAX) {
3381 kasan_zrecs = ZRECORDS_MAX;
3382 }
3383 }
3384 STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, kasan_tbi_init_zrecs);
3385
3386 static void
zone_setup_kasan_logging(zone_t z)3387 zone_setup_kasan_logging(zone_t z)
3388 {
3389 if (!z->z_tbi_tag) {
3390 printf("zone[%s%s]: kasan logging disabled for this zone\n",
3391 zone_heap_name(z), z->z_name);
3392 return;
3393 }
3394
3395 z->z_log_on = true;
3396 z->z_btlog = btlog_create(BTLOG_LOG, kasan_zrecs, 0);
3397 if (!z->z_btlog) {
3398 printf("zone[%s%s]: failed to enable kasan logging\n",
3399 zone_heap_name(z), z->z_name);
3400 }
3401 }
3402
3403 #endif /* KASAN_TBI */
3404 #if CONFIG_ZLEAKS
3405
3406 static thread_call_data_t zone_leaks_callout;
3407
3408 /*
3409 * The zone leak detector, abbreviated 'zleak', keeps track
3410 * of a subset of the currently outstanding allocations
3411 * made by the zone allocator.
3412 *
3413 * Zones who use more than zleak_pages_per_zone_wired_threshold
3414 * pages will get a BTLOG_HASH btlog with sampling to minimize
3415 * perf impact, yet receive statistical data about the backtrace
3416 * that is the most likely to cause the leak.
3417 *
3418 * If the zone goes under the threshold enough, then the log
3419 * is disabled and backtraces freed. Data can be collected
3420 * from userspace with the zlog(1) command.
3421 */
3422
3423 uint32_t zleak_active;
3424 SECURITY_READ_ONLY_LATE(vm_size_t) zleak_max_zonemap_size;
3425
3426 /* Size a zone will have before we will collect data on it */
3427 static size_t zleak_pages_per_zone_wired_threshold = ~0;
3428 vm_size_t zleak_per_zone_tracking_threshold = ~0;
3429
3430 static inline bool
zleak_should_enable_for_zone(zone_t z)3431 zleak_should_enable_for_zone(zone_t z)
3432 {
3433 if (z->z_log_on) {
3434 return false;
3435 }
3436 if (z->z_btlog) {
3437 return false;
3438 }
3439 if (z->z_exhausts) {
3440 return false;
3441 }
3442 if (zone_exhaustible(z)) {
3443 return z->z_wired_cur * 8 >= z->z_wired_max * 7;
3444 }
3445 return z->z_wired_cur >= zleak_pages_per_zone_wired_threshold;
3446 }
3447
3448 static inline bool
zleak_should_disable_for_zone(zone_t z)3449 zleak_should_disable_for_zone(zone_t z)
3450 {
3451 if (z->z_log_on) {
3452 return false;
3453 }
3454 if (!z->z_btlog) {
3455 return false;
3456 }
3457 if (zone_exhaustible(z)) {
3458 return z->z_wired_cur * 8 < z->z_wired_max * 7;
3459 }
3460 return z->z_wired_cur < zleak_pages_per_zone_wired_threshold / 2;
3461 }
3462
3463 static void
zleaks_enable_async(__unused thread_call_param_t p0,__unused thread_call_param_t p1)3464 zleaks_enable_async(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
3465 {
3466 btlog_t log;
3467
3468 zone_foreach(z) {
3469 if (zleak_should_disable_for_zone(z)) {
3470 log = z->z_btlog;
3471 z->z_btlog = NULL;
3472 assert(z->z_btlog_disabled == NULL);
3473 btlog_disable(log);
3474 z->z_btlog_disabled = log;
3475 os_atomic_dec(&zleak_active, relaxed);
3476 }
3477
3478 if (zleak_should_enable_for_zone(z)) {
3479 log = z->z_btlog_disabled;
3480 if (log == NULL) {
3481 log = btlog_create(BTLOG_HASH,
3482 zone_leaks_record_count(z),
3483 zone_leaks_sample_rate(z));
3484 } else if (btlog_enable(log) == KERN_SUCCESS) {
3485 z->z_btlog_disabled = NULL;
3486 } else {
3487 log = NULL;
3488 }
3489 os_atomic_store(&z->z_btlog, log, release);
3490 os_atomic_inc(&zleak_active, relaxed);
3491 }
3492 }
3493 }
3494
3495 __startup_func
3496 static void
zleak_init(void)3497 zleak_init(void)
3498 {
3499 zleak_max_zonemap_size = ptoa(zone_pages_wired_max);
3500
3501 zleak_update_threshold(&zleak_per_zone_tracking_threshold,
3502 zleak_max_zonemap_size / 8);
3503
3504 thread_call_setup_with_options(&zone_leaks_callout,
3505 zleaks_enable_async, NULL, THREAD_CALL_PRIORITY_USER,
3506 THREAD_CALL_OPTIONS_ONCE);
3507 }
3508 STARTUP(ZALLOC, STARTUP_RANK_SECOND, zleak_init);
3509
3510 kern_return_t
zleak_update_threshold(vm_size_t * arg,uint64_t value)3511 zleak_update_threshold(vm_size_t *arg, uint64_t value)
3512 {
3513 if (value >= zleak_max_zonemap_size) {
3514 return KERN_INVALID_VALUE;
3515 }
3516
3517 if (arg == &zleak_per_zone_tracking_threshold) {
3518 zleak_per_zone_tracking_threshold = (vm_size_t)value;
3519 zleak_pages_per_zone_wired_threshold = atop(value);
3520 if (startup_phase >= STARTUP_SUB_THREAD_CALL) {
3521 thread_call_enter(&zone_leaks_callout);
3522 }
3523 return KERN_SUCCESS;
3524 }
3525
3526 return KERN_INVALID_ARGUMENT;
3527 }
3528
3529 static void
panic_display_zleaks(bool has_syms)3530 panic_display_zleaks(bool has_syms)
3531 {
3532 bool did_header = false;
3533 vm_address_t bt[BTLOG_MAX_DEPTH];
3534 uint32_t len, count;
3535
3536 zone_foreach(z) {
3537 btlog_t log = z->z_btlog;
3538
3539 if (log == NULL || btlog_get_type(log) != BTLOG_HASH) {
3540 continue;
3541 }
3542
3543 count = btlog_guess_top(log, bt, &len);
3544 if (count == 0) {
3545 continue;
3546 }
3547
3548 if (!did_header) {
3549 paniclog_append_noflush("Zone (suspected) leak report:\n");
3550 did_header = true;
3551 }
3552
3553 paniclog_append_noflush(" Zone: %s%s\n",
3554 zone_heap_name(z), zone_name(z));
3555 paniclog_append_noflush(" Count: %d (%ld bytes)\n", count,
3556 (long)count * zone_scale_for_percpu(z, zone_elem_inner_size(z)));
3557 paniclog_append_noflush(" Size: %ld\n",
3558 (long)zone_size_wired(z));
3559 paniclog_append_noflush(" Top backtrace:\n");
3560 for (uint32_t i = 0; i < len; i++) {
3561 if (has_syms) {
3562 paniclog_append_noflush(" %p ", (void *)bt[i]);
3563 panic_print_symbol_name(bt[i]);
3564 paniclog_append_noflush("\n");
3565 } else {
3566 paniclog_append_noflush(" %p\n", (void *)bt[i]);
3567 }
3568 }
3569
3570 kmod_panic_dump(bt, len);
3571 paniclog_append_noflush("\n");
3572 }
3573 }
3574 #endif /* CONFIG_ZLEAKS */
3575
3576 #endif /* ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS */
3577 #if ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS || KASAN_TBI
3578
3579 #if !KASAN_TBI
3580 __cold
3581 #endif
3582 static void
zalloc_log(zone_t zone,vm_offset_t addr,uint32_t count,void * fp)3583 zalloc_log(zone_t zone, vm_offset_t addr, uint32_t count, void *fp)
3584 {
3585 btlog_t log = zone->z_btlog;
3586 btref_get_flags_t flags = 0;
3587 btref_t ref;
3588
3589 #if !KASAN_TBI
3590 if (!log || !btlog_sample(log)) {
3591 return;
3592 }
3593 #endif
3594 if (get_preemption_level() || zone_supports_vm(zone)) {
3595 /*
3596 * VM zones can be used by btlog, avoid reentrancy issues.
3597 */
3598 flags = BTREF_GET_NOWAIT;
3599 }
3600
3601 ref = btref_get(fp, flags);
3602 while (count-- > 0) {
3603 if (count) {
3604 btref_retain(ref);
3605 }
3606 btlog_record(log, (void *)addr, ZOP_ALLOC, ref);
3607 addr += *(vm_offset_t *)addr;
3608 }
3609 }
3610
3611 #define ZALLOC_LOG(zone, addr, count) ({ \
3612 if ((zone)->z_btlog) { \
3613 zalloc_log(zone, addr, count, __builtin_frame_address(0)); \
3614 } \
3615 })
3616
3617 #if !KASAN_TBI
3618 __cold
3619 #endif
3620 static void
zfree_log(zone_t zone,vm_offset_t addr,uint32_t count,void * fp)3621 zfree_log(zone_t zone, vm_offset_t addr, uint32_t count, void *fp)
3622 {
3623 btlog_t log = zone->z_btlog;
3624 btref_get_flags_t flags = 0;
3625 btref_t ref;
3626
3627 #if !KASAN_TBI
3628 if (!log) {
3629 return;
3630 }
3631 #endif
3632
3633 /*
3634 * See if we're doing logging on this zone.
3635 *
3636 * There are two styles of logging used depending on
3637 * whether we're trying to catch a leak or corruption.
3638 */
3639 #if !KASAN_TBI
3640 if (btlog_get_type(log) == BTLOG_HASH) {
3641 /*
3642 * We're logging to catch a leak.
3643 *
3644 * Remove any record we might have for this element
3645 * since it's being freed. Note that we may not find it
3646 * if the buffer overflowed and that's OK.
3647 *
3648 * Since the log is of a limited size, old records get
3649 * overwritten if there are more zallocs than zfrees.
3650 */
3651 while (count-- > 0) {
3652 btlog_erase(log, (void *)addr);
3653 addr += *(vm_offset_t *)addr;
3654 }
3655 return;
3656 }
3657 #endif /* !KASAN_TBI */
3658
3659 if (get_preemption_level() || zone_supports_vm(zone)) {
3660 /*
3661 * VM zones can be used by btlog, avoid reentrancy issues.
3662 */
3663 flags = BTREF_GET_NOWAIT;
3664 }
3665
3666 ref = btref_get(fp, flags);
3667 while (count-- > 0) {
3668 if (count) {
3669 btref_retain(ref);
3670 }
3671 btlog_record(log, (void *)addr, ZOP_FREE, ref);
3672 addr += *(vm_offset_t *)addr;
3673 }
3674 }
3675
3676 #define ZFREE_LOG(zone, addr, count) ({ \
3677 if ((zone)->z_btlog) { \
3678 zfree_log(zone, addr, count, __builtin_frame_address(0)); \
3679 } \
3680 })
3681
3682 #else
3683 #define ZALLOC_LOG(...) ((void)0)
3684 #define ZFREE_LOG(...) ((void)0)
3685 #endif /* ZALLOC_ENABLE_LOGGING || CONFIG_ZLEAKS || KASAN_TBI */
3686 #endif /* !ZALLOC_TEST */
3687 #pragma mark zone (re)fill
3688 #if !ZALLOC_TEST
3689
3690 /*!
3691 * @defgroup Zone Refill
3692 * @{
3693 *
3694 * @brief
3695 * Functions handling The zone refill machinery.
3696 *
3697 * @discussion
3698 * Zones are refilled based on 2 mechanisms: direct expansion, async expansion.
3699 *
3700 * @c zalloc_ext() is the codepath that kicks the zone refill when the zone is
3701 * dropping below half of its @c z_elems_rsv (0 for most zones) and will:
3702 *
3703 * - call @c zone_expand_locked() directly if the caller is allowed to block,
3704 *
3705 * - wakeup the asynchroous expansion thread call if the caller is not allowed
3706 * to block, or if the reserve becomes depleted.
3707 *
3708 *
3709 * <h2>Synchronous expansion</h2>
3710 *
3711 * This mechanism is actually the only one that may refill a zone, and all the
3712 * other ones funnel through this one eventually.
3713 *
3714 * @c zone_expand_locked() implements the core of the expansion mechanism,
3715 * and will do so while a caller specified predicate is true.
3716 *
3717 * Zone expansion allows for up to 2 threads to concurrently refill the zone:
3718 * - one VM privileged thread,
3719 * - one regular thread.
3720 *
3721 * Regular threads that refill will put down their identity in @c z_expander,
3722 * so that priority inversion avoidance can be implemented.
3723 *
3724 * However, VM privileged threads are allowed to use VM page reserves,
3725 * which allows for the system to recover from extreme memory pressure
3726 * situations, allowing for the few allocations that @c zone_gc() or
3727 * killing processes require.
3728 *
3729 * When a VM privileged thread is also expanding, the @c z_expander_vm_priv bit
3730 * is set. @c z_expander is not necessarily the identity of this VM privileged
3731 * thread (it is if the VM privileged thread came in first, but wouldn't be, and
3732 * could even be @c THREAD_NULL otherwise).
3733 *
3734 * Note that the pageout-scan daemon might be BG and is VM privileged. To avoid
3735 * spending a whole pointer on priority inheritance for VM privileged threads
3736 * (and other issues related to having two owners), we use the rwlock boost as
3737 * a stop gap to avoid priority inversions.
3738 *
3739 *
3740 * <h2>Chunk wiring policies</h2>
3741 *
3742 * Zones allocate memory in chunks of @c zone_t::z_chunk_pages pages at a time
3743 * to try to minimize fragmentation relative to element sizes not aligning with
3744 * a chunk size well. However, this can grow large and be hard to fulfill on
3745 * a system under a lot of memory pressure (chunks can be as long as 8 pages on
3746 * 4k page systems).
3747 *
3748 * This is why, when under memory pressure the system allows chunks to be
3749 * partially populated. The metadata of the first page in the chunk maintains
3750 * the count of actually populated pages.
3751 *
3752 * The metadata for addresses assigned to a zone are found of 4 queues:
3753 * - @c z_pageq_empty has chunk heads with populated pages and no allocated
3754 * elements (those can be targeted by @c zone_gc()),
3755 * - @c z_pageq_partial has chunk heads with populated pages that are partially
3756 * used,
3757 * - @c z_pageq_full has chunk heads with populated pages with no free elements
3758 * left,
3759 * - @c z_pageq_va has either chunk heads for sequestered VA space assigned to
3760 * the zone forever, or the first secondary metadata for a chunk whose
3761 * corresponding page is not populated in the chunk.
3762 *
3763 * When new pages need to be wired/populated, chunks from the @c z_pageq_va
3764 * queues are preferred.
3765 *
3766 *
3767 * <h2>Asynchronous expansion</h2>
3768 *
3769 * This mechanism allows for refilling zones used mostly with non blocking
3770 * callers. It relies on a thread call (@c zone_expand_callout) which will
3771 * iterate all zones and refill the ones marked with @c z_async_refilling.
3772 *
3773 * NOTE: If the calling thread for zalloc_noblock is lower priority than
3774 * the thread_call, then zalloc_noblock to an empty zone may succeed.
3775 *
3776 *
3777 * <h2>Dealing with zone allocations from the mach VM code</h2>
3778 *
3779 * The implementation of the mach VM itself uses the zone allocator
3780 * for things like the vm_map_entry data structure. In order to prevent
3781 * a recursion problem when adding more pages to a zone, the VM zones
3782 * use the Z_SUBMAP_IDX_VM submap which doesn't use kmem_alloc()
3783 * or any VM map functions to allocate.
3784 *
3785 * Instead, a really simple coalescing first-fit allocator is used
3786 * for this submap, and no one else than zalloc can allocate from it.
3787 *
3788 * Memory is directly populated which doesn't require allocation of
3789 * VM map entries, and avoids recursion. The cost of this scheme however,
3790 * is that `vm_map_lookup_entry` will not function on those addresses
3791 * (nor any API relying on it).
3792 */
3793
3794 static void zone_reclaim_elements(zone_t z, uint16_t n, vm_offset_t *elems);
3795 static void zone_depot_trim(zone_t z, uint32_t target, struct zone_depot *zd);
3796 static thread_call_data_t zone_expand_callout;
3797
3798 __attribute__((overloadable))
3799 static inline bool
zone_submap_is_sequestered(zone_submap_idx_t idx)3800 zone_submap_is_sequestered(zone_submap_idx_t idx)
3801 {
3802 return idx != Z_SUBMAP_IDX_DATA;
3803 }
3804
3805 __attribute__((overloadable))
3806 static inline bool
zone_submap_is_sequestered(zone_security_flags_t zsflags)3807 zone_submap_is_sequestered(zone_security_flags_t zsflags)
3808 {
3809 return zone_submap_is_sequestered(zsflags.z_submap_idx);
3810 }
3811
3812 static inline kma_flags_t
zone_kma_flags(zone_t z,zone_security_flags_t zsflags,zalloc_flags_t flags)3813 zone_kma_flags(zone_t z, zone_security_flags_t zsflags, zalloc_flags_t flags)
3814 {
3815 kma_flags_t kmaflags = KMA_KOBJECT | KMA_ZERO;
3816
3817 if (zsflags.z_noencrypt) {
3818 kmaflags |= KMA_NOENCRYPT;
3819 }
3820 if (zsflags.z_submap_idx == Z_SUBMAP_IDX_DATA) {
3821 kmaflags |= KMA_DATA;
3822 }
3823 if (flags & Z_NOPAGEWAIT) {
3824 kmaflags |= KMA_NOPAGEWAIT;
3825 }
3826 if (z->z_permanent || (!z->z_destructible &&
3827 zone_submap_is_sequestered(zsflags))) {
3828 kmaflags |= KMA_PERMANENT;
3829 }
3830 if (zsflags.z_submap_from_end) {
3831 kmaflags |= KMA_LAST_FREE;
3832 }
3833
3834
3835 return kmaflags;
3836 }
3837
3838 static inline void
zone_add_wired_pages(zone_t z,uint32_t pages)3839 zone_add_wired_pages(zone_t z, uint32_t pages)
3840 {
3841 os_atomic_add(&zone_pages_wired, pages, relaxed);
3842
3843 #if CONFIG_ZLEAKS
3844 if (__improbable(zleak_should_enable_for_zone(z) &&
3845 startup_phase >= STARTUP_SUB_THREAD_CALL)) {
3846 thread_call_enter(&zone_leaks_callout);
3847 }
3848 #else
3849 (void)z;
3850 #endif
3851 }
3852
3853 static inline void
zone_remove_wired_pages(zone_t z,uint32_t pages)3854 zone_remove_wired_pages(zone_t z, uint32_t pages)
3855 {
3856 os_atomic_sub(&zone_pages_wired, pages, relaxed);
3857
3858 #if CONFIG_ZLEAKS
3859 if (__improbable(zleak_should_disable_for_zone(z) &&
3860 startup_phase >= STARTUP_SUB_THREAD_CALL)) {
3861 thread_call_enter(&zone_leaks_callout);
3862 }
3863 #else
3864 (void)z;
3865 #endif
3866 }
3867
3868 #if ZSECURITY_CONFIG(ZONE_TAGGING)
3869 static inline vm_address_t
zone_tag_element(zone_t zone,vm_offset_t addr,vm_size_t elem_size)3870 zone_tag_element(zone_t zone, vm_offset_t addr, vm_size_t elem_size)
3871 {
3872 vm_offset_t tagged_address = vm_memtag_assign_tag(addr, elem_size);
3873 vm_memtag_set_tag(tagged_address, elem_size);
3874
3875 if (zone->z_percpu) {
3876 zpercpu_foreach_cpu(index) {
3877 vm_memtag_set_tag(tagged_address + ptoa(index), elem_size);
3878 }
3879 }
3880
3881 return tagged_address;
3882 }
3883
3884 static inline vm_address_t
zone_tag_free_element(zone_t zone,vm_offset_t addr,vm_size_t elem_size)3885 zone_tag_free_element(zone_t zone, vm_offset_t addr, vm_size_t elem_size)
3886 {
3887 if (__improbable(addr > 0xFF00000000000000ULL)) {
3888 return addr;
3889 }
3890
3891 return zone_tag_element(zone, addr, elem_size);
3892 }
3893
3894 static inline void
zcram_memtag_init(zone_t zone,vm_offset_t base,uint32_t start,uint32_t end)3895 zcram_memtag_init(zone_t zone, vm_offset_t base, uint32_t start, uint32_t end)
3896 {
3897 zone_security_flags_t *zsflags = &zone_security_array[zone_index(zone)];
3898
3899 if (!zsflags->z_tag) {
3900 return;
3901 }
3902
3903 vm_offset_t elem_size = zone_elem_outer_size(zone);
3904 vm_offset_t oob_offs = zone_elem_outer_offs(zone);
3905
3906 for (uint32_t i = start; i < end; i++) {
3907 vm_offset_t elem_addr = base + oob_offs + i * elem_size;
3908
3909 (void)zone_tag_element(zone, elem_addr, elem_size);
3910 }
3911 }
3912 #else /* ZSECURITY_CONFIG(ZONE_TAGGING) */
3913 #define zone_tag_free_element(z, a, s) (a)
3914 #define zcram_memtag_init(z, b, s, e) do {} while (0)
3915 #endif /* ZSECURITY_CONFIG(ZONE_TAGGING) */
3916
3917 /*!
3918 * @function zcram_and_lock()
3919 *
3920 * @brief
3921 * Prepare some memory for being usable for allocation purposes.
3922 *
3923 * @discussion
3924 * Prepare memory in <code>[addr + ptoa(pg_start), addr + ptoa(pg_end))</code>
3925 * to be usable in the zone.
3926 *
3927 * This function assumes the metadata is already populated for the range.
3928 *
3929 * Calling this function with @c pg_start being 0 means that the memory
3930 * is either a partial chunk, or a full chunk, that isn't published anywhere
3931 * and the initialization can happen without locks held.
3932 *
3933 * Calling this function with a non zero @c pg_start means that we are extending
3934 * an existing chunk: the memory in <code>[addr, addr + ptoa(pg_start))</code>,
3935 * is already usable and published in the zone, so extending it requires holding
3936 * the zone lock.
3937 *
3938 * @param zone The zone to cram new populated pages into
3939 * @param addr The base address for the chunk(s)
3940 * @param pg_va_new The number of virtual pages newly assigned to the zone
3941 * @param pg_start The first newly populated page relative to @a addr.
3942 * @param pg_end The after-last newly populated page relative to @a addr.
3943 * @param lock 0 or ZM_ALLOC_SIZE_LOCK (used by early crams)
3944 */
3945 static void
zcram_and_lock(zone_t zone,vm_offset_t addr,uint32_t pg_va_new,uint32_t pg_start,uint32_t pg_end,uint16_t lock)3946 zcram_and_lock(zone_t zone, vm_offset_t addr, uint32_t pg_va_new,
3947 uint32_t pg_start, uint32_t pg_end, uint16_t lock)
3948 {
3949 zone_id_t zindex = zone_index(zone);
3950 vm_offset_t elem_size = zone_elem_outer_size(zone);
3951 uint32_t free_start = 0, free_end = 0;
3952 uint32_t oob_offs = zone_elem_outer_offs(zone);
3953
3954 struct zone_page_metadata *meta = zone_meta_from_addr(addr);
3955 uint32_t chunk_pages = zone->z_chunk_pages;
3956 bool guarded = meta->zm_guarded;
3957
3958 assert(pg_start < pg_end && pg_end <= chunk_pages);
3959
3960 if (pg_start == 0) {
3961 uint16_t chunk_len = (uint16_t)pg_end;
3962 uint16_t secondary_len = ZM_SECONDARY_PAGE;
3963 bool inline_bitmap = false;
3964
3965 if (zone->z_percpu) {
3966 chunk_len = 1;
3967 secondary_len = ZM_SECONDARY_PCPU_PAGE;
3968 assert(pg_end == zpercpu_count());
3969 }
3970 if (!zone->z_permanent && !zone->z_uses_tags) {
3971 inline_bitmap = zone->z_chunk_elems <= 32 * chunk_pages;
3972 }
3973
3974 free_end = (uint32_t)(ptoa(chunk_len) - oob_offs) / elem_size;
3975
3976 meta[0] = (struct zone_page_metadata){
3977 .zm_index = zindex,
3978 .zm_guarded = guarded,
3979 .zm_inline_bitmap = inline_bitmap,
3980 .zm_chunk_len = chunk_len,
3981 .zm_alloc_size = lock,
3982 };
3983
3984 if (!zone->z_permanent && !inline_bitmap) {
3985 meta[0].zm_bitmap = zone_meta_bits_alloc_init(free_end,
3986 zone->z_chunk_elems, zone->z_uses_tags);
3987 }
3988
3989 for (uint16_t i = 1; i < chunk_pages; i++) {
3990 meta[i] = (struct zone_page_metadata){
3991 .zm_index = zindex,
3992 .zm_guarded = guarded,
3993 .zm_inline_bitmap = inline_bitmap,
3994 .zm_chunk_len = secondary_len,
3995 .zm_page_index = (uint8_t)i,
3996 .zm_bitmap = meta[0].zm_bitmap,
3997 .zm_subchunk_len = (uint8_t)(chunk_pages - i),
3998 };
3999 }
4000
4001 if (inline_bitmap) {
4002 zone_meta_bits_init_inline(meta, free_end);
4003 }
4004 } else {
4005 assert(!zone->z_percpu && !zone->z_permanent);
4006
4007 free_end = (uint32_t)(ptoa(pg_end) - oob_offs) / elem_size;
4008 free_start = (uint32_t)(ptoa(pg_start) - oob_offs) / elem_size;
4009 }
4010
4011 zcram_memtag_init(zone, addr, free_start, free_end);
4012
4013 #if KASAN_CLASSIC
4014 assert(pg_start == 0); /* KASAN_CLASSIC never does partial chunks */
4015 if (zone->z_permanent) {
4016 kasan_poison_range(addr, ptoa(pg_end), ASAN_VALID);
4017 } else if (zone->z_percpu) {
4018 for (uint32_t i = 0; i < pg_end; i++) {
4019 kasan_zmem_add(addr + ptoa(i), PAGE_SIZE,
4020 zone_elem_outer_size(zone),
4021 zone_elem_outer_offs(zone),
4022 zone_elem_redzone(zone));
4023 }
4024 } else {
4025 kasan_zmem_add(addr, ptoa(pg_end),
4026 zone_elem_outer_size(zone),
4027 zone_elem_outer_offs(zone),
4028 zone_elem_redzone(zone));
4029 }
4030 #endif /* KASAN_CLASSIC */
4031
4032 /*
4033 * Insert the initialized pages / metadatas into the right lists.
4034 */
4035
4036 zone_lock(zone);
4037 assert(zone->z_self == zone);
4038
4039 if (pg_start != 0) {
4040 assert(meta->zm_chunk_len == pg_start);
4041
4042 zone_meta_bits_merge(meta, free_start, free_end);
4043 meta->zm_chunk_len = (uint16_t)pg_end;
4044
4045 /*
4046 * consume the zone_meta_lock_in_partial()
4047 * done in zone_expand_locked()
4048 */
4049 zone_meta_alloc_size_sub(zone, meta, ZM_ALLOC_SIZE_LOCK);
4050 zone_meta_remqueue(zone, meta);
4051 }
4052
4053 if (zone->z_permanent || meta->zm_alloc_size) {
4054 zone_meta_queue_push(zone, &zone->z_pageq_partial, meta);
4055 } else {
4056 zone_meta_queue_push(zone, &zone->z_pageq_empty, meta);
4057 zone->z_wired_empty += zone->z_percpu ? 1 : pg_end;
4058 }
4059 if (pg_end < chunk_pages) {
4060 /* push any non populated residual VA on z_pageq_va */
4061 zone_meta_queue_push(zone, &zone->z_pageq_va, meta + pg_end);
4062 }
4063
4064 zone->z_elems_free += free_end - free_start;
4065 zone->z_elems_avail += free_end - free_start;
4066 zone->z_wired_cur += zone->z_percpu ? 1 : pg_end - pg_start;
4067 if (pg_va_new) {
4068 zone->z_va_cur += zone->z_percpu ? 1 : pg_va_new;
4069 }
4070 if (zone->z_wired_hwm < zone->z_wired_cur) {
4071 zone->z_wired_hwm = zone->z_wired_cur;
4072 }
4073
4074 #if CONFIG_ZLEAKS
4075 if (__improbable(zleak_should_enable_for_zone(zone) &&
4076 startup_phase >= STARTUP_SUB_THREAD_CALL)) {
4077 thread_call_enter(&zone_leaks_callout);
4078 }
4079 #endif /* CONFIG_ZLEAKS */
4080
4081 zone_add_wired_pages(zone, pg_end - pg_start);
4082 }
4083
4084 static void
zcram(zone_t zone,vm_offset_t addr,uint32_t pages,uint16_t lock)4085 zcram(zone_t zone, vm_offset_t addr, uint32_t pages, uint16_t lock)
4086 {
4087 uint32_t chunk_pages = zone->z_chunk_pages;
4088
4089 assert(pages % chunk_pages == 0);
4090 for (; pages > 0; pages -= chunk_pages, addr += ptoa(chunk_pages)) {
4091 zcram_and_lock(zone, addr, chunk_pages, 0, chunk_pages, lock);
4092 zone_unlock(zone);
4093 }
4094 }
4095
4096 __startup_func
4097 void
zone_cram_early(zone_t zone,vm_offset_t newmem,vm_size_t size)4098 zone_cram_early(zone_t zone, vm_offset_t newmem, vm_size_t size)
4099 {
4100 uint32_t pages = (uint32_t)atop(size);
4101
4102
4103 assert(from_zone_map(newmem, size));
4104 assert3u(size % ptoa(zone->z_chunk_pages), ==, 0);
4105 assert3u(startup_phase, <, STARTUP_SUB_ZALLOC);
4106
4107 /*
4108 * The early pages we move at the pmap layer can't be "depopulated"
4109 * because there's no vm_page_t for them.
4110 *
4111 * "Lock" them so that they never hit z_pageq_empty.
4112 */
4113 vm_memtag_bzero((void *)newmem, size);
4114 zcram(zone, newmem, pages, ZM_ALLOC_SIZE_LOCK);
4115 }
4116
4117 /*!
4118 * @function zone_submap_alloc_sequestered_va
4119 *
4120 * @brief
4121 * Allocates VA without using vm_find_space().
4122 *
4123 * @discussion
4124 * Allocate VA quickly without using the slower vm_find_space() for cases
4125 * when the submaps are fully sequestered.
4126 *
4127 * The VM submap is used to implement the VM itself so it is always sequestered,
4128 * as it can't kmem_alloc which needs to always allocate vm entries.
4129 * However, it can use vm_map_enter() which tries to coalesce entries, which
4130 * always works, so the VM map only ever needs 2 entries (one for each end).
4131 *
4132 * The RO submap is similarly always sequestered if it exists (as a non
4133 * sequestered RO submap makes very little sense).
4134 *
4135 * The allocator is a very simple bump-allocator
4136 * that allocates from either end.
4137 */
4138 static kern_return_t
zone_submap_alloc_sequestered_va(zone_security_flags_t zsflags,uint32_t pages,vm_offset_t * addrp)4139 zone_submap_alloc_sequestered_va(zone_security_flags_t zsflags, uint32_t pages,
4140 vm_offset_t *addrp)
4141 {
4142 vm_size_t size = ptoa(pages);
4143 vm_map_t map = zone_submap(zsflags);
4144 vm_map_entry_t first, last;
4145 vm_map_offset_t addr;
4146
4147 vm_map_lock(map);
4148
4149 first = vm_map_first_entry(map);
4150 last = vm_map_last_entry(map);
4151
4152 if (first->vme_end + size > last->vme_start) {
4153 vm_map_unlock(map);
4154 return KERN_NO_SPACE;
4155 }
4156
4157 if (zsflags.z_submap_from_end) {
4158 last->vme_start -= size;
4159 addr = last->vme_start;
4160 VME_OFFSET_SET(last, addr);
4161 } else {
4162 addr = first->vme_end;
4163 first->vme_end += size;
4164 }
4165 map->size += size;
4166
4167 vm_map_unlock(map);
4168
4169 *addrp = addr;
4170 return KERN_SUCCESS;
4171 }
4172
4173 void
zone_fill_initially(zone_t zone,vm_size_t nelems)4174 zone_fill_initially(zone_t zone, vm_size_t nelems)
4175 {
4176 kma_flags_t kmaflags = KMA_NOFAIL | KMA_PERMANENT;
4177 kern_return_t kr;
4178 vm_offset_t addr;
4179 uint32_t pages;
4180 zone_security_flags_t zsflags = zone_security_config(zone);
4181
4182 assert(!zone->z_permanent && !zone->collectable && !zone->z_destructible);
4183 assert(zone->z_elems_avail == 0);
4184
4185 kmaflags |= zone_kma_flags(zone, zsflags, Z_WAITOK);
4186 pages = zone_alloc_pages_for_nelems(zone, nelems);
4187 if (zone_submap_is_sequestered(zsflags)) {
4188 kr = zone_submap_alloc_sequestered_va(zsflags, pages, &addr);
4189 if (kr != KERN_SUCCESS) {
4190 panic("zone_submap_alloc_sequestered_va() "
4191 "of %u pages failed", pages);
4192 }
4193 kernel_memory_populate(addr, ptoa(pages),
4194 kmaflags, VM_KERN_MEMORY_ZONE);
4195 } else {
4196 assert(zsflags.z_submap_idx != Z_SUBMAP_IDX_READ_ONLY);
4197 kmem_alloc(zone_submap(zsflags), &addr, ptoa(pages),
4198 kmaflags, VM_KERN_MEMORY_ZONE);
4199 }
4200
4201 zone_meta_populate(addr, ptoa(pages));
4202 zcram(zone, addr, pages, 0);
4203 }
4204
4205 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
4206 __attribute__((noinline))
4207 static void
zone_scramble_va_and_unlock(zone_t z,struct zone_page_metadata * meta,uint32_t runs,uint32_t pages,uint32_t chunk_pages,uint64_t guard_mask)4208 zone_scramble_va_and_unlock(
4209 zone_t z,
4210 struct zone_page_metadata *meta,
4211 uint32_t runs,
4212 uint32_t pages,
4213 uint32_t chunk_pages,
4214 uint64_t guard_mask)
4215 {
4216 struct zone_page_metadata *arr[ZONE_CHUNK_ALLOC_SIZE / 4096];
4217
4218 for (uint32_t run = 0, n = 0; run < runs; run++) {
4219 arr[run] = meta + n;
4220 n += chunk_pages + ((guard_mask >> run) & 1);
4221 }
4222
4223 /*
4224 * Fisher–Yates shuffle, for an array with indices [0, n)
4225 *
4226 * for i from n−1 downto 1 do
4227 * j ← random integer such that 0 ≤ j ≤ i
4228 * exchange a[j] and a[i]
4229 *
4230 * The point here is that early allocations aren't at a fixed
4231 * distance from each other.
4232 */
4233 for (uint32_t i = runs - 1; i > 0; i--) {
4234 uint32_t j = zalloc_random_uniform32(0, i + 1);
4235
4236 meta = arr[j];
4237 arr[j] = arr[i];
4238 arr[i] = meta;
4239 }
4240
4241 zone_lock(z);
4242
4243 for (uint32_t i = 0; i < runs; i++) {
4244 zone_meta_queue_push(z, &z->z_pageq_va, arr[i]);
4245 }
4246 z->z_va_cur += z->z_percpu ? runs : pages;
4247 }
4248
4249 static inline uint32_t
dist_u32(uint32_t a,uint32_t b)4250 dist_u32(uint32_t a, uint32_t b)
4251 {
4252 return a < b ? b - a : a - b;
4253 }
4254
4255 static uint64_t
zalloc_random_clear_n_bits(uint64_t mask,uint32_t pop,uint32_t n)4256 zalloc_random_clear_n_bits(uint64_t mask, uint32_t pop, uint32_t n)
4257 {
4258 for (; n-- > 0; pop--) {
4259 uint32_t bit = zalloc_random_uniform32(0, pop);
4260 uint64_t m = mask;
4261
4262 for (; bit; bit--) {
4263 m &= m - 1;
4264 }
4265
4266 mask ^= 1ull << __builtin_ctzll(m);
4267 }
4268
4269 return mask;
4270 }
4271
4272 /**
4273 * @function zalloc_random_bits
4274 *
4275 * @brief
4276 * Compute a random number with a specified number of bit set in a given width.
4277 *
4278 * @discussion
4279 * This function generates a "uniform" distribution of sets of bits set in
4280 * a given width, with typically less than width/4 calls to random.
4281 *
4282 * @param pop the target number of bits set.
4283 * @param width the number of bits in the random integer to generate.
4284 */
4285 static uint64_t
zalloc_random_bits(uint32_t pop,uint32_t width)4286 zalloc_random_bits(uint32_t pop, uint32_t width)
4287 {
4288 uint64_t w_mask = (1ull << width) - 1;
4289 uint64_t mask;
4290 uint32_t cur;
4291
4292 if (3 * width / 4 <= pop) {
4293 mask = w_mask;
4294 cur = width;
4295 } else if (pop <= width / 4) {
4296 mask = 0;
4297 cur = 0;
4298 } else {
4299 /*
4300 * Chosing a random number this way will overwhelmingly
4301 * contain `width` bits +/- a few.
4302 */
4303 mask = zalloc_random_mask64(width);
4304 cur = __builtin_popcountll(mask);
4305
4306 if (dist_u32(cur, pop) > dist_u32(width - cur, pop)) {
4307 /*
4308 * If the opposite mask has a closer popcount,
4309 * then start with that one as the seed.
4310 */
4311 cur = width - cur;
4312 mask ^= w_mask;
4313 }
4314 }
4315
4316 if (cur < pop) {
4317 /*
4318 * Setting `pop - cur` bits is really clearing that many from
4319 * the opposite mask.
4320 */
4321 mask ^= w_mask;
4322 mask = zalloc_random_clear_n_bits(mask, width - cur, pop - cur);
4323 mask ^= w_mask;
4324 } else if (pop < cur) {
4325 mask = zalloc_random_clear_n_bits(mask, cur, cur - pop);
4326 }
4327
4328 return mask;
4329 }
4330 #endif
4331
4332 static void
zone_allocate_va_locked(zone_t z,zalloc_flags_t flags)4333 zone_allocate_va_locked(zone_t z, zalloc_flags_t flags)
4334 {
4335 zone_security_flags_t zsflags = zone_security_config(z);
4336 struct zone_page_metadata *meta;
4337 kma_flags_t kmaflags = zone_kma_flags(z, zsflags, flags) | KMA_VAONLY;
4338 uint32_t chunk_pages = z->z_chunk_pages;
4339 uint32_t runs, pages, guards, rnum;
4340 uint64_t guard_mask = 0;
4341 bool lead_guard = false;
4342 kern_return_t kr;
4343 vm_offset_t addr;
4344
4345 zone_unlock(z);
4346
4347 /*
4348 * A lot of OOB exploitation techniques rely on precise placement
4349 * and interleaving of zone pages. The layout that is sought
4350 * by attackers will be C/P/T types, where:
4351 * - (C)ompromised is the type for which attackers have a bug,
4352 * - (P)adding is used to pad memory,
4353 * - (T)arget is the type that the attacker will attempt to corrupt
4354 * by exploiting (C).
4355 *
4356 * Note that in some cases C==T and P isn't needed.
4357 *
4358 * In order to make those placement games much harder,
4359 * we grow zones by random runs of memory, up to 256k.
4360 * This makes predicting the precise layout of the heap
4361 * quite more complicated.
4362 *
4363 * Note: this function makes a very heavy use of random,
4364 * however, it is mostly limited to sequestered zones,
4365 * and eventually the layout will be fixed,
4366 * and the usage of random vastly reduced.
4367 *
4368 * For non sequestered zones, there's a single call
4369 * to random in order to decide whether we want
4370 * a guard page or not.
4371 */
4372 pages = chunk_pages;
4373 guards = 0;
4374 runs = 1;
4375 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
4376 if (!z->z_percpu && zone_submap_is_sequestered(zsflags)) {
4377 pages = atop(ZONE_CHUNK_ALLOC_SIZE);
4378 runs = (pages + chunk_pages - 1) / chunk_pages;
4379 runs = zalloc_random_uniform32(1, runs + 1);
4380 pages = runs * chunk_pages;
4381 }
4382 static_assert(ZONE_CHUNK_ALLOC_SIZE / 4096 <= 64,
4383 "make sure that `runs` will never be larger than 64");
4384 #endif /* !ZSECURITY_CONFIG(SAD_FENG_SHUI) */
4385
4386 /*
4387 * Zones that are suceptible to OOB (kalloc, ZC_PGZ_USE_GUARDS),
4388 * guards might be added after each chunk.
4389 *
4390 * Those guard pages are marked with the ZM_PGZ_GUARD
4391 * magical chunk len, and their zm_oob_offs field
4392 * is used to remember optional shift applied
4393 * to returned elements, in order to right-align-them
4394 * as much as possible.
4395 *
4396 * In an adversarial context, while guard pages
4397 * are extremely effective against linear overflow,
4398 * using a predictable density of guard pages feels like
4399 * a missed opportunity. Which is why we chose to insert
4400 * one guard page for about 32k of memory, and place it
4401 * randomly.
4402 */
4403 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
4404 if (z->z_percpu) {
4405 /*
4406 * For per-cpu runs, have a 75% chance to have a guard.
4407 */
4408 rnum = zalloc_random_uniform32(0, 4 * 128);
4409 guards = rnum >= 128;
4410 } else if (!zsflags.z_pgz_use_guards && !z->z_pgz_use_guards) {
4411 vm_offset_t rest;
4412
4413 /*
4414 * For types that are less susceptible to have OOBs,
4415 * have a density of 1 guard every 64k, with a uniform
4416 * distribution.
4417 */
4418 rnum = zalloc_random_uniform32(0, ZONE_GUARD_SPARSE);
4419 guards = (uint32_t)ptoa(pages) / ZONE_GUARD_SPARSE;
4420 rest = (uint32_t)ptoa(pages) % ZONE_GUARD_SPARSE;
4421 guards += rnum < rest;
4422 } else if (ptoa(chunk_pages) >= ZONE_GUARD_DENSE) {
4423 /*
4424 * For chunks >= 32k, have a 75% chance of guard pages
4425 * between chunks.
4426 */
4427 rnum = zalloc_random_uniform32(65, 129);
4428 guards = runs * rnum / 128;
4429 } else {
4430 vm_offset_t rest;
4431
4432 /*
4433 * Otherwise, aim at 1 guard every 32k,
4434 * with a uniform distribution.
4435 */
4436 rnum = zalloc_random_uniform32(0, ZONE_GUARD_DENSE);
4437 guards = (uint32_t)ptoa(pages) / ZONE_GUARD_DENSE;
4438 rest = (uint32_t)ptoa(pages) % ZONE_GUARD_DENSE;
4439 guards += rnum < rest;
4440 }
4441 assert3u(guards, <=, runs);
4442
4443 guard_mask = 0;
4444
4445 if (!z->z_percpu && zone_submap_is_sequestered(zsflags)) {
4446 uint32_t g = 0;
4447
4448 /*
4449 * Several exploitation strategies rely on a C/T (compromised
4450 * then target types) ordering of pages with a sub-page reach
4451 * from C into T.
4452 *
4453 * We want to reliably thwart such exploitations
4454 * and hence force a guard page between alternating
4455 * memory types.
4456 */
4457 guard_mask |= 1ull << (runs - 1);
4458 g++;
4459
4460 /*
4461 * While we randomize the chunks lengths, an attacker with
4462 * precise timing control can guess when overflows happen,
4463 * and "measure" the runs, which gives them an indication
4464 * of where the next run start offset is.
4465 *
4466 * In order to make this knowledge unusable, add a guard page
4467 * _before_ the new run with a 25% probability, regardless
4468 * of whether we had enough guard pages.
4469 */
4470 if ((rnum & 3) == 0) {
4471 lead_guard = true;
4472 g++;
4473 }
4474 if (guards > g) {
4475 guard_mask |= zalloc_random_bits(guards - g, runs - 1);
4476 } else {
4477 guards = g;
4478 }
4479 } else {
4480 assert3u(runs, ==, 1);
4481 assert3u(guards, <=, 1);
4482 guard_mask = guards << (runs - 1);
4483 }
4484 #else
4485 (void)rnum;
4486 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
4487
4488 if (zone_submap_is_sequestered(zsflags)) {
4489 kr = zone_submap_alloc_sequestered_va(zsflags,
4490 pages + guards, &addr);
4491 } else {
4492 assert(zsflags.z_submap_idx != Z_SUBMAP_IDX_READ_ONLY);
4493 kr = kmem_alloc(zone_submap(zsflags), &addr,
4494 ptoa(pages + guards), kmaflags, VM_KERN_MEMORY_ZONE);
4495 }
4496
4497 if (kr != KERN_SUCCESS) {
4498 uint64_t zone_size = 0;
4499 zone_t zone_largest = zone_find_largest(&zone_size);
4500 panic("zalloc[%d]: zone map exhausted while allocating from zone [%s%s], "
4501 "likely due to memory leak in zone [%s%s] "
4502 "(%u%c, %d elements allocated)",
4503 kr, zone_heap_name(z), zone_name(z),
4504 zone_heap_name(zone_largest), zone_name(zone_largest),
4505 mach_vm_size_pretty(zone_size),
4506 mach_vm_size_unit(zone_size),
4507 zone_count_allocated(zone_largest));
4508 }
4509
4510 meta = zone_meta_from_addr(addr);
4511 zone_meta_populate(addr, ptoa(pages + guards));
4512
4513 /*
4514 * Handle the leading guard page if any
4515 */
4516 if (lead_guard) {
4517 meta[0].zm_index = zone_index(z);
4518 meta[0].zm_chunk_len = ZM_PGZ_GUARD;
4519 meta[0].zm_guarded = true;
4520 meta++;
4521 }
4522
4523 for (uint32_t run = 0, n = 0; run < runs; run++) {
4524 bool guarded = (guard_mask >> run) & 1;
4525
4526 for (uint32_t i = 0; i < chunk_pages; i++, n++) {
4527 meta[n].zm_index = zone_index(z);
4528 meta[n].zm_guarded = guarded;
4529 }
4530 if (guarded) {
4531 meta[n].zm_index = zone_index(z);
4532 meta[n].zm_chunk_len = ZM_PGZ_GUARD;
4533 n++;
4534 }
4535 }
4536 if (guards) {
4537 os_atomic_add(&zone_guard_pages, guards, relaxed);
4538 }
4539
4540 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
4541 if (__improbable(zone_caching_disabled < 0)) {
4542 return zone_scramble_va_and_unlock(z, meta, runs, pages,
4543 chunk_pages, guard_mask);
4544 }
4545 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
4546
4547 zone_lock(z);
4548
4549 for (uint32_t run = 0, n = 0; run < runs; run++) {
4550 zone_meta_queue_push(z, &z->z_pageq_va, meta + n);
4551 n += chunk_pages + ((guard_mask >> run) & 1);
4552 }
4553 z->z_va_cur += z->z_percpu ? runs : pages;
4554 }
4555
4556 static inline void
ZONE_TRACE_VM_KERN_REQUEST_START(vm_size_t size)4557 ZONE_TRACE_VM_KERN_REQUEST_START(vm_size_t size)
4558 {
4559 #if DEBUG || DEVELOPMENT
4560 VM_DEBUG_CONSTANT_EVENT(vm_kern_request, DBG_VM_KERN_REQUEST, DBG_FUNC_START,
4561 size, 0, 0, 0);
4562 #else
4563 (void)size;
4564 #endif
4565 }
4566
4567 static inline void
ZONE_TRACE_VM_KERN_REQUEST_END(uint32_t pages)4568 ZONE_TRACE_VM_KERN_REQUEST_END(uint32_t pages)
4569 {
4570 #if DEBUG || DEVELOPMENT
4571 task_t task = current_task_early();
4572 if (pages && task) {
4573 ledger_credit(task->ledger, task_ledgers.pages_grabbed_kern, pages);
4574 }
4575 VM_DEBUG_CONSTANT_EVENT(vm_kern_request, DBG_VM_KERN_REQUEST, DBG_FUNC_END,
4576 pages, 0, 0, 0);
4577 #else
4578 (void)pages;
4579 #endif
4580 }
4581
4582 __attribute__((noinline))
4583 static void
__ZONE_MAP_EXHAUSTED_AND_WAITING_FOR_GC__(zone_t z,uint32_t pgs)4584 __ZONE_MAP_EXHAUSTED_AND_WAITING_FOR_GC__(zone_t z, uint32_t pgs)
4585 {
4586 uint64_t wait_start = 0;
4587 long mapped;
4588
4589 thread_wakeup(VM_PAGEOUT_GC_EVENT);
4590
4591 if (zone_supports_vm(z) || (current_thread()->options & TH_OPT_VMPRIV)) {
4592 return;
4593 }
4594
4595 mapped = os_atomic_load(&zone_pages_wired, relaxed);
4596
4597 /*
4598 * If the zone map is really exhausted, wait on the GC thread,
4599 * donating our priority (which is important because the GC
4600 * thread is at a rather low priority).
4601 */
4602 for (uint32_t n = 1; mapped >= zone_pages_wired_max - pgs; n++) {
4603 uint32_t wait_ms = n * (n + 1) / 2;
4604 uint64_t interval;
4605
4606 if (n == 1) {
4607 wait_start = mach_absolute_time();
4608 } else {
4609 thread_wakeup(VM_PAGEOUT_GC_EVENT);
4610 }
4611 if (zone_exhausted_timeout > 0 &&
4612 wait_ms > zone_exhausted_timeout) {
4613 panic("zone map exhaustion: waited for %dms "
4614 "(pages: %ld, max: %ld, wanted: %d)",
4615 wait_ms, mapped, zone_pages_wired_max, pgs);
4616 }
4617
4618 clock_interval_to_absolutetime_interval(wait_ms, NSEC_PER_MSEC,
4619 &interval);
4620
4621 lck_spin_lock(&zone_exhausted_lock);
4622 lck_spin_sleep_with_inheritor(&zone_exhausted_lock,
4623 LCK_SLEEP_UNLOCK, &zone_pages_wired,
4624 vm_pageout_gc_thread, THREAD_UNINT, wait_start + interval);
4625
4626 mapped = os_atomic_load(&zone_pages_wired, relaxed);
4627 }
4628 }
4629
4630 static bool
zone_expand_wait_for_pages(bool waited)4631 zone_expand_wait_for_pages(bool waited)
4632 {
4633 if (waited) {
4634 return false;
4635 }
4636 #if DEBUG || DEVELOPMENT
4637 if (zalloc_simulate_vm_pressure) {
4638 return false;
4639 }
4640 #endif /* DEBUG || DEVELOPMENT */
4641 return !vm_pool_low();
4642 }
4643
4644 static inline void
zone_expand_async_schedule_if_allowed(zone_t zone)4645 zone_expand_async_schedule_if_allowed(zone_t zone)
4646 {
4647 if (zone->z_async_refilling || zone->no_callout) {
4648 return;
4649 }
4650
4651 if (zone_exhausted(zone)) {
4652 return;
4653 }
4654
4655 if (__improbable(startup_phase < STARTUP_SUB_EARLY_BOOT)) {
4656 return;
4657 }
4658
4659 if (!vm_pool_low() || zone_supports_vm(zone)) {
4660 zone->z_async_refilling = true;
4661 thread_call_enter(&zone_expand_callout);
4662 }
4663 }
4664
4665 __attribute__((noinline))
4666 static bool
zalloc_expand_drain_exhausted_caches_locked(zone_t z)4667 zalloc_expand_drain_exhausted_caches_locked(zone_t z)
4668 {
4669 struct zone_depot zd;
4670 zone_magazine_t mag = NULL;
4671
4672 if (z->z_depot_size) {
4673 z->z_depot_size = 0;
4674 z->z_depot_cleanup = true;
4675
4676 zone_depot_init(&zd);
4677 zone_depot_trim(z, 0, &zd);
4678
4679 zone_recirc_lock_nopreempt(z);
4680 if (zd.zd_full) {
4681 zone_depot_move_full(&z->z_recirc,
4682 &zd, zd.zd_full, NULL);
4683 }
4684 if (zd.zd_empty) {
4685 zone_depot_move_empty(&z->z_recirc,
4686 &zd, zd.zd_empty, NULL);
4687 }
4688 zone_recirc_unlock_nopreempt(z);
4689 }
4690
4691 zone_recirc_lock_nopreempt(z);
4692 if (z->z_recirc.zd_full) {
4693 mag = zone_depot_pop_head_full(&z->z_recirc, z);
4694 }
4695 zone_recirc_unlock_nopreempt(z);
4696
4697 if (mag) {
4698 zone_reclaim_elements(z, zc_mag_size(), mag->zm_elems);
4699 zone_magazine_free(mag);
4700 }
4701
4702 return mag != NULL;
4703 }
4704
4705 static bool
zalloc_needs_refill(zone_t zone,zalloc_flags_t flags)4706 zalloc_needs_refill(zone_t zone, zalloc_flags_t flags)
4707 {
4708 if (zone->z_elems_free > zone->z_elems_rsv) {
4709 return false;
4710 }
4711 if (!zone_exhausted(zone)) {
4712 return true;
4713 }
4714 if (zone->z_pcpu_cache && zone->z_depot_size) {
4715 if (zalloc_expand_drain_exhausted_caches_locked(zone)) {
4716 return false;
4717 }
4718 }
4719 return (flags & Z_NOFAIL) != 0;
4720 }
4721
4722 static void
zone_wakeup_exhausted_waiters(zone_t z)4723 zone_wakeup_exhausted_waiters(zone_t z)
4724 {
4725 z->z_exhausted_wait = false;
4726 EVENT_INVOKE(ZONE_EXHAUSTED, zone_index(z), z, false);
4727 thread_wakeup(&z->z_expander);
4728 }
4729
4730 __attribute__((noinline))
4731 static void
__ZONE_EXHAUSTED_AND_WAITING_HARD__(zone_t z)4732 __ZONE_EXHAUSTED_AND_WAITING_HARD__(zone_t z)
4733 {
4734 if (z->z_pcpu_cache && z->z_depot_size &&
4735 zalloc_expand_drain_exhausted_caches_locked(z)) {
4736 return;
4737 }
4738
4739 if (!z->z_exhausted_wait) {
4740 zone_recirc_lock_nopreempt(z);
4741 z->z_exhausted_wait = true;
4742 zone_recirc_unlock_nopreempt(z);
4743 EVENT_INVOKE(ZONE_EXHAUSTED, zone_index(z), z, true);
4744 }
4745
4746 assert_wait(&z->z_expander, TH_UNINT);
4747 zone_unlock(z);
4748 thread_block(THREAD_CONTINUE_NULL);
4749 zone_lock(z);
4750 }
4751
4752 static pmap_mapping_type_t
zone_mapping_type(zone_t z)4753 zone_mapping_type(zone_t z)
4754 {
4755 zone_security_flags_t zsflags = zone_security_config(z);
4756
4757 /*
4758 * If the zone has z_submap_idx is not Z_SUBMAP_IDX_DATA or
4759 * Z_SUBMAP_IDX_READ_ONLY, mark the corresponding mapping
4760 * type as PMAP_MAPPING_TYPE_RESTRICTED.
4761 */
4762 switch (zsflags.z_submap_idx) {
4763 case Z_SUBMAP_IDX_DATA:
4764 return PMAP_MAPPING_TYPE_DEFAULT;
4765 case Z_SUBMAP_IDX_READ_ONLY:
4766 return PMAP_MAPPING_TYPE_ROZONE;
4767 default:
4768 return PMAP_MAPPING_TYPE_RESTRICTED;
4769 }
4770 }
4771
4772 static vm_prot_t
zone_page_prot(zone_security_flags_t zsflags)4773 zone_page_prot(zone_security_flags_t zsflags)
4774 {
4775 switch (zsflags.z_submap_idx) {
4776 case Z_SUBMAP_IDX_READ_ONLY:
4777 return VM_PROT_READ;
4778 default:
4779 return VM_PROT_READ | VM_PROT_WRITE;
4780 }
4781 }
4782
4783 static void
zone_expand_locked(zone_t z,zalloc_flags_t flags)4784 zone_expand_locked(zone_t z, zalloc_flags_t flags)
4785 {
4786 zone_security_flags_t zsflags = zone_security_config(z);
4787 struct zone_expand ze = {
4788 .ze_thread = current_thread(),
4789 };
4790
4791 if (!(ze.ze_thread->options & TH_OPT_VMPRIV) && zone_supports_vm(z)) {
4792 ze.ze_thread->options |= TH_OPT_VMPRIV;
4793 ze.ze_clear_priv = true;
4794 }
4795
4796 if (ze.ze_thread->options & TH_OPT_VMPRIV) {
4797 /*
4798 * When the thread is VM privileged,
4799 * vm_page_grab() will call VM_PAGE_WAIT()
4800 * without our knowledge, so we must assume
4801 * it's being called unfortunately.
4802 *
4803 * In practice it's not a big deal because
4804 * Z_NOPAGEWAIT is not really used on zones
4805 * that VM privileged threads are going to expand.
4806 */
4807 ze.ze_pg_wait = true;
4808 ze.ze_vm_priv = true;
4809 }
4810
4811 for (;;) {
4812 if (!z->z_permanent && !zalloc_needs_refill(z, flags)) {
4813 goto out;
4814 }
4815
4816 if (z->z_expander == NULL) {
4817 z->z_expander = &ze;
4818 break;
4819 }
4820
4821 if (ze.ze_vm_priv && !z->z_expander->ze_vm_priv) {
4822 change_sleep_inheritor(&z->z_expander, ze.ze_thread);
4823 ze.ze_next = z->z_expander;
4824 z->z_expander = &ze;
4825 break;
4826 }
4827
4828 if ((flags & Z_NOPAGEWAIT) && z->z_expander->ze_pg_wait) {
4829 goto out;
4830 }
4831
4832 z->z_expanding_wait = true;
4833 hw_lck_ticket_sleep_with_inheritor(&z->z_lock, &zone_locks_grp,
4834 LCK_SLEEP_DEFAULT, &z->z_expander, z->z_expander->ze_thread,
4835 TH_UNINT, TIMEOUT_WAIT_FOREVER);
4836 }
4837
4838 do {
4839 struct zone_page_metadata *meta = NULL;
4840 uint32_t new_va = 0, cur_pages = 0, min_pages = 0, pages = 0;
4841 vm_page_t page_list = NULL;
4842 vm_offset_t addr = 0;
4843 int waited = 0;
4844
4845 if ((flags & Z_NOFAIL) && zone_exhausted(z)) {
4846 __ZONE_EXHAUSTED_AND_WAITING_HARD__(z);
4847 continue; /* reevaluate if we really need it */
4848 }
4849
4850 /*
4851 * While we hold the zone lock, look if there's VA we can:
4852 * - complete from partial pages,
4853 * - reuse from the sequester list.
4854 *
4855 * When the page is being populated we pretend we allocated
4856 * an extra element so that zone_gc() can't attempt to free
4857 * the chunk (as it could become empty while we wait for pages).
4858 */
4859 if (zone_pva_is_null(z->z_pageq_va)) {
4860 zone_allocate_va_locked(z, flags);
4861 }
4862
4863 meta = zone_meta_queue_pop(z, &z->z_pageq_va);
4864 addr = zone_meta_to_addr(meta);
4865 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
4866 cur_pages = meta->zm_page_index;
4867 meta -= cur_pages;
4868 addr -= ptoa(cur_pages);
4869 zone_meta_lock_in_partial(z, meta, cur_pages);
4870 }
4871 zone_unlock(z);
4872
4873 /*
4874 * And now allocate pages to populate our VA.
4875 */
4876 min_pages = z->z_chunk_pages;
4877 #if !KASAN_CLASSIC
4878 if (!z->z_percpu) {
4879 min_pages = (uint32_t)atop(round_page(zone_elem_outer_offs(z) +
4880 zone_elem_outer_size(z)));
4881 }
4882 #endif /* !KASAN_CLASSIC */
4883
4884 /*
4885 * Trigger jetsams via VM_PAGEOUT_GC_EVENT
4886 * if we're running out of zone memory
4887 */
4888 if (__improbable(zone_map_nearing_exhaustion())) {
4889 __ZONE_MAP_EXHAUSTED_AND_WAITING_FOR_GC__(z, min_pages);
4890 }
4891
4892 ZONE_TRACE_VM_KERN_REQUEST_START(ptoa(z->z_chunk_pages - cur_pages));
4893
4894 while (pages < z->z_chunk_pages - cur_pages) {
4895 uint_t grab_options = VM_PAGE_GRAB_OPTIONS_NONE;
4896 vm_page_t m = vm_page_grab_options(grab_options);
4897
4898 if (m) {
4899 pages++;
4900 m->vmp_snext = page_list;
4901 page_list = m;
4902 vm_page_zero_fill(m);
4903 continue;
4904 }
4905
4906 if (pages >= min_pages &&
4907 !zone_expand_wait_for_pages(waited)) {
4908 break;
4909 }
4910
4911 if ((flags & Z_NOPAGEWAIT) == 0) {
4912 /*
4913 * The first time we're about to wait for pages,
4914 * mention that to waiters and wake them all.
4915 *
4916 * Set `ze_pg_wait` in our zone_expand context
4917 * so that waiters who care do not wait again.
4918 */
4919 if (!ze.ze_pg_wait) {
4920 zone_lock(z);
4921 if (z->z_expanding_wait) {
4922 z->z_expanding_wait = false;
4923 wakeup_all_with_inheritor(&z->z_expander,
4924 THREAD_AWAKENED);
4925 }
4926 ze.ze_pg_wait = true;
4927 zone_unlock(z);
4928 }
4929
4930 waited++;
4931 VM_PAGE_WAIT();
4932 continue;
4933 }
4934
4935 /*
4936 * Undo everything and bail out:
4937 *
4938 * - free pages
4939 * - undo the fake allocation if any
4940 * - put the VA back on the VA page queue.
4941 */
4942 vm_page_free_list(page_list, FALSE);
4943 ZONE_TRACE_VM_KERN_REQUEST_END(pages);
4944
4945 zone_lock(z);
4946
4947 zone_expand_async_schedule_if_allowed(z);
4948
4949 if (cur_pages) {
4950 zone_meta_unlock_from_partial(z, meta, cur_pages);
4951 }
4952 if (meta) {
4953 zone_meta_queue_push(z, &z->z_pageq_va,
4954 meta + cur_pages);
4955 }
4956 goto page_shortage;
4957 }
4958 vm_object_t object;
4959 object = kernel_object_default;
4960 vm_object_lock(object);
4961
4962 kernel_memory_populate_object_and_unlock(object,
4963 addr + ptoa(cur_pages), addr + ptoa(cur_pages), ptoa(pages), page_list,
4964 zone_kma_flags(z, zsflags, flags), VM_KERN_MEMORY_ZONE,
4965 zone_page_prot(zsflags), zone_mapping_type(z));
4966
4967 ZONE_TRACE_VM_KERN_REQUEST_END(pages);
4968
4969 zcram_and_lock(z, addr, new_va, cur_pages, cur_pages + pages, 0);
4970
4971 /*
4972 * permanent zones only try once,
4973 * the retry loop is in the caller
4974 */
4975 } while (!z->z_permanent && zalloc_needs_refill(z, flags));
4976
4977 page_shortage:
4978 if (z->z_expander == &ze) {
4979 z->z_expander = ze.ze_next;
4980 } else {
4981 assert(z->z_expander->ze_next == &ze);
4982 z->z_expander->ze_next = NULL;
4983 }
4984 if (z->z_expanding_wait) {
4985 z->z_expanding_wait = false;
4986 wakeup_all_with_inheritor(&z->z_expander, THREAD_AWAKENED);
4987 }
4988 out:
4989 if (ze.ze_clear_priv) {
4990 ze.ze_thread->options &= ~TH_OPT_VMPRIV;
4991 }
4992 }
4993
4994 static void
zone_expand_async(__unused thread_call_param_t p0,__unused thread_call_param_t p1)4995 zone_expand_async(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
4996 {
4997 zone_foreach(z) {
4998 if (z->no_callout) {
4999 /* z_async_refilling will never be set */
5000 continue;
5001 }
5002
5003 if (!z->z_async_refilling) {
5004 /*
5005 * avoid locking all zones, because the one(s)
5006 * we're looking for have been set _before_
5007 * thread_call_enter() was called, if we fail
5008 * to observe the bit, it means the thread-call
5009 * has been "dinged" again and we'll notice it then.
5010 */
5011 continue;
5012 }
5013
5014 zone_lock(z);
5015 if (z->z_self && z->z_async_refilling) {
5016 zone_expand_locked(z, Z_WAITOK);
5017 /*
5018 * clearing _after_ we grow is important,
5019 * so that we avoid waking up the thread call
5020 * while we grow and cause to run a second time.
5021 */
5022 z->z_async_refilling = false;
5023 }
5024 zone_unlock(z);
5025 }
5026 }
5027
5028 #endif /* !ZALLOC_TEST */
5029 #pragma mark zone jetsam integration
5030 #if !ZALLOC_TEST
5031
5032 /*
5033 * We're being very conservative here and picking a value of 95%. We might need to lower this if
5034 * we find that we're not catching the problem and are still hitting zone map exhaustion panics.
5035 */
5036 #define ZONE_MAP_JETSAM_LIMIT_DEFAULT 95
5037
5038 /*
5039 * Threshold above which largest zones should be included in the panic log
5040 */
5041 #define ZONE_MAP_EXHAUSTION_PRINT_PANIC 80
5042
5043 /*
5044 * Trigger zone-map-exhaustion jetsams if the zone map is X% full,
5045 * where X=zone_map_jetsam_limit.
5046 *
5047 * Can be set via boot-arg "zone_map_jetsam_limit". Set to 95% by default.
5048 */
5049 TUNABLE_WRITEABLE(unsigned int, zone_map_jetsam_limit, "zone_map_jetsam_limit",
5050 ZONE_MAP_JETSAM_LIMIT_DEFAULT);
5051
5052 kern_return_t
zone_map_jetsam_set_limit(uint32_t value)5053 zone_map_jetsam_set_limit(uint32_t value)
5054 {
5055 if (value <= 0 || value > 100) {
5056 return KERN_INVALID_VALUE;
5057 }
5058
5059 zone_map_jetsam_limit = value;
5060 os_atomic_store(&zone_pages_jetsam_threshold,
5061 zone_pages_wired_max * value / 100, relaxed);
5062 return KERN_SUCCESS;
5063 }
5064
5065 void
get_zone_map_size(uint64_t * current_size,uint64_t * capacity)5066 get_zone_map_size(uint64_t *current_size, uint64_t *capacity)
5067 {
5068 vm_offset_t phys_pages = os_atomic_load(&zone_pages_wired, relaxed);
5069 *current_size = ptoa_64(phys_pages);
5070 *capacity = ptoa_64(zone_pages_wired_max);
5071 }
5072
5073 void
get_largest_zone_info(char * zone_name,size_t zone_name_len,uint64_t * zone_size)5074 get_largest_zone_info(char *zone_name, size_t zone_name_len, uint64_t *zone_size)
5075 {
5076 zone_t largest_zone = zone_find_largest(zone_size);
5077
5078 /*
5079 * Append kalloc heap name to zone name (if zone is used by kalloc)
5080 */
5081 snprintf(zone_name, zone_name_len, "%s%s",
5082 zone_heap_name(largest_zone), largest_zone->z_name);
5083 }
5084
5085 static bool
zone_map_nearing_threshold(unsigned int threshold)5086 zone_map_nearing_threshold(unsigned int threshold)
5087 {
5088 uint64_t phys_pages = os_atomic_load(&zone_pages_wired, relaxed);
5089 return phys_pages * 100 > zone_pages_wired_max * threshold;
5090 }
5091
5092 bool
zone_map_nearing_exhaustion(void)5093 zone_map_nearing_exhaustion(void)
5094 {
5095 vm_size_t pages = os_atomic_load(&zone_pages_wired, relaxed);
5096
5097 return pages >= os_atomic_load(&zone_pages_jetsam_threshold, relaxed);
5098 }
5099
5100
5101 #define VMENTRY_TO_VMOBJECT_COMPARISON_RATIO 98
5102
5103 /*
5104 * Tries to kill a single process if it can attribute one to the largest zone. If not, wakes up the memorystatus thread
5105 * to walk through the jetsam priority bands and kill processes.
5106 */
5107 static zone_t
kill_process_in_largest_zone(void)5108 kill_process_in_largest_zone(void)
5109 {
5110 pid_t pid = -1;
5111 uint64_t zone_size = 0;
5112 zone_t largest_zone = zone_find_largest(&zone_size);
5113
5114 printf("zone_map_exhaustion: Zone mapped %lld of %lld, used %lld, capacity %lld [jetsam limit %d%%]\n",
5115 ptoa_64(os_atomic_load(&zone_pages_wired, relaxed)),
5116 ptoa_64(zone_pages_wired_max),
5117 (uint64_t)zone_submaps_approx_size(),
5118 (uint64_t)mach_vm_range_size(&zone_info.zi_map_range),
5119 zone_map_jetsam_limit);
5120 printf("zone_map_exhaustion: Largest zone %s%s, size %lu\n", zone_heap_name(largest_zone),
5121 largest_zone->z_name, (uintptr_t)zone_size);
5122
5123 /*
5124 * We want to make sure we don't call this function from userspace.
5125 * Or we could end up trying to synchronously kill the process
5126 * whose context we're in, causing the system to hang.
5127 */
5128 assert(current_task() == kernel_task);
5129
5130 /*
5131 * If vm_object_zone is the largest, check to see if the number of
5132 * elements in vm_map_entry_zone is comparable.
5133 *
5134 * If so, consider vm_map_entry_zone as the largest. This lets us target
5135 * a specific process to jetsam to quickly recover from the zone map
5136 * bloat.
5137 */
5138 if (largest_zone == vm_object_zone) {
5139 unsigned int vm_object_zone_count = zone_count_allocated(vm_object_zone);
5140 unsigned int vm_map_entry_zone_count = zone_count_allocated(vm_map_entry_zone);
5141 /* Is the VM map entries zone count >= 98% of the VM objects zone count? */
5142 if (vm_map_entry_zone_count >= ((vm_object_zone_count * VMENTRY_TO_VMOBJECT_COMPARISON_RATIO) / 100)) {
5143 largest_zone = vm_map_entry_zone;
5144 printf("zone_map_exhaustion: Picking VM map entries as the zone to target, size %lu\n",
5145 (uintptr_t)zone_size_wired(largest_zone));
5146 }
5147 }
5148
5149 /* TODO: Extend this to check for the largest process in other zones as well. */
5150 if (largest_zone == vm_map_entry_zone) {
5151 pid = find_largest_process_vm_map_entries();
5152 } else {
5153 printf("zone_map_exhaustion: Nothing to do for the largest zone [%s%s]. "
5154 "Waking up memorystatus thread.\n", zone_heap_name(largest_zone),
5155 largest_zone->z_name);
5156 }
5157 if (!memorystatus_kill_on_zone_map_exhaustion(pid)) {
5158 printf("zone_map_exhaustion: Call to memorystatus failed, victim pid: %d\n", pid);
5159 }
5160
5161 return largest_zone;
5162 }
5163
5164 #endif /* !ZALLOC_TEST */
5165 #pragma mark probabilistic gzalloc
5166 #if !ZALLOC_TEST
5167 #if CONFIG_PROB_GZALLOC
5168
5169 extern uint32_t random(void);
5170 struct pgz_backtrace {
5171 uint32_t pgz_depth;
5172 int32_t pgz_bt[MAX_ZTRACE_DEPTH];
5173 };
5174
5175 static int32_t PERCPU_DATA(pgz_sample_counter);
5176 static SECURITY_READ_ONLY_LATE(struct pgz_backtrace *) pgz_backtraces;
5177 static uint32_t pgz_uses; /* number of zones using PGZ */
5178 static int32_t pgz_slot_avail;
5179 #if OS_ATOMIC_HAS_LLSC
5180 struct zone_page_metadata *pgz_slot_head;
5181 #else
5182 static struct pgz_slot_head {
5183 uint32_t psh_count;
5184 uint32_t psh_slot;
5185 } pgz_slot_head;
5186 #endif
5187 struct zone_page_metadata *pgz_slot_tail;
5188 static SECURITY_READ_ONLY_LATE(vm_map_t) pgz_submap;
5189
5190 static struct zone_page_metadata *
pgz_meta(uint32_t index)5191 pgz_meta(uint32_t index)
5192 {
5193 return &zone_info.zi_pgz_meta[2 * index + 1];
5194 }
5195
5196 static struct pgz_backtrace *
pgz_bt(uint32_t slot,bool free)5197 pgz_bt(uint32_t slot, bool free)
5198 {
5199 return &pgz_backtraces[2 * slot + free];
5200 }
5201
5202 static void
pgz_backtrace(struct pgz_backtrace * bt,void * fp)5203 pgz_backtrace(struct pgz_backtrace *bt, void *fp)
5204 {
5205 struct backtrace_control ctl = {
5206 .btc_frame_addr = (uintptr_t)fp,
5207 };
5208
5209 bt->pgz_depth = (uint32_t)backtrace_packed(BTP_KERN_OFFSET_32,
5210 (uint8_t *)bt->pgz_bt, sizeof(bt->pgz_bt), &ctl, NULL) / 4;
5211 }
5212
5213 static uint32_t
pgz_slot(vm_offset_t addr)5214 pgz_slot(vm_offset_t addr)
5215 {
5216 return (uint32_t)((addr - zone_info.zi_pgz_range.min_address) >> (PAGE_SHIFT + 1));
5217 }
5218
5219 static vm_offset_t
pgz_addr(uint32_t slot)5220 pgz_addr(uint32_t slot)
5221 {
5222 return zone_info.zi_pgz_range.min_address + ptoa(2 * slot + 1);
5223 }
5224
5225 static bool
pgz_sample(vm_offset_t addr,vm_size_t esize)5226 pgz_sample(vm_offset_t addr, vm_size_t esize)
5227 {
5228 int32_t *counterp, cnt;
5229
5230 if (zone_addr_size_crosses_page(addr, esize)) {
5231 return false;
5232 }
5233
5234 /*
5235 * Note: accessing pgz_sample_counter is racy but this is
5236 * kind of acceptable given that this is not
5237 * a security load bearing feature.
5238 */
5239
5240 counterp = PERCPU_GET(pgz_sample_counter);
5241 cnt = *counterp;
5242 if (__probable(cnt > 0)) {
5243 *counterp = cnt - 1;
5244 return false;
5245 }
5246
5247 if (pgz_slot_avail <= 0) {
5248 return false;
5249 }
5250
5251 /*
5252 * zalloc_random_uniform() might block, so when preemption is disabled,
5253 * set the counter to `-1` which will cause the next allocation
5254 * that can block to generate a new random value.
5255 *
5256 * No allocation on this CPU will sample until then.
5257 */
5258 if (get_preemption_level()) {
5259 *counterp = -1;
5260 } else {
5261 *counterp = zalloc_random_uniform32(0, 2 * pgz_sample_rate);
5262 }
5263
5264 return cnt == 0;
5265 }
5266
5267 static inline bool
pgz_slot_alloc(uint32_t * slot)5268 pgz_slot_alloc(uint32_t *slot)
5269 {
5270 struct zone_page_metadata *m;
5271 uint32_t tries = 100;
5272
5273 disable_preemption();
5274
5275 #if OS_ATOMIC_USE_LLSC
5276 int32_t ov, nv;
5277 os_atomic_rmw_loop(&pgz_slot_avail, ov, nv, relaxed, {
5278 if (__improbable(ov <= 0)) {
5279 os_atomic_rmw_loop_give_up({
5280 enable_preemption();
5281 return false;
5282 });
5283 }
5284 nv = ov - 1;
5285 });
5286 #else
5287 if (__improbable(os_atomic_dec_orig(&pgz_slot_avail, relaxed) <= 0)) {
5288 os_atomic_inc(&pgz_slot_avail, relaxed);
5289 enable_preemption();
5290 return false;
5291 }
5292 #endif
5293
5294 again:
5295 if (__improbable(tries-- == 0)) {
5296 /*
5297 * Too much contention,
5298 * extremely unlikely but do not stay stuck.
5299 */
5300 os_atomic_inc(&pgz_slot_avail, relaxed);
5301 enable_preemption();
5302 return false;
5303 }
5304
5305 #if OS_ATOMIC_HAS_LLSC
5306 uint32_t castries = 20;
5307 do {
5308 if (__improbable(castries-- == 0)) {
5309 /*
5310 * rdar://115922110 On many many cores devices,
5311 * this can fail for a very long time.
5312 */
5313 goto again;
5314 }
5315
5316 m = os_atomic_load_exclusive(&pgz_slot_head, dependency);
5317 if (__improbable(m->zm_pgz_slot_next == NULL)) {
5318 /*
5319 * Either we are waiting for an enqueuer (unlikely)
5320 * or we are competing with another core and
5321 * are looking at a popped element.
5322 */
5323 os_atomic_clear_exclusive();
5324 goto again;
5325 }
5326 } while (!os_atomic_store_exclusive(&pgz_slot_head,
5327 m->zm_pgz_slot_next, relaxed));
5328 #else
5329 struct zone_page_metadata *base = zone_info.zi_pgz_meta;
5330 struct pgz_slot_head ov, nv;
5331 os_atomic_rmw_loop(&pgz_slot_head, ov, nv, dependency, {
5332 m = &base[ov.psh_slot * 2];
5333 if (__improbable(m->zm_pgz_slot_next == NULL)) {
5334 /*
5335 * Either we are waiting for an enqueuer (unlikely)
5336 * or we are competing with another core and
5337 * are looking at a popped element.
5338 */
5339 os_atomic_rmw_loop_give_up(goto again);
5340 }
5341 nv.psh_count = ov.psh_count + 1;
5342 nv.psh_slot = (uint32_t)((m->zm_pgz_slot_next - base) / 2);
5343 });
5344 #endif
5345
5346 enable_preemption();
5347
5348 m->zm_pgz_slot_next = NULL;
5349 *slot = (uint32_t)((m - zone_info.zi_pgz_meta) / 2);
5350 return true;
5351 }
5352
5353 static inline bool
pgz_slot_free(uint32_t slot)5354 pgz_slot_free(uint32_t slot)
5355 {
5356 struct zone_page_metadata *m = &zone_info.zi_pgz_meta[2 * slot];
5357 struct zone_page_metadata *t;
5358
5359 disable_preemption();
5360 t = os_atomic_xchg(&pgz_slot_tail, m, relaxed);
5361 os_atomic_store(&t->zm_pgz_slot_next, m, release);
5362 os_atomic_inc(&pgz_slot_avail, relaxed);
5363 enable_preemption();
5364
5365 return true;
5366 }
5367
5368 /*!
5369 * @function pgz_protect()
5370 *
5371 * @brief
5372 * Try to protect an allocation with PGZ.
5373 *
5374 * @param zone The zone the allocation was made against.
5375 * @param addr An allocated element address to protect.
5376 * @param fp The caller frame pointer (for the backtrace).
5377 * @returns The new address for the element, or @c addr.
5378 */
5379 __attribute__((noinline))
5380 static vm_offset_t
pgz_protect(zone_t zone,vm_offset_t addr,void * fp)5381 pgz_protect(zone_t zone, vm_offset_t addr, void *fp)
5382 {
5383 kern_return_t kr;
5384 uint32_t slot;
5385 uint_t flags = 0;
5386
5387 if (!pgz_slot_alloc(&slot)) {
5388 return addr;
5389 }
5390
5391 /*
5392 * Try to double-map the page (may fail if Z_NOWAIT).
5393 * we will always find a PA because pgz_init() pre-expanded the pmap.
5394 */
5395 pmap_paddr_t pa = kvtophys(trunc_page(addr));
5396 vm_offset_t new_addr = pgz_addr(slot);
5397 kr = pmap_enter_options_addr(kernel_pmap, new_addr, pa,
5398 VM_PROT_READ | VM_PROT_WRITE, VM_PROT_NONE, flags, TRUE,
5399 get_preemption_level() ? (PMAP_OPTIONS_NOWAIT | PMAP_OPTIONS_NOPREEMPT) : 0,
5400 NULL, PMAP_MAPPING_TYPE_INFER);
5401
5402 if (__improbable(kr != KERN_SUCCESS)) {
5403 pgz_slot_free(slot);
5404 return addr;
5405 }
5406
5407 struct zone_page_metadata tmp = {
5408 .zm_chunk_len = ZM_PGZ_ALLOCATED,
5409 .zm_index = zone_index(zone),
5410 };
5411 struct zone_page_metadata *meta = pgz_meta(slot);
5412
5413 os_atomic_store(&meta->zm_bits, tmp.zm_bits, relaxed);
5414 os_atomic_store(&meta->zm_pgz_orig_addr, addr, relaxed);
5415 pgz_backtrace(pgz_bt(slot, false), fp);
5416
5417 return new_addr + (addr & PAGE_MASK);
5418 }
5419
5420 /*!
5421 * @function pgz_unprotect()
5422 *
5423 * @brief
5424 * Release a PGZ slot and returns the original address of a freed element.
5425 *
5426 * @param addr A PGZ protected element address.
5427 * @param fp The caller frame pointer (for the backtrace).
5428 * @returns The non protected address for the element
5429 * that was passed to @c pgz_protect().
5430 */
5431 __attribute__((noinline))
5432 static vm_offset_t
pgz_unprotect(vm_offset_t addr,void * fp)5433 pgz_unprotect(vm_offset_t addr, void *fp)
5434 {
5435 struct zone_page_metadata *meta;
5436 struct zone_page_metadata tmp;
5437 uint32_t slot;
5438
5439 slot = pgz_slot(addr);
5440 meta = zone_meta_from_addr(addr);
5441 tmp = *meta;
5442 if (tmp.zm_chunk_len != ZM_PGZ_ALLOCATED) {
5443 goto double_free;
5444 }
5445
5446 pmap_remove_options(kernel_pmap, vm_memtag_canonicalize_address(trunc_page(addr)),
5447 vm_memtag_canonicalize_address(trunc_page(addr) + PAGE_SIZE),
5448 PMAP_OPTIONS_REMOVE | PMAP_OPTIONS_NOPREEMPT);
5449
5450 pgz_backtrace(pgz_bt(slot, true), fp);
5451
5452 tmp.zm_chunk_len = ZM_PGZ_FREE;
5453 tmp.zm_bits = os_atomic_xchg(&meta->zm_bits, tmp.zm_bits, relaxed);
5454 if (tmp.zm_chunk_len != ZM_PGZ_ALLOCATED) {
5455 goto double_free;
5456 }
5457
5458 pgz_slot_free(slot);
5459 return tmp.zm_pgz_orig_addr;
5460
5461 double_free:
5462 panic_fault_address = addr;
5463 meta->zm_chunk_len = ZM_PGZ_DOUBLE_FREE;
5464 panic("probabilistic gzalloc double free: %p", (void *)addr);
5465 }
5466
5467 bool
pgz_owned(mach_vm_address_t addr)5468 pgz_owned(mach_vm_address_t addr)
5469 {
5470 return mach_vm_range_contains(&zone_info.zi_pgz_range, vm_memtag_canonicalize_address(addr));
5471 }
5472
5473
5474 __attribute__((always_inline))
5475 vm_offset_t
__pgz_decode(mach_vm_address_t addr,mach_vm_size_t size)5476 __pgz_decode(mach_vm_address_t addr, mach_vm_size_t size)
5477 {
5478 struct zone_page_metadata *meta;
5479
5480 if (__probable(!pgz_owned(addr))) {
5481 return (vm_offset_t)addr;
5482 }
5483
5484 if (zone_addr_size_crosses_page(addr, size)) {
5485 panic("invalid size for PGZ protected address %p:%p",
5486 (void *)addr, (void *)(addr + size));
5487 }
5488
5489 meta = zone_meta_from_addr((vm_offset_t)addr);
5490 if (meta->zm_chunk_len != ZM_PGZ_ALLOCATED) {
5491 panic_fault_address = (vm_offset_t)addr;
5492 panic("probabilistic gzalloc use-after-free: %p", (void *)addr);
5493 }
5494
5495 return trunc_page(meta->zm_pgz_orig_addr) + (addr & PAGE_MASK);
5496 }
5497
5498 __attribute__((always_inline))
5499 vm_offset_t
__pgz_decode_allow_invalid(vm_offset_t addr,zone_id_t zid)5500 __pgz_decode_allow_invalid(vm_offset_t addr, zone_id_t zid)
5501 {
5502 struct zone_page_metadata *meta;
5503 struct zone_page_metadata tmp;
5504
5505 if (__probable(!pgz_owned(addr))) {
5506 return addr;
5507 }
5508
5509 meta = zone_meta_from_addr(addr);
5510 tmp.zm_bits = os_atomic_load(&meta->zm_bits, relaxed);
5511
5512 addr = trunc_page(meta->zm_pgz_orig_addr) + (addr & PAGE_MASK);
5513
5514 if (tmp.zm_chunk_len != ZM_PGZ_ALLOCATED) {
5515 return 0;
5516 }
5517
5518 if (zid != ZONE_ID_ANY && tmp.zm_index != zid) {
5519 return 0;
5520 }
5521
5522 return addr;
5523 }
5524
5525 static void
pgz_zone_init(zone_t z)5526 pgz_zone_init(zone_t z)
5527 {
5528 char zn[MAX_ZONE_NAME];
5529 char zv[MAX_ZONE_NAME];
5530 char key[30];
5531
5532 if (zone_elem_inner_size(z) > PAGE_SIZE) {
5533 return;
5534 }
5535
5536 if (pgz_all) {
5537 os_atomic_inc(&pgz_uses, relaxed);
5538 z->z_pgz_tracked = true;
5539 return;
5540 }
5541
5542 snprintf(zn, sizeof(zn), "%s%s", zone_heap_name(z), zone_name(z));
5543
5544 for (int i = 1;; i++) {
5545 snprintf(key, sizeof(key), "pgz%d", i);
5546 if (!PE_parse_boot_argn(key, zv, sizeof(zv))) {
5547 break;
5548 }
5549 if (track_this_zone(zn, zv) || track_kalloc_zones(z, zv)) {
5550 os_atomic_inc(&pgz_uses, relaxed);
5551 z->z_pgz_tracked = true;
5552 break;
5553 }
5554 }
5555 }
5556
5557 __startup_func
5558 static vm_size_t
pgz_get_size(void)5559 pgz_get_size(void)
5560 {
5561 if (pgz_slots == UINT32_MAX) {
5562 /*
5563 * Scale with RAM size: ~200 slots a G
5564 */
5565 pgz_slots = (uint32_t)(sane_size >> 22);
5566 }
5567
5568 /*
5569 * Make sure that the slot allocation scheme works.
5570 * see pgz_slot_alloc() / pgz_slot_free();
5571 */
5572 if (pgz_slots < zpercpu_count() * 4) {
5573 pgz_slots = zpercpu_count() * 4;
5574 }
5575 if (pgz_slots >= UINT16_MAX) {
5576 pgz_slots = UINT16_MAX - 1;
5577 }
5578
5579 /*
5580 * Quarantine is 33% of slots by default, no more than 90%.
5581 */
5582 if (pgz_quarantine == 0) {
5583 pgz_quarantine = pgz_slots / 3;
5584 }
5585 if (pgz_quarantine > pgz_slots * 9 / 10) {
5586 pgz_quarantine = pgz_slots * 9 / 10;
5587 }
5588 pgz_slot_avail = pgz_slots - pgz_quarantine;
5589
5590 return ptoa(2 * pgz_slots + 1);
5591 }
5592
5593 __startup_func
5594 static void
pgz_init(void)5595 pgz_init(void)
5596 {
5597 if (!pgz_uses) {
5598 return;
5599 }
5600
5601 if (pgz_sample_rate == 0) {
5602 /*
5603 * If no rate was provided, pick a random one that scales
5604 * with the number of protected zones.
5605 *
5606 * Use a binomal distribution to avoid having too many
5607 * really fast sample rates.
5608 */
5609 uint32_t factor = MIN(pgz_uses, 10);
5610 uint32_t max_rate = 1000 * factor;
5611 uint32_t min_rate = 100 * factor;
5612
5613 pgz_sample_rate = (zalloc_random_uniform32(min_rate, max_rate) +
5614 zalloc_random_uniform32(min_rate, max_rate)) / 2;
5615 }
5616
5617 struct mach_vm_range *r = &zone_info.zi_pgz_range;
5618 zone_info.zi_pgz_meta = zone_meta_from_addr(r->min_address);
5619 zone_meta_populate(r->min_address, mach_vm_range_size(r));
5620
5621 for (size_t i = 0; i < 2 * pgz_slots + 1; i += 2) {
5622 zone_info.zi_pgz_meta[i].zm_chunk_len = ZM_PGZ_GUARD;
5623 }
5624
5625 for (size_t i = 1; i < pgz_slots; i++) {
5626 zone_info.zi_pgz_meta[2 * i - 1].zm_pgz_slot_next =
5627 &zone_info.zi_pgz_meta[2 * i + 1];
5628 }
5629 #if OS_ATOMIC_HAS_LLSC
5630 pgz_slot_head = &zone_info.zi_pgz_meta[1];
5631 #endif
5632 pgz_slot_tail = &zone_info.zi_pgz_meta[2 * pgz_slots - 1];
5633
5634 pgz_backtraces = zalloc_permanent(sizeof(struct pgz_backtrace) *
5635 2 * pgz_slots, ZALIGN_PTR);
5636
5637 /*
5638 * expand the pmap so that pmap_enter_options_addr()
5639 * in pgz_protect() never need to call pmap_expand().
5640 */
5641 for (uint32_t slot = 0; slot < pgz_slots; slot++) {
5642 (void)pmap_enter_options_addr(kernel_pmap, pgz_addr(slot), 0,
5643 VM_PROT_NONE, VM_PROT_NONE, 0, FALSE,
5644 PMAP_OPTIONS_NOENTER, NULL, PMAP_MAPPING_TYPE_INFER);
5645 }
5646
5647 /* do this last as this will enable pgz */
5648 percpu_foreach(counter, pgz_sample_counter) {
5649 *counter = zalloc_random_uniform32(0, 2 * pgz_sample_rate);
5650 }
5651 }
5652 STARTUP(EARLY_BOOT, STARTUP_RANK_MIDDLE, pgz_init);
5653
5654 static void
panic_display_pgz_bt(bool has_syms,uint32_t slot,bool free)5655 panic_display_pgz_bt(bool has_syms, uint32_t slot, bool free)
5656 {
5657 struct pgz_backtrace *bt = pgz_bt(slot, free);
5658 const char *what = free ? "Free" : "Allocation";
5659 uintptr_t buf[MAX_ZTRACE_DEPTH];
5660
5661 if (!ml_validate_nofault((vm_offset_t)bt, sizeof(*bt))) {
5662 paniclog_append_noflush(" Can't decode %s Backtrace\n", what);
5663 return;
5664 }
5665
5666 backtrace_unpack(BTP_KERN_OFFSET_32, buf, MAX_ZTRACE_DEPTH,
5667 (uint8_t *)bt->pgz_bt, 4 * bt->pgz_depth);
5668
5669 paniclog_append_noflush(" %s Backtrace:\n", what);
5670 for (uint32_t i = 0; i < bt->pgz_depth && i < MAX_ZTRACE_DEPTH; i++) {
5671 if (has_syms) {
5672 paniclog_append_noflush(" %p ", (void *)buf[i]);
5673 panic_print_symbol_name(buf[i]);
5674 paniclog_append_noflush("\n");
5675 } else {
5676 paniclog_append_noflush(" %p\n", (void *)buf[i]);
5677 }
5678 }
5679 kmod_panic_dump((vm_offset_t *)buf, bt->pgz_depth);
5680 }
5681
5682 static void
panic_display_pgz_uaf_info(bool has_syms,vm_offset_t addr)5683 panic_display_pgz_uaf_info(bool has_syms, vm_offset_t addr)
5684 {
5685 struct zone_page_metadata *meta;
5686 vm_offset_t elem, esize;
5687 const char *type;
5688 const char *prob;
5689 uint32_t slot;
5690 zone_t z;
5691
5692 slot = pgz_slot(addr);
5693 meta = pgz_meta(slot);
5694 elem = pgz_addr(slot) + (meta->zm_pgz_orig_addr & PAGE_MASK);
5695
5696 paniclog_append_noflush("Probabilistic GZAlloc Report:\n");
5697
5698 if (ml_validate_nofault((vm_offset_t)meta, sizeof(*meta)) &&
5699 meta->zm_index &&
5700 meta->zm_index < os_atomic_load(&num_zones, relaxed)) {
5701 z = &zone_array[meta->zm_index];
5702 } else {
5703 paniclog_append_noflush(" Zone : <unknown>\n");
5704 paniclog_append_noflush(" Address : %p\n", (void *)addr);
5705 paniclog_append_noflush("\n");
5706 return;
5707 }
5708
5709 esize = zone_elem_inner_size(z);
5710 paniclog_append_noflush(" Zone : %s%s\n",
5711 zone_heap_name(z), zone_name(z));
5712 paniclog_append_noflush(" Address : %p\n", (void *)addr);
5713 paniclog_append_noflush(" Element : [%p, %p) of size %d\n",
5714 (void *)elem, (void *)(elem + esize), (uint32_t)esize);
5715
5716 if (addr < elem) {
5717 type = "out-of-bounds(underflow) + use-after-free";
5718 prob = "low";
5719 } else if (meta->zm_chunk_len == ZM_PGZ_DOUBLE_FREE) {
5720 type = "double-free";
5721 prob = "high";
5722 } else if (addr < elem + esize) {
5723 type = "use-after-free";
5724 prob = "high";
5725 } else if (meta->zm_chunk_len != ZM_PGZ_ALLOCATED) {
5726 type = "out-of-bounds + use-after-free";
5727 prob = "low";
5728 } else {
5729 type = "out-of-bounds";
5730 prob = "high";
5731 }
5732 paniclog_append_noflush(" Kind : %s (%s confidence)\n",
5733 type, prob);
5734 if (addr < elem) {
5735 paniclog_append_noflush(" Access : %d byte(s) before\n",
5736 (uint32_t)(elem - addr) + 1);
5737 } else if (addr < elem + esize) {
5738 paniclog_append_noflush(" Access : %d byte(s) inside\n",
5739 (uint32_t)(addr - elem) + 1);
5740 } else {
5741 paniclog_append_noflush(" Access : %d byte(s) past\n",
5742 (uint32_t)(addr - (elem + esize)) + 1);
5743 }
5744
5745 panic_display_pgz_bt(has_syms, slot, false);
5746 if (meta->zm_chunk_len != ZM_PGZ_ALLOCATED) {
5747 panic_display_pgz_bt(has_syms, slot, true);
5748 }
5749
5750 paniclog_append_noflush("\n");
5751 }
5752
5753 vm_offset_t pgz_protect_for_testing_only(zone_t zone, vm_offset_t addr, void *fp);
5754 vm_offset_t
pgz_protect_for_testing_only(zone_t zone,vm_offset_t addr,void * fp)5755 pgz_protect_for_testing_only(zone_t zone, vm_offset_t addr, void *fp)
5756 {
5757 return pgz_protect(zone, addr, fp);
5758 }
5759
5760
5761 #endif /* CONFIG_PROB_GZALLOC */
5762 #endif /* !ZALLOC_TEST */
5763 #pragma mark zfree
5764 #if !ZALLOC_TEST
5765
5766 /*!
5767 * @defgroup zfree
5768 * @{
5769 *
5770 * @brief
5771 * The codepath for zone frees.
5772 *
5773 * @discussion
5774 * There are 4 major ways to allocate memory that end up in the zone allocator:
5775 * - @c zfree()
5776 * - @c zfree_percpu()
5777 * - @c kfree*()
5778 * - @c zfree_permanent()
5779 *
5780 * While permanent zones have their own allocation scheme, all other codepaths
5781 * will eventually go through the @c zfree_ext() choking point.
5782 */
5783
5784 __header_always_inline void
zfree_drop(zone_t zone,vm_offset_t addr)5785 zfree_drop(zone_t zone, vm_offset_t addr)
5786 {
5787 vm_offset_t esize = zone_elem_outer_size(zone);
5788 struct zone_page_metadata *meta;
5789 vm_offset_t eidx;
5790
5791 meta = zone_element_resolve(zone, addr, &eidx);
5792
5793 if (!zone_meta_mark_free(meta, eidx)) {
5794 zone_meta_double_free_panic(zone, addr, __func__);
5795 }
5796
5797 vm_offset_t old_size = meta->zm_alloc_size;
5798 vm_offset_t max_size = ptoa(meta->zm_chunk_len) + ZM_ALLOC_SIZE_LOCK;
5799 vm_offset_t new_size = zone_meta_alloc_size_sub(zone, meta, esize);
5800
5801 if (new_size == 0) {
5802 /* whether the page was on the intermediate or all_used, queue, move it to free */
5803 zone_meta_requeue(zone, &zone->z_pageq_empty, meta);
5804 zone->z_wired_empty += meta->zm_chunk_len;
5805 } else if (old_size + esize > max_size) {
5806 /* first free element on page, move from all_used */
5807 zone_meta_requeue(zone, &zone->z_pageq_partial, meta);
5808 }
5809
5810 if (__improbable(zone->z_exhausted_wait)) {
5811 zone_wakeup_exhausted_waiters(zone);
5812 }
5813 }
5814
5815 __attribute__((noinline))
5816 static void
zfree_item(zone_t zone,vm_offset_t addr)5817 zfree_item(zone_t zone, vm_offset_t addr)
5818 {
5819 /* transfer preemption count to lock */
5820 zone_lock_nopreempt_check_contention(zone);
5821
5822 zfree_drop(zone, addr);
5823 zone->z_elems_free += 1;
5824
5825 zone_unlock(zone);
5826 }
5827
5828 static void
zfree_cached_depot_recirculate(zone_t zone,uint32_t depot_max,zone_cache_t cache)5829 zfree_cached_depot_recirculate(
5830 zone_t zone,
5831 uint32_t depot_max,
5832 zone_cache_t cache)
5833 {
5834 smr_t smr = zone_cache_smr(cache);
5835 smr_seq_t seq;
5836 uint32_t n;
5837
5838 zone_recirc_lock_nopreempt_check_contention(zone);
5839
5840 n = cache->zc_depot.zd_full;
5841 if (n >= depot_max) {
5842 /*
5843 * If SMR is in use, rotate the entire chunk of magazines.
5844 *
5845 * If the head of the recirculation layer is ready to be
5846 * reused, pull them back to refill a little.
5847 */
5848 seq = zone_depot_move_full(&zone->z_recirc,
5849 &cache->zc_depot, smr ? n : n - depot_max / 2, NULL);
5850
5851 if (smr) {
5852 smr_deferred_advance_commit(smr, seq);
5853 if (depot_max > 1 && zone_depot_poll(&zone->z_recirc, smr)) {
5854 zone_depot_move_full(&cache->zc_depot,
5855 &zone->z_recirc, depot_max / 2, NULL);
5856 }
5857 }
5858 }
5859
5860 n = depot_max - cache->zc_depot.zd_full;
5861 if (n > zone->z_recirc.zd_empty) {
5862 n = zone->z_recirc.zd_empty;
5863 }
5864 if (n) {
5865 zone_depot_move_empty(&cache->zc_depot, &zone->z_recirc,
5866 n, zone);
5867 }
5868
5869 zone_recirc_unlock_nopreempt(zone);
5870 }
5871
5872 static zone_cache_t
zfree_cached_recirculate(zone_t zone,zone_cache_t cache)5873 zfree_cached_recirculate(zone_t zone, zone_cache_t cache)
5874 {
5875 zone_magazine_t mag = NULL, tmp = NULL;
5876 smr_t smr = zone_cache_smr(cache);
5877 bool wakeup_exhausted = false;
5878
5879 if (zone->z_recirc.zd_empty == 0) {
5880 mag = zone_magazine_alloc(Z_NOWAIT);
5881 }
5882
5883 zone_recirc_lock_nopreempt_check_contention(zone);
5884
5885 if (mag == NULL && zone->z_recirc.zd_empty) {
5886 mag = zone_depot_pop_head_empty(&zone->z_recirc, zone);
5887 __builtin_assume(mag);
5888 }
5889 if (mag) {
5890 tmp = zone_magazine_replace(cache, mag, true);
5891 if (smr) {
5892 smr_deferred_advance_commit(smr, tmp->zm_seq);
5893 }
5894 if (zone_security_array[zone_index(zone)].z_lifo) {
5895 zone_depot_insert_head_full(&zone->z_recirc, tmp);
5896 } else {
5897 zone_depot_insert_tail_full(&zone->z_recirc, tmp);
5898 }
5899
5900 wakeup_exhausted = zone->z_exhausted_wait;
5901 }
5902
5903 zone_recirc_unlock_nopreempt(zone);
5904
5905 if (__improbable(wakeup_exhausted)) {
5906 zone_lock_nopreempt(zone);
5907 if (zone->z_exhausted_wait) {
5908 zone_wakeup_exhausted_waiters(zone);
5909 }
5910 zone_unlock_nopreempt(zone);
5911 }
5912
5913 return mag ? cache : NULL;
5914 }
5915
5916 __attribute__((noinline))
5917 static zone_cache_t
zfree_cached_trim(zone_t zone,zone_cache_t cache)5918 zfree_cached_trim(zone_t zone, zone_cache_t cache)
5919 {
5920 zone_magazine_t mag = NULL, tmp = NULL;
5921 uint32_t depot_max;
5922
5923 depot_max = os_atomic_load(&zone->z_depot_size, relaxed);
5924 if (depot_max) {
5925 zone_depot_lock_nopreempt(cache);
5926
5927 if (cache->zc_depot.zd_empty == 0) {
5928 zfree_cached_depot_recirculate(zone, depot_max, cache);
5929 }
5930
5931 if (__probable(cache->zc_depot.zd_empty)) {
5932 mag = zone_depot_pop_head_empty(&cache->zc_depot, NULL);
5933 __builtin_assume(mag);
5934 } else {
5935 mag = zone_magazine_alloc(Z_NOWAIT);
5936 }
5937 if (mag) {
5938 tmp = zone_magazine_replace(cache, mag, true);
5939 zone_depot_insert_tail_full(&cache->zc_depot, tmp);
5940 }
5941
5942 zone_depot_unlock_nopreempt(cache);
5943
5944 return mag ? cache : NULL;
5945 }
5946
5947 return zfree_cached_recirculate(zone, cache);
5948 }
5949
5950 __attribute__((always_inline))
5951 static inline zone_cache_t
zfree_cached_get_pcpu_cache(zone_t zone,int cpu)5952 zfree_cached_get_pcpu_cache(zone_t zone, int cpu)
5953 {
5954 zone_cache_t cache = zpercpu_get_cpu(zone->z_pcpu_cache, cpu);
5955
5956 if (__probable(cache->zc_free_cur < zc_mag_size())) {
5957 return cache;
5958 }
5959
5960 if (__probable(cache->zc_alloc_cur < zc_mag_size())) {
5961 zone_cache_swap_magazines(cache);
5962 return cache;
5963 }
5964
5965 return zfree_cached_trim(zone, cache);
5966 }
5967
5968 __attribute__((always_inline))
5969 static inline zone_cache_t
zfree_cached_get_pcpu_cache_smr(zone_t zone,int cpu)5970 zfree_cached_get_pcpu_cache_smr(zone_t zone, int cpu)
5971 {
5972 zone_cache_t cache = zpercpu_get_cpu(zone->z_pcpu_cache, cpu);
5973 size_t idx = cache->zc_free_cur;
5974
5975 if (__probable(idx + 1 < zc_mag_size())) {
5976 return cache;
5977 }
5978
5979 /*
5980 * when SMR is in use, the bucket is tagged early with
5981 * @c smr_deferred_advance(), which costs a full barrier,
5982 * but performs no store.
5983 *
5984 * When zones hit the recirculation layer, the advance is commited,
5985 * under the recirculation lock (see zfree_cached_recirculate()).
5986 *
5987 * When done this way, the zone contention detection mechanism
5988 * will adjust the size of the per-cpu depots gracefully, which
5989 * mechanically reduces the pace of these commits as usage increases.
5990 */
5991
5992 if (__probable(idx + 1 == zc_mag_size())) {
5993 zone_magazine_t mag;
5994
5995 mag = (zone_magazine_t)((uintptr_t)cache->zc_free_elems -
5996 offsetof(struct zone_magazine, zm_elems));
5997 mag->zm_seq = smr_deferred_advance(zone_cache_smr(cache));
5998 return cache;
5999 }
6000
6001 return zfree_cached_trim(zone, cache);
6002 }
6003
6004 __attribute__((always_inline))
6005 static inline vm_offset_t
__zcache_mark_invalid(zone_t zone,vm_offset_t elem,uint64_t combined_size)6006 __zcache_mark_invalid(zone_t zone, vm_offset_t elem, uint64_t combined_size)
6007 {
6008 struct zone_page_metadata *meta;
6009 vm_offset_t offs;
6010
6011 #pragma unused(combined_size)
6012 #if CONFIG_PROB_GZALLOC
6013 if (__improbable(pgz_owned(elem))) {
6014 elem = pgz_unprotect(elem, __builtin_frame_address(0));
6015 }
6016 #endif /* CONFIG_PROB_GZALLOC */
6017
6018 meta = zone_meta_from_addr(elem);
6019 if (!from_zone_map(elem, 1) || !zone_has_index(zone, meta->zm_index)) {
6020 zone_invalid_element_panic(zone, elem);
6021 }
6022
6023 offs = (elem & PAGE_MASK) - zone_elem_inner_offs(zone);
6024 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
6025 offs += ptoa(meta->zm_page_index);
6026 }
6027
6028 if (!Z_FAST_ALIGNED(offs, zone->z_align_magic)) {
6029 zone_invalid_element_panic(zone, elem);
6030 }
6031
6032 #if VM_TAG_SIZECLASSES
6033 if (__improbable(zone->z_uses_tags)) {
6034 vm_tag_t *slot;
6035
6036 slot = zba_extra_ref_ptr(meta->zm_bitmap,
6037 Z_FAST_QUO(offs, zone->z_quo_magic));
6038 vm_tag_update_zone_size(*slot, zone->z_tags_sizeclass,
6039 -(long)ZFREE_ELEM_SIZE(combined_size));
6040 *slot = VM_KERN_MEMORY_NONE;
6041 }
6042 #endif /* VM_TAG_SIZECLASSES */
6043
6044 #if KASAN_CLASSIC
6045 kasan_free(elem, ZFREE_ELEM_SIZE(combined_size),
6046 ZFREE_USER_SIZE(combined_size), zone_elem_redzone(zone),
6047 zone->z_percpu, __builtin_frame_address(0));
6048 #endif
6049
6050 elem = zone_tag_free_element(zone, elem, ZFREE_ELEM_SIZE(combined_size));
6051 return elem;
6052 }
6053
6054 __attribute__((always_inline))
6055 void *
zcache_mark_invalid(zone_t zone,void * elem)6056 zcache_mark_invalid(zone_t zone, void *elem)
6057 {
6058 vm_size_t esize = zone_elem_inner_size(zone);
6059
6060 ZFREE_LOG(zone, (vm_offset_t)elem, 1);
6061 return (void *)__zcache_mark_invalid(zone, (vm_offset_t)elem, ZFREE_PACK_SIZE(esize, esize));
6062 }
6063
6064 /*
6065 * The function is noinline when zlog can be used so that the backtracing can
6066 * reliably skip the zfree_ext() and zfree_log()
6067 * boring frames.
6068 */
6069 #if ZALLOC_ENABLE_LOGGING
6070 __attribute__((noinline))
6071 #endif /* ZALLOC_ENABLE_LOGGING */
6072 void
zfree_ext(zone_t zone,zone_stats_t zstats,void * addr,uint64_t combined_size)6073 zfree_ext(zone_t zone, zone_stats_t zstats, void *addr, uint64_t combined_size)
6074 {
6075 vm_offset_t esize = ZFREE_ELEM_SIZE(combined_size);
6076 vm_offset_t elem = (vm_offset_t)addr;
6077 int cpu;
6078
6079 DTRACE_VM2(zfree, zone_t, zone, void*, elem);
6080
6081 ZFREE_LOG(zone, elem, 1);
6082 elem = __zcache_mark_invalid(zone, elem, combined_size);
6083
6084 disable_preemption();
6085 cpu = cpu_number();
6086 zpercpu_get_cpu(zstats, cpu)->zs_mem_freed += esize;
6087
6088 #if KASAN_CLASSIC
6089 if (zone->z_kasan_quarantine && startup_phase >= STARTUP_SUB_ZALLOC) {
6090 struct kasan_quarantine_result kqr;
6091
6092 kqr = kasan_quarantine(elem, esize);
6093 elem = kqr.addr;
6094 zone = kqr.zone;
6095 if (elem == 0) {
6096 return enable_preemption();
6097 }
6098 }
6099 #endif
6100
6101 if (zone->z_pcpu_cache) {
6102 zone_cache_t cache = zfree_cached_get_pcpu_cache(zone, cpu);
6103
6104 if (__probable(cache)) {
6105 cache->zc_free_elems[cache->zc_free_cur++] = elem;
6106 return enable_preemption();
6107 }
6108 }
6109
6110 return zfree_item(zone, elem);
6111 }
6112
6113 __attribute__((always_inline))
6114 static inline zstack_t
zcache_free_stack_to_cpu(zone_id_t zid,zone_cache_t cache,zstack_t stack,vm_size_t esize,zone_cache_ops_t ops,bool zero)6115 zcache_free_stack_to_cpu(
6116 zone_id_t zid,
6117 zone_cache_t cache,
6118 zstack_t stack,
6119 vm_size_t esize,
6120 zone_cache_ops_t ops,
6121 bool zero)
6122 {
6123 size_t n = MIN(zc_mag_size() - cache->zc_free_cur, stack.z_count);
6124 vm_offset_t *p;
6125
6126 stack.z_count -= n;
6127 cache->zc_free_cur += n;
6128 p = cache->zc_free_elems + cache->zc_free_cur;
6129
6130 do {
6131 void *o = zstack_pop_no_delta(&stack);
6132
6133 if (ops) {
6134 o = ops->zc_op_mark_invalid(zid, o);
6135 } else {
6136 if (zero) {
6137 bzero(o, esize);
6138 }
6139 o = (void *)__zcache_mark_invalid(zone_by_id(zid),
6140 (vm_offset_t)o, ZFREE_PACK_SIZE(esize, esize));
6141 }
6142 *--p = (vm_offset_t)o;
6143 } while (--n > 0);
6144
6145 return stack;
6146 }
6147
6148 __attribute__((always_inline))
6149 static inline void
zcache_free_1_ext(zone_id_t zid,void * addr,zone_cache_ops_t ops)6150 zcache_free_1_ext(zone_id_t zid, void *addr, zone_cache_ops_t ops)
6151 {
6152 vm_offset_t elem = (vm_offset_t)addr;
6153 zone_cache_t cache;
6154 vm_size_t esize;
6155 zone_t zone = zone_by_id(zid);
6156 int cpu;
6157
6158 ZFREE_LOG(zone, elem, 1);
6159
6160 disable_preemption();
6161 cpu = cpu_number();
6162 esize = zone_elem_inner_size(zone);
6163 zpercpu_get_cpu(zone->z_stats, cpu)->zs_mem_freed += esize;
6164 if (!ops) {
6165 addr = (void *)__zcache_mark_invalid(zone, elem,
6166 ZFREE_PACK_SIZE(esize, esize));
6167 }
6168 cache = zfree_cached_get_pcpu_cache(zone, cpu);
6169 if (__probable(cache)) {
6170 if (ops) {
6171 addr = ops->zc_op_mark_invalid(zid, addr);
6172 }
6173 cache->zc_free_elems[cache->zc_free_cur++] = elem;
6174 enable_preemption();
6175 } else if (ops) {
6176 enable_preemption();
6177 os_atomic_dec(&zone_by_id(zid)->z_elems_avail, relaxed);
6178 ops->zc_op_free(zid, addr);
6179 } else {
6180 zfree_item(zone, elem);
6181 }
6182 }
6183
6184 __attribute__((always_inline))
6185 static inline void
zcache_free_n_ext(zone_id_t zid,zstack_t stack,zone_cache_ops_t ops,bool zero)6186 zcache_free_n_ext(zone_id_t zid, zstack_t stack, zone_cache_ops_t ops, bool zero)
6187 {
6188 zone_t zone = zone_by_id(zid);
6189 zone_cache_t cache;
6190 vm_size_t esize;
6191 int cpu;
6192
6193 ZFREE_LOG(zone, stack.z_head, stack.z_count);
6194
6195 disable_preemption();
6196 cpu = cpu_number();
6197 esize = zone_elem_inner_size(zone);
6198 zpercpu_get_cpu(zone->z_stats, cpu)->zs_mem_freed +=
6199 stack.z_count * esize;
6200
6201 for (;;) {
6202 cache = zfree_cached_get_pcpu_cache(zone, cpu);
6203 if (__probable(cache)) {
6204 stack = zcache_free_stack_to_cpu(zid, cache,
6205 stack, esize, ops, zero);
6206 enable_preemption();
6207 } else if (ops) {
6208 enable_preemption();
6209 os_atomic_dec(&zone->z_elems_avail, relaxed);
6210 ops->zc_op_free(zid, zstack_pop(&stack));
6211 } else {
6212 vm_offset_t addr = (vm_offset_t)zstack_pop(&stack);
6213
6214 if (zero) {
6215 bzero((void *)addr, esize);
6216 }
6217 addr = __zcache_mark_invalid(zone, addr,
6218 ZFREE_PACK_SIZE(esize, esize));
6219 zfree_item(zone, addr);
6220 }
6221
6222 if (stack.z_count == 0) {
6223 break;
6224 }
6225
6226 disable_preemption();
6227 cpu = cpu_number();
6228 }
6229 }
6230
6231 void
6232 (zcache_free)(zone_id_t zid, void *addr, zone_cache_ops_t ops)
6233 {
6234 __builtin_assume(ops != NULL);
6235 zcache_free_1_ext(zid, addr, ops);
6236 }
6237
6238 void
6239 (zcache_free_n)(zone_id_t zid, zstack_t stack, zone_cache_ops_t ops)
6240 {
6241 __builtin_assume(ops != NULL);
6242 zcache_free_n_ext(zid, stack, ops, false);
6243 }
6244
6245 void
6246 (zfree_n)(zone_id_t zid, zstack_t stack)
6247 {
6248 zcache_free_n_ext(zid, stack, NULL, true);
6249 }
6250
6251 void
6252 (zfree_nozero)(zone_id_t zid, void *addr)
6253 {
6254 zcache_free_1_ext(zid, addr, NULL);
6255 }
6256
6257 void
6258 (zfree_nozero_n)(zone_id_t zid, zstack_t stack)
6259 {
6260 zcache_free_n_ext(zid, stack, NULL, false);
6261 }
6262
6263 void
6264 (zfree)(zone_t zov, void *addr)
6265 {
6266 zone_t zone = zov->z_self;
6267 zone_stats_t zstats = zov->z_stats;
6268 vm_offset_t esize = zone_elem_inner_size(zone);
6269
6270 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
6271 assert(!zone->z_percpu && !zone->z_permanent && !zone->z_smr);
6272 vm_memtag_bzero(addr, esize);
6273
6274 zfree_ext(zone, zstats, addr, ZFREE_PACK_SIZE(esize, esize));
6275 }
6276
6277 __attribute__((noinline))
6278 void
zfree_percpu(union zone_or_view zov,void * addr)6279 zfree_percpu(union zone_or_view zov, void *addr)
6280 {
6281 zone_t zone = zov.zov_view->zv_zone;
6282 zone_stats_t zstats = zov.zov_view->zv_stats;
6283 vm_offset_t esize = zone_elem_inner_size(zone);
6284
6285 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
6286 assert(zone->z_percpu);
6287 addr = (void *)__zpcpu_demangle(addr);
6288 zpercpu_foreach_cpu(i) {
6289 vm_memtag_bzero((char *)addr + ptoa(i), esize);
6290 }
6291 zfree_ext(zone, zstats, addr, ZFREE_PACK_SIZE(esize, esize));
6292 }
6293
6294 void
6295 (zfree_id)(zone_id_t zid, void *addr)
6296 {
6297 (zfree)(&zone_array[zid], addr);
6298 }
6299
6300 void
6301 (zfree_ro)(zone_id_t zid, void *addr)
6302 {
6303 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
6304 zone_t zone = zone_by_id(zid);
6305 zone_stats_t zstats = zone->z_stats;
6306 vm_offset_t esize = zone_ro_size_params[zid].z_elem_size;
6307
6308 #if ZSECURITY_CONFIG(READ_ONLY)
6309 assert(zone_security_array[zid].z_submap_idx == Z_SUBMAP_IDX_READ_ONLY);
6310 pmap_ro_zone_bzero(zid, (vm_offset_t)addr, 0, esize);
6311 #else
6312 (void)zid;
6313 bzero(addr, esize);
6314 #endif /* !KASAN_CLASSIC */
6315 zfree_ext(zone, zstats, addr, ZFREE_PACK_SIZE(esize, esize));
6316 }
6317
6318 __attribute__((noinline))
6319 static void
zfree_item_smr(zone_t zone,vm_offset_t addr)6320 zfree_item_smr(zone_t zone, vm_offset_t addr)
6321 {
6322 zone_cache_t cache = zpercpu_get_cpu(zone->z_pcpu_cache, 0);
6323 vm_size_t esize = zone_elem_inner_size(zone);
6324
6325 /*
6326 * This should be taken extremely rarely:
6327 * this happens if we failed allocating an empty bucket.
6328 */
6329 smr_synchronize(zone_cache_smr(cache));
6330
6331 cache->zc_free((void *)addr, esize);
6332 addr = __zcache_mark_invalid(zone, addr, ZFREE_PACK_SIZE(esize, esize));
6333
6334 zfree_item(zone, addr);
6335 }
6336
6337 void
6338 (zfree_smr)(zone_t zone, void *addr)
6339 {
6340 vm_offset_t elem = (vm_offset_t)addr;
6341 vm_offset_t esize;
6342 zone_cache_t cache;
6343 int cpu;
6344
6345 ZFREE_LOG(zone, elem, 1);
6346
6347 disable_preemption();
6348 cpu = cpu_number();
6349 #if MACH_ASSERT
6350 cache = zpercpu_get_cpu(zone->z_pcpu_cache, cpu);
6351 assert(!smr_entered_cpu_noblock(cache->zc_smr, cpu));
6352 #endif
6353 esize = zone_elem_inner_size(zone);
6354 zpercpu_get_cpu(zone->z_stats, cpu)->zs_mem_freed += esize;
6355 cache = zfree_cached_get_pcpu_cache_smr(zone, cpu);
6356 if (__probable(cache)) {
6357 cache->zc_free_elems[cache->zc_free_cur++] = elem;
6358 enable_preemption();
6359 } else {
6360 zfree_item_smr(zone, elem);
6361 }
6362 }
6363
6364 void
6365 (zfree_id_smr)(zone_id_t zid, void *addr)
6366 {
6367 (zfree_smr)(&zone_array[zid], addr);
6368 }
6369
6370 void
kfree_type_impl_internal(kalloc_type_view_t kt_view,void * ptr __unsafe_indexable)6371 kfree_type_impl_internal(
6372 kalloc_type_view_t kt_view,
6373 void *ptr __unsafe_indexable)
6374 {
6375 zone_t zsig = kt_view->kt_zsig;
6376 zone_t z = kt_view->kt_zv.zv_zone;
6377 struct zone_page_metadata *meta;
6378 zone_id_t zidx_meta;
6379 zone_security_flags_t zsflags_meta;
6380 zone_security_flags_t zsflags_z = zone_security_config(z);
6381 zone_security_flags_t zsflags_zsig;
6382
6383 if (NULL == ptr) {
6384 return;
6385 }
6386
6387 meta = zone_meta_from_addr((vm_offset_t) ptr);
6388 zidx_meta = meta->zm_index;
6389 zsflags_meta = zone_security_array[zidx_meta];
6390
6391 if ((zsflags_z.z_kheap_id == KHEAP_ID_DATA_BUFFERS) ||
6392 zone_has_index(z, zidx_meta)) {
6393 return (zfree)(&kt_view->kt_zv, ptr);
6394 }
6395 zsflags_zsig = zone_security_config(zsig);
6396 if (zsflags_meta.z_sig_eq == zsflags_zsig.z_sig_eq) {
6397 z = zone_array + zidx_meta;
6398 return (zfree)(z, ptr);
6399 }
6400
6401 return (zfree)(kt_view->kt_zshared, ptr);
6402 }
6403
6404 /*! @} */
6405 #endif /* !ZALLOC_TEST */
6406 #pragma mark zalloc
6407 #if !ZALLOC_TEST
6408
6409 /*!
6410 * @defgroup zalloc
6411 * @{
6412 *
6413 * @brief
6414 * The codepath for zone allocations.
6415 *
6416 * @discussion
6417 * There are 4 major ways to allocate memory that end up in the zone allocator:
6418 * - @c zalloc(), @c zalloc_flags(), ...
6419 * - @c zalloc_percpu()
6420 * - @c kalloc*()
6421 * - @c zalloc_permanent()
6422 *
6423 * While permanent zones have their own allocation scheme, all other codepaths
6424 * will eventually go through the @c zalloc_ext() choking point.
6425 *
6426 * @c zalloc_return() is the final function everyone tail calls into,
6427 * which prepares the element for consumption by the caller and deals with
6428 * common treatment (zone logging, tags, kasan, validation, ...).
6429 */
6430
6431 /*!
6432 * @function zalloc_import
6433 *
6434 * @brief
6435 * Import @c n elements in the specified array, opposite of @c zfree_drop().
6436 *
6437 * @param zone The zone to import elements from
6438 * @param elems The array to import into
6439 * @param n The number of elements to import. Must be non zero,
6440 * and smaller than @c zone->z_elems_free.
6441 */
6442 __header_always_inline vm_size_t
zalloc_import(zone_t zone,vm_offset_t * elems,zalloc_flags_t flags,uint32_t n)6443 zalloc_import(
6444 zone_t zone,
6445 vm_offset_t *elems,
6446 zalloc_flags_t flags,
6447 uint32_t n)
6448 {
6449 vm_offset_t esize = zone_elem_outer_size(zone);
6450 vm_offset_t offs = zone_elem_inner_offs(zone);
6451 zone_stats_t zs;
6452 int cpu = cpu_number();
6453 uint32_t i = 0;
6454
6455 zs = zpercpu_get_cpu(zone->z_stats, cpu);
6456
6457 if (__improbable(zone_caching_disabled < 0)) {
6458 /*
6459 * In the first 10s after boot, mess with
6460 * the scan position in order to make early
6461 * allocations patterns less predictable.
6462 */
6463 zone_early_scramble_rr(zone, cpu, zs);
6464 }
6465
6466 do {
6467 vm_offset_t page, eidx, size = 0;
6468 struct zone_page_metadata *meta;
6469
6470 if (!zone_pva_is_null(zone->z_pageq_partial)) {
6471 meta = zone_pva_to_meta(zone->z_pageq_partial);
6472 page = zone_pva_to_addr(zone->z_pageq_partial);
6473 } else if (!zone_pva_is_null(zone->z_pageq_empty)) {
6474 meta = zone_pva_to_meta(zone->z_pageq_empty);
6475 page = zone_pva_to_addr(zone->z_pageq_empty);
6476 zone_counter_sub(zone, z_wired_empty, meta->zm_chunk_len);
6477 } else {
6478 zone_accounting_panic(zone, "z_elems_free corruption");
6479 }
6480
6481 zone_meta_validate(zone, meta, page);
6482
6483 vm_offset_t old_size = meta->zm_alloc_size;
6484 vm_offset_t max_size = ptoa(meta->zm_chunk_len) + ZM_ALLOC_SIZE_LOCK;
6485
6486 do {
6487 eidx = zone_meta_find_and_clear_bit(zone, zs, meta, flags);
6488 elems[i++] = page + offs + eidx * esize;
6489 size += esize;
6490 } while (i < n && old_size + size + esize <= max_size);
6491
6492 vm_offset_t new_size = zone_meta_alloc_size_add(zone, meta, size);
6493
6494 if (new_size + esize > max_size) {
6495 zone_meta_requeue(zone, &zone->z_pageq_full, meta);
6496 } else if (old_size == 0) {
6497 /* remove from free, move to intermediate */
6498 zone_meta_requeue(zone, &zone->z_pageq_partial, meta);
6499 }
6500 } while (i < n);
6501
6502 n = zone_counter_sub(zone, z_elems_free, n);
6503 if (zone->z_pcpu_cache == NULL && zone->z_elems_free_min > n) {
6504 zone->z_elems_free_min = n;
6505 }
6506
6507 return zone_elem_inner_size(zone);
6508 }
6509
6510 __attribute__((always_inline))
6511 static inline vm_offset_t
__zcache_mark_valid(zone_t zone,vm_offset_t addr,zalloc_flags_t flags)6512 __zcache_mark_valid(zone_t zone, vm_offset_t addr, zalloc_flags_t flags)
6513 {
6514 #pragma unused(zone, flags)
6515 #if KASAN_CLASSIC || CONFIG_PROB_GZALLOC || VM_TAG_SIZECLASSES
6516 vm_offset_t esize = zone_elem_inner_size(zone);
6517 #endif
6518
6519 addr = vm_memtag_fixup_ptr(addr);
6520
6521 #if VM_TAG_SIZECLASSES
6522 if (__improbable(zone->z_uses_tags)) {
6523 struct zone_page_metadata *meta;
6524 vm_offset_t offs;
6525 vm_tag_t *slot;
6526 vm_tag_t tag;
6527
6528 tag = zalloc_flags_get_tag(flags);
6529 meta = zone_meta_from_addr(addr);
6530 offs = (addr & PAGE_MASK) - zone_elem_inner_offs(zone);
6531 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
6532 offs += ptoa(meta->zm_page_index);
6533 }
6534
6535 slot = zba_extra_ref_ptr(meta->zm_bitmap,
6536 Z_FAST_QUO(offs, zone->z_quo_magic));
6537 *slot = tag;
6538
6539 vm_tag_update_zone_size(tag, zone->z_tags_sizeclass,
6540 (long)esize);
6541 }
6542 #endif /* VM_TAG_SIZECLASSES */
6543
6544 #if CONFIG_PROB_GZALLOC
6545 if (zone->z_pgz_tracked && pgz_sample(addr, esize)) {
6546 addr = pgz_protect(zone, addr, __builtin_frame_address(0));
6547 }
6548 #endif
6549
6550 #if KASAN_CLASSIC
6551 /*
6552 * KASAN_CLASSIC integration of kalloc heaps are handled by kalloc_ext()
6553 */
6554 if ((flags & Z_SKIP_KASAN) == 0) {
6555 kasan_alloc(addr, esize, esize, zone_elem_redzone(zone),
6556 (flags & Z_PCPU), __builtin_frame_address(0));
6557 }
6558 #endif /* KASAN_CLASSIC */
6559
6560 return addr;
6561 }
6562
6563 __attribute__((always_inline))
6564 void *
zcache_mark_valid(zone_t zone,void * addr)6565 zcache_mark_valid(zone_t zone, void *addr)
6566 {
6567 addr = (void *)__zcache_mark_valid(zone, (vm_offset_t)addr, 0);
6568 ZALLOC_LOG(zone, (vm_offset_t)addr, 1);
6569 return addr;
6570 }
6571
6572 /*!
6573 * @function zalloc_return
6574 *
6575 * @brief
6576 * Performs the tail-end of the work required on allocations before the caller
6577 * uses them.
6578 *
6579 * @discussion
6580 * This function is called without any zone lock held,
6581 * and preemption back to the state it had when @c zalloc_ext() was called.
6582 *
6583 * @param zone The zone we're allocating from.
6584 * @param addr The element we just allocated.
6585 * @param flags The flags passed to @c zalloc_ext() (for Z_ZERO).
6586 * @param elem_size The element size for this zone.
6587 */
6588 __attribute__((always_inline))
6589 static struct kalloc_result
zalloc_return(zone_t zone,vm_offset_t addr,zalloc_flags_t flags,vm_offset_t elem_size)6590 zalloc_return(
6591 zone_t zone,
6592 vm_offset_t addr,
6593 zalloc_flags_t flags,
6594 vm_offset_t elem_size)
6595 {
6596 addr = __zcache_mark_valid(zone, addr, flags);
6597 #if ZALLOC_ENABLE_ZERO_CHECK
6598 zalloc_validate_element(zone, addr, elem_size, flags);
6599 #endif /* ZALLOC_ENABLE_ZERO_CHECK */
6600 ZALLOC_LOG(zone, addr, 1);
6601
6602 DTRACE_VM2(zalloc, zone_t, zone, void*, addr);
6603 return (struct kalloc_result){ (void *)addr, elem_size };
6604 }
6605
6606 static vm_size_t
zalloc_get_shared_threshold(zone_t zone,vm_size_t esize)6607 zalloc_get_shared_threshold(zone_t zone, vm_size_t esize)
6608 {
6609 if (esize <= 512) {
6610 return zone_early_thres_mul * page_size / 4;
6611 } else if (esize < 2048) {
6612 return zone_early_thres_mul * esize * 8;
6613 }
6614 return zone_early_thres_mul * zone->z_chunk_elems * esize;
6615 }
6616
6617 __attribute__((noinline))
6618 static struct kalloc_result
zalloc_item(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags)6619 zalloc_item(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags)
6620 {
6621 vm_offset_t esize, addr;
6622 zone_stats_t zs;
6623
6624 zone_lock_nopreempt_check_contention(zone);
6625
6626 zs = zpercpu_get(zstats);
6627 if (__improbable(zone->z_elems_free <= zone->z_elems_rsv / 2)) {
6628 if ((flags & Z_NOWAIT) || zone->z_elems_free) {
6629 zone_expand_async_schedule_if_allowed(zone);
6630 } else {
6631 zone_expand_locked(zone, flags);
6632 }
6633 if (__improbable(zone->z_elems_free == 0)) {
6634 zs->zs_alloc_fail++;
6635 zone_unlock(zone);
6636 if (__improbable(flags & Z_NOFAIL)) {
6637 zone_nofail_panic(zone);
6638 }
6639 DTRACE_VM2(zalloc, zone_t, zone, void*, NULL);
6640 return (struct kalloc_result){ };
6641 }
6642 }
6643
6644 esize = zalloc_import(zone, &addr, flags, 1);
6645 zs->zs_mem_allocated += esize;
6646
6647 if (__improbable(!zone_share_always &&
6648 !os_atomic_load(&zs->zs_alloc_not_shared, relaxed))) {
6649 if (flags & Z_SET_NOTSHARED) {
6650 vm_size_t shared_threshold = zalloc_get_shared_threshold(zone, esize);
6651
6652 if (zs->zs_mem_allocated >= shared_threshold) {
6653 zpercpu_foreach(zs_cpu, zstats) {
6654 os_atomic_store(&zs_cpu->zs_alloc_not_shared, 1, relaxed);
6655 }
6656 }
6657 }
6658 }
6659 zone_unlock(zone);
6660
6661 return zalloc_return(zone, addr, flags, esize);
6662 }
6663
6664 static void
zalloc_cached_import(zone_t zone,zalloc_flags_t flags,zone_cache_t cache)6665 zalloc_cached_import(
6666 zone_t zone,
6667 zalloc_flags_t flags,
6668 zone_cache_t cache)
6669 {
6670 uint16_t n_elems = zc_mag_size();
6671
6672 zone_lock_nopreempt(zone);
6673
6674 if (__probable(!zone_caching_disabled &&
6675 zone->z_elems_free > zone->z_elems_rsv / 2)) {
6676 if (__improbable(zone->z_elems_free <= zone->z_elems_rsv)) {
6677 zone_expand_async_schedule_if_allowed(zone);
6678 }
6679 if (zone->z_elems_free < n_elems) {
6680 n_elems = (uint16_t)zone->z_elems_free;
6681 }
6682 zalloc_import(zone, cache->zc_alloc_elems, flags, n_elems);
6683 cache->zc_alloc_cur = n_elems;
6684 }
6685
6686 zone_unlock_nopreempt(zone);
6687 }
6688
6689 static void
zalloc_cached_depot_recirculate(zone_t zone,uint32_t depot_max,zone_cache_t cache,smr_t smr)6690 zalloc_cached_depot_recirculate(
6691 zone_t zone,
6692 uint32_t depot_max,
6693 zone_cache_t cache,
6694 smr_t smr)
6695 {
6696 smr_seq_t seq;
6697 uint32_t n;
6698
6699 zone_recirc_lock_nopreempt_check_contention(zone);
6700
6701 n = cache->zc_depot.zd_empty;
6702 if (n >= depot_max) {
6703 zone_depot_move_empty(&zone->z_recirc, &cache->zc_depot,
6704 n - depot_max / 2, NULL);
6705 }
6706
6707 n = cache->zc_depot.zd_full;
6708 if (smr && n) {
6709 /*
6710 * if SMR is in use, it means smr_poll() failed,
6711 * so rotate the entire chunk of magazines in order
6712 * to let the sequence numbers age.
6713 */
6714 seq = zone_depot_move_full(&zone->z_recirc, &cache->zc_depot,
6715 n, NULL);
6716 smr_deferred_advance_commit(smr, seq);
6717 }
6718
6719 n = depot_max - cache->zc_depot.zd_empty;
6720 if (n > zone->z_recirc.zd_full) {
6721 n = zone->z_recirc.zd_full;
6722 }
6723
6724 if (n && zone_depot_poll(&zone->z_recirc, smr)) {
6725 zone_depot_move_full(&cache->zc_depot, &zone->z_recirc,
6726 n, zone);
6727 }
6728
6729 zone_recirc_unlock_nopreempt(zone);
6730 }
6731
6732 static void
zalloc_cached_reuse_smr(zone_t z,zone_cache_t cache,zone_magazine_t mag)6733 zalloc_cached_reuse_smr(zone_t z, zone_cache_t cache, zone_magazine_t mag)
6734 {
6735 zone_smr_free_cb_t zc_free = cache->zc_free;
6736 vm_size_t esize = zone_elem_inner_size(z);
6737
6738 for (uint16_t i = 0; i < zc_mag_size(); i++) {
6739 vm_offset_t elem = mag->zm_elems[i];
6740
6741 zc_free((void *)elem, zone_elem_inner_size(z));
6742 elem = __zcache_mark_invalid(z, elem,
6743 ZFREE_PACK_SIZE(esize, esize));
6744 mag->zm_elems[i] = elem;
6745 }
6746 }
6747
6748 static void
zalloc_cached_recirculate(zone_t zone,zone_cache_t cache)6749 zalloc_cached_recirculate(
6750 zone_t zone,
6751 zone_cache_t cache)
6752 {
6753 zone_magazine_t mag = NULL;
6754
6755 zone_recirc_lock_nopreempt_check_contention(zone);
6756
6757 if (zone_depot_poll(&zone->z_recirc, zone_cache_smr(cache))) {
6758 mag = zone_depot_pop_head_full(&zone->z_recirc, zone);
6759 if (zone_cache_smr(cache)) {
6760 zalloc_cached_reuse_smr(zone, cache, mag);
6761 }
6762 mag = zone_magazine_replace(cache, mag, false);
6763 zone_depot_insert_head_empty(&zone->z_recirc, mag);
6764 }
6765
6766 zone_recirc_unlock_nopreempt(zone);
6767 }
6768
6769 __attribute__((noinline))
6770 static zone_cache_t
zalloc_cached_prime(zone_t zone,zone_cache_ops_t ops,zalloc_flags_t flags,zone_cache_t cache)6771 zalloc_cached_prime(
6772 zone_t zone,
6773 zone_cache_ops_t ops,
6774 zalloc_flags_t flags,
6775 zone_cache_t cache)
6776 {
6777 zone_magazine_t mag = NULL;
6778 uint32_t depot_max;
6779 smr_t smr;
6780
6781 depot_max = os_atomic_load(&zone->z_depot_size, relaxed);
6782 if (depot_max) {
6783 smr = zone_cache_smr(cache);
6784
6785 zone_depot_lock_nopreempt(cache);
6786
6787 if (!zone_depot_poll(&cache->zc_depot, smr)) {
6788 zalloc_cached_depot_recirculate(zone, depot_max, cache,
6789 smr);
6790 }
6791
6792 if (__probable(cache->zc_depot.zd_full)) {
6793 mag = zone_depot_pop_head_full(&cache->zc_depot, NULL);
6794 if (zone_cache_smr(cache)) {
6795 zalloc_cached_reuse_smr(zone, cache, mag);
6796 }
6797 mag = zone_magazine_replace(cache, mag, false);
6798 zone_depot_insert_head_empty(&cache->zc_depot, mag);
6799 }
6800
6801 zone_depot_unlock_nopreempt(cache);
6802 } else if (zone->z_recirc.zd_full) {
6803 zalloc_cached_recirculate(zone, cache);
6804 }
6805
6806 if (__probable(cache->zc_alloc_cur)) {
6807 return cache;
6808 }
6809
6810 if (ops == NULL) {
6811 zalloc_cached_import(zone, flags, cache);
6812 if (__probable(cache->zc_alloc_cur)) {
6813 return cache;
6814 }
6815 }
6816
6817 return NULL;
6818 }
6819
6820 __attribute__((always_inline))
6821 static inline zone_cache_t
zalloc_cached_get_pcpu_cache(zone_t zone,zone_cache_ops_t ops,int cpu,zalloc_flags_t flags)6822 zalloc_cached_get_pcpu_cache(
6823 zone_t zone,
6824 zone_cache_ops_t ops,
6825 int cpu,
6826 zalloc_flags_t flags)
6827 {
6828 zone_cache_t cache = zpercpu_get_cpu(zone->z_pcpu_cache, cpu);
6829
6830 if (__probable(cache->zc_alloc_cur != 0)) {
6831 return cache;
6832 }
6833
6834 if (__probable(cache->zc_free_cur != 0 && !cache->zc_smr)) {
6835 zone_cache_swap_magazines(cache);
6836 return cache;
6837 }
6838
6839 return zalloc_cached_prime(zone, ops, flags, cache);
6840 }
6841
6842
6843 /*!
6844 * @function zalloc_ext
6845 *
6846 * @brief
6847 * The core implementation of @c zalloc(), @c zalloc_flags(), @c zalloc_percpu().
6848 */
6849 struct kalloc_result
zalloc_ext(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags)6850 zalloc_ext(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags)
6851 {
6852 /*
6853 * KASan uses zalloc() for fakestack, which can be called anywhere.
6854 * However, we make sure these calls can never block.
6855 */
6856 assertf(startup_phase < STARTUP_SUB_EARLY_BOOT ||
6857 #if KASAN_FAKESTACK
6858 zone->z_kasan_fakestacks ||
6859 #endif /* KASAN_FAKESTACK */
6860 ml_get_interrupts_enabled() ||
6861 ml_is_quiescing() ||
6862 debug_mode_active(),
6863 "Calling {k,z}alloc from interrupt disabled context isn't allowed");
6864
6865 /*
6866 * Make sure Z_NOFAIL was not obviously misused
6867 */
6868 if (flags & Z_NOFAIL) {
6869 assert((flags & (Z_NOWAIT | Z_NOPAGEWAIT)) == 0);
6870 }
6871
6872 #if VM_TAG_SIZECLASSES
6873 if (__improbable(zone->z_uses_tags)) {
6874 vm_tag_t tag = zalloc_flags_get_tag(flags);
6875
6876 if (flags & Z_VM_TAG_BT_BIT) {
6877 tag = vm_tag_bt() ?: tag;
6878 }
6879 if (tag != VM_KERN_MEMORY_NONE) {
6880 tag = vm_tag_will_update_zone(tag,
6881 flags & (Z_WAITOK | Z_NOWAIT | Z_NOPAGEWAIT));
6882 }
6883 if (tag == VM_KERN_MEMORY_NONE) {
6884 zone_security_flags_t zsflags = zone_security_config(zone);
6885
6886 if (zsflags.z_kheap_id == KHEAP_ID_DATA_BUFFERS) {
6887 tag = VM_KERN_MEMORY_KALLOC_DATA;
6888 } else if (zsflags.z_kheap_id == KHEAP_ID_KT_VAR ||
6889 zsflags.z_kalloc_type) {
6890 tag = VM_KERN_MEMORY_KALLOC_TYPE;
6891 } else {
6892 tag = VM_KERN_MEMORY_KALLOC;
6893 }
6894 }
6895 flags = Z_VM_TAG(flags & ~Z_VM_TAG_MASK, tag);
6896 }
6897 #endif /* VM_TAG_SIZECLASSES */
6898
6899 disable_preemption();
6900
6901 #if ZALLOC_ENABLE_ZERO_CHECK
6902 if (zalloc_skip_zero_check()) {
6903 flags |= Z_NOZZC;
6904 }
6905 #endif
6906
6907 if (zone->z_pcpu_cache) {
6908 zone_cache_t cache;
6909 vm_offset_t index, addr, esize;
6910 int cpu = cpu_number();
6911
6912 cache = zalloc_cached_get_pcpu_cache(zone, NULL, cpu, flags);
6913 if (__probable(cache)) {
6914 esize = zone_elem_inner_size(zone);
6915 zpercpu_get_cpu(zstats, cpu)->zs_mem_allocated += esize;
6916 index = --cache->zc_alloc_cur;
6917 addr = cache->zc_alloc_elems[index];
6918 cache->zc_alloc_elems[index] = 0;
6919 enable_preemption();
6920 return zalloc_return(zone, addr, flags, esize);
6921 }
6922 }
6923
6924 __attribute__((musttail))
6925 return zalloc_item(zone, zstats, flags);
6926 }
6927
6928 __attribute__((always_inline))
6929 static inline zstack_t
zcache_alloc_stack_from_cpu(zone_id_t zid,zone_cache_t cache,zstack_t stack,uint32_t n,zone_cache_ops_t ops)6930 zcache_alloc_stack_from_cpu(
6931 zone_id_t zid,
6932 zone_cache_t cache,
6933 zstack_t stack,
6934 uint32_t n,
6935 zone_cache_ops_t ops)
6936 {
6937 vm_offset_t *p;
6938
6939 n = MIN(n, cache->zc_alloc_cur);
6940 p = cache->zc_alloc_elems + cache->zc_alloc_cur;
6941 cache->zc_alloc_cur -= n;
6942 stack.z_count += n;
6943
6944 do {
6945 vm_offset_t e = *--p;
6946
6947 *p = 0;
6948 if (ops) {
6949 e = (vm_offset_t)ops->zc_op_mark_valid(zid, (void *)e);
6950 } else {
6951 e = __zcache_mark_valid(zone_by_id(zid), e, 0);
6952 }
6953 zstack_push_no_delta(&stack, (void *)e);
6954 } while (--n > 0);
6955
6956 return stack;
6957 }
6958
6959 __attribute__((noinline))
6960 static zstack_t
zcache_alloc_fail(zone_id_t zid,zstack_t stack,uint32_t count)6961 zcache_alloc_fail(zone_id_t zid, zstack_t stack, uint32_t count)
6962 {
6963 zone_t zone = zone_by_id(zid);
6964 zone_stats_t zstats = zone->z_stats;
6965 int cpu;
6966
6967 count -= stack.z_count;
6968
6969 disable_preemption();
6970 cpu = cpu_number();
6971 zpercpu_get_cpu(zstats, cpu)->zs_mem_allocated -=
6972 count * zone_elem_inner_size(zone);
6973 zpercpu_get_cpu(zstats, cpu)->zs_alloc_fail += 1;
6974 enable_preemption();
6975
6976 return stack;
6977 }
6978
6979 #define ZCACHE_ALLOC_RETRY ((void *)-1)
6980
6981 __attribute__((noinline))
6982 static void *
zcache_alloc_one(zone_id_t zid,zalloc_flags_t flags,zone_cache_ops_t ops)6983 zcache_alloc_one(
6984 zone_id_t zid,
6985 zalloc_flags_t flags,
6986 zone_cache_ops_t ops)
6987 {
6988 zone_t zone = zone_by_id(zid);
6989 void *o;
6990
6991 /*
6992 * First try to allocate in rudimentary zones without ever going into
6993 * __ZONE_EXHAUSTED_AND_WAITING_HARD__() by clearing Z_NOFAIL.
6994 */
6995 enable_preemption();
6996 o = ops->zc_op_alloc(zid, flags & ~Z_NOFAIL);
6997 if (__probable(o)) {
6998 os_atomic_inc(&zone->z_elems_avail, relaxed);
6999 } else if (__probable(flags & Z_NOFAIL)) {
7000 zone_cache_t cache;
7001 vm_offset_t index;
7002 int cpu;
7003
7004 zone_lock(zone);
7005
7006 cpu = cpu_number();
7007 cache = zalloc_cached_get_pcpu_cache(zone, ops, cpu, flags);
7008 o = ZCACHE_ALLOC_RETRY;
7009 if (__probable(cache)) {
7010 index = --cache->zc_alloc_cur;
7011 o = (void *)cache->zc_alloc_elems[index];
7012 cache->zc_alloc_elems[index] = 0;
7013 o = ops->zc_op_mark_valid(zid, o);
7014 } else if (zone->z_elems_free == 0) {
7015 __ZONE_EXHAUSTED_AND_WAITING_HARD__(zone);
7016 }
7017
7018 zone_unlock(zone);
7019 }
7020
7021 return o;
7022 }
7023
7024 __attribute__((always_inline))
7025 static zstack_t
zcache_alloc_n_ext(zone_id_t zid,uint32_t count,zalloc_flags_t flags,zone_cache_ops_t ops)7026 zcache_alloc_n_ext(
7027 zone_id_t zid,
7028 uint32_t count,
7029 zalloc_flags_t flags,
7030 zone_cache_ops_t ops)
7031 {
7032 zstack_t stack = { };
7033 zone_cache_t cache;
7034 zone_t zone;
7035 int cpu;
7036
7037 disable_preemption();
7038 cpu = cpu_number();
7039 zone = zone_by_id(zid);
7040 zpercpu_get_cpu(zone->z_stats, cpu)->zs_mem_allocated +=
7041 count * zone_elem_inner_size(zone);
7042
7043 for (;;) {
7044 cache = zalloc_cached_get_pcpu_cache(zone, ops, cpu, flags);
7045 if (__probable(cache)) {
7046 stack = zcache_alloc_stack_from_cpu(zid, cache, stack,
7047 count - stack.z_count, ops);
7048 enable_preemption();
7049 } else {
7050 void *o;
7051
7052 if (ops) {
7053 o = zcache_alloc_one(zid, flags, ops);
7054 } else {
7055 o = zalloc_item(zone, zone->z_stats, flags).addr;
7056 }
7057 if (__improbable(o == NULL)) {
7058 return zcache_alloc_fail(zid, stack, count);
7059 }
7060 if (ops == NULL || o != ZCACHE_ALLOC_RETRY) {
7061 zstack_push(&stack, o);
7062 }
7063 }
7064
7065 if (stack.z_count == count) {
7066 break;
7067 }
7068
7069 disable_preemption();
7070 cpu = cpu_number();
7071 }
7072
7073 ZALLOC_LOG(zone, stack.z_head, stack.z_count);
7074
7075 return stack;
7076 }
7077
7078 zstack_t
zalloc_n(zone_id_t zid,uint32_t count,zalloc_flags_t flags)7079 zalloc_n(zone_id_t zid, uint32_t count, zalloc_flags_t flags)
7080 {
7081 return zcache_alloc_n_ext(zid, count, flags, NULL);
7082 }
7083
zstack_t(zcache_alloc_n)7084 zstack_t
7085 (zcache_alloc_n)(
7086 zone_id_t zid,
7087 uint32_t count,
7088 zalloc_flags_t flags,
7089 zone_cache_ops_t ops)
7090 {
7091 __builtin_assume(ops != NULL);
7092 return zcache_alloc_n_ext(zid, count, flags, ops);
7093 }
7094
7095 __attribute__((always_inline))
7096 void *
zalloc(zone_t zov)7097 zalloc(zone_t zov)
7098 {
7099 return zalloc_flags(zov, Z_WAITOK);
7100 }
7101
7102 __attribute__((always_inline))
7103 void *
zalloc_noblock(zone_t zov)7104 zalloc_noblock(zone_t zov)
7105 {
7106 return zalloc_flags(zov, Z_NOWAIT);
7107 }
7108
7109 void *
7110 (zalloc_flags)(zone_t zov, zalloc_flags_t flags)
7111 {
7112 zone_t zone = zov->z_self;
7113 zone_stats_t zstats = zov->z_stats;
7114
7115 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
7116 assert(!zone->z_percpu && !zone->z_permanent);
7117 return zalloc_ext(zone, zstats, flags).addr;
7118 }
7119
7120 __attribute__((always_inline))
7121 void *
7122 (zalloc_id)(zone_id_t zid, zalloc_flags_t flags)
7123 {
7124 return (zalloc_flags)(zone_by_id(zid), flags);
7125 }
7126
7127 void *
7128 (zalloc_ro)(zone_id_t zid, zalloc_flags_t flags)
7129 {
7130 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
7131 zone_t zone = zone_by_id(zid);
7132 zone_stats_t zstats = zone->z_stats;
7133 struct kalloc_result kr;
7134
7135 kr = zalloc_ext(zone, zstats, flags);
7136 #if ZSECURITY_CONFIG(READ_ONLY)
7137 assert(zone_security_array[zid].z_submap_idx == Z_SUBMAP_IDX_READ_ONLY);
7138 if (kr.addr) {
7139 zone_require_ro(zid, kr.size, kr.addr);
7140 }
7141 #endif
7142 return kr.addr;
7143 }
7144
7145 #if ZSECURITY_CONFIG(READ_ONLY)
7146
7147 __attribute__((always_inline))
7148 static bool
from_current_stack(vm_offset_t addr,vm_size_t size)7149 from_current_stack(vm_offset_t addr, vm_size_t size)
7150 {
7151 vm_offset_t start = (vm_offset_t)__builtin_frame_address(0);
7152 vm_offset_t end = (start + kernel_stack_size - 1) & -kernel_stack_size;
7153
7154 addr = vm_memtag_canonicalize_address(addr);
7155
7156 return (addr >= start) && (addr + size < end);
7157 }
7158
7159 /*
7160 * Check if an address is from const memory i.e TEXT or DATA CONST segements
7161 * or the SECURITY_READ_ONLY_LATE section.
7162 */
7163 #if defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR)
7164 __attribute__((always_inline))
7165 static bool
from_const_memory(const vm_offset_t addr,vm_size_t size)7166 from_const_memory(const vm_offset_t addr, vm_size_t size)
7167 {
7168 return rorgn_contains(addr, size, true);
7169 }
7170 #else /* defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR) */
7171 __attribute__((always_inline))
7172 static bool
from_const_memory(const vm_offset_t addr,vm_size_t size)7173 from_const_memory(const vm_offset_t addr, vm_size_t size)
7174 {
7175 #pragma unused(addr, size)
7176 return true;
7177 }
7178 #endif /* defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR) */
7179
7180 __abortlike
7181 static void
zalloc_ro_mut_validation_panic(zone_id_t zid,void * elem,const vm_offset_t src,vm_size_t src_size)7182 zalloc_ro_mut_validation_panic(zone_id_t zid, void *elem,
7183 const vm_offset_t src, vm_size_t src_size)
7184 {
7185 vm_offset_t stack_start = (vm_offset_t)__builtin_frame_address(0);
7186 vm_offset_t stack_end = (stack_start + kernel_stack_size - 1) & -kernel_stack_size;
7187 #if defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR)
7188 extern vm_offset_t rorgn_begin;
7189 extern vm_offset_t rorgn_end;
7190 #else
7191 vm_offset_t const rorgn_begin = 0;
7192 vm_offset_t const rorgn_end = 0;
7193 #endif
7194
7195 if (from_ro_map(src, src_size)) {
7196 zone_t src_zone = &zone_array[zone_index_from_ptr((void *)src)];
7197 zone_t dst_zone = &zone_array[zid];
7198 panic("zalloc_ro_mut failed: source (%p) not from same zone as dst (%p)"
7199 " (expected: %s, actual: %s", (void *)src, elem, src_zone->z_name,
7200 dst_zone->z_name);
7201 }
7202
7203 panic("zalloc_ro_mut failed: source (%p, phys %p) not from RO zone map (%p - %p), "
7204 "current stack (%p - %p) or const memory (phys %p - %p)",
7205 (void *)src, (void*)kvtophys(src),
7206 (void *)zone_info.zi_ro_range.min_address,
7207 (void *)zone_info.zi_ro_range.max_address,
7208 (void *)stack_start, (void *)stack_end,
7209 (void *)rorgn_begin, (void *)rorgn_end);
7210 }
7211
7212 __attribute__((always_inline))
7213 static void
zalloc_ro_mut_validate_src(zone_id_t zid,void * elem,const vm_offset_t src,vm_size_t src_size)7214 zalloc_ro_mut_validate_src(zone_id_t zid, void *elem,
7215 const vm_offset_t src, vm_size_t src_size)
7216 {
7217 if (from_current_stack(src, src_size) ||
7218 (from_ro_map(src, src_size) &&
7219 zid == zone_index_from_ptr((void *)src)) ||
7220 from_const_memory(src, src_size)) {
7221 return;
7222 }
7223 zalloc_ro_mut_validation_panic(zid, elem, src, src_size);
7224 }
7225
7226 #endif /* ZSECURITY_CONFIG(READ_ONLY) */
7227
7228 __attribute__((noinline))
7229 void
zalloc_ro_mut(zone_id_t zid,void * elem,vm_offset_t offset,const void * new_data,vm_size_t new_data_size)7230 zalloc_ro_mut(zone_id_t zid, void *elem, vm_offset_t offset,
7231 const void *new_data, vm_size_t new_data_size)
7232 {
7233 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
7234
7235 #if ZSECURITY_CONFIG(READ_ONLY)
7236 bool skip_src_check = false;
7237
7238 /*
7239 * The OSEntitlements RO-zone is a little differently treated. For more
7240 * information: rdar://100518485.
7241 */
7242 if (zid == ZONE_ID_AMFI_OSENTITLEMENTS) {
7243 code_signing_config_t cs_config = 0;
7244
7245 code_signing_configuration(NULL, &cs_config);
7246 if (cs_config & CS_CONFIG_CSM_ENABLED) {
7247 skip_src_check = true;
7248 }
7249 }
7250
7251 if (skip_src_check == false) {
7252 zalloc_ro_mut_validate_src(zid, elem, (vm_offset_t)new_data,
7253 new_data_size);
7254 }
7255 pmap_ro_zone_memcpy(zid, (vm_offset_t) elem, offset,
7256 (vm_offset_t) new_data, new_data_size);
7257 #else
7258 (void)zid;
7259 memcpy((void *)((uintptr_t)elem + offset), new_data, new_data_size);
7260 #endif
7261 }
7262
7263 __attribute__((noinline))
7264 uint64_t
zalloc_ro_mut_atomic(zone_id_t zid,void * elem,vm_offset_t offset,zro_atomic_op_t op,uint64_t value)7265 zalloc_ro_mut_atomic(zone_id_t zid, void *elem, vm_offset_t offset,
7266 zro_atomic_op_t op, uint64_t value)
7267 {
7268 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
7269
7270 #if ZSECURITY_CONFIG(READ_ONLY)
7271 value = pmap_ro_zone_atomic_op(zid, (vm_offset_t)elem, offset, op, value);
7272 #else
7273 (void)zid;
7274 value = __zalloc_ro_mut_atomic((vm_offset_t)elem + offset, op, value);
7275 #endif
7276 return value;
7277 }
7278
7279 void
zalloc_ro_clear(zone_id_t zid,void * elem,vm_offset_t offset,vm_size_t size)7280 zalloc_ro_clear(zone_id_t zid, void *elem, vm_offset_t offset, vm_size_t size)
7281 {
7282 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
7283 #if ZSECURITY_CONFIG(READ_ONLY)
7284 pmap_ro_zone_bzero(zid, (vm_offset_t)elem, offset, size);
7285 #else
7286 (void)zid;
7287 bzero((void *)((uintptr_t)elem + offset), size);
7288 #endif
7289 }
7290
7291 /*
7292 * This function will run in the PPL and needs to be robust
7293 * against an attacker with arbitrary kernel write.
7294 */
7295
7296 #if ZSECURITY_CONFIG(READ_ONLY)
7297
7298 __abortlike
7299 static void
zone_id_require_ro_panic(zone_id_t zid,void * addr)7300 zone_id_require_ro_panic(zone_id_t zid, void *addr)
7301 {
7302 struct zone_size_params p = zone_ro_size_params[zid];
7303 vm_offset_t elem = (vm_offset_t)addr;
7304 uint32_t zindex;
7305 zone_t other;
7306 zone_t zone = &zone_array[zid];
7307
7308 if (!from_ro_map(addr, 1)) {
7309 panic("zone_require_ro failed: address not in a ro zone (addr: %p)", addr);
7310 }
7311
7312 if (!Z_FAST_ALIGNED(PAGE_SIZE - (elem & PAGE_MASK), p.z_align_magic)) {
7313 panic("zone_require_ro failed: element improperly aligned (addr: %p)", addr);
7314 }
7315
7316 zindex = zone_index_from_ptr(addr);
7317 other = &zone_array[zindex];
7318 if (zindex >= os_atomic_load(&num_zones, relaxed) || !other->z_self) {
7319 panic("zone_require_ro failed: invalid zone index %d "
7320 "(addr: %p, expected: %s%s)", zindex,
7321 addr, zone_heap_name(zone), zone->z_name);
7322 } else {
7323 panic("zone_require_ro failed: address in unexpected zone id %d (%s%s) "
7324 "(addr: %p, expected: %s%s)",
7325 zindex, zone_heap_name(other), other->z_name,
7326 addr, zone_heap_name(zone), zone->z_name);
7327 }
7328 }
7329
7330 #endif /* ZSECURITY_CONFIG(READ_ONLY) */
7331
7332 __attribute__((always_inline))
7333 void
zone_require_ro(zone_id_t zid,vm_size_t elem_size __unused,void * addr)7334 zone_require_ro(zone_id_t zid, vm_size_t elem_size __unused, void *addr)
7335 {
7336 #if ZSECURITY_CONFIG(READ_ONLY)
7337 struct zone_size_params p = zone_ro_size_params[zid];
7338 vm_offset_t elem = (vm_offset_t)addr;
7339
7340 if (!from_ro_map(addr, 1) ||
7341 !Z_FAST_ALIGNED(PAGE_SIZE - (elem & PAGE_MASK), p.z_align_magic) ||
7342 zid != zone_meta_from_addr(elem)->zm_index) {
7343 zone_id_require_ro_panic(zid, addr);
7344 }
7345 #else
7346 #pragma unused(zid, addr)
7347 #endif
7348 }
7349
7350 void *
7351 (zalloc_percpu)(union zone_or_view zov, zalloc_flags_t flags)
7352 {
7353 zone_t zone = zov.zov_view->zv_zone;
7354 zone_stats_t zstats = zov.zov_view->zv_stats;
7355
7356 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
7357 assert(zone->z_percpu);
7358 flags |= Z_PCPU;
7359 return (void *)__zpcpu_mangle(zalloc_ext(zone, zstats, flags).addr);
7360 }
7361
7362 static void *
_zalloc_permanent(zone_t zone,vm_size_t size,vm_offset_t mask)7363 _zalloc_permanent(zone_t zone, vm_size_t size, vm_offset_t mask)
7364 {
7365 struct zone_page_metadata *page_meta;
7366 vm_offset_t offs, addr;
7367 zone_pva_t pva;
7368
7369 assert(ml_get_interrupts_enabled() ||
7370 ml_is_quiescing() ||
7371 debug_mode_active() ||
7372 startup_phase < STARTUP_SUB_EARLY_BOOT);
7373
7374 size = (size + mask) & ~mask;
7375 assert(size <= PAGE_SIZE);
7376
7377 zone_lock(zone);
7378 assert(zone->z_self == zone);
7379
7380 for (;;) {
7381 pva = zone->z_pageq_partial;
7382 while (!zone_pva_is_null(pva)) {
7383 page_meta = zone_pva_to_meta(pva);
7384 if (page_meta->zm_bump + size <= PAGE_SIZE) {
7385 goto found;
7386 }
7387 pva = page_meta->zm_page_next;
7388 }
7389
7390 zone_expand_locked(zone, Z_WAITOK);
7391 }
7392
7393 found:
7394 offs = (uint16_t)((page_meta->zm_bump + mask) & ~mask);
7395 page_meta->zm_bump = (uint16_t)(offs + size);
7396 page_meta->zm_alloc_size += size;
7397 zone->z_elems_free -= size;
7398 zpercpu_get(zone->z_stats)->zs_mem_allocated += size;
7399
7400 if (page_meta->zm_alloc_size >= PAGE_SIZE - sizeof(vm_offset_t)) {
7401 zone_meta_requeue(zone, &zone->z_pageq_full, page_meta);
7402 }
7403
7404 zone_unlock(zone);
7405
7406 if (zone->z_tbi_tag) {
7407 addr = vm_memtag_fixup_ptr(offs + zone_pva_to_addr(pva));
7408 } else {
7409 addr = offs + zone_pva_to_addr(pva);
7410 }
7411
7412 DTRACE_VM2(zalloc, zone_t, zone, void*, addr);
7413 return (void *)addr;
7414 }
7415
7416 static void *
_zalloc_permanent_large(size_t size,vm_offset_t mask,vm_tag_t tag)7417 _zalloc_permanent_large(size_t size, vm_offset_t mask, vm_tag_t tag)
7418 {
7419 vm_offset_t addr;
7420
7421 kernel_memory_allocate(kernel_map, &addr, size, mask,
7422 KMA_NOFAIL | KMA_KOBJECT | KMA_PERMANENT | KMA_ZERO, tag);
7423
7424 return (void *)addr;
7425 }
7426
7427 void *
zalloc_permanent_tag(vm_size_t size,vm_offset_t mask,vm_tag_t tag)7428 zalloc_permanent_tag(vm_size_t size, vm_offset_t mask, vm_tag_t tag)
7429 {
7430 if (size <= PAGE_SIZE) {
7431 zone_t zone = &zone_array[ZONE_ID_PERMANENT];
7432 return _zalloc_permanent(zone, size, mask);
7433 }
7434 return _zalloc_permanent_large(size, mask, tag);
7435 }
7436
7437 void *
zalloc_percpu_permanent(vm_size_t size,vm_offset_t mask)7438 zalloc_percpu_permanent(vm_size_t size, vm_offset_t mask)
7439 {
7440 zone_t zone = &zone_array[ZONE_ID_PERCPU_PERMANENT];
7441 return (void *)__zpcpu_mangle(_zalloc_permanent(zone, size, mask));
7442 }
7443
7444 /*! @} */
7445 #endif /* !ZALLOC_TEST */
7446 #pragma mark zone GC / trimming
7447 #if !ZALLOC_TEST
7448
7449 static thread_call_data_t zone_trim_callout;
7450 EVENT_DEFINE(ZONE_EXHAUSTED);
7451
7452 static void
zone_reclaim_chunk(zone_t z,struct zone_page_metadata * meta,uint32_t free_count)7453 zone_reclaim_chunk(
7454 zone_t z,
7455 struct zone_page_metadata *meta,
7456 uint32_t free_count)
7457 {
7458 vm_address_t page_addr;
7459 vm_size_t size_to_free;
7460 uint32_t bitmap_ref;
7461 uint32_t page_count;
7462 zone_security_flags_t zsflags = zone_security_config(z);
7463 bool sequester = !z->z_destroyed;
7464 bool oob_guard = false;
7465
7466 if (zone_submap_is_sequestered(zsflags)) {
7467 /*
7468 * If the entire map is sequestered, we can't return the VA.
7469 * It stays pinned to the zone forever.
7470 */
7471 sequester = true;
7472 }
7473
7474 zone_meta_queue_pop(z, &z->z_pageq_empty);
7475
7476 page_addr = zone_meta_to_addr(meta);
7477 page_count = meta->zm_chunk_len;
7478 oob_guard = meta->zm_guarded;
7479
7480 if (meta->zm_alloc_size) {
7481 zone_metadata_corruption(z, meta, "alloc_size");
7482 }
7483 if (z->z_percpu) {
7484 if (page_count != 1) {
7485 zone_metadata_corruption(z, meta, "page_count");
7486 }
7487 size_to_free = ptoa(z->z_chunk_pages);
7488 zone_remove_wired_pages(z, z->z_chunk_pages);
7489 } else {
7490 if (page_count > z->z_chunk_pages) {
7491 zone_metadata_corruption(z, meta, "page_count");
7492 }
7493 if (page_count < z->z_chunk_pages) {
7494 /* Dequeue non populated VA from z_pageq_va */
7495 zone_meta_remqueue(z, meta + page_count);
7496 }
7497 size_to_free = ptoa(page_count);
7498 zone_remove_wired_pages(z, page_count);
7499 }
7500
7501 zone_counter_sub(z, z_elems_free, free_count);
7502 zone_counter_sub(z, z_elems_avail, free_count);
7503 zone_counter_sub(z, z_wired_empty, page_count);
7504 zone_counter_sub(z, z_wired_cur, page_count);
7505
7506 if (z->z_pcpu_cache == NULL) {
7507 if (z->z_elems_free_min < free_count) {
7508 z->z_elems_free_min = 0;
7509 } else {
7510 z->z_elems_free_min -= free_count;
7511 }
7512 }
7513 if (z->z_elems_free_wma < free_count) {
7514 z->z_elems_free_wma = 0;
7515 } else {
7516 z->z_elems_free_wma -= free_count;
7517 }
7518
7519 bitmap_ref = 0;
7520 if (sequester) {
7521 if (meta->zm_inline_bitmap) {
7522 for (int i = 0; i < meta->zm_chunk_len; i++) {
7523 meta[i].zm_bitmap = 0;
7524 }
7525 } else {
7526 bitmap_ref = meta->zm_bitmap;
7527 meta->zm_bitmap = 0;
7528 }
7529 meta->zm_chunk_len = 0;
7530 } else {
7531 if (!meta->zm_inline_bitmap) {
7532 bitmap_ref = meta->zm_bitmap;
7533 }
7534 zone_counter_sub(z, z_va_cur, z->z_percpu ? 1 : z->z_chunk_pages);
7535 bzero(meta, sizeof(*meta) * (z->z_chunk_pages + oob_guard));
7536 }
7537
7538 #if CONFIG_ZLEAKS
7539 if (__improbable(zleak_should_disable_for_zone(z) &&
7540 startup_phase >= STARTUP_SUB_THREAD_CALL)) {
7541 thread_call_enter(&zone_leaks_callout);
7542 }
7543 #endif /* CONFIG_ZLEAKS */
7544
7545 zone_unlock(z);
7546
7547 if (bitmap_ref) {
7548 zone_bits_free(bitmap_ref);
7549 }
7550
7551 /* Free the pages for metadata and account for them */
7552 #if KASAN_CLASSIC
7553 if (z->z_percpu) {
7554 for (uint32_t i = 0; i < z->z_chunk_pages; i++) {
7555 kasan_zmem_remove(page_addr + ptoa(i), PAGE_SIZE,
7556 zone_elem_outer_size(z),
7557 zone_elem_outer_offs(z),
7558 zone_elem_redzone(z));
7559 }
7560 } else {
7561 kasan_zmem_remove(page_addr, size_to_free,
7562 zone_elem_outer_size(z),
7563 zone_elem_outer_offs(z),
7564 zone_elem_redzone(z));
7565 }
7566 #endif /* KASAN_CLASSIC */
7567
7568 if (sequester) {
7569 kma_flags_t flags = zone_kma_flags(z, zsflags, 0) | KMA_KOBJECT;
7570 kernel_memory_depopulate(page_addr, size_to_free,
7571 flags, VM_KERN_MEMORY_ZONE);
7572 } else {
7573 assert(zsflags.z_submap_idx != Z_SUBMAP_IDX_VM);
7574 kmem_free(zone_submap(zsflags), page_addr,
7575 ptoa(z->z_chunk_pages + oob_guard));
7576 if (oob_guard) {
7577 os_atomic_dec(&zone_guard_pages, relaxed);
7578 }
7579 }
7580
7581 thread_yield_to_preemption();
7582
7583 zone_lock(z);
7584
7585 if (sequester) {
7586 zone_meta_queue_push(z, &z->z_pageq_va, meta);
7587 }
7588 }
7589
7590 static void
zone_reclaim_elements(zone_t z,uint16_t n,vm_offset_t * elems)7591 zone_reclaim_elements(zone_t z, uint16_t n, vm_offset_t *elems)
7592 {
7593 z_debug_assert(n <= zc_mag_size());
7594
7595 for (uint16_t i = 0; i < n; i++) {
7596 vm_offset_t addr = elems[i];
7597 elems[i] = 0;
7598 zfree_drop(z, addr);
7599 }
7600
7601 z->z_elems_free += n;
7602 }
7603
7604 static void
zcache_reclaim_elements(zone_id_t zid,uint16_t n,vm_offset_t * elems)7605 zcache_reclaim_elements(zone_id_t zid, uint16_t n, vm_offset_t *elems)
7606 {
7607 z_debug_assert(n <= zc_mag_size());
7608 zone_cache_ops_t ops = zcache_ops[zid];
7609
7610 for (uint16_t i = 0; i < n; i++) {
7611 vm_offset_t addr = elems[i];
7612 elems[i] = 0;
7613 addr = (vm_offset_t)ops->zc_op_mark_valid(zid, (void *)addr);
7614 ops->zc_op_free(zid, (void *)addr);
7615 }
7616
7617 os_atomic_sub(&zone_by_id(zid)->z_elems_avail, n, relaxed);
7618 }
7619
7620 static void
zone_depot_trim(zone_t z,uint32_t target,struct zone_depot * zd)7621 zone_depot_trim(zone_t z, uint32_t target, struct zone_depot *zd)
7622 {
7623 zpercpu_foreach(zc, z->z_pcpu_cache) {
7624 zone_depot_lock(zc);
7625
7626 if (zc->zc_depot.zd_full > (target + 1) / 2) {
7627 uint32_t n = zc->zc_depot.zd_full - (target + 1) / 2;
7628 zone_depot_move_full(zd, &zc->zc_depot, n, NULL);
7629 }
7630
7631 if (zc->zc_depot.zd_empty > target / 2) {
7632 uint32_t n = zc->zc_depot.zd_empty - target / 2;
7633 zone_depot_move_empty(zd, &zc->zc_depot, n, NULL);
7634 }
7635
7636 zone_depot_unlock(zc);
7637 }
7638 }
7639
7640 __enum_decl(zone_reclaim_mode_t, uint32_t, {
7641 ZONE_RECLAIM_TRIM,
7642 ZONE_RECLAIM_DRAIN,
7643 ZONE_RECLAIM_DESTROY,
7644 });
7645
7646 static void
zone_reclaim_pcpu(zone_t z,zone_reclaim_mode_t mode,struct zone_depot * zd)7647 zone_reclaim_pcpu(zone_t z, zone_reclaim_mode_t mode, struct zone_depot *zd)
7648 {
7649 uint32_t depot_max = 0;
7650 bool cleanup = mode != ZONE_RECLAIM_TRIM;
7651
7652 if (z->z_depot_cleanup) {
7653 z->z_depot_cleanup = false;
7654 depot_max = z->z_depot_size;
7655 cleanup = true;
7656 }
7657
7658 if (cleanup) {
7659 zone_depot_trim(z, depot_max, zd);
7660 }
7661
7662 if (mode == ZONE_RECLAIM_DESTROY) {
7663 zpercpu_foreach(zc, z->z_pcpu_cache) {
7664 zone_reclaim_elements(z, zc->zc_alloc_cur,
7665 zc->zc_alloc_elems);
7666 zone_reclaim_elements(z, zc->zc_free_cur,
7667 zc->zc_free_elems);
7668 zc->zc_alloc_cur = zc->zc_free_cur = 0;
7669 }
7670
7671 z->z_recirc_empty_min = 0;
7672 z->z_recirc_empty_wma = 0;
7673 z->z_recirc_full_min = 0;
7674 z->z_recirc_full_wma = 0;
7675 z->z_recirc_cont_cur = 0;
7676 z->z_recirc_cont_wma = 0;
7677 }
7678 }
7679
7680 static void
zone_reclaim_recirc_drain(zone_t z,struct zone_depot * zd)7681 zone_reclaim_recirc_drain(zone_t z, struct zone_depot *zd)
7682 {
7683 assert(zd->zd_empty == 0);
7684 assert(zd->zd_full == 0);
7685
7686 zone_recirc_lock_nopreempt(z);
7687
7688 *zd = z->z_recirc;
7689 if (zd->zd_full == 0) {
7690 zd->zd_tail = &zd->zd_head;
7691 }
7692 zone_depot_init(&z->z_recirc);
7693 z->z_recirc_empty_min = 0;
7694 z->z_recirc_empty_wma = 0;
7695 z->z_recirc_full_min = 0;
7696 z->z_recirc_full_wma = 0;
7697
7698 zone_recirc_unlock_nopreempt(z);
7699 }
7700
7701 static void
zone_reclaim_recirc_trim(zone_t z,struct zone_depot * zd)7702 zone_reclaim_recirc_trim(zone_t z, struct zone_depot *zd)
7703 {
7704 for (;;) {
7705 uint32_t budget = zc_free_batch_size();
7706 uint32_t count;
7707 bool done = true;
7708
7709 zone_recirc_lock_nopreempt(z);
7710 count = MIN(z->z_recirc_empty_wma / Z_WMA_UNIT,
7711 z->z_recirc_empty_min);
7712 assert(count <= z->z_recirc.zd_empty);
7713
7714 if (count > budget) {
7715 count = budget;
7716 done = false;
7717 }
7718 if (count) {
7719 budget -= count;
7720 zone_depot_move_empty(zd, &z->z_recirc, count, NULL);
7721 z->z_recirc_empty_min -= count;
7722 z->z_recirc_empty_wma -= count * Z_WMA_UNIT;
7723 }
7724
7725 count = MIN(z->z_recirc_full_wma / Z_WMA_UNIT,
7726 z->z_recirc_full_min);
7727 assert(count <= z->z_recirc.zd_full);
7728
7729 if (count > budget) {
7730 count = budget;
7731 done = false;
7732 }
7733 if (count) {
7734 zone_depot_move_full(zd, &z->z_recirc, count, NULL);
7735 z->z_recirc_full_min -= count;
7736 z->z_recirc_full_wma -= count * Z_WMA_UNIT;
7737 }
7738
7739 zone_recirc_unlock_nopreempt(z);
7740
7741 if (done) {
7742 return;
7743 }
7744
7745 /*
7746 * If the number of magazines to reclaim is too large,
7747 * we might be keeping preemption disabled for too long.
7748 *
7749 * Drop and retake the lock to allow for preemption to occur.
7750 */
7751 zone_unlock(z);
7752 zone_lock(z);
7753 }
7754 }
7755
7756 /*!
7757 * @function zone_reclaim
7758 *
7759 * @brief
7760 * Drains or trim the zone.
7761 *
7762 * @discussion
7763 * Draining the zone will free it from all its elements.
7764 *
7765 * Trimming the zone tries to respect the working set size, and avoids draining
7766 * the depot when it's not necessary.
7767 *
7768 * @param z The zone to reclaim from
7769 * @param mode The purpose of this reclaim.
7770 */
7771 static void
zone_reclaim(zone_t z,zone_reclaim_mode_t mode)7772 zone_reclaim(zone_t z, zone_reclaim_mode_t mode)
7773 {
7774 struct zone_depot zd;
7775
7776 zone_depot_init(&zd);
7777
7778 zone_lock(z);
7779
7780 if (mode == ZONE_RECLAIM_DESTROY) {
7781 if (!z->z_destructible || z->z_elems_rsv) {
7782 panic("zdestroy: Zone %s%s isn't destructible",
7783 zone_heap_name(z), z->z_name);
7784 }
7785
7786 if (!z->z_self || z->z_expander ||
7787 z->z_async_refilling || z->z_expanding_wait) {
7788 panic("zdestroy: Zone %s%s in an invalid state for destruction",
7789 zone_heap_name(z), z->z_name);
7790 }
7791
7792 #if !KASAN_CLASSIC
7793 /*
7794 * Unset the valid bit. We'll hit an assert failure on further
7795 * operations on this zone, until zinit() is called again.
7796 *
7797 * Leave the zone valid for KASan as we will see zfree's on
7798 * quarantined free elements even after the zone is destroyed.
7799 */
7800 z->z_self = NULL;
7801 #endif
7802 z->z_destroyed = true;
7803 } else if (z->z_destroyed) {
7804 return zone_unlock(z);
7805 } else if (zone_count_free(z) <= z->z_elems_rsv) {
7806 /* If the zone is under its reserve level, leave it alone. */
7807 return zone_unlock(z);
7808 }
7809
7810 if (z->z_pcpu_cache) {
7811 zone_magazine_t mag;
7812 uint32_t freed = 0;
7813
7814 /*
7815 * This is all done with the zone lock held on purpose.
7816 * The work here is O(ncpu), which should still be short.
7817 *
7818 * We need to keep the lock held until we have reclaimed
7819 * at least a few magazines, otherwise if the zone has no
7820 * free elements outside of the depot, a thread performing
7821 * a concurrent allocatiuon could try to grow the zone
7822 * while we're trying to drain it.
7823 */
7824 if (mode == ZONE_RECLAIM_TRIM) {
7825 zone_reclaim_recirc_trim(z, &zd);
7826 } else {
7827 zone_reclaim_recirc_drain(z, &zd);
7828 }
7829 zone_reclaim_pcpu(z, mode, &zd);
7830
7831 if (z->z_chunk_elems) {
7832 zone_cache_t cache = zpercpu_get_cpu(z->z_pcpu_cache, 0);
7833 smr_t smr = zone_cache_smr(cache);
7834
7835 while (zd.zd_full) {
7836 mag = zone_depot_pop_head_full(&zd, NULL);
7837 if (smr) {
7838 smr_wait(smr, mag->zm_seq);
7839 zalloc_cached_reuse_smr(z, cache, mag);
7840 freed += zc_mag_size();
7841 }
7842 zone_reclaim_elements(z, zc_mag_size(),
7843 mag->zm_elems);
7844 zone_depot_insert_head_empty(&zd, mag);
7845
7846 freed += zc_mag_size();
7847 if (freed >= zc_free_batch_size()) {
7848 zone_unlock(z);
7849 zone_magazine_free_list(&zd);
7850 thread_yield_to_preemption();
7851 zone_lock(z);
7852 freed = 0;
7853 }
7854 }
7855 } else {
7856 zone_id_t zid = zone_index(z);
7857
7858 zone_unlock(z);
7859
7860 assert(zid <= ZONE_ID__FIRST_DYNAMIC && zcache_ops[zid]);
7861
7862 while (zd.zd_full) {
7863 mag = zone_depot_pop_head_full(&zd, NULL);
7864 zcache_reclaim_elements(zid, zc_mag_size(),
7865 mag->zm_elems);
7866 zone_magazine_free(mag);
7867 }
7868
7869 goto cleanup;
7870 }
7871 }
7872
7873 while (!zone_pva_is_null(z->z_pageq_empty)) {
7874 struct zone_page_metadata *meta;
7875 uint32_t count, limit = z->z_elems_rsv * 5 / 4;
7876
7877 if (mode == ZONE_RECLAIM_TRIM && z->z_pcpu_cache == NULL) {
7878 limit = MAX(limit, z->z_elems_free -
7879 MIN(z->z_elems_free_min, z->z_elems_free_wma));
7880 }
7881
7882 meta = zone_pva_to_meta(z->z_pageq_empty);
7883 count = (uint32_t)ptoa(meta->zm_chunk_len) / zone_elem_outer_size(z);
7884
7885 if (zone_count_free(z) - count < limit) {
7886 break;
7887 }
7888
7889 zone_reclaim_chunk(z, meta, count);
7890 }
7891
7892 zone_unlock(z);
7893
7894 cleanup:
7895 zone_magazine_free_list(&zd);
7896 }
7897
7898 void
zone_drain(zone_t zone)7899 zone_drain(zone_t zone)
7900 {
7901 current_thread()->options |= TH_OPT_ZONE_PRIV;
7902 lck_mtx_lock(&zone_gc_lock);
7903 zone_reclaim(zone, ZONE_RECLAIM_DRAIN);
7904 lck_mtx_unlock(&zone_gc_lock);
7905 current_thread()->options &= ~TH_OPT_ZONE_PRIV;
7906 }
7907
7908 void
zcache_drain(zone_id_t zid)7909 zcache_drain(zone_id_t zid)
7910 {
7911 zone_drain(zone_by_id(zid));
7912 }
7913
7914 static void
zone_reclaim_all(zone_reclaim_mode_t mode)7915 zone_reclaim_all(zone_reclaim_mode_t mode)
7916 {
7917 /*
7918 * Start with zcaches, so that they flow into the regular zones.
7919 *
7920 * Then the zones with VA sequester since depopulating
7921 * pages will not need to allocate vm map entries for holes,
7922 * which will give memory back to the system faster.
7923 */
7924 for (zone_id_t zid = ZONE_ID__LAST_RO + 1; zid < ZONE_ID__FIRST_DYNAMIC; zid++) {
7925 zone_t z = zone_by_id(zid);
7926
7927 if (z->z_self && z->z_chunk_elems == 0) {
7928 zone_reclaim(z, mode);
7929 }
7930 }
7931 zone_index_foreach(zid) {
7932 zone_t z = zone_by_id(zid);
7933
7934 if (z == zc_magazine_zone || z->z_chunk_elems == 0) {
7935 continue;
7936 }
7937 if (zone_submap_is_sequestered(zone_security_array[zid]) &&
7938 z->collectable) {
7939 zone_reclaim(z, mode);
7940 }
7941 }
7942
7943 zone_index_foreach(zid) {
7944 zone_t z = zone_by_id(zid);
7945
7946 if (z == zc_magazine_zone || z->z_chunk_elems == 0) {
7947 continue;
7948 }
7949 if (!zone_submap_is_sequestered(zone_security_array[zid]) &&
7950 z->collectable) {
7951 zone_reclaim(z, mode);
7952 }
7953 }
7954
7955 zone_reclaim(zc_magazine_zone, mode);
7956 }
7957
7958 void
zone_userspace_reboot_checks(void)7959 zone_userspace_reboot_checks(void)
7960 {
7961 vm_size_t label_zone_size = zone_size_allocated(ipc_service_port_label_zone);
7962 if (label_zone_size != 0) {
7963 panic("Zone %s should be empty upon userspace reboot. Actual size: %lu.",
7964 ipc_service_port_label_zone->z_name, (unsigned long)label_zone_size);
7965 }
7966 }
7967
7968 void
zone_gc(zone_gc_level_t level)7969 zone_gc(zone_gc_level_t level)
7970 {
7971 zone_reclaim_mode_t mode;
7972 zone_t largest_zone = NULL;
7973
7974 switch (level) {
7975 case ZONE_GC_TRIM:
7976 mode = ZONE_RECLAIM_TRIM;
7977 break;
7978 case ZONE_GC_DRAIN:
7979 mode = ZONE_RECLAIM_DRAIN;
7980 break;
7981 case ZONE_GC_JETSAM:
7982 largest_zone = kill_process_in_largest_zone();
7983 mode = ZONE_RECLAIM_TRIM;
7984 break;
7985 }
7986
7987 current_thread()->options |= TH_OPT_ZONE_PRIV;
7988 lck_mtx_lock(&zone_gc_lock);
7989
7990 zone_reclaim_all(mode);
7991
7992 if (level == ZONE_GC_JETSAM && zone_map_nearing_exhaustion()) {
7993 /*
7994 * If we possibly killed a process, but we're still critical,
7995 * we need to drain harder.
7996 */
7997 zone_reclaim(largest_zone, ZONE_RECLAIM_DRAIN);
7998 zone_reclaim_all(ZONE_RECLAIM_DRAIN);
7999 }
8000
8001 lck_mtx_unlock(&zone_gc_lock);
8002 current_thread()->options &= ~TH_OPT_ZONE_PRIV;
8003 }
8004
8005 void
zone_gc_trim(void)8006 zone_gc_trim(void)
8007 {
8008 zone_gc(ZONE_GC_TRIM);
8009 }
8010
8011 void
zone_gc_drain(void)8012 zone_gc_drain(void)
8013 {
8014 zone_gc(ZONE_GC_DRAIN);
8015 }
8016
8017 static bool
zone_trim_needed(zone_t z)8018 zone_trim_needed(zone_t z)
8019 {
8020 if (z->z_depot_cleanup) {
8021 return true;
8022 }
8023
8024 if (z->z_async_refilling) {
8025 /* Don't fight with refill */
8026 return false;
8027 }
8028
8029 if (z->z_pcpu_cache) {
8030 uint32_t e_n, f_n;
8031
8032 e_n = MIN(z->z_recirc_empty_wma, z->z_recirc_empty_min * Z_WMA_UNIT);
8033 f_n = MIN(z->z_recirc_full_wma, z->z_recirc_full_min * Z_WMA_UNIT);
8034
8035 if (e_n > zc_autotrim_buckets() * Z_WMA_UNIT) {
8036 return true;
8037 }
8038
8039 if (f_n * zc_mag_size() > z->z_elems_rsv * Z_WMA_UNIT &&
8040 f_n * zc_mag_size() * zone_elem_inner_size(z) >
8041 zc_autotrim_size() * Z_WMA_UNIT) {
8042 return true;
8043 }
8044
8045 return false;
8046 }
8047
8048 if (!zone_pva_is_null(z->z_pageq_empty)) {
8049 uint32_t n;
8050
8051 n = MIN(z->z_elems_free_wma, z->z_elems_free_min);
8052
8053 return n >= z->z_elems_rsv + z->z_chunk_elems;
8054 }
8055
8056 return false;
8057 }
8058
8059 static void
zone_trim_async(__unused thread_call_param_t p0,__unused thread_call_param_t p1)8060 zone_trim_async(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
8061 {
8062 current_thread()->options |= TH_OPT_ZONE_PRIV;
8063
8064 zone_foreach(z) {
8065 if (!z->collectable || z == zc_magazine_zone) {
8066 continue;
8067 }
8068
8069 if (zone_trim_needed(z)) {
8070 lck_mtx_lock(&zone_gc_lock);
8071 zone_reclaim(z, ZONE_RECLAIM_TRIM);
8072 lck_mtx_unlock(&zone_gc_lock);
8073 }
8074 }
8075
8076 if (zone_trim_needed(zc_magazine_zone)) {
8077 lck_mtx_lock(&zone_gc_lock);
8078 zone_reclaim(zc_magazine_zone, ZONE_RECLAIM_TRIM);
8079 lck_mtx_unlock(&zone_gc_lock);
8080 }
8081
8082 current_thread()->options &= ~TH_OPT_ZONE_PRIV;
8083 }
8084
8085 void
compute_zone_working_set_size(__unused void * param)8086 compute_zone_working_set_size(__unused void *param)
8087 {
8088 uint32_t zc_auto = zc_enable_level();
8089 bool needs_trim = false;
8090
8091 /*
8092 * Keep zone caching disabled until the first proc is made.
8093 */
8094 if (__improbable(zone_caching_disabled < 0)) {
8095 return;
8096 }
8097
8098 zone_caching_disabled = vm_pool_low();
8099
8100 if (os_mul_overflow(zc_auto, Z_WMA_UNIT, &zc_auto)) {
8101 zc_auto = 0;
8102 }
8103
8104 zone_foreach(z) {
8105 uint32_t old, wma, cur;
8106 bool needs_caching = false;
8107
8108 if (z->z_self != z) {
8109 continue;
8110 }
8111
8112 zone_lock(z);
8113
8114 zone_recirc_lock_nopreempt(z);
8115
8116 if (z->z_pcpu_cache) {
8117 wma = Z_WMA_MIX(z->z_recirc_empty_wma, z->z_recirc_empty_min);
8118 z->z_recirc_empty_min = z->z_recirc.zd_empty;
8119 z->z_recirc_empty_wma = wma;
8120 } else {
8121 wma = Z_WMA_MIX(z->z_elems_free_wma, z->z_elems_free_min);
8122 z->z_elems_free_min = z->z_elems_free;
8123 z->z_elems_free_wma = wma;
8124 }
8125
8126 wma = Z_WMA_MIX(z->z_recirc_full_wma, z->z_recirc_full_min);
8127 z->z_recirc_full_min = z->z_recirc.zd_full;
8128 z->z_recirc_full_wma = wma;
8129
8130 /* fixed point decimal of contentions per second */
8131 old = z->z_recirc_cont_wma;
8132 cur = z->z_recirc_cont_cur * Z_WMA_UNIT /
8133 (zpercpu_count() * ZONE_WSS_UPDATE_PERIOD);
8134 cur = (3 * old + cur) / 4;
8135 zone_recirc_unlock_nopreempt(z);
8136
8137 if (z->z_pcpu_cache) {
8138 uint16_t size = z->z_depot_size;
8139
8140 if (zone_exhausted(z)) {
8141 if (z->z_depot_size) {
8142 z->z_depot_size = 0;
8143 z->z_depot_cleanup = true;
8144 }
8145 } else if (size < z->z_depot_limit && cur > zc_grow_level()) {
8146 /*
8147 * lose history on purpose now
8148 * that we just grew, to give
8149 * the sytem time to adjust.
8150 */
8151 cur = (zc_grow_level() + zc_shrink_level()) / 2;
8152 size = size ? (3 * size + 2) / 2 : 2;
8153 z->z_depot_size = MIN(z->z_depot_limit, size);
8154 } else if (size > 0 && cur <= zc_shrink_level()) {
8155 /*
8156 * lose history on purpose now
8157 * that we just shrunk, to give
8158 * the sytem time to adjust.
8159 */
8160 cur = (zc_grow_level() + zc_shrink_level()) / 2;
8161 z->z_depot_size = size - 1;
8162 z->z_depot_cleanup = true;
8163 }
8164 } else if (!z->z_nocaching && !zone_exhaustible(z) && zc_auto &&
8165 old >= zc_auto && cur >= zc_auto) {
8166 needs_caching = true;
8167 }
8168
8169 z->z_recirc_cont_wma = cur;
8170 z->z_recirc_cont_cur = 0;
8171
8172 if (!needs_trim && zone_trim_needed(z)) {
8173 needs_trim = true;
8174 }
8175
8176 zone_unlock(z);
8177
8178 if (needs_caching) {
8179 zone_enable_caching(z);
8180 }
8181 }
8182
8183 if (needs_trim) {
8184 thread_call_enter(&zone_trim_callout);
8185 }
8186 }
8187
8188 #endif /* !ZALLOC_TEST */
8189 #pragma mark vm integration, MIG routines
8190 #if !ZALLOC_TEST
8191
8192 extern unsigned int stack_total;
8193 #if defined (__x86_64__)
8194 extern unsigned int inuse_ptepages_count;
8195 #endif
8196
8197 static const char *
panic_print_get_typename(kalloc_type_views_t cur,kalloc_type_views_t * next,bool is_kt_var)8198 panic_print_get_typename(kalloc_type_views_t cur, kalloc_type_views_t *next,
8199 bool is_kt_var)
8200 {
8201 if (is_kt_var) {
8202 next->ktv_var = (kalloc_type_var_view_t) cur.ktv_var->kt_next;
8203 return cur.ktv_var->kt_name;
8204 } else {
8205 next->ktv_fixed = (kalloc_type_view_t) cur.ktv_fixed->kt_zv.zv_next;
8206 return cur.ktv_fixed->kt_zv.zv_name;
8207 }
8208 }
8209
8210 static void
panic_print_types_in_zone(zone_t z,const char * debug_str)8211 panic_print_types_in_zone(zone_t z, const char* debug_str)
8212 {
8213 kalloc_type_views_t kt_cur = {};
8214 const char *prev_type = "";
8215 size_t skip_over_site = sizeof("site.") - 1;
8216 zone_security_flags_t zsflags = zone_security_config(z);
8217 bool is_kt_var = false;
8218
8219 if (zsflags.z_kheap_id == KHEAP_ID_KT_VAR) {
8220 uint32_t heap_id = KT_VAR_PTR_HEAP0 + ((zone_index(z) -
8221 kalloc_type_heap_array[KT_VAR_PTR_HEAP0].kh_zstart) / KHEAP_NUM_ZONES);
8222 kt_cur.ktv_var = kalloc_type_heap_array[heap_id].kt_views;
8223 is_kt_var = true;
8224 } else {
8225 kt_cur.ktv_fixed = (kalloc_type_view_t) z->z_views;
8226 }
8227
8228 paniclog_append_noflush("kalloc %s in zone, %s (%s):\n",
8229 is_kt_var? "type arrays" : "types", debug_str, z->z_name);
8230
8231 while (kt_cur.ktv_fixed) {
8232 kalloc_type_views_t kt_next = {};
8233 const char *typename = panic_print_get_typename(kt_cur, &kt_next,
8234 is_kt_var) + skip_over_site;
8235 if (strcmp(typename, prev_type) != 0) {
8236 paniclog_append_noflush("\t%-50s\n", typename);
8237 prev_type = typename;
8238 }
8239 kt_cur = kt_next;
8240 }
8241 paniclog_append_noflush("\n");
8242 }
8243
8244 static void
panic_display_kalloc_types(void)8245 panic_display_kalloc_types(void)
8246 {
8247 if (kalloc_type_src_zone) {
8248 panic_print_types_in_zone(kalloc_type_src_zone, "addr belongs to");
8249 }
8250 if (kalloc_type_dst_zone) {
8251 panic_print_types_in_zone(kalloc_type_dst_zone,
8252 "addr is being freed to");
8253 }
8254 }
8255
8256 static void
zone_find_n_largest(const uint32_t n,zone_t * largest_zones,uint64_t * zone_size)8257 zone_find_n_largest(const uint32_t n, zone_t *largest_zones,
8258 uint64_t *zone_size)
8259 {
8260 zone_index_foreach(zid) {
8261 zone_t z = &zone_array[zid];
8262 vm_offset_t size = zone_size_wired(z);
8263
8264 if (zid == ZONE_ID_VM_PAGES) {
8265 continue;
8266 }
8267 for (uint32_t i = 0; i < n; i++) {
8268 if (size > zone_size[i]) {
8269 largest_zones[i] = z;
8270 zone_size[i] = size;
8271 break;
8272 }
8273 }
8274 }
8275 }
8276
8277 #define NUM_LARGEST_ZONES 5
8278 static void
panic_display_largest_zones(void)8279 panic_display_largest_zones(void)
8280 {
8281 zone_t largest_zones[NUM_LARGEST_ZONES] = { NULL };
8282 uint64_t largest_size[NUM_LARGEST_ZONES] = { 0 };
8283
8284 zone_find_n_largest(NUM_LARGEST_ZONES, (zone_t *) &largest_zones,
8285 (uint64_t *) &largest_size);
8286
8287 paniclog_append_noflush("Largest zones:\n%-28s %10s %10s\n",
8288 "Zone Name", "Cur Size", "Free Size");
8289 for (uint32_t i = 0; i < NUM_LARGEST_ZONES; i++) {
8290 zone_t z = largest_zones[i];
8291 paniclog_append_noflush("%-8s%-20s %9u%c %9u%c\n",
8292 zone_heap_name(z), z->z_name,
8293 mach_vm_size_pretty(largest_size[i]),
8294 mach_vm_size_unit(largest_size[i]),
8295 mach_vm_size_pretty(zone_size_free(z)),
8296 mach_vm_size_unit(zone_size_free(z)));
8297 }
8298 }
8299
8300 static void
panic_display_zprint(void)8301 panic_display_zprint(void)
8302 {
8303 panic_display_largest_zones();
8304 paniclog_append_noflush("%-20s %10lu\n", "Kernel Stacks",
8305 (uintptr_t)(kernel_stack_size * stack_total));
8306 #if defined (__x86_64__)
8307 paniclog_append_noflush("%-20s %10lu\n", "PageTables",
8308 (uintptr_t)ptoa(inuse_ptepages_count));
8309 #endif
8310 paniclog_append_noflush("%-20s %10llu\n", "Kalloc.Large",
8311 counter_load(&kalloc_large_total));
8312
8313 if (panic_kext_memory_info) {
8314 mach_memory_info_t *mem_info = panic_kext_memory_info;
8315
8316 paniclog_append_noflush("\n%-5s %10s\n", "Kmod", "Size");
8317 for (uint32_t i = 0; i < panic_kext_memory_size / sizeof(mem_info[0]); i++) {
8318 if ((mem_info[i].flags & VM_KERN_SITE_TYPE) != VM_KERN_SITE_KMOD) {
8319 continue;
8320 }
8321 if (mem_info[i].size > (1024 * 1024)) {
8322 paniclog_append_noflush("%-5lld %10lld\n",
8323 mem_info[i].site, mem_info[i].size);
8324 }
8325 }
8326 }
8327 }
8328
8329 static void
panic_display_zone_info(void)8330 panic_display_zone_info(void)
8331 {
8332 paniclog_append_noflush("Zone info:\n");
8333 paniclog_append_noflush(" Zone map: %p - %p\n",
8334 (void *)zone_info.zi_map_range.min_address,
8335 (void *)zone_info.zi_map_range.max_address);
8336 #if CONFIG_PROB_GZALLOC
8337 if (pgz_submap) {
8338 paniclog_append_noflush(" . PGZ : %p - %p\n",
8339 (void *)pgz_submap->min_offset,
8340 (void *)pgz_submap->max_offset);
8341 }
8342 #endif /* CONFIG_PROB_GZALLOC */
8343 for (int i = 0; i < Z_SUBMAP_IDX_COUNT; i++) {
8344 vm_map_t map = zone_submaps[i];
8345
8346 if (map == VM_MAP_NULL) {
8347 continue;
8348 }
8349 paniclog_append_noflush(" . %-6s: %p - %p\n",
8350 zone_submaps_names[i],
8351 (void *)map->min_offset,
8352 (void *)map->max_offset);
8353 }
8354 paniclog_append_noflush(" Metadata: %p - %p\n"
8355 " Bitmaps : %p - %p\n"
8356 " Extra : %p - %p\n"
8357 "\n",
8358 (void *)zone_info.zi_meta_range.min_address,
8359 (void *)zone_info.zi_meta_range.max_address,
8360 (void *)zone_info.zi_bits_range.min_address,
8361 (void *)zone_info.zi_bits_range.max_address,
8362 (void *)zone_info.zi_xtra_range.min_address,
8363 (void *)zone_info.zi_xtra_range.max_address);
8364 }
8365
8366 static void
panic_display_zone_fault(vm_offset_t addr)8367 panic_display_zone_fault(vm_offset_t addr)
8368 {
8369 struct zone_page_metadata meta = { };
8370 vm_map_t map = VM_MAP_NULL;
8371 vm_offset_t oob_offs = 0, size = 0;
8372 int map_idx = -1;
8373 zone_t z = NULL;
8374 const char *kind = "whild deref";
8375 bool oob = false;
8376
8377 /*
8378 * First: look if we bumped into guard pages between submaps
8379 */
8380 for (int i = 0; i < Z_SUBMAP_IDX_COUNT; i++) {
8381 map = zone_submaps[i];
8382 if (map == VM_MAP_NULL) {
8383 continue;
8384 }
8385
8386 if (addr >= map->min_offset && addr < map->max_offset) {
8387 map_idx = i;
8388 break;
8389 }
8390 }
8391
8392 if (map_idx == -1) {
8393 /* this really shouldn't happen, submaps are back to back */
8394 return;
8395 }
8396
8397 paniclog_append_noflush("Probabilistic GZAlloc Report:\n");
8398
8399 /*
8400 * Second: look if there's just no metadata at all
8401 */
8402 if (ml_nofault_copy((vm_offset_t)zone_meta_from_addr(addr),
8403 (vm_offset_t)&meta, sizeof(meta)) != sizeof(meta) ||
8404 meta.zm_index == 0 || meta.zm_index >= MAX_ZONES ||
8405 zone_array[meta.zm_index].z_self == NULL) {
8406 paniclog_append_noflush(" Zone : <unknown>\n");
8407 kind = "wild deref, missing or invalid metadata";
8408 } else {
8409 z = &zone_array[meta.zm_index];
8410 paniclog_append_noflush(" Zone : %s%s\n",
8411 zone_heap_name(z), zone_name(z));
8412 if (meta.zm_chunk_len == ZM_PGZ_GUARD) {
8413 kind = "out-of-bounds (high confidence)";
8414 oob = true;
8415 size = zone_element_size((void *)addr,
8416 &z, false, &oob_offs);
8417 } else {
8418 kind = "use-after-free (medium confidence)";
8419 }
8420 }
8421
8422 paniclog_append_noflush(" Address : %p\n", (void *)addr);
8423 if (oob) {
8424 paniclog_append_noflush(" Element : [%p, %p) of size %d\n",
8425 (void *)(trunc_page(addr) - (size - oob_offs)),
8426 (void *)trunc_page(addr), (uint32_t)(size - oob_offs));
8427 }
8428 paniclog_append_noflush(" Submap : %s [%p; %p)\n",
8429 zone_submaps_names[map_idx],
8430 (void *)map->min_offset, (void *)map->max_offset);
8431 paniclog_append_noflush(" Kind : %s\n", kind);
8432 if (oob) {
8433 paniclog_append_noflush(" Access : %d byte(s) past\n",
8434 (uint32_t)(addr & PAGE_MASK) + 1);
8435 }
8436 paniclog_append_noflush(" Metadata: zid:%d inl:%d cl:0x%x "
8437 "0x%04x 0x%08x 0x%08x 0x%08x\n",
8438 meta.zm_index, meta.zm_inline_bitmap, meta.zm_chunk_len,
8439 meta.zm_alloc_size, meta.zm_bitmap,
8440 meta.zm_page_next.packed_address,
8441 meta.zm_page_prev.packed_address);
8442 paniclog_append_noflush("\n");
8443 }
8444
8445 void
panic_display_zalloc(void)8446 panic_display_zalloc(void)
8447 {
8448 bool keepsyms = false;
8449
8450 PE_parse_boot_argn("keepsyms", &keepsyms, sizeof(keepsyms));
8451
8452 panic_display_zone_info();
8453
8454 if (panic_fault_address) {
8455 #if CONFIG_PROB_GZALLOC
8456 if (pgz_owned(panic_fault_address)) {
8457 panic_display_pgz_uaf_info(keepsyms, panic_fault_address);
8458 } else
8459 #endif /* CONFIG_PROB_GZALLOC */
8460 if (zone_maps_owned(panic_fault_address, 1)) {
8461 panic_display_zone_fault(panic_fault_address);
8462 }
8463 }
8464
8465 if (panic_include_zprint) {
8466 panic_display_zprint();
8467 } else if (zone_map_nearing_threshold(ZONE_MAP_EXHAUSTION_PRINT_PANIC)) {
8468 panic_display_largest_zones();
8469 }
8470 #if CONFIG_ZLEAKS
8471 if (zleak_active) {
8472 panic_display_zleaks(keepsyms);
8473 }
8474 #endif
8475 if (panic_include_kalloc_types) {
8476 panic_display_kalloc_types();
8477 }
8478 }
8479
8480 /*
8481 * Creates a vm_map_copy_t to return to the caller of mach_* MIG calls
8482 * requesting zone information.
8483 * Frees unused pages towards the end of the region, and zero'es out unused
8484 * space on the last page.
8485 */
8486 static vm_map_copy_t
create_vm_map_copy(vm_offset_t start_addr,vm_size_t total_size,vm_size_t used_size)8487 create_vm_map_copy(
8488 vm_offset_t start_addr,
8489 vm_size_t total_size,
8490 vm_size_t used_size)
8491 {
8492 kern_return_t kr;
8493 vm_offset_t end_addr;
8494 vm_size_t free_size;
8495 vm_map_copy_t copy;
8496
8497 if (used_size != total_size) {
8498 end_addr = start_addr + used_size;
8499 free_size = total_size - (round_page(end_addr) - start_addr);
8500
8501 if (free_size >= PAGE_SIZE) {
8502 kmem_free(ipc_kernel_map,
8503 round_page(end_addr), free_size);
8504 }
8505 bzero((char *) end_addr, round_page(end_addr) - end_addr);
8506 }
8507
8508 kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)start_addr,
8509 (vm_map_size_t)used_size, TRUE, ©);
8510 assert(kr == KERN_SUCCESS);
8511
8512 return copy;
8513 }
8514
8515 static boolean_t
get_zone_info(zone_t z,mach_zone_name_t * zn,mach_zone_info_t * zi)8516 get_zone_info(
8517 zone_t z,
8518 mach_zone_name_t *zn,
8519 mach_zone_info_t *zi)
8520 {
8521 struct zone zcopy;
8522 vm_size_t cached = 0;
8523
8524 assert(z != ZONE_NULL);
8525 zone_lock(z);
8526 if (!z->z_self) {
8527 zone_unlock(z);
8528 return FALSE;
8529 }
8530 zcopy = *z;
8531 if (z->z_pcpu_cache) {
8532 zpercpu_foreach(zc, z->z_pcpu_cache) {
8533 cached += zc->zc_alloc_cur + zc->zc_free_cur;
8534 cached += zc->zc_depot.zd_full * zc_mag_size();
8535 }
8536 }
8537 zone_unlock(z);
8538
8539 if (zn != NULL) {
8540 /*
8541 * Append kalloc heap name to zone name (if zone is used by kalloc)
8542 */
8543 char temp_zone_name[MAX_ZONE_NAME] = "";
8544 snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
8545 zone_heap_name(z), z->z_name);
8546
8547 /* assuming here the name data is static */
8548 (void) __nosan_strlcpy(zn->mzn_name, temp_zone_name,
8549 strlen(temp_zone_name) + 1);
8550 }
8551
8552 if (zi != NULL) {
8553 *zi = (mach_zone_info_t) {
8554 .mzi_count = zone_count_allocated(&zcopy) - cached,
8555 .mzi_cur_size = ptoa_64(zone_scale_for_percpu(&zcopy, zcopy.z_wired_cur)),
8556 // max_size for zprint is now high-watermark of pages used
8557 .mzi_max_size = ptoa_64(zone_scale_for_percpu(&zcopy, zcopy.z_wired_hwm)),
8558 .mzi_elem_size = zone_scale_for_percpu(&zcopy, zcopy.z_elem_size),
8559 .mzi_alloc_size = ptoa_64(zcopy.z_chunk_pages),
8560 .mzi_exhaustible = (uint64_t)zone_exhaustible(&zcopy),
8561 };
8562 if (zcopy.z_chunk_pages == 0) {
8563 /* this is a zcache */
8564 zi->mzi_cur_size = zcopy.z_elems_avail * zcopy.z_elem_size;
8565 }
8566 zpercpu_foreach(zs, zcopy.z_stats) {
8567 zi->mzi_sum_size += zs->zs_mem_allocated;
8568 }
8569 if (zcopy.collectable) {
8570 SET_MZI_COLLECTABLE_BYTES(zi->mzi_collectable,
8571 ptoa_64(zone_scale_for_percpu(&zcopy, zcopy.z_wired_empty)));
8572 SET_MZI_COLLECTABLE_FLAG(zi->mzi_collectable, TRUE);
8573 }
8574 }
8575
8576 return TRUE;
8577 }
8578
8579 /* mach_memory_info entitlement */
8580 #define MEMORYINFO_ENTITLEMENT "com.apple.private.memoryinfo"
8581
8582 /* macro needed to rate-limit mach_memory_info */
8583 #define NSEC_DAY (NSEC_PER_SEC * 60 * 60 * 24)
8584
8585 /* declarations necessary to call kauth_cred_issuser() */
8586 struct ucred;
8587 extern int kauth_cred_issuser(struct ucred *);
8588 extern struct ucred *kauth_cred_get(void);
8589
8590 static kern_return_t
8591 mach_memory_info_internal(
8592 host_t host,
8593 mach_zone_name_array_t *namesp,
8594 mach_msg_type_number_t *namesCntp,
8595 mach_zone_info_array_t *infop,
8596 mach_msg_type_number_t *infoCntp,
8597 mach_memory_info_array_t *memoryInfop,
8598 mach_msg_type_number_t *memoryInfoCntp,
8599 bool redact_info);
8600
8601 static kern_return_t
mach_memory_info_security_check(bool redact_info)8602 mach_memory_info_security_check(bool redact_info)
8603 {
8604 /* If not root, only allow redacted calls. */
8605 if (!kauth_cred_issuser(kauth_cred_get()) && !redact_info) {
8606 return KERN_NO_ACCESS;
8607 }
8608
8609 if (PE_srd_fused) {
8610 return KERN_SUCCESS;
8611 }
8612
8613 /* If does not have the memory entitlement, fail. */
8614 #if CONFIG_DEBUGGER_FOR_ZONE_INFO
8615 task_t task = current_task();
8616 if (task != kernel_task && !IOTaskHasEntitlement(task, MEMORYINFO_ENTITLEMENT)) {
8617 return KERN_DENIED;
8618 }
8619
8620 /*
8621 * On release non-mac arm devices, allow mach_memory_info
8622 * to be called twice per day per boot. memorymaintenanced
8623 * calls it once per day, which leaves room for a sysdiagnose.
8624 * Allow redacted version to be called without rate limit.
8625 */
8626
8627 if (!redact_info) {
8628 static uint64_t first_call = 0, second_call = 0;
8629 uint64_t now = 0;
8630 absolutetime_to_nanoseconds(ml_get_timebase(), &now);
8631
8632 if (!first_call) {
8633 first_call = now;
8634 } else if (!second_call) {
8635 second_call = now;
8636 } else if (first_call + NSEC_DAY > now) {
8637 return KERN_DENIED;
8638 } else if (first_call + NSEC_DAY < now) {
8639 first_call = now;
8640 second_call = 0;
8641 }
8642 }
8643 #endif
8644
8645 return KERN_SUCCESS;
8646 }
8647
8648 kern_return_t
mach_zone_info(mach_port_t host_port,mach_zone_name_array_t * namesp,mach_msg_type_number_t * namesCntp,mach_zone_info_array_t * infop,mach_msg_type_number_t * infoCntp)8649 mach_zone_info(
8650 mach_port_t host_port,
8651 mach_zone_name_array_t *namesp,
8652 mach_msg_type_number_t *namesCntp,
8653 mach_zone_info_array_t *infop,
8654 mach_msg_type_number_t *infoCntp)
8655 {
8656 return mach_memory_info(host_port, namesp, namesCntp, infop, infoCntp, NULL, NULL);
8657 }
8658
8659 kern_return_t
mach_memory_info(mach_port_t host_port,mach_zone_name_array_t * namesp,mach_msg_type_number_t * namesCntp,mach_zone_info_array_t * infop,mach_msg_type_number_t * infoCntp,mach_memory_info_array_t * memoryInfop,mach_msg_type_number_t * memoryInfoCntp)8660 mach_memory_info(
8661 mach_port_t host_port,
8662 mach_zone_name_array_t *namesp,
8663 mach_msg_type_number_t *namesCntp,
8664 mach_zone_info_array_t *infop,
8665 mach_msg_type_number_t *infoCntp,
8666 mach_memory_info_array_t *memoryInfop,
8667 mach_msg_type_number_t *memoryInfoCntp)
8668 {
8669 bool redact_info = false;
8670 host_t host = HOST_NULL;
8671
8672 host = convert_port_to_host_priv(host_port);
8673 if (host == HOST_NULL) {
8674 redact_info = true;
8675 host = convert_port_to_host(host_port);
8676 }
8677
8678 return mach_memory_info_internal(host, namesp, namesCntp, infop, infoCntp, memoryInfop, memoryInfoCntp, redact_info);
8679 }
8680
8681 static void
zone_info_redact(mach_zone_info_t * zi)8682 zone_info_redact(mach_zone_info_t *zi)
8683 {
8684 zi->mzi_cur_size = 0;
8685 zi->mzi_max_size = 0;
8686 zi->mzi_alloc_size = 0;
8687 zi->mzi_sum_size = 0;
8688 zi->mzi_collectable = 0;
8689 }
8690
8691 static bool
zone_info_needs_to_be_coalesced(int zone_index)8692 zone_info_needs_to_be_coalesced(int zone_index)
8693 {
8694 zone_security_flags_t zsflags = zone_security_array[zone_index];
8695 if (zsflags.z_kalloc_type || zsflags.z_kheap_id == KHEAP_ID_KT_VAR) {
8696 return true;
8697 }
8698 return false;
8699 }
8700
8701 static bool
zone_info_find_coalesce_zone(mach_zone_info_t * zi,mach_zone_info_t * info,int * coalesce,int coalesce_count,int * coalesce_index)8702 zone_info_find_coalesce_zone(
8703 mach_zone_info_t *zi,
8704 mach_zone_info_t *info,
8705 int *coalesce,
8706 int coalesce_count,
8707 int *coalesce_index)
8708 {
8709 for (int i = 0; i < coalesce_count; i++) {
8710 if (zi->mzi_elem_size == info[coalesce[i]].mzi_elem_size) {
8711 *coalesce_index = coalesce[i];
8712 return true;
8713 }
8714 }
8715
8716 return false;
8717 }
8718
8719 static void
zone_info_coalesce(mach_zone_info_t * info,int coalesce_index,mach_zone_info_t * zi)8720 zone_info_coalesce(
8721 mach_zone_info_t *info,
8722 int coalesce_index,
8723 mach_zone_info_t *zi)
8724 {
8725 info[coalesce_index].mzi_count += zi->mzi_count;
8726 }
8727
8728 kern_return_t
mach_memory_info_sample(mach_zone_name_t * names,mach_zone_info_t * info,int * coalesce,unsigned int * zonesCnt,mach_memory_info_t * memoryInfo,unsigned int memoryInfoCnt,bool redact_info)8729 mach_memory_info_sample(
8730 mach_zone_name_t *names,
8731 mach_zone_info_t *info,
8732 int *coalesce,
8733 unsigned int *zonesCnt,
8734 mach_memory_info_t *memoryInfo,
8735 unsigned int memoryInfoCnt,
8736 bool redact_info)
8737 {
8738 int coalesce_count = 0;
8739 unsigned int max_zones, used_zones = 0;
8740 mach_zone_name_t *zn;
8741 mach_zone_info_t *zi;
8742 kern_return_t kr;
8743
8744 uint64_t zones_collectable_bytes = 0;
8745
8746 kr = mach_memory_info_security_check(redact_info);
8747 if (kr != KERN_SUCCESS) {
8748 return kr;
8749 }
8750
8751 max_zones = *zonesCnt;
8752
8753 bzero(names, max_zones * sizeof(*names));
8754 bzero(info, max_zones * sizeof(*info));
8755 if (redact_info) {
8756 bzero(coalesce, max_zones * sizeof(*coalesce));
8757 }
8758
8759 zn = &names[0];
8760 zi = &info[0];
8761
8762 zone_index_foreach(i) {
8763 if (used_zones > max_zones) {
8764 break;
8765 }
8766
8767 if (!get_zone_info(&(zone_array[i]), zn, zi)) {
8768 continue;
8769 }
8770
8771 if (!redact_info) {
8772 zones_collectable_bytes += GET_MZI_COLLECTABLE_BYTES(zi->mzi_collectable);
8773 zn++;
8774 zi++;
8775 used_zones++;
8776 continue;
8777 }
8778
8779 zone_info_redact(zi);
8780 if (!zone_info_needs_to_be_coalesced(i)) {
8781 zn++;
8782 zi++;
8783 used_zones++;
8784 continue;
8785 }
8786
8787 int coalesce_index;
8788 bool found_coalesce_zone = zone_info_find_coalesce_zone(zi, info,
8789 coalesce, coalesce_count, &coalesce_index);
8790
8791 /* Didn't find a zone to coalesce */
8792 if (!found_coalesce_zone) {
8793 /* Updates the zone name */
8794 __nosan_bzero(zn->mzn_name, MAX_ZONE_NAME);
8795 snprintf(zn->mzn_name, MAX_ZONE_NAME, "kalloc.%d",
8796 (int)zi->mzi_elem_size);
8797
8798 coalesce[coalesce_count] = used_zones;
8799 coalesce_count++;
8800 zn++;
8801 zi++;
8802 used_zones++;
8803 continue;
8804 }
8805
8806 zone_info_coalesce(info, coalesce_index, zi);
8807 }
8808
8809 *zonesCnt = used_zones;
8810
8811 if (memoryInfo) {
8812 bzero(memoryInfo, memoryInfoCnt * sizeof(*memoryInfo));
8813 kr = vm_page_diagnose(memoryInfo, memoryInfoCnt, zones_collectable_bytes, redact_info);
8814 if (kr != KERN_SUCCESS) {
8815 return kr;
8816 }
8817 }
8818
8819 return kr;
8820 }
8821
8822 static kern_return_t
mach_memory_info_internal(host_t host,mach_zone_name_array_t * namesp,mach_msg_type_number_t * namesCntp,mach_zone_info_array_t * infop,mach_msg_type_number_t * infoCntp,mach_memory_info_array_t * memoryInfop,mach_msg_type_number_t * memoryInfoCntp,bool redact_info)8823 mach_memory_info_internal(
8824 host_t host,
8825 mach_zone_name_array_t *namesp,
8826 mach_msg_type_number_t *namesCntp,
8827 mach_zone_info_array_t *infop,
8828 mach_msg_type_number_t *infoCntp,
8829 mach_memory_info_array_t *memoryInfop,
8830 mach_msg_type_number_t *memoryInfoCntp,
8831 bool redact_info)
8832 {
8833 mach_zone_name_t *names;
8834 vm_offset_t names_addr;
8835 vm_size_t names_size;
8836
8837 mach_zone_info_t *info;
8838 vm_offset_t info_addr;
8839 vm_size_t info_size;
8840
8841 int *coalesce;
8842 vm_offset_t coalesce_addr;
8843 vm_size_t coalesce_size;
8844
8845 mach_memory_info_t *memory_info = NULL;
8846 vm_offset_t memory_info_addr = 0;
8847 vm_size_t memory_info_size;
8848 vm_size_t memory_info_vmsize;
8849 vm_map_copy_t memory_info_copy;
8850 unsigned int num_info = 0;
8851
8852 unsigned int max_zones, used_zones;
8853 kern_return_t kr;
8854
8855 if (host == HOST_NULL) {
8856 return KERN_INVALID_HOST;
8857 }
8858
8859 /*
8860 * We assume that zones aren't freed once allocated.
8861 * We won't pick up any zones that are allocated later.
8862 */
8863
8864 max_zones = os_atomic_load(&num_zones, relaxed);
8865
8866 names_size = round_page(max_zones * sizeof *names);
8867 kr = kmem_alloc(ipc_kernel_map, &names_addr, names_size,
8868 KMA_PAGEABLE | KMA_DATA, VM_KERN_MEMORY_IPC);
8869 if (kr != KERN_SUCCESS) {
8870 return kr;
8871 }
8872 names = (mach_zone_name_t *) names_addr;
8873
8874 info_size = round_page(max_zones * sizeof *info);
8875 kr = kmem_alloc(ipc_kernel_map, &info_addr, info_size,
8876 KMA_PAGEABLE | KMA_DATA, VM_KERN_MEMORY_IPC);
8877 if (kr != KERN_SUCCESS) {
8878 kmem_free(ipc_kernel_map,
8879 names_addr, names_size);
8880 return kr;
8881 }
8882 info = (mach_zone_info_t *) info_addr;
8883
8884 if (redact_info) {
8885 coalesce_size = round_page(max_zones * sizeof *coalesce);
8886 kr = kmem_alloc(ipc_kernel_map, &coalesce_addr, coalesce_size,
8887 KMA_PAGEABLE | KMA_DATA, VM_KERN_MEMORY_IPC);
8888 if (kr != KERN_SUCCESS) {
8889 kmem_free(ipc_kernel_map,
8890 names_addr, names_size);
8891 kmem_free(ipc_kernel_map,
8892 info_addr, info_size);
8893 return kr;
8894 }
8895 coalesce = (int *)coalesce_addr;
8896 }
8897
8898 if (memoryInfop && memoryInfoCntp) {
8899 num_info = vm_page_diagnose_estimate();
8900 memory_info_size = num_info * sizeof(*memory_info);
8901 memory_info_vmsize = round_page(memory_info_size);
8902 kr = kmem_alloc(ipc_kernel_map, &memory_info_addr, memory_info_vmsize,
8903 KMA_PAGEABLE | KMA_DATA, VM_KERN_MEMORY_IPC);
8904 if (kr != KERN_SUCCESS) {
8905 return kr;
8906 }
8907
8908 kr = vm_map_wire_kernel(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize,
8909 VM_PROT_READ | VM_PROT_WRITE, VM_KERN_MEMORY_IPC, FALSE);
8910 assert(kr == KERN_SUCCESS);
8911
8912 memory_info = (mach_memory_info_t *) memory_info_addr;
8913 }
8914
8915 used_zones = max_zones;
8916 mach_memory_info_sample(names, info, coalesce, &used_zones, memory_info, num_info, redact_info);
8917
8918 if (redact_info) {
8919 kmem_free(ipc_kernel_map, coalesce_addr, coalesce_size);
8920 }
8921
8922 *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, used_zones * sizeof *names);
8923 *namesCntp = used_zones;
8924
8925 *infop = (mach_zone_info_t *) create_vm_map_copy(info_addr, info_size, used_zones * sizeof *info);
8926 *infoCntp = used_zones;
8927
8928 if (memoryInfop && memoryInfoCntp) {
8929 kr = vm_map_unwire(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize, FALSE);
8930 assert(kr == KERN_SUCCESS);
8931
8932 kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)memory_info_addr,
8933 (vm_map_size_t)memory_info_size, TRUE, &memory_info_copy);
8934 assert(kr == KERN_SUCCESS);
8935
8936 *memoryInfop = (mach_memory_info_t *) memory_info_copy;
8937 *memoryInfoCntp = num_info;
8938 }
8939
8940 return KERN_SUCCESS;
8941 }
8942
8943 kern_return_t
mach_zone_info_for_zone(host_priv_t host,mach_zone_name_t name,mach_zone_info_t * infop)8944 mach_zone_info_for_zone(
8945 host_priv_t host,
8946 mach_zone_name_t name,
8947 mach_zone_info_t *infop)
8948 {
8949 zone_t zone_ptr;
8950
8951 if (host == HOST_NULL) {
8952 return KERN_INVALID_HOST;
8953 }
8954
8955 #if CONFIG_DEBUGGER_FOR_ZONE_INFO
8956 if (!PE_i_can_has_debugger(NULL)) {
8957 return KERN_INVALID_HOST;
8958 }
8959 #endif
8960
8961 if (infop == NULL) {
8962 return KERN_INVALID_ARGUMENT;
8963 }
8964
8965 zone_ptr = ZONE_NULL;
8966 zone_foreach(z) {
8967 /*
8968 * Append kalloc heap name to zone name (if zone is used by kalloc)
8969 */
8970 char temp_zone_name[MAX_ZONE_NAME] = "";
8971 snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
8972 zone_heap_name(z), z->z_name);
8973
8974 /* Find the requested zone by name */
8975 if (track_this_zone(temp_zone_name, name.mzn_name)) {
8976 zone_ptr = z;
8977 break;
8978 }
8979 }
8980
8981 /* No zones found with the requested zone name */
8982 if (zone_ptr == ZONE_NULL) {
8983 return KERN_INVALID_ARGUMENT;
8984 }
8985
8986 if (get_zone_info(zone_ptr, NULL, infop)) {
8987 return KERN_SUCCESS;
8988 }
8989 return KERN_FAILURE;
8990 }
8991
8992 kern_return_t
mach_zone_info_for_largest_zone(host_priv_t host,mach_zone_name_t * namep,mach_zone_info_t * infop)8993 mach_zone_info_for_largest_zone(
8994 host_priv_t host,
8995 mach_zone_name_t *namep,
8996 mach_zone_info_t *infop)
8997 {
8998 if (host == HOST_NULL) {
8999 return KERN_INVALID_HOST;
9000 }
9001
9002 #if CONFIG_DEBUGGER_FOR_ZONE_INFO
9003 if (!PE_i_can_has_debugger(NULL)) {
9004 return KERN_INVALID_HOST;
9005 }
9006 #endif
9007
9008 if (namep == NULL || infop == NULL) {
9009 return KERN_INVALID_ARGUMENT;
9010 }
9011
9012 if (get_zone_info(zone_find_largest(NULL), namep, infop)) {
9013 return KERN_SUCCESS;
9014 }
9015 return KERN_FAILURE;
9016 }
9017
9018 uint64_t
get_zones_collectable_bytes(void)9019 get_zones_collectable_bytes(void)
9020 {
9021 uint64_t zones_collectable_bytes = 0;
9022 mach_zone_info_t zi;
9023
9024 zone_foreach(z) {
9025 if (get_zone_info(z, NULL, &zi)) {
9026 zones_collectable_bytes +=
9027 GET_MZI_COLLECTABLE_BYTES(zi.mzi_collectable);
9028 }
9029 }
9030
9031 return zones_collectable_bytes;
9032 }
9033
9034 kern_return_t
mach_zone_get_zlog_zones(host_priv_t host,mach_zone_name_array_t * namesp,mach_msg_type_number_t * namesCntp)9035 mach_zone_get_zlog_zones(
9036 host_priv_t host,
9037 mach_zone_name_array_t *namesp,
9038 mach_msg_type_number_t *namesCntp)
9039 {
9040 #if ZALLOC_ENABLE_LOGGING
9041 unsigned int max_zones, logged_zones, i;
9042 kern_return_t kr;
9043 zone_t zone_ptr;
9044 mach_zone_name_t *names;
9045 vm_offset_t names_addr;
9046 vm_size_t names_size;
9047
9048 if (host == HOST_NULL) {
9049 return KERN_INVALID_HOST;
9050 }
9051
9052 if (namesp == NULL || namesCntp == NULL) {
9053 return KERN_INVALID_ARGUMENT;
9054 }
9055
9056 max_zones = os_atomic_load(&num_zones, relaxed);
9057
9058 names_size = round_page(max_zones * sizeof *names);
9059 kr = kmem_alloc(ipc_kernel_map, &names_addr, names_size,
9060 KMA_PAGEABLE | KMA_DATA, VM_KERN_MEMORY_IPC);
9061 if (kr != KERN_SUCCESS) {
9062 return kr;
9063 }
9064 names = (mach_zone_name_t *) names_addr;
9065
9066 zone_ptr = ZONE_NULL;
9067 logged_zones = 0;
9068 for (i = 0; i < max_zones; i++) {
9069 zone_t z = &(zone_array[i]);
9070 assert(z != ZONE_NULL);
9071
9072 /* Copy out the zone name if zone logging is enabled */
9073 if (z->z_btlog) {
9074 get_zone_info(z, &names[logged_zones], NULL);
9075 logged_zones++;
9076 }
9077 }
9078
9079 *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, logged_zones * sizeof *names);
9080 *namesCntp = logged_zones;
9081
9082 return KERN_SUCCESS;
9083
9084 #else /* ZALLOC_ENABLE_LOGGING */
9085 #pragma unused(host, namesp, namesCntp)
9086 return KERN_FAILURE;
9087 #endif /* ZALLOC_ENABLE_LOGGING */
9088 }
9089
9090 kern_return_t
mach_zone_get_btlog_records(host_priv_t host,mach_zone_name_t name,zone_btrecord_array_t * recsp,mach_msg_type_number_t * numrecs)9091 mach_zone_get_btlog_records(
9092 host_priv_t host,
9093 mach_zone_name_t name,
9094 zone_btrecord_array_t *recsp,
9095 mach_msg_type_number_t *numrecs)
9096 {
9097 #if ZALLOC_ENABLE_LOGGING
9098 zone_btrecord_t *recs;
9099 kern_return_t kr;
9100 vm_address_t addr;
9101 vm_size_t size;
9102 zone_t zone_ptr;
9103 vm_map_copy_t copy;
9104
9105 if (host == HOST_NULL) {
9106 return KERN_INVALID_HOST;
9107 }
9108
9109 if (recsp == NULL || numrecs == NULL) {
9110 return KERN_INVALID_ARGUMENT;
9111 }
9112
9113 zone_ptr = ZONE_NULL;
9114 zone_foreach(z) {
9115 /*
9116 * Append kalloc heap name to zone name (if zone is used by kalloc)
9117 */
9118 char temp_zone_name[MAX_ZONE_NAME] = "";
9119 snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
9120 zone_heap_name(z), z->z_name);
9121
9122 /* Find the requested zone by name */
9123 if (track_this_zone(temp_zone_name, name.mzn_name)) {
9124 zone_ptr = z;
9125 break;
9126 }
9127 }
9128
9129 /* No zones found with the requested zone name */
9130 if (zone_ptr == ZONE_NULL) {
9131 return KERN_INVALID_ARGUMENT;
9132 }
9133
9134 /* Logging not turned on for the requested zone */
9135 if (!zone_ptr->z_btlog) {
9136 return KERN_FAILURE;
9137 }
9138
9139 kr = btlog_get_records(zone_ptr->z_btlog, &recs, numrecs);
9140 if (kr != KERN_SUCCESS) {
9141 return kr;
9142 }
9143
9144 addr = (vm_address_t)recs;
9145 size = sizeof(zone_btrecord_t) * *numrecs;
9146
9147 kr = vm_map_copyin(ipc_kernel_map, addr, size, TRUE, ©);
9148 assert(kr == KERN_SUCCESS);
9149
9150 *recsp = (zone_btrecord_t *)copy;
9151 return KERN_SUCCESS;
9152
9153 #else /* !ZALLOC_ENABLE_LOGGING */
9154 #pragma unused(host, name, recsp, numrecs)
9155 return KERN_FAILURE;
9156 #endif /* !ZALLOC_ENABLE_LOGGING */
9157 }
9158
9159
9160 kern_return_t
mach_zone_force_gc(host_t host)9161 mach_zone_force_gc(
9162 host_t host)
9163 {
9164 if (host == HOST_NULL) {
9165 return KERN_INVALID_HOST;
9166 }
9167
9168 #if DEBUG || DEVELOPMENT
9169 extern boolean_t(*volatile consider_buffer_cache_collect)(int);
9170 /* Callout to buffer cache GC to drop elements in the apfs zones */
9171 if (consider_buffer_cache_collect != NULL) {
9172 (void)(*consider_buffer_cache_collect)(0);
9173 }
9174 zone_gc(ZONE_GC_DRAIN);
9175 #endif /* DEBUG || DEVELOPMENT */
9176 return KERN_SUCCESS;
9177 }
9178
9179 zone_t
zone_find_largest(uint64_t * zone_size)9180 zone_find_largest(uint64_t *zone_size)
9181 {
9182 zone_t largest_zone = 0;
9183 uint64_t largest_zone_size = 0;
9184 zone_find_n_largest(1, &largest_zone, &largest_zone_size);
9185 if (zone_size) {
9186 *zone_size = largest_zone_size;
9187 }
9188 return largest_zone;
9189 }
9190
9191 void
zone_get_stats(zone_t zone,struct zone_basic_stats * stats)9192 zone_get_stats(
9193 zone_t zone,
9194 struct zone_basic_stats *stats)
9195 {
9196 stats->zbs_avail = zone->z_elems_avail;
9197
9198 stats->zbs_alloc_fail = 0;
9199 zpercpu_foreach(zs, zone->z_stats) {
9200 stats->zbs_alloc_fail += zs->zs_alloc_fail;
9201 }
9202
9203 stats->zbs_cached = 0;
9204 if (zone->z_pcpu_cache) {
9205 zpercpu_foreach(zc, zone->z_pcpu_cache) {
9206 stats->zbs_cached += zc->zc_alloc_cur +
9207 zc->zc_free_cur +
9208 zc->zc_depot.zd_full * zc_mag_size();
9209 }
9210 }
9211
9212 stats->zbs_free = zone_count_free(zone) + stats->zbs_cached;
9213
9214 /*
9215 * Since we don't take any locks, deal with possible inconsistencies
9216 * as the counters may have changed.
9217 */
9218 if (os_sub_overflow(stats->zbs_avail, stats->zbs_free,
9219 &stats->zbs_alloc)) {
9220 stats->zbs_avail = stats->zbs_free;
9221 stats->zbs_alloc = 0;
9222 }
9223 }
9224
9225 #endif /* !ZALLOC_TEST */
9226 #pragma mark zone creation, configuration, destruction
9227 #if !ZALLOC_TEST
9228
9229 static zone_t
zone_init_defaults(zone_id_t zid)9230 zone_init_defaults(zone_id_t zid)
9231 {
9232 zone_t z = &zone_array[zid];
9233
9234 z->z_wired_max = ~0u;
9235 z->collectable = true;
9236
9237 hw_lck_ticket_init(&z->z_lock, &zone_locks_grp);
9238 hw_lck_ticket_init(&z->z_recirc_lock, &zone_locks_grp);
9239 zone_depot_init(&z->z_recirc);
9240 return z;
9241 }
9242
9243 void
zone_set_exhaustible(zone_t zone,vm_size_t nelems,bool exhausts_by_design)9244 zone_set_exhaustible(zone_t zone, vm_size_t nelems, bool exhausts_by_design)
9245 {
9246 zone_lock(zone);
9247 zone->z_wired_max = zone_alloc_pages_for_nelems(zone, nelems);
9248 zone->z_exhausts = exhausts_by_design;
9249 zone_unlock(zone);
9250 }
9251
9252 void
zone_raise_reserve(union zone_or_view zov,uint16_t min_elements)9253 zone_raise_reserve(union zone_or_view zov, uint16_t min_elements)
9254 {
9255 zone_t zone = zov.zov_zone;
9256
9257 if (zone < zone_array || zone > &zone_array[MAX_ZONES]) {
9258 zone = zov.zov_view->zv_zone;
9259 } else {
9260 zone = zov.zov_zone;
9261 }
9262
9263 os_atomic_max(&zone->z_elems_rsv, min_elements, relaxed);
9264 }
9265
9266 /**
9267 * @function zone_create_find
9268 *
9269 * @abstract
9270 * Finds an unused zone for the given name and element size.
9271 *
9272 * @param name the zone name
9273 * @param size the element size (including redzones, ...)
9274 * @param flags the flags passed to @c zone_create*
9275 * @param zid_inout the desired zone ID or ZONE_ID_ANY
9276 *
9277 * @returns a zone to initialize further.
9278 */
9279 static zone_t
zone_create_find(const char * name,vm_size_t size,zone_create_flags_t flags,zone_id_t * zid_inout)9280 zone_create_find(
9281 const char *name,
9282 vm_size_t size,
9283 zone_create_flags_t flags,
9284 zone_id_t *zid_inout)
9285 {
9286 zone_id_t nzones, zid = *zid_inout;
9287 zone_t z;
9288
9289 simple_lock(&all_zones_lock, &zone_locks_grp);
9290
9291 nzones = (zone_id_t)os_atomic_load(&num_zones, relaxed);
9292 assert(num_zones_in_use <= nzones && nzones < MAX_ZONES);
9293
9294 if (__improbable(nzones < ZONE_ID__FIRST_DYNAMIC)) {
9295 /*
9296 * The first time around, make sure the reserved zone IDs
9297 * have an initialized lock as zone_index_foreach() will
9298 * enumerate them.
9299 */
9300 while (nzones < ZONE_ID__FIRST_DYNAMIC) {
9301 zone_init_defaults(nzones++);
9302 }
9303
9304 os_atomic_store(&num_zones, nzones, release);
9305 }
9306
9307 if (zid != ZONE_ID_ANY) {
9308 if (zid >= ZONE_ID__FIRST_DYNAMIC) {
9309 panic("zone_create: invalid desired zone ID %d for %s",
9310 zid, name);
9311 }
9312 if (flags & ZC_DESTRUCTIBLE) {
9313 panic("zone_create: ID %d (%s) must be permanent", zid, name);
9314 }
9315 if (zone_array[zid].z_self) {
9316 panic("zone_create: creating zone ID %d (%s) twice", zid, name);
9317 }
9318 z = &zone_array[zid];
9319 } else {
9320 if (flags & ZC_DESTRUCTIBLE) {
9321 /*
9322 * If possible, find a previously zdestroy'ed zone in the
9323 * zone_array that we can reuse.
9324 */
9325 for (int i = bitmap_first(zone_destroyed_bitmap, MAX_ZONES);
9326 i >= 0; i = bitmap_next(zone_destroyed_bitmap, i)) {
9327 z = &zone_array[i];
9328
9329 /*
9330 * If the zone name and the element size are the
9331 * same, we can just reuse the old zone struct.
9332 */
9333 if (strcmp(z->z_name, name) ||
9334 zone_elem_outer_size(z) != size) {
9335 continue;
9336 }
9337 bitmap_clear(zone_destroyed_bitmap, i);
9338 z->z_destroyed = false;
9339 z->z_self = z;
9340 zid = (zone_id_t)i;
9341 goto out;
9342 }
9343 }
9344
9345 zid = nzones++;
9346 z = zone_init_defaults(zid);
9347
9348 /*
9349 * The release barrier pairs with the acquire in
9350 * zone_index_foreach() and makes sure that enumeration loops
9351 * always see an initialized zone lock.
9352 */
9353 os_atomic_store(&num_zones, nzones, release);
9354 }
9355
9356 out:
9357 num_zones_in_use++;
9358 simple_unlock(&all_zones_lock);
9359
9360 *zid_inout = zid;
9361 return z;
9362 }
9363
9364 __abortlike
9365 static void
zone_create_panic(const char * name,const char * f1,const char * f2)9366 zone_create_panic(const char *name, const char *f1, const char *f2)
9367 {
9368 panic("zone_create: creating zone %s: flag %s and %s are incompatible",
9369 name, f1, f2);
9370 }
9371 #define zone_create_assert_not_both(name, flags, current_flag, forbidden_flag) \
9372 if ((flags) & forbidden_flag) { \
9373 zone_create_panic(name, #current_flag, #forbidden_flag); \
9374 }
9375
9376 /*
9377 * Adjusts the size of the element based on minimum size, alignment
9378 * and kasan redzones
9379 */
9380 static vm_size_t
zone_elem_adjust_size(const char * name __unused,vm_size_t elem_size,zone_create_flags_t flags __unused,uint16_t * redzone __unused)9381 zone_elem_adjust_size(
9382 const char *name __unused,
9383 vm_size_t elem_size,
9384 zone_create_flags_t flags __unused,
9385 uint16_t *redzone __unused)
9386 {
9387 vm_size_t size;
9388
9389 /*
9390 * Adjust element size for minimum size and pointer alignment
9391 */
9392 size = (elem_size + ZONE_ALIGN_SIZE - 1) & -ZONE_ALIGN_SIZE;
9393 if (size < ZONE_MIN_ELEM_SIZE) {
9394 size = ZONE_MIN_ELEM_SIZE;
9395 }
9396
9397 #if KASAN_CLASSIC
9398 /*
9399 * Expand the zone allocation size to include the redzones.
9400 *
9401 * For page-multiple zones add a full guard page because they
9402 * likely require alignment.
9403 */
9404 uint16_t redzone_tmp;
9405 if (flags & (ZC_KASAN_NOREDZONE | ZC_PERCPU | ZC_OBJ_CACHE)) {
9406 redzone_tmp = 0;
9407 } else if ((size & PAGE_MASK) == 0) {
9408 if (size != PAGE_SIZE && (flags & ZC_ALIGNMENT_REQUIRED)) {
9409 panic("zone_create: zone %s can't provide more than PAGE_SIZE"
9410 "alignment", name);
9411 }
9412 redzone_tmp = PAGE_SIZE;
9413 } else if (flags & ZC_ALIGNMENT_REQUIRED) {
9414 redzone_tmp = 0;
9415 } else {
9416 redzone_tmp = KASAN_GUARD_SIZE;
9417 }
9418 size += redzone_tmp;
9419 if (redzone) {
9420 *redzone = redzone_tmp;
9421 }
9422 #endif
9423 return size;
9424 }
9425
9426 /*
9427 * Returns the allocation chunk size that has least framentation
9428 */
9429 static vm_size_t
zone_get_min_alloc_granule(vm_size_t elem_size,zone_create_flags_t flags)9430 zone_get_min_alloc_granule(
9431 vm_size_t elem_size,
9432 zone_create_flags_t flags)
9433 {
9434 vm_size_t alloc_granule = PAGE_SIZE;
9435 if (flags & ZC_PERCPU) {
9436 alloc_granule = PAGE_SIZE * zpercpu_count();
9437 if (PAGE_SIZE % elem_size > 256) {
9438 panic("zone_create: per-cpu zone has too much fragmentation");
9439 }
9440 } else if (flags & ZC_READONLY) {
9441 alloc_granule = PAGE_SIZE;
9442 } else if ((elem_size & PAGE_MASK) == 0) {
9443 /* zero fragmentation by definition */
9444 alloc_granule = elem_size;
9445 } else if (alloc_granule % elem_size == 0) {
9446 /* zero fragmentation by definition */
9447 } else {
9448 vm_size_t frag = (alloc_granule % elem_size) * 100 / alloc_granule;
9449 vm_size_t alloc_tmp = PAGE_SIZE;
9450 vm_size_t max_chunk_size = ZONE_MAX_ALLOC_SIZE;
9451
9452 #if __arm64__
9453 /*
9454 * Increase chunk size to 48K for sizes larger than 4K on 16k
9455 * machines, so as to reduce internal fragementation for kalloc
9456 * zones with sizes 12K and 24K.
9457 */
9458 if (elem_size > 4 * 1024 && PAGE_SIZE == 16 * 1024) {
9459 max_chunk_size = 48 * 1024;
9460 }
9461 #endif
9462 while ((alloc_tmp += PAGE_SIZE) <= max_chunk_size) {
9463 vm_size_t frag_tmp = (alloc_tmp % elem_size) * 100 / alloc_tmp;
9464 if (frag_tmp < frag) {
9465 frag = frag_tmp;
9466 alloc_granule = alloc_tmp;
9467 }
9468 }
9469 }
9470 return alloc_granule;
9471 }
9472
9473 vm_size_t
zone_get_early_alloc_size(const char * name __unused,vm_size_t elem_size,zone_create_flags_t flags,vm_size_t min_elems)9474 zone_get_early_alloc_size(
9475 const char *name __unused,
9476 vm_size_t elem_size,
9477 zone_create_flags_t flags,
9478 vm_size_t min_elems)
9479 {
9480 vm_size_t adjusted_size, alloc_granule, chunk_elems;
9481
9482 adjusted_size = zone_elem_adjust_size(name, elem_size, flags, NULL);
9483 alloc_granule = zone_get_min_alloc_granule(adjusted_size, flags);
9484 chunk_elems = alloc_granule / adjusted_size;
9485
9486 return ((min_elems + chunk_elems - 1) / chunk_elems) * alloc_granule;
9487 }
9488
9489 zone_t
9490 zone_create_ext(
9491 const char *name,
9492 vm_size_t size,
9493 zone_create_flags_t flags,
9494 zone_id_t zid,
9495 void (^extra_setup)(zone_t))
9496 {
9497 zone_security_flags_t *zsflags;
9498 uint16_t redzone;
9499 zone_t z;
9500
9501 if (size > ZONE_MAX_ALLOC_SIZE) {
9502 panic("zone_create: element size too large: %zd", (size_t)size);
9503 }
9504
9505 if (size < 2 * sizeof(vm_size_t)) {
9506 /* Elements are too small for kasan. */
9507 flags |= ZC_KASAN_NOQUARANTINE | ZC_KASAN_NOREDZONE;
9508 }
9509
9510 size = zone_elem_adjust_size(name, size, flags, &redzone);
9511
9512 /*
9513 * Allocate the zone slot, return early if we found an older match.
9514 */
9515 z = zone_create_find(name, size, flags, &zid);
9516 if (__improbable(z->z_self)) {
9517 /* We found a zone to reuse */
9518 return z;
9519 }
9520 zsflags = &zone_security_array[zid];
9521
9522 /*
9523 * Initialize the zone properly.
9524 */
9525
9526 /*
9527 * If the kernel is post lockdown, copy the zone name passed in.
9528 * Else simply maintain a pointer to the name string as it can only
9529 * be a core XNU zone (no unloadable kext exists before lockdown).
9530 */
9531 if (startup_phase >= STARTUP_SUB_LOCKDOWN) {
9532 size_t nsz = MIN(strlen(name) + 1, MACH_ZONE_NAME_MAX_LEN);
9533 char *buf = zalloc_permanent(nsz, ZALIGN_NONE);
9534 strlcpy(buf, name, nsz);
9535 z->z_name = buf;
9536 } else {
9537 z->z_name = name;
9538 }
9539 if (__probable(zone_array[ZONE_ID_PERCPU_PERMANENT].z_self)) {
9540 z->z_stats = zalloc_percpu_permanent_type(struct zone_stats);
9541 } else {
9542 /*
9543 * zone_init() hasn't run yet, use the storage provided by
9544 * zone_stats_startup(), and zone_init() will replace it
9545 * with the final value once the PERCPU zone exists.
9546 */
9547 z->z_stats = __zpcpu_mangle_for_boot(&zone_stats_startup[zone_index(z)]);
9548 }
9549
9550 if (flags & ZC_OBJ_CACHE) {
9551 zone_create_assert_not_both(name, flags, ZC_OBJ_CACHE, ZC_NOCACHING);
9552 zone_create_assert_not_both(name, flags, ZC_OBJ_CACHE, ZC_PERCPU);
9553 zone_create_assert_not_both(name, flags, ZC_OBJ_CACHE, ZC_NOGC);
9554 zone_create_assert_not_both(name, flags, ZC_OBJ_CACHE, ZC_DESTRUCTIBLE);
9555
9556 z->z_elem_size = (uint16_t)size;
9557 z->z_chunk_pages = 0;
9558 z->z_quo_magic = 0;
9559 z->z_align_magic = 0;
9560 z->z_chunk_elems = 0;
9561 z->z_elem_offs = 0;
9562 z->no_callout = true;
9563 zsflags->z_lifo = true;
9564 } else {
9565 vm_size_t alloc = zone_get_min_alloc_granule(size, flags);
9566
9567 z->z_elem_size = (uint16_t)(size - redzone);
9568 z->z_chunk_pages = (uint16_t)atop(alloc);
9569 z->z_quo_magic = Z_MAGIC_QUO(size);
9570 z->z_align_magic = Z_MAGIC_ALIGNED(size);
9571 if (flags & ZC_PERCPU) {
9572 z->z_chunk_elems = (uint16_t)(PAGE_SIZE / size);
9573 z->z_elem_offs = (uint16_t)(PAGE_SIZE % size) + redzone;
9574 } else {
9575 z->z_chunk_elems = (uint16_t)(alloc / size);
9576 z->z_elem_offs = (uint16_t)(alloc % size) + redzone;
9577 }
9578 }
9579
9580 /*
9581 * Handle KPI flags
9582 */
9583
9584 /* ZC_CACHING applied after all configuration is done */
9585 if (flags & ZC_NOCACHING) {
9586 z->z_nocaching = true;
9587 }
9588
9589 if (flags & ZC_READONLY) {
9590 zone_create_assert_not_both(name, flags, ZC_READONLY, ZC_VM);
9591 zone_create_assert_not_both(name, flags, ZC_READONLY, ZC_DATA);
9592 assert(zid <= ZONE_ID__LAST_RO);
9593 #if ZSECURITY_CONFIG(READ_ONLY)
9594 zsflags->z_submap_idx = Z_SUBMAP_IDX_READ_ONLY;
9595 #endif
9596 zone_ro_size_params[zid].z_elem_size = z->z_elem_size;
9597 zone_ro_size_params[zid].z_align_magic = z->z_align_magic;
9598 assert(size <= PAGE_SIZE);
9599 if ((PAGE_SIZE % size) * 10 >= PAGE_SIZE) {
9600 panic("Fragmentation greater than 10%% with elem size %d zone %s%s",
9601 (uint32_t)size, zone_heap_name(z), z->z_name);
9602 }
9603 }
9604
9605 if (flags & ZC_PERCPU) {
9606 zone_create_assert_not_both(name, flags, ZC_PERCPU, ZC_READONLY);
9607 zone_create_assert_not_both(name, flags, ZC_PERCPU, ZC_PGZ_USE_GUARDS);
9608 z->z_percpu = true;
9609 }
9610 if (flags & ZC_NOGC) {
9611 z->collectable = false;
9612 }
9613 /*
9614 * Handle ZC_NOENCRYPT from xnu only
9615 */
9616 if (startup_phase < STARTUP_SUB_LOCKDOWN && flags & ZC_NOENCRYPT) {
9617 zsflags->z_noencrypt = true;
9618 }
9619 if (flags & ZC_NOCALLOUT) {
9620 z->no_callout = true;
9621 }
9622 if (flags & ZC_DESTRUCTIBLE) {
9623 zone_create_assert_not_both(name, flags, ZC_DESTRUCTIBLE, ZC_READONLY);
9624 z->z_destructible = true;
9625 }
9626 /*
9627 * Handle Internal flags
9628 */
9629 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
9630 if (flags & ZC_PGZ_USE_GUARDS) {
9631 /*
9632 * Try to turn on guard pages only for zones
9633 * with a chance of OOB.
9634 */
9635 if (startup_phase < STARTUP_SUB_LOCKDOWN) {
9636 zsflags->z_pgz_use_guards = true;
9637 }
9638 z->z_pgz_use_guards = true;
9639 }
9640 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
9641
9642 #if ZSECURITY_CONFIG(ZONE_TAGGING)
9643 if ((flags & ZC_NO_TBI_TAG)) {
9644 zsflags->z_tag = false;
9645 }
9646
9647 #endif /* ZSECURITY_CONFIG(ZONE_TAGGING) */
9648
9649 if (flags & ZC_KALLOC_TYPE) {
9650 zsflags->z_kalloc_type = true;
9651 }
9652 if (flags & ZC_VM) {
9653 zone_create_assert_not_both(name, flags, ZC_VM, ZC_DATA);
9654 zsflags->z_submap_idx = Z_SUBMAP_IDX_VM;
9655 }
9656 if (flags & ZC_DATA) {
9657 zsflags->z_kheap_id = KHEAP_ID_DATA_BUFFERS;
9658 }
9659 #if KASAN_CLASSIC
9660 if (redzone && !(flags & ZC_KASAN_NOQUARANTINE)) {
9661 z->z_kasan_quarantine = true;
9662 }
9663 z->z_kasan_redzone = redzone;
9664 #endif /* KASAN_CLASSIC */
9665 #if KASAN_FAKESTACK
9666 if (strncmp(name, "fakestack.", sizeof("fakestack.") - 1) == 0) {
9667 z->z_kasan_fakestacks = true;
9668 }
9669 #endif /* KASAN_FAKESTACK */
9670
9671 /*
9672 * Then if there's extra tuning, do it
9673 */
9674 if (extra_setup) {
9675 extra_setup(z);
9676 }
9677
9678 /*
9679 * Configure debugging features
9680 */
9681 #if CONFIG_PROB_GZALLOC
9682 if ((flags & (ZC_READONLY | ZC_PERCPU | ZC_OBJ_CACHE | ZC_NOPGZ)) == 0) {
9683 pgz_zone_init(z);
9684 }
9685 #endif
9686 if (zc_magazine_zone) { /* proxy for "has zone_init run" */
9687 #if ZALLOC_ENABLE_LOGGING
9688 /*
9689 * Check for and set up zone leak detection
9690 * if requested via boot-args.
9691 */
9692 zone_setup_logging(z);
9693 #endif /* ZALLOC_ENABLE_LOGGING */
9694 #if KASAN_TBI
9695 zone_setup_kasan_logging(z);
9696 #endif /* KASAN_TBI */
9697 }
9698
9699 #if VM_TAG_SIZECLASSES
9700 if ((zsflags->z_kheap_id || zsflags->z_kalloc_type) && zone_tagging_on) {
9701 static uint16_t sizeclass_idx;
9702
9703 assert(startup_phase < STARTUP_SUB_LOCKDOWN);
9704 z->z_uses_tags = true;
9705 if (zsflags->z_kheap_id == KHEAP_ID_DATA_BUFFERS) {
9706 zone_tags_sizeclasses[sizeclass_idx] = (uint16_t)size;
9707 z->z_tags_sizeclass = sizeclass_idx++;
9708 } else {
9709 uint16_t i = 0;
9710 for (; i < sizeclass_idx; i++) {
9711 if (size == zone_tags_sizeclasses[i]) {
9712 z->z_tags_sizeclass = i;
9713 break;
9714 }
9715 }
9716
9717 /*
9718 * Size class wasn't found, add it to zone_tags_sizeclasses
9719 */
9720 if (i == sizeclass_idx) {
9721 assert(i < VM_TAG_SIZECLASSES);
9722 zone_tags_sizeclasses[i] = (uint16_t)size;
9723 z->z_tags_sizeclass = sizeclass_idx++;
9724 }
9725 }
9726 assert(z->z_tags_sizeclass < VM_TAG_SIZECLASSES);
9727 }
9728 #endif
9729
9730 /*
9731 * Finally, fixup properties based on security policies, boot-args, ...
9732 */
9733 if (zsflags->z_kheap_id == KHEAP_ID_DATA_BUFFERS) {
9734 /*
9735 * We use LIFO in the data map, because workloads like network
9736 * usage or similar tend to rotate through allocations very
9737 * quickly with sometimes epxloding working-sets and using
9738 * a FIFO policy might cause massive TLB trashing with rather
9739 * dramatic performance impacts.
9740 */
9741 zsflags->z_submap_idx = Z_SUBMAP_IDX_DATA;
9742 zsflags->z_lifo = true;
9743 }
9744
9745 if ((flags & (ZC_CACHING | ZC_OBJ_CACHE)) && !z->z_nocaching) {
9746 /*
9747 * No zone made before zone_init() can have ZC_CACHING set.
9748 */
9749 assert(zc_magazine_zone);
9750 zone_enable_caching(z);
9751 }
9752
9753 zone_lock(z);
9754 z->z_self = z;
9755 zone_unlock(z);
9756
9757 return z;
9758 }
9759
9760 void
zone_set_sig_eq(zone_t zone,zone_id_t sig_eq)9761 zone_set_sig_eq(zone_t zone, zone_id_t sig_eq)
9762 {
9763 zone_security_array[zone_index(zone)].z_sig_eq = sig_eq;
9764 }
9765
9766 zone_id_t
zone_get_sig_eq(zone_t zone)9767 zone_get_sig_eq(zone_t zone)
9768 {
9769 return zone_security_array[zone_index(zone)].z_sig_eq;
9770 }
9771
9772 void
zone_enable_smr(zone_t zone,struct smr * smr,zone_smr_free_cb_t free_cb)9773 zone_enable_smr(zone_t zone, struct smr *smr, zone_smr_free_cb_t free_cb)
9774 {
9775 /* moving to SMR must be done before the zone has ever been used */
9776 assert(zone->z_va_cur == 0 && !zone->z_smr && !zone->z_nocaching);
9777 assert(!zone_security_array[zone_index(zone)].z_lifo);
9778 assert((smr->smr_flags & SMR_SLEEPABLE) == 0);
9779
9780 if (!zone->z_pcpu_cache) {
9781 zone_enable_caching(zone);
9782 }
9783
9784 zone_lock(zone);
9785
9786 zpercpu_foreach(it, zone->z_pcpu_cache) {
9787 it->zc_smr = smr;
9788 it->zc_free = free_cb;
9789 }
9790 zone->z_smr = true;
9791
9792 zone_unlock(zone);
9793 }
9794
9795 __startup_func
9796 void
zone_create_startup(struct zone_create_startup_spec * spec)9797 zone_create_startup(struct zone_create_startup_spec *spec)
9798 {
9799 zone_t z;
9800
9801 z = zone_create_ext(spec->z_name, spec->z_size,
9802 spec->z_flags, spec->z_zid, spec->z_setup);
9803 if (spec->z_var) {
9804 *spec->z_var = z;
9805 }
9806 }
9807
9808 /*
9809 * The 4 first field of a zone_view and a zone alias, so that the zone_or_view_t
9810 * union works. trust but verify.
9811 */
9812 #define zalloc_check_zov_alias(f1, f2) \
9813 static_assert(offsetof(struct zone, f1) == offsetof(struct zone_view, f2))
9814 zalloc_check_zov_alias(z_self, zv_zone);
9815 zalloc_check_zov_alias(z_stats, zv_stats);
9816 zalloc_check_zov_alias(z_name, zv_name);
9817 zalloc_check_zov_alias(z_views, zv_next);
9818 #undef zalloc_check_zov_alias
9819
9820 __startup_func
9821 void
zone_view_startup_init(struct zone_view_startup_spec * spec)9822 zone_view_startup_init(struct zone_view_startup_spec *spec)
9823 {
9824 struct kalloc_heap *heap = NULL;
9825 zone_view_t zv = spec->zv_view;
9826 zone_t z;
9827 zone_security_flags_t zsflags;
9828
9829 switch (spec->zv_heapid) {
9830 case KHEAP_ID_DATA_BUFFERS:
9831 heap = KHEAP_DATA_BUFFERS;
9832 break;
9833 default:
9834 heap = NULL;
9835 }
9836
9837 if (heap) {
9838 z = kalloc_zone_for_size(heap->kh_zstart, spec->zv_size);
9839 } else {
9840 z = *spec->zv_zone;
9841 assert(spec->zv_size <= zone_elem_inner_size(z));
9842 }
9843
9844 assert(z);
9845
9846 zv->zv_zone = z;
9847 zv->zv_stats = zalloc_percpu_permanent_type(struct zone_stats);
9848 zv->zv_next = z->z_views;
9849 zsflags = zone_security_config(z);
9850 if (z->z_views == NULL && zsflags.z_kheap_id == KHEAP_ID_NONE) {
9851 /*
9852 * count the raw view for zones not in a heap,
9853 * kalloc_heap_init() already counts it for its members.
9854 */
9855 zone_view_count += 2;
9856 } else {
9857 zone_view_count += 1;
9858 }
9859 z->z_views = zv;
9860 }
9861
9862 zone_t
zone_create(const char * name,vm_size_t size,zone_create_flags_t flags)9863 zone_create(
9864 const char *name,
9865 vm_size_t size,
9866 zone_create_flags_t flags)
9867 {
9868 return zone_create_ext(name, size, flags, ZONE_ID_ANY, NULL);
9869 }
9870
9871 vm_size_t
zone_get_elem_size(zone_t zone)9872 zone_get_elem_size(zone_t zone)
9873 {
9874 return zone->z_elem_size;
9875 }
9876
9877 static_assert(ZONE_ID__LAST_RO_EXT - ZONE_ID__FIRST_RO_EXT == ZC_RO_ID__LAST);
9878
9879 zone_id_t
zone_create_ro(const char * name,vm_size_t size,zone_create_flags_t flags,zone_create_ro_id_t zc_ro_id)9880 zone_create_ro(
9881 const char *name,
9882 vm_size_t size,
9883 zone_create_flags_t flags,
9884 zone_create_ro_id_t zc_ro_id)
9885 {
9886 assert(zc_ro_id <= ZC_RO_ID__LAST);
9887 zone_id_t reserved_zid = ZONE_ID__FIRST_RO_EXT + zc_ro_id;
9888 (void)zone_create_ext(name, size, ZC_READONLY | flags, reserved_zid, NULL);
9889 return reserved_zid;
9890 }
9891
9892 zone_t
zinit(vm_size_t size,vm_size_t max __unused,vm_size_t alloc __unused,const char * name)9893 zinit(
9894 vm_size_t size, /* the size of an element */
9895 vm_size_t max __unused, /* maximum memory to use */
9896 vm_size_t alloc __unused, /* allocation size */
9897 const char *name) /* a name for the zone */
9898 {
9899 return zone_create(name, size, ZC_DESTRUCTIBLE);
9900 }
9901
9902 void
zdestroy(zone_t z)9903 zdestroy(zone_t z)
9904 {
9905 unsigned int zindex = zone_index(z);
9906 zone_security_flags_t zsflags = zone_security_array[zindex];
9907
9908 current_thread()->options |= TH_OPT_ZONE_PRIV;
9909 lck_mtx_lock(&zone_gc_lock);
9910
9911 zone_reclaim(z, ZONE_RECLAIM_DESTROY);
9912
9913 lck_mtx_unlock(&zone_gc_lock);
9914 current_thread()->options &= ~TH_OPT_ZONE_PRIV;
9915
9916 zone_lock(z);
9917
9918 if (!zone_submap_is_sequestered(zsflags)) {
9919 while (!zone_pva_is_null(z->z_pageq_va)) {
9920 struct zone_page_metadata *meta;
9921
9922 zone_counter_sub(z, z_va_cur, z->z_percpu ? 1 : z->z_chunk_pages);
9923 meta = zone_meta_queue_pop(z, &z->z_pageq_va);
9924 assert(meta->zm_chunk_len <= ZM_CHUNK_LEN_MAX);
9925 bzero(meta, sizeof(*meta) * z->z_chunk_pages);
9926 zone_unlock(z);
9927 kmem_free(zone_submap(zsflags), zone_meta_to_addr(meta),
9928 ptoa(z->z_chunk_pages));
9929 zone_lock(z);
9930 }
9931 }
9932
9933 #if !KASAN_CLASSIC
9934 /* Assert that all counts are zero */
9935 if (z->z_elems_avail || z->z_elems_free || zone_size_wired(z) ||
9936 (z->z_va_cur && !zone_submap_is_sequestered(zsflags))) {
9937 panic("zdestroy: Zone %s%s isn't empty at zdestroy() time",
9938 zone_heap_name(z), z->z_name);
9939 }
9940
9941 /* consistency check: make sure everything is indeed empty */
9942 assert(zone_pva_is_null(z->z_pageq_empty));
9943 assert(zone_pva_is_null(z->z_pageq_partial));
9944 assert(zone_pva_is_null(z->z_pageq_full));
9945 if (!zone_submap_is_sequestered(zsflags)) {
9946 assert(zone_pva_is_null(z->z_pageq_va));
9947 }
9948 #endif
9949
9950 zone_unlock(z);
9951
9952 simple_lock(&all_zones_lock, &zone_locks_grp);
9953
9954 assert(!bitmap_test(zone_destroyed_bitmap, zindex));
9955 /* Mark the zone as empty in the bitmap */
9956 bitmap_set(zone_destroyed_bitmap, zindex);
9957 num_zones_in_use--;
9958 assert(num_zones_in_use > 0);
9959
9960 simple_unlock(&all_zones_lock);
9961 }
9962
9963 #endif /* !ZALLOC_TEST */
9964 #pragma mark zalloc module init
9965 #if !ZALLOC_TEST
9966
9967 /*
9968 * Initialize the "zone of zones" which uses fixed memory allocated
9969 * earlier in memory initialization. zone_bootstrap is called
9970 * before zone_init.
9971 */
9972 __startup_func
9973 void
zone_bootstrap(void)9974 zone_bootstrap(void)
9975 {
9976 #if DEBUG || DEVELOPMENT
9977 #if __x86_64__
9978 if (PE_parse_boot_argn("kernPOST", NULL, 0)) {
9979 /*
9980 * rdar://79781535 Disable early gaps while running kernPOST on Intel
9981 * the fp faulting code gets triggered and deadlocks.
9982 */
9983 zone_caching_disabled = 1;
9984 }
9985 #endif /* __x86_64__ */
9986 #endif /* DEBUG || DEVELOPMENT */
9987
9988 /* Validate struct zone_packed_virtual_address expectations */
9989 static_assert((intptr_t)VM_MIN_KERNEL_ADDRESS < 0, "the top bit must be 1");
9990 if (VM_KERNEL_POINTER_SIGNIFICANT_BITS - PAGE_SHIFT > 31) {
9991 panic("zone_pva_t can't pack a kernel page address in 31 bits");
9992 }
9993
9994 zpercpu_early_count = ml_early_cpu_max_number() + 1;
9995 if (!PE_parse_boot_argn("zc_mag_size", NULL, 0)) {
9996 /*
9997 * Scale zc_mag_size() per machine.
9998 *
9999 * - wide machines get 128B magazines to avoid all false sharing
10000 * - smaller machines but with enough RAM get a bit bigger
10001 * buckets (empirically affects networking performance)
10002 */
10003 if (zpercpu_early_count >= 10) {
10004 _zc_mag_size = 14;
10005 } else if ((sane_size >> 30) >= 4) {
10006 _zc_mag_size = 10;
10007 }
10008 }
10009
10010 /*
10011 * Initialize random used to scramble early allocations
10012 */
10013 zpercpu_foreach_cpu(cpu) {
10014 random_bool_init(&zone_bool_gen[cpu].zbg_bg);
10015 }
10016
10017 #if CONFIG_PROB_GZALLOC
10018 /*
10019 * Set pgz_sample_counter on the boot CPU so that we do not sample
10020 * any allocation until PGZ has been properly setup (in pgz_init()).
10021 */
10022 *PERCPU_GET_MASTER(pgz_sample_counter) = INT32_MAX;
10023 #endif /* CONFIG_PROB_GZALLOC */
10024
10025 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
10026 /*
10027 * Randomly assign zones to one of the 4 general submaps,
10028 * and pick whether they allocate from the begining
10029 * or the end of it.
10030 *
10031 * A lot of OOB exploitation relies on precise interleaving
10032 * of specific types in the heap.
10033 *
10034 * Woops, you can't guarantee that anymore.
10035 */
10036 for (zone_id_t i = 1; i < MAX_ZONES; i++) {
10037 uint32_t r = zalloc_random_uniform32(0,
10038 ZSECURITY_CONFIG_GENERAL_SUBMAPS * 2);
10039
10040 zone_security_array[i].z_submap_from_end = (r & 1);
10041 zone_security_array[i].z_submap_idx += (r >> 1);
10042 }
10043 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
10044
10045
10046 thread_call_setup_with_options(&zone_expand_callout,
10047 zone_expand_async, NULL, THREAD_CALL_PRIORITY_HIGH,
10048 THREAD_CALL_OPTIONS_ONCE);
10049
10050 thread_call_setup_with_options(&zone_trim_callout,
10051 zone_trim_async, NULL, THREAD_CALL_PRIORITY_USER,
10052 THREAD_CALL_OPTIONS_ONCE);
10053 }
10054
10055 #define ZONE_GUARD_SIZE (64UL << 10)
10056
10057 __startup_func
10058 static void
zone_tunables_fixup(void)10059 zone_tunables_fixup(void)
10060 {
10061 int wdt = 0;
10062
10063 #if CONFIG_PROB_GZALLOC && (DEVELOPMENT || DEBUG)
10064 if (!PE_parse_boot_argn("pgz", NULL, 0) &&
10065 PE_parse_boot_argn("pgz1", NULL, 0)) {
10066 /*
10067 * if pgz1= was used, but pgz= was not,
10068 * then the more specific pgz1 takes precedence.
10069 */
10070 pgz_all = false;
10071 }
10072 #endif
10073
10074 if (zone_map_jetsam_limit == 0 || zone_map_jetsam_limit > 100) {
10075 zone_map_jetsam_limit = ZONE_MAP_JETSAM_LIMIT_DEFAULT;
10076 }
10077 if (PE_parse_boot_argn("wdt", &wdt, sizeof(wdt)) && wdt == -1 &&
10078 !PE_parse_boot_argn("zet", NULL, 0)) {
10079 zone_exhausted_timeout = -1;
10080 }
10081 }
10082 STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, zone_tunables_fixup);
10083
10084 __startup_func
10085 static void
zone_submap_init(mach_vm_offset_t * submap_min,zone_submap_idx_t idx,uint64_t zone_sub_map_numer,uint64_t * remaining_denom,vm_offset_t * remaining_size)10086 zone_submap_init(
10087 mach_vm_offset_t *submap_min,
10088 zone_submap_idx_t idx,
10089 uint64_t zone_sub_map_numer,
10090 uint64_t *remaining_denom,
10091 vm_offset_t *remaining_size)
10092 {
10093 vm_map_create_options_t vmco;
10094 vm_map_address_t addr;
10095 vm_offset_t submap_start, submap_end;
10096 vm_size_t submap_size;
10097 vm_map_t submap;
10098 vm_prot_t prot = VM_PROT_DEFAULT;
10099 vm_prot_t prot_max = VM_PROT_ALL;
10100 kern_return_t kr;
10101
10102 submap_size = trunc_page(zone_sub_map_numer * *remaining_size /
10103 *remaining_denom);
10104 submap_start = *submap_min;
10105
10106 if (idx == Z_SUBMAP_IDX_READ_ONLY) {
10107 vm_offset_t submap_padding = pmap_ro_zone_align(submap_start) - submap_start;
10108 submap_start += submap_padding;
10109 submap_size = pmap_ro_zone_align(submap_size);
10110 assert(*remaining_size >= (submap_padding + submap_size));
10111 *remaining_size -= submap_padding;
10112 *submap_min = submap_start;
10113 }
10114
10115 submap_end = submap_start + submap_size;
10116 if (idx == Z_SUBMAP_IDX_VM) {
10117 vm_packing_verify_range("vm_compressor",
10118 submap_start, submap_end, VM_PACKING_PARAMS(C_SLOT_PACKED_PTR));
10119 vm_packing_verify_range("vm_page",
10120 submap_start, submap_end, VM_PACKING_PARAMS(VM_PAGE_PACKED_PTR));
10121 }
10122
10123 vmco = VM_MAP_CREATE_NEVER_FAULTS;
10124 if (!zone_submap_is_sequestered(idx)) {
10125 vmco |= VM_MAP_CREATE_DISABLE_HOLELIST;
10126 }
10127
10128 vm_map_will_allocate_early_map(&zone_submaps[idx]);
10129 submap = kmem_suballoc(kernel_map, submap_min, submap_size, vmco,
10130 VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, KMS_PERMANENT | KMS_NOFAIL,
10131 VM_KERN_MEMORY_ZONE).kmr_submap;
10132
10133 if (idx == Z_SUBMAP_IDX_READ_ONLY) {
10134 zone_info.zi_ro_range.min_address = submap_start;
10135 zone_info.zi_ro_range.max_address = submap_end;
10136 prot_max = prot = VM_PROT_NONE;
10137 }
10138
10139 addr = submap_start;
10140 vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_FIXED_PERMANENT(
10141 .vm_tag = VM_KERN_MEMORY_ZONE);
10142 vm_object_t kobject = kernel_object_default;
10143 kr = vm_map_enter(submap, &addr, ZONE_GUARD_SIZE / 2, 0,
10144 vmk_flags, kobject, addr, FALSE, prot, prot_max, VM_INHERIT_NONE);
10145 if (kr != KERN_SUCCESS) {
10146 panic("ksubmap[%s]: failed to make first entry (%d)",
10147 zone_submaps_names[idx], kr);
10148 }
10149
10150 addr = submap_end - ZONE_GUARD_SIZE / 2;
10151 kr = vm_map_enter(submap, &addr, ZONE_GUARD_SIZE / 2, 0,
10152 vmk_flags, kobject, addr, FALSE, prot, prot_max, VM_INHERIT_NONE);
10153 if (kr != KERN_SUCCESS) {
10154 panic("ksubmap[%s]: failed to make last entry (%d)",
10155 zone_submaps_names[idx], kr);
10156 }
10157
10158 #if DEBUG || DEVELOPMENT
10159 printf("zone_init: map %-5s %p:%p (%u%c)\n",
10160 zone_submaps_names[idx], (void *)submap_start, (void *)submap_end,
10161 mach_vm_size_pretty(submap_size), mach_vm_size_unit(submap_size));
10162 #endif /* DEBUG || DEVELOPMENT */
10163
10164 zone_submaps[idx] = submap;
10165 *submap_min = submap_end;
10166 *remaining_size -= submap_size;
10167 *remaining_denom -= zone_sub_map_numer;
10168 }
10169
10170 static inline void
zone_pva_relocate(zone_pva_t * pva,uint32_t delta)10171 zone_pva_relocate(zone_pva_t *pva, uint32_t delta)
10172 {
10173 if (!zone_pva_is_null(*pva) && !zone_pva_is_queue(*pva)) {
10174 pva->packed_address += delta;
10175 }
10176 }
10177
10178 /*
10179 * Allocate metadata array and migrate bootstrap initial metadata and memory.
10180 */
10181 __startup_func
10182 static void
zone_metadata_init(void)10183 zone_metadata_init(void)
10184 {
10185 vm_map_t vm_map = zone_submaps[Z_SUBMAP_IDX_VM];
10186 vm_map_entry_t first;
10187
10188 struct mach_vm_range meta_r, bits_r, xtra_r, early_r;
10189 vm_size_t early_sz;
10190 vm_offset_t reloc_base;
10191
10192 /*
10193 * Step 1: Allocate the metadata + bitmaps range
10194 *
10195 * Allocations can't be smaller than 8 bytes, which is 128b / 16B per 1k
10196 * of physical memory (16M per 1G).
10197 *
10198 * Let's preallocate for the worst to avoid weird panics.
10199 */
10200 vm_map_will_allocate_early_map(&zone_meta_map);
10201 meta_r = zone_kmem_suballoc(zone_info.zi_meta_range.min_address,
10202 zone_meta_size + zone_bits_size + zone_xtra_size,
10203 VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
10204 VM_KERN_MEMORY_ZONE, &zone_meta_map);
10205 meta_r.min_address += ZONE_GUARD_SIZE;
10206 meta_r.max_address -= ZONE_GUARD_SIZE;
10207 if (zone_xtra_size) {
10208 xtra_r.max_address = meta_r.max_address;
10209 meta_r.max_address -= zone_xtra_size;
10210 xtra_r.min_address = meta_r.max_address;
10211 } else {
10212 xtra_r.min_address = xtra_r.max_address = 0;
10213 }
10214 bits_r.max_address = meta_r.max_address;
10215 meta_r.max_address -= zone_bits_size;
10216 bits_r.min_address = meta_r.max_address;
10217
10218 #if DEBUG || DEVELOPMENT
10219 printf("zone_init: metadata %p:%p (%u%c)\n",
10220 (void *)meta_r.min_address, (void *)meta_r.max_address,
10221 mach_vm_size_pretty(mach_vm_range_size(&meta_r)),
10222 mach_vm_size_unit(mach_vm_range_size(&meta_r)));
10223 printf("zone_init: metabits %p:%p (%u%c)\n",
10224 (void *)bits_r.min_address, (void *)bits_r.max_address,
10225 mach_vm_size_pretty(mach_vm_range_size(&bits_r)),
10226 mach_vm_size_unit(mach_vm_range_size(&bits_r)));
10227 printf("zone_init: extra %p:%p (%u%c)\n",
10228 (void *)xtra_r.min_address, (void *)xtra_r.max_address,
10229 mach_vm_size_pretty(mach_vm_range_size(&xtra_r)),
10230 mach_vm_size_unit(mach_vm_range_size(&xtra_r)));
10231 #endif /* DEBUG || DEVELOPMENT */
10232
10233 bits_r.min_address = (bits_r.min_address + ZBA_CHUNK_SIZE - 1) & -ZBA_CHUNK_SIZE;
10234 bits_r.max_address = bits_r.max_address & -ZBA_CHUNK_SIZE;
10235
10236 /*
10237 * Step 2: Install new ranges.
10238 * Relocate metadata and bits.
10239 */
10240 early_r = zone_info.zi_map_range;
10241 early_sz = mach_vm_range_size(&early_r);
10242
10243 zone_info.zi_map_range = zone_map_range;
10244 zone_info.zi_meta_range = meta_r;
10245 zone_info.zi_bits_range = bits_r;
10246 zone_info.zi_xtra_range = xtra_r;
10247 zone_info.zi_meta_base = (struct zone_page_metadata *)meta_r.min_address -
10248 zone_pva_from_addr(zone_map_range.min_address).packed_address;
10249
10250 vm_map_lock(vm_map);
10251 first = vm_map_first_entry(vm_map);
10252 reloc_base = first->vme_end;
10253 first->vme_end += early_sz;
10254 vm_map->size += early_sz;
10255 vm_map_unlock(vm_map);
10256
10257 struct zone_page_metadata *early_meta = zone_early_meta_array_startup;
10258 struct zone_page_metadata *new_meta = zone_meta_from_addr(reloc_base);
10259 vm_offset_t reloc_delta = reloc_base - early_r.min_address;
10260 /* this needs to sign extend */
10261 uint32_t pva_delta = (uint32_t)((intptr_t)reloc_delta >> PAGE_SHIFT);
10262
10263 zone_meta_populate(reloc_base, early_sz);
10264 memcpy(new_meta, early_meta,
10265 atop(early_sz) * sizeof(struct zone_page_metadata));
10266 for (uint32_t i = 0; i < atop(early_sz); i++) {
10267 zone_pva_relocate(&new_meta[i].zm_page_next, pva_delta);
10268 zone_pva_relocate(&new_meta[i].zm_page_prev, pva_delta);
10269 }
10270
10271 static_assert(ZONE_ID_VM_MAP_ENTRY == ZONE_ID_VM_MAP + 1);
10272 static_assert(ZONE_ID_VM_MAP_HOLES == ZONE_ID_VM_MAP + 2);
10273
10274 for (zone_id_t zid = ZONE_ID_VM_MAP; zid <= ZONE_ID_VM_MAP_HOLES; zid++) {
10275 zone_pva_relocate(&zone_array[zid].z_pageq_partial, pva_delta);
10276 zone_pva_relocate(&zone_array[zid].z_pageq_full, pva_delta);
10277 }
10278
10279 zba_populate(0, false);
10280 memcpy(zba_base_header(), zba_chunk_startup, sizeof(zba_chunk_startup));
10281 zba_meta()->zbam_right = (uint32_t)atop(zone_bits_size);
10282
10283 /*
10284 * Step 3: Relocate the boostrap VM structs
10285 * (including rewriting their content).
10286 */
10287 kma_flags_t flags = KMA_KOBJECT | KMA_NOENCRYPT | KMA_NOFAIL;
10288
10289 #if ZSECURITY_CONFIG(ZONE_TAGGING)
10290 flags |= KMA_TAG;
10291 #endif /* ZSECURITY_CONFIG_ZONE_TAGGING */
10292
10293
10294 kernel_memory_populate(reloc_base, early_sz, flags,
10295 VM_KERN_MEMORY_OSFMK);
10296
10297 vm_memtag_disable_checking();
10298 __nosan_memcpy((void *)reloc_base, (void *)early_r.min_address, early_sz);
10299 vm_memtag_enable_checking();
10300
10301 #if ZSECURITY_CONFIG(ZONE_TAGGING)
10302 vm_memtag_relocate_tags(reloc_base, early_r.min_address, early_sz);
10303 #endif /* ZSECURITY_CONFIG_ZONE_TAGGING */
10304
10305 #if KASAN
10306 kasan_notify_address(reloc_base, early_sz);
10307 #endif /* KASAN */
10308
10309 vm_map_relocate_early_maps(reloc_delta);
10310
10311 for (uint32_t i = 0; i < atop(early_sz); i++) {
10312 zone_id_t zid = new_meta[i].zm_index;
10313 zone_t z = &zone_array[zid];
10314 vm_size_t esize = zone_elem_outer_size(z);
10315 vm_address_t base = reloc_base + ptoa(i) + zone_elem_inner_offs(z);
10316 vm_address_t addr;
10317
10318 if (new_meta[i].zm_chunk_len >= ZM_SECONDARY_PAGE) {
10319 continue;
10320 }
10321
10322 for (uint32_t eidx = 0; eidx < z->z_chunk_elems; eidx++) {
10323 if (zone_meta_is_free(&new_meta[i], eidx)) {
10324 continue;
10325 }
10326
10327 addr = vm_memtag_fixup_ptr(base + eidx * esize);
10328 #if KASAN_CLASSIC
10329 kasan_alloc(addr,
10330 zone_elem_inner_size(z), zone_elem_inner_size(z),
10331 zone_elem_redzone(z), false,
10332 __builtin_frame_address(0));
10333 #endif
10334 vm_map_relocate_early_elem(zid, addr, reloc_delta);
10335 }
10336 }
10337 }
10338
10339 __startup_data
10340 static uint16_t submap_ratios[Z_SUBMAP_IDX_COUNT] = {
10341 #if ZSECURITY_CONFIG(READ_ONLY)
10342 [Z_SUBMAP_IDX_VM] = 15,
10343 [Z_SUBMAP_IDX_READ_ONLY] = 5,
10344 #else
10345 [Z_SUBMAP_IDX_VM] = 20,
10346 #endif /* !ZSECURITY_CONFIG(READ_ONLY) */
10347 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
10348 [Z_SUBMAP_IDX_GENERAL_0] = 15,
10349 [Z_SUBMAP_IDX_GENERAL_1] = 15,
10350 [Z_SUBMAP_IDX_GENERAL_2] = 15,
10351 [Z_SUBMAP_IDX_GENERAL_3] = 15,
10352 [Z_SUBMAP_IDX_DATA] = 20,
10353 #else
10354 [Z_SUBMAP_IDX_GENERAL_0] = 60,
10355 [Z_SUBMAP_IDX_DATA] = 20,
10356 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
10357 };
10358
10359 __startup_func
10360 static inline uint16_t
zone_submap_ratios_denom(void)10361 zone_submap_ratios_denom(void)
10362 {
10363 uint16_t denom = 0;
10364
10365 for (unsigned idx = 0; idx < Z_SUBMAP_IDX_COUNT; idx++) {
10366 denom += submap_ratios[idx];
10367 }
10368
10369 assert(denom == 100);
10370
10371 return denom;
10372 }
10373
10374 __startup_func
10375 static inline vm_offset_t
zone_restricted_va_max(void)10376 zone_restricted_va_max(void)
10377 {
10378 vm_offset_t compressor_max = VM_PACKING_MAX_PACKABLE(C_SLOT_PACKED_PTR);
10379 vm_offset_t vm_page_max = VM_PACKING_MAX_PACKABLE(VM_PAGE_PACKED_PTR);
10380
10381 return trunc_page(MIN(compressor_max, vm_page_max));
10382 }
10383
10384 __startup_func
10385 static void
zone_set_map_sizes(void)10386 zone_set_map_sizes(void)
10387 {
10388 vm_size_t zsize;
10389 vm_size_t zsizearg;
10390
10391 /*
10392 * Compute the physical limits for the zone map
10393 */
10394
10395 if (PE_parse_boot_argn("zsize", &zsizearg, sizeof(zsizearg))) {
10396 zsize = zsizearg * (1024ULL * 1024);
10397 } else {
10398 /* Set target zone size as 1/4 of physical memory */
10399 zsize = (vm_size_t)(sane_size >> 2);
10400 zsize += zsize >> 1;
10401 }
10402
10403 if (zsize < CONFIG_ZONE_MAP_MIN) {
10404 zsize = CONFIG_ZONE_MAP_MIN; /* Clamp to min */
10405 }
10406 if (zsize > sane_size >> 1) {
10407 zsize = (vm_size_t)(sane_size >> 1); /* Clamp to half of RAM max */
10408 }
10409 if (zsizearg == 0 && zsize > ZONE_MAP_MAX) {
10410 /* if zsize boot-arg not present and zsize exceeds platform maximum, clip zsize */
10411 printf("NOTE: zonemap size reduced from 0x%lx to 0x%lx\n",
10412 (uintptr_t)zsize, (uintptr_t)ZONE_MAP_MAX);
10413 zsize = ZONE_MAP_MAX;
10414 }
10415
10416 zone_pages_wired_max = (uint32_t)atop(trunc_page(zsize));
10417
10418
10419 /*
10420 * Declare restrictions on zone max
10421 */
10422 vm_offset_t vm_submap_size = round_page(
10423 (submap_ratios[Z_SUBMAP_IDX_VM] * ZONE_MAP_VA_SIZE) /
10424 zone_submap_ratios_denom());
10425
10426 #if CONFIG_PROB_GZALLOC
10427 vm_submap_size += pgz_get_size();
10428 #endif /* CONFIG_PROB_GZALLOC */
10429 if (os_sub_overflow(zone_restricted_va_max(), vm_submap_size,
10430 &zone_map_range.min_address)) {
10431 zone_map_range.min_address = 0;
10432 }
10433
10434 zone_meta_size = round_page(atop(ZONE_MAP_VA_SIZE) *
10435 sizeof(struct zone_page_metadata)) + ZONE_GUARD_SIZE * 2;
10436
10437 static_assert(ZONE_MAP_MAX / (CHAR_BIT * KALLOC_MINSIZE) <=
10438 ZBA_PTR_MASK + 1);
10439 zone_bits_size = round_page(ptoa(zone_pages_wired_max) /
10440 (CHAR_BIT * KALLOC_MINSIZE));
10441
10442 #if VM_TAG_SIZECLASSES
10443 if (zone_tagging_on) {
10444 zba_xtra_shift = (uint8_t)fls(sizeof(vm_tag_t) - 1);
10445 }
10446 if (zba_xtra_shift) {
10447 /*
10448 * if we need the extra space range, then limit the size of the
10449 * bitmaps to something reasonable instead of a theoretical
10450 * worst case scenario of all zones being for the smallest
10451 * allocation granule, in order to avoid fake VA pressure on
10452 * other parts of the system.
10453 */
10454 zone_bits_size = round_page(zone_bits_size / 8);
10455 zone_xtra_size = round_page(zone_bits_size * CHAR_BIT << zba_xtra_shift);
10456 }
10457 #endif /* VM_TAG_SIZECLASSES */
10458 }
10459 STARTUP(KMEM, STARTUP_RANK_FIRST, zone_set_map_sizes);
10460
10461 /*
10462 * Can't use zone_info.zi_map_range at this point as it is being used to
10463 * store the range of early pmap memory that was stolen to bootstrap the
10464 * necessary VM zones.
10465 */
10466 KMEM_RANGE_REGISTER_STATIC(zones, &zone_map_range, ZONE_MAP_VA_SIZE);
10467 KMEM_RANGE_REGISTER_DYNAMIC(zone_meta, &zone_info.zi_meta_range, ^{
10468 return zone_meta_size + zone_bits_size + zone_xtra_size;
10469 });
10470
10471 /*
10472 * Global initialization of Zone Allocator.
10473 * Runs after zone_bootstrap.
10474 */
10475 __startup_func
10476 static void
zone_init(void)10477 zone_init(void)
10478 {
10479 vm_size_t remaining_size = ZONE_MAP_VA_SIZE;
10480 mach_vm_offset_t submap_min = 0;
10481 uint64_t denom = zone_submap_ratios_denom();
10482 /*
10483 * And now allocate the various pieces of VA and submaps.
10484 */
10485
10486 submap_min = zone_map_range.min_address;
10487
10488 #if CONFIG_PROB_GZALLOC
10489 vm_size_t pgz_size = pgz_get_size();
10490
10491 vm_map_will_allocate_early_map(&pgz_submap);
10492 zone_info.zi_pgz_range = zone_kmem_suballoc(submap_min, pgz_size,
10493 VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
10494 VM_KERN_MEMORY_ZONE, &pgz_submap);
10495
10496 submap_min += pgz_size;
10497 remaining_size -= pgz_size;
10498 #if DEBUG || DEVELOPMENT
10499 printf("zone_init: pgzalloc %p:%p (%u%c) [%d slots]\n",
10500 (void *)zone_info.zi_pgz_range.min_address,
10501 (void *)zone_info.zi_pgz_range.max_address,
10502 mach_vm_size_pretty(pgz_size), mach_vm_size_unit(pgz_size),
10503 pgz_slots);
10504 #endif /* DEBUG || DEVELOPMENT */
10505 #endif /* CONFIG_PROB_GZALLOC */
10506
10507 /*
10508 * Allocate the submaps
10509 */
10510 for (zone_submap_idx_t idx = 0; idx < Z_SUBMAP_IDX_COUNT; idx++) {
10511 if (submap_ratios[idx] == 0) {
10512 zone_submaps[idx] = VM_MAP_NULL;
10513 } else {
10514 zone_submap_init(&submap_min, idx, submap_ratios[idx],
10515 &denom, &remaining_size);
10516 }
10517 }
10518
10519 zone_metadata_init();
10520
10521 #if VM_TAG_SIZECLASSES
10522 if (zone_tagging_on) {
10523 vm_allocation_zones_init();
10524 }
10525 #endif /* VM_TAG_SIZECLASSES */
10526
10527 zone_create_flags_t kma_flags = ZC_NOCACHING | ZC_NOGC | ZC_NOCALLOUT |
10528 ZC_KASAN_NOQUARANTINE | ZC_KASAN_NOREDZONE | ZC_VM;
10529
10530 (void)zone_create_ext("vm.permanent", 1, kma_flags | ZC_NO_TBI_TAG,
10531 ZONE_ID_PERMANENT, ^(zone_t z) {
10532 z->z_permanent = true;
10533 z->z_elem_size = 1;
10534 });
10535 (void)zone_create_ext("vm.permanent.percpu", 1,
10536 kma_flags | ZC_PERCPU | ZC_NO_TBI_TAG, ZONE_ID_PERCPU_PERMANENT, ^(zone_t z) {
10537 z->z_permanent = true;
10538 z->z_elem_size = 1;
10539 });
10540
10541 zc_magazine_zone = zone_create("zcc_magazine_zone", sizeof(struct zone_magazine) +
10542 zc_mag_size() * sizeof(vm_offset_t),
10543 ZC_VM | ZC_NOCACHING | ZC_ZFREE_CLEARMEM | ZC_PGZ_USE_GUARDS);
10544 zone_raise_reserve(zc_magazine_zone, (uint16_t)(2 * zpercpu_count()));
10545
10546 /*
10547 * Now migrate the startup statistics into their final storage,
10548 * and enable logging for early zones (that zone_create_ext() skipped).
10549 */
10550 int cpu = cpu_number();
10551 zone_index_foreach(idx) {
10552 zone_t tz = &zone_array[idx];
10553
10554 if (tz->z_stats == __zpcpu_mangle_for_boot(&zone_stats_startup[idx])) {
10555 zone_stats_t zs = zalloc_percpu_permanent_type(struct zone_stats);
10556
10557 *zpercpu_get_cpu(zs, cpu) = *zpercpu_get_cpu(tz->z_stats, cpu);
10558 tz->z_stats = zs;
10559 }
10560 if (tz->z_self == tz) {
10561 #if ZALLOC_ENABLE_LOGGING
10562 zone_setup_logging(tz);
10563 #endif /* ZALLOC_ENABLE_LOGGING */
10564 #if KASAN_TBI
10565 zone_setup_kasan_logging(tz);
10566 #endif /* KASAN_TBI */
10567 }
10568 }
10569 }
10570 STARTUP(ZALLOC, STARTUP_RANK_FIRST, zone_init);
10571
10572 void
zalloc_iokit_lockdown(void)10573 zalloc_iokit_lockdown(void)
10574 {
10575 zone_share_always = false;
10576 }
10577
10578 void
zalloc_first_proc_made(void)10579 zalloc_first_proc_made(void)
10580 {
10581 zone_caching_disabled = 0;
10582 zone_early_thres_mul = 1;
10583 }
10584
10585 __startup_func
10586 vm_offset_t
zone_early_mem_init(vm_size_t size)10587 zone_early_mem_init(vm_size_t size)
10588 {
10589 vm_offset_t mem;
10590
10591 assert3u(atop(size), <=, ZONE_EARLY_META_INLINE_COUNT);
10592
10593 /*
10594 * The zone that is used early to bring up the VM is stolen here.
10595 *
10596 * When the zone subsystem is actually initialized,
10597 * zone_metadata_init() will be called, and those pages
10598 * and the elements they contain, will be relocated into
10599 * the VM submap (even for architectures when those zones
10600 * do not live there).
10601 */
10602 assert3u(size, <=, sizeof(zone_early_pages_to_cram));
10603 mem = (vm_offset_t)zone_early_pages_to_cram;
10604
10605
10606 zone_info.zi_meta_base = zone_early_meta_array_startup -
10607 zone_pva_from_addr(mem).packed_address;
10608 zone_info.zi_map_range.min_address = mem;
10609 zone_info.zi_map_range.max_address = mem + size;
10610
10611 zone_info.zi_bits_range = (struct mach_vm_range){
10612 .min_address = (mach_vm_offset_t)zba_chunk_startup,
10613 .max_address = (mach_vm_offset_t)zba_chunk_startup +
10614 sizeof(zba_chunk_startup),
10615 };
10616
10617 zba_meta()->zbam_left = 1;
10618 zba_meta()->zbam_right = 1;
10619 zba_init_chunk(0, false);
10620
10621 return mem;
10622 }
10623
10624 #endif /* !ZALLOC_TEST */
10625 #pragma mark - tests
10626 #if DEBUG || DEVELOPMENT
10627
10628 /*
10629 * Used for sysctl zone tests that aren't thread-safe. Ensure only one
10630 * thread goes through at a time.
10631 *
10632 * Or we can end up with multiple test zones (if a second zinit() comes through
10633 * before zdestroy()), which could lead us to run out of zones.
10634 */
10635 static bool any_zone_test_running = FALSE;
10636
10637 static uintptr_t *
zone_copy_allocations(zone_t z,uintptr_t * elems,zone_pva_t page_index)10638 zone_copy_allocations(zone_t z, uintptr_t *elems, zone_pva_t page_index)
10639 {
10640 vm_offset_t elem_size = zone_elem_outer_size(z);
10641 vm_offset_t base;
10642 struct zone_page_metadata *meta;
10643
10644 while (!zone_pva_is_null(page_index)) {
10645 base = zone_pva_to_addr(page_index) + zone_elem_inner_offs(z);
10646 meta = zone_pva_to_meta(page_index);
10647
10648 if (meta->zm_inline_bitmap) {
10649 for (size_t i = 0; i < meta->zm_chunk_len; i++) {
10650 uint32_t map = meta[i].zm_bitmap;
10651
10652 for (; map; map &= map - 1) {
10653 *elems++ = INSTANCE_PUT(base +
10654 elem_size * __builtin_clz(map));
10655 }
10656 base += elem_size * 32;
10657 }
10658 } else {
10659 uint32_t order = zba_bits_ref_order(meta->zm_bitmap);
10660 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
10661 for (size_t i = 0; i < (1u << order); i++) {
10662 uint64_t map = bits[i];
10663
10664 for (; map; map &= map - 1) {
10665 *elems++ = INSTANCE_PUT(base +
10666 elem_size * __builtin_clzll(map));
10667 }
10668 base += elem_size * 64;
10669 }
10670 }
10671
10672 page_index = meta->zm_page_next;
10673 }
10674 return elems;
10675 }
10676
10677 kern_return_t
zone_leaks(const char * zoneName,uint32_t nameLen,leak_site_proc proc)10678 zone_leaks(const char * zoneName, uint32_t nameLen, leak_site_proc proc)
10679 {
10680 zone_t zone = NULL;
10681 uintptr_t * array;
10682 uintptr_t * next;
10683 uintptr_t element;
10684 uint32_t idx, count, found;
10685 uint32_t nobtcount;
10686 uint32_t elemSize;
10687 size_t maxElems;
10688
10689 zone_foreach(z) {
10690 if (!z->z_name) {
10691 continue;
10692 }
10693 if (!strncmp(zoneName, z->z_name, nameLen)) {
10694 zone = z;
10695 break;
10696 }
10697 }
10698 if (zone == NULL) {
10699 return KERN_INVALID_NAME;
10700 }
10701
10702 elemSize = (uint32_t)zone_elem_inner_size(zone);
10703 maxElems = (zone->z_elems_avail + 1) & ~1ul;
10704
10705 array = kalloc_type_tag(vm_offset_t, maxElems, Z_WAITOK, VM_KERN_MEMORY_DIAG);
10706 if (array == NULL) {
10707 return KERN_RESOURCE_SHORTAGE;
10708 }
10709
10710 zone_lock(zone);
10711
10712 next = array;
10713 next = zone_copy_allocations(zone, next, zone->z_pageq_partial);
10714 next = zone_copy_allocations(zone, next, zone->z_pageq_full);
10715 count = (uint32_t)(next - array);
10716
10717 zone_unlock(zone);
10718
10719 zone_leaks_scan(array, count, (uint32_t)zone_elem_outer_size(zone), &found);
10720 assert(found <= count);
10721
10722 for (idx = 0; idx < count; idx++) {
10723 element = array[idx];
10724 if (kInstanceFlagReferenced & element) {
10725 continue;
10726 }
10727 element = INSTANCE_PUT(element) & ~kInstanceFlags;
10728 }
10729
10730 #if ZALLOC_ENABLE_LOGGING
10731 if (zone->z_btlog && !corruption_debug_flag) {
10732 // btlog_copy_backtraces_for_elements will set kInstanceFlagReferenced on elements it found
10733 static_assert(sizeof(vm_address_t) == sizeof(uintptr_t));
10734 btlog_copy_backtraces_for_elements(zone->z_btlog,
10735 (vm_address_t *)array, &count, elemSize, proc);
10736 }
10737 #endif /* ZALLOC_ENABLE_LOGGING */
10738
10739 for (nobtcount = idx = 0; idx < count; idx++) {
10740 element = array[idx];
10741 if (!element) {
10742 continue;
10743 }
10744 if (kInstanceFlagReferenced & element) {
10745 continue;
10746 }
10747 nobtcount++;
10748 }
10749 if (nobtcount) {
10750 proc(nobtcount, elemSize, BTREF_NULL);
10751 }
10752
10753 kfree_type(vm_offset_t, maxElems, array);
10754 return KERN_SUCCESS;
10755 }
10756
10757 static int
zone_ro_basic_test_run(__unused int64_t in,int64_t * out)10758 zone_ro_basic_test_run(__unused int64_t in, int64_t *out)
10759 {
10760 zone_security_flags_t zsflags;
10761 uint32_t x = 4;
10762 uint32_t *test_ptr;
10763
10764 if (os_atomic_xchg(&any_zone_test_running, true, relaxed)) {
10765 printf("zone_ro_basic_test: Test already running.\n");
10766 return EALREADY;
10767 }
10768
10769 zsflags = zone_security_array[ZONE_ID__FIRST_RO];
10770
10771 for (int i = 0; i < 3; i++) {
10772 #if ZSECURITY_CONFIG(READ_ONLY)
10773 /* Basic Test: Create int zone, zalloc int, modify value, free int */
10774 printf("zone_ro_basic_test: Basic Test iteration %d\n", i);
10775 printf("zone_ro_basic_test: create a sub-page size zone\n");
10776
10777 printf("zone_ro_basic_test: verify flags were set\n");
10778 assert(zsflags.z_submap_idx == Z_SUBMAP_IDX_READ_ONLY);
10779
10780 printf("zone_ro_basic_test: zalloc an element\n");
10781 test_ptr = (zalloc_ro)(ZONE_ID__FIRST_RO, Z_WAITOK);
10782 assert(test_ptr);
10783
10784 printf("zone_ro_basic_test: verify we can't write to it\n");
10785 assert(verify_write(&x, test_ptr, sizeof(x)) == EFAULT);
10786
10787 x = 4;
10788 printf("zone_ro_basic_test: test zalloc_ro_mut to assign value\n");
10789 zalloc_ro_mut(ZONE_ID__FIRST_RO, test_ptr, 0, &x, sizeof(uint32_t));
10790 assert(test_ptr);
10791 assert(*(uint32_t*)test_ptr == x);
10792
10793 x = 5;
10794 printf("zone_ro_basic_test: test zalloc_ro_update_elem to assign value\n");
10795 zalloc_ro_update_elem(ZONE_ID__FIRST_RO, test_ptr, &x);
10796 assert(test_ptr);
10797 assert(*(uint32_t*)test_ptr == x);
10798
10799 printf("zone_ro_basic_test: verify we can't write to it after assigning value\n");
10800 assert(verify_write(&x, test_ptr, sizeof(x)) == EFAULT);
10801
10802 printf("zone_ro_basic_test: free elem\n");
10803 zfree_ro(ZONE_ID__FIRST_RO, test_ptr);
10804 assert(!test_ptr);
10805 #else
10806 printf("zone_ro_basic_test: Read-only allocator n/a on 32bit platforms, test functionality of API\n");
10807
10808 printf("zone_ro_basic_test: verify flags were set\n");
10809 assert(zsflags.z_submap_idx != Z_SUBMAP_IDX_READ_ONLY);
10810
10811 printf("zone_ro_basic_test: zalloc an element\n");
10812 test_ptr = (zalloc_ro)(ZONE_ID__FIRST_RO, Z_WAITOK);
10813 assert(test_ptr);
10814
10815 x = 4;
10816 printf("zone_ro_basic_test: test zalloc_ro_mut to assign value\n");
10817 zalloc_ro_mut(ZONE_ID__FIRST_RO, test_ptr, 0, &x, sizeof(uint32_t));
10818 assert(test_ptr);
10819 assert(*(uint32_t*)test_ptr == x);
10820
10821 x = 5;
10822 printf("zone_ro_basic_test: test zalloc_ro_update_elem to assign value\n");
10823 zalloc_ro_update_elem(ZONE_ID__FIRST_RO, test_ptr, &x);
10824 assert(test_ptr);
10825 assert(*(uint32_t*)test_ptr == x);
10826
10827 printf("zone_ro_basic_test: free elem\n");
10828 zfree_ro(ZONE_ID__FIRST_RO, test_ptr);
10829 assert(!test_ptr);
10830 #endif /* !ZSECURITY_CONFIG(READ_ONLY) */
10831 }
10832
10833 printf("zone_ro_basic_test: garbage collection\n");
10834 zone_gc(ZONE_GC_DRAIN);
10835
10836 printf("zone_ro_basic_test: Test passed\n");
10837
10838 *out = 1;
10839 os_atomic_store(&any_zone_test_running, false, relaxed);
10840 return 0;
10841 }
10842 SYSCTL_TEST_REGISTER(zone_ro_basic_test, zone_ro_basic_test_run);
10843
10844 static int
zone_basic_test_run(__unused int64_t in,int64_t * out)10845 zone_basic_test_run(__unused int64_t in, int64_t *out)
10846 {
10847 static zone_t test_zone_ptr = NULL;
10848
10849 unsigned int i = 0, max_iter = 5;
10850 void * test_ptr;
10851 zone_t test_zone;
10852 int rc = 0;
10853
10854 if (os_atomic_xchg(&any_zone_test_running, true, relaxed)) {
10855 printf("zone_basic_test: Test already running.\n");
10856 return EALREADY;
10857 }
10858
10859 printf("zone_basic_test: Testing zinit(), zalloc(), zfree() and zdestroy() on zone \"test_zone_sysctl\"\n");
10860
10861 /* zinit() and zdestroy() a zone with the same name a bunch of times, verify that we get back the same zone each time */
10862 do {
10863 test_zone = zinit(sizeof(uint64_t), 100 * sizeof(uint64_t), sizeof(uint64_t), "test_zone_sysctl");
10864 assert(test_zone);
10865
10866 #if KASAN_CLASSIC
10867 if (test_zone_ptr == NULL && test_zone->z_elems_free != 0)
10868 #else
10869 if (test_zone->z_elems_free != 0)
10870 #endif
10871 {
10872 printf("zone_basic_test: free count is not zero\n");
10873 rc = EIO;
10874 goto out;
10875 }
10876
10877 if (test_zone_ptr == NULL) {
10878 /* Stash the zone pointer returned on the fist zinit */
10879 printf("zone_basic_test: zone created for the first time\n");
10880 test_zone_ptr = test_zone;
10881 } else if (test_zone != test_zone_ptr) {
10882 printf("zone_basic_test: old zone pointer and new zone pointer don't match\n");
10883 rc = EIO;
10884 goto out;
10885 }
10886
10887 test_ptr = zalloc_flags(test_zone, Z_WAITOK | Z_NOFAIL);
10888 zfree(test_zone, test_ptr);
10889
10890 zdestroy(test_zone);
10891 i++;
10892
10893 printf("zone_basic_test: Iteration %d successful\n", i);
10894 } while (i < max_iter);
10895
10896 #if !KASAN_CLASSIC /* because of the quarantine and redzones */
10897 /* test Z_VA_SEQUESTER */
10898 {
10899 zone_t test_pcpu_zone;
10900 kern_return_t kr;
10901 const int num_allocs = 8;
10902 int idx;
10903 vm_size_t elem_size = 2 * PAGE_SIZE / num_allocs;
10904 void *allocs[num_allocs];
10905 void **allocs_pcpu;
10906 vm_offset_t phys_pages = os_atomic_load(&zone_pages_wired, relaxed);
10907
10908 test_zone = zone_create("test_zone_sysctl", elem_size,
10909 ZC_DESTRUCTIBLE);
10910 assert(test_zone);
10911
10912 test_pcpu_zone = zone_create("test_zone_sysctl.pcpu", sizeof(uint64_t),
10913 ZC_DESTRUCTIBLE | ZC_PERCPU);
10914 assert(test_pcpu_zone);
10915
10916 for (idx = 0; idx < num_allocs; idx++) {
10917 allocs[idx] = zalloc(test_zone);
10918 assert(NULL != allocs[idx]);
10919 printf("alloc[%d] %p\n", idx, allocs[idx]);
10920 }
10921 for (idx = 0; idx < num_allocs; idx++) {
10922 zfree(test_zone, allocs[idx]);
10923 }
10924 assert(!zone_pva_is_null(test_zone->z_pageq_empty));
10925
10926 kr = kmem_alloc(kernel_map, (vm_address_t *)&allocs_pcpu, PAGE_SIZE,
10927 KMA_ZERO | KMA_KOBJECT, VM_KERN_MEMORY_DIAG);
10928 assert(kr == KERN_SUCCESS);
10929
10930 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
10931 allocs_pcpu[idx] = zalloc_percpu(test_pcpu_zone,
10932 Z_WAITOK | Z_ZERO);
10933 assert(NULL != allocs_pcpu[idx]);
10934 }
10935 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
10936 zfree_percpu(test_pcpu_zone, allocs_pcpu[idx]);
10937 }
10938 assert(!zone_pva_is_null(test_pcpu_zone->z_pageq_empty));
10939
10940 printf("vm_page_wire_count %d, vm_page_free_count %d, p to v %ld%%\n",
10941 vm_page_wire_count, vm_page_free_count,
10942 100L * phys_pages / zone_pages_wired_max);
10943 zone_gc(ZONE_GC_DRAIN);
10944 printf("vm_page_wire_count %d, vm_page_free_count %d, p to v %ld%%\n",
10945 vm_page_wire_count, vm_page_free_count,
10946 100L * phys_pages / zone_pages_wired_max);
10947
10948 unsigned int allva = 0;
10949
10950 zone_foreach(z) {
10951 zone_lock(z);
10952 allva += z->z_wired_cur;
10953 if (zone_pva_is_null(z->z_pageq_va)) {
10954 zone_unlock(z);
10955 continue;
10956 }
10957 unsigned count = 0;
10958 uint64_t size;
10959 zone_pva_t pg = z->z_pageq_va;
10960 struct zone_page_metadata *page_meta;
10961 while (pg.packed_address) {
10962 page_meta = zone_pva_to_meta(pg);
10963 count += z->z_percpu ? 1 : z->z_chunk_pages;
10964 if (page_meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
10965 count -= page_meta->zm_page_index;
10966 }
10967 pg = page_meta->zm_page_next;
10968 }
10969 size = zone_size_wired(z);
10970 if (!size) {
10971 size = 1;
10972 }
10973 printf("%s%s: seq %d, res %d, %qd %%\n",
10974 zone_heap_name(z), z->z_name, z->z_va_cur - z->z_wired_cur,
10975 z->z_wired_cur, zone_size_allocated(z) * 100ULL / size);
10976 zone_unlock(z);
10977 }
10978
10979 printf("total va: %d\n", allva);
10980
10981 assert(zone_pva_is_null(test_zone->z_pageq_empty));
10982 assert(zone_pva_is_null(test_zone->z_pageq_partial));
10983 assert(!zone_pva_is_null(test_zone->z_pageq_va));
10984 assert(zone_pva_is_null(test_pcpu_zone->z_pageq_empty));
10985 assert(zone_pva_is_null(test_pcpu_zone->z_pageq_partial));
10986 assert(!zone_pva_is_null(test_pcpu_zone->z_pageq_va));
10987
10988 for (idx = 0; idx < num_allocs; idx++) {
10989 assert(0 == pmap_find_phys(kernel_pmap, (addr64_t)(uintptr_t) allocs[idx]));
10990 }
10991
10992 /* make sure the zone is still usable after a GC */
10993
10994 for (idx = 0; idx < num_allocs; idx++) {
10995 allocs[idx] = zalloc(test_zone);
10996 assert(allocs[idx]);
10997 printf("alloc[%d] %p\n", idx, allocs[idx]);
10998 }
10999 for (idx = 0; idx < num_allocs; idx++) {
11000 zfree(test_zone, allocs[idx]);
11001 }
11002
11003 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
11004 allocs_pcpu[idx] = zalloc_percpu(test_pcpu_zone,
11005 Z_WAITOK | Z_ZERO);
11006 assert(NULL != allocs_pcpu[idx]);
11007 }
11008 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
11009 zfree_percpu(test_pcpu_zone, allocs_pcpu[idx]);
11010 }
11011
11012 assert(!zone_pva_is_null(test_pcpu_zone->z_pageq_empty));
11013
11014 kmem_free(kernel_map, (vm_address_t)allocs_pcpu, PAGE_SIZE);
11015
11016 zdestroy(test_zone);
11017 zdestroy(test_pcpu_zone);
11018 }
11019 #endif /* KASAN_CLASSIC */
11020
11021 printf("zone_basic_test: Test passed\n");
11022
11023
11024 *out = 1;
11025 out:
11026 os_atomic_store(&any_zone_test_running, false, relaxed);
11027 return rc;
11028 }
11029 SYSCTL_TEST_REGISTER(zone_basic_test, zone_basic_test_run);
11030
11031 struct zone_stress_obj {
11032 TAILQ_ENTRY(zone_stress_obj) zso_link;
11033 };
11034
11035 struct zone_stress_ctx {
11036 thread_t zsc_leader;
11037 lck_mtx_t zsc_lock;
11038 zone_t zsc_zone;
11039 uint64_t zsc_end;
11040 uint32_t zsc_workers;
11041 };
11042
11043 static void
zone_stress_worker(void * arg,wait_result_t __unused wr)11044 zone_stress_worker(void *arg, wait_result_t __unused wr)
11045 {
11046 struct zone_stress_ctx *ctx = arg;
11047 bool leader = ctx->zsc_leader == current_thread();
11048 TAILQ_HEAD(zone_stress_head, zone_stress_obj) head = TAILQ_HEAD_INITIALIZER(head);
11049 struct zone_bool_gen bg = { };
11050 struct zone_stress_obj *obj;
11051 uint32_t allocs = 0;
11052
11053 random_bool_init(&bg.zbg_bg);
11054
11055 do {
11056 for (int i = 0; i < 2000; i++) {
11057 uint32_t what = random_bool_gen_bits(&bg.zbg_bg,
11058 bg.zbg_entropy, ZONE_ENTROPY_CNT, 1);
11059 switch (what) {
11060 case 0:
11061 case 1:
11062 if (allocs < 10000) {
11063 obj = zalloc(ctx->zsc_zone);
11064 TAILQ_INSERT_HEAD(&head, obj, zso_link);
11065 allocs++;
11066 }
11067 break;
11068 case 2:
11069 case 3:
11070 if (allocs < 10000) {
11071 obj = zalloc(ctx->zsc_zone);
11072 TAILQ_INSERT_TAIL(&head, obj, zso_link);
11073 allocs++;
11074 }
11075 break;
11076 case 4:
11077 if (leader) {
11078 zone_gc(ZONE_GC_DRAIN);
11079 }
11080 break;
11081 case 5:
11082 case 6:
11083 if (!TAILQ_EMPTY(&head)) {
11084 obj = TAILQ_FIRST(&head);
11085 TAILQ_REMOVE(&head, obj, zso_link);
11086 zfree(ctx->zsc_zone, obj);
11087 allocs--;
11088 }
11089 break;
11090 case 7:
11091 if (!TAILQ_EMPTY(&head)) {
11092 obj = TAILQ_LAST(&head, zone_stress_head);
11093 TAILQ_REMOVE(&head, obj, zso_link);
11094 zfree(ctx->zsc_zone, obj);
11095 allocs--;
11096 }
11097 break;
11098 }
11099 }
11100 } while (mach_absolute_time() < ctx->zsc_end);
11101
11102 while (!TAILQ_EMPTY(&head)) {
11103 obj = TAILQ_FIRST(&head);
11104 TAILQ_REMOVE(&head, obj, zso_link);
11105 zfree(ctx->zsc_zone, obj);
11106 }
11107
11108 lck_mtx_lock(&ctx->zsc_lock);
11109 if (--ctx->zsc_workers == 0) {
11110 thread_wakeup(ctx);
11111 } else if (leader) {
11112 while (ctx->zsc_workers) {
11113 lck_mtx_sleep(&ctx->zsc_lock, LCK_SLEEP_DEFAULT, ctx,
11114 THREAD_UNINT);
11115 }
11116 }
11117 lck_mtx_unlock(&ctx->zsc_lock);
11118
11119 if (!leader) {
11120 thread_terminate_self();
11121 __builtin_unreachable();
11122 }
11123 }
11124
11125 static int
zone_stress_test_run(__unused int64_t in,int64_t * out)11126 zone_stress_test_run(__unused int64_t in, int64_t *out)
11127 {
11128 struct zone_stress_ctx ctx = {
11129 .zsc_leader = current_thread(),
11130 .zsc_workers = 3,
11131 };
11132 kern_return_t kr;
11133 thread_t th;
11134
11135 if (os_atomic_xchg(&any_zone_test_running, true, relaxed)) {
11136 printf("zone_stress_test: Test already running.\n");
11137 return EALREADY;
11138 }
11139
11140 lck_mtx_init(&ctx.zsc_lock, &zone_locks_grp, LCK_ATTR_NULL);
11141 ctx.zsc_zone = zone_create("test_zone_344", 344,
11142 ZC_DESTRUCTIBLE | ZC_NOCACHING);
11143 assert(ctx.zsc_zone->z_chunk_pages > 1);
11144
11145 clock_interval_to_deadline(5, NSEC_PER_SEC, &ctx.zsc_end);
11146
11147 printf("zone_stress_test: Starting (leader %p)\n", current_thread());
11148
11149 os_atomic_inc(&zalloc_simulate_vm_pressure, relaxed);
11150
11151 for (uint32_t i = 1; i < ctx.zsc_workers; i++) {
11152 kr = kernel_thread_start_priority(zone_stress_worker, &ctx,
11153 BASEPRI_DEFAULT, &th);
11154 if (kr == KERN_SUCCESS) {
11155 printf("zone_stress_test: thread %d: %p\n", i, th);
11156 thread_deallocate(th);
11157 } else {
11158 ctx.zsc_workers--;
11159 }
11160 }
11161
11162 zone_stress_worker(&ctx, 0);
11163
11164 lck_mtx_destroy(&ctx.zsc_lock, &zone_locks_grp);
11165
11166 zdestroy(ctx.zsc_zone);
11167
11168 printf("zone_stress_test: Done\n");
11169
11170 *out = 1;
11171 os_atomic_dec(&zalloc_simulate_vm_pressure, relaxed);
11172 os_atomic_store(&any_zone_test_running, false, relaxed);
11173 return 0;
11174 }
11175 SYSCTL_TEST_REGISTER(zone_stress_test, zone_stress_test_run);
11176
11177 struct zone_gc_stress_obj {
11178 STAILQ_ENTRY(zone_gc_stress_obj) zgso_link;
11179 uintptr_t zgso_pad[63];
11180 };
11181 STAILQ_HEAD(zone_gc_stress_head, zone_gc_stress_obj);
11182
11183 #define ZONE_GC_OBJ_PER_PAGE (PAGE_SIZE / sizeof(struct zone_gc_stress_obj))
11184
11185 KALLOC_TYPE_DEFINE(zone_gc_stress_zone, struct zone_gc_stress_obj, KT_DEFAULT);
11186
11187 struct zone_gc_stress_ctx {
11188 bool zgsc_done;
11189 lck_mtx_t zgsc_lock;
11190 zone_t zgsc_zone;
11191 uint64_t zgsc_end;
11192 uint32_t zgsc_workers;
11193 };
11194
11195 static void
zone_gc_stress_test_alloc_n(struct zone_gc_stress_head * head,size_t n)11196 zone_gc_stress_test_alloc_n(struct zone_gc_stress_head *head, size_t n)
11197 {
11198 struct zone_gc_stress_obj *obj;
11199
11200 for (size_t i = 0; i < n; i++) {
11201 obj = zalloc_flags(zone_gc_stress_zone, Z_WAITOK);
11202 STAILQ_INSERT_TAIL(head, obj, zgso_link);
11203 }
11204 }
11205
11206 static void
zone_gc_stress_test_free_n(struct zone_gc_stress_head * head)11207 zone_gc_stress_test_free_n(struct zone_gc_stress_head *head)
11208 {
11209 struct zone_gc_stress_obj *obj;
11210
11211 while ((obj = STAILQ_FIRST(head))) {
11212 STAILQ_REMOVE_HEAD(head, zgso_link);
11213 zfree(zone_gc_stress_zone, obj);
11214 }
11215 }
11216
11217 __dead2
11218 static void
zone_gc_stress_worker(void * arg,wait_result_t __unused wr)11219 zone_gc_stress_worker(void *arg, wait_result_t __unused wr)
11220 {
11221 struct zone_gc_stress_ctx *ctx = arg;
11222 struct zone_gc_stress_head head = STAILQ_HEAD_INITIALIZER(head);
11223
11224 while (!ctx->zgsc_done) {
11225 zone_gc_stress_test_alloc_n(&head, ZONE_GC_OBJ_PER_PAGE * 4);
11226 zone_gc_stress_test_free_n(&head);
11227 }
11228
11229 lck_mtx_lock(&ctx->zgsc_lock);
11230 if (--ctx->zgsc_workers == 0) {
11231 thread_wakeup(ctx);
11232 }
11233 lck_mtx_unlock(&ctx->zgsc_lock);
11234
11235 thread_terminate_self();
11236 __builtin_unreachable();
11237 }
11238
11239 static int
zone_gc_stress_test_run(__unused int64_t in,int64_t * out)11240 zone_gc_stress_test_run(__unused int64_t in, int64_t *out)
11241 {
11242 struct zone_gc_stress_head head = STAILQ_HEAD_INITIALIZER(head);
11243 struct zone_gc_stress_ctx ctx = {
11244 .zgsc_workers = 3,
11245 };
11246 kern_return_t kr;
11247 thread_t th;
11248
11249 if (os_atomic_xchg(&any_zone_test_running, true, relaxed)) {
11250 printf("zone_gc_stress_test: Test already running.\n");
11251 return EALREADY;
11252 }
11253
11254 lck_mtx_init(&ctx.zgsc_lock, &zone_locks_grp, LCK_ATTR_NULL);
11255 lck_mtx_lock(&ctx.zgsc_lock);
11256
11257 printf("zone_gc_stress_test: Starting (leader %p)\n", current_thread());
11258
11259 os_atomic_inc(&zalloc_simulate_vm_pressure, relaxed);
11260
11261 for (uint32_t i = 0; i < ctx.zgsc_workers; i++) {
11262 kr = kernel_thread_start_priority(zone_gc_stress_worker, &ctx,
11263 BASEPRI_DEFAULT, &th);
11264 if (kr == KERN_SUCCESS) {
11265 printf("zone_gc_stress_test: thread %d: %p\n", i, th);
11266 thread_deallocate(th);
11267 } else {
11268 ctx.zgsc_workers--;
11269 }
11270 }
11271
11272 for (uint64_t i = 0; i < in; i++) {
11273 size_t count = zc_mag_size() * zc_free_batch_size() * 10;
11274
11275 if (count < ZONE_GC_OBJ_PER_PAGE * 20) {
11276 count = ZONE_GC_OBJ_PER_PAGE * 20;
11277 }
11278
11279 zone_gc_stress_test_alloc_n(&head, count);
11280 zone_gc_stress_test_free_n(&head);
11281
11282 lck_mtx_lock(&zone_gc_lock);
11283 zone_reclaim(zone_gc_stress_zone->kt_zv.zv_zone,
11284 ZONE_RECLAIM_TRIM);
11285 lck_mtx_unlock(&zone_gc_lock);
11286
11287 printf("zone_gc_stress_test: round %lld/%lld\n", i + 1, in);
11288 }
11289
11290 os_atomic_thread_fence(seq_cst);
11291 ctx.zgsc_done = true;
11292 lck_mtx_sleep(&ctx.zgsc_lock, LCK_SLEEP_DEFAULT, &ctx, THREAD_UNINT);
11293 lck_mtx_unlock(&ctx.zgsc_lock);
11294
11295 lck_mtx_destroy(&ctx.zgsc_lock, &zone_locks_grp);
11296
11297 lck_mtx_lock(&zone_gc_lock);
11298 zone_reclaim(zone_gc_stress_zone->kt_zv.zv_zone,
11299 ZONE_RECLAIM_DRAIN);
11300 lck_mtx_unlock(&zone_gc_lock);
11301
11302 printf("zone_gc_stress_test: Done\n");
11303
11304 *out = 1;
11305 os_atomic_dec(&zalloc_simulate_vm_pressure, relaxed);
11306 os_atomic_store(&any_zone_test_running, false, relaxed);
11307 return 0;
11308 }
11309 SYSCTL_TEST_REGISTER(zone_gc_stress_test, zone_gc_stress_test_run);
11310
11311 /*
11312 * Routines to test that zone garbage collection and zone replenish threads
11313 * running at the same time don't cause problems.
11314 */
11315
11316 static int
zone_gc_replenish_test(__unused int64_t in,int64_t * out)11317 zone_gc_replenish_test(__unused int64_t in, int64_t *out)
11318 {
11319 zone_gc(ZONE_GC_DRAIN);
11320 *out = 1;
11321 return 0;
11322 }
11323 SYSCTL_TEST_REGISTER(zone_gc_replenish_test, zone_gc_replenish_test);
11324
11325 static int
zone_alloc_replenish_test(__unused int64_t in,int64_t * out)11326 zone_alloc_replenish_test(__unused int64_t in, int64_t *out)
11327 {
11328 zone_t z = vm_map_entry_zone;
11329 struct data { struct data *next; } *node, *list = NULL;
11330
11331 if (z == NULL) {
11332 printf("Couldn't find a replenish zone\n");
11333 return EIO;
11334 }
11335
11336 /* big enough to go past replenishment */
11337 for (uint32_t i = 0; i < 10 * z->z_elems_rsv; ++i) {
11338 node = zalloc(z);
11339 node->next = list;
11340 list = node;
11341 }
11342
11343 /*
11344 * release the memory we allocated
11345 */
11346 while (list != NULL) {
11347 node = list;
11348 list = list->next;
11349 zfree(z, node);
11350 }
11351
11352 *out = 1;
11353 return 0;
11354 }
11355 SYSCTL_TEST_REGISTER(zone_alloc_replenish_test, zone_alloc_replenish_test);
11356
11357 #endif /* DEBUG || DEVELOPMENT */
11358