xref: /xnu-8020.140.41/osfmk/kern/gzalloc.c (revision 27b03b360a988dfd3dfdf34262bb0042026747cc)
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  *	File:	kern/gzalloc.c
30  *	Author:	Derek Kumar
31  *
32  *	"Guard mode" zone allocator, used to trap use-after-free errors,
33  *	overruns, underruns, mismatched allocations/frees, uninitialized
34  *	zone element use, timing dependent races etc.
35  *
36  *	The allocator is configured by these boot-args:
37  *	gzalloc_size=<size>: target all zones with elements of <size> bytes
38  *	gzalloc_min=<size>: target zones with elements >= size
39  *	gzalloc_max=<size>: target zones with elements <= size
40  *      gzalloc_min/max can be specified in conjunction to target a range of
41  *	sizes
42  *	gzalloc_fc_size=<size>: number of zone elements (effectively page
43  *	multiple sized) to retain in the free VA cache. This cache is evicted
44  *	(backing pages and VA released) in a least-recently-freed fashion.
45  *	Larger free VA caches allow for a longer window of opportunity to trap
46  *	delayed use-after-free operations, but use more memory.
47  *	-gzalloc_wp: Write protect, rather than unmap, freed allocations
48  *	lingering in the free VA cache. Useful to disambiguate between
49  *	read-after-frees/read overruns and writes. Also permits direct inspection
50  *	of the freed element in the cache via the kernel debugger. As each
51  *	element has a "header" (trailer in underflow detection mode), the zone
52  *	of origin of the element can be easily determined in this mode.
53  *	-gzalloc_uf_mode: Underflow detection mode, where the guard page
54  *	adjoining each element is placed *before* the element page rather than
55  *	after. The element is also located at the top of the page, rather than
56  *	abutting the bottom as with the standard overflow detection mode.
57  *	-gzalloc_noconsistency: disable consistency checks that flag mismatched
58  *	frees, corruptions of the header/trailer signatures etc.
59  *	-nogzalloc_mode: Disables the guard mode allocator. The DEBUG kernel
60  *	enables the guard allocator for zones sized 1K (if present) by
61  *	default, this option can disable that behaviour.
62  *	gzname=<name> target a zone by name. Can be coupled with size-based
63  *	targeting. Naming conventions match those of the zlog boot-arg, i.e.
64  *	"a period in the logname will match a space in the zone name"
65  *	-gzalloc_no_dfree_check Eliminate double free checks
66  *	gzalloc_zscale=<value> specify size multiplier for the dedicated gzalloc submap
67  */
68 
69 #include <mach/mach_types.h>
70 #include <mach/vm_param.h>
71 #include <mach/kern_return.h>
72 #include <mach/machine/vm_types.h>
73 #include <mach_debug/zone_info.h>
74 #include <mach/vm_map.h>
75 
76 #include <kern/kern_types.h>
77 #include <kern/assert.h>
78 #include <kern/sched.h>
79 #include <kern/locks.h>
80 #include <kern/misc_protos.h>
81 #include <kern/zalloc_internal.h>
82 
83 #include <vm/pmap.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_kern.h>
86 #include <vm/vm_page.h>
87 
88 #include <pexpert/pexpert.h>
89 
90 #include <machine/machparam.h>
91 
92 #include <libkern/OSDebug.h>
93 #include <libkern/OSAtomic.h>
94 #include <sys/kdebug.h>
95 
96 boolean_t gzalloc_mode = FALSE;
97 uint32_t pdzalloc_count, pdzfree_count;
98 
99 #define GZALLOC_MIN_DEFAULT (1024)
100 #define GZDEADZONE ((zone_t) 0xDEAD201E)
101 #define GZALLOC_SIGNATURE (0xABADCAFE)
102 #define GZALLOC_RESERVE_SIZE_DEFAULT (2 * 1024 * 1024)
103 #define GZFC_DEFAULT_SIZE (1536)
104 
105 char gzalloc_fill_pattern = 0x67; /* 'g' */
106 
107 uint32_t gzalloc_min = ~0U;
108 uint32_t gzalloc_max = 0;
109 uint32_t gzalloc_size = 0;
110 uint64_t gzalloc_allocated, gzalloc_freed, gzalloc_early_alloc, gzalloc_early_free, gzalloc_wasted;
111 boolean_t gzalloc_uf_mode = FALSE, gzalloc_consistency_checks = TRUE, gzalloc_dfree_check = TRUE;
112 vm_prot_t gzalloc_prot = VM_PROT_NONE;
113 uint32_t gzalloc_guard = KMA_GUARD_LAST;
114 uint32_t gzfc_size = GZFC_DEFAULT_SIZE;
115 uint32_t gzalloc_zonemap_scale = 1;
116 
117 __startup_data
118 vm_map_size_t gzalloc_map_size = 0;
119 vm_map_t gzalloc_map;
120 struct kmem_range gzalloc_range;
121 vm_offset_t gzalloc_reserve;
122 vm_size_t gzalloc_reserve_size;
123 
124 typedef struct gzalloc_header {
125 	zone_t gzone;
126 	uint32_t  gzsize;
127 	uint32_t  gzsig;
128 } gzhdr_t;
129 
130 #define GZHEADER_SIZE (sizeof(gzhdr_t))
131 
132 extern zone_t vm_page_zone;
133 
134 static zone_t gztrackzone = NULL;
135 static char gznamedzone[MAX_ZONE_NAME] = "";
136 
137 boolean_t
gzalloc_enabled(void)138 gzalloc_enabled(void)
139 {
140 	return gzalloc_mode;
141 }
142 
143 void
gzalloc_zone_init(zone_t z)144 gzalloc_zone_init(zone_t z)
145 {
146 	if (gzalloc_mode == 0) {
147 		return;
148 	}
149 
150 	bzero(&z->gz, sizeof(z->gz));
151 
152 	if (track_this_zone(z->z_name, gznamedzone)) {
153 		gztrackzone = z;
154 	}
155 
156 	z->z_gzalloc_tracked = (z == gztrackzone) ||
157 	    ((zone_elem_size(z) >= gzalloc_min) && (zone_elem_size(z) <= gzalloc_max));
158 
159 	if (gzfc_size && z->z_gzalloc_tracked) {
160 		vm_size_t gzfcsz = round_page(sizeof(*z->gz.gzfc) * gzfc_size);
161 
162 		/* If the VM/kmem system aren't yet configured, carve
163 		 * out the free element cache structure directly from the
164 		 * gzalloc_reserve supplied by the pmap layer.
165 		 */
166 		if (__improbable(startup_phase < STARTUP_SUB_KMEM)) {
167 			if (gzalloc_reserve_size < gzfcsz) {
168 				panic("gzalloc reserve exhausted");
169 			}
170 
171 			z->gz.gzfc = (vm_offset_t *)gzalloc_reserve;
172 			gzalloc_reserve += gzfcsz;
173 			gzalloc_reserve_size -= gzfcsz;
174 			bzero(z->gz.gzfc, gzfcsz);
175 		} else {
176 			kernel_memory_allocate(kernel_map,
177 			    (vm_offset_t *)&z->gz.gzfc, gzfcsz, 0,
178 			    KMA_NOFAIL | KMA_KOBJECT | KMA_ZERO, VM_KERN_MEMORY_OSFMK);
179 		}
180 	}
181 }
182 
183 /* Called by zdestroy() to dump the free cache elements so the zone count can drop to zero. */
184 void
gzalloc_empty_free_cache(zone_t zone)185 gzalloc_empty_free_cache(zone_t zone)
186 {
187 	int freed_elements = 0;
188 	vm_offset_t free_addr = 0;
189 	vm_offset_t rounded_size = round_page(zone_elem_size(zone) + GZHEADER_SIZE);
190 	vm_offset_t gzfcsz = round_page(sizeof(*zone->gz.gzfc) * gzfc_size);
191 	vm_offset_t gzfc_copy;
192 
193 	assert(zone->z_gzalloc_tracked); // the caller is responsible for checking
194 
195 	kernel_memory_allocate(kernel_map, &gzfc_copy, gzfcsz, 0,
196 	    KMA_NOFAIL, VM_KERN_MEMORY_OSFMK);
197 
198 	/* Reset gzalloc_data. */
199 	zone_lock(zone);
200 	memcpy((void *)gzfc_copy, (void *)zone->gz.gzfc, gzfcsz);
201 	bzero((void *)zone->gz.gzfc, gzfcsz);
202 	zone->gz.gzfc_index = 0;
203 	zone_unlock(zone);
204 
205 	/* Free up all the cached elements. */
206 	for (uint32_t index = 0; index < gzfc_size; index++) {
207 		free_addr = ((vm_offset_t *)gzfc_copy)[index];
208 		if (free_addr && kmem_range_contains(&gzalloc_range, free_addr)) {
209 			kmem_free(gzalloc_map, free_addr, rounded_size + PAGE_SIZE);
210 			OSAddAtomic64((SInt32)rounded_size, &gzalloc_freed);
211 			OSAddAtomic64(-((SInt32) (rounded_size - zone_elem_size(zone))), &gzalloc_wasted);
212 
213 			freed_elements++;
214 		}
215 	}
216 	/*
217 	 * TODO: Consider freeing up zone->gz.gzfc as well if it didn't come from the gzalloc_reserve pool.
218 	 * For now we're reusing this buffer across zdestroy's. We would have to allocate it again on a
219 	 * subsequent zinit() as well.
220 	 */
221 
222 	/* Decrement zone counters. */
223 	zone_lock(zone);
224 	zone->z_elems_free += freed_elements;
225 	zone->z_wired_cur -= freed_elements;
226 	zone_unlock(zone);
227 
228 	kmem_free(kernel_map, gzfc_copy, gzfcsz);
229 }
230 
231 __startup_func
232 static void
gzalloc_configure(void)233 gzalloc_configure(void)
234 {
235 #if !KASAN_ZALLOC
236 	char temp_buf[16];
237 
238 	if (PE_parse_boot_argn("-gzalloc_mode", temp_buf, sizeof(temp_buf))) {
239 		gzalloc_mode = TRUE;
240 		gzalloc_min = GZALLOC_MIN_DEFAULT;
241 		gzalloc_max = ~0U;
242 	}
243 
244 	if (PE_parse_boot_argn("gzalloc_min", &gzalloc_min, sizeof(gzalloc_min))) {
245 		gzalloc_mode = TRUE;
246 		gzalloc_max = ~0U;
247 	}
248 
249 	if (PE_parse_boot_argn("gzalloc_max", &gzalloc_max, sizeof(gzalloc_max))) {
250 		gzalloc_mode = TRUE;
251 		if (gzalloc_min == ~0U) {
252 			gzalloc_min = 0;
253 		}
254 	}
255 
256 	if (PE_parse_boot_argn("gzalloc_size", &gzalloc_size, sizeof(gzalloc_size))) {
257 		gzalloc_min = gzalloc_max = gzalloc_size;
258 		gzalloc_mode = TRUE;
259 	}
260 
261 	(void)PE_parse_boot_argn("gzalloc_fc_size", &gzfc_size, sizeof(gzfc_size));
262 
263 	if (PE_parse_boot_argn("-gzalloc_wp", temp_buf, sizeof(temp_buf))) {
264 		gzalloc_prot = VM_PROT_READ;
265 	}
266 
267 	if (PE_parse_boot_argn("-gzalloc_uf_mode", temp_buf, sizeof(temp_buf))) {
268 		gzalloc_uf_mode = TRUE;
269 		gzalloc_guard = KMA_GUARD_FIRST;
270 	}
271 
272 	if (PE_parse_boot_argn("-gzalloc_no_dfree_check", temp_buf, sizeof(temp_buf))) {
273 		gzalloc_dfree_check = FALSE;
274 	}
275 
276 	(void) PE_parse_boot_argn("gzalloc_zscale", &gzalloc_zonemap_scale, sizeof(gzalloc_zonemap_scale));
277 
278 	if (PE_parse_boot_argn("-gzalloc_noconsistency", temp_buf, sizeof(temp_buf))) {
279 		gzalloc_consistency_checks = FALSE;
280 	}
281 
282 	if (PE_parse_boot_argn("gzname", gznamedzone, sizeof(gznamedzone))) {
283 		gzalloc_mode = TRUE;
284 	}
285 #if DEBUG
286 	if (gzalloc_mode == FALSE) {
287 		gzalloc_min = 1024;
288 		gzalloc_max = 1024;
289 		strlcpy(gznamedzone, "pmap", sizeof(gznamedzone));
290 		gzalloc_prot = VM_PROT_READ;
291 		gzalloc_mode = TRUE;
292 	}
293 #endif
294 	if (PE_parse_boot_argn("-nogzalloc_mode", temp_buf, sizeof(temp_buf))) {
295 		gzalloc_mode = FALSE;
296 	}
297 
298 	if (gzalloc_mode) {
299 		gzalloc_reserve_size = GZALLOC_RESERVE_SIZE_DEFAULT;
300 		gzalloc_reserve = (vm_offset_t) pmap_steal_memory(gzalloc_reserve_size);
301 	}
302 #endif
303 }
304 STARTUP(PMAP_STEAL, STARTUP_RANK_FIRST, gzalloc_configure);
305 
306 KMEM_RANGE_REGISTER_DYNAMIC(gzalloc_map, &gzalloc_range, ^{
307 	if (gzalloc_mode) {
308 	        gzalloc_map_size = (zone_map_size * gzalloc_zonemap_scale);
309 	}
310 	return gzalloc_map_size;
311 });
312 
313 void
gzalloc_init(void)314 gzalloc_init(void)
315 {
316 	if (gzalloc_mode) {
317 		gzalloc_map = kmem_suballoc(kernel_map, &gzalloc_range.min_address,
318 		    gzalloc_map_size, VM_MAP_CREATE_DEFAULT,
319 		    VM_FLAGS_FIXED_RANGE_SUBALLOC, KMS_PERMANENT | KMS_NOFAIL,
320 		    VM_KERN_MEMORY_ZONE).kmr_submap;
321 	}
322 }
323 
324 vm_offset_t
gzalloc_alloc(zone_t zone,zone_stats_t zstats,zalloc_flags_t flags)325 gzalloc_alloc(zone_t zone, zone_stats_t zstats, zalloc_flags_t flags)
326 {
327 	vm_offset_t addr = 0;
328 
329 	assert(zone->z_gzalloc_tracked); // the caller is responsible for checking
330 
331 	if (get_preemption_level() != 0) {
332 		if (flags & Z_NOWAIT) {
333 			return 0;
334 		}
335 		pdzalloc_count++;
336 	}
337 
338 	bool kmem_ready = (startup_phase >= STARTUP_SUB_KMEM);
339 	vm_offset_t rounded_size = round_page(zone_elem_size(zone) + GZHEADER_SIZE);
340 	vm_offset_t residue = rounded_size - zone_elem_size(zone);
341 	vm_offset_t gzaddr = 0;
342 	gzhdr_t *gzh, *gzhcopy = NULL;
343 	bool new_va = false;
344 
345 	if (!kmem_ready || (vm_page_zone == ZONE_NULL)) {
346 		/* Early allocations are supplied directly from the
347 		 * reserve.
348 		 */
349 		if (gzalloc_reserve_size < (rounded_size + PAGE_SIZE)) {
350 			panic("gzalloc reserve exhausted");
351 		}
352 		gzaddr = gzalloc_reserve;
353 		/* No guard page for these early allocations, just
354 		 * waste an additional page.
355 		 */
356 		gzalloc_reserve += rounded_size + PAGE_SIZE;
357 		gzalloc_reserve_size -= rounded_size + PAGE_SIZE;
358 		OSAddAtomic64((SInt32) (rounded_size), &gzalloc_early_alloc);
359 	} else {
360 		kernel_memory_allocate(gzalloc_map,
361 		    &gzaddr, rounded_size + PAGE_SIZE, 0,
362 		    KMA_NOFAIL | KMA_ZERO | KMA_KOBJECT | gzalloc_guard,
363 		    VM_KERN_MEMORY_OSFMK);
364 		new_va = true;
365 	}
366 
367 	if (gzalloc_uf_mode) {
368 		gzaddr += PAGE_SIZE;
369 		/* The "header" becomes a "footer" in underflow
370 		 * mode.
371 		 */
372 		gzh = (gzhdr_t *) (gzaddr + zone_elem_size(zone));
373 		addr = gzaddr;
374 		gzhcopy = (gzhdr_t *) (gzaddr + rounded_size - sizeof(gzhdr_t));
375 	} else {
376 		gzh = (gzhdr_t *) (gzaddr + residue - GZHEADER_SIZE);
377 		addr = (gzaddr + residue);
378 	}
379 
380 	/*
381 	 * All zone allocations are always zeroed
382 	 */
383 	bzero((void *)gzaddr, rounded_size);
384 
385 	gzh->gzone = (kmem_ready && vm_page_zone) ? zone : GZDEADZONE;
386 	gzh->gzsize = (uint32_t)zone_elem_size(zone);
387 	gzh->gzsig = GZALLOC_SIGNATURE;
388 
389 	/* In underflow detection mode, stash away a copy of the
390 	 * metadata at the edge of the allocated range, for
391 	 * retrieval by gzalloc_element_size()
392 	 */
393 	if (gzhcopy) {
394 		*gzhcopy = *gzh;
395 	}
396 
397 	zone_lock(zone);
398 	assert(zone->z_self == zone);
399 	zone->z_elems_free--;
400 	if (new_va) {
401 		zone->z_va_cur += 1;
402 	}
403 	zone->z_wired_cur += 1;
404 	zpercpu_get(zstats)->zs_mem_allocated += rounded_size;
405 	zone_unlock(zone);
406 
407 	OSAddAtomic64((SInt32) rounded_size, &gzalloc_allocated);
408 	OSAddAtomic64((SInt32) (rounded_size - zone_elem_size(zone)), &gzalloc_wasted);
409 
410 	return addr;
411 }
412 
413 void
gzalloc_free(zone_t zone,zone_stats_t zstats,void * addr)414 gzalloc_free(zone_t zone, zone_stats_t zstats, void *addr)
415 {
416 	kern_return_t kr;
417 
418 	assert(zone->z_gzalloc_tracked); // the caller is responsible for checking
419 
420 	gzhdr_t *gzh;
421 	vm_offset_t rounded_size = round_page(zone_elem_size(zone) + GZHEADER_SIZE);
422 	vm_offset_t residue = rounded_size - zone_elem_size(zone);
423 	vm_offset_t saddr;
424 	vm_offset_t free_addr = 0;
425 
426 	if (gzalloc_uf_mode) {
427 		gzh = (gzhdr_t *)((vm_offset_t)addr + zone_elem_size(zone));
428 		saddr = (vm_offset_t) addr - PAGE_SIZE;
429 	} else {
430 		gzh = (gzhdr_t *)((vm_offset_t)addr - GZHEADER_SIZE);
431 		saddr = ((vm_offset_t)addr) - residue;
432 	}
433 
434 	if ((saddr & PAGE_MASK) != 0) {
435 		panic("%s: invalid address supplied: "
436 		    "%p (adjusted: 0x%lx) for zone with element sized 0x%lx\n",
437 		    __func__, addr, saddr, zone_elem_size(zone));
438 	}
439 
440 	if (gzfc_size && gzalloc_dfree_check) {
441 		zone_lock(zone);
442 		assert(zone->z_self == zone);
443 		for (uint32_t gd = 0; gd < gzfc_size; gd++) {
444 			if (zone->gz.gzfc[gd] != saddr) {
445 				continue;
446 			}
447 			panic("%s: double free detected, freed address: 0x%lx, "
448 			    "current free cache index: %d, freed index: %d",
449 			    __func__, saddr, zone->gz.gzfc_index, gd);
450 		}
451 		zone_unlock(zone);
452 	}
453 
454 	if (gzalloc_consistency_checks) {
455 		if (gzh->gzsig != GZALLOC_SIGNATURE) {
456 			panic("GZALLOC signature mismatch for element %p, "
457 			    "expected 0x%x, found 0x%x",
458 			    addr, GZALLOC_SIGNATURE, gzh->gzsig);
459 		}
460 
461 		if (gzh->gzone != zone && (gzh->gzone != GZDEADZONE)) {
462 			panic("%s: Mismatched zone or under/overflow, "
463 			    "current zone: %p, recorded zone: %p, address: %p",
464 			    __func__, zone, gzh->gzone, (void *)addr);
465 		}
466 		/* Partially redundant given the zone check, but may flag header corruption */
467 		if (gzh->gzsize != zone_elem_size(zone)) {
468 			panic("Mismatched zfree or under/overflow for zone %p, "
469 			    "recorded size: 0x%x, element size: 0x%x, address: %p",
470 			    zone, gzh->gzsize, (uint32_t)zone_elem_size(zone), (void *)addr);
471 		}
472 
473 		char *gzc, *checkstart, *checkend;
474 		if (gzalloc_uf_mode) {
475 			checkstart = (char *) ((uintptr_t) gzh + sizeof(gzh));
476 			checkend = (char *) ((((vm_offset_t)addr) & ~PAGE_MASK) + PAGE_SIZE);
477 		} else {
478 			checkstart = (char *) trunc_page_64(addr);
479 			checkend = (char *)gzh;
480 		}
481 
482 		for (gzc = checkstart; gzc < checkend; gzc++) {
483 			if (*gzc == gzalloc_fill_pattern) {
484 				continue;
485 			}
486 			panic("%s: detected over/underflow, byte at %p, element %p, "
487 			    "contents 0x%x from 0x%lx byte sized zone (%s%s) "
488 			    "doesn't match fill pattern (%c)",
489 			    __func__, gzc, addr, *gzc, zone_elem_size(zone),
490 			    zone_heap_name(zone), zone->z_name, gzalloc_fill_pattern);
491 		}
492 	}
493 
494 	if ((startup_phase < STARTUP_SUB_KMEM) || gzh->gzone == GZDEADZONE) {
495 		/* For now, just leak frees of early allocations
496 		 * performed before kmem is fully configured.
497 		 * They don't seem to get freed currently;
498 		 * consider ml_static_mfree in the future.
499 		 */
500 		OSAddAtomic64((SInt32) (rounded_size), &gzalloc_early_free);
501 		return;
502 	}
503 
504 	if (get_preemption_level() != 0) {
505 		pdzfree_count++;
506 	}
507 
508 	if (gzfc_size) {
509 		/* Either write protect or unmap the newly freed
510 		 * allocation
511 		 */
512 		kr = vm_map_protect(gzalloc_map, saddr,
513 		    saddr + rounded_size + (1 * PAGE_SIZE),
514 		    gzalloc_prot, FALSE);
515 		if (kr != KERN_SUCCESS) {
516 			panic("%s: vm_map_protect: %p, 0x%x", __func__, (void *)saddr, kr);
517 		}
518 	} else {
519 		free_addr = saddr;
520 	}
521 
522 	zone_lock(zone);
523 	assert(zone->z_self == zone);
524 
525 	/* Insert newly freed element into the protected free element
526 	 * cache, and rotate out the LRU element.
527 	 */
528 	if (gzfc_size) {
529 		if (zone->gz.gzfc_index >= gzfc_size) {
530 			zone->gz.gzfc_index = 0;
531 		}
532 		free_addr = zone->gz.gzfc[zone->gz.gzfc_index];
533 		zone->gz.gzfc[zone->gz.gzfc_index++] = saddr;
534 	}
535 
536 	if (free_addr) {
537 		zone->z_elems_free++;
538 		zone->z_wired_cur -= 1;
539 	}
540 
541 	zpercpu_get(zstats)->zs_mem_freed += rounded_size;
542 	zone_unlock(zone);
543 
544 	if (free_addr) {
545 		// TODO: consider using physical reads to check for
546 		// corruption while on the protected freelist
547 		// (i.e. physical corruption)
548 		kmem_free(gzalloc_map, free_addr, rounded_size + PAGE_SIZE);
549 		// TODO: sysctl-ize for quick reference
550 		OSAddAtomic64((SInt32)rounded_size, &gzalloc_freed);
551 		OSAddAtomic64(-((SInt32) (rounded_size - zone_elem_size(zone))),
552 		    &gzalloc_wasted);
553 	}
554 }
555 
556 boolean_t
gzalloc_element_size(void * gzaddr,zone_t * z,vm_size_t * gzsz)557 gzalloc_element_size(void *gzaddr, zone_t *z, vm_size_t *gzsz)
558 {
559 	uintptr_t a = (uintptr_t)gzaddr;
560 	if (__improbable(gzalloc_mode && kmem_range_contains(&gzalloc_range, a))) {
561 		gzhdr_t *gzh;
562 		boolean_t       vmef;
563 		vm_map_entry_t  gzvme = NULL;
564 		vm_map_lock_read(gzalloc_map);
565 		vmef = vm_map_lookup_entry(gzalloc_map, (vm_map_offset_t)a, &gzvme);
566 		vm_map_unlock(gzalloc_map);
567 		if (vmef == FALSE) {
568 			panic("GZALLOC: unable to locate map entry for %p", (void *)a);
569 		}
570 		assertf(gzvme->vme_atomic != 0, "GZALLOC: VM map entry inconsistency, "
571 		    "vme: %p, start: %llu end: %llu", gzvme, gzvme->vme_start, gzvme->vme_end);
572 
573 		/* Locate the gzalloc metadata adjoining the element */
574 		if (gzalloc_uf_mode == TRUE) {
575 			/* In underflow detection mode, locate the map entry describing
576 			 * the element, and then locate the copy of the gzalloc
577 			 * header at the trailing edge of the range.
578 			 */
579 			gzh = (gzhdr_t *)(gzvme->vme_end - GZHEADER_SIZE);
580 		} else {
581 			/* In overflow detection mode, scan forward from
582 			 * the base of the map entry to locate the
583 			 * gzalloc header.
584 			 */
585 			uint32_t *p = (uint32_t*) gzvme->vme_start;
586 			while (p < (uint32_t *) gzvme->vme_end) {
587 				if (*p == GZALLOC_SIGNATURE) {
588 					break;
589 				} else {
590 					p++;
591 				}
592 			}
593 			if (p >= (uint32_t *) gzvme->vme_end) {
594 				panic("GZALLOC signature missing addr %p, zone %p", gzaddr, z);
595 			}
596 			p++;
597 			uintptr_t q = (uintptr_t) p;
598 			gzh = (gzhdr_t *) (q - sizeof(gzhdr_t));
599 		}
600 
601 		if (gzh->gzsig != GZALLOC_SIGNATURE) {
602 			panic("GZALLOC signature mismatch for element %p, expected 0x%x, found 0x%x",
603 			    (void *)a, GZALLOC_SIGNATURE, gzh->gzsig);
604 		}
605 
606 		*gzsz = zone_elem_size(gzh->gzone);
607 		if (__improbable(!gzh->gzone->z_gzalloc_tracked)) {
608 			panic("GZALLOC: zone mismatch (%p)", gzh->gzone);
609 		}
610 
611 		if (z) {
612 			*z = gzh->gzone;
613 		}
614 		return TRUE;
615 	} else {
616 		return FALSE;
617 	}
618 }
619