+ alloc = best_alloc;
+ if (max && (max < alloc))
+ max = alloc;
+
+ 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->count = 0;
+ z->countfree = 0;
+ z->count_all_free_pages = 0;
+ z->sum_count = 0LL;
+ z->doing_alloc_without_vm_priv = FALSE;
+ z->doing_alloc_with_vm_priv = 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->zone_replenishing = FALSE;
+ z->prio_refill_watermark = 0;
+ z->zone_replenish_thread = NULL;
+ z->zp_count = 0;
+ z->kasan_quarantine = TRUE;
+ z->zone_valid = TRUE;
+
+#if CONFIG_ZLEAKS
+ z->zleak_capture = 0;
+ z->zleak_on = FALSE;
+#endif /* CONFIG_ZLEAKS */
+
+ /*
+ * If the VM is ready to handle kmem_alloc requests, copy the zone name passed in.
+ *
+ * Else simply maintain a pointer to the name string. The only zones we'll actually have
+ * to do this for would be the VM-related zones that are created very early on before any
+ * kexts can be loaded (unloaded). So we should be fine with just a pointer in this case.
+ */
+ if (kmem_alloc_ready) {
+ size_t len = MIN(strlen(name)+1, MACH_ZONE_NAME_MAX_LEN);
+
+ if (zone_names_start == 0 || ((zone_names_next - zone_names_start) + len) > PAGE_SIZE) {
+ printf("zalloc: allocating memory for zone names buffer\n");
+ kern_return_t retval = kmem_alloc_kobject(kernel_map, &zone_names_start,
+ PAGE_SIZE, VM_KERN_MEMORY_OSFMK);
+ if (retval != KERN_SUCCESS) {
+ panic("zalloc: zone_names memory allocation failed");
+ }
+ bzero((char *)zone_names_start, PAGE_SIZE);
+ zone_names_next = zone_names_start;
+ }
+
+ strlcpy((char *)zone_names_next, name, len);
+ z->zone_name = (char *)zone_names_next;
+ zone_names_next += len;
+ } else {
+ z->zone_name = name;
+ }
+
+ /*
+ * 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 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.
+ */
+
+ if (num_zones_logged < max_num_zones_to_log) {
+
+ int i = 1; /* zlog0 isn't allowed. */
+ boolean_t zone_logging_enabled = FALSE;
+ char zlog_name[MAX_ZONE_NAME] = ""; /* Temp. buffer to create the strings zlog1, zlog2 etc... */
+
+ while (i <= max_num_zones_to_log) {
+
+ snprintf(zlog_name, MAX_ZONE_NAME, "zlog%d", i);
+
+ if (PE_parse_boot_argn(zlog_name, zone_name_to_log, sizeof(zone_name_to_log)) == TRUE) {
+ if (track_this_zone(z->zone_name, zone_name_to_log)) {
+ if (z->zone_valid) {
+ z->zone_logging = TRUE;
+ zone_logging_enabled = TRUE;
+ num_zones_logged++;
+ break;
+ }
+ }
+ }
+ i++;
+ }
+
+ if (zone_logging_enabled == FALSE) {
+ /*
+ * 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 (PE_parse_boot_argn("zlog", zone_name_to_log, sizeof(zone_name_to_log)) == TRUE) {
+ if (track_this_zone(z->zone_name, zone_name_to_log)) {
+ if (z->zone_valid) {
+ z->zone_logging = TRUE;
+ zone_logging_enabled = TRUE;
+ num_zones_logged++;
+ }
+ }
+ }
+ }
+
+ if (log_records_init == FALSE && zone_logging_enabled == 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);
+ log_records_init = TRUE;
+ } else {
+ log_records = ZRECORDS_DEFAULT;
+ log_records_init = TRUE;
+ }
+ }
+
+ /*
+ * 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 (kmem_alloc_ready) {
+
+ zone_t curr_zone = NULL;
+ unsigned int max_zones = 0, zone_idx = 0;
+
+ simple_lock(&all_zones_lock);
+ max_zones = num_zones;
+ simple_unlock(&all_zones_lock);
+
+ for (zone_idx = 0; zone_idx < max_zones; zone_idx++) {
+
+ curr_zone = &(zone_array[zone_idx]);
+
+ if (!curr_zone->zone_valid) {
+ continue;
+ }
+
+ /*
+ * We work with the zone unlocked here because we could end up needing the zone lock to
+ * enable logging for this zone e.g. need a VM object to allocate memory to enable logging for the
+ * VM objects zone.
+ *
+ * We don't expect these zones to be needed at this early a time in boot and so take this chance.
+ */
+ if (curr_zone->zone_logging && curr_zone->zlog_btlog == NULL) {
+
+ curr_zone->zlog_btlog = btlog_create(log_records, MAX_ZTRACE_DEPTH, (corruption_debug_flag == FALSE) /* caller_will_remove_entries_for_element? */);
+
+ if (curr_zone->zlog_btlog) {
+
+ printf("zone: logging started for zone %s\n", curr_zone->zone_name);
+ } else {
+ printf("zone: couldn't allocate memory for zrecords, turning off zleak logging\n");
+ curr_zone->zone_logging = FALSE;
+ }
+ }
+
+ }
+ }
+ }
+
+#if CONFIG_GZALLOC
+ gzalloc_zone_init(z);
+#endif
+
+ return(z);
+}
+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.
+ */
+__attribute__((noreturn))
+static void
+zone_replenish_thread(zone_t z)
+{
+ vm_size_t free_size;
+ current_thread()->options |= TH_OPT_VMPRIV;
+
+ for (;;) {
+ lock_zone(z);
+ assert(z->zone_valid);
+ z->zone_replenishing = TRUE;
+ 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);
+
+ 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;
+
+ /* 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);
+ }
+
+ kr = kernel_memory_allocate(zone_map, &space, alloc_size, 0, zflags, VM_KERN_MEMORY_ZONE);
+
+ if (kr == KERN_SUCCESS) {
+ 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) {
+ 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);
+ }
+ }
+
+ lock_zone(z);
+ assert(z->zone_valid);
+ zone_replenish_loops++;
+ }
+
+ z->zone_replenishing = FALSE;
+ /* Signal any potential throttled consumers, terminating
+ * their timer-bounded waits.
+ */
+ thread_wakeup(z);
+
+ assert_wait(&z->zone_replenish_thread, THREAD_UNINT);
+ unlock_zone(z);
+ 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;
+ OSMemoryBarrier();
+ kern_return_t tres = kernel_thread_start_priority((thread_continue_t)zone_replenish_thread, z, MAXPRI_KERNEL, &z->zone_replenish_thread);
+
+ if (tres != KERN_SUCCESS) {
+ panic("zone_prio_refill_configure, thread create: 0x%x", tres);
+ }
+
+ thread_deallocate(z->zone_replenish_thread);
+}
+
+void
+zdestroy(zone_t z)
+{
+ unsigned int zindex;
+
+ assert(z != NULL);
+
+ lock_zone(z);
+ assert(z->zone_valid);
+
+ /* Assert that the zone does not have any allocations in flight */
+ assert(z->doing_alloc_without_vm_priv == FALSE);
+ assert(z->doing_alloc_with_vm_priv == FALSE);
+ assert(z->async_pending == FALSE);
+ assert(z->waiting == FALSE);
+ assert(z->async_prio_refill == FALSE);
+
+#if !KASAN_ZALLOC
+ /*
+ * 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.
+ */
+ z->zone_valid = FALSE;
+#endif
+ unlock_zone(z);
+
+ /* Dump all the free elements */
+ drop_free_elements(z);
+
+#if CONFIG_GZALLOC
+ /* If the zone is gzalloc managed dump all the elements in the free cache */
+ gzalloc_empty_free_cache(z);
+#endif
+
+ lock_zone(z);
+
+#if !KASAN_ZALLOC
+ /* Assert that all counts are zero */
+ assert(z->count == 0);
+ assert(z->countfree == 0);
+ assert(z->cur_size == 0);
+ assert(z->page_count == 0);
+ assert(z->count_all_free_pages == 0);
+
+ /* Assert that all queues except the foreign queue are empty. The zone allocator doesn't know how to free up foreign memory. */
+ assert(queue_empty(&z->pages.all_used));
+ assert(queue_empty(&z->pages.intermediate));
+ assert(queue_empty(&z->pages.all_free));
+#endif
+
+ zindex = z->index;
+
+ unlock_zone(z);
+
+ simple_lock(&all_zones_lock);
+
+ assert(!bitmap_test(zone_empty_bitmap, zindex));
+ /* Mark the zone as empty in the bitmap */
+ bitmap_set(zone_empty_bitmap, zindex);
+ num_zones_in_use--;
+ assert(num_zones_in_use > 0);
+
+ simple_unlock(&all_zones_lock);
+}
+
+/* Initialize the metadata for an allocation chunk */
+static inline void
+zcram_metadata_init(vm_offset_t newmem, vm_size_t size, struct zone_page_metadata *chunk_metadata)
+{
+ struct zone_page_metadata *page_metadata;
+
+ /* The first page is the real metadata for this allocation chunk. We mark the others as fake metadata */
+ size -= PAGE_SIZE;
+ newmem += PAGE_SIZE;
+
+ for (; size > 0; newmem += PAGE_SIZE, size -= PAGE_SIZE) {
+ page_metadata = get_zone_page_metadata((struct zone_free_element *)newmem, TRUE);
+ assert(page_metadata != chunk_metadata);
+ PAGE_METADATA_SET_ZINDEX(page_metadata, MULTIPAGE_METADATA_MAGIC);
+ page_metadata_set_realmeta(page_metadata, chunk_metadata);
+ page_metadata->free_count = 0;
+ }
+ return;
+}
+
+
+/*
+ * Boolean Random Number Generator for generating booleans to randomize
+ * the order of elements in newly zcram()'ed memory. The algorithm is a
+ * modified version of the KISS RNG proposed in the paper:
+ * http://stat.fsu.edu/techreports/M802.pdf
+ * The modifications have been documented in the technical paper
+ * paper from UCL:
+ * http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf
+ */
+
+static void random_bool_gen_entropy(
+ int *buffer,
+ int count)
+{
+
+ int i, t;
+ simple_lock(&bool_gen_lock);
+ for (i = 0; i < count; i++) {
+ bool_gen_seed[1] ^= (bool_gen_seed[1] << 5);
+ bool_gen_seed[1] ^= (bool_gen_seed[1] >> 7);
+ bool_gen_seed[1] ^= (bool_gen_seed[1] << 22);
+ t = bool_gen_seed[2] + bool_gen_seed[3] + bool_gen_global;
+ bool_gen_seed[2] = bool_gen_seed[3];
+ bool_gen_global = t < 0;
+ bool_gen_seed[3] = t &2147483647;
+ bool_gen_seed[0] += 1411392427;
+ buffer[i] = (bool_gen_seed[0] + bool_gen_seed[1] + bool_gen_seed[3]);
+ }
+ simple_unlock(&bool_gen_lock);
+}
+
+static boolean_t random_bool_gen(
+ int *buffer,
+ int index,
+ int bufsize)
+{
+ int valindex, bitpos;
+ valindex = (index / (8 * sizeof(int))) % bufsize;
+ bitpos = index % (8 * sizeof(int));
+ return (boolean_t)(buffer[valindex] & (1 << bitpos));
+}
+
+static void
+random_free_to_zone(
+ zone_t zone,
+ vm_offset_t newmem,
+ vm_offset_t first_element_offset,
+ int element_count,
+ int *entropy_buffer)
+{
+ vm_offset_t last_element_offset;
+ vm_offset_t element_addr;
+ vm_size_t elem_size;
+ int index;
+
+ assert(element_count <= ZONE_CHUNK_MAXELEMENTS);
+ elem_size = zone->elem_size;
+ last_element_offset = first_element_offset + ((element_count * elem_size) - elem_size);
+ for (index = 0; index < element_count; index++) {
+ assert(first_element_offset <= last_element_offset);
+ if (
+#if DEBUG || DEVELOPMENT
+ leak_scan_debug_flag || __improbable(zone->tags) ||
+#endif /* DEBUG || DEVELOPMENT */
+ random_bool_gen(entropy_buffer, index, MAX_ENTROPY_PER_ZCRAM)) {
+ element_addr = newmem + first_element_offset;
+ first_element_offset += elem_size;
+ } else {
+ element_addr = newmem + last_element_offset;
+ last_element_offset -= elem_size;
+ }
+ if (element_addr != (vm_offset_t)zone) {
+ zone->count++; /* compensate for free_to_zone */
+ free_to_zone(zone, element_addr, FALSE);
+ }
+ zone->cur_size += elem_size;
+ }
+}
+
+/*
+ * 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)
+{
+ vm_size_t elem_size;
+ boolean_t from_zm = FALSE;
+ int element_count;
+ int entropy_buffer[MAX_ENTROPY_PER_ZCRAM];
+
+ /* Basic sanity checks */
+ assert(zone != ZONE_NULL && newmem != (vm_offset_t)0);
+ assert(!zone->collectable || zone->allows_foreign
+ || (from_zone_map(newmem, size)));
+
+ elem_size = zone->elem_size;
+
+ KDBG(MACHDBG_CODE(DBG_MACH_ZALLOC, ZALLOC_ZCRAM) | DBG_FUNC_START, zone->index, size);
+
+ if (from_zone_map(newmem, size))
+ from_zm = TRUE;
+
+ if (!from_zm) {
+ /* 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->allows_foreign == TRUE) && (zone->elem_size <= (PAGE_SIZE - sizeof(struct zone_page_metadata))));
+ }
+
+ 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);
+
+ ZONE_PAGE_COUNT_INCR(zone, (size / PAGE_SIZE));
+
+ random_bool_gen_entropy(entropy_buffer, MAX_ENTROPY_PER_ZCRAM);
+
+ /*
+ * Initialize the metadata for all pages. We dont need the zone lock
+ * here because we are not manipulating any zone related state yet.
+ */
+
+ struct zone_page_metadata *chunk_metadata;
+ size_t zone_page_metadata_size = sizeof(struct zone_page_metadata);
+
+ assert((newmem & PAGE_MASK) == 0);
+ assert((size & PAGE_MASK) == 0);
+
+ chunk_metadata = get_zone_page_metadata((struct zone_free_element *)newmem, TRUE);
+ chunk_metadata->pages.next = NULL;
+ chunk_metadata->pages.prev = NULL;
+ page_metadata_set_freelist(chunk_metadata, 0);
+ PAGE_METADATA_SET_ZINDEX(chunk_metadata, zone->index);
+ chunk_metadata->free_count = 0;
+ assert((size / PAGE_SIZE) <= ZONE_CHUNK_MAXPAGES);
+ chunk_metadata->page_count = (unsigned)(size / PAGE_SIZE);
+
+ zcram_metadata_init(newmem, size, chunk_metadata);
+
+#if VM_MAX_TAG_ZONES
+ if (__improbable(zone->tags)) {
+ assert(from_zm);
+ ztMemoryAdd(zone, newmem, size);
+ }
+#endif /* VM_MAX_TAG_ZONES */
+
+ lock_zone(zone);
+ assert(zone->zone_valid);
+ enqueue_tail(&zone->pages.all_used, &(chunk_metadata->pages));
+
+ if (!from_zm) {
+ /* 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
+ */
+
+ for (; size > 0; newmem += PAGE_SIZE, size -= PAGE_SIZE) {
+ vm_offset_t first_element_offset = 0;
+ 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));
+ }
+ element_count = (int)((PAGE_SIZE - first_element_offset) / elem_size);
+ random_free_to_zone(zone, newmem, first_element_offset, element_count, entropy_buffer);
+ }
+ } else {
+ element_count = (int)(size / elem_size);
+ random_free_to_zone(zone, newmem, 0, element_count, entropy_buffer);
+ }
+ unlock_zone(zone);
+
+ KDBG(MACHDBG_CODE(DBG_MACH_ZALLOC, ZALLOC_ZCRAM) | DBG_FUNC_END, zone->index);
+
+}
+
+/*
+ * Fill a zone with enough memory to contain at least nelem elements.
+ * 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 the next zone allocation size.
+ */
+int
+zfill(
+ zone_t zone,
+ int nelem)
+{
+ kern_return_t kr;
+ vm_offset_t memory;
+
+ vm_size_t alloc_size = zone->alloc_size;
+ vm_size_t elem_per_alloc = alloc_size / zone->elem_size;
+ vm_size_t nalloc = (nelem + elem_per_alloc - 1) / elem_per_alloc;
+
+ /* Don't mix-and-match zfill with foreign memory */
+ assert(!zone->allows_foreign);
+
+ /* 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);
+ }
+
+ kr = kernel_memory_allocate(zone_map, &memory, nalloc * alloc_size, 0, KMA_KOBJECT, VM_KERN_MEMORY_ZONE);
+ if (kr != KERN_SUCCESS) {
+ printf("%s: kernel_memory_allocate() of %lu bytes failed\n",
+ __func__, (unsigned long)(nalloc * alloc_size));
+ return 0;
+ }
+
+ for (vm_size_t i = 0; i < nalloc; i++) {
+ zcram(zone, memory + i * alloc_size, alloc_size);
+ }
+
+ return (int)(nalloc * elem_per_alloc);
+}
+
+/*
+ * Initialize the "zone of zones" which uses fixed memory allocated
+ * earlier in memory initialization. zone_bootstrap is called
+ * before zone_init.
+ */
+void
+zone_bootstrap(void)
+{
+ char temp_buf[16];
+ unsigned int i;
+
+ if (!PE_parse_boot_argn("zalloc_debug", &zalloc_debug, sizeof(zalloc_debug)))
+ zalloc_debug = 0;
+
+ /* Set up zone element poisoning */
+ zp_init();
+
+ /* Seed the random boolean generator for elements in zone free list */
+ for (i = 0; i < RANDOM_BOOL_GEN_SEED_COUNT; i++) {
+ bool_gen_seed[i] = (unsigned int)early_random();
+ }
+ simple_lock_init(&bool_gen_lock, 0);
+
+ /* 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;
+ }
+
+#if DEBUG || DEVELOPMENT
+#if VM_MAX_TAG_ZONES
+ /* enable tags for zones that ask for */
+ if (PE_parse_boot_argn("-zt", temp_buf, sizeof(temp_buf))) {
+ zone_tagging_on = TRUE;
+ }
+#endif /* VM_MAX_TAG_ZONES */
+ /* disable element location randomization in a page */
+ if (PE_parse_boot_argn("-zl", temp_buf, sizeof(temp_buf))) {
+ leak_scan_debug_flag = TRUE;
+ }
+#endif
+
+ simple_lock_init(&all_zones_lock, 0);
+
+ num_zones_in_use = 0;
+ num_zones = 0;
+ /* Mark all zones as empty */
+ bitmap_full(zone_empty_bitmap, BITMAP_LEN(MAX_ZONES));
+ zone_names_next = zone_names_start = 0;
+
+#if DEBUG || DEVELOPMENT
+ simple_lock_init(&zone_test_lock, 0);
+#endif /* DEBUG || DEVELOPMENT */
+
+ thread_call_setup(&call_async_alloc, zalloc_async, 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);
+
+ lck_attr_setdefault(&zone_metadata_lock_attr);
+ lck_mtx_init_ext(&zone_metadata_region_lck, &zone_metadata_region_lck_ext, &zone_locks_grp, &zone_metadata_lock_attr);
+}
+
+/*
+ * 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.
+ */
+unsigned int zone_map_jetsam_limit = ZONE_MAP_JETSAM_LIMIT_DEFAULT;
+
+/*
+ * Returns pid of the task with the largest number of VM map entries.
+ */
+extern pid_t find_largest_process_vm_map_entries(void);
+
+/*
+ * 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.
+ */
+boolean_t memorystatus_kill_on_zone_map_exhaustion(pid_t pid);
+
+void get_zone_map_size(uint64_t *current_size, uint64_t *capacity)
+{
+ *current_size = zone_map->size;
+ *capacity = vm_map_max(zone_map) - vm_map_min(zone_map);
+}
+
+void get_largest_zone_info(char *zone_name, size_t zone_name_len, uint64_t *zone_size)
+{
+ zone_t largest_zone = zone_find_largest();
+ strlcpy(zone_name, largest_zone->zone_name, zone_name_len);
+ *zone_size = largest_zone->cur_size;
+}
+
+boolean_t is_zone_map_nearing_exhaustion(void)
+{
+ uint64_t size = zone_map->size;
+ uint64_t capacity = vm_map_max(zone_map) - vm_map_min(zone_map);
+ if (size > ((capacity * zone_map_jetsam_limit) / 100)) {
+ return TRUE;
+ }
+ return FALSE;
+}
+
+extern zone_t vm_map_entry_zone;
+extern zone_t vm_object_zone;
+
+#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 map size %lld, capacity %lld [jetsam limit %d%%]\n", (uint64_t)zone_map->size,
+ (uint64_t)(vm_map_max(zone_map) - vm_map_min(zone_map)), zone_map_jetsam_limit);
+ printf("zone_map_exhaustion: Largest zone %s, size %lu\n", largest_zone->zone_name, (uintptr_t)largest_zone->cur_size);
+
+ /*
+ * 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);
+
+ /*
+ * 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) {
+ int vm_object_zone_count = vm_object_zone->count;
+ int vm_map_entry_zone_count = vm_map_entry_zone->count;
+ /* 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)largest_zone->cur_size);
+ }
+ }
+
+ /* 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]. Waking up memorystatus thread.\n", largest_zone->zone_name);
+ }
+ if (!memorystatus_kill_on_zone_map_exhaustion(pid)) {
+ printf("zone_map_exhaustion: Call to memorystatus failed, victim pid: %d\n", pid);
+ }
+}
+
+/* Global initialization of Zone Allocator.
+ * Runs after zone_bootstrap.
+ */
+void
+zone_init(
+ vm_size_t max_zonemap_size)
+{
+ kern_return_t retval;
+ vm_offset_t zone_min;
+ vm_offset_t zone_max;
+ vm_offset_t zone_metadata_space;
+ unsigned int zone_pages;
+ vm_map_kernel_flags_t vmk_flags;
+
+#if VM_MAX_TAG_ZONES
+ if (zone_tagging_on) ztInit(max_zonemap_size, &zone_locks_grp);
+#endif
+
+ vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
+ vmk_flags.vmkf_permanent = TRUE;
+ retval = kmem_suballoc(kernel_map, &zone_min, max_zonemap_size,
+ FALSE, VM_FLAGS_ANYWHERE, vmk_flags, VM_KERN_MEMORY_ZONE,
+ &zone_map);
+
+ 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);
+#endif
+ /*
+ * Setup garbage collection information:
+ */
+ zone_map_min_address = zone_min;
+ zone_map_max_address = zone_max;
+
+ zone_pages = (unsigned int)atop_kernel(zone_max - zone_min);
+ zone_metadata_space = round_page(zone_pages * sizeof(struct zone_page_metadata));
+ retval = kernel_memory_allocate(zone_map, &zone_metadata_region_min, zone_metadata_space,
+ 0, KMA_KOBJECT | KMA_VAONLY | KMA_PERMANENT, VM_KERN_MEMORY_OSFMK);
+ if (retval != KERN_SUCCESS)
+ panic("zone_init: zone_metadata_region initialization failed!");
+ zone_metadata_region_max = zone_metadata_region_min + zone_metadata_space;
+
+#if defined(__LP64__)
+ /*
+ * 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
+ */
+ if ((vm_page_t)(VM_PAGE_UNPACK_PTR(VM_PAGE_PACK_PTR(zone_metadata_region_max))) != (vm_page_t)zone_metadata_region_max)
+ panic("VM_PAGE_PACK_PTR failed on zone_metadata_region_max - %p", (void *)zone_metadata_region_max);
+
+ if ((vm_page_t)(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
+
+ 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
+ /*
+ * Initialize the zone leak monitor
+ */
+ zleak_init(max_zonemap_size);
+#endif /* CONFIG_ZLEAKS */
+
+#if VM_MAX_TAG_ZONES
+ if (zone_tagging_on) vm_allocation_zones_init();
+#endif
+
+ int jetsam_limit_temp = 0;
+ if (PE_parse_boot_argn("zone_map_jetsam_limit", &jetsam_limit_temp, sizeof (jetsam_limit_temp)) &&
+ jetsam_limit_temp > 0 && jetsam_limit_temp <= 100)
+ zone_map_jetsam_limit = jetsam_limit_temp;
+}
+
+extern volatile SInt32 kfree_nop_count;
+
+#pragma mark -
+#pragma mark zalloc_canblock
+
+extern boolean_t early_boot_complete;
+
+/*
+ * zalloc returns an element from the specified zone.
+ */
+static void *
+zalloc_internal(
+ zone_t zone,
+ boolean_t canblock,
+ boolean_t nopagewait,
+ vm_size_t
+#if !VM_MAX_TAG_ZONES
+ __unused
+#endif
+ reqsize,
+ vm_tag_t tag)
+{
+ 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;
+ 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 */
+
+#if KASAN
+ /*
+ * KASan uses zalloc() for fakestack, which can be called anywhere. However,
+ * we make sure these calls can never block.
+ */
+ boolean_t irq_safe = FALSE;
+ const char *fakestack_name = "fakestack.";
+ if (strncmp(zone->zone_name, fakestack_name, strlen(fakestack_name)) == 0) {
+ irq_safe = TRUE;
+ }
+#elif MACH_ASSERT
+ /* In every other case, zalloc() from interrupt context is unsafe. */
+ const boolean_t irq_safe = FALSE;
+#endif
+
+ assert(zone != ZONE_NULL);
+ assert(irq_safe || ml_get_interrupts_enabled() || ml_is_quiescing() || debug_mode_active() || !early_boot_complete);
+
+#if CONFIG_GZALLOC
+ addr = gzalloc_alloc(zone, canblock);
+#endif
+ /*
+ * If zone logging is turned on and this is the zone we're tracking, grab a backtrace.
+ */
+ if (__improbable(DO_LOGGING(zone)))
+ numsaved = OSBacktrace((void*) zbt, MAX_ZTRACE_DEPTH);
+
+#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 = backtrace(zbt, MAX_ZTRACE_DEPTH);
+ else
+ zleak_tracedepth = numsaved;
+ }
+#endif /* CONFIG_ZLEAKS */
+
+#if VM_MAX_TAG_ZONES
+ if (__improbable(zone->tags)) vm_tag_will_update_zone(tag, zone->tag_zone_index);
+#endif /* VM_MAX_TAG_ZONES */
+
+ lock_zone(zone);
+ assert(zone->zone_valid);
+
+ if (zone->async_prio_refill && zone->zone_replenish_thread) {
+ 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)) || (zfreec == 0));
+
+ do {
+ if (zone_replenish_wakeup) {
+ zone_replenish_wakeups_initiated++;
+ /* Signal the potentially waiting
+ * refill thread.
+ */
+ thread_wakeup(&zone->zone_replenish_thread);
+
+ /* We don't want to wait around for zone_replenish_thread to bump up the free count
+ * if we're in zone_gc(). This keeps us from deadlocking with zone_replenish_thread.
+ */
+ if (thr->options & TH_OPT_ZONE_GC)
+ break;
+
+ unlock_zone(zone);
+ /* 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);
+ assert(zone->zone_valid);
+ }
+
+ zfreec = (zone->cur_size - (zone->count * zone->elem_size));
+ 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)) || (zfreec == 0));
+
+ } while (zone_alloc_throttle == TRUE);
+ }
+
+ if (__probable(addr == 0))
+ addr = try_alloc_from_zone(zone, tag, &check_poison);
+
+ /* 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 did successfully grab an element. And we only need to assert
+ * this for zones that have a replenish thread configured (in this case, the Reserved VM map
+ * entries zone).
+ */
+ if (thr->options & TH_OPT_ZONE_GC && zone->async_prio_refill)
+ assert(addr != 0);
+
+ while ((addr == 0) && canblock) {
+ /*
+ * 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)) {
+ /*
+ * This is a non-vm_privileged thread and a non-vm_privileged or
+ * a vm_privileged thread is already expanding the zone...
+ * OR
+ * this is a vm_privileged thread and a vm_privileged thread is
+ * already expanding the zone...
+ *
+ * In either case wait for a thread to finish, then try 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);
+ }
+ }
+ /*
+ * 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();
+
+ if ((thr->options & TH_OPT_VMPRIV)) {
+ zone->doing_alloc_with_vm_priv = TRUE;
+ set_doing_alloc_with_vm_priv = TRUE;
+ } else {
+ zone->doing_alloc_without_vm_priv = TRUE;
+ }
+ 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;
+
+ /* 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);
+ }
+
+ retval = kernel_memory_allocate(zone_map, &space, alloc_size, 0, zflags, VM_KERN_MEMORY_ZONE);
+ if (retval == KERN_SUCCESS) {
+#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 == 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;
+ }
+ }
+ lock_zone(zone);
+ assert(zone->zone_valid);
+
+ 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);
+ }
+ clear_thread_rwlock_boost();
+
+ addr = try_alloc_from_zone(zone, tag, &check_poison);
+ if (addr == 0 &&
+ retval == KERN_RESOURCE_SHORTAGE) {
+ if (nopagewait == TRUE)
+ break; /* out of the main while loop */
+ unlock_zone(zone);
+
+ VM_PAGE_WAIT();
+ lock_zone(zone);
+ assert(zone->zone_valid);
+ }
+ }
+ if (addr == 0)
+ addr = try_alloc_from_zone(zone, tag, &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;
+ unlock_zone(zone);
+ thread_call_enter(&call_async_alloc);
+ lock_zone(zone);
+ assert(zone->zone_valid);
+ addr = try_alloc_from_zone(zone, tag, &check_poison);
+ }
+
+#if VM_MAX_TAG_ZONES
+ if (__improbable(zone->tags) && addr) {
+ if (reqsize) reqsize = zone->elem_size - reqsize;
+ vm_tag_update_zone_size(tag, zone->tag_zone_index, zone->elem_size, reqsize);
+ }
+#endif /* VM_MAX_TAG_ZONES */
+
+ unlock_zone(zone);
+
+ vm_offset_t inner_size = zone->elem_size;
+
+ if (__improbable(DO_LOGGING(zone) && addr)) {
+ btlog_add_entry(zone->zlog_btlog, (void *)addr, ZOP_ALLOC, (void **)zbt, numsaved);
+ }
+
+ 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;
+
+#if DEBUG || DEVELOPMENT
+ if (__improbable(leak_scan_debug_flag && !(zone->elem_size & (sizeof(uintptr_t) - 1)))) {
+ int count, idx;
+ /* Fill element, from tail, with backtrace in reverse order */
+ if (numsaved == 0) numsaved = backtrace(zbt, MAX_ZTRACE_DEPTH);
+ count = (int) (zone->elem_size / sizeof(uintptr_t));
+ if (count >= numsaved) count = numsaved - 1;
+ for (idx = 0; idx < count; idx++) ((uintptr_t *)addr)[count - 1 - idx] = zbt[idx + 1];
+ }
+#endif /* DEBUG || DEVELOPMENT */
+ }
+
+ TRACE_MACHLEAKS(ZALLOC_CODE, ZALLOC_CODE_2, zone->elem_size, addr);
+
+#if KASAN_ZALLOC
+ /* Fixup the return address to skip the redzone */
+ if (zone->kasan_redzone) {
+ addr = kasan_alloc(addr, zone->elem_size,
+ zone->elem_size - 2 * zone->kasan_redzone, zone->kasan_redzone);
+ }
+#endif
+
+ return((void *)addr);
+}
+
+void *
+zalloc(zone_t zone)
+{
+ return (zalloc_internal(zone, TRUE, FALSE, 0, VM_KERN_MEMORY_NONE));
+}
+
+void *
+zalloc_noblock(zone_t zone)
+{
+ return (zalloc_internal(zone, FALSE, FALSE, 0, VM_KERN_MEMORY_NONE));
+}
+
+void *
+zalloc_nopagewait(zone_t zone)
+{
+ return (zalloc_internal(zone, TRUE, TRUE, 0, VM_KERN_MEMORY_NONE));
+}
+
+void *
+zalloc_canblock_tag(zone_t zone, boolean_t canblock, vm_size_t reqsize, vm_tag_t tag)
+{
+ return (zalloc_internal(zone, canblock, FALSE, reqsize, tag));
+}
+
+void *
+zalloc_canblock(zone_t zone, boolean_t canblock)
+{
+ return (zalloc_internal(zone, canblock, FALSE, 0, VM_KERN_MEMORY_NONE));
+}
+
+
+void
+zalloc_async(
+ __unused thread_call_param_t p0,
+ __unused thread_call_param_t p1)
+{
+ zone_t current_z = NULL;
+ unsigned int max_zones, i;
+ void *elt = NULL;
+ boolean_t pending = FALSE;
+
+ simple_lock(&all_zones_lock);
+ max_zones = num_zones;
+ simple_unlock(&all_zones_lock);
+ for (i = 0; i < max_zones; i++) {
+ current_z = &(zone_array[i]);
+
+ if (current_z->no_callout == TRUE) {
+ /* async_pending will never be set */
+ continue;
+ }
+
+ lock_zone(current_z);
+ if (current_z->zone_valid && current_z->async_pending == TRUE) {
+ current_z->async_pending = FALSE;
+ pending = TRUE;
+ }
+ unlock_zone(current_z);
+
+ if (pending == TRUE) {
+ elt = zalloc_canblock_tag(current_z, TRUE, 0, VM_KERN_MEMORY_OSFMK);
+ zfree(current_z, elt);
+ pending = FALSE;
+ }
+ }
+}
+
+/*
+ * zget returns an element from the specified zone
+ * and immediately returns nothing if there is nothing there.
+ */
+void *
+zget(
+ zone_t zone)
+{
+ return zalloc_internal(zone, FALSE, TRUE, 0, VM_KERN_MEMORY_NONE);
+}
+
+/* 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)
+{
+ struct zone_free_element *this;
+ struct zone_page_metadata *thispage;
+
+ if (zone->allows_foreign) {
+ for (thispage = (struct zone_page_metadata *)queue_first(&zone->pages.any_free_foreign);
+ !queue_end(&zone->pages.any_free_foreign, &(thispage->pages));
+ thispage = (struct zone_page_metadata *)queue_next(&(thispage->pages))) {
+ for (this = page_metadata_get_freelist(thispage);
+ 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, &(thispage->pages));
+ thispage = (struct zone_page_metadata *)queue_next(&(thispage->pages))) {
+ for (this = page_metadata_get_freelist(thispage);
+ 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, &(thispage->pages));
+ thispage = (struct zone_page_metadata *)queue_next(&(thispage->pages))) {
+ for (this = page_metadata_get_freelist(thispage);
+ this != NULL;
+ this = this->next) {
+ if (!is_sane_zone_element(zone, (vm_address_t)this) || (vm_address_t)this == elem)
+ panic("zone_check_freelist");
+ }
+ }
+}
+
+void
+zfree(
+ 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;
+#if VM_MAX_TAG_ZONES
+ vm_tag_t tag;
+#endif /* VM_MAX_TAG_ZONES */
+
+ assert(zone != ZONE_NULL);
+
+#if KASAN_ZALLOC
+ /*
+ * Resize back to the real allocation size and hand off to the KASan
+ * quarantine. `addr` may then point to a different allocation.
+ */
+ vm_size_t usersz = zone->elem_size - 2 * zone->kasan_redzone;
+ vm_size_t sz = usersz;
+ 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);
+ }
+ if (addr && zone->kasan_quarantine) {
+ kasan_free(&addr, &sz, KASAN_HEAP_ZALLOC, &zone, usersz, true);
+ if (!addr) {
+ return;
+ }
+ }
+ elem = (vm_offset_t)addr;
+#endif
+
+ /*
+ * If zone logging is turned on and this is the zone we're tracking, grab a backtrace.
+ */
+
+ if (__improbable(DO_LOGGING(zone) && corruption_debug_flag))
+ numsaved = OSBacktrace((void *)zbt, MAX_ZTRACE_DEPTH);
+
+#if MACH_ASSERT
+ /* Basic sanity checks */
+ if (zone == ZONE_NULL || elem == (vm_offset_t)0)
+ panic("zfree: NULL");
+#endif
+
+#if CONFIG_GZALLOC
+ gzfreed = gzalloc_free(zone, addr);
+#endif
+
+ if (!gzfreed) {
+ struct zone_page_metadata *page_meta = get_zone_page_metadata((struct zone_free_element *)addr, FALSE);
+ if (zone != PAGE_METADATA_GET_ZONE(page_meta)) {
+ panic("Element %p from zone %s caught being freed to wrong zone %s\n", addr, PAGE_METADATA_GET_ZONE(page_meta)->zone_name, zone->zone_name);
+ }
+ }
+
+ TRACE_MACHLEAKS(ZFREE_CODE, ZFREE_CODE_2, zone->elem_size, (uintptr_t)addr);
+
+ if (__improbable(!gzfreed && zone->collectable && !zone->allows_foreign &&
+ !from_zone_map(elem, zone->elem_size))) {
+ panic("zfree: non-allocated memory in collectable zone!");
+ }
+
+ if ((zp_factor != 0 || zp_tiny_zone_limit != 0) && !gzfreed) {
+ /*
+ * Poison the memory before it ends up on the freelist to catch
+ * use-after-free and use of uninitialized memory
+ *
+ * Always poison tiny zones' elements (limit is 0 if -no-zp is set)
+ * Also poison larger elements periodically
+ */
+
+ vm_offset_t inner_size = zone->elem_size;
+
+ uint32_t sample_factor = zp_factor + (((uint32_t)inner_size) >> zp_scale);
+
+ if (inner_size <= zp_tiny_zone_limit)
+ poison = TRUE;
+ else if (zp_factor != 0 && sample_counter(&zone->zp_count, sample_factor) == TRUE)
+ poison = TRUE;
+
+ if (__improbable(poison)) {
+
+ /* 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);
+
+ for ( ; element_cursor < backup; element_cursor++)
+ *element_cursor = ZP_POISON;
+ }
+ }
+
+ /*
+ * 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.
+ */
+
+ 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(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);
+ }
+ }
+
+ lock_zone(zone);
+ assert(zone->zone_valid);
+
+ if (zone_check) {
+ zone_check_freelist(zone, elem);
+ }
+
+ if (__probable(!gzfreed)) {
+#if VM_MAX_TAG_ZONES
+ if (__improbable(zone->tags)) {
+ tag = (ZTAG(zone, elem)[0] >> 1);
+ // set the tag with b0 clear so the block remains inuse
+ ZTAG(zone, elem)[0] = 0xFFFE;
+ }
+#endif /* VM_MAX_TAG_ZONES */
+ free_to_zone(zone, elem, poison);
+ }
+
+#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);
+#endif
+
+
+#if CONFIG_ZLEAKS
+ /*
+ * Zone leak detection: un-track the allocation
+ */
+ if (zone->zleak_on) {
+ zleak_free(elem, zone->elem_size);
+ }
+#endif /* CONFIG_ZLEAKS */
+
+#if VM_MAX_TAG_ZONES
+ if (__improbable(zone->tags) && __probable(!gzfreed)) {
+ vm_tag_update_zone_size(tag, zone->tag_zone_index, -((int64_t)zone->elem_size), 0);
+ }
+#endif /* VM_MAX_TAG_ZONES */
+
+ unlock_zone(zone);
+}
+
+/* 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)
+{
+ 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_TAGS_ENABLED:
+#if VM_MAX_TAG_ZONES
+ {
+ static int tag_zone_index;
+ zone->tags = TRUE;
+ zone->tags_inline = (((page_size + zone->elem_size - 1) / zone->elem_size) <= (sizeof(uint32_t) / sizeof(uint16_t)));
+ zone->tag_zone_index = OSAddAtomic(1, &tag_zone_index);
+ }
+#endif /* VM_MAX_TAG_ZONES */
+ 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;
+#if KASAN_ZALLOC
+ if (zone->kasan_redzone == KASAN_GUARD_SIZE) {
+ /* Don't disturb alignment with the redzone for zones with
+ * specific alignment requirements. */
+ zone->elem_size -= zone->kasan_redzone * 2;
+ zone->kasan_redzone = 0;