]> git.saurik.com Git - apple/xnu.git/blob - osfmk/kern/kalloc.c
ffe8d7658ae754edfaa683d4330d3d5151a98fd7
[apple/xnu.git] / osfmk / kern / kalloc.c
1 /*
2 * Copyright (c) 2000-2011 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * @OSF_COPYRIGHT@
30 */
31 /*
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34 * All Rights Reserved.
35 *
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
41 *
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45 *
46 * Carnegie Mellon requests users of this software to return to
47 *
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
52 *
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
55 */
56 /*
57 */
58 /*
59 * File: kern/kalloc.c
60 * Author: Avadis Tevanian, Jr.
61 * Date: 1985
62 *
63 * General kernel memory allocator. This allocator is designed
64 * to be used by the kernel to manage dynamic memory fast.
65 */
66
67 #include <zone_debug.h>
68
69 #include <mach/boolean.h>
70 #include <mach/sdt.h>
71 #include <mach/machine/vm_types.h>
72 #include <mach/vm_param.h>
73 #include <kern/misc_protos.h>
74 #include <kern/zalloc.h>
75 #include <kern/kalloc.h>
76 #include <kern/ledger.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_map.h>
80 #include <libkern/OSMalloc.h>
81 #include <sys/kdebug.h>
82
83 #include <san/kasan.h>
84
85 #ifdef MACH_BSD
86 zone_t kalloc_zone(vm_size_t);
87 #endif
88
89 #define KALLOC_MAP_SIZE_MIN (16 * 1024 * 1024)
90 #define KALLOC_MAP_SIZE_MAX (128 * 1024 * 1024)
91 vm_map_t kalloc_map;
92 vm_size_t kalloc_max;
93 vm_size_t kalloc_max_prerounded;
94 vm_size_t kalloc_kernmap_size; /* size of kallocs that can come from kernel map */
95
96 /* how many times we couldn't allocate out of kalloc_map and fell back to kernel_map */
97 unsigned long kalloc_fallback_count;
98
99 uint_t kalloc_large_inuse;
100 vm_size_t kalloc_large_total;
101 vm_size_t kalloc_large_max;
102 vm_size_t kalloc_largest_allocated = 0;
103 uint64_t kalloc_large_sum;
104
105 int kalloc_fake_zone_index = -1; /* index of our fake zone in statistics arrays */
106
107 vm_offset_t kalloc_map_min;
108 vm_offset_t kalloc_map_max;
109
110 #ifdef MUTEX_ZONE
111 /*
112 * Diagnostic code to track mutexes separately rather than via the 2^ zones
113 */
114 zone_t lck_mtx_zone;
115 #endif
116
117 static void
118 KALLOC_ZINFO_SALLOC(vm_size_t bytes)
119 {
120 thread_t thr = current_thread();
121 ledger_debit(thr->t_ledger, task_ledgers.tkm_shared, bytes);
122 }
123
124 static void
125 KALLOC_ZINFO_SFREE(vm_size_t bytes)
126 {
127 thread_t thr = current_thread();
128 ledger_credit(thr->t_ledger, task_ledgers.tkm_shared, bytes);
129 }
130
131 /*
132 * All allocations of size less than kalloc_max are rounded to the next nearest
133 * sized zone. This allocator is built on top of the zone allocator. A zone
134 * is created for each potential size that we are willing to get in small
135 * blocks.
136 *
137 * We assume that kalloc_max is not greater than 64K;
138 *
139 * Note that kalloc_max is somewhat confusingly named. It represents the first
140 * power of two for which no zone exists. kalloc_max_prerounded is the
141 * smallest allocation size, before rounding, for which no zone exists.
142 *
143 * Also if the allocation size is more than kalloc_kernmap_size then allocate
144 * from kernel map rather than kalloc_map.
145 */
146
147 #define KALLOC_MINALIGN (1 << KALLOC_LOG2_MINALIGN)
148 #define KiB(x) (1024 * (x))
149
150 /*
151 * The k_zone_config table defines the configuration of zones on various platforms.
152 * The currently defined list of zones and their per-CPU caching behavior are as
153 * follows (X:zone not present; N:zone present no cpu-caching; Y:zone present with cpu-caching):
154 *
155 * Size macOS(64-bit) embedded(32-bit) embedded(64-bit)
156 *-------- ---------------- ---------------- ----------------
157 *
158 * 8 X Y X
159 * 16 Y Y Y
160 * 24 X Y X
161 * 32 Y Y Y
162 * 40 X Y X
163 * 48 Y Y Y
164 * 64 Y Y Y
165 * 72 X Y X
166 * 80 Y X Y
167 * 88 X Y X
168 * 96 Y X Y
169 * 112 X Y X
170 * 128 Y Y Y
171 * 160 Y X Y
172 * 192 Y Y Y
173 * 224 Y X Y
174 * 256 Y Y Y
175 * 288 Y Y Y
176 * 368 Y X Y
177 * 384 X Y X
178 * 400 Y X Y
179 * 440 X Y X
180 * 512 Y Y Y
181 * 576 Y N N
182 * 768 Y N N
183 * 1024 Y Y Y
184 * 1152 N N N
185 * 1280 N N N
186 * 1536 X N X
187 * 1664 N X N
188 * 2048 Y N N
189 * 2128 X N X
190 * 3072 X N X
191 * 4096 Y N N
192 * 6144 N N N
193 * 8192 Y N N
194 * 12288 N X X
195 * 16384 N N N
196 * 32768 X N N
197 *
198 */
199 static const struct kalloc_zone_config {
200 bool kzc_caching;
201 int kzc_size;
202 const char *kzc_name;
203 } k_zone_config[] = {
204 #define KZC_ENTRY(SIZE, caching) { .kzc_caching = (caching), .kzc_size = (SIZE), .kzc_name = "kalloc." #SIZE }
205
206 #if CONFIG_EMBEDDED
207
208 #if KALLOC_MINSIZE == 16 && KALLOC_LOG2_MINALIGN == 4
209 /* Zone config for embedded 64-bit platforms */
210 KZC_ENTRY(16, true),
211 KZC_ENTRY(32, true),
212 KZC_ENTRY(48, true),
213 KZC_ENTRY(64, true),
214 KZC_ENTRY(80, true),
215 KZC_ENTRY(96, true),
216 KZC_ENTRY(128, true),
217 KZC_ENTRY(160, true),
218 KZC_ENTRY(192, true),
219 KZC_ENTRY(224, true),
220 KZC_ENTRY(256, true),
221 KZC_ENTRY(288, true),
222 KZC_ENTRY(368, true),
223 KZC_ENTRY(400, true),
224 KZC_ENTRY(512, true),
225 KZC_ENTRY(576, false),
226 KZC_ENTRY(768, false),
227 KZC_ENTRY(1024, true),
228 KZC_ENTRY(1152, false),
229 KZC_ENTRY(1280, false),
230 KZC_ENTRY(1664, false),
231 KZC_ENTRY(2048, false),
232 KZC_ENTRY(4096, false),
233 KZC_ENTRY(6144, false),
234 KZC_ENTRY(8192, false),
235 KZC_ENTRY(16384, false),
236 KZC_ENTRY(32768, false),
237
238 #elif KALLOC_MINSIZE == 8 && KALLOC_LOG2_MINALIGN == 3
239 /* Zone config for embedded 32-bit platforms */
240 KZC_ENTRY(8, true),
241 KZC_ENTRY(16, true),
242 KZC_ENTRY(24, true),
243 KZC_ENTRY(32, true),
244 KZC_ENTRY(40, true),
245 KZC_ENTRY(48, true),
246 KZC_ENTRY(64, true),
247 KZC_ENTRY(72, true),
248 KZC_ENTRY(88, true),
249 KZC_ENTRY(112, true),
250 KZC_ENTRY(128, true),
251 KZC_ENTRY(192, true),
252 KZC_ENTRY(256, true),
253 KZC_ENTRY(288, true),
254 KZC_ENTRY(384, true),
255 KZC_ENTRY(440, true),
256 KZC_ENTRY(512, true),
257 KZC_ENTRY(576, false),
258 KZC_ENTRY(768, false),
259 KZC_ENTRY(1024, true),
260 KZC_ENTRY(1152, false),
261 KZC_ENTRY(1280, false),
262 KZC_ENTRY(1536, false),
263 KZC_ENTRY(2048, false),
264 KZC_ENTRY(2128, false),
265 KZC_ENTRY(3072, false),
266 KZC_ENTRY(4096, false),
267 KZC_ENTRY(6144, false),
268 KZC_ENTRY(8192, false),
269 KZC_ENTRY(16384, false),
270 KZC_ENTRY(32768, false),
271
272 #else
273 #error missing or invalid zone size parameters for kalloc
274 #endif
275
276 #else /* CONFIG_EMBEDDED */
277
278 /* Zone config for macOS 64-bit platforms */
279 KZC_ENTRY(16, true),
280 KZC_ENTRY(32, true),
281 KZC_ENTRY(48, true),
282 KZC_ENTRY(64, true),
283 KZC_ENTRY(80, true),
284 KZC_ENTRY(96, true),
285 KZC_ENTRY(128, true),
286 KZC_ENTRY(160, true),
287 KZC_ENTRY(192, true),
288 KZC_ENTRY(224, true),
289 KZC_ENTRY(256, true),
290 KZC_ENTRY(288, true),
291 KZC_ENTRY(368, true),
292 KZC_ENTRY(400, true),
293 KZC_ENTRY(512, true),
294 KZC_ENTRY(576, true),
295 KZC_ENTRY(768, true),
296 KZC_ENTRY(1024, true),
297 KZC_ENTRY(1152, false),
298 KZC_ENTRY(1280, false),
299 KZC_ENTRY(1664, false),
300 KZC_ENTRY(2048, true),
301 KZC_ENTRY(4096, true),
302 KZC_ENTRY(6144, false),
303 KZC_ENTRY(8192, true),
304 KZC_ENTRY(12288, false),
305 KZC_ENTRY(16384, false)
306
307 #endif /* CONFIG_EMBEDDED */
308
309 #undef KZC_ENTRY
310 };
311
312 #define MAX_K_ZONE (int)(sizeof(k_zone_config) / sizeof(k_zone_config[0]))
313
314 /*
315 * Many kalloc() allocations are for small structures containing a few
316 * pointers and longs - the k_zone_dlut[] direct lookup table, indexed by
317 * size normalized to the minimum alignment, finds the right zone index
318 * for them in one dereference.
319 */
320
321 #define INDEX_ZDLUT(size) \
322 (((size) + KALLOC_MINALIGN - 1) / KALLOC_MINALIGN)
323 #define N_K_ZDLUT (2048 / KALLOC_MINALIGN)
324 /* covers sizes [0 .. 2048 - KALLOC_MINALIGN] */
325 #define MAX_SIZE_ZDLUT ((N_K_ZDLUT - 1) * KALLOC_MINALIGN)
326
327 static int8_t k_zone_dlut[N_K_ZDLUT]; /* table of indices into k_zone[] */
328
329 /*
330 * If there's no hit in the DLUT, then start searching from k_zindex_start.
331 */
332 static int k_zindex_start;
333
334 static zone_t k_zone[MAX_K_ZONE];
335
336 /* #define KALLOC_DEBUG 1 */
337
338 /* forward declarations */
339
340 lck_grp_t kalloc_lck_grp;
341 lck_mtx_t kalloc_lock;
342
343 #define kalloc_spin_lock() lck_mtx_lock_spin(&kalloc_lock)
344 #define kalloc_unlock() lck_mtx_unlock(&kalloc_lock)
345
346
347 /* OSMalloc local data declarations */
348 static
349 queue_head_t OSMalloc_tag_list;
350
351 lck_grp_t *OSMalloc_tag_lck_grp;
352 lck_mtx_t OSMalloc_tag_lock;
353
354 #define OSMalloc_tag_spin_lock() lck_mtx_lock_spin(&OSMalloc_tag_lock)
355 #define OSMalloc_tag_unlock() lck_mtx_unlock(&OSMalloc_tag_lock)
356
357
358 /* OSMalloc forward declarations */
359 void OSMalloc_init(void);
360 void OSMalloc_Tagref(OSMallocTag tag);
361 void OSMalloc_Tagrele(OSMallocTag tag);
362
363 /*
364 * Initialize the memory allocator. This should be called only
365 * once on a system wide basis (i.e. first processor to get here
366 * does the initialization).
367 *
368 * This initializes all of the zones.
369 */
370
371 void
372 kalloc_init(
373 void)
374 {
375 kern_return_t retval;
376 vm_offset_t min;
377 vm_size_t size, kalloc_map_size;
378 vm_map_kernel_flags_t vmk_flags;
379
380 /*
381 * Scale the kalloc_map_size to physical memory size: stay below
382 * 1/8th the total zone map size, or 128 MB (for a 32-bit kernel).
383 */
384 kalloc_map_size = (vm_size_t)(sane_size >> 5);
385 #if !__LP64__
386 if (kalloc_map_size > KALLOC_MAP_SIZE_MAX) {
387 kalloc_map_size = KALLOC_MAP_SIZE_MAX;
388 }
389 #endif /* !__LP64__ */
390 if (kalloc_map_size < KALLOC_MAP_SIZE_MIN) {
391 kalloc_map_size = KALLOC_MAP_SIZE_MIN;
392 }
393
394 vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
395 vmk_flags.vmkf_permanent = TRUE;
396
397 retval = kmem_suballoc(kernel_map, &min, kalloc_map_size,
398 FALSE,
399 (VM_FLAGS_ANYWHERE),
400 vmk_flags,
401 VM_KERN_MEMORY_KALLOC,
402 &kalloc_map);
403
404 if (retval != KERN_SUCCESS) {
405 panic("kalloc_init: kmem_suballoc failed");
406 }
407
408 kalloc_map_min = min;
409 kalloc_map_max = min + kalloc_map_size - 1;
410
411 kalloc_max = (k_zone_config[MAX_K_ZONE - 1].kzc_size << 1);
412 if (kalloc_max < KiB(16)) {
413 kalloc_max = KiB(16);
414 }
415 assert(kalloc_max <= KiB(64)); /* assumption made in size arrays */
416
417 kalloc_max_prerounded = kalloc_max / 2 + 1;
418 /* allocations larger than 16 times kalloc_max go directly to kernel map */
419 kalloc_kernmap_size = (kalloc_max * 16) + 1;
420 kalloc_largest_allocated = kalloc_kernmap_size;
421
422 /*
423 * Allocate a zone for each size we are going to handle.
424 */
425 for (int i = 0; i < MAX_K_ZONE && (size = k_zone_config[i].kzc_size) < kalloc_max; i++) {
426 k_zone[i] = zinit(size, size, size, k_zone_config[i].kzc_name);
427
428 /*
429 * Don't charge the caller for the allocation, as we aren't sure how
430 * the memory will be handled.
431 */
432 zone_change(k_zone[i], Z_CALLERACCT, FALSE);
433 #if VM_MAX_TAG_ZONES
434 if (zone_tagging_on) {
435 zone_change(k_zone[i], Z_TAGS_ENABLED, TRUE);
436 }
437 #endif
438 zone_change(k_zone[i], Z_KASAN_QUARANTINE, FALSE);
439 if (k_zone_config[i].kzc_caching) {
440 zone_change(k_zone[i], Z_CACHING_ENABLED, TRUE);
441 }
442 }
443
444 /*
445 * Build the Direct LookUp Table for small allocations
446 */
447 size = 0;
448 for (int i = 0; i <= N_K_ZDLUT; i++, size += KALLOC_MINALIGN) {
449 int zindex = 0;
450
451 while ((vm_size_t)k_zone_config[zindex].kzc_size < size) {
452 zindex++;
453 }
454
455 if (i == N_K_ZDLUT) {
456 k_zindex_start = zindex;
457 break;
458 }
459 k_zone_dlut[i] = (int8_t)zindex;
460 }
461
462 #ifdef KALLOC_DEBUG
463 printf("kalloc_init: k_zindex_start %d\n", k_zindex_start);
464
465 /*
466 * Do a quick synthesis to see how well/badly we can
467 * find-a-zone for a given size.
468 * Useful when debugging/tweaking the array of zone sizes.
469 * Cache misses probably more critical than compare-branches!
470 */
471 for (int i = 0; i < MAX_K_ZONE; i++) {
472 vm_size_t testsize = (vm_size_t)k_zone_config[i].kzc_size - 1;
473 int compare = 0;
474 int zindex;
475
476 if (testsize < MAX_SIZE_ZDLUT) {
477 compare += 1; /* 'if' (T) */
478
479 long dindex = INDEX_ZDLUT(testsize);
480 zindex = (int)k_zone_dlut[dindex];
481 } else if (testsize < kalloc_max_prerounded) {
482 compare += 2; /* 'if' (F), 'if' (T) */
483
484 zindex = k_zindex_start;
485 while ((vm_size_t)k_zone_config[zindex].kzc_size < testsize) {
486 zindex++;
487 compare++; /* 'while' (T) */
488 }
489 compare++; /* 'while' (F) */
490 } else {
491 break; /* not zone-backed */
492 }
493 zone_t z = k_zone[zindex];
494 printf("kalloc_init: req size %4lu: %11s took %d compare%s\n",
495 (unsigned long)testsize, z->zone_name, compare,
496 compare == 1 ? "" : "s");
497 }
498 #endif
499
500 lck_grp_init(&kalloc_lck_grp, "kalloc.large", LCK_GRP_ATTR_NULL);
501 lck_mtx_init(&kalloc_lock, &kalloc_lck_grp, LCK_ATTR_NULL);
502 OSMalloc_init();
503 #ifdef MUTEX_ZONE
504 lck_mtx_zone = zinit(sizeof(struct _lck_mtx_), 1024 * 256, 4096, "lck_mtx");
505 #endif
506 }
507
508 /*
509 * Given an allocation size, return the kalloc zone it belongs to.
510 * Direct LookUp Table variant.
511 */
512 static __inline zone_t
513 get_zone_dlut(vm_size_t size)
514 {
515 long dindex = INDEX_ZDLUT(size);
516 int zindex = (int)k_zone_dlut[dindex];
517 return k_zone[zindex];
518 }
519
520 /* As above, but linear search k_zone_config[] for the next zone that fits. */
521
522 static __inline zone_t
523 get_zone_search(vm_size_t size, int zindex)
524 {
525 assert(size < kalloc_max_prerounded);
526
527 while ((vm_size_t)k_zone_config[zindex].kzc_size < size) {
528 zindex++;
529 }
530
531 assert(zindex < MAX_K_ZONE &&
532 (vm_size_t)k_zone_config[zindex].kzc_size < kalloc_max);
533
534 return k_zone[zindex];
535 }
536
537 static vm_size_t
538 vm_map_lookup_kalloc_entry_locked(
539 vm_map_t map,
540 void *addr)
541 {
542 boolean_t ret;
543 vm_map_entry_t vm_entry = NULL;
544
545 ret = vm_map_lookup_entry(map, (vm_map_offset_t)addr, &vm_entry);
546 if (!ret) {
547 panic("Attempting to lookup/free an address not allocated via kalloc! (vm_map_lookup_entry() failed map: %p, addr: %p)\n",
548 map, addr);
549 }
550 if (vm_entry->vme_start != (vm_map_offset_t)addr) {
551 panic("Attempting to lookup/free the middle of a kalloc'ed element! (map: %p, addr: %p, entry: %p)\n",
552 map, addr, vm_entry);
553 }
554 if (!vm_entry->vme_atomic) {
555 panic("Attempting to lookup/free an address not managed by kalloc! (map: %p, addr: %p, entry: %p)\n",
556 map, addr, vm_entry);
557 }
558 return vm_entry->vme_end - vm_entry->vme_start;
559 }
560
561 #if KASAN_KALLOC
562 /*
563 * KASAN kalloc stashes the original user-requested size away in the poisoned
564 * area. Return that directly.
565 */
566 vm_size_t
567 kalloc_size(void *addr)
568 {
569 (void)vm_map_lookup_kalloc_entry_locked; /* silence warning */
570 return kasan_user_size((vm_offset_t)addr);
571 }
572 #else
573 vm_size_t
574 kalloc_size(
575 void *addr)
576 {
577 vm_map_t map;
578 vm_size_t size;
579
580 size = zone_element_size(addr, NULL);
581 if (size) {
582 return size;
583 }
584 if (((vm_offset_t)addr >= kalloc_map_min) && ((vm_offset_t)addr < kalloc_map_max)) {
585 map = kalloc_map;
586 } else {
587 map = kernel_map;
588 }
589 vm_map_lock_read(map);
590 size = vm_map_lookup_kalloc_entry_locked(map, addr);
591 vm_map_unlock_read(map);
592 return size;
593 }
594 #endif
595
596 vm_size_t
597 kalloc_bucket_size(
598 vm_size_t size)
599 {
600 zone_t z;
601 vm_map_t map;
602
603 if (size < MAX_SIZE_ZDLUT) {
604 z = get_zone_dlut(size);
605 return z->elem_size;
606 }
607
608 if (size < kalloc_max_prerounded) {
609 z = get_zone_search(size, k_zindex_start);
610 return z->elem_size;
611 }
612
613 if (size >= kalloc_kernmap_size) {
614 map = kernel_map;
615 } else {
616 map = kalloc_map;
617 }
618
619 return vm_map_round_page(size, VM_MAP_PAGE_MASK(map));
620 }
621
622 #if KASAN_KALLOC
623 vm_size_t
624 (kfree_addr)(void *addr)
625 {
626 vm_size_t origsz = kalloc_size(addr);
627 kfree(addr, origsz);
628 return origsz;
629 }
630 #else
631 vm_size_t
632 (kfree_addr)(
633 void *addr)
634 {
635 vm_map_t map;
636 vm_size_t size = 0;
637 kern_return_t ret;
638 zone_t z;
639
640 size = zone_element_size(addr, &z);
641 if (size) {
642 DTRACE_VM3(kfree, vm_size_t, -1, vm_size_t, z->elem_size, void*, addr);
643 zfree(z, addr);
644 return size;
645 }
646
647 if (((vm_offset_t)addr >= kalloc_map_min) && ((vm_offset_t)addr < kalloc_map_max)) {
648 map = kalloc_map;
649 } else {
650 map = kernel_map;
651 }
652 if ((vm_offset_t)addr < VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
653 panic("kfree on an address not in the kernel & kext address range! addr: %p\n", addr);
654 }
655
656 vm_map_lock(map);
657 size = vm_map_lookup_kalloc_entry_locked(map, addr);
658 ret = vm_map_remove_locked(map,
659 vm_map_trunc_page((vm_map_offset_t)addr,
660 VM_MAP_PAGE_MASK(map)),
661 vm_map_round_page((vm_map_offset_t)addr + size,
662 VM_MAP_PAGE_MASK(map)),
663 VM_MAP_REMOVE_KUNWIRE);
664 if (ret != KERN_SUCCESS) {
665 panic("vm_map_remove_locked() failed for kalloc vm_entry! addr: %p, map: %p ret: %d\n",
666 addr, map, ret);
667 }
668 vm_map_unlock(map);
669 DTRACE_VM3(kfree, vm_size_t, -1, vm_size_t, size, void*, addr);
670
671 kalloc_spin_lock();
672 assert(kalloc_large_total >= size);
673 kalloc_large_total -= size;
674 kalloc_large_inuse--;
675 kalloc_unlock();
676
677 KALLOC_ZINFO_SFREE(size);
678 return size;
679 }
680 #endif
681
682 void *
683 kalloc_canblock(
684 vm_size_t *psize,
685 boolean_t canblock,
686 vm_allocation_site_t *site)
687 {
688 zone_t z;
689 vm_size_t size;
690 void *addr;
691 vm_tag_t tag;
692
693 tag = VM_KERN_MEMORY_KALLOC;
694 size = *psize;
695
696 #if KASAN_KALLOC
697 /* expand the allocation to accomodate redzones */
698 vm_size_t req_size = size;
699 size = kasan_alloc_resize(req_size);
700 #endif
701
702 if (size < MAX_SIZE_ZDLUT) {
703 z = get_zone_dlut(size);
704 } else if (size < kalloc_max_prerounded) {
705 z = get_zone_search(size, k_zindex_start);
706 } else {
707 /*
708 * If size is too large for a zone, then use kmem_alloc.
709 * (We use kmem_alloc instead of kmem_alloc_kobject so that
710 * krealloc can use kmem_realloc.)
711 */
712 vm_map_t alloc_map;
713
714 /* kmem_alloc could block so we return if noblock */
715 if (!canblock) {
716 return NULL;
717 }
718
719 #if KASAN_KALLOC
720 /* large allocation - use guard pages instead of small redzones */
721 size = round_page(req_size + 2 * PAGE_SIZE);
722 assert(size >= MAX_SIZE_ZDLUT && size >= kalloc_max_prerounded);
723 #else
724 size = round_page(size);
725 #endif
726
727 if (size >= kalloc_kernmap_size) {
728 alloc_map = kernel_map;
729 } else {
730 alloc_map = kalloc_map;
731 }
732
733 if (site) {
734 tag = vm_tag_alloc(site);
735 }
736
737 if (kmem_alloc_flags(alloc_map, (vm_offset_t *)&addr, size, tag, KMA_ATOMIC) != KERN_SUCCESS) {
738 if (alloc_map != kernel_map) {
739 if (kalloc_fallback_count++ == 0) {
740 printf("%s: falling back to kernel_map\n", __func__);
741 }
742 if (kmem_alloc_flags(kernel_map, (vm_offset_t *)&addr, size, tag, KMA_ATOMIC) != KERN_SUCCESS) {
743 addr = NULL;
744 }
745 } else {
746 addr = NULL;
747 }
748 }
749
750 if (addr != NULL) {
751 kalloc_spin_lock();
752 /*
753 * Thread-safe version of the workaround for 4740071
754 * (a double FREE())
755 */
756 if (size > kalloc_largest_allocated) {
757 kalloc_largest_allocated = size;
758 }
759
760 kalloc_large_inuse++;
761 assert(kalloc_large_total + size >= kalloc_large_total); /* no wrap around */
762 kalloc_large_total += size;
763 kalloc_large_sum += size;
764
765 if (kalloc_large_total > kalloc_large_max) {
766 kalloc_large_max = kalloc_large_total;
767 }
768
769 kalloc_unlock();
770
771 KALLOC_ZINFO_SALLOC(size);
772 }
773 #if KASAN_KALLOC
774 /* fixup the return address to skip the redzone */
775 addr = (void *)kasan_alloc((vm_offset_t)addr, size, req_size, PAGE_SIZE);
776 #else
777 *psize = size;
778 #endif
779 DTRACE_VM3(kalloc, vm_size_t, size, vm_size_t, *psize, void*, addr);
780 return addr;
781 }
782 #ifdef KALLOC_DEBUG
783 if (size > z->elem_size) {
784 panic("%s: z %p (%s) but requested size %lu", __func__,
785 z, z->zone_name, (unsigned long)size);
786 }
787 #endif
788
789 assert(size <= z->elem_size);
790
791 #if VM_MAX_TAG_ZONES
792 if (z->tags && site) {
793 tag = vm_tag_alloc(site);
794 if (!canblock && !vm_allocation_zone_totals[tag]) {
795 tag = VM_KERN_MEMORY_KALLOC;
796 }
797 }
798 #endif
799
800 addr = zalloc_canblock_tag(z, canblock, size, tag);
801
802 #if KASAN_KALLOC
803 /* fixup the return address to skip the redzone */
804 addr = (void *)kasan_alloc((vm_offset_t)addr, z->elem_size, req_size, KASAN_GUARD_SIZE);
805
806 /* For KASan, the redzone lives in any additional space, so don't
807 * expand the allocation. */
808 #else
809 *psize = z->elem_size;
810 #endif
811
812 DTRACE_VM3(kalloc, vm_size_t, size, vm_size_t, *psize, void*, addr);
813 return addr;
814 }
815
816 void *
817 kalloc_external(
818 vm_size_t size);
819 void *
820 kalloc_external(
821 vm_size_t size)
822 {
823 return kalloc_tag_bt(size, VM_KERN_MEMORY_KALLOC);
824 }
825
826 void
827 (kfree)(
828 void *data,
829 vm_size_t size)
830 {
831 zone_t z;
832
833 #if KASAN_KALLOC
834 /*
835 * Resize back to the real allocation size and hand off to the KASan
836 * quarantine. `data` may then point to a different allocation.
837 */
838 vm_size_t user_size = size;
839 kasan_check_free((vm_address_t)data, size, KASAN_HEAP_KALLOC);
840 data = (void *)kasan_dealloc((vm_address_t)data, &size);
841 kasan_free(&data, &size, KASAN_HEAP_KALLOC, NULL, user_size, true);
842 if (!data) {
843 return;
844 }
845 #endif
846
847 if (size < MAX_SIZE_ZDLUT) {
848 z = get_zone_dlut(size);
849 } else if (size < kalloc_max_prerounded) {
850 z = get_zone_search(size, k_zindex_start);
851 } else {
852 /* if size was too large for a zone, then use kmem_free */
853
854 vm_map_t alloc_map = kernel_map;
855
856 if ((((vm_offset_t) data) >= kalloc_map_min) && (((vm_offset_t) data) <= kalloc_map_max)) {
857 alloc_map = kalloc_map;
858 }
859 if (size > kalloc_largest_allocated) {
860 panic("kfree: size %lu > kalloc_largest_allocated %lu", (unsigned long)size, (unsigned long)kalloc_largest_allocated);
861 }
862 kmem_free(alloc_map, (vm_offset_t)data, size);
863 kalloc_spin_lock();
864
865 assert(kalloc_large_total >= size);
866 kalloc_large_total -= size;
867 kalloc_large_inuse--;
868
869 kalloc_unlock();
870
871 #if !KASAN_KALLOC
872 DTRACE_VM3(kfree, vm_size_t, size, vm_size_t, size, void*, data);
873 #endif
874
875 KALLOC_ZINFO_SFREE(size);
876 return;
877 }
878
879 /* free to the appropriate zone */
880 #ifdef KALLOC_DEBUG
881 if (size > z->elem_size) {
882 panic("%s: z %p (%s) but requested size %lu", __func__,
883 z, z->zone_name, (unsigned long)size);
884 }
885 #endif
886 assert(size <= z->elem_size);
887 #if !KASAN_KALLOC
888 DTRACE_VM3(kfree, vm_size_t, size, vm_size_t, z->elem_size, void*, data);
889 #endif
890 zfree(z, data);
891 }
892
893 #ifdef MACH_BSD
894 zone_t
895 kalloc_zone(
896 vm_size_t size)
897 {
898 if (size < MAX_SIZE_ZDLUT) {
899 return get_zone_dlut(size);
900 }
901 if (size <= kalloc_max) {
902 return get_zone_search(size, k_zindex_start);
903 }
904 return ZONE_NULL;
905 }
906 #endif
907
908 void
909 OSMalloc_init(
910 void)
911 {
912 queue_init(&OSMalloc_tag_list);
913
914 OSMalloc_tag_lck_grp = lck_grp_alloc_init("OSMalloc_tag", LCK_GRP_ATTR_NULL);
915 lck_mtx_init(&OSMalloc_tag_lock, OSMalloc_tag_lck_grp, LCK_ATTR_NULL);
916 }
917
918 OSMallocTag
919 OSMalloc_Tagalloc(
920 const char *str,
921 uint32_t flags)
922 {
923 OSMallocTag OSMTag;
924
925 OSMTag = (OSMallocTag)kalloc(sizeof(*OSMTag));
926
927 bzero((void *)OSMTag, sizeof(*OSMTag));
928
929 if (flags & OSMT_PAGEABLE) {
930 OSMTag->OSMT_attr = OSMT_ATTR_PAGEABLE;
931 }
932
933 OSMTag->OSMT_refcnt = 1;
934
935 strlcpy(OSMTag->OSMT_name, str, OSMT_MAX_NAME);
936
937 OSMalloc_tag_spin_lock();
938 enqueue_tail(&OSMalloc_tag_list, (queue_entry_t)OSMTag);
939 OSMalloc_tag_unlock();
940 OSMTag->OSMT_state = OSMT_VALID;
941 return OSMTag;
942 }
943
944 void
945 OSMalloc_Tagref(
946 OSMallocTag tag)
947 {
948 if (!((tag->OSMT_state & OSMT_VALID_MASK) == OSMT_VALID)) {
949 panic("OSMalloc_Tagref():'%s' has bad state 0x%08X\n", tag->OSMT_name, tag->OSMT_state);
950 }
951
952 os_atomic_inc(&tag->OSMT_refcnt, relaxed);
953 }
954
955 void
956 OSMalloc_Tagrele(
957 OSMallocTag tag)
958 {
959 if (!((tag->OSMT_state & OSMT_VALID_MASK) == OSMT_VALID)) {
960 panic("OSMalloc_Tagref():'%s' has bad state 0x%08X\n", tag->OSMT_name, tag->OSMT_state);
961 }
962
963 if (os_atomic_dec(&tag->OSMT_refcnt, relaxed) == 0) {
964 if (os_atomic_cmpxchg(&tag->OSMT_state, OSMT_VALID | OSMT_RELEASED, OSMT_VALID | OSMT_RELEASED, acq_rel)) {
965 OSMalloc_tag_spin_lock();
966 (void)remque((queue_entry_t)tag);
967 OSMalloc_tag_unlock();
968 kfree(tag, sizeof(*tag));
969 } else {
970 panic("OSMalloc_Tagrele():'%s' has refcnt 0\n", tag->OSMT_name);
971 }
972 }
973 }
974
975 void
976 OSMalloc_Tagfree(
977 OSMallocTag tag)
978 {
979 if (!os_atomic_cmpxchg(&tag->OSMT_state, OSMT_VALID, OSMT_VALID | OSMT_RELEASED, acq_rel)) {
980 panic("OSMalloc_Tagfree():'%s' has bad state 0x%08X \n", tag->OSMT_name, tag->OSMT_state);
981 }
982
983 if (os_atomic_dec(&tag->OSMT_refcnt, relaxed) == 0) {
984 OSMalloc_tag_spin_lock();
985 (void)remque((queue_entry_t)tag);
986 OSMalloc_tag_unlock();
987 kfree(tag, sizeof(*tag));
988 }
989 }
990
991 void *
992 OSMalloc(
993 uint32_t size,
994 OSMallocTag tag)
995 {
996 void *addr = NULL;
997 kern_return_t kr;
998
999 OSMalloc_Tagref(tag);
1000 if ((tag->OSMT_attr & OSMT_PAGEABLE)
1001 && (size & ~PAGE_MASK)) {
1002 if ((kr = kmem_alloc_pageable_external(kernel_map, (vm_offset_t *)&addr, size)) != KERN_SUCCESS) {
1003 addr = NULL;
1004 }
1005 } else {
1006 addr = kalloc_tag_bt((vm_size_t)size, VM_KERN_MEMORY_KALLOC);
1007 }
1008
1009 if (!addr) {
1010 OSMalloc_Tagrele(tag);
1011 }
1012
1013 return addr;
1014 }
1015
1016 void *
1017 OSMalloc_nowait(
1018 uint32_t size,
1019 OSMallocTag tag)
1020 {
1021 void *addr = NULL;
1022
1023 if (tag->OSMT_attr & OSMT_PAGEABLE) {
1024 return NULL;
1025 }
1026
1027 OSMalloc_Tagref(tag);
1028 /* XXX: use non-blocking kalloc for now */
1029 addr = kalloc_noblock_tag_bt((vm_size_t)size, VM_KERN_MEMORY_KALLOC);
1030 if (addr == NULL) {
1031 OSMalloc_Tagrele(tag);
1032 }
1033
1034 return addr;
1035 }
1036
1037 void *
1038 OSMalloc_noblock(
1039 uint32_t size,
1040 OSMallocTag tag)
1041 {
1042 void *addr = NULL;
1043
1044 if (tag->OSMT_attr & OSMT_PAGEABLE) {
1045 return NULL;
1046 }
1047
1048 OSMalloc_Tagref(tag);
1049 addr = kalloc_noblock_tag_bt((vm_size_t)size, VM_KERN_MEMORY_KALLOC);
1050 if (addr == NULL) {
1051 OSMalloc_Tagrele(tag);
1052 }
1053
1054 return addr;
1055 }
1056
1057 void
1058 OSFree(
1059 void *addr,
1060 uint32_t size,
1061 OSMallocTag tag)
1062 {
1063 if ((tag->OSMT_attr & OSMT_PAGEABLE)
1064 && (size & ~PAGE_MASK)) {
1065 kmem_free(kernel_map, (vm_offset_t)addr, size);
1066 } else {
1067 kfree(addr, size);
1068 }
1069
1070 OSMalloc_Tagrele(tag);
1071 }
1072
1073 uint32_t
1074 OSMalloc_size(
1075 void *addr)
1076 {
1077 return (uint32_t)kalloc_size(addr);
1078 }