X-Git-Url: https://git.saurik.com/apple/xnu.git/blobdiff_plain/a39ff7e25e19b3a8c3020042a3872ca9ec9659f1..c6bf4f310a33a9262d455ea4d3f0630b1255e3fe:/osfmk/kern/zalloc.c?ds=inline diff --git a/osfmk/kern/zalloc.c b/osfmk/kern/zalloc.c index 8da4fe3c8..f25e40407 100644 --- a/osfmk/kern/zalloc.c +++ b/osfmk/kern/zalloc.c @@ -1,8 +1,8 @@ /* - * Copyright (c) 2000-2016 Apple Inc. All rights reserved. + * Copyright (c) 2000-2019 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 @@ -11,10 +11,10 @@ * 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, @@ -22,34 +22,34 @@ * 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. */ @@ -70,7 +70,6 @@ #include #include #include -#include #include #include @@ -102,17 +101,27 @@ #include #include +#include #include #include +/* + * 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_t zone_locks_grp; +lck_grp_attr_t zone_locks_grp_attr; + /* * ZONE_ALIAS_ADDR (deprecated) */ #define from_zone_map(addr, size) \ - ((vm_offset_t)(addr) >= zone_map_min_address && \ - ((vm_offset_t)(addr) + size - 1) < zone_map_max_address ) + ((vm_offset_t)(addr) >= zone_map_min_address && \ + ((vm_offset_t)(addr) + size - 1) < zone_map_max_address ) /* * Zone Corruption Debugging @@ -179,7 +188,6 @@ sample_counter(volatile uint32_t * count_p, uint32_t factor) } else { rolled_over = FALSE; } - } while (!OSCompareAndSwap(old_count, new_count, count_p)); return rolled_over; @@ -191,6 +199,9 @@ sample_counter(volatile uint32_t * count_p, uint32_t factor) #define ZP_POISON 0xdeadbeef #endif +boolean_t zfree_poison_element(zone_t zone, vm_offset_t elem); +void zalloc_poison_element(boolean_t check_poison, zone_t zone, vm_offset_t addr); + #define ZP_DEFAULT_SAMPLING_FACTOR 16 #define ZP_DEFAULT_SCALE_FACTOR 4 @@ -202,7 +213,12 @@ sample_counter(volatile uint32_t * count_p, uint32_t factor) */ /* set by zp-factor=N boot arg, zero indicates non-tiny poisoning disabled */ -uint32_t zp_factor = 0; +#if DEBUG +#define DEFAULT_ZP_FACTOR (1) +#else +#define DEFAULT_ZP_FACTOR (0) +#endif +uint32_t zp_factor = DEFAULT_ZP_FACTOR; /* set by zp-scale=N boot arg, scales zp_factor by zone size */ uint32_t zp_scale = 0; @@ -218,6 +234,7 @@ uintptr_t zp_nopoison_cookie = 0; boolean_t zone_tagging_on; #endif /* VM_MAX_TAG_ZONES */ +SECURITY_READ_ONLY_LATE(boolean_t) copyio_zalloc_check = TRUE; static struct bool_gen zone_bool_gen; /* @@ -257,10 +274,11 @@ zp_init(void) if (zp_factor != 0) { uint32_t rand_bits = early_random() & 0x3; - if (rand_bits == 0x1) + if (rand_bits == 0x1) { zp_factor += 1; - else if (rand_bits == 0x2) + } else if (rand_bits == 0x2) { zp_factor -= 1; + } /* if 0x0 or 0x3, leave it alone */ } @@ -290,9 +308,10 @@ zp_init(void) zp_nopoison_cookie = (uintptr_t) early_random(); #if MACH_ASSERT - if (zp_poisoned_cookie == zp_nopoison_cookie) + 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); + (void *) zp_poisoned_cookie, (void *) zp_nopoison_cookie); + } #endif /* @@ -328,14 +347,14 @@ zp_init(void) * of pages being used by the zone currently. The * z->page_count is not protected by the zone lock. */ -#define ZONE_PAGE_COUNT_INCR(z, count) \ -{ \ - OSAddAtomic64(count, &(z->page_count)); \ +#define ZONE_PAGE_COUNT_INCR(z, count) \ +{ \ + OSAddAtomic64(count, &(z->page_count)); \ } -#define ZONE_PAGE_COUNT_DECR(z, count) \ -{ \ - OSAddAtomic64(-count, &(z->page_count)); \ +#define ZONE_PAGE_COUNT_DECR(z, count) \ +{ \ + OSAddAtomic64(-count, &(z->page_count)); \ } vm_map_t zone_map = VM_MAP_NULL; @@ -346,14 +365,14 @@ vm_offset_t zone_map_min_address = 0; /* initialized in zone_init */ vm_offset_t zone_map_max_address = 0; /* Globals for random boolean generator for elements in free list */ -#define MAX_ENTROPY_PER_ZCRAM 4 +#define MAX_ENTROPY_PER_ZCRAM 4 /* VM region for all metadata structures */ -vm_offset_t zone_metadata_region_min = 0; -vm_offset_t zone_metadata_region_max = 0; -decl_lck_mtx_data(static ,zone_metadata_region_lck) +vm_offset_t zone_metadata_region_min = 0; +vm_offset_t zone_metadata_region_max = 0; +decl_lck_mtx_data(static, zone_metadata_region_lck); lck_attr_t zone_metadata_lock_attr; -lck_mtx_ext_t zone_metadata_region_lck_ext; +lck_mtx_ext_t zone_metadata_region_lck_ext; /* Helpful for walking through a zone's free element list. */ struct zone_free_element { @@ -362,14 +381,40 @@ struct zone_free_element { /* void *backup_ptr; */ }; +#if CONFIG_ZCACHE + +/* + * Decides whether per-cpu zone caching is to be enabled for all zones. + * Can be set to TRUE via the boot-arg '-zcache_all'. + */ +bool cache_all_zones = FALSE; + +/* + * Specifies a single zone to enable CPU caching for. + * Can be set using boot-args: zcc_enable_for_zone_name= + */ +static char cache_zone_name[MAX_ZONE_NAME]; + +static inline bool +zone_caching_enabled(zone_t z) +{ + return z->cpu_cache_enabled && !z->tags && !z->zleak_on; +} + +#endif /* CONFIG_ZCACHE */ + /* * Protects zone_array, num_zones, num_zones_in_use, and zone_empty_bitmap */ -decl_simple_lock_data(, all_zones_lock) +decl_simple_lock_data(, all_zones_lock); unsigned int num_zones_in_use; unsigned int num_zones; +#if KASAN +#define MAX_ZONES 512 +#else /* !KASAN */ #define MAX_ZONES 320 +#endif/* !KASAN */ struct zone zone_array[MAX_ZONES]; /* Used to keep track of empty slots in the zone_array */ @@ -381,71 +426,72 @@ bitmap_t zone_empty_bitmap[BITMAP_LEN(MAX_ZONES)]; * 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. */ -decl_simple_lock_data(, zone_test_lock) +decl_simple_lock_data(, zone_test_lock); static boolean_t zone_test_running = FALSE; static zone_t test_zone_ptr = NULL; #endif /* DEBUG || DEVELOPMENT */ -#define PAGE_METADATA_GET_ZINDEX(page_meta) \ +#define PAGE_METADATA_GET_ZINDEX(page_meta) \ (page_meta->zindex) -#define PAGE_METADATA_GET_ZONE(page_meta) \ +#define PAGE_METADATA_GET_ZONE(page_meta) \ (&(zone_array[page_meta->zindex])) -#define PAGE_METADATA_SET_ZINDEX(page_meta, index) \ +#define PAGE_METADATA_SET_ZINDEX(page_meta, index) \ page_meta->zindex = (index); struct zone_page_metadata { - queue_chain_t pages; /* linkage pointer for metadata lists */ + queue_chain_t pages; /* linkage pointer for metadata lists */ /* Union for maintaining start of element free list and real metadata (for multipage allocations) */ union { - /* - * The start of the freelist can be maintained as a 32-bit offset instead of a pointer because - * the free elements would be at max ZONE_MAX_ALLOC_SIZE bytes away from the metadata. Offset + /* + * The start of the freelist can be maintained as a 32-bit offset instead of a pointer because + * the free elements would be at max ZONE_MAX_ALLOC_SIZE bytes away from the metadata. Offset * from start of the allocation chunk to free element list head. */ - uint32_t freelist_offset; - /* - * This field is used to lookup the real metadata for multipage allocations, where we mark the - * metadata for all pages except the first as "fake" metadata using MULTIPAGE_METADATA_MAGIC. + uint32_t freelist_offset; + /* + * This field is used to lookup the real metadata for multipage allocations, where we mark the + * metadata for all pages except the first as "fake" metadata using MULTIPAGE_METADATA_MAGIC. * Offset from this fake metadata to real metadata of allocation chunk (-ve offset). */ - uint32_t real_metadata_offset; + uint32_t real_metadata_offset; }; - /* - * For the first page in the allocation chunk, this represents the total number of free elements in - * the chunk. + /* + * For the first page in the allocation chunk, this represents the total number of free elements in + * the chunk. */ - uint16_t free_count; - unsigned zindex : ZINDEX_BITS; /* Zone index within the zone_array */ - unsigned page_count : PAGECOUNT_BITS; /* Count of pages within the allocation chunk */ + uint16_t free_count; + unsigned zindex : ZINDEX_BITS; /* Zone index within the zone_array */ + unsigned page_count : PAGECOUNT_BITS; /* Count of pages within the allocation chunk */ }; /* Macro to get page index (within zone_map) of page containing element */ -#define PAGE_INDEX_FOR_ELEMENT(element) \ +#define PAGE_INDEX_FOR_ELEMENT(element) \ (((vm_offset_t)trunc_page(element) - zone_map_min_address) / PAGE_SIZE) /* Macro to get metadata structure given a page index in zone_map */ -#define PAGE_METADATA_FOR_PAGE_INDEX(index) \ +#define PAGE_METADATA_FOR_PAGE_INDEX(index) \ (zone_metadata_region_min + ((index) * sizeof(struct zone_page_metadata))) /* Macro to get index (within zone_map) for given metadata */ -#define PAGE_INDEX_FOR_METADATA(page_meta) \ +#define PAGE_INDEX_FOR_METADATA(page_meta) \ (((vm_offset_t)page_meta - zone_metadata_region_min) / sizeof(struct zone_page_metadata)) /* Macro to get page for given page index in zone_map */ -#define PAGE_FOR_PAGE_INDEX(index) \ - (zone_map_min_address + (PAGE_SIZE * (index))) +#define PAGE_FOR_PAGE_INDEX(index) \ + (zone_map_min_address + (PAGE_SIZE * (index))) /* Macro to get the actual metadata for a given address */ -#define PAGE_METADATA_FOR_ELEMENT(element) \ +#define PAGE_METADATA_FOR_ELEMENT(element) \ (struct zone_page_metadata *)(PAGE_METADATA_FOR_PAGE_INDEX(PAGE_INDEX_FOR_ELEMENT(element))) /* Magic value to indicate empty element free list */ -#define PAGE_METADATA_EMPTY_FREELIST ((uint32_t)(~0)) +#define PAGE_METADATA_EMPTY_FREELIST ((uint32_t)(~0)) +vm_map_copy_t create_vm_map_copy(vm_offset_t start_addr, vm_size_t total_size, vm_size_t used_size); boolean_t get_zone_info(zone_t z, mach_zone_name_t *zn, mach_zone_info_t *zi); boolean_t is_zone_map_nearing_exhaustion(void); extern void vm_pageout_garbage_collect(int collect); @@ -454,13 +500,14 @@ static inline void * page_metadata_get_freelist(struct zone_page_metadata *page_meta) { assert(PAGE_METADATA_GET_ZINDEX(page_meta) != MULTIPAGE_METADATA_MAGIC); - if (page_meta->freelist_offset == PAGE_METADATA_EMPTY_FREELIST) + if (page_meta->freelist_offset == PAGE_METADATA_EMPTY_FREELIST) { return NULL; - else { - if (from_zone_map(page_meta, sizeof(struct zone_page_metadata))) + } else { + if (from_zone_map(page_meta, sizeof(struct zone_page_metadata))) { return (void *)(PAGE_FOR_PAGE_INDEX(PAGE_INDEX_FOR_METADATA(page_meta)) + page_meta->freelist_offset); - else + } else { return (void *)((vm_offset_t)page_meta + page_meta->freelist_offset); + } } } @@ -468,13 +515,14 @@ static inline void page_metadata_set_freelist(struct zone_page_metadata *page_meta, void *addr) { assert(PAGE_METADATA_GET_ZINDEX(page_meta) != MULTIPAGE_METADATA_MAGIC); - if (addr == NULL) + if (addr == NULL) { page_meta->freelist_offset = PAGE_METADATA_EMPTY_FREELIST; - else { - if (from_zone_map(page_meta, sizeof(struct zone_page_metadata))) + } else { + if (from_zone_map(page_meta, sizeof(struct zone_page_metadata))) { page_meta->freelist_offset = (uint32_t)((vm_offset_t)(addr) - PAGE_FOR_PAGE_INDEX(PAGE_INDEX_FOR_METADATA(page_meta))); - else + } else { page_meta->freelist_offset = (uint32_t)((vm_offset_t)(addr) - (vm_offset_t)page_meta); + } } } @@ -485,46 +533,55 @@ page_metadata_get_realmeta(struct zone_page_metadata *page_meta) return (struct zone_page_metadata *)((vm_offset_t)page_meta - page_meta->real_metadata_offset); } -static inline void +static inline void page_metadata_set_realmeta(struct zone_page_metadata *page_meta, struct zone_page_metadata *real_meta) { - assert(PAGE_METADATA_GET_ZINDEX(page_meta) == MULTIPAGE_METADATA_MAGIC); - assert(PAGE_METADATA_GET_ZINDEX(real_meta) != MULTIPAGE_METADATA_MAGIC); - assert((vm_offset_t)page_meta > (vm_offset_t)real_meta); - vm_offset_t offset = (vm_offset_t)page_meta - (vm_offset_t)real_meta; - assert(offset <= UINT32_MAX); - page_meta->real_metadata_offset = (uint32_t)offset; + assert(PAGE_METADATA_GET_ZINDEX(page_meta) == MULTIPAGE_METADATA_MAGIC); + assert(PAGE_METADATA_GET_ZINDEX(real_meta) != MULTIPAGE_METADATA_MAGIC); + assert((vm_offset_t)page_meta > (vm_offset_t)real_meta); + vm_offset_t offset = (vm_offset_t)page_meta - (vm_offset_t)real_meta; + assert(offset <= UINT32_MAX); + page_meta->real_metadata_offset = (uint32_t)offset; } /* 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) + vm_offset_t *element) { return (vm_offset_t *) ((vm_offset_t)element + elem_size - sizeof(vm_offset_t)); } -/* +/* * 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. + * Must be called without the zone lock held as it might potentially block. */ static inline void -zone_populate_metadata_page(struct zone_page_metadata *page_meta) +zone_populate_metadata_page(struct zone_page_metadata *page_meta) { vm_offset_t page_metadata_begin = trunc_page(page_meta); vm_offset_t page_metadata_end = trunc_page((vm_offset_t)page_meta + sizeof(struct zone_page_metadata)); - - for(;page_metadata_begin <= page_metadata_end; page_metadata_begin += PAGE_SIZE) { - if (pmap_find_phys(kernel_pmap, (vm_map_address_t)page_metadata_begin)) + + for (; page_metadata_begin <= page_metadata_end; page_metadata_begin += PAGE_SIZE) { +#if !KASAN + /* + * 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, (vm_map_address_t)page_metadata_begin)) { continue; + } +#endif /* 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, (vm_map_address_t)page_metadata_begin)) { - kern_return_t __unused ret = kernel_memory_populate(zone_map, - page_metadata_begin, - PAGE_SIZE, - KMA_KOBJECT, - VM_KERN_MEMORY_OSFMK); + kern_return_t __assert_only ret = kernel_memory_populate(zone_map, + page_metadata_begin, + PAGE_SIZE, + KMA_KOBJECT, + VM_KERN_MEMORY_OSFMK); /* should not fail with the given arguments */ assert(ret == KERN_SUCCESS); @@ -537,13 +594,13 @@ zone_populate_metadata_page(struct zone_page_metadata *page_meta) static inline uint16_t get_metadata_alloc_count(struct zone_page_metadata *page_meta) { - assert(PAGE_METADATA_GET_ZINDEX(page_meta) != MULTIPAGE_METADATA_MAGIC); - struct zone *z = PAGE_METADATA_GET_ZONE(page_meta); - return ((page_meta->page_count * PAGE_SIZE) / z->elem_size); + assert(PAGE_METADATA_GET_ZINDEX(page_meta) != MULTIPAGE_METADATA_MAGIC); + struct zone *z = PAGE_METADATA_GET_ZONE(page_meta); + return (page_meta->page_count * PAGE_SIZE) / z->elem_size; } -/* - * Routine to lookup metadata for any given address. +/* + * Routine to lookup metadata for any given address. * If init is marked as TRUE, this should be called without holding the zone lock * since the initialization might block. */ @@ -552,26 +609,54 @@ get_zone_page_metadata(struct zone_free_element *element, boolean_t init) { struct zone_page_metadata *page_meta = 0; - if (from_zone_map(element, sizeof(struct zone_free_element))) { + if (from_zone_map(element, sizeof(struct zone_free_element))) { page_meta = (struct zone_page_metadata *)(PAGE_METADATA_FOR_ELEMENT(element)); - if (init) + if (init) { zone_populate_metadata_page(page_meta); + } } else { page_meta = (struct zone_page_metadata *)(trunc_page((vm_offset_t)element)); } - if (init) - __nosan_bzero((char *)page_meta, sizeof(struct zone_page_metadata)); - return ((PAGE_METADATA_GET_ZINDEX(page_meta) != MULTIPAGE_METADATA_MAGIC) ? page_meta : page_metadata_get_realmeta(page_meta)); + if (init) { + bzero((char *)page_meta, sizeof(struct zone_page_metadata)); + } + return (PAGE_METADATA_GET_ZINDEX(page_meta) != MULTIPAGE_METADATA_MAGIC) ? page_meta : page_metadata_get_realmeta(page_meta); } /* Routine to get the page for a given metadata */ static inline vm_offset_t get_zone_page(struct zone_page_metadata *page_meta) { - if (from_zone_map(page_meta, sizeof(struct zone_page_metadata))) + if (from_zone_map(page_meta, sizeof(struct zone_page_metadata))) { return (vm_offset_t)(PAGE_FOR_PAGE_INDEX(PAGE_INDEX_FOR_METADATA(page_meta))); - else + } else { return (vm_offset_t)(trunc_page(page_meta)); + } +} + +/* + * Routine 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. + */ + +void +zone_require(void *addr, zone_t expected_zone) +{ + struct zone *src_zone = NULL; + struct zone_page_metadata *page_meta = get_zone_page_metadata((struct zone_free_element *)addr, FALSE); + + src_zone = PAGE_METADATA_GET_ZONE(page_meta); + if (__improbable(src_zone == NULL)) { + panic("Address not in a zone for zone_require check (addr: %p)", addr); + } + + if (__improbable(src_zone != expected_zone)) { + panic("Address not in expected zone for zone_require check (addr: %p, zone: %s)", addr, src_zone->zone_name); + } } /* @@ -592,14 +677,14 @@ get_zone_page(struct zone_page_metadata *page_meta) // 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) result++; \ - } else { \ - result = &((vm_tag_t *)zone_tags_min)[ZTAGBASE((zone), (element))[0] + ((element) & page_mask) / (zone)->elem_size]; \ - } \ - result; \ + vm_tag_t * result; \ + if ((zone)->tags_inline) { \ + result = (vm_tag_t *) ZTAGBASE((zone), (element)); \ + if ((page_mask & element) >= (zone)->elem_size) result++; \ + } else { \ + result = &((vm_tag_t *)zone_tags_min)[ZTAGBASE((zone), (element))[0] + ((element) & page_mask) / (zone)->elem_size]; \ + } \ + result; \ }) @@ -615,21 +700,19 @@ static vm_map_t zone_tags_map; // simple heap allocator for allocating the tags for new memory -decl_lck_mtx_data(,ztLock) /* heap lock */ -enum -{ - ztFreeIndexCount = 8, - ztFreeIndexMax = (ztFreeIndexCount - 1), - ztTagsPerBlock = 4 +decl_lck_mtx_data(, ztLock); /* heap lock */ +enum{ + ztFreeIndexCount = 8, + ztFreeIndexMax = (ztFreeIndexCount - 1), + ztTagsPerBlock = 4 }; -struct ztBlock -{ +struct ztBlock { #if __LITTLE_ENDIAN__ - uint64_t free:1, - next:21, - prev:21, - size:21; + uint64_t free:1, + next:21, + prev:21, + size:21; #else // ztBlock needs free bit least significant #error !__LITTLE_ENDIAN__ @@ -644,54 +727,56 @@ static uint32_t ztBlocksFree; static uint32_t ztLog2up(uint32_t size) { - if (1 == size) size = 0; - else size = 32 - __builtin_clz(size - 1); - return (size); + if (1 == size) { + size = 0; + } else { + size = 32 - __builtin_clz(size - 1); + } + return size; } static uint32_t ztLog2down(uint32_t size) { - size = 31 - __builtin_clz(size); - return (size); + size = 31 - __builtin_clz(size); + return size; } 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); - } - } + 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); + } + } } 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); + 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; } @@ -700,40 +785,43 @@ 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"); + 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"); + } } @@ -745,254 +833,267 @@ ztDump(boolean_t sanity) 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; - } + 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); + 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; } static void ztInit(vm_size_t max_zonemap_size, lck_grp_t * group) { - kern_return_t ret; - vm_map_kernel_flags_t vmk_flags; - uint32_t idx; - - lck_mtx_init(&ztLock, group, LCK_ATTR_NULL); - - // 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); + kern_return_t ret; + vm_map_kernel_flags_t vmk_flags; + uint32_t idx; + + lck_mtx_init(&ztLock, group, LCK_ATTR_NULL); + + // 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); - 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++) - { - tagbase[idx] = block + (uint32_t)((ptoa(idx) + (zone->elem_size - 1)) / zone->elem_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); + 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++) { + tagbase[idx] = block + (uint32_t)((ptoa(idx) + (zone->elem_size - 1)) / zone->elem_size); + } + } } 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); - blocks = ((count + ztTagsPerBlock - 1) / ztTagsPerBlock); - assert(block != 0xFFFFFFFF); - block /= ztTagsPerBlock; - ztFree(NULL /* zone is unlocked */, block, blocks); - } - - lck_mtx_unlock(&ztLock); + 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); + 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) { - zone_t z; - uint32_t idx; + zone_t z; + uint32_t idx; - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); - for (idx = 0; idx < num_zones; idx++) - { + for (idx = 0; idx < num_zones; idx++) { z = &(zone_array[idx]); - if (!z->tags) continue; - if (tag_zone_index != z->tag_zone_index) continue; - *elem_size = z->elem_size; - break; - } + if (!z->tags) { + continue; + } + if (tag_zone_index != z->tag_zone_index) { + continue; + } + *elem_size = z->elem_size; + break; + } - simple_unlock(&all_zones_lock); + simple_unlock(&all_zones_lock); - if (idx == num_zones) idx = -1U; + if (idx == num_zones) { + idx = -1U; + } - return (idx); + return idx; } #endif /* VM_MAX_TAG_ZONES */ -/* Routine to get the size of a zone allocated address. If the address doesnt belong to the +/* Routine to get the size of a zone allocated address. If the address doesnt belong to the * zone_map, returns 0. */ vm_size_t @@ -1005,7 +1106,7 @@ zone_element_size(void *addr, zone_t *z) if (z) { *z = src_zone; } - return (src_zone->elem_size); + return src_zone->elem_size; } else { #if CONFIG_GZALLOC vm_size_t gzsize; @@ -1031,9 +1132,9 @@ zone_element_info(void *addr, vm_tag_t * ptag) struct zone_page_metadata *page_meta = get_zone_page_metadata((struct zone_free_element *)addr, FALSE); src_zone = PAGE_METADATA_GET_ZONE(page_meta); #if VM_MAX_TAG_ZONES - if (__improbable(src_zone->tags)) { + if (__improbable(src_zone->tags)) { tag = (ZTAG(src_zone, (vm_offset_t) addr)[0] >> 1); - } + } #endif /* VM_MAX_TAG_ZONES */ size = src_zone->elem_size; } else { @@ -1053,17 +1154,19 @@ zone_element_info(void *addr, vm_tag_t * ptag) * 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) +is_sane_zone_ptr(zone_t zone, + vm_offset_t addr, + size_t obj_size) { /* Must be aligned to pointer boundary */ - if (__improbable((addr & (sizeof(vm_offset_t) - 1)) != 0)) + if (__improbable((addr & (sizeof(vm_offset_t) - 1)) != 0)) { return FALSE; + } /* Must be a kernel address */ - if (__improbable(!pmap_kernel_va(addr))) + if (__improbable(!pmap_kernel_va(addr))) { return FALSE; + } /* Must be from zone map if the zone only uses memory from the zone_map */ /* @@ -1072,9 +1175,10 @@ is_sane_zone_ptr(zone_t zone, */ if (zone->collectable && !zone->allows_foreign) { /* check if addr is from zone map */ - if (addr >= zone_map_min_address && - (addr + obj_size - 1) < zone_map_max_address ) + if (addr >= zone_map_min_address && + (addr + obj_size - 1) < zone_map_max_address) { return TRUE; + } return FALSE; } @@ -1083,56 +1187,59 @@ is_sane_zone_ptr(zone_t zone, } static inline boolean_t -is_sane_zone_page_metadata(zone_t zone, - vm_offset_t page_meta) +is_sane_zone_page_metadata(zone_t zone, + vm_offset_t page_meta) { /* NULL page metadata structures are invalid */ - if (page_meta == 0) + if (page_meta == 0) { return FALSE; + } return is_sane_zone_ptr(zone, page_meta, sizeof(struct zone_page_metadata)); } static inline boolean_t is_sane_zone_element(zone_t zone, - vm_offset_t addr) + vm_offset_t addr) { /* NULL is OK because it indicates the tail of the list */ - if (addr == 0) + if (addr == 0) { return TRUE; + } return is_sane_zone_ptr(zone, addr, zone->elem_size); } - + /* Someone wrote to freed memory. */ -static inline void /* noreturn */ +__dead2 +static inline 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) + 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); + 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); } /* * 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 */ +__dead2 +static void backup_ptr_mismatch_panic(zone_t zone, - vm_offset_t element, - vm_offset_t primary, - vm_offset_t backup) + vm_offset_t element, + vm_offset_t primary, + vm_offset_t backup) { vm_offset_t likely_backup; vm_offset_t likely_primary; @@ -1144,10 +1251,11 @@ backup_ptr_mismatch_panic(zone_t zone, #if defined(__LP64__) /* We can inspect the tag in the upper bits for additional confirmation */ - if ((backup & 0xFFFFFF0000000000) == 0xFACADE0000000000) + if ((backup & 0xFFFFFF0000000000) == 0xFACADE0000000000) { element_was_poisoned = TRUE; - else if ((backup & 0xFFFFFF0000000000) == 0xC0FFEE0000000000) + } else if ((backup & 0xFFFFFF0000000000) == 0xC0FFEE0000000000) { element_was_poisoned = FALSE; + } #endif if (element_was_poisoned) { @@ -1159,14 +1267,16 @@ backup_ptr_mismatch_panic(zone_t zone, } /* The primary is definitely the corrupted one */ - if (!sane_primary && sane_backup) + 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) + 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 - sizeof(vm_offset_t)); + (likely_primary ^ (element_was_poisoned ? zp_poisoned_cookie : zp_nopoison_cookie)), + zone->elem_size - sizeof(vm_offset_t)); + } /* * Not sure which is the corrupted one. @@ -1174,8 +1284,9 @@ backup_ptr_mismatch_panic(zone_t zone, * ( (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) + 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); @@ -1187,8 +1298,8 @@ backup_ptr_mismatch_panic(zone_t zone, */ static inline void free_to_zone(zone_t zone, - vm_offset_t element, - boolean_t poison) + vm_offset_t element, + boolean_t poison) { vm_offset_t old_head; struct zone_page_metadata *page_meta; @@ -1200,16 +1311,20 @@ free_to_zone(zone_t zone, assert(PAGE_METADATA_GET_ZONE(page_meta) == zone); old_head = (vm_offset_t)page_metadata_get_freelist(page_meta); -#if MACH_ASSERT - if (__improbable(!is_sane_zone_element(zone, old_head))) + 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); -#endif + (void *) old_head, zone->zone_name); + } - if (__improbable(!is_sane_zone_element(zone, element))) + if (__improbable(!is_sane_zone_element(zone, element))) { panic("zfree: freeing invalid pointer %p to zone %s\n", - (void *) element, zone->zone_name); + (void *) element, zone->zone_name); + } + if (__improbable(old_head == element)) { + panic("zfree: double free of %p to zone %s\n", + (void *) element, zone->zone_name); + } /* * Always write a redundant next pointer * So that it is more difficult to forge, xor it with a random cookie @@ -1219,9 +1334,9 @@ free_to_zone(zone_t zone, *backup = old_head ^ (poison ? zp_poisoned_cookie : zp_nopoison_cookie); - /* - * 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 + /* + * 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; @@ -1258,8 +1373,8 @@ free_to_zone(zone_t zone, */ static inline vm_offset_t try_alloc_from_zone(zone_t zone, - vm_tag_t tag __unused, - boolean_t* check_poison) + vm_tag_t tag __unused, + boolean_t* check_poison) { vm_offset_t element; struct zone_page_metadata *page_meta; @@ -1267,11 +1382,11 @@ try_alloc_from_zone(zone_t zone, *check_poison = FALSE; /* if zone is empty, bail */ - if (zone->allows_foreign && !queue_empty(&zone->pages.any_free_foreign)) + 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)) + } 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)) { + } else if (!queue_empty(&zone->pages.all_free)) { page_meta = (struct zone_page_metadata *)queue_first(&zone->pages.all_free); assert(zone->count_all_free_pages >= page_meta->page_count); zone->count_all_free_pages -= page_meta->page_count; @@ -1279,20 +1394,22 @@ try_alloc_from_zone(zone_t zone, return 0; } /* Check if page_meta passes is_sane_zone_element */ - if (__improbable(!is_sane_zone_page_metadata(zone, (vm_offset_t)page_meta))) + 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); + (void *) page_meta, zone->zone_name); + } assert(PAGE_METADATA_GET_ZONE(page_meta) == zone); element = (vm_offset_t)page_metadata_get_freelist(page_meta); - if (__improbable(!is_sane_zone_ptr(zone, element, zone->elem_size))) + if (__improbable(!is_sane_zone_ptr(zone, element, zone->elem_size))) { panic("zfree: invalid head pointer %p for freelist of zone %s\n", - (void *) element, zone->zone_name); + (void *) element, zone->zone_name); + } vm_offset_t *primary = (vm_offset_t *) element; vm_offset_t *backup = get_backup_ptr(zone->elem_size, primary); - /* + /* * Since the primary next pointer is xor'ed with zp_nopoison_cookie * for obfuscation, retrieve the original value back */ @@ -1304,16 +1421,17 @@ try_alloc_from_zone(zone_t zone, * 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))) + if (__improbable(!is_sane_zone_element(zone, next_element))) { backup_ptr_mismatch_panic(zone, element, next_element_primary, next_element_backup); + } /* Check the backup pointer for the regular cookie */ if (__improbable(next_element != (next_element_backup ^ zp_nopoison_cookie))) { - /* Check for the poisoned cookie instead */ - if (__improbable(next_element != (next_element_backup ^ zp_poisoned_cookie))) + 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_primary, next_element_backup); + } /* * Element was marked as poisoned, so check its integrity before using it. @@ -1322,15 +1440,17 @@ try_alloc_from_zone(zone_t zone, } /* 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, FALSE))) + if (__improbable(page_meta != get_zone_page_metadata((struct zone_free_element *)element, FALSE))) { panic("zalloc: Incorrect metadata %p found in zone %s page queue. Expected metadata: %p\n", - page_meta, zone->zone_name, get_zone_page_metadata((struct zone_free_element *)element, FALSE)); + page_meta, zone->zone_name, get_zone_page_metadata((struct zone_free_element *)element, FALSE)); + } /* 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, FALSE))) + if (__improbable(page_meta != get_zone_page_metadata((struct zone_free_element *)next_element, FALSE))) { 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); + (void *)next_element, (void *)element, zone->zone_name); + } } /* Remove this element from the free list */ @@ -1353,10 +1473,10 @@ try_alloc_from_zone(zone_t zone, zone->sum_count++; #if VM_MAX_TAG_ZONES - if (__improbable(zone->tags)) { + if (__improbable(zone->tags)) { // set the tag with b0 clear so the block remains inuse ZTAG(zone, element)[0] = (tag << 1); - } + } #endif /* VM_MAX_TAG_ZONES */ @@ -1374,26 +1494,26 @@ try_alloc_from_zone(zone_t zone, /* * Zone info options */ -#define ZINFO_SLOTS MAX_ZONES /* for now */ +#define ZINFO_SLOTS MAX_ZONES /* for now */ -zone_t zone_find_largest(void); +zone_t zone_find_largest(void); -/* - * Async allocation of zones - * This mechanism allows for bootstrapping an empty zone which is setup with +/* + * 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. + * 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. - * + * 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. + * then zalloc_noblock to an empty zone may succeed. */ -void zalloc_async( - thread_call_param_t p0, - thread_call_param_t p1); +void zalloc_async( + thread_call_param_t p0, + thread_call_param_t p1); static thread_call_data_t call_async_alloc; @@ -1403,31 +1523,23 @@ static thread_call_data_t call_async_alloc; #define ZONE_ELEMENT_ALIGNMENT 32 #define zone_wakeup(zone) thread_wakeup((event_t)(zone)) -#define zone_sleep(zone) \ +#define zone_sleep(zone) \ (void) lck_mtx_sleep(&(zone)->lock, LCK_SLEEP_SPIN_ALWAYS, (event_t)(zone), THREAD_UNINT); -/* - * 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_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); \ +#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 -#define lock_try_zone(zone) lck_mtx_try_lock_spin(&zone->lock) +#define lock_try_zone(zone) lck_mtx_try_lock_spin(&zone->lock) /* * Exclude more than one concurrent garbage collection */ -decl_lck_mtx_data(, zone_gc_lock) +decl_lck_mtx_data(, zone_gc_lock); lck_attr_t zone_gc_lck_attr; lck_grp_t zone_gc_lck_grp; @@ -1440,9 +1552,12 @@ boolean_t panic_include_zprint = FALSE; mach_memory_info_t *panic_kext_memory_info = NULL; vm_size_t panic_kext_memory_size = 0; -#define ZALLOC_DEBUG_ZONEGC 0x00000001 -#define ZALLOC_DEBUG_ZCRAM 0x00000002 -uint32_t zalloc_debug = 0; +#define ZALLOC_DEBUG_ZONEGC 0x00000001 +#define ZALLOC_DEBUG_ZCRAM 0x00000002 + +#if DEBUG || DEVELOPMENT +static uint32_t zalloc_debug = 0; +#endif /* * Zone leak debugging code @@ -1453,7 +1568,7 @@ uint32_t zalloc_debug = 0; * off by default. * * Enable the logging via the boot-args. Add the parameter "zlog=" to boot-args where - * 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 @@ -1475,17 +1590,17 @@ uint32_t zalloc_debug = 0; */ static boolean_t log_records_init = FALSE; -static int log_records; /* size of the log, expressed in number of records */ +static int log_records; /* size of the log, expressed in number of records */ -#define MAX_NUM_ZONES_ALLOWED_LOGGING 10 /* Maximum 10 zones can be logged at once */ +#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; -static char zone_name_to_log[MAX_ZONE_NAME] = ""; /* the zone name we're logging, if any */ +static char zone_name_to_log[MAX_ZONE_NAME] = ""; /* the zone name we're logging, if any */ /* Log allocations and frees to help debug a zone element corruption */ -boolean_t corruption_debug_flag = FALSE; /* enabled by "-zc" boot-arg */ +boolean_t corruption_debug_flag = DEBUG; /* enabled by "-zc" boot-arg */ /* Making pointer scanning leaks detection possible for all zones */ #if DEBUG || DEVELOPMENT @@ -1494,17 +1609,17 @@ boolean_t leak_scan_debug_flag = FALSE; /* enabled by "-zl" boot-ar /* - * The number of records in the log is configurable via the zrecs parameter in boot-args. Set this to + * 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 2560 /* Max records allowed in the log */ +#if defined(__LP64__) +#define ZRECORDS_MAX 2560 /* Max records allowed in the log */ #else -#define ZRECORDS_MAX 1536 /* Max records allowed in the log */ +#define ZRECORDS_MAX 1536 /* Max records allowed in the log */ #endif -#define ZRECORDS_DEFAULT 1024 /* 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 */ /* * Each record in the log contains a pointer to the zone element it refers to, @@ -1515,13 +1630,6 @@ boolean_t leak_scan_debug_flag = FALSE; /* enabled by "-zl" boot-ar */ -/* - * Opcodes for the btlog operation field: - */ - -#define ZOP_ALLOC 1 -#define ZOP_FREE 0 - /* * 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 @@ -1532,7 +1640,7 @@ boolean_t leak_scan_debug_flag = FALSE; /* enabled by "-zl" boot-ar int track_this_zone(const char *zonename, const char *logname) { - int len; + unsigned int len; const char *zc = zonename; const char *lc = logname; @@ -1541,22 +1649,23 @@ track_this_zone(const char *zonename, const char *logname) */ 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 == '.')) + 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') + if (*zc == '\0') { return TRUE; + } } return FALSE; @@ -1568,7 +1677,7 @@ track_this_zone(const char *zonename, const char *logname) * the buffer for the records has been allocated. */ -#define DO_LOGGING(z) (z->zone_logging == TRUE && z->zlog_btlog) +#define DO_LOGGING(z) (z->zone_logging == TRUE && z->zlog_btlog) extern boolean_t kmem_alloc_ready; @@ -1576,13 +1685,13 @@ extern boolean_t kmem_alloc_ready; #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. @@ -1590,20 +1699,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; @@ -1614,11 +1723,11 @@ 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 @@ -1627,11 +1736,11 @@ unsigned int z_total_conflicts = 0; * 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 */ @@ -1641,29 +1750,29 @@ 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; +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; /* * Initializes the zone leak monitor. Called from zone_init() */ -static void -zleak_init(vm_size_t max_zonemap_size) +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 @@ -1684,7 +1793,7 @@ zleak_init(vm_size_t max_zonemap_size) 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); @@ -1694,26 +1803,26 @@ 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; } @@ -1728,11 +1837,13 @@ 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 @@ -1781,7 +1892,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]; @@ -1795,10 +1906,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. @@ -1820,15 +1931,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. @@ -1838,47 +1949,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) { @@ -1886,28 +1997,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; @@ -1916,15 +2028,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; } @@ -1935,37 +2048,38 @@ zleak_log(uintptr_t* bt, */ 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; } @@ -1986,16 +2100,16 @@ hash_mix(uintptr_t x) #ifndef __LP64__ x += ~(x << 15); x ^= (x >> 10); - x += (x << 3 ); - x ^= (x >> 6 ); + 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 >> 8); + x += (x << 3); x ^= (x >> 15); x += ~(x << 27); x ^= (x >> 31); @@ -2006,7 +2120,6 @@ hash_mix(uintptr_t x) uint32_t hashbacktrace(uintptr_t* bt, uint32_t depth, uint32_t max_size) { - uintptr_t hash = 0; uintptr_t mask = max_size - 1; @@ -2041,7 +2154,7 @@ hashaddr(uintptr_t pt, uint32_t max_size) /* End of all leak-detection code */ #pragma mark - -#define ZONE_MAX_ALLOC_SIZE (32 * 1024) +#define ZONE_MAX_ALLOC_SIZE (32 * 1024) #define ZONE_ALLOC_FRAG_PERCENT(alloc_size, ele_size) (((alloc_size % ele_size) * 100) / alloc_size) /* Used to manage copying in of new zone names */ @@ -2055,45 +2168,141 @@ compute_element_size(vm_size_t requested_size) /* Zone elements must fit both a next pointer and a backup pointer */ vm_size_t minimum_element_size = sizeof(vm_offset_t) * 2; - if (element_size < minimum_element_size) + if (element_size < minimum_element_size) { element_size = minimum_element_size; + } /* * Round element size to a multiple of sizeof(pointer) * This also enforces that allocations will be aligned on pointer boundaries */ - element_size = ((element_size-1) + sizeof(vm_offset_t)) - - ((element_size-1) % sizeof(vm_offset_t)); + element_size = ((element_size - 1) + sizeof(vm_offset_t)) - + ((element_size - 1) % sizeof(vm_offset_t)); return element_size; } +#if KASAN_ZALLOC + /* - * 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. + * Called from zinit(). + * + * Fixes up the zone's element size to incorporate the redzones. */ - -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 */ +static void +kasan_update_element_size_for_redzone( + zone_t zone, /* the zone that needs to be updated */ + vm_size_t *size, /* requested zone element size */ + vm_size_t *max, /* maximum memory to use */ + const char *name) /* zone name */ { - zone_t z; - - size = compute_element_size(size); + /* Expand the zone allocation size to include the redzones. For page-multiple + * zones add a full guard page because they likely require alignment. kalloc + * and fakestack handles its own KASan state, so ignore those zones. */ + /* XXX: remove this when zinit_with_options() is a thing */ + const char *kalloc_name = "kalloc."; + const char *fakestack_name = "fakestack."; + if (strncmp(name, kalloc_name, strlen(kalloc_name)) == 0) { + zone->kasan_redzone = 0; + } else if (strncmp(name, fakestack_name, strlen(fakestack_name)) == 0) { + zone->kasan_redzone = 0; + } else { + if ((*size % PAGE_SIZE) != 0) { + zone->kasan_redzone = KASAN_GUARD_SIZE; + } else { + zone->kasan_redzone = PAGE_SIZE; + } + *max = (*max / *size) * (*size + zone->kasan_redzone * 2); + *size += zone->kasan_redzone * 2; + } +} + +/* + * Called from zalloc_internal() to fix up the address of the newly + * allocated element. + * + * Returns the element address skipping over the redzone on the left. + */ +static vm_offset_t +kasan_fixup_allocated_element_address( + zone_t zone, /* the zone the element belongs to */ + vm_offset_t addr) /* address of the element, including the redzone */ +{ + /* 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); + } + return addr; +} + +/* + * 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; + + /* + * 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. + */ + 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, zonep, usersz, true); + if (!addr) { + return TRUE; + } + } + *addrp = addr; + return FALSE; +} + +#endif /* KASAN_ZALLOC */ - simple_lock(&all_zones_lock); +/* + * 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 */ +{ + zone_t z; + + size = compute_element_size(size); + + simple_lock(&all_zones_lock, &zone_locks_grp); assert(num_zones < MAX_ZONES); assert(num_zones_in_use <= num_zones); /* If possible, find a previously zdestroy'ed zone in the zone_array that we can reuse instead of initializing a new zone. */ for (int index = bitmap_first(zone_empty_bitmap, MAX_ZONES); - index >= 0 && index < (int)num_zones; - index = bitmap_next(zone_empty_bitmap, index)) { + index >= 0 && index < (int)num_zones; + index = bitmap_next(zone_empty_bitmap, index)) { z = &(zone_array[index]); /* @@ -2110,10 +2319,11 @@ zinit( bitmap_clear(zone_empty_bitmap, index); num_zones_in_use++; z->zone_valid = TRUE; + z->zone_destruction = FALSE; /* All other state is already set up since the zone was previously in use. Return early. */ simple_unlock(&all_zones_lock); - return (z); + return z; } } } @@ -2138,25 +2348,7 @@ zinit( simple_unlock(&all_zones_lock); #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. kalloc - * and fakestack handles its own KASan state, so ignore those zones. */ - /* XXX: remove this when zinit_with_options() is a thing */ - const char *kalloc_name = "kalloc."; - const char *fakestack_name = "fakestack."; - if (strncmp(name, kalloc_name, strlen(kalloc_name)) == 0) { - z->kasan_redzone = 0; - } else if (strncmp(name, fakestack_name, strlen(fakestack_name)) == 0) { - z->kasan_redzone = 0; - } else { - if ((size % PAGE_SIZE) != 0) { - z->kasan_redzone = KASAN_GUARD_SIZE; - } else { - z->kasan_redzone = PAGE_SIZE; - } - max = (max / size) * (size + z->kasan_redzone * 2); - size += z->kasan_redzone * 2; - } + kasan_update_element_size_for_redzone(z, &size, &max, name); #endif max = round_page(max); @@ -2176,8 +2368,9 @@ zinit( } alloc = best_alloc; - if (max && (max < alloc)) + if (max && (max < alloc)) { max = alloc; + } z->free_elements = NULL; queue_init(&z->pages.any_free_foreign); @@ -2213,6 +2406,9 @@ zinit( z->zp_count = 0; z->kasan_quarantine = TRUE; z->zone_valid = TRUE; + z->zone_destruction = FALSE; + z->cpu_cache_enabled = FALSE; + z->clear_memory = FALSE; #if CONFIG_ZLEAKS z->zleak_capture = 0; @@ -2227,12 +2423,12 @@ zinit( * 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); + 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); + PAGE_SIZE, VM_KERN_MEMORY_OSFMK); if (retval != KERN_SUCCESS) { panic("zalloc: zone_names memory allocation failed"); } @@ -2259,13 +2455,11 @@ zinit( */ 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... */ + 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) { @@ -2282,7 +2476,7 @@ zinit( } 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. @@ -2299,7 +2493,7 @@ zinit( } if (log_records_init == FALSE && zone_logging_enabled == TRUE) { - if (PE_parse_boot_argn("zrecs", &log_records, sizeof(log_records)) == 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 @@ -2323,16 +2517,14 @@ zinit( * right now. */ if (kmem_alloc_ready) { - zone_t curr_zone = NULL; unsigned int max_zones = 0, zone_idx = 0; - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); 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) { @@ -2347,36 +2539,40 @@ zinit( * 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 +#if CONFIG_GZALLOC gzalloc_zone_init(z); #endif - return(z); +#if CONFIG_ZCACHE + /* Check if boot-arg specified it should have a cache */ + if (cache_all_zones || track_this_zone(name, cache_zone_name)) { + zone_change(z, Z_CACHING_ENABLED, TRUE); + } +#endif + + return z; } -unsigned zone_replenish_loops, zone_replenish_wakeups, zone_replenish_wakeups_initiated, zone_replenish_throttle_count; +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)) +__dead2 static void zone_replenish_thread(zone_t z) { @@ -2394,18 +2590,24 @@ zone_replenish_thread(zone_t z) assert(z->async_prio_refill == TRUE); unlock_zone(z); - int zflags = KMA_KOBJECT|KMA_NOPAGEWAIT; + int zflags = KMA_KOBJECT | KMA_NOPAGEWAIT; vm_offset_t space, alloc_size; kern_return_t kr; - - if (vm_pool_low()) + + if (vm_pool_low()) { alloc_size = round_page(z->elem_size); - else + } else { alloc_size = z->alloc_size; - - if (z->noencrypt) + } + + if (z->noencrypt) { zflags |= KMA_NOENCRYPT; - + } + + if (z->clear_memory) { + zflags |= KMA_ZERO; + } + /* 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); @@ -2446,7 +2648,8 @@ zone_replenish_thread(zone_t z) } void -zone_prio_refill_configure(zone_t z, vm_size_t low_water_mark) { +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; @@ -2484,12 +2687,20 @@ zdestroy(zone_t z) */ z->zone_valid = FALSE; #endif + z->zone_destruction = TRUE; unlock_zone(z); +#if CONFIG_ZCACHE + /* Drain the per-cpu caches if caching is enabled for the zone. */ + if (zone_caching_enabled(z)) { + panic("zdestroy: Zone caching enabled for zone %s", z->zone_name); + } +#endif /* CONFIG_ZCACHE */ + /* Dump all the free elements */ drop_free_elements(z); -#if CONFIG_GZALLOC +#if CONFIG_GZALLOC /* If the zone is gzalloc managed dump all the elements in the free cache */ gzalloc_empty_free_cache(z); #endif @@ -2514,7 +2725,7 @@ zdestroy(zone_t z) unlock_zone(z); - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); assert(!bitmap_test(zone_empty_bitmap, zindex)); /* Mark the zone as empty in the bitmap */ @@ -2545,29 +2756,30 @@ zcram_metadata_init(vm_offset_t newmem, vm_size_t size, struct zone_page_metadat return; } + static void random_free_to_zone( - zone_t zone, - vm_offset_t newmem, - vm_offset_t first_element_offset, - int element_count, - unsigned int *entropy_buffer) + zone_t zone, + vm_offset_t newmem, + vm_offset_t first_element_offset, + int element_count, + unsigned int *entropy_buffer) { - vm_offset_t last_element_offset; - vm_offset_t element_addr; + vm_offset_t last_element_offset; + vm_offset_t element_addr; vm_size_t elem_size; - int index; + int index; - assert(element_count <= ZONE_CHUNK_MAXELEMENTS); + assert(element_count && 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) || + leak_scan_debug_flag || __improbable(zone->tags) || #endif /* DEBUG || DEVELOPMENT */ - random_bool_gen_bits(&zone_bool_gen, entropy_buffer, MAX_ENTROPY_PER_ZCRAM, 1)) { + random_bool_gen_bits(&zone_bool_gen, entropy_buffer, MAX_ENTROPY_PER_ZCRAM, 1)) { element_addr = newmem + first_element_offset; first_element_offset += elem_size; } else { @@ -2587,11 +2799,11 @@ random_free_to_zone( */ void zcram( - zone_t zone, - vm_offset_t newmem, - vm_size_t size) + zone_t zone, + vm_offset_t newmem, + vm_size_t size) { - vm_size_t elem_size; + vm_size_t elem_size; boolean_t from_zm = FALSE; int element_count; unsigned int entropy_buffer[MAX_ENTROPY_PER_ZCRAM] = { 0 }; @@ -2599,14 +2811,15 @@ zcram( /* Basic sanity checks */ assert(zone != ZONE_NULL && newmem != (vm_offset_t)0); assert(!zone->collectable || zone->allows_foreign - || (from_zone_map(newmem, size))); + || (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)) + 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 @@ -2616,9 +2829,12 @@ zcram( assert((zone->allows_foreign == TRUE) && (zone->elem_size <= (PAGE_SIZE - sizeof(struct zone_page_metadata)))); } - if (zalloc_debug & ZALLOC_DEBUG_ZCRAM) +#if DEBUG || DEVELOPMENT + 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); + (unsigned long)newmem, from_zm ? "" : "[F]", (unsigned long)size); + } +#endif /* DEBUG || DEVELOPMENT */ ZONE_PAGE_COUNT_INCR(zone, (size / PAGE_SIZE)); @@ -2645,10 +2861,10 @@ zcram( zcram_metadata_init(newmem, size, chunk_metadata); #if VM_MAX_TAG_ZONES - if (__improbable(zone->tags)) { - assert(from_zm); - ztMemoryAdd(zone, newmem, size); - } + if (__improbable(zone->tags)) { + assert(from_zm); + ztMemoryAdd(zone, newmem, size); + } #endif /* VM_MAX_TAG_ZONES */ lock_zone(zone); @@ -2656,29 +2872,28 @@ zcram( 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 + /* 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){ + 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); + element_count = (unsigned 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); + element_count = (unsigned 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); + KDBG(MACHDBG_CODE(DBG_MACH_ZALLOC, ZALLOC_ZCRAM) | DBG_FUNC_END, zone->index); } /* @@ -2689,15 +2904,20 @@ zcram( */ int zfill( - zone_t zone, - int nelem) + zone_t zone, + int nelem) { kern_return_t kr; - vm_offset_t memory; + 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; + int zflags = KMA_KOBJECT; + + if (zone->clear_memory) { + zflags |= KMA_ZERO; + } /* Don't mix-and-match zfill with foreign memory */ assert(!zone->allows_foreign); @@ -2707,10 +2927,10 @@ zfill( 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); + kr = kernel_memory_allocate(zone_map, &memory, nalloc * alloc_size, 0, zflags, VM_KERN_MEMORY_ZONE); if (kr != KERN_SUCCESS) { printf("%s: kernel_memory_allocate() of %lu bytes failed\n", - __func__, (unsigned long)(nalloc * alloc_size)); + __func__, (unsigned long)(nalloc * alloc_size)); return 0; } @@ -2731,8 +2951,11 @@ zone_bootstrap(void) { char temp_buf[16]; - if (!PE_parse_boot_argn("zalloc_debug", &zalloc_debug, sizeof(zalloc_debug))) +#if DEBUG || DEVELOPMENT + if (!PE_parse_boot_argn("zalloc_debug", &zalloc_debug, sizeof(zalloc_debug))) { zalloc_debug = 0; + } +#endif /* DEBUG || DEVELOPMENT */ /* Set up zone element poisoning */ zp_init(); @@ -2742,9 +2965,13 @@ zone_bootstrap(void) /* 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 + /* should perform zone element size checking in copyin/copyout? */ + if (PE_parse_boot_argn("-no-copyio-zalloc-check", temp_buf, sizeof(temp_buf))) { + copyio_zalloc_check = FALSE; + } #if VM_MAX_TAG_ZONES /* enable tags for zones that ask for */ if (PE_parse_boot_argn("-zt", temp_buf, sizeof(temp_buf))) { @@ -2775,8 +3002,21 @@ zone_bootstrap(void) 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_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); + +#if CONFIG_ZCACHE + /* zcc_enable_for_zone_name=: enable per-cpu zone caching for . */ + 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); + } + + /* -zcache_all: enable per-cpu zone caching for all zones, overrides 'zcc_enable_for_zone_name'. */ + if (PE_parse_boot_argn("-zcache_all", temp_buf, sizeof(temp_buf))) { + cache_all_zones = TRUE; + printf("zcache: caching enabled for all zones\n"); + } +#endif /* CONFIG_ZCACHE */ } /* @@ -2802,20 +3042,23 @@ extern pid_t find_largest_process_vm_map_entries(void); */ boolean_t memorystatus_kill_on_zone_map_exhaustion(pid_t pid); -void get_zone_map_size(uint64_t *current_size, uint64_t *capacity) +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) +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) +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); @@ -2834,13 +3077,14 @@ extern zone_t vm_object_zone; * 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) +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); + (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); /* @@ -2854,8 +3098,8 @@ static void kill_process_in_largest_zone(void) * 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; + unsigned int vm_object_zone_count = vm_object_zone->count; + unsigned 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; @@ -2881,29 +3125,34 @@ 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; + 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); + 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); + FALSE, VM_FLAGS_ANYWHERE, vmk_flags, VM_KERN_MEMORY_ZONE, + &zone_map); - if (retval != KERN_SUCCESS) + if (retval != KERN_SUCCESS) { panic("zone_init: kmem_suballoc failed"); + } zone_max = zone_min + round_page(max_zonemap_size); -#if CONFIG_GZALLOC + +#if CONFIG_GZALLOC gzalloc_init(max_zonemap_size); #endif + /* * Setup garbage collection information: */ @@ -2913,9 +3162,10 @@ zone_init( 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) + 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__) @@ -2924,18 +3174,20 @@ zone_init( * 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) + 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) + 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 @@ -2944,48 +3196,93 @@ zone_init( #endif /* CONFIG_ZLEAKS */ #if VM_MAX_TAG_ZONES - if (zone_tagging_on) vm_allocation_zones_init(); + 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) + 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; +void +zalloc_poison_element(boolean_t check_poison, zone_t zone, vm_offset_t addr) +{ + vm_offset_t inner_size = zone->elem_size; + 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; + } +} + +/* + * When deleting page mappings from the kernel map, it might be necessary to split + * apart an existing vm_map_entry. That means that a "free" operation, will need to + * *allocate* new vm_map_entry structures before it can free a page. + * + * This reserve here is the number of elements which are held back from everyone except + * the zone_gc thread. This is done so the zone_gc thread should never have to wait for + * the zone replenish thread for vm_map_entry structs. If it did, it could wind up + * in a deadlock. + */ +#define VM_MAP_ENTRY_RESERVE_CNT 8 + /* * zalloc returns an element from the specified zone. */ static void * zalloc_internal( - zone_t zone, + zone_t zone, boolean_t canblock, boolean_t nopagewait, vm_size_t #if !VM_MAX_TAG_ZONES - __unused + __unused #endif - reqsize, + 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(); + vm_offset_t addr = 0; + kern_return_t retval; + uintptr_t zbt[MAX_ZTRACE_DEPTH]; /* used in zone leak logging and zone leak detection */ + unsigned int numsaved = 0; + 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 */ + uint32_t zleak_tracedepth = 0; /* log this allocation if nonzero */ #endif /* CONFIG_ZLEAKS */ #if KASAN @@ -3006,14 +3303,15 @@ zalloc_internal( assert(zone != ZONE_NULL); assert(irq_safe || ml_get_interrupts_enabled() || ml_is_quiescing() || debug_mode_active() || !early_boot_complete); -#if CONFIG_GZALLOC +#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 (__improbable(DO_LOGGING(zone))) { + numsaved = OSBacktrace((void*) zbt, MAX_ZTRACE_DEPTH); + } #if CONFIG_ZLEAKS /* @@ -3022,79 +3320,112 @@ zalloc_internal( */ 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 + if (numsaved == 0) { + zleak_tracedepth = backtrace(zbt, MAX_ZTRACE_DEPTH, NULL); + } 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); + if (__improbable(zone->tags)) { + vm_tag_will_update_zone(tag, zone->tag_zone_index); + } #endif /* VM_MAX_TAG_ZONES */ +#if CONFIG_ZCACHE + if (__probable(addr == 0)) { + if (zone_caching_enabled(zone)) { + addr = zcache_alloc_from_cpu_cache(zone); + if (addr) { +#if KASAN_ZALLOC + addr = kasan_fixup_allocated_element_address(zone, addr); +#endif + if (__improbable(DO_LOGGING(zone) && addr)) { + btlog_add_entry(zone->zlog_btlog, (void *)addr, + ZOP_ALLOC, (void **)zbt, numsaved); + } + DTRACE_VM2(zalloc, zone_t, zone, void*, addr); + return (void *)addr; + } + } + } +#endif /* CONFIG_ZCACHE */ + lock_zone(zone); assert(zone->zone_valid); + /* + * Check if we need another thread to replenish the zone. + * This is used for elements, like vm_map_entry, which are + * needed themselves to implement zalloc(). + */ 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; + vm_size_t curr_free; + vm_size_t refill_level; + const vm_size_t reserved_min = VM_MAP_ENTRY_RESERVE_CNT * zone->elem_size; + + for (;;) { + curr_free = (zone->cur_size - (zone->count * zone->elem_size)); + refill_level = zone->prio_refill_watermark * zone->elem_size; + + /* + * Nothing to do if there are plenty of elements. + */ + if (curr_free > refill_level) { + break; + } + + /* + * Wakeup the replenish thread. + */ + zone_replenish_wakeups_initiated++; + thread_wakeup(&zone->zone_replenish_thread); + + /* + * If we: + * - still have head room, more than half the refill amount, or + * - this is a VMPRIV thread and we're still above reserved, or + * - this is the zone garbage collection thread which may use the reserve + * then we don't have to wait for the replenish thread. + * + * The reserve for the garbage collection thread is to avoid a deadlock + * on the zone_map_lock between the replenish thread and GC thread. + */ + if (curr_free > refill_level / 2 || + ((thr->options & TH_OPT_VMPRIV) && curr_free > reserved_min) || + (thr->options & TH_OPT_ZONE_GC)) { + break; + } + 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); + + assert(zone->zone_valid); + } + } - 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)) + 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). + * entries zone). The value of reserved_min in the previous bit of code should have given us + * headroom even though the GC thread didn't wait. */ - if (thr->options & TH_OPT_ZONE_GC && zone->async_prio_refill) + 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 - * + * 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 @@ -3122,8 +3453,9 @@ zalloc_internal( if ((zone->cur_size + zone->elem_size) > zone->max_size) { - if (zone->exhaustible) + if (zone->exhaustible) { break; + } if (zone->expandable) { /* * We're willing to overflow certain @@ -3133,7 +3465,7 @@ zalloc_internal( * with the collectable flag. What we * want is an assurance we can get the * memory back, assuming there's no - * leak. + * leak. */ zone->max_size += (zone->max_size >> 1); } else { @@ -3141,40 +3473,47 @@ zalloc_internal( panic_include_zprint = TRUE; #if CONFIG_ZLEAKS - if (zleak_state & ZLEAK_STATE_ACTIVE) + 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; + zone->doing_alloc_with_vm_priv = TRUE; set_doing_alloc_with_vm_priv = TRUE; } else { - zone->doing_alloc_without_vm_priv = TRUE; + zone->doing_alloc_without_vm_priv = TRUE; } unlock_zone(zone); for (;;) { - int zflags = KMA_KOBJECT|KMA_NOPAGEWAIT; + int zflags = KMA_KOBJECT | KMA_NOPAGEWAIT; - if (vm_pool_low() || retry >= 1) - alloc_size = - round_page(zone->elem_size); - else + if (vm_pool_low() || retry >= 1) { + alloc_size = + round_page(zone->elem_size); + } else { alloc_size = zone->alloc_size; - - if (zone->noencrypt) + } + + if (zone->noencrypt) { zflags |= KMA_NOENCRYPT; - + } + + if (zone->clear_memory) { + zflags |= KMA_ZERO; + } + /* 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); @@ -3186,41 +3525,40 @@ zalloc_internal( 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 */ +#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); - + 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); + panic("zalloc: \"%s\" (%d elements) retry fail %d", zone->zone_name, zone->count, retval); } } else { break; @@ -3229,13 +3567,14 @@ zalloc_internal( 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 (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->waiting = FALSE; zone_wakeup(zone); } clear_thread_rwlock_boost(); @@ -3243,8 +3582,9 @@ zalloc_internal( 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 */ + if (nopagewait == TRUE) { + break; /* out of the main while loop */ + } unlock_zone(zone); VM_PAGE_WAIT(); @@ -3252,24 +3592,25 @@ zalloc_internal( assert(zone->zone_valid); } } - if (addr == 0) + 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 we're sampling this allocation, add it to the zleaks hash table. */ - if (addr && zleak_tracedepth > 0) { + 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 */ - - +#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); @@ -3280,100 +3621,97 @@ zalloc_internal( } #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); - } + 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); - } + zalloc_poison_element(check_poison, zone, 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; + unsigned 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]; + if (numsaved == 0) { + numsaved = backtrace(zbt, MAX_ZTRACE_DEPTH, NULL); + } + count = (unsigned 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); - } + addr = kasan_fixup_allocated_element_address(zone, addr); #endif DTRACE_VM2(zalloc, zone_t, zone, void*, addr); - return((void *)addr); + return (void *)addr; } void * zalloc(zone_t zone) { - return (zalloc_internal(zone, TRUE, FALSE, 0, VM_KERN_MEMORY_NONE)); + 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)); + 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)); + 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)); + 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)); + return zalloc_internal(zone, canblock, FALSE, 0, VM_KERN_MEMORY_NONE); +} + +void * +zalloc_attempt(zone_t zone) +{ + boolean_t check_poison = FALSE; + vm_offset_t addr = try_alloc_from_zone(zone, VM_KERN_MEMORY_NONE, &check_poison); + zalloc_poison_element(check_poison, zone, addr); + return (void *)addr; +} + +void +zfree_direct(zone_t zone, vm_offset_t elem) +{ + boolean_t poison = zfree_poison_element(zone, elem); + free_to_zone(zone, elem, poison); } @@ -3386,8 +3724,8 @@ zalloc_async( unsigned int max_zones, i; void *elt = NULL; boolean_t pending = FALSE; - - simple_lock(&all_zones_lock); + + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = num_zones; simple_unlock(&all_zones_lock); for (i = 0; i < max_zones; i++) { @@ -3419,88 +3757,113 @@ zalloc_async( */ void * zget( - zone_t zone) + zone_t zone) { - return zalloc_internal(zone, FALSE, TRUE, 0, VM_KERN_MEMORY_NONE); + 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 */ + * 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) +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))) { + !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) + 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))) { + !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) + 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))) { + !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) + this != NULL; + this = this->next) { + if (!is_sane_zone_element(zone, (vm_address_t)this) || (vm_address_t)this == elem) { panic("zone_check_freelist"); + } } } } +boolean_t +zfree_poison_element(zone_t zone, vm_offset_t elem) +{ + boolean_t poison = FALSE; + if (zp_factor != 0 || zp_tiny_zone_limit != 0) { + /* + * 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: */ + /* 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; + } + } + } + return poison; +} void -zfree( - zone_t zone, - void *addr) +(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; + vm_offset_t elem = (vm_offset_t) addr; + uintptr_t zbt[MAX_ZTRACE_DEPTH]; /* only used if zone logging is enabled via boot-args */ + unsigned int numsaved = 0; + boolean_t gzfreed = FALSE; boolean_t poison = FALSE; #if VM_MAX_TAG_ZONES - vm_tag_t tag; + vm_tag_t tag; #endif /* VM_MAX_TAG_ZONES */ assert(zone != ZONE_NULL); DTRACE_VM2(zfree, zone_t, zone, void*, addr); - #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; - } + if (kasan_quarantine_freed_element(&zone, &addr)) { + return; } elem = (vm_offset_t)addr; #endif @@ -3509,16 +3872,18 @@ zfree( * 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)) + 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) + if (zone == ZONE_NULL || elem == (vm_offset_t)0) { panic("zfree: NULL"); + } #endif -#if CONFIG_GZALLOC +#if CONFIG_GZALLOC gzfreed = gzalloc_free(zone, addr); #endif @@ -3532,38 +3897,12 @@ zfree( 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))) { + !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: */ - /* 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; - } + if (!gzfreed) { + poison = zfree_poison_element(zone, elem); } /* @@ -3589,6 +3928,14 @@ zfree( } } +#if CONFIG_ZCACHE + if (zone_caching_enabled(zone)) { + int __assert_only ret = zcache_free_to_cpu_cache(zone, addr); + assert(ret != FALSE); + return; + } +#endif /* CONFIG_ZCACHE */ + lock_zone(zone); assert(zone->zone_valid); @@ -3598,31 +3945,29 @@ zfree( if (__probable(!gzfreed)) { #if VM_MAX_TAG_ZONES - if (__improbable(zone->tags)) { + 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) + if (__improbable(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 - + zone->zone_name, addr); + } #if CONFIG_ZLEAKS /* - * Zone leak detection: un-track the allocation + * 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); @@ -3637,71 +3982,94 @@ zfree( */ void zone_change( - zone_t zone, - unsigned int item, - boolean_t value) + 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: + 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); - } + { + 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); + 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; + 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; + 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; + } +#endif +#if CONFIG_GZALLOC + gzalloc_reconfigure(zone); +#endif + break; + case Z_KASAN_QUARANTINE: + zone->kasan_quarantine = value; + break; + case Z_CACHING_ENABLED: +#if CONFIG_ZCACHE + if (value == TRUE) { +#if CONFIG_GZALLOC + /* + * Per cpu zone caching should be + * disabled if gzalloc is enabled. + */ + if (gzalloc_enabled()) { + break; } #endif -#if CONFIG_GZALLOC - gzalloc_reconfigure(zone); + if (zcache_ready()) { + zcache_init(zone); + } else { + zone->cpu_cache_enable_when_ready = TRUE; + } + } #endif - break; - case Z_KASAN_QUARANTINE: - zone->kasan_quarantine = value; - break; - default: - panic("Zone_change: Wrong Item Type!"); - /* break; */ + break; + case Z_CLEARMEMORY: + zone->clear_memory = value; + break; + default: + panic("Zone_change: Wrong Item Type!"); + /* break; */ } } @@ -3723,72 +4091,84 @@ zone_free_count(zone_t zone) assert(free_count >= 0); - return(free_count); + return free_count; } -/* Drops the elements in the free queue of a zone. Called by zone_gc() on each zone, and when a zone is zdestroy'ed. */ +/* + * 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. + */ void drop_free_elements(zone_t z) { - vm_size_t elt_size, size_freed; - int total_freed_pages = 0; - uint64_t old_all_free_count; - struct zone_page_metadata *page_meta; - queue_head_t page_meta_head; + vm_size_t elt_size; + unsigned int total_freed_pages = 0; + struct zone_page_metadata *page_meta; + vm_address_t free_page_address; + vm_size_t size_to_free; lock_zone(z); - if (queue_empty(&z->pages.all_free)) { - unlock_zone(z); - return; - } - /* - * Snatch all of the free elements away from the zone. - */ elt_size = z->elem_size; - old_all_free_count = z->count_all_free_pages; - queue_new_head(&z->pages.all_free, &page_meta_head, struct zone_page_metadata *, pages); - queue_init(&z->pages.all_free); - z->count_all_free_pages = 0; - unlock_zone(z); - /* Iterate through all elements to find out size and count of elements we snatched */ - size_freed = 0; - queue_iterate(&page_meta_head, page_meta, struct zone_page_metadata *, pages) { + while (!queue_empty(&z->pages.all_free)) { + page_meta = (struct zone_page_metadata *)queue_first(&z->pages.all_free); assert(from_zone_map((vm_address_t)page_meta, sizeof(*page_meta))); /* foreign elements should be in any_free_foreign */ - size_freed += elt_size * page_meta->free_count; - } + /* + * Don't drain zones with async refill to below the refill threshold, + * as they need some reserve to function properly. + */ + if (!z->zone_destruction && + z->async_prio_refill && z->zone_replenish_thread && + (vm_size_t)(page_meta->free_count - z->countfree) < z->prio_refill_watermark) { + break; + } - /* Update the zone size and free element count */ - lock_zone(z); - z->cur_size -= size_freed; - z->countfree -= size_freed/elt_size; - unlock_zone(z); + (void)dequeue_head(&z->pages.all_free); + + assert(z->countfree >= page_meta->free_count); + z->countfree -= page_meta->free_count; + + assert(z->count_all_free_pages >= page_meta->page_count); + z->count_all_free_pages -= page_meta->page_count; + + assert(z->cur_size >= page_meta->free_count * elt_size); + z->cur_size -= page_meta->free_count * elt_size; + + ZONE_PAGE_COUNT_DECR(z, page_meta->page_count); + unlock_zone(z); - while ((page_meta = (struct zone_page_metadata *)dequeue_head(&page_meta_head)) != NULL) { - vm_address_t free_page_address; /* Free the pages for metadata and account for them */ free_page_address = get_zone_page(page_meta); - ZONE_PAGE_COUNT_DECR(z, page_meta->page_count); total_freed_pages += page_meta->page_count; - old_all_free_count -= page_meta->page_count; + size_to_free = page_meta->page_count * PAGE_SIZE; #if KASAN_ZALLOC - kasan_poison_range(free_page_address, page_meta->page_count * PAGE_SIZE, ASAN_VALID); + kasan_poison_range(free_page_address, size_to_free, ASAN_VALID); #endif #if VM_MAX_TAG_ZONES - if (z->tags) ztMemoryRemove(z, free_page_address, (page_meta->page_count * PAGE_SIZE)); + if (z->tags) { + ztMemoryRemove(z, free_page_address, size_to_free); + } #endif /* VM_MAX_TAG_ZONES */ - kmem_free(zone_map, free_page_address, (page_meta->page_count * PAGE_SIZE)); + kmem_free(zone_map, free_page_address, size_to_free); if (current_thread()->options & TH_OPT_ZONE_GC) { thread_yield_to_preemption(); } + lock_zone(z); } + if (z->zone_destruction) { + assert(queue_empty(&z->pages.all_free)); + assert(z->count_all_free_pages == 0); + } + unlock_zone(z); - /* We freed all the pages from the all_free list for this zone */ - assert(old_all_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); +#if DEBUG || DEVELOPMENT + if (zalloc_debug & ZALLOC_DEBUG_ZONEGC) { + kprintf("zone_gc() of zone %s freed %lu elements, %d pages\n", z->zone_name, + (unsigned long)((total_freed_pages * PAGE_SIZE) / elt_size), total_freed_pages); + } +#endif /* DEBUG || DEVELOPMENT */ } /* Zone garbage collection @@ -3803,9 +4183,9 @@ drop_free_elements(zone_t z) void zone_gc(boolean_t consider_jetsams) { - unsigned int max_zones; - zone_t z; - unsigned int i; + unsigned int max_zones; + zone_t z; + unsigned int i; if (consider_jetsams) { kill_process_in_largest_zone(); @@ -3820,12 +4200,15 @@ zone_gc(boolean_t consider_jetsams) current_thread()->options |= TH_OPT_ZONE_GC; - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = num_zones; simple_unlock(&all_zones_lock); - if (zalloc_debug & ZALLOC_DEBUG_ZONEGC) +#if DEBUG || DEVELOPMENT + if (zalloc_debug & ZALLOC_DEBUG_ZONEGC) { kprintf("zone_gc() starting...\n"); + } +#endif /* DEBUG || DEVELOPMENT */ for (i = 0; i < max_zones; i++) { z = &(zone_array[i]); @@ -3834,11 +4217,15 @@ zone_gc(boolean_t consider_jetsams) if (!z->collectable) { continue; } - +#if CONFIG_ZCACHE + if (zone_caching_enabled(z)) { + zcache_drain_depot(z); + } +#endif /* CONFIG_ZCACHE */ if (queue_empty(&z->pages.all_free)) { continue; } - + drop_free_elements(z); } @@ -3869,16 +4256,51 @@ consider_zone_gc(boolean_t consider_jetsams) kmapoff_kaddr = 0; } - if (zone_gc_allowed) + if (zone_gc_allowed) { 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. + */ +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, ©); + assert(kr == KERN_SUCCESS); + + return copy; +} boolean_t get_zone_info( - zone_t z, - mach_zone_name_t *zn, - mach_zone_info_t *zi) + zone_t z, + mach_zone_name_t *zn, + mach_zone_info_t *zi) { struct zone zcopy; @@ -3894,7 +4316,7 @@ get_zone_info( if (zn != NULL) { /* assuming here the name data is static */ (void) __nosan_strlcpy(zn->mzn_name, zcopy.zone_name, - strlen(zcopy.zone_name)+1); + strlen(zcopy.zone_name) + 1); } if (zi != NULL) { @@ -3917,10 +4339,10 @@ get_zone_info( kern_return_t task_zone_info( - __unused task_t task, - __unused mach_zone_name_array_t *namesp, + __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 task_zone_info_array_t *infop, __unused mach_msg_type_number_t *infoCntp) { return KERN_FAILURE; @@ -3928,54 +4350,54 @@ task_zone_info( kern_return_t mach_zone_info( - host_priv_t host, - mach_zone_name_array_t *namesp, + host_priv_t host, + mach_zone_name_array_t *namesp, mach_msg_type_number_t *namesCntp, - mach_zone_info_array_t *infop, + mach_zone_info_array_t *infop, mach_msg_type_number_t *infoCntp) { - return (mach_memory_info(host, namesp, namesCntp, infop, infoCntp, NULL, NULL)); + return mach_memory_info(host, namesp, namesCntp, infop, infoCntp, NULL, NULL); } kern_return_t mach_memory_info( - host_priv_t host, - mach_zone_name_array_t *namesp, + host_priv_t host, + mach_zone_name_array_t *namesp, mach_msg_type_number_t *namesCntp, - mach_zone_info_array_t *infop, + 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; - - 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; - - unsigned int max_zones, used_zones, i; - mach_zone_name_t *zn; - mach_zone_info_t *zi; - kern_return_t kr; - - vm_size_t used; - vm_map_copy_t copy; - uint64_t zones_collectable_bytes = 0; - - if (host == HOST_NULL) + 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; + + 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 (host == HOST_NULL) { return KERN_INVALID_HOST; + } #if CONFIG_DEBUGGER_FOR_ZONE_INFO - if (!PE_i_can_has_debugger(NULL)) + if (!PE_i_can_has_debugger(NULL)) { return KERN_INVALID_HOST; + } #endif /* @@ -3983,23 +4405,24 @@ mach_memory_info( * We won't pick up any zones that are allocated later. */ - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = (unsigned int)(num_zones); simple_unlock(&all_zones_lock); 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 = (mach_zone_info_t *) info_addr; @@ -4018,60 +4441,28 @@ mach_memory_info( zi++; } - used = used_zones * sizeof *names; - if (used != names_size) { - vm_offset_t names_addr_end = names_addr + used; - vm_size_t free_size = names_size - (round_page(names_addr_end) - names_addr); - - if (free_size >= PAGE_SIZE) { - kmem_free(ipc_kernel_map, - round_page(names_addr_end), free_size); - } - bzero((char *) names_addr_end, round_page(names_addr_end) - names_addr_end); - } - - kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)names_addr, - (vm_map_size_t)used, TRUE, ©); - assert(kr == KERN_SUCCESS); - - *namesp = (mach_zone_name_t *) copy; + *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, used_zones * sizeof *names); *namesCntp = used_zones; - used = used_zones * sizeof *info; - if (used != info_size) { - vm_offset_t info_addr_end = info_addr + used; - vm_size_t free_size = info_size - (round_page(info_addr_end) - info_addr); - - if (free_size >= PAGE_SIZE) { - kmem_free(ipc_kernel_map, - round_page(info_addr_end), free_size); - } - bzero((char *) info_addr_end, round_page(info_addr_end) - info_addr_end); - } - - kr = vm_map_copyin(ipc_kernel_map, (vm_map_address_t)info_addr, - (vm_map_size_t)used, TRUE, ©); - assert(kr == KERN_SUCCESS); - - *infop = (mach_zone_info_t *) copy; + *infop = (mach_zone_info_t *) create_vm_map_copy(info_addr, info_size, used_zones * sizeof *info); *infoCntp = used_zones; - + num_info = 0; memory_info_addr = 0; - if (memoryInfop && memoryInfoCntp) - { + 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); + &memory_info_addr, memory_info_vmsize, VM_KERN_MEMORY_IPC); if (kr != KERN_SUCCESS) { return kr; } 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); + VM_PROT_READ | VM_PROT_WRITE, VM_KERN_MEMORY_IPC, FALSE); assert(kr == KERN_SUCCESS); memory_info = (mach_memory_info_t *) memory_info_addr; @@ -4079,9 +4470,9 @@ mach_memory_info( 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, ©); + (vm_map_size_t)memory_info_size, TRUE, ©); assert(kr == KERN_SUCCESS); *memoryInfop = (mach_memory_info_t *) copy; @@ -4093,25 +4484,27 @@ mach_memory_info( kern_return_t mach_zone_info_for_zone( - host_priv_t host, - mach_zone_name_t name, - mach_zone_info_t *infop) + host_priv_t host, + mach_zone_name_t name, + mach_zone_info_t *infop) { unsigned int max_zones, i; zone_t zone_ptr; - if (host == HOST_NULL) + if (host == HOST_NULL) { return KERN_INVALID_HOST; + } #if CONFIG_DEBUGGER_FOR_ZONE_INFO - if (!PE_i_can_has_debugger(NULL)) + if (!PE_i_can_has_debugger(NULL)) { return KERN_INVALID_HOST; + } #endif if (infop == NULL) { return KERN_INVALID_ARGUMENT; } - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = (unsigned int)(num_zones); simple_unlock(&all_zones_lock); @@ -4121,7 +4514,7 @@ mach_zone_info_for_zone( assert(z != ZONE_NULL); /* Find the requested zone by name */ - if (!strncmp(name.mzn_name, z->zone_name, strlen(z->zone_name))) { + if (track_this_zone(z->zone_name, name.mzn_name)) { zone_ptr = z; break; } @@ -4140,15 +4533,17 @@ mach_zone_info_for_zone( kern_return_t mach_zone_info_for_largest_zone( - host_priv_t host, - mach_zone_name_t *namep, - mach_zone_info_t *infop) + host_priv_t host, + mach_zone_name_t *namep, + mach_zone_info_t *infop) { - if (host == HOST_NULL) + if (host == HOST_NULL) { return KERN_INVALID_HOST; + } #if CONFIG_DEBUGGER_FOR_ZONE_INFO - if (!PE_i_can_has_debugger(NULL)) + if (!PE_i_can_has_debugger(NULL)) { return KERN_INVALID_HOST; + } #endif if (namep == NULL || infop == NULL) { @@ -4168,7 +4563,7 @@ get_zones_collectable_bytes(void) uint64_t zones_collectable_bytes = 0; mach_zone_info_t zi; - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = (unsigned int)(num_zones); simple_unlock(&all_zones_lock); @@ -4181,95 +4576,245 @@ get_zones_collectable_bytes(void) return zones_collectable_bytes; } +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 DEBUG || DEVELOPMENT + 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; + } + + if (namesp == NULL || namesCntp == NULL) { + return KERN_INVALID_ARGUMENT; + } + + simple_lock(&all_zones_lock, &zone_locks_grp); + max_zones = (unsigned int)(num_zones); + simple_unlock(&all_zones_lock); + + 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; + + 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++; + } + } + + *namesp = (mach_zone_name_t *) create_vm_map_copy(names_addr, names_size, logged_zones * sizeof *names); + *namesCntp = logged_zones; + + return KERN_SUCCESS; + +#else /* DEBUG || DEVELOPMENT */ +#pragma unused(host, namesp, namesCntp) + return KERN_FAILURE; +#endif /* DEBUG || DEVELOPMENT */ +} + +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 max_zones, i, 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; + } + + if (recsp == NULL || recsCntp == NULL) { + return KERN_INVALID_ARGUMENT; + } + + simple_lock(&all_zones_lock, &zone_locks_grp); + max_zones = (unsigned int)(num_zones); + simple_unlock(&all_zones_lock); + + zone_ptr = ZONE_NULL; + for (i = 0; i < max_zones; i++) { + zone_t z = &(zone_array[i]); + assert(z != ZONE_NULL); + + /* Find the requested zone by name */ + if (track_this_zone(z->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; + } + + /* Logging not turned on for the requested zone */ + if (!DO_LOGGING(zone_ptr)) { + return KERN_FAILURE; + } + + /* Allocate memory for btlog records */ + numrecs = (unsigned int)(get_btlog_records_count(zone_ptr->zlog_btlog)); + recs_size = round_page(numrecs * sizeof *recs); + + kr = kmem_alloc_pageable(ipc_kernel_map, &recs_addr, recs_size, VM_KERN_MEMORY_IPC); + if (kr != KERN_SUCCESS) { + return kr; + } + + /* + * 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_unwire(ipc_kernel_map, recs_addr, recs_addr + recs_size, FALSE); + assert(kr == KERN_SUCCESS); + + *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 */ +} + + #if DEBUG || DEVELOPMENT kern_return_t mach_memory_info_check(void) { - mach_memory_info_t * memory_info; - mach_memory_info_t * info; - zone_t zone; - unsigned int idx, num_info, max_zones; - vm_offset_t memory_info_addr; + mach_memory_info_t * memory_info; + mach_memory_info_t * info; + zone_t zone; + unsigned int idx, num_info, max_zones; + vm_offset_t memory_info_addr; kern_return_t kr; - size_t memory_info_size, memory_info_vmsize; + 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); + assert(kr == KERN_SUCCESS); memory_info = (mach_memory_info_t *) memory_info_addr; vm_page_diagnose(memory_info, num_info, 0); - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = num_zones; simple_unlock(&all_zones_lock); - top_wired = total = zonestotal = 0; - for (idx = 0; idx < max_zones; idx++) - { + top_wired = total = zonestotal = 0; + for (idx = 0; idx < max_zones; idx++) { zone = &(zone_array[idx]); assert(zone != ZONE_NULL); lock_zone(zone); - zonestotal += ptoa_64(zone->page_count); + zonestotal += ptoa_64(zone->page_count); unlock_zone(zone); } - for (idx = 0; idx < num_info; idx++) - { + for (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; + 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; 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); + kmem_free(kernel_map, memory_info_addr, memory_info_vmsize); - return (kr); + return kr; } +extern boolean_t(*volatile consider_buffer_cache_collect)(int); + #endif /* DEBUG || DEVELOPMENT */ kern_return_t mach_zone_force_gc( host_t host) { - if (host == HOST_NULL) + 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); + 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 - zone_t zone_find_largest(void) { unsigned int i; unsigned int max_zones; - zone_t the_zone; + zone_t the_zone; zone_t zone_largest; - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = num_zones; simple_unlock(&all_zones_lock); - + zone_largest = &(zone_array[0]); for (i = 0; i < max_zones; i++) { the_zone = &(zone_array[i]); @@ -4280,17 +4825,17 @@ zone_find_largest(void) return zone_largest; } -#if ZONE_DEBUG +#if ZONE_DEBUG /* should we care about locks here ? */ -#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))) +#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))) -#endif /* ZONE_DEBUG */ +#endif /* ZONE_DEBUG */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ @@ -4300,156 +4845,169 @@ zone_find_largest(void) static uintptr_t * zone_copy_all_allocations_inqueue(zone_t z, queue_head_t * queue, uintptr_t * elems) { - struct zone_page_metadata *page_meta; - vm_offset_t free, elements; - vm_offset_t idx, numElements, freeCount, bytesAvail, metaSize; - - queue_iterate(queue, page_meta, struct zone_page_metadata *, pages) - { - elements = get_zone_page(page_meta); - bytesAvail = ptoa(page_meta->page_count); - freeCount = 0; - if (z->allows_foreign && !from_zone_map(elements, z->elem_size)) - { - metaSize = (sizeof(struct zone_page_metadata) + ZONE_ELEMENT_ALIGNMENT - 1) & ~(ZONE_ELEMENT_ALIGNMENT - 1); - bytesAvail -= metaSize; - elements += metaSize; - } - numElements = bytesAvail / z->elem_size; - // construct array of all possible elements - for (idx = 0; idx < numElements; idx++) - { - elems[idx] = INSTANCE_PUT(elements + idx * z->elem_size); - } - // remove from the array all free elements - free = (vm_offset_t)page_metadata_get_freelist(page_meta); - while (free) - { - // find idx of free element - for (idx = 0; (idx < numElements) && (elems[idx] != INSTANCE_PUT(free)); idx++) {} - assert(idx < numElements); - // remove it - bcopy(&elems[idx + 1], &elems[idx], (numElements - (idx + 1)) * sizeof(elems[0])); - numElements--; - freeCount++; - // next free element - vm_offset_t *primary = (vm_offset_t *) free; - free = *primary ^ zp_nopoison_cookie; - } - elems += numElements; - } - - return (elems); + struct zone_page_metadata *page_meta; + vm_offset_t free, elements; + vm_offset_t idx, numElements, freeCount, bytesAvail, metaSize; + + queue_iterate(queue, page_meta, struct zone_page_metadata *, pages) + { + elements = get_zone_page(page_meta); + bytesAvail = ptoa(page_meta->page_count); + freeCount = 0; + if (z->allows_foreign && !from_zone_map(elements, z->elem_size)) { + metaSize = (sizeof(struct zone_page_metadata) + ZONE_ELEMENT_ALIGNMENT - 1) & ~(ZONE_ELEMENT_ALIGNMENT - 1); + bytesAvail -= metaSize; + elements += metaSize; + } + numElements = bytesAvail / z->elem_size; + // construct array of all possible elements + for (idx = 0; idx < numElements; idx++) { + elems[idx] = INSTANCE_PUT(elements + idx * z->elem_size); + } + // remove from the array all free elements + free = (vm_offset_t)page_metadata_get_freelist(page_meta); + while (free) { + // find idx of free element + for (idx = 0; (idx < numElements) && (elems[idx] != INSTANCE_PUT(free)); idx++) { + } + assert(idx < numElements); + // remove it + bcopy(&elems[idx + 1], &elems[idx], (numElements - (idx + 1)) * sizeof(elems[0])); + numElements--; + freeCount++; + // next free element + vm_offset_t *primary = (vm_offset_t *) free; + free = *primary ^ zp_nopoison_cookie; + } + elems += numElements; + } + + return elems; } 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; - 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; + uintptr_t zbt[MAX_ZTRACE_DEPTH]; + zone_t zone; + 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; unsigned int max_zones; kern_return_t kr; - simple_lock(&all_zones_lock); + simple_lock(&all_zones_lock, &zone_locks_grp); max_zones = num_zones; simple_unlock(&all_zones_lock); - for (idx = 0; idx < max_zones; idx++) - { - if (!strncmp(zoneName, zone_array[idx].zone_name, nameLen)) break; - } - if (idx >= max_zones) return (KERN_INVALID_NAME); - zone = &zone_array[idx]; - - elemSize = (uint32_t) zone->elem_size; - maxElems = ptoa(zone->page_count) / elemSize; - - if ((zone->alloc_size % elemSize) - && !leak_scan_debug_flag) return (KERN_INVALID_CAPABILITY); - - kr = kmem_alloc_kobject(kernel_map, (vm_offset_t *) &array, - maxElems * sizeof(uintptr_t), VM_KERN_MEMORY_DIAG); - if (KERN_SUCCESS != kr) return (kr); - - lock_zone(zone); - - next = array; - next = zone_copy_all_allocations_inqueue(zone, &zone->pages.any_free_foreign, next); - next = zone_copy_all_allocations_inqueue(zone, &zone->pages.intermediate, next); - next = zone_copy_all_allocations_inqueue(zone, &zone->pages.all_used, next); - count = (uint32_t)(next - array); - - unlock_zone(zone); - - zone_leaks_scan(array, count, (uint32_t)zone->elem_size, &found); - assert(found <= count); - - for (idx = 0; idx < count; idx++) - { - element = array[idx]; - if (kInstanceFlagReferenced & element) continue; - element = INSTANCE_PUT(element) & ~kInstanceFlags; - } - - 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); - } - - for (nobtcount = idx = 0; idx < count; idx++) - { - element = array[idx]; - if (!element) continue; - if (kInstanceFlagReferenced & element) continue; - element = INSTANCE_PUT(element) & ~kInstanceFlags; - - // see if we can find any backtrace left in the element - btcount = (typeof(btcount)) (zone->elem_size / 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); - } - - kmem_free(kernel_map, (vm_offset_t) array, maxElems * sizeof(uintptr_t)); - - return (KERN_SUCCESS); + for (idx = 0; idx < max_zones; idx++) { + if (!strncmp(zoneName, zone_array[idx].zone_name, nameLen)) { + break; + } + } + if (idx >= max_zones) { + return KERN_INVALID_NAME; + } + zone = &zone_array[idx]; + + elemSize = (uint32_t) zone->elem_size; + maxElems = ptoa(zone->page_count) / elemSize; + + if ((zone->alloc_size % elemSize) + && !leak_scan_debug_flag) { + return KERN_INVALID_CAPABILITY; + } + + kr = kmem_alloc_kobject(kernel_map, (vm_offset_t *) &array, + maxElems * sizeof(uintptr_t), VM_KERN_MEMORY_DIAG); + if (KERN_SUCCESS != kr) { + return kr; + } + + lock_zone(zone); + + next = array; + next = zone_copy_all_allocations_inqueue(zone, &zone->pages.any_free_foreign, next); + next = zone_copy_all_allocations_inqueue(zone, &zone->pages.intermediate, next); + next = zone_copy_all_allocations_inqueue(zone, &zone->pages.all_used, next); + count = (uint32_t)(next - array); + + unlock_zone(zone); + + zone_leaks_scan(array, count, (uint32_t)zone->elem_size, &found); + assert(found <= count); + + for (idx = 0; idx < count; idx++) { + element = array[idx]; + if (kInstanceFlagReferenced & element) { + continue; + } + element = INSTANCE_PUT(element) & ~kInstanceFlags; + } + + 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); + } + + for (nobtcount = idx = 0; idx < count; idx++) { + element = array[idx]; + if (!element) { + continue; + } + if (kInstanceFlagReferenced & element) { + continue; + } + element = INSTANCE_PUT(element) & ~kInstanceFlags; + + // see if we can find any backtrace left in the element + btcount = (typeof(btcount))(zone->elem_size / 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); + } + + kmem_free(kernel_map, (vm_offset_t) array, maxElems * sizeof(uintptr_t)); + + return KERN_SUCCESS; } boolean_t kdp_is_in_zone(void *addr, const char *zone_name) { zone_t z; - return (zone_element_size(addr, &z) && !strcmp(z->zone_name, zone_name)); + return zone_element_size(addr, &z) && !strcmp(z->zone_name, zone_name); } boolean_t run_zone_test(void) { - int i = 0, max_iter = 5; + unsigned int i = 0, max_iter = 5; void * test_ptr; zone_t test_zone; - simple_lock(&zone_test_lock); + simple_lock(&zone_test_lock, &zone_locks_grp); if (!zone_test_running) { zone_test_running = TRUE; } else { @@ -4502,7 +5060,7 @@ run_zone_test(void) printf("run_zone_test: Test passed\n"); - simple_lock(&zone_test_lock); + simple_lock(&zone_test_lock, &zone_locks_grp); zone_test_running = FALSE; simple_unlock(&zone_test_lock);