This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
kalloc.c
1513 lines (1330 loc) · 40 KB
/
kalloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2020 Apple Computer, 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
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* 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,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* 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.
*/
/*
*/
/*
* File: kern/kalloc.c
* Author: Avadis Tevanian, Jr.
* Date: 1985
*
* General kernel memory allocator. This allocator is designed
* to be used by the kernel to manage dynamic memory fast.
*/
#include <mach/boolean.h>
#include <mach/sdt.h>
#include <mach/machine/vm_types.h>
#include <mach/vm_param.h>
#include <kern/misc_protos.h>
#include <kern/zalloc_internal.h>
#include <kern/kalloc.h>
#include <kern/ledger.h>
#include <kern/backtrace.h>
#include <vm/vm_kern.h>
#include <vm/vm_object.h>
#include <vm/vm_map.h>
#include <sys/kdebug.h>
#include <san/kasan.h>
#include <libkern/section_keywords.h>
/* #define KALLOC_DEBUG 1 */
#define KALLOC_MAP_SIZE_MIN (16 * 1024 * 1024)
#define KALLOC_MAP_SIZE_MAX (128 * 1024 * 1024)
static SECURITY_READ_ONLY_LATE(vm_offset_t) kalloc_map_min;
static SECURITY_READ_ONLY_LATE(vm_offset_t) kalloc_map_max;
static SECURITY_READ_ONLY_LATE(vm_size_t) kalloc_max;
SECURITY_READ_ONLY_LATE(vm_size_t) kalloc_max_prerounded;
/* size of kallocs that can come from kernel map */
SECURITY_READ_ONLY_LATE(vm_size_t) kalloc_kernmap_size;
SECURITY_READ_ONLY_LATE(vm_map_t) kalloc_map;
#if DEBUG || DEVELOPMENT
static TUNABLE(bool, kheap_temp_debug, "kheap_temp_debug", false);
#define KHT_BT_COUNT 14
struct kheap_temp_header {
queue_chain_t kht_hdr_link;
uintptr_t kht_hdr_pcs[KHT_BT_COUNT];
};
#endif
/* how many times we couldn't allocate out of kalloc_map and fell back to kernel_map */
unsigned long kalloc_fallback_count;
uint_t kalloc_large_inuse;
vm_size_t kalloc_large_total;
vm_size_t kalloc_large_max;
vm_size_t kalloc_largest_allocated = 0;
uint64_t kalloc_large_sum;
LCK_GRP_DECLARE(kalloc_lck_grp, "kalloc.large");
LCK_SPIN_DECLARE(kalloc_lock, &kalloc_lck_grp);
#define kalloc_spin_lock() lck_spin_lock(&kalloc_lock)
#define kalloc_unlock() lck_spin_unlock(&kalloc_lock)
#pragma mark initialization
/*
* All allocations of size less than kalloc_max are rounded to the next nearest
* sized zone. This allocator is built on top of the zone allocator. A zone
* is created for each potential size that we are willing to get in small
* blocks.
*
* We assume that kalloc_max is not greater than 64K;
*
* Note that kalloc_max is somewhat confusingly named. It represents the first
* power of two for which no zone exists. kalloc_max_prerounded is the
* smallest allocation size, before rounding, for which no zone exists.
*
* Also if the allocation size is more than kalloc_kernmap_size then allocate
* from kernel map rather than kalloc_map.
*/
#define KiB(x) (1024 * (x))
/*
* The k_zone_cfg table defines the configuration of zones on various platforms.
* The currently defined list of zones and their per-CPU caching behavior are as
* follows
*
* X:zone not present
* N:zone present no cpu-caching
* Y:zone present with cpu-caching
*
* Size macOS(64-bit) embedded(32-bit) embedded(64-bit)
*-------- ---------------- ---------------- ----------------
*
* 8 X Y X
* 16 Y Y Y
* 24 X Y X
* 32 Y Y Y
* 40 X Y X
* 48 Y Y Y
* 64 Y Y Y
* 72 X Y X
* 80 Y X Y
* 88 X Y X
* 96 Y X Y
* 112 X Y X
* 128 Y Y Y
* 160 Y X Y
* 192 Y Y Y
* 224 Y X Y
* 256 Y Y Y
* 288 Y Y Y
* 368 Y X Y
* 384 X Y X
* 400 Y X Y
* 440 X Y X
* 512 Y Y Y
* 576 Y N N
* 768 Y N N
* 1024 Y Y Y
* 1152 N N N
* 1280 N N N
* 1536 X N X
* 1664 N X N
* 2048 Y N N
* 2128 X N X
* 3072 X N X
* 4096 Y N N
* 6144 N N N
* 8192 Y N N
* 12288 N X X
* 16384 N X N
* 32768 X X N
*
*/
struct kalloc_zone_cfg {
bool kzc_caching;
uint32_t kzc_size;
const char *kzc_name;
};
static SECURITY_READ_ONLY_LATE(struct kalloc_zone_cfg) k_zone_cfg[] = {
#define KZC_ENTRY(SIZE, caching) { \
.kzc_caching = (caching), \
.kzc_size = (SIZE), \
.kzc_name = "kalloc." #SIZE \
}
#if !defined(XNU_TARGET_OS_OSX)
#if KALLOC_MINSIZE == 16 && KALLOC_LOG2_MINALIGN == 4
/* Zone config for embedded 64-bit platforms */
KZC_ENTRY(16, true),
KZC_ENTRY(32, true),
KZC_ENTRY(48, true),
KZC_ENTRY(64, true),
KZC_ENTRY(80, true),
KZC_ENTRY(96, true),
KZC_ENTRY(128, true),
KZC_ENTRY(160, true),
KZC_ENTRY(192, true),
KZC_ENTRY(224, true),
KZC_ENTRY(256, true),
KZC_ENTRY(288, true),
KZC_ENTRY(368, true),
KZC_ENTRY(400, true),
KZC_ENTRY(512, true),
KZC_ENTRY(576, false),
KZC_ENTRY(768, false),
KZC_ENTRY(1024, true),
KZC_ENTRY(1152, false),
KZC_ENTRY(1280, false),
KZC_ENTRY(1664, false),
KZC_ENTRY(2048, false),
KZC_ENTRY(4096, false),
KZC_ENTRY(6144, false),
KZC_ENTRY(8192, false),
KZC_ENTRY(16384, false),
KZC_ENTRY(32768, false),
#elif KALLOC_MINSIZE == 8 && KALLOC_LOG2_MINALIGN == 3
/* Zone config for embedded 32-bit platforms */
KZC_ENTRY(8, true),
KZC_ENTRY(16, true),
KZC_ENTRY(24, true),
KZC_ENTRY(32, true),
KZC_ENTRY(40, true),
KZC_ENTRY(48, true),
KZC_ENTRY(64, true),
KZC_ENTRY(72, true),
KZC_ENTRY(88, true),
KZC_ENTRY(112, true),
KZC_ENTRY(128, true),
KZC_ENTRY(192, true),
KZC_ENTRY(256, true),
KZC_ENTRY(288, true),
KZC_ENTRY(384, true),
KZC_ENTRY(440, true),
KZC_ENTRY(512, true),
KZC_ENTRY(576, false),
KZC_ENTRY(768, false),
KZC_ENTRY(1024, true),
KZC_ENTRY(1152, false),
KZC_ENTRY(1280, false),
KZC_ENTRY(1536, false),
KZC_ENTRY(2048, false),
KZC_ENTRY(2128, false),
KZC_ENTRY(3072, false),
KZC_ENTRY(4096, false),
KZC_ENTRY(6144, false),
KZC_ENTRY(8192, false),
/* To limit internal fragmentation, only add the following zones if the
* page size is greater than 4K.
* Note that we use ARM_PGBYTES here (instead of one of the VM macros)
* since it's guaranteed to be a compile time constant.
*/
#if ARM_PGBYTES > 4096
KZC_ENTRY(16384, false),
KZC_ENTRY(32768, false),
#endif /* ARM_PGBYTES > 4096 */
#else
#error missing or invalid zone size parameters for kalloc
#endif
#else /* !defined(XNU_TARGET_OS_OSX) */
/* Zone config for macOS 64-bit platforms */
KZC_ENTRY(16, true),
KZC_ENTRY(32, true),
KZC_ENTRY(48, true),
KZC_ENTRY(64, true),
KZC_ENTRY(80, true),
KZC_ENTRY(96, true),
KZC_ENTRY(128, true),
KZC_ENTRY(160, true),
KZC_ENTRY(192, true),
KZC_ENTRY(224, true),
KZC_ENTRY(256, true),
KZC_ENTRY(288, true),
KZC_ENTRY(368, true),
KZC_ENTRY(400, true),
KZC_ENTRY(512, true),
KZC_ENTRY(576, true),
KZC_ENTRY(768, true),
KZC_ENTRY(1024, true),
KZC_ENTRY(1152, false),
KZC_ENTRY(1280, false),
KZC_ENTRY(1664, false),
KZC_ENTRY(2048, true),
KZC_ENTRY(4096, true),
KZC_ENTRY(6144, false),
KZC_ENTRY(8192, true),
KZC_ENTRY(12288, false),
KZC_ENTRY(16384, false)
#endif /* !defined(XNU_TARGET_OS_OSX) */
#undef KZC_ENTRY
};
#define MAX_K_ZONE(kzc) (uint32_t)(sizeof(kzc) / sizeof(kzc[0]))
/*
* Many kalloc() allocations are for small structures containing a few
* pointers and longs - the dlut[] direct lookup table, indexed by
* size normalized to the minimum alignment, finds the right zone index
* for them in one dereference.
*/
#define INDEX_ZDLUT(size) (((size) + KALLOC_MINALIGN - 1) / KALLOC_MINALIGN)
#define MAX_SIZE_ZDLUT ((KALLOC_DLUT_SIZE - 1) * KALLOC_MINALIGN)
static SECURITY_READ_ONLY_LATE(zone_t) k_zone_default[MAX_K_ZONE(k_zone_cfg)];
static SECURITY_READ_ONLY_LATE(zone_t) k_zone_data_buffers[MAX_K_ZONE(k_zone_cfg)];
static SECURITY_READ_ONLY_LATE(zone_t) k_zone_kext[MAX_K_ZONE(k_zone_cfg)];
#if VM_MAX_TAG_ZONES
#if __LP64__
static_assert(VM_MAX_TAG_ZONES >=
MAX_K_ZONE(k_zone_cfg) + MAX_K_ZONE(k_zone_cfg) + MAX_K_ZONE(k_zone_cfg));
#else
static_assert(VM_MAX_TAG_ZONES >= MAX_K_ZONE(k_zone_cfg));
#endif
#endif
const char * const kalloc_heap_names[] = {
[KHEAP_ID_NONE] = "",
[KHEAP_ID_DEFAULT] = "default.",
[KHEAP_ID_DATA_BUFFERS] = "data.",
[KHEAP_ID_KEXT] = "kext.",
};
/*
* Default kalloc heap configuration
*/
static SECURITY_READ_ONLY_LATE(struct kheap_zones) kalloc_zones_default = {
.cfg = k_zone_cfg,
.heap_id = KHEAP_ID_DEFAULT,
.k_zone = k_zone_default,
.max_k_zone = MAX_K_ZONE(k_zone_cfg)
};
SECURITY_READ_ONLY_LATE(struct kalloc_heap) KHEAP_DEFAULT[1] = {
{
.kh_zones = &kalloc_zones_default,
.kh_name = "default.",
.kh_heap_id = KHEAP_ID_DEFAULT,
}
};
KALLOC_HEAP_DEFINE(KHEAP_TEMP, "temp allocations", KHEAP_ID_DEFAULT);
/*
* Bag of bytes heap configuration
*/
static SECURITY_READ_ONLY_LATE(struct kheap_zones) kalloc_zones_data_buffers = {
.cfg = k_zone_cfg,
.heap_id = KHEAP_ID_DATA_BUFFERS,
.k_zone = k_zone_data_buffers,
.max_k_zone = MAX_K_ZONE(k_zone_cfg)
};
SECURITY_READ_ONLY_LATE(struct kalloc_heap) KHEAP_DATA_BUFFERS[1] = {
{
.kh_zones = &kalloc_zones_data_buffers,
.kh_name = "data.",
.kh_heap_id = KHEAP_ID_DATA_BUFFERS,
}
};
/*
* Kext heap configuration
*/
static SECURITY_READ_ONLY_LATE(struct kheap_zones) kalloc_zones_kext = {
.cfg = k_zone_cfg,
.heap_id = KHEAP_ID_KEXT,
.k_zone = k_zone_kext,
.max_k_zone = MAX_K_ZONE(k_zone_cfg)
};
SECURITY_READ_ONLY_LATE(struct kalloc_heap) KHEAP_KEXT[1] = {
{
.kh_zones = &kalloc_zones_kext,
.kh_name = "kext.",
.kh_heap_id = KHEAP_ID_KEXT,
}
};
KALLOC_HEAP_DEFINE(KERN_OS_MALLOC, "kern_os_malloc", KHEAP_ID_KEXT);
/*
* Initialize kalloc heap: Create zones, generate direct lookup table and
* do a quick test on lookups
*/
__startup_func
static void
kalloc_zones_init(struct kheap_zones *zones)
{
struct kalloc_zone_cfg *cfg = zones->cfg;
zone_t *k_zone = zones->k_zone;
vm_size_t size;
/*
* Allocate a zone for each size we are going to handle.
*/
for (uint32_t i = 0; i < zones->max_k_zone &&
(size = cfg[i].kzc_size) < kalloc_max; i++) {
zone_create_flags_t flags = ZC_KASAN_NOREDZONE |
ZC_KASAN_NOQUARANTINE | ZC_KALLOC_HEAP;
if (cfg[i].kzc_caching) {
flags |= ZC_CACHING;
}
k_zone[i] = zone_create_ext(cfg[i].kzc_name, size, flags,
ZONE_ID_ANY, ^(zone_t z){
z->kalloc_heap = zones->heap_id;
});
/*
* Set the updated elem size back to the config
*/
cfg[i].kzc_size = k_zone[i]->z_elem_size;
}
/*
* Count all the "raw" views for zones in the heap.
*/
zone_view_count += zones->max_k_zone;
/*
* Build the Direct LookUp Table for small allocations
* As k_zone_cfg is shared between the heaps the
* Direct LookUp Table is also shared and doesn't need to
* be rebuilt per heap.
*/
size = 0;
for (int i = 0; i <= KALLOC_DLUT_SIZE; i++, size += KALLOC_MINALIGN) {
uint8_t zindex = 0;
while ((vm_size_t)(cfg[zindex].kzc_size) < size) {
zindex++;
}
if (i == KALLOC_DLUT_SIZE) {
zones->k_zindex_start = zindex;
break;
}
zones->dlut[i] = zindex;
}
#ifdef KALLOC_DEBUG
printf("kalloc_init: k_zindex_start %d\n", zones->k_zindex_start);
/*
* Do a quick synthesis to see how well/badly we can
* find-a-zone for a given size.
* Useful when debugging/tweaking the array of zone sizes.
* Cache misses probably more critical than compare-branches!
*/
for (uint32_t i = 0; i < zones->max_k_zone; i++) {
vm_size_t testsize = (vm_size_t)(cfg[i].kzc_size - 1);
int compare = 0;
uint8_t zindex;
if (testsize < MAX_SIZE_ZDLUT) {
compare += 1; /* 'if' (T) */
long dindex = INDEX_ZDLUT(testsize);
zindex = (int)zones->dlut[dindex];
} else if (testsize < kalloc_max_prerounded) {
compare += 2; /* 'if' (F), 'if' (T) */
zindex = zones->k_zindex_start;
while ((vm_size_t)(cfg[zindex].kzc_size) < testsize) {
zindex++;
compare++; /* 'while' (T) */
}
compare++; /* 'while' (F) */
} else {
break; /* not zone-backed */
}
zone_t z = k_zone[zindex];
printf("kalloc_init: req size %4lu: %8s.%16s took %d compare%s\n",
(unsigned long)testsize, kalloc_heap_names[zones->heap_id],
z->z_name, compare, compare == 1 ? "" : "s");
}
#endif
}
/*
* Initialize the memory allocator. This should be called only
* once on a system wide basis (i.e. first processor to get here
* does the initialization).
*
* This initializes all of the zones.
*/
__startup_func
static void
kalloc_init(void)
{
kern_return_t retval;
vm_offset_t min;
vm_size_t kalloc_map_size;
vm_map_kernel_flags_t vmk_flags;
/*
* Scale the kalloc_map_size to physical memory size: stay below
* 1/8th the total zone map size, or 128 MB (for a 32-bit kernel).
*/
kalloc_map_size = (vm_size_t)(sane_size >> 5);
#if !__LP64__
if (kalloc_map_size > KALLOC_MAP_SIZE_MAX) {
kalloc_map_size = KALLOC_MAP_SIZE_MAX;
}
#endif /* !__LP64__ */
if (kalloc_map_size < KALLOC_MAP_SIZE_MIN) {
kalloc_map_size = KALLOC_MAP_SIZE_MIN;
}
vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
vmk_flags.vmkf_permanent = TRUE;
retval = kmem_suballoc(kernel_map, &min, kalloc_map_size,
FALSE, VM_FLAGS_ANYWHERE, vmk_flags,
VM_KERN_MEMORY_KALLOC, &kalloc_map);
if (retval != KERN_SUCCESS) {
panic("kalloc_init: kmem_suballoc failed");
}
kalloc_map_min = min;
kalloc_map_max = min + kalloc_map_size - 1;
struct kheap_zones *khz_default = &kalloc_zones_default;
kalloc_max = (khz_default->cfg[khz_default->max_k_zone - 1].kzc_size << 1);
if (kalloc_max < KiB(16)) {
kalloc_max = KiB(16);
}
assert(kalloc_max <= KiB(64)); /* assumption made in size arrays */
kalloc_max_prerounded = kalloc_max / 2 + 1;
/* allocations larger than 16 times kalloc_max go directly to kernel map */
kalloc_kernmap_size = (kalloc_max * 16) + 1;
kalloc_largest_allocated = kalloc_kernmap_size;
/* Initialize kalloc default heap */
kalloc_zones_init(&kalloc_zones_default);
/* Initialize kalloc data buffers heap */
if (ZSECURITY_OPTIONS_SUBMAP_USER_DATA & zsecurity_options) {
kalloc_zones_init(&kalloc_zones_data_buffers);
} else {
*KHEAP_DATA_BUFFERS = *KHEAP_DEFAULT;
}
/* Initialize kalloc kext heap */
if (ZSECURITY_OPTIONS_SEQUESTER_KEXT_KALLOC & zsecurity_options) {
kalloc_zones_init(&kalloc_zones_kext);
} else {
*KHEAP_KEXT = *KHEAP_DEFAULT;
}
}
STARTUP(ZALLOC, STARTUP_RANK_THIRD, kalloc_init);
#pragma mark accessors
static void
KALLOC_ZINFO_SALLOC(vm_size_t bytes)
{
thread_t thr = current_thread();
ledger_debit_thread(thr, thr->t_ledger, task_ledgers.tkm_shared, bytes);
}
static void
KALLOC_ZINFO_SFREE(vm_size_t bytes)
{
thread_t thr = current_thread();
ledger_credit_thread(thr, thr->t_ledger, task_ledgers.tkm_shared, bytes);
}
static inline vm_map_t
kalloc_map_for_addr(vm_address_t addr)
{
if (addr >= kalloc_map_min && addr < kalloc_map_max) {
return kalloc_map;
}
return kernel_map;
}
static inline vm_map_t
kalloc_map_for_size(vm_size_t size)
{
if (size < kalloc_kernmap_size) {
return kalloc_map;
}
return kernel_map;
}
zone_t
kalloc_heap_zone_for_size(kalloc_heap_t kheap, vm_size_t size)
{
struct kheap_zones *khz = kheap->kh_zones;
if (size < MAX_SIZE_ZDLUT) {
uint32_t zindex = khz->dlut[INDEX_ZDLUT(size)];
return khz->k_zone[zindex];
}
if (size < kalloc_max_prerounded) {
uint32_t zindex = khz->k_zindex_start;
while (khz->cfg[zindex].kzc_size < size) {
zindex++;
}
assert(zindex < khz->max_k_zone);
return khz->k_zone[zindex];
}
return ZONE_NULL;
}
static vm_size_t
vm_map_lookup_kalloc_entry_locked(vm_map_t map, void *addr)
{
vm_map_entry_t vm_entry = NULL;
if (!vm_map_lookup_entry(map, (vm_map_offset_t)addr, &vm_entry)) {
panic("address %p not allocated via kalloc, map %p",
addr, map);
}
if (vm_entry->vme_start != (vm_map_offset_t)addr) {
panic("address %p inside vm entry %p [%p:%p), map %p",
addr, vm_entry, (void *)vm_entry->vme_start,
(void *)vm_entry->vme_end, map);
}
if (!vm_entry->vme_atomic) {
panic("address %p not managed by kalloc (entry %p, map %p)",
addr, vm_entry, map);
}
return vm_entry->vme_end - vm_entry->vme_start;
}
#if KASAN_KALLOC
/*
* KASAN kalloc stashes the original user-requested size away in the poisoned
* area. Return that directly.
*/
vm_size_t
kalloc_size(void *addr)
{
(void)vm_map_lookup_kalloc_entry_locked; /* silence warning */
return kasan_user_size((vm_offset_t)addr);
}
#else
vm_size_t
kalloc_size(void *addr)
{
vm_map_t map;
vm_size_t size;
size = zone_element_size(addr, NULL);
if (size) {
return size;
}
map = kalloc_map_for_addr((vm_offset_t)addr);
vm_map_lock_read(map);
size = vm_map_lookup_kalloc_entry_locked(map, addr);
vm_map_unlock_read(map);
return size;
}
#endif
vm_size_t
kalloc_bucket_size(vm_size_t size)
{
zone_t z = kalloc_heap_zone_for_size(KHEAP_DEFAULT, size);
vm_map_t map = kalloc_map_for_size(size);
if (z) {
return zone_elem_size(z);
}
return vm_map_round_page(size, VM_MAP_PAGE_MASK(map));
}
#pragma mark kalloc
void
kheap_temp_leak_panic(thread_t self)
{
#if DEBUG || DEVELOPMENT
if (__improbable(kheap_temp_debug)) {
struct kheap_temp_header *hdr = qe_dequeue_head(&self->t_temp_alloc_list,
struct kheap_temp_header, kht_hdr_link);
panic_plain("KHEAP_TEMP leak on thread %p (%d), allocated at:\n"
" %#016lx\n" " %#016lx\n" " %#016lx\n" " %#016lx\n"
" %#016lx\n" " %#016lx\n" " %#016lx\n" " %#016lx\n"
" %#016lx\n" " %#016lx\n" " %#016lx\n" " %#016lx\n"
" %#016lx\n" " %#016lx\n",
self, self->t_temp_alloc_count,
hdr->kht_hdr_pcs[0], hdr->kht_hdr_pcs[1],
hdr->kht_hdr_pcs[2], hdr->kht_hdr_pcs[3],
hdr->kht_hdr_pcs[4], hdr->kht_hdr_pcs[5],
hdr->kht_hdr_pcs[6], hdr->kht_hdr_pcs[7],
hdr->kht_hdr_pcs[8], hdr->kht_hdr_pcs[9],
hdr->kht_hdr_pcs[10], hdr->kht_hdr_pcs[11],
hdr->kht_hdr_pcs[12], hdr->kht_hdr_pcs[13]);
}
panic("KHEAP_TEMP leak on thread %p (%d) "
"(boot with kheap_temp_debug=1 to debug)",
self, self->t_temp_alloc_count);
#else /* !DEBUG && !DEVELOPMENT */
panic("KHEAP_TEMP leak on thread %p (%d)",
self, self->t_temp_alloc_count);
#endif /* !DEBUG && !DEVELOPMENT */
}
__abortlike
static void
kheap_temp_overuse_panic(thread_t self)
{
panic("too many KHEAP_TEMP allocations in flight: %d",
self->t_temp_alloc_count);
}
__attribute__((noinline))
static struct kalloc_result
kalloc_large(
kalloc_heap_t kheap,
vm_size_t req_size,
vm_size_t size,
zalloc_flags_t flags,
vm_allocation_site_t *site)
{
int kma_flags = KMA_ATOMIC | KMA_KOBJECT;
vm_tag_t tag = VM_KERN_MEMORY_KALLOC;
vm_map_t alloc_map;
vm_offset_t addr;
if (flags & Z_NOFAIL) {
panic("trying to kalloc(Z_NOFAIL) with a large size (%zd)",
(size_t)size);
}
/* kmem_alloc could block so we return if noblock */
if (flags & Z_NOWAIT) {
return (struct kalloc_result){ };
}
if (flags & Z_NOPAGEWAIT) {
kma_flags |= KMA_NOPAGEWAIT;
}
if (flags & Z_ZERO) {
kma_flags |= KMA_ZERO;
}
#if KASAN_KALLOC
/* large allocation - use guard pages instead of small redzones */
size = round_page(req_size + 2 * PAGE_SIZE);
assert(size >= MAX_SIZE_ZDLUT && size >= kalloc_max_prerounded);
#else
size = round_page(size);
#endif
alloc_map = kalloc_map_for_size(size);
if (site) {
tag = vm_tag_alloc(site);
}
if (kmem_alloc_flags(alloc_map, &addr, size, tag, kma_flags) != KERN_SUCCESS) {
if (alloc_map != kernel_map) {
if (kalloc_fallback_count++ == 0) {
printf("%s: falling back to kernel_map\n", __func__);
}
if (kmem_alloc_flags(kernel_map, &addr, size, tag, kma_flags) != KERN_SUCCESS) {
addr = 0;
}
} else {
addr = 0;
}
}
if (addr != 0) {
kalloc_spin_lock();
/*
* Thread-safe version of the workaround for 4740071
* (a double FREE())
*/
if (size > kalloc_largest_allocated) {
kalloc_largest_allocated = size;
}
kalloc_large_inuse++;
assert(kalloc_large_total + size >= kalloc_large_total); /* no wrap around */
kalloc_large_total += size;
kalloc_large_sum += size;
if (kalloc_large_total > kalloc_large_max) {
kalloc_large_max = kalloc_large_total;
}
kalloc_unlock();
KALLOC_ZINFO_SALLOC(size);
}
#if KASAN_KALLOC
/* fixup the return address to skip the redzone */
addr = kasan_alloc(addr, size, req_size, PAGE_SIZE);
/*
* Initialize buffer with unique pattern only if memory
* wasn't expected to be zeroed.
*/
if (!(flags & Z_ZERO)) {
kasan_leak_init(addr, req_size);
}
#else
req_size = size;
#endif
if (addr && kheap == KHEAP_TEMP) {
thread_t self = current_thread();
if (self->t_temp_alloc_count++ > UINT16_MAX) {
kheap_temp_overuse_panic(self);
}
#if DEBUG || DEVELOPMENT
if (__improbable(kheap_temp_debug)) {
struct kheap_temp_header *hdr = (void *)addr;
enqueue_head(&self->t_temp_alloc_list,
&hdr->kht_hdr_link);
backtrace(hdr->kht_hdr_pcs, KHT_BT_COUNT, NULL);
req_size -= sizeof(struct kheap_temp_header);
addr += sizeof(struct kheap_temp_header);
}
#endif /* DEBUG || DEVELOPMENT */
}
DTRACE_VM3(kalloc, vm_size_t, size, vm_size_t, req_size, void*, addr);
return (struct kalloc_result){ .addr = (void *)addr, .size = req_size };
}
struct kalloc_result
kalloc_ext(
kalloc_heap_t kheap,
vm_size_t req_size,
zalloc_flags_t flags,
vm_allocation_site_t *site)
{
vm_tag_t tag = VM_KERN_MEMORY_KALLOC;
vm_size_t size;
void *addr;
zone_t z;
#if DEBUG || DEVELOPMENT
if (__improbable(kheap_temp_debug)) {
if (kheap == KHEAP_TEMP) {
req_size += sizeof(struct kheap_temp_header);
}
}
#endif /* DEBUG || DEVELOPMENT */
/*
* Kasan for kalloc heaps will put the redzones *inside*
* the allocation, and hence augment its size.
*
* kalloc heaps do not use zone_t::kasan_redzone.
*/
#if KASAN_KALLOC
size = kasan_alloc_resize(req_size);
#else
size = req_size;
#endif
z = kalloc_heap_zone_for_size(kheap, size);
if (__improbable(z == ZONE_NULL)) {
return kalloc_large(kheap, req_size, size, flags, site);
}
#ifdef KALLOC_DEBUG
if (size > zone_elem_size(z)) {
panic("%s: z %p (%s%s) but requested size %lu", __func__, z,
kalloc_heap_names[kheap->kh_zones->heap_id], z->z_name,
(unsigned long)size);
}
#endif
assert(size <= zone_elem_size(z));
#if VM_MAX_TAG_ZONES
if (z->tags && site) {
tag = vm_tag_alloc(site);
if ((flags & (Z_NOWAIT | Z_NOPAGEWAIT)) && !vm_allocation_zone_totals[tag]) {
tag = VM_KERN_MEMORY_KALLOC;
}
}
#endif
addr = zalloc_ext(z, kheap->kh_stats ?: z->z_stats,
flags | Z_VM_TAG(tag), zone_elem_size(z) - size);
#if KASAN_KALLOC
addr = (void *)kasan_alloc((vm_offset_t)addr, zone_elem_size(z),
req_size, KASAN_GUARD_SIZE);
#else
req_size = zone_elem_size(z);
#endif
if (addr && kheap == KHEAP_TEMP) {
thread_t self = current_thread();
if (self->t_temp_alloc_count++ > UINT16_MAX) {
kheap_temp_overuse_panic(self);
}
#if DEBUG || DEVELOPMENT
if (__improbable(kheap_temp_debug)) {
struct kheap_temp_header *hdr = (void *)addr;
enqueue_head(&self->t_temp_alloc_list,
&hdr->kht_hdr_link);
backtrace(hdr->kht_hdr_pcs, KHT_BT_COUNT, NULL);
req_size -= sizeof(struct kheap_temp_header);
addr += sizeof(struct kheap_temp_header);
}
#endif /* DEBUG || DEVELOPMENT */
}
DTRACE_VM3(kalloc, vm_size_t, size, vm_size_t, req_size, void*, addr);
return (struct kalloc_result){ .addr = addr, .size = req_size };
}
void *
kalloc_external(vm_size_t size);
void *
kalloc_external(vm_size_t size)
{
return kheap_alloc_tag_bt(KHEAP_KEXT, size, Z_WAITOK, VM_KERN_MEMORY_KALLOC);
}
#pragma mark kfree
__attribute__((noinline))
static void
kfree_large(vm_offset_t addr, vm_size_t size)
{
vm_map_t map = kalloc_map_for_addr(addr);
kern_return_t ret;
vm_offset_t end;
if (addr < VM_MIN_KERNEL_AND_KEXT_ADDRESS ||
os_add_overflow(addr, size, &end) ||
end > VM_MAX_KERNEL_ADDRESS) {
panic("kfree: address range (%p, %ld) doesn't belong to the kernel",
(void *)addr, (uintptr_t)size);
}
if (size == 0) {
vm_map_lock(map);
size = vm_map_lookup_kalloc_entry_locked(map, (void *)addr);
ret = vm_map_remove_locked(map,
vm_map_trunc_page(addr, VM_MAP_PAGE_MASK(map)),
vm_map_round_page(addr + size, VM_MAP_PAGE_MASK(map)),
VM_MAP_REMOVE_KUNWIRE);
if (ret != KERN_SUCCESS) {
panic("kfree: vm_map_remove_locked() failed for "
"addr: %p, map: %p ret: %d", (void *)addr, map, ret);
}
vm_map_unlock(map);
} else {
size = round_page(size);
if (size > kalloc_largest_allocated) {
panic("kfree: size %lu > kalloc_largest_allocated %lu",
(uintptr_t)size, (uintptr_t)kalloc_largest_allocated);
}
kmem_free(map, addr, size);
}
kalloc_spin_lock();
assert(kalloc_large_total >= size);
kalloc_large_total -= size;
kalloc_large_inuse--;
kalloc_unlock();