-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
gcenv.unix.cpp
1659 lines (1427 loc) · 49.9 KB
/
gcenv.unix.cpp
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#define _WITH_GETLINE
#include <cstdint>
#include <cstddef>
#include <cstdio>
#include <cassert>
#define __STDC_FORMAT_MACROS
#include <cinttypes>
#include <memory>
#include <pthread.h>
#include <signal.h>
#include "config.gc.h"
#include "common.h"
#include "gcenv.structs.h"
#include "gcenv.base.h"
#include "gcenv.os.h"
#include "gcenv.ee.h"
#include "gcenv.unix.inl"
#include "volatile.h"
#include "gcconfig.h"
#include "numasupport.h"
#include <minipal/thread.h>
#if HAVE_SWAPCTL
#include <sys/swap.h>
#endif
#include <sys/resource.h>
#undef min
#undef max
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) (0)
#endif
#include <algorithm>
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#error "sys/time.h required by GC PAL for the time being"
#endif
#if HAVE_SYS_MMAN_H
#include <sys/mman.h>
#else
#error "sys/mman.h required by GC PAL"
#endif
#if HAVE_SYSCTLBYNAME
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#if HAVE_SYSINFO
#include <sys/sysinfo.h>
#endif
#if HAVE_XSWDEV
#include <vm/vm_param.h>
#endif // HAVE_XSWDEV
#ifdef __APPLE__
#include <mach/vm_types.h>
#include <mach/vm_param.h>
#include <mach/mach_port.h>
#include <mach/mach_host.h>
#include <mach/task.h>
#include <mach/vm_map.h>
extern "C"
{
# include <mach/thread_state.h>
}
#define CHECK_MACH(_msg, machret) do { \
if (machret != KERN_SUCCESS) \
{ \
char _szError[1024]; \
snprintf(_szError, ARRAY_SIZE(_szError), "%s: %u: %s", __FUNCTION__, __LINE__, _msg); \
mach_error(_szError, machret); \
abort(); \
} \
} while (false)
#endif // __APPLE__
#ifdef __HAIKU__
#include <OS.h>
#endif // __HAIKU__
#ifdef __linux__
#include <sys/syscall.h> // __NR_membarrier
// Ensure __NR_membarrier is defined for portable builds.
# if !defined(__NR_membarrier)
# if defined(__amd64__)
# define __NR_membarrier 324
# elif defined(__i386__)
# define __NR_membarrier 375
# elif defined(__arm__)
# define __NR_membarrier 389
# elif defined(__aarch64__)
# define __NR_membarrier 283
# elif defined(__loongarch64)
# define __NR_membarrier 283
# else
# error Unknown architecture
# endif
# endif
#endif
#if HAVE_PTHREAD_NP_H
#include <pthread_np.h>
#endif
#if HAVE_CPUSET_T
typedef cpuset_t cpu_set_t;
#endif
#include <time.h> // nanosleep
#include <sched.h> // sched_yield
#include <errno.h>
#include <unistd.h> // sysconf
#include "globals.h"
#include "cgroup.h"
#ifndef __APPLE__
#if HAVE_SYSCONF && HAVE__SC_AVPHYS_PAGES
#define SYSCONF_PAGES _SC_AVPHYS_PAGES
#elif HAVE_SYSCONF && HAVE__SC_PHYS_PAGES
#define SYSCONF_PAGES _SC_PHYS_PAGES
#else
#error Dont know how to get page-size on this architecture!
#endif
#endif // __APPLE__
#if defined(HOST_ARM) || defined(HOST_ARM64) || defined(HOST_LOONGARCH64) || defined(HOST_RISCV64)
#define SYSCONF_GET_NUMPROCS _SC_NPROCESSORS_CONF
#else
#define SYSCONF_GET_NUMPROCS _SC_NPROCESSORS_ONLN
#endif
// The cached total number of CPUs that can be used in the OS.
static uint32_t g_totalCpuCount = 0;
//
// Helper membarrier function
//
#ifdef __NR_membarrier
# define membarrier(...) syscall(__NR_membarrier, __VA_ARGS__)
#else
# define membarrier(...) -ENOSYS
#endif
enum membarrier_cmd
{
MEMBARRIER_CMD_QUERY = 0,
MEMBARRIER_CMD_GLOBAL = (1 << 0),
MEMBARRIER_CMD_GLOBAL_EXPEDITED = (1 << 1),
MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED = (1 << 2),
MEMBARRIER_CMD_PRIVATE_EXPEDITED = (1 << 3),
MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED = (1 << 4),
MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE = (1 << 5),
MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE = (1 << 6)
};
bool CanFlushUsingMembarrier()
{
#ifdef TARGET_ANDROID
// Avoid calling membarrier on older Android versions where membarrier
// may be barred by seccomp causing the process to be killed.
int apiLevel = android_get_device_api_level();
if (apiLevel < __ANDROID_API_Q__)
{
return false;
}
#endif
// Starting with Linux kernel 4.14, process memory barriers can be generated
// using MEMBARRIER_CMD_PRIVATE_EXPEDITED.
int mask = membarrier(MEMBARRIER_CMD_QUERY, 0);
if (mask >= 0 &&
mask & MEMBARRIER_CMD_PRIVATE_EXPEDITED &&
// Register intent to use the private expedited command.
membarrier(MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED, 0) == 0)
{
return true;
}
return false;
}
//
// Tracks if the OS supports FlushProcessWriteBuffers using membarrier
//
static int s_flushUsingMemBarrier = 0;
// Helper memory page used by the FlushProcessWriteBuffers
static uint8_t* g_helperPage = 0;
// Mutex to make the FlushProcessWriteBuffersMutex thread safe
static pthread_mutex_t g_flushProcessWriteBuffersMutex;
size_t GetRestrictedPhysicalMemoryLimit();
bool GetPhysicalMemoryUsed(size_t* val);
static size_t g_RestrictedPhysicalMemoryLimit = 0;
uint32_t g_pageSizeUnixInl = 0;
AffinitySet g_processAffinitySet;
extern "C" int g_highestNumaNode;
extern "C" bool g_numaAvailable;
static int64_t g_totalPhysicalMemSize = 0;
#ifdef TARGET_APPLE
static int *g_kern_memorystatus_level_mib = NULL;
static size_t g_kern_memorystatus_level_mib_length = 0;
#endif
// Initialize the interface implementation
// Return:
// true if it has succeeded, false if it has failed
bool GCToOSInterface::Initialize()
{
int pageSize = sysconf( _SC_PAGE_SIZE );
g_pageSizeUnixInl = uint32_t((pageSize > 0) ? pageSize : 0x1000);
// Calculate and cache the number of processors on this machine
int cpuCount = sysconf(SYSCONF_GET_NUMPROCS);
if (cpuCount == -1)
{
return false;
}
g_totalCpuCount = cpuCount;
//
// support for FlusProcessWriteBuffers
//
assert(s_flushUsingMemBarrier == 0);
if (CanFlushUsingMembarrier())
{
s_flushUsingMemBarrier = TRUE;
}
#ifndef TARGET_APPLE
else
{
assert(g_helperPage == 0);
g_helperPage = static_cast<uint8_t*>(mmap(0, OS_PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0));
if (g_helperPage == MAP_FAILED)
{
return false;
}
// Verify that the s_helperPage is really aligned to the g_SystemInfo.dwPageSize
assert((((size_t)g_helperPage) & (OS_PAGE_SIZE - 1)) == 0);
// Locking the page ensures that it stays in memory during the two mprotect
// calls in the FlushProcessWriteBuffers below. If the page was unmapped between
// those calls, they would not have the expected effect of generating IPI.
int status = mlock(g_helperPage, OS_PAGE_SIZE);
if (status != 0)
{
return false;
}
status = pthread_mutex_init(&g_flushProcessWriteBuffersMutex, NULL);
if (status != 0)
{
munlock(g_helperPage, OS_PAGE_SIZE);
return false;
}
}
#endif // !TARGET_APPLE
InitializeCGroup();
#if HAVE_SCHED_GETAFFINITY
cpu_set_t cpuSet;
int st = sched_getaffinity(getpid(), sizeof(cpu_set_t), &cpuSet);
if (st == 0)
{
for (size_t i = 0; i < CPU_SETSIZE; i++)
{
if (CPU_ISSET(i, &cpuSet))
{
g_processAffinitySet.Add(i);
}
}
}
else
{
// We should not get any of the errors that the sched_getaffinity can return since none
// of them applies for the current thread, so this is an unexpected kind of failure.
assert(false);
}
#else // HAVE_SCHED_GETAFFINITY
for (size_t i = 0; i < g_totalCpuCount; i++)
{
g_processAffinitySet.Add(i);
}
#endif // HAVE_SCHED_GETAFFINITY
NUMASupportInitialize();
#ifdef TARGET_APPLE
const char* mem_free_name = "kern.memorystatus_level";
int rc = sysctlnametomib(mem_free_name, NULL, &g_kern_memorystatus_level_mib_length);
if (rc != 0)
{
return false;
}
g_kern_memorystatus_level_mib = (int*)malloc(g_kern_memorystatus_level_mib_length * sizeof(int));
if (g_kern_memorystatus_level_mib == NULL)
{
return false;
}
rc = sysctlnametomib(mem_free_name, g_kern_memorystatus_level_mib, &g_kern_memorystatus_level_mib_length);
if (rc != 0)
{
free(g_kern_memorystatus_level_mib);
g_kern_memorystatus_level_mib = NULL;
g_kern_memorystatus_level_mib_length = 0;
return false;
}
#endif
// Get the physical memory size
#if HAVE_SYSCONF && HAVE__SC_PHYS_PAGES
long pages = sysconf(_SC_PHYS_PAGES);
if (pages == -1)
{
return false;
}
g_totalPhysicalMemSize = (uint64_t)pages * (uint64_t)g_pageSizeUnixInl;
#elif HAVE_SYSCTL
int mib[2];
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
size_t length = sizeof(INT64);
int rc = sysctl(mib, 2, &g_totalPhysicalMemSize, &length, NULL, 0);
if (rc == 0)
{
return false;
}
#else // HAVE_SYSCTL
#error "Don't know how to get total physical memory on this platform"
#endif // HAVE_SYSCTL
assert(g_totalPhysicalMemSize != 0);
return true;
}
// Shutdown the interface implementation
void GCToOSInterface::Shutdown()
{
int ret = munlock(g_helperPage, OS_PAGE_SIZE);
assert(ret == 0);
ret = pthread_mutex_destroy(&g_flushProcessWriteBuffersMutex);
assert(ret == 0);
munmap(g_helperPage, OS_PAGE_SIZE);
CleanupCGroup();
}
// Get numeric id of the current thread if possible on the
// current platform. It is intended for logging purposes only.
// Return:
// Numeric id of the current thread, as best we can retrieve it.
uint64_t GCToOSInterface::GetCurrentThreadIdForLogging()
{
return (uint64_t)minipal_get_current_thread_id();
}
// Get the process ID of the process.
uint32_t GCToOSInterface::GetCurrentProcessId()
{
return getpid();
}
// Set ideal processor for the current thread
// Parameters:
// srcProcNo - processor number the thread currently runs on
// dstProcNo - processor number the thread should be migrated to
// Return:
// true if it has succeeded, false if it has failed
bool GCToOSInterface::SetCurrentThreadIdealAffinity(uint16_t srcProcNo, uint16_t dstProcNo)
{
// There is no way to set a thread ideal processor on Unix, so do nothing.
return true;
}
// Get the number of the current processor
uint32_t GCToOSInterface::GetCurrentProcessorNumber()
{
#if HAVE_SCHED_GETCPU
int processorNumber = sched_getcpu();
assert(processorNumber != -1);
return processorNumber;
#else
assert(false); // This method is expected to be called only if CanGetCurrentProcessorNumber is true
return 0;
#endif
}
// Check if the OS supports getting current processor number
bool GCToOSInterface::CanGetCurrentProcessorNumber()
{
return HAVE_SCHED_GETCPU;
}
// Flush write buffers of processors that are executing threads of the current process
void GCToOSInterface::FlushProcessWriteBuffers()
{
if (s_flushUsingMemBarrier)
{
int status = membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED, 0);
assert(status == 0 && "Failed to flush using membarrier");
}
else if (g_helperPage != 0)
{
int status = pthread_mutex_lock(&g_flushProcessWriteBuffersMutex);
assert(status == 0 && "Failed to lock the flushProcessWriteBuffersMutex lock");
// Changing a helper memory page protection from read / write to no access
// causes the OS to issue IPI to flush TLBs on all processors. This also
// results in flushing the processor buffers.
status = mprotect(g_helperPage, OS_PAGE_SIZE, PROT_READ | PROT_WRITE);
assert(status == 0 && "Failed to change helper page protection to read / write");
// Ensure that the page is dirty before we change the protection so that
// we prevent the OS from skipping the global TLB flush.
__sync_add_and_fetch((size_t*)g_helperPage, 1);
status = mprotect(g_helperPage, OS_PAGE_SIZE, PROT_NONE);
assert(status == 0 && "Failed to change helper page protection to no access");
status = pthread_mutex_unlock(&g_flushProcessWriteBuffersMutex);
assert(status == 0 && "Failed to unlock the flushProcessWriteBuffersMutex lock");
}
#ifdef TARGET_APPLE
else
{
mach_msg_type_number_t cThreads;
thread_act_t *pThreads;
kern_return_t machret = task_threads(mach_task_self(), &pThreads, &cThreads);
CHECK_MACH("task_threads()", machret);
uintptr_t sp;
uintptr_t registerValues[128];
// Iterate through each of the threads in the list.
for (mach_msg_type_number_t i = 0; i < cThreads; i++)
{
if (__builtin_available (macOS 10.14, iOS 12, tvOS 9, *))
{
// Request the threads pointer values to force the thread to emit a memory barrier
size_t registers = 128;
machret = thread_get_register_pointer_values(pThreads[i], &sp, ®isters, registerValues);
}
else
{
// fallback implementation for older OS versions
#if defined(HOST_AMD64)
x86_thread_state64_t threadState;
mach_msg_type_number_t count = x86_THREAD_STATE64_COUNT;
machret = thread_get_state(pThreads[i], x86_THREAD_STATE64, (thread_state_t)&threadState, &count);
#elif defined(HOST_ARM64)
arm_thread_state64_t threadState;
mach_msg_type_number_t count = ARM_THREAD_STATE64_COUNT;
machret = thread_get_state(pThreads[i], ARM_THREAD_STATE64, (thread_state_t)&threadState, &count);
#else
#error Unexpected architecture
#endif
}
if (machret == KERN_INSUFFICIENT_BUFFER_SIZE)
{
CHECK_MACH("thread_get_register_pointer_values()", machret);
}
machret = mach_port_deallocate(mach_task_self(), pThreads[i]);
CHECK_MACH("mach_port_deallocate()", machret);
}
// Deallocate the thread list now we're done with it.
machret = vm_deallocate(mach_task_self(), (vm_address_t)pThreads, cThreads * sizeof(thread_act_t));
CHECK_MACH("vm_deallocate()", machret);
}
#endif // TARGET_APPLE
}
// Break into a debugger. Uses a compiler intrinsic if one is available,
// otherwise raises a SIGTRAP.
void GCToOSInterface::DebugBreak()
{
#if __has_builtin(__builtin_debugtrap)
__builtin_debugtrap();
#else
raise(SIGTRAP);
#endif
}
// Causes the calling thread to sleep for the specified number of milliseconds
// Parameters:
// sleepMSec - time to sleep before switching to another thread
void GCToOSInterface::Sleep(uint32_t sleepMSec)
{
if (sleepMSec == 0)
{
return;
}
timespec requested;
requested.tv_sec = sleepMSec / tccSecondsToMilliSeconds;
requested.tv_nsec = (sleepMSec - requested.tv_sec * tccSecondsToMilliSeconds) * tccMilliSecondsToNanoSeconds;
timespec remaining;
while (nanosleep(&requested, &remaining) == EINTR)
{
requested = remaining;
}
}
// Causes the calling thread to yield execution to another thread that is ready to run on the current processor.
// Parameters:
// switchCount - number of times the YieldThread was called in a loop
void GCToOSInterface::YieldThread(uint32_t switchCount)
{
int ret = sched_yield();
// sched_yield never fails on Linux, unclear about other OSes
assert(ret == 0);
}
// Reserve virtual memory range.
// Parameters:
// size - size of the virtual memory range
// alignment - requested memory alignment, 0 means no specific alignment requested
// flags - flags to control special settings like write watching
// committing - memory will be comitted
// Return:
// Starting virtual address of the reserved range
static void* VirtualReserveInner(size_t size, size_t alignment, uint32_t flags, uint32_t hugePagesFlag, bool committing)
{
assert(!(flags & VirtualReserveFlags::WriteWatch) && "WriteWatch not supported on Unix");
if (alignment < OS_PAGE_SIZE)
{
alignment = OS_PAGE_SIZE;
}
size_t alignedSize = size + (alignment - OS_PAGE_SIZE);
int mmapFlags = MAP_ANON | MAP_PRIVATE | hugePagesFlag;
#ifdef __HAIKU__
mmapFlags |= MAP_NORESERVE;
#endif
void * pRetVal = mmap(nullptr, alignedSize, PROT_NONE, mmapFlags, -1, 0);
if (pRetVal != MAP_FAILED)
{
void * pAlignedRetVal = (void *)(((size_t)pRetVal + (alignment - 1)) & ~(alignment - 1));
size_t startPadding = (size_t)pAlignedRetVal - (size_t)pRetVal;
if (startPadding != 0)
{
int ret = munmap(pRetVal, startPadding);
assert(ret == 0);
}
size_t endPadding = alignedSize - (startPadding + size);
if (endPadding != 0)
{
int ret = munmap((void *)((size_t)pAlignedRetVal + size), endPadding);
assert(ret == 0);
}
pRetVal = pAlignedRetVal;
#ifdef MADV_DONTDUMP
// Do not include reserved uncommitted memory in coredump.
if (!committing)
{
madvise(pRetVal, size, MADV_DONTDUMP);
}
#endif
return pRetVal;
}
return NULL; // return NULL if mmap failed
}
// Reserve virtual memory range.
// Parameters:
// size - size of the virtual memory range
// alignment - requested memory alignment, 0 means no specific alignment requested
// flags - flags to control special settings like write watching
// node - the NUMA node to reserve memory on
// Return:
// Starting virtual address of the reserved range
void* GCToOSInterface::VirtualReserve(size_t size, size_t alignment, uint32_t flags, uint16_t node)
{
return VirtualReserveInner(size, alignment, flags, 0, /* committing */ false);
}
// Release virtual memory range previously reserved using VirtualReserve
// Parameters:
// address - starting virtual address
// size - size of the virtual memory range
// Return:
// true if it has succeeded, false if it has failed
bool GCToOSInterface::VirtualRelease(void* address, size_t size)
{
int ret = munmap(address, size);
return (ret == 0);
}
// Commit virtual memory range. It must be part of a range reserved using VirtualReserve.
// Parameters:
// address - starting virtual address
// size - size of the virtual memory range
// newMemory - memory has been newly allocated
// Return:
// true if it has succeeded, false if it has failed
static bool VirtualCommitInner(void* address, size_t size, uint16_t node, bool newMemory)
{
bool success = mprotect(address, size, PROT_WRITE | PROT_READ) == 0;
#ifdef MADV_DODUMP
if (success && !newMemory)
{
// Include committed memory in coredump. New memory is included by default.
madvise(address, size, MADV_DODUMP);
}
#endif
#ifdef TARGET_LINUX
if (success && g_numaAvailable && (node != NUMA_NODE_UNDEFINED))
{
if ((int)node <= g_highestNumaNode)
{
int usedNodeMaskBits = g_highestNumaNode + 1;
int nodeMaskLength = usedNodeMaskBits + sizeof(unsigned long) - 1;
unsigned long* nodeMask = (unsigned long*)alloca(nodeMaskLength);
memset(nodeMask, 0, nodeMaskLength);
int index = node / sizeof(unsigned long);
nodeMask[index] = ((unsigned long)1) << (node & (sizeof(unsigned long) - 1));
int st = BindMemoryPolicy(address, size, nodeMask, usedNodeMaskBits);
assert(st == 0);
// If the mbind fails, we still return the allocated memory since the node is just a hint
}
}
#endif // TARGET_LINUX
return success;
}
// Commit virtual memory range. It must be part of a range reserved using VirtualReserve.
// Parameters:
// address - starting virtual address
// size - size of the virtual memory range
// Return:
// true if it has succeeded, false if it has failed
bool GCToOSInterface::VirtualCommit(void* address, size_t size, uint16_t node)
{
return VirtualCommitInner(address, size, node, /* newMemory */ false);
}
// Commit virtual memory range.
// Parameters:
// size - size of the virtual memory range
// Return:
// Starting virtual address of the committed range
void* GCToOSInterface::VirtualReserveAndCommitLargePages(size_t size, uint16_t node)
{
#if HAVE_MAP_HUGETLB
uint32_t largePagesFlag = MAP_HUGETLB;
#elif HAVE_VM_FLAGS_SUPERPAGE_SIZE_ANY
uint32_t largePagesFlag = VM_FLAGS_SUPERPAGE_SIZE_ANY;
#else
uint32_t largePagesFlag = 0;
#endif
void* pRetVal = VirtualReserveInner(size, OS_PAGE_SIZE, 0, largePagesFlag, true);
if (VirtualCommitInner(pRetVal, size, node, /* newMemory */ true))
{
return pRetVal;
}
return nullptr;
}
// Decomit virtual memory range.
// Parameters:
// address - starting virtual address
// size - size of the virtual memory range
// Return:
// true if it has succeeded, false if it has failed
bool GCToOSInterface::VirtualDecommit(void* address, size_t size)
{
// TODO: This can fail, however the GC does not handle the failure gracefully
// Explicitly calling mmap instead of mprotect here makes it
// that much more clear to the operating system that we no
// longer need these pages. Also, GC depends on re-committed pages to
// be zeroed-out.
int mmapFlags = MAP_FIXED | MAP_ANON | MAP_PRIVATE;
#ifdef TARGET_HAIKU
mmapFlags |= MAP_NORESERVE;
#endif
bool bRetVal = mmap(address, size, PROT_NONE, mmapFlags, -1, 0) != MAP_FAILED;
#ifdef MADV_DONTDUMP
if (bRetVal)
{
// Do not include freed memory in coredump.
madvise(address, size, MADV_DONTDUMP);
}
#endif
return bRetVal;
}
// Reset virtual memory range. Indicates that data in the memory range specified by address and size is no
// longer of interest, but it should not be decommitted.
// Parameters:
// address - starting virtual address
// size - size of the virtual memory range
// unlock - true if the memory range should also be unlocked
// Return:
// true if it has succeeded, false if it has failed
bool GCToOSInterface::VirtualReset(void * address, size_t size, bool unlock)
{
int st = EINVAL;
#if defined(MADV_DONTDUMP) || defined(HAVE_MADV_FREE)
int madviseFlags = 0;
#ifdef MADV_DONTDUMP
// Do not include reset memory in coredump.
madviseFlags |= MADV_DONTDUMP;
#endif
#ifdef HAVE_MADV_FREE
// Tell the kernel that the application doesn't need the pages in the range.
// Freeing the pages can be delayed until a memory pressure occurs.
madviseFlags |= MADV_FREE;
#endif
st = madvise(address, size, madviseFlags);
#endif //defined(MADV_DONTDUMP) || defined(HAVE_MADV_FREE)
#if defined(HAVE_POSIX_MADVISE) && !defined(MADV_DONTDUMP)
// DONTNEED is the nearest posix equivalent of FREE.
// Prefer FREE as, since glibc2.6 DONTNEED is a nop.
st = posix_madvise(address, size, POSIX_MADV_DONTNEED);
#endif //defined(HAVE_POSIX_MADVISE) && !defined(MADV_DONTDUMP)
return (st == 0);
}
// Check if the OS supports write watching
bool GCToOSInterface::SupportsWriteWatch()
{
return false;
}
// Reset the write tracking state for the specified virtual memory range.
// Parameters:
// address - starting virtual address
// size - size of the virtual memory range
void GCToOSInterface::ResetWriteWatch(void* address, size_t size)
{
assert(!"should never call ResetWriteWatch on Unix");
}
// Retrieve addresses of the pages that are written to in a region of virtual memory
// Parameters:
// resetState - true indicates to reset the write tracking state
// address - starting virtual address
// size - size of the virtual memory range
// pageAddresses - buffer that receives an array of page addresses in the memory region
// pageAddressesCount - on input, size of the lpAddresses array, in array elements
// on output, the number of page addresses that are returned in the array.
// Return:
// true if it has succeeded, false if it has failed
bool GCToOSInterface::GetWriteWatch(bool resetState, void* address, size_t size, void** pageAddresses, uintptr_t* pageAddressesCount)
{
assert(!"should never call GetWriteWatch on Unix");
return false;
}
bool ReadMemoryValueFromFile(const char* filename, uint64_t* val)
{
bool result = false;
char* line = nullptr;
size_t lineLen = 0;
char* endptr = nullptr;
uint64_t num = 0, l, multiplier;
FILE* file = nullptr;
if (val == nullptr)
goto done;
file = fopen(filename, "r");
if (file == nullptr)
goto done;
if (getline(&line, &lineLen, file) == -1)
goto done;
errno = 0;
num = strtoull(line, &endptr, 0);
if (line == endptr || errno != 0)
goto done;
multiplier = 1;
switch (*endptr)
{
case 'g':
case 'G': multiplier = 1024;
FALLTHROUGH;
case 'm':
case 'M': multiplier = multiplier * 1024;
FALLTHROUGH;
case 'k':
case 'K': multiplier = multiplier * 1024;
}
*val = num * multiplier;
result = true;
if (*val / multiplier != num)
result = false;
done:
if (file)
fclose(file);
free(line);
return result;
}
static void GetLogicalProcessorCacheSizeFromSysConf(size_t* cacheLevel, size_t* cacheSize)
{
assert (cacheLevel != nullptr);
assert (cacheSize != nullptr);
#if defined(_SC_LEVEL1_DCACHE_SIZE) || defined(_SC_LEVEL2_CACHE_SIZE) || defined(_SC_LEVEL3_CACHE_SIZE) || defined(_SC_LEVEL4_CACHE_SIZE)
const int cacheLevelNames[] =
{
_SC_LEVEL1_DCACHE_SIZE,
_SC_LEVEL2_CACHE_SIZE,
_SC_LEVEL3_CACHE_SIZE,
_SC_LEVEL4_CACHE_SIZE,
};
for (int i = ARRAY_SIZE(cacheLevelNames) - 1; i >= 0; i--)
{
long size = sysconf(cacheLevelNames[i]);
if (size > 0)
{
*cacheSize = (size_t)size;
*cacheLevel = i + 1;
break;
}
}
#endif
}
static void GetLogicalProcessorCacheSizeFromSysFs(size_t* cacheLevel, size_t* cacheSize)
{
assert (cacheLevel != nullptr);
assert (cacheSize != nullptr);
#if defined(TARGET_LINUX) && !defined(HOST_ARM) && !defined(HOST_X86)
//
// Retrieve cachesize via sysfs by reading the file /sys/devices/system/cpu/cpu0/cache/index{LastLevelCache}/size
// for the platform. Currently musl and arm64 should be only cases to use
// this method to determine cache size.
//
size_t level;
char path_to_size_file[] = "/sys/devices/system/cpu/cpu0/cache/index-/size";
char path_to_level_file[] = "/sys/devices/system/cpu/cpu0/cache/index-/level";
int index = 40;
assert(path_to_size_file[index] == '-');
assert(path_to_level_file[index] == '-');
for (int i = 0; i < 5; i++)
{
path_to_size_file[index] = (char)(48 + i);
uint64_t cache_size_from_sys_file = 0;
if (ReadMemoryValueFromFile(path_to_size_file, &cache_size_from_sys_file))
{
*cacheSize = std::max(*cacheSize, (size_t)cache_size_from_sys_file);
path_to_level_file[index] = (char)(48 + i);
if (ReadMemoryValueFromFile(path_to_level_file, &level))
{
*cacheLevel = level;
}
}
}
#endif
}
static void GetLogicalProcessorCacheSizeFromHeuristic(size_t* cacheLevel, size_t* cacheSize)
{
assert (cacheLevel != nullptr);
assert (cacheSize != nullptr);
#if (defined(TARGET_LINUX) && !defined(TARGET_APPLE))
{
// Use the following heuristics at best depending on the CPU count
// 1 ~ 4 : 4 MB
// 5 ~ 16 : 8 MB
// 17 ~ 64 : 16 MB
// 65+ : 32 MB
DWORD logicalCPUs = g_processAffinitySet.Count();
if (logicalCPUs < 5)
{
*cacheSize = 4;
}
else if (logicalCPUs < 17)
{
*cacheSize = 8;
}
else if (logicalCPUs < 65)
{
*cacheSize = 16;
}
else
{
*cacheSize = 32;
}
*cacheSize *= (1024 * 1024);
}
#endif
}
static size_t GetLogicalProcessorCacheSizeFromOS()
{
size_t cacheLevel = 0;
size_t cacheSize = 0;
if (GCConfig::GetGCCacheSizeFromSysConf())
{
GetLogicalProcessorCacheSizeFromSysConf(&cacheLevel, &cacheSize);
}
if (cacheSize == 0)
{
GetLogicalProcessorCacheSizeFromSysFs(&cacheLevel, &cacheSize);
if (cacheSize == 0)
{
GetLogicalProcessorCacheSizeFromHeuristic(&cacheLevel, &cacheSize);
}
}
#if HAVE_SYSCTLBYNAME
if (cacheSize == 0)
{
int64_t cacheSizeFromSysctl = 0;
size_t sz = sizeof(cacheSizeFromSysctl);
const bool success = false
// macOS: Since macOS 12.0, Apple added ".perflevelX." to determinate cache sizes for efficiency
// and performance cores separately. "perflevel0" stands for "performance"
|| sysctlbyname("hw.perflevel0.l3cachesize", &cacheSizeFromSysctl, &sz, nullptr, 0) == 0
|| sysctlbyname("hw.perflevel0.l2cachesize", &cacheSizeFromSysctl, &sz, nullptr, 0) == 0
// macOS: these report cache sizes for efficiency cores only:
|| sysctlbyname("hw.l3cachesize", &cacheSizeFromSysctl, &sz, nullptr, 0) == 0
|| sysctlbyname("hw.l2cachesize", &cacheSizeFromSysctl, &sz, nullptr, 0) == 0