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/startup.h>
83 #include <kern/kern_types.h>
84 #include <kern/assert.h>
85 #include <kern/backtrace.h>
86 #include <kern/host.h>
87 #include <kern/macro_help.h>
88 #include <kern/sched.h>
89 #include <kern/locks.h>
90 #include <kern/sched_prim.h>
91 #include <kern/misc_protos.h>
92 #include <kern/thread_call.h>
93 #include <kern/zalloc_internal.h>
94 #include <kern/kalloc.h>
95 #include <kern/debug.h>
96
97 #include <prng/random.h>
98
99 #include <vm/pmap.h>
100 #include <vm/vm_map.h>
101 #include <vm/vm_kern.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_pageout.h>
104 #include <vm/vm_compressor.h> /* C_SLOT_PACKED_PTR* */
105
106 #include <pexpert/pexpert.h>
107
108 #include <machine/machparam.h>
109 #include <machine/machine_routines.h> /* ml_cpu_get_info */
110
111 #include <os/atomic.h>
112
113 #include <libkern/OSDebug.h>
114 #include <libkern/OSAtomic.h>
115 #include <libkern/section_keywords.h>
116 #include <sys/kdebug.h>
117
118 #include <san/kasan.h>
119 #include <libsa/stdlib.h>
120 #include <sys/errno.h>
121
122 #include <IOKit/IOBSD.h>
123
124 #if KASAN_ZALLOC
125 /*
126 * Disable zalloc zero validation under kasan as it is
127 * double-duty with what kasan already does.
128 */
129 #define ZALLOC_ENABLE_ZERO_CHECK 0
130 #define ZONE_ENABLE_LOGGING 0
131 #elif DEBUG || DEVELOPMENT
132 #define ZALLOC_ENABLE_ZERO_CHECK 1
133 #define ZONE_ENABLE_LOGGING 1
134 #else
135 #define ZALLOC_ENABLE_ZERO_CHECK 1
136 #define ZONE_ENABLE_LOGGING 0
137 #endif
138
139 #if DEBUG
140 #define z_debug_assert(expr) assert(expr)
141 #else
142 #define z_debug_assert(expr) (void)(expr)
143 #endif
144
145 extern void vm_pageout_garbage_collect(int collect);
146
147 /* Returns pid of the task with the largest number of VM map entries. */
148 extern pid_t find_largest_process_vm_map_entries(void);
149
150 /*
151 * Callout to jetsam. If pid is -1, we wake up the memorystatus thread to do asynchronous kills.
152 * For any other pid we try to kill that process synchronously.
153 */
154 extern boolean_t memorystatus_kill_on_zone_map_exhaustion(pid_t pid);
155
156 extern zone_t vm_map_entry_zone;
157 extern zone_t vm_object_zone;
158 extern zone_t ipc_service_port_label_zone;
159
160 ZONE_DECLARE(percpu_u64_zone, "percpu.64", sizeof(uint64_t),
161 ZC_PERCPU | ZC_ALIGNMENT_REQUIRED | ZC_KASAN_NOREDZONE);
162
163 #if CONFIG_KERNEL_TBI && KASAN_TBI
164 #define ZONE_MIN_ELEM_SIZE (sizeof(uint64_t) * 2)
165 #define ZONE_ALIGN_SIZE ZONE_MIN_ELEM_SIZE
166 #else /* CONFIG_KERNEL_TBI && KASAN_TBI */
167 #define ZONE_MIN_ELEM_SIZE sizeof(uint64_t)
168 #define ZONE_ALIGN_SIZE ZONE_MIN_ELEM_SIZE
169 #endif /* CONFIG_KERNEL_TBI && KASAN_TBI */
170
171 #define ZONE_MAX_ALLOC_SIZE (32 * 1024)
172 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
173 #define ZONE_CHUNK_ALLOC_SIZE (256 * 1024)
174 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
175
176 struct zone_page_metadata {
177 /* The index of the zone this metadata page belongs to */
178 zone_id_t zm_index : 11;
179
180 /* Whether `zm_bitmap` is an inline bitmap or a packed bitmap reference */
181 uint16_t zm_inline_bitmap : 1;
182
183 /*
184 * Zones allocate in "chunks" of zone_t::z_chunk_pages consecutive
185 * pages, or zpercpu_count() pages if the zone is percpu.
186 *
187 * The first page of it has its metadata set with:
188 * - 0 if none of the pages are currently wired
189 * - the number of wired pages in the chunk (not scaled for percpu).
190 *
191 * Other pages in the chunk have their zm_chunk_len set to
192 * ZM_SECONDARY_PAGE or ZM_SECONDARY_PCPU_PAGE depending on whether
193 * the zone is percpu or not. For those, zm_page_index holds the
194 * index of that page in the run.
195 */
196 uint16_t zm_chunk_len : 4;
197 #define ZM_CHUNK_LEN_MAX 0x8
198 #define ZM_SUBMAP_CHUNK 0xc
199 #define ZM_SUBMAP_CHUNK_REST 0xd
200 #define ZM_SECONDARY_PAGE 0xe
201 #define ZM_SECONDARY_PCPU_PAGE 0xf
202
203 union {
204 #define ZM_ALLOC_SIZE_LOCK 1u
205 uint16_t zm_alloc_size; /* first page only */
206 uint16_t zm_page_index; /* secondary pages only */
207 };
208 union {
209 uint32_t zm_bitmap; /* most zones */
210 uint32_t zm_bump; /* permanent zones */
211 uint32_t zm_va_len; /* submap chunks */
212 };
213
214 zone_pva_t zm_page_next;
215 zone_pva_t zm_page_prev;
216 };
217 static_assert(sizeof(struct zone_page_metadata) == 16, "validate packing");
218
219 __enum_closed_decl(zone_addr_kind_t, uint32_t, {
220 ZONE_ADDR_FOREIGN,
221 ZONE_ADDR_NATIVE,
222 ZONE_ADDR_READONLY
223 });
224 #define ZONE_ADDR_KIND_COUNT 3
225
226 static const char * const zone_map_range_names[] = {
227 [ZONE_ADDR_FOREIGN] = "Foreign",
228 [ZONE_ADDR_NATIVE] = "Native",
229 [ZONE_ADDR_READONLY] = "Readonly",
230 };
231
232 /*!
233 * @typedef zone_element_t
234 *
235 * @brief
236 * Type that represents a "resolved" zone element.
237 *
238 * @description
239 * This type encodes an element pointer as a pair of:
240 * { chunk base, element index }.
241 *
242 * The chunk base is extracted with @c trunc_page()
243 * as it is always page aligned, and occupies the bits above @c PAGE_SHIFT.
244 *
245 * The other bits encode the element index in the chunk rather than its address.
246 */
247 typedef struct zone_element {
248 vm_offset_t ze_value;
249 } zone_element_t;
250
251 /*!
252 * @typedef zone_magazine_t
253 *
254 * @brief
255 * Magazine of cached allocations.
256 *
257 * @field zm_cur how many elements this magazine holds (unused while loaded).
258 * @field zm_link linkage used by magazine depots.
259 * @field zm_elems an array of @c zc_mag_size() elements.
260 */
261 typedef struct zone_magazine {
262 uint16_t zm_cur;
263 STAILQ_ENTRY(zone_magazine) zm_link;
264 zone_element_t zm_elems[0];
265 } *zone_magazine_t;
266
267 /*!
268 * @typedef zone_cache_t
269 *
270 * @brief
271 * Magazine of cached allocations.
272 *
273 * @discussion
274 * Below is a diagram of the caching system. This design is inspired by the
275 * paper "Magazines and Vmem: Extending the Slab Allocator to Many CPUs and
276 * Arbitrary Resources" by Jeff Bonwick and Jonathan Adams and the FreeBSD UMA
277 * zone allocator (itself derived from this seminal work).
278 *
279 * It is divided into 3 layers:
280 * - the per-cpu layer,
281 * - the recirculation depot layer,
282 * - the Zone Allocator.
283 *
284 * The per-cpu and recirculation depot layer use magazines (@c zone_magazine_t),
285 * which are stacks of up to @c zc_mag_size() elements.
286 *
287 * <h2>CPU layer</h2>
288 *
289 * The CPU layer (@c zone_cache_t) looks like this:
290 *
291 * ╭─ a ─ f ─┬───────── zm_depot ──────────╮
292 * │ ╭─╮ ╭─╮ │ ╭─╮ ╭─╮ ╭─╮ ╭─╮ ╭─╮ │
293 * │ │#│ │#│ │ │#│ │#│ │#│ │#│ │#│ │
294 * │ │#│ │ │ │ │#│ │#│ │#│ │#│ │#│ │
295 * │ │ │ │ │ │ │#│ │#│ │#│ │#│ │#│ │
296 * │ ╰─╯ ╰─╯ │ ╰─╯ ╰─╯ ╰─╯ ╰─╯ ╰─╯ │
297 * ╰─────────┴─────────────────────────────╯
298 *
299 * It has two pre-loaded magazines (a)lloc and (f)ree which we allocate from,
300 * or free to. Serialization is achieved through disabling preemption, and only
301 * the current CPU can acces those allocations. This is represented on the left
302 * hand side of the diagram above.
303 *
304 * The right hand side is the per-cpu depot. It consists of @c zm_depot_count
305 * full magazines, and is protected by the @c zm_depot_lock for access.
306 * The lock is expected to absolutely never be contended, as only the local CPU
307 * tends to access the local per-cpu depot in regular operation mode.
308 *
309 * However unlike UMA, our implementation allows for the zone GC to reclaim
310 * per-CPU magazines aggresively, which is serialized with the @c zm_depot_lock.
311 *
312 *
313 * <h2>Recirculation Depot</h2>
314 *
315 * The recirculation depot layer is a list similar to the per-cpu depot,
316 * however it is different in two fundamental ways:
317 *
318 * - it is protected by the regular zone lock,
319 * - elements referenced by the magazines in that layer appear free
320 * to the zone layer.
321 *
322 *
323 * <h2>Magazine circulation and sizing</h2>
324 *
325 * The caching system sizes itself dynamically. Operations that allocate/free
326 * a single element call @c zone_lock_nopreempt_check_contention() which records
327 * contention on the lock by doing a trylock and recording its success.
328 *
329 * This information is stored in the @c z_contention_cur field of the zone,
330 * and a windoed moving average is maintained in @c z_contention_wma.
331 * Each time a CPU registers any contention, it will also allow its own per-cpu
332 * cache to grow, incrementing @c zc_depot_max, which is how the per-cpu layer
333 * might grow into using its local depot.
334 *
335 * Note that @c zc_depot_max assume that the (a) and (f) pre-loaded magazines
336 * on average contain @c zc_mag_size() elements.
337 *
338 * When a per-cpu layer cannot hold more full magazines in its depot,
339 * then it will overflow about 1/3 of its depot into the recirculation depot
340 * (see @c zfree_cached_slow(). Conversely, when a depot is empty, then it will
341 * refill its per-cpu depot to about 1/3 of its size from the recirculation
342 * depot (see @c zalloc_cached_slow()).
343 *
344 * Lastly, the zone layer keeps track of the high and low watermark of how many
345 * elements have been free per period of time (including being part of the
346 * recirculation depot) in the @c z_elems_free_min and @c z_elems_free_max
347 * fields. A weighted moving average of the amplitude of this is maintained in
348 * the @c z_elems_free_wss which informs the zone GC on how to gently trim
349 * zones without hurting performance.
350 *
351 *
352 * <h2>Security considerations</h2>
353 *
354 * The zone caching layer has been designed to avoid returning elements in
355 * a strict LIFO behavior: @c zalloc() will allocate from the (a) magazine,
356 * and @c zfree() free to the (f) magazine, and only swap them when the
357 * requested operation cannot be fulfilled.
358 *
359 * The per-cpu overflow depot or the recirculation depots are similarly used
360 * in FIFO order.
361 *
362 * More importantly, when magazines flow through the recirculation depot,
363 * the elements they contain are marked as "free" in the zone layer bitmaps.
364 * Because allocations out of per-cpu caches verify the bitmaps at allocation
365 * time, this acts as a poor man's double-free quarantine. The magazines
366 * allow to avoid the cost of the bit-scanning involved in the zone-level
367 * @c zalloc_item() codepath.
368 *
369 *
370 * @field zc_alloc_cur denormalized number of elements in the (a) magazine
371 * @field zc_free_cur denormalized number of elements in the (f) magazine
372 * @field zc_alloc_elems a pointer to the array of elements in (a)
373 * @field zc_free_elems a pointer to the array of elements in (f)
374 *
375 * @field zc_depot_lock a lock to access @c zc_depot, @c zc_depot_cur.
376 * @field zc_depot a list of @c zc_depot_cur full magazines
377 * @field zc_depot_cur number of magazines in @c zc_depot
378 * @field zc_depot_max the maximum number of elements in @c zc_depot,
379 * protected by the zone lock.
380 */
381 typedef struct zone_cache {
382 uint16_t zc_alloc_cur;
383 uint16_t zc_free_cur;
384 uint16_t zc_depot_cur;
385 uint16_t __zc_padding;
386 zone_element_t *zc_alloc_elems;
387 zone_element_t *zc_free_elems;
388 hw_lock_bit_t zc_depot_lock;
389 uint32_t zc_depot_max;
390 struct zone_depot zc_depot;
391 } *zone_cache_t;
392
393 #if !__x86_64__
394 static
395 #endif
396 __security_const_late struct {
397 struct zone_map_range zi_map_range[ZONE_ADDR_KIND_COUNT];
398 struct zone_map_range zi_meta_range; /* debugging only */
399 struct zone_map_range zi_bits_range; /* bits buddy allocator */
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(MIN(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 * Do note that the array might have a hole punched in the middle,
415 * see zone_metadata_init().
416 */
417 struct zone_page_metadata *zi_meta_base;
418 } zone_info;
419
420 /*
421 * Initial array of metadata for stolen memory.
422 *
423 * The numbers here have to be kept in sync with vm_map_steal_memory()
424 * so that we have reserved enough metadata.
425 *
426 * After zone_init() has run (which happens while the kernel is still single
427 * threaded), the metadata is moved to its final dynamic location, and
428 * this array is unmapped with the rest of __startup_data at lockdown.
429 */
430 #define ZONE_FOREIGN_META_INLINE_COUNT 64
431 __startup_data
432 static struct zone_page_metadata
433 zone_foreign_meta_array_startup[ZONE_FOREIGN_META_INLINE_COUNT];
434 __startup_data
435 static struct zone_map_range zone_early_steal;
436
437 /*
438 * The zone_locks_grp allows for collecting lock statistics.
439 * All locks are associated to this group in zinit.
440 * Look at tools/lockstat for debugging lock contention.
441 */
442 static LCK_GRP_DECLARE(zone_locks_grp, "zone_locks");
443 static LCK_MTX_EARLY_DECLARE(zone_metadata_region_lck, &zone_locks_grp);
444
445 /*
446 * The zone metadata lock protects:
447 * - metadata faulting,
448 * - VM submap VA allocations,
449 * - early gap page queue list
450 */
451 #define zone_meta_lock() lck_mtx_lock(&zone_metadata_region_lck);
452 #define zone_meta_unlock() lck_mtx_unlock(&zone_metadata_region_lck);
453
454 /*
455 * Exclude more than one concurrent garbage collection
456 */
457 static LCK_GRP_DECLARE(zone_gc_lck_grp, "zone_gc");
458 static LCK_MTX_EARLY_DECLARE(zone_gc_lock, &zone_gc_lck_grp);
459 static LCK_SPIN_DECLARE(zone_exhausted_lock, &zone_gc_lck_grp);
460
461 /*
462 * Panic logging metadata
463 */
464 bool panic_include_zprint = false;
465 bool panic_include_kalloc_types = false;
466 zone_t kalloc_type_src_zone = ZONE_NULL;
467 zone_t kalloc_type_dst_zone = ZONE_NULL;
468 mach_memory_info_t *panic_kext_memory_info = NULL;
469 vm_size_t panic_kext_memory_size = 0;
470
471 /*
472 * Protects zone_array, num_zones, num_zones_in_use, and
473 * zone_destroyed_bitmap
474 */
475 static SIMPLE_LOCK_DECLARE(all_zones_lock, 0);
476 static zone_id_t num_zones_in_use;
477 zone_id_t _Atomic num_zones;
478 SECURITY_READ_ONLY_LATE(unsigned int) zone_view_count;
479
480 /*
481 * Initial globals for zone stats until we can allocate the real ones.
482 * Those get migrated inside the per-CPU ones during zone_init() and
483 * this array is unmapped with the rest of __startup_data at lockdown.
484 */
485
486 /* zone to allocate zone_magazine structs from */
487 static SECURITY_READ_ONLY_LATE(zone_t) zc_magazine_zone;
488 /*
489 * Until pid1 is made, zone caching is off,
490 * until compute_zone_working_set_size() runs for the firt time.
491 *
492 * -1 represents the "never enabled yet" value.
493 */
494 static int8_t zone_caching_disabled = -1;
495
496 __startup_data
497 static struct zone_cache zone_cache_startup[MAX_ZONES];
498 __startup_data
499 static struct zone_stats zone_stats_startup[MAX_ZONES];
500 struct zone zone_array[MAX_ZONES];
501 SECURITY_READ_ONLY_LATE(zone_security_flags_t) zone_security_array[MAX_ZONES] = {
502 [0 ... MAX_ZONES - 1] = {
503 .z_allows_foreign = false,
504 .z_kheap_id = KHEAP_ID_NONE,
505 .z_noencrypt = false,
506 .z_submap_idx = Z_SUBMAP_IDX_GENERAL_0,
507 .z_kalloc_type = false,
508 .z_va_sequester = ZSECURITY_CONFIG(SEQUESTER),
509 },
510 };
511 SECURITY_READ_ONLY_LATE(uint16_t) zone_ro_elem_size[MAX_ZONES];
512
513 /* Initialized in zone_bootstrap(), how many "copies" the per-cpu system does */
514 static SECURITY_READ_ONLY_LATE(unsigned) zpercpu_early_count;
515
516 /* Used to keep track of destroyed slots in the zone_array */
517 static bitmap_t zone_destroyed_bitmap[BITMAP_LEN(MAX_ZONES)];
518
519 /* number of zone mapped pages used by all zones */
520 static long _Atomic zones_phys_page_mapped_count;
521
522 #define ZSECURITY_DEFAULT ( \
523 ZSECURITY_OPTIONS_KERNEL_DATA_MAP | \
524 0)
525 TUNABLE(zone_security_options_t, zsecurity_options, "zs", ZSECURITY_DEFAULT);
526
527 /* Time in (ms) after which we panic for zone exhaustions */
528 TUNABLE(int, zone_exhausted_timeout, "zet", 5000);
529
530 #if VM_TAG_SIZECLASSES
531 /* enable tags for zones that ask for it */
532 static TUNABLE(bool, zone_tagging_on, "-zt", false);
533 #endif /* VM_TAG_SIZECLASSES */
534
535 #if DEBUG || DEVELOPMENT
536 static int zalloc_simulate_vm_pressure;
537 TUNABLE(bool, zalloc_disable_copyio_check, "-no-copyio-zalloc-check", false);
538 #endif /* DEBUG || DEVELOPMENT */
539 #if CONFIG_ZLEAKS
540 /* Making pointer scanning leaks detection possible for all zones */
541 static TUNABLE(bool, zone_leaks_scan_enable, "-zl", false);
542 #else
543 #define zone_leaks_scan_enable false
544 #endif
545
546 /*
547 * Zone caching tunables
548 *
549 * zc_mag_size():
550 * size of magazines, larger to reduce contention at the expense of memory
551 *
552 * zc_auto_enable_threshold
553 * number of contentions per second after which zone caching engages
554 * automatically.
555 *
556 * 0 to disable.
557 *
558 * zc_grow_threshold
559 * numer of contentions per second after which the per-cpu depot layer
560 * grows at each newly observed contention without restriction.
561 *
562 * 0 to disable.
563 *
564 * zc_recirc_denom
565 * denominator of the fraction of per-cpu depot to migrate to/from
566 * the recirculation depot layer at a time. Default 3 (1/3).
567 *
568 * zc_defrag_ratio
569 * percentage of the working set to recirc size below which
570 * the zone is defragmented. Default is 50%.
571 *
572 * zc_free_batch_size
573 * The size of batches of frees/reclaim that can be done keeping
574 * the zone lock held (and preemption disabled).
575 */
576 static TUNABLE(uint16_t, zc_magazine_size, "zc_mag_size()", 8);
577 static TUNABLE(uint32_t, zc_auto_threshold, "zc_auto_enable_threshold", 20);
578 static TUNABLE(uint32_t, zc_grow_threshold, "zc_grow_threshold", 8);
579 static TUNABLE(uint32_t, zc_recirc_denom, "zc_recirc_denom", 3);
580 static TUNABLE(uint32_t, zc_defrag_ratio, "zc_defrag_ratio", 50);
581 static TUNABLE(uint32_t, zc_free_batch_size, "zc_free_batch_size", 256);
582
583 static SECURITY_READ_ONLY_LATE(long) zone_phys_mapped_max_pages;
SECURITY_READ_ONLY_LATE(vm_map_t)584 static SECURITY_READ_ONLY_LATE(vm_map_t) zone_submaps[Z_SUBMAP_IDX_COUNT];
585 static struct zone_pva_range {
586 zone_pva_t zpr_min;
587 zone_pva_t zpr_max;
588 } zone_alloc_range[Z_SUBMAP_IDX_COUNT];
589
590 #if __x86_64__
591 #define ZONE_ENTROPY_CNT 8
592 #else
593 #define ZONE_ENTROPY_CNT 2
594 #endif
595 static struct zone_bool_gen {
596 struct bool_gen zbg_bg;
597 uint32_t zbg_entropy[ZONE_ENTROPY_CNT];
598 } zone_bool_gen[MAX_CPUS];
599
600 static zone_t zone_find_largest(uint64_t *zone_size);
601
602 #endif /* !ZALLOC_TEST */
603 #pragma mark Zone metadata
604 #if !ZALLOC_TEST
605
606 static inline bool
zone_has_index(zone_t z,zone_id_t zid)607 zone_has_index(zone_t z, zone_id_t zid)
608 {
609 return zone_array + zid == z;
610 }
611
612 static zone_element_t
zone_element_encode(vm_offset_t base,vm_offset_t eidx)613 zone_element_encode(vm_offset_t base, vm_offset_t eidx)
614 {
615 return (zone_element_t){ .ze_value = base | eidx };
616 }
617
618 static vm_offset_t
zone_element_base(zone_element_t ze)619 zone_element_base(zone_element_t ze)
620 {
621 return trunc_page(ze.ze_value);
622 }
623
624 static vm_offset_t
zone_element_idx(zone_element_t ze)625 zone_element_idx(zone_element_t ze)
626 {
627 return ze.ze_value & PAGE_MASK;
628 }
629
630 static vm_offset_t
zone_element_addr(zone_element_t ze,vm_offset_t esize)631 zone_element_addr(zone_element_t ze, vm_offset_t esize)
632 {
633 return zone_element_base(ze) + esize * zone_element_idx(ze);
634 }
635
636 __abortlike
637 void
zone_invalid_panic(zone_t zone)638 zone_invalid_panic(zone_t zone)
639 {
640 panic("zone %p isn't in the zone_array", zone);
641 }
642
643 __abortlike
644 static void
zone_metadata_corruption(zone_t zone,struct zone_page_metadata * meta,const char * kind)645 zone_metadata_corruption(zone_t zone, struct zone_page_metadata *meta,
646 const char *kind)
647 {
648 panic("zone metadata corruption: %s (meta %p, zone %s%s)",
649 kind, meta, zone_heap_name(zone), zone->z_name);
650 }
651
652 __abortlike
653 static void
zone_invalid_element_addr_panic(zone_t zone,vm_offset_t addr)654 zone_invalid_element_addr_panic(zone_t zone, vm_offset_t addr)
655 {
656 panic("zone element pointer validation failed (addr: %p, zone %s%s)",
657 (void *)addr, zone_heap_name(zone), zone->z_name);
658 }
659
660 __abortlike
661 static void
zone_page_metadata_index_confusion_panic(zone_t zone,vm_offset_t addr,struct zone_page_metadata * meta)662 zone_page_metadata_index_confusion_panic(zone_t zone, vm_offset_t addr,
663 struct zone_page_metadata *meta)
664 {
665 zone_security_flags_t zsflags = zone_security_config(zone), src_zsflags;
666 zone_id_t zidx;
667 zone_t src_zone;
668
669 if (zsflags.z_kalloc_type) {
670 panic_include_kalloc_types = true;
671 kalloc_type_dst_zone = zone;
672 }
673
674 zidx = meta->zm_index;
675 if (zidx >= os_atomic_load(&num_zones, relaxed)) {
676 panic("%p expected in zone %s%s[%d], but metadata has invalid zidx: %d",
677 (void *)addr, zone_heap_name(zone), zone->z_name, zone_index(zone),
678 zidx);
679 }
680
681 src_zone = &zone_array[zidx];
682 src_zsflags = zone_security_array[zidx];
683 if (src_zsflags.z_kalloc_type) {
684 panic_include_kalloc_types = true;
685 kalloc_type_src_zone = src_zone;
686 }
687
688 panic("%p not in the expected zone %s%s[%d], but found in %s%s[%d]",
689 (void *)addr, zone_heap_name(zone), zone->z_name, zone_index(zone),
690 zone_heap_name(src_zone), src_zone->z_name, zidx);
691 }
692
693 __abortlike
694 static void
zone_page_metadata_native_queue_corruption(zone_t zone,zone_pva_t * queue)695 zone_page_metadata_native_queue_corruption(zone_t zone, zone_pva_t *queue)
696 {
697 panic("foreign metadata index %d enqueued in native head %p from zone %s%s",
698 queue->packed_address, queue, zone_heap_name(zone),
699 zone->z_name);
700 }
701
702 __abortlike
703 static void
zone_page_metadata_list_corruption(zone_t zone,struct zone_page_metadata * meta)704 zone_page_metadata_list_corruption(zone_t zone, struct zone_page_metadata *meta)
705 {
706 panic("metadata list corruption through element %p detected in zone %s%s",
707 meta, zone_heap_name(zone), zone->z_name);
708 }
709
710 __abortlike __unused
711 static void
zone_invalid_foreign_addr_panic(zone_t zone,vm_offset_t addr)712 zone_invalid_foreign_addr_panic(zone_t zone, vm_offset_t addr)
713 {
714 panic("addr %p being freed to foreign zone %s%s not from foreign range",
715 (void *)addr, zone_heap_name(zone), zone->z_name);
716 }
717
718 __abortlike
719 static void
zone_page_meta_accounting_panic(zone_t zone,struct zone_page_metadata * meta,const char * kind)720 zone_page_meta_accounting_panic(zone_t zone, struct zone_page_metadata *meta,
721 const char *kind)
722 {
723 panic("accounting mismatch (%s) for zone %s%s, meta %p", kind,
724 zone_heap_name(zone), zone->z_name, meta);
725 }
726
727 __abortlike
728 static void
zone_meta_double_free_panic(zone_t zone,zone_element_t ze,const char * caller)729 zone_meta_double_free_panic(zone_t zone, zone_element_t ze, const char *caller)
730 {
731 panic("%s: double free of %p to zone %s%s", caller,
732 (void *)zone_element_addr(ze, zone_elem_size(zone)),
733 zone_heap_name(zone), zone->z_name);
734 }
735
736 __abortlike
737 static void
zone_accounting_panic(zone_t zone,const char * kind)738 zone_accounting_panic(zone_t zone, const char *kind)
739 {
740 panic("accounting mismatch (%s) for zone %s%s", kind,
741 zone_heap_name(zone), zone->z_name);
742 }
743
744 #define zone_counter_sub(z, stat, value) ({ \
745 if (os_sub_overflow((z)->stat, value, &(z)->stat)) { \
746 zone_accounting_panic(z, #stat " wrap-around"); \
747 } \
748 (z)->stat; \
749 })
750
751 static inline void
zone_elems_free_add(zone_t z,uint32_t count)752 zone_elems_free_add(zone_t z, uint32_t count)
753 {
754 uint32_t n = (z->z_elems_free += count);
755 if (z->z_elems_free_max < n) {
756 z->z_elems_free_max = n;
757 }
758 }
759
760 static inline void
zone_elems_free_sub(zone_t z,uint32_t count)761 zone_elems_free_sub(zone_t z, uint32_t count)
762 {
763 uint32_t n = zone_counter_sub(z, z_elems_free, count);
764
765 if (z->z_elems_free_min > n) {
766 z->z_elems_free_min = n;
767 }
768 }
769
770 static inline uint16_t
zone_meta_alloc_size_add(zone_t z,struct zone_page_metadata * m,vm_offset_t esize)771 zone_meta_alloc_size_add(zone_t z, struct zone_page_metadata *m,
772 vm_offset_t esize)
773 {
774 if (os_add_overflow(m->zm_alloc_size, (uint16_t)esize, &m->zm_alloc_size)) {
775 zone_page_meta_accounting_panic(z, m, "alloc_size wrap-around");
776 }
777 return m->zm_alloc_size;
778 }
779
780 static inline uint16_t
zone_meta_alloc_size_sub(zone_t z,struct zone_page_metadata * m,vm_offset_t esize)781 zone_meta_alloc_size_sub(zone_t z, struct zone_page_metadata *m,
782 vm_offset_t esize)
783 {
784 if (os_sub_overflow(m->zm_alloc_size, esize, &m->zm_alloc_size)) {
785 zone_page_meta_accounting_panic(z, m, "alloc_size wrap-around");
786 }
787 return m->zm_alloc_size;
788 }
789
790 __abortlike
791 static void
zone_nofail_panic(zone_t zone)792 zone_nofail_panic(zone_t zone)
793 {
794 panic("zalloc(Z_NOFAIL) can't be satisfied for zone %s%s (potential leak)",
795 zone_heap_name(zone), zone->z_name);
796 }
797
798 #if __arm64__
799 // <rdar://problem/48304934> arm64 doesn't use ldp when I'd expect it to
800 #define zone_range_load(r, rmin, rmax) \
801 asm("ldp %[rmin], %[rmax], [%[range]]" \
802 : [rmin] "=r"(rmin), [rmax] "=r"(rmax) \
803 : [range] "r"(r), "m"((r)->min_address), "m"((r)->max_address))
804 #else
805 #define zone_range_load(r, rmin, rmax) \
806 ({ rmin = (r)->min_address; rmax = (r)->max_address; })
807 #endif
808
809 __attribute__((overloadable))
810 __header_always_inline bool
zone_range_contains(const struct zone_map_range * r,vm_offset_t addr)811 zone_range_contains(const struct zone_map_range *r, vm_offset_t addr)
812 {
813 vm_offset_t rmin, rmax;
814
815 #if CONFIG_KERNEL_TBI
816 addr = VM_KERNEL_TBI_FILL(addr);
817 #endif /* CONFIG_KERNEL_TBI */
818
819 /*
820 * The `&` is not a typo: we really expect the check to pass,
821 * so encourage the compiler to eagerly load and test without branches
822 */
823 zone_range_load(r, rmin, rmax);
824 return (addr >= rmin) & (addr < rmax);
825 }
826
827 __attribute__((overloadable))
828 __header_always_inline bool
zone_range_contains(const struct zone_map_range * r,vm_offset_t addr,vm_offset_t size)829 zone_range_contains(const struct zone_map_range *r, vm_offset_t addr, vm_offset_t size)
830 {
831 vm_offset_t rmin, rmax;
832
833 #if CONFIG_KERNEL_TBI
834 addr = VM_KERNEL_TBI_FILL(addr);
835 #endif /* CONFIG_KERNEL_TBI */
836
837 /*
838 * The `&` is not a typo: we really expect the check to pass,
839 * so encourage the compiler to eagerly load and test without branches
840 */
841 zone_range_load(r, rmin, rmax);
842 return (addr >= rmin) & (addr + size >= rmin) & (addr + size <= rmax);
843 }
844
845 __header_always_inline bool
zone_spans_ro_va(vm_offset_t addr_start,vm_offset_t addr_end)846 zone_spans_ro_va(vm_offset_t addr_start, vm_offset_t addr_end)
847 {
848 vm_offset_t rmin, rmax;
849
850 #if CONFIG_KERNEL_TBI
851 addr_start = VM_KERNEL_STRIP_UPTR(addr_start);
852 addr_end = VM_KERNEL_STRIP_UPTR(addr_end);
853 #endif /* CONFIG_KERNEL_TBI */
854
855 zone_range_load(&zone_info.zi_map_range[ZONE_ADDR_READONLY], rmin, rmax);
856
857 /*
858 * Either the start and the end are leftward of the read-only range, or they
859 * are both completely rightward. If neither, then they span over the range.
860 */
861
862 if ((addr_start < rmin) && (addr_end < rmin)) {
863 /* Leftward */
864 return false;
865 } else if ((addr_start > rmax) && (addr_end > rmax)) {
866 /* Rightward */
867 return false;
868 }
869
870 return true;
871 }
872
873 __header_always_inline vm_size_t
zone_range_size(const struct zone_map_range * r)874 zone_range_size(const struct zone_map_range *r)
875 {
876 vm_offset_t rmin, rmax;
877
878 zone_range_load(r, rmin, rmax);
879 return rmax - rmin;
880 }
881
882 #define from_zone_map(addr, size, kind) \
883 __builtin_choose_expr(__builtin_constant_p(size) ? (size) == 1 : 0, \
884 zone_range_contains(&zone_info.zi_map_range[kind], (vm_offset_t)(addr)), \
885 zone_range_contains(&zone_info.zi_map_range[kind], \
886 (vm_offset_t)(addr), size))
887
888 #define zone_native_size() \
889 zone_range_size(&zone_info.zi_map_range[ZONE_ADDR_NATIVE])
890
891 #define zone_foreign_size() \
892 zone_range_size(&zone_info.zi_map_range[ZONE_ADDR_FOREIGN])
893
894 #define zone_readonly_size() \
895 zone_range_size(&zone_info.zi_map_range[ZONE_ADDR_READONLY])
896
897 __header_always_inline bool
zone_pva_is_null(zone_pva_t page)898 zone_pva_is_null(zone_pva_t page)
899 {
900 return page.packed_address == 0;
901 }
902
903 __header_always_inline bool
zone_pva_is_queue(zone_pva_t page)904 zone_pva_is_queue(zone_pva_t page)
905 {
906 // actual kernel pages have the top bit set
907 return (int32_t)page.packed_address > 0;
908 }
909
910 __header_always_inline bool
zone_pva_is_equal(zone_pva_t pva1,zone_pva_t pva2)911 zone_pva_is_equal(zone_pva_t pva1, zone_pva_t pva2)
912 {
913 return pva1.packed_address == pva2.packed_address;
914 }
915
916 __header_always_inline zone_pva_t *
zone_pageq_base(void)917 zone_pageq_base(void)
918 {
919 extern zone_pva_t data_seg_start[] __SEGMENT_START_SYM("__DATA");
920
921 /*
922 * `-1` so that if the first __DATA variable is a page queue,
923 * it gets a non 0 index
924 */
925 return data_seg_start - 1;
926 }
927
928 __header_always_inline void
zone_queue_set_head(zone_t z,zone_pva_t queue,zone_pva_t oldv,struct zone_page_metadata * meta)929 zone_queue_set_head(zone_t z, zone_pva_t queue, zone_pva_t oldv,
930 struct zone_page_metadata *meta)
931 {
932 zone_pva_t *queue_head = &zone_pageq_base()[queue.packed_address];
933
934 if (!zone_pva_is_equal(*queue_head, oldv)) {
935 zone_page_metadata_list_corruption(z, meta);
936 }
937 *queue_head = meta->zm_page_next;
938 }
939
940 __header_always_inline zone_pva_t
zone_queue_encode(zone_pva_t * headp)941 zone_queue_encode(zone_pva_t *headp)
942 {
943 return (zone_pva_t){ (uint32_t)(headp - zone_pageq_base()) };
944 }
945
946 __header_always_inline zone_pva_t
zone_pva_from_addr(vm_address_t addr)947 zone_pva_from_addr(vm_address_t addr)
948 {
949 // cannot use atop() because we want to maintain the sign bit
950 return (zone_pva_t){ (uint32_t)((intptr_t)addr >> PAGE_SHIFT) };
951 }
952
953 __header_always_inline zone_pva_t
zone_pva_from_element(zone_element_t ze)954 zone_pva_from_element(zone_element_t ze)
955 {
956 return zone_pva_from_addr(ze.ze_value);
957 }
958
959 __header_always_inline vm_address_t
zone_pva_to_addr(zone_pva_t page)960 zone_pva_to_addr(zone_pva_t page)
961 {
962 // cause sign extension so that we end up with the right address
963 return (vm_offset_t)(int32_t)page.packed_address << PAGE_SHIFT;
964 }
965
966 __header_always_inline struct zone_page_metadata *
zone_pva_to_meta(zone_pva_t page)967 zone_pva_to_meta(zone_pva_t page)
968 {
969 return &zone_info.zi_meta_base[page.packed_address];
970 }
971
972 __header_always_inline zone_pva_t
zone_pva_from_meta(struct zone_page_metadata * meta)973 zone_pva_from_meta(struct zone_page_metadata *meta)
974 {
975 return (zone_pva_t){ (uint32_t)(meta - zone_info.zi_meta_base) };
976 }
977
978 __header_always_inline struct zone_page_metadata *
zone_meta_from_addr(vm_offset_t addr)979 zone_meta_from_addr(vm_offset_t addr)
980 {
981 return zone_pva_to_meta(zone_pva_from_addr(addr));
982 }
983
984 __header_always_inline struct zone_page_metadata *
zone_meta_from_element(zone_element_t ze)985 zone_meta_from_element(zone_element_t ze)
986 {
987 return zone_pva_to_meta(zone_pva_from_element(ze));
988 }
989
990 __header_always_inline zone_id_t
zone_index_from_ptr(const void * ptr)991 zone_index_from_ptr(const void *ptr)
992 {
993 return zone_pva_to_meta(zone_pva_from_addr((vm_offset_t)ptr))->zm_index;
994 }
995
996 __header_always_inline vm_offset_t
zone_meta_to_addr(struct zone_page_metadata * meta)997 zone_meta_to_addr(struct zone_page_metadata *meta)
998 {
999 return ptoa((int32_t)(meta - zone_info.zi_meta_base));
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_native(zone_t z,zone_pva_t * headp,vm_offset_t * page_addrp)1023 zone_meta_queue_pop_native(zone_t z, zone_pva_t *headp, vm_offset_t *page_addrp)
1024 {
1025 zone_pva_t head = *headp;
1026 struct zone_page_metadata *meta = zone_pva_to_meta(head);
1027 vm_offset_t page_addr = zone_pva_to_addr(head);
1028 struct zone_page_metadata *tmp;
1029
1030 if (!from_zone_map(page_addr, 1, ZONE_ADDR_NATIVE)) {
1031 zone_page_metadata_native_queue_corruption(z, headp);
1032 }
1033
1034 if (!zone_pva_is_null(meta->zm_page_next)) {
1035 tmp = zone_pva_to_meta(meta->zm_page_next);
1036 if (!zone_pva_is_equal(tmp->zm_page_prev, head)) {
1037 zone_page_metadata_list_corruption(z, meta);
1038 }
1039 tmp->zm_page_prev = meta->zm_page_prev;
1040 }
1041 *headp = meta->zm_page_next;
1042
1043 meta->zm_page_next = meta->zm_page_prev = (zone_pva_t){ 0 };
1044 *page_addrp = page_addr;
1045
1046 if (!zone_has_index(z, meta->zm_index)) {
1047 zone_page_metadata_index_confusion_panic(z,
1048 zone_meta_to_addr(meta), meta);
1049 }
1050 return meta;
1051 }
1052
1053 __header_always_inline void
zone_meta_remqueue(zone_t z,struct zone_page_metadata * meta)1054 zone_meta_remqueue(zone_t z, struct zone_page_metadata *meta)
1055 {
1056 zone_pva_t meta_pva = zone_pva_from_meta(meta);
1057 struct zone_page_metadata *tmp;
1058
1059 if (!zone_pva_is_null(meta->zm_page_next)) {
1060 tmp = zone_pva_to_meta(meta->zm_page_next);
1061 if (!zone_pva_is_equal(tmp->zm_page_prev, meta_pva)) {
1062 zone_page_metadata_list_corruption(z, meta);
1063 }
1064 tmp->zm_page_prev = meta->zm_page_prev;
1065 }
1066 if (zone_pva_is_queue(meta->zm_page_prev)) {
1067 zone_queue_set_head(z, meta->zm_page_prev, meta_pva, meta);
1068 } else {
1069 tmp = zone_pva_to_meta(meta->zm_page_prev);
1070 if (!zone_pva_is_equal(tmp->zm_page_next, meta_pva)) {
1071 zone_page_metadata_list_corruption(z, meta);
1072 }
1073 tmp->zm_page_next = meta->zm_page_next;
1074 }
1075
1076 meta->zm_page_next = meta->zm_page_prev = (zone_pva_t){ 0 };
1077 }
1078
1079 __header_always_inline void
zone_meta_requeue(zone_t z,zone_pva_t * headp,struct zone_page_metadata * meta)1080 zone_meta_requeue(zone_t z, zone_pva_t *headp,
1081 struct zone_page_metadata *meta)
1082 {
1083 zone_meta_remqueue(z, meta);
1084 zone_meta_queue_push(z, headp, meta);
1085 }
1086
1087 /* prevents a given metadata from ever reaching the z_pageq_empty queue */
1088 static inline void
zone_meta_lock_in_partial(zone_t z,struct zone_page_metadata * m,uint32_t len)1089 zone_meta_lock_in_partial(zone_t z, struct zone_page_metadata *m, uint32_t len)
1090 {
1091 uint16_t new_size = zone_meta_alloc_size_add(z, m, ZM_ALLOC_SIZE_LOCK);
1092
1093 assert(new_size % sizeof(vm_offset_t) == ZM_ALLOC_SIZE_LOCK);
1094 if (new_size == ZM_ALLOC_SIZE_LOCK) {
1095 zone_meta_requeue(z, &z->z_pageq_partial, m);
1096 zone_counter_sub(z, z_wired_empty, len);
1097 }
1098 }
1099
1100 /* allows a given metadata to reach the z_pageq_empty queue again */
1101 static inline void
zone_meta_unlock_from_partial(zone_t z,struct zone_page_metadata * m,uint32_t len)1102 zone_meta_unlock_from_partial(zone_t z, struct zone_page_metadata *m, uint32_t len)
1103 {
1104 uint16_t new_size = zone_meta_alloc_size_sub(z, m, ZM_ALLOC_SIZE_LOCK);
1105
1106 assert(new_size % sizeof(vm_offset_t) == 0);
1107 if (new_size == 0) {
1108 zone_meta_requeue(z, &z->z_pageq_empty, m);
1109 z->z_wired_empty += len;
1110 }
1111 }
1112
1113 /*
1114 * Routine to populate a page backing metadata in the zone_metadata_region.
1115 * Must be called without the zone lock held as it might potentially block.
1116 */
1117 static void
zone_meta_populate(vm_offset_t base,vm_size_t size)1118 zone_meta_populate(vm_offset_t base, vm_size_t size)
1119 {
1120 struct zone_page_metadata *from = zone_meta_from_addr(base);
1121 struct zone_page_metadata *to = from + atop(size);
1122 vm_offset_t page_addr = trunc_page(from);
1123
1124 for (; page_addr < (vm_offset_t)to; page_addr += PAGE_SIZE) {
1125 #if !KASAN_ZALLOC
1126 /*
1127 * This can race with another thread doing a populate on the same metadata
1128 * page, where we see an updated pmap but unmapped KASan shadow, causing a
1129 * fault in the shadow when we first access the metadata page. Avoid this
1130 * by always synchronizing on the zone_metadata_region lock with KASan.
1131 */
1132 if (pmap_find_phys(kernel_pmap, page_addr)) {
1133 continue;
1134 }
1135 #endif
1136
1137 for (;;) {
1138 kern_return_t ret = KERN_SUCCESS;
1139
1140 /*
1141 * All updates to the zone_metadata_region are done
1142 * under the zone_metadata_region_lck
1143 */
1144 zone_meta_lock();
1145 if (0 == pmap_find_phys(kernel_pmap, page_addr)) {
1146 ret = kernel_memory_populate(kernel_map, page_addr,
1147 PAGE_SIZE, KMA_NOPAGEWAIT | KMA_KOBJECT | KMA_ZERO,
1148 VM_KERN_MEMORY_OSFMK);
1149 }
1150 zone_meta_unlock();
1151
1152 if (ret == KERN_SUCCESS) {
1153 break;
1154 }
1155
1156 /*
1157 * We can't pass KMA_NOPAGEWAIT under a global lock as it leads
1158 * to bad system deadlocks, so if the allocation failed,
1159 * we need to do the VM_PAGE_WAIT() outside of the lock.
1160 */
1161 VM_PAGE_WAIT();
1162 }
1163 }
1164 }
1165
1166 __abortlike
1167 static void
zone_invalid_element_panic(zone_t zone,vm_offset_t addr,bool cache)1168 zone_invalid_element_panic(zone_t zone, vm_offset_t addr, bool cache)
1169 {
1170 struct zone_page_metadata *meta;
1171 vm_offset_t page, esize = zone_elem_size(zone);
1172 const char *from_cache = "";
1173
1174 if (cache) {
1175 zone_element_t ze = { .ze_value = addr };
1176 addr = zone_element_addr(ze, esize);
1177 from_cache = " (from cache)";
1178
1179 if (zone_element_idx(ze) >= zone->z_chunk_elems) {
1180 panic("eidx %d for addr %p being freed to zone %s%s, is larger "
1181 "than number fo element in chunk (%d)", (int)zone_element_idx(ze),
1182 (void *)addr, zone_heap_name(zone), zone->z_name,
1183 zone->z_chunk_elems);
1184 }
1185 }
1186
1187 if (!from_zone_map(addr, esize, ZONE_ADDR_NATIVE) &&
1188 !from_zone_map(addr, esize, ZONE_ADDR_FOREIGN)) {
1189 panic("addr %p being freed to zone %s%s%s, isn't from zone map",
1190 (void *)addr, zone_heap_name(zone), zone->z_name, from_cache);
1191 }
1192 page = trunc_page(addr);
1193 meta = zone_meta_from_addr(addr);
1194
1195 if (meta->zm_chunk_len == ZM_SECONDARY_PCPU_PAGE) {
1196 panic("metadata %p corresponding to addr %p being freed to "
1197 "zone %s%s%s, is marked as secondary per cpu page",
1198 meta, (void *)addr, zone_heap_name(zone), zone->z_name,
1199 from_cache);
1200 }
1201 if (meta->zm_chunk_len > ZM_CHUNK_LEN_MAX) {
1202 panic("metadata %p corresponding to addr %p being freed to "
1203 "zone %s%s%s, has chunk len greater than max",
1204 meta, (void *)addr, zone_heap_name(zone), zone->z_name,
1205 from_cache);
1206 }
1207
1208 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1209 page -= ptoa(meta->zm_page_index);
1210 }
1211
1212 if ((addr - page) % esize) {
1213 panic("addr %p being freed to zone %s%s%s, isn't aligned to "
1214 "zone element size", (void *)addr, zone_heap_name(zone),
1215 zone->z_name, from_cache);
1216 }
1217
1218 zone_invalid_element_addr_panic(zone, addr);
1219 }
1220
1221 __header_always_inline
1222 struct zone_page_metadata *
zone_element_validate(zone_t zone,zone_element_t ze)1223 zone_element_validate(zone_t zone, zone_element_t ze)
1224 {
1225 struct zone_page_metadata *meta;
1226 vm_offset_t page = zone_element_base(ze);
1227
1228 if (!from_zone_map(page, 1, ZONE_ADDR_NATIVE) &&
1229 !from_zone_map(page, 1, ZONE_ADDR_FOREIGN)) {
1230 zone_invalid_element_panic(zone, ze.ze_value, true);
1231 }
1232 meta = zone_meta_from_addr(page);
1233
1234 if (meta->zm_chunk_len > ZM_CHUNK_LEN_MAX) {
1235 zone_invalid_element_panic(zone, ze.ze_value, true);
1236 }
1237 if (zone_element_idx(ze) >= zone->z_chunk_elems) {
1238 zone_invalid_element_panic(zone, ze.ze_value, true);
1239 }
1240
1241 if (!zone_has_index(zone, meta->zm_index)) {
1242 vm_offset_t addr = zone_element_addr(ze, zone_elem_size(zone));
1243 zone_page_metadata_index_confusion_panic(zone, addr, meta);
1244 }
1245
1246 return meta;
1247 }
1248
1249 __attribute__((always_inline))
1250 static struct zone_page_metadata *
zone_element_resolve(zone_t zone,vm_offset_t addr,vm_offset_t esize,zone_element_t * ze)1251 zone_element_resolve(zone_t zone, vm_offset_t addr, vm_offset_t esize,
1252 zone_element_t *ze)
1253 {
1254 struct zone_page_metadata *meta;
1255 vm_offset_t page, eidx;
1256
1257 if (!from_zone_map(addr, esize, ZONE_ADDR_NATIVE) &&
1258 !from_zone_map(addr, esize, ZONE_ADDR_FOREIGN)) {
1259 zone_invalid_element_panic(zone, addr, false);
1260 }
1261 page = trunc_page(addr);
1262 meta = zone_meta_from_addr(addr);
1263
1264 if (meta->zm_chunk_len == ZM_SECONDARY_PCPU_PAGE) {
1265 zone_invalid_element_panic(zone, addr, false);
1266 }
1267 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
1268 page -= ptoa(meta->zm_page_index);
1269 meta -= meta->zm_page_index;
1270 }
1271
1272 eidx = (addr - page) / esize;
1273 if ((addr - page) % esize) {
1274 zone_invalid_element_panic(zone, addr, false);
1275 }
1276
1277 if (!zone_has_index(zone, meta->zm_index)) {
1278 zone_page_metadata_index_confusion_panic(zone, addr, meta);
1279 }
1280
1281 *ze = zone_element_encode(page, eidx);
1282 return meta;
1283 }
1284
1285 /* Routine to get the size of a zone allocated address.
1286 * If the address doesnt belong to the zone maps, returns 0.
1287 */
1288 vm_size_t
zone_element_size(void * addr,zone_t * z)1289 zone_element_size(void *addr, zone_t *z)
1290 {
1291 struct zone *src_zone;
1292
1293 if (from_zone_map(addr, sizeof(void *), ZONE_ADDR_NATIVE) ||
1294 from_zone_map(addr, sizeof(void *), ZONE_ADDR_FOREIGN)) {
1295 src_zone = &zone_array[zone_index_from_ptr(addr)];
1296 if (z) {
1297 *z = src_zone;
1298 }
1299 return zone_elem_size_safe(src_zone);
1300 }
1301
1302 #if CONFIG_GZALLOC
1303 if (__improbable(gzalloc_enabled())) {
1304 vm_size_t gzsize;
1305 if (gzalloc_element_size(addr, z, &gzsize)) {
1306 return gzsize;
1307 }
1308 }
1309 #endif /* CONFIG_GZALLOC */
1310
1311 return 0;
1312 }
1313
1314 zone_id_t
zone_id_for_native_element(void * addr,vm_size_t esize)1315 zone_id_for_native_element(void *addr, vm_size_t esize)
1316 {
1317 zone_id_t zid = ZONE_ID_INVALID;
1318 if (from_zone_map(addr, esize, ZONE_ADDR_NATIVE)) {
1319 zid = zone_index_from_ptr(addr);
1320 __builtin_assume(zid != ZONE_ID_INVALID);
1321 }
1322 return zid;
1323 }
1324
1325 /* This function just formats the reason for the panics by redoing the checks */
1326 __abortlike
1327 static void
zone_require_panic(zone_t zone,void * addr)1328 zone_require_panic(zone_t zone, void *addr)
1329 {
1330 uint32_t zindex;
1331 zone_t other;
1332
1333 if (!from_zone_map(addr, zone_elem_size(zone), ZONE_ADDR_NATIVE)) {
1334 panic("zone_require failed: address not in a zone (addr: %p)", addr);
1335 }
1336
1337 zindex = zone_index_from_ptr(addr);
1338 other = &zone_array[zindex];
1339 if (zindex >= os_atomic_load(&num_zones, relaxed) || !other->z_self) {
1340 panic("zone_require failed: invalid zone index %d "
1341 "(addr: %p, expected: %s%s)", zindex,
1342 addr, zone_heap_name(zone), zone->z_name);
1343 } else {
1344 panic("zone_require failed: address in unexpected zone id %d (%s%s) "
1345 "(addr: %p, expected: %s%s)",
1346 zindex, zone_heap_name(other), other->z_name,
1347 addr, zone_heap_name(zone), zone->z_name);
1348 }
1349 }
1350
1351 __abortlike
1352 static void
zone_id_require_panic(zone_id_t zid,void * addr)1353 zone_id_require_panic(zone_id_t zid, void *addr)
1354 {
1355 zone_require_panic(&zone_array[zid], addr);
1356 }
1357
1358 /*
1359 * Routines to panic if a pointer is not mapped to an expected zone.
1360 * This can be used as a means of pinning an object to the zone it is expected
1361 * to be a part of. Causes a panic if the address does not belong to any
1362 * specified zone, does not belong to any zone, has been freed and therefore
1363 * unmapped from the zone, or the pointer contains an uninitialized value that
1364 * does not belong to any zone.
1365 *
1366 * Note that this can only work with collectable zones without foreign pages.
1367 */
1368 void
zone_require(zone_t zone,void * addr)1369 zone_require(zone_t zone, void *addr)
1370 {
1371 vm_size_t esize = zone_elem_size(zone);
1372
1373 if (__probable(from_zone_map(addr, esize, ZONE_ADDR_NATIVE))) {
1374 if (zone_has_index(zone, zone_index_from_ptr(addr))) {
1375 return;
1376 }
1377 #if CONFIG_GZALLOC
1378 } else if (__probable(zone->gzalloc_tracked)) {
1379 return;
1380 #endif
1381 }
1382 zone_require_panic(zone, addr);
1383 }
1384
1385 void
zone_id_require(zone_id_t zid,vm_size_t esize,void * addr)1386 zone_id_require(zone_id_t zid, vm_size_t esize, void *addr)
1387 {
1388 if (__probable(from_zone_map(addr, esize, ZONE_ADDR_NATIVE))) {
1389 if (zid == zone_index_from_ptr(addr)) {
1390 return;
1391 }
1392 #if CONFIG_GZALLOC
1393 } else if (__probable(zone_array[zid].gzalloc_tracked)) {
1394 return;
1395 #endif
1396 }
1397 zone_id_require_panic(zid, addr);
1398 }
1399
1400 void
zone_id_require_allow_foreign(zone_id_t zid,vm_size_t esize,void * addr)1401 zone_id_require_allow_foreign(zone_id_t zid, vm_size_t esize, void *addr)
1402 {
1403 if (__probable(from_zone_map(addr, esize, ZONE_ADDR_NATIVE) ||
1404 from_zone_map(addr, esize, ZONE_ADDR_FOREIGN))) {
1405 if (zid == zone_index_from_ptr(addr)) {
1406 return;
1407 }
1408 #if CONFIG_GZALLOC
1409 } else if (__probable(zone_array[zid].gzalloc_tracked)) {
1410 return;
1411 #endif
1412 }
1413 zone_id_require_panic(zid, addr);
1414 }
1415
1416 bool
zone_owns(zone_t zone,void * addr)1417 zone_owns(zone_t zone, void *addr)
1418 {
1419 vm_size_t esize = zone_elem_size_safe(zone);
1420
1421 if (__probable(from_zone_map(addr, esize, ZONE_ADDR_NATIVE))) {
1422 return zone_has_index(zone, zone_index_from_ptr(addr));
1423 #if CONFIG_GZALLOC
1424 } else if (__probable(zone->gzalloc_tracked)) {
1425 return true;
1426 #endif
1427 }
1428 return false;
1429 }
1430
1431 #endif /* !ZALLOC_TEST */
1432 #pragma mark Zone bits allocator
1433
1434 /*!
1435 * @defgroup Zone Bitmap allocator
1436 * @{
1437 *
1438 * @brief
1439 * Functions implementing the zone bitmap allocator
1440 *
1441 * @discussion
1442 * The zone allocator maintains which elements are allocated or free in bitmaps.
1443 *
1444 * When the number of elements per page is smaller than 32, it is stored inline
1445 * on the @c zone_page_metadata structure (@c zm_inline_bitmap is set,
1446 * and @c zm_bitmap used for storage).
1447 *
1448 * When the number of elements is larger, then a bitmap is allocated from
1449 * a buddy allocator (impelemented under the @c zba_* namespace). Pointers
1450 * to bitmaps are implemented as a packed 32 bit bitmap reference, stored in
1451 * @c zm_bitmap. The low 3 bits encode the scale (order) of the allocation in
1452 * @c ZBA_GRANULE units, and hence actual allocations encoded with that scheme
1453 * cannot be larger than 1024 bytes (8192 bits).
1454 *
1455 * This buddy allocator can actually accomodate allocations as large
1456 * as 8k on 16k systems and 2k on 4k systems.
1457 *
1458 * Note: @c zba_* functions are implementation details not meant to be used
1459 * outside of the allocation of the allocator itself. Interfaces to the rest of
1460 * the zone allocator are documented and not @c zba_* prefixed.
1461 */
1462
1463 #define ZBA_CHUNK_SIZE PAGE_MAX_SIZE
1464 #define ZBA_GRANULE sizeof(uint64_t)
1465 #define ZBA_GRANULE_BITS (8 * sizeof(uint64_t))
1466 #define ZBA_MAX_ORDER (PAGE_MAX_SHIFT - 4)
1467 #define ZBA_MAX_ALLOC_ORDER 7
1468 #define ZBA_SLOTS (ZBA_CHUNK_SIZE / ZBA_GRANULE)
1469 static_assert(2ul * ZBA_GRANULE << ZBA_MAX_ORDER == ZBA_CHUNK_SIZE, "chunk sizes");
1470 static_assert(ZBA_MAX_ALLOC_ORDER <= ZBA_MAX_ORDER, "ZBA_MAX_ORDER is enough");
1471
1472 struct zone_bits_chain {
1473 uint32_t zbc_next;
1474 uint32_t zbc_prev;
1475 } __attribute__((aligned(ZBA_GRANULE)));
1476
1477 struct zone_bits_head {
1478 uint32_t zbh_next;
1479 uint32_t zbh_unused;
1480 } __attribute__((aligned(ZBA_GRANULE)));
1481
1482 static_assert(sizeof(struct zone_bits_chain) == ZBA_GRANULE, "zbc size");
1483 static_assert(sizeof(struct zone_bits_head) == ZBA_GRANULE, "zbh size");
1484
1485 struct zone_bits_allocator_meta {
1486 uint32_t zbam_chunks;
1487 uint32_t __zbam_padding;
1488 struct zone_bits_head zbam_lists[ZBA_MAX_ORDER + 1];
1489 };
1490
1491 struct zone_bits_allocator_header {
1492 uint64_t zbah_bits[ZBA_SLOTS / (8 * sizeof(uint64_t))];
1493 };
1494
1495 #if ZALLOC_TEST
1496 static struct zalloc_bits_allocator_test_setup {
1497 vm_offset_t zbats_base;
1498 void (*zbats_populate)(vm_address_t addr, vm_size_t size);
1499 } zba_test_info;
1500
1501 static struct zone_bits_allocator_header *
zba_base_header(void)1502 zba_base_header(void)
1503 {
1504 return (struct zone_bits_allocator_header *)zba_test_info.zbats_base;
1505 }
1506
1507 static void
zba_populate(uint32_t n)1508 zba_populate(uint32_t n)
1509 {
1510 vm_address_t base = zba_test_info.zbats_base;
1511 zba_test_info.zbats_populate(base + n * ZBA_CHUNK_SIZE, ZBA_CHUNK_SIZE);
1512 }
1513 #else
1514 __startup_data
1515 static uint8_t zba_chunk_startup[ZBA_CHUNK_SIZE]
1516 __attribute__((aligned(ZBA_CHUNK_SIZE)));
1517 static LCK_MTX_EARLY_DECLARE(zba_mtx, &zone_locks_grp);
1518
1519 static struct zone_bits_allocator_header *
zba_base_header(void)1520 zba_base_header(void)
1521 {
1522 return (struct zone_bits_allocator_header *)zone_info.zi_bits_range.min_address;
1523 }
1524
1525 static void
zba_lock(void)1526 zba_lock(void)
1527 {
1528 lck_mtx_lock(&zba_mtx);
1529 }
1530
1531 static void
zba_unlock(void)1532 zba_unlock(void)
1533 {
1534 lck_mtx_unlock(&zba_mtx);
1535 }
1536
1537 static void
zba_populate(uint32_t n)1538 zba_populate(uint32_t n)
1539 {
1540 vm_size_t size = ZBA_CHUNK_SIZE;
1541 vm_address_t addr;
1542
1543 addr = zone_info.zi_bits_range.min_address + n * size;
1544 if (addr >= zone_info.zi_bits_range.max_address) {
1545 uint64_t zsize = 0;
1546 zone_t z = zone_find_largest(&zsize);
1547 panic("zba_populate: out of bitmap space, "
1548 "likely due to memory leak in zone [%s%s] "
1549 "(%luM, %d elements allocated)",
1550 zone_heap_name(z), zone_name(z),
1551 (unsigned long)zsize >> 20,
1552 zone_count_allocated(z));
1553 }
1554
1555 for (;;) {
1556 kern_return_t kr = KERN_SUCCESS;
1557
1558 if (0 == pmap_find_phys(kernel_pmap, addr)) {
1559 kr = kernel_memory_populate(kernel_map, addr, size,
1560 KMA_NOPAGEWAIT | KMA_KOBJECT | KMA_ZERO,
1561 VM_KERN_MEMORY_OSFMK);
1562 }
1563
1564 if (kr == KERN_SUCCESS) {
1565 return;
1566 }
1567
1568 zba_unlock();
1569 VM_PAGE_WAIT();
1570 zba_lock();
1571 }
1572 }
1573 #endif
1574
1575 __pure2
1576 static struct zone_bits_allocator_meta *
zba_meta(void)1577 zba_meta(void)
1578 {
1579 return (struct zone_bits_allocator_meta *)&zba_base_header()[1];
1580 }
1581
1582 __pure2
1583 static uint64_t *
zba_slot_base(void)1584 zba_slot_base(void)
1585 {
1586 return (uint64_t *)zba_base_header();
1587 }
1588
1589 __pure2
1590 static vm_address_t
zba_page_addr(uint32_t n)1591 zba_page_addr(uint32_t n)
1592 {
1593 return (vm_address_t)zba_base_header() + n * ZBA_CHUNK_SIZE;
1594 }
1595
1596 __pure2
1597 static struct zone_bits_head *
zba_head(uint32_t order)1598 zba_head(uint32_t order)
1599 {
1600 return &zba_meta()->zbam_lists[order];
1601 }
1602
1603 __pure2
1604 static uint32_t
zba_head_index(uint32_t order)1605 zba_head_index(uint32_t order)
1606 {
1607 uint32_t hdr_size = sizeof(struct zone_bits_allocator_header) +
1608 offsetof(struct zone_bits_allocator_meta, zbam_lists);
1609 return (hdr_size / ZBA_GRANULE) + order;
1610 }
1611
1612 __pure2
1613 static struct zone_bits_chain *
zba_chain_for_index(uint32_t index)1614 zba_chain_for_index(uint32_t index)
1615 {
1616 return (struct zone_bits_chain *)(zba_slot_base() + index);
1617 }
1618
1619 __pure2
1620 static uint32_t
zba_chain_to_index(const struct zone_bits_chain * zbc)1621 zba_chain_to_index(const struct zone_bits_chain *zbc)
1622 {
1623 return (uint32_t)((const uint64_t *)zbc - zba_slot_base());
1624 }
1625
1626 __abortlike
1627 static void
zba_head_corruption_panic(uint32_t order)1628 zba_head_corruption_panic(uint32_t order)
1629 {
1630 panic("zone bits allocator head[%d:%p] is corrupt", order,
1631 zba_head(order));
1632 }
1633
1634 __abortlike
1635 static void
zba_chain_corruption_panic(struct zone_bits_chain * a,struct zone_bits_chain * b)1636 zba_chain_corruption_panic(struct zone_bits_chain *a, struct zone_bits_chain *b)
1637 {
1638 panic("zone bits allocator freelist is corrupt (%p <-> %p)", a, b);
1639 }
1640
1641 static void
zba_push_block(struct zone_bits_chain * zbc,uint32_t order)1642 zba_push_block(struct zone_bits_chain *zbc, uint32_t order)
1643 {
1644 struct zone_bits_head *hd = zba_head(order);
1645 uint32_t hd_index = zba_head_index(order);
1646 uint32_t index = zba_chain_to_index(zbc);
1647 struct zone_bits_chain *next;
1648
1649 if (hd->zbh_next) {
1650 next = zba_chain_for_index(hd->zbh_next);
1651 if (next->zbc_prev != hd_index) {
1652 zba_head_corruption_panic(order);
1653 }
1654 next->zbc_prev = index;
1655 }
1656 zbc->zbc_next = hd->zbh_next;
1657 zbc->zbc_prev = hd_index;
1658 hd->zbh_next = index;
1659 }
1660
1661 static void
zba_remove_block(struct zone_bits_chain * zbc)1662 zba_remove_block(struct zone_bits_chain *zbc)
1663 {
1664 struct zone_bits_chain *prev = zba_chain_for_index(zbc->zbc_prev);
1665 uint32_t index = zba_chain_to_index(zbc);
1666
1667 if (prev->zbc_next != index) {
1668 zba_chain_corruption_panic(prev, zbc);
1669 }
1670 if ((prev->zbc_next = zbc->zbc_next)) {
1671 struct zone_bits_chain *next = zba_chain_for_index(zbc->zbc_next);
1672 if (next->zbc_prev != index) {
1673 zba_chain_corruption_panic(zbc, next);
1674 }
1675 next->zbc_prev = zbc->zbc_prev;
1676 }
1677 }
1678
1679 static vm_address_t
zba_try_pop_block(uint32_t order)1680 zba_try_pop_block(uint32_t order)
1681 {
1682 struct zone_bits_head *hd = zba_head(order);
1683 struct zone_bits_chain *zbc;
1684
1685 if (hd->zbh_next == 0) {
1686 return 0;
1687 }
1688
1689 zbc = zba_chain_for_index(hd->zbh_next);
1690 zba_remove_block(zbc);
1691 return (vm_address_t)zbc;
1692 }
1693
1694 static struct zone_bits_allocator_header *
zba_header(vm_offset_t addr)1695 zba_header(vm_offset_t addr)
1696 {
1697 addr &= -(vm_offset_t)ZBA_CHUNK_SIZE;
1698 return (struct zone_bits_allocator_header *)addr;
1699 }
1700
1701 static size_t
zba_node_parent(size_t node)1702 zba_node_parent(size_t node)
1703 {
1704 return (node - 1) / 2;
1705 }
1706
1707 static size_t
zba_node_left_child(size_t node)1708 zba_node_left_child(size_t node)
1709 {
1710 return node * 2 + 1;
1711 }
1712
1713 static size_t
zba_node_buddy(size_t node)1714 zba_node_buddy(size_t node)
1715 {
1716 return ((node - 1) ^ 1) + 1;
1717 }
1718
1719 static size_t
zba_node(vm_offset_t addr,uint32_t order)1720 zba_node(vm_offset_t addr, uint32_t order)
1721 {
1722 vm_offset_t offs = (addr % ZBA_CHUNK_SIZE) / ZBA_GRANULE;
1723 return (offs >> order) + (1 << (ZBA_MAX_ORDER - order + 1)) - 1;
1724 }
1725
1726 static struct zone_bits_chain *
zba_chain_for_node(struct zone_bits_allocator_header * zbah,size_t node,uint32_t order)1727 zba_chain_for_node(struct zone_bits_allocator_header *zbah, size_t node, uint32_t order)
1728 {
1729 vm_offset_t offs = (node - (1 << (ZBA_MAX_ORDER - order + 1)) + 1) << order;
1730 return (struct zone_bits_chain *)((vm_offset_t)zbah + offs * ZBA_GRANULE);
1731 }
1732
1733 static void
zba_node_flip_split(struct zone_bits_allocator_header * zbah,size_t node)1734 zba_node_flip_split(struct zone_bits_allocator_header *zbah, size_t node)
1735 {
1736 zbah->zbah_bits[node / 64] ^= 1ull << (node % 64);
1737 }
1738
1739 static bool
zba_node_is_split(struct zone_bits_allocator_header * zbah,size_t node)1740 zba_node_is_split(struct zone_bits_allocator_header *zbah, size_t node)
1741 {
1742 return zbah->zbah_bits[node / 64] & (1ull << (node % 64));
1743 }
1744
1745 static void
zba_free(vm_offset_t addr,uint32_t order)1746 zba_free(vm_offset_t addr, uint32_t order)
1747 {
1748 struct zone_bits_allocator_header *zbah = zba_header(addr);
1749 struct zone_bits_chain *zbc;
1750 size_t node = zba_node(addr, order);
1751
1752 while (node) {
1753 size_t parent = zba_node_parent(node);
1754
1755 zba_node_flip_split(zbah, parent);
1756 if (zba_node_is_split(zbah, parent)) {
1757 break;
1758 }
1759
1760 zbc = zba_chain_for_node(zbah, zba_node_buddy(node), order);
1761 zba_remove_block(zbc);
1762 order++;
1763 node = parent;
1764 }
1765
1766 zba_push_block(zba_chain_for_node(zbah, node, order), order);
1767 }
1768
1769 static vm_size_t
zba_chunk_header_size(uint32_t n)1770 zba_chunk_header_size(uint32_t n)
1771 {
1772 vm_size_t hdr_size = sizeof(struct zone_bits_allocator_header);
1773 if (n == 0) {
1774 hdr_size += sizeof(struct zone_bits_allocator_meta);
1775 }
1776 return hdr_size;
1777 }
1778
1779 static void
zba_init_chunk(uint32_t n)1780 zba_init_chunk(uint32_t n)
1781 {
1782 vm_size_t hdr_size = zba_chunk_header_size(n);
1783 vm_offset_t page = zba_page_addr(n);
1784 struct zone_bits_allocator_header *zbah = zba_header(page);
1785 vm_size_t size = ZBA_CHUNK_SIZE;
1786 size_t node;
1787
1788 for (uint32_t o = ZBA_MAX_ORDER + 1; o-- > 0;) {
1789 if (size < hdr_size + (ZBA_GRANULE << o)) {
1790 continue;
1791 }
1792 size -= ZBA_GRANULE << o;
1793 node = zba_node(page + size, o);
1794 zba_node_flip_split(zbah, zba_node_parent(node));
1795 zba_push_block(zba_chain_for_node(zbah, node, o), o);
1796 }
1797
1798 zba_meta()->zbam_chunks = n + 1;
1799 }
1800
1801 __attribute__((noinline))
1802 static void
zba_grow(void)1803 zba_grow(void)
1804 {
1805 uint32_t chunk = zba_meta()->zbam_chunks;
1806
1807 zba_populate(chunk);
1808 if (zba_meta()->zbam_chunks == chunk) {
1809 zba_init_chunk(chunk);
1810 }
1811 }
1812
1813 static vm_offset_t
zba_alloc(uint32_t order)1814 zba_alloc(uint32_t order)
1815 {
1816 struct zone_bits_allocator_header *zbah;
1817 uint32_t cur = order;
1818 vm_address_t addr;
1819 size_t node;
1820
1821 while ((addr = zba_try_pop_block(cur)) == 0) {
1822 if (cur++ >= ZBA_MAX_ORDER) {
1823 zba_grow();
1824 cur = order;
1825 }
1826 }
1827
1828 zbah = zba_header(addr);
1829 node = zba_node(addr, cur);
1830 zba_node_flip_split(zbah, zba_node_parent(node));
1831 while (cur > order) {
1832 cur--;
1833 zba_node_flip_split(zbah, node);
1834 node = zba_node_left_child(node);
1835 zba_push_block(zba_chain_for_node(zbah, node + 1, cur), cur);
1836 }
1837
1838 return addr;
1839 }
1840
1841 #define zba_map_index(type, n) (n / (8 * sizeof(type)))
1842 #define zba_map_bit(type, n) ((type)1 << (n % (8 * sizeof(type))))
1843 #define zba_map_mask_lt(type, n) (zba_map_bit(type, n) - 1)
1844 #define zba_map_mask_ge(type, n) ((type)-zba_map_bit(type, n))
1845
1846 #if !ZALLOC_TEST
1847 static uint32_t
zba_bits_ref_order(uint32_t bref)1848 zba_bits_ref_order(uint32_t bref)
1849 {
1850 return bref & 0x7;
1851 }
1852
1853 static bitmap_t *
zba_bits_ref_ptr(uint32_t bref)1854 zba_bits_ref_ptr(uint32_t bref)
1855 {
1856 return zba_slot_base() + (bref >> 3);
1857 }
1858
1859 static vm_offset_t
zba_scan_bitmap_inline(zone_t zone,struct zone_page_metadata * meta,zalloc_flags_t flags,vm_offset_t eidx)1860 zba_scan_bitmap_inline(zone_t zone, struct zone_page_metadata *meta,
1861 zalloc_flags_t flags, vm_offset_t eidx)
1862 {
1863 size_t i = eidx / 32;
1864 uint32_t map;
1865
1866 if (eidx % 32) {
1867 map = meta[i].zm_bitmap & zba_map_mask_ge(uint32_t, eidx);
1868 if (map) {
1869 eidx = __builtin_ctz(map);
1870 meta[i].zm_bitmap ^= 1u << eidx;
1871 return i * 32 + eidx;
1872 }
1873 i++;
1874 }
1875
1876 uint32_t chunk_len = meta->zm_chunk_len;
1877 if (flags & Z_PCPU) {
1878 chunk_len = zpercpu_count();
1879 }
1880 for (int j = 0; j < chunk_len; j++, i++) {
1881 if (i >= chunk_len) {
1882 i = 0;
1883 }
1884 if (__probable(map = meta[i].zm_bitmap)) {
1885 meta[i].zm_bitmap &= map - 1;
1886 return i * 32 + __builtin_ctz(map);
1887 }
1888 }
1889
1890 zone_page_meta_accounting_panic(zone, meta, "zm_bitmap");
1891 }
1892
1893 static vm_offset_t
zba_scan_bitmap_ref(zone_t zone,struct zone_page_metadata * meta,vm_offset_t eidx)1894 zba_scan_bitmap_ref(zone_t zone, struct zone_page_metadata *meta,
1895 vm_offset_t eidx)
1896 {
1897 uint32_t bits_size = 1 << zba_bits_ref_order(meta->zm_bitmap);
1898 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
1899 size_t i = eidx / 64;
1900 uint64_t map;
1901
1902 if (eidx % 64) {
1903 map = bits[i] & zba_map_mask_ge(uint64_t, eidx);
1904 if (map) {
1905 eidx = __builtin_ctzll(map);
1906 bits[i] ^= 1ull << eidx;
1907 return i * 64 + eidx;
1908 }
1909 i++;
1910 }
1911
1912 for (int j = 0; j < bits_size; i++, j++) {
1913 if (i >= bits_size) {
1914 i = 0;
1915 }
1916 if (__probable(map = bits[i])) {
1917 bits[i] &= map - 1;
1918 return i * 64 + __builtin_ctzll(map);
1919 }
1920 }
1921
1922 zone_page_meta_accounting_panic(zone, meta, "zm_bitmap");
1923 }
1924
1925 /*!
1926 * @function zone_meta_find_and_clear_bit
1927 *
1928 * @brief
1929 * The core of the bitmap allocator: find a bit set in the bitmaps.
1930 *
1931 * @discussion
1932 * This method will round robin through available allocations,
1933 * with a per-core memory of the last allocated element index allocated.
1934 *
1935 * This is done in order to avoid a fully LIFO behavior which makes exploiting
1936 * double-free bugs way too practical.
1937 *
1938 * @param zone The zone we're allocating from.
1939 * @param meta The main metadata for the chunk being allocated from.
1940 * @param flags the alloc flags (for @c Z_PCPU).
1941 */
1942 static vm_offset_t
zone_meta_find_and_clear_bit(zone_t zone,struct zone_page_metadata * meta,zalloc_flags_t flags)1943 zone_meta_find_and_clear_bit(zone_t zone, struct zone_page_metadata *meta,
1944 zalloc_flags_t flags)
1945 {
1946 zone_stats_t zs = zpercpu_get(zone->z_stats);
1947 vm_offset_t eidx = zs->zs_alloc_rr + 1;
1948
1949 if (meta->zm_inline_bitmap) {
1950 eidx = zba_scan_bitmap_inline(zone, meta, flags, eidx);
1951 } else {
1952 eidx = zba_scan_bitmap_ref(zone, meta, eidx);
1953 }
1954 zs->zs_alloc_rr = (uint16_t)eidx;
1955 return eidx;
1956 }
1957
1958 /*!
1959 * @function zone_meta_bits_init
1960 *
1961 * @brief
1962 * Initializes the zm_bitmap field(s) for a newly assigned chunk.
1963 *
1964 * @param meta The main metadata for the initialized chunk.
1965 * @param count The number of elements the chunk can hold
1966 * (which might be partial for partially populated chunks).
1967 * @param nbits The maximum nuber of bits that will be used.
1968 */
1969 static void
zone_meta_bits_init(struct zone_page_metadata * meta,uint32_t count,uint32_t nbits)1970 zone_meta_bits_init(struct zone_page_metadata *meta,
1971 uint32_t count, uint32_t nbits)
1972 {
1973 static_assert(ZONE_MAX_ALLOC_SIZE / ZONE_MIN_ELEM_SIZE <=
1974 ZBA_GRANULE_BITS << ZBA_MAX_ORDER, "bitmaps will be large enough");
1975
1976 if (meta->zm_inline_bitmap) {
1977 /*
1978 * We're called with the metadata zm_bitmap fields already
1979 * zeroed out.
1980 */
1981 for (size_t i = 0; 32 * i < count; i++) {
1982 if (32 * i + 32 <= count) {
1983 meta[i].zm_bitmap = ~0u;
1984 } else {
1985 meta[i].zm_bitmap = zba_map_mask_lt(uint32_t, count);
1986 }
1987 }
1988 } else {
1989 uint32_t order = flsll((nbits - 1) / ZBA_GRANULE_BITS);
1990 uint64_t *bits;
1991
1992 assert(order <= ZBA_MAX_ALLOC_ORDER);
1993 assert(count <= ZBA_GRANULE_BITS << order);
1994
1995 zba_lock();
1996 bits = (uint64_t *)zba_alloc(order);
1997 zba_unlock();
1998
1999 for (size_t i = 0; i < 1u << order; i++) {
2000 if (64 * i + 64 <= count) {
2001 bits[i] = ~0ull;
2002 } else if (64 * i < count) {
2003 bits[i] = zba_map_mask_lt(uint64_t, count);
2004 } else {
2005 bits[i] = 0ull;
2006 }
2007 }
2008
2009 meta->zm_bitmap = (uint32_t)((vm_offset_t)bits -
2010 (vm_offset_t)zba_slot_base()) + order;
2011 }
2012 }
2013
2014 /*!
2015 * @function zone_meta_bits_merge
2016 *
2017 * @brief
2018 * Adds elements <code>[start, end)</code> to a chunk being extended.
2019 *
2020 * @param meta The main metadata for the extended chunk.
2021 * @param start The index of the first element to add to the chunk.
2022 * @param end The index of the last (exclusive) element to add.
2023 */
2024 static void
zone_meta_bits_merge(struct zone_page_metadata * meta,uint32_t start,uint32_t end)2025 zone_meta_bits_merge(struct zone_page_metadata *meta,
2026 uint32_t start, uint32_t end)
2027 {
2028 if (meta->zm_inline_bitmap) {
2029 while (start < end) {
2030 size_t s_i = start / 32;
2031 size_t s_e = end / 32;
2032
2033 if (s_i == s_e) {
2034 meta[s_i].zm_bitmap |= zba_map_mask_lt(uint32_t, end) &
2035 zba_map_mask_ge(uint32_t, start);
2036 break;
2037 }
2038
2039 meta[s_i].zm_bitmap |= zba_map_mask_ge(uint32_t, start);
2040 start += 32 - (start % 32);
2041 }
2042 } else {
2043 uint64_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2044
2045 while (start < end) {
2046 size_t s_i = start / 64;
2047 size_t s_e = end / 64;
2048
2049 if (s_i == s_e) {
2050 bits[s_i] |= zba_map_mask_lt(uint64_t, end) &
2051 zba_map_mask_ge(uint64_t, start);
2052 break;
2053 }
2054 bits[s_i] |= zba_map_mask_ge(uint64_t, start);
2055 start += 64 - (start % 64);
2056 }
2057 }
2058 }
2059
2060 /*!
2061 * @function zone_bits_free
2062 *
2063 * @brief
2064 * Frees a bitmap to the zone bitmap allocator.
2065 *
2066 * @param bref
2067 * A bitmap reference set by @c zone_meta_bits_init() in a @c zm_bitmap field.
2068 */
2069 static void
zone_bits_free(uint32_t bref)2070 zone_bits_free(uint32_t bref)
2071 {
2072 zba_lock();
2073 zba_free((vm_offset_t)zba_bits_ref_ptr(bref), zba_bits_ref_order(bref));
2074 zba_unlock();
2075 }
2076
2077 /*!
2078 * @function zone_meta_is_free
2079 *
2080 * @brief
2081 * Returns whether a given element appears free.
2082 */
2083 static bool
zone_meta_is_free(struct zone_page_metadata * meta,zone_element_t ze)2084 zone_meta_is_free(struct zone_page_metadata *meta, zone_element_t ze)
2085 {
2086 vm_offset_t eidx = zone_element_idx(ze);
2087 if (meta->zm_inline_bitmap) {
2088 uint32_t bit = zba_map_bit(uint32_t, eidx);
2089 return meta[zba_map_index(uint32_t, eidx)].zm_bitmap & bit;
2090 } else {
2091 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2092 uint64_t bit = zba_map_bit(uint64_t, eidx);
2093 return bits[zba_map_index(uint64_t, eidx)] & bit;
2094 }
2095 }
2096
2097 /*!
2098 * @function zone_meta_mark_free
2099 *
2100 * @brief
2101 * Marks an element as free and returns whether it was marked as used.
2102 */
2103 static bool
zone_meta_mark_free(struct zone_page_metadata * meta,zone_element_t ze)2104 zone_meta_mark_free(struct zone_page_metadata *meta, zone_element_t ze)
2105 {
2106 vm_offset_t eidx = zone_element_idx(ze);
2107
2108 if (meta->zm_inline_bitmap) {
2109 uint32_t bit = zba_map_bit(uint32_t, eidx);
2110 if (meta[zba_map_index(uint32_t, eidx)].zm_bitmap & bit) {
2111 return false;
2112 }
2113 meta[zba_map_index(uint32_t, eidx)].zm_bitmap ^= bit;
2114 } else {
2115 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2116 uint64_t bit = zba_map_bit(uint64_t, eidx);
2117 if (bits[zba_map_index(uint64_t, eidx)] & bit) {
2118 return false;
2119 }
2120 bits[zba_map_index(uint64_t, eidx)] ^= bit;
2121 }
2122 return true;
2123 }
2124
2125 /*!
2126 * @function zone_meta_mark_used
2127 *
2128 * @brief
2129 * Marks an element as used and returns whether it was marked as free
2130 */
2131 static bool
zone_meta_mark_used(struct zone_page_metadata * meta,zone_element_t ze)2132 zone_meta_mark_used(struct zone_page_metadata *meta, zone_element_t ze)
2133 {
2134 vm_offset_t eidx = zone_element_idx(ze);
2135
2136 if (meta->zm_inline_bitmap) {
2137 uint32_t bit = zba_map_bit(uint32_t, eidx);
2138 if (meta[zba_map_index(uint32_t, eidx)].zm_bitmap & bit) {
2139 meta[zba_map_index(uint32_t, eidx)].zm_bitmap ^= bit;
2140 return true;
2141 }
2142 } else {
2143 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
2144 uint64_t bit = zba_map_bit(uint64_t, eidx);
2145 if (bits[zba_map_index(uint64_t, eidx)] & bit) {
2146 bits[zba_map_index(uint64_t, eidx)] ^= bit;
2147 return true;
2148 }
2149 }
2150 return false;
2151 }
2152
2153 #endif /* !ZALLOC_TEST */
2154 /*! @} */
2155 #pragma mark ZTAGS
2156 #if !ZALLOC_TEST
2157 #if VM_TAG_SIZECLASSES
2158 /*
2159 * Zone tagging allows for per "tag" accounting of allocations for the kalloc
2160 * zones only.
2161 *
2162 * There are 3 kinds of tags that can be used:
2163 * - pre-registered VM_KERN_MEMORY_*
2164 * - dynamic tags allocated per call sites in core-kernel (using vm_tag_alloc())
2165 * - per-kext tags computed by IOKit (using the magic VM_TAG_BT marker).
2166 *
2167 * The VM tracks the statistics in lazily allocated structures.
2168 * See vm_tag_will_update_zone(), vm_tag_update_zone_size().
2169 *
2170 * If for some reason the requested tag cannot be accounted for,
2171 * the tag is forced to VM_KERN_MEMORY_KALLOC which is pre-allocated.
2172 *
2173 * Each allocated element also remembers the tag it was assigned,
2174 * in its ztSlot() which lets zalloc/zfree update statistics correctly.
2175 */
2176
2177 // for zones with tagging enabled:
2178
2179 // calculate a pointer to the tag base entry,
2180 // holding either a uint32_t the first tag offset for a page in the zone map,
2181 // or two uint16_t tags if the page can only hold one or two elements
2182
2183 #define ZTAGBASE(zone, element) \
2184 (&((uint32_t *)zone_tagbase_min)[atop((element) - \
2185 zone_info.zi_map_range[ZONE_ADDR_NATIVE].min_address)])
2186
2187 static vm_offset_t zone_tagbase_min;
2188 static vm_offset_t zone_tagbase_max;
2189 static vm_offset_t zone_tagbase_map_size;
2190 static vm_map_t zone_tagbase_map;
2191
2192 static vm_offset_t zone_tags_min;
2193 static vm_offset_t zone_tags_max;
2194 static vm_offset_t zone_tags_map_size;
2195 static vm_map_t zone_tags_map;
2196
2197 // simple heap allocator for allocating the tags for new memory
2198
2199 static LCK_MTX_EARLY_DECLARE(ztLock, &zone_locks_grp); /* heap lock */
2200
2201 /*
2202 * Array of all sizeclasses used by kalloc variants so that we can
2203 * have accounting per size class for each kalloc callsite
2204 */
2205 uint16_t zone_tags_sizeclasses[VM_TAG_SIZECLASSES];
2206
2207 enum{
2208 ztFreeIndexCount = 8,
2209 ztFreeIndexMax = (ztFreeIndexCount - 1),
2210 ztTagsPerBlock = 4
2211 };
2212
2213 struct ztBlock {
2214 #if __LITTLE_ENDIAN__
2215 uint64_t free:1,
2216 next:21,
2217 prev:21,
2218 size:21;
2219 #else
2220 // ztBlock needs free bit least significant
2221 #error !__LITTLE_ENDIAN__
2222 #endif
2223 };
2224 typedef struct ztBlock ztBlock;
2225
2226 static ztBlock * ztBlocks;
2227 static uint32_t ztBlocksCount;
2228 static uint32_t ztBlocksFree;
2229
2230 static uint32_t
ztLog2up(uint32_t size)2231 ztLog2up(uint32_t size)
2232 {
2233 if (1 == size) {
2234 size = 0;
2235 } else {
2236 size = 32 - __builtin_clz(size - 1);
2237 }
2238 return size;
2239 }
2240
2241 // pointer to the tag for an element
2242 static vm_tag_t *
ztSlot(zone_t zone,vm_offset_t element)2243 ztSlot(zone_t zone, vm_offset_t element)
2244 {
2245 vm_tag_t *result;
2246 if (zone->z_tags_inline) {
2247 result = (vm_tag_t *)ZTAGBASE(zone, element);
2248 if ((PAGE_MASK & element) >= zone_elem_size(zone)) {
2249 result++;
2250 }
2251 } else {
2252 result = &((vm_tag_t *)zone_tags_min)[ZTAGBASE(zone, element)[0] +
2253 (element & PAGE_MASK) / zone_elem_size(zone)];
2254 }
2255 return result;
2256 }
2257
2258 static uint32_t
ztLog2down(uint32_t size)2259 ztLog2down(uint32_t size)
2260 {
2261 size = 31 - __builtin_clz(size);
2262 return size;
2263 }
2264
2265 static void
ztFault(vm_map_t map,const void * address,size_t size,uint32_t flags)2266 ztFault(vm_map_t map, const void * address, size_t size, uint32_t flags)
2267 {
2268 vm_map_offset_t addr = (vm_map_offset_t) address;
2269 vm_map_offset_t page, end;
2270
2271 page = trunc_page(addr);
2272 end = round_page(addr + size);
2273
2274 for (; page < end; page += page_size) {
2275 if (!pmap_find_phys(kernel_pmap, page)) {
2276 kern_return_t __unused
2277 ret = kernel_memory_populate(map, page, PAGE_SIZE,
2278 KMA_KOBJECT | flags, VM_KERN_MEMORY_DIAG);
2279 assert(ret == KERN_SUCCESS);
2280 }
2281 }
2282 }
2283
2284 static boolean_t
ztPresent(const void * address,size_t size)2285 ztPresent(const void * address, size_t size)
2286 {
2287 vm_map_offset_t addr = (vm_map_offset_t) address;
2288 vm_map_offset_t page, end;
2289 boolean_t result;
2290
2291 page = trunc_page(addr);
2292 end = round_page(addr + size);
2293 for (result = TRUE; (page < end); page += page_size) {
2294 result = pmap_find_phys(kernel_pmap, page);
2295 if (!result) {
2296 break;
2297 }
2298 }
2299 return result;
2300 }
2301
2302
2303 void __unused
2304 ztDump(boolean_t sanity);
2305 void __unused
ztDump(boolean_t sanity)2306 ztDump(boolean_t sanity)
2307 {
2308 uint32_t q, cq, p;
2309
2310 for (q = 0; q <= ztFreeIndexMax; q++) {
2311 p = q;
2312 do{
2313 if (sanity) {
2314 cq = ztLog2down(ztBlocks[p].size);
2315 if (cq > ztFreeIndexMax) {
2316 cq = ztFreeIndexMax;
2317 }
2318 if (!ztBlocks[p].free
2319 || ((p != q) && (q != cq))
2320 || (ztBlocks[ztBlocks[p].next].prev != p)
2321 || (ztBlocks[ztBlocks[p].prev].next != p)) {
2322 kprintf("zterror at %d", p);
2323 ztDump(FALSE);
2324 kprintf("zterror at %d", p);
2325 assert(FALSE);
2326 }
2327 continue;
2328 }
2329 kprintf("zt[%03d]%c %d, %d, %d\n",
2330 p, ztBlocks[p].free ? 'F' : 'A',
2331 ztBlocks[p].next, ztBlocks[p].prev,
2332 ztBlocks[p].size);
2333 p = ztBlocks[p].next;
2334 if (p == q) {
2335 break;
2336 }
2337 }while (p != q);
2338 if (!sanity) {
2339 printf("\n");
2340 }
2341 }
2342 if (!sanity) {
2343 printf("-----------------------\n");
2344 }
2345 }
2346
2347
2348
2349 #define ZTBDEQ(idx) \
2350 ztBlocks[ztBlocks[(idx)].prev].next = ztBlocks[(idx)].next; \
2351 ztBlocks[ztBlocks[(idx)].next].prev = ztBlocks[(idx)].prev;
2352
2353 static void
ztFree(zone_t zone __unused,uint32_t index,uint32_t count)2354 ztFree(zone_t zone __unused, uint32_t index, uint32_t count)
2355 {
2356 uint32_t q, w, p, size, merge;
2357
2358 assert(count);
2359 ztBlocksFree += count;
2360
2361 // merge with preceding
2362 merge = (index + count);
2363 if ((merge < ztBlocksCount)
2364 && ztPresent(&ztBlocks[merge], sizeof(ztBlocks[merge]))
2365 && ztBlocks[merge].free) {
2366 ZTBDEQ(merge);
2367 count += ztBlocks[merge].size;
2368 }
2369
2370 // merge with following
2371 merge = (index - 1);
2372 if ((merge > ztFreeIndexMax)
2373 && ztPresent(&ztBlocks[merge], sizeof(ztBlocks[merge]))
2374 && ztBlocks[merge].free) {
2375 size = ztBlocks[merge].size;
2376 count += size;
2377 index -= size;
2378 ZTBDEQ(index);
2379 }
2380
2381 q = ztLog2down(count);
2382 if (q > ztFreeIndexMax) {
2383 q = ztFreeIndexMax;
2384 }
2385 w = q;
2386 // queue in order of size
2387 while (TRUE) {
2388 p = ztBlocks[w].next;
2389 if (p == q) {
2390 break;
2391 }
2392 if (ztBlocks[p].size >= count) {
2393 break;
2394 }
2395 w = p;
2396 }
2397 ztBlocks[p].prev = index;
2398 ztBlocks[w].next = index;
2399
2400 // fault in first
2401 ztFault(zone_tags_map, &ztBlocks[index], sizeof(ztBlocks[index]), 0);
2402
2403 // mark first & last with free flag and size
2404 ztBlocks[index].free = TRUE;
2405 ztBlocks[index].size = count;
2406 ztBlocks[index].prev = w;
2407 ztBlocks[index].next = p;
2408 if (count > 1) {
2409 index += (count - 1);
2410 // fault in last
2411 ztFault(zone_tags_map, &ztBlocks[index], sizeof(ztBlocks[index]), 0);
2412 ztBlocks[index].free = TRUE;
2413 ztBlocks[index].size = count;
2414 }
2415 }
2416
2417 static uint32_t
ztAlloc(zone_t zone,uint32_t count)2418 ztAlloc(zone_t zone, uint32_t count)
2419 {
2420 uint32_t q, w, p, leftover;
2421
2422 assert(count);
2423
2424 q = ztLog2up(count);
2425 if (q > ztFreeIndexMax) {
2426 q = ztFreeIndexMax;
2427 }
2428 do{
2429 w = q;
2430 while (TRUE) {
2431 p = ztBlocks[w].next;
2432 if (p == q) {
2433 break;
2434 }
2435 if (ztBlocks[p].size >= count) {
2436 // dequeue, mark both ends allocated
2437 ztBlocks[w].next = ztBlocks[p].next;
2438 ztBlocks[ztBlocks[p].next].prev = w;
2439 ztBlocks[p].free = FALSE;
2440 ztBlocksFree -= ztBlocks[p].size;
2441 if (ztBlocks[p].size > 1) {
2442 ztBlocks[p + ztBlocks[p].size - 1].free = FALSE;
2443 }
2444
2445 // fault all the allocation
2446 ztFault(zone_tags_map, &ztBlocks[p], count * sizeof(ztBlocks[p]), 0);
2447 // mark last as allocated
2448 if (count > 1) {
2449 ztBlocks[p + count - 1].free = FALSE;
2450 }
2451 // free remainder
2452 leftover = ztBlocks[p].size - count;
2453 if (leftover) {
2454 ztFree(zone, p + ztBlocks[p].size - leftover, leftover);
2455 }
2456
2457 return p;
2458 }
2459 w = p;
2460 }
2461 q++;
2462 }while (q <= ztFreeIndexMax);
2463
2464 return -1U;
2465 }
2466
2467 __startup_func
2468 static void
zone_tagging_init(vm_size_t max_zonemap_size)2469 zone_tagging_init(vm_size_t max_zonemap_size)
2470 {
2471 kern_return_t ret;
2472 vm_map_kernel_flags_t vmk_flags;
2473 uint32_t idx;
2474
2475 // allocate submaps VM_KERN_MEMORY_DIAG
2476
2477 zone_tagbase_map_size = atop(max_zonemap_size) * sizeof(uint32_t);
2478 vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
2479 vmk_flags.vmkf_permanent = TRUE;
2480 ret = kmem_suballoc(kernel_map, &zone_tagbase_min, zone_tagbase_map_size,
2481 FALSE, VM_FLAGS_ANYWHERE, vmk_flags, VM_KERN_MEMORY_DIAG,
2482 &zone_tagbase_map);
2483
2484 if (ret != KERN_SUCCESS) {
2485 panic("zone_init: kmem_suballoc failed");
2486 }
2487 zone_tagbase_max = zone_tagbase_min + round_page(zone_tagbase_map_size);
2488
2489 zone_tags_map_size = 2048 * 1024 * sizeof(vm_tag_t);
2490 vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
2491 vmk_flags.vmkf_permanent = TRUE;
2492 ret = kmem_suballoc(kernel_map, &zone_tags_min, zone_tags_map_size,
2493 FALSE, VM_FLAGS_ANYWHERE, vmk_flags, VM_KERN_MEMORY_DIAG,
2494 &zone_tags_map);
2495
2496 if (ret != KERN_SUCCESS) {
2497 panic("zone_init: kmem_suballoc failed");
2498 }
2499 zone_tags_max = zone_tags_min + round_page(zone_tags_map_size);
2500
2501 ztBlocks = (ztBlock *) zone_tags_min;
2502 ztBlocksCount = (uint32_t)(zone_tags_map_size / sizeof(ztBlock));
2503
2504 // initialize the qheads
2505 lck_mtx_lock(&ztLock);
2506
2507 ztFault(zone_tags_map, &ztBlocks[0], sizeof(ztBlocks[0]), 0);
2508 for (idx = 0; idx < ztFreeIndexCount; idx++) {
2509 ztBlocks[idx].free = TRUE;
2510 ztBlocks[idx].next = idx;
2511 ztBlocks[idx].prev = idx;
2512 ztBlocks[idx].size = 0;
2513 }
2514 // free remaining space
2515 ztFree(NULL, ztFreeIndexCount, ztBlocksCount - ztFreeIndexCount);
2516
2517 lck_mtx_unlock(&ztLock);
2518 }
2519
2520 static void
ztMemoryAdd(zone_t zone,vm_offset_t mem,vm_size_t size)2521 ztMemoryAdd(zone_t zone, vm_offset_t mem, vm_size_t size)
2522 {
2523 uint32_t * tagbase;
2524 uint32_t count, block, blocks, idx;
2525 size_t pages;
2526
2527 pages = atop(size);
2528 tagbase = ZTAGBASE(zone, mem);
2529
2530 lck_mtx_lock(&ztLock);
2531
2532 // fault tagbase
2533 ztFault(zone_tagbase_map, tagbase, pages * sizeof(uint32_t), 0);
2534
2535 if (!zone->z_tags_inline) {
2536 // allocate tags
2537 count = (uint32_t)(size / zone_elem_size(zone));
2538 blocks = ((count + ztTagsPerBlock - 1) / ztTagsPerBlock);
2539 block = ztAlloc(zone, blocks);
2540 if (-1U == block) {
2541 ztDump(false);
2542 }
2543 assert(-1U != block);
2544 }
2545
2546 lck_mtx_unlock(&ztLock);
2547
2548 if (!zone->z_tags_inline) {
2549 // set tag base for each page
2550 block *= ztTagsPerBlock;
2551 for (idx = 0; idx < pages; idx++) {
2552 vm_offset_t esize = zone_elem_size(zone);
2553 tagbase[idx] = block + (uint32_t)((ptoa(idx) + esize - 1) / esize);
2554 }
2555 }
2556 }
2557
2558 static void
ztMemoryRemove(zone_t zone,vm_offset_t mem,vm_size_t size)2559 ztMemoryRemove(zone_t zone, vm_offset_t mem, vm_size_t size)
2560 {
2561 uint32_t * tagbase;
2562 uint32_t count, block, blocks, idx;
2563 size_t pages;
2564
2565 // set tag base for each page
2566 pages = atop(size);
2567 tagbase = ZTAGBASE(zone, mem);
2568 block = tagbase[0];
2569 for (idx = 0; idx < pages; idx++) {
2570 tagbase[idx] = 0xFFFFFFFF;
2571 }
2572
2573 lck_mtx_lock(&ztLock);
2574 if (!zone->z_tags_inline) {
2575 count = (uint32_t)(size / zone_elem_size(zone));
2576 blocks = ((count + ztTagsPerBlock - 1) / ztTagsPerBlock);
2577 assert(block != 0xFFFFFFFF);
2578 block /= ztTagsPerBlock;
2579 ztFree(NULL /* zone is unlocked */, block, blocks);
2580 }
2581
2582 lck_mtx_unlock(&ztLock);
2583 }
2584
2585 uint16_t
zone_index_from_tag_index(uint32_t sizeclass_idx)2586 zone_index_from_tag_index(uint32_t sizeclass_idx)
2587 {
2588 return zone_tags_sizeclasses[sizeclass_idx];
2589 }
2590
2591 #endif /* VM_TAG_SIZECLASSES */
2592 #endif /* !ZALLOC_TEST */
2593 #pragma mark zalloc helpers
2594 #if !ZALLOC_TEST
2595
2596 __pure2
2597 static inline uint16_t
zc_mag_size(void)2598 zc_mag_size(void)
2599 {
2600 return zc_magazine_size;
2601 }
2602
2603 __attribute__((noinline, cold))
2604 static void
zone_lock_was_contended(zone_t zone,zone_cache_t zc)2605 zone_lock_was_contended(zone_t zone, zone_cache_t zc)
2606 {
2607 lck_spin_lock_nopreempt(&zone->z_lock);
2608
2609 /*
2610 * If zone caching has been disabled due to memory pressure,
2611 * then recording contention is not useful, give the system
2612 * time to recover.
2613 */
2614 if (__improbable(zone_caching_disabled)) {
2615 return;
2616 }
2617
2618 zone->z_contention_cur++;
2619
2620 if (zc == NULL || zc->zc_depot_max >= INT16_MAX * zc_mag_size()) {
2621 return;
2622 }
2623
2624 /*
2625 * Let the depot grow based on how bad the contention is,
2626 * and how populated the zone is.
2627 */
2628 if (zone->z_contention_wma < 2 * Z_CONTENTION_WMA_UNIT) {
2629 if (zc->zc_depot_max * zpercpu_count() * 20u >=
2630 zone->z_elems_avail) {
2631 return;
2632 }
2633 }
2634 if (zone->z_contention_wma < 4 * Z_CONTENTION_WMA_UNIT) {
2635 if (zc->zc_depot_max * zpercpu_count() * 10u >=
2636 zone->z_elems_avail) {
2637 return;
2638 }
2639 }
2640 if (!zc_grow_threshold || zone->z_contention_wma <
2641 zc_grow_threshold * Z_CONTENTION_WMA_UNIT) {
2642 return;
2643 }
2644
2645 zc->zc_depot_max++;
2646 }
2647
2648 static inline void
zone_lock_nopreempt_check_contention(zone_t zone,zone_cache_t zc)2649 zone_lock_nopreempt_check_contention(zone_t zone, zone_cache_t zc)
2650 {
2651 if (lck_spin_try_lock_nopreempt(&zone->z_lock)) {
2652 return;
2653 }
2654
2655 zone_lock_was_contended(zone, zc);
2656 }
2657
2658 static inline void
zone_lock_check_contention(zone_t zone,zone_cache_t zc)2659 zone_lock_check_contention(zone_t zone, zone_cache_t zc)
2660 {
2661 disable_preemption();
2662 zone_lock_nopreempt_check_contention(zone, zc);
2663 }
2664
2665 static inline void
zone_unlock_nopreempt(zone_t zone)2666 zone_unlock_nopreempt(zone_t zone)
2667 {
2668 lck_spin_unlock_nopreempt(&zone->z_lock);
2669 }
2670
2671 static inline void
zone_depot_lock_nopreempt(zone_cache_t zc)2672 zone_depot_lock_nopreempt(zone_cache_t zc)
2673 {
2674 hw_lock_bit_nopreempt(&zc->zc_depot_lock, 0, &zone_locks_grp);
2675 }
2676
2677 static inline void
zone_depot_unlock_nopreempt(zone_cache_t zc)2678 zone_depot_unlock_nopreempt(zone_cache_t zc)
2679 {
2680 hw_unlock_bit_nopreempt(&zc->zc_depot_lock, 0);
2681 }
2682
2683 static inline void
zone_depot_lock(zone_cache_t zc)2684 zone_depot_lock(zone_cache_t zc)
2685 {
2686 hw_lock_bit(&zc->zc_depot_lock, 0, &zone_locks_grp);
2687 }
2688
2689 static inline void
zone_depot_unlock(zone_cache_t zc)2690 zone_depot_unlock(zone_cache_t zc)
2691 {
2692 hw_unlock_bit(&zc->zc_depot_lock, 0);
2693 }
2694
2695 const char *
zone_name(zone_t z)2696 zone_name(zone_t z)
2697 {
2698 return z->z_name;
2699 }
2700
2701 const char *
zone_heap_name(zone_t z)2702 zone_heap_name(zone_t z)
2703 {
2704 zone_security_flags_t zsflags = zone_security_config(z);
2705 if (__probable(zsflags.z_kheap_id < KHEAP_ID_COUNT)) {
2706 return kalloc_heap_names[zsflags.z_kheap_id];
2707 }
2708 return "invalid";
2709 }
2710
2711 static uint32_t
zone_alloc_pages_for_nelems(zone_t z,vm_size_t max_elems)2712 zone_alloc_pages_for_nelems(zone_t z, vm_size_t max_elems)
2713 {
2714 vm_size_t elem_count, chunks;
2715
2716 elem_count = ptoa(z->z_percpu ? 1 : z->z_chunk_pages) /
2717 zone_elem_size_safe(z);
2718 chunks = (max_elems + elem_count - 1) / elem_count;
2719
2720 return (uint32_t)MIN(UINT32_MAX, chunks * z->z_chunk_pages);
2721 }
2722
2723 static inline vm_size_t
zone_submaps_approx_size(void)2724 zone_submaps_approx_size(void)
2725 {
2726 vm_size_t size = 0;
2727
2728 for (unsigned idx = 0; idx < Z_SUBMAP_IDX_COUNT; idx++) {
2729 if (zone_submaps[idx] != VM_MAP_NULL) {
2730 size += zone_submaps[idx]->size;
2731 }
2732 }
2733
2734 return size;
2735 }
2736
2737 static void
zone_cache_swap_magazines(zone_cache_t cache)2738 zone_cache_swap_magazines(zone_cache_t cache)
2739 {
2740 uint16_t count_a = cache->zc_alloc_cur;
2741 uint16_t count_f = cache->zc_free_cur;
2742 zone_element_t *elems_a = cache->zc_alloc_elems;
2743 zone_element_t *elems_f = cache->zc_free_elems;
2744
2745 z_debug_assert(count_a <= zc_mag_size());
2746 z_debug_assert(count_f <= zc_mag_size());
2747
2748 cache->zc_alloc_cur = count_f;
2749 cache->zc_free_cur = count_a;
2750 cache->zc_alloc_elems = elems_f;
2751 cache->zc_free_elems = elems_a;
2752 }
2753
2754 /*!
2755 * @function zone_magazine_load
2756 *
2757 * @brief
2758 * Cache the value of @c zm_cur on the cache to avoid a dependent load
2759 * on the allocation fastpath.
2760 */
2761 static void
zone_magazine_load(uint16_t * count,zone_element_t ** elems,zone_magazine_t mag)2762 zone_magazine_load(uint16_t *count, zone_element_t **elems, zone_magazine_t mag)
2763 {
2764 z_debug_assert(mag->zm_cur <= zc_mag_size());
2765 *count = mag->zm_cur;
2766 *elems = mag->zm_elems;
2767 }
2768
2769 /*!
2770 * @function zone_magazine_replace
2771 *
2772 * @brief
2773 * Unlod a magazine and load a new one instead.
2774 */
2775 static zone_magazine_t
zone_magazine_replace(uint16_t * count,zone_element_t ** elems,zone_magazine_t mag)2776 zone_magazine_replace(uint16_t *count, zone_element_t **elems,
2777 zone_magazine_t mag)
2778 {
2779 zone_magazine_t old;
2780
2781 old = (zone_magazine_t)((uintptr_t)*elems -
2782 offsetof(struct zone_magazine, zm_elems));
2783 old->zm_cur = *count;
2784 z_debug_assert(old->zm_cur <= zc_mag_size());
2785 zone_magazine_load(count, elems, mag);
2786
2787 return old;
2788 }
2789
2790 static zone_magazine_t
zone_magazine_alloc(zalloc_flags_t flags)2791 zone_magazine_alloc(zalloc_flags_t flags)
2792 {
2793 return zalloc_flags(zc_magazine_zone, flags | Z_ZERO);
2794 }
2795
2796 static void
zone_magazine_free(zone_magazine_t mag)2797 zone_magazine_free(zone_magazine_t mag)
2798 {
2799 (zfree)(zc_magazine_zone, mag);
2800 }
2801
2802 static void
zone_magazine_free_list(struct zone_depot * mags)2803 zone_magazine_free_list(struct zone_depot *mags)
2804 {
2805 zone_magazine_t mag, tmp;
2806
2807 STAILQ_FOREACH_SAFE(mag, mags, zm_link, tmp) {
2808 zone_magazine_free(mag);
2809 }
2810
2811 STAILQ_INIT(mags);
2812 }
2813
2814 static void
zone_enable_caching(zone_t zone)2815 zone_enable_caching(zone_t zone)
2816 {
2817 zone_cache_t caches;
2818
2819 caches = zalloc_percpu_permanent_type(struct zone_cache);
2820 zpercpu_foreach(zc, caches) {
2821 zone_magazine_load(&zc->zc_alloc_cur, &zc->zc_alloc_elems,
2822 zone_magazine_alloc(Z_WAITOK | Z_NOFAIL));
2823 zone_magazine_load(&zc->zc_free_cur, &zc->zc_free_elems,
2824 zone_magazine_alloc(Z_WAITOK | Z_NOFAIL));
2825 STAILQ_INIT(&zc->zc_depot);
2826 }
2827
2828 if (os_atomic_xchg(&zone->z_pcpu_cache, caches, release)) {
2829 panic("allocating caches for zone %s twice", zone->z_name);
2830 }
2831 }
2832
2833 bool
zone_maps_owned(vm_address_t addr,vm_size_t size)2834 zone_maps_owned(vm_address_t addr, vm_size_t size)
2835 {
2836 return from_zone_map(addr, size, ZONE_ADDR_NATIVE);
2837 }
2838
2839 void
zone_map_sizes(vm_map_size_t * psize,vm_map_size_t * pfree,vm_map_size_t * plargest_free)2840 zone_map_sizes(
2841 vm_map_size_t *psize,
2842 vm_map_size_t *pfree,
2843 vm_map_size_t *plargest_free)
2844 {
2845 vm_map_size_t size, free, largest;
2846
2847 vm_map_sizes(zone_submaps[0], psize, pfree, plargest_free);
2848
2849 for (uint32_t i = 1; i < Z_SUBMAP_IDX_COUNT; i++) {
2850 vm_map_sizes(zone_submaps[i], &size, &free, &largest);
2851 *psize += size;
2852 *pfree += free;
2853 *plargest_free = MAX(*plargest_free, largest);
2854 }
2855 }
2856
2857 __attribute__((always_inline))
2858 vm_map_t
zone_submap(zone_security_flags_t zsflags)2859 zone_submap(zone_security_flags_t zsflags)
2860 {
2861 return zone_submaps[zsflags.z_submap_idx];
2862 }
2863
2864 unsigned
zpercpu_count(void)2865 zpercpu_count(void)
2866 {
2867 return zpercpu_early_count;
2868 }
2869
2870 /*
2871 * Returns a random number between [bound_min, bound_max)
2872 *
2873 * DO NOT COPY THIS CODE OUTSIDE OF ZALLOC
2874 *
2875 * This uses Intel's rdrand because random() uses FP registers
2876 * which causes FP faults and allocations which isn't something
2877 * we can do from zalloc itself due to reentrancy problems.
2878 *
2879 * For pre-rdrand machines (which we no longer support),
2880 * we use a bad biased random generator that doesn't use FP.
2881 * Such HW is no longer supported, but VM of newer OSes on older
2882 * bare metal is made to limp along (with reduced security) this way.
2883 */
2884 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
2885 static uint32_t
zalloc_random_uniform(uint32_t bound_min,uint32_t bound_max)2886 zalloc_random_uniform(uint32_t bound_min, uint32_t bound_max)
2887 {
2888 uint32_t bits = 32 - __builtin_clz(bound_max - bound_min);
2889 uint32_t mask = ~0u >> (32 - bits);
2890 uint32_t v;
2891
2892 do {
2893 #if __x86_64__
2894 if (__probable(cpuid_features() & CPUID_FEATURE_RDRAND)) {
2895 asm volatile ("1: rdrand %0; jnc 1b\n"
2896 : "=r" (v) :: "cc");
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 = (uint32_t)early_random();
2907 #endif
2908 v = bound_min + (v & mask);
2909 } while (v >= bound_max);
2910
2911 return v;
2912 }
2913 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
2914
2915 #if ZONE_ENABLE_LOGGING
2916 /*
2917 * Track all kalloc zones of specified size for zlog name
2918 * kalloc.type.<size> or kalloc.<size>
2919 */
2920 static bool
track_kalloc_zones(const char * logname,zone_t z)2921 track_kalloc_zones(const char *logname, zone_t z)
2922 {
2923 const char *prefix;
2924 size_t len;
2925 zone_security_flags_t zsflags = zone_security_config(z);
2926
2927 prefix = "kalloc.type.";
2928 len = strlen(prefix);
2929 if (zsflags.z_kalloc_type && strncmp(logname, prefix, len) == 0) {
2930 vm_size_t sizeclass = strtoul(logname + len, NULL, 0);
2931
2932 return zone_elem_size(z) == sizeclass;
2933 }
2934
2935 prefix = "kalloc.";
2936 len = strlen(prefix);
2937 if ((zsflags.z_kheap_id || zsflags.z_kalloc_type) &&
2938 strncmp(logname, prefix, len) == 0) {
2939 vm_size_t sizeclass = strtoul(logname + len, NULL, 0);
2940
2941 return zone_elem_size(z) == sizeclass;
2942 }
2943
2944 return false;
2945 }
2946 #endif
2947
2948 int
track_this_zone(const char * zonename,const char * logname)2949 track_this_zone(const char *zonename, const char *logname)
2950 {
2951 unsigned int len;
2952 const char *zc = zonename;
2953 const char *lc = logname;
2954
2955 /*
2956 * Compare the strings. We bound the compare by MAX_ZONE_NAME.
2957 */
2958
2959 for (len = 1; len <= MAX_ZONE_NAME; zc++, lc++, len++) {
2960 /*
2961 * If the current characters don't match, check for a space in
2962 * in the zone name and a corresponding period in the log name.
2963 * If that's not there, then the strings don't match.
2964 */
2965
2966 if (*zc != *lc && !(*zc == ' ' && *lc == '.')) {
2967 break;
2968 }
2969
2970 /*
2971 * The strings are equal so far. If we're at the end, then it's a match.
2972 */
2973
2974 if (*zc == '\0') {
2975 return TRUE;
2976 }
2977 }
2978
2979 return FALSE;
2980 }
2981
2982 #if DEBUG || DEVELOPMENT
2983
2984 vm_size_t
zone_element_info(void * addr,vm_tag_t * ptag)2985 zone_element_info(void *addr, vm_tag_t * ptag)
2986 {
2987 vm_size_t size = 0;
2988 vm_tag_t tag = VM_KERN_MEMORY_NONE;
2989 struct zone *src_zone;
2990
2991 if (from_zone_map(addr, sizeof(void *), ZONE_ADDR_NATIVE) ||
2992 from_zone_map(addr, sizeof(void *), ZONE_ADDR_FOREIGN)) {
2993 src_zone = &zone_array[zone_index_from_ptr(addr)];
2994 #if VM_TAG_SIZECLASSES
2995 if (__improbable(src_zone->z_uses_tags)) {
2996 tag = *ztSlot(src_zone, (vm_offset_t)addr) >> 1;
2997 }
2998 #endif /* VM_TAG_SIZECLASSES */
2999 size = zone_elem_size_safe(src_zone);
3000 } else {
3001 #if CONFIG_GZALLOC
3002 gzalloc_element_size(addr, NULL, &size);
3003 #endif /* CONFIG_GZALLOC */
3004 }
3005 *ptag = tag;
3006 return size;
3007 }
3008
3009 #endif /* DEBUG || DEVELOPMENT */
3010 #endif /* !ZALLOC_TEST */
3011
3012 #pragma mark Zone zeroing and early random
3013 #if !ZALLOC_TEST
3014
3015 /*
3016 * Zone zeroing
3017 *
3018 * All allocations from zones are zeroed on free and are additionally
3019 * check that they are still zero on alloc. The check is
3020 * always on, on embedded devices. Perf regression was detected
3021 * on intel as we cant use the vectorized implementation of
3022 * memcmp_zero_ptr_aligned due to cyclic dependenices between
3023 * initization and allocation. Therefore we perform the check
3024 * on 20% of the allocations.
3025 */
3026 #if ZALLOC_ENABLE_ZERO_CHECK
3027 #if defined(__x86_64__) || defined(__arm__)
3028 /*
3029 * Peform zero validation on every 5th allocation
3030 */
3031 static TUNABLE(uint32_t, zzc_rate, "zzc_rate", 5);
3032 static uint32_t PERCPU_DATA(zzc_decrementer);
3033 #endif /* defined(__x86_64__) || defined(__arm__) */
3034
3035 /*
3036 * Determine if zero validation for allocation should be skipped
3037 */
3038 static bool
zalloc_skip_zero_check(void)3039 zalloc_skip_zero_check(void)
3040 {
3041 #if defined(__x86_64__) || defined(__arm__)
3042 uint32_t *counterp, cnt;
3043
3044 counterp = PERCPU_GET(zzc_decrementer);
3045 cnt = *counterp;
3046 if (__probable(cnt > 0)) {
3047 *counterp = cnt - 1;
3048 return true;
3049 }
3050 *counterp = zzc_rate - 1;
3051 #endif /* !(defined(__x86_64__) || defined(__arm__)) */
3052 return false;
3053 }
3054
3055 __abortlike
3056 static void
zalloc_uaf_panic(zone_t z,uintptr_t elem,size_t size)3057 zalloc_uaf_panic(zone_t z, uintptr_t elem, size_t size)
3058 {
3059 uint32_t esize = (uint32_t)zone_elem_size(z);
3060 uint32_t first_offs = ~0u;
3061 uintptr_t first_bits = 0, v;
3062 char buf[1024];
3063 int pos = 0;
3064
3065 #if __LP64__
3066 #define ZPF "0x%016lx"
3067 #else
3068 #define ZPF "0x%08lx"
3069 #endif
3070
3071 buf[0] = '\0';
3072
3073 for (uint32_t o = 0; o < size; o += sizeof(v)) {
3074 if ((v = *(uintptr_t *)(elem + o)) == 0) {
3075 continue;
3076 }
3077 pos += scnprintf(buf + pos, sizeof(buf) - pos, "\n"
3078 "%5d: "ZPF, o, v);
3079 if (first_offs > o) {
3080 first_offs = o;
3081 first_bits = v;
3082 }
3083 }
3084
3085 (panic)("[%s%s]: element modified after free "
3086 "(off:%d, val:"ZPF", sz:%d, ptr:%p)%s",
3087 zone_heap_name(z), zone_name(z),
3088 first_offs, first_bits, esize, (void *)elem, buf);
3089
3090 #undef ZPF
3091 }
3092
3093 static void
zalloc_validate_element(zone_t zone,vm_offset_t elem,vm_size_t size,zalloc_flags_t flags)3094 zalloc_validate_element(zone_t zone, vm_offset_t elem, vm_size_t size,
3095 zalloc_flags_t flags)
3096 {
3097 #if CONFIG_GZALLOC
3098 if (zone->gzalloc_tracked) {
3099 return;
3100 }
3101 #endif /* CONFIG_GZALLOC */
3102
3103 if (flags & Z_NOZZC) {
3104 return;
3105 }
3106 if (memcmp_zero_ptr_aligned((void *)elem, size)) {
3107 zalloc_uaf_panic(zone, elem, size);
3108 }
3109 if (flags & Z_PCPU) {
3110 for (size_t i = zpercpu_count(); --i > 0;) {
3111 elem += PAGE_SIZE;
3112 if (memcmp_zero_ptr_aligned((void *)elem, size)) {
3113 zalloc_uaf_panic(zone, elem, size);
3114 }
3115 }
3116 }
3117 }
3118
3119 #endif /* ZALLOC_ENABLE_ZERO_CHECK */
3120
3121 static void
zone_early_scramble_rr(zone_t zone,zone_stats_t zstats)3122 zone_early_scramble_rr(zone_t zone, zone_stats_t zstats)
3123 {
3124 int cpu = cpu_number();
3125 zone_stats_t zs = zpercpu_get_cpu(zstats, cpu);
3126 uint32_t bits;
3127
3128 bits = random_bool_gen_bits(&zone_bool_gen[cpu].zbg_bg,
3129 zone_bool_gen[cpu].zbg_entropy, ZONE_ENTROPY_CNT, 8);
3130
3131 zs->zs_alloc_rr += bits;
3132 zs->zs_alloc_rr %= zone->z_chunk_elems;
3133 }
3134
3135 #endif /* !ZALLOC_TEST */
3136 #pragma mark Zone Leak Detection
3137 #if !ZALLOC_TEST
3138
3139 /*
3140 * Zone leak debugging code
3141 *
3142 * When enabled, this code keeps a log to track allocations to a particular zone that have not
3143 * yet been freed. Examining this log will reveal the source of a zone leak. The log is allocated
3144 * only when logging is enabled, so there is no effect on the system when it's turned off. Logging is
3145 * off by default.
3146 *
3147 * Enable the logging via the boot-args. Add the parameter "zlog=<zone>" to boot-args where <zone>
3148 * is the name of the zone you wish to log.
3149 *
3150 * This code only tracks one zone, so you need to identify which one is leaking first.
3151 * Generally, you'll know you have a leak when you get a "zalloc retry failed 3" panic from the zone
3152 * garbage collector. Note that the zone name printed in the panic message is not necessarily the one
3153 * containing the leak. So do a zprint from gdb and locate the zone with the bloated size. This
3154 * is most likely the problem zone, so set zlog in boot-args to this zone name, reboot and re-run the test. The
3155 * next time it panics with this message, examine the log using the kgmacros zstack, findoldest and countpcs.
3156 * See the help in the kgmacros for usage info.
3157 *
3158 *
3159 * Zone corruption logging
3160 *
3161 * Logging can also be used to help identify the source of a zone corruption. First, identify the zone
3162 * that is being corrupted, then add "-zc zlog=<zone name>" to the boot-args. When -zc is used in conjunction
3163 * with zlog, it changes the logging style to track both allocations and frees to the zone. So when the
3164 * corruption is detected, examining the log will show you the stack traces of the callers who last allocated
3165 * and freed any particular element in the zone. Use the findelem kgmacro with the address of the element that's been
3166 * corrupted to examine its history. This should lead to the source of the corruption.
3167 */
3168
3169 /* Returns TRUE if we rolled over the counter at factor */
3170 __header_always_inline bool
sample_counter(volatile uint32_t * count_p,uint32_t factor)3171 sample_counter(volatile uint32_t *count_p, uint32_t factor)
3172 {
3173 uint32_t old_count, new_count = 0;
3174 if (count_p != NULL) {
3175 os_atomic_rmw_loop(count_p, old_count, new_count, relaxed, {
3176 new_count = old_count + 1;
3177 if (new_count >= factor) {
3178 new_count = 0;
3179 }
3180 });
3181 }
3182
3183 return new_count == 0;
3184 }
3185
3186 #if ZONE_ENABLE_LOGGING
3187 /* Log allocations and frees to help debug a zone element corruption */
3188 static TUNABLE(bool, corruption_debug_flag, "-zc", false);
3189
3190 /*
3191 * A maximum of 10 zlog<n> boot args can be provided (zlog1 -> zlog10)
3192 */
3193 #define MAX_ZONES_LOG_REQUESTS 10
3194 /*
3195 * As all kalloc type zones of a specificified size are logged, by providing
3196 * a single zlog boot-arg, the maximum number of zones that can be logged
3197 * is higher than MAX_ZONES_LOG_REQUESTS
3198 */
3199 #define MAX_ZONES_LOGGED 20
3200
3201 static int num_zones_logged = 0;
3202
3203 /*
3204 * The number of records in the log is configurable via the zrecs parameter in boot-args. Set this to
3205 * the number of records you want in the log. For example, "zrecs=10" sets it to 10 records. Since this
3206 * is the number of stacks suspected of leaking, we don't need many records.
3207 */
3208
3209 #if defined(__LP64__)
3210 #define ZRECORDS_MAX 2560 /* Max records allowed in the log */
3211 #else
3212 #define ZRECORDS_MAX 1536 /* Max records allowed in the log */
3213 #endif
3214 #define ZRECORDS_DEFAULT 1024 /* default records in log if zrecs is not specificed in boot-args */
3215
3216 static TUNABLE(uint32_t, log_records, "zrecs", ZRECORDS_DEFAULT);
3217
3218 static void
zone_enable_logging(zone_t z)3219 zone_enable_logging(zone_t z)
3220 {
3221 z->zlog_btlog = btlog_create(log_records, MAX_ZTRACE_DEPTH,
3222 (corruption_debug_flag == FALSE) /* caller_will_remove_entries_for_element? */);
3223
3224 if (z->zlog_btlog) {
3225 printf("zone: logging started for zone %s%s\n",
3226 zone_heap_name(z), z->z_name);
3227 } else {
3228 printf("zone: couldn't allocate memory for zrecords, turning off zleak logging\n");
3229 z->zone_logging = false;
3230 }
3231 }
3232
3233 /**
3234 * @function zone_setup_logging
3235 *
3236 * @abstract
3237 * Optionally sets up a zone for logging.
3238 *
3239 * @discussion
3240 * We recognized two boot-args:
3241 *
3242 * zlog=<zone_to_log>
3243 * zrecs=<num_records_in_log>
3244 *
3245 * The zlog arg is used to specify the zone name that should be logged,
3246 * and zrecs is used to control the size of the log.
3247 *
3248 * If zrecs is not specified, a default value is used.
3249 */
3250 static void
zone_setup_logging(zone_t z)3251 zone_setup_logging(zone_t z)
3252 {
3253 char zone_name[MAX_ZONE_NAME]; /* Temp. buffer for the zone name */
3254 char zlog_name[MAX_ZONE_NAME]; /* Temp. buffer to create the strings zlog1, zlog2 etc... */
3255 char zlog_val[MAX_ZONE_NAME]; /* the zone name we're logging, if any */
3256
3257 /*
3258 * Don't allow more than ZRECORDS_MAX records even if the user asked for more.
3259 *
3260 * This prevents accidentally hogging too much kernel memory
3261 * and making the system unusable.
3262 */
3263 if (log_records > ZRECORDS_MAX) {
3264 log_records = ZRECORDS_MAX;
3265 }
3266
3267 /*
3268 * Append kalloc heap name to zone name (if zone is used by kalloc)
3269 */
3270 snprintf(zone_name, MAX_ZONE_NAME, "%s%s", zone_heap_name(z), z->z_name);
3271
3272 /* zlog0 isn't allowed. */
3273 for (int i = 1; i <= MAX_ZONES_LOG_REQUESTS; i++) {
3274 snprintf(zlog_name, MAX_ZONE_NAME, "zlog%d", i);
3275
3276 if (PE_parse_boot_argn(zlog_name, zlog_val, sizeof(zlog_val))) {
3277 if (track_this_zone(zone_name, zlog_val) ||
3278 track_kalloc_zones(zlog_val, z)) {
3279 z->zone_logging = true;
3280 num_zones_logged++;
3281 break;
3282 }
3283 }
3284 }
3285
3286 /*
3287 * Backwards compat. with the old boot-arg used to specify single zone
3288 * logging i.e. zlog Needs to happen after the newer zlogn checks
3289 * because the prefix will match all the zlogn
3290 * boot-args.
3291 */
3292 if (!z->zone_logging &&
3293 PE_parse_boot_argn("zlog", zlog_val, sizeof(zlog_val))) {
3294 if (track_this_zone(zone_name, zlog_val) ||
3295 track_kalloc_zones(zlog_val, z)) {
3296 z->zone_logging = true;
3297 num_zones_logged++;
3298 }
3299 }
3300
3301
3302 /*
3303 * If we want to log a zone, see if we need to allocate buffer space for
3304 * the log.
3305 *
3306 * Some vm related zones are zinit'ed before we can do a kmem_alloc, so
3307 * we have to defer allocation in that case.
3308 *
3309 * zone_init() will finish the job.
3310 *
3311 * If we want to log one of the VM related zones that's set up early on,
3312 * we will skip allocation of the log until zinit is called again later
3313 * on some other zone.
3314 */
3315 if (z->zone_logging && startup_phase >= STARTUP_SUB_KMEM_ALLOC) {
3316 zone_enable_logging(z);
3317 }
3318 }
3319
3320 /*
3321 * Each record in the log contains a pointer to the zone element it refers to,
3322 * and a small array to hold the pc's from the stack trace. A
3323 * record is added to the log each time a zalloc() is done in the zone_of_interest. For leak debugging,
3324 * the record is cleared when a zfree() is done. For corruption debugging, the log tracks both allocs and frees.
3325 * If the log fills, old records are replaced as if it were a circular buffer.
3326 */
3327
3328
3329 /*
3330 * Decide if we want to log this zone by doing a string compare between a zone name and the name
3331 * of the zone to log. Return true if the strings are equal, false otherwise. Because it's not
3332 * possible to include spaces in strings passed in via the boot-args, a period in the logname will
3333 * match a space in the zone name.
3334 */
3335
3336 /*
3337 * Test if we want to log this zalloc/zfree event. We log if this is the zone we're interested in and
3338 * the buffer for the records has been allocated.
3339 */
3340
3341 #define DO_LOGGING(z) (z->zlog_btlog != NULL)
3342 #else /* !ZONE_ENABLE_LOGGING */
3343 #define DO_LOGGING(z) 0
3344 #endif /* !ZONE_ENABLE_LOGGING */
3345 #if CONFIG_ZLEAKS
3346
3347 /*
3348 * The zone leak detector, abbreviated 'zleak', keeps track of a subset of the currently outstanding
3349 * allocations made by the zone allocator. Every zleak_sample_factor allocations in each zone, we capture a
3350 * backtrace. Every free, we examine the table and determine if the allocation was being tracked,
3351 * and stop tracking it if it was being tracked.
3352 *
3353 * We track the allocations in the zallocations hash table, which stores the address that was returned from
3354 * the zone allocator. Each stored entry in the zallocations table points to an entry in the ztraces table, which
3355 * stores the backtrace associated with that allocation. This provides uniquing for the relatively large
3356 * backtraces - we don't store them more than once.
3357 *
3358 * Data collection begins when the zone map is 50% full, and only occurs for zones that are taking up
3359 * a large amount of virtual space.
3360 */
3361 #define ZLEAK_STATE_ENABLED 0x01 /* Zone leak monitoring should be turned on if zone_map fills up. */
3362 #define ZLEAK_STATE_ACTIVE 0x02 /* We are actively collecting traces. */
3363 #define ZLEAK_STATE_ACTIVATING 0x04 /* Some thread is doing setup; others should move along. */
3364 #define ZLEAK_STATE_FAILED 0x08 /* Attempt to allocate tables failed. We will not try again. */
3365 static uint32_t zleak_state = 0; /* State of collection, as above */
3366 static unsigned int zleak_sample_factor = 1000; /* Allocations per sample attempt */
3367
3368 static bool panic_include_ztrace; /* Enable zleak logging on panic */
3369 vm_size_t zleak_global_tracking_threshold; /* Size of zone map at which to start collecting data */
3370 vm_size_t zleak_per_zone_tracking_threshold; /* Size a zone will have before we will collect data on it */
3371
3372 /*
3373 * Counters for allocation statistics.
3374 */
3375
3376 /* Times two active records want to occupy the same spot */
3377 static unsigned int z_alloc_collisions = 0;
3378 static unsigned int z_trace_collisions = 0;
3379
3380 /* Times a new record lands on a spot previously occupied by a freed allocation */
3381 static unsigned int z_alloc_overwrites = 0;
3382 static unsigned int z_trace_overwrites = 0;
3383
3384 /* Times a new alloc or trace is put into the hash table */
3385 static unsigned int z_alloc_recorded = 0;
3386 static unsigned int z_trace_recorded = 0;
3387
3388 /* Times zleak_log returned false due to not being able to acquire the lock */
3389 static unsigned int z_total_conflicts = 0;
3390
3391 /*
3392 * Structure for keeping track of an allocation
3393 * An allocation bucket is in use if its element is not NULL
3394 */
3395 struct zallocation {
3396 uintptr_t za_element; /* the element that was zalloc'ed or zfree'ed, NULL if bucket unused */
3397 vm_size_t za_size; /* how much memory did this allocation take up? */
3398 uint32_t za_trace_index; /* index into ztraces for backtrace associated with allocation */
3399 /* TODO: #if this out */
3400 uint32_t za_hit_count; /* for determining effectiveness of hash function */
3401 };
3402
3403 /* Size must be a power of two for the zhash to be able to just mask off bits instead of mod */
3404 static uint32_t zleak_alloc_buckets = CONFIG_ZLEAK_ALLOCATION_MAP_NUM;
3405 static uint32_t zleak_trace_buckets = CONFIG_ZLEAK_TRACE_MAP_NUM;
3406
3407 vm_size_t zleak_max_zonemap_size;
3408
3409 /* Hashmaps of allocations and their corresponding traces */
3410 static struct zallocation* zallocations;
3411 static struct ztrace* ztraces;
3412
3413 /* not static so that panic can see this, see kern/debug.c */
3414 static struct ztrace* top_ztrace;
3415
3416 /* Lock to protect zallocations, ztraces, and top_ztrace from concurrent modification. */
3417 static LCK_GRP_DECLARE(zleak_lock_grp, "zleak_lock");
3418 static LCK_SPIN_DECLARE(zleak_lock, &zleak_lock_grp);
3419
3420 /*
3421 * Initializes the zone leak monitor. Called from zone_init()
3422 */
3423 __startup_func
3424 static void
zleak_init(vm_size_t max_zonemap_size)3425 zleak_init(vm_size_t max_zonemap_size)
3426 {
3427 char scratch_buf[16];
3428 boolean_t zleak_enable_flag = FALSE;
3429
3430 zleak_max_zonemap_size = max_zonemap_size;
3431 zleak_global_tracking_threshold = max_zonemap_size / 2;
3432 zleak_per_zone_tracking_threshold = zleak_global_tracking_threshold / 8;
3433
3434 #if CONFIG_EMBEDDED
3435 if (PE_parse_boot_argn("-zleakon", scratch_buf, sizeof(scratch_buf))) {
3436 zleak_enable_flag = TRUE;
3437 printf("zone leak detection enabled\n");
3438 } else {
3439 zleak_enable_flag = FALSE;
3440 printf("zone leak detection disabled\n");
3441 }
3442 #else /* CONFIG_EMBEDDED */
3443 /* -zleakoff (flag to disable zone leak monitor) */
3444 if (PE_parse_boot_argn("-zleakoff", scratch_buf, sizeof(scratch_buf))) {
3445 zleak_enable_flag = FALSE;
3446 printf("zone leak detection disabled\n");
3447 } else {
3448 zleak_enable_flag = TRUE;
3449 printf("zone leak detection enabled\n");
3450 }
3451 #endif /* CONFIG_EMBEDDED */
3452
3453 /* zfactor=XXXX (override how often to sample the zone allocator) */
3454 if (PE_parse_boot_argn("zfactor", &zleak_sample_factor, sizeof(zleak_sample_factor))) {
3455 printf("Zone leak factor override: %u\n", zleak_sample_factor);
3456 }
3457
3458 /* zleak-allocs=XXXX (override number of buckets in zallocations) */
3459 if (PE_parse_boot_argn("zleak-allocs", &zleak_alloc_buckets, sizeof(zleak_alloc_buckets))) {
3460 printf("Zone leak alloc buckets override: %u\n", zleak_alloc_buckets);
3461 /* uses 'is power of 2' trick: (0x01000 & 0x00FFF == 0) */
3462 if (zleak_alloc_buckets == 0 || (zleak_alloc_buckets & (zleak_alloc_buckets - 1))) {
3463 printf("Override isn't a power of two, bad things might happen!\n");
3464 }
3465 }
3466
3467 /* zleak-traces=XXXX (override number of buckets in ztraces) */
3468 if (PE_parse_boot_argn("zleak-traces", &zleak_trace_buckets, sizeof(zleak_trace_buckets))) {
3469 printf("Zone leak trace buckets override: %u\n", zleak_trace_buckets);
3470 /* uses 'is power of 2' trick: (0x01000 & 0x00FFF == 0) */
3471 if (zleak_trace_buckets == 0 || (zleak_trace_buckets & (zleak_trace_buckets - 1))) {
3472 printf("Override isn't a power of two, bad things might happen!\n");
3473 }
3474 }
3475
3476 if (zleak_enable_flag) {
3477 zleak_state = ZLEAK_STATE_ENABLED;
3478 }
3479 }
3480
3481 /*
3482 * Support for kern.zleak.active sysctl - a simplified
3483 * version of the zleak_state variable.
3484 */
3485 int
get_zleak_state(void)3486 get_zleak_state(void)
3487 {
3488 if (zleak_state & ZLEAK_STATE_FAILED) {
3489 return -1;
3490 }
3491 if (zleak_state & ZLEAK_STATE_ACTIVE) {
3492 return 1;
3493 }
3494 return 0;
3495 }
3496
3497 kern_return_t
zleak_activate(void)3498 zleak_activate(void)
3499 {
3500 kern_return_t retval;
3501 vm_size_t z_alloc_size = zleak_alloc_buckets * sizeof(struct zallocation);
3502 vm_size_t z_trace_size = zleak_trace_buckets * sizeof(struct ztrace);
3503 void *allocations_ptr = NULL;
3504 void *traces_ptr = NULL;
3505
3506 /* Only one thread attempts to activate at a time */
3507 if (zleak_state & (ZLEAK_STATE_ACTIVE | ZLEAK_STATE_ACTIVATING | ZLEAK_STATE_FAILED)) {
3508 return KERN_SUCCESS;
3509 }
3510
3511 /* Indicate that we're doing the setup */
3512 lck_spin_lock(&zleak_lock);
3513 if (zleak_state & (ZLEAK_STATE_ACTIVE | ZLEAK_STATE_ACTIVATING | ZLEAK_STATE_FAILED)) {
3514 lck_spin_unlock(&zleak_lock);
3515 return KERN_SUCCESS;
3516 }
3517
3518 zleak_state |= ZLEAK_STATE_ACTIVATING;
3519 lck_spin_unlock(&zleak_lock);
3520
3521 /* Allocate and zero tables */
3522 retval = kmem_alloc_kobject(kernel_map, (vm_offset_t*)&allocations_ptr, z_alloc_size, VM_KERN_MEMORY_DIAG);
3523 if (retval != KERN_SUCCESS) {
3524 goto fail;
3525 }
3526
3527 retval = kmem_alloc_kobject(kernel_map, (vm_offset_t*)&traces_ptr, z_trace_size, VM_KERN_MEMORY_DIAG);
3528 if (retval != KERN_SUCCESS) {
3529 goto fail;
3530 }
3531
3532 bzero(allocations_ptr, z_alloc_size);
3533 bzero(traces_ptr, z_trace_size);
3534
3535 /* Everything's set. Install tables, mark active. */
3536 zallocations = allocations_ptr;
3537 ztraces = traces_ptr;
3538
3539 /*
3540 * Initialize the top_ztrace to the first entry in ztraces,
3541 * so we don't have to check for null in zleak_log
3542 */
3543 top_ztrace = &ztraces[0];
3544
3545 /*
3546 * Note that we do need a barrier between installing
3547 * the tables and setting the active flag, because the zfree()
3548 * path accesses the table without a lock if we're active.
3549 */
3550 lck_spin_lock(&zleak_lock);
3551 zleak_state |= ZLEAK_STATE_ACTIVE;
3552 zleak_state &= ~ZLEAK_STATE_ACTIVATING;
3553 lck_spin_unlock(&zleak_lock);
3554
3555 return 0;
3556
3557 fail:
3558 /*
3559 * If we fail to allocate memory, don't further tax
3560 * the system by trying again.
3561 */
3562 lck_spin_lock(&zleak_lock);
3563 zleak_state |= ZLEAK_STATE_FAILED;
3564 zleak_state &= ~ZLEAK_STATE_ACTIVATING;
3565 lck_spin_unlock(&zleak_lock);
3566
3567 if (allocations_ptr != NULL) {
3568 kmem_free(kernel_map, (vm_offset_t)allocations_ptr, z_alloc_size);
3569 }
3570
3571 if (traces_ptr != NULL) {
3572 kmem_free(kernel_map, (vm_offset_t)traces_ptr, z_trace_size);
3573 }
3574
3575 return retval;
3576 }
3577
3578 static inline void
zleak_activate_if_needed(void)3579 zleak_activate_if_needed(void)
3580 {
3581 if (__probable((zleak_state & ZLEAK_STATE_ENABLED) == 0)) {
3582 return;
3583 }
3584 if (zleak_state & ZLEAK_STATE_ACTIVE) {
3585 return;
3586 }
3587 if (zone_submaps_approx_size() < zleak_global_tracking_threshold) {
3588 return;
3589 }
3590
3591 kern_return_t kr = zleak_activate();
3592 if (kr != KERN_SUCCESS) {
3593 printf("Failed to activate live zone leak debugging (%d).\n", kr);
3594 }
3595 }
3596
3597 static inline void
zleak_track_if_needed(zone_t z)3598 zleak_track_if_needed(zone_t z)
3599 {
3600 if (__improbable(zleak_state & ZLEAK_STATE_ACTIVE)) {
3601 if (!z->zleak_on &&
3602 zone_size_wired(z) >= zleak_per_zone_tracking_threshold) {
3603 z->zleak_on = true;
3604 }
3605 }
3606 }
3607
3608 /*
3609 * TODO: What about allocations that never get deallocated,
3610 * especially ones with unique backtraces? Should we wait to record
3611 * until after boot has completed?
3612 * (How many persistent zallocs are there?)
3613 */
3614
3615 /*
3616 * This function records the allocation in the allocations table,
3617 * and stores the associated backtrace in the traces table
3618 * (or just increments the refcount if the trace is already recorded)
3619 * If the allocation slot is in use, the old allocation is replaced with the new allocation, and
3620 * the associated trace's refcount is decremented.
3621 * If the trace slot is in use, it returns.
3622 * The refcount is incremented by the amount of memory the allocation consumes.
3623 * The return value indicates whether to try again next time.
3624 */
3625 static boolean_t
zleak_log(uintptr_t * bt,uintptr_t addr,uint32_t depth,vm_size_t allocation_size)3626 zleak_log(uintptr_t* bt,
3627 uintptr_t addr,
3628 uint32_t depth,
3629 vm_size_t allocation_size)
3630 {
3631 /* Quit if there's someone else modifying the hash tables */
3632 if (!lck_spin_try_lock(&zleak_lock)) {
3633 z_total_conflicts++;
3634 return FALSE;
3635 }
3636
3637 struct zallocation* allocation = &zallocations[hashaddr(addr, zleak_alloc_buckets)];
3638
3639 uint32_t trace_index = hashbacktrace(bt, depth, zleak_trace_buckets);
3640 struct ztrace* trace = &ztraces[trace_index];
3641
3642 allocation->za_hit_count++;
3643 trace->zt_hit_count++;
3644
3645 /*
3646 * If the allocation bucket we want to be in is occupied, and if the occupier
3647 * has the same trace as us, just bail.
3648 */
3649 if (allocation->za_element != (uintptr_t) 0 && trace_index == allocation->za_trace_index) {
3650 z_alloc_collisions++;
3651
3652 lck_spin_unlock(&zleak_lock);
3653 return TRUE;
3654 }
3655
3656 /* STEP 1: Store the backtrace in the traces array. */
3657 /* A size of zero indicates that the trace bucket is free. */
3658
3659 if (trace->zt_size > 0 && bcmp(trace->zt_stack, bt, (depth * sizeof(uintptr_t))) != 0) {
3660 /*
3661 * Different unique trace with same hash!
3662 * Just bail - if we're trying to record the leaker, hopefully the other trace will be deallocated
3663 * and get out of the way for later chances
3664 */
3665 trace->zt_collisions++;
3666 z_trace_collisions++;
3667
3668 lck_spin_unlock(&zleak_lock);
3669 return TRUE;
3670 } else if (trace->zt_size > 0) {
3671 /* Same trace, already added, so increment refcount */
3672 trace->zt_size += allocation_size;
3673 } else {
3674 /* Found an unused trace bucket, record the trace here! */
3675 if (trace->zt_depth != 0) { /* if this slot was previously used but not currently in use */
3676 z_trace_overwrites++;
3677 }
3678
3679 z_trace_recorded++;
3680 trace->zt_size = allocation_size;
3681 memcpy(trace->zt_stack, bt, (depth * sizeof(uintptr_t)));
3682
3683 trace->zt_depth = depth;
3684 trace->zt_collisions = 0;
3685 }
3686
3687 /* STEP 2: Store the allocation record in the allocations array. */
3688
3689 if (allocation->za_element != (uintptr_t) 0) {
3690 /*
3691 * Straight up replace any allocation record that was there. We don't want to do the work
3692 * to preserve the allocation entries that were there, because we only record a subset of the
3693 * allocations anyways.
3694 */
3695
3696 z_alloc_collisions++;
3697
3698 struct ztrace* associated_trace = &ztraces[allocation->za_trace_index];
3699 /* Knock off old allocation's size, not the new allocation */
3700 associated_trace->zt_size -= allocation->za_size;
3701 } else if (allocation->za_trace_index != 0) {
3702 /* Slot previously used but not currently in use */
3703 z_alloc_overwrites++;
3704 }
3705
3706 allocation->za_element = addr;
3707 allocation->za_trace_index = trace_index;
3708 allocation->za_size = allocation_size;
3709
3710 z_alloc_recorded++;
3711
3712 if (top_ztrace->zt_size < trace->zt_size) {
3713 top_ztrace = trace;
3714 }
3715
3716 lck_spin_unlock(&zleak_lock);
3717 return TRUE;
3718 }
3719
3720 /*
3721 * Free the allocation record and release the stacktrace.
3722 * This should be as fast as possible because it will be called for every free.
3723 */
3724 __attribute__((noinline))
3725 static void
zleak_free(uintptr_t addr,vm_size_t allocation_size)3726 zleak_free(uintptr_t addr,
3727 vm_size_t allocation_size)
3728 {
3729 if (addr == (uintptr_t) 0) {
3730 return;
3731 }
3732
3733 struct zallocation* allocation = &zallocations[hashaddr(addr, zleak_alloc_buckets)];
3734
3735 /* Double-checked locking: check to find out if we're interested, lock, check to make
3736 * sure it hasn't changed, then modify it, and release the lock.
3737 */
3738
3739 if (allocation->za_element == addr && allocation->za_trace_index < zleak_trace_buckets) {
3740 /* if the allocation was the one, grab the lock, check again, then delete it */
3741 lck_spin_lock(&zleak_lock);
3742
3743 if (allocation->za_element == addr && allocation->za_trace_index < zleak_trace_buckets) {
3744 struct ztrace *trace;
3745
3746 /* allocation_size had better match what was passed into zleak_log - otherwise someone is freeing into the wrong zone! */
3747 if (allocation->za_size != allocation_size) {
3748 panic("Freeing as size %lu memory that was allocated with size %lu",
3749 (uintptr_t)allocation_size, (uintptr_t)allocation->za_size);
3750 }
3751
3752 trace = &ztraces[allocation->za_trace_index];
3753
3754 /* size of 0 indicates trace bucket is unused */
3755 if (trace->zt_size > 0) {
3756 trace->zt_size -= allocation_size;
3757 }
3758
3759 /* A NULL element means the allocation bucket is unused */
3760 allocation->za_element = 0;
3761 }
3762 lck_spin_unlock(&zleak_lock);
3763 }
3764 }
3765
3766 static void
panic_display_ztrace(bool has_syms)3767 panic_display_ztrace(bool has_syms)
3768 {
3769 struct ztrace top_ztrace_copy;
3770
3771 /* Make sure not to trip another panic if there's something wrong with memory */
3772 if (ml_nofault_copy((vm_offset_t)top_ztrace, (vm_offset_t)&top_ztrace_copy,
3773 sizeof(struct ztrace)) != sizeof(struct ztrace)) {
3774 paniclog_append_noflush("\nCan't access top_ztrace...\n\n");
3775 return;
3776 }
3777
3778 paniclog_append_noflush("\nBacktrace suspected of leaking: (outstanding bytes: %lu)\n",
3779 (uintptr_t)top_ztrace_copy.zt_size);
3780
3781 for (uint32_t i = 0; i < top_ztrace_copy.zt_depth && i < MAX_ZTRACE_DEPTH; i++) {
3782 if (has_syms) {
3783 paniclog_append_noflush("%p ", top_ztrace_copy.zt_stack[i]);
3784 panic_print_symbol_name((vm_address_t)top_ztrace_copy.zt_stack[i]);
3785 paniclog_append_noflush("\n");
3786 } else {
3787 paniclog_append_noflush("%p\n", top_ztrace_copy.zt_stack[i]);
3788 }
3789 }
3790
3791 /*
3792 * Print any kexts in that backtrace,
3793 * along with their link addresses so we can properly blame them
3794 */
3795 kmod_panic_dump((vm_offset_t *)&top_ztrace_copy.zt_stack[0], top_ztrace_copy.zt_depth);
3796 paniclog_append_noflush("\n");
3797 }
3798 #else
3799 static inline void
zleak_activate_if_needed(void)3800 zleak_activate_if_needed(void)
3801 {
3802 }
3803
3804 static inline void
zleak_track_if_needed(__unused zone_t z)3805 zleak_track_if_needed(__unused zone_t z)
3806 {
3807 }
3808 #endif /* CONFIG_ZLEAKS */
3809 #if ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS
3810
3811 /*
3812 * work-around for (80538830): never return an empty backtrace,
3813 * which can happen with zfree() if it is tail-called into
3814 * from a continuation
3815 */
3816 #define SAFE_BACKTRACE(buf, depth, ctl) ({ \
3817 uintptr_t *__buf = (buf); \
3818 struct backtrace_control *__ctl = (ctl); \
3819 uint32_t __n = backtrace(__buf, depth, __ctl, NULL); \
3820 if (__improbable(__n == 0)) { \
3821 __ctl->btc_frame_addr = (uintptr_t)__builtin_frame_address(0); \
3822 __n = backtrace(__buf, depth, __ctl, NULL); \
3823 } \
3824 __n; \
3825 })
3826
3827 __attribute__((noinline))
3828 static void
zalloc_log_or_trace_leaks(zone_t zone,vm_offset_t addr,void * fp)3829 zalloc_log_or_trace_leaks(zone_t zone, vm_offset_t addr, void *fp)
3830 {
3831 uintptr_t zbt[MAX_ZTRACE_DEPTH]; /* used in zone leak logging and zone leak detection */
3832 unsigned int numsaved = 0;
3833 struct backtrace_control ctl = {
3834 .btc_frame_addr = (uintptr_t)fp,
3835 };
3836
3837 #if ZONE_ENABLE_LOGGING
3838 if (DO_LOGGING(zone)) {
3839 numsaved = SAFE_BACKTRACE(zbt, MAX_ZTRACE_DEPTH, &ctl);
3840 btlog_add_entry(zone->zlog_btlog, (void *)addr,
3841 ZOP_ALLOC, (void **)zbt, numsaved);
3842 }
3843 #endif /* ZONE_ENABLE_LOGGING */
3844
3845 #if CONFIG_ZLEAKS
3846 /*
3847 * Zone leak detection: capture a backtrace every zleak_sample_factor
3848 * allocations in this zone.
3849 */
3850 if (__improbable(zone->zleak_on)) {
3851 if (sample_counter(&zone->zleak_capture, zleak_sample_factor)) {
3852 /* Avoid backtracing twice if zone logging is on */
3853 if (numsaved == 0) {
3854 numsaved = SAFE_BACKTRACE(zbt, MAX_ZTRACE_DEPTH, &ctl);
3855 }
3856 /* Sampling can fail if another sample is happening at the same time in a different zone. */
3857 if (!zleak_log(zbt, addr, numsaved, zone_elem_size(zone))) {
3858 /* If it failed, roll back the counter so we sample the next allocation instead. */
3859 zone->zleak_capture = zleak_sample_factor;
3860 }
3861 }
3862 }
3863
3864 if (__improbable(zone_leaks_scan_enable &&
3865 !(zone_elem_size(zone) & (sizeof(uintptr_t) - 1)))) {
3866 unsigned int count, idx;
3867 /* Fill element, from tail, with backtrace in reverse order */
3868 if (numsaved == 0) {
3869 numsaved = SAFE_BACKTRACE(zbt, MAX_ZTRACE_DEPTH, &ctl);
3870 }
3871 count = (unsigned int)(zone_elem_size(zone) / sizeof(uintptr_t));
3872 if (count >= numsaved) {
3873 count = numsaved - 1;
3874 }
3875 for (idx = 0; idx < count; idx++) {
3876 ((uintptr_t *)addr)[count - 1 - idx] = zbt[idx + 1];
3877 }
3878 }
3879 #endif /* CONFIG_ZLEAKS */
3880 }
3881
3882 static inline bool
zalloc_should_log_or_trace_leaks(zone_t zone,vm_size_t elem_size)3883 zalloc_should_log_or_trace_leaks(zone_t zone, vm_size_t elem_size)
3884 {
3885 #if ZONE_ENABLE_LOGGING
3886 if (DO_LOGGING(zone)) {
3887 return true;
3888 }
3889 #endif /* ZONE_ENABLE_LOGGING */
3890 #if CONFIG_ZLEAKS
3891 /*
3892 * Zone leak detection: capture a backtrace every zleak_sample_factor
3893 * allocations in this zone.
3894 */
3895 if (zone->zleak_on) {
3896 return true;
3897 }
3898 if (zone_leaks_scan_enable && !(elem_size & (sizeof(uintptr_t) - 1))) {
3899 return true;
3900 }
3901 #endif /* CONFIG_ZLEAKS */
3902 return false;
3903 }
3904
3905 #endif /* ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS */
3906 #if ZONE_ENABLE_LOGGING
3907
3908 __attribute__((noinline))
3909 static void
zfree_log_trace(zone_t zone,vm_offset_t addr,void * fp)3910 zfree_log_trace(zone_t zone, vm_offset_t addr, void *fp)
3911 {
3912 /*
3913 * See if we're doing logging on this zone.
3914 *
3915 * There are two styles of logging used depending on
3916 * whether we're trying to catch a leak or corruption.
3917 */
3918 if (__improbable(DO_LOGGING(zone))) {
3919 if (corruption_debug_flag) {
3920 uintptr_t zbt[MAX_ZTRACE_DEPTH];
3921 unsigned int numsaved;
3922 /*
3923 * We're logging to catch a corruption.
3924 *
3925 * Add a record of this zfree operation to log.
3926 */
3927 struct backtrace_control ctl = { .btc_frame_addr = (uintptr_t)fp, };
3928 numsaved = SAFE_BACKTRACE(zbt, MAX_ZTRACE_DEPTH, &ctl);
3929 btlog_add_entry(zone->zlog_btlog, (void *)addr, ZOP_FREE,
3930 (void **)zbt, numsaved);
3931 } else {
3932 /*
3933 * We're logging to catch a leak.
3934 *
3935 * Remove any record we might have for this element
3936 * since it's being freed. Note that we may not find it
3937 * if the buffer overflowed and that's OK.
3938 *
3939 * Since the log is of a limited size, old records get
3940 * overwritten if there are more zallocs than zfrees.
3941 */
3942 btlog_remove_entries_for_element(zone->zlog_btlog, (void *)addr);
3943 }
3944 }
3945 }
3946
3947 #endif /* ZONE_ENABLE_LOGGING */
3948
3949 /* These functions outside of CONFIG_ZLEAKS because they are also used in
3950 * mbuf.c for mbuf leak-detection. This is why they lack the z_ prefix.
3951 */
3952
3953 /* "Thomas Wang's 32/64 bit mix functions." http://www.concentric.net/~Ttwang/tech/inthash.htm */
3954 uintptr_t
hash_mix(uintptr_t x)3955 hash_mix(uintptr_t x)
3956 {
3957 #ifndef __LP64__
3958 x += ~(x << 15);
3959 x ^= (x >> 10);
3960 x += (x << 3);
3961 x ^= (x >> 6);
3962 x += ~(x << 11);
3963 x ^= (x >> 16);
3964 #else
3965 x += ~(x << 32);
3966 x ^= (x >> 22);
3967 x += ~(x << 13);
3968 x ^= (x >> 8);
3969 x += (x << 3);
3970 x ^= (x >> 15);
3971 x += ~(x << 27);
3972 x ^= (x >> 31);
3973 #endif
3974 return x;
3975 }
3976
3977 uint32_t
hashbacktrace(uintptr_t * bt,uint32_t depth,uint32_t max_size)3978 hashbacktrace(uintptr_t* bt, uint32_t depth, uint32_t max_size)
3979 {
3980 uintptr_t hash = 0;
3981 uintptr_t mask = max_size - 1;
3982
3983 while (depth) {
3984 hash += bt[--depth];
3985 }
3986
3987 hash = hash_mix(hash) & mask;
3988
3989 assert(hash < max_size);
3990
3991 return (uint32_t) hash;
3992 }
3993
3994 /*
3995 * TODO: Determine how well distributed this is
3996 * max_size must be a power of 2. i.e 0x10000 because 0x10000-1 is 0x0FFFF which is a great bitmask
3997 */
3998 uint32_t
hashaddr(uintptr_t pt,uint32_t max_size)3999 hashaddr(uintptr_t pt, uint32_t max_size)
4000 {
4001 uintptr_t hash = 0;
4002 uintptr_t mask = max_size - 1;
4003
4004 hash = hash_mix(pt) & mask;
4005
4006 assert(hash < max_size);
4007
4008 return (uint32_t) hash;
4009 }
4010
4011 #endif /* !ZALLOC_TEST */
4012 #pragma mark zone (re)fill
4013 #if !ZALLOC_TEST
4014
4015 /*!
4016 * @defgroup Zone Refill
4017 * @{
4018 *
4019 * @brief
4020 * Functions handling The zone refill machinery.
4021 *
4022 * @discussion
4023 * Zones are refilled based on 2 mechanisms: direct expansion, async expansion.
4024 *
4025 * @c zalloc_ext() is the codepath that kicks the zone refill when the zone is
4026 * dropping below half of its @c z_elems_rsv (0 for most zones) and will:
4027 *
4028 * - call @c zone_expand_locked() directly if the caller is allowed to block,
4029 *
4030 * - wakeup the asynchroous expansion thread call if the caller is not allowed
4031 * to block, or if the reserve becomes depleted.
4032 *
4033 *
4034 * <h2>Synchronous expansion</h2>
4035 *
4036 * This mechanism is actually the only one that may refill a zone, and all the
4037 * other ones funnel through this one eventually.
4038 *
4039 * @c zone_expand_locked() implements the core of the expansion mechanism,
4040 * and will do so while a caller specified predicate is true.
4041 *
4042 * Zone expansion allows for up to 2 threads to concurrently refill the zone:
4043 * - one VM privileged thread,
4044 * - one regular thread.
4045 *
4046 * Regular threads that refill will put down their identity in @c z_expander,
4047 * so that priority inversion avoidance can be implemented.
4048 *
4049 * However, VM privileged threads are allowed to use VM page reserves,
4050 * which allows for the system to recover from extreme memory pressure
4051 * situations, allowing for the few allocations that @c zone_gc() or
4052 * killing processes require.
4053 *
4054 * When a VM privileged thread is also expanding, the @c z_expander_vm_priv bit
4055 * is set. @c z_expander is not necessarily the identity of this VM privileged
4056 * thread (it is if the VM privileged thread came in first, but wouldn't be, and
4057 * could even be @c THREAD_NULL otherwise).
4058 *
4059 * Note that the pageout-scan daemon might be BG and is VM privileged. To avoid
4060 * spending a whole pointer on priority inheritance for VM privileged threads
4061 * (and other issues related to having two owners), we use the rwlock boost as
4062 * a stop gap to avoid priority inversions.
4063 *
4064 *
4065 * <h2>Chunk wiring policies</h2>
4066 *
4067 * Zones allocate memory in chunks of @c zone_t::z_chunk_pages pages at a time
4068 * to try to minimize fragmentation relative to element sizes not aligning with
4069 * a chunk size well. However, this can grow large and be hard to fulfill on
4070 * a system under a lot of memory pressure (chunks can be as long as 8 pages on
4071 * 4k page systems).
4072 *
4073 * This is why, when under memory pressure the system allows chunks to be
4074 * partially populated. The metadata of the first page in the chunk maintains
4075 * the count of actually populated pages.
4076 *
4077 * The metadata for addresses assigned to a zone are found of 4 queues:
4078 * - @c z_pageq_empty has chunk heads with populated pages and no allocated
4079 * elements (those can be targeted by @c zone_gc()),
4080 * - @c z_pageq_partial has chunk heads with populated pages that are partially
4081 * used,
4082 * - @c z_pageq_full has chunk heads with populated pages with no free elements
4083 * left,
4084 * - @c z_pageq_va has either chunk heads for sequestered VA space assigned to
4085 * the zone forever (if @c z_va_sequester is enabled), or the first secondary
4086 * metadata for a chunk whose corresponding page is not populated in the
4087 * chunk.
4088 *
4089 * When new pages need to be wired/populated, chunks from the @c z_pageq_va
4090 * queues are preferred.
4091 *
4092 *
4093 * <h2>Asynchronous expansion</h2>
4094 *
4095 * This mechanism allows for refilling zones used mostly with non blocking
4096 * callers. It relies on a thread call (@c zone_expand_callout) which will
4097 * iterate all zones and refill the ones marked with @c z_async_refilling.
4098 *
4099 * NOTE: If the calling thread for zalloc_noblock is lower priority than
4100 * the thread_call, then zalloc_noblock to an empty zone may succeed.
4101 *
4102 *
4103 * <h2>Dealing with zone allocations from the mach VM code</h2>
4104 *
4105 * The implementation of the mach VM itself uses the zone allocator
4106 * for things like the vm_map_entry data structure. In order to prevent
4107 * a recursion problem when adding more pages to a zone, the VM zones
4108 * use the Z_SUBMAP_IDX_VM submap which doesn't use kernel_memory_allocate()
4109 * or any VM map functions to allocate.
4110 *
4111 * Instead, a really simple coalescing first-fit allocator is used
4112 * for this submap, and no one else than zalloc can allocate from it.
4113 *
4114 * Memory is directly populated which doesn't require allocation of
4115 * VM map entries, and avoids recursion. The cost of this scheme however,
4116 * is that `vm_map_lookup_entry` will not function on those addresses
4117 * (nor any API relying on it).
4118 */
4119
4120 static thread_call_data_t zone_expand_callout;
4121
4122 static inline kma_flags_t
zone_kma_flags(zone_t z,zone_security_flags_t zsflags,zalloc_flags_t flags)4123 zone_kma_flags(zone_t z, zone_security_flags_t zsflags, zalloc_flags_t flags)
4124 {
4125 kma_flags_t kmaflags = KMA_KOBJECT | KMA_ZERO;
4126
4127 if (zsflags.z_noencrypt) {
4128 kmaflags |= KMA_NOENCRYPT;
4129 }
4130 if (flags & Z_NOPAGEWAIT) {
4131 kmaflags |= KMA_NOPAGEWAIT;
4132 }
4133 if (z->z_permanent || (!z->z_destructible && zsflags.z_va_sequester)) {
4134 kmaflags |= KMA_PERMANENT;
4135 }
4136 if (zsflags.z_submap_from_end) {
4137 kmaflags |= KMA_LAST_FREE;
4138 }
4139
4140 return kmaflags;
4141 }
4142
4143 /*!
4144 * @function zcram_and_lock()
4145 *
4146 * @brief
4147 * Prepare some memory for being usable for allocation purposes.
4148 *
4149 * @discussion
4150 * Prepare memory in <code>[addr + ptoa(pg_start), addr + ptoa(pg_end))</code>
4151 * to be usable in the zone.
4152 *
4153 * This function assumes the metadata is already populated for the range.
4154 *
4155 * Calling this function with @c pg_start being 0 means that the memory
4156 * is either a partial chunk, or a full chunk, that isn't published anywhere
4157 * and the initialization can happen without locks held.
4158 *
4159 * Calling this function with a non zero @c pg_start means that we are extending
4160 * an existing chunk: the memory in <code>[addr, addr + ptoa(pg_start))</code>,
4161 * is already usable and published in the zone, so extending it requires holding
4162 * the zone lock.
4163 *
4164 * @param zone The zone to cram new populated pages into
4165 * @param addr The base address for the chunk(s)
4166 * @param pg_va_new The number of virtual pages newly assigned to the zone
4167 * @param pg_start The first newly populated page relative to @a addr.
4168 * @param pg_end The after-last newly populated page relative to @a addr.
4169 * @param kind The kind of memory assigned to the zone.
4170 */
4171 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,zone_addr_kind_t kind)4172 zcram_and_lock(zone_t zone, vm_offset_t addr, uint32_t pg_va_new,
4173 uint32_t pg_start, uint32_t pg_end, zone_addr_kind_t kind)
4174 {
4175 zone_id_t zindex = zone_index(zone);
4176 vm_offset_t elem_size = zone_elem_size_safe(zone);
4177 uint32_t free_start = 0, free_end = 0;
4178
4179 struct zone_page_metadata *meta = zone_meta_from_addr(addr);
4180 uint32_t chunk_pages = zone->z_chunk_pages;
4181
4182 assert(pg_start < pg_end && pg_end <= chunk_pages);
4183
4184 if (pg_start == 0) {
4185 uint16_t chunk_len = (uint16_t)pg_end;
4186 uint16_t secondary_len = ZM_SECONDARY_PAGE;
4187 bool inline_bitmap = false;
4188
4189 if (zone->z_percpu) {
4190 chunk_len = 1;
4191 secondary_len = ZM_SECONDARY_PCPU_PAGE;
4192 assert(pg_end == zpercpu_count());
4193 }
4194 if (!zone->z_permanent) {
4195 inline_bitmap = zone->z_chunk_elems <= 32 * chunk_pages;
4196 }
4197
4198 meta[0] = (struct zone_page_metadata){
4199 .zm_index = zindex,
4200 .zm_inline_bitmap = inline_bitmap,
4201 .zm_chunk_len = chunk_len,
4202 };
4203 if (kind == ZONE_ADDR_FOREIGN) {
4204 /* Never hit z_pageq_empty */
4205 meta[0].zm_alloc_size = ZM_ALLOC_SIZE_LOCK;
4206 }
4207
4208 for (uint16_t i = 1; i < chunk_pages; i++) {
4209 meta[i] = (struct zone_page_metadata){
4210 .zm_index = zindex,
4211 .zm_inline_bitmap = inline_bitmap,
4212 .zm_chunk_len = secondary_len,
4213 .zm_page_index = i,
4214 };
4215 }
4216
4217 free_end = (uint32_t)ptoa(chunk_len) / elem_size;
4218 if (!zone->z_permanent) {
4219 zone_meta_bits_init(meta, free_end, zone->z_chunk_elems);
4220 }
4221 } else {
4222 assert(!zone->z_percpu && !zone->z_permanent);
4223
4224 free_end = (uint32_t)ptoa(pg_end) / elem_size;
4225 free_start = (uint32_t)ptoa(pg_start) / elem_size;
4226 }
4227
4228 #if VM_TAG_SIZECLASSES
4229 if (__improbable(zone->z_uses_tags)) {
4230 assert(kind == ZONE_ADDR_NATIVE && !zone->z_percpu);
4231 ztMemoryAdd(zone, addr + ptoa(pg_start),
4232 ptoa(pg_end - pg_start));
4233 }
4234 #endif /* VM_TAG_SIZECLASSES */
4235
4236 /*
4237 * Insert the initialized pages / metadatas into the right lists.
4238 */
4239
4240 zone_lock(zone);
4241 assert(zone->z_self == zone);
4242
4243 if (pg_start != 0) {
4244 assert(meta->zm_chunk_len == pg_start);
4245
4246 zone_meta_bits_merge(meta, free_start, free_end);
4247 meta->zm_chunk_len = (uint16_t)pg_end;
4248
4249 /*
4250 * consume the zone_meta_lock_in_partial()
4251 * done in zone_expand_locked()
4252 */
4253 zone_meta_alloc_size_sub(zone, meta, ZM_ALLOC_SIZE_LOCK);
4254 zone_meta_remqueue(zone, meta);
4255 }
4256
4257 if (zone->z_permanent || meta->zm_alloc_size) {
4258 zone_meta_queue_push(zone, &zone->z_pageq_partial, meta);
4259 } else {
4260 zone_meta_queue_push(zone, &zone->z_pageq_empty, meta);
4261 zone->z_wired_empty += zone->z_percpu ? 1 : pg_end;
4262 }
4263 if (pg_end < chunk_pages) {
4264 /* push any non populated residual VA on z_pageq_va */
4265 zone_meta_queue_push(zone, &zone->z_pageq_va, meta + pg_end);
4266 }
4267
4268 zone_elems_free_add(zone, free_end - free_start);
4269 zone->z_elems_avail += free_end - free_start;
4270 zone->z_wired_cur += zone->z_percpu ? 1 : pg_end - pg_start;
4271 if (pg_va_new) {
4272 zone->z_va_cur += zone->z_percpu ? 1 : pg_va_new;
4273 }
4274 if (zone->z_wired_hwm < zone->z_wired_cur) {
4275 zone->z_wired_hwm = zone->z_wired_cur;
4276 }
4277
4278 os_atomic_add(&zones_phys_page_mapped_count, pg_end - pg_start, relaxed);
4279 }
4280
4281 static void
zcram(zone_t zone,vm_offset_t addr,uint32_t pages,zone_addr_kind_t kind)4282 zcram(zone_t zone, vm_offset_t addr, uint32_t pages, zone_addr_kind_t kind)
4283 {
4284 uint32_t chunk_pages = zone->z_chunk_pages;
4285
4286 assert(pages % chunk_pages == 0);
4287 for (; pages > 0; pages -= chunk_pages, addr += ptoa(chunk_pages)) {
4288 zcram_and_lock(zone, addr, chunk_pages, 0, chunk_pages, kind);
4289 zone_unlock(zone);
4290 }
4291 }
4292
4293 void
zone_cram_foreign(zone_t zone,vm_offset_t newmem,vm_size_t size)4294 zone_cram_foreign(zone_t zone, vm_offset_t newmem, vm_size_t size)
4295 {
4296 uint32_t pages = (uint32_t)atop(size);
4297 zone_security_flags_t zsflags = zone_security_config(zone);
4298
4299 if (!from_zone_map(newmem, size, ZONE_ADDR_FOREIGN)) {
4300 panic("zone_cram_foreign: foreign memory [%p] being crammed is "
4301 "outside of expected range", (void *)newmem);
4302 }
4303 if (!zsflags.z_allows_foreign) {
4304 panic("zone_cram_foreign: foreign memory [%p] being crammed in "
4305 "zone '%s%s' not expecting it", (void *)newmem,
4306 zone_heap_name(zone), zone_name(zone));
4307 }
4308 if (size % ptoa(zone->z_chunk_pages)) {
4309 panic("zone_cram_foreign: foreign memory [%p] being crammed has "
4310 "invalid size %zx", (void *)newmem, (size_t)size);
4311 }
4312 if (startup_phase >= STARTUP_SUB_ZALLOC) {
4313 panic("zone_cram_foreign: foreign memory [%p] being crammed "
4314 "after zalloc is initialized", (void *)newmem);
4315 }
4316
4317 bzero((void *)newmem, size);
4318 zcram(zone, newmem, pages, ZONE_ADDR_FOREIGN);
4319 }
4320
4321 __attribute__((overloadable))
4322 static inline bool
zone_submap_is_sequestered(zone_submap_idx_t idx)4323 zone_submap_is_sequestered(zone_submap_idx_t idx)
4324 {
4325 switch (idx) {
4326 case Z_SUBMAP_IDX_READ_ONLY:
4327 case Z_SUBMAP_IDX_VM:
4328 return true;
4329 case Z_SUBMAP_IDX_DATA:
4330 return false;
4331 default:
4332 return ZSECURITY_CONFIG(SEQUESTER);
4333 }
4334 }
4335
4336 __attribute__((overloadable))
4337 static inline bool
zone_submap_is_sequestered(zone_security_flags_t zsflags)4338 zone_submap_is_sequestered(zone_security_flags_t zsflags)
4339 {
4340 return zone_submap_is_sequestered(zsflags.z_submap_idx);
4341 }
4342
4343 static inline vm_prot_t
zone_submap_prot(zone_security_flags_t zsflags)4344 zone_submap_prot(zone_security_flags_t zsflags)
4345 {
4346 if (zsflags.z_submap_idx == Z_SUBMAP_IDX_READ_ONLY) {
4347 return VM_PROT_NONE;
4348 }
4349 return VM_PROT_DEFAULT;
4350 }
4351
4352 /*!
4353 * @function zone_submap_alloc_sequestered_va
4354 *
4355 * @brief
4356 * Allocates VA without using vm_find_space().
4357 *
4358 * @discussion
4359 * Allocate VA quickly without using the slower vm_find_space() for cases
4360 * when the submaps are fully sequestered.
4361 *
4362 * The VM submap is used to implement the VM itself so it is always sequestered,
4363 * as it can't kernel_memory_allocate which needs to always allocate vm entries.
4364 * However, it can use vm_map_enter() which tries to coalesce entries, which
4365 * always works, so the VM map only ever needs 2 entries (one for each end).
4366 *
4367 * The RO submap is similarly always sequestered if it exists (as a non
4368 * sequestered RO submap makes very little sense).
4369 *
4370 * The allocator is a very simple bump-allocator
4371 * that allocates from either end.
4372 */
4373 static kern_return_t
zone_submap_alloc_sequestered_va(zone_security_flags_t zsflags,uint32_t pages,vm_offset_t * addrp)4374 zone_submap_alloc_sequestered_va(zone_security_flags_t zsflags, uint32_t pages,
4375 vm_offset_t *addrp)
4376 {
4377 zone_submap_idx_t idx = zsflags.z_submap_idx;
4378 struct zone_pva_range *r = &zone_alloc_range[idx];
4379 vm_map_offset_t addr;
4380 vm_map_t map = zone_submap(zsflags);
4381 vm_map_entry_t entry;
4382
4383 vm_map_lock(map);
4384
4385 if (r->zpr_min.packed_address + pages > r->zpr_max.packed_address) {
4386 vm_map_unlock(map);
4387 return KERN_NO_SPACE;
4388 }
4389
4390 if (zsflags.z_submap_from_end) {
4391 vm_map_lookup_entry(map, map->max_offset - 1, &entry);
4392 r->zpr_max.packed_address -= pages;
4393 addr = entry->vme_start = zone_pva_to_addr(r->zpr_max);
4394 VME_OFFSET_SET(entry, addr);
4395 } else {
4396 vm_map_lookup_entry(map, map->min_offset, &entry);
4397 addr = zone_pva_to_addr(r->zpr_min);
4398 r->zpr_min.packed_address += pages;
4399 entry->vme_end = zone_pva_to_addr(r->zpr_min);
4400 }
4401
4402 vm_map_unlock(map);
4403
4404 *addrp = addr;
4405 return KERN_SUCCESS;
4406 }
4407
4408 void
zone_fill_initially(zone_t zone,vm_size_t nelems)4409 zone_fill_initially(zone_t zone, vm_size_t nelems)
4410 {
4411 kma_flags_t kmaflags;
4412 kern_return_t kr;
4413 vm_offset_t addr;
4414 uint32_t pages;
4415 zone_security_flags_t zsflags = zone_security_config(zone);
4416
4417 assert(!zone->z_permanent && !zone->collectable && !zone->z_destructible);
4418 assert(zone->z_elems_avail == 0);
4419
4420 kmaflags = zone_kma_flags(zone, zsflags, Z_WAITOK) | KMA_PERMANENT;
4421 pages = zone_alloc_pages_for_nelems(zone, nelems);
4422 if (zone_submap_is_sequestered(zsflags)) {
4423 kr = zone_submap_alloc_sequestered_va(zsflags, pages, &addr);
4424 if (kr == KERN_SUCCESS) {
4425 kr = kernel_memory_populate(zone_submap(zsflags), addr,
4426 ptoa(pages), kmaflags, VM_KERN_MEMORY_ZONE);
4427 }
4428 } else {
4429 kr = kernel_memory_allocate_prot(zone_submap(zsflags), &addr,
4430 ptoa(pages), 0, kmaflags, VM_KERN_MEMORY_ZONE,
4431 zone_submap_prot(zsflags), zone_submap_prot(zsflags));
4432 }
4433
4434 if (kr != KERN_SUCCESS) {
4435 panic("kernel_memory_allocate() of %u pages failed", pages);
4436 }
4437
4438 zone_meta_populate(addr, ptoa(pages));
4439 zcram(zone, addr, pages, ZONE_ADDR_NATIVE);
4440 }
4441
4442 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
4443 __attribute__((noinline))
4444 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)4445 zone_scramble_va_and_unlock(
4446 zone_t z,
4447 struct zone_page_metadata *meta,
4448 uint32_t runs,
4449 uint32_t pages,
4450 uint32_t chunk_pages)
4451 {
4452 struct zone_page_metadata *arr[ZONE_CHUNK_ALLOC_SIZE / 4096];
4453
4454 /*
4455 * Fisher–Yates shuffle, for an array with indices [0, n)
4456 *
4457 * for i from n−1 downto 1 do
4458 * j ← random integer such that 0 ≤ j ≤ i
4459 * exchange a[j] and a[i]
4460 *
4461 * The point here is that early allocations aren't at a fixed
4462 * distance from each other.
4463 */
4464 for (uint32_t i = 0, j = 0; i < runs; i++, j += chunk_pages) {
4465 arr[i] = meta + j;
4466 }
4467
4468 for (uint32_t i = runs - 1; i > 0; i--) {
4469 uint32_t j = zalloc_random_uniform(0, i + 1);
4470
4471 meta = arr[j];
4472 arr[j] = arr[i];
4473 arr[i] = meta;
4474 }
4475
4476 zone_lock(z);
4477
4478 for (uint32_t i = 0; i < runs; i++) {
4479 zone_meta_queue_push(z, &z->z_pageq_va, arr[i]);
4480 }
4481 z->z_va_cur += z->z_percpu ? runs : pages;
4482 }
4483 #endif
4484
4485 static void
zone_allocate_va_locked(zone_t z,zalloc_flags_t flags)4486 zone_allocate_va_locked(zone_t z, zalloc_flags_t flags)
4487 {
4488 zone_security_flags_t zsflags = zone_security_config(z);
4489 kma_flags_t kmaflags = zone_kma_flags(z, zsflags, flags) | KMA_VAONLY;
4490 uint32_t runs, pages, chunk_pages = z->z_chunk_pages;
4491 struct zone_page_metadata *meta;
4492 kern_return_t kr;
4493 vm_offset_t addr;
4494
4495 zone_unlock(z);
4496
4497 pages = chunk_pages;
4498 runs = 1;
4499 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
4500 if (!z->z_percpu && zone_submap_is_sequestered(zsflags)) {
4501 pages = roundup(atop(ZONE_CHUNK_ALLOC_SIZE), chunk_pages);
4502 runs = pages / chunk_pages;
4503 }
4504 #endif /* !ZSECURITY_CONFIG(SAD_FENG_SHUI) */
4505
4506 if (zone_submap_is_sequestered(zsflags)) {
4507 kr = zone_submap_alloc_sequestered_va(zsflags, pages, &addr);
4508 } else {
4509 kr = kernel_memory_allocate_prot(zone_submap(zsflags), &addr,
4510 ptoa(pages), 0, kmaflags, VM_KERN_MEMORY_ZONE,
4511 zone_submap_prot(zsflags), zone_submap_prot(zsflags));
4512 }
4513
4514 if (kr != KERN_SUCCESS) {
4515 #if CONFIG_ZLEAKS
4516 if ((zleak_state & ZLEAK_STATE_ACTIVE)) {
4517 panic_include_ztrace = true;
4518 }
4519 #endif /* CONFIG_ZLEAKS */
4520 uint64_t zone_size = 0;
4521 zone_t zone_largest = zone_find_largest(&zone_size);
4522 panic("zalloc[%d]: zone map exhausted while allocating from zone [%s%s], "
4523 "likely due to memory leak in zone [%s%s] "
4524 "(%luM, %d elements allocated)",
4525 kr, zone_heap_name(z), zone_name(z),
4526 zone_heap_name(zone_largest), zone_name(zone_largest),
4527 (unsigned long)zone_size >> 20,
4528 zone_count_allocated(zone_largest));
4529 }
4530
4531 meta = zone_meta_from_addr(addr);
4532 zone_meta_populate(addr, ptoa(pages));
4533
4534 for (uint32_t i = 0; i < pages; i++) {
4535 meta[i].zm_index = zone_index(z);
4536 }
4537
4538 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
4539 if (__improbable(zone_caching_disabled < 0)) {
4540 return zone_scramble_va_and_unlock(z, meta, runs, pages, chunk_pages);
4541 }
4542 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
4543
4544 zone_lock(z);
4545
4546 for (uint32_t i = 0, pg = 0; i < runs; pg += chunk_pages, i++) {
4547 zone_meta_queue_push(z, &z->z_pageq_va, meta + pg);
4548 }
4549 z->z_va_cur += z->z_percpu ? runs : pages;
4550 }
4551
4552 static bool
zone_expand_pred_nope(__unused zone_t z)4553 zone_expand_pred_nope(__unused zone_t z)
4554 {
4555 return false;
4556 }
4557
4558 static inline void
ZONE_TRACE_VM_KERN_REQUEST_START(vm_size_t size)4559 ZONE_TRACE_VM_KERN_REQUEST_START(vm_size_t size)
4560 {
4561 #if DEBUG || DEVELOPMENT
4562 VM_DEBUG_CONSTANT_EVENT(vm_kern_request, VM_KERN_REQUEST, DBG_FUNC_START,
4563 size, 0, 0, 0);
4564 #else
4565 (void)size;
4566 #endif
4567 }
4568
4569 static inline void
ZONE_TRACE_VM_KERN_REQUEST_END(uint32_t pages)4570 ZONE_TRACE_VM_KERN_REQUEST_END(uint32_t pages)
4571 {
4572 #if DEBUG || DEVELOPMENT
4573 task_t task = current_task_early();
4574 if (pages && task) {
4575 ledger_credit(task->ledger, task_ledgers.pages_grabbed_kern, pages);
4576 }
4577 VM_DEBUG_CONSTANT_EVENT(vm_kern_request, VM_KERN_REQUEST, DBG_FUNC_END,
4578 pages, 0, 0, 0);
4579 #else
4580 (void)pages;
4581 #endif
4582 }
4583
4584 __attribute__((noinline))
4585 static void
__ZONE_MAP_EXHAUSTED_AND_WAITING_FOR_GC__(zone_t z,uint32_t pgs)4586 __ZONE_MAP_EXHAUSTED_AND_WAITING_FOR_GC__(zone_t z, uint32_t pgs)
4587 {
4588 event_t event = &vm_pageout_garbage_collect;
4589 uint64_t wait_start = 0;
4590 long mapped;
4591 zone_security_flags_t zsflags = zone_security_config(z);
4592
4593 thread_wakeup(event);
4594
4595 if (zsflags.z_allows_foreign || current_thread()->options & TH_OPT_VMPRIV) {
4596 /*
4597 * "allow foreign" zones are allowed to overcommit
4598 * because they're used to reclaim memory (VM support).
4599 */
4600 return;
4601 }
4602
4603 mapped = os_atomic_load(&zones_phys_page_mapped_count, relaxed);
4604
4605 /*
4606 * If the zone map is really exhausted, wait on the GC thread,
4607 * donating our priority (which is important because the GC
4608 * thread is at a rather low priority).
4609 */
4610 for (uint32_t n = 1; mapped >= zone_phys_mapped_max_pages - pgs; n++) {
4611 uint32_t wait_ms = n * (n + 1) / 2;
4612 uint64_t interval;
4613
4614 if (n == 1) {
4615 wait_start = mach_absolute_time();
4616 } else {
4617 thread_wakeup(event);
4618 }
4619 if (zone_exhausted_timeout > 0 &&
4620 wait_ms > zone_exhausted_timeout) {
4621 panic("zone map exhaustion: waited for %dms "
4622 "(pages: %ld, max: %ld, wanted: %d)",
4623 wait_ms, mapped, zone_phys_mapped_max_pages, pgs);
4624 }
4625
4626 clock_interval_to_absolutetime_interval(wait_ms, NSEC_PER_MSEC,
4627 &interval);
4628
4629 lck_spin_lock(&zone_exhausted_lock);
4630 lck_spin_sleep_with_inheritor(&zone_exhausted_lock,
4631 LCK_SLEEP_UNLOCK, &zones_phys_page_mapped_count,
4632 vm_pageout_scan_thread, THREAD_UNINT, wait_start + interval);
4633
4634 mapped = os_atomic_load(&zones_phys_page_mapped_count, relaxed);
4635 }
4636 }
4637
4638 static bool
zone_expand_wait_for_pages(bool waited)4639 zone_expand_wait_for_pages(bool waited)
4640 {
4641 if (waited) {
4642 return false;
4643 }
4644 #if DEBUG || DEVELOPMENT
4645 if (zalloc_simulate_vm_pressure) {
4646 return false;
4647 }
4648 #endif /* DEBUG || DEVELOPMENT */
4649 return !vm_pool_low();
4650 }
4651
4652 static void
zone_expand_locked(zone_t z,zalloc_flags_t flags,bool (* pred)(zone_t))4653 zone_expand_locked(zone_t z, zalloc_flags_t flags, bool (*pred)(zone_t))
4654 {
4655 thread_t self = current_thread();
4656 bool vm_priv = (self->options & TH_OPT_VMPRIV);
4657 bool clear_vm_priv;
4658 thread_pri_floor_t token;
4659 zone_security_flags_t zsflags = zone_security_config(z);
4660
4661 for (;;) {
4662 if (!pred) {
4663 /* NULL pred means "try just once" */
4664 pred = zone_expand_pred_nope;
4665 } else if (!pred(z)) {
4666 return;
4667 }
4668
4669 if (vm_priv && !z->z_expander_vm_priv) {
4670 /*
4671 * Claim the vm priv overcommit slot
4672 *
4673 * We do not track exact ownership for VM privileged
4674 * threads, so use the rwlock boost as a stop-gap
4675 * just in case.
4676 */
4677 token = thread_priority_floor_start();
4678 z->z_expander_vm_priv = true;
4679 clear_vm_priv = true;
4680 } else {
4681 clear_vm_priv = false;
4682 }
4683
4684 if (z->z_expander == NULL) {
4685 z->z_expander = self;
4686 break;
4687 }
4688 if (clear_vm_priv) {
4689 break;
4690 }
4691
4692 if (flags & Z_NOPAGEWAIT) {
4693 return;
4694 }
4695
4696 z->z_expanding_wait = true;
4697 lck_spin_sleep_with_inheritor(&z->z_lock, LCK_SLEEP_DEFAULT,
4698 &z->z_expander, z->z_expander,
4699 TH_UNINT, TIMEOUT_WAIT_FOREVER);
4700 }
4701
4702 do {
4703 struct zone_page_metadata *meta = NULL;
4704 uint32_t new_va = 0, cur_pages = 0, min_pages = 0, pages = 0;
4705 vm_page_t page_list = NULL;
4706 vm_offset_t addr = 0;
4707 int waited = 0;
4708
4709 /*
4710 * While we hold the zone lock, look if there's VA we can:
4711 * - complete from partial pages,
4712 * - reuse from the sequester list.
4713 *
4714 * When the page is being populated we pretend we allocated
4715 * an extra element so that zone_gc() can't attempt to free
4716 * the chunk (as it could become empty while we wait for pages).
4717 */
4718 if (zone_pva_is_null(z->z_pageq_va)) {
4719 zone_allocate_va_locked(z, flags);
4720 }
4721
4722 meta = zone_meta_queue_pop_native(z, &z->z_pageq_va, &addr);
4723 if (meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
4724 cur_pages = meta->zm_page_index;
4725 meta -= cur_pages;
4726 addr -= ptoa(cur_pages);
4727 zone_meta_lock_in_partial(z, meta, cur_pages);
4728 }
4729 zone_unlock(z);
4730
4731 /*
4732 * And now allocate pages to populate our VA.
4733 */
4734 if (z->z_percpu) {
4735 min_pages = z->z_chunk_pages;
4736 } else {
4737 min_pages = (uint32_t)atop(round_page(zone_elem_size(z)));
4738 }
4739
4740 /*
4741 * Do the zone leak activation here because zleak_activate()
4742 * may block, and can't be done on the way out.
4743 *
4744 * Trigger jetsams via the vm_pageout_garbage_collect thread if
4745 * we're running out of zone memory
4746 */
4747 zleak_activate_if_needed();
4748 if (__improbable(zone_map_nearing_exhaustion())) {
4749 __ZONE_MAP_EXHAUSTED_AND_WAITING_FOR_GC__(z, min_pages);
4750 }
4751
4752 ZONE_TRACE_VM_KERN_REQUEST_START(ptoa(z->z_chunk_pages - cur_pages));
4753
4754 while (pages < z->z_chunk_pages - cur_pages) {
4755 vm_page_t m = vm_page_grab();
4756
4757 if (m) {
4758 pages++;
4759 m->vmp_snext = page_list;
4760 page_list = m;
4761 vm_page_zero_fill(m);
4762 continue;
4763 }
4764
4765 if (pages >= min_pages &&
4766 !zone_expand_wait_for_pages(waited)) {
4767 break;
4768 }
4769
4770 if ((flags & Z_NOPAGEWAIT) == 0) {
4771 waited++;
4772 VM_PAGE_WAIT();
4773 continue;
4774 }
4775
4776 /*
4777 * Undo everything and bail out:
4778 *
4779 * - free pages
4780 * - undo the fake allocation if any
4781 * - put the VA back on the VA page queue.
4782 */
4783 vm_page_free_list(page_list, FALSE);
4784 ZONE_TRACE_VM_KERN_REQUEST_END(pages);
4785
4786 zone_lock(z);
4787
4788 if (cur_pages) {
4789 zone_meta_unlock_from_partial(z, meta, cur_pages);
4790 }
4791 if (meta) {
4792 zone_meta_queue_push(z, &z->z_pageq_va,
4793 meta + cur_pages);
4794 }
4795 goto page_shortage;
4796 }
4797
4798 kernel_memory_populate_with_pages(zone_submap(zsflags),
4799 addr + ptoa(cur_pages), ptoa(pages), page_list,
4800 zone_kma_flags(z, zsflags, flags), VM_KERN_MEMORY_ZONE,
4801 (zsflags.z_submap_idx == Z_SUBMAP_IDX_READ_ONLY) ? VM_PROT_READ : VM_PROT_READ | VM_PROT_WRITE);
4802
4803 ZONE_TRACE_VM_KERN_REQUEST_END(pages);
4804
4805 zcram_and_lock(z, addr, new_va, cur_pages, cur_pages + pages,
4806 ZONE_ADDR_NATIVE);
4807 } while (pred(z));
4808
4809 page_shortage:
4810 zleak_track_if_needed(z);
4811
4812 if (clear_vm_priv) {
4813 z->z_expander_vm_priv = false;
4814 thread_priority_floor_end(&token);
4815 }
4816 if (z->z_expander == self) {
4817 z->z_expander = THREAD_NULL;
4818 }
4819 if (z->z_expanding_wait) {
4820 z->z_expanding_wait = false;
4821 wakeup_all_with_inheritor(&z->z_expander, THREAD_AWAKENED);
4822 }
4823 }
4824
4825 static bool
zalloc_needs_refill(zone_t zone)4826 zalloc_needs_refill(zone_t zone)
4827 {
4828 if (zone->z_elems_free > zone->z_elems_rsv) {
4829 return false;
4830 }
4831 if (zone->z_wired_cur < zone->z_wired_max) {
4832 return true;
4833 }
4834 if (zone->exhaustible) {
4835 return false;
4836 }
4837 if (zone->expandable) {
4838 /*
4839 * If we're expandable, just don't go through this again.
4840 */
4841 zone->z_wired_max = ~0u;
4842 return true;
4843 }
4844 zone_unlock(zone);
4845
4846 #if CONFIG_ZLEAKS
4847 if (zleak_state & ZLEAK_STATE_ACTIVE) {
4848 panic_include_ztrace = true;
4849 }
4850 #endif /* CONFIG_ZLEAKS */
4851 panic("zone '%s%s' exhausted", zone_heap_name(zone), zone_name(zone));
4852 }
4853
4854 static void
zone_expand_async(__unused thread_call_param_t p0,__unused thread_call_param_t p1)4855 zone_expand_async(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
4856 {
4857 zone_foreach(z) {
4858 if (z->no_callout) {
4859 /* z_async_refilling will never be set */
4860 continue;
4861 }
4862
4863 zone_lock(z);
4864 if (z->z_self && z->z_async_refilling) {
4865 z->z_async_refilling = false;
4866 zone_expand_locked(z, Z_WAITOK, zalloc_needs_refill);
4867 }
4868 zone_unlock(z);
4869 }
4870 }
4871
4872 static inline void
zone_expand_async_schedule_if_needed(zone_t zone)4873 zone_expand_async_schedule_if_needed(zone_t zone)
4874 {
4875 if (__improbable(startup_phase < STARTUP_SUB_THREAD_CALL)) {
4876 return;
4877 }
4878
4879 if (zone->z_elems_free > zone->z_elems_rsv || zone->z_async_refilling ||
4880 zone->no_callout) {
4881 return;
4882 }
4883
4884 if (!zone->expandable && zone->z_wired_cur >= zone->z_wired_max) {
4885 return;
4886 }
4887
4888 if (startup_phase < STARTUP_SUB_EARLY_BOOT) {
4889 return;
4890 }
4891
4892 if (zone->z_elems_free == 0 || !vm_pool_low()) {
4893 zone->z_async_refilling = true;
4894 thread_call_enter(&zone_expand_callout);
4895 }
4896 }
4897
4898 #endif /* !ZALLOC_TEST */
4899 #pragma mark zone jetsam integration
4900 #if !ZALLOC_TEST
4901
4902 /*
4903 * We're being very conservative here and picking a value of 95%. We might need to lower this if
4904 * we find that we're not catching the problem and are still hitting zone map exhaustion panics.
4905 */
4906 #define ZONE_MAP_JETSAM_LIMIT_DEFAULT 95
4907
4908 /*
4909 * Threshold above which largest zones should be included in the panic log
4910 */
4911 #define ZONE_MAP_EXHAUSTION_PRINT_PANIC 80
4912
4913 /*
4914 * Trigger zone-map-exhaustion jetsams if the zone map is X% full, where X=zone_map_jetsam_limit.
4915 * Can be set via boot-arg "zone_map_jetsam_limit". Set to 95% by default.
4916 */
4917 TUNABLE_WRITEABLE(unsigned int, zone_map_jetsam_limit, "zone_map_jetsam_limit",
4918 ZONE_MAP_JETSAM_LIMIT_DEFAULT);
4919
4920 void
get_zone_map_size(uint64_t * current_size,uint64_t * capacity)4921 get_zone_map_size(uint64_t *current_size, uint64_t *capacity)
4922 {
4923 vm_offset_t phys_pages = os_atomic_load(&zones_phys_page_mapped_count, relaxed);
4924 *current_size = ptoa_64(phys_pages);
4925 *capacity = ptoa_64(zone_phys_mapped_max_pages);
4926 }
4927
4928 void
get_largest_zone_info(char * zone_name,size_t zone_name_len,uint64_t * zone_size)4929 get_largest_zone_info(char *zone_name, size_t zone_name_len, uint64_t *zone_size)
4930 {
4931 zone_t largest_zone = zone_find_largest(zone_size);
4932
4933 /*
4934 * Append kalloc heap name to zone name (if zone is used by kalloc)
4935 */
4936 snprintf(zone_name, zone_name_len, "%s%s",
4937 zone_heap_name(largest_zone), largest_zone->z_name);
4938 }
4939
4940 static bool
zone_map_nearing_threshold(unsigned int threshold)4941 zone_map_nearing_threshold(unsigned int threshold)
4942 {
4943 uint64_t phys_pages = os_atomic_load(&zones_phys_page_mapped_count, relaxed);
4944 return phys_pages * 100 > zone_phys_mapped_max_pages * threshold;
4945 }
4946
4947 bool
zone_map_nearing_exhaustion(void)4948 zone_map_nearing_exhaustion(void)
4949 {
4950 return zone_map_nearing_threshold(zone_map_jetsam_limit);
4951 }
4952
4953
4954 #define VMENTRY_TO_VMOBJECT_COMPARISON_RATIO 98
4955
4956 /*
4957 * Tries to kill a single process if it can attribute one to the largest zone. If not, wakes up the memorystatus thread
4958 * to walk through the jetsam priority bands and kill processes.
4959 */
4960 static void
kill_process_in_largest_zone(void)4961 kill_process_in_largest_zone(void)
4962 {
4963 pid_t pid = -1;
4964 uint64_t zone_size = 0;
4965 zone_t largest_zone = zone_find_largest(&zone_size);
4966
4967 printf("zone_map_exhaustion: Zone mapped %lld of %lld, used %lld, capacity %lld [jetsam limit %d%%]\n",
4968 ptoa_64(os_atomic_load(&zones_phys_page_mapped_count, relaxed)),
4969 ptoa_64(zone_phys_mapped_max_pages),
4970 (uint64_t)zone_submaps_approx_size(),
4971 (uint64_t)(zone_foreign_size() + zone_native_size()),
4972 zone_map_jetsam_limit);
4973 printf("zone_map_exhaustion: Largest zone %s%s, size %lu\n", zone_heap_name(largest_zone),
4974 largest_zone->z_name, (uintptr_t)zone_size);
4975
4976 /*
4977 * We want to make sure we don't call this function from userspace.
4978 * Or we could end up trying to synchronously kill the process
4979 * whose context we're in, causing the system to hang.
4980 */
4981 assert(current_task() == kernel_task);
4982
4983 /*
4984 * If vm_object_zone is the largest, check to see if the number of
4985 * elements in vm_map_entry_zone is comparable.
4986 *
4987 * If so, consider vm_map_entry_zone as the largest. This lets us target
4988 * a specific process to jetsam to quickly recover from the zone map
4989 * bloat.
4990 */
4991 if (largest_zone == vm_object_zone) {
4992 unsigned int vm_object_zone_count = zone_count_allocated(vm_object_zone);
4993 unsigned int vm_map_entry_zone_count = zone_count_allocated(vm_map_entry_zone);
4994 /* Is the VM map entries zone count >= 98% of the VM objects zone count? */
4995 if (vm_map_entry_zone_count >= ((vm_object_zone_count * VMENTRY_TO_VMOBJECT_COMPARISON_RATIO) / 100)) {
4996 largest_zone = vm_map_entry_zone;
4997 printf("zone_map_exhaustion: Picking VM map entries as the zone to target, size %lu\n",
4998 (uintptr_t)zone_size_wired(largest_zone));
4999 }
5000 }
5001
5002 /* TODO: Extend this to check for the largest process in other zones as well. */
5003 if (largest_zone == vm_map_entry_zone) {
5004 pid = find_largest_process_vm_map_entries();
5005 } else {
5006 printf("zone_map_exhaustion: Nothing to do for the largest zone [%s%s]. "
5007 "Waking up memorystatus thread.\n", zone_heap_name(largest_zone),
5008 largest_zone->z_name);
5009 }
5010 if (!memorystatus_kill_on_zone_map_exhaustion(pid)) {
5011 printf("zone_map_exhaustion: Call to memorystatus failed, victim pid: %d\n", pid);
5012 }
5013 }
5014
5015 #endif /* !ZALLOC_TEST */
5016 #pragma mark zfree
5017 #if !ZALLOC_TEST
5018
5019 /*!
5020 * @defgroup zfree
5021 * @{
5022 *
5023 * @brief
5024 * The codepath for zone frees.
5025 *
5026 * @discussion
5027 * There are 4 major ways to allocate memory that end up in the zone allocator:
5028 * - @c zfree()
5029 * - @c zfree_percpu()
5030 * - @c kfree*()
5031 * - @c zfree_permanent()
5032 *
5033 * While permanent zones have their own allocation scheme, all other codepaths
5034 * will eventually go through the @c zfree_ext() choking point.
5035 *
5036 * Ignoring the @c gzalloc_free() codepath, the decision tree looks like this:
5037 * <code>
5038 * zfree_ext()
5039 * ├───> zfree_cached() ────────────────╮
5040 * │ │ │
5041 * │ │ │
5042 * │ ├───> zfree_cached_slow() ───┤
5043 * │ │ │ │
5044 * │ │ v │
5045 * ╰───────┴───> zfree_item() ──────────┴───>
5046 * </code>
5047 *
5048 * @c zfree_ext() takes care of all the generic work to perform on an element
5049 * before it is freed (zeroing, logging, tagging, ...) then will hand it off to:
5050 * - @c zfree_item() if zone caching is off
5051 * - @c zfree_cached() if zone caching is on.
5052 *
5053 * @c zfree_cached can take a number of decisions:
5054 * - a fast path if the (f) or (a) magazines have space (preemption disabled),
5055 * - using the cpu local or recirculation depot calling @c zfree_cached_slow(),
5056 * - falling back to @c zfree_item() when CPU caching has been disabled.
5057 */
5058
5059 #if KASAN_ZALLOC
5060 /*
5061 * Called from zfree() to add the element being freed to the KASan quarantine.
5062 *
5063 * Returns true if the newly-freed element made it into the quarantine without
5064 * displacing another, false otherwise. In the latter case, addrp points to the
5065 * address of the displaced element, which will be freed by the zone.
5066 */
5067 static bool
kasan_quarantine_freed_element(zone_t * zonep,void ** addrp)5068 kasan_quarantine_freed_element(
5069 zone_t *zonep, /* the zone the element is being freed to */
5070 void **addrp) /* address of the element being freed */
5071 {
5072 zone_t zone = *zonep;
5073 void *addr = *addrp;
5074
5075 /*
5076 * Resize back to the real allocation size and hand off to the KASan
5077 * quarantine. `addr` may then point to a different allocation, if the
5078 * current element replaced another in the quarantine. The zone then
5079 * takes ownership of the swapped out free element.
5080 */
5081 vm_size_t usersz = zone_elem_size(zone) - 2 * zone->z_kasan_redzone;
5082 vm_size_t sz = usersz;
5083
5084 if (addr && zone->z_kasan_redzone) {
5085 kasan_check_free((vm_address_t)addr, usersz, KASAN_HEAP_ZALLOC);
5086 addr = (void *)kasan_dealloc((vm_address_t)addr, &sz);
5087 assert(sz == zone_elem_size(zone));
5088 }
5089 if (addr && !zone->kasan_noquarantine) {
5090 kasan_free(&addr, &sz, KASAN_HEAP_ZALLOC, zonep, usersz, true);
5091 if (!addr) {
5092 return TRUE;
5093 }
5094 }
5095 if (addr && zone->kasan_noquarantine) {
5096 kasan_unpoison(addr, zone_elem_size(zone));
5097 }
5098 *addrp = addr;
5099 return FALSE;
5100 }
5101 #endif /* KASAN_ZALLOC */
5102
5103 __header_always_inline void
zfree_drop(zone_t zone,struct zone_page_metadata * meta,zone_element_t ze,bool recirc)5104 zfree_drop(zone_t zone, struct zone_page_metadata *meta, zone_element_t ze,
5105 bool recirc)
5106 {
5107 vm_offset_t esize = zone_elem_size(zone);
5108
5109 if (zone_meta_mark_free(meta, ze) == recirc) {
5110 zone_meta_double_free_panic(zone, ze, __func__);
5111 }
5112
5113 vm_offset_t old_size = meta->zm_alloc_size;
5114 vm_offset_t max_size = ptoa(meta->zm_chunk_len) + ZM_ALLOC_SIZE_LOCK;
5115 vm_offset_t new_size = zone_meta_alloc_size_sub(zone, meta, esize);
5116
5117 if (new_size == 0) {
5118 /* whether the page was on the intermediate or all_used, queue, move it to free */
5119 zone_meta_requeue(zone, &zone->z_pageq_empty, meta);
5120 zone->z_wired_empty += meta->zm_chunk_len;
5121 } else if (old_size + esize > max_size) {
5122 /* first free element on page, move from all_used */
5123 zone_meta_requeue(zone, &zone->z_pageq_partial, meta);
5124 }
5125 }
5126
5127 static void
zfree_item(zone_t zone,struct zone_page_metadata * meta,zone_element_t ze)5128 zfree_item(zone_t zone, struct zone_page_metadata *meta, zone_element_t ze)
5129 {
5130 /* transfer preemption count to lock */
5131 zone_lock_nopreempt_check_contention(zone, NULL);
5132
5133 zfree_drop(zone, meta, ze, false);
5134 zone_elems_free_add(zone, 1);
5135
5136 zone_unlock(zone);
5137 }
5138
5139 __attribute__((noinline))
5140 static void
zfree_cached_slow(zone_t zone,struct zone_page_metadata * meta,zone_element_t ze,zone_cache_t cache)5141 zfree_cached_slow(zone_t zone, struct zone_page_metadata *meta,
5142 zone_element_t ze, zone_cache_t cache)
5143 {
5144 struct zone_depot mags = STAILQ_HEAD_INITIALIZER(mags);
5145 zone_magazine_t mag = NULL;
5146 uint16_t n = 0;
5147
5148 if (zone_meta_is_free(meta, ze)) {
5149 zone_meta_double_free_panic(zone, ze, __func__);
5150 }
5151
5152 if (zone == zc_magazine_zone) {
5153 mag = (zone_magazine_t)zone_element_addr(ze,
5154 zone_elem_size(zone));
5155 #if KASAN_ZALLOC
5156 kasan_poison_range((vm_offset_t)mag, zone_elem_size(zone),
5157 ASAN_VALID);
5158 #endif
5159 } else {
5160 mag = zone_magazine_alloc(Z_NOWAIT);
5161 if (__improbable(mag == NULL)) {
5162 return zfree_item(zone, meta, ze);
5163 }
5164 mag->zm_cur = 1;
5165 mag->zm_elems[0] = ze;
5166 }
5167
5168 mag = zone_magazine_replace(&cache->zc_free_cur,
5169 &cache->zc_free_elems, mag);
5170
5171 z_debug_assert(cache->zc_free_cur <= 1);
5172 z_debug_assert(mag->zm_cur == zc_mag_size());
5173
5174 STAILQ_INSERT_HEAD(&mags, mag, zm_link);
5175 n = 1;
5176
5177 if (cache->zc_depot_max >= 2 * zc_mag_size()) {
5178 /*
5179 * If we can use the local depot (zc_depot_max allows for
5180 * 2 magazines worth of elements) then:
5181 *
5182 * 1. if we have space for an extra depot locally,
5183 * push it, and leave.
5184 *
5185 * 2. if we overflow, then take (1 / zc_recirc_denom)
5186 * of the depot out, in order to migrate it to the
5187 * recirculation depot.
5188 */
5189 zone_depot_lock_nopreempt(cache);
5190
5191 if ((cache->zc_depot_cur + 2) * zc_mag_size() <=
5192 cache->zc_depot_max) {
5193 cache->zc_depot_cur++;
5194 STAILQ_INSERT_TAIL(&cache->zc_depot, mag, zm_link);
5195 return zone_depot_unlock(cache);
5196 }
5197
5198 while (zc_recirc_denom * cache->zc_depot_cur * zc_mag_size() >=
5199 (zc_recirc_denom - 1) * cache->zc_depot_max) {
5200 mag = STAILQ_FIRST(&cache->zc_depot);
5201 STAILQ_REMOVE_HEAD(&cache->zc_depot, zm_link);
5202 STAILQ_INSERT_TAIL(&mags, mag, zm_link);
5203 cache->zc_depot_cur--;
5204 n++;
5205 }
5206
5207 zone_depot_unlock(cache);
5208 } else {
5209 enable_preemption();
5210 }
5211
5212 /*
5213 * Preflight validity of all the elements before we touch the zone
5214 * metadata, and then insert them into the recirculation depot.
5215 */
5216 STAILQ_FOREACH(mag, &mags, zm_link) {
5217 for (uint16_t i = 0; i < zc_mag_size(); i++) {
5218 zone_element_validate(zone, mag->zm_elems[i]);
5219 }
5220 }
5221
5222 zone_lock_check_contention(zone, cache);
5223
5224 STAILQ_FOREACH(mag, &mags, zm_link) {
5225 for (uint16_t i = 0; i < zc_mag_size(); i++) {
5226 zone_element_t e = mag->zm_elems[i];
5227
5228 if (!zone_meta_mark_free(zone_meta_from_element(e), e)) {
5229 zone_meta_double_free_panic(zone, e, __func__);
5230 }
5231 }
5232 }
5233 STAILQ_CONCAT(&zone->z_recirc, &mags);
5234 zone->z_recirc_cur += n;
5235
5236 zone_elems_free_add(zone, n * zc_mag_size());
5237
5238 zone_unlock(zone);
5239 }
5240
5241 static void
zfree_cached(zone_t zone,struct zone_page_metadata * meta,zone_element_t ze)5242 zfree_cached(zone_t zone, struct zone_page_metadata *meta, zone_element_t ze)
5243 {
5244 zone_cache_t cache = zpercpu_get(zone->z_pcpu_cache);
5245
5246 if (cache->zc_free_cur >= zc_mag_size()) {
5247 if (cache->zc_alloc_cur >= zc_mag_size()) {
5248 return zfree_cached_slow(zone, meta, ze, cache);
5249 }
5250 zone_cache_swap_magazines(cache);
5251 }
5252
5253 if (__improbable(cache->zc_alloc_elems == NULL)) {
5254 return zfree_item(zone, meta, ze);
5255 }
5256
5257 if (zone_meta_is_free(meta, ze)) {
5258 zone_meta_double_free_panic(zone, ze, __func__);
5259 }
5260
5261 uint16_t idx = cache->zc_free_cur++;
5262 if (idx >= zc_mag_size()) {
5263 zone_accounting_panic(zone, "zc_free_cur overflow");
5264 }
5265 cache->zc_free_elems[idx] = ze;
5266
5267 enable_preemption();
5268 }
5269
5270 /*
5271 * The function is noinline when zlog can be used so that the backtracing can
5272 * reliably skip the zfree_ext() and zfree_log_trace()
5273 * boring frames.
5274 */
5275 #if ZONE_ENABLE_LOGGING
5276 __attribute__((noinline))
5277 #endif /* ZONE_ENABLE_LOGGING */
5278 void
zfree_ext(zone_t zone,zone_stats_t zstats,void * addr,vm_size_t elem_size)5279 zfree_ext(zone_t zone, zone_stats_t zstats, void *addr, vm_size_t elem_size)
5280 {
5281 struct zone_page_metadata *page_meta;
5282 vm_offset_t elem = (vm_offset_t)addr;
5283 zone_element_t ze;
5284
5285 DTRACE_VM2(zfree, zone_t, zone, void*, addr);
5286 TRACE_MACHLEAKS(ZFREE_CODE, ZFREE_CODE_2, elem_size, elem);
5287
5288 #if CONFIG_KERNEL_TBI && KASAN_TBI
5289 if (zone->z_tbi_tag) {
5290 elem = kasan_tbi_tag_zfree(elem, elem_size, zone->z_percpu);
5291 /* addr is still consumed in the function: gzalloc_free */
5292 addr = (void *)elem;
5293 }
5294 #endif /* CONFIG_KERNEL_TBI && KASAN_TBI */
5295
5296 #if VM_TAG_SIZECLASSES
5297 if (__improbable(zone->z_uses_tags)) {
5298 vm_tag_t tag = *ztSlot(zone, elem) >> 1;
5299 // set the tag with b0 clear so the block remains inuse
5300 *ztSlot(zone, elem) = 0xFFFE;
5301 vm_tag_update_zone_size(tag, zone->z_tags_sizeclass,
5302 -(long)elem_size);
5303 }
5304 #endif /* VM_TAG_SIZECLASSES */
5305
5306 #if KASAN_ZALLOC
5307 /*
5308 * Call zone_element_resolve() and throw away the results in
5309 * order to validate the element and its zone membership.
5310 * Any validation panics need to happen now, while we're
5311 * still close to the caller.
5312 *
5313 * Note that elem has not been adjusted, so we have to remove the
5314 * redzone first.
5315 */
5316 zone_element_t ze_discard;
5317 vm_offset_t elem_actual = elem - zone->z_kasan_redzone;
5318 (void)zone_element_resolve(zone, elem_actual, elem_size, &ze_discard);
5319
5320 if (kasan_quarantine_freed_element(&zone, &addr)) {
5321 return;
5322 }
5323 /*
5324 * kasan_quarantine_freed_element() might return a different
5325 * {zone, addr} than the one being freed for kalloc heaps.
5326 *
5327 * Make sure we reload everything.
5328 */
5329 elem = (vm_offset_t)addr;
5330 elem_size = zone_elem_size(zone);
5331 #endif
5332 #if CONFIG_ZLEAKS
5333 /*
5334 * Zone leak detection: un-track the allocation
5335 */
5336 if (__improbable(zone->zleak_on)) {
5337 zleak_free(elem, elem_size);
5338 }
5339 #endif /* CONFIG_ZLEAKS */
5340 #if ZONE_ENABLE_LOGGING
5341 if (__improbable(DO_LOGGING(zone))) {
5342 zfree_log_trace(zone, elem, __builtin_frame_address(0));
5343 }
5344 #endif /* ZONE_ENABLE_LOGGING */
5345 #if CONFIG_GZALLOC
5346 if (__improbable(zone->gzalloc_tracked)) {
5347 return gzalloc_free(zone, zstats, addr);
5348 }
5349 #endif /* CONFIG_GZALLOC */
5350
5351 page_meta = zone_element_resolve(zone, elem, elem_size, &ze);
5352 #if KASAN_ZALLOC
5353 if (zone->z_percpu) {
5354 zpercpu_foreach_cpu(i) {
5355 kasan_poison_range(elem + ptoa(i), elem_size,
5356 ASAN_HEAP_FREED);
5357 }
5358 } else {
5359 kasan_poison_range(elem, elem_size, ASAN_HEAP_FREED);
5360 }
5361 #endif
5362
5363 disable_preemption();
5364 zpercpu_get(zstats)->zs_mem_freed += elem_size;
5365
5366 if (zone->z_pcpu_cache) {
5367 return zfree_cached(zone, page_meta, ze);
5368 }
5369
5370 return zfree_item(zone, page_meta, ze);
5371 }
5372
5373 void
5374 (zfree)(union zone_or_view zov, void *addr)
5375 {
5376 zone_t zone = zov.zov_view->zv_zone;
5377 zone_stats_t zstats = zov.zov_view->zv_stats;
5378 vm_offset_t esize = zone_elem_size(zone);
5379
5380 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
5381 assert(!zone->z_percpu);
5382 #if !KASAN_KALLOC
5383 bzero(addr, esize);
5384 #endif /* !KASAN_KALLOC */
5385 zfree_ext(zone, zstats, addr, esize);
5386 }
5387
5388 __attribute__((noinline))
5389 void
zfree_percpu(union zone_or_view zov,void * addr)5390 zfree_percpu(union zone_or_view zov, void *addr)
5391 {
5392 zone_t zone = zov.zov_view->zv_zone;
5393 zone_stats_t zstats = zov.zov_view->zv_stats;
5394 vm_offset_t esize = zone_elem_size(zone);
5395
5396 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
5397 assert(zone->z_percpu);
5398 addr = (void *)__zpcpu_demangle(addr);
5399 #if !KASAN_KALLOC
5400 zpercpu_foreach_cpu(i) {
5401 bzero((char *)addr + ptoa(i), esize);
5402 }
5403 #endif /* !KASAN_KALLOC */
5404 zfree_ext(zone, zstats, addr, esize);
5405 }
5406
5407 void
5408 (zfree_ro)(zone_id_t zid, void *addr)
5409 {
5410 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
5411 zone_t zone = &zone_array[zid];
5412 zone_stats_t zstats = zone->z_stats;
5413 vm_offset_t esize = zone_ro_elem_size[zid];
5414
5415 #if ZSECURITY_CONFIG(READ_ONLY)
5416 assert(zone_security_array[zid].z_submap_idx == Z_SUBMAP_IDX_READ_ONLY);
5417 pmap_ro_zone_bzero(zid, (vm_offset_t)addr, 0, esize);
5418 #elif !KASAN_KALLOC
5419 (void)zid;
5420 bzero(addr, esize);
5421 #endif /* !KASAN_KALLOC */
5422 zfree_ext(zone, zstats, addr, esize);
5423 }
5424
5425 /*! @} */
5426 #endif /* !ZALLOC_TEST */
5427 #pragma mark zalloc
5428 #if !ZALLOC_TEST
5429
5430 /*!
5431 * @defgroup zalloc
5432 * @{
5433 *
5434 * @brief
5435 * The codepath for zone allocations.
5436 *
5437 * @discussion
5438 * There are 4 major ways to allocate memory that end up in the zone allocator:
5439 * - @c zalloc(), @c zalloc_flags(), ...
5440 * - @c zalloc_percpu()
5441 * - @c kalloc*()
5442 * - @c zalloc_permanent()
5443 *
5444 * While permanent zones have their own allocation scheme, all other codepaths
5445 * will eventually go through the @c zalloc_ext() choking point.
5446 *
5447 * Ignoring the @c zalloc_gz() codepath, the decision tree looks like this:
5448 * <code>
5449 * zalloc_ext()
5450 * │
5451 * ├───> zalloc_cached() ──────> zalloc_cached_fast() ───╮
5452 * │ │ ^ │
5453 * │ │ │ │
5454 * │ ╰───> zalloc_cached_slow() ───╯ │
5455 * │ │ │
5456 * │<─────────────────╮ ├─────────────╮ │
5457 * │ │ │ │ │
5458 * │ │ v │ │
5459 * │<───────╮ ╭──> zalloc_item_slow() ────┤ │
5460 * │ │ │ │ │
5461 * │ │ │ v │
5462 * ╰───> zalloc_item() ──────────> zalloc_item_fast() ───┤
5463 * │
5464 * v
5465 * zalloc_return()
5466 * </code>
5467 *
5468 *
5469 * The @c zalloc_item() track is used when zone caching is off:
5470 * - @c zalloc_item_fast() is used when there are enough elements available,
5471 * - @c zalloc_item_slow() is used when a refill is needed, which can cause
5472 * the zone to grow. This is the only codepath that refills.
5473 *
5474 * This track uses the zone lock for serialization:
5475 * - taken in @c zalloc_item(),
5476 * - maintained during @c zalloc_item_slow() (possibly dropped and re-taken),
5477 * - dropped in @c zalloc_item_fast().
5478 *
5479 *
5480 * The @c zalloc_cached() track is used when zone caching is on:
5481 * - @c zalloc_cached_fast() is taken when the cache has elements,
5482 * - @c zalloc_cached_slow() is taken if a cache refill is needed.
5483 * It can chose many strategies:
5484 * ~ @c zalloc_cached_from_depot() to try to reuse cpu stashed magazines,
5485 * ~ using the global recirculation depot @c z_recirc,
5486 * ~ using zalloc_import() if the zone has enough elements,
5487 * ~ falling back to the @c zalloc_item() track if zone caching is disabled
5488 * due to VM pressure or the zone has no available elements.
5489 *
5490 * This track disables preemption for serialization:
5491 * - preemption is disabled in @c zalloc_ext(),
5492 * - kept disabled during @c zalloc_cached_slow(), converted into a zone lock
5493 * if switching to @c zalloc_item_slow(),
5494 * - preemption is reenabled in @c zalloc_cached_fast().
5495 *
5496 * @c zalloc_cached_from_depot() also takes depot locks (taken by the caller,
5497 * released by @c zalloc_cached_from_depot().
5498 *
5499 * In general the @c zalloc_*_slow() codepaths deal with refilling and will
5500 * tail call into the @c zalloc_*_fast() code to perform the actual allocation.
5501 *
5502 * @c zalloc_return() is the final function everyone tail calls into,
5503 * which prepares the element for consumption by the caller and deals with
5504 * common treatment (zone logging, tags, kasan, validation, ...).
5505 */
5506
5507 /*!
5508 * @function zalloc_import
5509 *
5510 * @brief
5511 * Import @c n elements in the specified array, opposite of @c zfree_drop().
5512 *
5513 * @param zone The zone to import elements from
5514 * @param elems The array to import into
5515 * @param n The number of elements to import. Must be non zero,
5516 * and smaller than @c zone->z_elems_free.
5517 */
5518 __header_always_inline void
zalloc_import(zone_t zone,zone_element_t * elems,zalloc_flags_t flags,vm_size_t esize,uint32_t n)5519 zalloc_import(zone_t zone, zone_element_t *elems, zalloc_flags_t flags,
5520 vm_size_t esize, uint32_t n)
5521 {
5522 uint32_t i = 0;
5523
5524 assertf(STAILQ_EMPTY(&zone->z_recirc),
5525 "Trying to import from zone %p [%s%s] with non empty recirc",
5526 zone, zone_heap_name(zone), zone_name(zone));
5527
5528 do {
5529 vm_offset_t page, eidx, size = 0;
5530 struct zone_page_metadata *meta;
5531
5532 if (!zone_pva_is_null(zone->z_pageq_partial)) {
5533 meta = zone_pva_to_meta(zone->z_pageq_partial);
5534 page = zone_pva_to_addr(zone->z_pageq_partial);
5535 } else if (!zone_pva_is_null(zone->z_pageq_empty)) {
5536 meta = zone_pva_to_meta(zone->z_pageq_empty);
5537 page = zone_pva_to_addr(zone->z_pageq_empty);
5538 zone_counter_sub(zone, z_wired_empty, meta->zm_chunk_len);
5539 } else {
5540 zone_accounting_panic(zone, "z_elems_free corruption");
5541 }
5542
5543 if (!zone_has_index(zone, meta->zm_index)) {
5544 zone_page_metadata_index_confusion_panic(zone, page, meta);
5545 }
5546
5547 vm_offset_t old_size = meta->zm_alloc_size;
5548 vm_offset_t max_size = ptoa(meta->zm_chunk_len) + ZM_ALLOC_SIZE_LOCK;
5549
5550 do {
5551 eidx = zone_meta_find_and_clear_bit(zone, meta, flags);
5552 elems[i++] = zone_element_encode(page, eidx);
5553 size += esize;
5554 } while (i < n && old_size + size + esize <= max_size);
5555
5556 vm_offset_t new_size = zone_meta_alloc_size_add(zone, meta, size);
5557
5558 if (new_size + esize > max_size) {
5559 zone_meta_requeue(zone, &zone->z_pageq_full, meta);
5560 } else if (old_size == 0) {
5561 /* remove from free, move to intermediate */
5562 zone_meta_requeue(zone, &zone->z_pageq_partial, meta);
5563 }
5564 } while (i < n);
5565 }
5566
5567 /*!
5568 * @function zalloc_return
5569 *
5570 * @brief
5571 * Performs the tail-end of the work required on allocations before the caller
5572 * uses them.
5573 *
5574 * @discussion
5575 * This function is called without any zone lock held,
5576 * and preemption back to the state it had when @c zalloc_ext() was called.
5577 *
5578 * @param zone The zone we're allocating from.
5579 * @param ze The encoded element we just allocated.
5580 * @param flags The flags passed to @c zalloc_ext() (for Z_ZERO).
5581 * @param elem_size The element size for this zone.
5582 */
5583 __attribute__((noinline))
5584 static void *
zalloc_return(zone_t zone,zone_element_t ze,zalloc_flags_t flags __unused,vm_offset_t elem_size)5585 zalloc_return(zone_t zone, zone_element_t ze, zalloc_flags_t flags __unused,
5586 vm_offset_t elem_size)
5587 {
5588 vm_offset_t addr = zone_element_addr(ze, elem_size);
5589
5590 #if CONFIG_KERNEL_TBI && KASAN_TBI
5591 addr = kasan_tbi_fix_address_tag(addr);
5592 #endif /* CONFIG_KERNEL_TBI && KASAN_TBI */
5593 #if ZALLOC_ENABLE_ZERO_CHECK
5594 zalloc_validate_element(zone, addr, elem_size, flags);
5595 #endif /* ZALLOC_ENABLE_ZERO_CHECK */
5596 #if ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS
5597 if (__improbable(zalloc_should_log_or_trace_leaks(zone, elem_size))) {
5598 zalloc_log_or_trace_leaks(zone, addr, __builtin_frame_address(0));
5599 }
5600 #endif /* ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS */
5601 #if KASAN_ZALLOC
5602 if (zone->z_kasan_redzone) {
5603 addr = kasan_alloc(addr, elem_size,
5604 elem_size - 2 * zone->z_kasan_redzone,
5605 zone->z_kasan_redzone);
5606 elem_size -= 2 * zone->z_kasan_redzone;
5607 }
5608 if (flags & Z_PCPU) {
5609 zpercpu_foreach_cpu(i) {
5610 kasan_poison_range(addr + ptoa(i), elem_size, ASAN_VALID);
5611 __nosan_bzero((char *)addr + ptoa(i), elem_size);
5612 }
5613 } else {
5614 kasan_poison_range(addr, elem_size, ASAN_VALID);
5615 __nosan_bzero((char *)addr, elem_size);
5616 }
5617 #endif /* KASAN_ZALLOC */
5618
5619 #if VM_TAG_SIZECLASSES
5620 if (__improbable(zone->z_uses_tags)) {
5621 vm_tag_t tag = zalloc_flags_get_tag(flags);
5622 if (tag == VM_KERN_MEMORY_NONE) {
5623 zone_security_flags_t zsflags = zone_security_config(zone);
5624 if (zsflags.z_kheap_id == KHEAP_ID_DATA_BUFFERS) {
5625 tag = VM_KERN_MEMORY_KALLOC_DATA;
5626 } else {
5627 tag = VM_KERN_MEMORY_KALLOC;
5628 }
5629 }
5630 // set the tag with b0 clear so the block remains inuse
5631 *ztSlot(zone, addr) = (vm_tag_t)(tag << 1);
5632 vm_tag_update_zone_size(tag, zone->z_tags_sizeclass,
5633 (long)elem_size);
5634 }
5635 #endif /* VM_TAG_SIZECLASSES */
5636
5637 #if CONFIG_KERNEL_TBI && KASAN_TBI
5638 if (__probable(zone->z_tbi_tag)) {
5639 addr = kasan_tbi_tag_zalloc(addr, elem_size, (flags & Z_PCPU));
5640 } else {
5641 addr = kasan_tbi_tag_zalloc_default(addr, elem_size, (flags & Z_PCPU));
5642 }
5643 #endif /* CONFIG_KERNEL_TBI && KASAN_TBI */
5644
5645 TRACE_MACHLEAKS(ZALLOC_CODE, ZALLOC_CODE_2, elem_size, addr);
5646 DTRACE_VM2(zalloc, zone_t, zone, void*, addr);
5647 return (void *)addr;
5648 }
5649
5650 #if CONFIG_GZALLOC
5651 /*!
5652 * @function zalloc_gz
5653 *
5654 * @brief
5655 * Performs allocations for zones using gzalloc.
5656 *
5657 * @discussion
5658 * This function is noinline so that it doesn't affect the codegen
5659 * of the fastpath.
5660 */
5661 __attribute__((noinline))
5662 static void *
zalloc_gz(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize)5663 zalloc_gz(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags, vm_size_t esize)
5664 {
5665 vm_offset_t addr = gzalloc_alloc(zone, zstats, flags);
5666 return zalloc_return(zone, zone_element_encode(addr, 0),
5667 flags, esize);
5668 }
5669 #endif /* CONFIG_GZALLOC */
5670
5671 __attribute__((noinline))
5672 static void *
zalloc_item_fast(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize)5673 zalloc_item_fast(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags,
5674 vm_size_t esize)
5675 {
5676 zone_element_t ze;
5677
5678 zalloc_import(zone, &ze, flags, esize, 1);
5679 zone_elems_free_sub(zone, 1);
5680 zpercpu_get(zstats)->zs_mem_allocated += esize;
5681 zone_unlock(zone);
5682
5683 return zalloc_return(zone, ze, flags, esize);
5684 }
5685
5686 static inline bool
zalloc_item_slow_should_schedule_async(zone_t zone,zalloc_flags_t flags)5687 zalloc_item_slow_should_schedule_async(zone_t zone, zalloc_flags_t flags)
5688 {
5689 /*
5690 * If we can't wait, then async it is.
5691 */
5692 if (flags & (Z_NOWAIT | Z_NOPAGEWAIT)) {
5693 return true;
5694 }
5695
5696 if (zone->z_elems_free == 0) {
5697 return false;
5698 }
5699
5700 /*
5701 * Early boot gets to tap in foreign reserves
5702 */
5703 if (startup_phase < STARTUP_SUB_EARLY_BOOT) {
5704 return true;
5705 }
5706
5707 /*
5708 * Allow threads to tap up to 3/4 of the reserve only doing asyncs.
5709 * Note that reserve-less zones will always say "true" here.
5710 */
5711 if (zone->z_elems_free >= zone->z_elems_rsv / 4) {
5712 return true;
5713 }
5714
5715 /*
5716 * After this, only VM and GC threads get to tap in the reserve.
5717 */
5718 return current_thread()->options & (TH_OPT_ZONE_PRIV | TH_OPT_VMPRIV);
5719 }
5720
5721 /*!
5722 * @function zalloc_item_slow
5723 *
5724 * @brief
5725 * Performs allocations when the zone is out of elements.
5726 *
5727 * @discussion
5728 * This function might drop the lock and reenable preemption,
5729 * which means the per-CPU caching layer or recirculation depot
5730 * might have received elements.
5731 */
5732 __attribute__((noinline))
5733 static void *
zalloc_item_slow(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize)5734 zalloc_item_slow(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags,
5735 vm_size_t esize)
5736 {
5737 if (zalloc_item_slow_should_schedule_async(zone, flags)) {
5738 zone_expand_async_schedule_if_needed(zone);
5739 } else {
5740 zone_expand_locked(zone, flags, zalloc_needs_refill);
5741 }
5742 if (__improbable(zone->z_elems_free == 0)) {
5743 zone_unlock(zone);
5744 if (__improbable(flags & Z_NOFAIL)) {
5745 zone_nofail_panic(zone);
5746 }
5747 DTRACE_VM2(zalloc, zone_t, zone, void*, NULL);
5748 return NULL;
5749 }
5750
5751 /*
5752 * We might have changed core or got preempted/blocked while expanding
5753 * the zone. Allocating from the zone when the recirculation depot
5754 * is not empty is not allowed.
5755 *
5756 * It will be rare but possible for the depot to refill while we were
5757 * waiting for pages. If that happens we need to start over.
5758 */
5759 if (!STAILQ_EMPTY(&zone->z_recirc)) {
5760 zone_unlock(zone);
5761 return zalloc_ext(zone, zstats, flags, esize);
5762 }
5763
5764 return zalloc_item_fast(zone, zstats, flags, esize);
5765 }
5766
5767 /*!
5768 * @function zalloc_item
5769 *
5770 * @brief
5771 * Performs allocations when zone caching is off.
5772 *
5773 * @discussion
5774 * This function calls @c zalloc_item_slow() when refilling the zone
5775 * is needed, or @c zalloc_item_fast() if the zone has enough free elements.
5776 */
5777 static void *
zalloc_item(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize)5778 zalloc_item(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags,
5779 vm_size_t esize)
5780 {
5781 zone_lock_nopreempt_check_contention(zone, NULL);
5782
5783 /*
5784 * When we commited to the zalloc_item() path,
5785 * zone caching might have been flipped/enabled.
5786 *
5787 * If we got preempted for long enough, the recirculation layer
5788 * can have been populated, and allocating from the zone would be
5789 * incorrect.
5790 *
5791 * So double check for this extremely rare race here.
5792 */
5793 if (__improbable(!STAILQ_EMPTY(&zone->z_recirc))) {
5794 zone_unlock(zone);
5795 return zalloc_ext(zone, zstats, flags, esize);
5796 }
5797
5798 if (__improbable(zone->z_elems_free <= zone->z_elems_rsv)) {
5799 return zalloc_item_slow(zone, zstats, flags, esize);
5800 }
5801
5802 return zalloc_item_fast(zone, zstats, flags, esize);
5803 }
5804
5805 __attribute__((always_inline))
5806 static void *
zalloc_cached_fast(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize,zone_cache_t cache,zone_magazine_t freemag)5807 zalloc_cached_fast(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags,
5808 vm_size_t esize, zone_cache_t cache, zone_magazine_t freemag)
5809 {
5810 zone_element_t ze;
5811 uint32_t index;
5812
5813 index = --cache->zc_alloc_cur;
5814 if (index >= zc_mag_size()) {
5815 zone_accounting_panic(zone, "zc_alloc_cur wrap around");
5816 }
5817 ze = cache->zc_alloc_elems[index];
5818 cache->zc_alloc_elems[index].ze_value = 0;
5819
5820 zpercpu_get(zstats)->zs_mem_allocated += esize;
5821 enable_preemption();
5822
5823 if (zone_meta_is_free(zone_meta_from_element(ze), ze)) {
5824 zone_meta_double_free_panic(zone, ze, __func__);
5825 }
5826
5827 if (freemag) {
5828 zone_magazine_free(freemag);
5829 }
5830 return zalloc_return(zone, ze, flags, esize);
5831 }
5832
5833 __attribute__((noinline))
5834 static void *
zalloc_cached_from_depot(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize,zone_cache_t cache,zone_cache_t depot,zone_magazine_t mag)5835 zalloc_cached_from_depot(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags,
5836 vm_size_t esize, zone_cache_t cache, zone_cache_t depot, zone_magazine_t mag)
5837 {
5838 STAILQ_REMOVE_HEAD(&depot->zc_depot, zm_link);
5839 if (depot->zc_depot_cur-- == 0) {
5840 zone_accounting_panic(zone, "zc_depot_cur wrap-around");
5841 }
5842 zone_depot_unlock_nopreempt(depot);
5843
5844 mag = zone_magazine_replace(&cache->zc_alloc_cur,
5845 &cache->zc_alloc_elems, mag);
5846
5847 z_debug_assert(cache->zc_alloc_cur == zc_mag_size());
5848 z_debug_assert(mag->zm_cur == 0);
5849
5850 if (zone == zc_magazine_zone) {
5851 enable_preemption();
5852 bzero(mag, esize);
5853 return mag;
5854 }
5855
5856 return zalloc_cached_fast(zone, zstats, flags, esize, cache, mag);
5857 }
5858
5859 __attribute__((noinline))
5860 static void *
zalloc_cached_slow(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize,zone_cache_t cache)5861 zalloc_cached_slow(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags,
5862 vm_size_t esize, zone_cache_t cache)
5863 {
5864 zone_magazine_t mag = NULL;
5865 struct zone_depot mags = STAILQ_HEAD_INITIALIZER(mags);
5866
5867 /*
5868 * Try to allocate from our local depot, if there's one.
5869 */
5870 if (STAILQ_FIRST(&cache->zc_depot)) {
5871 zone_depot_lock_nopreempt(cache);
5872
5873 if ((mag = STAILQ_FIRST(&cache->zc_depot)) != NULL) {
5874 return zalloc_cached_from_depot(zone, zstats, flags,
5875 esize, cache, cache, mag);
5876 }
5877
5878 zone_depot_unlock_nopreempt(cache);
5879 }
5880
5881 zone_lock_nopreempt_check_contention(zone, cache);
5882
5883 /*
5884 * If the recirculation depot is empty, we'll need to import.
5885 * The system is tuned for this to be extremely rare.
5886 */
5887 if (__improbable(STAILQ_EMPTY(&zone->z_recirc))) {
5888 uint16_t n_elems = zc_mag_size();
5889
5890 if (zone->z_elems_free < n_elems + zone->z_elems_rsv / 2 &&
5891 os_sub_overflow(zone->z_elems_free,
5892 zone->z_elems_rsv / 2, &n_elems)) {
5893 n_elems = 0;
5894 }
5895
5896 z_debug_assert(n_elems <= zc_mag_size());
5897
5898 if (__improbable(n_elems == 0)) {
5899 /*
5900 * If importing elements would deplete the zone,
5901 * call zalloc_item_slow()
5902 */
5903 return zalloc_item_slow(zone, zstats, flags, esize);
5904 }
5905
5906 if (__improbable(zone_caching_disabled)) {
5907 if (__improbable(zone_caching_disabled < 0)) {
5908 /*
5909 * In the first 10s after boot, mess with
5910 * the scan position in order to make early
5911 * allocations patterns less predictible.
5912 */
5913 zone_early_scramble_rr(zone, zstats);
5914 }
5915 return zalloc_item_fast(zone, zstats, flags, esize);
5916 }
5917
5918 zalloc_import(zone, cache->zc_alloc_elems, flags,
5919 esize, n_elems);
5920
5921 cache->zc_alloc_cur = n_elems;
5922 zone_elems_free_sub(zone, n_elems);
5923
5924 zone_unlock_nopreempt(zone);
5925
5926 return zalloc_cached_fast(zone, zstats, flags, esize, cache, NULL);
5927 }
5928
5929 uint16_t n_mags = 0;
5930
5931 /*
5932 * If the recirculation depot has elements, then try to fill
5933 * the local per-cpu depot to (1 / zc_recirc_denom)
5934 */
5935 do {
5936 mag = STAILQ_FIRST(&zone->z_recirc);
5937 STAILQ_REMOVE_HEAD(&zone->z_recirc, zm_link);
5938 STAILQ_INSERT_TAIL(&mags, mag, zm_link);
5939 n_mags++;
5940
5941 for (uint16_t i = 0; i < zc_mag_size(); i++) {
5942 zone_element_t e = mag->zm_elems[i];
5943
5944 if (!zone_meta_mark_used(zone_meta_from_element(e), e)) {
5945 zone_meta_double_free_panic(zone, e, __func__);
5946 }
5947 }
5948 } while (!STAILQ_EMPTY(&zone->z_recirc) &&
5949 zc_recirc_denom * n_mags * zc_mag_size() <= cache->zc_depot_max);
5950
5951 zone_elems_free_sub(zone, n_mags * zc_mag_size());
5952 zone_counter_sub(zone, z_recirc_cur, n_mags);
5953
5954 zone_unlock_nopreempt(zone);
5955
5956 /*
5957 * And then incorporate everything into our per-cpu layer.
5958 */
5959 mag = STAILQ_FIRST(&mags);
5960 STAILQ_REMOVE_HEAD(&mags, zm_link);
5961 mag = zone_magazine_replace(&cache->zc_alloc_cur,
5962 &cache->zc_alloc_elems, mag);
5963 z_debug_assert(cache->zc_alloc_cur == zc_mag_size());
5964 z_debug_assert(mag->zm_cur == 0);
5965
5966 if (--n_mags > 0) {
5967 zone_depot_lock_nopreempt(cache);
5968 cache->zc_depot_cur += n_mags;
5969 STAILQ_CONCAT(&cache->zc_depot, &mags);
5970 zone_depot_unlock_nopreempt(cache);
5971 }
5972
5973 return zalloc_cached_fast(zone, zstats, flags, esize, cache, mag);
5974 }
5975
5976 /*!
5977 * @function zalloc_cached
5978 *
5979 * @brief
5980 * Performs allocations when zone caching is on.
5981 *
5982 * @discussion
5983 * This function calls @c zalloc_cached_fast() when the caches have elements
5984 * ready.
5985 *
5986 * Else it will call @c zalloc_cached_slow() so that the cache is refilled,
5987 * which might switch to the @c zalloc_item_slow() track when the backing zone
5988 * needs to be refilled.
5989 */
5990 static void *
zalloc_cached(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize)5991 zalloc_cached(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags,
5992 vm_size_t esize)
5993 {
5994 zone_cache_t cache;
5995
5996 cache = zpercpu_get(zone->z_pcpu_cache);
5997
5998 if (cache->zc_alloc_cur == 0) {
5999 if (__improbable(cache->zc_free_cur == 0)) {
6000 return zalloc_cached_slow(zone, zstats, flags, esize, cache);
6001 }
6002 zone_cache_swap_magazines(cache);
6003 }
6004
6005 return zalloc_cached_fast(zone, zstats, flags, esize, cache, NULL);
6006 }
6007
6008 /*!
6009 * @function zalloc_ext
6010 *
6011 * @brief
6012 * The core implementation of @c zalloc(), @c zalloc_flags(), @c zalloc_percpu().
6013 */
6014 void *
zalloc_ext(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags,vm_size_t esize)6015 zalloc_ext(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags, vm_size_t esize)
6016 {
6017 /*
6018 * KASan uses zalloc() for fakestack, which can be called anywhere.
6019 * However, we make sure these calls can never block.
6020 */
6021 assertf(startup_phase < STARTUP_SUB_EARLY_BOOT ||
6022 #if KASAN_ZALLOC
6023 zone->kasan_fakestacks ||
6024 #endif /* KASAN_ZALLOC */
6025 ml_get_interrupts_enabled() ||
6026 ml_is_quiescing() ||
6027 debug_mode_active(),
6028 "Calling {k,z}alloc from interrupt disabled context isn't allowed");
6029
6030 /*
6031 * Make sure Z_NOFAIL was not obviously misused
6032 */
6033 if (flags & Z_NOFAIL) {
6034 assert(!zone->exhaustible &&
6035 (flags & (Z_NOWAIT | Z_NOPAGEWAIT)) == 0);
6036 }
6037
6038 #if CONFIG_GZALLOC
6039 if (__improbable(zone->gzalloc_tracked)) {
6040 return zalloc_gz(zone, zstats, flags, esize);
6041 }
6042 #endif /* CONFIG_GZALLOC */
6043
6044 disable_preemption();
6045
6046 #if ZALLOC_ENABLE_ZERO_CHECK
6047 if (zalloc_skip_zero_check()) {
6048 flags |= Z_NOZZC;
6049 }
6050 #endif
6051
6052 if (zone->z_pcpu_cache) {
6053 return zalloc_cached(zone, zstats, flags, esize);
6054 }
6055
6056 return zalloc_item(zone, zstats, flags, esize);
6057 }
6058
6059 void *
zalloc(union zone_or_view zov)6060 zalloc(union zone_or_view zov)
6061 {
6062 return zalloc_flags(zov, Z_WAITOK);
6063 }
6064
6065 void *
zalloc_noblock(union zone_or_view zov)6066 zalloc_noblock(union zone_or_view zov)
6067 {
6068 return zalloc_flags(zov, Z_NOWAIT);
6069 }
6070
6071 void *
zalloc_flags(union zone_or_view zov,zalloc_flags_t flags)6072 zalloc_flags(union zone_or_view zov, zalloc_flags_t flags)
6073 {
6074 zone_t zone = zov.zov_view->zv_zone;
6075 zone_stats_t zstats = zov.zov_view->zv_stats;
6076 vm_size_t esize = zone_elem_size(zone);
6077
6078 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
6079 assert(!zone->z_percpu);
6080 return zalloc_ext(zone, zstats, flags, esize);
6081 }
6082
6083 void *
zalloc_ro(zone_id_t zid,zalloc_flags_t flags)6084 zalloc_ro(zone_id_t zid, zalloc_flags_t flags)
6085 {
6086 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
6087 zone_t zone = &zone_array[zid];
6088 zone_stats_t zstats = zone->z_stats;
6089 vm_size_t esize = zone_ro_elem_size[zid];
6090 void *elem;
6091
6092 assert(!zone->z_percpu);
6093 elem = zalloc_ext(zone, zstats, flags, esize);
6094 #if ZSECURITY_CONFIG(READ_ONLY)
6095 assert(zone_security_array[zid].z_submap_idx == Z_SUBMAP_IDX_READ_ONLY);
6096 zone_require_ro(zid, esize, elem);
6097 #endif
6098 return elem;
6099 }
6100
6101 #if ZSECURITY_CONFIG(READ_ONLY)
6102
6103 __attribute__((always_inline))
6104 static bool
from_current_stack(const vm_offset_t addr,vm_size_t size)6105 from_current_stack(const vm_offset_t addr, vm_size_t size)
6106 {
6107 vm_offset_t start = (vm_offset_t)__builtin_frame_address(0);
6108 vm_offset_t end = (start + kernel_stack_size - 1) & -kernel_stack_size;
6109 return (addr >= start) && (addr + size < end);
6110 }
6111
6112 __abortlike
6113 static void
zalloc_ro_mut_validation_panic(zone_id_t zid,void * elem,const vm_offset_t src,vm_size_t src_size)6114 zalloc_ro_mut_validation_panic(zone_id_t zid, void *elem,
6115 const vm_offset_t src, vm_size_t src_size)
6116 {
6117 if (from_zone_map(src, src_size, ZONE_ADDR_READONLY)) {
6118 zone_t src_zone = &zone_array[zone_index_from_ptr((void *)src)];
6119 zone_t dst_zone = &zone_array[zid];
6120 panic("zalloc_ro_mut failed: source (%p) not from same zone as dst (%p)"
6121 " (expected: %s, actual: %s", (void *)src, elem, src_zone->z_name,
6122 dst_zone->z_name);
6123 }
6124 vm_offset_t start = (vm_offset_t)__builtin_frame_address(0);
6125 vm_offset_t end = (start + kernel_stack_size - 1) & -kernel_stack_size;
6126 panic("zalloc_ro_mut failed: source (%p) neither from RO zone map nor from"
6127 " current stack (%p - %p)\n", (void *)src, (void *)start, (void *)end);
6128 }
6129
6130 __attribute__((always_inline))
6131 static void
zalloc_ro_mut_validate_src(zone_id_t zid,void * elem,const vm_offset_t src,vm_size_t src_size)6132 zalloc_ro_mut_validate_src(zone_id_t zid, void *elem,
6133 const vm_offset_t src, vm_size_t src_size)
6134 {
6135 if (from_current_stack(src, src_size)) {
6136 return;
6137 }
6138 if (from_zone_map(src, src_size, ZONE_ADDR_READONLY) &&
6139 zid == zone_index_from_ptr((void *)src)) {
6140 return;
6141 }
6142 zalloc_ro_mut_validation_panic(zid, elem, src, src_size);
6143 }
6144
6145 #endif /* ZSECURITY_CONFIG(READ_ONLY) */
6146
6147 __attribute__((noinline))
6148 void
zalloc_ro_mut(zone_id_t zid,void * elem,vm_offset_t offset,const void * new_data,vm_size_t new_data_size)6149 zalloc_ro_mut(zone_id_t zid, void *elem, vm_offset_t offset,
6150 const void *new_data, vm_size_t new_data_size)
6151 {
6152 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
6153
6154 #if ZSECURITY_CONFIG(READ_ONLY)
6155 zalloc_ro_mut_validate_src(zid, elem, (vm_offset_t)new_data,
6156 new_data_size);
6157 pmap_ro_zone_memcpy(zid, (vm_offset_t) elem, offset,
6158 (vm_offset_t) new_data, new_data_size);
6159 #else
6160 (void)zid;
6161 memcpy((void *)((uintptr_t)elem + offset), new_data, new_data_size);
6162 #endif
6163 }
6164
6165 void
zalloc_ro_clear(zone_id_t zid,void * elem,vm_offset_t offset,vm_size_t size)6166 zalloc_ro_clear(zone_id_t zid, void *elem, vm_offset_t offset, vm_size_t size)
6167 {
6168 assert(zid >= ZONE_ID__FIRST_RO && zid <= ZONE_ID__LAST_RO);
6169 #if ZSECURITY_CONFIG(READ_ONLY)
6170 pmap_ro_zone_bzero(zid, (vm_offset_t)elem, offset, size);
6171 #else
6172 (void)zid;
6173 bzero((void *)((uintptr_t)elem + offset), size);
6174 #endif
6175 }
6176
6177 /*
6178 * This function will run in the PPL and needs to be robust
6179 * against an attacker with arbitrary kernel write.
6180 */
6181
6182 #if ZSECURITY_CONFIG(READ_ONLY)
6183
6184 __abortlike
6185 static void
zone_id_require_ro_panic(zone_id_t zid,vm_size_t esize,void * addr)6186 zone_id_require_ro_panic(zone_id_t zid, vm_size_t esize, void *addr)
6187 {
6188 vm_offset_t va = (vm_offset_t)addr;
6189 uint32_t zindex;
6190 zone_t other;
6191 zone_t zone = &zone_array[zid];
6192
6193 if (!from_zone_map(addr, 1, ZONE_ADDR_READONLY)) {
6194 panic("zone_require_ro failed: address not in a ro zone (addr: %p)", addr);
6195 }
6196
6197 if ((va ^ (va + esize - 1)) >> PAGE_SHIFT) {
6198 panic("zone_require_ro failed: address crosses a page (addr: %p)", addr);
6199 }
6200
6201 zindex = zone_index_from_ptr(addr);
6202 other = &zone_array[zindex];
6203 if (zindex >= os_atomic_load(&num_zones, relaxed) || !other->z_self) {
6204 panic("zone_require_ro failed: invalid zone index %d "
6205 "(addr: %p, expected: %s%s)", zindex,
6206 addr, zone_heap_name(zone), zone->z_name);
6207 } else {
6208 panic("zone_require_ro failed: address in unexpected zone id %d (%s%s) "
6209 "(addr: %p, expected: %s%s)",
6210 zindex, zone_heap_name(other), other->z_name,
6211 addr, zone_heap_name(zone), zone->z_name);
6212 }
6213 }
6214
6215 #endif /* ZSECURITY_CONFIG(READ_ONLY) */
6216
6217 __attribute__((always_inline))
6218 void
zone_require_ro(zone_id_t zid,vm_size_t esize,void * addr)6219 zone_require_ro(zone_id_t zid, vm_size_t esize, void *addr)
6220 {
6221 #if ZSECURITY_CONFIG(READ_ONLY)
6222 vm_offset_t va = (vm_offset_t)addr;
6223 struct zone_page_metadata *meta = zone_meta_from_addr(va);
6224
6225 /*
6226 * Check that:
6227 * - the first byte of the element is in the map
6228 * - the element doesn't cross a page (implies it is wholy in the map)
6229 * - the zone ID matches
6230 *
6231 * The code is weirdly written to minimize instruction count.
6232 */
6233 if (!from_zone_map(addr, 1, ZONE_ADDR_READONLY) ||
6234 (va ^ (va + esize - 1)) >> PAGE_SHIFT ||
6235 zid != meta->zm_index) {
6236 zone_id_require_ro_panic(zid, esize, addr);
6237 }
6238 #else
6239 #pragma unused(zid, esize, addr)
6240 #endif
6241 }
6242
6243 void
zone_require_ro_range_contains(zone_id_t zid,void * addr)6244 zone_require_ro_range_contains(zone_id_t zid, void *addr)
6245 {
6246 vm_size_t esize = zone_ro_elem_size[zid];
6247 vm_offset_t va = (vm_offset_t)addr;
6248
6249 /* this is called by the pmap and we know for those the RO submap is on */
6250 assert(zone_security_array[zid].z_submap_idx == Z_SUBMAP_IDX_READ_ONLY);
6251
6252 if (!from_zone_map(addr, esize, ZONE_ADDR_READONLY)) {
6253 zone_t zone = &zone_array[zid];
6254 zone_invalid_element_addr_panic(zone, va);
6255 }
6256 }
6257
6258 void *
zalloc_percpu(union zone_or_view zov,zalloc_flags_t flags)6259 zalloc_percpu(union zone_or_view zov, zalloc_flags_t flags)
6260 {
6261 zone_t zone = zov.zov_view->zv_zone;
6262 zone_stats_t zstats = zov.zov_view->zv_stats;
6263 vm_size_t esize = zone_elem_size(zone);
6264
6265 assert(zone > &zone_array[ZONE_ID__LAST_RO]);
6266 assert(zone->z_percpu);
6267 flags |= Z_PCPU;
6268 return (void *)__zpcpu_mangle(zalloc_ext(zone, zstats, flags, esize));
6269 }
6270
6271 static void *
_zalloc_permanent(zone_t zone,vm_size_t size,vm_offset_t mask)6272 _zalloc_permanent(zone_t zone, vm_size_t size, vm_offset_t mask)
6273 {
6274 struct zone_page_metadata *page_meta;
6275 vm_offset_t offs, addr;
6276 zone_pva_t pva;
6277
6278 assert(ml_get_interrupts_enabled() ||
6279 ml_is_quiescing() ||
6280 debug_mode_active() ||
6281 startup_phase < STARTUP_SUB_EARLY_BOOT);
6282
6283 size = (size + mask) & ~mask;
6284 assert(size <= PAGE_SIZE);
6285
6286 zone_lock(zone);
6287 assert(zone->z_self == zone);
6288
6289 for (;;) {
6290 pva = zone->z_pageq_partial;
6291 while (!zone_pva_is_null(pva)) {
6292 page_meta = zone_pva_to_meta(pva);
6293 if (page_meta->zm_bump + size <= PAGE_SIZE) {
6294 goto found;
6295 }
6296 pva = page_meta->zm_page_next;
6297 }
6298
6299 zone_expand_locked(zone, Z_WAITOK, NULL);
6300 }
6301
6302 found:
6303 offs = (uint16_t)((page_meta->zm_bump + mask) & ~mask);
6304 page_meta->zm_bump = (uint16_t)(offs + size);
6305 page_meta->zm_alloc_size += size;
6306 zone->z_elems_free -= size;
6307 zpercpu_get(zone->z_stats)->zs_mem_allocated += size;
6308
6309 if (page_meta->zm_alloc_size >= PAGE_SIZE - sizeof(vm_offset_t)) {
6310 zone_meta_requeue(zone, &zone->z_pageq_full, page_meta);
6311 }
6312
6313 zone_unlock(zone);
6314
6315 addr = offs + zone_pva_to_addr(pva);
6316
6317 DTRACE_VM2(zalloc, zone_t, zone, void*, addr);
6318 return (void *)addr;
6319 }
6320
6321 static void *
_zalloc_permanent_large(size_t size,vm_offset_t mask)6322 _zalloc_permanent_large(size_t size, vm_offset_t mask)
6323 {
6324 kern_return_t kr;
6325 vm_offset_t addr;
6326
6327 kr = kernel_memory_allocate(kernel_map, &addr, size, mask,
6328 KMA_KOBJECT | KMA_PERMANENT | KMA_ZERO,
6329 VM_KERN_MEMORY_KALLOC);
6330 if (kr != 0) {
6331 panic("%s: unable to allocate %zd bytes (%d)",
6332 __func__, (size_t)size, kr);
6333 }
6334 return (void *)addr;
6335 }
6336
6337 void *
zalloc_permanent(vm_size_t size,vm_offset_t mask)6338 zalloc_permanent(vm_size_t size, vm_offset_t mask)
6339 {
6340 if (size <= PAGE_SIZE) {
6341 zone_t zone = &zone_array[ZONE_ID_PERMANENT];
6342 return _zalloc_permanent(zone, size, mask);
6343 }
6344 return _zalloc_permanent_large(size, mask);
6345 }
6346
6347 void *
zalloc_percpu_permanent(vm_size_t size,vm_offset_t mask)6348 zalloc_percpu_permanent(vm_size_t size, vm_offset_t mask)
6349 {
6350 zone_t zone = &zone_array[ZONE_ID_PERCPU_PERMANENT];
6351 return (void *)__zpcpu_mangle(_zalloc_permanent(zone, size, mask));
6352 }
6353
6354 /*! @} */
6355 #endif /* !ZALLOC_TEST */
6356 #pragma mark zone GC / trimming
6357 #if !ZALLOC_TEST
6358
6359 static thread_call_data_t zone_defrag_callout;
6360
6361 static void
zone_reclaim_chunk(zone_t z,struct zone_page_metadata * meta,uint32_t free_count,struct zone_depot * mags)6362 zone_reclaim_chunk(zone_t z, struct zone_page_metadata *meta,
6363 uint32_t free_count, struct zone_depot *mags)
6364 {
6365 vm_address_t page_addr;
6366 vm_size_t size_to_free;
6367 uint32_t bitmap_ref;
6368 uint32_t page_count;
6369 zone_security_flags_t zsflags = zone_security_config(z);
6370 bool sequester = zsflags.z_va_sequester && !z->z_destroyed;
6371
6372 if (zone_submap_is_sequestered(zsflags)) {
6373 /*
6374 * If the entire map is sequestered, we can't return the VA.
6375 * It stays pinned to the zone forever.
6376 */
6377 sequester = true;
6378 }
6379
6380 zone_meta_queue_pop_native(z, &z->z_pageq_empty, &page_addr);
6381
6382 page_count = meta->zm_chunk_len;
6383
6384 if (meta->zm_alloc_size) {
6385 zone_metadata_corruption(z, meta, "alloc_size");
6386 }
6387 if (z->z_percpu) {
6388 if (page_count != 1) {
6389 zone_metadata_corruption(z, meta, "page_count");
6390 }
6391 size_to_free = ptoa(z->z_chunk_pages);
6392 os_atomic_sub(&zones_phys_page_mapped_count,
6393 z->z_chunk_pages, relaxed);
6394 } else {
6395 if (page_count > z->z_chunk_pages) {
6396 zone_metadata_corruption(z, meta, "page_count");
6397 }
6398 if (page_count < z->z_chunk_pages) {
6399 /* Dequeue non populated VA from z_pageq_va */
6400 zone_meta_remqueue(z, meta + page_count);
6401 }
6402 size_to_free = ptoa(page_count);
6403 os_atomic_sub(&zones_phys_page_mapped_count, page_count, relaxed);
6404 }
6405
6406 zone_counter_sub(z, z_elems_free, free_count);
6407 zone_counter_sub(z, z_elems_avail, free_count);
6408 zone_counter_sub(z, z_wired_empty, page_count);
6409 zone_counter_sub(z, z_wired_cur, page_count);
6410 if (z->z_elems_free_min < free_count) {
6411 z->z_elems_free_min = 0;
6412 } else {
6413 z->z_elems_free_min -= free_count;
6414 }
6415 if (z->z_elems_free_max < free_count) {
6416 z->z_elems_free_max = 0;
6417 } else {
6418 z->z_elems_free_max -= free_count;
6419 }
6420
6421 bitmap_ref = 0;
6422 if (sequester) {
6423 if (meta->zm_inline_bitmap) {
6424 for (int i = 0; i < meta->zm_chunk_len; i++) {
6425 meta[i].zm_bitmap = 0;
6426 }
6427 } else {
6428 bitmap_ref = meta->zm_bitmap;
6429 meta->zm_bitmap = 0;
6430 }
6431 meta->zm_chunk_len = 0;
6432 } else {
6433 if (!meta->zm_inline_bitmap) {
6434 bitmap_ref = meta->zm_bitmap;
6435 }
6436 zone_counter_sub(z, z_va_cur, z->z_percpu ? 1 : z->z_chunk_pages);
6437 bzero(meta, sizeof(*meta) * z->z_chunk_pages);
6438 }
6439
6440 zone_unlock(z);
6441
6442 if (bitmap_ref) {
6443 zone_bits_free(bitmap_ref);
6444 }
6445
6446 /* Free the pages for metadata and account for them */
6447 #if KASAN_ZALLOC
6448 kasan_poison_range(page_addr, size_to_free, ASAN_VALID);
6449 #endif
6450 #if VM_TAG_SIZECLASSES
6451 if (z->z_uses_tags) {
6452 ztMemoryRemove(z, page_addr, size_to_free);
6453 }
6454 #endif /* VM_TAG_SIZECLASSES */
6455
6456 if (sequester) {
6457 kernel_memory_depopulate(zone_submap(zsflags), page_addr,
6458 size_to_free, KMA_KOBJECT, VM_KERN_MEMORY_ZONE);
6459 } else {
6460 assert(zsflags.z_submap_idx != Z_SUBMAP_IDX_VM);
6461 kmem_free(zone_submap(zsflags), page_addr, ptoa(z->z_chunk_pages));
6462 }
6463
6464 zone_magazine_free_list(mags);
6465 thread_yield_to_preemption();
6466
6467 zone_lock(z);
6468
6469 if (sequester) {
6470 zone_meta_queue_push(z, &z->z_pageq_va, meta);
6471 }
6472 }
6473
6474 static uint16_t
zone_reclaim_elements(zone_t z,uint16_t * count,zone_element_t * elems)6475 zone_reclaim_elements(zone_t z, uint16_t *count, zone_element_t *elems)
6476 {
6477 uint16_t n = *count;
6478
6479 z_debug_assert(n <= zc_mag_size());
6480
6481 for (uint16_t i = 0; i < n; i++) {
6482 zone_element_t ze = elems[i];
6483 elems[i].ze_value = 0;
6484 zfree_drop(z, zone_element_validate(z, ze), ze, false);
6485 }
6486
6487 *count = 0;
6488 return n;
6489 }
6490
6491 static uint16_t
zone_reclaim_recirc_magazine(zone_t z,struct zone_depot * mags)6492 zone_reclaim_recirc_magazine(zone_t z, struct zone_depot *mags)
6493 {
6494 zone_magazine_t mag = STAILQ_FIRST(&z->z_recirc);
6495
6496 STAILQ_REMOVE_HEAD(&z->z_recirc, zm_link);
6497 STAILQ_INSERT_TAIL(mags, mag, zm_link);
6498 zone_counter_sub(z, z_recirc_cur, 1);
6499
6500 z_debug_assert(mag->zm_cur == zc_mag_size());
6501
6502 for (uint16_t i = 0; i < zc_mag_size(); i++) {
6503 zone_element_t ze = mag->zm_elems[i];
6504 mag->zm_elems[i].ze_value = 0;
6505 zfree_drop(z, zone_element_validate(z, ze), ze, true);
6506 }
6507
6508 mag->zm_cur = 0;
6509
6510 return zc_mag_size();
6511 }
6512
6513 static void
zone_depot_trim(zone_cache_t zc,struct zone_depot * head)6514 zone_depot_trim(zone_cache_t zc, struct zone_depot *head)
6515 {
6516 zone_magazine_t mag;
6517
6518 if (zc->zc_depot_cur == 0 ||
6519 2 * (zc->zc_depot_cur + 1) * zc_mag_size() <= zc->zc_depot_max) {
6520 return;
6521 }
6522
6523 zone_depot_lock(zc);
6524
6525 while (zc->zc_depot_cur &&
6526 2 * (zc->zc_depot_cur + 1) * zc_mag_size() > zc->zc_depot_max) {
6527 mag = STAILQ_FIRST(&zc->zc_depot);
6528 STAILQ_REMOVE_HEAD(&zc->zc_depot, zm_link);
6529 STAILQ_INSERT_TAIL(head, mag, zm_link);
6530 zc->zc_depot_cur--;
6531 }
6532
6533 zone_depot_unlock(zc);
6534 }
6535
6536 __enum_decl(zone_reclaim_mode_t, uint32_t, {
6537 ZONE_RECLAIM_TRIM,
6538 ZONE_RECLAIM_DRAIN,
6539 ZONE_RECLAIM_DESTROY,
6540 });
6541
6542 /*!
6543 * @function zone_reclaim
6544 *
6545 * @brief
6546 * Drains or trim the zone.
6547 *
6548 * @discussion
6549 * Draining the zone will free it from all its elements.
6550 *
6551 * Trimming the zone tries to respect the working set size, and avoids draining
6552 * the depot when it's not necessary.
6553 *
6554 * @param z The zone to reclaim from
6555 * @param mode The purpose of this reclaim.
6556 */
6557 static void
zone_reclaim(zone_t z,zone_reclaim_mode_t mode)6558 zone_reclaim(zone_t z, zone_reclaim_mode_t mode)
6559 {
6560 struct zone_depot mags = STAILQ_HEAD_INITIALIZER(mags);
6561 zone_magazine_t mag;
6562 zone_security_flags_t zsflags = zone_security_config(z);
6563
6564 zone_lock(z);
6565
6566 if (mode == ZONE_RECLAIM_DESTROY) {
6567 if (!z->z_destructible || z->z_pcpu_cache ||
6568 z->z_elems_rsv || zsflags.z_allows_foreign) {
6569 panic("zdestroy: Zone %s%s isn't destructible",
6570 zone_heap_name(z), z->z_name);
6571 }
6572
6573 if (!z->z_self || z->z_expander || z->z_expander_vm_priv ||
6574 z->z_async_refilling || z->z_expanding_wait) {
6575 panic("zdestroy: Zone %s%s in an invalid state for destruction",
6576 zone_heap_name(z), z->z_name);
6577 }
6578
6579 #if !KASAN_ZALLOC
6580 /*
6581 * Unset the valid bit. We'll hit an assert failure on further
6582 * operations on this zone, until zinit() is called again.
6583 *
6584 * Leave the zone valid for KASan as we will see zfree's on
6585 * quarantined free elements even after the zone is destroyed.
6586 */
6587 z->z_self = NULL;
6588 #endif
6589 z->z_destroyed = true;
6590 } else if (z->z_destroyed) {
6591 return zone_unlock(z);
6592 } else if (z->z_elems_free <= z->z_elems_rsv) {
6593 /* If the zone is under its reserve level, leave it alone. */
6594 return zone_unlock(z);
6595 }
6596
6597 if (z->z_pcpu_cache) {
6598 if (mode != ZONE_RECLAIM_TRIM) {
6599 zpercpu_foreach(zc, z->z_pcpu_cache) {
6600 zc->zc_depot_max /= 2;
6601 }
6602 } else {
6603 zpercpu_foreach(zc, z->z_pcpu_cache) {
6604 if (zc->zc_depot_max > 0) {
6605 zc->zc_depot_max--;
6606 }
6607 }
6608 }
6609
6610 zone_unlock(z);
6611
6612 if (mode == ZONE_RECLAIM_TRIM) {
6613 zpercpu_foreach(zc, z->z_pcpu_cache) {
6614 zone_depot_trim(zc, &mags);
6615 }
6616 } else {
6617 zpercpu_foreach(zc, z->z_pcpu_cache) {
6618 zone_depot_lock(zc);
6619 STAILQ_CONCAT(&mags, &zc->zc_depot);
6620 zc->zc_depot_cur = 0;
6621 zone_depot_unlock(zc);
6622 }
6623 }
6624
6625 zone_lock(z);
6626
6627 uint32_t freed = 0;
6628
6629 STAILQ_FOREACH(mag, &mags, zm_link) {
6630 freed += zone_reclaim_elements(z,
6631 &mag->zm_cur, mag->zm_elems);
6632
6633 if (freed >= zc_free_batch_size) {
6634 z->z_elems_free_min += freed;
6635 z->z_elems_free_max += freed;
6636 z->z_elems_free += freed;
6637 zone_unlock(z);
6638 thread_yield_to_preemption();
6639 zone_lock(z);
6640 freed = 0;
6641 }
6642 }
6643
6644 if (mode == ZONE_RECLAIM_DESTROY) {
6645 zpercpu_foreach(zc, z->z_pcpu_cache) {
6646 freed += zone_reclaim_elements(z,
6647 &zc->zc_alloc_cur, zc->zc_alloc_elems);
6648 freed += zone_reclaim_elements(z,
6649 &zc->zc_free_cur, zc->zc_free_elems);
6650 }
6651
6652 z->z_elems_free_wss = 0;
6653 z->z_elems_free_min = 0;
6654 z->z_elems_free_max = 0;
6655 z->z_contention_cur = 0;
6656 z->z_contention_wma = 0;
6657 } else {
6658 z->z_elems_free_min += freed;
6659 z->z_elems_free_max += freed;
6660 }
6661 z->z_elems_free += freed;
6662 }
6663
6664 for (;;) {
6665 struct zone_page_metadata *meta;
6666 uint32_t count, goal, freed = 0;
6667
6668 goal = z->z_elems_rsv;
6669 if (mode == ZONE_RECLAIM_TRIM) {
6670 /*
6671 * When trimming, only free elements in excess
6672 * of the working set estimate.
6673 *
6674 * However if we are in a situation where the working
6675 * set estimate is clearly growing, ignore the estimate
6676 * as the next working set update will grow it and
6677 * we want to avoid churn.
6678 */
6679 goal = MAX(goal, MAX(z->z_elems_free_wss,
6680 z->z_elems_free - z->z_elems_free_min));
6681
6682 /*
6683 * Add some slop to account for "the last partial chunk in flight"
6684 * so that we do not deplete the recirculation depot too harshly.
6685 */
6686 goal += z->z_chunk_elems / 2;
6687 }
6688
6689 if (z->z_elems_free <= goal) {
6690 break;
6691 }
6692
6693 /*
6694 * If we're above target, but we have no free page, then drain
6695 * the recirculation depot until we get a free chunk or exhaust
6696 * the depot.
6697 *
6698 * This is rather abrupt but also somehow will reduce
6699 * fragmentation anyway, and the zone code will import
6700 * over time anyway.
6701 */
6702 while (z->z_recirc_cur && zone_pva_is_null(z->z_pageq_empty)) {
6703 if (freed >= zc_free_batch_size) {
6704 zone_unlock(z);
6705 zone_magazine_free_list(&mags);
6706 thread_yield_to_preemption();
6707 zone_lock(z);
6708 freed = 0;
6709 /* we dropped the lock, needs to reassess */
6710 continue;
6711 }
6712 freed += zone_reclaim_recirc_magazine(z, &mags);
6713 }
6714
6715 if (zone_pva_is_null(z->z_pageq_empty)) {
6716 break;
6717 }
6718
6719 meta = zone_pva_to_meta(z->z_pageq_empty);
6720 count = (uint32_t)ptoa(meta->zm_chunk_len) / zone_elem_size(z);
6721
6722 if (z->z_elems_free - count < goal) {
6723 break;
6724 }
6725
6726 zone_reclaim_chunk(z, meta, count, &mags);
6727 }
6728
6729 zone_unlock(z);
6730
6731 zone_magazine_free_list(&mags);
6732 }
6733
6734 static void
zone_reclaim_all(zone_reclaim_mode_t mode)6735 zone_reclaim_all(zone_reclaim_mode_t mode)
6736 {
6737 /*
6738 * Start with zones with VA sequester since depopulating
6739 * pages will not need to allocate vm map entries for holes,
6740 * which will give memory back to the system faster.
6741 */
6742 zone_index_foreach(zid) {
6743 zone_t z = &zone_array[zid];
6744 if (z == zc_magazine_zone) {
6745 continue;
6746 }
6747 if (zone_security_array[zid].z_va_sequester && z->collectable) {
6748 zone_reclaim(z, mode);
6749 }
6750 }
6751
6752 zone_index_foreach(zid) {
6753 zone_t z = &zone_array[zid];
6754 if (z == zc_magazine_zone) {
6755 continue;
6756 }
6757 if (!zone_security_array[zid].z_va_sequester && z->collectable) {
6758 zone_reclaim(z, mode);
6759 }
6760 }
6761
6762 zone_reclaim(zc_magazine_zone, mode);
6763 }
6764
6765 void
zone_userspace_reboot_checks(void)6766 zone_userspace_reboot_checks(void)
6767 {
6768 vm_size_t label_zone_size = zone_size_allocated(ipc_service_port_label_zone);
6769 if (label_zone_size != 0) {
6770 panic("Zone %s should be empty upon userspace reboot. Actual size: %lu.",
6771 ipc_service_port_label_zone->z_name, (unsigned long)label_zone_size);
6772 }
6773 }
6774
6775 void
zone_gc(zone_gc_level_t level)6776 zone_gc(zone_gc_level_t level)
6777 {
6778 zone_reclaim_mode_t mode;
6779
6780 switch (level) {
6781 case ZONE_GC_TRIM:
6782 mode = ZONE_RECLAIM_TRIM;
6783 break;
6784 case ZONE_GC_DRAIN:
6785 mode = ZONE_RECLAIM_DRAIN;
6786 break;
6787 case ZONE_GC_JETSAM:
6788 kill_process_in_largest_zone();
6789 mode = ZONE_RECLAIM_TRIM;
6790 break;
6791 }
6792
6793 current_thread()->options |= TH_OPT_ZONE_PRIV;
6794 lck_mtx_lock(&zone_gc_lock);
6795
6796 zone_reclaim_all(mode);
6797
6798 if (level == ZONE_GC_JETSAM && zone_map_nearing_exhaustion()) {
6799 /*
6800 * If we possibly killed a process, but we're still critical,
6801 * we need to drain harder.
6802 */
6803 zone_reclaim_all(ZONE_RECLAIM_DRAIN);
6804 }
6805
6806 lck_mtx_unlock(&zone_gc_lock);
6807 current_thread()->options &= ~TH_OPT_ZONE_PRIV;
6808 }
6809
6810 void
zone_gc_trim(void)6811 zone_gc_trim(void)
6812 {
6813 zone_gc(ZONE_GC_TRIM);
6814 }
6815
6816 void
zone_gc_drain(void)6817 zone_gc_drain(void)
6818 {
6819 zone_gc(ZONE_GC_DRAIN);
6820 }
6821
6822 static bool
zone_defrag_needed(zone_t z)6823 zone_defrag_needed(zone_t z)
6824 {
6825 uint32_t recirc_size = z->z_recirc_cur * zc_mag_size();
6826
6827 if (recirc_size <= z->z_chunk_elems / 2) {
6828 return false;
6829 }
6830 return recirc_size * zc_defrag_ratio > z->z_elems_free_wss * 100;
6831 }
6832
6833 /*!
6834 * @function zone_defrag_async
6835 *
6836 * @brief
6837 * Resize the recirculation depot to match the working set size.
6838 *
6839 * @discussion
6840 * When zones grow very large due to a spike in usage, and then some of those
6841 * elements get freed, the elements in magazines in the recirculation depot
6842 * are in no particular order.
6843 *
6844 * In order to control fragmentation, we need to detect "empty" pages so that
6845 * they get onto the @c z_pageq_empty freelist, so that allocations re-pack
6846 * naturally.
6847 *
6848 * This is done very gently, never in excess of the working set and some slop.
6849 */
6850 static void
zone_defrag_async(__unused thread_call_param_t p0,__unused thread_call_param_t p1)6851 zone_defrag_async(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
6852 {
6853 zone_foreach(z) {
6854 struct zone_depot mags = STAILQ_HEAD_INITIALIZER(mags);
6855 zone_magazine_t mag, tmp;
6856 uint32_t freed = 0, goal = 0;
6857
6858 if (!z->collectable || !zone_defrag_needed(z)) {
6859 continue;
6860 }
6861
6862 zone_lock(z);
6863
6864 goal = z->z_elems_free_wss + z->z_chunk_elems / 2 +
6865 zc_mag_size() - 1;
6866
6867 while (z->z_recirc_cur * zc_mag_size() > goal) {
6868 if (freed >= zc_free_batch_size) {
6869 zone_unlock(z);
6870 thread_yield_to_preemption();
6871 zone_lock(z);
6872 freed = 0;
6873 /* we dropped the lock, needs to reassess */
6874 continue;
6875 }
6876 freed += zone_reclaim_recirc_magazine(z, &mags);
6877 }
6878
6879 zone_unlock(z);
6880
6881 STAILQ_FOREACH_SAFE(mag, &mags, zm_link, tmp) {
6882 zone_magazine_free(mag);
6883 }
6884 }
6885 }
6886
6887 void
compute_zone_working_set_size(__unused void * param)6888 compute_zone_working_set_size(__unused void *param)
6889 {
6890 uint32_t zc_auto = zc_auto_threshold;
6891 bool kick_defrag = false;
6892
6893 /*
6894 * Keep zone caching disabled until the first proc is made.
6895 */
6896 if (__improbable(zone_caching_disabled < 0)) {
6897 return;
6898 }
6899
6900 zone_caching_disabled = vm_pool_low();
6901
6902 if (os_mul_overflow(zc_auto, Z_CONTENTION_WMA_UNIT, &zc_auto)) {
6903 zc_auto = 0;
6904 }
6905
6906 zone_foreach(z) {
6907 uint32_t wma;
6908 bool needs_caching = false;
6909
6910 if (z->z_self != z) {
6911 continue;
6912 }
6913
6914 zone_lock(z);
6915
6916 wma = z->z_elems_free_max - z->z_elems_free_min;
6917 wma = (3 * wma + z->z_elems_free_wss) / 4;
6918 z->z_elems_free_max = z->z_elems_free_min = z->z_elems_free;
6919 z->z_elems_free_wss = wma;
6920
6921 if (!kick_defrag && zone_defrag_needed(z)) {
6922 kick_defrag = true;
6923 }
6924
6925 /* fixed point decimal of contentions per second */
6926 wma = z->z_contention_cur * Z_CONTENTION_WMA_UNIT /
6927 ZONE_WSS_UPDATE_PERIOD;
6928 z->z_contention_cur = 0;
6929 z->z_contention_wma = (3 * wma + z->z_contention_wma) / 4;
6930
6931 /*
6932 * If the zone seems to be very quiet,
6933 * gently lower its cpu-local depot size.
6934 */
6935 if (z->z_pcpu_cache && wma < Z_CONTENTION_WMA_UNIT / 2 &&
6936 z->z_contention_wma < Z_CONTENTION_WMA_UNIT / 2) {
6937 zpercpu_foreach(zc, z->z_pcpu_cache) {
6938 if (zc->zc_depot_max > zc_mag_size()) {
6939 zc->zc_depot_max--;
6940 }
6941 }
6942 }
6943
6944 /*
6945 * If the zone has been contending like crazy for two periods,
6946 * and is eligible, maybe it's time to enable caching.
6947 */
6948 if (!z->z_nocaching && !z->z_pcpu_cache && !z->exhaustible &&
6949 zc_auto && z->z_contention_wma >= zc_auto && wma >= zc_auto) {
6950 needs_caching = true;
6951 }
6952
6953 zone_unlock(z);
6954
6955 if (needs_caching) {
6956 zone_enable_caching(z);
6957 }
6958 }
6959
6960 if (kick_defrag) {
6961 thread_call_enter(&zone_defrag_callout);
6962 }
6963 }
6964
6965 #endif /* !ZALLOC_TEST */
6966 #pragma mark vm integration, MIG routines
6967 #if !ZALLOC_TEST
6968
6969 extern unsigned int stack_total;
6970 #if defined (__x86_64__)
6971 extern unsigned int inuse_ptepages_count;
6972 #endif
6973
6974 static void
panic_print_types_in_zone(zone_t z,const char * debug_str)6975 panic_print_types_in_zone(zone_t z, const char* debug_str)
6976 {
6977 kalloc_type_view_t kt_cur = NULL;
6978 const char *prev_type = "";
6979 size_t skip_over_site = sizeof("site.") - 1;
6980 paniclog_append_noflush("kalloc types in zone, %s (%s):\n",
6981 debug_str, z->z_name);
6982 kt_cur = (kalloc_type_view_t) z->z_views;
6983 while (kt_cur) {
6984 struct zone_view kt_zv = kt_cur->kt_zv;
6985 const char *typename = kt_zv.zv_name + skip_over_site;
6986 if (strcmp(typename, prev_type) != 0) {
6987 paniclog_append_noflush("\t%-50s\n", typename);
6988 prev_type = typename;
6989 }
6990 kt_cur = (kalloc_type_view_t) kt_zv.zv_next;
6991 }
6992 paniclog_append_noflush("\n");
6993 }
6994
6995 static void
panic_display_kalloc_types(void)6996 panic_display_kalloc_types(void)
6997 {
6998 if (kalloc_type_src_zone) {
6999 panic_print_types_in_zone(kalloc_type_src_zone, "addr belongs to");
7000 }
7001 if (kalloc_type_dst_zone) {
7002 panic_print_types_in_zone(kalloc_type_dst_zone,
7003 "addr is being freed to");
7004 }
7005 }
7006
7007 static void
zone_find_n_largest(const uint32_t n,zone_t * largest_zones,uint64_t * zone_size)7008 zone_find_n_largest(const uint32_t n, zone_t *largest_zones,
7009 uint64_t *zone_size)
7010 {
7011 zone_foreach(z) {
7012 vm_offset_t size = zone_size_wired(z);
7013 for (uint32_t i = 0; i < n; i++) {
7014 if (size > zone_size[i]) {
7015 largest_zones[i] = z;
7016 zone_size[i] = size;
7017 break;
7018 }
7019 }
7020 }
7021 }
7022
7023 #define NUM_LARGEST_ZONES 5
7024 static void
panic_display_largest_zones(void)7025 panic_display_largest_zones(void)
7026 {
7027 zone_t largest_zones[NUM_LARGEST_ZONES] = { NULL };
7028 uint64_t largest_size[NUM_LARGEST_ZONES] = { 0 };
7029
7030 zone_find_n_largest(NUM_LARGEST_ZONES, (zone_t *) &largest_zones,
7031 (uint64_t *) &largest_size);
7032
7033 paniclog_append_noflush("Largest zones:\n%-28s %10s %10s\n",
7034 "Zone Name", "Cur Size", "Free Size");
7035 for (uint32_t i = 0; i < NUM_LARGEST_ZONES; i++) {
7036 zone_t z = largest_zones[i];
7037 if (&zone_array[ZONE_ID_VM_PAGES] == z) {
7038 continue;
7039 }
7040 paniclog_append_noflush("%-8s%-20s %9luM %9luK\n",
7041 zone_heap_name(z), z->z_name,
7042 (uintptr_t)largest_size[i] >> 20,
7043 (uintptr_t)zone_size_free(z) >> 10);
7044 }
7045 }
7046
7047 static void
panic_display_zprint(void)7048 panic_display_zprint(void)
7049 {
7050 panic_display_largest_zones();
7051 paniclog_append_noflush("%-20s %10lu\n", "Kernel Stacks",
7052 (uintptr_t)(kernel_stack_size * stack_total));
7053 #if defined (__x86_64__)
7054 paniclog_append_noflush("%-20s %10lu\n", "PageTables",
7055 (uintptr_t)ptoa(inuse_ptepages_count));
7056 #endif
7057 paniclog_append_noflush("%-20s %10lu\n", "Kalloc.Large",
7058 (uintptr_t)kalloc_large_total);
7059
7060 if (panic_kext_memory_info) {
7061 mach_memory_info_t *mem_info = panic_kext_memory_info;
7062
7063 paniclog_append_noflush("\n%-5s %10s\n", "Kmod", "Size");
7064 for (uint32_t i = 0; i < panic_kext_memory_size / sizeof(mem_info[0]); i++) {
7065 if ((mem_info[i].flags & VM_KERN_SITE_TYPE) != VM_KERN_SITE_KMOD) {
7066 continue;
7067 }
7068 if (mem_info[i].size > (1024 * 1024)) {
7069 paniclog_append_noflush("%-5lld %10lld\n",
7070 mem_info[i].site, mem_info[i].size);
7071 }
7072 }
7073 }
7074 }
7075
7076 static void
panic_display_zone_info(void)7077 panic_display_zone_info(void)
7078 {
7079 paniclog_append_noflush("Zone info:\n");
7080 for (uint32_t i = 0; i < ZONE_ADDR_KIND_COUNT; i++) {
7081 paniclog_append_noflush("%-10s: %p - %p\n",
7082 zone_map_range_names[i],
7083 (void *) zone_info.zi_map_range[i].min_address,
7084 (void *) zone_info.zi_map_range[i].max_address);
7085 }
7086 paniclog_append_noflush("Metadata : %p - %p\n",
7087 (void *) zone_info.zi_meta_range.min_address,
7088 (void *) zone_info.zi_meta_range.max_address);
7089 paniclog_append_noflush("Bitmaps : %p - %p\n",
7090 (void *) zone_info.zi_bits_range.min_address,
7091 (void *) zone_info.zi_bits_range.max_address);
7092 }
7093
7094 void
panic_display_zalloc(void)7095 panic_display_zalloc(void)
7096 {
7097 bool keepsyms = false;
7098
7099 PE_parse_boot_argn("keepsyms", &keepsyms, sizeof(keepsyms));
7100
7101 panic_display_zone_info();
7102 if (panic_include_zprint) {
7103 panic_display_zprint();
7104 } else if (zone_map_nearing_threshold(ZONE_MAP_EXHAUSTION_PRINT_PANIC)) {
7105 panic_display_largest_zones();
7106 }
7107 #if CONFIG_ZLEAKS
7108 if (panic_include_ztrace) {
7109 panic_display_ztrace(keepsyms);
7110 }
7111 #endif
7112 if (panic_include_kalloc_types) {
7113 panic_display_kalloc_types();
7114 }
7115 }
7116
7117 /*
7118 * Creates a vm_map_copy_t to return to the caller of mach_* MIG calls
7119 * requesting zone information.
7120 * Frees unused pages towards the end of the region, and zero'es out unused
7121 * space on the last page.
7122 */
7123 static vm_map_copy_t
create_vm_map_copy(vm_offset_t start_addr,vm_size_t total_size,vm_size_t used_size)7124 create_vm_map_copy(
7125 vm_offset_t start_addr,
7126 vm_size_t total_size,
7127 vm_size_t used_size)
7128 {
7129 kern_return_t kr;
7130 vm_offset_t end_addr;
7131 vm_size_t free_size;
7132 vm_map_copy_t copy;
7133
7134 if (used_size != total_size) {
7135 end_addr = start_addr + used_size;
7136 free_size = total_size - (round_page(end_addr) - start_addr);
7137
7138 if (free_size >= PAGE_SIZE) {
7139 kmem_free(ipc_kernel_map,
7140 round_page(end_addr), free_size);
7141 }
7142 bzero((char *) end_addr, round_page(end_addr) - end_addr);
7143 }
7144
7145 kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)start_addr,
7146 (vm_map_size_t)used_size, TRUE, ©);
7147 assert(kr == KERN_SUCCESS);
7148
7149 return copy;
7150 }
7151
7152 static boolean_t
get_zone_info(zone_t z,mach_zone_name_t * zn,mach_zone_info_t * zi)7153 get_zone_info(
7154 zone_t z,
7155 mach_zone_name_t *zn,
7156 mach_zone_info_t *zi)
7157 {
7158 struct zone zcopy;
7159 vm_size_t cached = 0;
7160
7161 assert(z != ZONE_NULL);
7162 zone_lock(z);
7163 if (!z->z_self) {
7164 zone_unlock(z);
7165 return FALSE;
7166 }
7167 zcopy = *z;
7168 if (z->z_pcpu_cache) {
7169 zpercpu_foreach(zc, z->z_pcpu_cache) {
7170 cached += zc->zc_alloc_cur + zc->zc_free_cur;
7171 cached += zc->zc_depot_cur * zc_mag_size();
7172 }
7173 }
7174 zone_unlock(z);
7175
7176 if (zn != NULL) {
7177 /*
7178 * Append kalloc heap name to zone name (if zone is used by kalloc)
7179 */
7180 char temp_zone_name[MAX_ZONE_NAME] = "";
7181 snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
7182 zone_heap_name(z), z->z_name);
7183
7184 /* assuming here the name data is static */
7185 (void) __nosan_strlcpy(zn->mzn_name, temp_zone_name,
7186 strlen(temp_zone_name) + 1);
7187 }
7188
7189 if (zi != NULL) {
7190 *zi = (mach_zone_info_t) {
7191 .mzi_count = zone_count_allocated(&zcopy) - cached,
7192 .mzi_cur_size = ptoa_64(zone_scale_for_percpu(&zcopy, zcopy.z_wired_cur)),
7193 // max_size for zprint is now high-watermark of pages used
7194 .mzi_max_size = ptoa_64(zone_scale_for_percpu(&zcopy, zcopy.z_wired_hwm)),
7195 .mzi_elem_size = zone_scale_for_percpu(&zcopy, zcopy.z_elem_size),
7196 .mzi_alloc_size = ptoa_64(zcopy.z_chunk_pages),
7197 .mzi_exhaustible = (uint64_t)zcopy.exhaustible,
7198 };
7199 zpercpu_foreach(zs, zcopy.z_stats) {
7200 zi->mzi_sum_size += zs->zs_mem_allocated;
7201 }
7202 if (zcopy.collectable) {
7203 SET_MZI_COLLECTABLE_BYTES(zi->mzi_collectable,
7204 ptoa_64(zone_scale_for_percpu(&zcopy, zcopy.z_wired_empty)));
7205 SET_MZI_COLLECTABLE_FLAG(zi->mzi_collectable, TRUE);
7206 }
7207 }
7208
7209 return TRUE;
7210 }
7211
7212 kern_return_t
task_zone_info(__unused task_t task,__unused mach_zone_name_array_t * namesp,__unused mach_msg_type_number_t * namesCntp,__unused task_zone_info_array_t * infop,__unused mach_msg_type_number_t * infoCntp)7213 task_zone_info(
7214 __unused task_t task,
7215 __unused mach_zone_name_array_t *namesp,
7216 __unused mach_msg_type_number_t *namesCntp,
7217 __unused task_zone_info_array_t *infop,
7218 __unused mach_msg_type_number_t *infoCntp)
7219 {
7220 return KERN_FAILURE;
7221 }
7222
7223
7224 /* mach_memory_info entitlement */
7225 #define MEMORYINFO_ENTITLEMENT "com.apple.private.memoryinfo"
7226
7227 /* macro needed to rate-limit mach_memory_info */
7228 #define NSEC_DAY (NSEC_PER_SEC * 60 * 60 * 24)
7229
7230 /* declarations necessary to call kauth_cred_issuser() */
7231 struct ucred;
7232 extern int kauth_cred_issuser(struct ucred *);
7233 extern struct ucred *kauth_cred_get(void);
7234
7235 static kern_return_t
mach_memory_info_security_check(void)7236 mach_memory_info_security_check(void)
7237 {
7238 /* If not root or does not have the memoryinfo entitlement, fail */
7239 if (!kauth_cred_issuser(kauth_cred_get())) {
7240 return KERN_NO_ACCESS;
7241 }
7242
7243 #if CONFIG_DEBUGGER_FOR_ZONE_INFO
7244 if (!IOTaskHasEntitlement(current_task(), MEMORYINFO_ENTITLEMENT)) {
7245 return KERN_DENIED;
7246 }
7247
7248 /*
7249 * On release non-mac arm devices, allow mach_memory_info
7250 * to be called twice per day per boot. memorymaintenanced
7251 * calls it once per day, which leaves room for a sysdiagnose.
7252 */
7253 static uint64_t first_call, second_call = 0;
7254 uint64_t now = 0;
7255 absolutetime_to_nanoseconds(ml_get_timebase(), &now);
7256
7257 if (!first_call) {
7258 first_call = now;
7259 } else if (!second_call) {
7260 second_call = now;
7261 } else if (first_call + NSEC_DAY > now) {
7262 return KERN_DENIED;
7263 } else if (first_call + NSEC_DAY < now) {
7264 first_call = now;
7265 second_call = 0;
7266 }
7267 #endif
7268
7269 return KERN_SUCCESS;
7270 }
7271
7272 kern_return_t
mach_zone_info(host_priv_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)7273 mach_zone_info(
7274 host_priv_t host,
7275 mach_zone_name_array_t *namesp,
7276 mach_msg_type_number_t *namesCntp,
7277 mach_zone_info_array_t *infop,
7278 mach_msg_type_number_t *infoCntp)
7279 {
7280 return mach_memory_info(host, namesp, namesCntp, infop, infoCntp, NULL, NULL);
7281 }
7282
7283
7284 kern_return_t
mach_memory_info(host_priv_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)7285 mach_memory_info(
7286 host_priv_t host,
7287 mach_zone_name_array_t *namesp,
7288 mach_msg_type_number_t *namesCntp,
7289 mach_zone_info_array_t *infop,
7290 mach_msg_type_number_t *infoCntp,
7291 mach_memory_info_array_t *memoryInfop,
7292 mach_msg_type_number_t *memoryInfoCntp)
7293 {
7294 mach_zone_name_t *names;
7295 vm_offset_t names_addr;
7296 vm_size_t names_size;
7297
7298 mach_zone_info_t *info;
7299 vm_offset_t info_addr;
7300 vm_size_t info_size;
7301
7302 mach_memory_info_t *memory_info;
7303 vm_offset_t memory_info_addr;
7304 vm_size_t memory_info_size;
7305 vm_size_t memory_info_vmsize;
7306 unsigned int num_info;
7307
7308 unsigned int max_zones, used_zones, i;
7309 mach_zone_name_t *zn;
7310 mach_zone_info_t *zi;
7311 kern_return_t kr;
7312
7313 uint64_t zones_collectable_bytes = 0;
7314
7315 if (host == HOST_NULL) {
7316 return KERN_INVALID_HOST;
7317 }
7318
7319 kr = mach_memory_info_security_check();
7320 if (kr != KERN_SUCCESS) {
7321 return kr;
7322 }
7323
7324 /*
7325 * We assume that zones aren't freed once allocated.
7326 * We won't pick up any zones that are allocated later.
7327 */
7328
7329 max_zones = os_atomic_load(&num_zones, relaxed);
7330
7331 names_size = round_page(max_zones * sizeof *names);
7332 kr = kmem_alloc_pageable(ipc_kernel_map,
7333 &names_addr, names_size, VM_KERN_MEMORY_IPC);
7334 if (kr != KERN_SUCCESS) {
7335 return kr;
7336 }
7337 names = (mach_zone_name_t *) names_addr;
7338
7339 info_size = round_page(max_zones * sizeof *info);
7340 kr = kmem_alloc_pageable(ipc_kernel_map,
7341 &info_addr, info_size, VM_KERN_MEMORY_IPC);
7342 if (kr != KERN_SUCCESS) {
7343 kmem_free(ipc_kernel_map,
7344 names_addr, names_size);
7345 return kr;
7346 }
7347 info = (mach_zone_info_t *) info_addr;
7348
7349 zn = &names[0];
7350 zi = &info[0];
7351
7352 used_zones = max_zones;
7353 for (i = 0; i < max_zones; i++) {
7354 if (!get_zone_info(&(zone_array[i]), zn, zi)) {
7355 used_zones--;
7356 continue;
7357 }
7358 zones_collectable_bytes += GET_MZI_COLLECTABLE_BYTES(zi->mzi_collectable);
7359 zn++;
7360 zi++;
7361 }
7362
7363 *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, used_zones * sizeof *names);
7364 *namesCntp = used_zones;
7365
7366 *infop = (mach_zone_info_t *) create_vm_map_copy(info_addr, info_size, used_zones * sizeof *info);
7367 *infoCntp = used_zones;
7368
7369 num_info = 0;
7370 memory_info_addr = 0;
7371
7372 if (memoryInfop && memoryInfoCntp) {
7373 vm_map_copy_t copy;
7374 num_info = vm_page_diagnose_estimate();
7375 memory_info_size = num_info * sizeof(*memory_info);
7376 memory_info_vmsize = round_page(memory_info_size);
7377 kr = kmem_alloc_pageable(ipc_kernel_map,
7378 &memory_info_addr, memory_info_vmsize, VM_KERN_MEMORY_IPC);
7379 if (kr != KERN_SUCCESS) {
7380 return kr;
7381 }
7382
7383 kr = vm_map_wire_kernel(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize,
7384 VM_PROT_READ | VM_PROT_WRITE, VM_KERN_MEMORY_IPC, FALSE);
7385 assert(kr == KERN_SUCCESS);
7386
7387 memory_info = (mach_memory_info_t *) memory_info_addr;
7388 vm_page_diagnose(memory_info, num_info, zones_collectable_bytes);
7389
7390 kr = vm_map_unwire(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize, FALSE);
7391 assert(kr == KERN_SUCCESS);
7392
7393 kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)memory_info_addr,
7394 (vm_map_size_t)memory_info_size, TRUE, ©);
7395 assert(kr == KERN_SUCCESS);
7396
7397 *memoryInfop = (mach_memory_info_t *) copy;
7398 *memoryInfoCntp = num_info;
7399 }
7400
7401 return KERN_SUCCESS;
7402 }
7403
7404 kern_return_t
mach_zone_info_for_zone(host_priv_t host,mach_zone_name_t name,mach_zone_info_t * infop)7405 mach_zone_info_for_zone(
7406 host_priv_t host,
7407 mach_zone_name_t name,
7408 mach_zone_info_t *infop)
7409 {
7410 zone_t zone_ptr;
7411
7412 if (host == HOST_NULL) {
7413 return KERN_INVALID_HOST;
7414 }
7415
7416 #if CONFIG_DEBUGGER_FOR_ZONE_INFO
7417 if (!PE_i_can_has_debugger(NULL)) {
7418 return KERN_INVALID_HOST;
7419 }
7420 #endif
7421
7422 if (infop == NULL) {
7423 return KERN_INVALID_ARGUMENT;
7424 }
7425
7426 zone_ptr = ZONE_NULL;
7427 zone_foreach(z) {
7428 /*
7429 * Append kalloc heap name to zone name (if zone is used by kalloc)
7430 */
7431 char temp_zone_name[MAX_ZONE_NAME] = "";
7432 snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
7433 zone_heap_name(z), z->z_name);
7434
7435 /* Find the requested zone by name */
7436 if (track_this_zone(temp_zone_name, name.mzn_name)) {
7437 zone_ptr = z;
7438 break;
7439 }
7440 }
7441
7442 /* No zones found with the requested zone name */
7443 if (zone_ptr == ZONE_NULL) {
7444 return KERN_INVALID_ARGUMENT;
7445 }
7446
7447 if (get_zone_info(zone_ptr, NULL, infop)) {
7448 return KERN_SUCCESS;
7449 }
7450 return KERN_FAILURE;
7451 }
7452
7453 kern_return_t
mach_zone_info_for_largest_zone(host_priv_t host,mach_zone_name_t * namep,mach_zone_info_t * infop)7454 mach_zone_info_for_largest_zone(
7455 host_priv_t host,
7456 mach_zone_name_t *namep,
7457 mach_zone_info_t *infop)
7458 {
7459 if (host == HOST_NULL) {
7460 return KERN_INVALID_HOST;
7461 }
7462
7463 #if CONFIG_DEBUGGER_FOR_ZONE_INFO
7464 if (!PE_i_can_has_debugger(NULL)) {
7465 return KERN_INVALID_HOST;
7466 }
7467 #endif
7468
7469 if (namep == NULL || infop == NULL) {
7470 return KERN_INVALID_ARGUMENT;
7471 }
7472
7473 if (get_zone_info(zone_find_largest(NULL), namep, infop)) {
7474 return KERN_SUCCESS;
7475 }
7476 return KERN_FAILURE;
7477 }
7478
7479 uint64_t
get_zones_collectable_bytes(void)7480 get_zones_collectable_bytes(void)
7481 {
7482 uint64_t zones_collectable_bytes = 0;
7483 mach_zone_info_t zi;
7484
7485 zone_foreach(z) {
7486 if (get_zone_info(z, NULL, &zi)) {
7487 zones_collectable_bytes +=
7488 GET_MZI_COLLECTABLE_BYTES(zi.mzi_collectable);
7489 }
7490 }
7491
7492 return zones_collectable_bytes;
7493 }
7494
7495 kern_return_t
mach_zone_get_zlog_zones(host_priv_t host,mach_zone_name_array_t * namesp,mach_msg_type_number_t * namesCntp)7496 mach_zone_get_zlog_zones(
7497 host_priv_t host,
7498 mach_zone_name_array_t *namesp,
7499 mach_msg_type_number_t *namesCntp)
7500 {
7501 #if ZONE_ENABLE_LOGGING
7502 unsigned int max_zones, logged_zones, i;
7503 kern_return_t kr;
7504 zone_t zone_ptr;
7505 mach_zone_name_t *names;
7506 vm_offset_t names_addr;
7507 vm_size_t names_size;
7508
7509 if (host == HOST_NULL) {
7510 return KERN_INVALID_HOST;
7511 }
7512
7513 if (namesp == NULL || namesCntp == NULL) {
7514 return KERN_INVALID_ARGUMENT;
7515 }
7516
7517 max_zones = os_atomic_load(&num_zones, relaxed);
7518
7519 names_size = round_page(max_zones * sizeof *names);
7520 kr = kmem_alloc_pageable(ipc_kernel_map,
7521 &names_addr, names_size, VM_KERN_MEMORY_IPC);
7522 if (kr != KERN_SUCCESS) {
7523 return kr;
7524 }
7525 names = (mach_zone_name_t *) names_addr;
7526
7527 zone_ptr = ZONE_NULL;
7528 logged_zones = 0;
7529 for (i = 0; i < max_zones; i++) {
7530 zone_t z = &(zone_array[i]);
7531 assert(z != ZONE_NULL);
7532
7533 /* Copy out the zone name if zone logging is enabled */
7534 if (z->zlog_btlog) {
7535 get_zone_info(z, &names[logged_zones], NULL);
7536 logged_zones++;
7537 }
7538 }
7539
7540 *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, logged_zones * sizeof *names);
7541 *namesCntp = logged_zones;
7542
7543 return KERN_SUCCESS;
7544
7545 #else /* ZONE_ENABLE_LOGGING */
7546 #pragma unused(host, namesp, namesCntp)
7547 return KERN_FAILURE;
7548 #endif /* ZONE_ENABLE_LOGGING */
7549 }
7550
7551 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 * recsCntp)7552 mach_zone_get_btlog_records(
7553 host_priv_t host,
7554 mach_zone_name_t name,
7555 zone_btrecord_array_t *recsp,
7556 mach_msg_type_number_t *recsCntp)
7557 {
7558 #if DEBUG || DEVELOPMENT
7559 unsigned int numrecs = 0;
7560 zone_btrecord_t *recs;
7561 kern_return_t kr;
7562 zone_t zone_ptr;
7563 vm_offset_t recs_addr;
7564 vm_size_t recs_size;
7565
7566 if (host == HOST_NULL) {
7567 return KERN_INVALID_HOST;
7568 }
7569
7570 if (recsp == NULL || recsCntp == NULL) {
7571 return KERN_INVALID_ARGUMENT;
7572 }
7573
7574 zone_ptr = ZONE_NULL;
7575 zone_foreach(z) {
7576 /*
7577 * Append kalloc heap name to zone name (if zone is used by kalloc)
7578 */
7579 char temp_zone_name[MAX_ZONE_NAME] = "";
7580 snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
7581 zone_heap_name(z), z->z_name);
7582
7583 /* Find the requested zone by name */
7584 if (track_this_zone(temp_zone_name, name.mzn_name)) {
7585 zone_ptr = z;
7586 break;
7587 }
7588 }
7589
7590 /* No zones found with the requested zone name */
7591 if (zone_ptr == ZONE_NULL) {
7592 return KERN_INVALID_ARGUMENT;
7593 }
7594
7595 /* Logging not turned on for the requested zone */
7596 if (!DO_LOGGING(zone_ptr)) {
7597 return KERN_FAILURE;
7598 }
7599
7600 /* Allocate memory for btlog records */
7601 numrecs = (unsigned int)(get_btlog_records_count(zone_ptr->zlog_btlog));
7602 recs_size = round_page(numrecs * sizeof *recs);
7603
7604 kr = kmem_alloc_pageable(ipc_kernel_map, &recs_addr, recs_size, VM_KERN_MEMORY_IPC);
7605 if (kr != KERN_SUCCESS) {
7606 return kr;
7607 }
7608
7609 /*
7610 * We will call get_btlog_records() below which populates this region while holding a spinlock
7611 * (the btlog lock). So these pages need to be wired.
7612 */
7613 kr = vm_map_wire_kernel(ipc_kernel_map, recs_addr, recs_addr + recs_size,
7614 VM_PROT_READ | VM_PROT_WRITE, VM_KERN_MEMORY_IPC, FALSE);
7615 assert(kr == KERN_SUCCESS);
7616
7617 recs = (zone_btrecord_t *)recs_addr;
7618 get_btlog_records(zone_ptr->zlog_btlog, recs, &numrecs);
7619
7620 kr = vm_map_unwire(ipc_kernel_map, recs_addr, recs_addr + recs_size, FALSE);
7621 assert(kr == KERN_SUCCESS);
7622
7623 *recsp = (zone_btrecord_t *) create_vm_map_copy(recs_addr, recs_size, numrecs * sizeof *recs);
7624 *recsCntp = numrecs;
7625
7626 return KERN_SUCCESS;
7627
7628 #else /* DEBUG || DEVELOPMENT */
7629 #pragma unused(host, name, recsp, recsCntp)
7630 return KERN_FAILURE;
7631 #endif /* DEBUG || DEVELOPMENT */
7632 }
7633
7634
7635 #if DEBUG || DEVELOPMENT
7636
7637 kern_return_t
mach_memory_info_check(void)7638 mach_memory_info_check(void)
7639 {
7640 mach_memory_info_t * memory_info;
7641 mach_memory_info_t * info;
7642 unsigned int num_info;
7643 vm_offset_t memory_info_addr;
7644 kern_return_t kr;
7645 size_t memory_info_size, memory_info_vmsize;
7646 uint64_t top_wired, zonestotal, total;
7647
7648 num_info = vm_page_diagnose_estimate();
7649 memory_info_size = num_info * sizeof(*memory_info);
7650 memory_info_vmsize = round_page(memory_info_size);
7651 kr = kmem_alloc(kernel_map, &memory_info_addr, memory_info_vmsize, VM_KERN_MEMORY_DIAG);
7652 assert(kr == KERN_SUCCESS);
7653
7654 memory_info = (mach_memory_info_t *) memory_info_addr;
7655 vm_page_diagnose(memory_info, num_info, 0);
7656
7657 top_wired = total = zonestotal = 0;
7658 zone_foreach(z) {
7659 zonestotal += zone_size_wired(z);
7660 }
7661
7662 for (uint32_t idx = 0; idx < num_info; idx++) {
7663 info = &memory_info[idx];
7664 if (!info->size) {
7665 continue;
7666 }
7667 if (VM_KERN_COUNT_WIRED == info->site) {
7668 top_wired = info->size;
7669 }
7670 if (VM_KERN_SITE_HIDE & info->flags) {
7671 continue;
7672 }
7673 if (!(VM_KERN_SITE_WIRED & info->flags)) {
7674 continue;
7675 }
7676 total += info->size;
7677 }
7678 total += zonestotal;
7679
7680 printf("vm_page_diagnose_check %qd of %qd, zones %qd, short 0x%qx\n",
7681 total, top_wired, zonestotal, top_wired - total);
7682
7683 kmem_free(kernel_map, memory_info_addr, memory_info_vmsize);
7684
7685 return kr;
7686 }
7687
7688 extern boolean_t(*volatile consider_buffer_cache_collect)(int);
7689
7690 #endif /* DEBUG || DEVELOPMENT */
7691
7692 kern_return_t
mach_zone_force_gc(host_t host)7693 mach_zone_force_gc(
7694 host_t host)
7695 {
7696 if (host == HOST_NULL) {
7697 return KERN_INVALID_HOST;
7698 }
7699
7700 #if DEBUG || DEVELOPMENT
7701 /* Callout to buffer cache GC to drop elements in the apfs zones */
7702 if (consider_buffer_cache_collect != NULL) {
7703 (void)(*consider_buffer_cache_collect)(0);
7704 }
7705 zone_gc(ZONE_GC_DRAIN);
7706 #endif /* DEBUG || DEVELOPMENT */
7707 return KERN_SUCCESS;
7708 }
7709
7710 zone_t
zone_find_largest(uint64_t * zone_size)7711 zone_find_largest(uint64_t *zone_size)
7712 {
7713 zone_t largest_zone = 0;
7714 uint64_t largest_zone_size = 0;
7715 zone_find_n_largest(1, &largest_zone, &largest_zone_size);
7716 if (zone_size) {
7717 *zone_size = largest_zone_size;
7718 }
7719 return largest_zone;
7720 }
7721
7722 #endif /* !ZALLOC_TEST */
7723 #pragma mark zone creation, configuration, destruction
7724 #if !ZALLOC_TEST
7725
7726 static zone_t
zone_init_defaults(zone_id_t zid)7727 zone_init_defaults(zone_id_t zid)
7728 {
7729 zone_t z = &zone_array[zid];
7730
7731 z->z_wired_max = ~0u;
7732 z->collectable = true;
7733 z->expandable = true;
7734
7735 lck_spin_init(&z->z_lock, &zone_locks_grp, LCK_ATTR_NULL);
7736 STAILQ_INIT(&z->z_recirc);
7737 return z;
7738 }
7739
7740 static bool
zone_is_initializing(zone_t z)7741 zone_is_initializing(zone_t z)
7742 {
7743 return !z->z_self && !z->z_destroyed;
7744 }
7745
7746 void
zone_set_noexpand(zone_t zone,vm_size_t nelems)7747 zone_set_noexpand(zone_t zone, vm_size_t nelems)
7748 {
7749 if (!zone_is_initializing(zone)) {
7750 panic("%s: called after zone_create()", __func__);
7751 }
7752 zone->expandable = false;
7753 zone->z_wired_max = zone_alloc_pages_for_nelems(zone, nelems);
7754 }
7755
7756 void
zone_set_exhaustible(zone_t zone,vm_size_t nelems)7757 zone_set_exhaustible(zone_t zone, vm_size_t nelems)
7758 {
7759 if (!zone_is_initializing(zone)) {
7760 panic("%s: called after zone_create()", __func__);
7761 }
7762 zone->expandable = false;
7763 zone->exhaustible = true;
7764 zone->z_wired_max = zone_alloc_pages_for_nelems(zone, nelems);
7765 }
7766
7767 /**
7768 * @function zone_create_find
7769 *
7770 * @abstract
7771 * Finds an unused zone for the given name and element size.
7772 *
7773 * @param name the zone name
7774 * @param size the element size (including redzones, ...)
7775 * @param flags the flags passed to @c zone_create*
7776 * @param zid_inout the desired zone ID or ZONE_ID_ANY
7777 *
7778 * @returns a zone to initialize further.
7779 */
7780 static zone_t
zone_create_find(const char * name,vm_size_t size,zone_create_flags_t flags,zone_id_t * zid_inout)7781 zone_create_find(
7782 const char *name,
7783 vm_size_t size,
7784 zone_create_flags_t flags,
7785 zone_id_t *zid_inout)
7786 {
7787 zone_id_t nzones, zid = *zid_inout;
7788 zone_t z;
7789
7790 simple_lock(&all_zones_lock, &zone_locks_grp);
7791
7792 nzones = (zone_id_t)os_atomic_load(&num_zones, relaxed);
7793 assert(num_zones_in_use <= nzones && nzones < MAX_ZONES);
7794
7795 if (__improbable(nzones < ZONE_ID__FIRST_DYNAMIC)) {
7796 /*
7797 * The first time around, make sure the reserved zone IDs
7798 * have an initialized lock as zone_index_foreach() will
7799 * enumerate them.
7800 */
7801 while (nzones < ZONE_ID__FIRST_DYNAMIC) {
7802 zone_init_defaults(nzones++);
7803 }
7804
7805 os_atomic_store(&num_zones, nzones, release);
7806 }
7807
7808 if (zid != ZONE_ID_ANY) {
7809 if (zid >= ZONE_ID__FIRST_DYNAMIC) {
7810 panic("zone_create: invalid desired zone ID %d for %s",
7811 zid, name);
7812 }
7813 if (flags & ZC_DESTRUCTIBLE) {
7814 panic("zone_create: ID %d (%s) must be permanent", zid, name);
7815 }
7816 if (zone_array[zid].z_self) {
7817 panic("zone_create: creating zone ID %d (%s) twice", zid, name);
7818 }
7819 z = &zone_array[zid];
7820 } else {
7821 if (flags & ZC_DESTRUCTIBLE) {
7822 /*
7823 * If possible, find a previously zdestroy'ed zone in the
7824 * zone_array that we can reuse.
7825 */
7826 for (int i = bitmap_first(zone_destroyed_bitmap, MAX_ZONES);
7827 i >= 0; i = bitmap_next(zone_destroyed_bitmap, i)) {
7828 z = &zone_array[i];
7829
7830 /*
7831 * If the zone name and the element size are the
7832 * same, we can just reuse the old zone struct.
7833 */
7834 if (strcmp(z->z_name, name) || zone_elem_size(z) != size) {
7835 continue;
7836 }
7837 bitmap_clear(zone_destroyed_bitmap, i);
7838 z->z_destroyed = false;
7839 z->z_self = z;
7840 zid = (zone_id_t)i;
7841 goto out;
7842 }
7843 }
7844
7845 zid = nzones++;
7846 z = zone_init_defaults(zid);
7847
7848 /*
7849 * The release barrier pairs with the acquire in
7850 * zone_index_foreach() and makes sure that enumeration loops
7851 * always see an initialized zone lock.
7852 */
7853 os_atomic_store(&num_zones, nzones, release);
7854 }
7855
7856 out:
7857 num_zones_in_use++;
7858 simple_unlock(&all_zones_lock);
7859
7860 *zid_inout = zid;
7861 return z;
7862 }
7863
7864 __abortlike
7865 static void
zone_create_panic(const char * name,const char * f1,const char * f2)7866 zone_create_panic(const char *name, const char *f1, const char *f2)
7867 {
7868 panic("zone_create: creating zone %s: flag %s and %s are incompatible",
7869 name, f1, f2);
7870 }
7871 #define zone_create_assert_not_both(name, flags, current_flag, forbidden_flag) \
7872 if ((flags) & forbidden_flag) { \
7873 zone_create_panic(name, #current_flag, #forbidden_flag); \
7874 }
7875
7876 /*
7877 * Adjusts the size of the element based on minimum size, alignment
7878 * and kasan redzones
7879 */
7880 static vm_size_t
zone_elem_adjust_size(const char * name __unused,vm_size_t elem_size,zone_create_flags_t flags __unused,uint32_t * redzone __unused)7881 zone_elem_adjust_size(
7882 const char *name __unused,
7883 vm_size_t elem_size,
7884 zone_create_flags_t flags __unused,
7885 uint32_t *redzone __unused)
7886 {
7887 vm_size_t size;
7888 /*
7889 * Adjust element size for minimum size and pointer alignment
7890 */
7891 size = (elem_size + ZONE_ALIGN_SIZE - 1) & -ZONE_ALIGN_SIZE;
7892 if (size < ZONE_MIN_ELEM_SIZE) {
7893 size = ZONE_MIN_ELEM_SIZE;
7894 }
7895
7896 #if KASAN_ZALLOC
7897 /*
7898 * Expand the zone allocation size to include the redzones.
7899 *
7900 * For page-multiple zones add a full guard page because they
7901 * likely require alignment.
7902 */
7903 uint32_t redzone_tmp;
7904 if (flags & (ZC_KASAN_NOREDZONE | ZC_PERCPU)) {
7905 redzone_tmp = 0;
7906 } else if ((size & PAGE_MASK) == 0) {
7907 if (size != PAGE_SIZE && (flags & ZC_ALIGNMENT_REQUIRED)) {
7908 panic("zone_create: zone %s can't provide more than PAGE_SIZE"
7909 "alignment", name);
7910 }
7911 redzone_tmp = PAGE_SIZE;
7912 } else if (flags & ZC_ALIGNMENT_REQUIRED) {
7913 redzone_tmp = 0;
7914 } else {
7915 redzone_tmp = KASAN_GUARD_SIZE;
7916 }
7917 size += redzone_tmp * 2;
7918 if (redzone) {
7919 *redzone = redzone_tmp;
7920 }
7921 #endif
7922 return size;
7923 }
7924
7925 /*
7926 * Returns the allocation chunk size that has least framentation
7927 */
7928 static vm_size_t
zone_get_min_alloc_granule(vm_size_t elem_size,zone_create_flags_t flags)7929 zone_get_min_alloc_granule(
7930 vm_size_t elem_size,
7931 zone_create_flags_t flags)
7932 {
7933 vm_size_t alloc_granule = PAGE_SIZE;
7934 if (flags & ZC_PERCPU) {
7935 alloc_granule = PAGE_SIZE * zpercpu_count();
7936 if (PAGE_SIZE % elem_size > 256) {
7937 panic("zone_create: per-cpu zone has too much fragmentation");
7938 }
7939 } else if (flags & ZC_READONLY) {
7940 alloc_granule = PAGE_SIZE;
7941 } else if ((elem_size & PAGE_MASK) == 0) {
7942 /* zero fragmentation by definition */
7943 alloc_granule = elem_size;
7944 } else if (alloc_granule % elem_size == 0) {
7945 /* zero fragmentation by definition */
7946 } else {
7947 vm_size_t frag = (alloc_granule % elem_size) * 100 / alloc_granule;
7948 vm_size_t alloc_tmp = PAGE_SIZE;
7949 while ((alloc_tmp += PAGE_SIZE) <= ZONE_MAX_ALLOC_SIZE) {
7950 vm_size_t frag_tmp = (alloc_tmp % elem_size) * 100 / alloc_tmp;
7951 if (frag_tmp < frag) {
7952 frag = frag_tmp;
7953 alloc_granule = alloc_tmp;
7954 }
7955 }
7956 }
7957 return alloc_granule;
7958 }
7959
7960 vm_size_t
zone_get_foreign_alloc_size(const char * name __unused,vm_size_t elem_size,zone_create_flags_t flags,uint16_t min_pages)7961 zone_get_foreign_alloc_size(
7962 const char *name __unused,
7963 vm_size_t elem_size,
7964 zone_create_flags_t flags,
7965 uint16_t min_pages)
7966 {
7967 vm_size_t adjusted_size = zone_elem_adjust_size(name, elem_size, flags,
7968 NULL);
7969 vm_size_t alloc_granule = zone_get_min_alloc_granule(adjusted_size,
7970 flags);
7971 vm_size_t min_size = min_pages * PAGE_SIZE;
7972 /*
7973 * Round up min_size to a multiple of alloc_granule
7974 */
7975 return ((min_size + alloc_granule - 1) / alloc_granule)
7976 * alloc_granule;
7977 }
7978
7979 zone_t
7980 zone_create_ext(
7981 const char *name,
7982 vm_size_t size,
7983 zone_create_flags_t flags,
7984 zone_id_t zid,
7985 void (^extra_setup)(zone_t))
7986 {
7987 vm_size_t alloc;
7988 uint32_t redzone;
7989 zone_t z;
7990 zone_security_flags_t *zsflags;
7991
7992 if (size > ZONE_MAX_ALLOC_SIZE) {
7993 panic("zone_create: element size too large: %zd", (size_t)size);
7994 }
7995
7996 if (size < 2 * sizeof(vm_size_t)) {
7997 /* Elements are too small for kasan. */
7998 flags |= ZC_KASAN_NOQUARANTINE | ZC_KASAN_NOREDZONE;
7999 }
8000
8001 size = zone_elem_adjust_size(name, size, flags, &redzone);
8002 /*
8003 * Allocate the zone slot, return early if we found an older match.
8004 */
8005 z = zone_create_find(name, size, flags, &zid);
8006 if (__improbable(z->z_self)) {
8007 /* We found a zone to reuse */
8008 return z;
8009 }
8010
8011 /*
8012 * Initialize the zone properly.
8013 */
8014
8015 /*
8016 * If the kernel is post lockdown, copy the zone name passed in.
8017 * Else simply maintain a pointer to the name string as it can only
8018 * be a core XNU zone (no unloadable kext exists before lockdown).
8019 */
8020 if (startup_phase >= STARTUP_SUB_LOCKDOWN) {
8021 size_t nsz = MIN(strlen(name) + 1, MACH_ZONE_NAME_MAX_LEN);
8022 char *buf = zalloc_permanent(nsz, ZALIGN_NONE);
8023 strlcpy(buf, name, nsz);
8024 z->z_name = buf;
8025 } else {
8026 z->z_name = name;
8027 }
8028 if (__probable(zone_array[ZONE_ID_PERCPU_PERMANENT].z_self)) {
8029 z->z_stats = zalloc_percpu_permanent_type(struct zone_stats);
8030 } else {
8031 /*
8032 * zone_init() hasn't run yet, use the storage provided by
8033 * zone_stats_startup(), and zone_init() will replace it
8034 * with the final value once the PERCPU zone exists.
8035 */
8036 z->z_stats = __zpcpu_mangle_for_boot(&zone_stats_startup[zone_index(z)]);
8037 }
8038
8039 alloc = zone_get_min_alloc_granule(size, flags);
8040
8041 #if 0
8042 /*
8043 * Turning off redistriution of slack space for now. Will adjust this
8044 * when we tune the kalloc buckets.
8045 */
8046 if (flags & (ZC_KALLOC_HEAP | ZC_KALLOC_TYPE)) {
8047 size_t rem = (alloc % size) / (alloc / size);
8048
8049 /*
8050 * Try to grow the elements size and spread them more if the remaining
8051 * space is large enough.
8052 */
8053 size += rem & ~(KALLOC_MINALIGN - 1);
8054 }
8055 #endif
8056
8057 z->z_elem_size = (uint16_t)size;
8058 z->z_chunk_pages = (uint16_t)atop(alloc);
8059 if (flags & ZC_PERCPU) {
8060 z->z_chunk_elems = (uint16_t)(PAGE_SIZE / z->z_elem_size);
8061 } else {
8062 z->z_chunk_elems = (uint16_t)(alloc / z->z_elem_size);
8063 }
8064 if (zone_element_idx(zone_element_encode(0,
8065 z->z_chunk_elems - 1)) != z->z_chunk_elems - 1) {
8066 panic("zone_element_encode doesn't work for zone [%s]", name);
8067 }
8068
8069 #if KASAN_ZALLOC
8070 z->z_kasan_redzone = redzone;
8071 if (strncmp(name, "fakestack.", sizeof("fakestack.") - 1) == 0) {
8072 z->kasan_fakestacks = true;
8073 }
8074 #endif
8075
8076 /*
8077 * Handle KPI flags
8078 */
8079 zsflags = &zone_security_array[zid];
8080 /*
8081 * Some zones like ipc ports and procs rely on sequestering for
8082 * correctness, so explicitly turn on sequestering despite the
8083 * configuration in zsecurity_options.
8084 */
8085 if (flags & ZC_SEQUESTER) {
8086 zsflags->z_va_sequester = true;
8087 }
8088
8089 /* ZC_CACHING applied after all configuration is done */
8090 if (flags & ZC_NOCACHING) {
8091 z->z_nocaching = true;
8092 }
8093
8094 if (flags & ZC_READONLY) {
8095 zone_create_assert_not_both(name, flags, ZC_READONLY, ZC_VM);
8096 #if ZSECURITY_CONFIG(READ_ONLY)
8097 zsflags->z_submap_idx = Z_SUBMAP_IDX_READ_ONLY;
8098 zsflags->z_va_sequester = true;
8099 #endif
8100 zone_ro_elem_size[zid] = (uint16_t)size;
8101 assert(size <= PAGE_SIZE);
8102 if ((PAGE_SIZE % size) * 10 >= PAGE_SIZE) {
8103 panic("Fragmentation greater than 10%% with elem size %d zone %s%s",
8104 (uint32_t)size, zone_heap_name(z), z->z_name);
8105 }
8106 }
8107
8108 if (flags & ZC_PERCPU) {
8109 zone_create_assert_not_both(name, flags, ZC_PERCPU, ZC_ALLOW_FOREIGN);
8110 zone_create_assert_not_both(name, flags, ZC_PERCPU, ZC_READONLY);
8111 z->z_percpu = true;
8112 z->gzalloc_exempt = true;
8113 }
8114 if (flags & ZC_NOGC) {
8115 z->collectable = false;
8116 }
8117 /*
8118 * Handle ZC_NOENCRYPT from xnu only
8119 */
8120 if (startup_phase < STARTUP_SUB_LOCKDOWN && flags & ZC_NOENCRYPT) {
8121 zsflags->z_noencrypt = true;
8122 }
8123 if (flags & ZC_ALIGNMENT_REQUIRED) {
8124 z->alignment_required = true;
8125 }
8126 if (flags & (ZC_NOGZALLOC | ZC_READONLY)) {
8127 z->gzalloc_exempt = true;
8128 }
8129 if (flags & ZC_NOCALLOUT) {
8130 z->no_callout = true;
8131 }
8132 if (flags & ZC_DESTRUCTIBLE) {
8133 zone_create_assert_not_both(name, flags, ZC_DESTRUCTIBLE, ZC_ALLOW_FOREIGN);
8134 zone_create_assert_not_both(name, flags, ZC_DESTRUCTIBLE, ZC_READONLY);
8135 z->z_destructible = true;
8136 }
8137 if (!(flags & ZC_NOTBITAG)) {
8138 z->z_tbi_tag = true;
8139 }
8140
8141 /*
8142 * Handle Internal flags
8143 */
8144 if (flags & ZC_KALLOC_TYPE) {
8145 zsflags->z_kalloc_type = true;
8146 }
8147 if (flags & ZC_ALLOW_FOREIGN) {
8148 zsflags->z_allows_foreign = true;
8149 }
8150 if (flags & ZC_VM) {
8151 zsflags->z_submap_idx = Z_SUBMAP_IDX_VM;
8152 zsflags->z_va_sequester = true;
8153 }
8154 if (flags & ZC_KASAN_NOQUARANTINE) {
8155 z->kasan_noquarantine = true;
8156 }
8157 /* ZC_KASAN_NOREDZONE already handled */
8158
8159 /*
8160 * Then if there's extra tuning, do it
8161 */
8162 if (extra_setup) {
8163 extra_setup(z);
8164 }
8165
8166 /*
8167 * Configure debugging features
8168 */
8169 #if CONFIG_GZALLOC
8170 if ((flags & ZC_VM) == 0) {
8171 gzalloc_zone_init(z); /* might set z->gzalloc_tracked */
8172 if (z->gzalloc_tracked) {
8173 z->z_nocaching = true;
8174 }
8175 }
8176 #endif
8177 #if ZONE_ENABLE_LOGGING
8178 if (!z->gzalloc_tracked && num_zones_logged < MAX_ZONES_LOGGED) {
8179 /*
8180 * Check for and set up zone leak detection if requested via boot-args.
8181 * might set z->zone_logging
8182 */
8183 zone_setup_logging(z);
8184 }
8185 #endif /* ZONE_ENABLE_LOGGING */
8186
8187 #if VM_TAG_SIZECLASSES
8188 if (!z->gzalloc_tracked && (zsflags->z_kheap_id || zsflags->z_kalloc_type)
8189 && zone_tagging_on) {
8190 assert(startup_phase < STARTUP_SUB_LOCKDOWN);
8191 static uint16_t sizeclass_idx;
8192 z->z_uses_tags = true;
8193 z->z_tags_inline = (((page_size + size - 1) / size) <=
8194 (sizeof(uint32_t) / sizeof(uint16_t)));
8195 if (zsflags->z_kheap_id == KHEAP_ID_DEFAULT) {
8196 zone_tags_sizeclasses[sizeclass_idx] = (uint16_t)size;
8197 z->z_tags_sizeclass = sizeclass_idx++;
8198 } else {
8199 uint16_t i = 0;
8200 for (; i < sizeclass_idx; i++) {
8201 if (size == zone_tags_sizeclasses[i]) {
8202 z->z_tags_sizeclass = i;
8203 break;
8204 }
8205 }
8206 /*
8207 * Size class wasn't found, add it to zone_tags_sizeclasses
8208 */
8209 if (i == sizeclass_idx) {
8210 assert(i < VM_TAG_SIZECLASSES);
8211 zone_tags_sizeclasses[i] = (uint16_t)size;
8212 z->z_tags_sizeclass = sizeclass_idx++;
8213 }
8214 }
8215 assert(z->z_tags_sizeclass < VM_TAG_SIZECLASSES);
8216 }
8217 #endif
8218
8219 /*
8220 * Finally, fixup properties based on security policies, boot-args, ...
8221 */
8222 #if ZSECURITY_CONFIG(SUBMAP_USER_DATA)
8223 if (zsflags->z_kheap_id == KHEAP_ID_DATA_BUFFERS) {
8224 zsflags->z_submap_idx = Z_SUBMAP_IDX_DATA;
8225 zsflags->z_va_sequester = false;
8226 }
8227 #endif
8228
8229 if ((flags & ZC_CACHING) && !z->z_nocaching) {
8230 /*
8231 * If zcache hasn't been initialized yet, remember our decision,
8232 *
8233 * zone_enable_caching() will be called again by
8234 * zcache_bootstrap(), while the system is still single
8235 * threaded, to build the missing caches.
8236 */
8237 if (__probable(zc_magazine_zone)) {
8238 zone_enable_caching(z);
8239 } else {
8240 z->z_pcpu_cache =
8241 __zpcpu_mangle_for_boot(&zone_cache_startup[zid]);
8242 }
8243 }
8244
8245 zone_lock(z);
8246 z->z_self = z;
8247 zone_unlock(z);
8248
8249 return z;
8250 }
8251
8252 __startup_func
8253 void
zone_create_startup(struct zone_create_startup_spec * spec)8254 zone_create_startup(struct zone_create_startup_spec *spec)
8255 {
8256 *spec->z_var = zone_create_ext(spec->z_name, spec->z_size,
8257 spec->z_flags, spec->z_zid, spec->z_setup);
8258 }
8259
8260 /*
8261 * The 4 first field of a zone_view and a zone alias, so that the zone_or_view_t
8262 * union works. trust but verify.
8263 */
8264 #define zalloc_check_zov_alias(f1, f2) \
8265 static_assert(offsetof(struct zone, f1) == offsetof(struct zone_view, f2))
8266 zalloc_check_zov_alias(z_self, zv_zone);
8267 zalloc_check_zov_alias(z_stats, zv_stats);
8268 zalloc_check_zov_alias(z_name, zv_name);
8269 zalloc_check_zov_alias(z_views, zv_next);
8270 #undef zalloc_check_zov_alias
8271
8272 __startup_func
8273 void
zone_view_startup_init(struct zone_view_startup_spec * spec)8274 zone_view_startup_init(struct zone_view_startup_spec *spec)
8275 {
8276 struct kalloc_heap *heap = NULL;
8277 zone_view_t zv = spec->zv_view;
8278 zone_t z;
8279 zone_security_flags_t zsflags;
8280
8281 switch (spec->zv_heapid) {
8282 case KHEAP_ID_DEFAULT:
8283 panic("%s: Use KALLOC_TYPE_DEFINE for zone view %s instead"
8284 "of ZONE_VIEW_DEFINE as it is from default kalloc heap",
8285 __func__, zv->zv_name);
8286 __builtin_unreachable();
8287 case KHEAP_ID_DATA_BUFFERS:
8288 heap = KHEAP_DATA_BUFFERS;
8289 break;
8290 case KHEAP_ID_KEXT:
8291 heap = KHEAP_KEXT;
8292 break;
8293 default:
8294 heap = NULL;
8295 }
8296
8297 if (heap) {
8298 z = kalloc_heap_zone_for_size(heap, spec->zv_size);
8299 } else {
8300 z = *spec->zv_zone;
8301 assert(spec->zv_size <= zone_elem_size(z));
8302 }
8303
8304 assert(z);
8305
8306 zv->zv_zone = z;
8307 zv->zv_stats = zalloc_percpu_permanent_type(struct zone_stats);
8308 zv->zv_next = z->z_views;
8309 zsflags = zone_security_config(z);
8310 if (z->z_views == NULL && zsflags.z_kheap_id == KHEAP_ID_NONE) {
8311 /*
8312 * count the raw view for zones not in a heap,
8313 * kalloc_heap_init() already counts it for its members.
8314 */
8315 zone_view_count += 2;
8316 } else {
8317 zone_view_count += 1;
8318 }
8319 z->z_views = zv;
8320 }
8321
8322 zone_t
zone_create(const char * name,vm_size_t size,zone_create_flags_t flags)8323 zone_create(
8324 const char *name,
8325 vm_size_t size,
8326 zone_create_flags_t flags)
8327 {
8328 return zone_create_ext(name, size, flags, ZONE_ID_ANY, NULL);
8329 }
8330
8331 zone_t
zinit(vm_size_t size,vm_size_t max,vm_size_t alloc __unused,const char * name)8332 zinit(
8333 vm_size_t size, /* the size of an element */
8334 vm_size_t max, /* maximum memory to use */
8335 vm_size_t alloc __unused, /* allocation size */
8336 const char *name) /* a name for the zone */
8337 {
8338 zone_t z = zone_create(name, size, ZC_DESTRUCTIBLE);
8339 z->z_wired_max = zone_alloc_pages_for_nelems(z, max / size);
8340 return z;
8341 }
8342
8343 void
zdestroy(zone_t z)8344 zdestroy(zone_t z)
8345 {
8346 unsigned int zindex = zone_index(z);
8347 zone_security_flags_t zsflags = zone_security_array[zindex];
8348
8349 current_thread()->options |= TH_OPT_ZONE_PRIV;
8350 lck_mtx_lock(&zone_gc_lock);
8351
8352 zone_reclaim(z, ZONE_RECLAIM_DESTROY);
8353
8354 lck_mtx_unlock(&zone_gc_lock);
8355 current_thread()->options &= ~TH_OPT_ZONE_PRIV;
8356
8357 #if CONFIG_GZALLOC
8358 if (__improbable(z->gzalloc_tracked)) {
8359 /* If the zone is gzalloc managed dump all the elements in the free cache */
8360 gzalloc_empty_free_cache(z);
8361 }
8362 #endif
8363
8364 zone_lock(z);
8365
8366 if (!zone_submap_is_sequestered(zsflags)) {
8367 while (!zone_pva_is_null(z->z_pageq_va)) {
8368 struct zone_page_metadata *meta;
8369 vm_offset_t free_addr;
8370
8371 zone_counter_sub(z, z_va_cur, z->z_percpu ? 1 : z->z_chunk_pages);
8372 meta = zone_meta_queue_pop_native(z, &z->z_pageq_va, &free_addr);
8373 assert(meta->zm_chunk_len <= ZM_CHUNK_LEN_MAX);
8374 bzero(meta, sizeof(*meta) * z->z_chunk_pages);
8375 zone_unlock(z);
8376 kmem_free(zone_submap(zsflags), free_addr, ptoa(z->z_chunk_pages));
8377 zone_lock(z);
8378 }
8379 }
8380
8381 #if !KASAN_ZALLOC
8382 /* Assert that all counts are zero */
8383 if (z->z_elems_avail || z->z_elems_free || zone_size_wired(z) ||
8384 (z->z_va_cur && !zone_submap_is_sequestered(zsflags))) {
8385 panic("zdestroy: Zone %s%s isn't empty at zdestroy() time",
8386 zone_heap_name(z), z->z_name);
8387 }
8388
8389 /* consistency check: make sure everything is indeed empty */
8390 assert(zone_pva_is_null(z->z_pageq_empty));
8391 assert(zone_pva_is_null(z->z_pageq_partial));
8392 assert(zone_pva_is_null(z->z_pageq_full));
8393 if (!zone_submap_is_sequestered(zsflags)) {
8394 assert(zone_pva_is_null(z->z_pageq_va));
8395 }
8396 #endif
8397
8398 zone_unlock(z);
8399
8400 simple_lock(&all_zones_lock, &zone_locks_grp);
8401
8402 assert(!bitmap_test(zone_destroyed_bitmap, zindex));
8403 /* Mark the zone as empty in the bitmap */
8404 bitmap_set(zone_destroyed_bitmap, zindex);
8405 num_zones_in_use--;
8406 assert(num_zones_in_use > 0);
8407
8408 simple_unlock(&all_zones_lock);
8409 }
8410
8411 #endif /* !ZALLOC_TEST */
8412 #pragma mark zalloc module init
8413 #if !ZALLOC_TEST
8414
8415 /*
8416 * Initialize the "zone of zones" which uses fixed memory allocated
8417 * earlier in memory initialization. zone_bootstrap is called
8418 * before zone_init.
8419 */
8420 __startup_func
8421 void
zone_bootstrap(void)8422 zone_bootstrap(void)
8423 {
8424 /* Validate struct zone_packed_virtual_address expectations */
8425 static_assert((intptr_t)VM_MIN_KERNEL_ADDRESS < 0, "the top bit must be 1");
8426 if (VM_KERNEL_POINTER_SIGNIFICANT_BITS - PAGE_SHIFT > 31) {
8427 panic("zone_pva_t can't pack a kernel page address in 31 bits");
8428 }
8429
8430 zpercpu_early_count = ml_early_cpu_max_number() + 1;
8431 /*
8432 * Initialize random used to scramble early allocations
8433 */
8434 zpercpu_foreach_cpu(cpu) {
8435 random_bool_init(&zone_bool_gen[cpu].zbg_bg);
8436 }
8437 /*
8438 * the KASAN quarantine for kalloc doesn't understand heaps
8439 * and trips the heap confusion panics. At the end of the day,
8440 * all these security measures are double duty with KASAN.
8441 *
8442 * On 32bit kernels, these protections are just too expensive.
8443 */
8444 #if !defined(__LP64__) || KASAN_ZALLOC
8445 zsecurity_options &= ~ZSECURITY_OPTIONS_KERNEL_DATA_MAP;
8446 #endif
8447
8448 #if ZSECURITY_CONFIG(SAD_FENG_SHUI)
8449 /*
8450 * Randomly assign zones to one of the 4 general submaps,
8451 * and pick whether they allocate from the begining
8452 * or the end of it.
8453 *
8454 * A lot of OOB exploitation relies on precise interleaving
8455 * of specific types in the heap.
8456 *
8457 * Woops, you can't guarantee that anymore.
8458 */
8459 for (zone_id_t i = 1; i < MAX_ZONES; i++) {
8460 uint32_t r = zalloc_random_uniform(0,
8461 ZSECURITY_CONFIG_GENERAL_SUBMAPS * 2);
8462
8463 zone_security_array[i].z_submap_from_end = (r & 1);
8464 zone_security_array[i].z_submap_idx += (r >> 1);
8465 }
8466 #endif /* ZSECURITY_CONFIG(SAD_FENG_SHUI) */
8467
8468 thread_call_setup_with_options(&zone_expand_callout,
8469 zone_expand_async, NULL, THREAD_CALL_PRIORITY_HIGH,
8470 THREAD_CALL_OPTIONS_ONCE);
8471
8472 thread_call_setup_with_options(&zone_defrag_callout,
8473 zone_defrag_async, NULL, THREAD_CALL_PRIORITY_USER,
8474 THREAD_CALL_OPTIONS_ONCE);
8475 }
8476
8477 #if __LP64__
8478 #if ARM_LARGE_MEMORY || __x86_64__
8479 #define ZONE_MAP_VIRTUAL_SIZE_LP64 (128ULL * 1024ULL * 1024 * 1024)
8480 #else
8481 #define ZONE_MAP_VIRTUAL_SIZE_LP64 (24ULL * 1024ULL * 1024 * 1024)
8482 #endif
8483 #endif /* __LP64__ */
8484
8485 #define ZONE_GUARD_SIZE (64UL << 10)
8486
8487 #if __LP64__
8488 static inline vm_offset_t
zone_restricted_va_max(void)8489 zone_restricted_va_max(void)
8490 {
8491 vm_offset_t compressor_max = VM_PACKING_MAX_PACKABLE(C_SLOT_PACKED_PTR);
8492 vm_offset_t vm_page_max = VM_PACKING_MAX_PACKABLE(VM_PAGE_PACKED_PTR);
8493
8494 return trunc_page(MIN(compressor_max, vm_page_max));
8495 }
8496 #endif
8497
8498 __startup_func
8499 static void
zone_tunables_fixup(void)8500 zone_tunables_fixup(void)
8501 {
8502 int wdt = 0;
8503
8504 if (zone_map_jetsam_limit == 0 || zone_map_jetsam_limit > 100) {
8505 zone_map_jetsam_limit = ZONE_MAP_JETSAM_LIMIT_DEFAULT;
8506 }
8507 if (zc_magazine_size > PAGE_SIZE / ZONE_MIN_ELEM_SIZE) {
8508 zc_magazine_size = (uint16_t)(PAGE_SIZE / ZONE_MIN_ELEM_SIZE);
8509 }
8510 if (PE_parse_boot_argn("wdt", &wdt, sizeof(wdt)) && wdt == -1 &&
8511 !PE_parse_boot_argn("zet", NULL, 0)) {
8512 zone_exhausted_timeout = -1;
8513 }
8514 }
8515 STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, zone_tunables_fixup);
8516
8517 __startup_func
8518 static vm_size_t
zone_phys_size_max(void)8519 zone_phys_size_max(void)
8520 {
8521 vm_size_t zsize;
8522 vm_size_t zsizearg;
8523
8524 if (PE_parse_boot_argn("zsize", &zsizearg, sizeof(zsizearg))) {
8525 zsize = zsizearg * (1024ULL * 1024);
8526 } else {
8527 /* Set target zone size as 1/4 of physical memory */
8528 zsize = (vm_size_t)(sane_size >> 2);
8529 #if defined(__LP64__)
8530 zsize += zsize >> 1;
8531 #endif /* __LP64__ */
8532 }
8533
8534 if (zsize < CONFIG_ZONE_MAP_MIN) {
8535 zsize = CONFIG_ZONE_MAP_MIN; /* Clamp to min */
8536 }
8537 if (zsize > sane_size >> 1) {
8538 zsize = (vm_size_t)(sane_size >> 1); /* Clamp to half of RAM max */
8539 }
8540 if (zsizearg == 0 && zsize > ZONE_MAP_MAX) {
8541 /* if zsize boot-arg not present and zsize exceeds platform maximum, clip zsize */
8542 printf("NOTE: zonemap size reduced from 0x%lx to 0x%lx\n",
8543 (uintptr_t)zsize, (uintptr_t)ZONE_MAP_MAX);
8544 zsize = ZONE_MAP_MAX;
8545 }
8546
8547 return (vm_size_t)trunc_page(zsize);
8548 }
8549
8550 __options_decl(zone_init_allocate_flags_t, unsigned, {
8551 ZIA_NONE = 0x00000000,
8552 ZIA_REPLACE = 0x00000001, /* replace a previous non permanent range */
8553 ZIA_RANDOM = 0x00000002, /* place at a random address */
8554 ZIA_PERMANENT = 0x00000004, /* permanent allocation */
8555 ZIA_GUARD = 0x00000008, /* will be used as a guard */
8556 });
8557
8558 __startup_func
8559 static struct zone_map_range
zone_init_allocate_va(vm_map_address_t addr,vm_size_t size,zone_init_allocate_flags_t flags)8560 zone_init_allocate_va(vm_map_address_t addr, vm_size_t size,
8561 zone_init_allocate_flags_t flags)
8562 {
8563 vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
8564 int vm_alloc_flags = 0;
8565 struct zone_map_range r;
8566 kern_return_t kr;
8567
8568 if (flags & ZIA_REPLACE) {
8569 vm_alloc_flags |= VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE;
8570 } else {
8571 vm_alloc_flags |= VM_FLAGS_ANYWHERE;
8572 }
8573 if (flags & ZIA_RANDOM) {
8574 vm_alloc_flags |= VM_FLAGS_RANDOM_ADDR;
8575 }
8576 if (flags & ZIA_PERMANENT) {
8577 vmk_flags.vmkf_permanent = true;
8578 }
8579
8580 vm_object_reference(kernel_object);
8581
8582 kr = vm_map_enter(kernel_map, &addr, size, 0,
8583 vm_alloc_flags, vmk_flags, VM_KERN_MEMORY_ZONE,
8584 kernel_object, addr, FALSE,
8585 (flags & ZIA_GUARD) ? VM_PROT_NONE : VM_PROT_DEFAULT,
8586 (flags & ZIA_GUARD) ? VM_PROT_NONE : VM_PROT_DEFAULT,
8587 VM_INHERIT_NONE);
8588
8589 if (KERN_SUCCESS != kr) {
8590 panic("vm_map_enter(0x%zx) failed: %d", (size_t)size, kr);
8591 }
8592
8593 r.min_address = (vm_offset_t)addr;
8594 r.max_address = (vm_offset_t)addr + size;
8595 return r;
8596 }
8597
8598 __startup_func
8599 static void
zone_submap_init(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,vm_size_t guard_size)8600 zone_submap_init(
8601 vm_offset_t *submap_min,
8602 zone_submap_idx_t idx,
8603 uint64_t zone_sub_map_numer,
8604 uint64_t *remaining_denom,
8605 vm_offset_t *remaining_size,
8606 vm_size_t guard_size)
8607 {
8608 vm_offset_t submap_start, submap_end;
8609 vm_size_t submap_size;
8610 vm_map_t submap;
8611 kern_return_t kr;
8612
8613 submap_size = trunc_page(zone_sub_map_numer * *remaining_size /
8614 *remaining_denom);
8615 submap_start = *submap_min;
8616 submap_end = submap_start + submap_size;
8617
8618 #if defined(__LP64__)
8619 if (idx == Z_SUBMAP_IDX_VM) {
8620 vm_offset_t restricted_va_max = zone_restricted_va_max();
8621 if (submap_end > restricted_va_max) {
8622 #if DEBUG || DEVELOPMENT
8623 printf("zone_init: submap[%d] clipped to %zdM of %zdM\n", idx,
8624 (size_t)(restricted_va_max - submap_start) >> 20,
8625 (size_t)submap_size >> 20);
8626 #endif /* DEBUG || DEVELOPMENT */
8627 guard_size += submap_end - restricted_va_max;
8628 *remaining_size -= submap_end - restricted_va_max;
8629 submap_end = restricted_va_max;
8630 submap_size = restricted_va_max - submap_start;
8631 }
8632
8633 vm_packing_verify_range("vm_compressor",
8634 submap_start, submap_end, VM_PACKING_PARAMS(C_SLOT_PACKED_PTR));
8635 vm_packing_verify_range("vm_page",
8636 submap_start, submap_end, VM_PACKING_PARAMS(VM_PAGE_PACKED_PTR));
8637 }
8638 #endif /* defined(__LP64__) */
8639
8640 vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
8641 vmk_flags.vmkf_permanent = TRUE;
8642 kr = kmem_suballoc(kernel_map, submap_min, submap_size,
8643 FALSE, VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, vmk_flags,
8644 VM_KERN_MEMORY_ZONE, &submap);
8645 if (kr != KERN_SUCCESS) {
8646 panic("kmem_suballoc(kernel_map[%d] %p:%p) failed: %d",
8647 idx, (void *)submap_start, (void *)submap_end, kr);
8648 }
8649
8650 if (idx == Z_SUBMAP_IDX_READ_ONLY) {
8651 zone_info.zi_map_range[ZONE_ADDR_READONLY].min_address = submap_start;
8652 zone_info.zi_map_range[ZONE_ADDR_READONLY].max_address = submap_end;
8653 }
8654 zone_alloc_range[idx].zpr_min = zone_pva_from_addr(submap_start);
8655 zone_alloc_range[idx].zpr_max = zone_pva_from_addr(submap_end);
8656
8657 if (zone_submap_is_sequestered(idx)) {
8658 vm_prot_t prot = VM_PROT_DEFAULT;
8659 vm_map_address_t addr;
8660
8661 if (idx == Z_SUBMAP_IDX_READ_ONLY) {
8662 prot = VM_PROT_NONE;
8663 }
8664
8665 addr = submap_start;
8666 kr = vm_map_enter(submap, &addr, PAGE_SIZE, 0,
8667 VM_FLAGS_FIXED | VM_FLAGS_PERMANENT,
8668 VM_MAP_KERNEL_FLAGS_NONE, VM_KERN_MEMORY_ZONE,
8669 kernel_object, addr, FALSE, prot, prot, VM_INHERIT_NONE);
8670 if (kr != KERN_SUCCESS) {
8671 panic("kmem_suballoc(kernel_map[%d]: "
8672 "failed to make first entry (%d)", idx, kr);
8673 }
8674
8675 addr = submap_end - PAGE_SIZE;
8676 kr = vm_map_enter(submap, &addr, PAGE_SIZE, 0,
8677 VM_FLAGS_FIXED | VM_FLAGS_PERMANENT,
8678 VM_MAP_KERNEL_FLAGS_NONE, VM_KERN_MEMORY_ZONE,
8679 kernel_object, addr, FALSE, prot, prot, VM_INHERIT_NONE);
8680 if (kr != KERN_SUCCESS) {
8681 panic("kmem_suballoc(kernel_map[%d]: "
8682 "failed to make last entry (%d)", idx, kr);
8683 }
8684 }
8685
8686 #if DEBUG || DEVELOPMENT
8687 printf("zone_init: submap[%d] %p:%p (%zuM)\n",
8688 idx, (void *)submap_start, (void *)submap_end,
8689 (size_t)submap_size >> 20);
8690 #endif /* DEBUG || DEVELOPMENT */
8691
8692 zone_init_allocate_va(submap_end, guard_size,
8693 ZIA_PERMANENT | ZIA_GUARD | ZIA_REPLACE);
8694
8695 zone_submaps[idx] = submap;
8696 *submap_min = submap_end + guard_size;
8697 *remaining_size -= submap_size;
8698 *remaining_denom -= zone_sub_map_numer;
8699 }
8700
8701 /*
8702 * Allocate metadata array and migrate foreign initial metadata.
8703 *
8704 * So that foreign pages and native pages have the same scheme,
8705 * we allocate VA space that covers both foreign and native pages.
8706 */
8707 __startup_func
8708 static void
zone_metadata_init(void)8709 zone_metadata_init(void)
8710 {
8711 struct zone_map_range r0 = zone_info.zi_map_range[0];
8712 struct zone_map_range r1 = zone_info.zi_map_range[1];
8713 struct zone_map_range mr, br;
8714 vm_size_t meta_size, bits_size, foreign_base;
8715 vm_offset_t hstart, hend;
8716
8717 if (r0.min_address > r1.min_address) {
8718 r0 = zone_info.zi_map_range[1];
8719 r1 = zone_info.zi_map_range[0];
8720 }
8721
8722 meta_size = round_page(atop(r1.max_address - r0.min_address) *
8723 sizeof(struct zone_page_metadata)) + ZONE_GUARD_SIZE * 2;
8724
8725 /*
8726 * Allocations can't be smaller than 8 bytes, which is 128b / 16B per 1k
8727 * of physical memory (16M per 1G).
8728 *
8729 * Let's preallocate for the worst to avoid weird panics.
8730 */
8731 bits_size = round_page(16 * (ptoa(zone_phys_mapped_max_pages) >> 10));
8732
8733 /*
8734 * Compute the size of the "hole" in the middle of the range.
8735 *
8736 * If it is smaller than 256k, just leave it be, with this layout:
8737 *
8738 * [G][ r0 meta ][ hole ][ r1 meta ][ bits ][G]
8739 *
8740 * else punch a hole with guard pages around the hole, and place the
8741 * bits in the hole if it fits, or after r1 otherwise, yielding either
8742 * of the following layouts:
8743 *
8744 * |__________________hend____________|
8745 * |__hstart_| |
8746 * [G][ r0 meta ][ bits ][G]..........[G][ r1 meta ][G]
8747 * [G][ r0 meta ][G]..................[G][ r1 meta ][ bits ][G]
8748 */
8749 hstart = round_page(atop(r0.max_address - r0.min_address) *
8750 sizeof(struct zone_page_metadata));
8751 hend = trunc_page(atop(r1.min_address - r0.min_address) *
8752 sizeof(struct zone_page_metadata));
8753
8754 if (hstart >= hend || hend - hstart < (256ul << 10)) {
8755 mr = zone_init_allocate_va(0, meta_size + bits_size,
8756 ZIA_PERMANENT | ZIA_RANDOM);
8757 mr.min_address += ZONE_GUARD_SIZE;
8758 mr.max_address -= ZONE_GUARD_SIZE;
8759 br.max_address = mr.max_address;
8760 mr.max_address -= bits_size;
8761 br.min_address = mr.max_address;
8762
8763 #if DEBUG || DEVELOPMENT
8764 printf("zone_init: metadata %p:%p (%zuK)\n",
8765 (void *)mr.min_address, (void *)mr.max_address,
8766 (size_t)zone_range_size(&mr) >> 10);
8767 printf("zone_init: metabits %p:%p (%zuK)\n",
8768 (void *)br.min_address, (void *)br.max_address,
8769 (size_t)zone_range_size(&br) >> 10);
8770 #endif /* DEBUG || DEVELOPMENT */
8771 } else {
8772 vm_size_t size, alloc_size = meta_size;
8773 vm_offset_t base;
8774 bool bits_in_middle = true;
8775
8776 if (hend - hstart - 2 * ZONE_GUARD_SIZE < bits_size) {
8777 alloc_size += bits_size;
8778 bits_in_middle = false;
8779 }
8780
8781 mr = zone_init_allocate_va(0, alloc_size, ZIA_RANDOM);
8782
8783 base = mr.min_address;
8784 size = ZONE_GUARD_SIZE + hstart + ZONE_GUARD_SIZE;
8785 if (bits_in_middle) {
8786 size += bits_size;
8787 br.min_address = base + ZONE_GUARD_SIZE + hstart;
8788 br.max_address = br.min_address + bits_size;
8789 }
8790 zone_init_allocate_va(base, size, ZIA_PERMANENT | ZIA_REPLACE);
8791
8792 base += size;
8793 size = mr.min_address + hend - base;
8794 kmem_free(kernel_map, base, size);
8795
8796 base = mr.min_address + hend;
8797 size = mr.max_address - base;
8798 zone_init_allocate_va(base, size, ZIA_PERMANENT | ZIA_REPLACE);
8799
8800 mr.min_address += ZONE_GUARD_SIZE;
8801 mr.max_address -= ZONE_GUARD_SIZE;
8802 if (!bits_in_middle) {
8803 br.max_address = mr.max_address;
8804 mr.max_address -= bits_size;
8805 br.min_address = mr.max_address;
8806 }
8807
8808 #if DEBUG || DEVELOPMENT
8809 printf("zone_init: metadata0 %p:%p (%zuK)\n",
8810 (void *)mr.min_address, (void *)(mr.min_address + hstart),
8811 (size_t)hstart >> 10);
8812 printf("zone_init: metadata1 %p:%p (%zuK)\n",
8813 (void *)(mr.min_address + hend), (void *)mr.max_address,
8814 (size_t)(zone_range_size(&mr) - hend) >> 10);
8815 printf("zone_init: metabits %p:%p (%zuK)\n",
8816 (void *)br.min_address, (void *)br.max_address,
8817 (size_t)zone_range_size(&br) >> 10);
8818 #endif /* DEBUG || DEVELOPMENT */
8819 }
8820
8821 br.min_address = (br.min_address + ZBA_CHUNK_SIZE - 1) & -ZBA_CHUNK_SIZE;
8822 br.max_address = br.max_address & -ZBA_CHUNK_SIZE;
8823
8824 zone_info.zi_meta_range = mr;
8825 zone_info.zi_bits_range = br;
8826
8827 /*
8828 * Migrate the original static metadata into its new location.
8829 */
8830 struct zone_page_metadata *early_meta = zone_foreign_meta_array_startup;
8831
8832 if (zone_early_steal.min_address) {
8833 early_meta = (void *)zone_early_steal.min_address;
8834 }
8835
8836 zone_info.zi_meta_base = (struct zone_page_metadata *)mr.min_address -
8837 zone_pva_from_addr(r0.min_address).packed_address;
8838 foreign_base = zone_info.zi_map_range[ZONE_ADDR_FOREIGN].min_address;
8839 zone_meta_populate(foreign_base, zone_foreign_size());
8840 memcpy(zone_meta_from_addr(foreign_base), early_meta,
8841 atop(zone_foreign_size()) * sizeof(struct zone_page_metadata));
8842
8843 if (zone_early_steal.min_address) {
8844 pmap_remove(kernel_pmap, zone_early_steal.min_address,
8845 zone_early_steal.max_address);
8846 }
8847
8848 zba_populate(0);
8849 memcpy(zba_base_header(), zba_chunk_startup,
8850 sizeof(zba_chunk_startup));
8851
8852 /*
8853 * Initialize the vm submap allocator
8854 *
8855 * Note that we declare one more page than there is,
8856 * because we know it is the metadata for the guard
8857 * before the next submap.
8858 *
8859 * That lets us have a backstop metadata with
8860 * a ZM_SUBMAP_CHUNK_REST marker even with a full submap.
8861 */
8862 struct zone_page_metadata *meta;
8863 vm_address_t addr;
8864
8865 addr = vm_map_min(zone_submaps[0]);
8866 meta = zone_meta_from_addr(addr);
8867 zone_meta_populate(addr, PAGE_SIZE);
8868
8869 meta->zm_chunk_len = ZM_SUBMAP_CHUNK_REST;
8870 meta->zm_va_len = (uint32_t)atop(vm_map_max(zone_submaps[0]) - addr) + 1;
8871 }
8872
8873 /*
8874 * Global initialization of Zone Allocator.
8875 * Runs after zone_bootstrap.
8876 */
8877 __startup_func
8878 static void
zone_init(void)8879 zone_init(void)
8880 {
8881 vm_size_t zone_map_size;
8882 vm_size_t remaining_size;
8883 vm_offset_t submap_min = 0;
8884 uint64_t denom = 0;
8885 uint32_t submap_count = 0;
8886 uint16_t submap_ratios[Z_SUBMAP_IDX_COUNT] = {
8887 #if ZSECURITY_CONFIG(READ_ONLY)
8888 [Z_SUBMAP_IDX_VM] = 15,
8889 [Z_SUBMAP_IDX_READ_ONLY] = 5,
8890 #else
8891 [Z_SUBMAP_IDX_VM] = 20,
8892 #endif /* !ZSECURITY_CONFIG(READ_ONLY) */
8893 #if ZSECURITY_CONFIG(SUBMAP_USER_DATA) && ZSECURITY_CONFIG(SAD_FENG_SHUI)
8894 [Z_SUBMAP_IDX_GENERAL_0] = 15,
8895 [Z_SUBMAP_IDX_GENERAL_1] = 15,
8896 [Z_SUBMAP_IDX_GENERAL_2] = 15,
8897 [Z_SUBMAP_IDX_GENERAL_3] = 15,
8898 [Z_SUBMAP_IDX_DATA] = 20,
8899 #elif ZSECURITY_CONFIG(SUBMAP_USER_DATA)
8900 [Z_SUBMAP_IDX_GENERAL_0] = 40,
8901 [Z_SUBMAP_IDX_DATA] = 40,
8902 #elif ZSECURITY_CONFIG(SAD_FENG_SHUI)
8903 #error invalid configuration: SAD_FENG_SHUI requires SUBMAP_USER_DATA
8904 #else
8905 [Z_SUBMAP_IDX_GENERAL_0] = 80,
8906 #endif /* ZSECURITY_CONFIG(SUBMAP_USER_DATA) && ZSECURITY_CONFIG(SAD_FENG_SHUI) */
8907 };
8908
8909 zone_phys_mapped_max_pages = (uint32_t)atop(zone_phys_size_max());
8910
8911 for (unsigned idx = 0; idx < Z_SUBMAP_IDX_COUNT; idx++) {
8912 denom += submap_ratios[idx];
8913 if (submap_ratios[idx] != 0) {
8914 submap_count++;
8915 }
8916 }
8917
8918 #if __LP64__
8919 zone_map_size = ZONE_MAP_VIRTUAL_SIZE_LP64;
8920 #else
8921 zone_map_size = ptoa(zone_phys_mapped_max_pages *
8922 (denom + submap_ratios[Z_SUBMAP_IDX_VM]) / denom);
8923 #endif
8924
8925 remaining_size = zone_map_size -
8926 ZONE_GUARD_SIZE * (submap_count);
8927
8928 /*
8929 * And now allocate the various pieces of VA and submaps.
8930 *
8931 * Make a first allocation of contiguous VA, that we'll deallocate,
8932 * and we'll carve-out memory in that range again linearly.
8933 * The kernel is stil single threaded at this stage.
8934 */
8935
8936 struct zone_map_range *map_range =
8937 &zone_info.zi_map_range[ZONE_ADDR_NATIVE];
8938
8939 *map_range = zone_init_allocate_va(0, zone_map_size, ZIA_NONE);
8940 submap_min = map_range->min_address;
8941
8942 /*
8943 * Allocate the submaps
8944 */
8945 for (zone_submap_idx_t idx = 0; idx < Z_SUBMAP_IDX_COUNT; idx++) {
8946 if (submap_ratios[idx] == 0) {
8947 zone_submaps[idx] = VM_MAP_NULL;
8948 } else {
8949 zone_submap_init(&submap_min, idx, submap_ratios[idx],
8950 &denom, &remaining_size, ZONE_GUARD_SIZE);
8951 }
8952 }
8953
8954 assert(submap_min == map_range->max_address);
8955
8956 /*
8957 * needs to be done before zone_metadata_init() which occupies
8958 * random space in the kernel, and the maps need a HUGE range.
8959 */
8960 kalloc_init_maps(map_range->max_address);
8961
8962 zone_metadata_init();
8963
8964 #if VM_TAG_SIZECLASSES
8965 if (zone_tagging_on) {
8966 zone_tagging_init(zone_map_size);
8967 }
8968 #endif
8969 #if CONFIG_GZALLOC
8970 gzalloc_init(zone_map_size);
8971 #endif
8972
8973 zone_create_flags_t kma_flags = ZC_NOCACHING |
8974 ZC_NOGC | ZC_NOGZALLOC | ZC_NOCALLOUT |
8975 ZC_KASAN_NOQUARANTINE | ZC_KASAN_NOREDZONE | ZC_VM_LP64;
8976
8977 (void)zone_create_ext("vm.permanent", 1, kma_flags,
8978 ZONE_ID_PERMANENT, ^(zone_t z) {
8979 z->z_permanent = true;
8980 z->z_elem_size = 1;
8981 });
8982 (void)zone_create_ext("vm.permanent.percpu", 1,
8983 kma_flags | ZC_PERCPU, ZONE_ID_PERCPU_PERMANENT, ^(zone_t z) {
8984 z->z_permanent = true;
8985 z->z_elem_size = 1;
8986 });
8987
8988 /*
8989 * Now migrate the startup statistics into their final storage.
8990 */
8991 int cpu = cpu_number();
8992 zone_index_foreach(idx) {
8993 zone_t tz = &zone_array[idx];
8994
8995 if (tz->z_stats == __zpcpu_mangle_for_boot(&zone_stats_startup[idx])) {
8996 zone_stats_t zs = zalloc_percpu_permanent_type(struct zone_stats);
8997
8998 *zpercpu_get_cpu(zs, cpu) = *zpercpu_get_cpu(tz->z_stats, cpu);
8999 tz->z_stats = zs;
9000 #if ZONE_ENABLE_LOGGING
9001 if (tz->zone_logging && !tz->zlog_btlog) {
9002 zone_enable_logging(tz);
9003 }
9004 #endif /* ZONE_ENABLE_LOGGING */
9005 }
9006 }
9007
9008 #if CONFIG_ZLEAKS
9009 /*
9010 * Initialize the zone leak monitor
9011 */
9012 zleak_init(zone_map_size);
9013 #endif /* CONFIG_ZLEAKS */
9014
9015 #if VM_TAG_SIZECLASSES
9016 if (zone_tagging_on) {
9017 vm_allocation_zones_init();
9018 }
9019 #endif
9020 }
9021 STARTUP(ZALLOC, STARTUP_RANK_FIRST, zone_init);
9022
9023 __startup_func
9024 static void
zone_cache_bootstrap(void)9025 zone_cache_bootstrap(void)
9026 {
9027 zone_t magzone;
9028
9029 magzone = zone_create("zcc_magazine_zone", sizeof(struct zone_magazine) +
9030 zc_mag_size() * sizeof(zone_element_t),
9031 ZC_NOGZALLOC | ZC_KASAN_NOREDZONE | ZC_KASAN_NOQUARANTINE |
9032 ZC_SEQUESTER | ZC_CACHING | ZC_ZFREE_CLEARMEM);
9033 magzone->z_elems_rsv = (uint16_t)(2 * zpercpu_count());
9034
9035 os_atomic_store(&zc_magazine_zone, magzone, compiler_acq_rel);
9036
9037 /*
9038 * Now that we are initialized, we can enable zone caching for zones that
9039 * were made before zcache_bootstrap() was called.
9040 *
9041 * The system is still single threaded so we don't need to take the lock.
9042 */
9043 zone_index_foreach(i) {
9044 zone_t z = &zone_array[i];
9045 if (z->z_pcpu_cache) {
9046 z->z_pcpu_cache = NULL;
9047 zone_enable_caching(z);
9048 }
9049 }
9050 }
9051 STARTUP(ZALLOC, STARTUP_RANK_FOURTH, zone_cache_bootstrap);
9052
9053 void
zalloc_first_proc_made(void)9054 zalloc_first_proc_made(void)
9055 {
9056 zone_caching_disabled = 0;
9057 }
9058
9059 __startup_func
9060 vm_offset_t
zone_foreign_mem_init(vm_size_t size,bool allow_meta_steal)9061 zone_foreign_mem_init(vm_size_t size, bool allow_meta_steal)
9062 {
9063 struct zone_page_metadata *base;
9064 vm_offset_t mem;
9065
9066 if (atop(size) <= ZONE_FOREIGN_META_INLINE_COUNT) {
9067 base = zone_foreign_meta_array_startup;
9068 } else if (allow_meta_steal) {
9069 vm_size_t steal_size;
9070
9071 printf("zinit: not enough early foreigh metadata "
9072 "(%d > %d) stealing from the pmap\n",
9073 (int)atop(size), ZONE_FOREIGN_META_INLINE_COUNT);
9074 steal_size = round_page(atop(size) * sizeof(*base));
9075 base = pmap_steal_memory(steal_size);
9076 zone_early_steal.min_address = (vm_offset_t)base;
9077 zone_early_steal.max_address = (vm_offset_t)base + steal_size;
9078 } else {
9079 panic("ZONE_FOREIGN_META_INLINE_COUNT has become too small: "
9080 "%d > %d", (int)atop(size), ZONE_FOREIGN_META_INLINE_COUNT);
9081 }
9082
9083 mem = (vm_offset_t)pmap_steal_memory(size);
9084
9085 zone_info.zi_meta_base = base - zone_pva_from_addr(mem).packed_address;
9086 zone_info.zi_map_range[ZONE_ADDR_FOREIGN].min_address = mem;
9087 zone_info.zi_map_range[ZONE_ADDR_FOREIGN].max_address = mem + size;
9088
9089 zone_info.zi_bits_range = (struct zone_map_range){
9090 .min_address = (vm_offset_t)zba_chunk_startup,
9091 .max_address = (vm_offset_t)zba_chunk_startup +
9092 sizeof(zba_chunk_startup),
9093 };
9094 zba_init_chunk(0);
9095
9096 return mem;
9097 }
9098
9099 #endif /* !ZALLOC_TEST */
9100 #pragma mark - tests
9101 #if DEBUG || DEVELOPMENT
9102
9103 /*
9104 * Used for sysctl zone tests that aren't thread-safe. Ensure only one
9105 * thread goes through at a time.
9106 *
9107 * Or we can end up with multiple test zones (if a second zinit() comes through
9108 * before zdestroy()), which could lead us to run out of zones.
9109 */
9110 static bool any_zone_test_running = FALSE;
9111
9112 static uintptr_t *
zone_copy_allocations(zone_t z,uintptr_t * elems,zone_pva_t page_index)9113 zone_copy_allocations(zone_t z, uintptr_t *elems, zone_pva_t page_index)
9114 {
9115 vm_offset_t elem_size = zone_elem_size(z);
9116 vm_offset_t base;
9117 struct zone_page_metadata *meta;
9118
9119 while (!zone_pva_is_null(page_index)) {
9120 base = zone_pva_to_addr(page_index);
9121 meta = zone_pva_to_meta(page_index);
9122
9123 if (meta->zm_inline_bitmap) {
9124 for (size_t i = 0; i < meta->zm_chunk_len; i++) {
9125 uint32_t map = meta[i].zm_bitmap;
9126
9127 for (; map; map &= map - 1) {
9128 *elems++ = INSTANCE_PUT(base +
9129 elem_size * __builtin_clz(map));
9130 }
9131 base += elem_size * 32;
9132 }
9133 } else {
9134 uint32_t order = zba_bits_ref_order(meta->zm_bitmap);
9135 bitmap_t *bits = zba_bits_ref_ptr(meta->zm_bitmap);
9136 for (size_t i = 0; i < (1u << order); i++) {
9137 uint64_t map = bits[i];
9138
9139 for (; map; map &= map - 1) {
9140 *elems++ = INSTANCE_PUT(base +
9141 elem_size * __builtin_clzll(map));
9142 }
9143 base += elem_size * 64;
9144 }
9145 }
9146
9147 page_index = meta->zm_page_next;
9148 }
9149 return elems;
9150 }
9151
9152 kern_return_t
zone_leaks(const char * zoneName,uint32_t nameLen,leak_site_proc proc,void * refCon)9153 zone_leaks(const char * zoneName, uint32_t nameLen, leak_site_proc proc, void * refCon)
9154 {
9155 uintptr_t zbt[MAX_ZTRACE_DEPTH];
9156 zone_t zone = NULL;
9157 uintptr_t * array;
9158 uintptr_t * next;
9159 uintptr_t element, bt;
9160 uint32_t idx, count, found;
9161 uint32_t btidx, btcount, nobtcount, btfound;
9162 uint32_t elemSize;
9163 size_t maxElems;
9164 kern_return_t kr;
9165
9166 zone_foreach(z) {
9167 if (!strncmp(zoneName, z->z_name, nameLen)) {
9168 zone = z;
9169 break;
9170 }
9171 }
9172 if (zone == NULL) {
9173 return KERN_INVALID_NAME;
9174 }
9175
9176 elemSize = (uint32_t)zone_elem_size(zone);
9177 maxElems = (zone->z_elems_avail + 1) & ~1ul;
9178
9179 if ((ptoa(zone->z_percpu ? 1 : zone->z_chunk_pages) % elemSize) &&
9180 !zone_leaks_scan_enable) {
9181 return KERN_INVALID_CAPABILITY;
9182 }
9183
9184 kr = kmem_alloc_kobject(kernel_map, (vm_offset_t *) &array,
9185 maxElems * sizeof(uintptr_t), VM_KERN_MEMORY_DIAG);
9186 if (KERN_SUCCESS != kr) {
9187 return kr;
9188 }
9189
9190 zone_lock(zone);
9191
9192 next = array;
9193 next = zone_copy_allocations(zone, next, zone->z_pageq_partial);
9194 next = zone_copy_allocations(zone, next, zone->z_pageq_full);
9195 count = (uint32_t)(next - array);
9196
9197 zone_unlock(zone);
9198
9199 zone_leaks_scan(array, count, (uint32_t)zone_elem_size(zone), &found);
9200 assert(found <= count);
9201
9202 for (idx = 0; idx < count; idx++) {
9203 element = array[idx];
9204 if (kInstanceFlagReferenced & element) {
9205 continue;
9206 }
9207 element = INSTANCE_PUT(element) & ~kInstanceFlags;
9208 }
9209
9210 #if ZONE_ENABLE_LOGGING
9211 if (zone->zlog_btlog && !corruption_debug_flag) {
9212 // btlog_copy_backtraces_for_elements will set kInstanceFlagReferenced on elements it found
9213 btlog_copy_backtraces_for_elements(zone->zlog_btlog, array, &count, elemSize, proc, refCon);
9214 }
9215 #endif /* ZONE_ENABLE_LOGGING */
9216
9217 for (nobtcount = idx = 0; idx < count; idx++) {
9218 element = array[idx];
9219 if (!element) {
9220 continue;
9221 }
9222 if (kInstanceFlagReferenced & element) {
9223 continue;
9224 }
9225 element = INSTANCE_PUT(element) & ~kInstanceFlags;
9226
9227 // see if we can find any backtrace left in the element
9228 btcount = (typeof(btcount))(zone_elem_size(zone) / sizeof(uintptr_t));
9229 if (btcount >= MAX_ZTRACE_DEPTH) {
9230 btcount = MAX_ZTRACE_DEPTH - 1;
9231 }
9232 for (btfound = btidx = 0; btidx < btcount; btidx++) {
9233 bt = ((uintptr_t *)element)[btcount - 1 - btidx];
9234 if (!VM_KERNEL_IS_SLID(bt)) {
9235 break;
9236 }
9237 zbt[btfound++] = bt;
9238 }
9239 if (btfound) {
9240 (*proc)(refCon, 1, elemSize, &zbt[0], btfound);
9241 } else {
9242 nobtcount++;
9243 }
9244 }
9245 if (nobtcount) {
9246 // fake backtrace when we found nothing
9247 zbt[0] = (uintptr_t) &zalloc;
9248 (*proc)(refCon, nobtcount, elemSize, &zbt[0], 1);
9249 }
9250
9251 kmem_free(kernel_map, (vm_offset_t) array, maxElems * sizeof(uintptr_t));
9252
9253 return KERN_SUCCESS;
9254 }
9255
9256 static int
zone_ro_basic_test_run(__unused int64_t in,int64_t * out)9257 zone_ro_basic_test_run(__unused int64_t in, int64_t *out)
9258 {
9259 zone_security_flags_t zsflags;
9260 uint32_t x = 4;
9261 uint32_t *test_ptr;
9262
9263 if (os_atomic_xchg(&any_zone_test_running, true, relaxed)) {
9264 printf("zone_ro_basic_test: Test already running.\n");
9265 return EALREADY;
9266 }
9267
9268 zsflags = zone_security_array[ZONE_ID__FIRST_RO];
9269
9270 for (int i = 0; i < 3; i++) {
9271 #if ZSECURITY_CONFIG(READ_ONLY)
9272 /* Basic Test: Create int zone, zalloc int, modify value, free int */
9273 printf("zone_ro_basic_test: Basic Test iteration %d\n", i);
9274 printf("zone_ro_basic_test: create a sub-page size zone\n");
9275
9276 printf("zone_ro_basic_test: verify flags were set\n");
9277 assert(zsflags.z_submap_idx == Z_SUBMAP_IDX_READ_ONLY);
9278
9279 printf("zone_ro_basic_test: zalloc an element\n");
9280 test_ptr = zalloc_ro(ZONE_ID__FIRST_RO, Z_WAITOK);
9281 assert(test_ptr);
9282
9283 printf("zone_ro_basic_test: verify elem in the right submap\n");
9284 zone_require_ro_range_contains(ZONE_ID__FIRST_RO, test_ptr);
9285
9286 printf("zone_ro_basic_test: verify we can't write to it\n");
9287 assert(verify_write(&x, test_ptr, sizeof(x)) == EFAULT);
9288
9289 x = 4;
9290 printf("zone_ro_basic_test: test zalloc_ro_mut to assign value\n");
9291 zalloc_ro_mut(ZONE_ID__FIRST_RO, test_ptr, 0, &x, sizeof(uint32_t));
9292 assert(test_ptr);
9293 assert(*(uint32_t*)test_ptr == x);
9294
9295 x = 5;
9296 printf("zone_ro_basic_test: test zalloc_ro_update_elem to assign value\n");
9297 zalloc_ro_update_elem(ZONE_ID__FIRST_RO, test_ptr, &x);
9298 assert(test_ptr);
9299 assert(*(uint32_t*)test_ptr == x);
9300
9301 printf("zone_ro_basic_test: verify we can't write to it after assigning value\n");
9302 assert(verify_write(&x, test_ptr, sizeof(x)) == EFAULT);
9303
9304 printf("zone_ro_basic_test: free elem\n");
9305 zfree_ro(ZONE_ID__FIRST_RO, test_ptr);
9306 assert(!test_ptr);
9307 #else
9308 printf("zone_ro_basic_test: Read-only allocator n/a on 32bit platforms, test functionality of API\n");
9309
9310 printf("zone_ro_basic_test: verify flags were set\n");
9311 assert(zsflags.z_submap_idx != Z_SUBMAP_IDX_READ_ONLY);
9312
9313 printf("zone_ro_basic_test: zalloc an element\n");
9314 test_ptr = zalloc_ro(ZONE_ID__FIRST_RO, Z_WAITOK);
9315 assert(test_ptr);
9316
9317 x = 4;
9318 printf("zone_ro_basic_test: test zalloc_ro_mut to assign value\n");
9319 zalloc_ro_mut(ZONE_ID__FIRST_RO, test_ptr, 0, &x, sizeof(uint32_t));
9320 assert(test_ptr);
9321 assert(*(uint32_t*)test_ptr == x);
9322
9323 x = 5;
9324 printf("zone_ro_basic_test: test zalloc_ro_update_elem to assign value\n");
9325 zalloc_ro_update_elem(ZONE_ID__FIRST_RO, test_ptr, &x);
9326 assert(test_ptr);
9327 assert(*(uint32_t*)test_ptr == x);
9328
9329 printf("zone_ro_basic_test: free elem\n");
9330 zfree_ro(ZONE_ID__FIRST_RO, test_ptr);
9331 assert(!test_ptr);
9332 #endif /* !ZSECURITY_CONFIG(READ_ONLY) */
9333 }
9334
9335 printf("zone_ro_basic_test: garbage collection\n");
9336 zone_gc(ZONE_GC_DRAIN);
9337
9338 printf("zone_ro_basic_test: Test passed\n");
9339
9340 *out = 1;
9341 os_atomic_store(&any_zone_test_running, false, relaxed);
9342 return 0;
9343 }
9344 SYSCTL_TEST_REGISTER(zone_ro_basic_test, zone_ro_basic_test_run);
9345
9346 static int
zone_basic_test_run(__unused int64_t in,int64_t * out)9347 zone_basic_test_run(__unused int64_t in, int64_t *out)
9348 {
9349 static zone_t test_zone_ptr = NULL;
9350
9351 unsigned int i = 0, max_iter = 5;
9352 void * test_ptr;
9353 zone_t test_zone;
9354 int rc = 0;
9355
9356 if (os_atomic_xchg(&any_zone_test_running, true, relaxed)) {
9357 printf("zone_basic_test: Test already running.\n");
9358 return EALREADY;
9359 }
9360
9361 printf("zone_basic_test: Testing zinit(), zalloc(), zfree() and zdestroy() on zone \"test_zone_sysctl\"\n");
9362
9363 /* zinit() and zdestroy() a zone with the same name a bunch of times, verify that we get back the same zone each time */
9364 do {
9365 test_zone = zinit(sizeof(uint64_t), 100 * sizeof(uint64_t), sizeof(uint64_t), "test_zone_sysctl");
9366 assert(test_zone);
9367
9368 #if KASAN_ZALLOC
9369 if (test_zone_ptr == NULL && test_zone->z_elems_free != 0)
9370 #else
9371 if (test_zone->z_elems_free != 0)
9372 #endif
9373 {
9374 printf("zone_basic_test: free count is not zero\n");
9375 rc = EIO;
9376 goto out;
9377 }
9378
9379 if (test_zone_ptr == NULL) {
9380 /* Stash the zone pointer returned on the fist zinit */
9381 printf("zone_basic_test: zone created for the first time\n");
9382 test_zone_ptr = test_zone;
9383 } else if (test_zone != test_zone_ptr) {
9384 printf("zone_basic_test: old zone pointer and new zone pointer don't match\n");
9385 rc = EIO;
9386 goto out;
9387 }
9388
9389 test_ptr = zalloc_flags(test_zone, Z_WAITOK | Z_NOFAIL);
9390 zfree(test_zone, test_ptr);
9391
9392 zdestroy(test_zone);
9393 i++;
9394
9395 printf("zone_basic_test: Iteration %d successful\n", i);
9396 } while (i < max_iter);
9397
9398 /* test Z_VA_SEQUESTER */
9399 #if ZSECURITY_CONFIG(SEQUESTER)
9400 {
9401 zone_t test_pcpu_zone;
9402 kern_return_t kr;
9403 int idx, num_allocs = 8;
9404 vm_size_t elem_size = 2 * PAGE_SIZE / num_allocs;
9405 void *allocs[num_allocs];
9406 void **allocs_pcpu;
9407 vm_offset_t phys_pages = os_atomic_load(&zones_phys_page_mapped_count, relaxed);
9408
9409 test_zone = zone_create("test_zone_sysctl", elem_size,
9410 ZC_DESTRUCTIBLE);
9411 assert(test_zone);
9412 assert(zone_security_config(test_zone).z_va_sequester);
9413
9414 test_pcpu_zone = zone_create("test_zone_sysctl.pcpu", sizeof(uint64_t),
9415 ZC_DESTRUCTIBLE | ZC_PERCPU);
9416 assert(test_pcpu_zone);
9417 assert(zone_security_config(test_pcpu_zone).z_va_sequester);
9418
9419 for (idx = 0; idx < num_allocs; idx++) {
9420 allocs[idx] = zalloc(test_zone);
9421 assert(NULL != allocs[idx]);
9422 printf("alloc[%d] %p\n", idx, allocs[idx]);
9423 }
9424 for (idx = 0; idx < num_allocs; idx++) {
9425 zfree(test_zone, allocs[idx]);
9426 }
9427 assert(!zone_pva_is_null(test_zone->z_pageq_empty));
9428
9429 kr = kernel_memory_allocate(kernel_map,
9430 (vm_address_t *)&allocs_pcpu, PAGE_SIZE,
9431 0, KMA_ZERO | KMA_KOBJECT, VM_KERN_MEMORY_DIAG);
9432 assert(kr == KERN_SUCCESS);
9433
9434 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
9435 allocs_pcpu[idx] = zalloc_percpu(test_pcpu_zone,
9436 Z_WAITOK | Z_ZERO);
9437 assert(NULL != allocs_pcpu[idx]);
9438 }
9439 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
9440 zfree_percpu(test_pcpu_zone, allocs_pcpu[idx]);
9441 }
9442 assert(!zone_pva_is_null(test_pcpu_zone->z_pageq_empty));
9443
9444 printf("vm_page_wire_count %d, vm_page_free_count %d, p to v %ld%%\n",
9445 vm_page_wire_count, vm_page_free_count,
9446 100L * phys_pages / zone_phys_mapped_max_pages);
9447 zone_gc(ZONE_GC_DRAIN);
9448 printf("vm_page_wire_count %d, vm_page_free_count %d, p to v %ld%%\n",
9449 vm_page_wire_count, vm_page_free_count,
9450 100L * phys_pages / zone_phys_mapped_max_pages);
9451
9452 unsigned int allva = 0;
9453
9454 zone_foreach(z) {
9455 zone_lock(z);
9456 allva += z->z_wired_cur;
9457 if (zone_pva_is_null(z->z_pageq_va)) {
9458 zone_unlock(z);
9459 continue;
9460 }
9461 unsigned count = 0;
9462 uint64_t size;
9463 zone_pva_t pg = z->z_pageq_va;
9464 struct zone_page_metadata *page_meta;
9465 while (pg.packed_address) {
9466 page_meta = zone_pva_to_meta(pg);
9467 count += z->z_percpu ? 1 : z->z_chunk_pages;
9468 if (page_meta->zm_chunk_len == ZM_SECONDARY_PAGE) {
9469 count -= page_meta->zm_page_index;
9470 }
9471 pg = page_meta->zm_page_next;
9472 }
9473 size = zone_size_wired(z);
9474 if (!size) {
9475 size = 1;
9476 }
9477 printf("%s%s: seq %d, res %d, %qd %%\n",
9478 zone_heap_name(z), z->z_name, z->z_va_cur - z->z_wired_cur,
9479 z->z_wired_cur, zone_size_allocated(z) * 100ULL / size);
9480 zone_unlock(z);
9481 }
9482
9483 printf("total va: %d\n", allva);
9484
9485 assert(zone_pva_is_null(test_zone->z_pageq_empty));
9486 assert(zone_pva_is_null(test_zone->z_pageq_partial));
9487 assert(!zone_pva_is_null(test_zone->z_pageq_va));
9488 assert(zone_pva_is_null(test_pcpu_zone->z_pageq_empty));
9489 assert(zone_pva_is_null(test_pcpu_zone->z_pageq_partial));
9490 assert(!zone_pva_is_null(test_pcpu_zone->z_pageq_va));
9491
9492 for (idx = 0; idx < num_allocs; idx++) {
9493 assert(0 == pmap_find_phys(kernel_pmap, (addr64_t)(uintptr_t) allocs[idx]));
9494 }
9495
9496 /* make sure the zone is still usable after a GC */
9497
9498 for (idx = 0; idx < num_allocs; idx++) {
9499 allocs[idx] = zalloc(test_zone);
9500 assert(allocs[idx]);
9501 printf("alloc[%d] %p\n", idx, allocs[idx]);
9502 }
9503 for (idx = 0; idx < num_allocs; idx++) {
9504 zfree(test_zone, allocs[idx]);
9505 }
9506
9507 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
9508 allocs_pcpu[idx] = zalloc_percpu(test_pcpu_zone,
9509 Z_WAITOK | Z_ZERO);
9510 assert(NULL != allocs_pcpu[idx]);
9511 }
9512 for (idx = 0; idx < PAGE_SIZE / sizeof(uint64_t); idx++) {
9513 zfree_percpu(test_pcpu_zone, allocs_pcpu[idx]);
9514 }
9515
9516 assert(!zone_pva_is_null(test_pcpu_zone->z_pageq_empty));
9517
9518 kmem_free(kernel_map, (vm_address_t)allocs_pcpu, PAGE_SIZE);
9519
9520 zdestroy(test_zone);
9521 zdestroy(test_pcpu_zone);
9522 }
9523 #else
9524 printf("zone_basic_test: skipping sequester test (not enabled)\n");
9525 #endif /* ZSECURITY_CONFIG(SEQUESTER) */
9526
9527 printf("zone_basic_test: Test passed\n");
9528
9529
9530 *out = 1;
9531 out:
9532 os_atomic_store(&any_zone_test_running, false, relaxed);
9533 return rc;
9534 }
9535 SYSCTL_TEST_REGISTER(zone_basic_test, zone_basic_test_run);
9536
9537 struct zone_stress_obj {
9538 TAILQ_ENTRY(zone_stress_obj) zso_link;
9539 };
9540
9541 struct zone_stress_ctx {
9542 thread_t zsc_leader;
9543 lck_mtx_t zsc_lock;
9544 zone_t zsc_zone;
9545 uint64_t zsc_end;
9546 uint32_t zsc_workers;
9547 };
9548
9549 static void
zone_stress_worker(void * arg,wait_result_t __unused wr)9550 zone_stress_worker(void *arg, wait_result_t __unused wr)
9551 {
9552 struct zone_stress_ctx *ctx = arg;
9553 bool leader = ctx->zsc_leader == current_thread();
9554 TAILQ_HEAD(zone_stress_head, zone_stress_obj) head = TAILQ_HEAD_INITIALIZER(head);
9555 struct zone_bool_gen bg = { };
9556 struct zone_stress_obj *obj;
9557 uint32_t allocs = 0;
9558
9559 random_bool_init(&bg.zbg_bg);
9560
9561 do {
9562 for (int i = 0; i < 2000; i++) {
9563 uint32_t what = random_bool_gen_bits(&bg.zbg_bg,
9564 bg.zbg_entropy, ZONE_ENTROPY_CNT, 1);
9565 switch (what) {
9566 case 0:
9567 case 1:
9568 if (allocs < 10000) {
9569 obj = zalloc(ctx->zsc_zone);
9570 TAILQ_INSERT_HEAD(&head, obj, zso_link);
9571 allocs++;
9572 }
9573 break;
9574 case 2:
9575 case 3:
9576 if (allocs < 10000) {
9577 obj = zalloc(ctx->zsc_zone);
9578 TAILQ_INSERT_TAIL(&head, obj, zso_link);
9579 allocs++;
9580 }
9581 break;
9582 case 4:
9583 if (leader) {
9584 zone_gc(ZONE_GC_DRAIN);
9585 }
9586 break;
9587 case 5:
9588 case 6:
9589 if (!TAILQ_EMPTY(&head)) {
9590 obj = TAILQ_FIRST(&head);
9591 TAILQ_REMOVE(&head, obj, zso_link);
9592 zfree(ctx->zsc_zone, obj);
9593 allocs--;
9594 }
9595 break;
9596 case 7:
9597 if (!TAILQ_EMPTY(&head)) {
9598 obj = TAILQ_LAST(&head, zone_stress_head);
9599 TAILQ_REMOVE(&head, obj, zso_link);
9600 zfree(ctx->zsc_zone, obj);
9601 allocs--;
9602 }
9603 break;
9604 }
9605 }
9606 } while (mach_absolute_time() < ctx->zsc_end);
9607
9608 while (!TAILQ_EMPTY(&head)) {
9609 obj = TAILQ_FIRST(&head);
9610 TAILQ_REMOVE(&head, obj, zso_link);
9611 zfree(ctx->zsc_zone, obj);
9612 }
9613
9614 lck_mtx_lock(&ctx->zsc_lock);
9615 if (--ctx->zsc_workers == 0) {
9616 thread_wakeup(ctx);
9617 } else if (leader) {
9618 while (ctx->zsc_workers) {
9619 lck_mtx_sleep(&ctx->zsc_lock, LCK_SLEEP_DEFAULT, ctx,
9620 THREAD_UNINT);
9621 }
9622 }
9623 lck_mtx_unlock(&ctx->zsc_lock);
9624
9625 if (!leader) {
9626 thread_terminate_self();
9627 __builtin_unreachable();
9628 }
9629 }
9630
9631 static int
zone_stress_test_run(__unused int64_t in,int64_t * out)9632 zone_stress_test_run(__unused int64_t in, int64_t *out)
9633 {
9634 struct zone_stress_ctx ctx = {
9635 .zsc_leader = current_thread(),
9636 .zsc_workers = 3,
9637 };
9638 kern_return_t kr;
9639 thread_t th;
9640
9641 if (os_atomic_xchg(&any_zone_test_running, true, relaxed)) {
9642 printf("zone_stress_test: Test already running.\n");
9643 return EALREADY;
9644 }
9645
9646 lck_mtx_init(&ctx.zsc_lock, &zone_locks_grp, LCK_ATTR_NULL);
9647 ctx.zsc_zone = zone_create("test_zone_344", 344,
9648 ZC_DESTRUCTIBLE | ZC_NOCACHING);
9649 assert(ctx.zsc_zone->z_chunk_pages > 1);
9650
9651 clock_interval_to_deadline(5, NSEC_PER_SEC, &ctx.zsc_end);
9652
9653 printf("zone_stress_test: Starting (leader %p)\n", current_thread());
9654
9655 os_atomic_inc(&zalloc_simulate_vm_pressure, relaxed);
9656
9657 for (uint32_t i = 1; i < ctx.zsc_workers; i++) {
9658 kr = kernel_thread_start_priority(zone_stress_worker, &ctx,
9659 BASEPRI_DEFAULT, &th);
9660 if (kr == KERN_SUCCESS) {
9661 printf("zone_stress_test: thread %d: %p\n", i, th);
9662 thread_deallocate(th);
9663 } else {
9664 ctx.zsc_workers--;
9665 }
9666 }
9667
9668 zone_stress_worker(&ctx, 0);
9669
9670 lck_mtx_destroy(&ctx.zsc_lock, &zone_locks_grp);
9671
9672 zdestroy(ctx.zsc_zone);
9673
9674 printf("zone_stress_test: Done\n");
9675
9676 *out = 1;
9677 os_atomic_dec(&zalloc_simulate_vm_pressure, relaxed);
9678 os_atomic_store(&any_zone_test_running, false, relaxed);
9679 return 0;
9680 }
9681 SYSCTL_TEST_REGISTER(zone_stress_test, zone_stress_test_run);
9682
9683 /*
9684 * Routines to test that zone garbage collection and zone replenish threads
9685 * running at the same time don't cause problems.
9686 */
9687
9688 static int
zone_gc_replenish_test(__unused int64_t in,int64_t * out)9689 zone_gc_replenish_test(__unused int64_t in, int64_t *out)
9690 {
9691 zone_gc(ZONE_GC_DRAIN);
9692 *out = 1;
9693 return 0;
9694 }
9695 SYSCTL_TEST_REGISTER(zone_gc_replenish_test, zone_gc_replenish_test);
9696
9697 static int
zone_alloc_replenish_test(__unused int64_t in,int64_t * out)9698 zone_alloc_replenish_test(__unused int64_t in, int64_t *out)
9699 {
9700 zone_t z = vm_map_entry_zone;
9701 struct data { struct data *next; } *node, *list = NULL;
9702
9703 if (z == NULL) {
9704 printf("Couldn't find a replenish zone\n");
9705 return EIO;
9706 }
9707
9708 /* big enough to go past replenishment */
9709 for (uint32_t i = 0; i < 10 * z->z_elems_rsv; ++i) {
9710 node = zalloc(z);
9711 node->next = list;
9712 list = node;
9713 }
9714
9715 /*
9716 * release the memory we allocated
9717 */
9718 while (list != NULL) {
9719 node = list;
9720 list = list->next;
9721 zfree(z, node);
9722 }
9723
9724 *out = 1;
9725 return 0;
9726 }
9727 SYSCTL_TEST_REGISTER(zone_alloc_replenish_test, zone_alloc_replenish_test);
9728
9729 #endif /* DEBUG || DEVELOPMENT */
9730