-
Notifications
You must be signed in to change notification settings - Fork 392
/
omrvmem.c
1903 lines (1681 loc) · 64.3 KB
/
omrvmem.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 1991, 2020 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
/**
* @file
* @ingroup Port
* @brief Virtual memory
*/
/* for syscall */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "omrport.h"
#include "omrportpriv.h"
#include "omrportpg.h"
#include "ut_omrport.h"
#include "omrportasserts.h"
#include "omrvmem.h"
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <tpf/tpfapi.h>
#include <tpf/i_shm.h>
#include <tpf/c_cinfc.h>
#include <tpf/c_eb0eb.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#if defined(OMR_PORT_NUMA_SUPPORT)
#include <numaif.h>
#endif /* OMR_PORT_NUMA_SUPPORT */
#if !defined(MPOL_F_MEMS_ALLOWED)
#define MPOL_F_MEMS_ALLOWED 4
#endif
#include <sys/shm.h>
#if !defined(MAP_FAILED)
#define MAP_FAILED -1
#endif
#define INVALID_KEY -1
#if 0
#define OMRVMEM_DEBUG
#endif
#define VMEM_MEMINFO_SIZE_MAX 2048
#define VMEM_PROC_MEMINFO_FNAME "/proc/meminfo"
#define VMEM_PROC_MAPS_FNAME "/proc/self/maps"
#define FOUR_K_MINUS_1 (4*1024-1)
#define GET_4K_ALIGNED_PTR(alignedPtr, ptr) do { \
alignedPtr = ( ((uintptr_t)ptr) + FOUR_K_MINUS_1 + sizeof(uintptr_t) ) & ~0xfff; \
*(uintptr_t *)(alignedPtr-sizeof(uintptr_t)) = (uintptr_t)ptr; \
} while(0);
#define GET_BASE_PTR_FROM_ALIGNED_PTR(alignedPtr) ( *(void **)((uintptr_t)alignedPtr - sizeof(uintptr_t)) )
#define GET_4K_ALIGNED_ALLOCATION_SIZE(byteAmount) (byteAmount + FOUR_K_MINUS_1 + sizeof(uintptr_t))
typedef struct vmem_hugepage_info_t {
uintptr_t enabled; /*!< boolean enabling j9 large page support */
uintptr_t pages_total; /*!< total number of pages maintained by the kernel */
uintptr_t pages_free; /*!< number of free pages that may be allocated by us */
uintptr_t page_size; /*!< page size in bytes */
} vmem_hugepage_info_t;
typedef void* ADDRESS;
typedef struct AddressRange {
ADDRESS start;
ADDRESS end;
} AddressRange;
void addressRange_Init(AddressRange* range, ADDRESS start, ADDRESS end);
BOOLEAN addressRange_Intersect(AddressRange* a, AddressRange* b,
AddressRange* result);
BOOLEAN addressRange_IsValid(AddressRange* range);
uintptr_t addressRange_Width(AddressRange* range);
ADDRESS findAvailableMemoryBlockNoMalloc(struct OMRPortLibrary *portLibrary,
ADDRESS start, ADDRESS end, uintptr_t byteAmount, BOOLEAN reverse);
static void * getMemoryInRangeForLargePages(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier, key_t addressKey,
OMRMemCategory * category, uintptr_t byteAmount, void *startAddress,
void *endAddress, uintptr_t alignmentInBytes, uintptr_t vmemOptions,
uintptr_t pageSize, uintptr_t mode);
static void * getMemoryInRangeForDefaultPages(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier, OMRMemCategory * category,
uintptr_t byteAmount, void *startAddress, void *endAddress,
uintptr_t alignmentInBytes, uintptr_t vmemOptions, uintptr_t mode);
static void * allocateMemoryForLargePages(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier, void *currentAddress,
key_t addressKey, OMRMemCategory* category, uintptr_t byteAmount,
uintptr_t pageSize, uintptr_t mode);
static BOOLEAN isStrictAndOutOfRange(void *memoryPointer, void *startAddress,
void *endAddress, uintptr_t vmemOptions);
static BOOLEAN rangeIsValid(struct J9PortVmemIdentifier *identifier,
void *address, uintptr_t byteAmount);
static void *reserveLargePages(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier, OMRMemCategory * category,
uintptr_t byteAmount, void *startAddress, void *endAddress, uintptr_t pageSize,
uintptr_t alignmentInBytes, uintptr_t vmemOptions, uintptr_t mode);
void *default_pageSize_reserve_memory(struct OMRPortLibrary *portLibrary,
void *address, uintptr_t byteAmount,
struct J9PortVmemIdentifier *identifier, uintptr_t mode, uintptr_t pageSize,
OMRMemCategory * category);
static void port_numa_interleave_memory(struct OMRPortLibrary *portLibrary,
void *start, uintptr_t size);
void update_vmemIdentifier(J9PortVmemIdentifier *identifier, void *address,
void *handle, uintptr_t byteAmount, uintptr_t mode, uintptr_t pageSize,
uintptr_t pageFlags, uintptr_t allocator, OMRMemCategory * category);
static uintptr_t get_hugepages_info(struct OMRPortLibrary *portLibrary,
vmem_hugepage_info_t *page_info);
int get_protectionBits(uintptr_t mode);
#if defined(OMR_PORT_NUMA_SUPPORT)
/*
* glibc doesn't include mbind yet. It is in libnuma, but we can't rely on that being available on all systems.
* We define our own helper to make the syscall so that we can use it without relying on external libraries.
*/
static long
do_mbind(void *start, unsigned long len, int policy, const unsigned long *nodemask, unsigned long maxnode, unsigned flags)
{
return (long)syscall(SYS_mbind, start, len, policy, nodemask, maxnode, flags);
}
/**
* glibc doesn't include get_mempolicy. It is in libnuma, but we can't rely on that being available on all systems.
* We define our own helper to make the syscall so that we can use it without relying on external libraries.
*
* For details, see the man page for get_mempolicy(2).
* Below is an incomplete summary.
*
* do_get_mempolicy()
*
* gets the NUMA policy of the calling process or virtual memory address
*
* @param int *policy [out] returns the policy, or next interleave node
* @param unsigned long *nmask [out] the node bit mask associated with the policy
* @param unsigned long maxnode [in] length of nmask array
* @param unsigned long addr [in] virtual memory address of requested policy info
* @param unsigned long flags [in] controls get_mempolicy behaviour
*
* @return 0 on success, -1 on error returned via errno.
* errno==EFAULT: Part of all of memory specified by nmask inaccessible
* errno==EINVAL: Invalid arguments (many invalid combinations).
*/
static long
do_get_mempolicy(int *policy, unsigned long *nmask, unsigned long maxnode, unsigned long addr, unsigned long flags)
{
return (long)syscall(SYS_get_mempolicy, policy, nmask, maxnode, addr, flags);
}
/*
* Read the /sys/devices/system/node/ directory, if it exists, to find out the indices of
* all NUMA nodes on this system. Store them into a bitmask in the port platform globals.
*/
static intptr_t
initializeNumaGlobals(struct OMRPortLibrary *portLibrary)
{
uintptr_t result = 0;
uintptr_t maxNodes = sizeof(J9PortNodeMask) * 8;
uintptr_t nodeCount = 0;
int schedReturnCode = 0;
int mempolicyReturnCode = 0;
int useAllNodes = 0;
PPG_numaSyscallNotAllowed = FALSE;
memset(&PPG_numa_available_node_mask, 0, sizeof(J9PortNodeMask));
PPG_numa_max_node_bits = 0;
/* populate the processAffinity with the process's incoming affinity - this will allow us to honour options like "numactl --cpubind=" */
CPU_ZERO(&PPG_process_affinity);
schedReturnCode = sched_getaffinity(0, sizeof(PPG_process_affinity), &PPG_process_affinity);
/* look-up the process's default NUMA policy as applied to the set of nodes (the policy is usually "0" and applies to no nodes) */
PPG_numa_policy_mode = -1;
memset(&PPG_numa_mempolicy_node_mask, 0, sizeof(J9PortNodeMask));
mempolicyReturnCode = do_get_mempolicy(&PPG_numa_policy_mode, PPG_numa_mempolicy_node_mask.mask, maxNodes, (unsigned long)NULL, 0);
if ((0 != mempolicyReturnCode) && (EPERM == errno)) {
PPG_numaSyscallNotAllowed = TRUE;
}
if (0 == mempolicyReturnCode) {
long anySet = 0;
int arrayLen = sizeof(PPG_numa_mempolicy_node_mask.mask) / sizeof(PPG_numa_mempolicy_node_mask.mask[0]);
int i = 0;
/* Check if any bits are set in PPG_numa_mempolicy_node_mask. If no nodes are specified in either the system default or process default
* policies then the mask will be all 0's which (if used later) would indicate no nodes are available for virtual memory allocation. */
for (i = 0; ((0 == anySet) && (i < arrayLen)); i++) {
anySet |= PPG_numa_mempolicy_node_mask.mask[i];
}
if (0 == anySet) {
/* If an empty set is returned, e.g. if numactl is not used, ask again with MPOL_F_MEMS_ALLOWED to get the correct node mask. */
mempolicyReturnCode = do_get_mempolicy((int *) NULL, PPG_numa_mempolicy_node_mask.mask, maxNodes, (unsigned long)NULL, MPOL_F_MEMS_ALLOWED);
/* MPOL_F_MEMS_ALLOWED is unavailable on older systems. If it fails, we use PPG_numa_available_node_mask instead. */
if (0 != mempolicyReturnCode) {
Trc_PRT_vmem_omrvmem_initializeNumaGlobals_get_allowed_mems_failure(errno);
mempolicyReturnCode = 0;
useAllNodes = 1;
}
}
} else {
Trc_PRT_vmem_omrvmem_initializeNumaGlobals_get_mempolicy_failure(errno);
}
/* Proceed if we could successfully look up the default affinity.
* We proceed to get node count even if `getmempolicy` fails due to security restrictions.
*/
if ((0 == schedReturnCode) && ((0 == mempolicyReturnCode) || (PPG_numaSyscallNotAllowed))) {
DIR* nodes = opendir("/sys/devices/system/node/");
if (NULL != nodes) {
struct dirent *node = readdir(nodes);
while (NULL != node) {
unsigned long nodeIndex = 0;
if (1 == sscanf(node->d_name, "node%lu", &nodeIndex)) {
if (nodeIndex < maxNodes) {
unsigned long wordIndex = nodeIndex / sizeof(PPG_numa_available_node_mask.mask[0]);
unsigned long bit = 1 << (nodeIndex % sizeof(PPG_numa_available_node_mask.mask[0]));
PPG_numa_available_node_mask.mask[wordIndex] |= bit;
/**
* PPG_numa_max_node_bits represents the maximum number of nodes.
* Node indexes start from 0, therefore PPG_numa_max_node_bits is max node index number plus 1.
* For instance, if there are following nodes:node0, node5, node8,
* then PPG_numa_max_node_bits is equal to 8 + 1 = 9
*/
if (nodeIndex >= PPG_numa_max_node_bits) {
PPG_numa_max_node_bits = nodeIndex + 1;
}
nodeCount += 1;
}
}
node = readdir(nodes);
}
closedir(nodes);
}
}
/* if there aren't at least two nodes then there's nothing we can do with NUMA */
if (nodeCount < 2) {
result = -1;
} else if (1 == useAllNodes) {
/* Failed to get memory policy allowed nodes, use all available nodes instead. */
memcpy(PPG_numa_mempolicy_node_mask.mask, PPG_numa_available_node_mask.mask, sizeof(PPG_numa_available_node_mask.mask));
}
return result;
}
#endif /* defined(OMR_PORT_NUMA_SUPPORT) */
/*
* Init the range with values
*
* @param AddressRange* range [out] Returns the range object
* @param void* start [in] The start address of the range
* @param void* end [in] The end address of the range
*/
void
addressRange_Init(AddressRange* range, ADDRESS start, ADDRESS end)
{
range->start = start;
range->end = end;
}
/*
* Calculate out the intersection of 2 ranges
*
* @param AddressRange* a [in] a range object
* @param AddressRange* b [in] another range object
* @param AddressRange* result [out] the intersection of the above 2 ranges
*
* Returns TRUE if they have intersection.
*/
BOOLEAN
addressRange_Intersect(AddressRange* a, AddressRange* b, AddressRange* result)
{
result->start = a->start > b->start ? a->start : b->start;
result->end = a->end < b->end ? a->end : b->end;
return addressRange_IsValid(result);
}
/*
* Calculate if a range is valid.
* A valid range should have start < its end
*
* @param AddressRange* range [in] a range object
*
* Returns TRUE if range's start < end.
*/
BOOLEAN
addressRange_IsValid(AddressRange* range)
{
return (range->end > range->start) ? TRUE : FALSE;
}
/*
* Calculate out the with of a range
*
* @param AddressRange* range [in] a range object
*
* Returns the width of the range.
* Caller should make sure the input parameter 'range' is valid,
* otherwise, unexpected value may be returned.
*/
uintptr_t
addressRange_Width(AddressRange* range)
{
Assert_PRT_true(TRUE == addressRange_IsValid(range));
return range->end - range->start;
}
/*
* Find a memory block using maps information from file /proc/self/maps
* In order to avoid file context corruption, this method implemented without memory operation such as malloc/free
*
*
* @param OMRPortLibrary *portLibrary [in] The portLibrary object
* @param ADDRESS start [in] The start address allowed, see also @param end
* @param ADDRESS end [in] The end address allowed, see also @param start.
* The returned memory address should be within the range defined by the @param start and the @param end.
* @param uintptr_t byteAmount [in] The block size required.
* @param BOOLEAN reverse [in] Returns the first available memory block when this param equals FALSE, returns the last available memory block when this param equals TRUE
*
* returns the address available.
*/
ADDRESS
findAvailableMemoryBlockNoMalloc(struct OMRPortLibrary *portLibrary,
ADDRESS start, ADDRESS end, uintptr_t byteAmount, BOOLEAN reverse)
{
BOOLEAN dataCorrupt = FALSE;
BOOLEAN matchFound = FALSE;
/*
* The caller provides start and end addresses that constrain a non-null
* address that can be returned by this function. Internally, however,
* this function operates on ranges which are inclusive of the space
* requested by the caller: the allowed range must be initialized taking
* this difference into account by adding the requested block size to the
* end address.
*/
AddressRange allowedRange;
addressRange_Init(&allowedRange, start, end + byteAmount);
AddressRange lastAvailableRange;
addressRange_Init(&lastAvailableRange, NULL, NULL);
int fd = -1;
if ((fd = omrfile_open(portLibrary, VMEM_PROC_MAPS_FNAME, EsOpenRead, 0))
!= -1) {
char readBuf[1024];
intptr_t bytesRead = 0;
/*
* Please refer to the file format of /proc/self/maps.
* 'lineBuf' represent for a line in the file.
*
* Don't change the length of 'lineBuf' easily.
* The minimal length should be 34 on 64bit machine,
* as 34 is the minimal safe length to represent for a 64bit address range.
* For example: "1234567890120000-1234567890123000" (NOTE: there is a '\0' in the end)
*/
char lineBuf[100];
intptr_t lineCursor = 0;
AddressRange lastMmapRange;
addressRange_Init(&lastMmapRange, NULL, NULL);
while (TRUE) { /* read-file-loop */
BOOLEAN lineEnd = FALSE;
BOOLEAN gotEOF = FALSE;
bytesRead = omrfile_read(portLibrary, fd, readBuf, sizeof(readBuf));
if (-1 == bytesRead) {
break;
}
intptr_t readCursor = 0;
do { /* proc-chars-loop */
char ch = '\0';
/*
* Scan out a line from 'readBuf', and save the line data to 'lineBuf'.
* 1. End the line with '\0'.
* 2. Set lineEnd = TRUE when '\n' found.
*/
if (0 == bytesRead) {
gotEOF = TRUE;
ch = '\n';
} else {
ch = readBuf[readCursor];
readCursor++;
}
/*
* We only save the beginning chars for each line, because:
* 1. we only need the memory range data, it always at the beginning of the lines.
* 2. the size of the 'lineBuf' is fixed, we skip the extra chars in order to avoid out-of-bound-writting
*/
if (lineCursor < sizeof(lineBuf)) {
lineBuf[lineCursor] = ch;
lineCursor++;
}
if ('\n' == ch) {
lineEnd = TRUE;
lineBuf[lineCursor - 1] = '\0';
}
if (TRUE == lineEnd) { /* proc-line-data */
AddressRange currentMmapRange;
addressRange_Init(¤tMmapRange, NULL, NULL);
Assert_PRT_true(lineBuf[lineCursor - 1] == '\0');
if (TRUE == gotEOF) {
/* We reach the end of the file. */
addressRange_Init(¤tMmapRange,
(ADDRESS) (uintptr_t) (-1), (ADDRESS) (uintptr_t) (-1));
} else {
char* next = NULL;
uintptr_t start = 0;
uintptr_t end = 0;
start = (uintptr_t) strtoull(lineBuf, &next, 16);
if ((ULLONG_MAX == start) && (ERANGE == errno)) {
dataCorrupt = TRUE;
break;
}
/* skip the '-' */
next++;
if (next >= (lineBuf + lineCursor - 1)) {
dataCorrupt = TRUE;
break;
}
end = (uintptr_t) strtoull(next, &next, 16);
if ((ULLONG_MAX == end) && (ERANGE == errno)) {
dataCorrupt = TRUE;
break;
}
currentMmapRange.start = (ADDRESS) start;
currentMmapRange.end = (ADDRESS) end;
lineCursor = 0;
if ((currentMmapRange.start >= currentMmapRange.end)
|| (currentMmapRange.start < lastMmapRange.end)) {
dataCorrupt = TRUE;
break;
}
}
if (currentMmapRange.start == lastMmapRange.end) {
lastMmapRange.end = currentMmapRange.end;
} else {
/* free block found */
AddressRange freeRange;
AddressRange intersectAvailable;
BOOLEAN haveIntersect = FALSE;
addressRange_Init(&freeRange, lastMmapRange.end,
currentMmapRange.start);
memcpy(&lastMmapRange, ¤tMmapRange,
sizeof(AddressRange));
/* check if the free block has intersection with the allowed range */
haveIntersect = addressRange_Intersect(&allowedRange,
&freeRange, &intersectAvailable);
if (TRUE == haveIntersect) {
uintptr_t intersectSize = addressRange_Width(
&intersectAvailable);
if (intersectSize >= byteAmount) {
memcpy(&lastAvailableRange, &intersectAvailable,
sizeof(AddressRange));
matchFound = TRUE;
if (FALSE == reverse) {
break;
}
}
}
}
lineEnd = FALSE;
} /* end proc-line-data */
} while (readCursor < bytesRead); /* end proc-chars-loop */
if ((FALSE == reverse) && (TRUE == matchFound)) {
break;
}
if (TRUE == (gotEOF | dataCorrupt)) {
break;
}
} /* end read-file-loop */
omrfile_close(portLibrary, fd);
} else {
dataCorrupt = TRUE;
}
if (TRUE == dataCorrupt) {
return NULL;
}
if (TRUE == matchFound) {
if (FALSE == reverse) {
return lastAvailableRange.start;
} else {
return (lastAvailableRange.end - byteAmount);
}
} else {
return NULL;
}
}
void
omrvmem_shutdown(struct OMRPortLibrary *portLibrary)
{
#if defined(OMR_PORT_NUMA_SUPPORT)
if (NULL != portLibrary->portGlobals) {
PPG_numa_platform_supports_numa = 0;
}
#endif
}
int32_t
omrvmem_startup(struct OMRPortLibrary *portLibrary)
{
vmem_hugepage_info_t vmem_page_info;
/* clear page info data, this has the effect of starting off in a standard state */
memset(&vmem_page_info, 0x00, sizeof(vmem_hugepage_info_t));
get_hugepages_info(portLibrary, &vmem_page_info);
/* 0 terminate the table */
memset(PPG_vmem_pageSize, 0, OMRPORT_VMEM_PAGESIZE_COUNT * sizeof(uintptr_t));
memset(PPG_vmem_pageFlags, 0, OMRPORT_VMEM_PAGESIZE_COUNT * sizeof(uintptr_t));
/* First the default page size */
PPG_vmem_pageSize[0] = 4096;
PPG_vmem_pageFlags[0] = OMRPORT_VMEM_PAGE_FLAG_NOT_USED;
/* Now the large pages */
if (vmem_page_info.enabled) {
PPG_vmem_pageSize[1] = vmem_page_info.page_size;
PPG_vmem_pageFlags[1] = OMRPORT_VMEM_PAGE_FLAG_NOT_USED;
}
#if defined(OMR_PORT_NUMA_SUPPORT)
if (0 == initializeNumaGlobals(portLibrary)) {
PPG_numa_platform_supports_numa = 1;
} else {
PPG_numa_platform_supports_numa = 0;
}
#endif
/* set default value to advise OS about vmem that is no longer needed */
portLibrary->portGlobals->vmemAdviseOSonFree = 1;
/* set default value to advise OS about vmem to consider for Transparent HugePage (Only for Linux) */
portLibrary->portGlobals->vmemEnableMadvise = 0;
return 0;
}
void *
omrvmem_commit_memory(struct OMRPortLibrary *portLibrary, void *address,
uintptr_t byteAmount, struct J9PortVmemIdentifier *identifier)
{
void *rc = NULL;
Trc_PRT_vmem_omrvmem_commit_memory_Entry(address, byteAmount);
if (rangeIsValid(identifier, address, byteAmount)) {
ASSERT_VALUE_IS_PAGE_SIZE_ALIGNED(address, identifier->pageSize);ASSERT_VALUE_IS_PAGE_SIZE_ALIGNED(
byteAmount, identifier->pageSize);
/* Default page size */
if (PPG_vmem_pageSize[0] == identifier->pageSize
|| 0 != (identifier->mode & OMRPORT_VMEM_MEMORY_MODE_EXECUTE)) {
rc = address;
}
} else {
Trc_PRT_vmem_omrvmem_commit_memory_invalidRange(identifier->address,
identifier->size, address, byteAmount);
portLibrary->error_set_last_error(portLibrary, -1,
OMRPORT_ERROR_VMEM_INVALID_PARAMS);
}
#if defined(OMRVMEM_DEBUG)
printf("\t\t omrvmem_commit_memory returning 0x%x\n",rc);fflush(stdout);
#endif
Trc_PRT_vmem_omrvmem_commit_memory_Exit(rc);
return rc;
}
intptr_t
omrvmem_decommit_memory(struct OMRPortLibrary *portLibrary, void *address,
uintptr_t byteAmount, struct J9PortVmemIdentifier *identifier)
{
intptr_t result = 0;
Trc_PRT_vmem_omrvmem_decommit_memory_Entry(address, byteAmount);
/* JVM is not allowed to decommit, just return success */
Trc_PRT_vmem_decommit_memory_not_allowed(
portLibrary->portGlobals->vmemAdviseOSonFree);
Trc_PRT_vmem_omrvmem_decommit_memory_Exit(result);
return result;
}
int32_t
omrvmem_free_memory(struct OMRPortLibrary *portLibrary, void *address,
uintptr_t byteAmount, struct J9PortVmemIdentifier *identifier)
{
void *freeAddress;
int32_t ret = -1;
OMRMemCategory * category = identifier->category;
/* CMVC 180372 - Some users store the identifier in the allocated memory.
* We therefore store the allocator in a temp, clear the identifier then
* free the memory
*/
uintptr_t allocator = identifier->allocator;
Trc_PRT_vmem_omrvmem_free_memory_Entry(address, byteAmount);
/* CMVC 180372 - Identifier must be cleared before memory is freed, see comment above */
update_vmemIdentifier(identifier, NULL, NULL, 0, 0, 0, 0, 0, NULL);
/* Default page Size */
if (OMRPORT_VMEM_RESERVE_USED_SHM != allocator) {
freeAddress = GET_BASE_PTR_FROM_ALIGNED_PTR(address);
free(freeAddress);
} else {
ret = (int32_t) shmdt(address);
}
omrmem_categories_decrement_counters(category, byteAmount);
Trc_PRT_vmem_omrvmem_free_memory_Exit(ret);
return ret;
}
int32_t
omrvmem_vmem_params_init(struct OMRPortLibrary *portLibrary,
struct J9PortVmemParams *params)
{
memset(params, 0, sizeof(struct J9PortVmemParams));
params->startAddress = NULL;
params->endAddress = OMRPORT_VMEM_MAX_ADDRESS;
params->byteAmount = 0;
params->pageSize = PPG_vmem_pageSize[0];
params->pageFlags = PPG_vmem_pageFlags[0];
params->mode = OMRPORT_VMEM_MEMORY_MODE_READ | OMRPORT_VMEM_MEMORY_MODE_WRITE;
params->options = 0;
params->category = OMRMEM_CATEGORY_UNKNOWN;
params->alignmentInBytes = 0;
return 0;
}
void *
omrvmem_reserve_memory(struct OMRPortLibrary *portLibrary, void *address,
uintptr_t byteAmount, struct J9PortVmemIdentifier *identifier, uintptr_t mode,
uintptr_t pageSize, uint32_t category)
{
struct J9PortVmemParams params;
omrvmem_vmem_params_init(portLibrary, ¶ms);
if (NULL != address) {
params.startAddress = address;
params.endAddress = address;
}
params.byteAmount = byteAmount;
params.mode = mode;
params.pageSize = pageSize;
params.pageFlags = OMRPORT_VMEM_PAGE_FLAG_NOT_USED;
params.options = 0;
params.category = category;
return portLibrary->vmem_reserve_memory_ex(portLibrary, identifier, ¶ms);
}
void *
omrvmem_reserve_memory_ex(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier,
struct J9PortVmemParams *params)
{
void *memoryPointer = NULL;
OMRMemCategory * category = omrmem_get_category(portLibrary,
params->category);
Trc_PRT_vmem_omrvmem_reserve_memory_Entry_replacement(params->startAddress,
params->byteAmount, params->pageSize);
Assert_PRT_true(params->startAddress <= params->endAddress);
ASSERT_VALUE_IS_PAGE_SIZE_ALIGNED(params->byteAmount, params->pageSize);
/* Invalid input */
if (0 == params->pageSize) {
update_vmemIdentifier(identifier, NULL, NULL, 0, 0, 0, 0, 0, NULL);
Trc_PRT_vmem_omrvmem_reserve_memory_invalid_input();
} else if (PPG_vmem_pageSize[0] == params->pageSize) {
uintptr_t alignmentInBytes = OMR_MAX(params->pageSize,
params->alignmentInBytes);
uintptr_t minimumGranule = OMR_MIN(params->pageSize, params->alignmentInBytes);
/* Make sure that the alignment is a multiple of both requested alignment and page size (enforces that arguments are powers of two and, thus, their max is their lowest common multiple) */
if ((0 == minimumGranule)
|| (0 == (alignmentInBytes % minimumGranule))) {
memoryPointer = getMemoryInRangeForDefaultPages(portLibrary,
identifier, category, params->byteAmount,
params->startAddress, params->endAddress, alignmentInBytes,
params->options, params->mode);
}
} else if (PPG_vmem_pageSize[1] == params->pageSize) {
uintptr_t largePageAlignmentInBytes = OMR_MAX(params->pageSize,
params->alignmentInBytes);
uintptr_t largePageMinimumGranule = OMR_MIN(params->pageSize,
params->alignmentInBytes);
/* Make sure that the alignment is a multiple of both requested alignment and page size (enforces that arguments are powers of two and, thus, their max is their lowest common multiple) */
if ((0 == largePageMinimumGranule)
|| (0 == (largePageAlignmentInBytes % largePageMinimumGranule))) {
memoryPointer = reserveLargePages(portLibrary, identifier, category,
params->byteAmount, params->startAddress,
params->endAddress, params->pageSize,
largePageAlignmentInBytes, params->options, params->mode);
}
if (NULL == memoryPointer) {
/* If strict page size flag is not set try again with default page size */
if (0 == (OMRPORT_VMEM_STRICT_PAGE_SIZE & params->options)) {
#if defined(OMRVMEM_DEBUG)
printf("\t\t\t NULL == memoryPointer, reverting to default pages\n");fflush(stdout);
#endif
uintptr_t defaultPageSize = PPG_vmem_pageSize[0];
uintptr_t alignmentInBytes = OMR_MAX(defaultPageSize,
params->alignmentInBytes);
uintptr_t minimumGranule = OMR_MIN(defaultPageSize,
params->alignmentInBytes);
/* Make sure that the alignment is a multiple of both requested alignment and page size (enforces that arguments are powers of two and, thus, their max is their lowest common multiple) */
if ((0 == minimumGranule)
|| (0 == (alignmentInBytes % minimumGranule))) {
memoryPointer = getMemoryInRangeForDefaultPages(portLibrary,
identifier, category, params->byteAmount,
params->startAddress, params->endAddress,
alignmentInBytes, params->options, params->mode);
}
} else {
update_vmemIdentifier(identifier, NULL, NULL, 0, 0, 0, 0, 0,
NULL);
}
}
} else {
/* If the pageSize is not one of the supported page sizes, error */
update_vmemIdentifier(identifier, NULL, NULL, 0, 0, 0, 0, 0, NULL);
Trc_PRT_vmem_omrvmem_reserve_memory_unsupported_page_size(
params->pageSize);
}
#if defined(OMR_PORT_NUMA_SUPPORT)
if (NULL != memoryPointer) {
port_numa_interleave_memory(portLibrary, memoryPointer, params->byteAmount);
}
#endif
#if defined(OMRVMEM_DEBUG)
printf("\tomrvmem_reserve_memory_ex returning %p\n", memoryPointer);fflush(stdout);
#endif
Trc_PRT_vmem_omrvmem_reserve_memory_Exit_replacement(memoryPointer,
params->startAddress);
return memoryPointer;
}
static void *
reserveLargePages(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier, OMRMemCategory * category,
uintptr_t byteAmount, void *startAddress, void *endAddress, uintptr_t pageSize,
uintptr_t alignmentInBytes, uintptr_t vmemOptions, uintptr_t mode)
{
/* The address should usually be passed in as NULL in order to let the kernel find and assign a
* large enough window of virtual memory
*
* Requesting HUGETLB pages via shmget has the effect of "reserving" them. They have to be attached to become allocated for use
* The execute flags are ignored by shmget
*/
key_t addressKey;
int shmgetFlags = SHM_HUGETLB | IPC_CREAT | TPF_IPC64;
void *memoryPointer = NULL;
if (0 != (OMRPORT_VMEM_MEMORY_MODE_READ & mode)) {
shmgetFlags |= SHM_R;
}
if (0 != (OMRPORT_VMEM_MEMORY_MODE_WRITE & mode)) {
shmgetFlags |= SHM_W;
}
addressKey = shmget(IPC_PRIVATE, (size_t) byteAmount, shmgetFlags);
if (-1 == addressKey) {
Trc_PRT_vmem_omrvmem_reserve_memory_shmget_failed(byteAmount,
shmgetFlags);
} else {
memoryPointer = getMemoryInRangeForLargePages(portLibrary, identifier,
addressKey, category, byteAmount, startAddress, endAddress,
alignmentInBytes, vmemOptions, pageSize, mode);
/* release when complete, protect from ^C or crash */
if (0 != shmctl(addressKey, IPC_RMID, NULL)) {
/* if releasing addressKey fails detach memory to avoid leaks and fail */
if (NULL != memoryPointer) {
if (0 != shmdt(memoryPointer)) {
Trc_PRT_vmem_omrvmem_reserve_memory_shmdt_failed(
memoryPointer);
}
}
Trc_PRT_vmem_omrvmem_reserve_memory_failure();
memoryPointer = NULL;
}
if (NULL != memoryPointer) {
/* Commit memory if required, else return reserved memory */
if (0 != (OMRPORT_VMEM_MEMORY_MODE_COMMIT & mode)) {
if (NULL
== omrvmem_commit_memory(portLibrary, memoryPointer,
byteAmount, identifier)) {
/* If the commit fails free the memory */
omrvmem_free_memory(portLibrary, memoryPointer, byteAmount,
identifier);
memoryPointer = NULL;
}
}
}
}
if (NULL == memoryPointer) {
update_vmemIdentifier(identifier, NULL, NULL, 0, 0, 0, 0, 0, NULL);
}
#if defined(OMRVMEM_DEBUG)
printf("\treserveLargePages returning 0x%zx\n", memoryPointer);fflush(stdout);
#endif
return memoryPointer;
}
uintptr_t
omrvmem_get_page_size(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier)
{
return identifier->pageSize;
}
uintptr_t
omrvmem_get_page_flags(struct OMRPortLibrary *portLibrary,
struct J9PortVmemIdentifier *identifier)
{
return identifier->pageFlags;
}
uintptr_t*
omrvmem_supported_page_sizes(struct OMRPortLibrary *portLibrary)
{
return PPG_vmem_pageSize;
}
uintptr_t*
omrvmem_supported_page_flags(struct OMRPortLibrary *portLibrary)
{
return PPG_vmem_pageFlags;
}
static uintptr_t
get_hugepages_info(struct OMRPortLibrary *portLibrary,
vmem_hugepage_info_t *page_info)
{
int fd;
int bytes_read;
char *line_ptr, read_buf[VMEM_MEMINFO_SIZE_MAX];
char token_name[128];
int tokens_assigned;
uintptr_t token_value;
fd = omrfile_open(portLibrary, VMEM_PROC_MEMINFO_FNAME, EsOpenRead, 0);
if (fd < 0) {
return 0;
}
bytes_read = omrfile_read(portLibrary, fd, read_buf,
VMEM_MEMINFO_SIZE_MAX - 1);
if (bytes_read <= 0) {
omrfile_close(portLibrary, fd);
return 0;
}
/* make sure its null terminated */
read_buf[bytes_read] = 0;
/** Why this is data is not available via a well defined system call remains a mystery. Meanwhile
* we have to parse /proc/meminfo to figure out how many pages are available/free as well as
* their size
*/
line_ptr = read_buf;
while (line_ptr && *line_ptr) {
tokens_assigned = sscanf(line_ptr, "%127s %zu %*s", token_name,
&token_value);
#ifdef LPDEBUG
portLibrary->tty_printf(portLibrary, "/proc/meminfo => %s [%zu] %d\n", token_name, token_value, tokens_assigned);
#endif
if (tokens_assigned) {
if (!strcmp(token_name, "HugePages_Total:")) {
page_info->pages_total = token_value;
} else if (!strcmp(token_name, "HugePages_Free:")) {
page_info->pages_free = token_value;
} else if (!strcmp(token_name, "Hugepagesize:")) {
page_info->page_size = token_value * 1024; /* value is in KB, convert to bytes */
}
}
line_ptr = strpbrk(line_ptr, "\n");
if (line_ptr && *line_ptr) {
line_ptr++; /* skip the \n if we are not done yet */
}
}
omrfile_close(portLibrary, fd);
/* "Enable" large page support if the system has been found to be initialized */
if (page_info->pages_total) {
page_info->enabled = 1;
}
return 1;
}
void *
default_pageSize_reserve_memory(struct OMRPortLibrary *portLibrary,
void *address, uintptr_t byteAmount,
struct J9PortVmemIdentifier *identifier, uintptr_t mode, uintptr_t pageSize,
OMRMemCategory * category)
{
/* This function is cloned in J9SourceUnixJ9VMem (omrvmem_reserve_memory).
* Any changes made here may need to be reflected in that version .
*/
int fd = -1;
int flags = MAP_PRIVATE;
void *result = NULL;
int protectionFlags = PROT_NONE;
if(mode & OMRPORT_VMEM_MEMORY_MODE_SHARE_FILE_OPEN) {
portLibrary->error_set_last_error(portLibrary, errno, OMRPORT_ERROR_VMEM_NOT_SUPPORTED);
return result;
}
Trc_PRT_vmem_default_reserve_entry(address, byteAmount);
#if defined(MAP_ANONYMOUS)
flags |= MAP_ANONYMOUS;
#elif defined(MAP_ANON)
flags |= MAP_ANON;
#else
fd = portLibrary->file_open(portLibrary, "/dev/zero",
EsOpenRead | EsOpenWrite, 0);
if (-1 != fd)
#endif
{
if (0 != (OMRPORT_VMEM_MEMORY_MODE_COMMIT & mode)) {
protectionFlags = get_protectionBits(mode);
} else {
flags |= MAP_NORESERVE;
}