-
Notifications
You must be signed in to change notification settings - Fork 194
/
rpmalloc.c
2341 lines (2122 loc) · 69.5 KB
/
rpmalloc.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
/* rpmalloc.c - Memory allocator - Public Domain - 2016-2020 Mattias
* Jansson
*
* This library provides a cross-platform lock free thread caching malloc
* implementation in C11. The latest source code is always available at
*
* https://github.com/mjansson/rpmalloc
*
* This library is put in the public domain; you can redistribute it and/or
* modify it without any restrictions.
*
*/
#include "rpmalloc.h"
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdatomic.h>
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunused-macros"
#pragma clang diagnostic ignored "-Wunused-function"
#if __has_warning("-Wreserved-identifier")
#pragma clang diagnostic ignored "-Wreserved-identifier"
#endif
#if __has_warning("-Wstatic-in-inline")
#pragma clang diagnostic ignored "-Wstatic-in-inline"
#endif
#if __has_warning("-Wunsafe-buffer-usage")
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-macros"
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
#if defined(_WIN32) || defined(__WIN32__) || defined(_WIN64)
#define PLATFORM_WINDOWS 1
#define PLATFORM_POSIX 0
#else
#define PLATFORM_WINDOWS 0
#define PLATFORM_POSIX 1
#endif
#if defined(_MSC_VER)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE __attribute__((noinline))
#endif
#if PLATFORM_WINDOWS
#include <windows.h>
#include <fibersapi.h>
static DWORD fls_key;
#endif
#if PLATFORM_POSIX
#include <sys/mman.h>
#include <sched.h>
#include <unistd.h>
#include <pthread.h>
static pthread_key_t pthread_key;
#ifdef __FreeBSD__
#include <sys/sysctl.h>
#define MAP_HUGETLB MAP_ALIGNED_SUPER
#ifndef PROT_MAX
#define PROT_MAX(f) 0
#endif
#else
#define PROT_MAX(f) 0
#endif
#ifdef __sun
extern int
madvise(caddr_t, size_t, int);
#endif
#ifndef MAP_UNINITIALIZED
#define MAP_UNINITIALIZED 0
#endif
#endif
#if defined(__linux__) || defined(__ANDROID__)
#include <sys/prctl.h>
#if !defined(PR_SET_VMA)
#define PR_SET_VMA 0x53564d41
#define PR_SET_VMA_ANON_NAME 0
#endif
#endif
#if defined(__APPLE__)
#include <TargetConditionals.h>
#if !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
#include <mach/mach_vm.h>
#include <mach/vm_statistics.h>
#endif
#include <pthread.h>
#endif
#if defined(__HAIKU__) || defined(__TINYC__)
#include <pthread.h>
#endif
#include <limits.h>
#if (INTPTR_MAX > INT32_MAX)
#define ARCH_64BIT 1
#define ARCH_32BIT 0
#else
#define ARCH_64BIT 0
#define ARCH_32BIT 1
#endif
#if !defined(__has_builtin)
#define __has_builtin(b) 0
#endif
#define pointer_offset(ptr, ofs) (void*)((char*)(ptr) + (ptrdiff_t)(ofs))
#define pointer_diff(first, second) (ptrdiff_t)((const char*)(first) - (const char*)(second))
////////////
///
/// Build time configurable limits
///
//////
#ifndef ENABLE_VALIDATE_ARGS
//! Enable validation of args to public entry points
#define ENABLE_VALIDATE_ARGS 0
#endif
#ifndef ENABLE_ASSERTS
//! Enable asserts
#define ENABLE_ASSERTS 0
#endif
#ifndef ENABLE_UNMAP
//! Enable unmapping memory pages
#define ENABLE_UNMAP 1
#endif
#ifndef ENABLE_DECOMMIT
//! Enable decommitting memory pages
#define ENABLE_DECOMMIT 1
#endif
#ifndef ENABLE_DYNAMIC_LINK
//! Enable building as dynamic library
#define ENABLE_DYNAMIC_LINK 0
#endif
#ifndef ENABLE_OVERRIDE
//! Enable standard library malloc/free/new/delete overrides
#define ENABLE_OVERRIDE 1
#endif
#ifndef ENABLE_STATISTICS
//! Enable statistics
#define ENABLE_STATISTICS 0
#endif
////////////
///
/// Built in size configurations
///
//////
#define PAGE_HEADER_SIZE 128
#define SPAN_HEADER_SIZE PAGE_HEADER_SIZE
#define SMALL_GRANULARITY 16
#define SMALL_BLOCK_SIZE_LIMIT (4 * 1024)
#define MEDIUM_BLOCK_SIZE_LIMIT (256 * 1024)
#define LARGE_BLOCK_SIZE_LIMIT (8 * 1024 * 1024)
#define SMALL_SIZE_CLASS_COUNT 73
#define MEDIUM_SIZE_CLASS_COUNT 24
#define LARGE_SIZE_CLASS_COUNT 20
#define SIZE_CLASS_COUNT (SMALL_SIZE_CLASS_COUNT + MEDIUM_SIZE_CLASS_COUNT + LARGE_SIZE_CLASS_COUNT)
#define SMALL_PAGE_SIZE_SHIFT 16
#define SMALL_PAGE_SIZE (1 << SMALL_PAGE_SIZE_SHIFT)
#define SMALL_PAGE_MASK (~((uintptr_t)SMALL_PAGE_SIZE - 1))
#define MEDIUM_PAGE_SIZE_SHIFT 22
#define MEDIUM_PAGE_SIZE (1 << MEDIUM_PAGE_SIZE_SHIFT)
#define MEDIUM_PAGE_MASK (~((uintptr_t)MEDIUM_PAGE_SIZE - 1))
#define LARGE_PAGE_SIZE_SHIFT 26
#define LARGE_PAGE_SIZE (1 << LARGE_PAGE_SIZE_SHIFT)
#define LARGE_PAGE_MASK (~((uintptr_t)LARGE_PAGE_SIZE - 1))
#define SPAN_SIZE (256 * 1024 * 1024)
#define SPAN_MASK (~((uintptr_t)(SPAN_SIZE - 1)))
////////////
///
/// Utility macros
///
//////
#if ENABLE_ASSERTS
#undef NDEBUG
#if defined(_MSC_VER) && !defined(_DEBUG)
#define _DEBUG
#endif
#include <assert.h>
#define RPMALLOC_TOSTRING_M(x) #x
#define RPMALLOC_TOSTRING(x) RPMALLOC_TOSTRING_M(x)
#define rpmalloc_assert(truth, message) \
do { \
if (!(truth)) { \
assert((truth) && message); \
} \
} while (0)
#else
#define rpmalloc_assert(truth, message) \
do { \
} while (0)
#endif
#if __has_builtin(__builtin_assume)
#define rpmalloc_assume(cond) __builtin_assume(cond)
#elif defined(__GNUC__)
#define rpmalloc_assume(cond) \
do { \
if (!__builtin_expect(cond, 0)) \
__builtin_unreachable(); \
} while (0)
#elif defined(_MSC_VER)
#define rpmalloc_assume(cond) __assume(cond)
#else
#define rpmalloc_assume(cond) 0
#endif
////////////
///
/// Statistics
///
//////
#if ENABLE_STATISTICS
typedef struct rpmalloc_statistics_t {
atomic_size_t page_mapped;
atomic_size_t page_mapped_peak;
atomic_size_t page_commit;
atomic_size_t page_decommit;
atomic_size_t page_active;
atomic_size_t page_active_peak;
atomic_size_t heap_count;
} rpmalloc_statistics_t;
static rpmalloc_statistics_t global_statistics;
#else
#endif
////////////
///
/// Low level abstractions
///
//////
static inline size_t
rpmalloc_clz(uintptr_t x) {
#if ARCH_64BIT
#if defined(_MSC_VER) && !defined(__clang__)
return (size_t)_lzcnt_u64(x);
#else
return (size_t)__builtin_clzll(x);
#endif
#else
#if defined(_MSC_VER) && !defined(__clang__)
return (size_t)_lzcnt_u32(x);
#else
return (size_t)__builtin_clzl(x);
#endif
#endif
}
static inline void
wait_spin(void) {
#if defined(_MSC_VER)
#if defined(_M_ARM64)
__yield();
#else
_mm_pause();
#endif
#elif defined(__x86_64__) || defined(__i386__)
__asm__ volatile("pause" ::: "memory");
#elif defined(__aarch64__) || (defined(__arm__) && __ARM_ARCH >= 7)
__asm__ volatile("yield" ::: "memory");
#elif defined(__powerpc__) || defined(__powerpc64__)
// No idea if ever been compiled in such archs but ... as precaution
__asm__ volatile("or 27,27,27");
#elif defined(__sparc__)
__asm__ volatile("rd %ccr, %g0 \n\trd %ccr, %g0 \n\trd %ccr, %g0");
#else
struct timespec ts = {0};
nanosleep(&ts, 0);
#endif
}
#if defined(__GNUC__) || defined(__clang__)
#define EXPECTED(x) __builtin_expect((x), 1)
#define UNEXPECTED(x) __builtin_expect((x), 0)
#else
#define EXPECTED(x) x
#define UNEXPECTED(x) x
#endif
#if defined(__GNUC__) || defined(__clang__)
#if __has_builtin(__builtin_memcpy_inline)
#define memcpy_const(x, y, s) __builtin_memcpy_inline(x, y, s)
#else
#define memcpy_const(x, y, s) \
do { \
_Static_assert(__builtin_choose_expr(__builtin_constant_p(s), 1, 0), "len must be a constant integer"); \
memcpy(x, y, s); \
} while (0)
#endif
#if __has_builtin(__builtin_memset_inline)
#define memset_const(x, y, s) __builtin_memset_inline(x, y, s)
#else
#define memset_const(x, y, s) \
do { \
_Static_assert(__builtin_choose_expr(__builtin_constant_p(s), 1, 0), "len must be a constant integer"); \
memset(x, y, s); \
} while (0)
#endif
#else
#define memcpy_const(x, y, s) memcpy(x, y, s)
#define memset_const(x, y, s) memset(x, y, s)
#endif
////////////
///
/// Data types
///
//////
//! A memory heap, per thread
typedef struct heap_t heap_t;
//! Span of memory pages
typedef struct span_t span_t;
//! Memory page
typedef struct page_t page_t;
//! Memory block
typedef struct block_t block_t;
//! Size class for a memory block
typedef struct size_class_t size_class_t;
//! Memory page type
typedef enum page_type_t {
PAGE_SMALL, // 64KiB
PAGE_MEDIUM, // 4MiB
PAGE_LARGE, // 64MiB
PAGE_HUGE
} page_type_t;
//! Block size class
struct size_class_t {
//! Size of blocks in this class
uint32_t block_size;
//! Number of blocks in each chunk
uint32_t block_count;
};
//! A memory block
struct block_t {
//! Next block in list
block_t* next;
};
//! A page contains blocks of a given size
struct page_t {
//! Size class of blocks
uint32_t size_class;
//! Block size
uint32_t block_size;
//! Block count
uint32_t block_count;
//! Block initialized count
uint32_t block_initialized;
//! Block used count
uint32_t block_used;
//! Page type
page_type_t page_type;
//! Flag set if part of heap full list
uint32_t is_full : 1;
//! Flag set if part of heap free list
uint32_t is_free : 1;
//! Flag set if blocks are zero initialied
uint32_t is_zero : 1;
//! Flag set if memory pages have been decommitted
uint32_t is_decommitted : 1;
//! Flag set if containing aligned blocks
uint32_t has_aligned_block : 1;
//! Fast combination flag for either huge, fully allocated or has aligned blocks
uint32_t generic_free : 1;
//! Local free list count
uint32_t local_free_count;
//! Local free list
block_t* local_free;
//! Owning heap
heap_t* heap;
//! Next page in list
page_t* next;
//! Previous page in list
page_t* prev;
//! Multithreaded free list, block index is in low 32 bit, list count is high 32 bit
atomic_ullong thread_free;
};
//! A span contains pages of a given type
struct span_t {
//! Page header
page_t page;
//! Owning heap
heap_t* heap;
//! Page address mask
uintptr_t page_address_mask;
//! Number of pages initialized
uint32_t page_initialized;
//! Number of pages in use
uint32_t page_count;
//! Number of bytes per page
uint32_t page_size;
//! Page type
page_type_t page_type;
//! Offset to start of mapped memory region
uint32_t offset;
//! Mapped size
uint64_t mapped_size;
//! Next span in list
span_t* next;
};
// Control structure for a heap, either a thread heap or a first class heap if enabled
struct heap_t {
//! Owning thread ID
uintptr_t owner_thread;
//! Heap local free list for small size classes
block_t* local_free[SIZE_CLASS_COUNT];
//! Available non-full pages for each size class
page_t* page_available[SIZE_CLASS_COUNT];
//! Free pages for each page type
page_t* page_free[3];
//! Free but still committed page count for each page tyoe
uint32_t page_free_commit_count[3];
//! Multithreaded free list
atomic_uintptr_t thread_free[3];
//! Available partially initialized spans for each page type
span_t* span_partial[3];
//! Spans in full use for each page type
span_t* span_used[4];
//! Next heap in queue
heap_t* next;
//! Previous heap in queue
heap_t* prev;
//! Heap ID
uint32_t id;
//! Finalization state flag
uint32_t finalize;
//! Memory map region offset
uint32_t offset;
//! Memory map size
size_t mapped_size;
};
_Static_assert(sizeof(page_t) <= PAGE_HEADER_SIZE, "Invalid page header size");
_Static_assert(sizeof(span_t) <= SPAN_HEADER_SIZE, "Invalid span header size");
_Static_assert(sizeof(heap_t) <= 4096, "Invalid heap size");
////////////
///
/// Global data
///
//////
//! Fallback heap
static RPMALLOC_CACHE_ALIGNED heap_t global_heap_fallback;
//! Default heap
static heap_t* global_heap_default = &global_heap_fallback;
//! Available heaps
static heap_t* global_heap_queue;
//! In use heaps
static heap_t* global_heap_used;
//! Lock for heap queue
static atomic_uintptr_t global_heap_lock;
//! Heap ID counter
static atomic_uint global_heap_id = 1;
//! Initialized flag
static int global_rpmalloc_initialized;
//! Memory interface
static rpmalloc_interface_t* global_memory_interface;
//! Default memory interface
static rpmalloc_interface_t global_memory_interface_default;
//! Current configuration
static rpmalloc_config_t global_config = {0};
//! Main thread ID
static uintptr_t global_main_thread_id;
//! Size classes
#define SCLASS(n) \
{ (n * SMALL_GRANULARITY), (SMALL_PAGE_SIZE - PAGE_HEADER_SIZE) / (n * SMALL_GRANULARITY) }
#define MCLASS(n) \
{ (n * SMALL_GRANULARITY), (MEDIUM_PAGE_SIZE - PAGE_HEADER_SIZE) / (n * SMALL_GRANULARITY) }
#define LCLASS(n) \
{ (n * SMALL_GRANULARITY), (LARGE_PAGE_SIZE - PAGE_HEADER_SIZE) / (n * SMALL_GRANULARITY) }
static const size_class_t global_size_class[SIZE_CLASS_COUNT] = {
SCLASS(1), SCLASS(1), SCLASS(2), SCLASS(3), SCLASS(4), SCLASS(5), SCLASS(6),
SCLASS(7), SCLASS(8), SCLASS(9), SCLASS(10), SCLASS(11), SCLASS(12), SCLASS(13),
SCLASS(14), SCLASS(15), SCLASS(16), SCLASS(17), SCLASS(18), SCLASS(19), SCLASS(20),
SCLASS(21), SCLASS(22), SCLASS(23), SCLASS(24), SCLASS(25), SCLASS(26), SCLASS(27),
SCLASS(28), SCLASS(29), SCLASS(30), SCLASS(31), SCLASS(32), SCLASS(33), SCLASS(34),
SCLASS(35), SCLASS(36), SCLASS(37), SCLASS(38), SCLASS(39), SCLASS(40), SCLASS(41),
SCLASS(42), SCLASS(43), SCLASS(44), SCLASS(45), SCLASS(46), SCLASS(47), SCLASS(48),
SCLASS(49), SCLASS(50), SCLASS(51), SCLASS(52), SCLASS(53), SCLASS(54), SCLASS(55),
SCLASS(56), SCLASS(57), SCLASS(58), SCLASS(59), SCLASS(60), SCLASS(61), SCLASS(62),
SCLASS(63), SCLASS(64), SCLASS(80), SCLASS(96), SCLASS(112), SCLASS(128), SCLASS(160),
SCLASS(192), SCLASS(224), SCLASS(256), MCLASS(320), MCLASS(384), MCLASS(448), MCLASS(512),
MCLASS(640), MCLASS(768), MCLASS(896), MCLASS(1024), MCLASS(1280), MCLASS(1536), MCLASS(1792),
MCLASS(2048), MCLASS(2560), MCLASS(3072), MCLASS(3584), MCLASS(4096), MCLASS(5120), MCLASS(6144),
MCLASS(7168), MCLASS(8192), MCLASS(10240), MCLASS(12288), MCLASS(14336), MCLASS(16384), LCLASS(20480),
LCLASS(24576), LCLASS(28672), LCLASS(32768), LCLASS(40960), LCLASS(49152), LCLASS(57344), LCLASS(65536),
LCLASS(81920), LCLASS(98304), LCLASS(114688), LCLASS(131072), LCLASS(163840), LCLASS(196608), LCLASS(229376),
LCLASS(262144), LCLASS(327680), LCLASS(393216), LCLASS(458752), LCLASS(524288)};
//! Threshold number of pages for when free pages are decommitted
static uint32_t global_page_free_overflow[4] = {16, 8, 2, 0};
//! Number of pages to retain when free page threshold overflows
static uint32_t global_page_free_retain[4] = {4, 2, 1, 0};
//! OS huge page support
static int os_huge_pages;
//! OS memory map granularity
static size_t os_map_granularity;
//! OS memory page size
static size_t os_page_size;
////////////
///
/// Thread local heap and ID
///
//////
//! Current thread heap
#if defined(_MSC_VER) && !defined(__clang__)
#define TLS_MODEL
#define _Thread_local __declspec(thread)
#else
// #define TLS_MODEL __attribute__((tls_model("initial-exec")))
#define TLS_MODEL
#endif
static _Thread_local heap_t* global_thread_heap TLS_MODEL = &global_heap_fallback;
static heap_t*
heap_allocate(int first_class);
static void
heap_page_free_decommit(heap_t* heap, uint32_t page_type, uint32_t page_retain_count);
//! Fast thread ID
static inline uintptr_t
get_thread_id(void) {
#if defined(_WIN32)
return (uintptr_t)((void*)NtCurrentTeb());
#else
void* thp = __builtin_thread_pointer();
return (uintptr_t)thp;
#endif
/*
#elif (defined(__GNUC__) || defined(__clang__)) && !defined(__CYGWIN__)
uintptr_t tid;
#if defined(__i386__)
__asm__("movl %%gs:0, %0" : "=r"(tid) : :);
#elif defined(__x86_64__)
#if defined(__MACH__)
__asm__("movq %%gs:0, %0" : "=r"(tid) : :);
#else
__asm__("movq %%fs:0, %0" : "=r"(tid) : :);
#endif
#elif defined(__arm__)
__asm__ volatile("mrc p15, 0, %0, c13, c0, 3" : "=r"(tid));
#elif defined(__aarch64__)
#if defined(__MACH__)
// tpidr_el0 likely unused, always return 0 on iOS
__asm__ volatile("mrs %0, tpidrro_el0" : "=r"(tid));
#else
__asm__ volatile("mrs %0, tpidr_el0" : "=r"(tid));
#endif
#else
#error This platform needs implementation of get_thread_id()
#endif
return tid;
#else
#error This platform needs implementation of get_thread_id()
#endif
*/
}
//! Set the current thread heap
static void
set_thread_heap(heap_t* heap) {
global_thread_heap = heap;
if (heap && (heap->id != 0)) {
rpmalloc_assert(heap->id != 0, "Default heap being used");
heap->owner_thread = get_thread_id();
}
#if PLATFORM_WINDOWS
FlsSetValue(fls_key, heap);
#else
pthread_setspecific(pthread_key, heap);
#endif
}
static heap_t*
get_thread_heap_allocate(void) {
heap_t* heap = heap_allocate(0);
set_thread_heap(heap);
return heap;
}
//! Get the current thread heap
static inline heap_t*
get_thread_heap(void) {
return global_thread_heap;
}
//! Get the size class from given size in bytes for tiny blocks (below 16 times the minimum granularity)
static inline uint32_t
get_size_class_tiny(size_t size) {
return (((uint32_t)size + (SMALL_GRANULARITY - 1)) / SMALL_GRANULARITY);
}
//! Get the size class from given size in bytes
static inline uint32_t
get_size_class(size_t size) {
uintptr_t minblock_count = (size + (SMALL_GRANULARITY - 1)) / SMALL_GRANULARITY;
// For sizes up to 64 times the minimum granularity (i.e 1024 bytes) the size class is equal to number of such
// blocks
if (size <= (SMALL_GRANULARITY * 64)) {
rpmalloc_assert(global_size_class[minblock_count].block_size >= size, "Size class misconfiguration");
return (uint32_t)(minblock_count ? minblock_count : 1);
}
--minblock_count;
// Calculate position of most significant bit, since minblock_count now guaranteed to be > 64 this position is
// guaranteed to be >= 6
#if ARCH_64BIT
const uint32_t most_significant_bit = (uint32_t)(63 - (int)rpmalloc_clz(minblock_count));
#else
const uint32_t most_significant_bit = (uint32_t)(31 - (int)rpmalloc_clz(minblock_count));
#endif
// Class sizes are of the bit format [..]000xxx000[..] where we already have the position of the most significant
// bit, now calculate the subclass from the remaining two bits
const uint32_t subclass_bits = (minblock_count >> (most_significant_bit - 2)) & 0x03;
const uint32_t class_idx = (uint32_t)((most_significant_bit << 2) + subclass_bits) + 41;
rpmalloc_assert((class_idx >= SIZE_CLASS_COUNT) || (global_size_class[class_idx].block_size >= size),
"Size class misconfiguration");
rpmalloc_assert((class_idx >= SIZE_CLASS_COUNT) || (global_size_class[class_idx - 1].block_size < size),
"Size class misconfiguration");
return class_idx;
}
static inline page_type_t
get_page_type(uint32_t size_class) {
if (size_class < SMALL_SIZE_CLASS_COUNT)
return PAGE_SMALL;
else if (size_class < (SMALL_SIZE_CLASS_COUNT + MEDIUM_SIZE_CLASS_COUNT))
return PAGE_MEDIUM;
else if (size_class < SIZE_CLASS_COUNT)
return PAGE_LARGE;
return PAGE_HUGE;
}
static inline size_t
get_page_aligned_size(size_t size) {
size_t unalign = size % global_config.page_size;
if (unalign)
size += global_config.page_size - unalign;
return size;
}
////////////
///
/// OS entry points
///
//////
static void
os_set_page_name(void* address, size_t size) {
#if defined(__linux__) || defined(__ANDROID__)
const char* name = os_huge_pages ? global_config.huge_page_name : global_config.page_name;
if ((address == MAP_FAILED) || !name)
return;
// If the kernel does not support CONFIG_ANON_VMA_NAME or if the call fails
// (e.g. invalid name) it is a no-op basically.
(void)prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (uintptr_t)address, size, (uintptr_t)name);
#else
(void)sizeof(size);
(void)sizeof(address);
#endif
}
static void*
os_mmap(size_t size, size_t alignment, size_t* offset, size_t* mapped_size) {
size_t map_size = size + alignment;
#if PLATFORM_WINDOWS
// Ok to MEM_COMMIT - according to MSDN, "actual physical pages are not allocated unless/until the virtual addresses
// are actually accessed". But if we enable decommit it's better to not immediately commit and instead commit per
// page to avoid saturating the OS commit limit
#if ENABLE_DECOMMIT
DWORD do_commit = 0;
#else
DWORD do_commit = MEM_COMMIT;
#endif
void* ptr =
VirtualAlloc(0, map_size, (os_huge_pages ? MEM_LARGE_PAGES : 0) | MEM_RESERVE | do_commit, PAGE_READWRITE);
#else
int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_UNINITIALIZED;
#if defined(__APPLE__) && !TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
int fd = (int)VM_MAKE_TAG(240U);
if (os_huge_pages)
fd |= VM_FLAGS_SUPERPAGE_SIZE_2MB;
void* ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, flags, fd, 0);
#elif defined(MAP_HUGETLB)
void* ptr = mmap(0, map_size, PROT_READ | PROT_WRITE | PROT_MAX(PROT_READ | PROT_WRITE),
(os_huge_pages ? MAP_HUGETLB : 0) | flags, -1, 0);
#if defined(MADV_HUGEPAGE)
// In some configurations, huge pages allocations might fail thus
// we fallback to normal allocations and promote the region as transparent huge page
if ((ptr == MAP_FAILED || !ptr) && os_huge_pages) {
ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, flags, -1, 0);
if (ptr && ptr != MAP_FAILED) {
int prm = madvise(ptr, size, MADV_HUGEPAGE);
(void)prm;
rpmalloc_assert((prm == 0), "Failed to promote the page to transparent huge page");
}
}
#endif
os_set_page_name(ptr, map_size);
#elif defined(MAP_ALIGNED)
const size_t align = (sizeof(size_t) * 8) - (size_t)(__builtin_clzl(size - 1));
void* ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, (os_huge_pages ? MAP_ALIGNED(align) : 0) | flags, -1, 0);
#elif defined(MAP_ALIGN)
caddr_t base = (os_huge_pages ? (caddr_t)(4 << 20) : 0);
void* ptr = mmap(base, map_size, PROT_READ | PROT_WRITE, (os_huge_pages ? MAP_ALIGN : 0) | flags, -1, 0);
#else
void* ptr = mmap(0, map_size, PROT_READ | PROT_WRITE, flags, -1, 0);
#endif
if (ptr == MAP_FAILED)
ptr = 0;
#endif
if (!ptr) {
if (global_memory_interface->map_fail_callback) {
if (global_memory_interface->map_fail_callback(map_size))
return os_mmap(size, alignment, offset, mapped_size);
} else {
rpmalloc_assert(ptr != 0, "Failed to map more virtual memory");
}
return 0;
}
if (alignment) {
size_t padding = ((uintptr_t)ptr & (uintptr_t)(alignment - 1));
if (padding)
padding = alignment - padding;
rpmalloc_assert(padding <= alignment, "Internal failure in padding");
rpmalloc_assert(!(padding % 8), "Internal failure in padding");
ptr = pointer_offset(ptr, padding);
*offset = padding;
}
*mapped_size = map_size;
#if ENABLE_STATISTICS
size_t page_count = map_size / global_config.page_size;
size_t page_mapped_current =
atomic_fetch_add_explicit(&global_statistics.page_mapped, page_count, memory_order_relaxed) + page_count;
size_t page_mapped_peak = atomic_load_explicit(&global_statistics.page_mapped_peak, memory_order_relaxed);
while (page_mapped_current > page_mapped_peak) {
if (atomic_compare_exchange_weak_explicit(&global_statistics.page_mapped_peak, &page_mapped_peak,
page_mapped_current, memory_order_relaxed, memory_order_relaxed))
break;
}
#if ENABLE_DECOMMIT
size_t page_active_current =
atomic_fetch_add_explicit(&global_statistics.page_active, page_count, memory_order_relaxed) + page_count;
size_t page_active_peak = atomic_load_explicit(&global_statistics.page_active_peak, memory_order_relaxed);
while (page_active_current > page_active_peak) {
if (atomic_compare_exchange_weak_explicit(&global_statistics.page_active_peak, &page_active_peak,
page_active_current, memory_order_relaxed, memory_order_relaxed))
break;
}
#endif
#endif
return ptr;
}
static void
os_mcommit(void* address, size_t size) {
#if ENABLE_DECOMMIT
if (global_config.disable_decommit)
return;
#if PLATFORM_WINDOWS
if (!VirtualAlloc(address, size, MEM_COMMIT, PAGE_READWRITE)) {
rpmalloc_assert(0, "Failed to commit virtual memory block");
}
#else
/*
if (mprotect(address, size, PROT_READ | PROT_WRITE)) {
rpmalloc_assert(0, "Failed to commit virtual memory block");
}
*/
#endif
#if ENABLE_STATISTICS
size_t page_count = size / global_config.page_size;
atomic_fetch_add_explicit(&global_statistics.page_commit, page_count, memory_order_relaxed);
size_t page_active_current =
atomic_fetch_add_explicit(&global_statistics.page_active, page_count, memory_order_relaxed) + page_count;
size_t page_active_peak = atomic_load_explicit(&global_statistics.page_active_peak, memory_order_relaxed);
while (page_active_current > page_active_peak) {
if (atomic_compare_exchange_weak_explicit(&global_statistics.page_active_peak, &page_active_peak,
page_active_current, memory_order_relaxed, memory_order_relaxed))
break;
}
#endif
#endif
(void)sizeof(address);
(void)sizeof(size);
}
static void
os_mdecommit(void* address, size_t size) {
#if ENABLE_DECOMMIT
if (global_config.disable_decommit)
return;
#if PLATFORM_WINDOWS
if (!VirtualFree(address, size, MEM_DECOMMIT)) {
rpmalloc_assert(0, "Failed to decommit virtual memory block");
}
#else
/*
if (mprotect(address, size, PROT_NONE)) {
rpmalloc_assert(0, "Failed to decommit virtual memory block");
}
*/
#if defined(MADV_DONTNEED)
if (madvise(address, size, MADV_DONTNEED)) {
#elif defined(MADV_FREE_REUSABLE)
int ret;
while ((ret = madvise(address, size, MADV_FREE_REUSABLE)) == -1 && (errno == EAGAIN))
errno = 0;
if ((ret == -1) && (errno != 0)) {
#elif defined(MADV_PAGEOUT)
if (madvise(address, size, MADV_PAGEOUT)) {
#elif defined(MADV_FREE)
if (madvise(address, size, MADV_FREE)) {
#else
if (posix_madvise(address, size, POSIX_MADV_DONTNEED)) {
#endif
rpmalloc_assert(0, "Failed to decommit virtual memory block");
}
#endif
#if ENABLE_STATISTICS
size_t page_count = size / global_config.page_size;
atomic_fetch_add_explicit(&global_statistics.page_decommit, page_count, memory_order_relaxed);
size_t page_active_current =
atomic_fetch_sub_explicit(&global_statistics.page_active, page_count, memory_order_relaxed);
rpmalloc_assert(page_active_current >= page_count, "Decommit counter out of sync");
(void)sizeof(page_active_current);
#endif
#else
(void)sizeof(address);
(void)sizeof(size);
#endif
}
static void
os_munmap(void* address, size_t offset, size_t mapped_size) {
(void)sizeof(mapped_size);
address = pointer_offset(address, -(int32_t)offset);
#if ENABLE_UNMAP
#if PLATFORM_WINDOWS
if (!VirtualFree(address, 0, MEM_RELEASE)) {
rpmalloc_assert(0, "Failed to unmap virtual memory block");
}
#else
if (munmap(address, mapped_size))
rpmalloc_assert(0, "Failed to unmap virtual memory block");
#endif
#if ENABLE_STATISTICS
size_t page_count = mapped_size / global_config.page_size;
atomic_fetch_sub_explicit(&global_statistics.page_mapped, page_count, memory_order_relaxed);
atomic_fetch_sub_explicit(&global_statistics.page_active, page_count, memory_order_relaxed);
#endif
#endif
}
////////////
///
/// Page interface
///
//////
static inline span_t*
page_get_span(page_t* page) {
return (span_t*)((uintptr_t)page & SPAN_MASK);
}
static inline size_t
page_get_size(page_t* page) {
if (page->page_type == PAGE_SMALL)
return SMALL_PAGE_SIZE;
else if (page->page_type == PAGE_MEDIUM)
return MEDIUM_PAGE_SIZE;
else if (page->page_type == PAGE_LARGE)
return LARGE_PAGE_SIZE;
else
return page_get_span(page)->page_size;
}
static inline int
page_is_thread_heap(page_t* page) {
#if RPMALLOC_FIRST_CLASS_HEAPS
return (!page->heap->owner_thread || (page->heap->owner_thread == get_thread_id()));
#else
return (page->heap->owner_thread == get_thread_id());
#endif
}
static inline block_t*
page_block_start(page_t* page) {
return pointer_offset(page, PAGE_HEADER_SIZE);
}
static inline block_t*
page_block(page_t* page, uint32_t block_index) {
return pointer_offset(page, PAGE_HEADER_SIZE + (page->block_size * block_index));
}
static inline uint32_t
page_block_index(page_t* page, block_t* block) {
block_t* block_first = page_block_start(page);
return (uint32_t)pointer_diff(block, block_first) / page->block_size;
}
static inline uint32_t
page_block_from_thread_free_list(page_t* page, uint64_t token, block_t** block) {
uint32_t block_index = (uint32_t)(token & 0xFFFFFFFFULL);
uint32_t list_count = (uint32_t)((token >> 32ULL) & 0xFFFFFFFFULL);
*block = list_count ? page_block(page, block_index) : 0;
return list_count;
}
static inline uint64_t
page_block_to_thread_free_list(page_t* page, uint32_t block_index, uint32_t list_count) {
(void)sizeof(page);
return ((uint64_t)list_count << 32ULL) | (uint64_t)block_index;
}
static inline block_t*
page_block_realign(page_t* page, block_t* block) {
void* blocks_start = page_block_start(page);
uint32_t block_offset = (uint32_t)pointer_diff(block, blocks_start);
return pointer_offset(block, -(int32_t)(block_offset % page->block_size));
}
static block_t*
page_get_local_free_block(page_t* page) {
block_t* block = page->local_free;
page->local_free = block->next;
--page->local_free_count;
++page->block_used;
return block;
}
static inline void
page_decommit_memory_pages(page_t* page) {
if (page->is_decommitted)
return;
void* extra_page = pointer_offset(page, global_config.page_size);
size_t extra_page_size = page_get_size(page) - global_config.page_size;
global_memory_interface->memory_decommit(extra_page, extra_page_size);
page->is_decommitted = 1;
}
static inline void
page_commit_memory_pages(page_t* page) {
if (!page->is_decommitted)
return;
void* extra_page = pointer_offset(page, global_config.page_size);
size_t extra_page_size = page_get_size(page) - global_config.page_size;
global_memory_interface->memory_commit(extra_page, extra_page_size);
page->is_decommitted = 0;
#if ENABLE_DECOMMIT
#if !defined(__APPLE__)
// When page is recommitted, the blocks in the second memory page and forward
// will be zeroed out by OS - take advantage in zalloc/calloc calls and make sure
// blocks in first page is zeroed out
void* first_page = pointer_offset(page, PAGE_HEADER_SIZE);
memset(first_page, 0, global_config.page_size - PAGE_HEADER_SIZE);
page->is_zero = 1;