-
Notifications
You must be signed in to change notification settings - Fork 392
/
ParallelGlobalGC.cpp
1899 lines (1609 loc) · 69.1 KB
/
ParallelGlobalGC.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"
#include "omrmodroncore.h"
#include "gcutils.h"
#include "ModronAssertions.h"
#include "modronbase.h"
#include "modronopt.h"
#include "modronapicore.hpp"
#include "AllocateDescription.hpp"
#include "AllocationFailureStats.hpp"
#include "CollectionStatisticsStandard.hpp"
#include "CollectorLanguageInterface.hpp"
#if defined(OMR_GC_MODRON_COMPACTION)
#include "CompactScheme.hpp"
#endif /* OMR_GC_MODRON_COMPACTION */
#include "Configuration.hpp"
#include "CycleState.hpp"
#include "EnvironmentBase.hpp"
#include "GlobalAllocationManager.hpp"
#include "Heap.hpp"
#include "HeapMapIterator.hpp"
#include "HeapRegionDescriptorStandard.hpp"
#include "HeapRegionIteratorStandard.hpp"
#include "MarkingScheme.hpp"
#include "MemorySpace.hpp"
#include "MemorySubSpace.hpp"
#include "MemorySubSpaceSemiSpace.hpp"
#include "MemoryPoolLargeObjects.hpp"
#include "ObjectAllocationInterface.hpp"
#if defined(OMR_GC_OBJECT_MAP)
#include "ObjectMap.hpp"
#endif /* defined(OMR_GC_OBJECT_MAP) */
#include "OMRVMInterface.hpp"
#include "ObjectIterator.hpp"
#if defined(OMR_GC_MODRON_COMPACTION)
#include "ParallelCompactTask.hpp"
#endif /* OMR_GC_MODRON_COMPACTION */
#include "ParallelDispatcher.hpp"
#include "ParallelGlobalGC.hpp"
#include "ParallelMarkTask.hpp"
#include "ParallelSweepScheme.hpp"
#include "ParallelTask.hpp"
#if defined(OMR_GC_MODRON_SCAVENGER)
#include "Scavenger.hpp"
#endif /* OMR_GC_MODRON_SCAVENGER */
#include "WorkPackets.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_VALGRIND_MEMCHECK)
#include "MemcheckWrapper.hpp"
#endif /* defined(OMR_VALGRIND_MEMCHECK) */
#if defined(OMR_ENV_DATA64) && defined(OMR_GC_FULL_POINTERS)
void
poisonReferenceSlot(MM_EnvironmentBase *env, GC_SlotObject *slotObject)
{
MM_GCExtensionsBase *extensions = env->getExtensions();
uintptr_t heapBase = (uintptr_t)extensions->heap->getHeapBase();
uintptr_t heapTop = (uintptr_t)extensions->heap->getHeapTop();
uintptr_t referenceFromSlot = (uintptr_t)slotObject->readReferenceFromSlot();
if ((heapTop > referenceFromSlot) && (heapBase <= referenceFromSlot)) {
uintptr_t shadowHeapBase = (uintptr_t)extensions->shadowHeapBase;
uintptr_t poisonedAddress = shadowHeapBase + (referenceFromSlot - heapBase);
slotObject->writeReferenceToSlot((omrobjectptr_t)poisonedAddress);
}
}
void
poisonReferenceSlots(OMR_VMThread *omrVMThread, MM_HeapRegionDescriptor *region, omrobjectptr_t object, void *userData)
{
GC_ObjectIterator objectIterator(omrVMThread->_vm, object);
GC_SlotObject *slotObject = NULL;
MM_EnvironmentBase *env = MM_EnvironmentBase::getEnvironment(omrVMThread);
while (NULL != (slotObject = objectIterator.nextSlot())) {
poisonReferenceSlot(env, slotObject);
}
}
void
healReferenceSlot(MM_EnvironmentBase *env, GC_SlotObject *slotObject)
{
MM_GCExtensionsBase *extensions = env->getExtensions();
uintptr_t shadowHeapBase = (uintptr_t)extensions->shadowHeapBase;
uintptr_t referenceFromSlot = (uintptr_t)slotObject->readReferenceFromSlot();
uintptr_t shadowHeapTop = (uintptr_t)extensions->shadowHeapTop;
if ((shadowHeapTop > referenceFromSlot) && (shadowHeapBase <= referenceFromSlot)) {
uintptr_t heapBase = (uintptr_t)extensions->heap->getHeapBase();
uintptr_t healedHeapAddress = heapBase + (referenceFromSlot - shadowHeapBase);
/* This healing occurs at the start of GC, hence, does not need atomic write */
slotObject->writeReferenceToSlot((omrobjectptr_t)healedHeapAddress);
}
}
void
healReferenceSlots(OMR_VMThread *omrVMThread, MM_HeapRegionDescriptor *region, omrobjectptr_t object, void *userData)
{
GC_ObjectIterator objectIterator(omrVMThread->_vm, object);
GC_SlotObject *slotObject = NULL;
MM_EnvironmentBase *env = MM_EnvironmentBase::getEnvironment(omrVMThread);
while (NULL != (slotObject = objectIterator.nextSlot())) {
healReferenceSlot(env, slotObject);
}
}
#endif /* defined(OMR_ENV_DATA64) && defined(OMR_GC_FULL_POINTERS) */
/* Define hook routines to be called on AF start and End */
static void globalGCHookAFCycleStart(J9HookInterface** hook, uintptr_t eventNum, void* eventData, void* userData);
static void globalGCHookAFCycleEnd(J9HookInterface** hook, uintptr_t eventNum, void* eventData, void* userData);
#if defined(OMR_GC_MODRON_CONCURRENT_MARK)
static void globalGCHookCCStart(J9HookInterface** hook, uintptr_t eventNum, void* eventData, void* userData);
static void globalGCHookCCEnd(J9HookInterface** hook, uintptr_t eventNum, void* eventData, void* userData);
#endif /* OMR_GC_MODRON_CONCURRENT_MARK */
static void globalGCHookSysStart(J9HookInterface** hook, uintptr_t eventNum, void* eventData, void* userData);
static void globalGCHookSysEnd(J9HookInterface** hook, uintptr_t eventNum, void* eventData, void* userData);
/**
* Function to fix single dead object on the heap
*
* NOTE that this function is expected to represent the SUPERSET of dead object fixup needs in that it will
* fix all objects which are known to be dead. Any optimizations to this function must be careful not to
* violate that meaning (see CMVC 122959 for an example of such a mistake).
*/
static void
fixObject(OMR_VMThread *omrVMThread, MM_HeapRegionDescriptor *region, omrobjectptr_t object, void *userData)
{
MM_GCExtensionsBase *extensions = MM_GCExtensionsBase::getExtensions(omrVMThread->_vm);
MM_ParallelGlobalGC *collector = (MM_ParallelGlobalGC *)extensions->getGlobalCollector();
/* Check the mark state of each object. If it isn't marked, build a dead object */
if( !collector->getMarkingScheme()->isMarked(object) ) {
MM_MemorySubSpace *memorySubSpace = region->getSubSpace();
uintptr_t deadObjectByteSize = extensions->objectModel.getConsumedSizeInBytesWithHeader(object);
#if defined(OMR_VALGRIND_MEMCHECK)
/* Also clear dead object from valgrind pool
* This could have been done directly inside internalRecycleHeapChunk (MemoryPoolAddressOrderedListBase.hpp)
* but due to current limitation of API that requires address of object to be freed
* which we need to check from a set stored in extensions, which weren't further passed
* we will check it here. But in case new API is added, it is better to move there.
*/
if(valgrindCheckObjectInPool(extensions,(uintptr_t) object))
valgrindFreeObject(extensions,(uintptr_t) object);
#endif /* defined(OMR_VALGRIND_MEMCHECK) */
memorySubSpace->abandonHeapChunk(object, ((U_8*)object) + deadObjectByteSize);
/* the userdata is a counter of dead objects fixed up so increment it here as a uintptr_t */
*((uintptr_t *)userData) += 1;
}
}
#if defined(OMR_GC_MODRON_SCAVENGER)
/**
* Fix the heap if the remembered set for the scavenger is in an overflow state.
*/
static void
hookGlobalGcSweepEndRsoSafetyFixHeap(J9HookInterface** hook, uintptr_t eventNum, void* eventData, void* userData)
{
MM_SweepEndEvent* event = (MM_SweepEndEvent*)eventData;
MM_EnvironmentBase *env = MM_EnvironmentBase::getEnvironment(event->currentThread);
MM_GCExtensionsBase *extensions = env->getExtensions();
extensions->scavengerRsoScanUnsafe = !extensions->isRememberedSetInOverflowState();
if (!extensions->scavengerRsoScanUnsafe) {
MM_ParallelGlobalGC *pggc = (MM_ParallelGlobalGC *)userData;
pggc->fixHeapForWalk(env, MEMORY_TYPE_OLD_RAM, FIXUP_DEBUG_TOOLING, fixObject);
}
}
#if defined(OMR_GC_CONCURRENT_SCAVENGER)
static void
hookGlobalGcSweepEndAbortedCSFixHeap(J9HookInterface** hook, UDATA eventNum, void* eventData, void* userData)
{
MM_SweepEndEvent* event = (MM_SweepEndEvent*)eventData;
MM_EnvironmentStandard *env = MM_EnvironmentStandard::getEnvironment(event->currentThread);
MM_GCExtensionsBase *extensions = env->getExtensions();
uintptr_t holeCount = 0;
Trc_MM_FixHeapForWalk_Entry(env->getLanguageVMThread(), MEMORY_TYPE_NEW);
if (extensions->isScavengerBackOutFlagRaised()) {
GC_HeapRegionIteratorStandard regionIterator(extensions->getHeap()->getHeapRegionManager());
MM_HeapRegionDescriptorStandard *region = NULL;
/* create holes between two marked objects */
while(NULL != (region = regionIterator.nextRegion())) {
if (MEMORY_TYPE_NEW == (region->getTypeFlags() & MEMORY_TYPE_NEW)) {
void *lowAddress = region->getLowAddress();
void *highAddress = region->getHighAddress();
MM_HeapMapIterator markedObjectIterator(extensions, ((MM_ParallelGlobalGC *)extensions->getGlobalCollector())->getMarkingScheme()->getMarkMap(), (UDATA *)lowAddress, (UDATA *)highAddress);
void * prevEndObjectPtr = lowAddress;
omrobjectptr_t objectPtr = NULL;
while (NULL != (objectPtr = markedObjectIterator.nextObject())) {
UDATA objectSize = extensions->objectModel.getConsumedSizeInBytesWithHeader(objectPtr);
if (prevEndObjectPtr != objectPtr) {
region->getSubSpace()->abandonHeapChunk(prevEndObjectPtr, objectPtr);
holeCount += 1;
}
prevEndObjectPtr = (void *)((U_8*)objectPtr + objectSize);
}
if (prevEndObjectPtr != highAddress) {
region->getSubSpace()->abandonHeapChunk(prevEndObjectPtr, highAddress);
holeCount += 1;
}
}
}
}
Trc_MM_FixHeapForWalk_Exit(env->getLanguageVMThread(), holeCount);
}
#endif /* OMR_GC_CONCURRENT_SCAVENGER */
#endif /* OMR_GC_MODRON_SCAVENGER */
/**
* Initialization
*/
MM_ParallelGlobalGC *
MM_ParallelGlobalGC::newInstance(MM_EnvironmentBase *env)
{
MM_ParallelGlobalGC *globalGC;
globalGC = (MM_ParallelGlobalGC *)env->getForge()->allocate(sizeof(MM_ParallelGlobalGC), OMR::GC::AllocationCategory::FIXED, OMR_GET_CALLSITE());
if (globalGC) {
new(globalGC) MM_ParallelGlobalGC(env);
if (!globalGC->initialize(env)) {
globalGC->kill(env);
globalGC = NULL;
}
}
return globalGC;
}
void
MM_ParallelGlobalGC::kill(MM_EnvironmentBase *env)
{
tearDown(env);
env->getForge()->free(this);
}
/**
* Initialize the collector's internal structures and values.
* @return true if initialization completed, false otherwise
*/
bool
MM_ParallelGlobalGC::initialize(MM_EnvironmentBase *env)
{
J9HookInterface** mmPrivateHooks = J9_HOOK_INTERFACE(_extensions->privateHookInterface);
if (gc_policy_nogc == env->getExtensions()->configurationOptions._gcPolicy) {
_cycleType = OMR_GC_CYCLE_TYPE_EPSILON;
_disableGC = true;
}
_markingScheme = MM_MarkingScheme::newInstance(env);
if (NULL == _markingScheme) {
goto error_no_memory;
}
_delegate.initialize(env, this, _markingScheme);
_sweepScheme = createSweepScheme(env, this);
if (NULL == _sweepScheme) {
goto error_no_memory;
}
#if defined(OMR_GC_OBJECT_MAP)
_extensions->setObjectMap(MM_ObjectMap::newInstance(env));
if(NULL == _extensions->getObjectMap()) {
goto error_no_memory;
}
#endif /* defined(OMR_GC_OBJECT_MAP) */
#if defined(OMR_GC_MODRON_COMPACTION)
_compactScheme = MM_CompactScheme::newInstance(env, _markingScheme);
if(NULL == _compactScheme) {
goto error_no_memory;
}
#endif /* defined(OMR_GC_MODRON_COMPACTION) */
_heapWalker = MM_ParallelHeapWalker::newInstance(this, _markingScheme->getMarkMap(), env);
if (NULL == _heapWalker) {
goto error_no_memory;
}
/* Attach to hooks required by the global collector's
* heap resize (expand/contraction) functions
*/
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_ALLOCATION_FAILURE_CYCLE_START, globalGCHookAFCycleStart, OMR_GET_CALLSITE(), NULL);
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_ALLOCATION_FAILURE_CYCLE_END, globalGCHookAFCycleEnd, OMR_GET_CALLSITE(), NULL);
#if defined(OMR_GC_MODRON_CONCURRENT_MARK)
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_CONCURRENT_COLLECTION_START, globalGCHookCCStart, OMR_GET_CALLSITE(), NULL);
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_CONCURRENT_COLLECTION_END, globalGCHookCCEnd, OMR_GET_CALLSITE(), NULL);
#endif /* OMR_GC_MODRON_CONCURRENT_MARK */
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_SYSTEM_GC_START, globalGCHookSysStart, OMR_GET_CALLSITE(), NULL);
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_SYSTEM_GC_END, globalGCHookSysEnd, OMR_GET_CALLSITE(), NULL);
#if defined(OMR_GC_MODRON_SCAVENGER)
if (_extensions->scavengerEnabled) {
/* Hook the global collector to guarantee heap walk safety in the event of an RSO */
/* NOTE: This will be a one time hook across all instances as the function and user data will be identical - i.e.,
* we will only get one Hook registered no matter how many scavengers are created/initialized
*/
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_SWEEP_END, hookGlobalGcSweepEndRsoSafetyFixHeap, OMR_GET_CALLSITE(), this);
#if defined(OMR_GC_CONCURRENT_SCAVENGER)
if (_extensions->isConcurrentScavengerEnabled()) {
(*mmPrivateHooks)->J9HookRegisterWithCallSite(mmPrivateHooks, J9HOOK_MM_PRIVATE_SWEEP_END, hookGlobalGcSweepEndAbortedCSFixHeap, OMR_GET_CALLSITE(), this);
}
#endif /* OMR_GC_CONCURRENT_SCAVENGER */
}
#endif /* OMR_GC_MODRON_SCAVENGER */
return true;
error_no_memory:
return false;
}
/**
* Free any internal structures associated to the receiver.
*/
void
MM_ParallelGlobalGC::tearDown(MM_EnvironmentBase *env)
{
_delegate.tearDown(env);
if(NULL != _markingScheme) {
_markingScheme->kill(env);
_markingScheme = NULL;
}
if(NULL != _sweepScheme) {
_sweepScheme->kill(env);
_sweepScheme = NULL;
}
#if defined(OMR_GC_MODRON_COMPACTION)
if(NULL != _compactScheme) {
_compactScheme->kill(env);
_compactScheme = NULL;
}
#endif /* OMR_GC_MODRON_COMPACTION */
if (NULL != _heapWalker) {
_heapWalker->kill(env);
_heapWalker = NULL;
}
}
uintptr_t
MM_ParallelGlobalGC::getVMStateID()
{
return OMRVMSTATE_GC_COLLECTOR_GLOBALGC;
}
/****************************************
* Thread work routines
****************************************
*/
void
MM_ParallelGlobalGC::cleanupAfterGC(MM_EnvironmentBase *env, MM_AllocateDescription *allocDescription)
{
updateTuningStatistics(env);
/* Perform the resize now. The decision was earlier */
env->_cycleState->_activeSubSpace->performResize(env, allocDescription);
/* Heap size now fixed for next cycle so reset heap statistics */
_extensions->heap->resetHeapStatistics(true);
#if defined(OMR_GC_MODRON_SCAVENGER)
GC_OMRVMThreadListIterator threadIterator(_extensions->getOmrVM());
OMR_VMThread *walkThread = NULL;
/* Null tenure TLH (Copy Cache) references for all GC worker and Mutator (for concurrent scavenger) threads as the memory will be invalidated on sweep cycle*/
while((walkThread = threadIterator.nextOMRVMThread()) != NULL) {
MM_EnvironmentStandard *threadEnvironment = MM_EnvironmentStandard::getEnvironment(walkThread);
threadEnvironment->_tenureTLHRemainderBase = NULL;
threadEnvironment->_tenureTLHRemainderTop = NULL;
}
_extensions->_mainThreadTenureTLHRemainderTop = NULL;
_extensions->_mainThreadTenureTLHRemainderBase = NULL;
#endif /* OMR_GC_MODRON_SCAVENGER */
}
void
MM_ParallelGlobalGC::mainThreadGarbageCollect(MM_EnvironmentBase *env, MM_AllocateDescription *allocDescription, bool initMarkMap, bool rebuildMarkBits)
{
if (_extensions->trackMutatorThreadCategory) {
/* This thread is doing GC work, account for the time spent into the GC bucket */
omrthread_set_category(env->getOmrVMThread()->_os_thread, J9THREAD_CATEGORY_SYSTEM_GC_THREAD, J9THREAD_TYPE_SET_GC);
}
/* Perform any main-specific setup */
/* Tell the GAM to flush its contexts */
MM_GlobalAllocationManager *gam = _extensions->globalAllocationManager;
if (NULL != gam) {
gam->flushAllocationContexts(env);
}
/* ----- start of setupForCollect ------*/
/* ensure heap base is aligned to region size */
uintptr_t heapBase = (uintptr_t)_extensions->heap->getHeapBase();
uintptr_t regionSize = _extensions->regionSize;
Assert_MM_true((0 != regionSize) && (0 == (heapBase % regionSize)));
/* Reset memory pools of associated memory spaces */
_extensions->heap->resetSpacesForGarbageCollect(env);
/* Clear the gc stats structure */
_extensions->globalGCStats.clear();
#if defined(OMR_GC_MODRON_COMPACTION)
_compactThisCycle = false;
#endif /* OMR_GC_MODRON_COMPACTION */
_fixHeapForWalkCompleted = false;
_delegate.mainThreadGarbageCollectStarted(env);
/* ----- end of setupForCollect ------*/
/* Run a garbage collect */
/* Mark */
markAll(env, initMarkMap);
_delegate.postMarkProcessing(env);
sweep(env, allocDescription, rebuildMarkBits);
#if defined(OMR_GC_MODRON_COMPACTION)
/* If a compaction was required, then do one */
if (_compactThisCycle) {
_collectionStatistics._tenureFragmentation = MICRO_FRAGMENTATION;
if (GLOBALGC_ESTIMATE_FRAGMENTATION == (_extensions->estimateFragmentation & GLOBALGC_ESTIMATE_FRAGMENTATION)) {
_collectionStatistics._tenureFragmentation |= MACRO_FRAGMENTATION;
}
mainThreadCompact(env, allocDescription, rebuildMarkBits);
_collectionStatistics._tenureFragmentation = NO_FRAGMENTATION;
if (_extensions->processLargeAllocateStats) {
processLargeAllocateStatsAfterCompact(env);
}
} else {
/* If a compaction was prevented, report the reason */
CompactPreventedReason compactPreventedReason = (CompactPreventedReason)(_extensions->globalGCStats.compactStats._compactPreventedReason);
if(COMPACT_PREVENTED_NONE != compactPreventedReason) {
MM_CompactStats *compactStats = &_extensions->globalGCStats.compactStats;
reportCompactStart(env);
Trc_MM_CompactPrevented(env->getLanguageVMThread(), getCompactionPreventedReasonAsString(compactPreventedReason));
compactStats->_startTime = 0;
compactStats->_endTime = 0;
reportCompactEnd(env);
}
_collectionStatistics._tenureFragmentation = MICRO_FRAGMENTATION;
if (GLOBALGC_ESTIMATE_FRAGMENTATION == (_extensions->estimateFragmentation & GLOBALGC_ESTIMATE_FRAGMENTATION)) {
_collectionStatistics._tenureFragmentation |= MACRO_FRAGMENTATION;
}
}
#endif /* defined(OMR_GC_MODRON_COMPACTION) */
bool compactedThisCycle = false;
#if defined(OMR_GC_MODRON_COMPACTION)
compactedThisCycle = _compactThisCycle;
#endif /* OMR_GC_MODRON_COMPACTION */
/* If the delegate has isAllowUserHeapWalk set, fix the heap so that it can be walked */
if (_delegate.isAllowUserHeapWalk() || env->_cycleState->_gcCode.isRASDumpGC()) {
if (!_fixHeapForWalkCompleted) {
#if defined(OMR_GC_MODRON_COMPACTION)
if (compactedThisCycle) {
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
U_64 startTime = omrtime_hires_clock();
getCompactScheme(env)->fixHeapForWalk(env);
_extensions->globalGCStats.fixHeapForWalkTime = omrtime_hires_delta(startTime, omrtime_hires_clock(), OMRPORT_TIME_DELTA_IN_MICROSECONDS);
_extensions->globalGCStats.fixHeapForWalkReason = FIXUP_DEBUG_TOOLING;
} else
#endif /* OMR_GC_MODRON_COMPACTION */
{
fixHeapForWalk(env, MEMORY_TYPE_RAM, FIXUP_DEBUG_TOOLING, fixObject);
}
/* since this is the superset of all walk operations, we can safely set the flag that states other walks
* can be omitted for this cycle as redundant (CMVC 122959)
*/
_fixHeapForWalkCompleted = true;
}
}
_delegate.mainThreadGarbageCollectFinished(env, compactedThisCycle);
#if defined(OMR_GC_MODRON_COMPACTION)
if (compactedThisCycle) {
/* Free space will have changed as a result of compaction so recalculate
* any expand or contract target.
* Concurrent Scavenger requires this be done after fixup heap for walk pass.
*/
env->_cycleState->_activeSubSpace->checkResize(env, allocDescription, env->_cycleState->_gcCode.isExplicitGC());
}
#endif
#if defined(OMR_GC_MODRON_SCAVENGER)
/* Merge sublists in the remembered set (if necessary) */
_extensions->rememberedSet.compact(env);
_extensions->oldHeapSizeOnLastGlobalGC = _extensions->heap->getActiveMemorySize(MEMORY_TYPE_OLD);
_extensions->freeOldHeapSizeOnLastGlobalGC = _extensions->heap->getApproximateActiveFreeMemorySize(MEMORY_TYPE_OLD);
#endif /* OMR_GC_MODRON_SCAVENGER */
/* Restart the allocation caches associated to all threads */
mainThreadRestartAllocationCaches(env);
/* ----- start of cleanupAfterCollect ------*/
reportGlobalGCCollectComplete(env);
cleanupAfterGC(env, allocDescription);
if (_extensions->trackMutatorThreadCategory) {
/* Done doing GC, reset the category back to the old one */
omrthread_set_category(env->getOmrVMThread()->_os_thread, 0, J9THREAD_TYPE_SET_GC);
}
}
#if defined(OMR_GC_MODRON_COMPACTION)
bool
MM_ParallelGlobalGC::shouldCompactThisCycle(MM_EnvironmentBase *env, MM_AllocateDescription *allocDescription, uintptr_t activeSubspaceMaxExpansionInSpace, MM_GCCode gcCode)
{
MM_Heap *heap = _extensions->heap;
MM_AllocationStats *allocStats = &_extensions->allocationStats;
CompactReason compactReason = COMPACT_NONE;
CompactPreventedReason compactPreventedReason = COMPACT_PREVENTED_NONE;
uintptr_t tlhPercent, totalBytesAllocated;
/* Assume no compaction is required until we prove otherwise*/
/* If user has specified -XnoCompact then were done */
if(_extensions->noCompactOnGlobalGC) {
compactReason = COMPACT_NONE;
goto nocompact;
}
#if defined(OMR_GC_IDLE_HEAP_MANAGER)
if((_extensions->compactOnIdle) && (J9MMCONSTANT_EXPLICIT_GC_IDLE_GC == gcCode.getCode())) {
compactReason = COMPACT_FORCED_GC;
goto compactionReqd;
}
#endif
/* RAS dump compact requests override all other options. If a dump agent requested
* a compact we always honour it in order to produce optimal heap dumps
*/
if (J9MMCONSTANT_EXPLICIT_GC_RASDUMP_COMPACT == gcCode.getCode()) {
compactReason = COMPACT_FORCED_GC;
goto compactionReqd;
}
/* If user has specified -XCompact then we compact every time */
if(_extensions->compactOnGlobalGC) {
compactReason = COMPACT_ALWAYS;
goto compactionReqd;
}
/* Aborted CS needs global GC with Nursery compaction */
if (_extensions->isConcurrentScavengerEnabled() && _extensions->isScavengerBackOutFlagRaised()) {
compactReason = COMPACT_ABORTED_SCAVENGE;
goto compactionReqd;
}
/* Is this a system GC ? */
if(gcCode.isExplicitGC()) {
/* If the user as specified -XcompactexplicitGC then compact*/
if(_extensions->compactOnSystemGC){
compactReason = COMPACT_FORCED_GC;
goto compactionReqd;
} else if(_extensions->nocompactOnSystemGC){
compactReason = COMPACT_NONE;
/* The user as specified -XnocompactexplicitGC then we don't compact*/
goto nocompact;
}
}
/* Has GC found enough storage to satisfy the allocation request ? */
if(allocDescription){
MM_MemorySpace *memorySpace = env->getMemorySpace();
uintptr_t largestFreeEntry = memorySpace->findLargestFreeEntry(env, allocDescription);
uintptr_t bytesRequested = allocDescription->getBytesRequested();
if(bytesRequested > largestFreeEntry){
compactReason = COMPACT_LARGE;
goto compactionReqd;
}
}
/* If -Xgc:compactToSatisfyAllocate has been specified, then we skip the rest of the triggers */
if (_extensions->compactToSatisfyAllocate) {
compactReason = COMPACT_NONE;
goto nocompact;
}
#if defined(OMR_GC_MODRON_SCAVENGER)
if (_extensions->scavengerEnabled) {
/* Get size of largest object we failed to tenure on last scavenege */
uintptr_t failedTenureLargest = _extensions->scavengerStats._failedTenureLargest;
if (failedTenureLargest > 0) {
MM_MemorySpace *memorySpace = env->getMemorySpace();
MM_AllocateDescription tenureAllocDescription(failedTenureLargest, OMR_GC_ALLOCATE_OBJECT_TENURED, false, true);
uintptr_t largestTenureFreeEntry = memorySpace->findLargestFreeEntry(env, &tenureAllocDescription);
if(failedTenureLargest > largestTenureFreeEntry){
compactReason = COMPACT_LARGE;
goto compactionReqd;
}
}
}
#endif /* OMR_GC_MODRON_SCAVENGER */
/* If this is an aggressive collect and the last collect did not compact then
* make sure we do this time.
*/
if (gcCode.isAggressiveGC() &&
(_extensions->globalGCStats.compactStats._lastHeapCompaction + 1 < _extensions->globalGCStats.gcCount)) {
compactReason = COMPACT_AGGRESSIVE;
goto compactionReqd;
}
#if defined(OMR_GC_THREAD_LOCAL_HEAP)
/* Now check for signs of fragmentation by checking the average size of TLH
* allocated since the last global collection
*/
if (allocStats->_tlhRefreshCountFresh > 0) {
Assert_MM_true(allocStats->_tlhAllocatedFresh > 0);
}
/* Calculate total bytes allocated in tenure area since last global collection */
totalBytesAllocated = allocStats->_allocationBytes + allocStats->_tlhAllocatedFresh;
/* ..and what percentage of allocations were tlh's */
tlhPercent = allocStats->_tlhRefreshCountFresh > 0 ? (uintptr_t) (((uint64_t) allocStats->_tlhAllocatedFresh * 100) / (uint64_t) totalBytesAllocated) : 0;
/* Check at least 50% of free space at end of last GC has been consumed by tlh allocations */
if( tlhPercent > 50 ) {
/* Calculate average size of tlh allocated since tenure area last collected */
uintptr_t avgTlh= allocStats->_tlhAllocatedFresh / allocStats->_tlhRefreshCountFresh;
/* Compaction trigger is a multiple of the minimum tlh size */
uintptr_t compaction_trigger_avgtlh= _extensions->tlhMinimumSize * MINIMUM_TLHSIZE_MULTIPLIER;
if(avgTlh < compaction_trigger_avgtlh) {
compactReason = COMPACT_FRAGMENTED;
goto compactionReqd;
}
}
#endif
/* We know if we get here we know:
* o we can meet the allocation request out of available free memory, and
* o the heap is not fragmented
*
* So if we are not fully expanded but we are low on storage there is little point doing
* a compaction, we just need to expand. However, if we are fully expanded but low
* on free memory there is little more we can do to avoid OOM at this point other than
* compact to get as much free memory as possible.
*/
if ( activeSubspaceMaxExpansionInSpace == 0) {
uintptr_t oldFree = heap->getApproximateActiveFreeMemorySize(MEMORY_TYPE_OLD);
uintptr_t oldSize = heap->getActiveMemorySize(MEMORY_TYPE_OLD);
uintptr_t desperateFree = (oldSize / OLDFREE_DESPERATE_RATIO_DIVISOR) * OLDFREE_DESPERATE_RATIO_MULTIPLIER;
/* Is heap space getting tight? */
if(oldFree < desperateFree) {
compactReason = COMPACT_AVOID_DESPERATE;
goto compactionReqd;
}
if(oldFree < OLDFREE_INSUFFICIENT ) {
compactReason = COMPACT_MEMORY_INSUFFICIENT;
goto compactionReqd;
}
}
{
/* Tenure space dark matter trigger */
MM_MemorySubSpace *memorySubSpace = heap->getDefaultMemorySpace()->getTenureMemorySubSpace();
uintptr_t totalSize = memorySubSpace->getActiveMemorySize();
MM_MemoryPool *memoryPool= memorySubSpace->getMemoryPool();
uintptr_t darkMatterBytes = 0;
if (!_extensions->concurrentSweep) {
darkMatterBytes = memoryPool->getDarkMatterBytes();
}
uintptr_t freeMemorySize = memoryPool->getActualFreeMemorySize();
/* Consider the trigger only if heap fully expanded */
if (heap->getMemorySize() == heap->getMaximumMemorySize()) {
float darkMatterRatio = ((float)darkMatterBytes)/((float)freeMemorySize + (float)totalSize / 2);
if (darkMatterRatio > _extensions->getDarkMatterCompactThreshold()) {
compactReason = COMPACT_MICRO_FRAG;
goto compactionReqd;
}
}
#if defined(OMR_GC_IDLE_HEAP_MANAGER)
if ((J9MMCONSTANT_EXPLICIT_GC_IDLE_GC == gcCode.getCode()) && (_extensions->gcOnIdle)){
MM_LargeObjectAllocateStats *stats = memoryPool->getLargeObjectAllocateStats();
uintptr_t pageSize = heap->getPageSize();
uintptr_t reusableFreeMemory = stats->getPageAlignedFreeMemory(pageSize);
uintptr_t memoryFragmentationDiff = freeMemorySize - reusableFreeMemory;
uintptr_t totalFragmentation = memoryFragmentationDiff + darkMatterBytes;
float totalFragmentationRatio = ((float)totalFragmentation)/((float)freeMemorySize + (float)totalSize / 2);
Trc_ParallelGlobalGC_shouldCompactThisCycle(env->getLanguageVMThread(), totalFragmentationRatio, _extensions->gcOnIdleCompactThreshold);
if (totalFragmentationRatio > _extensions->gcOnIdleCompactThreshold) {
compactReason = COMPACT_PAGE;
goto compactionReqd;
}
}
#endif /* OMR_GC_IDLE_HEAP_MANAGER */
}
nocompact:
/* Compaction not required or prevented from running */
_extensions->globalGCStats.compactStats._compactReason = compactReason;
_extensions->globalGCStats.compactStats._compactPreventedReason = compactPreventedReason;
return false;
compactionReqd:
compactPreventedReason = _delegate.checkIfCompactionShouldBePrevented(env);
if (COMPACT_PREVENTED_NONE != compactPreventedReason) {
goto nocompact;
}
_extensions->globalGCStats.compactStats._compactReason = compactReason;
_extensions->globalGCStats.compactStats._compactPreventedReason = compactPreventedReason;
return true;
}
/**
* Determine if a compact is required to aid contraction.
* A heap contraction is due so decide whether a compaction would be
* beneficial before we attempt to contract the heap.
* @return true if a compaction is required, false otherwise.
*/
bool
MM_ParallelGlobalGC::compactRequiredBeforeHeapContraction(MM_EnvironmentBase *env, MM_AllocateDescription *allocDescription, uintptr_t contractionSize)
{
uintptr_t lengthLastFree;
/* Assume no compaction is required until we prove otherwise*/
/* if the user specified -XnoCompact then we're done */
if (_extensions->noCompactOnGlobalGC) {
return false;
}
if (env->_cycleState->_gcCode.isExplicitGC() && _extensions->nocompactOnSystemGC){
/* if the user specified -XnocompactexplicitGC then we don't compact*/
return false;
}
uintptr_t actualSoftMx = _extensions->heap->getActualSoftMxSize(env);
if(0 != actualSoftMx) {
if(actualSoftMx < _extensions->heap->getActiveMemorySize()) {
/* a softmx has been set that's less than the current heap size - it's
* highly likely we'll need to compact in order to meet the contract, so do it */
goto compactionReqd;
}
}
/* We should compact to assist a later contraction if:
*
* - no compaction performed this GC (if we get here then we have decided not to compact for other
* reasons so non eed to check that)
* - the last GC did not do a shrink and compact
* - there is no free chunk at the end of the heap or the chunk at the end of the heap
* is less than 10% of required shrink size
*/
if((_extensions->globalGCStats.compactStats._lastHeapCompaction + 1 == _extensions->globalGCStats.gcCount) &&
(_extensions->heap->getResizeStats()->getLastHeapContractionGCCount() + 1 == _extensions->globalGCStats.gcCount)) {
return false;
}
/* Determine length of free chunk at top of heap */
/* Note: We know based on the collector that this is a single contiguous area */
lengthLastFree = env->_cycleState->_activeSubSpace->getAvailableContractionSize(env, allocDescription);
/* If chunk at end of heap is free then check its at least minimumContractionRatio percent of the
* requested contraction amount
*/
if (lengthLastFree > 0) {
uintptr_t minContractSize = (contractionSize / MINIMUM_CONTRACTION_RATIO_DIVISOR)
* _extensions->minimumContractionRatio;
if (lengthLastFree > minContractSize) {
return false;
}
}
compactionReqd:
_extensions->globalGCStats.compactStats._compactPreventedReason = _delegate.checkIfCompactionShouldBePrevented(env);
if (COMPACT_PREVENTED_NONE != _extensions->globalGCStats.compactStats._compactPreventedReason) {
return false;
}
/* If we get here we need to compact to assist the contraction.
* Remember why for verbose
*/
_extensions->globalGCStats.compactStats._compactReason = COMPACT_CONTRACT;
return true;
}
#endif /* defined(OMR_GC_MODRON_COMPACTION) */
void
MM_ParallelGlobalGC::sweep(MM_EnvironmentBase *env, MM_AllocateDescription *allocDescription, bool rebuildMarkBits)
{
OMRPORT_ACCESS_FROM_OMRPORT(env->getPortLibrary());
MM_SweepStats *sweepStats = &_extensions->globalGCStats.sweepStats;
reportSweepStart(env);
sweepStats->_startTime = omrtime_hires_clock();
mainThreadSweepStart(env, allocDescription);
if (_extensions->processLargeAllocateStats) {
processLargeAllocateStatsAfterSweep(env);
}
MM_MemorySubSpace *activeSubSpace = env->_cycleState->_activeSubSpace;
bool isExplicitGC = env->_cycleState->_gcCode.isExplicitGC();
#if defined(OMR_GC_MODRON_COMPACTION)
/* Decide is a compaction is required - this decision must be made after we sweep since we use the largestFreeEntrySize, as changed by sweep, to determine if a compaction should be done */
_compactThisCycle = shouldCompactThisCycle(env, allocDescription, activeSubSpace->maxExpansionInSpace(env), env->_cycleState->_gcCode);
if (!_compactThisCycle)
#endif /* OMR_GC_MODRON_COMPACTION */
{
/* Decide whether we need to expand or shrink the heap. If the decision is to
* shrink, we may need to force a compaction to assist the contraction.
*/
activeSubSpace->checkResize(env, allocDescription, isExplicitGC);
}
/* If we need to completely rebuild the freeelist (impending compaction or contraction), then do it */
SweepCompletionReason reason = NOT_REQUIRED;
if(completeFreelistRebuildRequired(env, &reason)) {
mainThreadSweepComplete(env, reason);
#if defined(OMR_GC_MODRON_COMPACTION)
if (!_compactThisCycle)
#endif /* OMR_GC_MODRON_COMPACTION */
{
/* We now have accurate free space statistics so recalculate any expand/contract amount
* as it will no doubt have changed
*/
activeSubSpace->checkResize(env, allocDescription, isExplicitGC);
}
}
#if defined(OMR_GC_MODRON_COMPACTION)
if (0 != activeSubSpace->getContractionSize()) {
_compactThisCycle = compactRequiredBeforeHeapContraction(env, allocDescription, activeSubSpace->getContractionSize());
}
#endif /* OMR_GC_MODRON_COMPACTION */
sweepStats->_endTime = omrtime_hires_clock();
reportSweepEnd(env);
}
bool
MM_ParallelGlobalGC::completeFreelistRebuildRequired(MM_EnvironmentBase *env, SweepCompletionReason *reason)
{
*reason = NOT_REQUIRED;
MM_MemorySubSpace *activeSubSpace = env->_cycleState->_activeSubSpace;
#if defined(OMR_GC_MODRON_COMPACTION)
if (_compactThisCycle) {
*reason = COMPACTION_REQUIRED;
} else
#endif /* OMR_GC_MODRON_COMPACTION */
if (activeSubSpace->getActiveLOAMemorySize(MEMORY_TYPE_OLD) > 0 && 0 != activeSubSpace->getExpansionSize()) {
//todo remove once we sort out how to reallocate sweep chunks if heap expands
// after a concurrent sweep cycle has started but for now we need to complete sweep
// if current LOA size is > 0.
*reason = EXPANSION_REQUIRED;
} else if (0 != activeSubSpace->getContractionSize()) {
*reason = CONTRACTION_REQUIRED;
} else if (activeSubSpace->completeFreelistRebuildRequired(env)) {
*reason = LOA_RESIZE;
} else if (env->_cycleState->_gcCode.isExplicitGC()) {
*reason = SYSTEM_GC;
}
return (*reason == NOT_REQUIRED ? false : true);
}
void
MM_ParallelGlobalGC::markAll(MM_EnvironmentBase *env, bool initMarkMap)
{
OMRPORT_ACCESS_FROM_OMRPORT(env->getPortLibrary());
MM_MarkStats *markStats = &_extensions->globalGCStats.markStats;
reportMarkStart(env);
markStats->_startTime = omrtime_hires_clock();
_markingScheme->mainSetupForGC(env);
if (env->_cycleState->_gcCode.isOutOfMemoryGC()) {
env->_cycleState->_referenceObjectOptions |= MM_CycleState::references_soft_as_weak;
}
/* run the mark */
MM_ParallelMarkTask markTask(env, _dispatcher, _markingScheme, initMarkMap, env->_cycleState);
_dispatcher->run(env, &markTask);
Assert_MM_true(_markingScheme->getWorkPackets()->isAllPacketsEmpty());
/* Do any post mark checks */
postMark(env);
_markingScheme->mainCleanupAfterGC(env);
markStats->_endTime = omrtime_hires_clock();
reportMarkEnd(env);
}
void
MM_ParallelGlobalGC::mainThreadSweepStart(MM_EnvironmentBase *env, MM_AllocateDescription *allocDescription)
{
_sweepScheme->setMarkMap(_markingScheme->getMarkMap());
_sweepScheme->sweepForMinimumSize(env, env->_cycleState->_activeSubSpace, allocDescription);
}
void
MM_ParallelGlobalGC::mainThreadSweepComplete(MM_EnvironmentBase *env, SweepCompletionReason reason)
{
_sweepScheme->completeSweep(env, reason);
}
#if defined(OMR_GC_MODRON_COMPACTION)
void
MM_ParallelGlobalGC::mainThreadCompact(MM_EnvironmentBase *env, MM_AllocateDescription *allocDescription, bool rebuildMarkBits)
{
OMRPORT_ACCESS_FROM_OMRPORT(env->getPortLibrary());
MM_CompactStats *compactStats = &_extensions->globalGCStats.compactStats;
MM_MarkMap *markMap = _markingScheme->getMarkMap();
markMap->setMarkMapValid(false);
_compactScheme->setMarkMap(markMap);
reportCompactStart(env);
compactStats->_startTime = omrtime_hires_clock();
MM_ParallelCompactTask compactTask(env, _dispatcher, _compactScheme, rebuildMarkBits, env->_cycleState->_gcCode.shouldAggressivelyCompact());
_dispatcher->run(env, &compactTask);
compactStats->_endTime = omrtime_hires_clock();
reportCompactEnd(env);
/* Remember the gc count of the last compaction */
_extensions->globalGCStats.compactStats._lastHeapCompaction= _extensions->globalGCStats.gcCount;
}