-
Notifications
You must be signed in to change notification settings - Fork 392
/
CompactScheme.cpp
1537 lines (1333 loc) · 52.9 KB
/
CompactScheme.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
/*******************************************************************************
* Copyright (c) 1991, 2021 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
*******************************************************************************/
#include "omrcfg.h"
#if defined(OMR_GC_MODRON_COMPACTION)
#include "CompactScheme.hpp"
#include "ModronAssertions.h"
#include "AllocateDescription.hpp"
#include "AtomicOperations.hpp"
#include "Bits.hpp"
#include "CollectorLanguageInterface.hpp"
#include "CompactFixHeapForWalkTask.hpp"
#include "CompactSchemeFixupObject.hpp"
#include "Debug.hpp"
#include "EnvironmentBase.hpp"
#include "Heap.hpp"
#include "HeapLinkedFreeHeader.hpp"
#include "HeapMapIterator.hpp"
#include "HeapMapWordIterator.hpp"
#include "HeapMemoryPoolIterator.hpp"
#include "HeapRegionDescriptorStandard.hpp"
#include "HeapRegionIteratorStandard.hpp"
#include "HeapStats.hpp"
#include "MarkingScheme.hpp"
#include "MarkMap.hpp"
#include "MemoryPool.hpp"
#include "MemorySpace.hpp"
#include "MemorySubSpace.hpp"
#include "ObjectHeapIteratorAddressOrderedList.hpp"
#include "ObjectModel.hpp"
#include "ParallelDispatcher.hpp"
#include "ParallelSweepScheme.hpp"
#include "ParallelTask.hpp"
#include "SlotObject.hpp"
#include "SublistPool.hpp"
#include "SublistPuddle.hpp"
#include "SweepHeapSectioning.hpp"
#include "CompactDelegate.hpp"
/* OMRTODO temporary workaround to allow both ut_j9mm.h and ut_omrmm.h to be included.
* Dependency on ut_j9mm.h should be removed in the future.
*/
#undef UT_MODULE_LOADED
#undef UT_MODULE_UNLOADED
#include "ut_omrmm.h"
#if !defined(OMR_GC_DEFERRED_HASHCODE_INSERTION)
#define getConsumedSizeInBytesWithHeaderForMove getConsumedSizeInBytesWithHeader
#endif /* !defined(OMR_GC_DEFERRED_HASHCODE_INSERTION) */
/**
* Allocate and initialize a new instance of the receiver.
* @return a new instance of the receiver, or NULL on failure.
*/
MM_CompactScheme *
MM_CompactScheme::newInstance(MM_EnvironmentBase *env, MM_MarkingScheme *markingScheme)
{
MM_CompactScheme *compactScheme;
compactScheme = (MM_CompactScheme *)env->getForge()->allocate(sizeof(MM_CompactScheme), OMR::GC::AllocationCategory::FIXED, OMR_GET_CALLSITE());
if (compactScheme) {
new(compactScheme) MM_CompactScheme(env, markingScheme);
if (!compactScheme->initialize(env)) {
compactScheme->kill(env);
compactScheme = NULL;
}
}
return compactScheme;
}
MMINLINE uintptr_t
makeMask(intptr_t maskSize)
{
return ((uintptr_t)1 << maskSize) - 1;
}
MMINLINE intptr_t
countBits(uintptr_t x)
{
intptr_t count = 0;
while (x) {
count++;
x &= x-1;
}
return count;
}
/************************************************************
*
* 32-bit layout
*
* addr 0:32 forwardingPtr
*
* bits 0:22 compressed mark bits
* bits 22:28 hint0 bits 0:6
*
************************************************************
*
* 64-bit layout
*
* addr 0:63 forwardingPtr
* bits 0:43 compressed mark bits
* bits 43:50 hint0
* bits 50:57 hint1
* bits 57:64 hint2
*/
enum {
#if defined(OMR_ENV_DATA64)
#if defined(OMR_THR_LOCK_NURSERY) || defined(OMR_GC_COMPRESSED_POINTERS)
maxOffset = 64, // number of bits in compressed mark bits
maxHints = 0, // 0 hints on 64 bit hardware
hintSize = 7, // bits per hint
#else /* OMR_THR_LOCK_NURSERY */
maxOffset = 43, // number of bits in compressed mark bits
maxHints = 3, // 3 hints on 64 bit hardware
hintSize = 7, // bits per hint
#endif /* OMR_THR_LOCK_NURSERY */
#else /* OMR_ENV_DATA64 */
#if defined(OMR_GC_MINIMUM_OBJECT_SIZE)
maxOffset = 32, // number of bits in compressed mark bits
maxHints = 0, // 0 hints on 32 bit hardware
hintSize = 7, // bits per hint
#else /* OMR_GC_MINIMUM_OBJECT_SIZE */
#if defined(OMR_THR_LOCK_NURSERY)
maxOffset = 32, // number of bits in compressed mark bits
maxHints = 0, // 0 hints on 32 bit hardware
hintSize = 6, // bits per hint
#else /* OMR_THR_LOCK_NURSERY */
maxOffset = 22, // number of bits in compressed mark bits
maxHints = 1, // 1 hint on 32 bit hardware
hintSize = 6, // bits per hint
#endif /* OMR_THR_LOCK_NURSERY */
#endif /* OMR_GC_MINIMUM_OBJECT_SIZE */
#endif /* OMR_ENV_DATA64 */
// Max value of a hint log2(maxValue) == hintSize
maxValue = MM_CompactScheme::sizeof_page / sizeof(uintptr_t),
/* Invalid value is used when, because of object growth due to hash, the hint exceeds or
* is equal to maxValue. The hint would then be invalid.
*/
invalidValue = maxValue - 1,
};
class CompactTableEntry {
private:
uintptr_t _addr;
uintptr_t _bits;
private:
MMINLINE uintptr_t
getHintShiftCount(intptr_t index) const
{
uintptr_t shiftCount = maxOffset;
#if defined(OMR_ENV_DATA64)
shiftCount += index * hintSize;
#endif /* OMR_ENV_DATA64 */
/* assert that the shift value is within range (8 bits per byte) */
Assert_MM_true(shiftCount < (sizeof(uintptr_t) * 8));
return shiftCount;
}
public:
void
operator=(const CompactTableEntry& otherEntry)
{
_addr = otherEntry._addr;
_bits = otherEntry._bits;
}
void
initialize(omrobjectptr_t addr)
{
_addr = (uintptr_t)addr | 3; // both 32 and 64 bit hardware
_bits = 0;
}
omrobjectptr_t
getAddr()
{
return ((_addr & 3) != 3) ? 0 : (omrobjectptr_t) (_addr & ~3);
}
void
setBit(intptr_t offset)
{
assume0(offset >= 0 && offset < maxOffset);
_bits |= (uintptr_t)1 << offset;
}
uintptr_t
getBit(intptr_t offset) const
{
assume0(offset >= 0 && offset < maxOffset);
return _bits & ((uintptr_t)1 << offset);
}
intptr_t
getObjectOrdinal(intptr_t offset) const
{
return countBits(_bits & makeMask(offset));
}
void
setHint(intptr_t index, intptr_t value)
{
/* this function shouldn't be reached if maxHints is 0 */
Assert_MM_true(maxHints > 0);
Assert_MM_true((index >= 0) && (index < maxHints));
Assert_MM_true(value > 0);
if (value >= maxValue) {
/* Adding a hash to an object may grow the object. It is possible that because
* of this growth, value may be greater than or equal to maxValue. If this
* happens, we want to set this hint as invalid.
*/
value = invalidValue;
}
_bits |= (uintptr_t)value << getHintShiftCount(index);
}
/**
* Answer the hint for the specified object in a chunk. The hint is the
* distance (in UDATAs) of the object from the beginning of the chunk.
* index is the ordinality of the object within the chunk, relative to the
* first object. i.e. the second object in the chunk has index 0.
* (The first object has an implicit hint of 0, and is not handled by this
* function).
*
* @parm[in] index the index of the object, where 0 is the second object
* in the chunk
* @return the distance of the relocated object from the beginning of the
* chunk, in UDATAs
*/
intptr_t
getHint(intptr_t index) const
{
Assert_MM_true((index >= 0) && (index < maxHints));
#if defined(OMR_ENV_DATA64)
intptr_t hint = (_bits >> getHintShiftCount(index)) & makeMask(hintSize);
#else /* OMR_ENV_DATA64 */
intptr_t hint = _bits >> getHintShiftCount(index);
#endif /* OMR_ENV_DATA64 */
Assert_MM_true( (hint != 0) && (hint < maxValue) );
return hint;
}
CompactTableEntry()
: _addr(0)
, _bits(0)
{}
};
bool
MM_CompactScheme::initialize(MM_EnvironmentBase *env)
{
return _delegate.initialize(env, _omrVM, _markMap, this);
}
void
MM_CompactScheme::tearDown(MM_EnvironmentBase *env)
{
_delegate.tearDown(env);
}
/**
* Free the receiver and all associated resources.
*/
void
MM_CompactScheme::kill(MM_EnvironmentBase *env)
{
tearDown(env);
env->getForge()->free(this);
}
size_t
MM_CompactScheme::getFreeChunkSize(omrobjectptr_t freeChunk)
{
if (freeChunk == 0) {
return 0;
}
/* This duplicates code in GC_ObjectHeapIteratorAddressOrderedList::nextObject() */
if ( ! _extensions->objectModel.isDeadObject(freeChunk)) {
return _extensions->objectModel.getConsumedSizeInBytesWithHeader(freeChunk);
}
if (_extensions->objectModel.isSingleSlotDeadObject(freeChunk)) {
return _extensions->objectModel.getSizeInBytesSingleSlotDeadObject(freeChunk);
}
return _extensions->objectModel.getSizeInBytesMultiSlotDeadObject(freeChunk);
}
void
MM_CompactScheme::setFreeChunkSize(omrobjectptr_t deadObject, uintptr_t deadObjectSize)
{
if (deadObjectSize == 0) {
return;
}
bool const compressed = _extensions->compressObjectReferences();
#if defined(DEBUG_PAINT_FREE)
memset(deadObject, 0xAA, deadObjectSize);
#endif /* DEBUG_PAINT_FREE */
assume0(deadObjectSize >= sizeof(uintptr_t));
MM_HeapLinkedFreeHeader::fillWithHoles(deadObject, deadObjectSize, compressed);
}
size_t
MM_CompactScheme::setFreeChunk(omrobjectptr_t from, omrobjectptr_t to)
{
size_t size = (size_t)to - (size_t)from;
setFreeChunkSize(from, size);
return size;
}
MMINLINE void
MM_CompactScheme::preObjectMove(MM_EnvironmentBase *env, omrobjectptr_t objectPtr)
{
env->preObjectMoveForCompact(objectPtr);
}
MMINLINE void
MM_CompactScheme::postObjectMove(MM_EnvironmentBase *env, omrobjectptr_t objectPtr)
{
env->postObjectMoveForCompact(objectPtr);
if(_extensions->objectModel.isIndexable(objectPtr)) {
/* Updates internal field of indexable objects. Every indexable object have an extra field
* that can be used to store any extra information about the indexable object. One use case is
* OpenJ9 where we use this field to point to array data. In this case it will always point to
* the address right after the header, in case of contiguous data it will point to the data
* itself, and in case of discontiguous arraylet it will point to the first arrayiod. How to
* updated dataAddr is up to the target language that must override fixupDataAddr */
_extensions->indexableObjectModel.fixupDataAddr(objectPtr);
}
}
void
MM_CompactScheme::workerSetupForGC(MM_EnvironmentStandard *env, bool singleThreaded)
{
createSubAreaTable(env, singleThreaded);
setRealLimitsSubAreas(env);
removeNullSubAreas(env);
completeSubAreaTable(env);
}
void
MM_CompactScheme::mainSetupForGC(MM_EnvironmentStandard *env)
{
_heap = _extensions->heap;
_rootManager = _heap->getHeapRegionManager();
_heapBase = (uintptr_t)_heap->getHeapBase();
_compactTable = (CompactTableEntry*)_markingScheme->getMarkMap()->getMarkBits();
_subAreaTable = (SubAreaEntry*)_extensions->sweepHeapSectioning->getBackingStoreAddress();
_subAreaTableSize = _extensions->sweepHeapSectioning->getBackingStoreSize();
_delegate.mainSetupForGC(env);
}
omrobjectptr_t
MM_CompactScheme::freeChunkEnd(omrobjectptr_t chunk)
{
if (!chunk) {
return NULL;
}
return (omrobjectptr_t)((uintptr_t)chunk + getFreeChunkSize(chunk));
}
/**
* Create sub areas table for regions.
*/
void
MM_CompactScheme::createSubAreaTable(MM_EnvironmentStandard *env, bool singleThreaded)
{
/* finding whether there are memory limitations */
uintptr_t max_subarea_num = _subAreaTableSize / sizeof(_subAreaTable[0]);
uintptr_t necessary_subareas = 0;
uintptr_t min_subarea_size;
GC_HeapRegionIteratorStandard regionCounter(_rootManager);
MM_HeapRegionDescriptorStandard *region = NULL;
uintptr_t number_of_regions = 0;
while(NULL != (region = regionCounter.nextRegion())) {
if (region->isCommitted()) {
number_of_regions += 1;
}
}
necessary_subareas = 3 * number_of_regions + 1; //1 is for last seg
Assert_MM_true(max_subarea_num > 0);
if(max_subarea_num > necessary_subareas) {
min_subarea_size = _heap->getMaximumPhysicalRange() / (max_subarea_num - necessary_subareas);
} else {
min_subarea_size = _heap->getMaximumPhysicalRange();
}
uintptr_t size = (DESIRED_SUBAREA_SIZE >= min_subarea_size) ? DESIRED_SUBAREA_SIZE : min_subarea_size;
/* Single threaded pass to set tentative sub area limits tentative limits are
* listed in freeChunk field. This field will be reset during the third pass.
*/
if (env->_currentTask->synchronizeGCThreadsAndReleaseMain(env, UNIQUE_ID)) {
GC_HeapRegionIteratorStandard regionIterator(_rootManager);
uintptr_t i = 0;
while(NULL != (region = regionIterator.nextRegion())) {
if (!region->isCommitted() || (0 == region->getSize())) {
continue;
}
void *lowAddress = region->getLowAddress();
void *highAddress = region->getHighAddress();
uintptr_t areaSize = region->getSize();
MM_MemorySubSpace *memorySubSpace = region->getSubSpace();
intptr_t state = SubAreaEntry::init;
if (singleThreaded) {
size = areaSize;
}
_subAreaTable[i].firstObject = (omrobjectptr_t)lowAddress;
/* Calculate number of sub areas..take care to avoid overflow if size is large */
uintptr_t numSubAreas = ((areaSize - 1) / size) + 1;
for( uintptr_t subAreaNum=0; subAreaNum < numSubAreas; subAreaNum++){
uint8_t *p = (uint8_t*)(((uintptr_t)lowAddress) + (subAreaNum * size));
_subAreaTable[i].freeChunk = (omrobjectptr_t)p;
_subAreaTable[i].memoryPool = memorySubSpace->getMemoryPool(p);
_subAreaTable[i].state = state;
_subAreaTable[i++].currentAction = SubAreaEntry::none;
}
_subAreaTable[i].freeChunk = (omrobjectptr_t)highAddress;
_subAreaTable[i].memoryPool = NULL;
_subAreaTable[i].firstObject = (omrobjectptr_t)highAddress;
_subAreaTable[i].state = SubAreaEntry::end_segment;
_subAreaTable[i++].currentAction = SubAreaEntry::none;
}
_subAreaTable[i].state = SubAreaEntry::end_heap;
env->_currentTask->releaseSynchronizedGCThreads(env);
}
}
/**
* Set real limits for each subarea
*/
void
MM_CompactScheme::setRealLimitsSubAreas(MM_EnvironmentStandard *env)
{
/* multi threaded pass to find real regions limits - where an object is found */
for (uintptr_t i = 1; _subAreaTable[i].state != SubAreaEntry::end_heap; i++) {
/* i=1 because first region starts with heapAlloc thus we don't need to find its first object */
if ((SubAreaEntry::end_segment == _subAreaTable[i].state)
|| (SubAreaEntry::end_segment == _subAreaTable[i - 1].state)
) {
/* skip the end_segment and its successor */
continue;
}
if (changeSubAreaAction(env, &_subAreaTable[i], SubAreaEntry::setting_real_limits)) {
uintptr_t *start = (uintptr_t*)pageStart(pageIndex(_subAreaTable[i].freeChunk));
uintptr_t *end = (uintptr_t*)pageStart(pageIndex(_subAreaTable[i+1].freeChunk));
MM_HeapMapIterator markedObjectIterator(_extensions, _markMap, start, end);
omrobjectptr_t objectPtr = markedObjectIterator.nextObject();
_subAreaTable[i].firstObject = objectPtr;
Assert_MM_true(objectPtr == 0 || _markMap->isBitSet(objectPtr));
}
}
}
/**
* Remove empty sub areas from lists.
*/
void
MM_CompactScheme::removeNullSubAreas(MM_EnvironmentStandard *env)
{
/*single threaded pass to eliminate null sub areas */
if (env->_currentTask->synchronizeGCThreadsAndReleaseMain(env, UNIQUE_ID)) {
_compactFrom = (omrobjectptr_t)_heap->getHeapTop();
_compactTo = (omrobjectptr_t)_heap->getHeapBase();
uintptr_t j = 0;
for (uintptr_t i = 0; _subAreaTable[i].state != SubAreaEntry::end_heap; i++) {
if (NULL != _subAreaTable[i].firstObject) {
_subAreaTable[j].firstObject = _subAreaTable[i].firstObject;
_subAreaTable[j].memoryPool = _subAreaTable[i].memoryPool;
_subAreaTable[j].state = _subAreaTable[i].state;
if ((j > 0) && (_subAreaTable[j-1].state == SubAreaEntry::init)) {
_compactFrom = (_compactFrom < _subAreaTable[j-1].firstObject) ? _compactFrom : _subAreaTable[j-1].firstObject;
_compactTo = (_compactTo > _subAreaTable[j].firstObject) ? _compactTo : _subAreaTable[j].firstObject;
}
_subAreaTable[j].freeChunk = 0;
j++;
}
}
env->_currentTask->releaseSynchronizedGCThreads(env);
}
}
/**
* Complete setup for each sub area.
*/
void
MM_CompactScheme::completeSubAreaTable(MM_EnvironmentStandard *env)
{
if (env->_currentTask->synchronizeGCThreadsAndReleaseMain(env, UNIQUE_ID)) {
MM_HeapRegionDescriptorStandard *region = NULL;
/* Finally iterate over all memory pools and reset in preparation for
* rebuild of free list at end of compaction
*/
GC_HeapRegionIteratorStandard regionIterator2(_rootManager);
while(NULL != (region = regionIterator2.nextRegion())) {
if (!region->isCommitted() || (0 == region->getSize())) {
continue;
}
MM_MemorySubSpace *subspace = region->getSubSpace();
MM_MemoryPool *memoryPool = subspace->getMemoryPool();
memoryPool->reset(MM_MemoryPool::forCompact);
}
env->_currentTask->releaseSynchronizedGCThreads(env);
}
}
void
MM_CompactScheme::compact(MM_EnvironmentBase *envBase, bool rebuildMarkBits, bool aggressive)
{
MM_EnvironmentStandard *env = MM_EnvironmentStandard::getEnvironment(envBase);
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
uintptr_t objectCount = 0;
uintptr_t byteCount = 0;
uintptr_t skippedObjectCount = 0;
uintptr_t fixupObjectsCount = 0;
bool singleThreaded = false;
if (env->_currentTask->synchronizeGCThreadsAndReleaseMain(env, UNIQUE_ID)) {
/* Do any necessary initialization */
/* TODO: Perhaps the task dispatch should occur internally within so that the initialization doesn't need to be
* done at a synchronize point?
*/
mainSetupForGC(env);
#if defined(DEBUG)
_delegate.verifyHeap(env, _markMap);
#endif /* DEBUG */
/* Reset largestFreeEntry of all subSpaces at beginning of compaction */
_extensions->heap->resetLargestFreeEntry();
env->_currentTask->releaseSynchronizedGCThreads(env);
}
/* We force a single sub area compaction if:
* o the compaction is aggressive. We use a single sub area per segment to avoid potentially having
* multiple holes created per segment, thereby fragmenting the space. This will result in
* singlethreaded compaction per segment, and so should only be done in extreme OOM situations.
* o no worker GC threads
*/
if (aggressive || (1 == env->_currentTask->getThreadCount())) {
singleThreaded = true;
}
env->_compactStats._setupStartTime = omrtime_hires_clock();
workerSetupForGC(env, singleThreaded);
env->_compactStats._setupEndTime = omrtime_hires_clock();
/* If a single threaded compaction force compact to run on main thread. Required
* to ensure all events issued on main thread.
*/
if (!singleThreaded || env->_currentTask->synchronizeGCThreadsAndReleaseMain(env, UNIQUE_ID)) {
env->_compactStats._moveStartTime = omrtime_hires_clock();
moveObjects(env, objectCount, byteCount, skippedObjectCount);
env->_compactStats._moveEndTime = omrtime_hires_clock();
if (!singleThreaded) {
env->_currentTask->synchronizeGCThreads(env, UNIQUE_ID);
MM_AtomicOperations::sync();
}
env->_compactStats._fixupStartTime = omrtime_hires_clock();
fixupObjects(env, fixupObjectsCount);
env->_compactStats._fixupEndTime = omrtime_hires_clock();
if (singleThreaded) {
env->_currentTask->releaseSynchronizedGCThreads(env);
}
}
/* FixupRoots can always be done in parallel */
env->_compactStats._rootFixupStartTime = omrtime_hires_clock();
_delegate.fixupRoots(env, this);
env->_compactStats._rootFixupEndTime = omrtime_hires_clock();
MM_AtomicOperations::sync();
if (env->_currentTask->synchronizeGCThreadsAndReleaseMain(env, UNIQUE_ID)) {
rebuildFreelist(env);
MM_MemoryPool *memoryPool;
MM_HeapMemoryPoolIterator poolIterator(env, _extensions->heap);
while(NULL != (memoryPool = poolIterator.nextPool())) {
memoryPool->postProcess(env, MM_MemoryPool::forCompact);
}
MM_AtomicOperations::sync();
env->_currentTask->releaseSynchronizedGCThreads(env);
}
if (rebuildMarkBits) {
rebuildMarkbits(env);
MM_AtomicOperations::sync();
}
_delegate.workerCleanupAfterGC(env);
env->_compactStats._movedObjects = objectCount;
env->_compactStats._movedBytes = byteCount;
env->_compactStats._fixupObjects = fixupObjectsCount;
}
void
MM_CompactScheme::flushPool(MM_EnvironmentStandard *env, MM_CompactMemoryPoolState *poolState)
{
MM_MemoryPool *memoryPool = poolState->_memoryPool;
if(poolState->_freeListHead) {
memoryPool->addFreeEntries(env, poolState->_freeListHead, poolState->_previousFreeEntry, poolState->_freeHoles, poolState->_freeBytes);
}
/* Update the free memory values */
memoryPool->setFreeMemorySize(poolState->_freeBytes);
memoryPool->setFreeEntryCount(poolState->_freeHoles);
memoryPool->setLargestFreeEntry(poolState->_largestFreeEntry);
memoryPool->setLastFreeEntry(poolState->_previousFreeEntry);
}
void MM_CompactScheme::rebuildFreelist(MM_EnvironmentStandard *env)
{
uintptr_t i = 0;
MM_HeapRegionManager *regionManager = _heap->getHeapRegionManager();
GC_HeapRegionIteratorStandard regionIterator(regionManager);
MM_HeapRegionDescriptorStandard *region = NULL;
SubAreaEntry *subAreaTable = _subAreaTable;
while(NULL != (region = regionIterator.nextRegion())) {
if (!region->isCommitted() || (0 == region->getSize())) {
continue;
}
MM_MemorySubSpace *memorySubSpace = region->getSubSpace();
Assert_MM_true(region->getLowAddress() == subAreaTable[i].firstObject);
MM_CompactMemoryPoolState poolStateObj;
MM_CompactMemoryPoolState *poolState = &poolStateObj;
void *currentFreeBase = NULL;
uintptr_t currentFreeSize = 0;
/* Initialize current memory pool sweep chunk */
poolState->_memoryPool = subAreaTable[i].memoryPool;
do {
if (NULL != subAreaTable[i].freeChunk) {
if (subAreaTable[i].freeChunk == subAreaTable[i].firstObject) {
/* The entire sub area is free */
if (NULL == currentFreeBase) {
currentFreeBase = (void *)subAreaTable[i].firstObject; //orizzz - round down to page
}
} else {
/* There is some free area in the sub area but not all of it */
if (NULL != currentFreeBase) {
currentFreeSize = (uintptr_t)subAreaTable[i].firstObject - (uintptr_t)currentFreeBase;
#if defined(DEBUG_PAINT_FREE)
memset(currentFreeBase, 0xBB, currentFreeSize);
#endif /* DEBUG_PAINT_FREE */
addFreeEntry(env, memorySubSpace, poolState, currentFreeBase, currentFreeSize);
}
currentFreeSize = 0;
currentFreeBase = (void *)subAreaTable[i].freeChunk;
}
} else {
/* Either there is no free area in the sub area or sub area is
* a fixup_only sub area, i.e. IC is active
*/
if (NULL != currentFreeBase) {
currentFreeSize = (uintptr_t)subAreaTable[i].firstObject - (uintptr_t)currentFreeBase;
#if defined(DEBUG_PAINT_FREE)
memset(currentFreeBase, 0xCC, currentFreeSize);
#endif /* DEBUG_PAINT_FREE */
addFreeEntry(env, memorySubSpace, poolState, currentFreeBase, currentFreeSize);
}
currentFreeBase = NULL;
currentFreeSize = 0;
}
} while (subAreaTable[i++].state != SubAreaEntry::end_segment);
Assert_MM_true(currentFreeBase == NULL);
if (NULL != poolState->_freeListHead) {
/* Terminate the free list with NULL*/
poolState->_memoryPool->createFreeEntry(env, poolState->_previousFreeEntry,
(uint8_t *)poolState->_previousFreeEntry + poolState->_previousFreeEntrySize);
}
flushPool(env, poolState);
}
}
/*
* Call appropriate Memory Pool to add a new free entry to the pool. If the free entry
* spans more than one subpool then it will be split into 2 free entries.
*
* @param previousFreeEntry Address of previous entry added
* @param previousFreeEntrySize Size of previous entry
* @param currentFreeBase Address of new entry to be added to pool
* @param currentFreeSize Size of new entry
*
*/
MMINLINE void
MM_CompactScheme::addFreeEntry(MM_EnvironmentStandard *env, MM_MemorySubSpace *memorySubSpace, MM_CompactMemoryPoolState *poolState, void *currentFreeBase, uintptr_t currentFreeSize)
{
void *highAddr;
uintptr_t lowChunkSize, highChunkSize;
MM_MemoryPool *lowPool, *highPool;
/* Determine which memory pool the free entry belongs in and if
* the entry spans the top of the pool
*/
lowPool = memorySubSpace->getMemoryPool(env, currentFreeBase, (uint8_t *)currentFreeBase + currentFreeSize, highAddr);
/* Does new entry belong to same pool as last entry ? */
if (lowPool != poolState->_memoryPool) {
/* No.. So flush all statistics for current pool */
flushPool(env, poolState);
/* ..and reset all stats data for next pool */
poolState->clear();
poolState->_memoryPool = lowPool;
}
assume0(lowPool != NULL);
lowChunkSize = (highAddr ? (uint8_t*)highAddr - (uint8_t*)currentFreeBase : currentFreeSize);
if (lowChunkSize > lowPool->getMinimumFreeEntrySize()) {
if (!poolState->_freeListHead) {
poolState->_freeListHead = (MM_HeapLinkedFreeHeader *)currentFreeBase;
}
lowPool->createFreeEntry(env, currentFreeBase, (uint8_t *)currentFreeBase + lowChunkSize, poolState->_previousFreeEntry, NULL);
/* Update chunk stats */
poolState->_freeBytes += lowChunkSize;
poolState->_freeHoles += 1;
poolState->_largestFreeEntry = OMR_MAX(poolState->_largestFreeEntry, lowChunkSize);
poolState->_previousFreeEntry = (MM_HeapLinkedFreeHeader *)currentFreeBase;
poolState->_previousFreeEntrySize = lowChunkSize;
} else {
lowPool->abandonHeapChunk(currentFreeBase, (uint8_t *)currentFreeBase + lowChunkSize);
}
/* Did range span top of current pool ? */
if(NULL != highAddr) {
/* calculate size of high chunk while we know base of low chunk..*/
highChunkSize = ((uint8_t *)currentFreeBase + currentFreeSize) - (uint8_t*)highAddr;
/* Then flush all statistics for current pool */
flushPool(env, poolState);
/* Reset all stats data for next pool */
poolState->clear();
highPool = memorySubSpace->getMemoryPool(highAddr);
poolState->_memoryPool = highPool;
if ( highChunkSize > highPool->getMinimumFreeEntrySize()) {
/* this must be first free chunk in this pool */
poolState->_freeListHead = (MM_HeapLinkedFreeHeader *)highAddr;
highPool->createFreeEntry(env, highAddr, (uint8_t *)highAddr + highChunkSize, NULL, NULL);
/* Update chunk stats */
poolState->_freeBytes += highChunkSize;
poolState->_freeHoles += 1;
poolState->_largestFreeEntry = OMR_MAX(poolState->_largestFreeEntry, highChunkSize);
poolState->_previousFreeEntry = (MM_HeapLinkedFreeHeader *)highAddr;
poolState->_previousFreeEntrySize = highChunkSize;
} else {
highPool->abandonHeapChunk(highAddr, (uint8_t *)highAddr + highChunkSize);
}
}
}
void
MM_CompactScheme::moveObjects(MM_EnvironmentStandard *env, uintptr_t &objectCount, uintptr_t &byteCount, uintptr_t &skippedObjectCount)
{
MM_HeapRegionManager *regionManager = _heap->getHeapRegionManager();
GC_HeapRegionIteratorStandard regionIterator(regionManager);
MM_HeapRegionDescriptorStandard *region = NULL;
SubAreaEntry *subAreaTable = _subAreaTable;
while(NULL != (region = regionIterator.nextRegion())) {
if (!region->isCommitted() || (0 == region->getSize())) {
continue;
}
intptr_t i;
for (i = 0; subAreaTable[i].state != SubAreaEntry::end_segment; i++) {
if (changeSubAreaAction(env, &subAreaTable[i], SubAreaEntry::evacuating)) {
evacuateSubArea(env, region, subAreaTable, i, objectCount, byteCount, skippedObjectCount);
}
}
/* Number of regions in regionTable, including
* the end_segment region, is i+1 */
subAreaTable += (i+1);
}
}
/* Create two free chunks: the first is (from:to_aligned), and the second
* is (to_aligned:to), where to_aligned=ALIGN(to,page_size). Return the size
* of the FIRST chunk (if exists), or zero otherwise.
*
* The idea behind the two chunks is that the second chunk is discarded to
* prevent race conditions on multi-thread evacuation.
*/
size_t
MM_CompactScheme::setFreeChunkPageAligned(omrobjectptr_t from, omrobjectptr_t to)
{
assume0(from && to);
omrobjectptr_t to_aligned = pageStart(pageIndex(to));
if (from >= to_aligned) {
/* This is the special case where only the SECOND of the two
* chunks is created. Return value is 0... think of the first
* chunk as having zero length.
*/
setFreeChunk(from, to);
return 0;
}
if (to == to_aligned) {
/* Here only the FIRST of the two free chunks is created.*/
return setFreeChunk(from, to_aligned);
}
/* Both free chunks are created; returned size of the FIRST one. */
setFreeChunk(to_aligned, to);
return setFreeChunk(from, to_aligned);
}
void
MM_CompactScheme::evacuateSubArea(MM_EnvironmentStandard *env, MM_HeapRegionDescriptorStandard *subAreaRegion, SubAreaEntry *subAreaTableEvacuate, intptr_t i, uintptr_t &objectCount, uintptr_t &byteCount, uintptr_t &skippedObjectCount)
{
uintptr_t minFreeChunk = _extensions->tlhMinimumSize;
if (subAreaTableEvacuate[i].state != SubAreaEntry::init) {
Assert_MM_true(subAreaTableEvacuate[i].state == SubAreaEntry::fixup_only);
return;
}
uintptr_t nobjects = 0;
uintptr_t nbytes = 0;
omrobjectptr_t freeChunk;
omrobjectptr_t firstObject = subAreaTableEvacuate[i].firstObject;
omrobjectptr_t endObject = subAreaTableEvacuate[i+1].firstObject;
omrobjectptr_t objectPtr = firstObject;
MM_MemorySubSpace *subspace = subAreaRegion->getSubSpace();
intptr_t j = -1;
do {
freeChunk = 0;
for (j++; j < i; j++) { // keeps searching from the prev. value to prevent inf loop
if ((subAreaTableEvacuate[j].state == SubAreaEntry::ready) &&
(SubAreaEntry::ready == MM_AtomicOperations::lockCompareExchange(&subAreaTableEvacuate[j].state, SubAreaEntry::ready, SubAreaEntry::busy)))
{
MM_AtomicOperations::loadSync();
freeChunk = subAreaTableEvacuate[j].freeChunk;
break;
}
}
if (j == i) {
/* freeChunk == 0 */
break; // can't evacuate
}
nobjects = nbytes = 0;
objectPtr = doCompact(env, subspace, objectPtr, endObject, freeChunk, nobjects, nbytes, true);
/* Free chunks initially get into the table after compaction,
* so the problematic last page had already been truncated by now.
*/
size_t size = getFreeChunkSize(freeChunk);
subAreaTableEvacuate[j].freeChunk = freeChunk;
Trc_MM_CompactScheme_evacuateSubArea_evacuated(env->getLanguageVMThread(), firstObject, endObject, nbytes, subAreaTableEvacuate[j].firstObject);
if (size < minFreeChunk) {
Trc_MM_CompactScheme_evacuateSubArea_bytesRemainingIgnored(env->getLanguageVMThread(), size, subAreaTableEvacuate[j].firstObject);
} else {
Trc_MM_CompactScheme_evacuateSubArea_bytesRemaining(env->getLanguageVMThread(), size, subAreaTableEvacuate[j].firstObject);
}
objectCount += nobjects;
byteCount += nbytes;
/* change state from 'busy' to 'ready' or 'full' */
MM_AtomicOperations::storeSync();
if (size < minFreeChunk) {
uintptr_t state = MM_AtomicOperations::lockCompareExchange(&subAreaTableEvacuate[j].state, SubAreaEntry::busy, SubAreaEntry::full);
Assert_MM_true(state == SubAreaEntry::busy);
}
else {
uintptr_t state = MM_AtomicOperations::lockCompareExchange(&subAreaTableEvacuate[j].state, SubAreaEntry::busy, SubAreaEntry::ready);
Assert_MM_true(state == SubAreaEntry::busy);
}
} while (objectPtr);
if (objectPtr == 0) {
/* All objects in the sub area were successfully evacuated. */
size_t size = setFreeChunkPageAligned(firstObject, endObject);
if (size < minFreeChunk) {
Trc_MM_CompactScheme_evacuateSubArea_subAreaFullIgnored(env->getLanguageVMThread(), firstObject, endObject, size);
} else {
Trc_MM_CompactScheme_evacuateSubArea_subAreaFull(env->getLanguageVMThread(), firstObject, endObject, size);
}
subAreaTableEvacuate[i].freeChunk = firstObject;
MM_AtomicOperations::storeSync();
if (size < minFreeChunk) {
uintptr_t state = MM_AtomicOperations::lockCompareExchange(&subAreaTableEvacuate[i].state, SubAreaEntry::init, SubAreaEntry::full);
Assert_MM_true(state == SubAreaEntry::init);
} else {
uintptr_t state = MM_AtomicOperations::lockCompareExchange(&subAreaTableEvacuate[i].state, SubAreaEntry::init, SubAreaEntry::ready);
Assert_MM_true(state == SubAreaEntry::init);
}
return;
}
if (objectPtr == firstObject) { // nothing evacuated
/* Skip over the objects in the beginning of the sub area until
* the first empty bubble is found. Usually, sub areas start with
* an object, but the first sub area is an exception. It starts with
* segment->heapBase even if there is no object there. In that case,
* the number of skipped objects is zero.
*/
GC_ObjectHeapIteratorAddressOrderedList objectHeapIterator(_extensions, firstObject, pageStart(pageIndex(endObject)), true);
omrobjectptr_t lastLive = firstObject;
while (NULL != (objectPtr = objectHeapIterator.nextObject())) {
if (objectHeapIterator.isDeadObject() || !_markMap->isBitSet(objectPtr)) {
break;
}
lastLive = objectPtr;
skippedObjectCount++;
}
/* We found the first free chunk in the sub area.
* It is pointed to by objectPtr, unless it is zero,
* which means that the sub area contains no free chunks.
*/
if (objectPtr == 0) {
subAreaTableEvacuate[i].freeChunk = 0;
omrobjectptr_t lastLiveEnd = (omrobjectptr_t)((uintptr_t)lastLive + _extensions->objectModel.getConsumedSizeInBytesWithHeader(lastLive));
Assert_MM_true(lastLiveEnd >= pageStart(pageIndex(endObject)) && lastLiveEnd <= endObject);
setFreeChunk(lastLiveEnd, endObject);