-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllmalloc.h
5035 lines (4111 loc) · 174 KB
/
llmalloc.h
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
/*
LLMALLOC VERSION 1.0.1
MIT License
Copyright (c) 2025 Akin Ocal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Acknowledgements:
This project uses a cosmetically modified version of Erik Rigtorp's lock-free queue implementation,
available at https://github.com/rigtorp/MPMCQueue, which is licenced under the MIT License.
*/
#ifndef _LLMALLOC_H_
#define _LLMALLOC_H_
// STD C
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cmath>
#include <cassert>
#include <cstring>
#include <cctype>
#include <cstdlib>
// STD
#include <type_traits>
#include <array>
#include <string_view>
#include <new>
#ifdef ENABLE_PMR
#include <memory_resource>
#endif
#ifdef ENABLE_OVERRIDE
#include <stdexcept>
#endif
// CPU INTRINSICS
#include <immintrin.h>
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__GNUC__)
#include <emmintrin.h>
#endif
// LINUX
#ifdef __linux__
#include <unistd.h>
#include <sys/mman.h>
#include <pthread.h>
#include <sched.h>
#include <fcntl.h>
#ifdef ENABLE_OVERRIDE
#include <limits.h>
#include <dlfcn.h>
#include <errno.h>
#endif
#ifdef ENABLE_NUMA
#include <numa.h>
#include <numaif.h>
#endif
#endif
// WINDOWS
#ifdef _WIN32
#include <windows.h>
#include <fibersapi.h>
#include <chrono>
#include <thread>
#endif
// TRACES
#if defined(ENABLE_PERF_TRACES) || defined(DISPLAY_ENV_VARS) || !defined(NDEBUG)
#include <cstdio>
#endif
// UNIT TESTS
#ifdef UNIT_TEST
#include <string>
#include <cstdio>
#endif
namespace llmalloc
{
//////////////////////////////////////////////////////////////////////
// COMPILER CHECK
#if (! defined(_MSC_VER)) && (! defined(__GNUC__))
#error "This library is supported for only GCC and MSVC compilers"
#endif
//////////////////////////////////////////////////////////////////////
// C++ VERSION CHECK
#if defined(_MSC_VER)
#if _MSVC_LANG < 201703L
#error "This library requires to be compiled with C++17"
#endif
#elif defined(__GNUC__)
#if __cplusplus < 201703L
#error "This library requires to be compiled with C++17"
#endif
#endif
//////////////////////////////////////////////////////////////////////
// ARCHITECTURE CHECK
#if defined(_MSC_VER)
#if (! defined(_M_X64))
#error "This library is supported for only x86-x64 architectures"
#endif
#elif defined(__GNUC__)
#if (! defined(__x86_64__)) && (! defined(__x86_64))
#error "This library is supported for only x86-x64 architectures"
#endif
#endif
//////////////////////////////////////////////////////////////////////
// OPERATING SYSTEM CHECK
#if (! defined(__linux__)) && (! defined(_WIN32) )
#error "This library is supported for Linux and Windows systems"
#endif
//////////////////////////////////////////////////////////////////////
// Count leading zeroes
#if defined(__GNUC__)
#define builtin_clzl(n) __builtin_clzl(n)
#elif defined(_MSC_VER)
#if defined(_WIN64) // Implementation is for 64-bit only.
inline int builtin_clzl(unsigned long value)
{
unsigned long index = 0;
return _BitScanReverse64(&index, static_cast<unsigned __int64>(value)) ? static_cast<int>(63 - index) : 64;
}
#else
#error "This code is intended for 64-bit Windows platforms only."
#endif
#endif
//////////////////////////////////////////////////////////////////////
// Compare and swap, standard C++ provides them however it requires non-POD std::atomic usage
// They are needed when we want to embed spinlocks in "packed" data structures which need all members to be POD such as headers
#if defined(__GNUC__)
#define builtin_cas(pointer, old_value, new_value) __sync_val_compare_and_swap(pointer, old_value, new_value)
#elif defined(_MSC_VER)
#define builtin_cas(pointer, old_value, new_value) _InterlockedCompareExchange(reinterpret_cast<long*>(pointer), new_value, old_value)
#endif
//////////////////////////////////////////////////////////////////////
// memcpy
#if defined(__GNUC__)
#define builtin_memcpy(destination, source, size) __builtin_memcpy(destination, source, size)
#elif defined(_MSC_VER)
#define builtin_memcpy(destination, source, size) std::memcpy(destination, source, size)
#endif
//////////////////////////////////////////////////////////////////////
// memset
#if defined(__GNUC__)
#define builtin_memset(destination, character, count) __builtin_memset(destination, character, count)
#elif defined(_MSC_VER)
#define builtin_memset(destination, character, count) std::memset(destination, character, count)
#endif
//////////////////////////////////////////////////////////////////////
// aligned_alloc , It exists because MSVC does not provide std::aligned_alloc
#if defined(__GNUC__)
#define builtin_aligned_alloc(size, alignment) std::aligned_alloc(alignment, size)
#define builtin_aligned_free(ptr) std::free(ptr)
#elif defined(_MSC_VER)
#define builtin_aligned_alloc(size, alignment) _aligned_malloc(size, alignment)
#define builtin_aligned_free(ptr) _aligned_free(ptr)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LIKELY
#if defined(_MSC_VER)
//No implementation provided for MSVC for pre C++20 :
//https://social.msdn.microsoft.com/Forums/vstudio/en-US/2dbdca4d-c0c0-40a3-993b-dc78817be26e/branch-hints?forum=vclanguage
#define likely(x) x
#elif defined(__GNUC__)
#define likely(x) __builtin_expect(!!(x), 1)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// UNLIKELY
#if defined(_MSC_VER)
//No implementation provided for MSVC for pre C++20 :
//https://social.msdn.microsoft.com/Forums/vstudio/en-US/2dbdca4d-c0c0-40a3-993b-dc78817be26e/branch-hints?forum=vclanguage
#define unlikely(x) x
#elif defined(__GNUC__)
#define unlikely(x) __builtin_expect(!!(x), 0)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FORCE_INLINE
#if defined(_MSC_VER)
#define FORCE_INLINE __forceinline
#elif defined(__GNUC__)
#define FORCE_INLINE __attribute__((always_inline))
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ALIGN_DATA , some GCC versions gives warnings about standard C++ 'alignas' when applied to data
#ifdef __GNUC__
#define ALIGN_DATA( _alignment_ ) __attribute__((aligned( (_alignment_) )))
#elif _MSC_VER
#define ALIGN_DATA( _alignment_ ) alignas( _alignment_ )
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ALIGN_CODE, using alignas(64) or __attribute__(aligned(alignment)) for a function will work in GCC but MSVC won't compile
#ifdef __GNUC__
#define ALIGN_CODE( _alignment_ ) __attribute__((aligned( (_alignment_) )))
#elif _MSC_VER
//No implementation provided for MSVC :
#define ALIGN_CODE( _alignment_ )
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PACKED
// Compilers may add additional padding zeroes for alignment
// Though those additions may increase the size of your structs/classes
// The ideal way is manually aligning data structures and minimising the memory footprint
// Compilers won`t add additional padding zeroes for "packed" data structures
#ifdef __GNUC__
#define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__))
#elif _MSC_VER
#define PACKED( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop))
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// UNUSED
//To avoid unused variable warnings
#if defined(__GNUC__)
#define UNUSED(x) (void)(x)
#elif defined(_MSC_VER)
#define UNUSED(x) __pragma(warning(suppress:4100)) x
#endif
namespace AlignmentConstants
{
// All constants are in bytes
constexpr std::size_t CPU_CACHE_LINE_SIZE = 64;
// SIMD REGISTER WIDTHS
constexpr std::size_t SIMD_SSE42_WIDTH = 16;
constexpr std::size_t SIMD_AVX_WIDTH = 32;
constexpr std::size_t SIMD_AVX2_WIDTH = 32;
constexpr std::size_t SIMD_AVX512_WIDTH = 64;
constexpr std::size_t SIMD_AVX10_WIDTH = 64;
constexpr std::size_t MINIMUM_VECTORISATION_WIDTH = SIMD_SSE42_WIDTH;
constexpr std::size_t LARGEST_VECTORISATION_WIDTH = SIMD_AVX10_WIDTH;
// VIRTUAL MEMORY PAGE SIZES ARE HANDLED IN os/virtual_memory.h
}
/*
Intel initially advised using _mm_pause in spin-wait loops in case of hyperthreading
Before Skylake it was about 10 cycles, but with Skylake it becomes 140 cycles and that applies to successor architectures
-> Intel opt manual 2.5.4 "Pause Latency in Skylake Client Microarchitecture"
Later _tpause / _umonitor / _umwait instructions were introduced however not using them for the time being as they are not widespread yet
Pause implementation is instead using nop
*/
inline void pause(uint16_t repeat_count=100)
{
#if defined(__GNUC__)
// rep is for repeating by the no provided in 16 bit cx register
__asm__ __volatile__("mov %0, %%cx\n\trep; nop" : : "r" (repeat_count) : "cx");
#elif defined(_WIN32)
for (uint16_t i = 0; i < repeat_count; ++i)
{
_mm_lfence();
__nop();
_mm_lfence();
}
#endif
}
// ANSI coloured output for Linux , message box for Windows
#ifdef NDEBUG
#define assert_msg(expr, message) ((void)0)
#else
#ifdef __linux__
#define MAKE_RED(x) "\033[0;31m" x "\033[0m"
#define MAKE_YELLOW(x) "\033[0;33m" x "\033[0m"
#define assert_msg(expr, message) \
do { \
if (!(expr)) { \
fprintf(stderr, MAKE_RED("Assertion failed : ") MAKE_YELLOW("%s") "\n", message); \
assert(false); \
} \
} while (0)
#elif _WIN32
#pragma comment(lib, "user32.lib")
#define assert_msg(expr, message) \
do { \
if (!(expr)) { \
MessageBoxA(NULL, message, "Assertion Failed", MB_ICONERROR | MB_OK); \
assert(false); \
} \
} while (0)
#endif
#endif
/*
- To work with 2MB huge pages on Linux and 2MB or 1 GB huge pages on Windows , you may need to configure your system :
- Linux : /proc/meminfo should have non-zero "Hugepagesize" & "HugePages_Total/HugePages_Free" attributes
( If HugePages_Total or HugePages_Free is 0
then run "echo 20 | sudo tee /proc/sys/vm/nr_hugepages" ( Allocates 20 x 2MB huge pages )
Reference : https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt )
( If THP is enabled , we will use madvise. Otherwise we will use HUGE_TLB flag for mmap.
To check if THP enabled : cat /sys/kernel/mm/transparent_hugepage/enabled
To disable THP : echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
)
- Windows : SeLockMemoryPrivilege is required.
It can be acquired using gpedit.msc :
Local Computer Policy -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Managements -> Lock pages in memory
- For NUMA-local allocations :
You need : #define ENABLE_NUMA
Also if on Linux , you need libnuma ( For ex : RHEL -> sudo yum install numactl-devel & Ubuntu -> sudo apt install libnuma-dev ) and -lnuma for GCC
*/
#ifdef _WIN32
#pragma warning(disable:6250)
#endif
class VirtualMemory
{
public:
#ifdef __linux__
constexpr static std::size_t PAGE_ALLOCATION_GRANULARITY = 4096; // In bytes
#elif _WIN32
constexpr static std::size_t PAGE_ALLOCATION_GRANULARITY = 65536; // In bytes , https://devblogs.microsoft.com/oldnewthing/20031008-00/?p=42223
#endif
static std::size_t get_page_size()
{
std::size_t ret{ 0 };
#ifdef __linux__
ret = static_cast<std::size_t>(sysconf(_SC_PAGESIZE)); // TYPICALLY 4096, 2^ 12
#elif _WIN32
// https://learn.microsoft.com/en-gb/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
ret = system_info.dwPageSize; // TYPICALLY 4096, 2^ 12
#endif
return ret;
}
static bool is_huge_page_available()
{
bool ret{ false };
#ifdef __linux__
if (get_minimum_huge_page_size() <= 0)
{
ret = false;
}
else
{
if ( get_huge_page_total_count_2mb() > 0 )
{
ret = true;
}
}
#elif _WIN32
auto huge_page_size = get_minimum_huge_page_size();
if (huge_page_size)
{
HANDLE token = 0;
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token);
if (token)
{
LUID luid;
if (LookupPrivilegeValue(0, SE_LOCK_MEMORY_NAME, &luid))
{
TOKEN_PRIVILEGES token_privileges;
memset(&token_privileges, 0, sizeof(token_privileges));
token_privileges.PrivilegeCount = 1;
token_privileges.Privileges[0].Luid = luid;
token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (AdjustTokenPrivileges(token, FALSE, &token_privileges, 0, 0, 0))
{
auto last_error = GetLastError();
if (last_error == ERROR_SUCCESS)
{
ret = true;
}
}
}
}
}
#endif
return ret;
}
static std::size_t get_minimum_huge_page_size()
{
std::size_t ret{ 0 };
#ifdef __linux__
ret = get_proc_mem_info("Hugepagesize", 13) * 1024; // It is in KBs
#elif _WIN32
ret = static_cast<std::size_t>(GetLargePageMinimum());
#endif
return ret;
}
// Note about alignments : Windows always returns page ( typically 4KB ) or huge page ( typially 2MB ) aligned addresses
// On Linux , page sized ( again 4KB) allocations are aligned to 4KB, but the same does not apply to huge page allocations : They are aligned to 4KB but never to 2MB
// Therefore in case of huge page use, there is no guarantee that the allocated address will be huge-page-aligned , so alignment requirements have to be handled by the caller
//
// Note about huge page failures : If huge page allocation fails, for the time being not doing a fallback for a subsequent non huge page allocation
// So library users have to check return values
//
static void* allocate(std::size_t size, bool use_huge_pages, int numa_node = -1, void* hint_address = nullptr)
{
void* ret = nullptr;
#ifdef __linux__
static bool thp_enabled = is_thp_enabled();
// MAP_ANONYMOUS rather than going thru a file (memory mapped file)
// MAP_PRIVATE rather than shared memory
int flags = MAP_PRIVATE | MAP_ANONYMOUS;
// MAP_POPULATE forces system to access the just-allocated memory. That helps by creating TLB entries
flags |= MAP_POPULATE;
if(use_huge_pages)
{
if (!thp_enabled)
{
flags |= MAP_HUGETLB;
}
}
ret = mmap(hint_address, size, PROT_READ | PROT_WRITE, flags, -1, 0);
if (ret == nullptr || ret == MAP_FAILED)
{
return nullptr;
}
if(use_huge_pages)
{
if (thp_enabled)
{
madvise(ret, size, MADV_HUGEPAGE);
}
}
#ifdef ENABLE_NUMA
if(numa_node >= 0)
{
auto numa_node_count = get_numa_node_count();
if (numa_node_count > 0 && numa_node != static_cast<std::size_t>(-1))
{
unsigned long nodemask = 1UL << numa_node;
int result = mbind(ret, size, MPOL_BIND, &nodemask, sizeof(nodemask), MPOL_MF_MOVE);
if (result != 0)
{
munmap(ret, size);
ret = nullptr;
}
else
{
int actual_numa_node = get_numa_node_of_address(ret);
if(actual_numa_node != numa_node)
{
munmap(ret, size);
ret = nullptr;
}
}
}
}
#else
UNUSED(numa_node);
#endif
#elif _WIN32
int flags = MEM_RESERVE | MEM_COMMIT;
if (use_huge_pages)
{
flags |= MEM_LARGE_PAGES;
}
#ifndef ENABLE_NUMA
UNUSED(numa_node);
ret = VirtualAlloc(hint_address, size, flags, PAGE_READWRITE);
#else
if(numa_node >= 0)
{
auto numa_node_count = get_numa_node_count();
if (numa_node_count > 0 && numa_node != static_cast<std::size_t>(-1))
{
ret = VirtualAllocExNuma(GetCurrentProcess(), hint_address, size, flags, PAGE_READWRITE, static_cast<DWORD>(numa_node));
}
else
{
ret = VirtualAlloc(hint_address, size, flags, PAGE_READWRITE);
}
}
else
{
ret = VirtualAlloc(hint_address, size, flags, PAGE_READWRITE);
}
#endif
#endif
return ret;
}
static bool deallocate(void* address, std::size_t size)
{
bool ret{ false };
#ifdef __linux__
ret = munmap(address, size) == 0 ? true : false;
#elif _WIN32
ret = VirtualFree(address, size, MEM_DECOMMIT) ? true : false;
#endif
return ret;
}
#ifdef __linux__
// THP stands for "transparent huge page". A Linux mechanism
// It affects how we handle allocation of huge pages on Linux
static bool is_thp_enabled()
{
const char* thp_enabled_file = "/sys/kernel/mm/transparent_hugepage/enabled";
if (access(thp_enabled_file, F_OK) != 0)
{
return false;
}
int fd = open(thp_enabled_file, O_RDONLY);
if (fd < 0)
{
return false;
}
char buffer[256] = {0};
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
close(fd);
if (bytes_read <= 0)
{
return false;
}
if (strstr(buffer, "[always]") != nullptr || strstr(buffer, "[madvise]") != nullptr)
{
return true;
}
return false;
}
#endif
private :
#ifdef __linux__
// Equivalent of /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
static std::size_t get_huge_page_total_count_2mb()
{
auto ret = get_proc_mem_info("HugePages_Total", 16);
if(ret == 0 )
{
ret = get_proc_mem_info("HugePages_Free", 15);
}
return ret;
}
static std::size_t get_proc_mem_info(const char* attribute, std::size_t attribute_len)
{
// Using syscalls to avoid memory allocations
std::size_t ret = 0;
const char* mem_info_file = "/proc/meminfo";
int fd = open(mem_info_file, O_RDONLY);
if (fd < 0)
{
return ret;
}
char buffer[256] = {0};
std::size_t read_bytes;
while ((read_bytes = read(fd, buffer, sizeof(buffer))) > 0)
{
char* pos = strstr(buffer, attribute);
if (pos != nullptr)
{
ret = std::strtoul(pos + attribute_len, nullptr, 10);
break;
}
}
close(fd);
return ret;
}
#endif
#ifdef ENABLE_NUMA
static std::size_t get_numa_node_count()
{
std::size_t ret{ 0 };
#ifdef __linux__
// Requires -lnuma
ret = static_cast<std::size_t>(numa_num_configured_nodes());
#elif _WIN32
// GetNumaHighestNodeNumber is not guaranteed to be equal to NUMA node count so we need to iterate backwards
ULONG current_numa_node = 0;
GetNumaHighestNodeNumber(¤t_numa_node);
while (current_numa_node > 0)
{
GROUP_AFFINITY affinity;
if ((GetNumaNodeProcessorMaskEx)(static_cast<USHORT>(current_numa_node), &affinity))
{
//If the specified node has no processors configured, the Mask member is zero
if (affinity.Mask != 0)
{
ret++;
}
}
// max node was invalid or had no processor assigned, try again
current_numa_node--;
}
#endif
return ret;
}
static int get_numa_node_of_address(void* ptr)
{
int actual_numa_node = -1;
#ifdef __linux__
get_mempolicy(&actual_numa_node, nullptr, 0, (void*)ptr, MPOL_F_NODE | MPOL_F_ADDR);
#elif _WIN32
// Not supported on Windows
#endif
return actual_numa_node;
}
#endif
};
/*
Standard C++ thread_local keyword does not allow you to specify thread specific destructors
and also can't be applied to class members
*/
class ThreadLocalStorage
{
public:
static ThreadLocalStorage& get_instance()
{
static ThreadLocalStorage instance;
return instance;
}
// Call it only once for a process
bool create(void(*thread_destructor)(void*) = nullptr)
{
#if __linux__
return pthread_key_create(&m_tls_index, thread_destructor) == 0;
#elif _WIN32
// Using FLSs rather TLS as it is identical + TLSAlloc doesn't support dtor
m_tls_index = FlsAlloc(thread_destructor);
return m_tls_index == FLS_OUT_OF_INDEXES ? false : true;
#endif
}
// Same as create
void destroy()
{
if (m_tls_index)
{
#if __linux__
pthread_key_delete(m_tls_index);
#elif _WIN32
FlsFree(m_tls_index);
#endif
m_tls_index = 0;
}
}
// GUARANTEED TO BE THREAD-SAFE/LOCAL
void* get()
{
#if __linux__
return pthread_getspecific(m_tls_index);
#elif _WIN32
return FlsGetValue(m_tls_index);
#endif
}
void set(void* data_address)
{
#if __linux__
pthread_setspecific(m_tls_index, data_address);
#elif _WIN32
FlsSetValue(m_tls_index, data_address);
#endif
}
private:
#if __linux__
pthread_key_t m_tls_index = 0;
#elif _WIN32
unsigned long m_tls_index = 0;
#endif
ThreadLocalStorage() = default;
~ThreadLocalStorage() = default;
ThreadLocalStorage(const ThreadLocalStorage& other) = delete;
ThreadLocalStorage& operator= (const ThreadLocalStorage& other) = delete;
ThreadLocalStorage(ThreadLocalStorage&& other) = delete;
ThreadLocalStorage& operator=(ThreadLocalStorage&& other) = delete;
};
/*
Provides :
static unsigned int get_number_of_logical_cores()
static unsigned int get_number_of_physical_cores()
static bool is_hyper_threading()
static inline void yield()
*/
/*
Currently this module is not hybrid-architecture-aware
Ex: P-cores and E-cores starting from Alder Lake
That means all methods assume that all CPU cores are identical
*/
class ThreadUtilities
{
public:
static unsigned int get_number_of_logical_cores()
{
unsigned int num_cores{0};
#ifdef __linux__
num_cores = sysconf(_SC_NPROCESSORS_ONLN);
#elif _WIN32
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
num_cores = sysinfo.dwNumberOfProcessors;
#endif
return num_cores;
}
static unsigned int get_number_of_physical_cores()
{
auto num_logical_cores = get_number_of_logical_cores();
bool cpu_hyperthreading = is_hyper_threading();
return cpu_hyperthreading ? num_logical_cores / 2 : num_logical_cores;
}
static bool is_hyper_threading()
{
bool ret = false;
#ifdef __linux__
// Using syscalls to avoid dynamic memory allocation
int file_descriptor = open("/sys/devices/system/cpu/smt/active", O_RDONLY);
if (file_descriptor != -1)
{
char value;
if (read(file_descriptor, &value, sizeof(value)) > 0)
{
int smt_active = value - '0';
ret = (smt_active > 0);
}
close(file_descriptor);
}
#elif _WIN32
SYSTEM_INFO sys_info;
GetSystemInfo(&sys_info);
char buffer[2048]; // It may be insufficient however even if one logical processor has SMT flag , it means we are hyperthreading
DWORD buffer_size = sizeof(buffer);
GetLogicalProcessorInformation(reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION*>(&buffer), &buffer_size);
DWORD num_system_logical_processors = buffer_size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
for (DWORD i = 0; i < num_system_logical_processors; ++i)
{
if (reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION*>(&buffer[i])->Relationship == RelationProcessorCore)
{
if (reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION*>(&buffer[i])->ProcessorCore.Flags == LTP_PC_SMT)
{
ret = true;
break;
}
}
}
#endif
return ret;
}
static inline void yield()
{
#ifdef __linux__
sched_yield();
#elif _WIN32
SwitchToThread();
#endif
}
private:
};
#ifdef DISPLAY_ENV_VARS
#define MAKE_RED(x) "\033[0;31m" x "\033[0m"
#define MAKE_BLUE(x) "\033[0;34m" x "\033[0m"
#define MAKE_YELLOW(x) "\033[0;33m" x "\033[0m"
#endif
class EnvironmentVariable
{
public:
// Does not allocate memory
template <typename T>
static T get_variable(const char* environment_variable_name, T default_value)
{
T value = default_value;
char* str_value = nullptr;
#ifdef _WIN32
// MSVC does not allow std::getenv due to safety
std::size_t str_value_len;
errno_t err = _dupenv_s(&str_value, &str_value_len, environment_variable_name);
if (err)
return value;
#elif __linux__
str_value = std::getenv(environment_variable_name);
#endif
if (str_value)
{
if constexpr (std::is_arithmetic<T>::value)
{
char* end_ptr = nullptr;
auto current_val = std::strtold(str_value, &end_ptr);
if (*end_ptr == '\0')
{
value = static_cast<T>(current_val);
}
}
else if constexpr (std::is_same<T, char*>::value || std::is_same<T, const char*>::value)
{
value = str_value;
}
}
#ifdef DISPLAY_ENV_VARS
// Non allocating trace
fprintf(stderr, MAKE_RED("variable:") " " MAKE_BLUE("%s") ", " MAKE_RED("value:") " ", environment_variable_name);
if constexpr (std::is_same<T, double>::value)
{
fprintf(stderr, MAKE_YELLOW("%f") "\n", value);
}
else if constexpr (std::is_same<T, std::size_t>::value)
{
fprintf(stderr, MAKE_YELLOW("%zu") "\n", value);
}
else if constexpr (std::is_arithmetic<T>::value)
{
fprintf(stderr, MAKE_YELLOW("%d") "\n", value);
}
else
{
fprintf(stderr, MAKE_YELLOW("%s") "\n", value);
}
#endif
return value;
}
// Utility function when handling csv numeric parameters from environment variables, does not allocate memory
static void set_numeric_array_from_comma_separated_value_string(std::size_t* target_array, std::size_t array_size, const char* str)
{
auto len = strlen(str);
constexpr std::size_t MAX_STRING_LEN = 64;
constexpr std::size_t MAX_TOKEN_LEN = 8;
std::size_t start = 0;
std::size_t end = 0;
std::size_t counter = 0;
auto is_string_numeric = [](const char*str)
{
auto len = std::strlen(str);
for(std::size_t i = 0 ; i<len; i++)
{
if (!std::isdigit(static_cast<unsigned char>(str[i])))
{
return false;
}
}
return true;
};
while (end <= len && end < MAX_STRING_LEN - 1 && counter <array_size)
{
if (str[end] == ',' || (end > start && end == len))
{
char token[MAX_TOKEN_LEN];
std::size_t token_len = end - start;
#ifdef __linux__
strncpy(token, str + start, token_len);
#elif _WIN32
strncpy_s(token, str + start, token_len);
#endif
token[token_len] = '\0';
if(is_string_numeric(token) == false)
{
return;
}
target_array[counter] = atoi(token);
start = end + 1;
counter++;
}
++end;
}
}
};
class AlignmentAndSizeUtils
{
public:
static constexpr inline std::size_t CPP_DEFAULT_ALLOCATION_ALIGNMENT = 16;
// Generic check including non pow2
static bool is_address_aligned(void* address, std::size_t alignment)
{
auto address_in_question = reinterpret_cast<uint64_t>( address );
auto remainder = address_in_question - (address_in_question / alignment) * alignment;
return remainder == 0;
}
static bool is_pow2(std::size_t size)
{
return size > 0 && (size & (size - 1)) == 0;
}