]> git.saurik.com Git - apple/xnu.git/blobdiff - osfmk/kern/zalloc.c
xnu-7195.81.3.tar.gz
[apple/xnu.git] / osfmk / kern / zalloc.c
index 6bcab735d1eb582b37a63afcb0d425544d4f75c4..1ef23d043ac16388bf8d1ec075437f3f2b5fc3ad 100644 (file)
@@ -1,8 +1,8 @@
 /*
- * Copyright (c) 2000-2014 Apple Inc. All rights reserved.
+ * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
  *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
- * 
+ *
  * This file contains Original Code and/or Modifications of Original Code
  * as defined in and that are subject to the Apple Public Source License
  * Version 2.0 (the 'License'). You may not use this file except in
  * unlawful or unlicensed copies of an Apple operating system, or to
  * circumvent, violate, or enable the circumvention or violation of, any
  * terms of an Apple operating system software license agreement.
- * 
+ *
  * Please obtain a copy of the License at
  * http://www.opensource.apple.com/apsl/ and read it before using this file.
- * 
+ *
  * The Original Code and all software distributed under the License are
  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  * Please see the License for the specific language governing rights and
  * limitations under the License.
- * 
+ *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
  */
 /*
  * @OSF_COPYRIGHT@
  */
-/* 
+/*
  * Mach Operating System
  * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
  * All Rights Reserved.
- * 
+ *
  * Permission to use, copy, modify and distribute this software and its
  * documentation is hereby granted, provided that both the copyright
  * notice and this permission notice appear in all copies of the
  * software, derivative works or modified versions, and any portions
  * thereof, and that both notices appear in supporting documentation.
- * 
+ *
  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
- * 
+ *
  * Carnegie Mellon requests users of this software to return to
- * 
+ *
  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
  *  School of Computer Science
  *  Carnegie Mellon University
  *  Pittsburgh PA 15213-3890
- * 
+ *
  * any improvements or extensions that they make and grant Carnegie Mellon
  * the rights to redistribute these changes.
  */
  *     Zone-based memory allocator.  A zone is a collection of fixed size
  *     data blocks for which quick allocation/deallocation is possible.
  */
-#include <zone_debug.h>
-#include <zone_alias_addr.h>
 
+#define ZALLOC_ALLOW_DEPRECATED 1
 #include <mach/mach_types.h>
 #include <mach/vm_param.h>
 #include <mach/kern_return.h>
 #include <mach/mach_host_server.h>
 #include <mach/task_server.h>
 #include <mach/machine/vm_types.h>
-#include <mach_debug/zone_info.h>
 #include <mach/vm_map.h>
+#include <mach/sdt.h>
 
+#include <kern/bits.h>
+#include <kern/startup.h>
 #include <kern/kern_types.h>
 #include <kern/assert.h>
+#include <kern/backtrace.h>
 #include <kern/host.h>
 #include <kern/macro_help.h>
 #include <kern/sched.h>
 #include <kern/sched_prim.h>
 #include <kern/misc_protos.h>
 #include <kern/thread_call.h>
-#include <kern/zalloc.h>
+#include <kern/zalloc_internal.h>
 #include <kern/kalloc.h>
-#include <kern/btlog.h>
+
+#include <prng/random.h>
 
 #include <vm/pmap.h>
 #include <vm/vm_map.h>
 #include <vm/vm_kern.h>
 #include <vm/vm_page.h>
+#include <vm/vm_compressor.h> /* C_SLOT_PACKED_PTR* */
 
 #include <pexpert/pexpert.h>
 
 #include <machine/machparam.h>
 #include <machine/machine_routines.h>  /* ml_cpu_get_info */
 
+#include <os/atomic.h>
+
 #include <libkern/OSDebug.h>
 #include <libkern/OSAtomic.h>
+#include <libkern/section_keywords.h>
 #include <sys/kdebug.h>
 
+#include <san/kasan.h>
+
+#if KASAN_ZALLOC
+#define ZONE_ENABLE_LOGGING 0
+#elif DEBUG || DEVELOPMENT
+#define ZONE_ENABLE_LOGGING 1
+#else
+#define ZONE_ENABLE_LOGGING 0
+#endif
+
+extern void vm_pageout_garbage_collect(int collect);
+
+/* Returns pid of the task with the largest number of VM map entries.  */
+extern pid_t find_largest_process_vm_map_entries(void);
+
 /*
- *  ZONE_ALIAS_ADDR
- *
- * With this option enabled, zones with alloc_size <= PAGE_SIZE allocate
- * a virtual page from the zone_map, but before zcram-ing the allocated memory
- * into the zone, the page is translated to use the alias address of the page
- * in the static kernel region. zone_gc reverses that translation when
- * scanning the freelist to collect free pages so that it can look up the page
- * in the zone_page_table, and free it to kmem_free.
- *
- * The static kernel region is a flat 1:1 mapping of physical memory passed
- * to xnu by the booter. It is mapped to the range:
- * [gVirtBase, gVirtBase + gPhysSize]
- *
- * Accessing memory via the static kernel region is faster due to the
- * entire region being mapped via large pages, cutting down
- * on TLB misses.
- *
- * zinit favors using PAGE_SIZE backing allocations for a zone unless it would
- * waste more than 10% space to use a single page, in order to take advantage
- * of the speed benefit for as many zones as possible.
- *
- * Zones with > PAGE_SIZE allocations can't take advantage of this
- * because kernel_memory_allocate doesn't give out physically contiguous pages.
- *
- * zone_virtual_addr()
- *  - translates an address from the static kernel region to the zone_map
- *  - returns the same address if it's not from the static kernel region
- * It relies on the fact that a physical page mapped to the
- * zone_map is not mapped anywhere else (except the static kernel region).
- *
- * zone_alias_addr()
- *  - translates a virtual memory address from the zone_map to the
- *    corresponding address in the static kernel region
+ * Callout to jetsam. If pid is -1, we wake up the memorystatus thread to do asynchronous kills.
+ * For any other pid we try to kill that process synchronously.
+ */
+extern boolean_t memorystatus_kill_on_zone_map_exhaustion(pid_t pid);
+
+extern zone_t vm_map_entry_zone;
+extern zone_t vm_object_zone;
+extern vm_offset_t kmapoff_kaddr;
+extern unsigned int kmapoff_pgcnt;
+extern unsigned int stack_total;
+extern unsigned long long stack_allocs;
+
+/*
+ * The max # of elements in a chunk should fit into
+ * zone_page_metadata.free_count (uint16_t).
  *
+ * Update this if the type of free_count changes.
  */
+#define ZONE_CHUNK_MAXELEMENTS  (UINT16_MAX)
 
-#if     !ZONE_ALIAS_ADDR
-#define from_zone_map(addr, size) \
-        ((vm_offset_t)(addr)             >= zone_map_min_address && \
-        ((vm_offset_t)(addr) + size - 1) <  zone_map_max_address )
+#define ZONE_PAGECOUNT_BITS     14
+
+/* Zone elements must fit both a next pointer and a backup pointer */
+#define ZONE_MIN_ELEM_SIZE      (2 * sizeof(vm_offset_t))
+#define ZONE_MAX_ALLOC_SIZE     (32 * 1024)
+
+/* per-cpu zones are special because of counters */
+#define ZONE_MIN_PCPU_ELEM_SIZE (1 * sizeof(vm_offset_t))
+
+struct zone_map_range {
+       vm_offset_t min_address;
+       vm_offset_t max_address;
+};
+
+struct zone_page_metadata {
+       /* The index of the zone this metadata page belongs to */
+       zone_id_t       zm_index;
+
+       /*
+        * zm_secondary_page == 0: number of pages in this run
+        * zm_secondary_page == 1: offset to the chunk start
+        */
+       uint16_t        zm_page_count : ZONE_PAGECOUNT_BITS;
+
+       /* Whether this page is part of a chunk run */
+       uint16_t        zm_percpu : 1;
+       uint16_t        zm_secondary_page : 1;
+
+       /*
+        * The start of the freelist can be maintained as a 16-bit
+        * offset instead of a pointer because the free elements would
+        * be at max ZONE_MAX_ALLOC_SIZE bytes away from the start
+        * of the allocation chunk.
+        *
+        * Offset from start of the allocation chunk to free element
+        * list head.
+        */
+       uint16_t        zm_freelist_offs;
+
+       /*
+        * zm_secondary_page == 0: number of allocated elements in the chunk
+        * zm_secondary_page == 1: unused
+        *
+        * PAGE_METADATA_EMPTY_FREELIST indicates an empty freelist
+        */
+       uint16_t        zm_alloc_count;
+#define PAGE_METADATA_EMPTY_FREELIST  UINT16_MAX
+
+       zone_pva_t      zm_page_next;
+       zone_pva_t      zm_page_prev;
+
+       /*
+        * This is only for the sake of debuggers
+        */
+#define ZONE_FOREIGN_COOKIE           0x123456789abcdef
+       uint64_t        zm_foreign_cookie[];
+};
+
+
+/* Align elements that use the zone page list to 32 byte boundaries. */
+#define ZONE_PAGE_FIRST_OFFSET(kind)  ((kind) == ZONE_ADDR_NATIVE ? 0 : 32)
+
+static_assert(sizeof(struct zone_page_metadata) == 16, "validate packing");
+
+static __security_const_late struct {
+       struct zone_map_range      zi_map_range;
+       struct zone_map_range      zi_general_range;
+       struct zone_map_range      zi_meta_range;
+       struct zone_map_range      zi_foreign_range;
+
+       /*
+        * The metadata lives within the zi_meta_range address range.
+        *
+        * The correct formula to find a metadata index is:
+        *     absolute_page_index - page_index(zi_meta_range.min_address)
+        *
+        * And then this index is used to dereference zi_meta_range.min_address
+        * as a `struct zone_page_metadata` array.
+        *
+        * To avoid doing that substraction all the time in the various fast-paths,
+        * zi_array_base is offset by `page_index(zi_meta_range.min_address)`
+        * to avoid redoing that math all the time.
+        */
+       struct zone_page_metadata *zi_array_base;
+} zone_info;
+
+/*
+ *     The zone_locks_grp allows for collecting lock statistics.
+ *     All locks are associated to this group in zinit.
+ *     Look at tools/lockstat for debugging lock contention.
+ */
+LCK_GRP_DECLARE(zone_locks_grp, "zone_locks");
+LCK_MTX_EARLY_DECLARE(zone_metadata_region_lck, &zone_locks_grp);
+
+/*
+ *     Exclude more than one concurrent garbage collection
+ */
+LCK_GRP_DECLARE(zone_gc_lck_grp, "zone_gc");
+LCK_MTX_EARLY_DECLARE(zone_gc_lock, &zone_gc_lck_grp);
+
+boolean_t panic_include_zprint = FALSE;
+mach_memory_info_t *panic_kext_memory_info = NULL;
+vm_size_t panic_kext_memory_size = 0;
+
+/*
+ *      Protects zone_array, num_zones, num_zones_in_use, and
+ *      zone_destroyed_bitmap
+ */
+static SIMPLE_LOCK_DECLARE(all_zones_lock, 0);
+static unsigned int     num_zones_in_use;
+unsigned int _Atomic    num_zones;
+SECURITY_READ_ONLY_LATE(unsigned int) zone_view_count;
+
+#if KASAN_ZALLOC
+#define MAX_ZONES       566
+#else /* !KASAN_ZALLOC */
+#define MAX_ZONES       402
+#endif/* !KASAN_ZALLOC */
+struct zone             zone_array[MAX_ZONES];
+
+/* Initialized in zone_bootstrap(), how many "copies" the per-cpu system does */
+static SECURITY_READ_ONLY_LATE(unsigned) zpercpu_early_count;
+
+/* Used to keep track of destroyed slots in the zone_array */
+static bitmap_t zone_destroyed_bitmap[BITMAP_LEN(MAX_ZONES)];
+
+/* number of pages used by all zones */
+static long _Atomic zones_phys_page_count;
+
+/* number of zone mapped pages used by all zones */
+static long _Atomic zones_phys_page_mapped_count;
+
+/*
+ * Turn ZSECURITY_OPTIONS_STRICT_IOKIT_FREE off on x86 so as not
+ * not break third party kexts that haven't yet been recompiled
+ * to use the new iokit macros.
+ */
+#if XNU_TARGET_OS_OSX && __x86_64__
+#define ZSECURITY_OPTIONS_STRICT_IOKIT_FREE_DEFAULT 0
 #else
-#define from_zone_map(addr, size) \
-        ((vm_offset_t)(zone_virtual_addr((vm_map_address_t)(uintptr_t)addr))            >= zone_map_min_address && \
-        ((vm_offset_t)(zone_virtual_addr((vm_map_address_t)(uintptr_t)addr)) + size -1) <  zone_map_max_address )
+#define ZSECURITY_OPTIONS_STRICT_IOKIT_FREE_DEFAULT \
+  ZSECURITY_OPTIONS_STRICT_IOKIT_FREE
+#endif
+
+#define ZSECURITY_DEFAULT ( \
+               ZSECURITY_OPTIONS_SEQUESTER | \
+               ZSECURITY_OPTIONS_SUBMAP_USER_DATA | \
+               ZSECURITY_OPTIONS_SEQUESTER_KEXT_KALLOC | \
+               ZSECURITY_OPTIONS_STRICT_IOKIT_FREE_DEFAULT | \
+               0)
+TUNABLE(zone_security_options_t, zsecurity_options, "zs", ZSECURITY_DEFAULT);
+
+#if VM_MAX_TAG_ZONES
+/* enable tags for zones that ask for it */
+TUNABLE(bool, zone_tagging_on, "-zt", false);
+#endif /* VM_MAX_TAG_ZONES */
+
+#if DEBUG || DEVELOPMENT
+TUNABLE(bool, zalloc_disable_copyio_check, "-no-copyio-zalloc-check", false);
+__options_decl(zalloc_debug_t, uint32_t, {
+       ZALLOC_DEBUG_ZONEGC     = 0x00000001,
+       ZALLOC_DEBUG_ZCRAM      = 0x00000002,
+});
+
+TUNABLE(zalloc_debug_t, zalloc_debug, "zalloc_debug", 0);
+#endif /* DEBUG || DEVELOPMENT */
+#if CONFIG_ZLEAKS
+/* Making pointer scanning leaks detection possible for all zones */
+TUNABLE(bool, zone_leaks_scan_enable, "-zl", false);
+#else
+#define zone_leaks_scan_enable false
 #endif
 
+/*
+ * Async allocation of zones
+ * This mechanism allows for bootstrapping an empty zone which is setup with
+ * non-blocking flags. The first call to zalloc_noblock() will kick off a thread_call
+ * to zalloc_async. We perform a zalloc() (which may block) and then an immediate free.
+ * This will prime the zone for the next use.
+ *
+ * Currently the thread_callout function (zalloc_async) will loop through all zones
+ * looking for any zone with async_pending set and do the work for it.
+ *
+ * NOTE: If the calling thread for zalloc_noblock is lower priority than thread_call,
+ * then zalloc_noblock to an empty zone may succeed.
+ */
+static void zalloc_async(thread_call_param_t p0, thread_call_param_t p1);
+static thread_call_data_t call_async_alloc;
+static void zcram_and_lock(zone_t zone, vm_offset_t newmem, vm_size_t size);
+
 /*
  * Zone Corruption Debugging
  *
- * We use three techniques to detect modification of a zone element
+ * We use four techniques to detect modification of a zone element
  * after it's been freed.
  *
  * (1) Check the freelist next pointer for sanity.
  *     no part of the element has been modified while it was on the freelist.
  *     This will also help catch read-after-frees, as code will now dereference
  *     0xdeadbeef instead of a valid but freed pointer.
+ * (4) If the zfree_clear_mem flag is set clear the element on free and
+ *     assert that it is still clear when alloc-ed.
  *
  * (1) and (2) occur for every allocation and free to a zone.
  * This is done to make it slightly more difficult for an attacker to
  * manipulate the freelist to behave in a specific way.
  *
- * Poisoning (3) occurs periodically for every N frees (counted per-zone)
- * and on every free for zones smaller than a cacheline.  If -zp
- * is passed as a boot arg, poisoning occurs for every free.
+ * Poisoning (3) occurs periodically for every N frees (counted per-zone).
+ * If -zp is passed as a boot arg, poisoning occurs for every free.
+ *
+ * Zeroing (4) is done for those zones that pass the ZC_ZFREE_CLEARMEM
+ * flag on creation or if the element size is less than one cacheline.
  *
  * Performance slowdown is inversely proportional to the frequency of poisoning,
  * with a 4-5% hit around N=1, down to ~0.3% at N=16 and just "noise" at N=32
  *
  */
 
-/* Returns TRUE if we rolled over the counter at factor */
-static inline boolean_t
-sample_counter(volatile uint32_t * count_p, uint32_t factor)
-{
-       uint32_t old_count, new_count;
-       boolean_t rolled_over;
+#define ZP_DEFAULT_SAMPLING_FACTOR 16
+#define ZP_DEFAULT_SCALE_FACTOR 4
 
-       do {
-               new_count = old_count = *count_p;
+/*
+ * set by zp-factor=N boot arg
+ *
+ * A zp_factor of 0 indicates zone poisoning is disabled and can also be set by
+ * passing the -no-zp boot-arg.
+ *
+ * A zp_factor of 1 indicates zone poisoning is on for all elements and can be
+ * set by passing the -zp boot-arg.
+ */
+static TUNABLE(uint32_t, zp_factor, "zp-factor", ZP_DEFAULT_SAMPLING_FACTOR);
 
-               if (++new_count >= factor) {
-                       rolled_over = TRUE;
-                       new_count = 0;
-               } else {
-                       rolled_over = FALSE;
-               }
+/* set by zp-scale=N boot arg, scales zp_factor by zone size */
+static TUNABLE(uint32_t, zp_scale, "zp-scale", ZP_DEFAULT_SCALE_FACTOR);
 
-       } while (!OSCompareAndSwap(old_count, new_count, count_p));
+/* initialized to a per-boot random value in zp_bootstrap */
+static SECURITY_READ_ONLY_LATE(uintptr_t) zp_poisoned_cookie;
+static SECURITY_READ_ONLY_LATE(uintptr_t) zp_nopoison_cookie;
+static SECURITY_READ_ONLY_LATE(uintptr_t) zp_min_size;
+static SECURITY_READ_ONLY_LATE(uint64_t) zone_phys_mapped_max;
 
-       return rolled_over;
-}
+static SECURITY_READ_ONLY_LATE(vm_map_t) zone_submaps[Z_SUBMAP_IDX_COUNT];
+static SECURITY_READ_ONLY_LATE(uint32_t) zone_last_submap_idx;
 
-#if defined(__LP64__)
-#define ZP_POISON       0xdeadbeefdeadbeef
-#else
-#define ZP_POISON       0xdeadbeef
-#endif
+static struct bool_gen zone_bool_gen;
+static zone_t          zone_find_largest(void);
+static void            zone_drop_free_elements(zone_t z);
 
-#define ZP_DEFAULT_SAMPLING_FACTOR 16
-#define ZP_DEFAULT_SCALE_FACTOR 4
+#define submap_for_zone(z) zone_submaps[(z)->submap_idx]
+#define MAX_SUBMAP_NAME                16
+
+/* Globals for random boolean generator for elements in free list */
+#define MAX_ENTROPY_PER_ZCRAM           4
 
+#if CONFIG_ZCACHE
 /*
- *  A zp_factor of 0 indicates zone poisoning is disabled,
- *  however, we still poison zones smaller than zp_tiny_zone_limit (a cacheline).
- *  Passing the -no-zp boot-arg disables even this behavior.
- *  In all cases, we record and check the integrity of a backup pointer.
+ * Specifies a single zone to enable CPU caching for.
+ * Can be set using boot-args: zcc_enable_for_zone_name=<zone>
  */
+static char cache_zone_name[MAX_ZONE_NAME];
+static TUNABLE(bool, zcc_kalloc, "zcc_kalloc", false);
+
+__header_always_inline bool
+zone_caching_enabled(zone_t z)
+{
+       return z->zcache.zcc_depot != NULL;
+}
+#else
+__header_always_inline bool
+zone_caching_enabled(zone_t z __unused)
+{
+       return false;
+}
+#endif /* CONFIG_ZCACHE */
 
-/* set by zp-factor=N boot arg, zero indicates non-tiny poisoning disabled */
-uint32_t        zp_factor               = 0;
+#pragma mark Zone metadata
 
-/* set by zp-scale=N boot arg, scales zp_factor by zone size */
-uint32_t        zp_scale                = 0;
+__enum_closed_decl(zone_addr_kind_t, bool, {
+       ZONE_ADDR_NATIVE,
+       ZONE_ADDR_FOREIGN,
+});
 
-/* set in zp_init, zero indicates -no-zp boot-arg */
-vm_size_t       zp_tiny_zone_limit      = 0;
+static inline zone_id_t
+zone_index(zone_t z)
+{
+       return (zone_id_t)(z - zone_array);
+}
 
-/* initialized to a per-boot random value in zp_init */
-uintptr_t       zp_poisoned_cookie      = 0;
-uintptr_t       zp_nopoison_cookie      = 0;
+static inline bool
+zone_has_index(zone_t z, zone_id_t zid)
+{
+       return zone_array + zid == z;
+}
 
+static inline vm_size_t
+zone_elem_count(zone_t zone, vm_size_t alloc_size, zone_addr_kind_t kind)
+{
+       if (kind == ZONE_ADDR_NATIVE) {
+               if (zone->percpu) {
+                       return PAGE_SIZE / zone_elem_size(zone);
+               }
+               return alloc_size / zone_elem_size(zone);
+       } else {
+               assert(alloc_size == PAGE_SIZE);
+               return (PAGE_SIZE - ZONE_PAGE_FIRST_OFFSET(kind)) / zone_elem_size(zone);
+       }
+}
 
-/*
- * initialize zone poisoning
- * called from zone_bootstrap before any allocations are made from zalloc
- */
-static inline void
-zp_init(void)
+__abortlike
+static void
+zone_metadata_corruption(zone_t zone, struct zone_page_metadata *meta,
+    const char *kind)
 {
-       char temp_buf[16];
+       panic("zone metadata corruption: %s (meta %p, zone %s%s)",
+           kind, meta, zone_heap_name(zone), zone->z_name);
+}
 
-       /*
-        * Initialize backup pointer random cookie for poisoned elements
-        * Try not to call early_random() back to back, it may return
-        * the same value if mach_absolute_time doesn't have sufficient time
-        * to tick over between calls.  <rdar://problem/11597395>
-        * (This is only a problem on embedded devices)
-        */
-       zp_poisoned_cookie = (uintptr_t) early_random();
+__abortlike
+static void
+zone_invalid_element_addr_panic(zone_t zone, vm_offset_t addr)
+{
+       panic("zone element pointer validation failed (addr: %p, zone %s%s)",
+           (void *)addr, zone_heap_name(zone), zone->z_name);
+}
 
-       /*
-        * Always poison zones smaller than a cacheline,
-        * because it's pretty close to free
-        */
-       ml_cpu_info_t cpu_info;
-       ml_cpu_get_info(&cpu_info);
-       zp_tiny_zone_limit = (vm_size_t) cpu_info.cache_line_size;
+__abortlike
+static void
+zone_page_metadata_index_confusion_panic(zone_t zone, vm_offset_t addr,
+    struct zone_page_metadata *meta)
+{
+       panic("%p not in the expected zone %s%s (%d != %d)",
+           (void *)addr, zone_heap_name(zone), zone->z_name,
+           meta->zm_index, zone_index(zone));
+}
 
-       zp_factor = ZP_DEFAULT_SAMPLING_FACTOR;
-       zp_scale  = ZP_DEFAULT_SCALE_FACTOR;
+__abortlike
+static void
+zone_page_metadata_native_queue_corruption(zone_t zone, zone_pva_t *queue)
+{
+       panic("foreign metadata index %d enqueued in native head %p from zone %s%s",
+           queue->packed_address, queue, zone_heap_name(zone),
+           zone->z_name);
+}
 
-       //TODO: Bigger permutation?
-       /*
-        * Permute the default factor +/- 1 to make it less predictable
-        * This adds or subtracts ~4 poisoned objects per 1000 frees.
-        */
-       if (zp_factor != 0) {
-               uint32_t rand_bits = early_random() & 0x3;
+__abortlike
+static void
+zone_page_metadata_list_corruption(zone_t zone, struct zone_page_metadata *meta)
+{
+       panic("metadata list corruption through element %p detected in zone %s%s",
+           meta, zone_heap_name(zone), zone->z_name);
+}
 
-               if (rand_bits == 0x1)
-                       zp_factor += 1;
-               else if (rand_bits == 0x2)
-                       zp_factor -= 1;
-               /* if 0x0 or 0x3, leave it alone */
-       }
+__abortlike
+static void
+zone_page_metadata_foreign_queue_corruption(zone_t zone, zone_pva_t *queue)
+{
+       panic("native metadata index %d enqueued in foreign head %p from zone %s%s",
+           queue->packed_address, queue, zone_heap_name(zone), zone->z_name);
+}
 
-       /* -zp: enable poisoning for every alloc and free */
-       if (PE_parse_boot_argn("-zp", temp_buf, sizeof(temp_buf))) {
-               zp_factor = 1;
-       }
+__abortlike
+static void
+zone_page_metadata_foreign_confusion_panic(zone_t zone, vm_offset_t addr)
+{
+       panic("manipulating foreign address %p in a native-only zone %s%s",
+           (void *)addr, zone_heap_name(zone), zone->z_name);
+}
 
-       /* -no-zp: disable poisoning completely even for tiny zones */
-       if (PE_parse_boot_argn("-no-zp", temp_buf, sizeof(temp_buf))) {
-               zp_factor          = 0;
-               zp_tiny_zone_limit = 0;
-               printf("Zone poisoning disabled\n");
-       }
+__abortlike __unused
+static void
+zone_invalid_foreign_addr_panic(zone_t zone, vm_offset_t addr)
+{
+       panic("addr %p being freed to foreign zone %s%s not from foreign range",
+           (void *)addr, zone_heap_name(zone), zone->z_name);
+}
 
-       /* zp-factor=XXXX: override how often to poison freed zone elements */
-       if (PE_parse_boot_argn("zp-factor", &zp_factor, sizeof(zp_factor))) {
-               printf("Zone poisoning factor override: %u\n", zp_factor);
-       }
+__abortlike
+static void
+zone_page_meta_accounting_panic(zone_t zone, struct zone_page_metadata *meta,
+    const char *kind)
+{
+       panic("accounting mismatch (%s) for zone %s%s, meta %p", kind,
+           zone_heap_name(zone), zone->z_name, meta);
+}
 
-       /* zp-scale=XXXX: override how much zone size scales zp-factor by */
-       if (PE_parse_boot_argn("zp-scale", &zp_scale, sizeof(zp_scale))) {
-               printf("Zone poisoning scale factor override: %u\n", zp_scale);
-       }
+__abortlike
+static void
+zone_accounting_panic(zone_t zone, const char *kind)
+{
+       panic("accounting mismatch (%s) for zone %s%s", kind,
+           zone_heap_name(zone), zone->z_name);
+}
 
-       /* Initialize backup pointer random cookie for unpoisoned elements */
-       zp_nopoison_cookie = (uintptr_t) early_random();
+__abortlike
+static void
+zone_nofail_panic(zone_t zone)
+{
+       panic("zalloc(Z_NOFAIL) can't be satisfied for zone %s%s (potential leak)",
+           zone_heap_name(zone), zone->z_name);
+}
 
-#if MACH_ASSERT
-       if (zp_poisoned_cookie == zp_nopoison_cookie)
-               panic("early_random() is broken: %p and %p are not random\n",
-                     (void *) zp_poisoned_cookie, (void *) zp_nopoison_cookie);
+#if __arm64__
+// <rdar://problem/48304934> arm64 doesn't use ldp when I'd expect it to
+#define zone_range_load(r, rmin, rmax) \
+       asm("ldp %[rmin], %[rmax], [%[range]]" \
+           : [rmin] "=r"(rmin), [rmax] "=r"(rmax) \
+           : [range] "r"(r))
+#else
+#define zone_range_load(r, rmin, rmax) \
+       ({ rmin = (r)->min_address; rmax = (r)->max_address; })
 #endif
 
-       /*
-        * Use the last bit in the backup pointer to hint poisoning state
-        * to backup_ptr_mismatch_panic. Valid zone pointers are aligned, so
-        * the low bits are zero.
-        */
-       zp_poisoned_cookie |=   (uintptr_t)0x1ULL;
-       zp_nopoison_cookie &= ~((uintptr_t)0x1ULL);
+__header_always_inline bool
+zone_range_contains(const struct zone_map_range *r, vm_offset_t addr, vm_offset_t size)
+{
+       vm_offset_t rmin, rmax;
 
-#if defined(__LP64__)
        /*
-        * Make backup pointers more obvious in GDB for 64 bit
-        * by making OxFFFFFF... ^ cookie = 0xFACADE...
-        * (0xFACADE = 0xFFFFFF ^ 0x053521)
-        * (0xC0FFEE = 0xFFFFFF ^ 0x3f0011)
-        * The high 3 bytes of a zone pointer are always 0xFFFFFF, and are checked
-        * by the sanity check, so it's OK for that part of the cookie to be predictable.
-        *
-        * TODO: Use #defines, xors, and shifts
+        * The `&` is not a typo: we really expect the check to pass,
+        * so encourage the compiler to eagerly load and test without branches
         */
+       zone_range_load(r, rmin, rmax);
+       return (addr >= rmin) & (addr + size >= rmin) & (addr + size <= rmax);
+}
 
-       zp_poisoned_cookie &= 0x000000FFFFFFFFFF;
-       zp_poisoned_cookie |= 0x0535210000000000; /* 0xFACADE */
+__header_always_inline vm_size_t
+zone_range_size(const struct zone_map_range *r)
+{
+       vm_offset_t rmin, rmax;
 
-       zp_nopoison_cookie &= 0x000000FFFFFFFFFF;
-       zp_nopoison_cookie |= 0x3f00110000000000; /* 0xC0FFEE */
-#endif
+       zone_range_load(r, rmin, rmax);
+       return rmax - rmin;
 }
 
-/* zone_map page count for page table structure */
-uint64_t zone_map_table_page_count = 0;
+#define from_zone_map(addr, size) \
+       zone_range_contains(&zone_info.zi_map_range, (vm_offset_t)(addr), size)
 
-/*
- * These macros are used to keep track of the number
- * of pages being used by the zone currently. The
- * z->page_count is protected by the zone lock.
- */
-#define ZONE_PAGE_COUNT_INCR(z, count)         \
-{                                              \
-       OSAddAtomic64(count, &(z->page_count)); \
-}
+#define from_general_submap(addr, size) \
+       zone_range_contains(&zone_info.zi_general_range, (vm_offset_t)(addr), size)
 
-#define ZONE_PAGE_COUNT_DECR(z, count)                 \
-{                                                      \
-       OSAddAtomic64(-count, &(z->page_count));        \
-}
+#define from_foreign_range(addr, size) \
+       zone_range_contains(&zone_info.zi_foreign_range, (vm_offset_t)(addr), size)
 
-/* for is_sane_zone_element and garbage collection */
+#define from_native_meta_map(addr) \
+       zone_range_contains(&zone_info.zi_meta_range, (vm_offset_t)(addr), \
+           sizeof(struct zone_page_metadata))
 
-vm_offset_t     zone_map_min_address = 0;  /* initialized in zone_init */
-vm_offset_t     zone_map_max_address = 0;
+#define zone_addr_kind(addr, size) \
+       (from_zone_map(addr, size) ? ZONE_ADDR_NATIVE : ZONE_ADDR_FOREIGN)
 
-/* Helpful for walking through a zone's free element list. */
-struct zone_free_element {
-       struct zone_free_element *next;
-       /* ... */
-       /* void *backup_ptr; */
-};
+__header_always_inline bool
+zone_pva_is_null(zone_pva_t page)
+{
+       return page.packed_address == 0;
+}
 
-struct zone_page_metadata {
-       queue_chain_t                           pages;
-       struct zone_free_element        *elements;
-       zone_t                                          zone;
-       uint16_t                                        alloc_count;
-       uint16_t                                        free_count;
-};
+__header_always_inline bool
+zone_pva_is_queue(zone_pva_t page)
+{
+       // actual kernel pages have the top bit set
+       return (int32_t)page.packed_address > 0;
+}
 
-/* The backup pointer is stored in the last pointer-sized location in an element. */
-static inline vm_offset_t *
-get_backup_ptr(vm_size_t  elem_size,
-               vm_offset_t *element)
+__header_always_inline bool
+zone_pva_is_equal(zone_pva_t pva1, zone_pva_t pva2)
 {
-       return (vm_offset_t *) ((vm_offset_t)element + elem_size - sizeof(vm_offset_t));
+       return pva1.packed_address == pva2.packed_address;
 }
 
-static inline struct zone_page_metadata *
-get_zone_page_metadata(struct zone_free_element *element)
+__header_always_inline void
+zone_queue_set_head(zone_t z, zone_pva_t queue, zone_pva_t oldv,
+    struct zone_page_metadata *meta)
 {
-       return (struct zone_page_metadata *)(trunc_page((vm_offset_t)element));
+       zone_pva_t *queue_head = &((zone_pva_t *)zone_array)[queue.packed_address];
+
+       if (!zone_pva_is_equal(*queue_head, oldv)) {
+               zone_page_metadata_list_corruption(z, meta);
+       }
+       *queue_head = meta->zm_page_next;
 }
 
-/*
- * Zone checking helper function.
- * A pointer that satisfies these conditions is OK to be a freelist next pointer
- * A pointer that doesn't satisfy these conditions indicates corruption
- */
-static inline boolean_t
-is_sane_zone_ptr(zone_t                zone,
-                 vm_offset_t   addr,
-                size_t         obj_size)
+__header_always_inline zone_pva_t
+zone_queue_encode(zone_pva_t *headp)
 {
-       /*  Must be aligned to pointer boundary */
-       if (__improbable((addr & (sizeof(vm_offset_t) - 1)) != 0))
-               return FALSE;
+       return (zone_pva_t){ (uint32_t)(headp - (zone_pva_t *)zone_array) };
+}
 
-       /*  Must be a kernel address */
-       if (__improbable(!pmap_kernel_va(addr)))
-               return FALSE;
+__header_always_inline zone_pva_t
+zone_pva_from_addr(vm_address_t addr)
+{
+       // cannot use atop() because we want to maintain the sign bit
+       return (zone_pva_t){ (uint32_t)((intptr_t)addr >> PAGE_SHIFT) };
+}
 
-       /*  Must be from zone map if the zone only uses memory from the zone_map */
-       /*
-        *  TODO: Remove the zone->collectable check when every
-        *  zone using foreign memory is properly tagged with allows_foreign
-        */
-       if (zone->collectable && !zone->allows_foreign) {
-#if ZONE_ALIAS_ADDR
-               /*
-                * If this address is in the static kernel region, it might be
-                * the alias address of a valid zone element.
-                * If we tried to find the zone_virtual_addr() of an invalid
-                * address in the static kernel region, it will panic, so don't 
-                * check addresses in this region.
-                *
-                * TODO: Use a safe variant of zone_virtual_addr to
-                *  make this check more accurate
-                *
-                * The static kernel region is mapped at:
-                * [gVirtBase, gVirtBase + gPhysSize]
-                */
-               if ((addr - gVirtBase) < gPhysSize)
-                       return TRUE;
-#endif
-               /*  check if addr is from zone map */
-               if (addr                 >= zone_map_min_address &&
-                  (addr + obj_size - 1) <  zone_map_max_address )
-                       return TRUE;
-
-               return FALSE;
-       }
-
-       return TRUE;
+__header_always_inline vm_address_t
+zone_pva_to_addr(zone_pva_t page)
+{
+       // cause sign extension so that we end up with the right address
+       return (vm_offset_t)(int32_t)page.packed_address << PAGE_SHIFT;
 }
 
-static inline boolean_t
-is_sane_zone_page_metadata(zone_t      zone,
-                          vm_offset_t  page_meta)
+__header_always_inline struct zone_page_metadata *
+zone_pva_to_meta(zone_pva_t page, zone_addr_kind_t kind)
 {
-       /* NULL page metadata structures are invalid */
-       if (page_meta == 0)
-               return FALSE;
-       return is_sane_zone_ptr(zone, page_meta, sizeof(struct zone_page_metadata));
+       if (kind == ZONE_ADDR_NATIVE) {
+               return &zone_info.zi_array_base[page.packed_address];
+       } else {
+               return (struct zone_page_metadata *)zone_pva_to_addr(page);
+       }
 }
 
-static inline boolean_t
-is_sane_zone_element(zone_t      zone,
-                     vm_offset_t addr)
+__header_always_inline zone_pva_t
+zone_pva_from_meta(struct zone_page_metadata *meta, zone_addr_kind_t kind)
 {
-       /*  NULL is OK because it indicates the tail of the list */
-       if (addr == 0)
-               return TRUE;
-       return is_sane_zone_ptr(zone, addr, zone->elem_size);
-}
-       
-/* Someone wrote to freed memory. */
-static inline void /* noreturn */
-zone_element_was_modified_panic(zone_t        zone,
-                                vm_offset_t   element,
-                                vm_offset_t   found,
-                                vm_offset_t   expected,
-                                vm_offset_t   offset)
-{
-       panic("a freed zone element has been modified in zone %s: expected %p but found %p, bits changed %p, at offset %d of %d in element %p, cookies %p %p",
-                        zone->zone_name,
-             (void *)   expected,
-             (void *)   found,
-             (void *)   (expected ^ found),
-             (uint32_t) offset,
-             (uint32_t) zone->elem_size,
-             (void *)   element,
-             (void *)   zp_nopoison_cookie,
-             (void *)   zp_poisoned_cookie);
+       if (kind == ZONE_ADDR_NATIVE) {
+               uint32_t index = (uint32_t)(meta - zone_info.zi_array_base);
+               return (zone_pva_t){ index };
+       } else {
+               return zone_pva_from_addr((vm_address_t)meta);
+       }
 }
 
-/*
- * The primary and backup pointers don't match.
- * Determine which one was likely the corrupted pointer, find out what it
- * probably should have been, and panic.
- * I would like to mark this as noreturn, but panic() isn't marked noreturn.
- */
-static void /* noreturn */
-backup_ptr_mismatch_panic(zone_t        zone,
-                          vm_offset_t   element,
-                          vm_offset_t   primary,
-                          vm_offset_t   backup)
+__header_always_inline struct zone_page_metadata *
+zone_meta_from_addr(vm_offset_t addr, zone_addr_kind_t kind)
 {
-       vm_offset_t likely_backup;
-
-       boolean_t   sane_backup;
-       boolean_t   sane_primary = is_sane_zone_element(zone, primary);
-       boolean_t   element_was_poisoned = (backup & 0x1) ? TRUE : FALSE;
-
-#if defined(__LP64__)
-       /* We can inspect the tag in the upper bits for additional confirmation */
-       if ((backup & 0xFFFFFF0000000000) == 0xFACADE0000000000)
-               element_was_poisoned = TRUE;
-       else if ((backup & 0xFFFFFF0000000000) == 0xC0FFEE0000000000)
-               element_was_poisoned = FALSE;
-#endif
-
-       if (element_was_poisoned) {
-               likely_backup = backup ^ zp_poisoned_cookie;
-               sane_backup = is_sane_zone_element(zone, likely_backup);
+       if (kind == ZONE_ADDR_NATIVE) {
+               return zone_pva_to_meta(zone_pva_from_addr(addr), kind);
        } else {
-               likely_backup = backup ^ zp_nopoison_cookie;
-               sane_backup = is_sane_zone_element(zone, likely_backup);
+               return (struct zone_page_metadata *)trunc_page(addr);
        }
+}
 
-       /* The primary is definitely the corrupted one */
-       if (!sane_primary && sane_backup)
-               zone_element_was_modified_panic(zone, element, primary, likely_backup, 0);
-
-       /* The backup is definitely the corrupted one */
-       if (sane_primary && !sane_backup)
-               zone_element_was_modified_panic(zone, element, backup,
-                                               (primary ^ (element_was_poisoned ? zp_poisoned_cookie : zp_nopoison_cookie)),
-                                               zone->elem_size - sizeof(vm_offset_t));
-
-       /*
-        * Not sure which is the corrupted one.
-        * It's less likely that the backup pointer was overwritten with
-        * ( (sane address) ^ (valid cookie) ), so we'll guess that the
-        * primary pointer has been overwritten with a sane but incorrect address.
-        */
-       if (sane_primary && sane_backup)
-               zone_element_was_modified_panic(zone, element, primary, likely_backup, 0);
+#define zone_native_meta_from_addr(addr) \
+       zone_meta_from_addr((vm_offset_t)(addr), ZONE_ADDR_NATIVE)
 
-       /* Neither are sane, so just guess. */
-       zone_element_was_modified_panic(zone, element, primary, likely_backup, 0);
+__header_always_inline vm_offset_t
+zone_meta_to_addr(struct zone_page_metadata *meta, zone_addr_kind_t kind)
+{
+       if (kind == ZONE_ADDR_NATIVE) {
+               return ptoa((int)(meta - zone_info.zi_array_base));
+       } else {
+               return (vm_offset_t)meta;
+       }
 }
 
-/*
- * Sets the next element of tail to elem.
- * elem can be NULL.
- * Preserves the poisoning state of the element.
- */
-static inline void
-append_zone_element(zone_t                    zone,
-                    struct zone_free_element *tail,
-                    struct zone_free_element *elem)
+__header_always_inline void
+zone_meta_queue_push(zone_t z, zone_pva_t *headp,
+    struct zone_page_metadata *meta, zone_addr_kind_t kind)
 {
-       vm_offset_t *backup = get_backup_ptr(zone->elem_size, (vm_offset_t *) tail);
+       zone_pva_t head = *headp;
+       zone_pva_t queue_pva = zone_queue_encode(headp);
+       struct zone_page_metadata *tmp;
+
+       meta->zm_page_next = head;
+       if (!zone_pva_is_null(head)) {
+               tmp = zone_pva_to_meta(head, kind);
+               if (!zone_pva_is_equal(tmp->zm_page_prev, queue_pva)) {
+                       zone_page_metadata_list_corruption(z, meta);
+               }
+               tmp->zm_page_prev = zone_pva_from_meta(meta, kind);
+       }
+       meta->zm_page_prev = queue_pva;
+       *headp = zone_pva_from_meta(meta, kind);
+}
 
-       vm_offset_t old_backup = *backup;
+__header_always_inline struct zone_page_metadata *
+zone_meta_queue_pop(zone_t z, zone_pva_t *headp, zone_addr_kind_t kind,
+    vm_offset_t *page_addrp)
+{
+       zone_pva_t head = *headp;
+       struct zone_page_metadata *meta = zone_pva_to_meta(head, kind);
+       vm_offset_t page_addr = zone_pva_to_addr(head);
+       struct zone_page_metadata *tmp;
 
-       vm_offset_t old_next = (vm_offset_t) tail->next;
-       vm_offset_t new_next = (vm_offset_t) elem;
+       if (kind == ZONE_ADDR_NATIVE && !from_native_meta_map(meta)) {
+               zone_page_metadata_native_queue_corruption(z, headp);
+       }
+       if (kind == ZONE_ADDR_FOREIGN && from_zone_map(meta, sizeof(*meta))) {
+               zone_page_metadata_foreign_queue_corruption(z, headp);
+       }
 
-       if      (old_next == (old_backup ^ zp_nopoison_cookie))
-               *backup = new_next ^ zp_nopoison_cookie;
-       else if (old_next == (old_backup ^ zp_poisoned_cookie))
-               *backup = new_next ^ zp_poisoned_cookie;
-       else
-               backup_ptr_mismatch_panic(zone,
-                                         (vm_offset_t) tail,
-                                         old_next,
-                                         old_backup);
+       if (!zone_pva_is_null(meta->zm_page_next)) {
+               tmp = zone_pva_to_meta(meta->zm_page_next, kind);
+               if (!zone_pva_is_equal(tmp->zm_page_prev, head)) {
+                       zone_page_metadata_list_corruption(z, meta);
+               }
+               tmp->zm_page_prev = meta->zm_page_prev;
+       }
+       *headp = meta->zm_page_next;
 
-       tail->next = elem;
+       *page_addrp = page_addr;
+       return meta;
 }
 
-
-/*
- * Insert a linked list of elements (delineated by head and tail) at the head of
- * the zone free list. Every element in the list being added has already gone
- * through append_zone_element, so their backup pointers are already
- * set properly.
- * Precondition: There should be no elements after tail
- */
-static inline void
-add_list_to_zone(zone_t                    zone,
-                 struct zone_free_element *head,
-                 struct zone_free_element *tail)
+__header_always_inline void
+zone_meta_requeue(zone_t z, zone_pva_t *headp,
+    struct zone_page_metadata *meta, zone_addr_kind_t kind)
 {
-       assert(tail->next == NULL);
-       assert(!zone->use_page_list);
+       zone_pva_t meta_pva = zone_pva_from_meta(meta, kind);
+       struct zone_page_metadata *tmp;
 
-       append_zone_element(zone, tail, zone->free_elements);
+       if (!zone_pva_is_null(meta->zm_page_next)) {
+               tmp = zone_pva_to_meta(meta->zm_page_next, kind);
+               if (!zone_pva_is_equal(tmp->zm_page_prev, meta_pva)) {
+                       zone_page_metadata_list_corruption(z, meta);
+               }
+               tmp->zm_page_prev = meta->zm_page_prev;
+       }
+       if (zone_pva_is_queue(meta->zm_page_prev)) {
+               zone_queue_set_head(z, meta->zm_page_prev, meta_pva, meta);
+       } else {
+               tmp = zone_pva_to_meta(meta->zm_page_prev, kind);
+               if (!zone_pva_is_equal(tmp->zm_page_next, meta_pva)) {
+                       zone_page_metadata_list_corruption(z, meta);
+               }
+               tmp->zm_page_next = meta->zm_page_next;
+       }
 
-       zone->free_elements = head;
+       zone_meta_queue_push(z, headp, meta, kind);
 }
 
-
 /*
- * Adds the element to the head of the zone's free list
- * Keeps a backup next-pointer at the end of the element
+ * Routine to populate a page backing metadata in the zone_metadata_region.
+ * Must be called without the zone lock held as it might potentially block.
  */
-static inline void
-free_to_zone(zone_t      zone,
-             vm_offset_t element,
-             boolean_t   poison)
+static void
+zone_meta_populate(struct zone_page_metadata *from, struct zone_page_metadata *to)
 {
-       vm_offset_t old_head;
-       struct zone_page_metadata *page_meta;
-
-       vm_offset_t *primary  = (vm_offset_t *) element;
-       vm_offset_t *backup   = get_backup_ptr(zone->elem_size, primary);
+       vm_offset_t page_addr = trunc_page(from);
 
-       if (zone->use_page_list) {
-               page_meta = get_zone_page_metadata((struct zone_free_element *)element);
-               assert(page_meta->zone == zone);
-               old_head = (vm_offset_t)page_meta->elements;
-       } else {
-               old_head = (vm_offset_t)zone->free_elements;
-       }
-
-#if MACH_ASSERT
-       if (__improbable(!is_sane_zone_element(zone, old_head)))
-               panic("zfree: invalid head pointer %p for freelist of zone %s\n",
-                     (void *) old_head, zone->zone_name);
+       for (; page_addr < (vm_offset_t)to; page_addr += PAGE_SIZE) {
+#if !KASAN_ZALLOC
+               /*
+                * This can race with another thread doing a populate on the same metadata
+                * page, where we see an updated pmap but unmapped KASan shadow, causing a
+                * fault in the shadow when we first access the metadata page. Avoid this
+                * by always synchronizing on the zone_metadata_region lock with KASan.
+                */
+               if (pmap_find_phys(kernel_pmap, page_addr)) {
+                       continue;
+               }
 #endif
 
-       if (__improbable(!is_sane_zone_element(zone, element)))
-               panic("zfree: freeing invalid pointer %p to zone %s\n",
-                     (void *) element, zone->zone_name);
+               for (;;) {
+                       kern_return_t ret = KERN_SUCCESS;
 
-       /*
-        * Always write a redundant next pointer
-        * So that it is more difficult to forge, xor it with a random cookie
-        * A poisoned element is indicated by using zp_poisoned_cookie
-        * instead of zp_nopoison_cookie
-        */
-
-       *backup = old_head ^ (poison ? zp_poisoned_cookie : zp_nopoison_cookie);
+                       /* All updates to the zone_metadata_region are done under the zone_metadata_region_lck */
+                       lck_mtx_lock(&zone_metadata_region_lck);
+                       if (0 == pmap_find_phys(kernel_pmap, page_addr)) {
+                               ret = kernel_memory_populate(kernel_map, page_addr,
+                                   PAGE_SIZE, KMA_NOPAGEWAIT | KMA_KOBJECT | KMA_ZERO,
+                                   VM_KERN_MEMORY_OSFMK);
+                       }
+                       lck_mtx_unlock(&zone_metadata_region_lck);
 
-       /* Insert this element at the head of the free list */
-       *primary             = old_head;
-       if (zone->use_page_list) {
-               page_meta->elements = (struct zone_free_element *)element;
-               page_meta->free_count++;
-               if (zone->allows_foreign && !from_zone_map(element, zone->elem_size)) {
-                       if (page_meta->free_count == 1) {
-                               /* first foreign element freed on page, move from all_used */
-                               remqueue((queue_entry_t)page_meta);
-                               enqueue_tail(&zone->pages.any_free_foreign, (queue_entry_t)page_meta);
-                       } else {
-                               /* no other list transitions */
+                       if (ret == KERN_SUCCESS) {
+                               break;
                        }
-               } else if (page_meta->free_count == page_meta->alloc_count) {
-                       /* whether the page was on the intermediate or all_used, queue, move it to free */
-                       remqueue((queue_entry_t)page_meta);
-                       enqueue_tail(&zone->pages.all_free, (queue_entry_t)page_meta);
-               } else if (page_meta->free_count == 1) {
-                       /* first free element on page, move from all_used */
-                       remqueue((queue_entry_t)page_meta);
-                       enqueue_tail(&zone->pages.intermediate, (queue_entry_t)page_meta);
+
+                       /*
+                        * We can't pass KMA_NOPAGEWAIT under a global lock as it leads
+                        * to bad system deadlocks, so if the allocation failed,
+                        * we need to do the VM_PAGE_WAIT() outside of the lock.
+                        */
+                       VM_PAGE_WAIT();
                }
-       } else {
-               zone->free_elements = (struct zone_free_element *)element;
        }
-       zone->count--;
-       zone->countfree++;
 }
 
-
-/*
- * Removes an element from the zone's free list, returning 0 if the free list is empty.
- * Verifies that the next-pointer and backup next-pointer are intact,
- * and verifies that a poisoned element hasn't been modified.
- */
-static inline vm_offset_t
-try_alloc_from_zone(zone_t zone,
-                    boolean_t* check_poison)
+static inline bool
+zone_allocated_element_offset_is_valid(zone_t zone, vm_offset_t addr,
+    vm_offset_t page, zone_addr_kind_t kind)
 {
-       vm_offset_t  element;
-       struct zone_page_metadata *page_meta;
+       vm_offset_t offs = addr - page - ZONE_PAGE_FIRST_OFFSET(kind);
+       vm_offset_t esize = zone_elem_size(zone);
 
-       *check_poison = FALSE;
-
-       /* if zone is empty, bail */
-       if (zone->use_page_list) {
-               if (zone->allows_foreign && !queue_empty(&zone->pages.any_free_foreign))
-                       page_meta = (struct zone_page_metadata *)queue_first(&zone->pages.any_free_foreign);
-               else if (!queue_empty(&zone->pages.intermediate))
-                       page_meta = (struct zone_page_metadata *)queue_first(&zone->pages.intermediate);
-               else if (!queue_empty(&zone->pages.all_free))
-                       page_meta = (struct zone_page_metadata *)queue_first(&zone->pages.all_free);
-               else {
-                       return 0;
-               }
-
-               /* Check if page_meta passes is_sane_zone_element */
-               if (__improbable(!is_sane_zone_page_metadata(zone, (vm_offset_t)page_meta)))
-                       panic("zalloc: invalid metadata structure %p for freelist of zone %s\n",
-                               (void *) page_meta, zone->zone_name);
-               assert(page_meta->zone == zone);
-               element = (vm_offset_t)page_meta->elements;
+       if (esize & (esize - 1)) { /* not a power of 2 */
+               return (offs % esize) == 0;
        } else {
-               if (zone->free_elements == NULL)
-                       return 0;
-
-               element = (vm_offset_t)zone->free_elements;
+               return (offs & (esize - 1)) == 0;
        }
+}
 
-#if MACH_ASSERT
-       if (__improbable(!is_sane_zone_element(zone, element)))
-               panic("zfree: invalid head pointer %p for freelist of zone %s\n",
-                     (void *) element, zone->zone_name);
+__attribute__((always_inline))
+static struct zone_page_metadata *
+zone_allocated_element_resolve(zone_t zone, vm_offset_t addr,
+    vm_offset_t *pagep, zone_addr_kind_t *kindp)
+{
+       struct zone_page_metadata *meta;
+       zone_addr_kind_t kind;
+       vm_offset_t page;
+       vm_offset_t esize = zone_elem_size(zone);
+
+       kind = zone_addr_kind(addr, esize);
+       page = trunc_page(addr);
+       meta = zone_meta_from_addr(addr, kind);
+
+       if (kind == ZONE_ADDR_NATIVE) {
+               if (meta->zm_secondary_page) {
+                       if (meta->zm_percpu) {
+                               zone_invalid_element_addr_panic(zone, addr);
+                       }
+                       page -= ptoa(meta->zm_page_count);
+                       meta -= meta->zm_page_count;
+               }
+       } else if (!zone->allows_foreign) {
+               zone_page_metadata_foreign_confusion_panic(zone, addr);
+#if __LP64__
+       } else if (!from_foreign_range(addr, esize)) {
+               zone_invalid_foreign_addr_panic(zone, addr);
+#else
+       } else if (!pmap_kernel_va(addr)) {
+               zone_invalid_element_addr_panic(zone, addr);
 #endif
+       }
 
-       vm_offset_t *primary = (vm_offset_t *) element;
-       vm_offset_t *backup  = get_backup_ptr(zone->elem_size, primary);
+       if (!zone_allocated_element_offset_is_valid(zone, addr, page, kind)) {
+               zone_invalid_element_addr_panic(zone, addr);
+       }
 
-       vm_offset_t  next_element          = *primary;
-       vm_offset_t  next_element_backup   = *backup;
+       if (!zone_has_index(zone, meta->zm_index)) {
+               zone_page_metadata_index_confusion_panic(zone, addr, meta);
+       }
 
-       /*
-        * backup_ptr_mismatch_panic will determine what next_element
-        * should have been, and print it appropriately
-        */
-       if (__improbable(!is_sane_zone_element(zone, next_element)))
-               backup_ptr_mismatch_panic(zone, element, next_element, next_element_backup);
+       if (kindp) {
+               *kindp = kind;
+       }
+       if (pagep) {
+               *pagep = page;
+       }
+       return meta;
+}
 
-       /* Check the backup pointer for the regular cookie */
-       if (__improbable(next_element != (next_element_backup ^ zp_nopoison_cookie))) {
+__attribute__((always_inline))
+void
+zone_allocated_element_validate(zone_t zone, vm_offset_t addr)
+{
+       zone_allocated_element_resolve(zone, addr, NULL, NULL);
+}
 
-               /* Check for the poisoned cookie instead */
-               if (__improbable(next_element != (next_element_backup ^ zp_poisoned_cookie)))
-                       /* Neither cookie is valid, corruption has occurred */
-                       backup_ptr_mismatch_panic(zone, element, next_element, next_element_backup);
+__header_always_inline vm_offset_t
+zone_page_meta_get_freelist(zone_t zone, struct zone_page_metadata *meta,
+    vm_offset_t page)
+{
+       assert(!meta->zm_secondary_page);
+       if (meta->zm_freelist_offs == PAGE_METADATA_EMPTY_FREELIST) {
+               return 0;
+       }
 
-               /*
-                * Element was marked as poisoned, so check its integrity before using it.
-                */
-               *check_poison = TRUE;
+       vm_size_t size = ptoa(meta->zm_percpu ? 1 : meta->zm_page_count);
+       if (meta->zm_freelist_offs + zone_elem_size(zone) > size) {
+               zone_metadata_corruption(zone, meta, "freelist corruption");
        }
 
-       if (zone->use_page_list) {
-                       
-               /* Make sure the page_meta is at the correct offset from the start of page */
-               if (__improbable(page_meta != get_zone_page_metadata((struct zone_free_element *)element)))
-                       panic("zalloc: metadata located at incorrect location on page of zone %s\n",
-                               zone->zone_name);
+       return page + meta->zm_freelist_offs;
+}
 
-               /* Make sure next_element belongs to the same page as page_meta */
-               if (next_element) {
-                       if (__improbable(page_meta != get_zone_page_metadata((struct zone_free_element *)next_element)))
-                               panic("zalloc: next element pointer %p for element %p points to invalid element for zone %s\n",
-                                       (void *)next_element, (void *)element, zone->zone_name);
-               }
+__header_always_inline void
+zone_page_meta_set_freelist(struct zone_page_metadata *meta,
+    vm_offset_t page, vm_offset_t addr)
+{
+       assert(!meta->zm_secondary_page);
+       if (addr) {
+               meta->zm_freelist_offs = (uint16_t)(addr - page);
+       } else {
+               meta->zm_freelist_offs = PAGE_METADATA_EMPTY_FREELIST;
        }
+}
 
-       /* Remove this element from the free list */
-       if (zone->use_page_list) {
-
-               page_meta->elements = (struct zone_free_element *)next_element;
-               page_meta->free_count--;
+static bool
+zone_page_meta_is_sane_element(zone_t zone, struct zone_page_metadata *meta,
+    vm_offset_t page, vm_offset_t element, zone_addr_kind_t kind)
+{
+       if (element == 0) {
+               /* ends of the freelist are NULL */
+               return true;
+       }
+       if (element < page + ZONE_PAGE_FIRST_OFFSET(kind)) {
+               return false;
+       }
+       vm_size_t size = ptoa(meta->zm_percpu ? 1 : meta->zm_page_count);
+       if (element > page + size - zone_elem_size(zone)) {
+               return false;
+       }
+       return true;
+}
 
-               if (zone->allows_foreign && !from_zone_map(element, zone->elem_size)) {
-                       if (page_meta->free_count == 0) {
-                               /* move to all used */
-                               remqueue((queue_entry_t)page_meta);
-                               enqueue_tail(&zone->pages.all_used, (queue_entry_t)page_meta);
-                       } else {
-                               /* no other list transitions */
-                       }
-               } else if (page_meta->free_count == 0) {
-                       /* remove from intermediate or free, move to all_used */
-                       remqueue((queue_entry_t)page_meta);
-                       enqueue_tail(&zone->pages.all_used, (queue_entry_t)page_meta);
-               } else if (page_meta->alloc_count == page_meta->free_count + 1) {
-                       /* remove from free, move to intermediate */
-                       remqueue((queue_entry_t)page_meta);
-                       enqueue_tail(&zone->pages.intermediate, (queue_entry_t)page_meta);
+/* Routine to get the size of a zone allocated address.
+ * If the address doesnt belong to the zone maps, returns 0.
+ */
+vm_size_t
+zone_element_size(void *addr, zone_t *z)
+{
+       struct zone_page_metadata *meta;
+       struct zone *src_zone;
+
+       if (from_zone_map(addr, sizeof(void *))) {
+               meta = zone_native_meta_from_addr(addr);
+               src_zone = &zone_array[meta->zm_index];
+               if (z) {
+                       *z = src_zone;
+               }
+               return zone_elem_size(src_zone);
+       }
+#if CONFIG_GZALLOC
+       if (__improbable(gzalloc_enabled())) {
+               vm_size_t gzsize;
+               if (gzalloc_element_size(addr, z, &gzsize)) {
+                       return gzsize;
                }
-       } else {
-               zone->free_elements = (struct zone_free_element *)next_element;
        }
-       zone->countfree--;
-       zone->count++;
-       zone->sum_count++;
+#endif /* CONFIG_GZALLOC */
 
-       return element;
+       return 0;
 }
 
+/* This function just formats the reason for the panics by redoing the checks */
+__abortlike
+static void
+zone_require_panic(zone_t zone, void *addr)
+{
+       uint32_t zindex;
+       zone_t other;
 
-/*
- * End of zone poisoning
- */
-
-/*
- * Fake zones for things that want to report via zprint but are not actually zones.
- */
-struct fake_zone_info {
-       const char* name;
-       void (*init)(int);
-       void (*query)(int *,
-                    vm_size_t *, vm_size_t *, vm_size_t *, vm_size_t *,
-                     uint64_t *, int *, int *, int *);
-};
+       if (!from_zone_map(addr, zone_elem_size(zone))) {
+               panic("zone_require failed: address not in a zone (addr: %p)", addr);
+       }
 
-static const struct fake_zone_info fake_zones[] = {
-};
-static const unsigned int num_fake_zones =
-       sizeof (fake_zones) / sizeof (fake_zones[0]);
+       zindex = zone_native_meta_from_addr(addr)->zm_index;
+       other = &zone_array[zindex];
+       if (zindex >= os_atomic_load(&num_zones, relaxed) || !other->z_self) {
+               panic("zone_require failed: invalid zone index %d "
+                   "(addr: %p, expected: %s%s)", zindex,
+                   addr, zone_heap_name(zone), zone->z_name);
+       } else {
+               panic("zone_require failed: address in unexpected zone id %d (%s%s) "
+                   "(addr: %p, expected: %s%s)",
+                   zindex, zone_heap_name(other), other->z_name,
+                   addr, zone_heap_name(zone), zone->z_name);
+       }
+}
 
-/*
- * Zone info options
- */
-boolean_t zinfo_per_task = FALSE;              /* enabled by -zinfop in boot-args */
-#define ZINFO_SLOTS 200                                /* for now */
-#define ZONES_MAX (ZINFO_SLOTS - num_fake_zones - 1)
+__abortlike
+static void
+zone_id_require_panic(zone_id_t zid, void *addr)
+{
+       zone_require_panic(&zone_array[zid], addr);
+}
 
 /*
- * Support for garbage collection of unused zone pages
+ * Routines to panic if a pointer is not mapped to an expected zone.
+ * This can be used as a means of pinning an object to the zone it is expected
+ * to be a part of.  Causes a panic if the address does not belong to any
+ * specified zone, does not belong to any zone, has been freed and therefore
+ * unmapped from the zone, or the pointer contains an uninitialized value that
+ * does not belong to any zone.
  *
- * The kernel virtually allocates the "zone map" submap of the kernel
- * map. When an individual zone needs more storage, memory is allocated
- * out of the zone map, and the two-level "zone_page_table" is
- * on-demand expanded so that it has entries for those pages.
- * zone_page_init()/zone_page_alloc() initialize "alloc_count"
- * to the number of zone elements that occupy the zone page (which may
- * be a minimum of 1, including if a zone element spans multiple
- * pages).
- *
- * Asynchronously, the zone_gc() logic attempts to walk zone free
- * lists to see if all the elements on a zone page are free. If
- * "collect_count" (which it increments during the scan) matches
- * "alloc_count", the zone page is a candidate for collection and the
- * physical page is returned to the VM system. During this process, the
- * first word of the zone page is re-used to maintain a linked list of
- * to-be-collected zone pages.
+ * Note that this can only work with collectable zones without foreign pages.
  */
-typedef uint32_t zone_page_index_t;
-#define ZONE_PAGE_INDEX_INVALID ((zone_page_index_t)0xFFFFFFFFU)
+void
+zone_require(zone_t zone, void *addr)
+{
+       if (__probable(from_general_submap(addr, zone_elem_size(zone)) &&
+           (zone_has_index(zone, zone_native_meta_from_addr(addr)->zm_index)))) {
+               return;
+       }
+#if CONFIG_GZALLOC
+       if (__probable(gzalloc_enabled())) {
+               return;
+       }
+#endif
+       zone_require_panic(zone, addr);
+}
 
-struct zone_page_table_entry {
-       volatile        uint16_t        alloc_count;
-       volatile        uint16_t        collect_count;
-};
+void
+zone_id_require(zone_id_t zid, vm_size_t esize, void *addr)
+{
+       if (__probable(from_general_submap(addr, esize) &&
+           (zid == zone_native_meta_from_addr(addr)->zm_index))) {
+               return;
+       }
+#if CONFIG_GZALLOC
+       if (__probable(gzalloc_enabled())) {
+               return;
+       }
+#endif
+       zone_id_require_panic(zid, addr);
+}
 
-#define        ZONE_PAGE_USED  0
-#define ZONE_PAGE_UNUSED 0xffff
+bool
+zone_owns(zone_t zone, void *addr)
+{
+       if (__probable(from_general_submap(addr, zone_elem_size(zone)) &&
+           (zone_has_index(zone, zone_native_meta_from_addr(addr)->zm_index)))) {
+               return true;
+       }
+#if CONFIG_GZALLOC
+       if (__probable(gzalloc_enabled())) {
+               return true;
+       }
+#endif
+       return false;
+}
 
-/* Forwards */
-void           zone_page_init(
-                               vm_offset_t     addr,
-                               vm_size_t       size);
+#pragma mark ZTAGS
+#if VM_MAX_TAG_ZONES
 
-void           zone_page_alloc(
-                               vm_offset_t     addr,
-                               vm_size_t       size);
+// for zones with tagging enabled:
 
-void           zone_page_free_element(
-                               zone_page_index_t       *free_page_head,
-                               zone_page_index_t       *free_page_tail,
-                               vm_offset_t     addr,
-                               vm_size_t       size);
+// calculate a pointer to the tag base entry,
+// holding either a uint32_t the first tag offset for a page in the zone map,
+// or two uint16_t tags if the page can only hold one or two elements
 
-void           zone_page_collect(
-                               vm_offset_t     addr,
-                               vm_size_t       size);
+#define ZTAGBASE(zone, element) \
+    (&((uint32_t *)zone_tagbase_min)[atop((element) - zone_info.zi_map_range.min_address)])
 
-boolean_t      zone_page_collectable(
-                               vm_offset_t     addr,
-                               vm_size_t       size);
+// pointer to the tag for an element
+#define ZTAG(zone, element)                                     \
+    ({                                                          \
+       vm_tag_t * result;                                      \
+       if ((zone)->tags_inline) {                              \
+           result = (vm_tag_t *) ZTAGBASE((zone), (element));  \
+           if ((page_mask & element) >= zone_elem_size(zone)) result++;    \
+       } else {                                                \
+           result =  &((vm_tag_t *)zone_tags_min)[ZTAGBASE((zone), (element))[0] + ((element) & page_mask) / zone_elem_size((zone))];   \
+       }                                                       \
+       result;                                                 \
+    })
 
-void           zone_page_keep(
-                               vm_offset_t     addr,
-                               vm_size_t       size);
 
-void           zone_display_zprint(void);
+static vm_offset_t  zone_tagbase_min;
+static vm_offset_t  zone_tagbase_max;
+static vm_offset_t  zone_tagbase_map_size;
+static vm_map_t     zone_tagbase_map;
 
-zone_t         zone_find_largest(void);
+static vm_offset_t  zone_tags_min;
+static vm_offset_t  zone_tags_max;
+static vm_offset_t  zone_tags_map_size;
+static vm_map_t     zone_tags_map;
 
-/* 
- * Async allocation of zones 
- * This mechanism allows for bootstrapping an empty zone which is setup with 
- * non-blocking flags. The first call to zalloc_noblock() will kick off a thread_call
- * to zalloc_async. We perform a zalloc() (which may block) and then an immediate free. 
- * This will prime the zone for the next use.
- *
- * Currently the thread_callout function (zalloc_async) will loop through all zones
- * looking for any zone with async_pending set and do the work for it. 
- * 
- * NOTE: If the calling thread for zalloc_noblock is lower priority than thread_call,
- * then zalloc_noblock to an empty zone may succeed. 
- */
-void           zalloc_async(
-                               thread_call_param_t     p0,  
-                               thread_call_param_t     p1);
+// simple heap allocator for allocating the tags for new memory
 
-static thread_call_data_t call_async_alloc;
+LCK_MTX_EARLY_DECLARE(ztLock, &zone_locks_grp); /* heap lock */
 
-vm_map_t       zone_map = VM_MAP_NULL;
+enum{
+       ztFreeIndexCount = 8,
+       ztFreeIndexMax   = (ztFreeIndexCount - 1),
+       ztTagsPerBlock   = 4
+};
 
-zone_t         zone_zone = ZONE_NULL;  /* the zone containing other zones */
+struct ztBlock {
+#if __LITTLE_ENDIAN__
+       uint64_t free:1,
+           next:21,
+           prev:21,
+           size:21;
+#else
+// ztBlock needs free bit least significant
+#error !__LITTLE_ENDIAN__
+#endif
+};
+typedef struct ztBlock ztBlock;
 
-zone_t         zinfo_zone = ZONE_NULL; /* zone of per-task zone info */
+static ztBlock * ztBlocks;
+static uint32_t  ztBlocksCount;
+static uint32_t  ztBlocksFree;
 
-/*
- *     The VM system gives us an initial chunk of memory.
- *     It has to be big enough to allocate the zone_zone
- *     all the way through the pmap zone.
- */
+static uint32_t
+ztLog2up(uint32_t size)
+{
+       if (1 == size) {
+               size = 0;
+       } else {
+               size = 32 - __builtin_clz(size - 1);
+       }
+       return size;
+}
 
-vm_offset_t    zdata;
-vm_size_t      zdata_size;
-/*
- * Align elements that use the zone page list to 32 byte boundaries.
- */
-#define ZONE_ELEMENT_ALIGNMENT 32
+static uint32_t
+ztLog2down(uint32_t size)
+{
+       size = 31 - __builtin_clz(size);
+       return size;
+}
 
-#define zone_wakeup(zone) thread_wakeup((event_t)(zone))
-#define zone_sleep(zone)                               \
-       (void) lck_mtx_sleep(&(zone)->lock, LCK_SLEEP_SPIN, (event_t)(zone), THREAD_UNINT);
+static void
+ztFault(vm_map_t map, const void * address, size_t size, uint32_t flags)
+{
+       vm_map_offset_t addr = (vm_map_offset_t) address;
+       vm_map_offset_t page, end;
+
+       page = trunc_page(addr);
+       end  = round_page(addr + size);
+
+       for (; page < end; page += page_size) {
+               if (!pmap_find_phys(kernel_pmap, page)) {
+                       kern_return_t __unused
+                       ret = kernel_memory_populate(map, page, PAGE_SIZE,
+                           KMA_KOBJECT | flags, VM_KERN_MEMORY_DIAG);
+                       assert(ret == KERN_SUCCESS);
+               }
+       }
+}
 
-/*
- *     The zone_locks_grp allows for collecting lock statistics.
- *     All locks are associated to this group in zinit.
- *     Look at tools/lockstat for debugging lock contention.
- */
+static boolean_t
+ztPresent(const void * address, size_t size)
+{
+       vm_map_offset_t addr = (vm_map_offset_t) address;
+       vm_map_offset_t page, end;
+       boolean_t       result;
+
+       page = trunc_page(addr);
+       end  = round_page(addr + size);
+       for (result = TRUE; (page < end); page += page_size) {
+               result = pmap_find_phys(kernel_pmap, page);
+               if (!result) {
+                       break;
+               }
+       }
+       return result;
+}
 
-lck_grp_t      zone_locks_grp;
-lck_grp_attr_t zone_locks_grp_attr;
 
-#define lock_zone_init(zone)                           \
-MACRO_BEGIN                                            \
-       lck_attr_setdefault(&(zone)->lock_attr);                        \
-       lck_mtx_init_ext(&(zone)->lock, &(zone)->lock_ext,              \
-           &zone_locks_grp, &(zone)->lock_attr);                       \
-MACRO_END
+void __unused
+ztDump(boolean_t sanity);
+void __unused
+ztDump(boolean_t sanity)
+{
+       uint32_t q, cq, p;
+
+       for (q = 0; q <= ztFreeIndexMax; q++) {
+               p = q;
+               do{
+                       if (sanity) {
+                               cq = ztLog2down(ztBlocks[p].size);
+                               if (cq > ztFreeIndexMax) {
+                                       cq = ztFreeIndexMax;
+                               }
+                               if (!ztBlocks[p].free
+                                   || ((p != q) && (q != cq))
+                                   || (ztBlocks[ztBlocks[p].next].prev != p)
+                                   || (ztBlocks[ztBlocks[p].prev].next != p)) {
+                                       kprintf("zterror at %d", p);
+                                       ztDump(FALSE);
+                                       kprintf("zterror at %d", p);
+                                       assert(FALSE);
+                               }
+                               continue;
+                       }
+                       kprintf("zt[%03d]%c %d, %d, %d\n",
+                           p, ztBlocks[p].free ? 'F' : 'A',
+                           ztBlocks[p].next, ztBlocks[p].prev,
+                           ztBlocks[p].size);
+                       p = ztBlocks[p].next;
+                       if (p == q) {
+                               break;
+                       }
+               }while (p != q);
+               if (!sanity) {
+                       printf("\n");
+               }
+       }
+       if (!sanity) {
+               printf("-----------------------\n");
+       }
+}
 
-#define lock_try_zone(zone)    lck_mtx_try_lock_spin(&zone->lock)
 
-/*
- *     Garbage collection map information
+
+#define ZTBDEQ(idx)                                                 \
+    ztBlocks[ztBlocks[(idx)].prev].next = ztBlocks[(idx)].next;     \
+    ztBlocks[ztBlocks[(idx)].next].prev = ztBlocks[(idx)].prev;
+
+static void
+ztFree(zone_t zone __unused, uint32_t index, uint32_t count)
+{
+       uint32_t q, w, p, size, merge;
+
+       assert(count);
+       ztBlocksFree += count;
+
+       // merge with preceding
+       merge = (index + count);
+       if ((merge < ztBlocksCount)
+           && ztPresent(&ztBlocks[merge], sizeof(ztBlocks[merge]))
+           && ztBlocks[merge].free) {
+               ZTBDEQ(merge);
+               count += ztBlocks[merge].size;
+       }
+
+       // merge with following
+       merge = (index - 1);
+       if ((merge > ztFreeIndexMax)
+           && ztPresent(&ztBlocks[merge], sizeof(ztBlocks[merge]))
+           && ztBlocks[merge].free) {
+               size = ztBlocks[merge].size;
+               count += size;
+               index -= size;
+               ZTBDEQ(index);
+       }
+
+       q = ztLog2down(count);
+       if (q > ztFreeIndexMax) {
+               q = ztFreeIndexMax;
+       }
+       w = q;
+       // queue in order of size
+       while (TRUE) {
+               p = ztBlocks[w].next;
+               if (p == q) {
+                       break;
+               }
+               if (ztBlocks[p].size >= count) {
+                       break;
+               }
+               w = p;
+       }
+       ztBlocks[p].prev = index;
+       ztBlocks[w].next = index;
+
+       // fault in first
+       ztFault(zone_tags_map, &ztBlocks[index], sizeof(ztBlocks[index]), 0);
+
+       // mark first & last with free flag and size
+       ztBlocks[index].free = TRUE;
+       ztBlocks[index].size = count;
+       ztBlocks[index].prev = w;
+       ztBlocks[index].next = p;
+       if (count > 1) {
+               index += (count - 1);
+               // fault in last
+               ztFault(zone_tags_map, &ztBlocks[index], sizeof(ztBlocks[index]), 0);
+               ztBlocks[index].free = TRUE;
+               ztBlocks[index].size = count;
+       }
+}
+
+static uint32_t
+ztAlloc(zone_t zone, uint32_t count)
+{
+       uint32_t q, w, p, leftover;
+
+       assert(count);
+
+       q = ztLog2up(count);
+       if (q > ztFreeIndexMax) {
+               q = ztFreeIndexMax;
+       }
+       do{
+               w = q;
+               while (TRUE) {
+                       p = ztBlocks[w].next;
+                       if (p == q) {
+                               break;
+                       }
+                       if (ztBlocks[p].size >= count) {
+                               // dequeue, mark both ends allocated
+                               ztBlocks[w].next = ztBlocks[p].next;
+                               ztBlocks[ztBlocks[p].next].prev = w;
+                               ztBlocks[p].free = FALSE;
+                               ztBlocksFree -= ztBlocks[p].size;
+                               if (ztBlocks[p].size > 1) {
+                                       ztBlocks[p + ztBlocks[p].size - 1].free = FALSE;
+                               }
+
+                               // fault all the allocation
+                               ztFault(zone_tags_map, &ztBlocks[p], count * sizeof(ztBlocks[p]), 0);
+                               // mark last as allocated
+                               if (count > 1) {
+                                       ztBlocks[p + count - 1].free = FALSE;
+                               }
+                               // free remainder
+                               leftover = ztBlocks[p].size - count;
+                               if (leftover) {
+                                       ztFree(zone, p + ztBlocks[p].size - leftover, leftover);
+                               }
+
+                               return p;
+                       }
+                       w = p;
+               }
+               q++;
+       }while (q <= ztFreeIndexMax);
+
+       return -1U;
+}
+
+__startup_func
+static void
+zone_tagging_init(vm_size_t max_zonemap_size)
+{
+       kern_return_t         ret;
+       vm_map_kernel_flags_t vmk_flags;
+       uint32_t              idx;
+
+       // allocate submaps VM_KERN_MEMORY_DIAG
+
+       zone_tagbase_map_size = atop(max_zonemap_size) * sizeof(uint32_t);
+       vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
+       vmk_flags.vmkf_permanent = TRUE;
+       ret = kmem_suballoc(kernel_map, &zone_tagbase_min, zone_tagbase_map_size,
+           FALSE, VM_FLAGS_ANYWHERE, vmk_flags, VM_KERN_MEMORY_DIAG,
+           &zone_tagbase_map);
+
+       if (ret != KERN_SUCCESS) {
+               panic("zone_init: kmem_suballoc failed");
+       }
+       zone_tagbase_max = zone_tagbase_min + round_page(zone_tagbase_map_size);
+
+       zone_tags_map_size = 2048 * 1024 * sizeof(vm_tag_t);
+       vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
+       vmk_flags.vmkf_permanent = TRUE;
+       ret = kmem_suballoc(kernel_map, &zone_tags_min, zone_tags_map_size,
+           FALSE, VM_FLAGS_ANYWHERE, vmk_flags, VM_KERN_MEMORY_DIAG,
+           &zone_tags_map);
+
+       if (ret != KERN_SUCCESS) {
+               panic("zone_init: kmem_suballoc failed");
+       }
+       zone_tags_max = zone_tags_min + round_page(zone_tags_map_size);
+
+       ztBlocks = (ztBlock *) zone_tags_min;
+       ztBlocksCount = (uint32_t)(zone_tags_map_size / sizeof(ztBlock));
+
+       // initialize the qheads
+       lck_mtx_lock(&ztLock);
+
+       ztFault(zone_tags_map, &ztBlocks[0], sizeof(ztBlocks[0]), 0);
+       for (idx = 0; idx < ztFreeIndexCount; idx++) {
+               ztBlocks[idx].free = TRUE;
+               ztBlocks[idx].next = idx;
+               ztBlocks[idx].prev = idx;
+               ztBlocks[idx].size = 0;
+       }
+       // free remaining space
+       ztFree(NULL, ztFreeIndexCount, ztBlocksCount - ztFreeIndexCount);
+
+       lck_mtx_unlock(&ztLock);
+}
+
+static void
+ztMemoryAdd(zone_t zone, vm_offset_t mem, vm_size_t size)
+{
+       uint32_t * tagbase;
+       uint32_t   count, block, blocks, idx;
+       size_t     pages;
+
+       pages = atop(size);
+       tagbase = ZTAGBASE(zone, mem);
+
+       lck_mtx_lock(&ztLock);
+
+       // fault tagbase
+       ztFault(zone_tagbase_map, tagbase, pages * sizeof(uint32_t), 0);
+
+       if (!zone->tags_inline) {
+               // allocate tags
+               count = (uint32_t)(size / zone_elem_size(zone));
+               blocks = ((count + ztTagsPerBlock - 1) / ztTagsPerBlock);
+               block = ztAlloc(zone, blocks);
+               if (-1U == block) {
+                       ztDump(false);
+               }
+               assert(-1U != block);
+       }
+
+       lck_mtx_unlock(&ztLock);
+
+       if (!zone->tags_inline) {
+               // set tag base for each page
+               block *= ztTagsPerBlock;
+               for (idx = 0; idx < pages; idx++) {
+                       vm_offset_t esize = zone_elem_size(zone);
+                       tagbase[idx] = block + (uint32_t)((ptoa(idx) + esize - 1) / esize);
+               }
+       }
+}
+
+static void
+ztMemoryRemove(zone_t zone, vm_offset_t mem, vm_size_t size)
+{
+       uint32_t * tagbase;
+       uint32_t   count, block, blocks, idx;
+       size_t     pages;
+
+       // set tag base for each page
+       pages = atop(size);
+       tagbase = ZTAGBASE(zone, mem);
+       block = tagbase[0];
+       for (idx = 0; idx < pages; idx++) {
+               tagbase[idx] = 0xFFFFFFFF;
+       }
+
+       lck_mtx_lock(&ztLock);
+       if (!zone->tags_inline) {
+               count = (uint32_t)(size / zone_elem_size(zone));
+               blocks = ((count + ztTagsPerBlock - 1) / ztTagsPerBlock);
+               assert(block != 0xFFFFFFFF);
+               block /= ztTagsPerBlock;
+               ztFree(NULL /* zone is unlocked */, block, blocks);
+       }
+
+       lck_mtx_unlock(&ztLock);
+}
+
+uint32_t
+zone_index_from_tag_index(uint32_t tag_zone_index, vm_size_t * elem_size)
+{
+       simple_lock(&all_zones_lock, &zone_locks_grp);
+
+       zone_index_foreach(idx) {
+               zone_t z = &zone_array[idx];
+               if (!z->tags) {
+                       continue;
+               }
+               if (tag_zone_index != z->tag_zone_index) {
+                       continue;
+               }
+
+               *elem_size = zone_elem_size(z);
+               simple_unlock(&all_zones_lock);
+               return idx;
+       }
+
+       simple_unlock(&all_zones_lock);
+
+       return -1U;
+}
+
+#endif /* VM_MAX_TAG_ZONES */
+#pragma mark zalloc helpers
+
+const char *
+zone_name(zone_t z)
+{
+       return z->z_name;
+}
+
+const char *
+zone_heap_name(zone_t z)
+{
+       if (__probable(z->kalloc_heap < KHEAP_ID_COUNT)) {
+               return kalloc_heap_names[z->kalloc_heap];
+       }
+       return "invalid";
+}
+
+static inline vm_size_t
+zone_submaps_approx_size(void)
+{
+       vm_size_t size = 0;
+
+       for (unsigned idx = 0; idx <= zone_last_submap_idx; idx++) {
+               size += zone_submaps[idx]->size;
+       }
+
+       return size;
+}
+
+bool
+zone_maps_owned(vm_address_t addr, vm_size_t size)
+{
+       return from_zone_map(addr, size);
+}
+
+void
+zone_map_sizes(
+       vm_map_size_t    *psize,
+       vm_map_size_t    *pfree,
+       vm_map_size_t    *plargest_free)
+{
+       vm_map_sizes(zone_submaps[Z_SUBMAP_IDX_GENERAL_MAP], psize, pfree, plargest_free);
+}
+
+vm_map_t
+zone_submap(zone_t zone)
+{
+       return submap_for_zone(zone);
+}
+
+unsigned
+zpercpu_count(void)
+{
+       return zpercpu_early_count;
+}
+
+int
+track_this_zone(const char *zonename, const char *logname)
+{
+       unsigned int len;
+       const char *zc = zonename;
+       const char *lc = logname;
+
+       /*
+        * Compare the strings.  We bound the compare by MAX_ZONE_NAME.
+        */
+
+       for (len = 1; len <= MAX_ZONE_NAME; zc++, lc++, len++) {
+               /*
+                * If the current characters don't match, check for a space in
+                * in the zone name and a corresponding period in the log name.
+                * If that's not there, then the strings don't match.
+                */
+
+               if (*zc != *lc && !(*zc == ' ' && *lc == '.')) {
+                       break;
+               }
+
+               /*
+                * The strings are equal so far.  If we're at the end, then it's a match.
+                */
+
+               if (*zc == '\0') {
+                       return TRUE;
+               }
+       }
+
+       return FALSE;
+}
+
+#if DEBUG || DEVELOPMENT
+
+vm_size_t
+zone_element_info(void *addr, vm_tag_t * ptag)
+{
+       vm_size_t     size = 0;
+       vm_tag_t      tag = VM_KERN_MEMORY_NONE;
+       struct zone_page_metadata *meta;
+       struct zone *src_zone;
+
+       if (from_zone_map(addr, sizeof(void *))) {
+               meta = zone_native_meta_from_addr(addr);
+               src_zone = &zone_array[meta->zm_index];
+#if VM_MAX_TAG_ZONES
+               if (__improbable(src_zone->tags)) {
+                       tag = (ZTAG(src_zone, (vm_offset_t) addr)[0] >> 1);
+               }
+#endif /* VM_MAX_TAG_ZONES */
+               size = zone_elem_size(src_zone);
+       } else {
+#if CONFIG_GZALLOC
+               gzalloc_element_size(addr, NULL, &size);
+#endif /* CONFIG_GZALLOC */
+       }
+       *ptag = tag;
+       return size;
+}
+
+#endif /* DEBUG || DEVELOPMENT */
+
+/* Someone wrote to freed memory. */
+__abortlike
+static void
+zone_element_was_modified_panic(
+       zone_t        zone,
+       vm_offset_t   element,
+       vm_offset_t   found,
+       vm_offset_t   expected,
+       vm_offset_t   offset)
+{
+       panic("a freed zone element has been modified in zone %s%s: "
+           "expected %p but found %p, bits changed %p, "
+           "at offset %d of %d in element %p, cookies %p %p",
+           zone_heap_name(zone),
+           zone->z_name,
+           (void *)   expected,
+           (void *)   found,
+           (void *)   (expected ^ found),
+           (uint32_t) offset,
+           (uint32_t) zone_elem_size(zone),
+           (void *)   element,
+           (void *)   zp_nopoison_cookie,
+           (void *)   zp_poisoned_cookie);
+}
+
+/* The backup pointer is stored in the last pointer-sized location in an element. */
+__header_always_inline vm_offset_t *
+get_backup_ptr(vm_size_t elem_size, vm_offset_t *element)
+{
+       return (vm_offset_t *)((vm_offset_t)element + elem_size - sizeof(vm_offset_t));
+}
+
+/*
+ * The primary and backup pointers don't match.
+ * Determine which one was likely the corrupted pointer, find out what it
+ * probably should have been, and panic.
  */
-#define ZONE_PAGE_TABLE_FIRST_LEVEL_SIZE (32)
-struct zone_page_table_entry * volatile zone_page_table[ZONE_PAGE_TABLE_FIRST_LEVEL_SIZE];
-vm_size_t                      zone_page_table_used_size;
-unsigned int                   zone_pages;
-unsigned int                   zone_page_table_second_level_size;                      /* power of 2 */
-unsigned int                   zone_page_table_second_level_shift_amount;
+__abortlike
+static void
+backup_ptr_mismatch_panic(
+       zone_t        zone,
+       struct zone_page_metadata *page_meta,
+       vm_offset_t   page,
+       vm_offset_t   element)
+{
+       vm_offset_t primary = *(vm_offset_t *)element;
+       vm_offset_t backup  = *get_backup_ptr(zone_elem_size(zone), &element);
+       vm_offset_t likely_backup;
+       vm_offset_t likely_primary;
+       zone_addr_kind_t kind = zone_addr_kind(page, zone_elem_size(zone));
+
+       likely_primary = primary ^ zp_nopoison_cookie;
+       boolean_t   sane_backup;
+       boolean_t   sane_primary = zone_page_meta_is_sane_element(zone, page_meta,
+           page, likely_primary, kind);
+       boolean_t   element_was_poisoned = (backup & 0x1);
+
+#if defined(__LP64__)
+       /* We can inspect the tag in the upper bits for additional confirmation */
+       if ((backup & 0xFFFFFF0000000000) == 0xFACADE0000000000) {
+               element_was_poisoned = TRUE;
+       } else if ((backup & 0xFFFFFF0000000000) == 0xC0FFEE0000000000) {
+               element_was_poisoned = FALSE;
+       }
+#endif
 
-#define zone_page_table_first_level_slot(x)  ((x) >> zone_page_table_second_level_shift_amount)
-#define zone_page_table_second_level_slot(x) ((x) & (zone_page_table_second_level_size - 1))
+       if (element_was_poisoned) {
+               likely_backup = backup ^ zp_poisoned_cookie;
+       } else {
+               likely_backup = backup ^ zp_nopoison_cookie;
+       }
+       sane_backup = zone_page_meta_is_sane_element(zone, page_meta,
+           page, likely_backup, kind);
 
-void   zone_page_table_expand(zone_page_index_t pindex);
-struct zone_page_table_entry *zone_page_table_lookup(zone_page_index_t pindex);
+       /* The primary is definitely the corrupted one */
+       if (!sane_primary && sane_backup) {
+               zone_element_was_modified_panic(zone, element, primary, (likely_backup ^ zp_nopoison_cookie), 0);
+       }
+
+       /* The backup is definitely the corrupted one */
+       if (sane_primary && !sane_backup) {
+               zone_element_was_modified_panic(zone, element, backup,
+                   (likely_primary ^ (element_was_poisoned ? zp_poisoned_cookie : zp_nopoison_cookie)),
+                   zone_elem_size(zone) - sizeof(vm_offset_t));
+       }
+
+       /*
+        * Not sure which is the corrupted one.
+        * It's less likely that the backup pointer was overwritten with
+        * ( (sane address) ^ (valid cookie) ), so we'll guess that the
+        * primary pointer has been overwritten with a sane but incorrect address.
+        */
+       if (sane_primary && sane_backup) {
+               zone_element_was_modified_panic(zone, element, primary, (likely_backup ^ zp_nopoison_cookie), 0);
+       }
+
+       /* Neither are sane, so just guess. */
+       zone_element_was_modified_panic(zone, element, primary, (likely_backup ^ zp_nopoison_cookie), 0);
+}
 
 /*
- *     Exclude more than one concurrent garbage collection
+ * zone_sequestered_page_get
+ * z is locked
  */
-decl_lck_mtx_data(, zone_gc_lock)
+static struct zone_page_metadata *
+zone_sequestered_page_get(zone_t z, vm_offset_t *page)
+{
+       const zone_addr_kind_t kind = ZONE_ADDR_NATIVE;
 
-lck_attr_t      zone_gc_lck_attr;
-lck_grp_t       zone_gc_lck_grp;
-lck_grp_attr_t  zone_gc_lck_grp_attr;
-lck_mtx_ext_t   zone_gc_lck_ext;
+       if (!zone_pva_is_null(z->pages_sequester)) {
+               if (os_sub_overflow(z->sequester_page_count, z->alloc_pages,
+                   &z->sequester_page_count)) {
+                       zone_accounting_panic(z, "sequester_page_count wrap-around");
+               }
+               return zone_meta_queue_pop(z, &z->pages_sequester, kind, page);
+       }
+
+       return NULL;
+}
 
 /*
- *     Protects first_zone, last_zone, num_zones,
- *     and the next_zone field of zones.
+ * zone_sequestered_page_populate
+ * z is unlocked
+ * page_meta is invalid on failure
  */
-decl_simple_lock_data(,        all_zones_lock)
-zone_t                 first_zone;
-zone_t                 *last_zone;
-unsigned int           num_zones;
+static kern_return_t
+zone_sequestered_page_populate(zone_t z, struct zone_page_metadata *page_meta,
+    vm_offset_t space, vm_size_t alloc_size, int zflags)
+{
+       kern_return_t retval;
 
-boolean_t zone_gc_allowed = TRUE;
-boolean_t zone_gc_forced = FALSE;
-boolean_t panic_include_zprint = FALSE;
-boolean_t zone_gc_allowed_by_time_throttle = TRUE;
+       assert(alloc_size == ptoa(z->alloc_pages));
+       retval = kernel_memory_populate(submap_for_zone(z), space, alloc_size,
+           zflags, VM_KERN_MEMORY_ZONE);
+       if (retval != KERN_SUCCESS) {
+               lock_zone(z);
+               zone_meta_queue_push(z, &z->pages_sequester, page_meta, ZONE_ADDR_NATIVE);
+               z->sequester_page_count += z->alloc_pages;
+               unlock_zone(z);
+       }
+       return retval;
+}
 
-vm_offset_t panic_kext_memory_info = 0;
-vm_size_t panic_kext_memory_size = 0;
+#pragma mark Zone poisoning/zeroing
 
-#define ZALLOC_DEBUG_ZONEGC            0x00000001
-#define ZALLOC_DEBUG_ZCRAM             0x00000002
-uint32_t zalloc_debug = 0;
+/*
+ * Initialize zone poisoning
+ * called from zone_bootstrap before any allocations are made from zalloc
+ */
+__startup_func
+static void
+zp_bootstrap(void)
+{
+       char temp_buf[16];
+
+       /*
+        * Initialize backup pointer random cookie for poisoned elements
+        * Try not to call early_random() back to back, it may return
+        * the same value if mach_absolute_time doesn't have sufficient time
+        * to tick over between calls.  <rdar://problem/11597395>
+        * (This is only a problem on embedded devices)
+        */
+       zp_poisoned_cookie = (uintptr_t) early_random();
+
+       /* -zp: enable poisoning for every alloc and free */
+       if (PE_parse_boot_argn("-zp", temp_buf, sizeof(temp_buf))) {
+               zp_factor = 1;
+       }
+
+       /* -no-zp: disable poisoning */
+       if (PE_parse_boot_argn("-no-zp", temp_buf, sizeof(temp_buf))) {
+               zp_factor = 0;
+               printf("Zone poisoning disabled\n");
+       }
+
+       /* Initialize backup pointer random cookie for unpoisoned elements */
+       zp_nopoison_cookie = (uintptr_t) early_random();
+
+#if MACH_ASSERT
+       if (zp_poisoned_cookie == zp_nopoison_cookie) {
+               panic("early_random() is broken: %p and %p are not random\n",
+                   (void *) zp_poisoned_cookie, (void *) zp_nopoison_cookie);
+       }
+#endif
+
+       /*
+        * Use the last bit in the backup pointer to hint poisoning state
+        * to backup_ptr_mismatch_panic. Valid zone pointers are aligned, so
+        * the low bits are zero.
+        */
+       zp_poisoned_cookie |=   (uintptr_t)0x1ULL;
+       zp_nopoison_cookie &= ~((uintptr_t)0x1ULL);
+
+#if defined(__LP64__)
+       /*
+        * Make backup pointers more obvious in GDB for 64 bit
+        * by making OxFFFFFF... ^ cookie = 0xFACADE...
+        * (0xFACADE = 0xFFFFFF ^ 0x053521)
+        * (0xC0FFEE = 0xFFFFFF ^ 0x3f0011)
+        * The high 3 bytes of a zone pointer are always 0xFFFFFF, and are checked
+        * by the sanity check, so it's OK for that part of the cookie to be predictable.
+        *
+        * TODO: Use #defines, xors, and shifts
+        */
+
+       zp_poisoned_cookie &= 0x000000FFFFFFFFFF;
+       zp_poisoned_cookie |= 0x0535210000000000; /* 0xFACADE */
+
+       zp_nopoison_cookie &= 0x000000FFFFFFFFFF;
+       zp_nopoison_cookie |= 0x3f00110000000000; /* 0xC0FFEE */
+#endif
+
+       /*
+        * Initialize zp_min_size to two cachelines. Elements smaller than this will
+        * be zero-ed.
+        */
+       ml_cpu_info_t cpu_info;
+       ml_cpu_get_info(&cpu_info);
+       zp_min_size = 2 * cpu_info.cache_line_size;
+}
+
+inline uint32_t
+zone_poison_count_init(zone_t zone)
+{
+       return zp_factor + (((uint32_t)zone_elem_size(zone)) >> zp_scale) ^
+              (mach_absolute_time() & 0x7);
+}
+
+#if ZALLOC_ENABLE_POISONING
+static bool
+zfree_poison_element(zone_t zone, uint32_t *zp_count, vm_offset_t elem)
+{
+       bool poison = false;
+       uint32_t zp_count_local;
+
+       assert(!zone->percpu);
+       if (zp_factor != 0) {
+               /*
+                * Poison the memory of every zp_count-th element before it ends up
+                * on the freelist to catch use-after-free and use of uninitialized
+                * memory.
+                *
+                * Every element is poisoned when zp_factor is set to 1.
+                *
+                */
+               zp_count_local = os_atomic_load(zp_count, relaxed);
+               if (__improbable(zp_count_local == 0 || zp_factor == 1)) {
+                       poison = true;
+
+                       os_atomic_store(zp_count, zone_poison_count_init(zone), relaxed);
+
+                       /* memset_pattern{4|8} could help make this faster: <rdar://problem/4662004> */
+                       vm_offset_t *element_cursor  = ((vm_offset_t *) elem);
+                       vm_offset_t *end_cursor      = (vm_offset_t *)(elem + zone_elem_size(zone));
+
+                       for (; element_cursor < end_cursor; element_cursor++) {
+                               *element_cursor = ZONE_POISON;
+                       }
+               } else {
+                       os_atomic_store(zp_count, zp_count_local - 1, relaxed);
+                       /*
+                        * Zero first zp_min_size bytes of elements that aren't being poisoned.
+                        * Element size is larger than zp_min_size in this path as elements
+                        * that are smaller will always be zero-ed.
+                        */
+                       bzero((void *) elem, zp_min_size);
+               }
+       }
+       return poison;
+}
+#else
+static bool
+zfree_poison_element(zone_t zone, uint32_t *zp_count, vm_offset_t elem)
+{
+#pragma unused(zone, zp_count, elem)
+       assert(!zone->percpu);
+       return false;
+}
+#endif
+
+__attribute__((always_inline))
+static bool
+zfree_clear(zone_t zone, vm_offset_t addr, vm_size_t elem_size)
+{
+       assert(zone->zfree_clear_mem);
+       if (zone->percpu) {
+               zpercpu_foreach_cpu(i) {
+                       bzero((void *)(addr + ptoa(i)), elem_size);
+               }
+       } else {
+               bzero((void *)addr, elem_size);
+       }
+
+       return true;
+}
+
+/*
+ * Zero the element if zone has zfree_clear_mem flag set else poison
+ * the element if zp_count hits 0.
+ */
+__attribute__((always_inline))
+bool
+zfree_clear_or_poison(zone_t zone, uint32_t *zp_count, vm_offset_t addr)
+{
+       vm_size_t elem_size = zone_elem_size(zone);
+
+       if (zone->zfree_clear_mem) {
+               return zfree_clear(zone, addr, elem_size);
+       }
+
+       return zfree_poison_element(zone, zp_count, (vm_offset_t)addr);
+}
+
+/*
+ * Clear out the old next pointer and backup to avoid leaking the zone
+ * poisoning cookie and so that only values on the freelist have a valid
+ * cookie.
+ */
+void
+zone_clear_freelist_pointers(zone_t zone, vm_offset_t addr)
+{
+       vm_offset_t perm_value = 0;
+
+       if (!zone->zfree_clear_mem) {
+               perm_value = ZONE_POISON;
+       }
+
+       vm_offset_t *primary  = (vm_offset_t *) addr;
+       vm_offset_t *backup   = get_backup_ptr(zone_elem_size(zone), primary);
+
+       *primary = perm_value;
+       *backup  = perm_value;
+}
+
+#if ZALLOC_ENABLE_POISONING
+__abortlike
+static void
+zone_element_not_clear_panic(zone_t zone, void *addr)
+{
+       panic("Zone element %p was modified after free for zone %s%s: "
+           "Expected element to be cleared", addr, zone_heap_name(zone),
+           zone->z_name);
+}
+
+/*
+ * Validate that the element was not tampered with while it was in the
+ * freelist.
+ */
+void
+zalloc_validate_element(zone_t zone, vm_offset_t addr, vm_size_t size, bool validate)
+{
+       if (zone->percpu) {
+               assert(zone->zfree_clear_mem);
+               zpercpu_foreach_cpu(i) {
+                       if (memcmp_zero_ptr_aligned((void *)(addr + ptoa(i)), size)) {
+                               zone_element_not_clear_panic(zone, (void *)(addr + ptoa(i)));
+                       }
+               }
+       } else if (zone->zfree_clear_mem) {
+               if (memcmp_zero_ptr_aligned((void *)addr, size)) {
+                       zone_element_not_clear_panic(zone, (void *)addr);
+               }
+       } else if (__improbable(validate)) {
+               const vm_offset_t *p   = (vm_offset_t *)addr;
+               const vm_offset_t *end = (vm_offset_t *)(addr + size);
+
+               for (; p < end; p++) {
+                       if (*p != ZONE_POISON) {
+                               zone_element_was_modified_panic(zone, addr,
+                                   *p, ZONE_POISON, (vm_offset_t)p - addr);
+                       }
+               }
+       } else {
+               /*
+                * If element wasn't poisoned or entirely cleared, validate that the
+                * minimum bytes that were cleared on free haven't been corrupted.
+                * addr is advanced by ptr size as we have already validated and cleared
+                * the freelist pointer/zcache canary.
+                */
+               if (memcmp_zero_ptr_aligned((void *) (addr + sizeof(vm_offset_t)),
+                   zp_min_size - sizeof(vm_offset_t))) {
+                       zone_element_not_clear_panic(zone, (void *)addr);
+               }
+       }
+}
+#endif /* ZALLOC_ENABLE_POISONING */
+
+#pragma mark Zone Leak Detection
 
 /*
  * Zone leak debugging code
@@ -1003,7 +2017,7 @@ uint32_t zalloc_debug = 0;
  * off by default.
  *
  * Enable the logging via the boot-args. Add the parameter "zlog=<zone>" to boot-args where <zone>
- * is the name of the zone you wish to log.  
+ * is the name of the zone you wish to log.
  *
  * This code only tracks one zone, so you need to identify which one is leaking first.
  * Generally, you'll know you have a leak when you get a "zalloc retry failed 3" panic from the zone
@@ -1024,30 +2038,144 @@ uint32_t zalloc_debug = 0;
  * corrupted to examine its history.  This should lead to the source of the corruption.
  */
 
-static int log_records;        /* size of the log, expressed in number of records */
-
-#define MAX_ZONE_NAME  32      /* max length of a zone name we can take from the boot-args */
+/* Returns TRUE if we rolled over the counter at factor */
+__header_always_inline bool
+sample_counter(volatile uint32_t *count_p, uint32_t factor)
+{
+       uint32_t old_count, new_count = 0;
+       if (count_p != NULL) {
+               os_atomic_rmw_loop(count_p, old_count, new_count, relaxed, {
+                       new_count = old_count + 1;
+                       if (new_count >= factor) {
+                               new_count = 0;
+                       }
+               });
+       }
 
-static char zone_name_to_log[MAX_ZONE_NAME] = "";      /* the zone name we're logging, if any */
+       return new_count == 0;
+}
 
+#if ZONE_ENABLE_LOGGING
 /* Log allocations and frees to help debug a zone element corruption */
-boolean_t       corruption_debug_flag    = FALSE;    /* enabled by "-zc" boot-arg */
+TUNABLE(bool, corruption_debug_flag, "-zc", false);
+
+#define MAX_NUM_ZONES_ALLOWED_LOGGING   10 /* Maximum 10 zones can be logged at once */
+
+static int  max_num_zones_to_log = MAX_NUM_ZONES_ALLOWED_LOGGING;
+static int  num_zones_logged = 0;
 
 /*
- * The number of records in the log is configurable via the zrecs parameter in boot-args.  Set this to 
- * the number of records you want in the log.  For example, "zrecs=1000" sets it to 1000 records.  Note
- * that the larger the size of the log, the slower the system will run due to linear searching in the log,
- * but one doesn't generally care about performance when tracking down a leak.  The log is capped at 8000
- * records since going much larger than this tends to make the system unresponsive and unbootable on small
- * memory configurations.  The default value is 4000 records.
+ * The number of records in the log is configurable via the zrecs parameter in boot-args.  Set this to
+ * the number of records you want in the log.  For example, "zrecs=10" sets it to 10 records. Since this
+ * is the number of stacks suspected of leaking, we don't need many records.
  */
 
-#if    defined(__LP64__)
-#define ZRECORDS_MAX           128000          /* Max records allowed in the log */
+#if defined(__LP64__)
+#define ZRECORDS_MAX            2560            /* Max records allowed in the log */
 #else
-#define ZRECORDS_MAX           8000            /* Max records allowed in the log */
+#define ZRECORDS_MAX            1536            /* Max records allowed in the log */
 #endif
-#define ZRECORDS_DEFAULT       4000            /* default records in log if zrecs is not specificed in boot-args */
+#define ZRECORDS_DEFAULT        1024            /* default records in log if zrecs is not specificed in boot-args */
+
+static TUNABLE(uint32_t, log_records, "zrecs", ZRECORDS_DEFAULT);
+
+static void
+zone_enable_logging(zone_t z)
+{
+       z->zlog_btlog = btlog_create(log_records, MAX_ZTRACE_DEPTH,
+           (corruption_debug_flag == FALSE) /* caller_will_remove_entries_for_element? */);
+
+       if (z->zlog_btlog) {
+               printf("zone: logging started for zone %s%s\n",
+                   zone_heap_name(z), z->z_name);
+       } else {
+               printf("zone: couldn't allocate memory for zrecords, turning off zleak logging\n");
+               z->zone_logging = false;
+       }
+}
+
+/**
+ * @function zone_setup_logging
+ *
+ * @abstract
+ * Optionally sets up a zone for logging.
+ *
+ * @discussion
+ * We recognized two boot-args:
+ *
+ *     zlog=<zone_to_log>
+ *     zrecs=<num_records_in_log>
+ *
+ * The zlog arg is used to specify the zone name that should be logged,
+ * and zrecs is used to control the size of the log.
+ *
+ * If zrecs is not specified, a default value is used.
+ */
+static void
+zone_setup_logging(zone_t z)
+{
+       char zone_name[MAX_ZONE_NAME]; /* Temp. buffer for the zone name */
+       char zlog_name[MAX_ZONE_NAME]; /* Temp. buffer to create the strings zlog1, zlog2 etc... */
+       char zlog_val[MAX_ZONE_NAME];  /* the zone name we're logging, if any */
+
+       /*
+        * Don't allow more than ZRECORDS_MAX records even if the user asked for more.
+        *
+        * This prevents accidentally hogging too much kernel memory
+        * and making the system unusable.
+        */
+       if (log_records > ZRECORDS_MAX) {
+               log_records = ZRECORDS_MAX;
+       }
+
+       /*
+        * Append kalloc heap name to zone name (if zone is used by kalloc)
+        */
+       snprintf(zone_name, MAX_ZONE_NAME, "%s%s", zone_heap_name(z), z->z_name);
+
+       /* zlog0 isn't allowed. */
+       for (int i = 1; i <= max_num_zones_to_log; i++) {
+               snprintf(zlog_name, MAX_ZONE_NAME, "zlog%d", i);
+
+               if (PE_parse_boot_argn(zlog_name, zlog_val, sizeof(zlog_val)) &&
+                   track_this_zone(zone_name, zlog_val)) {
+                       z->zone_logging = true;
+                       num_zones_logged++;
+                       break;
+               }
+       }
+
+       /*
+        * Backwards compat. with the old boot-arg used to specify single zone
+        * logging i.e. zlog Needs to happen after the newer zlogn checks
+        * because the prefix will match all the zlogn
+        * boot-args.
+        */
+       if (!z->zone_logging &&
+           PE_parse_boot_argn("zlog", zlog_val, sizeof(zlog_val)) &&
+           track_this_zone(zone_name, zlog_val)) {
+               z->zone_logging = true;
+               num_zones_logged++;
+       }
+
+
+       /*
+        * If we want to log a zone, see if we need to allocate buffer space for
+        * the log.
+        *
+        * Some vm related zones are zinit'ed before we can do a kmem_alloc, so
+        * we have to defer allocation in that case.
+        *
+        * zone_init() will finish the job.
+        *
+        * If we want to log one of the VM related zones that's set up early on,
+        * we will skip allocation of the log until zinit is called again later
+        * on some other zone.
+        */
+       if (z->zone_logging && startup_phase >= STARTUP_SUB_KMEM_ALLOC) {
+               zone_enable_logging(z);
+       }
+}
 
 /*
  * Each record in the log contains a pointer to the zone element it refers to,
@@ -1058,19 +2186,6 @@ boolean_t       corruption_debug_flag    = FALSE;    /* enabled by "-zc" boot-ar
  */
 
 
-/*
- * Opcodes for the btlog operation field:
- */
-
-#define ZOP_ALLOC      1
-#define ZOP_FREE       0
-
-/*
- * The allocation log and all the related variables are protected by the zone lock for the zone_of_interest
- */
-static btlog_t *zlog_btlog;            /* the log itself, dynamically allocated when logging is enabled  */
-static zone_t  zone_of_interest = NULL;                /* the zone being watched; corresponds to zone_name_to_log */
-
 /*
  * Decide if we want to log this zone by doing a string compare between a zone name and the name
  * of the zone to log. Return true if the strings are equal, false otherwise.  Because it's not
@@ -1078,60 +2193,25 @@ static zone_t  zone_of_interest = NULL;         /* the zone being watched; corresponds
  * match a space in the zone name.
  */
 
-static int
-log_this_zone(const char *zonename, const char *logname) 
-{
-       int len;
-       const char *zc = zonename;
-       const char *lc = logname;
-
-       /*
-        * Compare the strings.  We bound the compare by MAX_ZONE_NAME.
-        */
-
-       for (len = 1; len <= MAX_ZONE_NAME; zc++, lc++, len++) {
-
-               /*
-                * If the current characters don't match, check for a space in
-                * in the zone name and a corresponding period in the log name.
-                * If that's not there, then the strings don't match.
-                */
-
-               if (*zc != *lc && !(*zc == ' ' && *lc == '.')) 
-                       break;
-
-               /*
-                * The strings are equal so far.  If we're at the end, then it's a match.
-                */
-
-               if (*zc == '\0')
-                       return TRUE;
-       }
-
-       return FALSE;
-}
-
-
 /*
  * Test if we want to log this zalloc/zfree event.  We log if this is the zone we're interested in and
  * the buffer for the records has been allocated.
  */
 
-#define DO_LOGGING(z)          (zlog_btlog && (z) == zone_of_interest)
-
-extern boolean_t kmem_alloc_ready;
+#define DO_LOGGING(z)           (z->zlog_btlog != NULL)
+#else /* !ZONE_ENABLE_LOGGING */
+#define DO_LOGGING(z)           0
+#endif /* !ZONE_ENABLE_LOGGING */
 
 #if CONFIG_ZLEAKS
-#pragma mark -
-#pragma mark Zone Leak Detection
 
-/* 
+/*
  * The zone leak detector, abbreviated 'zleak', keeps track of a subset of the currently outstanding
  * allocations made by the zone allocator.  Every zleak_sample_factor allocations in each zone, we capture a
- * backtrace.  Every free, we examine the table and determine if the allocation was being tracked, 
+ * backtrace.  Every free, we examine the table and determine if the allocation was being tracked,
  * and stop tracking it if it was being tracked.
  *
- * We track the allocations in the zallocations hash table, which stores the address that was returned from 
+ * We track the allocations in the zallocations hash table, which stores the address that was returned from
  * the zone allocator.  Each stored entry in the zallocations table points to an entry in the ztraces table, which
  * stores the backtrace associated with that allocation.  This provides uniquing for the relatively large
  * backtraces - we don't store them more than once.
@@ -1139,20 +2219,20 @@ extern boolean_t kmem_alloc_ready;
  * Data collection begins when the zone map is 50% full, and only occurs for zones that are taking up
  * a large amount of virtual space.
  */
-#define ZLEAK_STATE_ENABLED            0x01    /* Zone leak monitoring should be turned on if zone_map fills up. */
-#define ZLEAK_STATE_ACTIVE             0x02    /* We are actively collecting traces. */
-#define ZLEAK_STATE_ACTIVATING                 0x04    /* Some thread is doing setup; others should move along. */
-#define ZLEAK_STATE_FAILED             0x08    /* Attempt to allocate tables failed.  We will not try again. */
-uint32_t       zleak_state = 0;                /* State of collection, as above */
+#define ZLEAK_STATE_ENABLED             0x01    /* Zone leak monitoring should be turned on if zone_map fills up. */
+#define ZLEAK_STATE_ACTIVE              0x02    /* We are actively collecting traces. */
+#define ZLEAK_STATE_ACTIVATING          0x04    /* Some thread is doing setup; others should move along. */
+#define ZLEAK_STATE_FAILED              0x08    /* Attempt to allocate tables failed.  We will not try again. */
+uint32_t        zleak_state = 0;                /* State of collection, as above */
 
-boolean_t      panic_include_ztrace    = FALSE;        /* Enable zleak logging on panic */
-vm_size_t      zleak_global_tracking_threshold;        /* Size of zone map at which to start collecting data */
-vm_size_t      zleak_per_zone_tracking_threshold;      /* Size a zone will have before we will collect data on it */
-unsigned int   zleak_sample_factor     = 1000;         /* Allocations per sample attempt */
+boolean_t       panic_include_ztrace    = FALSE;        /* Enable zleak logging on panic */
+vm_size_t       zleak_global_tracking_threshold;        /* Size of zone map at which to start collecting data */
+vm_size_t       zleak_per_zone_tracking_threshold;      /* Size a zone will have before we will collect data on it */
+unsigned int    zleak_sample_factor     = 1000;         /* Allocations per sample attempt */
 
 /*
  * Counters for allocation statistics.
- */ 
+ */
 
 /* Times two active records want to occupy the same spot */
 unsigned int z_alloc_collisions = 0;
@@ -1163,24 +2243,22 @@ unsigned int z_alloc_overwrites = 0;
 unsigned int z_trace_overwrites = 0;
 
 /* Times a new alloc or trace is put into the hash table */
-unsigned int z_alloc_recorded  = 0;
-unsigned int z_trace_recorded  = 0;
+unsigned int z_alloc_recorded   = 0;
+unsigned int z_trace_recorded   = 0;
 
 /* Times zleak_log returned false due to not being able to acquire the lock */
-unsigned int z_total_conflicts = 0;
+unsigned int z_total_conflicts  = 0;
 
-
-#pragma mark struct zallocation
 /*
  * Structure for keeping track of an allocation
  * An allocation bucket is in use if its element is not NULL
  */
 struct zallocation {
-       uintptr_t               za_element;             /* the element that was zalloc'ed or zfree'ed, NULL if bucket unused */
-       vm_size_t               za_size;                        /* how much memory did this allocation take up? */
-       uint32_t                za_trace_index; /* index into ztraces for backtrace associated with allocation */
+       uintptr_t               za_element;             /* the element that was zalloc'ed or zfree'ed, NULL if bucket unused */
+       vm_size_t               za_size;                        /* how much memory did this allocation take up? */
+       uint32_t                za_trace_index; /* index into ztraces for backtrace associated with allocation */
        /* TODO: #if this out */
-       uint32_t                za_hit_count;           /* for determining effectiveness of hash function */
+       uint32_t                za_hit_count;           /* for determining effectiveness of hash function */
 };
 
 /* Size must be a power of two for the zhash to be able to just mask off bits instead of mod */
@@ -1190,31 +2268,39 @@ uint32_t zleak_trace_buckets = CONFIG_ZLEAK_TRACE_MAP_NUM;
 vm_size_t zleak_max_zonemap_size;
 
 /* Hashmaps of allocations and their corresponding traces */
-static struct zallocation*     zallocations;
-static struct ztrace*          ztraces;
+static struct zallocation*      zallocations;
+static struct ztrace*           ztraces;
 
 /* not static so that panic can see this, see kern/debug.c */
-struct ztrace*                         top_ztrace;
+struct ztrace*                          top_ztrace;
 
 /* Lock to protect zallocations, ztraces, and top_ztrace from concurrent modification. */
-static lck_spin_t                      zleak_lock;
-static lck_attr_t                      zleak_lock_attr;
-static lck_grp_t                       zleak_lock_grp;
-static lck_grp_attr_t                  zleak_lock_grp_attr;
+LCK_GRP_DECLARE(zleak_lock_grp, "zleak_lock");
+LCK_SPIN_DECLARE(zleak_lock, &zleak_lock_grp);
 
 /*
  * Initializes the zone leak monitor.  Called from zone_init()
  */
-static void 
-zleak_init(vm_size_t max_zonemap_size) 
+__startup_func
+static void
+zleak_init(vm_size_t max_zonemap_size)
 {
-       char                    scratch_buf[16];
-       boolean_t               zleak_enable_flag = FALSE;
+       char                    scratch_buf[16];
+       boolean_t               zleak_enable_flag = FALSE;
 
        zleak_max_zonemap_size = max_zonemap_size;
-       zleak_global_tracking_threshold = max_zonemap_size / 2; 
+       zleak_global_tracking_threshold = max_zonemap_size / 2;
        zleak_per_zone_tracking_threshold = zleak_global_tracking_threshold / 8;
 
+#if CONFIG_EMBEDDED
+       if (PE_parse_boot_argn("-zleakon", scratch_buf, sizeof(scratch_buf))) {
+               zleak_enable_flag = TRUE;
+               printf("zone leak detection enabled\n");
+       } else {
+               zleak_enable_flag = FALSE;
+               printf("zone leak detection disabled\n");
+       }
+#else /* CONFIG_EMBEDDED */
        /* -zleakoff (flag to disable zone leak monitor) */
        if (PE_parse_boot_argn("-zleakoff", scratch_buf, sizeof(scratch_buf))) {
                zleak_enable_flag = FALSE;
@@ -1223,7 +2309,8 @@ zleak_init(vm_size_t max_zonemap_size)
                zleak_enable_flag = TRUE;
                printf("zone leak detection enabled\n");
        }
-       
+#endif /* CONFIG_EMBEDDED */
+
        /* zfactor=XXXX (override how often to sample the zone allocator) */
        if (PE_parse_boot_argn("zfactor", &zleak_sample_factor, sizeof(zleak_sample_factor))) {
                printf("Zone leak factor override: %u\n", zleak_sample_factor);
@@ -1233,33 +2320,25 @@ zleak_init(vm_size_t max_zonemap_size)
        if (PE_parse_boot_argn("zleak-allocs", &zleak_alloc_buckets, sizeof(zleak_alloc_buckets))) {
                printf("Zone leak alloc buckets override: %u\n", zleak_alloc_buckets);
                /* uses 'is power of 2' trick: (0x01000 & 0x00FFF == 0) */
-               if (zleak_alloc_buckets == 0 || (zleak_alloc_buckets & (zleak_alloc_buckets-1))) {
+               if (zleak_alloc_buckets == 0 || (zleak_alloc_buckets & (zleak_alloc_buckets - 1))) {
                        printf("Override isn't a power of two, bad things might happen!\n");
                }
        }
-       
+
        /* zleak-traces=XXXX (override number of buckets in ztraces) */
        if (PE_parse_boot_argn("zleak-traces", &zleak_trace_buckets, sizeof(zleak_trace_buckets))) {
                printf("Zone leak trace buckets override: %u\n", zleak_trace_buckets);
                /* uses 'is power of 2' trick: (0x01000 & 0x00FFF == 0) */
-               if (zleak_trace_buckets == 0 || (zleak_trace_buckets & (zleak_trace_buckets-1))) {
+               if (zleak_trace_buckets == 0 || (zleak_trace_buckets & (zleak_trace_buckets - 1))) {
                        printf("Override isn't a power of two, bad things might happen!\n");
                }
        }
-       
-       /* allocate the zleak_lock */
-       lck_grp_attr_setdefault(&zleak_lock_grp_attr);
-       lck_grp_init(&zleak_lock_grp, "zleak_lock", &zleak_lock_grp_attr);
-       lck_attr_setdefault(&zleak_lock_attr);
-       lck_spin_init(&zleak_lock, &zleak_lock_grp, &zleak_lock_attr);
-       
+
        if (zleak_enable_flag) {
                zleak_state = ZLEAK_STATE_ENABLED;
        }
 }
 
-#if CONFIG_ZLEAKS
-
 /*
  * Support for kern.zleak.active sysctl - a simplified
  * version of the zleak_state variable.
@@ -1267,16 +2346,15 @@ zleak_init(vm_size_t max_zonemap_size)
 int
 get_zleak_state(void)
 {
-       if (zleak_state & ZLEAK_STATE_FAILED)
-               return (-1);
-       if (zleak_state & ZLEAK_STATE_ACTIVE)
-               return (1);
-       return (0);
+       if (zleak_state & ZLEAK_STATE_FAILED) {
+               return -1;
+       }
+       if (zleak_state & ZLEAK_STATE_ACTIVE) {
+               return 1;
+       }
+       return 0;
 }
 
-#endif
-
-
 kern_return_t
 zleak_activate(void)
 {
@@ -1320,7 +2398,7 @@ zleak_activate(void)
        ztraces = traces_ptr;
 
        /*
-        * Initialize the top_ztrace to the first entry in ztraces, 
+        * Initialize the top_ztrace to the first entry in ztraces,
         * so we don't have to check for null in zleak_log
         */
        top_ztrace = &ztraces[0];
@@ -1334,10 +2412,10 @@ zleak_activate(void)
        zleak_state |= ZLEAK_STATE_ACTIVE;
        zleak_state &= ~ZLEAK_STATE_ACTIVATING;
        lck_spin_unlock(&zleak_lock);
-       
+
        return 0;
 
-fail:  
+fail:
        /*
         * If we fail to allocate memory, don't further tax
         * the system by trying again.
@@ -1359,15 +2437,15 @@ fail:
 }
 
 /*
- * TODO: What about allocations that never get deallocated, 
+ * TODO: What about allocations that never get deallocated,
  * especially ones with unique backtraces? Should we wait to record
- * until after boot has completed?  
+ * until after boot has completed?
  * (How many persistent zallocs are there?)
  */
 
 /*
- * This function records the allocation in the allocations table, 
- * and stores the associated backtrace in the traces table 
+ * This function records the allocation in the allocations table,
+ * and stores the associated backtrace in the traces table
  * (or just increments the refcount if the trace is already recorded)
  * If the allocation slot is in use, the old allocation is replaced with the new allocation, and
  * the associated trace's refcount is decremented.
@@ -1377,47 +2455,47 @@ fail:
  */
 static boolean_t
 zleak_log(uintptr_t* bt,
-                 uintptr_t addr,
-                 uint32_t depth,
-                 vm_size_t allocation_size) 
+    uintptr_t addr,
+    uint32_t depth,
+    vm_size_t allocation_size)
 {
        /* Quit if there's someone else modifying the hash tables */
        if (!lck_spin_try_lock(&zleak_lock)) {
                z_total_conflicts++;
                return FALSE;
        }
-       
-       struct zallocation* allocation  = &zallocations[hashaddr(addr, zleak_alloc_buckets)];
-       
+
+       struct zallocation* allocation  = &zallocations[hashaddr(addr, zleak_alloc_buckets)];
+
        uint32_t trace_index = hashbacktrace(bt, depth, zleak_trace_buckets);
        struct ztrace* trace = &ztraces[trace_index];
-       
+
        allocation->za_hit_count++;
        trace->zt_hit_count++;
-       
-       /* 
+
+       /*
         * If the allocation bucket we want to be in is occupied, and if the occupier
-        * has the same trace as us, just bail.  
+        * has the same trace as us, just bail.
         */
        if (allocation->za_element != (uintptr_t) 0 && trace_index == allocation->za_trace_index) {
                z_alloc_collisions++;
-               
+
                lck_spin_unlock(&zleak_lock);
                return TRUE;
        }
-       
+
        /* STEP 1: Store the backtrace in the traces array. */
        /* A size of zero indicates that the trace bucket is free. */
-       
-       if (trace->zt_size > 0 && bcmp(trace->zt_stack, bt, (depth * sizeof(uintptr_t))) != 0 ) {
-               /* 
+
+       if (trace->zt_size > 0 && bcmp(trace->zt_stack, bt, (depth * sizeof(uintptr_t))) != 0) {
+               /*
                 * Different unique trace with same hash!
                 * Just bail - if we're trying to record the leaker, hopefully the other trace will be deallocated
                 * and get out of the way for later chances
                 */
                trace->zt_collisions++;
                z_trace_collisions++;
-               
+
                lck_spin_unlock(&zleak_lock);
                return TRUE;
        } else if (trace->zt_size > 0) {
@@ -1425,28 +2503,29 @@ zleak_log(uintptr_t* bt,
                trace->zt_size += allocation_size;
        } else {
                /* Found an unused trace bucket, record the trace here! */
-               if (trace->zt_depth != 0) /* if this slot was previously used but not currently in use */
+               if (trace->zt_depth != 0) /* if this slot was previously used but not currently in use */
                        z_trace_overwrites++;
-               
+               }
+
                z_trace_recorded++;
-               trace->zt_size                  = allocation_size;
-               memcpy(trace->zt_stack, bt, (depth * sizeof(uintptr_t)) );
-               
-               trace->zt_depth         = depth;
-               trace->zt_collisions    = 0;
+               trace->zt_size                  = allocation_size;
+               memcpy(trace->zt_stack, bt, (depth * sizeof(uintptr_t)));
+
+               trace->zt_depth         = depth;
+               trace->zt_collisions    = 0;
        }
-       
+
        /* STEP 2: Store the allocation record in the allocations array. */
-       
+
        if (allocation->za_element != (uintptr_t) 0) {
-               /* 
+               /*
                 * Straight up replace any allocation record that was there.  We don't want to do the work
-                * to preserve the allocation entries that were there, because we only record a subset of the 
+                * to preserve the allocation entries that were there, because we only record a subset of the
                 * allocations anyways.
                 */
-               
+
                z_alloc_collisions++;
-               
+
                struct ztrace* associated_trace = &ztraces[allocation->za_trace_index];
                /* Knock off old allocation's size, not the new allocation */
                associated_trace->zt_size -= allocation->za_size;
@@ -1455,15 +2534,16 @@ zleak_log(uintptr_t* bt,
                z_alloc_overwrites++;
        }
 
-       allocation->za_element          = addr;
-       allocation->za_trace_index      = trace_index;
-       allocation->za_size             = allocation_size;
-       
+       allocation->za_element          = addr;
+       allocation->za_trace_index      = trace_index;
+       allocation->za_size             = allocation_size;
+
        z_alloc_recorded++;
-       
-       if (top_ztrace->zt_size < trace->zt_size)
+
+       if (top_ztrace->zt_size < trace->zt_size) {
                top_ztrace = trace;
-       
+       }
+
        lck_spin_unlock(&zleak_lock);
        return TRUE;
 }
@@ -1472,944 +2552,1939 @@ zleak_log(uintptr_t* bt,
  * Free the allocation record and release the stacktrace.
  * This should be as fast as possible because it will be called for every free.
  */
+__attribute__((noinline))
 static void
 zleak_free(uintptr_t addr,
-                  vm_size_t allocation_size) 
+    vm_size_t allocation_size)
 {
-       if (addr == (uintptr_t) 0)
+       if (addr == (uintptr_t) 0) {
                return;
-       
+       }
+
        struct zallocation* allocation = &zallocations[hashaddr(addr, zleak_alloc_buckets)];
-       
+
        /* Double-checked locking: check to find out if we're interested, lock, check to make
         * sure it hasn't changed, then modify it, and release the lock.
         */
-       
+
        if (allocation->za_element == addr && allocation->za_trace_index < zleak_trace_buckets) {
                /* if the allocation was the one, grab the lock, check again, then delete it */
                lck_spin_lock(&zleak_lock);
-               
+
                if (allocation->za_element == addr && allocation->za_trace_index < zleak_trace_buckets) {
                        struct ztrace *trace;
 
                        /* allocation_size had better match what was passed into zleak_log - otherwise someone is freeing into the wrong zone! */
                        if (allocation->za_size != allocation_size) {
-                               panic("Freeing as size %lu memory that was allocated with size %lu\n", 
-                                               (uintptr_t)allocation_size, (uintptr_t)allocation->za_size);
+                               panic("Freeing as size %lu memory that was allocated with size %lu\n",
+                                   (uintptr_t)allocation_size, (uintptr_t)allocation->za_size);
                        }
-                       
+
                        trace = &ztraces[allocation->za_trace_index];
-                       
+
                        /* size of 0 indicates trace bucket is unused */
                        if (trace->zt_size > 0) {
                                trace->zt_size -= allocation_size;
                        }
-                       
-                       /* A NULL element means the allocation bucket is unused */
-                       allocation->za_element = 0;
+
+                       /* A NULL element means the allocation bucket is unused */
+                       allocation->za_element = 0;
+               }
+               lck_spin_unlock(&zleak_lock);
+       }
+}
+
+#endif /* CONFIG_ZLEAKS */
+
+/*  These functions outside of CONFIG_ZLEAKS because they are also used in
+ *  mbuf.c for mbuf leak-detection.  This is why they lack the z_ prefix.
+ */
+
+/* "Thomas Wang's 32/64 bit mix functions."  http://www.concentric.net/~Ttwang/tech/inthash.htm */
+uintptr_t
+hash_mix(uintptr_t x)
+{
+#ifndef __LP64__
+       x += ~(x << 15);
+       x ^=  (x >> 10);
+       x +=  (x << 3);
+       x ^=  (x >> 6);
+       x += ~(x << 11);
+       x ^=  (x >> 16);
+#else
+       x += ~(x << 32);
+       x ^=  (x >> 22);
+       x += ~(x << 13);
+       x ^=  (x >> 8);
+       x +=  (x << 3);
+       x ^=  (x >> 15);
+       x += ~(x << 27);
+       x ^=  (x >> 31);
+#endif
+       return x;
+}
+
+uint32_t
+hashbacktrace(uintptr_t* bt, uint32_t depth, uint32_t max_size)
+{
+       uintptr_t hash = 0;
+       uintptr_t mask = max_size - 1;
+
+       while (depth) {
+               hash += bt[--depth];
+       }
+
+       hash = hash_mix(hash) & mask;
+
+       assert(hash < max_size);
+
+       return (uint32_t) hash;
+}
+
+/*
+ *  TODO: Determine how well distributed this is
+ *      max_size must be a power of 2. i.e 0x10000 because 0x10000-1 is 0x0FFFF which is a great bitmask
+ */
+uint32_t
+hashaddr(uintptr_t pt, uint32_t max_size)
+{
+       uintptr_t hash = 0;
+       uintptr_t mask = max_size - 1;
+
+       hash = hash_mix(pt) & mask;
+
+       assert(hash < max_size);
+
+       return (uint32_t) hash;
+}
+
+/* End of all leak-detection code */
+#pragma mark zone creation, configuration, destruction
+
+static zone_t
+zone_init_defaults(zone_id_t zid)
+{
+       zone_t z = &zone_array[zid];
+
+       z->page_count_max = ~0u;
+       z->collectable = true;
+       z->expandable = true;
+       z->submap_idx = Z_SUBMAP_IDX_GENERAL_MAP;
+
+       simple_lock_init(&z->lock, 0);
+
+       return z;
+}
+
+static bool
+zone_is_initializing(zone_t z)
+{
+       return !z->z_self && !z->destroyed;
+}
+
+static void
+zone_set_max(zone_t z, vm_size_t max)
+{
+#if KASAN_ZALLOC
+       if (z->kasan_redzone) {
+               /*
+                * Adjust the max memory for the kasan redzones
+                */
+               max += (max / z->pcpu_elem_size) * z->kasan_redzone * 2;
+       }
+#endif
+       if (max < z->percpu ? 1 : z->alloc_pages) {
+               max = z->percpu ? 1 : z->alloc_pages;
+       } else {
+               max = atop(round_page(max));
+       }
+       z->page_count_max = max;
+}
+
+void
+zone_set_submap_idx(zone_t zone, unsigned int sub_map_idx)
+{
+       if (!zone_is_initializing(zone)) {
+               panic("%s: called after zone_create()", __func__);
+       }
+       if (sub_map_idx > zone_last_submap_idx) {
+               panic("zone_set_submap_idx(%d) > %d", sub_map_idx, zone_last_submap_idx);
+       }
+       zone->submap_idx = sub_map_idx;
+}
+
+void
+zone_set_noexpand(
+       zone_t          zone,
+       vm_size_t       max)
+{
+       if (!zone_is_initializing(zone)) {
+               panic("%s: called after zone_create()", __func__);
+       }
+       zone->expandable = false;
+       zone_set_max(zone, max);
+}
+
+void
+zone_set_exhaustible(
+       zone_t          zone,
+       vm_size_t       max)
+{
+       if (!zone_is_initializing(zone)) {
+               panic("%s: called after zone_create()", __func__);
+       }
+       zone->expandable = false;
+       zone->exhaustible = true;
+       zone_set_max(zone, max);
+}
+
+/**
+ * @function zone_create_find
+ *
+ * @abstract
+ * Finds an unused zone for the given name and element size.
+ *
+ * @param name          the zone name
+ * @param size          the element size (including redzones, ...)
+ * @param flags         the flags passed to @c zone_create*
+ * @param zid           the desired zone ID or ZONE_ID_ANY
+ *
+ * @returns             a zone to initialize further.
+ */
+static zone_t
+zone_create_find(
+       const char             *name,
+       vm_size_t               size,
+       zone_create_flags_t     flags,
+       zone_id_t               zid)
+{
+       zone_id_t nzones;
+       zone_t z;
+
+       simple_lock(&all_zones_lock, &zone_locks_grp);
+
+       nzones = (zone_id_t)os_atomic_load(&num_zones, relaxed);
+       assert(num_zones_in_use <= nzones && nzones < MAX_ZONES);
+
+       if (__improbable(nzones < ZONE_ID__FIRST_DYNAMIC)) {
+               /*
+                * The first time around, make sure the reserved zone IDs
+                * have an initialized lock as zone_index_foreach() will
+                * enumerate them.
+                */
+               while (nzones < ZONE_ID__FIRST_DYNAMIC) {
+                       zone_init_defaults(nzones++);
+               }
+
+               os_atomic_store(&num_zones, nzones, release);
+       }
+
+       if (zid != ZONE_ID_ANY) {
+               if (zid >= ZONE_ID__FIRST_DYNAMIC) {
+                       panic("zone_create: invalid desired zone ID %d for %s",
+                           zid, name);
+               }
+               if (flags & ZC_DESTRUCTIBLE) {
+                       panic("zone_create: ID %d (%s) must be permanent", zid, name);
+               }
+               if (zone_array[zid].z_self) {
+                       panic("zone_create: creating zone ID %d (%s) twice", zid, name);
+               }
+               z = &zone_array[zid];
+       } else {
+               if (flags & ZC_DESTRUCTIBLE) {
+                       /*
+                        * If possible, find a previously zdestroy'ed zone in the
+                        * zone_array that we can reuse.
+                        */
+                       for (int i = bitmap_first(zone_destroyed_bitmap, MAX_ZONES);
+                           i >= 0; i = bitmap_next(zone_destroyed_bitmap, i)) {
+                               z = &zone_array[i];
+
+                               /*
+                                * If the zone name and the element size are the
+                                * same, we can just reuse the old zone struct.
+                                */
+                               if (strcmp(z->z_name, name) || zone_elem_size(z) != size) {
+                                       continue;
+                               }
+                               bitmap_clear(zone_destroyed_bitmap, i);
+                               z->destroyed = false;
+                               z->z_self = z;
+                               zid = (zone_id_t)i;
+                               goto out;
+                       }
+               }
+
+               zid = nzones++;
+               z = zone_init_defaults(zid);
+
+               /*
+                * The release barrier pairs with the acquire in
+                * zone_index_foreach() and makes sure that enumeration loops
+                * always see an initialized zone lock.
+                */
+               os_atomic_store(&num_zones, nzones, release);
+       }
+
+out:
+       num_zones_in_use++;
+       simple_unlock(&all_zones_lock);
+
+       return z;
+}
+
+__abortlike
+static void
+zone_create_panic(const char *name, const char *f1, const char *f2)
+{
+       panic("zone_create: creating zone %s: flag %s and %s are incompatible",
+           name, f1, f2);
+}
+#define zone_create_assert_not_both(name, flags, current_flag, forbidden_flag) \
+       if ((flags) & forbidden_flag) { \
+               zone_create_panic(name, #current_flag, #forbidden_flag); \
+       }
+
+/*
+ * Adjusts the size of the element based on minimum size, alignment
+ * and kasan redzones
+ */
+static vm_size_t
+zone_elem_adjust_size(
+       const char             *name __unused,
+       vm_size_t               elem_size,
+       zone_create_flags_t     flags,
+       vm_size_t              *redzone __unused)
+{
+       vm_size_t size;
+       /*
+        * Adjust element size for minimum size and pointer alignment
+        */
+       size = (elem_size + sizeof(vm_offset_t) - 1) & -sizeof(vm_offset_t);
+       if (((flags & ZC_PERCPU) == 0) && size < ZONE_MIN_ELEM_SIZE) {
+               size = ZONE_MIN_ELEM_SIZE;
+       }
+
+#if KASAN_ZALLOC
+       /*
+        * Expand the zone allocation size to include the redzones.
+        *
+        * For page-multiple zones add a full guard page because they
+        * likely require alignment.
+        */
+       vm_size_t redzone_tmp;
+       if (flags & (ZC_KASAN_NOREDZONE | ZC_PERCPU)) {
+               redzone_tmp = 0;
+       } else if ((size & PAGE_MASK) == 0) {
+               if (size != PAGE_SIZE && (flags & ZC_ALIGNMENT_REQUIRED)) {
+                       panic("zone_create: zone %s can't provide more than PAGE_SIZE"
+                           "alignment", name);
+               }
+               redzone_tmp = PAGE_SIZE;
+       } else if (flags & ZC_ALIGNMENT_REQUIRED) {
+               redzone_tmp = 0;
+       } else {
+               redzone_tmp = KASAN_GUARD_SIZE;
+       }
+       size += redzone_tmp * 2;
+       if (redzone) {
+               *redzone = redzone_tmp;
+       }
+#endif
+       return size;
+}
+
+/*
+ * Returns the allocation chunk size that has least framentation
+ */
+static vm_size_t
+zone_get_min_alloc_granule(
+       vm_size_t               elem_size,
+       zone_create_flags_t     flags)
+{
+       vm_size_t alloc_granule = PAGE_SIZE;
+       if (flags & ZC_PERCPU) {
+               alloc_granule = PAGE_SIZE * zpercpu_count();
+               if (PAGE_SIZE % elem_size > 256) {
+                       panic("zone_create: per-cpu zone has too much fragmentation");
+               }
+       } else if ((elem_size & PAGE_MASK) == 0) {
+               /* zero fragmentation by definition */
+               alloc_granule = elem_size;
+       } else if (alloc_granule % elem_size == 0) {
+               /* zero fragmentation by definition */
+       } else {
+               vm_size_t frag = (alloc_granule % elem_size) * 100 / alloc_granule;
+               vm_size_t alloc_tmp = PAGE_SIZE;
+               while ((alloc_tmp += PAGE_SIZE) <= ZONE_MAX_ALLOC_SIZE) {
+                       vm_size_t frag_tmp = (alloc_tmp % elem_size) * 100 / alloc_tmp;
+                       if (frag_tmp < frag) {
+                               frag = frag_tmp;
+                               alloc_granule = alloc_tmp;
+                       }
                }
-               lck_spin_unlock(&zleak_lock);
        }
+       return alloc_granule;
 }
 
-#endif /* CONFIG_ZLEAKS */
+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)
+{
+       vm_size_t adjusted_size = zone_elem_adjust_size(name, elem_size, flags,
+           NULL);
+       vm_size_t alloc_granule = zone_get_min_alloc_granule(adjusted_size,
+           flags);
+       vm_size_t min_size = min_pages * PAGE_SIZE;
+       /*
+        * Round up min_size to a multiple of alloc_granule
+        */
+       return ((min_size + alloc_granule - 1) / alloc_granule)
+              * alloc_granule;
+}
 
-/*  These functions outside of CONFIG_ZLEAKS because they are also used in
- *  mbuf.c for mbuf leak-detection.  This is why they lack the z_ prefix.
- */
+zone_t
+zone_create_ext(
+       const char             *name,
+       vm_size_t               size,
+       zone_create_flags_t     flags,
+       zone_id_t               desired_zid,
+       void                  (^extra_setup)(zone_t))
+{
+       vm_size_t alloc;
+       vm_size_t redzone;
+       zone_t z;
 
-/*
- * This function captures a backtrace from the current stack and
- * returns the number of frames captured, limited by max_frames.
- * It's fast because it does no checking to make sure there isn't bad data.
- * Since it's only called from threads that we're going to keep executing,
- * if there's bad data we were going to die eventually.
- * If this function is inlined, it doesn't record the frame of the function it's inside.
- * (because there's no stack frame!)
- */
+       if (size > ZONE_MAX_ALLOC_SIZE) {
+               panic("zone_create: element size too large: %zd", (size_t)size);
+       }
 
-uint32_t
-fastbacktrace(uintptr_t* bt, uint32_t max_frames)
-{
-       uintptr_t* frameptr = NULL, *frameptr_next = NULL;
-       uintptr_t retaddr = 0;
-       uint32_t frame_index = 0, frames = 0;
-       uintptr_t kstackb, kstackt;
-       thread_t cthread = current_thread();
+       size = zone_elem_adjust_size(name, size, flags, &redzone);
+       /*
+        * Allocate the zone slot, return early if we found an older match.
+        */
+       z = zone_create_find(name, size, flags, desired_zid);
+       if (__improbable(z->z_self)) {
+               /* We found a zone to reuse */
+               return z;
+       }
 
-       if (__improbable(cthread == NULL))
-               return 0;
+       /*
+        * Initialize the zone properly.
+        */
 
-       kstackb = cthread->kernel_stack;
-       kstackt = kstackb + kernel_stack_size;
-       /* Load stack frame pointer (EBP on x86) into frameptr */
-       frameptr = __builtin_frame_address(0);
-       if (((uintptr_t)frameptr > kstackt) || ((uintptr_t)frameptr < kstackb))
-               frameptr = NULL;
+       /*
+        * If the kernel is post lockdown, copy the zone name passed in.
+        * Else simply maintain a pointer to the name string as it can only
+        * be a core XNU zone (no unloadable kext exists before lockdown).
+        */
+       if (startup_phase >= STARTUP_SUB_LOCKDOWN) {
+               size_t nsz = MIN(strlen(name) + 1, MACH_ZONE_NAME_MAX_LEN);
+               char *buf = zalloc_permanent(nsz, ZALIGN_NONE);
+               strlcpy(buf, name, nsz);
+               z->z_name = buf;
+       } else {
+               z->z_name = name;
+       }
+       /*
+        * If zone_init() hasn't run yet, the permanent zones do not exist.
+        * We can limp along without properly initialized stats for a while,
+        * zone_init() will rebuild the missing stats when it runs.
+        */
+       if (__probable(zone_array[ZONE_ID_PERCPU_PERMANENT].z_self)) {
+               z->z_stats = zalloc_percpu_permanent_type(struct zone_stats);
+       }
 
-       while (frameptr != NULL && frame_index < max_frames ) {
-               /* Next frame pointer is pointed to by the previous one */
-               frameptr_next = (uintptr_t*) *frameptr;
+       alloc = zone_get_min_alloc_granule(size, flags);
 
-               /* Bail if we see a zero in the stack frame, that means we've reached the top of the stack */
-                /* That also means the return address is worthless, so don't record it */
-               if (frameptr_next == NULL)
-                       break;
-               /* Verify thread stack bounds */
-               if (((uintptr_t)frameptr_next > kstackt) || ((uintptr_t)frameptr_next < kstackb))
-                       break;
-               /* Pull return address from one spot above the frame pointer */
-               retaddr = *(frameptr + 1);
+       if (flags & ZC_KALLOC_HEAP) {
+               size_t rem = (alloc % size) / (alloc / size);
 
-               /* Store it in the backtrace array */
-               bt[frame_index++] = retaddr;
+               /*
+                * Try to grow the elements size and spread them more if the remaining
+                * space is large enough.
+                */
+               size += rem & ~(KALLOC_MINALIGN - 1);
+       }
 
-               frameptr = frameptr_next;
+       z->pcpu_elem_size = z->z_elem_size = (uint16_t)size;
+       z->alloc_pages = (uint16_t)atop(alloc);
+#if KASAN_ZALLOC
+       z->kasan_redzone = redzone;
+       if (strncmp(name, "fakestack.", sizeof("fakestack.") - 1) == 0) {
+               z->kasan_fakestacks = true;
        }
+#endif
 
-       /* Save the number of frames captured for return value */
-       frames = frame_index;
+       /*
+        * Handle KPI flags
+        */
+#if __LP64__
+       if (flags & ZC_SEQUESTER) {
+               z->va_sequester = true;
+       }
+#endif
+       /* ZC_CACHING applied after all configuration is done */
 
-       /* Fill in the rest of the backtrace with zeros */
-       while (frame_index < max_frames)
-               bt[frame_index++] = 0;
+       if (flags & ZC_PERCPU) {
+               /*
+                * ZC_CACHING is disallowed because it uses per-cpu zones for its
+                * implementation and it would be circular. These allocations are
+                * also quite expensive, so caching feels dangerous memory wise too.
+                *
+                * ZC_ZFREE_CLEARMEM is forced because per-cpu zones allow for
+                * pointer-sized allocations which poisoning doesn't support.
+                */
+               zone_create_assert_not_both(name, flags, ZC_PERCPU, ZC_CACHING);
+               zone_create_assert_not_both(name, flags, ZC_PERCPU, ZC_ALLOW_FOREIGN);
+               z->percpu = true;
+               z->gzalloc_exempt = true;
+               z->zfree_clear_mem = true;
+               z->pcpu_elem_size *= zpercpu_count();
+       }
+       if (flags & ZC_ZFREE_CLEARMEM) {
+               z->zfree_clear_mem = true;
+       }
+       if (flags & ZC_NOGC) {
+               z->collectable = false;
+       }
+       if (flags & ZC_NOENCRYPT) {
+               z->noencrypt = true;
+       }
+       if (flags & ZC_ALIGNMENT_REQUIRED) {
+               z->alignment_required = true;
+       }
+       if (flags & ZC_NOGZALLOC) {
+               z->gzalloc_exempt = true;
+       }
+       if (flags & ZC_NOCALLOUT) {
+               z->no_callout = true;
+       }
+       if (flags & ZC_DESTRUCTIBLE) {
+               zone_create_assert_not_both(name, flags, ZC_DESTRUCTIBLE, ZC_CACHING);
+               zone_create_assert_not_both(name, flags, ZC_DESTRUCTIBLE, ZC_ALLOW_FOREIGN);
+               z->destructible = true;
+       }
 
-       return frames;
-}
+       /*
+        * Handle Internal flags
+        */
+       if (flags & ZC_ALLOW_FOREIGN) {
+               z->allows_foreign = true;
+       }
+       if ((ZSECURITY_OPTIONS_SUBMAP_USER_DATA & zsecurity_options) &&
+           (flags & ZC_DATA_BUFFERS)) {
+               z->submap_idx = Z_SUBMAP_IDX_BAG_OF_BYTES_MAP;
+       }
+       if (flags & ZC_KASAN_NOQUARANTINE) {
+               z->kasan_noquarantine = true;
+       }
+       /* ZC_KASAN_NOREDZONE already handled */
 
-/* "Thomas Wang's 32/64 bit mix functions."  http://www.concentric.net/~Ttwang/tech/inthash.htm */
-uintptr_t
-hash_mix(uintptr_t x)
-{
-#ifndef __LP64__
-       x += ~(x << 15);
-       x ^=  (x >> 10);
-       x +=  (x << 3 );
-       x ^=  (x >> 6 );
-       x += ~(x << 11);
-       x ^=  (x >> 16);
-#else
-       x += ~(x << 32);
-       x ^=  (x >> 22);
-       x += ~(x << 13);
-       x ^=  (x >> 8 );
-       x +=  (x << 3 );
-       x ^=  (x >> 15);
-       x += ~(x << 27);
-       x ^=  (x >> 31);
-#endif
-       return x;
-}
+       /*
+        * Then if there's extra tuning, do it
+        */
+       if (extra_setup) {
+               extra_setup(z);
+       }
 
-uint32_t
-hashbacktrace(uintptr_t* bt, uint32_t depth, uint32_t max_size)
-{
+       /*
+        * Configure debugging features
+        */
+#if CONFIG_GZALLOC
+       gzalloc_zone_init(z); /* might set z->gzalloc_tracked */
+#endif
+#if ZONE_ENABLE_LOGGING
+       if (!z->gzalloc_tracked && num_zones_logged < max_num_zones_to_log) {
+               /*
+                * Check for and set up zone leak detection if requested via boot-args.
+                * might set z->zone_logging
+                */
+               zone_setup_logging(z);
+       }
+#endif /* ZONE_ENABLE_LOGGING */
+#if VM_MAX_TAG_ZONES
+       if (!z->gzalloc_tracked && z->kalloc_heap && zone_tagging_on) {
+               static int tag_zone_index;
+               vm_offset_t esize = zone_elem_size(z);
+               z->tags = true;
+               z->tags_inline = (((page_size + esize - 1) / esize) <=
+                   (sizeof(uint32_t) / sizeof(uint16_t)));
+               z->tag_zone_index = os_atomic_inc_orig(&tag_zone_index, relaxed);
+               assert(z->tag_zone_index < VM_MAX_TAG_ZONES);
+       }
+#endif
 
-       uintptr_t hash = 0;
-       uintptr_t mask = max_size - 1;
+       /*
+        * Finally, fixup properties based on security policies, boot-args, ...
+        */
+       if ((ZSECURITY_OPTIONS_SUBMAP_USER_DATA & zsecurity_options) &&
+           z->kalloc_heap == KHEAP_ID_DATA_BUFFERS) {
+               z->submap_idx = Z_SUBMAP_IDX_BAG_OF_BYTES_MAP;
+       }
+#if __LP64__
+       if ((ZSECURITY_OPTIONS_SEQUESTER & zsecurity_options) &&
+           (flags & ZC_NOSEQUESTER) == 0 &&
+           z->submap_idx == Z_SUBMAP_IDX_GENERAL_MAP) {
+               z->va_sequester = true;
+       }
+#endif
+       /*
+        * Always clear zone elements smaller than a cacheline,
+        * because it's pretty close to free.
+        */
+       if (size <= zp_min_size) {
+               z->zfree_clear_mem = true;
+       }
+       if (zp_factor != 0 && !z->zfree_clear_mem) {
+               z->zp_count = zone_poison_count_init(z);
+       }
 
-       while (depth) {
-               hash += bt[--depth];
+#if CONFIG_ZCACHE
+       if ((flags & ZC_NOCACHING) == 0) {
+               /*
+                * Append kalloc heap name to zone name (if zone is used by kalloc)
+                */
+               char temp_zone_name[MAX_ZONE_NAME] = "";
+               snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s", zone_heap_name(z), z->z_name);
+
+               /* Check if boot-arg specified it should have a cache */
+               if (track_this_zone(temp_zone_name, cache_zone_name)) {
+                       flags |= ZC_CACHING;
+               } else if (zcc_kalloc && z->kalloc_heap) {
+                       flags |= ZC_CACHING;
+               }
+       }
+       if ((flags & ZC_CACHING) &&
+           !z->tags && !z->zone_logging && !z->gzalloc_tracked) {
+               zcache_init(z);
        }
+#endif /* CONFIG_ZCACHE */
 
-       hash = hash_mix(hash) & mask;
+       lock_zone(z);
+       z->z_self = z;
+       unlock_zone(z);
 
-       assert(hash < max_size);
+       return z;
+}
 
-       return (uint32_t) hash;
+__startup_func
+void
+zone_create_startup(struct zone_create_startup_spec *spec)
+{
+       *spec->z_var = zone_create_ext(spec->z_name, spec->z_size,
+           spec->z_flags, spec->z_zid, spec->z_setup);
 }
 
 /*
- *  TODO: Determine how well distributed this is
- *      max_size must be a power of 2. i.e 0x10000 because 0x10000-1 is 0x0FFFF which is a great bitmask
+ * The 4 first field of a zone_view and a zone alias, so that the zone_or_view_t
+ * union works. trust but verify.
  */
-uint32_t
-hashaddr(uintptr_t pt, uint32_t max_size)
+#define zalloc_check_zov_alias(f1, f2) \
+    static_assert(offsetof(struct zone, f1) == offsetof(struct zone_view, f2))
+zalloc_check_zov_alias(z_self, zv_zone);
+zalloc_check_zov_alias(z_stats, zv_stats);
+zalloc_check_zov_alias(z_name, zv_name);
+zalloc_check_zov_alias(z_views, zv_next);
+#undef zalloc_check_zov_alias
+
+__startup_func
+void
+zone_view_startup_init(struct zone_view_startup_spec *spec)
 {
-       uintptr_t hash = 0;
-       uintptr_t mask = max_size - 1;
-
-       hash = hash_mix(pt) & mask;
+       struct kalloc_heap *heap = NULL;
+       zone_view_t zv = spec->zv_view;
+       zone_t z;
+
+       switch (spec->zv_heapid) {
+       case KHEAP_ID_DEFAULT:
+               heap = KHEAP_DEFAULT;
+               break;
+       case KHEAP_ID_DATA_BUFFERS:
+               heap = KHEAP_DATA_BUFFERS;
+               break;
+       case KHEAP_ID_KEXT:
+               heap = KHEAP_KEXT;
+               break;
+       default:
+               heap = NULL;
+       }
 
-       assert(hash < max_size);
+       if (heap) {
+               z = kalloc_heap_zone_for_size(heap, spec->zv_size);
+               assert(z);
+       } else {
+               z = spec->zv_zone;
+               assert(spec->zv_size <= zone_elem_size(z));
+       }
 
-       return (uint32_t) hash;
+       zv->zv_zone  = z;
+       zv->zv_stats = zalloc_percpu_permanent_type(struct zone_stats);
+       zv->zv_next  = z->z_views;
+       if (z->z_views == NULL && z->kalloc_heap == KHEAP_ID_NONE) {
+               /*
+                * count the raw view for zones not in a heap,
+                * kalloc_heap_init() already counts it for its members.
+                */
+               zone_view_count += 2;
+       } else {
+               zone_view_count += 1;
+       }
+       z->z_views = zv;
 }
 
-/* End of all leak-detection code */
-#pragma mark -
+zone_t
+zone_create(
+       const char             *name,
+       vm_size_t               size,
+       zone_create_flags_t     flags)
+{
+       return zone_create_ext(name, size, flags, ZONE_ID_ANY, NULL);
+}
 
-/*
- *     zinit initializes a new zone.  The zone data structures themselves
- *     are stored in a zone, which is initially a static structure that
- *     is initialized by zone_init.
- */
 zone_t
 zinit(
-       vm_size_t       size,           /* the size of an element */
-       vm_size_t       max,            /* maximum memory to use */
-       vm_size_t       alloc,          /* allocation size */
-       const char      *name)          /* a name for the zone */
+       vm_size_t       size,           /* the size of an element */
+       vm_size_t       max,            /* maximum memory to use */
+       vm_size_t       alloc __unused, /* allocation size */
+       const char      *name)          /* a name for the zone */
 {
-       zone_t          z;
-       boolean_t       use_page_list = FALSE;
+       zone_t z = zone_create(name, size, ZC_DESTRUCTIBLE);
+       zone_set_max(z, max);
+       return z;
+}
 
-       if (zone_zone == ZONE_NULL) {
+void
+zdestroy(zone_t z)
+{
+       unsigned int zindex = zone_index(z);
 
-               z = (struct zone *)zdata;
-               /* special handling in zcram() because the first element is being used */
-       } else
-               z = (zone_t) zalloc(zone_zone);
+       lock_zone(z);
 
-       if (z == ZONE_NULL)
-               return(ZONE_NULL);
+       if (!z->destructible || zone_caching_enabled(z) || z->allows_foreign) {
+               panic("zdestroy: Zone %s%s isn't destructible",
+                   zone_heap_name(z), z->z_name);
+       }
 
-       /* Zone elements must fit both a next pointer and a backup pointer */
-       vm_size_t  minimum_element_size = sizeof(vm_offset_t) * 2;
-       if (size < minimum_element_size)
-               size = minimum_element_size;
+       if (!z->z_self || z->expanding_no_vm_priv || z->expanding_vm_priv ||
+           z->async_pending || z->waiting) {
+               panic("zdestroy: Zone %s%s in an invalid state for destruction",
+                   zone_heap_name(z), z->z_name);
+       }
 
+#if !KASAN_ZALLOC
        /*
-        *  Round element size to a multiple of sizeof(pointer)
-        *  This also enforces that allocations will be aligned on pointer boundaries
+        * Unset the valid bit. We'll hit an assert failure on further operations
+        * on this zone, until zinit() is called again.
+        *
+        * Leave the zone valid for KASan as we will see zfree's on quarantined free
+        * elements even after the zone is destroyed.
         */
-       size = ((size-1) + sizeof(vm_offset_t)) -
-              ((size-1) % sizeof(vm_offset_t));
-
-       if (alloc == 0)
-               alloc = PAGE_SIZE;
+       z->z_self = NULL;
+#endif
+       z->destroyed = true;
+       unlock_zone(z);
 
-       alloc = round_page(alloc);
-       max   = round_page(max);
+       /* Dump all the free elements */
+       zone_drop_free_elements(z);
 
-       /*
-        * we look for an allocation size with less than 1% waste
-        * up to 5 pages in size...
-        * otherwise, we look for an allocation size with least fragmentation
-        * in the range of 1 - 5 pages
-        * This size will be used unless
-        * the user suggestion is larger AND has less fragmentation
-        */
-#if    ZONE_ALIAS_ADDR
-       /* Favor PAGE_SIZE allocations unless we waste >10% space */
-       if ((size < PAGE_SIZE) && (PAGE_SIZE % size <= PAGE_SIZE / 10))
-               alloc = PAGE_SIZE;
-       else
+#if CONFIG_GZALLOC
+       if (__improbable(z->gzalloc_tracked)) {
+               /* If the zone is gzalloc managed dump all the elements in the free cache */
+               gzalloc_empty_free_cache(z);
+       }
 #endif
-#if    defined(__LP64__)               
-               if (((alloc % size) != 0) || (alloc > PAGE_SIZE * 8))
+
+       lock_zone(z);
+
+       while (!zone_pva_is_null(z->pages_sequester)) {
+               struct zone_page_metadata *page_meta;
+               vm_offset_t                free_addr;
+
+               page_meta = zone_sequestered_page_get(z, &free_addr);
+               unlock_zone(z);
+               kmem_free(submap_for_zone(z), free_addr, ptoa(z->alloc_pages));
+               lock_zone(z);
+       }
+
+#if !KASAN_ZALLOC
+       /* Assert that all counts are zero */
+       if (z->countavail || z->countfree || zone_size_wired(z) ||
+           z->allfree_page_count || z->sequester_page_count) {
+               panic("zdestroy: Zone %s%s isn't empty at zdestroy() time",
+                   zone_heap_name(z), z->z_name);
+       }
+
+       /* consistency check: make sure everything is indeed empty */
+       assert(zone_pva_is_null(z->pages_any_free_foreign));
+       assert(zone_pva_is_null(z->pages_all_used_foreign));
+       assert(zone_pva_is_null(z->pages_all_free));
+       assert(zone_pva_is_null(z->pages_intermediate));
+       assert(zone_pva_is_null(z->pages_all_used));
+       assert(zone_pva_is_null(z->pages_sequester));
 #endif
-               {
-               vm_size_t best, waste; unsigned int i;
-               best  = PAGE_SIZE;
-               waste = best % size;
 
-               for (i = 1; i <= 5; i++) {
-                       vm_size_t tsize, twaste;
+       unlock_zone(z);
 
-                       tsize = i * PAGE_SIZE;
+       simple_lock(&all_zones_lock, &zone_locks_grp);
 
-                       if ((tsize % size) < (tsize / 100)) {
-                               alloc = tsize;
-                               goto use_this_allocation;
-                       }
-                       twaste = tsize % size;
-                       if (twaste < waste)
-                               best = tsize, waste = twaste;
-               }
-               if (alloc <= best || (alloc % size >= waste))
-                       alloc = best;
+       assert(!bitmap_test(zone_destroyed_bitmap, zindex));
+       /* Mark the zone as empty in the bitmap */
+       bitmap_set(zone_destroyed_bitmap, zindex);
+       num_zones_in_use--;
+       assert(num_zones_in_use > 0);
+
+       simple_unlock(&all_zones_lock);
+}
+
+#pragma mark zone (re)fill, jetsam
+
+/*
+ * Dealing with zone allocations from the mach VM code.
+ *
+ * The implementation of the mach VM itself uses the zone allocator
+ * for things like the vm_map_entry data structure. In order to prevent
+ * an infinite recursion problem when adding more pages to a zone, zalloc
+ * uses a replenish thread to refill the VM layer's zones before they have
+ * too few remaining free entries. The reserved remaining free entries
+ * guarantee that the VM routines can get entries from already mapped pages.
+ *
+ * In order for that to work, the amount of allocations in the nested
+ * case have to be bounded. There are currently 2 replenish zones, and
+ * if each needs 1 element of each zone to add a new page to itself, that
+ * gives us a minumum reserve of 2 elements.
+ *
+ * There is also a deadlock issue with the zone garbage collection thread,
+ * or any thread that is trying to free zone pages. While holding
+ * the kernel's map lock they may need to allocate new VM map entries, hence
+ * we need enough reserve to allow them to get past the point of holding the
+ * map lock. After freeing that page, the GC thread will wait in drop_free_elements()
+ * until the replenish threads can finish. Since there's only 1 GC thread at a time,
+ * that adds a minimum of 1 to the reserve size.
+ *
+ * Since the minumum amount you can add to a zone is 1 page, we'll use 16K (from ARM)
+ * as the refill size on all platforms.
+ *
+ * When a refill zone drops to half that available, i.e. REFILL_SIZE / 2,
+ * zalloc_ext() will wake the replenish thread. The replenish thread runs
+ * until at least REFILL_SIZE worth of free elements exist, before sleeping again.
+ * In the meantime threads may continue to use the reserve until there are only REFILL_SIZE / 4
+ * elements left. Below that point only the replenish threads themselves and the GC
+ * thread may continue to use from the reserve.
+ */
+static unsigned zone_replenish_loops;
+static unsigned zone_replenish_wakeups;
+static unsigned zone_replenish_wakeups_initiated;
+static unsigned zone_replenish_throttle_count;
+
+#define ZONE_REPLENISH_TARGET (16 * 1024)
+static unsigned zone_replenish_active = 0; /* count of zones currently replenishing */
+static unsigned zone_replenish_max_threads = 0;
+
+LCK_GRP_DECLARE(zone_replenish_lock_grp, "zone_replenish_lock");
+LCK_SPIN_DECLARE(zone_replenish_lock, &zone_replenish_lock_grp);
+
+__abortlike
+static void
+zone_replenish_panic(zone_t zone, kern_return_t kr)
+{
+       panic_include_zprint = TRUE;
+#if CONFIG_ZLEAKS
+       if ((zleak_state & ZLEAK_STATE_ACTIVE)) {
+               panic_include_ztrace = TRUE;
+       }
+#endif /* CONFIG_ZLEAKS */
+       if (kr == KERN_NO_SPACE) {
+               zone_t zone_largest = zone_find_largest();
+               panic("zalloc: zone map exhausted while allocating from zone %s%s, "
+                   "likely due to memory leak in zone %s%s "
+                   "(%lu total bytes, %d elements allocated)",
+                   zone_heap_name(zone), zone->z_name,
+                   zone_heap_name(zone_largest), zone_largest->z_name,
+                   (unsigned long)zone_size_wired(zone_largest),
+                   zone_count_allocated(zone_largest));
        }
-use_this_allocation:
-       if (max && (max < alloc))
-               max = alloc;
+       panic("zalloc: %s%s (%d elements) retry fail %d",
+           zone_heap_name(zone), zone->z_name,
+           zone_count_allocated(zone), kr);
+}
 
-       /*
-        * Opt into page list tracking if we can reliably map an allocation
-        * to its page_metadata, and if the wastage in the tail of
-        * the allocation is not too large
-        */
+static void
+zone_replenish_locked(zone_t z, zalloc_flags_t flags, bool asynchronously)
+{
+       int kmaflags = KMA_KOBJECT | KMA_ZERO;
+       vm_offset_t space, alloc_size;
+       uint32_t retry = 0;
+       kern_return_t kr;
+
+       if (z->noencrypt) {
+               kmaflags |= KMA_NOENCRYPT;
+       }
+       if (flags & Z_NOPAGEWAIT) {
+               kmaflags |= KMA_NOPAGEWAIT;
+       }
+       if (z->permanent) {
+               kmaflags |= KMA_PERMANENT;
+       }
 
-       /* zone_zone can't use page metadata since the page metadata will overwrite zone metadata */
-       if (alloc == PAGE_SIZE && zone_zone != ZONE_NULL) {
-               vm_offset_t first_element_offset;
-               size_t zone_page_metadata_size = sizeof(struct zone_page_metadata);
+       for (;;) {
+               struct zone_page_metadata *page_meta = NULL;
 
-               if (zone_page_metadata_size % ZONE_ELEMENT_ALIGNMENT == 0) {
-                       first_element_offset = zone_page_metadata_size;
+               /*
+                * Try to allocate our regular chunk of pages,
+                * unless the system is under massive pressure
+                * and we're looking for more than 2 pages.
+                */
+               if (!z->percpu && z->alloc_pages > 2 && (vm_pool_low() || retry > 0)) {
+                       alloc_size = round_page(zone_elem_size(z));
                } else {
-                       first_element_offset = zone_page_metadata_size + (ZONE_ELEMENT_ALIGNMENT - (zone_page_metadata_size % ZONE_ELEMENT_ALIGNMENT));
-               }
-
-               if (((PAGE_SIZE - first_element_offset) % size) <= PAGE_SIZE / 100) {
-                       use_page_list = TRUE;
-               }
-       }
-
-       z->free_elements = NULL;
-       queue_init(&z->pages.any_free_foreign);
-       queue_init(&z->pages.all_free);
-       queue_init(&z->pages.intermediate);
-       queue_init(&z->pages.all_used);
-       z->cur_size = 0;
-       z->page_count = 0;
-       z->max_size = max;
-       z->elem_size = size;
-       z->alloc_size = alloc;
-       z->zone_name = name;
-       z->count = 0;
-       z->countfree = 0;
-       z->sum_count = 0LL;
-       z->doing_alloc_without_vm_priv = FALSE;
-       z->doing_alloc_with_vm_priv = FALSE;
-       z->doing_gc = FALSE;
-       z->exhaustible = FALSE;
-       z->collectable = TRUE;
-       z->allows_foreign = FALSE;
-       z->expandable  = TRUE;
-       z->waiting = FALSE;
-       z->async_pending = FALSE;
-       z->caller_acct = TRUE;
-       z->noencrypt = FALSE;
-       z->no_callout = FALSE;
-       z->async_prio_refill = FALSE;
-       z->gzalloc_exempt = FALSE;
-       z->alignment_required = FALSE;
-       z->use_page_list = use_page_list;
-       z->prio_refill_watermark = 0;
-       z->zone_replenish_thread = NULL;
-       z->zp_count = 0;
+                       alloc_size = ptoa(z->alloc_pages);
+                       page_meta = zone_sequestered_page_get(z, &space);
+               }
+
+               unlock_zone(z);
+
 #if CONFIG_ZLEAKS
-       z->zleak_capture = 0;
-       z->zleak_on = FALSE;
+               /*
+                * Do the zone leak activation here because zleak_activate()
+                * may block, and can't be done on the way out.
+                */
+               if (__improbable(zleak_state & ZLEAK_STATE_ENABLED)) {
+                       if (!(zleak_state & ZLEAK_STATE_ACTIVE) &&
+                           zone_submaps_approx_size() >= zleak_global_tracking_threshold) {
+                               kr = zleak_activate();
+                               if (kr != KERN_SUCCESS) {
+                                       printf("Failed to activate live zone leak debugging (%d).\n", kr);
+                               }
+                       }
+               }
 #endif /* CONFIG_ZLEAKS */
 
-#if    ZONE_DEBUG
-       z->active_zones.next = z->active_zones.prev = NULL;     
-       zone_debug_enable(z);
-#endif /* ZONE_DEBUG */
-       lock_zone_init(z);
+               /*
+                * Trigger jetsams via the vm_pageout_garbage_collect thread if
+                * we're running out of zone memory
+                */
+               if (is_zone_map_nearing_exhaustion()) {
+                       thread_wakeup((event_t) &vm_pageout_garbage_collect);
+               }
 
-       /*
-        *      Add the zone to the all-zones list.
-        *      If we are tracking zone info per task, and we have
-        *      already used all the available stat slots, then keep
-        *      using the overflow zone slot.
-        */
-       z->next_zone = ZONE_NULL;
-       simple_lock(&all_zones_lock);
-       *last_zone = z;
-       last_zone = &z->next_zone;
-       z->index = num_zones;
-       if (zinfo_per_task) {
-               if (num_zones > ZONES_MAX)
-                       z->index = ZONES_MAX;
-       }
-       num_zones++;
-       simple_unlock(&all_zones_lock);
+               if (page_meta) {
+                       kr = zone_sequestered_page_populate(z, page_meta, space,
+                           alloc_size, kmaflags);
+               } else {
+                       if (z->submap_idx == Z_SUBMAP_IDX_GENERAL_MAP && z->kalloc_heap != KHEAP_ID_NONE) {
+                               kmaflags |= KMA_KHEAP;
+                       }
+                       kr = kernel_memory_allocate(submap_for_zone(z),
+                           &space, alloc_size, 0, kmaflags, VM_KERN_MEMORY_ZONE);
+               }
 
-       /*
-        * Check if we should be logging this zone.  If so, remember the zone pointer.
-        */
-       if (log_this_zone(z->zone_name, zone_name_to_log)) {
-               zone_of_interest = z;
+#if !__LP64__
+               if (kr == KERN_NO_SPACE && z->allows_foreign) {
+                       /*
+                        * For zones allowing foreign pages, fallback to the kernel map
+                        */
+                       kr = kernel_memory_allocate(kernel_map, &space,
+                           alloc_size, 0, kmaflags, VM_KERN_MEMORY_ZONE);
+               }
+#endif
+
+               if (kr == KERN_SUCCESS) {
+                       break;
+               }
+
+               if (flags & Z_NOPAGEWAIT) {
+                       lock_zone(z);
+                       return;
+               }
+
+               if (asynchronously) {
+                       assert_wait_timeout(&z->prio_refill_count,
+                           THREAD_UNINT, 1, 100 * NSEC_PER_USEC);
+                       thread_block(THREAD_CONTINUE_NULL);
+               } else if (++retry == 3) {
+                       zone_replenish_panic(z, kr);
+               }
+
+               lock_zone(z);
        }
 
-       /*
-        * If we want to log a zone, see if we need to allocate buffer space for the log.  Some vm related zones are
-        * zinit'ed before we can do a kmem_alloc, so we have to defer allocation in that case.  kmem_alloc_ready is set to
-        * TRUE once enough of the VM system is up and running to allow a kmem_alloc to work.  If we want to log one
-        * of the VM related zones that's set up early on, we will skip allocation of the log until zinit is called again
-        * later on some other zone.  So note we may be allocating a buffer to log a zone other than the one being initialized
-        * right now.
-        */
-       if (zone_of_interest != NULL && zlog_btlog == NULL && kmem_alloc_ready) {
-               zlog_btlog = btlog_create(log_records, MAX_ZTRACE_DEPTH, NULL, NULL, NULL);
-               if (zlog_btlog) {
-                       printf("zone: logging started for zone %s\n", zone_of_interest->zone_name);
-               } else {
-                       printf("zone: couldn't allocate memory for zrecords, turning off zleak logging\n");
-                       zone_of_interest = NULL;
+       zcram_and_lock(z, space, alloc_size);
+
+#if CONFIG_ZLEAKS
+       if (__improbable(zleak_state & ZLEAK_STATE_ACTIVE)) {
+               if (!z->zleak_on &&
+                   zone_size_wired(z) >= zleak_per_zone_tracking_threshold) {
+                       z->zleak_on = true;
                }
        }
-#if    CONFIG_GZALLOC  
-       gzalloc_zone_init(z);
-#endif
-       return(z);
+#endif /* CONFIG_ZLEAKS */
 }
-unsigned       zone_replenish_loops, zone_replenish_wakeups, zone_replenish_wakeups_initiated, zone_replenish_throttle_count;
-
-static void zone_replenish_thread(zone_t);
 
-/* High priority VM privileged thread used to asynchronously refill a designated
- * zone, such as the reserved VM map entry zone.
+/*
+ * High priority VM privileged thread used to asynchronously refill a given zone.
+ * These are needed for data structures used by the lower level VM itself. The
+ * replenish thread maintains a reserve of elements, so that the VM will never
+ * block in the zone allocator.
  */
-static void zone_replenish_thread(zone_t z) {
-       vm_size_t free_size;
-       current_thread()->options |= TH_OPT_VMPRIV;
+__dead2
+static void
+zone_replenish_thread(void *_z, wait_result_t __unused wr)
+{
+       zone_t z = _z;
+
+       current_thread()->options |= (TH_OPT_VMPRIV | TH_OPT_ZONE_PRIV);
 
        for (;;) {
                lock_zone(z);
-               assert(z->prio_refill_watermark != 0);
-               while ((free_size = (z->cur_size - (z->count * z->elem_size))) < (z->prio_refill_watermark * z->elem_size)) {
-                       assert(z->doing_alloc_without_vm_priv == FALSE);
-                       assert(z->doing_alloc_with_vm_priv == FALSE);
-                       assert(z->async_prio_refill == TRUE);
+               assert(z->z_self == z);
+               assert(z->zone_replenishing);
+               assert(z->prio_refill_count != 0);
 
-                       unlock_zone(z);
-                       int     zflags = KMA_KOBJECT|KMA_NOPAGEWAIT;
-                       vm_offset_t space, alloc_size;
-                       kern_return_t kr;
-                               
-                       if (vm_pool_low())
-                               alloc_size = round_page(z->elem_size);
-                       else
-                               alloc_size = z->alloc_size;
-                               
-                       if (z->noencrypt)
-                               zflags |= KMA_NOENCRYPT;
-                               
-                       kr = kernel_memory_allocate(zone_map, &space, alloc_size, 0, zflags, VM_KERN_MEMORY_ZONE);
-
-                       if (kr == KERN_SUCCESS) {
-#if    ZONE_ALIAS_ADDR
-                               if (alloc_size == PAGE_SIZE)
-                                       space = zone_alias_addr(space);
-#endif
-                               zcram(z, space, alloc_size);
-                       } else if (kr == KERN_RESOURCE_SHORTAGE) {
-                               VM_PAGE_WAIT();
-                       } else if (kr == KERN_NO_SPACE) {
-                               kr = kernel_memory_allocate(kernel_map, &space, alloc_size, 0, zflags, VM_KERN_MEMORY_ZONE);
-                               if (kr == KERN_SUCCESS) {
-#if    ZONE_ALIAS_ADDR
-                                       if (alloc_size == PAGE_SIZE)
-                                               space = zone_alias_addr(space);
-#endif
-                                       zcram(z, space, alloc_size);
-                               } else {
-                                       assert_wait_timeout(&z->zone_replenish_thread, THREAD_UNINT, 1, 100 * NSEC_PER_USEC);
-                                       thread_block(THREAD_CONTINUE_NULL);
-                               }
-                       }
+               while (z->countfree < z->prio_refill_count) {
+                       assert(!z->expanding_no_vm_priv);
+                       assert(!z->expanding_vm_priv);
+
+                       zone_replenish_locked(z, Z_WAITOK, true);
+
+                       assert(z->z_self == z);
+                       zone_replenish_loops++;
+               }
+
+               /* Wakeup any potentially throttled allocations. */
+               thread_wakeup(z);
 
-                       lock_zone(z);
-                       zone_replenish_loops++;
+               assert_wait(&z->prio_refill_count, THREAD_UNINT);
+
+               /*
+                * We finished refilling the zone, so decrement the active count
+                * and wake up any waiting GC threads.
+                */
+               lck_spin_lock(&zone_replenish_lock);
+               assert(zone_replenish_active > 0);
+               if (--zone_replenish_active == 0) {
+                       thread_wakeup((event_t)&zone_replenish_active);
                }
+               lck_spin_unlock(&zone_replenish_lock);
 
+               z->zone_replenishing = false;
                unlock_zone(z);
-               /* Signal any potential throttled consumers, terminating
-                * their timer-bounded waits.
-                */
-               thread_wakeup(z);
 
-               assert_wait(&z->zone_replenish_thread, THREAD_UNINT);
                thread_block(THREAD_CONTINUE_NULL);
                zone_replenish_wakeups++;
        }
 }
 
 void
-zone_prio_refill_configure(zone_t z, vm_size_t low_water_mark) {
-       z->prio_refill_watermark = low_water_mark;
-
-       z->async_prio_refill = TRUE;
+zone_prio_refill_configure(zone_t z)
+{
+       thread_t th;
+       kern_return_t tres;
+
+       lock_zone(z);
+       assert(!z->prio_refill_count && !z->destructible);
+       z->prio_refill_count = (uint16_t)(ZONE_REPLENISH_TARGET / zone_elem_size(z));
+       z->zone_replenishing = true;
+       unlock_zone(z);
+
+       lck_spin_lock(&zone_replenish_lock);
+       ++zone_replenish_max_threads;
+       ++zone_replenish_active;
+       lck_spin_unlock(&zone_replenish_lock);
        OSMemoryBarrier();
-       kern_return_t tres = kernel_thread_start_priority((thread_continue_t)zone_replenish_thread, z, MAXPRI_KERNEL, &z->zone_replenish_thread);
 
+       tres = kernel_thread_start_priority(zone_replenish_thread, z,
+           MAXPRI_KERNEL, &th);
        if (tres != KERN_SUCCESS) {
                panic("zone_prio_refill_configure, thread create: 0x%x", tres);
        }
 
-       thread_deallocate(z->zone_replenish_thread);
+       thread_deallocate(th);
+}
+
+static void
+zone_randomize_freelist(zone_t zone, struct zone_page_metadata *meta,
+    vm_offset_t size, zone_addr_kind_t kind, unsigned int *entropy_buffer)
+{
+       const vm_size_t elem_size = zone_elem_size(zone);
+       vm_offset_t     left, right, head, base;
+       vm_offset_t     element;
+
+       left  = ZONE_PAGE_FIRST_OFFSET(kind);
+       right = size - ((size - left) % elem_size);
+       head  = 0;
+       base  = zone_meta_to_addr(meta, kind);
+
+       while (left < right) {
+               if (zone_leaks_scan_enable || __improbable(zone->tags) ||
+                   random_bool_gen_bits(&zone_bool_gen, entropy_buffer, MAX_ENTROPY_PER_ZCRAM, 1)) {
+                       element = base + left;
+                       left += elem_size;
+               } else {
+                       right -= elem_size;
+                       element = base + right;
+               }
+
+               vm_offset_t *primary  = (vm_offset_t *)element;
+               vm_offset_t *backup   = get_backup_ptr(elem_size, primary);
+
+               *primary = *backup = head ^ zp_nopoison_cookie;
+               head = element;
+       }
+
+       meta->zm_freelist_offs = (uint16_t)(head - base);
 }
 
 /*
  *     Cram the given memory into the specified zone. Update the zone page count accordingly.
  */
-void
-zcram(
-       zone_t          zone,
-       vm_offset_t                     newmem,
-       vm_size_t               size)
+static void
+zcram_and_lock(zone_t zone, vm_offset_t newmem, vm_size_t size)
 {
-       vm_size_t       elem_size;
-       boolean_t   from_zm = FALSE;
+       unsigned int entropy_buffer[MAX_ENTROPY_PER_ZCRAM] = { 0 };
+       struct zone_page_metadata *meta;
+       zone_addr_kind_t kind;
+       uint32_t pg_count = (uint32_t)atop(size);
+       uint32_t zindex = zone_index(zone);
+       uint32_t free_count;
+       uint16_t empty_freelist_offs = PAGE_METADATA_EMPTY_FREELIST;
 
        /* Basic sanity checks */
        assert(zone != ZONE_NULL && newmem != (vm_offset_t)0);
-       assert(!zone->collectable || zone->allows_foreign
-               || (from_zone_map(newmem, size)));
+       assert((newmem & PAGE_MASK) == 0);
+       assert((size & PAGE_MASK) == 0);
+
+       KDBG(MACHDBG_CODE(DBG_MACH_ZALLOC, ZALLOC_ZCRAM) | DBG_FUNC_START,
+           zindex, size);
+
+       kind = zone_addr_kind(newmem, size);
+#if DEBUG || DEVELOPMENT
+       if (zalloc_debug & ZALLOC_DEBUG_ZCRAM) {
+               kprintf("zcram(%p[%s%s], 0x%lx%s, 0x%lx)\n", zone,
+                   zone_heap_name(zone), zone->z_name, (uintptr_t)newmem,
+                   kind == ZONE_ADDR_FOREIGN ? "[F]" : "", (uintptr_t)size);
+       }
+#endif /* DEBUG || DEVELOPMENT */
+
+       /*
+        * Initialize the metadata for all pages. We dont need the zone lock
+        * here because we are not manipulating any zone related state yet.
+        *
+        * This includes randomizing the freelists as the metadata isn't
+        * published yet.
+        */
+
+       if (kind == ZONE_ADDR_NATIVE) {
+               /*
+                * We're being called by zfill,
+                * zone_replenish_thread or vm_page_more_fictitious,
+                *
+                * which will only either allocate a single page, or `alloc_pages`
+                * worth.
+                */
+               assert(pg_count <= zone->alloc_pages);
+
+               /*
+                * Make sure the range of metadata entries we're about to init
+                * have proper physical backing, then initialize them.
+                */
+               meta = zone_meta_from_addr(newmem, kind);
+               zone_meta_populate(meta, meta + pg_count);
+
+               if (zone->permanent) {
+                       empty_freelist_offs = 0;
+               }
 
-       elem_size = zone->elem_size;
+               meta[0] = (struct zone_page_metadata){
+                       .zm_index         = zindex,
+                       .zm_page_count    = pg_count,
+                       .zm_percpu        = zone->percpu,
+                       .zm_freelist_offs = empty_freelist_offs,
+               };
+
+               for (uint32_t i = 1; i < pg_count; i++) {
+                       meta[i] = (struct zone_page_metadata){
+                               .zm_index          = zindex,
+                               .zm_page_count     = i,
+                               .zm_percpu         = zone->percpu,
+                               .zm_secondary_page = true,
+                               .zm_freelist_offs  = empty_freelist_offs,
+                       };
+               }
 
-       if (from_zone_map(newmem, size))
-               from_zm = TRUE;
+               if (!zone->permanent) {
+                       zone_randomize_freelist(zone, meta,
+                           zone->percpu ? PAGE_SIZE : size, kind, entropy_buffer);
+               }
+       } else {
+               if (!zone->allows_foreign || !from_foreign_range(newmem, size)) {
+                       panic("zcram_and_lock: foreign memory [%lx] being crammed is "
+                           "outside of foreign range", (uintptr_t)newmem);
+               }
 
-       if (zalloc_debug & ZALLOC_DEBUG_ZCRAM)
-               kprintf("zcram(%p[%s], 0x%lx%s, 0x%lx)\n", zone, zone->zone_name,
-                               (unsigned long)newmem, from_zm ? "" : "[F]", (unsigned long)size);
+               /*
+                * We cannot support elements larger than page size for foreign
+                * memory because we put metadata on the page itself for each
+                * page of foreign memory.
+                *
+                * We need to do this in order to be able to reach the metadata
+                * when any element is freed.
+                */
+               assert(!zone->percpu && !zone->permanent);
+               assert(zone_elem_size(zone) <= PAGE_SIZE - sizeof(struct zone_page_metadata));
+
+               bzero((void *)newmem, size);
+
+               for (vm_offset_t offs = 0; offs < size; offs += PAGE_SIZE) {
+                       meta = (struct zone_page_metadata *)(newmem + offs);
+                       *meta = (struct zone_page_metadata){
+                               .zm_index         = zindex,
+                               .zm_page_count    = 1,
+                               .zm_freelist_offs = empty_freelist_offs,
+                       };
+                       meta->zm_foreign_cookie[0] = ZONE_FOREIGN_COOKIE;
+                       zone_randomize_freelist(zone, meta, PAGE_SIZE, kind,
+                           entropy_buffer);
+               }
+       }
 
-       if (from_zm && !zone->use_page_list)
-               zone_page_init(newmem, size);
+#if VM_MAX_TAG_ZONES
+       if (__improbable(zone->tags)) {
+               assert(kind == ZONE_ADDR_NATIVE && !zone->percpu);
+               ztMemoryAdd(zone, newmem, size);
+       }
+#endif /* VM_MAX_TAG_ZONES */
 
-       ZONE_PAGE_COUNT_INCR(zone, (size / PAGE_SIZE));
+       /*
+        * Insert the initialized pages / metadatas into the right lists.
+        */
 
        lock_zone(zone);
+       assert(zone->z_self == zone);
 
-       if (zone->use_page_list) {
-               struct zone_page_metadata *page_metadata;
-               size_t zone_page_metadata_size = sizeof(struct zone_page_metadata);
-
-               assert((newmem & PAGE_MASK) == 0);
-               assert((size & PAGE_MASK) == 0);
-               for (; size > 0; newmem += PAGE_SIZE, size -= PAGE_SIZE) {
-
-                       vm_size_t pos_in_page;
-                       page_metadata = (struct zone_page_metadata *)(newmem);
-                       
-                       page_metadata->pages.next = NULL;
-                       page_metadata->pages.prev = NULL;
-                       page_metadata->elements = NULL;
-                       page_metadata->zone = zone;
-                       page_metadata->alloc_count = 0;
-                       page_metadata->free_count = 0;
-
-                       enqueue_tail(&zone->pages.all_used, (queue_entry_t)page_metadata);
-
-                       vm_offset_t first_element_offset;
-                       if (zone_page_metadata_size % ZONE_ELEMENT_ALIGNMENT == 0){
-                               first_element_offset = zone_page_metadata_size;
-                       } else {
-                               first_element_offset = zone_page_metadata_size + (ZONE_ELEMENT_ALIGNMENT - (zone_page_metadata_size % ZONE_ELEMENT_ALIGNMENT));
-                       }
+       zone->page_count += pg_count;
+       if (zone->page_count_hwm < zone->page_count) {
+               zone->page_count_hwm = zone->page_count;
+       }
+       os_atomic_add(&zones_phys_page_count, pg_count, relaxed);
 
-                       for (pos_in_page = first_element_offset; (newmem + pos_in_page + elem_size) < (vm_offset_t)(newmem + PAGE_SIZE); pos_in_page += elem_size) {
-                               page_metadata->alloc_count++;
-                               zone->count++;  /* compensate for free_to_zone */
-                               free_to_zone(zone, newmem + pos_in_page, FALSE);
-                               zone->cur_size += elem_size;
-                       }
+       if (kind == ZONE_ADDR_NATIVE) {
+               os_atomic_add(&zones_phys_page_mapped_count, pg_count, relaxed);
+               if (zone->permanent) {
+                       zone_meta_queue_push(zone, &zone->pages_intermediate, meta, kind);
+               } else {
+                       zone_meta_queue_push(zone, &zone->pages_all_free, meta, kind);
+                       zone->allfree_page_count += meta->zm_page_count;
                }
+               free_count = zone_elem_count(zone, size, kind);
+               zone->countfree  += free_count;
+               zone->countavail += free_count;
        } else {
-               while (size >= elem_size) {
-                       zone->count++;  /* compensate for free_to_zone */
-                       if (newmem == (vm_offset_t)zone) {
-                               /* Don't free zone_zone zone */
-                       } else {
-                               free_to_zone(zone, newmem, FALSE);
-                       }
-                       if (from_zm)
-                               zone_page_alloc(newmem, elem_size);
-                       size -= elem_size;
-                       newmem += elem_size;
-                       zone->cur_size += elem_size;
+               free_count = zone_elem_count(zone, PAGE_SIZE, kind);
+               for (vm_offset_t offs = 0; offs < size; offs += PAGE_SIZE) {
+                       meta = (struct zone_page_metadata *)(newmem + offs);
+                       zone_meta_queue_push(zone, &zone->pages_any_free_foreign, meta, kind);
+                       zone->countfree  += free_count;
+                       zone->countavail += free_count;
                }
        }
-       unlock_zone(zone);
-}
 
+       KDBG(MACHDBG_CODE(DBG_MACH_ZALLOC, ZALLOC_ZCRAM) | DBG_FUNC_END, zindex);
+}
 
-/*
- *     Steal memory for the zone package.  Called from
- *     vm_page_bootstrap().
- */
 void
-zone_steal_memory(void)
+zcram(zone_t zone, vm_offset_t newmem, vm_size_t size)
 {
-#if    CONFIG_GZALLOC
-       gzalloc_configure();
-#endif
-       /* Request enough early memory to get to the pmap zone */
-       zdata_size = 12 * sizeof(struct zone);
-       zdata_size = round_page(zdata_size);
-       zdata = (vm_offset_t)pmap_steal_memory(zdata_size);
+       zcram_and_lock(zone, newmem, size);
+       unlock_zone(zone);
 }
 
-
 /*
  * Fill a zone with enough memory to contain at least nelem elements.
- * Memory is obtained with kmem_alloc_kobject from the kernel_map.
  * Return the number of elements actually put into the zone, which may
  * be more than the caller asked for since the memory allocation is
- * rounded up to a full page.
+ * rounded up to the next zone allocation size.
  */
 int
 zfill(
-       zone_t  zone,
-       int     nelem)
+       zone_t  zone,
+       int     nelem)
 {
-       kern_return_t   kr;
-       vm_size_t       size;
-       vm_offset_t     memory;
-       int             nalloc;
+       kern_return_t kr;
+       vm_offset_t   memory;
 
-       assert(nelem > 0);
-       if (nelem <= 0)
-               return 0;
-       size = nelem * zone->elem_size;
-       size = round_page(size);
-       kr = kmem_alloc_kobject(kernel_map, &memory, size, VM_KERN_MEMORY_ZONE);
-       if (kr != KERN_SUCCESS)
-               return 0;
+       vm_size_t alloc_size = ptoa(zone->alloc_pages);
+       vm_size_t nalloc_inc = zone_elem_count(zone, alloc_size, ZONE_ADDR_NATIVE);
+       vm_size_t nalloc = 0, goal = MAX(0, nelem);
+       int kmaflags = KMA_KOBJECT | KMA_ZERO;
+
+       if (zone->noencrypt) {
+               kmaflags |= KMA_NOENCRYPT;
+       }
+
+       assert(!zone->allows_foreign && !zone->permanent);
+
+       /*
+        * Trigger jetsams via the vm_pageout_garbage_collect thread if we're
+        * running out of zone memory
+        */
+       if (is_zone_map_nearing_exhaustion()) {
+               thread_wakeup((event_t) &vm_pageout_garbage_collect);
+       }
+
+       if (zone->va_sequester) {
+               lock_zone(zone);
+
+               do {
+                       struct zone_page_metadata *page_meta;
+                       page_meta = zone_sequestered_page_get(zone, &memory);
+                       if (NULL == page_meta) {
+                               break;
+                       }
+                       unlock_zone(zone);
+
+                       kr = zone_sequestered_page_populate(zone, page_meta,
+                           memory, alloc_size, kmaflags);
+                       if (KERN_SUCCESS != kr) {
+                               goto out_nolock;
+                       }
+
+                       zcram_and_lock(zone, memory, alloc_size);
+                       nalloc += nalloc_inc;
+               } while (nalloc < goal);
+
+               unlock_zone(zone);
+       }
+
+out_nolock:
+       while (nalloc < goal) {
+               kr = kernel_memory_allocate(submap_for_zone(zone), &memory,
+                   alloc_size, 0, kmaflags, VM_KERN_MEMORY_ZONE);
+               if (kr != KERN_SUCCESS) {
+                       printf("%s: kernel_memory_allocate() of %lu bytes failed\n",
+                           __func__, (unsigned long)(nalloc * alloc_size));
+                       break;
+               }
+
+               zcram(zone, memory, alloc_size);
+               nalloc += nalloc_inc;
+       }
+
+       return (int)nalloc;
+}
+
+/*
+ * We're being very conservative here and picking a value of 95%. We might need to lower this if
+ * we find that we're not catching the problem and are still hitting zone map exhaustion panics.
+ */
+#define ZONE_MAP_JETSAM_LIMIT_DEFAULT 95
+
+/*
+ * Trigger zone-map-exhaustion jetsams if the zone map is X% full, where X=zone_map_jetsam_limit.
+ * Can be set via boot-arg "zone_map_jetsam_limit". Set to 95% by default.
+ */
+TUNABLE_WRITEABLE(unsigned int, zone_map_jetsam_limit, "zone_map_jetsam_limit",
+    ZONE_MAP_JETSAM_LIMIT_DEFAULT);
+
+void
+get_zone_map_size(uint64_t *current_size, uint64_t *capacity)
+{
+       vm_offset_t phys_pages = os_atomic_load(&zones_phys_page_mapped_count, relaxed);
+       *current_size = ptoa_64(phys_pages);
+       *capacity = zone_phys_mapped_max;
+}
+
+void
+get_largest_zone_info(char *zone_name, size_t zone_name_len, uint64_t *zone_size)
+{
+       zone_t largest_zone = zone_find_largest();
+
+       /*
+        * Append kalloc heap name to zone name (if zone is used by kalloc)
+        */
+       snprintf(zone_name, zone_name_len, "%s%s",
+           zone_heap_name(largest_zone), largest_zone->z_name);
+
+       *zone_size = zone_size_wired(largest_zone);
+}
+
+boolean_t
+is_zone_map_nearing_exhaustion(void)
+{
+       vm_offset_t phys_pages = os_atomic_load(&zones_phys_page_mapped_count, relaxed);
+       return ptoa_64(phys_pages) > (zone_phys_mapped_max * zone_map_jetsam_limit) / 100;
+}
+
+
+#define VMENTRY_TO_VMOBJECT_COMPARISON_RATIO 98
+
+/*
+ * Tries to kill a single process if it can attribute one to the largest zone. If not, wakes up the memorystatus thread
+ * to walk through the jetsam priority bands and kill processes.
+ */
+static void
+kill_process_in_largest_zone(void)
+{
+       pid_t pid = -1;
+       zone_t largest_zone = zone_find_largest();
+
+       printf("zone_map_exhaustion: Zone mapped %lld of %lld, used %lld, map size %lld, capacity %lld [jetsam limit %d%%]\n",
+           ptoa_64(os_atomic_load(&zones_phys_page_mapped_count, relaxed)), ptoa_64(zone_phys_mapped_max),
+           ptoa_64(os_atomic_load(&zones_phys_page_count, relaxed)),
+           (uint64_t)zone_submaps_approx_size(),
+           (uint64_t)zone_range_size(&zone_info.zi_map_range),
+           zone_map_jetsam_limit);
+       printf("zone_map_exhaustion: Largest zone %s%s, size %lu\n", zone_heap_name(largest_zone),
+           largest_zone->z_name, (uintptr_t)zone_size_wired(largest_zone));
+
+       /*
+        * We want to make sure we don't call this function from userspace.
+        * Or we could end up trying to synchronously kill the process
+        * whose context we're in, causing the system to hang.
+        */
+       assert(current_task() == kernel_task);
 
-       zone_change(zone, Z_FOREIGN, TRUE);
-       zcram(zone, memory, size);
-       nalloc = (int)(size / zone->elem_size);
-       assert(nalloc >= nelem);
+       /*
+        * If vm_object_zone is the largest, check to see if the number of
+        * elements in vm_map_entry_zone is comparable.
+        *
+        * If so, consider vm_map_entry_zone as the largest. This lets us target
+        * a specific process to jetsam to quickly recover from the zone map
+        * bloat.
+        */
+       if (largest_zone == vm_object_zone) {
+               unsigned int vm_object_zone_count = zone_count_allocated(vm_object_zone);
+               unsigned int vm_map_entry_zone_count = zone_count_allocated(vm_map_entry_zone);
+               /* Is the VM map entries zone count >= 98% of the VM objects zone count? */
+               if (vm_map_entry_zone_count >= ((vm_object_zone_count * VMENTRY_TO_VMOBJECT_COMPARISON_RATIO) / 100)) {
+                       largest_zone = vm_map_entry_zone;
+                       printf("zone_map_exhaustion: Picking VM map entries as the zone to target, size %lu\n",
+                           (uintptr_t)zone_size_wired(largest_zone));
+               }
+       }
 
-       return nalloc;
+       /* TODO: Extend this to check for the largest process in other zones as well. */
+       if (largest_zone == vm_map_entry_zone) {
+               pid = find_largest_process_vm_map_entries();
+       } else {
+               printf("zone_map_exhaustion: Nothing to do for the largest zone [%s%s]. "
+                   "Waking up memorystatus thread.\n", zone_heap_name(largest_zone),
+                   largest_zone->z_name);
+       }
+       if (!memorystatus_kill_on_zone_map_exhaustion(pid)) {
+               printf("zone_map_exhaustion: Call to memorystatus failed, victim pid: %d\n", pid);
+       }
 }
 
+#pragma mark zalloc module init
+
 /*
  *     Initialize the "zone of zones" which uses fixed memory allocated
  *     earlier in memory initialization.  zone_bootstrap is called
  *     before zone_init.
  */
+__startup_func
 void
 zone_bootstrap(void)
 {
-       char temp_buf[16];
+       /* Validate struct zone_page_metadata expectations */
+       if ((1U << ZONE_PAGECOUNT_BITS) <
+           atop(ZONE_MAX_ALLOC_SIZE) * sizeof(struct zone_page_metadata)) {
+               panic("ZONE_PAGECOUNT_BITS is not large enough to hold page counts");
+       }
 
-       if (PE_parse_boot_argn("-zinfop", temp_buf, sizeof(temp_buf))) {
-               zinfo_per_task = TRUE;
+       /* Validate struct zone_packed_virtual_address expectations */
+       static_assert((intptr_t)VM_MIN_KERNEL_ADDRESS < 0, "the top bit must be 1");
+       if (VM_KERNEL_POINTER_SIGNIFICANT_BITS - PAGE_SHIFT > 31) {
+               panic("zone_pva_t can't pack a kernel page address in 31 bits");
        }
 
-       if (!PE_parse_boot_argn("zalloc_debug", &zalloc_debug, sizeof(zalloc_debug)))
-               zalloc_debug = 0;
+       zpercpu_early_count = ml_early_cpu_max_number() + 1;
 
        /* Set up zone element poisoning */
-       zp_init();
+       zp_bootstrap();
 
-       /* should zlog log to debug zone corruption instead of leaks? */
-       if (PE_parse_boot_argn("-zc", temp_buf, sizeof(temp_buf))) {
-               corruption_debug_flag = TRUE;
-       }       
+       random_bool_init(&zone_bool_gen);
 
        /*
-        * Check for and set up zone leak detection if requested via boot-args.  We recognized two
-        * boot-args:
-        *
-        *      zlog=<zone_to_log>
-        *      zrecs=<num_records_in_log>
+        * the KASAN quarantine for kalloc doesn't understand heaps
+        * and trips the heap confusion panics. At the end of the day,
+        * all these security measures are double duty with KASAN.
         *
-        * The zlog arg is used to specify the zone name that should be logged, and zrecs is used to
-        * control the size of the log.  If zrecs is not specified, a default value is used.
+        * On 32bit kernels, these protections are just too expensive.
         */
+#if !defined(__LP64__) || KASAN_ZALLOC
+       zsecurity_options &= ~ZSECURITY_OPTIONS_SEQUESTER;
+       zsecurity_options &= ~ZSECURITY_OPTIONS_SUBMAP_USER_DATA;
+       zsecurity_options &= ~ZSECURITY_OPTIONS_SEQUESTER_KEXT_KALLOC;
+#endif
 
-       if (PE_parse_boot_argn("zlog", zone_name_to_log, sizeof(zone_name_to_log)) == TRUE) {
-               if (PE_parse_boot_argn("zrecs", &log_records, sizeof(log_records)) == TRUE) {
-
-                       /*
-                        * Don't allow more than ZRECORDS_MAX records even if the user asked for more.
-                        * This prevents accidentally hogging too much kernel memory and making the system
-                        * unusable.
-                        */
-
-                       log_records = MIN(ZRECORDS_MAX, log_records);
+       thread_call_setup(&call_async_alloc, zalloc_async, NULL);
 
-               } else {
-                       log_records = ZRECORDS_DEFAULT;
-               }
+#if CONFIG_ZCACHE
+       /* zcc_enable_for_zone_name=<zone>: enable per-cpu zone caching for <zone>. */
+       if (PE_parse_boot_arg_str("zcc_enable_for_zone_name", cache_zone_name, sizeof(cache_zone_name))) {
+               printf("zcache: caching enabled for zone %s\n", cache_zone_name);
        }
+#endif /* CONFIG_ZCACHE */
+}
 
-       simple_lock_init(&all_zones_lock, 0);
+#if __LP64__
+#if CONFIG_EMBEDDED
+#define ZONE_MAP_VIRTUAL_SIZE_LP64      (32ULL * 1024ULL * 1024 * 1024)
+#else
+#define ZONE_MAP_VIRTUAL_SIZE_LP64      (128ULL * 1024ULL * 1024 * 1024)
+#endif
+#endif /* __LP64__ */
 
-       first_zone = ZONE_NULL;
-       last_zone = &first_zone;
-       num_zones = 0;
-       thread_call_setup(&call_async_alloc, zalloc_async, NULL);
+#define SINGLE_GUARD                    16384
+#define MULTI_GUARD                     (3 * SINGLE_GUARD)
 
-       /* assertion: nobody else called zinit before us */
-       assert(zone_zone == ZONE_NULL);
-       
-       /* initializing global lock group for zones */
-       lck_grp_attr_setdefault(&zone_locks_grp_attr);
-       lck_grp_init(&zone_locks_grp, "zone_locks", &zone_locks_grp_attr);
+#if __LP64__
+static inline vm_offset_t
+zone_restricted_va_max(void)
+{
+       vm_offset_t compressor_max = VM_PACKING_MAX_PACKABLE(C_SLOT_PACKED_PTR);
+       vm_offset_t vm_page_max    = VM_PACKING_MAX_PACKABLE(VM_PAGE_PACKED_PTR);
+
+       return trunc_page(MIN(compressor_max, vm_page_max));
+}
+#endif
 
-       zone_zone = zinit(sizeof(struct zone), 128 * sizeof(struct zone),
-                         sizeof(struct zone), "zones");
-       zone_change(zone_zone, Z_COLLECT, FALSE);
-       zone_change(zone_zone, Z_CALLERACCT, FALSE);
-       zone_change(zone_zone, Z_NOENCRYPT, TRUE);
+__startup_func
+static void
+zone_tunables_fixup(void)
+{
+       if (zone_map_jetsam_limit == 0 || zone_map_jetsam_limit > 100) {
+               zone_map_jetsam_limit = ZONE_MAP_JETSAM_LIMIT_DEFAULT;
+       }
+}
+STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, zone_tunables_fixup);
 
-       zcram(zone_zone, zdata, zdata_size);
-       VM_PAGE_MOVE_STOLEN(atop_64(zdata_size));
+__startup_func
+static vm_size_t
+zone_phys_size_max(void)
+{
+       mach_vm_size_t zsize;
+       vm_size_t zsizearg;
 
-       /* initialize fake zones and zone info if tracking by task */
-       if (zinfo_per_task) {
-               vm_size_t zisize = sizeof(zinfo_usage_store_t) * ZINFO_SLOTS;
-               unsigned int i;
+       if (PE_parse_boot_argn("zsize", &zsizearg, sizeof(zsizearg))) {
+               zsize = zsizearg * (1024ULL * 1024);
+       } else {
+               zsize = sane_size >> 2;         /* Set target zone size as 1/4 of physical memory */
+#if defined(__LP64__)
+               zsize += zsize >> 1;
+#endif /* __LP64__ */
+       }
 
-               for (i = 0; i < num_fake_zones; i++)
-                       fake_zones[i].init(ZINFO_SLOTS - num_fake_zones + i);
-               zinfo_zone = zinit(zisize, zisize * CONFIG_TASK_MAX,
-                                  zisize, "per task zinfo");
-               zone_change(zinfo_zone, Z_CALLERACCT, FALSE);
+       if (zsize < CONFIG_ZONE_MAP_MIN) {
+               zsize = CONFIG_ZONE_MAP_MIN;   /* Clamp to min */
+       }
+       if (zsize > sane_size >> 1) {
+               zsize = sane_size >> 1; /* Clamp to half of RAM max */
        }
+       if (zsizearg == 0 && zsize > ZONE_MAP_MAX) {
+               /* if zsize boot-arg not present and zsize exceeds platform maximum, clip zsize */
+               vm_size_t orig_zsize = zsize;
+               zsize = ZONE_MAP_MAX;
+               printf("NOTE: zonemap size reduced from 0x%lx to 0x%lx\n",
+                   (uintptr_t)orig_zsize, (uintptr_t)zsize);
+       }
+
+       assert((vm_size_t) zsize == zsize);
+       return (vm_size_t)trunc_page(zsize);
 }
 
-void
-zinfo_task_init(task_t task)
+__startup_func
+static struct zone_map_range
+zone_init_allocate_va(vm_offset_t *submap_min, vm_size_t size, bool guard)
 {
-       if (zinfo_per_task) {
-               task->tkm_zinfo = zalloc(zinfo_zone);
-               memset(task->tkm_zinfo, 0, sizeof(zinfo_usage_store_t) * ZINFO_SLOTS);
+       struct zone_map_range r;
+       kern_return_t kr;
+
+       if (guard) {
+               vm_map_offset_t addr = *submap_min;
+               vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
+
+               vmk_flags.vmkf_permanent = TRUE;
+               kr = vm_map_enter(kernel_map, &addr, size, 0,
+                   VM_FLAGS_FIXED, vmk_flags, VM_KERN_MEMORY_ZONE, kernel_object,
+                   0, FALSE, VM_PROT_NONE, VM_PROT_NONE, VM_INHERIT_DEFAULT);
+               *submap_min = (vm_offset_t)addr;
        } else {
-               task->tkm_zinfo = NULL;
+               kr = kernel_memory_allocate(kernel_map, submap_min, size,
+                   0, KMA_KOBJECT | KMA_PAGEABLE | KMA_VAONLY, VM_KERN_MEMORY_ZONE);
+       }
+       if (kr != KERN_SUCCESS) {
+               panic("zone_init_allocate_va(0x%lx:0x%zx) failed: %d",
+                   (uintptr_t)*submap_min, (size_t)size, kr);
        }
+
+       r.min_address = *submap_min;
+       *submap_min  += size;
+       r.max_address = *submap_min;
+
+       return r;
 }
 
-void
-zinfo_task_free(task_t task)
+__startup_func
+static void
+zone_submap_init(
+       vm_offset_t *submap_min,
+       unsigned    idx,
+       uint64_t    zone_sub_map_numer,
+       uint64_t    *remaining_denom,
+       vm_offset_t *remaining_size,
+       vm_size_t   guard_size)
 {
-       assert(task != kernel_task);
-       if (task->tkm_zinfo != NULL) {
-               zfree(zinfo_zone, task->tkm_zinfo);
-               task->tkm_zinfo = NULL;
+       vm_offset_t submap_start, submap_end;
+       vm_size_t submap_size;
+       vm_map_t  submap;
+       kern_return_t kr;
+
+       submap_size = trunc_page(zone_sub_map_numer * *remaining_size /
+           *remaining_denom);
+       submap_start = *submap_min;
+       submap_end = submap_start + submap_size;
+
+#if defined(__LP64__)
+       if (idx == Z_SUBMAP_IDX_VA_RESTRICTED_MAP) {
+               vm_offset_t restricted_va_max = zone_restricted_va_max();
+               if (submap_end > restricted_va_max) {
+#if DEBUG || DEVELOPMENT
+                       printf("zone_init: submap[%d] clipped to %zdM of %zdM\n", idx,
+                           (size_t)(restricted_va_max - submap_start) >> 20,
+                           (size_t)submap_size >> 20);
+#endif /* DEBUG || DEVELOPMENT */
+                       guard_size += submap_end - restricted_va_max;
+                       *remaining_size -= submap_end - restricted_va_max;
+                       submap_end  = restricted_va_max;
+                       submap_size = restricted_va_max - submap_start;
+               }
+
+               vm_packing_verify_range("vm_compressor",
+                   submap_start, submap_end, VM_PACKING_PARAMS(C_SLOT_PACKED_PTR));
+               vm_packing_verify_range("vm_page",
+                   submap_start, submap_end, VM_PACKING_PARAMS(VM_PAGE_PACKED_PTR));
        }
+#endif /* defined(__LP64__) */
+
+       vm_map_kernel_flags_t vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
+       vmk_flags.vmkf_permanent = TRUE;
+       kr = kmem_suballoc(kernel_map, submap_min, submap_size,
+           FALSE, VM_FLAGS_FIXED, vmk_flags,
+           VM_KERN_MEMORY_ZONE, &submap);
+       if (kr != KERN_SUCCESS) {
+               panic("kmem_suballoc(kernel_map[%d] %p:%p) failed: %d",
+                   idx, (void *)submap_start, (void *)submap_end, kr);
+       }
+
+#if DEBUG || DEVELOPMENT
+       printf("zone_init: submap[%d] %p:%p (%zuM)\n",
+           idx, (void *)submap_start, (void *)submap_end,
+           (size_t)submap_size >> 20);
+#endif /* DEBUG || DEVELOPMENT */
+
+       zone_submaps[idx] = submap;
+       *submap_min       = submap_end;
+       *remaining_size  -= submap_size;
+       *remaining_denom -= zone_sub_map_numer;
+
+       zone_init_allocate_va(submap_min, guard_size, true);
 }
-               
+
 /* Global initialization of Zone Allocator.
  * Runs after zone_bootstrap.
  */
-void
-zone_init(
-       vm_size_t max_zonemap_size)
+__startup_func
+static void
+zone_init(void)
 {
-       kern_return_t   retval;
-       vm_offset_t     zone_min;
-       vm_offset_t     zone_max;
+       vm_size_t       zone_meta_size;
+       vm_size_t       zone_map_size;
+       vm_size_t       remaining_size;
+       vm_offset_t     submap_min = 0;
 
-       retval = kmem_suballoc(kernel_map, &zone_min, max_zonemap_size,
-                              FALSE, VM_FLAGS_ANYWHERE | VM_FLAGS_PERMANENT | VM_MAKE_TAG(VM_KERN_MEMORY_ZONE),
-                              &zone_map);
+       if (ZSECURITY_OPTIONS_SUBMAP_USER_DATA & zsecurity_options) {
+               zone_last_submap_idx = Z_SUBMAP_IDX_BAG_OF_BYTES_MAP;
+       } else {
+               zone_last_submap_idx = Z_SUBMAP_IDX_GENERAL_MAP;
+       }
+       zone_phys_mapped_max  = zone_phys_size_max();
 
-       if (retval != KERN_SUCCESS)
-               panic("zone_init: kmem_suballoc failed");
-       zone_max = zone_min + round_page(max_zonemap_size);
-#if    CONFIG_GZALLOC
-       gzalloc_init(max_zonemap_size);
+#if __LP64__
+       zone_map_size = ZONE_MAP_VIRTUAL_SIZE_LP64;
+#else
+       zone_map_size = zone_phys_mapped_max;
 #endif
+       zone_meta_size = round_page(atop(zone_map_size) *
+           sizeof(struct zone_page_metadata));
+
        /*
-        * Setup garbage collection information:
+        * Zone "map" setup:
+        *
+        * [  VA_RESTRICTED  ] <-- LP64 only
+        * [  SINGLE_GUARD   ] <-- LP64 only
+        * [  meta           ]
+        * [  SINGLE_GUARD   ]
+        * [  map<i>         ] \ for each extra map
+        * [  MULTI_GUARD    ] /
         */
-       zone_map_min_address = zone_min;
-       zone_map_max_address = zone_max;
-
+       remaining_size = zone_map_size;
 #if defined(__LP64__)
+       remaining_size -= SINGLE_GUARD;
+#endif
+       remaining_size -= zone_meta_size + SINGLE_GUARD;
+       remaining_size -= MULTI_GUARD * (zone_last_submap_idx -
+           Z_SUBMAP_IDX_GENERAL_MAP + 1);
+
+#if VM_MAX_TAG_ZONES
+       if (zone_tagging_on) {
+               zone_tagging_init(zone_map_size);
+       }
+#endif
+
+       uint64_t remaining_denom = 0;
+       uint64_t zone_sub_map_numer[Z_SUBMAP_IDX_COUNT] = {
+#ifdef __LP64__
+               [Z_SUBMAP_IDX_VA_RESTRICTED_MAP] = 20,
+#endif /* defined(__LP64__) */
+               [Z_SUBMAP_IDX_GENERAL_MAP]       = 40,
+               [Z_SUBMAP_IDX_BAG_OF_BYTES_MAP]  = 40,
+       };
+
+       for (unsigned idx = 0; idx <= zone_last_submap_idx; idx++) {
+#if DEBUG || DEVELOPMENT
+               char submap_name[MAX_SUBMAP_NAME];
+               snprintf(submap_name, MAX_SUBMAP_NAME, "submap%d", idx);
+               PE_parse_boot_argn(submap_name, &zone_sub_map_numer[idx], sizeof(uint64_t));
+#endif
+               remaining_denom += zone_sub_map_numer[idx];
+       }
+
        /*
-        * ensure that any vm_page_t that gets created from
-        * the vm_page zone can be packed properly (see vm_page.h
-        * for the packing requirements
+        * And now allocate the various pieces of VA and submaps.
+        *
+        * Make a first allocation of contiguous VA, that we'll deallocate,
+        * and we'll carve-out memory in that range again linearly.
+        * The kernel is stil single threaded at this stage.
         */
-       if (VM_PAGE_UNPACK_PTR(VM_PAGE_PACK_PTR(zone_map_min_address)) != (vm_page_t)zone_map_min_address)
-               panic("VM_PAGE_PACK_PTR failed on zone_map_min_address - %p", (void *)zone_map_min_address);
 
-       if (VM_PAGE_UNPACK_PTR(VM_PAGE_PACK_PTR(zone_map_max_address)) != (vm_page_t)zone_map_max_address)
-               panic("VM_PAGE_PACK_PTR failed on zone_map_max_address - %p", (void *)zone_map_max_address);
-#endif
+       struct zone_map_range *map_range = &zone_info.zi_map_range;
 
-       zone_pages = (unsigned int)atop_kernel(zone_max - zone_min);
-       zone_page_table_used_size = sizeof(zone_page_table);
+       *map_range = zone_init_allocate_va(&submap_min, zone_map_size, false);
+       submap_min = map_range->min_address;
+       kmem_free(kernel_map, submap_min, zone_map_size);
 
-       zone_page_table_second_level_size = 1;
-       zone_page_table_second_level_shift_amount = 0;
-       
+#if defined(__LP64__)
        /*
-        * Find the power of 2 for the second level that allows
-        * the first level to fit in ZONE_PAGE_TABLE_FIRST_LEVEL_SIZE
-        * slots.
+        * Allocate `Z_SUBMAP_IDX_VA_RESTRICTED_MAP` first because its VA range
+        * can't go beyond RESTRICTED_VA_MAX for the vm_page_t packing to work.
         */
-       while ((zone_page_table_first_level_slot(zone_pages-1)) >= ZONE_PAGE_TABLE_FIRST_LEVEL_SIZE) {
-               zone_page_table_second_level_size <<= 1;
-               zone_page_table_second_level_shift_amount++;
-       }
-       
-       lck_grp_attr_setdefault(&zone_gc_lck_grp_attr);
-       lck_grp_init(&zone_gc_lck_grp, "zone_gc", &zone_gc_lck_grp_attr);
-       lck_attr_setdefault(&zone_gc_lck_attr);
-       lck_mtx_init_ext(&zone_gc_lock, &zone_gc_lck_ext, &zone_gc_lck_grp, &zone_gc_lck_attr);
-       
-#if CONFIG_ZLEAKS
+       zone_submap_init(&submap_min, Z_SUBMAP_IDX_VA_RESTRICTED_MAP,
+           zone_sub_map_numer[Z_SUBMAP_IDX_VA_RESTRICTED_MAP], &remaining_denom,
+           &remaining_size, SINGLE_GUARD);
+#endif /* defined(__LP64__) */
+
        /*
-        * Initialize the zone leak monitor
+        * Allocate metadata array
         */
-       zleak_init(max_zonemap_size);
-#endif /* CONFIG_ZLEAKS */
-}
+       zone_info.zi_meta_range =
+           zone_init_allocate_va(&submap_min, zone_meta_size, true);
+       zone_init_allocate_va(&submap_min, SINGLE_GUARD, true);
 
-void
-zone_page_table_expand(zone_page_index_t pindex)
-{
-       unsigned int first_index;
-       struct zone_page_table_entry * volatile * first_level_ptr;
+       zone_info.zi_array_base =
+           (struct zone_page_metadata *)zone_info.zi_meta_range.min_address -
+           zone_pva_from_addr(map_range->min_address).packed_address;
 
-       assert(pindex < zone_pages);
+       /*
+        * Allocate other submaps
+        */
+       for (unsigned idx = Z_SUBMAP_IDX_GENERAL_MAP; idx <= zone_last_submap_idx; idx++) {
+               zone_submap_init(&submap_min, idx, zone_sub_map_numer[idx],
+                   &remaining_denom, &remaining_size, MULTI_GUARD);
+       }
 
-       first_index = zone_page_table_first_level_slot(pindex);
-       first_level_ptr = &zone_page_table[first_index];
+       vm_map_t general_map = zone_submaps[Z_SUBMAP_IDX_GENERAL_MAP];
+       zone_info.zi_general_range.min_address = vm_map_min(general_map);
+       zone_info.zi_general_range.max_address = vm_map_max(general_map);
 
-       if (*first_level_ptr == NULL) {
-               /*
-                * We were able to verify the old first-level slot
-                * had NULL, so attempt to populate it.
-                */
+       assert(submap_min == map_range->max_address);
 
-               vm_offset_t second_level_array = 0;
-               vm_size_t second_level_size = round_page(zone_page_table_second_level_size * sizeof(struct zone_page_table_entry));
-               zone_page_index_t i;
-               struct zone_page_table_entry *entry_array;
+#if CONFIG_GZALLOC
+       gzalloc_init(zone_map_size);
+#endif
 
-               if (kmem_alloc_kobject(zone_map, &second_level_array,
-                                                          second_level_size, VM_KERN_MEMORY_OSFMK) != KERN_SUCCESS) {
-                       panic("zone_page_table_expand");
-               }
-               zone_map_table_page_count += (second_level_size / PAGE_SIZE);
+       zone_create_flags_t kma_flags = ZC_NOCACHING |
+           ZC_NOGC | ZC_NOENCRYPT | ZC_NOGZALLOC | ZC_NOCALLOUT |
+           ZC_KASAN_NOQUARANTINE | ZC_KASAN_NOREDZONE;
 
-               /*
-                * zone_gc() may scan the "zone_page_table" directly,
-                * so make sure any slots have a valid unused state.
-                */
-               entry_array = (struct zone_page_table_entry *)second_level_array;
-               for (i=0; i < zone_page_table_second_level_size; i++) {
-                       entry_array[i].alloc_count = ZONE_PAGE_UNUSED;
-                       entry_array[i].collect_count = 0;
-               }
+       (void)zone_create_ext("vm.permanent", 1, kma_flags,
+           ZONE_ID_PERMANENT, ^(zone_t z){
+               z->permanent = true;
+               z->z_elem_size = 1;
+               z->pcpu_elem_size = 1;
+#if defined(__LP64__)
+               z->submap_idx = Z_SUBMAP_IDX_VA_RESTRICTED_MAP;
+#endif
+       });
+       (void)zone_create_ext("vm.permanent.percpu", 1, kma_flags | ZC_PERCPU,
+           ZONE_ID_PERCPU_PERMANENT, ^(zone_t z){
+               z->permanent = true;
+               z->z_elem_size = 1;
+               z->pcpu_elem_size = zpercpu_count();
+#if defined(__LP64__)
+               z->submap_idx = Z_SUBMAP_IDX_VA_RESTRICTED_MAP;
+#endif
+       });
 
-               if (OSCompareAndSwapPtr(NULL, entry_array, first_level_ptr)) {
-                       /* Old slot was NULL, replaced with expanded level */
-                       OSAddAtomicLong(second_level_size, &zone_page_table_used_size);
-               } else {
-                       /* Old slot was not NULL, someone else expanded first */
-                       kmem_free(zone_map, second_level_array, second_level_size);
-                       zone_map_table_page_count -= (second_level_size / PAGE_SIZE);
+       /*
+        * Now fix the zones that are missing their zone stats
+        * we don't really know if zfree()s happened so our stats
+        * are slightly off for early boot. Â¯\_(ツ)_/¯
+        */
+       zone_index_foreach(idx) {
+               zone_t tz = &zone_array[idx];
+
+               if (tz->z_self) {
+                       zone_stats_t zs = zalloc_percpu_permanent_type(struct zone_stats);
+
+                       zpercpu_get_cpu(zs, 0)->zs_mem_allocated +=
+                           (tz->countavail - tz->countfree) *
+                           zone_elem_size(tz);
+                       assert(tz->z_stats == NULL);
+                       tz->z_stats = zs;
+#if ZONE_ENABLE_LOGGING
+                       if (tz->zone_logging && !tz->zlog_btlog) {
+                               zone_enable_logging(tz);
+                       }
+#endif
                }
-       } else {
-               /* Old slot was not NULL, already been expanded */
        }
-}
 
-struct zone_page_table_entry *
-zone_page_table_lookup(zone_page_index_t pindex)
-{
-       unsigned int first_index = zone_page_table_first_level_slot(pindex);
-       struct zone_page_table_entry *second_level = zone_page_table[first_index];
+#if CONFIG_ZLEAKS
+       /*
+        * Initialize the zone leak monitor
+        */
+       zleak_init(zone_map_size);
+#endif /* CONFIG_ZLEAKS */
 
-       if (second_level) {
-               return &second_level[zone_page_table_second_level_slot(pindex)];
+#if VM_MAX_TAG_ZONES
+       if (zone_tagging_on) {
+               vm_allocation_zones_init();
        }
+#endif
+}
+STARTUP(ZALLOC, STARTUP_RANK_FIRST, zone_init);
 
-       return NULL;
+__startup_func
+static void
+zone_set_foreign_range(
+       vm_offset_t range_min,
+       vm_offset_t range_max)
+{
+       zone_info.zi_foreign_range.min_address = range_min;
+       zone_info.zi_foreign_range.max_address = range_max;
 }
 
-extern volatile SInt32 kfree_nop_count;
+__startup_func
+vm_offset_t
+zone_foreign_mem_init(vm_size_t size)
+{
+       vm_offset_t mem = (vm_offset_t) pmap_steal_memory(size);
+       zone_set_foreign_range(mem, mem + size);
+       return mem;
+}
 
-#pragma mark -
-#pragma mark zalloc_canblock
+#pragma mark zalloc
 
+#if KASAN_ZALLOC
 /*
- *     zalloc returns an element from the specified zone.
- */
-static void *
-zalloc_internal(
-       zone_t  zone,
-       boolean_t canblock,
-       boolean_t nopagewait)
-{
-       vm_offset_t     addr = 0;
-       kern_return_t   retval;
-       uintptr_t       zbt[MAX_ZTRACE_DEPTH];  /* used in zone leak logging and zone leak detection */
-       int             numsaved = 0;
-       boolean_t       zone_replenish_wakeup = FALSE, zone_alloc_throttle = FALSE;
-#if    CONFIG_GZALLOC || ZONE_DEBUG    
-       boolean_t       did_gzalloc = FALSE;
-#endif
-       thread_t thr = current_thread();
-       boolean_t       check_poison = FALSE;
-       boolean_t       set_doing_alloc_with_vm_priv = FALSE;
-
-#if CONFIG_ZLEAKS
-       uint32_t        zleak_tracedepth = 0;  /* log this allocation if nonzero */
-#endif /* CONFIG_ZLEAKS */
-
-       assert(zone != ZONE_NULL);
-
-#if    CONFIG_GZALLOC
-       addr = gzalloc_alloc(zone, canblock);
-       did_gzalloc = (addr != 0);
-#endif
+ * Called from zfree() to add the element being freed to the KASan quarantine.
+ *
+ * Returns true if the newly-freed element made it into the quarantine without
+ * displacing another, false otherwise. In the latter case, addrp points to the
+ * address of the displaced element, which will be freed by the zone.
+ */
+static bool
+kasan_quarantine_freed_element(
+       zone_t          *zonep,         /* the zone the element is being freed to */
+       void            **addrp)        /* address of the element being freed */
+{
+       zone_t zone = *zonep;
+       void *addr = *addrp;
 
        /*
-        * If zone logging is turned on and this is the zone we're tracking, grab a backtrace.
+        * Resize back to the real allocation size and hand off to the KASan
+        * quarantine. `addr` may then point to a different allocation, if the
+        * current element replaced another in the quarantine. The zone then
+        * takes ownership of the swapped out free element.
         */
-       if (__improbable(DO_LOGGING(zone)))
-               numsaved = OSBacktrace((void*) zbt, MAX_ZTRACE_DEPTH);
+       vm_size_t usersz = zone_elem_size(zone) - 2 * zone->kasan_redzone;
+       vm_size_t sz = usersz;
 
-#if CONFIG_ZLEAKS
-       /*
-        * Zone leak detection: capture a backtrace every zleak_sample_factor
-        * allocations in this zone.
-        */
-       if (__improbable(zone->zleak_on && sample_counter(&zone->zleak_capture, zleak_sample_factor) == TRUE)) {
-               /* Avoid backtracing twice if zone logging is on */
-               if (numsaved == 0)
-                       zleak_tracedepth = fastbacktrace(zbt, MAX_ZTRACE_DEPTH);
-               else
-                       zleak_tracedepth = numsaved;
+       if (addr && zone->kasan_redzone) {
+               kasan_check_free((vm_address_t)addr, usersz, KASAN_HEAP_ZALLOC);
+               addr = (void *)kasan_dealloc((vm_address_t)addr, &sz);
+               assert(sz == zone_elem_size(zone));
        }
-#endif /* CONFIG_ZLEAKS */
+       if (addr && !zone->kasan_noquarantine) {
+               kasan_free(&addr, &sz, KASAN_HEAP_ZALLOC, zonep, usersz, true);
+               if (!addr) {
+                       return TRUE;
+               }
+       }
+       if (addr && zone->kasan_noquarantine) {
+               kasan_unpoison(addr, zone_elem_size(zone));
+       }
+       *addrp = addr;
+       return FALSE;
+}
 
-       lock_zone(zone);
+#endif /* KASAN_ZALLOC */
+
+static inline bool
+zone_needs_async_refill(zone_t zone)
+{
+       if (zone->countfree != 0 || zone->async_pending || zone->no_callout) {
+               return false;
+       }
+
+       return zone->expandable || zone->page_count < zone->page_count_max;
+}
+
+__attribute__((noinline))
+static void
+zone_refill_synchronously_locked(
+       zone_t         zone,
+       zalloc_flags_t flags)
+{
+       thread_t thr = current_thread();
+       bool     set_expanding_vm_priv = false;
+       zone_pva_t orig = zone->pages_intermediate;
 
-       if (zone->async_prio_refill && zone->zone_replenish_thread) {
-                   do {
-                           vm_size_t zfreec = (zone->cur_size - (zone->count * zone->elem_size));
-                           vm_size_t zrefillwm = zone->prio_refill_watermark * zone->elem_size;
-                           zone_replenish_wakeup = (zfreec < zrefillwm);
-                           zone_alloc_throttle = (zfreec < (zrefillwm / 2)) && ((thr->options & TH_OPT_VMPRIV) == 0);
-
-                           if (zone_replenish_wakeup) {
-                                   zone_replenish_wakeups_initiated++;
-                                   unlock_zone(zone);
-                                   /* Signal the potentially waiting
-                                    * refill thread.
-                                    */
-                                   thread_wakeup(&zone->zone_replenish_thread);
-
-                                   /* Scheduling latencies etc. may prevent
-                                    * the refill thread from keeping up
-                                    * with demand. Throttle consumers
-                                    * when we fall below half the
-                                    * watermark, unless VM privileged
-                                    */
-                                   if (zone_alloc_throttle) {
-                                           zone_replenish_throttle_count++;
-                                           assert_wait_timeout(zone, THREAD_UNINT, 1, NSEC_PER_MSEC);
-                                           thread_block(THREAD_CONTINUE_NULL);
-                                   }
-                                   lock_zone(zone);
-                           }
-                   } while (zone_alloc_throttle == TRUE);
-       }
-       
-       if (__probable(addr == 0))
-               addr = try_alloc_from_zone(zone, &check_poison);
-
-
-       while ((addr == 0) && canblock) {
+       while ((flags & Z_NOWAIT) == 0 && (zone->permanent
+           ? zone_pva_is_equal(zone->pages_intermediate, orig)
+           : zone->countfree == 0)) {
                /*
-                * zone is empty, try to expand it
-                * 
-                * Note that we now allow up to 2 threads (1 vm_privliged and 1 non-vm_privliged)
-                * to expand the zone concurrently...  this is necessary to avoid stalling
-                * vm_privileged threads running critical code necessary to continue compressing/swapping
-                * pages (i.e. making new free pages) from stalling behind non-vm_privileged threads
-                * waiting to acquire free pages when the vm_page_free_count is below the
+                * zone is empty, try to expand it
+                *
+                * Note that we now allow up to 2 threads (1 vm_privliged and
+                * 1 non-vm_privliged) to expand the zone concurrently...
+                *
+                * this is necessary to avoid stalling vm_privileged threads
+                * running critical code necessary to continue
+                * compressing/swapping pages (i.e. making new free pages) from
+                * stalling behind non-vm_privileged threads waiting to acquire
+                * free pages when the vm_page_free_count is below the
                 * vm_page_free_reserved limit.
                 */
-               if ((zone->doing_alloc_without_vm_priv || zone->doing_alloc_with_vm_priv) &&
-                   (((thr->options & TH_OPT_VMPRIV) == 0) || zone->doing_alloc_with_vm_priv)) {
+               if ((zone->expanding_no_vm_priv || zone->expanding_vm_priv) &&
+                   (((thr->options & TH_OPT_VMPRIV) == 0) || zone->expanding_vm_priv)) {
                        /*
                         * This is a non-vm_privileged thread and a non-vm_privileged or
                         * a vm_privileged thread is already expanding the zone...
@@ -2419,1412 +4494,1072 @@ zalloc_internal(
                         *
                         * In either case wait for a thread to finish, then try again.
                         */
-                       zone->waiting = TRUE;
-                       zone_sleep(zone);
-               } else if (zone->doing_gc) {
-                       /*
-                        * zone_gc() is running. Since we need an element
-                        * from the free list that is currently being
-                        * collected, set the waiting bit and 
-                        * wait for the GC process to finish
-                        * before trying again
-                        */
-                       zone->waiting = TRUE;
-                       zone_sleep(zone);
-               } else {
-                       vm_offset_t space;
-                       vm_size_t alloc_size;
-                       int retry = 0;
-
-                       if ((zone->cur_size + zone->elem_size) >
-                           zone->max_size) {
-                               if (zone->exhaustible)
-                                       break;
-                               if (zone->expandable) {
-                                       /*
-                                        * We're willing to overflow certain
-                                        * zones, but not without complaining.
-                                        *
-                                        * This is best used in conjunction
-                                        * with the collectable flag. What we
-                                        * want is an assurance we can get the
-                                        * memory back, assuming there's no
-                                        * leak. 
-                                        */
-                                       zone->max_size += (zone->max_size >> 1);
-                               } else {
-                                       unlock_zone(zone);
-
-                                       panic_include_zprint = TRUE;
-#if CONFIG_ZLEAKS
-                                       if (zleak_state & ZLEAK_STATE_ACTIVE)
-                                               panic_include_ztrace = TRUE;
-#endif /* CONFIG_ZLEAKS */
-                                       panic("zalloc: zone \"%s\" empty.", zone->zone_name);
-                               }
+                       zone->waiting = true;
+                       assert_wait(zone, THREAD_UNINT);
+                       unlock_zone(zone);
+                       thread_block(THREAD_CONTINUE_NULL);
+                       lock_zone(zone);
+                       continue;
+               }
+
+               if (zone->page_count >= zone->page_count_max) {
+                       if (zone->exhaustible) {
+                               break;
                        }
-                       if ((thr->options & TH_OPT_VMPRIV)) {
-                               zone->doing_alloc_with_vm_priv = TRUE;
-                               set_doing_alloc_with_vm_priv = TRUE;
+                       if (zone->expandable) {
+                               /*
+                                * If we're expandable, just don't go through this again.
+                                */
+                               zone->page_count_max = ~0u;
                        } else {
-                               zone->doing_alloc_without_vm_priv = TRUE;
-                       }
-                       unlock_zone(zone);
+                               unlock_zone(zone);
 
-                       for (;;) {
-                               int     zflags = KMA_KOBJECT|KMA_NOPAGEWAIT;
-
-                               if (vm_pool_low() || retry >= 1)
-                                       alloc_size = 
-                                               round_page(zone->elem_size);
-                               else
-                                       alloc_size = zone->alloc_size;
-                               
-                               if (zone->noencrypt)
-                                       zflags |= KMA_NOENCRYPT;
-                               
-                               retval = kernel_memory_allocate(zone_map, &space, alloc_size, 0, zflags, VM_KERN_MEMORY_ZONE);
-                               if (retval == KERN_SUCCESS) {
-#if    ZONE_ALIAS_ADDR
-                                       if (alloc_size == PAGE_SIZE)
-                                               space = zone_alias_addr(space);
-#endif
-                                       
+                               panic_include_zprint = true;
 #if CONFIG_ZLEAKS
-                                       if ((zleak_state & (ZLEAK_STATE_ENABLED | ZLEAK_STATE_ACTIVE)) == ZLEAK_STATE_ENABLED) {
-                                               if (zone_map->size >= zleak_global_tracking_threshold) {
-                                                       kern_return_t kr;
-                                                       
-                                                       kr = zleak_activate();
-                                                       if (kr != KERN_SUCCESS) {
-                                                               printf("Failed to activate live zone leak debugging (%d).\n", kr);
-                                                       }
-                                               }
-                                       }
-                                       
-                                       if ((zleak_state & ZLEAK_STATE_ACTIVE) && !(zone->zleak_on)) {
-                                               if (zone->cur_size > zleak_per_zone_tracking_threshold) {
-                                                       zone->zleak_on = TRUE;
-                                               }       
-                                       }
-#endif /* CONFIG_ZLEAKS */
-                                       zcram(zone, space, alloc_size);
-                                       
-                                       break;
-                               } else if (retval != KERN_RESOURCE_SHORTAGE) {
-                                       retry++;
-                                       
-                                       if (retry == 2) {
-                                               zone_gc(TRUE);
-                                               printf("zalloc did gc\n");
-                                               zone_display_zprint();
-                                       }
-                                       if (retry == 3) {
-                                               panic_include_zprint = TRUE;
-#if CONFIG_ZLEAKS
-                                               if ((zleak_state & ZLEAK_STATE_ACTIVE)) {
-                                                       panic_include_ztrace = TRUE;
-                                               }
-#endif /* CONFIG_ZLEAKS */             
-                                               if (retval == KERN_NO_SPACE) {
-                                                       zone_t zone_largest = zone_find_largest();
-                                                       panic("zalloc: zone map exhausted while allocating from zone %s, likely due to memory leak in zone %s (%lu total bytes, %d elements allocated)",
-                                                       zone->zone_name, zone_largest->zone_name,
-                                                       (unsigned long)zone_largest->cur_size, zone_largest->count);
-
-                                               }
-                                               panic("zalloc: \"%s\" (%d elements) retry fail %d, kfree_nop_count: %d", zone->zone_name, zone->count, retval, (int)kfree_nop_count);
-                                       }
-                               } else {
-                                       break;
+                               if (zleak_state & ZLEAK_STATE_ACTIVE) {
+                                       panic_include_ztrace = true;
                                }
+#endif /* CONFIG_ZLEAKS */
+                               panic("zalloc: zone \"%s\" empty.", zone->z_name);
                        }
-                       lock_zone(zone);
+               }
 
-                       if (set_doing_alloc_with_vm_priv == TRUE)
-                               zone->doing_alloc_with_vm_priv = FALSE;
-                       else
-                               zone->doing_alloc_without_vm_priv = FALSE; 
-                       
-                       if (zone->waiting) {
-                               zone->waiting = FALSE;
-                               zone_wakeup(zone);
-                       }
-                       addr = try_alloc_from_zone(zone, &check_poison);
-                       if (addr == 0 &&
-                           retval == KERN_RESOURCE_SHORTAGE) {
-                               if (nopagewait == TRUE)
-                                       break;  /* out of the main while loop */
-                               unlock_zone(zone);
+               /*
+                * It is possible that a BG thread is refilling/expanding the zone
+                * and gets pre-empted during that operation. That blocks all other
+                * threads from making progress leading to a watchdog timeout. To
+                * avoid that, boost the thread priority using the rwlock boost
+                */
+               set_thread_rwlock_boost();
 
-                               VM_PAGE_WAIT();
-                               lock_zone(zone);
-                       }
+               if ((thr->options & TH_OPT_VMPRIV)) {
+                       zone->expanding_vm_priv = true;
+                       set_expanding_vm_priv = true;
+               } else {
+                       zone->expanding_no_vm_priv = true;
+               }
+
+               zone_replenish_locked(zone, flags, false);
+
+               if (set_expanding_vm_priv == true) {
+                       zone->expanding_vm_priv = false;
+               } else {
+                       zone->expanding_no_vm_priv = false;
+               }
+
+               if (zone->waiting) {
+                       zone->waiting = false;
+                       thread_wakeup(zone);
+               }
+               clear_thread_rwlock_boost();
+
+               if (zone->countfree == 0) {
+                       assert(flags & Z_NOPAGEWAIT);
+                       break;
                }
-               if (addr == 0)
-                       addr = try_alloc_from_zone(zone, &check_poison);
        }
 
-#if CONFIG_ZLEAKS
-       /* Zone leak detection:
-        * If we're sampling this allocation, add it to the zleaks hash table. 
-        */
-       if (addr && zleak_tracedepth > 0)  {
-               /* Sampling can fail if another sample is happening at the same time in a different zone. */
-               if (!zleak_log(zbt, addr, zleak_tracedepth, zone->elem_size)) {
-                       /* If it failed, roll back the counter so we sample the next allocation instead. */
-                       zone->zleak_capture = zleak_sample_factor;
-               }
-       }
-#endif /* CONFIG_ZLEAKS */                     
-                       
-                       
-       if ((addr == 0) && (!canblock || nopagewait) && (zone->async_pending == FALSE) && (zone->no_callout == FALSE) && (zone->exhaustible == FALSE) && (!vm_pool_low())) {
-               zone->async_pending = TRUE;
+       if ((flags & (Z_NOWAIT | Z_NOPAGEWAIT)) &&
+           zone_needs_async_refill(zone) && !vm_pool_low()) {
+               zone->async_pending = true;
                unlock_zone(zone);
                thread_call_enter(&call_async_alloc);
                lock_zone(zone);
-               addr = try_alloc_from_zone(zone, &check_poison);
+               assert(zone->z_self == zone);
        }
+}
+
+__attribute__((noinline))
+static void
+zone_refill_asynchronously_locked(zone_t zone)
+{
+       uint32_t min_free = zone->prio_refill_count / 2;
+       uint32_t resv_free = zone->prio_refill_count / 4;
+       thread_t thr = current_thread();
 
        /*
-        * See if we should be logging allocations in this zone.  Logging is rarely done except when a leak is
-        * suspected, so this code rarely executes.  We need to do this code while still holding the zone lock
-        * since it protects the various log related data structures.
+        * Nothing to do if there are plenty of elements.
         */
+       while (zone->countfree <= min_free) {
+               /*
+                * Wakeup the replenish thread if not running.
+                */
+               if (!zone->zone_replenishing) {
+                       lck_spin_lock(&zone_replenish_lock);
+                       assert(zone_replenish_active < zone_replenish_max_threads);
+                       ++zone_replenish_active;
+                       lck_spin_unlock(&zone_replenish_lock);
+                       zone->zone_replenishing = true;
+                       zone_replenish_wakeups_initiated++;
+                       thread_wakeup(&zone->prio_refill_count);
+               }
 
-       if (__improbable(DO_LOGGING(zone) && addr)) {
-               btlog_add_entry(zlog_btlog, (void *)addr, ZOP_ALLOC, (void **)zbt, numsaved);
-       }
-
-       vm_offset_t     inner_size = zone->elem_size;
-       
-#if    ZONE_DEBUG
-       if (!did_gzalloc && addr && zone_debug_enabled(zone)) {
-               enqueue_tail(&zone->active_zones, (queue_entry_t)addr);
-               addr += ZONE_DEBUG_OFFSET;
-               inner_size -= ZONE_DEBUG_OFFSET;
-       }
-#endif
-
-       unlock_zone(zone);
-
-       if (__improbable(check_poison && addr)) {
-               vm_offset_t *element_cursor  = ((vm_offset_t *) addr) + 1;
-               vm_offset_t *backup  = get_backup_ptr(inner_size, (vm_offset_t *) addr);
-
-               for ( ; element_cursor < backup ; element_cursor++)
-                       if (__improbable(*element_cursor != ZP_POISON))
-                               zone_element_was_modified_panic(zone,
-                                                               addr,
-                                                               *element_cursor,
-                                                               ZP_POISON,
-                                                               ((vm_offset_t)element_cursor) - addr);
-       }
-
-       if (addr) {
                /*
-                * Clear out the old next pointer and backup to avoid leaking the cookie
-                * and so that only values on the freelist have a valid cookie
+                * We'll let VM_PRIV threads to continue to allocate until the
+                * reserve drops to 25%. After that only TH_OPT_ZONE_PRIV threads
+                * may continue.
+                *
+                * TH_OPT_ZONE_PRIV threads are the GC thread and a replenish thread itself.
+                * Replenish threads *need* to use the reserve. GC threads need to
+                * get through the current allocation, but then will wait at a higher
+                * level after they've dropped any locks which would deadlock the
+                * replenish thread.
                 */
+               if ((zone->countfree > resv_free && (thr->options & TH_OPT_VMPRIV)) ||
+                   (thr->options & TH_OPT_ZONE_PRIV)) {
+                       break;
+               }
 
-               vm_offset_t *primary  = (vm_offset_t *) addr;
-               vm_offset_t *backup   = get_backup_ptr(inner_size, primary);
+               /*
+                * Wait for the replenish threads to add more elements for us to allocate from.
+                */
+               zone_replenish_throttle_count++;
+               unlock_zone(zone);
+               assert_wait_timeout(zone, THREAD_UNINT, 1, NSEC_PER_MSEC);
+               thread_block(THREAD_CONTINUE_NULL);
+               lock_zone(zone);
 
-               *primary = ZP_POISON;
-               *backup  = ZP_POISON;
+               assert(zone->z_self == zone);
        }
 
-       TRACE_MACHLEAKS(ZALLOC_CODE, ZALLOC_CODE_2, zone->elem_size, addr);
-
-       if (addr) {
-               task_t task;
-               zinfo_usage_t zinfo;
-               vm_size_t sz = zone->elem_size;
-
-               if (zone->caller_acct)
-                       ledger_credit(thr->t_ledger, task_ledgers.tkm_private, sz);
-               else
-                       ledger_credit(thr->t_ledger, task_ledgers.tkm_shared, sz);
-
-               if ((task = thr->task) != NULL && (zinfo = task->tkm_zinfo) != NULL)
-                       OSAddAtomic64(sz, (int64_t *)&zinfo[zone->index].alloc);
+       /*
+        * If we're here because of zone_gc(), we didn't wait for
+        * zone_replenish_thread to finish.  So we need to ensure that
+        * we will successfully grab an element.
+        *
+        * zones that have a replenish thread configured.
+        * The value of (refill_level / 2) in the previous bit of code should have
+        * given us headroom even though this thread didn't wait.
+        */
+       if (thr->options & TH_OPT_ZONE_PRIV) {
+               assert(zone->countfree != 0);
        }
-       return((void *)addr);
-}
-
-
-void *
-zalloc(zone_t zone)
-{
-       return (zalloc_internal(zone, TRUE, FALSE));
-}
-
-void *
-zalloc_noblock(zone_t zone)
-{
-       return (zalloc_internal(zone, FALSE, FALSE));
-}
-
-void *
-zalloc_nopagewait(zone_t zone)
-{
-       return (zalloc_internal(zone, TRUE, TRUE));
 }
 
-void *
-zalloc_canblock(zone_t zone, boolean_t canblock)
+#if ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS
+__attribute__((noinline))
+static void
+zalloc_log_or_trace_leaks(zone_t zone, vm_offset_t addr)
 {
-       return (zalloc_internal(zone, canblock, FALSE));
-}
-
+       uintptr_t       zbt[MAX_ZTRACE_DEPTH];  /* used in zone leak logging and zone leak detection */
+       unsigned int    numsaved = 0;
+
+#if ZONE_ENABLE_LOGGING
+       if (DO_LOGGING(zone)) {
+               numsaved = backtrace_frame(zbt, MAX_ZTRACE_DEPTH,
+                   __builtin_frame_address(0), NULL);
+               btlog_add_entry(zone->zlog_btlog, (void *)addr,
+                   ZOP_ALLOC, (void **)zbt, numsaved);
+       }
+#endif
 
-void
-zalloc_async(
-       __unused thread_call_param_t          p0,
-       __unused thread_call_param_t p1)
-{
-       zone_t current_z = NULL, head_z;
-       unsigned int max_zones, i;
-       void *elt = NULL;
-       boolean_t pending = FALSE;
-       
-       simple_lock(&all_zones_lock);
-       head_z = first_zone;
-       max_zones = num_zones;
-       simple_unlock(&all_zones_lock);
-       current_z = head_z;
-       for (i = 0; i < max_zones; i++) {
-               lock_zone(current_z);
-               if (current_z->async_pending == TRUE) {
-                       current_z->async_pending = FALSE;
-                       pending = TRUE;
+#if CONFIG_ZLEAKS
+       /*
+        * Zone leak detection: capture a backtrace every zleak_sample_factor
+        * allocations in this zone.
+        */
+       if (__improbable(zone->zleak_on)) {
+               if (sample_counter(&zone->zleak_capture, zleak_sample_factor)) {
+                       /* Avoid backtracing twice if zone logging is on */
+                       if (numsaved == 0) {
+                               numsaved = backtrace_frame(zbt, MAX_ZTRACE_DEPTH,
+                                   __builtin_frame_address(1), NULL);
+                       }
+                       /* Sampling can fail if another sample is happening at the same time in a different zone. */
+                       if (!zleak_log(zbt, addr, numsaved, zone_elem_size(zone))) {
+                               /* If it failed, roll back the counter so we sample the next allocation instead. */
+                               zone->zleak_capture = zleak_sample_factor;
+                       }
                }
-               unlock_zone(current_z);
+       }
 
-               if (pending == TRUE) {
-                       elt = zalloc_canblock(current_z, TRUE);
-                       zfree(current_z, elt);
-                       pending = FALSE;
+       if (__improbable(zone_leaks_scan_enable &&
+           !(zone_elem_size(zone) & (sizeof(uintptr_t) - 1)))) {
+               unsigned int count, idx;
+               /* Fill element, from tail, with backtrace in reverse order */
+               if (numsaved == 0) {
+                       numsaved = backtrace_frame(zbt, MAX_ZTRACE_DEPTH,
+                           __builtin_frame_address(1), NULL);
+               }
+               count = (unsigned int)(zone_elem_size(zone) / sizeof(uintptr_t));
+               if (count >= numsaved) {
+                       count = numsaved - 1;
+               }
+               for (idx = 0; idx < count; idx++) {
+                       ((uintptr_t *)addr)[count - 1 - idx] = zbt[idx + 1];
                }
-               /*
-                * This is based on assumption that zones never get
-                * freed once allocated and linked. 
-                * Hence a read outside of lock is OK.
-                */
-               current_z = current_z->next_zone;
        }
+#endif /* CONFIG_ZLEAKS */
 }
 
-/*
- *     zget returns an element from the specified zone
- *     and immediately returns nothing if there is nothing there.
- *
- *     This form should be used when you can not block (like when
- *     processing an interrupt).
- *
- *     XXX: It seems like only vm_page_grab_fictitious_common uses this, and its
- *  friend vm_page_more_fictitious can block, so it doesn't seem like 
- *  this is used for interrupts any more....
- */
-void *
-zget(
-       register zone_t zone)
+static inline bool
+zalloc_should_log_or_trace_leaks(zone_t zone, vm_size_t elem_size)
 {
-       vm_offset_t     addr;
-       boolean_t       check_poison = FALSE;
-       
-#if CONFIG_ZLEAKS
-       uintptr_t       zbt[MAX_ZTRACE_DEPTH];          /* used for zone leak detection */
-       uint32_t        zleak_tracedepth = 0;  /* log this allocation if nonzero */
-#endif /* CONFIG_ZLEAKS */
-
-       assert( zone != ZONE_NULL );
-
+#if ZONE_ENABLE_LOGGING
+       if (DO_LOGGING(zone)) {
+               return true;
+       }
+#endif
 #if CONFIG_ZLEAKS
        /*
-        * Zone leak detection: capture a backtrace
+        * Zone leak detection: capture a backtrace every zleak_sample_factor
+        * allocations in this zone.
         */
-       if (__improbable(zone->zleak_on && sample_counter(&zone->zleak_capture, zleak_sample_factor) == TRUE)) {
-               zleak_tracedepth = fastbacktrace(zbt, MAX_ZTRACE_DEPTH);
+       if (zone->zleak_on) {
+               return true;
+       }
+       if (zone_leaks_scan_enable && !(elem_size & (sizeof(uintptr_t) - 1))) {
+               return true;
        }
 #endif /* CONFIG_ZLEAKS */
+       return false;
+}
+#endif /* ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS */
+#if ZONE_ENABLE_LOGGING
 
-       if (!lock_try_zone(zone))
-               return NULL;
-       
-       addr = try_alloc_from_zone(zone, &check_poison);
-
-       vm_offset_t     inner_size = zone->elem_size;
-       
-#if    ZONE_DEBUG
-       if (addr && zone_debug_enabled(zone)) {
-               enqueue_tail(&zone->active_zones, (queue_entry_t)addr);
-               addr += ZONE_DEBUG_OFFSET;
-               inner_size -= ZONE_DEBUG_OFFSET;
-       }
-#endif /* ZONE_DEBUG */
-       
-#if CONFIG_ZLEAKS
+__attribute__((noinline))
+static void
+zfree_log_trace(zone_t zone, vm_offset_t addr)
+{
        /*
-        * Zone leak detection: record the allocation 
+        * See if we're doing logging on this zone.
+        *
+        * There are two styles of logging used depending on
+        * whether we're trying to catch a leak or corruption.
         */
-       if (zone->zleak_on && zleak_tracedepth > 0 && addr) {
-               /* Sampling can fail if another sample is happening at the same time in a different zone. */
-               if (!zleak_log(zbt, addr, zleak_tracedepth, zone->elem_size)) {
-                       /* If it failed, roll back the counter so we sample the next allocation instead. */
-                       zone->zleak_capture = zleak_sample_factor;
+       if (__improbable(DO_LOGGING(zone))) {
+               if (corruption_debug_flag) {
+                       uintptr_t       zbt[MAX_ZTRACE_DEPTH];
+                       unsigned int    numsaved;
+                       /*
+                        * We're logging to catch a corruption.
+                        *
+                        * Add a record of this zfree operation to log.
+                        */
+                       numsaved = backtrace_frame(zbt, MAX_ZTRACE_DEPTH,
+                           __builtin_frame_address(1), NULL);
+                       btlog_add_entry(zone->zlog_btlog, (void *)addr, ZOP_FREE,
+                           (void **)zbt, numsaved);
+               } else {
+                       /*
+                        * We're logging to catch a leak.
+                        *
+                        * Remove any record we might have for this element
+                        * since it's being freed.  Note that we may not find it
+                        * if the buffer overflowed and that's OK.
+                        *
+                        * Since the log is of a limited size, old records get
+                        * overwritten if there are more zallocs than zfrees.
+                        */
+                       btlog_remove_entries_for_element(zone->zlog_btlog, (void *)addr);
                }
        }
-#endif /* CONFIG_ZLEAKS */
-       
-       unlock_zone(zone);
-
-       if (__improbable(check_poison && addr)) {
-               vm_offset_t *element_cursor  = ((vm_offset_t *) addr) + 1;
-               vm_offset_t *backup  = get_backup_ptr(inner_size, (vm_offset_t *) addr);
-
-               for ( ; element_cursor < backup ; element_cursor++)
-                       if (__improbable(*element_cursor != ZP_POISON))
-                               zone_element_was_modified_panic(zone,
-                                                               addr,
-                                                               *element_cursor,
-                                                               ZP_POISON,
-                                                               ((vm_offset_t)element_cursor) - addr);
-       }
-
-       if (addr) {
-               /*
-                * Clear out the old next pointer and backup to avoid leaking the cookie
-                * and so that only values on the freelist have a valid cookie
-                */
-               vm_offset_t *primary  = (vm_offset_t *) addr;
-               vm_offset_t *backup   = get_backup_ptr(inner_size, primary);
-
-               *primary = ZP_POISON;
-               *backup  = ZP_POISON;
-       }
-
-       return((void *) addr);
 }
+#endif /* ZONE_ENABLE_LOGGING */
 
-/* Keep this FALSE by default.  Large memory machine run orders of magnitude
-   slower in debug mode when true.  Use debugger to enable if needed */
-/* static */ boolean_t zone_check = FALSE;
-
-static void zone_check_freelist(zone_t zone, vm_offset_t elem)
+/*
+ * Removes an element from the zone's free list, returning 0 if the free list is empty.
+ * Verifies that the next-pointer and backup next-pointer are intact,
+ * and verifies that a poisoned element hasn't been modified.
+ */
+vm_offset_t
+zalloc_direct_locked(
+       zone_t              zone,
+       zalloc_flags_t      flags __unused,
+       vm_size_t           waste __unused)
 {
-       struct zone_free_element *this;
-       struct zone_page_metadata *thispage;
+       struct zone_page_metadata *page_meta;
+       zone_addr_kind_t kind = ZONE_ADDR_NATIVE;
+       vm_offset_t element, page, validate_bit = 0;
 
-       if (zone->use_page_list) {
-               if (zone->allows_foreign) {
-                       for (thispage = (struct zone_page_metadata *)queue_first(&zone->pages.any_free_foreign);
-                                !queue_end(&zone->pages.any_free_foreign, (queue_entry_t)thispage);
-                                thispage = (struct zone_page_metadata *)queue_next((queue_chain_t *)thispage)) {
-                               for (this = thispage->elements;
-                                        this != NULL;
-                                        this = this->next) {
-                                       if (!is_sane_zone_element(zone, (vm_address_t)this) || (vm_address_t)this == elem)
-                                               panic("zone_check_freelist");
-                               }
-                       }
-               }
-               for (thispage = (struct zone_page_metadata *)queue_first(&zone->pages.all_free);
-                        !queue_end(&zone->pages.all_free, (queue_entry_t)thispage);
-                        thispage = (struct zone_page_metadata *)queue_next((queue_chain_t *)thispage)) {
-                       for (this = thispage->elements;
-                                this != NULL;
-                                this = this->next) {
-                               if (!is_sane_zone_element(zone, (vm_address_t)this) || (vm_address_t)this == elem)
-                                       panic("zone_check_freelist");
-                       }
-               }
-               for (thispage = (struct zone_page_metadata *)queue_first(&zone->pages.intermediate);
-                        !queue_end(&zone->pages.intermediate, (queue_entry_t)thispage);
-                        thispage = (struct zone_page_metadata *)queue_next((queue_chain_t *)thispage)) {
-                       for (this = thispage->elements;
-                                this != NULL;
-                                this = this->next) {
-                               if (!is_sane_zone_element(zone, (vm_address_t)this) || (vm_address_t)this == elem)
-                                       panic("zone_check_freelist");
-                       }
+       /* if zone is empty, bail */
+       if (!zone_pva_is_null(zone->pages_any_free_foreign)) {
+               kind = ZONE_ADDR_FOREIGN;
+               page_meta = zone_pva_to_meta(zone->pages_any_free_foreign, kind);
+               page = (vm_offset_t)page_meta;
+       } else if (!zone_pva_is_null(zone->pages_intermediate)) {
+               page_meta = zone_pva_to_meta(zone->pages_intermediate, kind);
+               page = zone_pva_to_addr(zone->pages_intermediate);
+       } else if (!zone_pva_is_null(zone->pages_all_free)) {
+               page_meta = zone_pva_to_meta(zone->pages_all_free, kind);
+               page = zone_pva_to_addr(zone->pages_all_free);
+               if (os_sub_overflow(zone->allfree_page_count,
+                   page_meta->zm_page_count, &zone->allfree_page_count)) {
+                       zone_accounting_panic(zone, "allfree_page_count wrap-around");
                }
        } else {
-               for (this = zone->free_elements;
-                        this != NULL;
-                        this = this->next) {
-                       if (!is_sane_zone_element(zone, (vm_address_t)this) || (vm_address_t)this == elem)
-                               panic("zone_check_freelist");
-               }
+               zone_accounting_panic(zone, "countfree corruption");
        }
-}
-
-static zone_t zone_last_bogus_zone = ZONE_NULL;
-static vm_offset_t zone_last_bogus_elem = 0;
 
-void
-zfree(
-       register zone_t zone,
-       void            *addr)
-{
-       vm_offset_t     elem = (vm_offset_t) addr;
-       uintptr_t       zbt[MAX_ZTRACE_DEPTH];                  /* only used if zone logging is enabled via boot-args */
-       int             numsaved = 0;
-       boolean_t       gzfreed = FALSE;
-       boolean_t       poison = FALSE;
-
-       assert(zone != ZONE_NULL);
-
-#if 1
-       if (zone->use_page_list) {
-               struct zone_page_metadata *page_meta = get_zone_page_metadata((struct zone_free_element *)addr);
-               if (zone != page_meta->zone) {
-                       /*
-                        * Something bad has happened. Someone tried to zfree a pointer but the metadata says it is from
-                        * a different zone (or maybe it's from a zone that doesn't use page free lists at all). We can repair
-                        * some cases of this, if:
-                        * 1) The specified zone had use_page_list, and the true zone also has use_page_list set. In that case
-                        *    we can swap the zone_t
-                        * 2) The specified zone had use_page_list, but the true zone does not. In this case page_meta is garbage,
-                        *    and dereferencing page_meta->zone might panic.
-                        * To distinguish the two, we enumerate the zone list to match it up.
-                        * We do not handle the case where an incorrect zone is passed that does not have use_page_list set,
-                        * even if the true zone did have this set.
-                        */
-                       zone_t fixed_zone = NULL;
-                       int fixed_i, max_zones;
-
-                       simple_lock(&all_zones_lock);
-                       max_zones = num_zones;
-                       fixed_zone = first_zone;
-                       simple_unlock(&all_zones_lock);
-
-                       for (fixed_i=0; fixed_i < max_zones; fixed_i++, fixed_zone = fixed_zone->next_zone) {
-                               if (fixed_zone == page_meta->zone && fixed_zone->use_page_list) {
-                                       /* we can fix this */
-                                       printf("Fixing incorrect zfree from zone %s to zone %s\n", zone->zone_name, fixed_zone->zone_name);
-                                       zone = fixed_zone;
-                                       break;
-                               }
-                       }
-               }
+       if (!zone_has_index(zone, page_meta->zm_index)) {
+               zone_page_metadata_index_confusion_panic(zone, page, page_meta);
        }
-#endif
+
+       element = zone_page_meta_get_freelist(zone, page_meta, page);
+
+       vm_offset_t *primary = (vm_offset_t *) element;
+       vm_offset_t *backup  = get_backup_ptr(zone_elem_size(zone), primary);
 
        /*
-        * If zone logging is turned on and this is the zone we're tracking, grab a backtrace.
+        * since the primary next pointer is xor'ed with zp_nopoison_cookie
+        * for obfuscation, retrieve the original value back
         */
+       vm_offset_t  next_element          = *primary ^ zp_nopoison_cookie;
+       vm_offset_t  next_element_primary  = *primary;
+       vm_offset_t  next_element_backup   = *backup;
 
-       if (__improbable(DO_LOGGING(zone) && corruption_debug_flag))
-               numsaved = OSBacktrace((void *)zbt, MAX_ZTRACE_DEPTH);
+       /*
+        * backup_ptr_mismatch_panic will determine what next_element
+        * should have been, and print it appropriately
+        */
+       if (!zone_page_meta_is_sane_element(zone, page_meta, page, next_element, kind)) {
+               backup_ptr_mismatch_panic(zone, page_meta, page, element);
+       }
 
-#if MACH_ASSERT
-       /* Basic sanity checks */
-       if (zone == ZONE_NULL || elem == (vm_offset_t)0)
-               panic("zfree: NULL");
-       /* zone_gc assumes zones are never freed */
-       if (zone == zone_zone)
-               panic("zfree: freeing to zone_zone breaks zone_gc!");
-#endif
+       /* Check the backup pointer for the regular cookie */
+       if (__improbable(next_element_primary != next_element_backup)) {
+               /* Check for the poisoned cookie instead */
+               if (__improbable(next_element != (next_element_backup ^ zp_poisoned_cookie))) {
+                       /* Neither cookie is valid, corruption has occurred */
+                       backup_ptr_mismatch_panic(zone, page_meta, page, element);
+               }
 
-#if    CONFIG_GZALLOC  
-       gzfreed = gzalloc_free(zone, addr);
-#endif
+               /*
+                * Element was marked as poisoned, so check its integrity before using it.
+                */
+               validate_bit = ZALLOC_ELEMENT_NEEDS_VALIDATION;
+       } else if (zone->zfree_clear_mem) {
+               validate_bit = ZALLOC_ELEMENT_NEEDS_VALIDATION;
+       }
 
-       TRACE_MACHLEAKS(ZFREE_CODE, ZFREE_CODE_2, zone->elem_size, (uintptr_t)addr);
+       /* Remove this element from the free list */
+       zone_page_meta_set_freelist(page_meta, page, next_element);
 
-       if (__improbable(!gzfreed && zone->collectable && !zone->allows_foreign &&
-               !from_zone_map(elem, zone->elem_size))) {
-#if MACH_ASSERT
-               panic("zfree: non-allocated memory in collectable zone!");
-#endif
-               zone_last_bogus_zone = zone;
-               zone_last_bogus_elem = elem;
-               return;
+       if (kind == ZONE_ADDR_FOREIGN) {
+               if (next_element == 0) {
+                       /* last foreign element allocated on page, move to all_used_foreign */
+                       zone_meta_requeue(zone, &zone->pages_all_used_foreign, page_meta, kind);
+               }
+       } else if (next_element == 0) {
+               zone_meta_requeue(zone, &zone->pages_all_used, page_meta, kind);
+       } else if (page_meta->zm_alloc_count == 0) {
+               /* remove from free, move to intermediate */
+               zone_meta_requeue(zone, &zone->pages_intermediate, page_meta, kind);
        }
 
-       if ((zp_factor != 0 || zp_tiny_zone_limit != 0) && !gzfreed) {
+       if (os_add_overflow(page_meta->zm_alloc_count, 1,
+           &page_meta->zm_alloc_count)) {
                /*
-                * Poison the memory before it ends up on the freelist to catch
-                * use-after-free and use of uninitialized memory
+                * This will not catch a lot of errors, the proper check
+                * would be against the number of elements this run should
+                * have which is expensive to count.
                 *
-                * Always poison tiny zones' elements (limit is 0 if -no-zp is set)
-                * Also poison larger elements periodically
+                * But zm_alloc_count is a 16 bit number which could
+                * theoretically be valuable to cause to wrap around,
+                * so catch this.
                 */
+               zone_page_meta_accounting_panic(zone, page_meta,
+                   "zm_alloc_count overflow");
+       }
+       if (os_sub_overflow(zone->countfree, 1, &zone->countfree)) {
+               zone_accounting_panic(zone, "countfree wrap-around");
+       }
 
-               vm_offset_t     inner_size = zone->elem_size;
-
-#if    ZONE_DEBUG
-               if (!gzfreed && zone_debug_enabled(zone)) {
-                       inner_size -= ZONE_DEBUG_OFFSET;
+#if VM_MAX_TAG_ZONES
+       if (__improbable(zone->tags)) {
+               vm_tag_t tag = zalloc_flags_get_tag(flags);
+               // set the tag with b0 clear so the block remains inuse
+               ZTAG(zone, element)[0] = (vm_tag_t)(tag << 1);
+               vm_tag_update_zone_size(tag, zone->tag_zone_index,
+                   zone_elem_size(zone), waste);
+       }
+#endif /* VM_MAX_TAG_ZONES */
+#if KASAN_ZALLOC
+       if (zone->percpu) {
+               zpercpu_foreach_cpu(i) {
+                       kasan_poison_range(element + ptoa(i),
+                           zone_elem_size(zone), ASAN_VALID);
                }
+       } else {
+               kasan_poison_range(element, zone_elem_size(zone), ASAN_VALID);
+       }
+#endif
+
+       return element | validate_bit;
+}
+
+/*
+ *     zalloc returns an element from the specified zone.
+ *
+ *     The function is noinline when zlog can be used so that the backtracing can
+ *     reliably skip the zalloc_ext() and zalloc_log_or_trace_leaks()
+ *     boring frames.
+ */
+#if ZONE_ENABLE_LOGGING
+__attribute__((noinline))
 #endif
-               uint32_t sample_factor = zp_factor + (((uint32_t)inner_size) >> zp_scale);
+void *
+zalloc_ext(
+       zone_t          zone,
+       zone_stats_t    zstats,
+       zalloc_flags_t  flags,
+       vm_size_t       waste)
+{
+       vm_offset_t     addr = 0;
+       vm_size_t       elem_size = zone_elem_size(zone);
 
-               if (inner_size <= zp_tiny_zone_limit)
-                       poison = TRUE;
-               else if (zp_factor != 0 && sample_counter(&zone->zp_count, sample_factor) == TRUE)
-                       poison = TRUE;
+       /*
+        * KASan uses zalloc() for fakestack, which can be called anywhere.
+        * However, we make sure these calls can never block.
+        */
+       assert(zone->kasan_fakestacks ||
+           ml_get_interrupts_enabled() ||
+           ml_is_quiescing() ||
+           debug_mode_active() ||
+           startup_phase < STARTUP_SUB_EARLY_BOOT);
 
-               if (__improbable(poison)) {
+       /*
+        * Make sure Z_NOFAIL was not obviously misused
+        */
+       if ((flags & Z_NOFAIL) && !zone->prio_refill_count) {
+               assert(!zone->exhaustible && (flags & (Z_NOWAIT | Z_NOPAGEWAIT)) == 0);
+       }
 
-                       /* memset_pattern{4|8} could help make this faster: <rdar://problem/4662004> */
-                       /* Poison everything but primary and backup */
-                       vm_offset_t *element_cursor  = ((vm_offset_t *) elem) + 1;
-                       vm_offset_t *backup   = get_backup_ptr(inner_size, (vm_offset_t *)elem);
+#if CONFIG_ZCACHE
+       /*
+        * Note: if zone caching is on, gzalloc and tags aren't used
+        *       so we can always check this first
+        */
+       if (zone_caching_enabled(zone)) {
+               addr = zcache_alloc_from_cpu_cache(zone, zstats, waste);
+               if (__probable(addr)) {
+                       goto allocated_from_cache;
+               }
+       }
+#endif /* CONFIG_ZCACHE */
 
-                       for ( ; element_cursor < backup; element_cursor++)
-                               *element_cursor = ZP_POISON;
+#if CONFIG_GZALLOC
+       if (__improbable(zone->gzalloc_tracked)) {
+               addr = gzalloc_alloc(zone, zstats, flags);
+               goto allocated_from_gzalloc;
+       }
+#endif /* CONFIG_GZALLOC */
+#if VM_MAX_TAG_ZONES
+       if (__improbable(zone->tags)) {
+               vm_tag_t tag = zalloc_flags_get_tag(flags);
+               if (tag == VM_KERN_MEMORY_NONE) {
+                       /*
+                        * zone views into heaps can lead to a site-less call
+                        * and we fallback to KALLOC as a tag for those.
+                        */
+                       tag = VM_KERN_MEMORY_KALLOC;
+                       flags |= Z_VM_TAG(tag);
                }
+               vm_tag_will_update_zone(tag, zone->tag_zone_index);
        }
+#endif /* VM_MAX_TAG_ZONES */
 
        lock_zone(zone);
+       assert(zone->z_self == zone);
 
        /*
-        * See if we're doing logging on this zone.  There are two styles of logging used depending on
-        * whether we're trying to catch a leak or corruption.  See comments above in zalloc for details.
+        * Check if we need another thread to replenish the zone or
+        * if we have to wait for a replenish thread to finish.
+        * This is used for elements, like vm_map_entry, which are
+        * needed themselves to implement zalloc().
         */
-
-       if (__improbable(DO_LOGGING(zone))) {
-               if (corruption_debug_flag) {
-                       /*
-                        * We're logging to catch a corruption.  Add a record of this zfree operation
-                        * to log.
-                        */
-                       btlog_add_entry(zlog_btlog, (void *)addr, ZOP_FREE, (void **)zbt, numsaved);
-               } else {
-                       /*
-                        * We're logging to catch a leak. Remove any record we might have for this
-                        * element since it's being freed.  Note that we may not find it if the buffer
-                        * overflowed and that's OK.  Since the log is of a limited size, old records
-                        * get overwritten if there are more zallocs than zfrees.
-                        */
-                       btlog_remove_entries_for_element(zlog_btlog, (void *)addr);
+       if (__improbable(zone->prio_refill_count &&
+           zone->countfree <= zone->prio_refill_count / 2)) {
+               zone_refill_asynchronously_locked(zone);
+       } else if (__improbable(zone->countfree == 0)) {
+               zone_refill_synchronously_locked(zone, flags);
+               if (__improbable(zone->countfree == 0)) {
+                       unlock_zone(zone);
+                       if (__improbable(flags & Z_NOFAIL)) {
+                               zone_nofail_panic(zone);
+                       }
+                       goto out_nomem;
                }
        }
 
-#if    ZONE_DEBUG
-       if (!gzfreed && zone_debug_enabled(zone)) {
-               queue_t tmp_elem;
-
-               elem -= ZONE_DEBUG_OFFSET;
-               if (zone_check) {
-                       /* check the zone's consistency */
-
-                       for (tmp_elem = queue_first(&zone->active_zones);
-                            !queue_end(tmp_elem, &zone->active_zones);
-                            tmp_elem = queue_next(tmp_elem))
-                               if (elem == (vm_offset_t)tmp_elem)
-                                       break;
-                       if (elem != (vm_offset_t)tmp_elem)
-                               panic("zfree()ing element from wrong zone");
+       addr = zalloc_direct_locked(zone, flags, waste);
+       if (__probable(zstats != NULL)) {
+               /*
+                * The few vm zones used before zone_init() runs do not have
+                * per-cpu stats yet
+                */
+               int cpu = cpu_number();
+               zpercpu_get_cpu(zstats, cpu)->zs_mem_allocated += elem_size;
+#if ZALLOC_DETAILED_STATS
+               if (waste) {
+                       zpercpu_get_cpu(zstats, cpu)->zs_mem_wasted += waste;
                }
-               remqueue((queue_t) elem);
-       }
-#endif /* ZONE_DEBUG */
-       if (zone_check) {
-               zone_check_freelist(zone, elem);
+#endif /* ZALLOC_DETAILED_STATS */
        }
 
-       if (__probable(!gzfreed))
-               free_to_zone(zone, elem, poison);
+       unlock_zone(zone);
 
-#if MACH_ASSERT
-       if (zone->count < 0)
-               panic("zfree: zone count underflow in zone %s while freeing element %p, possible cause: double frees or freeing memory that did not come from this zone",
-               zone->zone_name, addr);
+#if ZALLOC_ENABLE_POISONING
+       bool validate = addr & ZALLOC_ELEMENT_NEEDS_VALIDATION;
 #endif
-       
-
-#if CONFIG_ZLEAKS
+       addr &= ~ZALLOC_ELEMENT_NEEDS_VALIDATION;
+       zone_clear_freelist_pointers(zone, addr);
+#if ZALLOC_ENABLE_POISONING
        /*
-        * Zone leak detection: un-track the allocation 
+        * Note: percpu zones do not respect ZONE_MIN_ELEM_SIZE,
+        *       so we will check the first word even if we just
+        *       cleared it.
         */
-       if (zone->zleak_on) {
-               zleak_free(elem, zone->elem_size);
+       zalloc_validate_element(zone, addr, elem_size - sizeof(vm_offset_t),
+           validate);
+#endif /* ZALLOC_ENABLE_POISONING */
+
+allocated_from_cache:
+#if ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS
+       if (__improbable(zalloc_should_log_or_trace_leaks(zone, elem_size))) {
+               zalloc_log_or_trace_leaks(zone, addr);
+       }
+#endif /* ZONE_ENABLE_LOGGING || CONFIG_ZLEAKS */
+
+#if CONFIG_GZALLOC
+allocated_from_gzalloc:
+#endif
+#if KASAN_ZALLOC
+       if (zone->kasan_redzone) {
+               addr = kasan_alloc(addr, elem_size,
+                   elem_size - 2 * zone->kasan_redzone, zone->kasan_redzone);
+               elem_size -= 2 * zone->kasan_redzone;
        }
-#endif /* CONFIG_ZLEAKS */
-       
        /*
-        * If elements have one or more pages, and memory is low,
-        * request to run the garbage collection in the zone  the next 
-        * time the pageout thread runs.
+        * Initialize buffer with unique pattern only if memory
+        * wasn't expected to be zeroed.
         */
-       if (zone->elem_size >= PAGE_SIZE && 
-           vm_pool_low()){
-               zone_gc_forced = TRUE;
+       if (!zone->zfree_clear_mem && !(flags & Z_ZERO)) {
+               kasan_leak_init(addr, elem_size);
+       }
+#endif /* KASAN_ZALLOC */
+       if ((flags & Z_ZERO) && !zone->zfree_clear_mem) {
+               bzero((void *)addr, elem_size);
        }
-       unlock_zone(zone);
-
-       {
-               thread_t thr = current_thread();
-               task_t task;
-               zinfo_usage_t zinfo;
-               vm_size_t sz = zone->elem_size;
 
-               if (zone->caller_acct)
-                       ledger_debit(thr->t_ledger, task_ledgers.tkm_private, sz);
-               else
-                       ledger_debit(thr->t_ledger, task_ledgers.tkm_shared, sz);
+       TRACE_MACHLEAKS(ZALLOC_CODE, ZALLOC_CODE_2, elem_size, addr);
 
-               if ((task = thr->task) != NULL && (zinfo = task->tkm_zinfo) != NULL)
-                       OSAddAtomic64(sz, (int64_t *)&zinfo[zone->index].free);
-       }
+out_nomem:
+       DTRACE_VM2(zalloc, zone_t, zone, void*, addr);
+       return (void *)addr;
 }
 
-
-/*     Change a zone's flags.
- *     This routine must be called immediately after zinit.
- */
-void
-zone_change(
-       zone_t          zone,
-       unsigned int    item,
-       boolean_t       value)
+void *
+zalloc(union zone_or_view zov)
 {
-       assert( zone != ZONE_NULL );
-       assert( value == TRUE || value == FALSE );
-
-       switch(item){
-               case Z_NOENCRYPT:
-                       zone->noencrypt = value;
-                       break;
-               case Z_EXHAUST:
-                       zone->exhaustible = value;
-                       break;
-               case Z_COLLECT:
-                       zone->collectable = value;
-                       break;
-               case Z_EXPAND:
-                       zone->expandable = value;
-                       break;
-               case Z_FOREIGN:
-                       zone->allows_foreign = value;
-                       break;
-               case Z_CALLERACCT:
-                       zone->caller_acct = value;
-                       break;
-               case Z_NOCALLOUT:
-                       zone->no_callout = value;
-                       break;
-               case Z_GZALLOC_EXEMPT:
-                       zone->gzalloc_exempt = value;
-#if    CONFIG_GZALLOC
-                       gzalloc_reconfigure(zone);
-#endif
-                       break;
-               case Z_ALIGNMENT_REQUIRED:
-                       zone->alignment_required = value;
-                       /*
-                        * Disable the page list optimization here to provide
-                        * more of an alignment guarantee. This prevents
-                        * the alignment from being modified by the metadata stored
-                        * at the beginning of the page.
-                        */
-                       zone->use_page_list = FALSE;
-#if    ZONE_DEBUG                      
-                       zone_debug_disable(zone);
-#endif
-#if    CONFIG_GZALLOC
-                       gzalloc_reconfigure(zone);
-#endif
-                       break;
-               default:
-                       panic("Zone_change: Wrong Item Type!");
-                       /* break; */
-       }
+       return zalloc_flags(zov, Z_WAITOK);
 }
 
-/*
- * Return the expected number of free elements in the zone.
- * This calculation will be incorrect if items are zfree'd that
- * were never zalloc'd/zget'd. The correct way to stuff memory
- * into a zone is by zcram.
- */
-
-integer_t
-zone_free_count(zone_t zone)
+void *
+zalloc_noblock(union zone_or_view zov)
 {
-       integer_t free_count;
-
-       lock_zone(zone);
-       free_count = zone->countfree;
-       unlock_zone(zone);
-
-       assert(free_count >= 0);
-
-       return(free_count);
+       return zalloc_flags(zov, Z_NOWAIT);
 }
 
-/*
- *  Zone garbage collection subroutines
- */
+void *
+zalloc_flags(union zone_or_view zov, zalloc_flags_t flags)
+{
+       zone_t zone = zov.zov_view->zv_zone;
+       zone_stats_t zstats = zov.zov_view->zv_stats;
+       assert(!zone->percpu);
+       return zalloc_ext(zone, zstats, flags, 0);
+}
 
-boolean_t
-zone_page_collectable(
-       vm_offset_t     addr,
-       vm_size_t       size)
+void *
+zalloc_percpu(union zone_or_view zov, zalloc_flags_t flags)
 {
-       struct zone_page_table_entry    *zp;
-       zone_page_index_t i, j;
+       zone_t zone = zov.zov_view->zv_zone;
+       zone_stats_t zstats = zov.zov_view->zv_stats;
+       assert(zone->percpu);
+       return (void *)__zpcpu_mangle(zalloc_ext(zone, zstats, flags, 0));
+}
 
-#if    ZONE_ALIAS_ADDR
-       addr = zone_virtual_addr(addr);
-#endif
-#if MACH_ASSERT
-       if (!from_zone_map(addr, size))
-               panic("zone_page_collectable");
-#endif
+static void *
+_zalloc_permanent(zone_t zone, vm_size_t size, vm_offset_t mask)
+{
+       const zone_addr_kind_t kind = ZONE_ADDR_NATIVE;
+       struct zone_page_metadata *page_meta;
+       vm_offset_t offs, addr;
+       zone_pva_t pva;
 
-       i = (zone_page_index_t)atop_kernel(addr-zone_map_min_address);
-       j = (zone_page_index_t)atop_kernel((addr+size-1) - zone_map_min_address);
+       assert(ml_get_interrupts_enabled() ||
+           ml_is_quiescing() ||
+           debug_mode_active() ||
+           startup_phase < STARTUP_SUB_EARLY_BOOT);
 
-       for (; i <= j; i++) {
-               zp = zone_page_table_lookup(i);
-               if (zp->collect_count == zp->alloc_count)
-                       return (TRUE);
-       }
+       size = (size + mask) & ~mask;
+       assert(size <= PAGE_SIZE);
 
-       return (FALSE);
-}
+       lock_zone(zone);
+       assert(zone->z_self == zone);
 
-void
-zone_page_keep(
-       vm_offset_t     addr,
-       vm_size_t       size)
-{
-       struct zone_page_table_entry    *zp;
-       zone_page_index_t i, j;
+       for (;;) {
+               pva = zone->pages_intermediate;
+               while (!zone_pva_is_null(pva)) {
+                       page_meta = zone_pva_to_meta(pva, kind);
+                       if (page_meta->zm_freelist_offs + size <= PAGE_SIZE) {
+                               goto found;
+                       }
+                       pva = page_meta->zm_page_next;
+               }
 
-#if    ZONE_ALIAS_ADDR
-       addr = zone_virtual_addr(addr);
-#endif
-#if MACH_ASSERT
-       if (!from_zone_map(addr, size))
-               panic("zone_page_keep");
-#endif
+               zone_refill_synchronously_locked(zone, Z_WAITOK);
+       }
 
-       i = (zone_page_index_t)atop_kernel(addr-zone_map_min_address);
-       j = (zone_page_index_t)atop_kernel((addr+size-1) - zone_map_min_address);
+found:
+       offs = (page_meta->zm_freelist_offs + mask) & ~mask;
+       page_meta->zm_freelist_offs = offs + size;
+       page_meta->zm_alloc_count += size;
+       zone->countfree -= size;
+       if (__probable(zone->z_stats)) {
+               zpercpu_get(zone->z_stats)->zs_mem_allocated += size;
+       }
 
-       for (; i <= j; i++) {
-               zp = zone_page_table_lookup(i);
-               zp->collect_count = 0;
+       if (page_meta->zm_alloc_count >= PAGE_SIZE - sizeof(vm_offset_t)) {
+               zone_meta_requeue(zone, &zone->pages_all_used, page_meta, kind);
        }
-}
 
-void
-zone_page_collect(
-       vm_offset_t     addr,
-       vm_size_t       size)
-{
-       struct zone_page_table_entry    *zp;
-       zone_page_index_t i, j;
+       unlock_zone(zone);
 
-#if    ZONE_ALIAS_ADDR
-       addr = zone_virtual_addr(addr);
-#endif
-#if MACH_ASSERT
-       if (!from_zone_map(addr, size))
-               panic("zone_page_collect");
-#endif
+       addr = offs + zone_pva_to_addr(pva);
 
-       i = (zone_page_index_t)atop_kernel(addr-zone_map_min_address);
-       j = (zone_page_index_t)atop_kernel((addr+size-1) - zone_map_min_address);
+       DTRACE_VM2(zalloc, zone_t, zone, void*, addr);
+       return (void *)addr;
+}
 
-       for (; i <= j; i++) {
-               zp = zone_page_table_lookup(i);
-               ++zp->collect_count;
+static void *
+_zalloc_permanent_large(size_t size, vm_offset_t mask)
+{
+       kern_return_t kr;
+       vm_offset_t addr;
+
+       kr = kernel_memory_allocate(kernel_map, &addr, size, mask,
+           KMA_KOBJECT | KMA_PERMANENT | KMA_ZERO,
+           VM_KERN_MEMORY_KALLOC);
+       if (kr != 0) {
+               panic("zalloc_permanent: unable to allocate %zd bytes (%d)",
+                   size, kr);
        }
+       return (void *)addr;
 }
 
-void
-zone_page_init(
-       vm_offset_t     addr,
-       vm_size_t       size)
+void *
+zalloc_permanent(vm_size_t size, vm_offset_t mask)
 {
-       struct zone_page_table_entry    *zp;
-       zone_page_index_t i, j;
-
-#if    ZONE_ALIAS_ADDR
-       addr = zone_virtual_addr(addr);
-#endif
-#if MACH_ASSERT
-       if (!from_zone_map(addr, size))
-               panic("zone_page_init");
-#endif
-
-       i = (zone_page_index_t)atop_kernel(addr-zone_map_min_address);
-       j = (zone_page_index_t)atop_kernel((addr+size-1) - zone_map_min_address);
-
-       for (; i <= j; i++) {
-               /* make sure entry exists before marking unused */
-               zone_page_table_expand(i);
-
-               zp = zone_page_table_lookup(i);
-               assert(zp);
-               zp->alloc_count = ZONE_PAGE_UNUSED;
-               zp->collect_count = 0;
+       if (size <= PAGE_SIZE) {
+               zone_t zone = &zone_array[ZONE_ID_PERMANENT];
+               return _zalloc_permanent(zone, size, mask);
        }
+       return _zalloc_permanent_large(size, mask);
 }
 
-void
-zone_page_alloc(
-       vm_offset_t     addr,
-       vm_size_t       size)
+void *
+zalloc_percpu_permanent(vm_size_t size, vm_offset_t mask)
 {
-       struct zone_page_table_entry    *zp;
-       zone_page_index_t i, j;
-
-#if    ZONE_ALIAS_ADDR
-       addr = zone_virtual_addr(addr);
-#endif
-#if MACH_ASSERT
-       if (!from_zone_map(addr, size))
-               panic("zone_page_alloc");
-#endif
-
-       i = (zone_page_index_t)atop_kernel(addr-zone_map_min_address);
-       j = (zone_page_index_t)atop_kernel((addr+size-1) - zone_map_min_address);
-
-       for (; i <= j; i++) {
-               zp = zone_page_table_lookup(i);
-               assert(zp);
-
-               /*
-                * Set alloc_count to ZONE_PAGE_USED if
-                * it was previously set to ZONE_PAGE_UNUSED.
-                */
-               if (zp->alloc_count == ZONE_PAGE_UNUSED)
-                       zp->alloc_count = ZONE_PAGE_USED;
-
-               ++zp->alloc_count;
-       }
+       zone_t zone = &zone_array[ZONE_ID_PERCPU_PERMANENT];
+       return (void *)__zpcpu_mangle(_zalloc_permanent(zone, size, mask));
 }
 
 void
-zone_page_free_element(
-       zone_page_index_t       *free_page_head,
-       zone_page_index_t       *free_page_tail,
-       vm_offset_t     addr,
-       vm_size_t       size)
+zalloc_async(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
 {
-       struct zone_page_table_entry    *zp;
-       zone_page_index_t i, j;
-
-#if    ZONE_ALIAS_ADDR
-       addr = zone_virtual_addr(addr);
-#endif
-#if MACH_ASSERT
-       if (!from_zone_map(addr, size))
-               panic("zone_page_free_element");
-#endif
-
-       /* Clear out the old next and backup pointers */
-       vm_offset_t *primary  = (vm_offset_t *) addr;
-       vm_offset_t *backup   = get_backup_ptr(size, primary);
-
-       *primary = ZP_POISON;
-       *backup  = ZP_POISON;
-
-       i = (zone_page_index_t)atop_kernel(addr-zone_map_min_address);
-       j = (zone_page_index_t)atop_kernel((addr+size-1) - zone_map_min_address);
-
-       for (; i <= j; i++) {
-               zp = zone_page_table_lookup(i);
-
-               if (zp->collect_count > 0)
-                       --zp->collect_count;
-               if (--zp->alloc_count == 0) {
-                       vm_address_t        free_page_address;
-                       vm_address_t        prev_free_page_address;
-
-                       zp->alloc_count  = ZONE_PAGE_UNUSED;
-                       zp->collect_count = 0;
-
+       zone_index_foreach(i) {
+               zone_t z = &zone_array[i];
 
-                       /*
-                        * This element was the last one on this page, re-use the page's
-                        * storage for a page freelist
-                        */
-                       free_page_address = zone_map_min_address + PAGE_SIZE * ((vm_size_t)i);
-                       *(zone_page_index_t *)free_page_address = ZONE_PAGE_INDEX_INVALID;
+               if (z->no_callout) {
+                       /* async_pending will never be set */
+                       continue;
+               }
 
-                       if (*free_page_head == ZONE_PAGE_INDEX_INVALID) {
-                               *free_page_head = i;
-                               *free_page_tail = i;
-                       } else {
-                               prev_free_page_address = zone_map_min_address + PAGE_SIZE * ((vm_size_t)(*free_page_tail));
-                               *(zone_page_index_t *)prev_free_page_address = i;
-                               *free_page_tail = i;
-                       }
+               lock_zone(z);
+               if (z->z_self && z->async_pending) {
+                       z->async_pending = false;
+                       zone_refill_synchronously_locked(z, Z_WAITOK);
                }
+               unlock_zone(z);
        }
 }
 
-
-#define ZONEGC_SMALL_ELEMENT_SIZE      4096
-
-struct {
-       uint64_t        zgc_invoked;
-       uint64_t        zgc_bailed;
-       uint32_t        pgs_freed;
-
-       uint32_t        elems_collected,
-                               elems_freed,
-                               elems_kept;
-} zgc_stats;
-
-/*     Zone garbage collection
- *
- *     zone_gc will walk through all the free elements in all the
- *     zones that are marked collectable looking for reclaimable
- *     pages.  zone_gc is called by consider_zone_gc when the system
- *     begins to run out of memory.
+/*
+ * Adds the element to the head of the zone's free list
+ * Keeps a backup next-pointer at the end of the element
  */
 void
-zone_gc(boolean_t all_zones)
+zfree_direct_locked(zone_t zone, vm_offset_t element, bool poison)
 {
-       unsigned int    max_zones;
-       zone_t                  z;
-       unsigned int    i;
-       uint32_t        old_pgs_freed;
-       zone_page_index_t zone_free_page_head;
-       zone_page_index_t zone_free_page_tail;
-       thread_t        mythread = current_thread();
+       struct zone_page_metadata *page_meta;
+       vm_offset_t page, old_head;
+       zone_addr_kind_t kind;
+       vm_size_t elem_size = zone_elem_size(zone);
 
-       lck_mtx_lock(&zone_gc_lock);
+       vm_offset_t *primary  = (vm_offset_t *) element;
+       vm_offset_t *backup   = get_backup_ptr(elem_size, primary);
 
-       zgc_stats.zgc_invoked++;
-       old_pgs_freed = zgc_stats.pgs_freed;
+       page_meta = zone_allocated_element_resolve(zone, element, &page, &kind);
+       old_head = zone_page_meta_get_freelist(zone, page_meta, page);
 
-       simple_lock(&all_zones_lock);
-       max_zones = num_zones;
-       z = first_zone;
-       simple_unlock(&all_zones_lock);
+       if (__improbable(old_head == element)) {
+               panic("zfree: double free of %p to zone %s%s\n",
+                   (void *) element, zone_heap_name(zone), zone->z_name);
+       }
 
-       if (zalloc_debug & ZALLOC_DEBUG_ZONEGC)
-               kprintf("zone_gc(all_zones=%s) starting...\n", all_zones ? "TRUE" : "FALSE");
+#if ZALLOC_ENABLE_POISONING
+       if (poison && elem_size < ZONE_MIN_ELEM_SIZE) {
+               assert(zone->percpu);
+               poison = false;
+       }
+#else
+       poison = false;
+#endif
 
        /*
-        * it's ok to allow eager kernel preemption while
-        * while holding a zone lock since it's taken
-        * as a spin lock (which prevents preemption)
+        * Always write a redundant next pointer
+        * So that it is more difficult to forge, xor it with a random cookie
+        * A poisoned element is indicated by using zp_poisoned_cookie
+        * instead of zp_nopoison_cookie
         */
-       thread_set_eager_preempt(mythread);
-
-#if MACH_ASSERT
-       for (i = 0; i < zone_pages; i++) {
-               struct zone_page_table_entry    *zp;
-       
-               zp = zone_page_table_lookup(i);
-               assert(!zp || (zp->collect_count == 0));
-       }
-#endif /* MACH_ASSERT */
-
-       for (i = 0; i < max_zones; i++, z = z->next_zone) {
-               unsigned int                    n, m;
-               vm_size_t                       elt_size, size_freed;
-               struct zone_free_element        *elt, *base_elt, *base_prev, *prev, *scan, *keep, *tail;
-               int                             kmem_frees = 0, total_freed_pages = 0;
-               struct zone_page_metadata               *page_meta;
-               queue_head_t    page_meta_head;
-
-               assert(z != ZONE_NULL);
-
-               if (!z->collectable)
-                       continue;
 
-               if (all_zones == FALSE && z->elem_size < ZONEGC_SMALL_ELEMENT_SIZE && !z->use_page_list)
-                       continue;
+       *backup = old_head ^ (poison ? zp_poisoned_cookie : zp_nopoison_cookie);
 
-               lock_zone(z);
+       /*
+        * Insert this element at the head of the free list. We also xor the
+        * primary pointer with the zp_nopoison_cookie to make sure a free
+        * element does not provide the location of the next free element directly.
+        */
+       *primary = old_head ^ zp_nopoison_cookie;
+
+#if VM_MAX_TAG_ZONES
+       if (__improbable(zone->tags)) {
+               vm_tag_t tag = (ZTAG(zone, element)[0] >> 1);
+               // set the tag with b0 clear so the block remains inuse
+               ZTAG(zone, element)[0] = 0xFFFE;
+               vm_tag_update_zone_size(tag, zone->tag_zone_index,
+                   -((int64_t)elem_size), 0);
+       }
+#endif /* VM_MAX_TAG_ZONES */
 
-               elt_size = z->elem_size;
+       zone_page_meta_set_freelist(page_meta, page, element);
+       if (os_sub_overflow(page_meta->zm_alloc_count, 1,
+           &page_meta->zm_alloc_count)) {
+               zone_page_meta_accounting_panic(zone, page_meta,
+                   "alloc_count wrap-around");
+       }
+       zone->countfree++;
 
-               /*
-                * Do a quick feasibility check before we scan the zone: 
-                * skip unless there is likelihood of getting pages back
-                * (i.e we need a whole allocation block's worth of free
-                * elements before we can garbage collect) and
-                * the zone has more than 10 percent of it's elements free
-                * or the element size is a multiple of the PAGE_SIZE 
-                */
-               if ((elt_size & PAGE_MASK) && 
-                   !z->use_page_list &&
-                    (((z->cur_size - z->count * elt_size) <= (2 * z->alloc_size)) ||
-                     ((z->cur_size - z->count * elt_size) <= (z->cur_size / 10)))) {
-                       unlock_zone(z);         
-                       continue;
+       if (kind == ZONE_ADDR_FOREIGN) {
+               if (old_head == 0) {
+                       /* first foreign element freed on page, move from all_used_foreign */
+                       zone_meta_requeue(zone, &zone->pages_any_free_foreign, page_meta, kind);
                }
+       } else if (page_meta->zm_alloc_count == 0) {
+               /* whether the page was on the intermediate or all_used, queue, move it to free */
+               zone_meta_requeue(zone, &zone->pages_all_free, page_meta, kind);
+               zone->allfree_page_count += page_meta->zm_page_count;
+       } else if (old_head == 0) {
+               /* first free element on page, move from all_used */
+               zone_meta_requeue(zone, &zone->pages_intermediate, page_meta, kind);
+       }
 
-               z->doing_gc = TRUE;
-
-               /*
-                * Snatch all of the free elements away from the zone.
-                */
-
-               if (z->use_page_list) {
-                       queue_new_head(&z->pages.all_free, &page_meta_head, struct zone_page_metadata *, pages);
-                       queue_init(&z->pages.all_free);
-               } else {
-                       scan = (void *)z->free_elements;
-                       z->free_elements = 0;
+#if KASAN_ZALLOC
+       if (zone->percpu) {
+               zpercpu_foreach_cpu(i) {
+                       kasan_poison_range(element + ptoa(i), elem_size,
+                           ASAN_HEAP_FREED);
                }
-
-               unlock_zone(z);
-
-               if (z->use_page_list) {
-                       /*
-                        * For zones that maintain page lists (which in turn
-                        * track free elements on those pages), zone_gc()
-                        * is incredibly easy, and we bypass all the logic
-                        * for scanning elements and mapping them to
-                        * collectable pages
-                        */
-
-                       size_freed = 0;
-
-                       queue_iterate(&page_meta_head, page_meta, struct zone_page_metadata *, pages) {
-                               assert(from_zone_map((vm_address_t)page_meta, sizeof(*page_meta))); /* foreign elements should be in any_free_foreign */
-
-                               zgc_stats.elems_freed += page_meta->free_count;
-                               size_freed += elt_size * page_meta->free_count;
-                               zgc_stats.elems_collected += page_meta->free_count;
-                       }
-                       
-                       lock_zone(z);
-
-                       if (size_freed > 0) {
-                               z->cur_size -= size_freed;
-                               z->countfree -= size_freed/elt_size;
-                       }
-
-                       z->doing_gc = FALSE;
-                       if (z->waiting) {
-                               z->waiting = FALSE;
-                               zone_wakeup(z);
-                       }
-
-                       unlock_zone(z);
-
-                       if (queue_empty(&page_meta_head))
-                               continue;
-
-                       thread_clear_eager_preempt(mythread);
-
-                       while ((page_meta = (struct zone_page_metadata *)dequeue_head(&page_meta_head)) != NULL) {
-                               vm_address_t            free_page_address;
-
-                               free_page_address = trunc_page((vm_address_t)page_meta);
-#if    ZONE_ALIAS_ADDR
-                               free_page_address = zone_virtual_addr(free_page_address);
+       } else {
+               kasan_poison_range(element, elem_size, ASAN_HEAP_FREED);
+       }
 #endif
-                               kmem_free(zone_map, free_page_address, PAGE_SIZE);
-                               ZONE_PAGE_COUNT_DECR(z, 1);
-                               total_freed_pages++;
-                               zgc_stats.pgs_freed += 1;
-                               
-                               if (++kmem_frees == 32) {
-                                       thread_yield_internal(1);
-                                       kmem_frees = 0;
-                               }
-                       }
-
-                       if (zalloc_debug & ZALLOC_DEBUG_ZONEGC)
-                               kprintf("zone_gc() of zone %s freed %lu elements, %d pages\n", z->zone_name, (unsigned long)size_freed/elt_size, total_freed_pages);
-
-                       thread_set_eager_preempt(mythread);
-                       continue; /* go to next zone */
-               }
-
-               /*
-                * Pass 1:
-                *
-                * Determine which elements we can attempt to collect
-                * and count them up in the page table.  Foreign elements
-                * are returned to the zone.
-                */
-
-               prev = (void *)&scan;
-               elt = scan;
-               n = 0; tail = keep = NULL;
-
-               zone_free_page_head = ZONE_PAGE_INDEX_INVALID;
-               zone_free_page_tail = ZONE_PAGE_INDEX_INVALID;
-
-
-               while (elt != NULL) {
-                       if (from_zone_map(elt, elt_size)) {
-                               zone_page_collect((vm_offset_t)elt, elt_size);
-
-                               prev = elt;
-                               elt = elt->next;
-
-                               ++zgc_stats.elems_collected;
-                       }
-                       else {
-                               if (keep == NULL)
-                                       keep = tail = elt;
-                               else {
-                                       append_zone_element(z, tail, elt);
-                                       tail = elt;
-                               }
-
-                               append_zone_element(z, prev, elt->next);
-                               elt = elt->next;
-                               append_zone_element(z, tail, NULL);
-                       }
-
-                       /*
-                        * Dribble back the elements we are keeping.
-                        * If there are none, give some elements that we haven't looked at yet
-                        * back to the freelist so that others waiting on the zone don't get stuck
-                        * for too long.  This might prevent us from recovering some memory,
-                        * but allows us to avoid having to allocate new memory to serve requests
-                        * while zone_gc has all the free memory tied up.
-                        * <rdar://problem/3893406>
-                        */
-
-                       if (++n >= 50) {
-                               if (z->waiting == TRUE) {
-                                       /* z->waiting checked without lock held, rechecked below after locking */
-                                       lock_zone(z);
-
-                                       if (keep != NULL) {
-                                               add_list_to_zone(z, keep, tail);
-                                               tail = keep = NULL;
-                                       } else {
-                                               m =0;
-                                               base_elt = elt;
-                                               base_prev = prev;
-                                               while ((elt != NULL) && (++m < 50)) { 
-                                                       prev = elt;
-                                                       elt = elt->next;
-                                               }
-                                               if (m !=0 ) {
-                                                       /* Extract the elements from the list and
-                                                        * give them back */
-                                                       append_zone_element(z, prev, NULL);
-                                                       add_list_to_zone(z, base_elt, prev);
-                                                       append_zone_element(z, base_prev, elt);
-                                                       prev = base_prev;
-                                               }
-                                       }
-
-                                       if (z->waiting) {
-                                               z->waiting = FALSE;
-                                               zone_wakeup(z);
-                                       }
-
-                                       unlock_zone(z);
-                               }
-                               n =0;
-                       }
-               }
-
-               /*
-                * Return any remaining elements.
-                */
-
-               if (keep != NULL) {
-                       lock_zone(z);
-
-                       add_list_to_zone(z, keep, tail);
+}
 
-                       if (z->waiting) {
-                               z->waiting = FALSE;
-                               zone_wakeup(z);
-                       }
+/*
+ *     The function is noinline when zlog can be used so that the backtracing can
+ *     reliably skip the zfree_ext() and zfree_log_trace()
+ *     boring frames.
+ */
+#if ZONE_ENABLE_LOGGING
+__attribute__((noinline))
+#endif
+void
+zfree_ext(zone_t zone, zone_stats_t zstats, void *addr)
+{
+       vm_offset_t     elem = (vm_offset_t)addr;
+       vm_size_t       elem_size = zone_elem_size(zone);
+       bool            poison = false;
 
-                       unlock_zone(z);
-               }
+       DTRACE_VM2(zfree, zone_t, zone, void*, addr);
+       TRACE_MACHLEAKS(ZFREE_CODE, ZFREE_CODE_2, elem_size, elem);
 
-               /*
-                * Pass 2:
-                *
-                * Determine which pages we can reclaim and
-                * free those elements.
-                */
+#if KASAN_ZALLOC
+       if (kasan_quarantine_freed_element(&zone, &addr)) {
+               return;
+       }
+       /*
+        * kasan_quarantine_freed_element() might return a different
+        * {zone, addr} than the one being freed for kalloc heaps.
+        *
+        * Make sure we reload everything.
+        */
+       elem = (vm_offset_t)addr;
+       elem_size = zone_elem_size(zone);
+#endif
 
-               size_freed = 0;
-               elt = scan;
-               n = 0; tail = keep = NULL;
+#if CONFIG_ZLEAKS
+       /*
+        * Zone leak detection: un-track the allocation
+        */
+       if (__improbable(zone->zleak_on)) {
+               zleak_free(elem, elem_size);
+       }
+#endif /* CONFIG_ZLEAKS */
 
-               while (elt != NULL) {
-                       if (zone_page_collectable((vm_offset_t)elt, elt_size)) {
-                               struct zone_free_element *next_elt = elt->next;
+#if CONFIG_ZCACHE
+       /*
+        * Note: if zone caching is on, gzalloc and tags aren't used
+        *       so we can always check this first
+        */
+       if (zone_caching_enabled(zone)) {
+               return zcache_free_to_cpu_cache(zone, zstats, (vm_offset_t)addr);
+       }
+#endif /* CONFIG_ZCACHE */
 
-                               size_freed += elt_size;
+#if CONFIG_GZALLOC
+       if (__improbable(zone->gzalloc_tracked)) {
+               return gzalloc_free(zone, zstats, addr);
+       }
+#endif /* CONFIG_GZALLOC */
 
-                               /*
-                                * If this is the last allocation on the page(s),
-                                * we may use their storage to maintain the linked
-                                * list of free-able pages. So store elt->next because
-                                * "elt" may be scribbled over.
-                                */
-                               zone_page_free_element(&zone_free_page_head, &zone_free_page_tail, (vm_offset_t)elt, elt_size);
+#if ZONE_ENABLE_LOGGING
+       if (__improbable(DO_LOGGING(zone))) {
+               zfree_log_trace(zone, elem);
+       }
+#endif /* ZONE_ENABLE_LOGGING */
 
-                               elt = next_elt;
+       if (zone->zfree_clear_mem) {
+               poison = zfree_clear(zone, elem, elem_size);
+       }
 
-                               ++zgc_stats.elems_freed;
-                       }
-                       else {
-                               zone_page_keep((vm_offset_t)elt, elt_size);
-
-                               if (keep == NULL)
-                                       keep = tail = elt;
-                               else {
-                                       append_zone_element(z, tail, elt);
-                                       tail = elt;
-                               }
+       lock_zone(zone);
+       assert(zone->z_self == zone);
 
-                               elt = elt->next;
-                               append_zone_element(z, tail, NULL);
+       if (!poison) {
+               poison = zfree_poison_element(zone, &zone->zp_count, elem);
+       }
 
-                               ++zgc_stats.elems_kept;
-                       }
+       if (__probable(zstats != NULL)) {
+               /*
+                * The few vm zones used before zone_init() runs do not have
+                * per-cpu stats yet
+                */
+               zpercpu_get(zstats)->zs_mem_freed += elem_size;
+       }
 
-                       /*
-                        * Dribble back the elements we are keeping,
-                        * and update the zone size info.
-                        */
+       zfree_direct_locked(zone, elem, poison);
 
-                       if (++n >= 50) {
-                               lock_zone(z);
+       unlock_zone(zone);
+}
 
-                               z->cur_size -= size_freed;
-                               z->countfree -= size_freed/elt_size;
-                               size_freed = 0;
+void
+(zfree)(union zone_or_view zov, void *addr)
+{
+       zone_t zone = zov.zov_view->zv_zone;
+       zone_stats_t zstats = zov.zov_view->zv_stats;
+       assert(!zone->percpu);
+       zfree_ext(zone, zstats, addr);
+}
 
-                               if (keep != NULL) {
-                                       add_list_to_zone(z, keep, tail);
-                               }
+void
+zfree_percpu(union zone_or_view zov, void *addr)
+{
+       zone_t zone = zov.zov_view->zv_zone;
+       zone_stats_t zstats = zov.zov_view->zv_stats;
+       assert(zone->percpu);
+       zfree_ext(zone, zstats, (void *)__zpcpu_demangle(addr));
+}
 
-                               if (z->waiting) {
-                                       z->waiting = FALSE;
-                                       zone_wakeup(z);
-                               }
+#pragma mark vm integration, MIG routines
 
+/*
+ * Drops (i.e. frees) the elements in the all free pages queue of a zone.
+ * Called by zone_gc() on each zone and when a zone is zdestroy()ed.
+ */
+static void
+zone_drop_free_elements(zone_t z)
+{
+       const zone_addr_kind_t    kind = ZONE_ADDR_NATIVE;
+       unsigned int              total_freed_pages = 0;
+       struct zone_page_metadata *page_meta, *seq_meta;
+       vm_address_t              page_addr;
+       vm_size_t                 size_to_free;
+       vm_size_t                 free_count;
+       uint32_t                  page_count;
+
+       current_thread()->options |= TH_OPT_ZONE_PRIV;
+       lock_zone(z);
+
+       while (!zone_pva_is_null(z->pages_all_free)) {
+               /*
+                * If any replenishment threads are running, defer to them,
+                * so that we don't deplete reserved zones.
+                *
+                * The timing of the check isn't super important, as there are
+                * enough reserves to allow freeing an extra page_meta.
+                *
+                * Hence, we can check without grabbing the lock every time
+                * through the loop.  We do need the lock however to avoid
+                * missing a wakeup when we decide to block.
+                */
+               if (zone_replenish_active > 0) {
+                       lck_spin_lock(&zone_replenish_lock);
+                       if (zone_replenish_active > 0) {
+                               assert_wait(&zone_replenish_active, THREAD_UNINT);
+                               lck_spin_unlock(&zone_replenish_lock);
                                unlock_zone(z);
-
-                               n = 0; tail = keep = NULL;
+                               thread_block(THREAD_CONTINUE_NULL);
+                               lock_zone(z);
+                               continue;
                        }
+                       lck_spin_unlock(&zone_replenish_lock);
                }
 
+               page_meta = zone_pva_to_meta(z->pages_all_free, kind);
+               page_count = page_meta->zm_page_count;
+               free_count = zone_elem_count(z, ptoa(page_count), kind);
+
                /*
-                * Return any remaining elements, and update
-                * the zone size info.
+                * Don't drain zones with async refill to below the refill
+                * threshold, as they need some reserve to function properly.
                 */
+               if (!z->destroyed && z->prio_refill_count &&
+                   (vm_size_t)(z->countfree - free_count) < z->prio_refill_count) {
+                       break;
+               }
 
-               lock_zone(z);
-
-               if (size_freed > 0 || keep != NULL) {
+               zone_meta_queue_pop(z, &z->pages_all_free, kind, &page_addr);
 
-                       z->cur_size -= size_freed;
-                       z->countfree -= size_freed/elt_size;
+               if (os_sub_overflow(z->countfree, free_count, &z->countfree)) {
+                       zone_accounting_panic(z, "countfree wrap-around");
+               }
+               if (os_sub_overflow(z->countavail, free_count, &z->countavail)) {
+                       zone_accounting_panic(z, "countavail wrap-around");
+               }
+               if (os_sub_overflow(z->allfree_page_count, page_count,
+                   &z->allfree_page_count)) {
+                       zone_accounting_panic(z, "allfree_page_count wrap-around");
+               }
+               if (os_sub_overflow(z->page_count, page_count, &z->page_count)) {
+                       zone_accounting_panic(z, "page_count wrap-around");
+               }
 
-                       if (keep != NULL) {
-                               add_list_to_zone(z, keep, tail);
-                       }
+               os_atomic_sub(&zones_phys_page_count, page_count, relaxed);
+               os_atomic_sub(&zones_phys_page_mapped_count, page_count, relaxed);
 
-               }
+               bzero(page_meta, sizeof(*page_meta) * page_count);
+               seq_meta = page_meta;
+               page_meta = NULL; /* page_meta fields are zeroed, prevent reuse */
 
-               z->doing_gc = FALSE;
-               if (z->waiting) {
-                       z->waiting = FALSE;
-                       zone_wakeup(z);
-               }
                unlock_zone(z);
 
-               if (zone_free_page_head == ZONE_PAGE_INDEX_INVALID)
-                       continue;
+               /* Free the pages for metadata and account for them */
+               total_freed_pages += page_count;
+               size_to_free = ptoa(page_count);
+#if KASAN_ZALLOC
+               kasan_poison_range(page_addr, size_to_free, ASAN_VALID);
+#endif
+#if VM_MAX_TAG_ZONES
+               if (z->tags) {
+                       ztMemoryRemove(z, page_addr, size_to_free);
+               }
+#endif /* VM_MAX_TAG_ZONES */
 
-               /*
-                * we don't want to allow eager kernel preemption while holding the
-                * various locks taken in the kmem_free path of execution
-                */
-               thread_clear_eager_preempt(mythread);
+               if (z->va_sequester && z->alloc_pages == page_count) {
+                       kernel_memory_depopulate(submap_for_zone(z), page_addr,
+                           size_to_free, KMA_KOBJECT, VM_KERN_MEMORY_ZONE);
+               } else {
+                       kmem_free(submap_for_zone(z), page_addr, size_to_free);
+                       seq_meta = NULL;
+               }
+               thread_yield_to_preemption();
 
+               lock_zone(z);
 
-               /*
-                * This loop counts the number of pages that should be freed by the
-                * next loop that tries to coalesce the kmem_frees()
-                */
-               uint32_t pages_to_free_count = 0;
-               vm_address_t            fpa;
-               zone_page_index_t index;
-               for (index = zone_free_page_head; index != ZONE_PAGE_INDEX_INVALID;) {
-                       pages_to_free_count++;
-                       fpa = zone_map_min_address + PAGE_SIZE * ((vm_size_t)index);
-                       index = *(zone_page_index_t *)fpa;
+               if (seq_meta) {
+                       zone_meta_queue_push(z, &z->pages_sequester, seq_meta, kind);
+                       z->sequester_page_count += page_count;
                }
+       }
+       if (z->destroyed) {
+               assert(zone_pva_is_null(z->pages_all_free));
+               assert(z->allfree_page_count == 0);
+       }
+       unlock_zone(z);
+       current_thread()->options &= ~TH_OPT_ZONE_PRIV;
+
+#if DEBUG || DEVELOPMENT
+       if (zalloc_debug & ZALLOC_DEBUG_ZONEGC) {
+               kprintf("zone_gc() of zone %s%s freed %lu elements, %d pages\n",
+                   zone_heap_name(z), z->z_name,
+                   (unsigned long)(ptoa(total_freed_pages) / z->pcpu_elem_size),
+                   total_freed_pages);
+       }
+#endif /* DEBUG || DEVELOPMENT */
+}
 
+/*     Zone garbage collection
+ *
+ *     zone_gc will walk through all the free elements in all the
+ *     zones that are marked collectable looking for reclaimable
+ *     pages.  zone_gc is called by consider_zone_gc when the system
+ *     begins to run out of memory.
+ *
+ *     We should ensure that zone_gc never blocks.
+ */
+void
+zone_gc(boolean_t consider_jetsams)
+{
+       if (consider_jetsams) {
+               kill_process_in_largest_zone();
                /*
-                * Reclaim the pages we are freeing.
+                * If we do end up jetsamming something, we need to do a zone_gc so that
+                * we can reclaim free zone elements and update the zone map size.
+                * Fall through.
                 */
-               while (zone_free_page_head != ZONE_PAGE_INDEX_INVALID) {
-                       zone_page_index_t       zind = zone_free_page_head;
-                       vm_address_t            free_page_address;
-                       int                     page_count;
-
-                       /*
-                        * Use the first word of the page about to be freed to find the next free page
-                        */
-                       free_page_address = zone_map_min_address + PAGE_SIZE * ((vm_size_t)zind);
-                       zone_free_page_head = *(zone_page_index_t *)free_page_address;
-
-                       page_count = 1;
-                       total_freed_pages++;
+       }
 
-                       while (zone_free_page_head != ZONE_PAGE_INDEX_INVALID) {
-                               zone_page_index_t       next_zind = zone_free_page_head;
-                               vm_address_t            next_free_page_address;
+       lck_mtx_lock(&zone_gc_lock);
 
-                               next_free_page_address = zone_map_min_address + PAGE_SIZE * ((vm_size_t)next_zind);
+#if DEBUG || DEVELOPMENT
+       if (zalloc_debug & ZALLOC_DEBUG_ZONEGC) {
+               kprintf("zone_gc() starting...\n");
+       }
+#endif /* DEBUG || DEVELOPMENT */
 
-                               if (next_free_page_address == (free_page_address - PAGE_SIZE)) {
-                                       free_page_address = next_free_page_address;
-                               } else if (next_free_page_address != (free_page_address + (PAGE_SIZE * page_count)))
-                                       break;
+       zone_index_foreach(i) {
+               zone_t z = &zone_array[i];
 
-                               zone_free_page_head = *(zone_page_index_t *)next_free_page_address;
-                               page_count++;
-                               total_freed_pages++;
-                       }
-                       kmem_free(zone_map, free_page_address, page_count * PAGE_SIZE);
-                       ZONE_PAGE_COUNT_DECR(z, page_count);
-                       zgc_stats.pgs_freed += page_count;
-                       pages_to_free_count -= page_count;
-
-                       if (++kmem_frees == 32) {
-                               thread_yield_internal(1);
-                               kmem_frees = 0;
-                       }
+               if (!z->collectable) {
+                       continue;
+               }
+#if CONFIG_ZCACHE
+               if (zone_caching_enabled(z)) {
+                       zcache_drain_depot(z);
+               }
+#endif /* CONFIG_ZCACHE */
+               if (zone_pva_is_null(z->pages_all_free)) {
+                       continue;
                }
 
-               /* Check that we actually free the exact number of pages we were supposed to */
-               assert(pages_to_free_count == 0);
-
-               if (zalloc_debug & ZALLOC_DEBUG_ZONEGC)
-                       kprintf("zone_gc() of zone %s freed %lu elements, %d pages\n", z->zone_name, (unsigned long)size_freed/elt_size, total_freed_pages);
-
-               thread_set_eager_preempt(mythread);
+               zone_drop_free_elements(z);
        }
 
-       if (old_pgs_freed == zgc_stats.pgs_freed)
-               zgc_stats.zgc_bailed++;
-
-       thread_clear_eager_preempt(mythread);
-
        lck_mtx_unlock(&zone_gc_lock);
-
 }
 
-extern vm_offset_t kmapoff_kaddr;
-extern unsigned int kmapoff_pgcnt;
-
 /*
  *     consider_zone_gc:
  *
@@ -3832,677 +5567,942 @@ extern unsigned int kmapoff_pgcnt;
  */
 
 void
-consider_zone_gc(boolean_t force)
+consider_zone_gc(boolean_t consider_jetsams)
+{
+       /*
+        * One-time reclaim of kernel_map resources we allocated in
+        * early boot.
+        *
+        * Use atomic exchange in case multiple threads race into here.
+        */
+       vm_offset_t deallocate_kaddr;
+       if (kmapoff_kaddr != 0 &&
+           (deallocate_kaddr = os_atomic_xchg(&kmapoff_kaddr, 0, relaxed)) != 0) {
+               vm_deallocate(kernel_map, deallocate_kaddr, ptoa_64(kmapoff_pgcnt));
+       }
+
+       zone_gc(consider_jetsams);
+}
+
+/*
+ * Creates a vm_map_copy_t to return to the caller of mach_* MIG calls
+ * requesting zone information.
+ * Frees unused pages towards the end of the region, and zero'es out unused
+ * space on the last page.
+ */
+static vm_map_copy_t
+create_vm_map_copy(
+       vm_offset_t             start_addr,
+       vm_size_t               total_size,
+       vm_size_t               used_size)
+{
+       kern_return_t   kr;
+       vm_offset_t             end_addr;
+       vm_size_t               free_size;
+       vm_map_copy_t   copy;
+
+       if (used_size != total_size) {
+               end_addr = start_addr + used_size;
+               free_size = total_size - (round_page(end_addr) - start_addr);
+
+               if (free_size >= PAGE_SIZE) {
+                       kmem_free(ipc_kernel_map,
+                           round_page(end_addr), free_size);
+               }
+               bzero((char *) end_addr, round_page(end_addr) - end_addr);
+       }
+
+       kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)start_addr,
+           (vm_map_size_t)used_size, TRUE, &copy);
+       assert(kr == KERN_SUCCESS);
+
+       return copy;
+}
+
+static boolean_t
+get_zone_info(
+       zone_t                   z,
+       mach_zone_name_t        *zn,
+       mach_zone_info_t        *zi)
 {
-       boolean_t all_zones = FALSE;
+       struct zone zcopy;
+
+       assert(z != ZONE_NULL);
+       lock_zone(z);
+       if (!z->z_self) {
+               unlock_zone(z);
+               return FALSE;
+       }
+       zcopy = *z;
+       unlock_zone(z);
 
-       if (kmapoff_kaddr != 0) {
+       if (zn != NULL) {
                /*
-                * One-time reclaim of kernel_map resources we allocated in
-                * early boot.
+                * Append kalloc heap name to zone name (if zone is used by kalloc)
                 */
-               (void) vm_deallocate(kernel_map,
-                   kmapoff_kaddr, kmapoff_pgcnt * PAGE_SIZE_64);
-               kmapoff_kaddr = 0;
+               char temp_zone_name[MAX_ZONE_NAME] = "";
+               snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
+                   zone_heap_name(z), z->z_name);
+
+               /* assuming here the name data is static */
+               (void) __nosan_strlcpy(zn->mzn_name, temp_zone_name,
+                   strlen(temp_zone_name) + 1);
        }
 
-       if (zone_gc_allowed &&
-           (zone_gc_allowed_by_time_throttle ||
-            zone_gc_forced ||
-            force)) {
-               if (zone_gc_allowed_by_time_throttle == TRUE) {
-                       zone_gc_allowed_by_time_throttle = FALSE;
-                       all_zones = TRUE;
+       if (zi != NULL) {
+               *zi = (mach_zone_info_t) {
+                       .mzi_count = zone_count_allocated(&zcopy),
+                       .mzi_cur_size = ptoa_64(zcopy.page_count),
+                       // max_size for zprint is now high-watermark of pages used
+                       .mzi_max_size = ptoa_64(zcopy.page_count_hwm),
+                       .mzi_elem_size = zcopy.pcpu_elem_size,
+                       .mzi_alloc_size = ptoa_64(zcopy.alloc_pages),
+                       .mzi_exhaustible = (uint64_t)zcopy.exhaustible,
+               };
+               zpercpu_foreach(zs, zcopy.z_stats) {
+                       zi->mzi_sum_size += zs->zs_mem_allocated;
+               }
+               if (zcopy.collectable) {
+                       SET_MZI_COLLECTABLE_BYTES(zi->mzi_collectable,
+                           ptoa_64(zcopy.allfree_page_count));
+                       SET_MZI_COLLECTABLE_FLAG(zi->mzi_collectable, TRUE);
                }
-               zone_gc_forced = FALSE;
-
-               zone_gc(all_zones);
        }
+
+       return TRUE;
 }
 
-/*
- *     By default, don't attempt zone GC more frequently
- *     than once / 1 minutes.
- */
-void
-compute_zone_gc_throttle(void *arg __unused)
+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)
 {
-       zone_gc_allowed_by_time_throttle = TRUE;
+       return KERN_FAILURE;
 }
 
+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)
+{
+       return mach_memory_info(host, namesp, namesCntp, infop, infoCntp, NULL, NULL);
+}
 
-#if CONFIG_TASK_ZONE_INFO
 
 kern_return_t
-task_zone_info(
-       task_t                  task,
-       mach_zone_name_array_t  *namesp,
+mach_memory_info(
+       host_priv_t             host,
+       mach_zone_name_array_t  *namesp,
        mach_msg_type_number_t  *namesCntp,
-       task_zone_info_array_t  *infop,
-       mach_msg_type_number_t  *infoCntp)
+       mach_zone_info_array_t  *infop,
+       mach_msg_type_number_t  *infoCntp,
+       mach_memory_info_array_t *memoryInfop,
+       mach_msg_type_number_t   *memoryInfoCntp)
 {
-       mach_zone_name_t        *names;
-       vm_offset_t             names_addr;
-       vm_size_t               names_size;
-       task_zone_info_t        *info;
-       vm_offset_t             info_addr;
-       vm_size_t               info_size;
-       unsigned int            max_zones, i;
-       zone_t                  z;
-       mach_zone_name_t        *zn;
-       task_zone_info_t        *zi;
-       kern_return_t           kr;
+       mach_zone_name_t        *names;
+       vm_offset_t             names_addr;
+       vm_size_t               names_size;
+
+       mach_zone_info_t        *info;
+       vm_offset_t             info_addr;
+       vm_size_t               info_size;
+
+       mach_memory_info_t      *memory_info;
+       vm_offset_t             memory_info_addr;
+       vm_size_t               memory_info_size;
+       vm_size_t               memory_info_vmsize;
+       unsigned int            num_info;
 
-       vm_size_t               used;
-       vm_map_copy_t           copy;
+       unsigned int            max_zones, used_zones, i;
+       mach_zone_name_t        *zn;
+       mach_zone_info_t        *zi;
+       kern_return_t           kr;
 
+       uint64_t                zones_collectable_bytes = 0;
 
-       if (task == TASK_NULL)
-               return KERN_INVALID_TASK;
+       if (host == HOST_NULL) {
+               return KERN_INVALID_HOST;
+       }
+#if CONFIG_DEBUGGER_FOR_ZONE_INFO
+       if (!PE_i_can_has_debugger(NULL)) {
+               return KERN_INVALID_HOST;
+       }
+#endif
 
        /*
         *      We assume that zones aren't freed once allocated.
         *      We won't pick up any zones that are allocated later.
         */
 
-       simple_lock(&all_zones_lock);
-       max_zones = (unsigned int)(num_zones + num_fake_zones);
-       z = first_zone;
-       simple_unlock(&all_zones_lock);
+       max_zones = os_atomic_load(&num_zones, relaxed);
 
        names_size = round_page(max_zones * sizeof *names);
        kr = kmem_alloc_pageable(ipc_kernel_map,
-                                &names_addr, names_size, VM_KERN_MEMORY_IPC);
-       if (kr != KERN_SUCCESS)
+           &names_addr, names_size, VM_KERN_MEMORY_IPC);
+       if (kr != KERN_SUCCESS) {
                return kr;
+       }
        names = (mach_zone_name_t *) names_addr;
 
        info_size = round_page(max_zones * sizeof *info);
        kr = kmem_alloc_pageable(ipc_kernel_map,
-                                &info_addr, info_size, VM_KERN_MEMORY_IPC);
+           &info_addr, info_size, VM_KERN_MEMORY_IPC);
        if (kr != KERN_SUCCESS) {
                kmem_free(ipc_kernel_map,
-                         names_addr, names_size);
+                   names_addr, names_size);
                return kr;
        }
-
-       info = (task_zone_info_t *) info_addr;
+       info = (mach_zone_info_t *) info_addr;
 
        zn = &names[0];
        zi = &info[0];
 
-       for (i = 0; i < max_zones - num_fake_zones; i++) {
-               struct zone zcopy;
-
-               assert(z != ZONE_NULL);
-
-               lock_zone(z);
-               zcopy = *z;
-               unlock_zone(z);
-
-               simple_lock(&all_zones_lock);
-               z = z->next_zone;
-               simple_unlock(&all_zones_lock);
-
-               /* assuming here the name data is static */
-               (void) strncpy(zn->mzn_name, zcopy.zone_name,
-                              sizeof zn->mzn_name);
-               zn->mzn_name[sizeof zn->mzn_name - 1] = '\0';
-
-               zi->tzi_count = (uint64_t)zcopy.count;
-               zi->tzi_cur_size = ptoa_64(zcopy.page_count);
-               zi->tzi_max_size = (uint64_t)zcopy.max_size;
-               zi->tzi_elem_size = (uint64_t)zcopy.elem_size;
-               zi->tzi_alloc_size = (uint64_t)zcopy.alloc_size;
-               zi->tzi_sum_size = zcopy.sum_count * zcopy.elem_size;
-               zi->tzi_exhaustible = (uint64_t)zcopy.exhaustible;
-               zi->tzi_collectable = (uint64_t)zcopy.collectable;
-               zi->tzi_caller_acct = (uint64_t)zcopy.caller_acct;
-               if (task->tkm_zinfo != NULL) {
-                       zi->tzi_task_alloc = task->tkm_zinfo[zcopy.index].alloc;
-                       zi->tzi_task_free = task->tkm_zinfo[zcopy.index].free;
-               } else {
-                       zi->tzi_task_alloc = 0;
-                       zi->tzi_task_free = 0;
+       used_zones = max_zones;
+       for (i = 0; i < max_zones; i++) {
+               if (!get_zone_info(&(zone_array[i]), zn, zi)) {
+                       used_zones--;
+                       continue;
                }
+               zones_collectable_bytes += GET_MZI_COLLECTABLE_BYTES(zi->mzi_collectable);
                zn++;
                zi++;
        }
 
-       /*
-        * loop through the fake zones and fill them using the specialized
-        * functions
-        */
-       for (i = 0; i < num_fake_zones; i++) {
-               int count, collectable, exhaustible, caller_acct, index;
-               vm_size_t cur_size, max_size, elem_size, alloc_size;
-               uint64_t sum_size;
-
-               strncpy(zn->mzn_name, fake_zones[i].name, sizeof zn->mzn_name);
-               zn->mzn_name[sizeof zn->mzn_name - 1] = '\0';
-               fake_zones[i].query(&count, &cur_size,
-                                   &max_size, &elem_size,
-                                   &alloc_size, &sum_size,
-                                   &collectable, &exhaustible, &caller_acct);
-               zi->tzi_count = (uint64_t)count;
-               zi->tzi_cur_size = (uint64_t)cur_size;
-               zi->tzi_max_size = (uint64_t)max_size;
-               zi->tzi_elem_size = (uint64_t)elem_size;
-               zi->tzi_alloc_size = (uint64_t)alloc_size;
-               zi->tzi_sum_size = sum_size;
-               zi->tzi_collectable = (uint64_t)collectable;
-               zi->tzi_exhaustible = (uint64_t)exhaustible;
-               zi->tzi_caller_acct = (uint64_t)caller_acct;
-               if (task->tkm_zinfo != NULL) {
-                       index = ZINFO_SLOTS - num_fake_zones + i;
-                       zi->tzi_task_alloc = task->tkm_zinfo[index].alloc;
-                       zi->tzi_task_free = task->tkm_zinfo[index].free;
-               } else {
-                       zi->tzi_task_alloc = 0;
-                       zi->tzi_task_free = 0;
-               }
-               zn++;
-               zi++;
-       }
+       *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, used_zones * sizeof *names);
+       *namesCntp = used_zones;
 
-       used = max_zones * sizeof *names;
-       if (used != names_size)
-               bzero((char *) (names_addr + used), names_size - used);
+       *infop = (mach_zone_info_t *) create_vm_map_copy(info_addr, info_size, used_zones * sizeof *info);
+       *infoCntp = used_zones;
 
-       kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)names_addr,
-                          (vm_map_size_t)used, TRUE, &copy);
-       assert(kr == KERN_SUCCESS);
+       num_info = 0;
+       memory_info_addr = 0;
 
-       *namesp = (mach_zone_name_t *) copy;
-       *namesCntp = max_zones;
+       if (memoryInfop && memoryInfoCntp) {
+               vm_map_copy_t           copy;
+               num_info = vm_page_diagnose_estimate();
+               memory_info_size = num_info * sizeof(*memory_info);
+               memory_info_vmsize = round_page(memory_info_size);
+               kr = kmem_alloc_pageable(ipc_kernel_map,
+                   &memory_info_addr, memory_info_vmsize, VM_KERN_MEMORY_IPC);
+               if (kr != KERN_SUCCESS) {
+                       return kr;
+               }
 
-       used = max_zones * sizeof *info;
+               kr = vm_map_wire_kernel(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize,
+                   VM_PROT_READ | VM_PROT_WRITE, VM_KERN_MEMORY_IPC, FALSE);
+               assert(kr == KERN_SUCCESS);
 
-       if (used != info_size)
-               bzero((char *) (info_addr + used), info_size - used);
+               memory_info = (mach_memory_info_t *) memory_info_addr;
+               vm_page_diagnose(memory_info, num_info, zones_collectable_bytes);
 
-       kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)info_addr,
-                          (vm_map_size_t)used, TRUE, &copy);
-       assert(kr == KERN_SUCCESS);
+               kr = vm_map_unwire(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize, FALSE);
+               assert(kr == KERN_SUCCESS);
+
+               kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)memory_info_addr,
+                   (vm_map_size_t)memory_info_size, TRUE, &copy);
+               assert(kr == KERN_SUCCESS);
 
-       *infop = (task_zone_info_t *) copy;
-       *infoCntp = max_zones;
+               *memoryInfop = (mach_memory_info_t *) copy;
+               *memoryInfoCntp = num_info;
+       }
 
        return KERN_SUCCESS;
 }
 
-#else  /* CONFIG_TASK_ZONE_INFO */
-
 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)
+mach_zone_info_for_zone(
+       host_priv_t                     host,
+       mach_zone_name_t        name,
+       mach_zone_info_t        *infop)
 {
-       return KERN_FAILURE;
-}
+       zone_t zone_ptr;
 
-#endif /* CONFIG_TASK_ZONE_INFO */
+       if (host == HOST_NULL) {
+               return KERN_INVALID_HOST;
+       }
+#if CONFIG_DEBUGGER_FOR_ZONE_INFO
+       if (!PE_i_can_has_debugger(NULL)) {
+               return KERN_INVALID_HOST;
+       }
+#endif
 
-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)
-{
-       return (mach_memory_info(host, namesp, namesCntp, infop, infoCntp, NULL, NULL));
+       if (infop == NULL) {
+               return KERN_INVALID_ARGUMENT;
+       }
+
+       zone_ptr = ZONE_NULL;
+       zone_index_foreach(i) {
+               zone_t z = &(zone_array[i]);
+               assert(z != ZONE_NULL);
+
+               /*
+                * Append kalloc heap name to zone name (if zone is used by kalloc)
+                */
+               char temp_zone_name[MAX_ZONE_NAME] = "";
+               snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
+                   zone_heap_name(z), z->z_name);
+
+               /* Find the requested zone by name */
+               if (track_this_zone(temp_zone_name, name.mzn_name)) {
+                       zone_ptr = z;
+                       break;
+               }
+       }
+
+       /* No zones found with the requested zone name */
+       if (zone_ptr == ZONE_NULL) {
+               return KERN_INVALID_ARGUMENT;
+       }
+
+       if (get_zone_info(zone_ptr, NULL, infop)) {
+               return KERN_SUCCESS;
+       }
+       return KERN_FAILURE;
 }
 
 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)
+mach_zone_info_for_largest_zone(
+       host_priv_t                     host,
+       mach_zone_name_t        *namep,
+       mach_zone_info_t        *infop)
 {
-       mach_zone_name_t        *names;
-       vm_offset_t             names_addr;
-       vm_size_t               names_size;
+       if (host == HOST_NULL) {
+               return KERN_INVALID_HOST;
+       }
+#if CONFIG_DEBUGGER_FOR_ZONE_INFO
+       if (!PE_i_can_has_debugger(NULL)) {
+               return KERN_INVALID_HOST;
+       }
+#endif
+
+       if (namep == NULL || infop == NULL) {
+               return KERN_INVALID_ARGUMENT;
+       }
 
-       mach_zone_info_t        *info;
-       vm_offset_t             info_addr;
-       vm_size_t               info_size;
+       if (get_zone_info(zone_find_largest(), namep, infop)) {
+               return KERN_SUCCESS;
+       }
+       return KERN_FAILURE;
+}
 
-       mach_memory_info_t      *memory_info;
-       vm_offset_t             memory_info_addr;
-       vm_size_t               memory_info_size;
-       vm_size_t               memory_info_vmsize;
-        unsigned int           num_sites;
+uint64_t
+get_zones_collectable_bytes(void)
+{
+       uint64_t zones_collectable_bytes = 0;
+       mach_zone_info_t zi;
 
-       unsigned int            max_zones, i;
-       zone_t                  z;
-       mach_zone_name_t        *zn;
-       mach_zone_info_t        *zi;
-       kern_return_t           kr;
-       
-       vm_size_t               used;
-       vm_map_copy_t           copy;
+       zone_index_foreach(i) {
+               if (get_zone_info(&zone_array[i], NULL, &zi)) {
+                       zones_collectable_bytes +=
+                           GET_MZI_COLLECTABLE_BYTES(zi.mzi_collectable);
+               }
+       }
 
+       return zones_collectable_bytes;
+}
 
-       if (host == HOST_NULL)
-               return KERN_INVALID_HOST;
-#if CONFIG_DEBUGGER_FOR_ZONE_INFO
-       if (!PE_i_can_has_debugger(NULL))
+kern_return_t
+mach_zone_get_zlog_zones(
+       host_priv_t                             host,
+       mach_zone_name_array_t  *namesp,
+       mach_msg_type_number_t  *namesCntp)
+{
+#if ZONE_ENABLE_LOGGING
+       unsigned int max_zones, logged_zones, i;
+       kern_return_t kr;
+       zone_t zone_ptr;
+       mach_zone_name_t *names;
+       vm_offset_t names_addr;
+       vm_size_t names_size;
+
+       if (host == HOST_NULL) {
                return KERN_INVALID_HOST;
-#endif
+       }
 
-       /*
-        *      We assume that zones aren't freed once allocated.
-        *      We won't pick up any zones that are allocated later.
-        */
+       if (namesp == NULL || namesCntp == NULL) {
+               return KERN_INVALID_ARGUMENT;
+       }
 
-       simple_lock(&all_zones_lock);
-       max_zones = (unsigned int)(num_zones + num_fake_zones);
-       z = first_zone;
-       simple_unlock(&all_zones_lock);
+       max_zones = os_atomic_load(&num_zones, relaxed);
 
        names_size = round_page(max_zones * sizeof *names);
        kr = kmem_alloc_pageable(ipc_kernel_map,
-                                &names_addr, names_size, VM_KERN_MEMORY_IPC);
-       if (kr != KERN_SUCCESS)
-               return kr;
-       names = (mach_zone_name_t *) names_addr;
-
-       info_size = round_page(max_zones * sizeof *info);
-       kr = kmem_alloc_pageable(ipc_kernel_map,
-                                &info_addr, info_size, VM_KERN_MEMORY_IPC);
+           &names_addr, names_size, VM_KERN_MEMORY_IPC);
        if (kr != KERN_SUCCESS) {
-               kmem_free(ipc_kernel_map,
-                         names_addr, names_size);
                return kr;
        }
-       info = (mach_zone_info_t *) info_addr;
+       names = (mach_zone_name_t *) names_addr;
 
-       num_sites = 0;
-       memory_info_addr = 0;
-       if (memoryInfop && memoryInfoCntp)
-       {
-               num_sites = VM_KERN_MEMORY_COUNT + VM_KERN_COUNTER_COUNT;
-               memory_info_size = num_sites * sizeof(*info);
-               memory_info_vmsize = round_page(memory_info_size);
-               kr = kmem_alloc_pageable(ipc_kernel_map,
-                                        &memory_info_addr, memory_info_vmsize, VM_KERN_MEMORY_IPC);
-               if (kr != KERN_SUCCESS) {
-                       kmem_free(ipc_kernel_map,
-                                 names_addr, names_size);
-                       kmem_free(ipc_kernel_map,
-                                 info_addr, info_size);
-                       return kr;
+       zone_ptr = ZONE_NULL;
+       logged_zones = 0;
+       for (i = 0; i < max_zones; i++) {
+               zone_t z = &(zone_array[i]);
+               assert(z != ZONE_NULL);
+
+               /* Copy out the zone name if zone logging is enabled */
+               if (z->zlog_btlog) {
+                       get_zone_info(z, &names[logged_zones], NULL);
+                       logged_zones++;
                }
+       }
 
-               kr = vm_map_wire(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize,
-                                    VM_PROT_READ|VM_PROT_WRITE|VM_PROT_MEMORY_TAG_MAKE(VM_KERN_MEMORY_IPC), FALSE);
-               assert(kr == KERN_SUCCESS);
+       *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, logged_zones * sizeof *names);
+       *namesCntp = logged_zones;
 
-               memory_info = (mach_memory_info_t *) memory_info_addr;
-               vm_page_diagnose(memory_info, num_sites);
+       return KERN_SUCCESS;
 
-               kr = vm_map_unwire(ipc_kernel_map, memory_info_addr, memory_info_addr + memory_info_vmsize, FALSE);
-               assert(kr == KERN_SUCCESS);
+#else /* ZONE_ENABLE_LOGGING */
+#pragma unused(host, namesp, namesCntp)
+       return KERN_FAILURE;
+#endif /* ZONE_ENABLE_LOGGING */
+}
+
+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)
+{
+#if DEBUG || DEVELOPMENT
+       unsigned int numrecs = 0;
+       zone_btrecord_t *recs;
+       kern_return_t kr;
+       zone_t zone_ptr;
+       vm_offset_t recs_addr;
+       vm_size_t recs_size;
+
+       if (host == HOST_NULL) {
+               return KERN_INVALID_HOST;
        }
 
-       zn = &names[0];
-       zi = &info[0];
+       if (recsp == NULL || recsCntp == NULL) {
+               return KERN_INVALID_ARGUMENT;
+       }
 
-       for (i = 0; i < max_zones - num_fake_zones; i++) {
-               struct zone zcopy;
+       zone_ptr = ZONE_NULL;
+       zone_index_foreach(i) {
+               zone_t z = &zone_array[i];
 
-               assert(z != ZONE_NULL);
+               /*
+                * Append kalloc heap name to zone name (if zone is used by kalloc)
+                */
+               char temp_zone_name[MAX_ZONE_NAME] = "";
+               snprintf(temp_zone_name, MAX_ZONE_NAME, "%s%s",
+                   zone_heap_name(z), z->z_name);
 
-               lock_zone(z);
-               zcopy = *z;
-               unlock_zone(z);
+               /* Find the requested zone by name */
+               if (track_this_zone(temp_zone_name, name.mzn_name)) {
+                       zone_ptr = z;
+                       break;
+               }
+       }
 
-               simple_lock(&all_zones_lock);
-               z = z->next_zone;
-               simple_unlock(&all_zones_lock);
+       /* No zones found with the requested zone name */
+       if (zone_ptr == ZONE_NULL) {
+               return KERN_INVALID_ARGUMENT;
+       }
 
-               /* assuming here the name data is static */
-               (void) strncpy(zn->mzn_name, zcopy.zone_name,
-                              sizeof zn->mzn_name);
-               zn->mzn_name[sizeof zn->mzn_name - 1] = '\0';
-
-               zi->mzi_count = (uint64_t)zcopy.count;
-               zi->mzi_cur_size = ptoa_64(zcopy.page_count);
-               zi->mzi_max_size = (uint64_t)zcopy.max_size;
-               zi->mzi_elem_size = (uint64_t)zcopy.elem_size;
-               zi->mzi_alloc_size = (uint64_t)zcopy.alloc_size;
-               zi->mzi_sum_size = zcopy.sum_count * zcopy.elem_size;
-               zi->mzi_exhaustible = (uint64_t)zcopy.exhaustible;
-               zi->mzi_collectable = (uint64_t)zcopy.collectable;
-               zn++;
-               zi++;
+       /* Logging not turned on for the requested zone */
+       if (!DO_LOGGING(zone_ptr)) {
+               return KERN_FAILURE;
        }
 
-       /*
-        * loop through the fake zones and fill them using the specialized
-        * functions
-        */
-       for (i = 0; i < num_fake_zones; i++) {
-               int count, collectable, exhaustible, caller_acct;
-               vm_size_t cur_size, max_size, elem_size, alloc_size;
-               uint64_t sum_size;
-
-               strncpy(zn->mzn_name, fake_zones[i].name, sizeof zn->mzn_name);
-               zn->mzn_name[sizeof zn->mzn_name - 1] = '\0';
-               fake_zones[i].query(&count, &cur_size,
-                                   &max_size, &elem_size,
-                                   &alloc_size, &sum_size,
-                                   &collectable, &exhaustible, &caller_acct);
-               zi->mzi_count = (uint64_t)count;
-               zi->mzi_cur_size = (uint64_t)cur_size;
-               zi->mzi_max_size = (uint64_t)max_size;
-               zi->mzi_elem_size = (uint64_t)elem_size;
-               zi->mzi_alloc_size = (uint64_t)alloc_size;
-               zi->mzi_sum_size = sum_size;
-               zi->mzi_collectable = (uint64_t)collectable;
-               zi->mzi_exhaustible = (uint64_t)exhaustible;
+       /* Allocate memory for btlog records */
+       numrecs = (unsigned int)(get_btlog_records_count(zone_ptr->zlog_btlog));
+       recs_size = round_page(numrecs * sizeof *recs);
 
-               zn++;
-               zi++;
+       kr = kmem_alloc_pageable(ipc_kernel_map, &recs_addr, recs_size, VM_KERN_MEMORY_IPC);
+       if (kr != KERN_SUCCESS) {
+               return kr;
        }
 
-       used = max_zones * sizeof *names;
-       if (used != names_size)
-               bzero((char *) (names_addr + used), names_size - used);
+       /*
+        * We will call get_btlog_records() below which populates this region while holding a spinlock
+        * (the btlog lock). So these pages need to be wired.
+        */
+       kr = vm_map_wire_kernel(ipc_kernel_map, recs_addr, recs_addr + recs_size,
+           VM_PROT_READ | VM_PROT_WRITE, VM_KERN_MEMORY_IPC, FALSE);
+       assert(kr == KERN_SUCCESS);
+
+       recs = (zone_btrecord_t *)recs_addr;
+       get_btlog_records(zone_ptr->zlog_btlog, recs, &numrecs);
 
-       kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)names_addr,
-                          (vm_map_size_t)used, TRUE, &copy);
+       kr = vm_map_unwire(ipc_kernel_map, recs_addr, recs_addr + recs_size, FALSE);
        assert(kr == KERN_SUCCESS);
 
-       *namesp = (mach_zone_name_t *) copy;
-       *namesCntp = max_zones;
+       *recsp = (zone_btrecord_t *) create_vm_map_copy(recs_addr, recs_size, numrecs * sizeof *recs);
+       *recsCntp = numrecs;
+
+       return KERN_SUCCESS;
+
+#else /* DEBUG || DEVELOPMENT */
+#pragma unused(host, name, recsp, recsCntp)
+       return KERN_FAILURE;
+#endif /* DEBUG || DEVELOPMENT */
+}
 
-       used = max_zones * sizeof *info;
 
-       if (used != info_size)
-               bzero((char *) (info_addr + used), info_size - used);
+#if DEBUG || DEVELOPMENT
 
-       kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)info_addr,
-                          (vm_map_size_t)used, TRUE, &copy);
+kern_return_t
+mach_memory_info_check(void)
+{
+       mach_memory_info_t * memory_info;
+       mach_memory_info_t * info;
+       unsigned int         num_info;
+       vm_offset_t          memory_info_addr;
+       kern_return_t        kr;
+       size_t               memory_info_size, memory_info_vmsize;
+       uint64_t             top_wired, zonestotal, total;
+
+       num_info = vm_page_diagnose_estimate();
+       memory_info_size = num_info * sizeof(*memory_info);
+       memory_info_vmsize = round_page(memory_info_size);
+       kr = kmem_alloc(kernel_map, &memory_info_addr, memory_info_vmsize, VM_KERN_MEMORY_DIAG);
        assert(kr == KERN_SUCCESS);
 
-       *infop = (mach_zone_info_t *) copy;
-       *infoCntp = max_zones;
+       memory_info = (mach_memory_info_t *) memory_info_addr;
+       vm_page_diagnose(memory_info, num_info, 0);
 
-       if (memoryInfop && memoryInfoCntp)
-       {
-               kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)memory_info_addr,
-                                  (vm_map_size_t)memory_info_size, TRUE, &copy);
-               assert(kr == KERN_SUCCESS);
+       top_wired = total = zonestotal = 0;
+       zone_index_foreach(idx) {
+               zonestotal += zone_size_wired(&zone_array[idx]);
+       }
 
-               *memoryInfop = (mach_memory_info_t *) copy;
-               *memoryInfoCntp = num_sites;
+       for (uint32_t idx = 0; idx < num_info; idx++) {
+               info = &memory_info[idx];
+               if (!info->size) {
+                       continue;
+               }
+               if (VM_KERN_COUNT_WIRED == info->site) {
+                       top_wired = info->size;
+               }
+               if (VM_KERN_SITE_HIDE & info->flags) {
+                       continue;
+               }
+               if (!(VM_KERN_SITE_WIRED & info->flags)) {
+                       continue;
+               }
+               total += info->size;
        }
+       total += zonestotal;
 
-       return KERN_SUCCESS;
+       printf("vm_page_diagnose_check %qd of %qd, zones %qd, short 0x%qx\n",
+           total, top_wired, zonestotal, top_wired - total);
+
+       kmem_free(kernel_map, memory_info_addr, memory_info_vmsize);
+
+       return kr;
 }
 
-/*
- * host_zone_info - LEGACY user interface for Mach zone information
- *                 Should use mach_zone_info() instead!
- */
+extern boolean_t(*volatile consider_buffer_cache_collect)(int);
+
+#endif /* DEBUG || DEVELOPMENT */
+
 kern_return_t
-host_zone_info(
-       host_priv_t             host,
-       zone_name_array_t       *namesp,
-       mach_msg_type_number_t  *namesCntp,
-       zone_info_array_t       *infop,
-       mach_msg_type_number_t  *infoCntp)
+mach_zone_force_gc(
+       host_t host)
 {
-       zone_name_t     *names;
-       vm_offset_t     names_addr;
-       vm_size_t       names_size;
-       zone_info_t     *info;
-       vm_offset_t     info_addr;
-       vm_size_t       info_size;
-       unsigned int    max_zones, i;
-       zone_t          z;
-       zone_name_t    *zn;
-       zone_info_t    *zi;
-       kern_return_t   kr;
-
-       vm_size_t       used;
-       vm_map_copy_t   copy;
+       if (host == HOST_NULL) {
+               return KERN_INVALID_HOST;
+       }
 
+#if DEBUG || DEVELOPMENT
+       /* Callout to buffer cache GC to drop elements in the apfs zones */
+       if (consider_buffer_cache_collect != NULL) {
+               (void)(*consider_buffer_cache_collect)(0);
+       }
+       consider_zone_gc(FALSE);
+#endif /* DEBUG || DEVELOPMENT */
+       return KERN_SUCCESS;
+}
 
-       if (host == HOST_NULL)
-               return KERN_INVALID_HOST;
-#if CONFIG_DEBUGGER_FOR_ZONE_INFO
-       if (!PE_i_can_has_debugger(NULL))
-               return KERN_INVALID_HOST;
-#endif
+zone_t
+zone_find_largest(void)
+{
+       uint32_t    largest_idx  = 0;
+       vm_offset_t largest_size = zone_size_wired(&zone_array[0]);
+
+       zone_index_foreach(i) {
+               vm_offset_t size = zone_size_wired(&zone_array[i]);
+               if (size > largest_size) {
+                       largest_idx = i;
+                       largest_size = size;
+               }
+       }
 
-#if defined(__LP64__)
-       if (!thread_is_64bit(current_thread()))
-               return KERN_NOT_SUPPORTED;
-#else
-       if (thread_is_64bit(current_thread()))
-               return KERN_NOT_SUPPORTED;
-#endif
+       return &zone_array[largest_idx];
+}
 
-       /*
-        *      We assume that zones aren't freed once allocated.
-        *      We won't pick up any zones that are allocated later.
-        */
+#pragma mark - tests
+#if DEBUG || DEVELOPMENT
 
-       simple_lock(&all_zones_lock);
-       max_zones = (unsigned int)(num_zones + num_fake_zones);
-       z = first_zone;
-       simple_unlock(&all_zones_lock);
+/*
+ * Used for sysctl kern.run_zone_test which is not thread-safe. Ensure only one
+ * thread goes through at a time.  Or we can end up with multiple test zones (if
+ * a second zinit() comes through before zdestroy()),  which could lead us to
+ * run out of zones.
+ */
+SIMPLE_LOCK_DECLARE(zone_test_lock, 0);
+static boolean_t zone_test_running = FALSE;
+static zone_t test_zone_ptr = NULL;
 
-       names_size = round_page(max_zones * sizeof *names);
-       kr = kmem_alloc_pageable(ipc_kernel_map,
-                                &names_addr, names_size, VM_KERN_MEMORY_IPC);
-       if (kr != KERN_SUCCESS)
-               return kr;
-       names = (zone_name_t *) names_addr;
+static uintptr_t *
+zone_copy_allocations(zone_t z, uintptr_t *elems, bitmap_t *bits,
+    zone_pva_t page_index, zone_addr_kind_t kind)
+{
+       vm_offset_t free, first, end, page;
+       struct zone_page_metadata *meta;
 
-       info_size = round_page(max_zones * sizeof *info);
-       kr = kmem_alloc_pageable(ipc_kernel_map,
-                                &info_addr, info_size, VM_KERN_MEMORY_IPC);
-       if (kr != KERN_SUCCESS) {
-               kmem_free(ipc_kernel_map,
-                         names_addr, names_size);
-               return kr;
-       }
+       while (!zone_pva_is_null(page_index)) {
+               page  = zone_pva_to_addr(page_index);
+               meta  = zone_pva_to_meta(page_index, kind);
+               end   = page + ptoa(meta->zm_percpu ? 1 : meta->zm_page_count);
+               first = page + ZONE_PAGE_FIRST_OFFSET(kind);
 
-       info = (zone_info_t *) info_addr;
+               bitmap_clear(bits, (uint32_t)((end - first) / zone_elem_size(z)));
 
-       zn = &names[0];
-       zi = &info[0];
+               // construct bitmap of all freed elements
+               free = zone_page_meta_get_freelist(z, meta, page);
+               while (free) {
+                       bitmap_set(bits, (uint32_t)((free - first) / zone_elem_size(z)));
 
-       for (i = 0; i < max_zones - num_fake_zones; i++) {
-               struct zone zcopy;
+                       // next free element
+                       free = *(vm_offset_t *)free ^ zp_nopoison_cookie;
+               }
 
-               assert(z != ZONE_NULL);
+               for (unsigned i = 0; first < end; i++, first += zone_elem_size(z)) {
+                       if (!bitmap_test(bits, i)) {
+                               *elems++ = INSTANCE_PUT(first);
+                       }
+               }
 
-               lock_zone(z);
-               zcopy = *z;
-               unlock_zone(z);
+               page_index = meta->zm_page_next;
+       }
+       return elems;
+}
 
-               simple_lock(&all_zones_lock);
-               z = z->next_zone;
-               simple_unlock(&all_zones_lock);
+kern_return_t
+zone_leaks(const char * zoneName, uint32_t nameLen, leak_site_proc proc, void * refCon)
+{
+       uintptr_t     zbt[MAX_ZTRACE_DEPTH];
+       zone_t        zone = NULL;
+       uintptr_t *   array;
+       uintptr_t *   next;
+       uintptr_t     element, bt;
+       uint32_t      idx, count, found;
+       uint32_t      btidx, btcount, nobtcount, btfound;
+       uint32_t      elemSize;
+       uint64_t      maxElems;
+       kern_return_t kr;
+       bitmap_t     *bits;
+
+       zone_index_foreach(i) {
+               if (!strncmp(zoneName, zone_array[i].z_name, nameLen)) {
+                       zone = &zone_array[i];
+                       break;
+               }
+       }
+       if (zone == NULL) {
+               return KERN_INVALID_NAME;
+       }
 
-               /* assuming here the name data is static */
-               (void) strncpy(zn->zn_name, zcopy.zone_name,
-                              sizeof zn->zn_name);
-               zn->zn_name[sizeof zn->zn_name - 1] = '\0';
-
-               zi->zi_count = zcopy.count;
-               zi->zi_cur_size = ptoa(zcopy.page_count);
-               zi->zi_max_size = zcopy.max_size;
-               zi->zi_elem_size = zcopy.elem_size;
-               zi->zi_alloc_size = zcopy.alloc_size;
-               zi->zi_exhaustible = zcopy.exhaustible;
-               zi->zi_collectable = zcopy.collectable;
+       elemSize = zone_elem_size(zone);
+       maxElems = (zone->countavail + 1) & ~1ul;
 
-               zn++;
-               zi++;
+       if ((ptoa(zone->percpu ? 1 : zone->alloc_pages) % elemSize) &&
+           !zone_leaks_scan_enable) {
+               return KERN_INVALID_CAPABILITY;
        }
 
-       /*
-        * loop through the fake zones and fill them using the specialized
-        * functions
-        */
-       for (i = 0; i < num_fake_zones; i++) {
-               int caller_acct;
-               uint64_t sum_space;
-               strncpy(zn->zn_name, fake_zones[i].name, sizeof zn->zn_name);
-               zn->zn_name[sizeof zn->zn_name - 1] = '\0';
-               fake_zones[i].query(&zi->zi_count, &zi->zi_cur_size,
-                                   &zi->zi_max_size, &zi->zi_elem_size,
-                                   &zi->zi_alloc_size, &sum_space,
-                                   &zi->zi_collectable, &zi->zi_exhaustible, &caller_acct);
-               zn++;
-               zi++;
+       kr = kmem_alloc_kobject(kernel_map, (vm_offset_t *) &array,
+           maxElems * sizeof(uintptr_t) + BITMAP_LEN(ZONE_CHUNK_MAXELEMENTS),
+           VM_KERN_MEMORY_DIAG);
+       if (KERN_SUCCESS != kr) {
+               return kr;
        }
 
-       used = max_zones * sizeof *names;
-       if (used != names_size)
-               bzero((char *) (names_addr + used), names_size - used);
+       /* maxElems is a 2-multiple so we're always aligned */
+       bits = CAST_DOWN_EXPLICIT(bitmap_t *, array + maxElems);
 
-       kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)names_addr,
-                          (vm_map_size_t)used, TRUE, &copy);
-       assert(kr == KERN_SUCCESS);
+       lock_zone(zone);
 
-       *namesp = (zone_name_t *) copy;
-       *namesCntp = max_zones;
+       next = array;
+       next = zone_copy_allocations(zone, next, bits,
+           zone->pages_any_free_foreign, ZONE_ADDR_FOREIGN);
+       next = zone_copy_allocations(zone, next, bits,
+           zone->pages_all_used_foreign, ZONE_ADDR_FOREIGN);
+       next = zone_copy_allocations(zone, next, bits,
+           zone->pages_intermediate, ZONE_ADDR_NATIVE);
+       next = zone_copy_allocations(zone, next, bits,
+           zone->pages_all_used, ZONE_ADDR_NATIVE);
+       count = (uint32_t)(next - array);
 
-       used = max_zones * sizeof *info;
-       if (used != info_size)
-               bzero((char *) (info_addr + used), info_size - used);
+       unlock_zone(zone);
 
-       kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)info_addr,
-                          (vm_map_size_t)used, TRUE, &copy);
-       assert(kr == KERN_SUCCESS);
+       zone_leaks_scan(array, count, zone_elem_size(zone), &found);
+       assert(found <= count);
 
-       *infop = (zone_info_t *) copy;
-       *infoCntp = max_zones;
+       for (idx = 0; idx < count; idx++) {
+               element = array[idx];
+               if (kInstanceFlagReferenced & element) {
+                       continue;
+               }
+               element = INSTANCE_PUT(element) & ~kInstanceFlags;
+       }
 
-       return KERN_SUCCESS;
-}
+#if ZONE_ENABLE_LOGGING
+       if (zone->zlog_btlog && !corruption_debug_flag) {
+               // btlog_copy_backtraces_for_elements will set kInstanceFlagReferenced on elements it found
+               btlog_copy_backtraces_for_elements(zone->zlog_btlog, array, &count, elemSize, proc, refCon);
+       }
+#endif /* ZONE_ENABLE_LOGGING */
 
-kern_return_t
-mach_zone_force_gc(
-       host_t host)
-{
+       for (nobtcount = idx = 0; idx < count; idx++) {
+               element = array[idx];
+               if (!element) {
+                       continue;
+               }
+               if (kInstanceFlagReferenced & element) {
+                       continue;
+               }
+               element = INSTANCE_PUT(element) & ~kInstanceFlags;
 
-       if (host == HOST_NULL)
-               return KERN_INVALID_HOST;
+               // see if we can find any backtrace left in the element
+               btcount = (typeof(btcount))(zone_elem_size(zone) / sizeof(uintptr_t));
+               if (btcount >= MAX_ZTRACE_DEPTH) {
+                       btcount = MAX_ZTRACE_DEPTH - 1;
+               }
+               for (btfound = btidx = 0; btidx < btcount; btidx++) {
+                       bt = ((uintptr_t *)element)[btcount - 1 - btidx];
+                       if (!VM_KERNEL_IS_SLID(bt)) {
+                               break;
+                       }
+                       zbt[btfound++] = bt;
+               }
+               if (btfound) {
+                       (*proc)(refCon, 1, elemSize, &zbt[0], btfound);
+               } else {
+                       nobtcount++;
+               }
+       }
+       if (nobtcount) {
+               // fake backtrace when we found nothing
+               zbt[0] = (uintptr_t) &zalloc;
+               (*proc)(refCon, nobtcount, elemSize, &zbt[0], 1);
+       }
 
-       consider_zone_gc(TRUE);
+       kmem_free(kernel_map, (vm_offset_t) array, maxElems * sizeof(uintptr_t));
 
-       return (KERN_SUCCESS);
+       return KERN_SUCCESS;
 }
 
-extern unsigned int stack_total;
-extern unsigned long long stack_allocs;
-
-#if defined(__i386__) || defined (__x86_64__)
-extern unsigned int inuse_ptepages_count;
-extern long long alloc_ptepages_count;
-#endif
-
-void zone_display_zprint()
+boolean_t
+run_zone_test(void)
 {
-       unsigned int    i;
-       zone_t          the_zone;
+       unsigned int i = 0, max_iter = 5;
+       void * test_ptr;
+       zone_t test_zone;
 
-       if(first_zone!=NULL) {
-               the_zone = first_zone;
-               for (i = 0; i < num_zones; i++) {
-                       if(the_zone->cur_size > (1024*1024)) {
-                               printf("%.20s:\t%lu\n",the_zone->zone_name,(uintptr_t)the_zone->cur_size);
-                       }
+       simple_lock(&zone_test_lock, &zone_locks_grp);
+       if (!zone_test_running) {
+               zone_test_running = TRUE;
+       } else {
+               simple_unlock(&zone_test_lock);
+               printf("run_zone_test: Test already running.\n");
+               return FALSE;
+       }
+       simple_unlock(&zone_test_lock);
 
-                       if(the_zone->next_zone == NULL) {
-                               break;
-                       }
+       printf("run_zone_test: Testing zinit(), zalloc(), zfree() and zdestroy() on zone \"test_zone_sysctl\"\n");
 
-                       the_zone = the_zone->next_zone;
+       /* zinit() and zdestroy() a zone with the same name a bunch of times, verify that we get back the same zone each time */
+       do {
+               test_zone = zinit(sizeof(uint64_t), 100 * sizeof(uint64_t), sizeof(uint64_t), "test_zone_sysctl");
+               if (test_zone == NULL) {
+                       printf("run_zone_test: zinit() failed\n");
+                       return FALSE;
                }
-       }
-
-       printf("Kernel Stacks:\t%lu\n",(uintptr_t)(kernel_stack_size * stack_total));
 
-#if defined(__i386__) || defined (__x86_64__)
-       printf("PageTables:\t%lu\n",(uintptr_t)(PAGE_SIZE * inuse_ptepages_count));
+#if KASAN_ZALLOC
+               if (test_zone_ptr == NULL && test_zone->countfree != 0) {
+#else
+               if (test_zone->countfree != 0) {
 #endif
+                       printf("run_zone_test: free count is not zero\n");
+                       return FALSE;
+               }
 
-       printf("Kalloc.Large:\t%lu\n",(uintptr_t)kalloc_large_total);
-}
-
-zone_t
-zone_find_largest(void)
-{
-       unsigned int    i;
-       unsigned int    max_zones;
-       zone_t          the_zone;
-       zone_t          zone_largest;
+               if (test_zone_ptr == NULL) {
+                       /* Stash the zone pointer returned on the fist zinit */
+                       printf("run_zone_test: zone created for the first time\n");
+                       test_zone_ptr = test_zone;
+               } else if (test_zone != test_zone_ptr) {
+                       printf("run_zone_test: old zone pointer and new zone pointer don't match\n");
+                       return FALSE;
+               }
 
-       simple_lock(&all_zones_lock);
-       the_zone = first_zone;
-       max_zones = num_zones;
-       simple_unlock(&all_zones_lock);
-       
-       zone_largest = the_zone;
-       for (i = 0; i < max_zones; i++) {
-               if (the_zone->cur_size > zone_largest->cur_size) {
-                       zone_largest = the_zone;
+               test_ptr = zalloc(test_zone);
+               if (test_ptr == NULL) {
+                       printf("run_zone_test: zalloc() failed\n");
+                       return FALSE;
+               }
+               zfree(test_zone, test_ptr);
+
+               zdestroy(test_zone);
+               i++;
+
+               printf("run_zone_test: Iteration %d successful\n", i);
+       } while (i < max_iter);
+
+       /* test Z_VA_SEQUESTER */
+       if (zsecurity_options & ZSECURITY_OPTIONS_SEQUESTER) {
+               int idx, num_allocs = 8;
+               vm_size_t elem_size = 2 * PAGE_SIZE / num_allocs;
+               void *allocs[num_allocs];
+               vm_offset_t phys_pages = os_atomic_load(&zones_phys_page_count, relaxed);
+               vm_size_t zone_map_size = zone_range_size(&zone_info.zi_map_range);
+
+               test_zone = zone_create("test_zone_sysctl", elem_size,
+                   ZC_DESTRUCTIBLE | ZC_SEQUESTER);
+               if (test_zone == NULL) {
+                       printf("run_zone_test: zinit() failed\n");
+                       return FALSE;
                }
 
-               if (the_zone->next_zone == NULL) {
-                       break;
+               for (idx = 0; idx < num_allocs; idx++) {
+                       allocs[idx] = zalloc(test_zone);
+                       assert(NULL != allocs[idx]);
+                       printf("alloc[%d] %p\n", idx, allocs[idx]);
+               }
+               for (idx = 0; idx < num_allocs; idx++) {
+                       zfree(test_zone, allocs[idx]);
+               }
+               assert(!zone_pva_is_null(test_zone->pages_all_free));
+
+               printf("vm_page_wire_count %d, vm_page_free_count %d, p to v %qd%%\n",
+                   vm_page_wire_count, vm_page_free_count,
+                   (100ULL * ptoa_64(phys_pages)) / zone_map_size);
+               zone_gc(FALSE);
+               printf("vm_page_wire_count %d, vm_page_free_count %d, p to v %qd%%\n",
+                   vm_page_wire_count, vm_page_free_count,
+                   (100ULL * ptoa_64(phys_pages)) / zone_map_size);
+               unsigned int allva = 0;
+               zone_index_foreach(zidx) {
+                       zone_t z = &zone_array[zidx];
+                       lock_zone(z);
+                       allva += z->page_count;
+                       if (!z->sequester_page_count) {
+                               unlock_zone(z);
+                               continue;
+                       }
+                       unsigned count = 0;
+                       uint64_t size;
+                       zone_pva_t pg = z->pages_sequester;
+                       struct zone_page_metadata *page_meta;
+                       while (pg.packed_address) {
+                               page_meta = zone_pva_to_meta(pg, ZONE_ADDR_NATIVE);
+                               count += z->alloc_pages;
+                               pg = page_meta->zm_page_next;
+                       }
+                       assert(count == z->sequester_page_count);
+                       size = zone_size_wired(z);
+                       if (!size) {
+                               size = 1;
+                       }
+                       printf("%s%s: seq %d, res %d, %qd %%\n",
+                           zone_heap_name(z), z->z_name, z->sequester_page_count,
+                           z->page_count, zone_size_allocated(z) * 100ULL / size);
+                       unlock_zone(z);
                }
 
-               the_zone = the_zone->next_zone;
+               printf("total va: %d\n", allva);
+
+               assert(zone_pva_is_null(test_zone->pages_all_free));
+               assert(!zone_pva_is_null(test_zone->pages_sequester));
+               assert(2 == test_zone->sequester_page_count);
+               for (idx = 0; idx < num_allocs; idx++) {
+                       assert(0 == pmap_find_phys(kernel_pmap, (addr64_t)(uintptr_t) allocs[idx]));
+               }
+               for (idx = 0; idx < num_allocs; idx++) {
+                       allocs[idx] = zalloc(test_zone);
+                       assert(allocs[idx]);
+                       printf("alloc[%d] %p\n", idx, allocs[idx]);
+               }
+               assert(zone_pva_is_null(test_zone->pages_sequester));
+               assert(0 == test_zone->sequester_page_count);
+               for (idx = 0; idx < num_allocs; idx++) {
+                       zfree(test_zone, allocs[idx]);
+               }
+               zdestroy(test_zone);
+       } else {
+               printf("run_zone_test: skipping sequester test (not enabled)\n");
        }
-       return zone_largest;
-}
 
-#if    ZONE_DEBUG
+       printf("run_zone_test: Test passed\n");
+
+       simple_lock(&zone_test_lock, &zone_locks_grp);
+       zone_test_running = FALSE;
+       simple_unlock(&zone_test_lock);
 
-/* should we care about locks here ? */
+       return TRUE;
+}
 
-#define zone_in_use(z)         ( z->count || z->free_elements \
-                                                 || !queue_empty(&z->pages.all_free) \
-                                                 || !queue_empty(&z->pages.intermediate) \
-                                                 || (z->allows_foreign && !queue_empty(&z->pages.any_free_foreign)))
+/*
+ * Routines to test that zone garbage collection and zone replenish threads
+ * running at the same time don't cause problems.
+ */
 
 void
-zone_debug_enable(
-       zone_t          z)
+zone_gc_replenish_test(void)
 {
-       if (zone_debug_enabled(z) || zone_in_use(z) ||
-           z->alloc_size < (z->elem_size + ZONE_DEBUG_OFFSET))
-               return;
-       queue_init(&z->active_zones);
-       z->elem_size += ZONE_DEBUG_OFFSET;
+       zone_gc(FALSE);
 }
 
+
 void
-zone_debug_disable(
-       zone_t          z)
+zone_alloc_replenish_test(void)
 {
-       if (!zone_debug_enabled(z) || zone_in_use(z))
+       zone_t z = NULL;
+       struct data { struct data *next; } *node, *list = NULL;
+
+       /*
+        * Find a zone that has a replenish thread
+        */
+       zone_index_foreach(i) {
+               z = &zone_array[i];
+               if (z->prio_refill_count &&
+                   zone_elem_size(z) >= sizeof(struct data)) {
+                       z = &zone_array[i];
+                       break;
+               }
+       }
+       if (z == NULL) {
+               printf("Couldn't find a replenish zone\n");
                return;
-       z->elem_size -= ZONE_DEBUG_OFFSET;
-       z->active_zones.next = z->active_zones.prev = NULL;
-}
+       }
+
+       for (uint32_t i = 0; i < 2000; ++i) {      /* something big enough to go past replenishment */
+               node = zalloc(z);
+               node->next = list;
+               list = node;
+       }
 
+       /*
+        * release the memory we allocated
+        */
+       while (list != NULL) {
+               node = list;
+               list = list->next;
+               zfree(z, node);
+       }
+}
 
-#endif /* ZONE_DEBUG */
+#endif /* DEBUG || DEVELOPMENT */