-
Notifications
You must be signed in to change notification settings - Fork 392
/
ConcurrentGC.cpp
2669 lines (2278 loc) · 92.3 KB
/
ConcurrentGC.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
*******************************************************************************/
/**
* @file
* @ingroup GC_Modron_Standard
*/
#include "omrcfg.h"
#if defined(OMR_GC_MODRON_CONCURRENT_MARK)
#define J9_EXTERNAL_TO_VM
#include "mmprivatehook.h"
#include "modronbase.h"
#include "modronopt.h"
#include "ModronAssertions.h"
#include "omr.h"
#include <string.h>
#include "AllocateDescription.hpp"
#include "AtomicOperations.hpp"
#include "CollectorLanguageInterfaceImpl.hpp"
#include "ConcurrentGC.hpp"
#include "ConcurrentCompleteTracingTask.hpp"
#include "ConcurrentClearNewMarkBitsTask.hpp"
#include "ConcurrentSafepointCallback.hpp"
#include "ConcurrentScanRememberedSetTask.hpp"
#if defined(OMR_GC_CONCURRENT_SWEEP)
#include "ConcurrentSweepScheme.hpp"
#endif /* OMR_GC_CONCURRENT_SWEEP */
#include "Configuration.hpp"
#include "CycleState.hpp"
#include "Debug.hpp"
#include "EnvironmentBase.hpp"
#include "GCExtensionsBase.hpp"
#include "Heap.hpp"
#include "HeapMapIterator.hpp"
#include "HeapRegionIterator.hpp"
#include "HeapRegionManager.hpp"
#include "MarkingScheme.hpp"
#include "Math.hpp"
#include "MemoryPool.hpp"
#include "MemorySpace.hpp"
#include "MemorySubSpace.hpp"
#include "MemorySubSpaceFlat.hpp"
#include "MemorySubSpaceSemiSpace.hpp"
#include "ObjectModel.hpp"
#include "ParallelDispatcher.hpp"
#include "SpinLimiter.hpp"
#include "SublistIterator.hpp"
#include "SublistPuddle.hpp"
#include "SublistSlotIterator.hpp"
#include "WorkPacketsConcurrent.hpp"
#if defined(OMR_GC_REALTIME)
#include "RememberedSetSATB.hpp"
#endif /* defined(OMR_GC_REALTIME) */
typedef struct ConHelperThreadInfo {
OMR_VM *omrVM;
uintptr_t threadID;
uintptr_t threadFlags;
MM_ConcurrentGC *collector;
} ConHelperThreadInfo;
#define CON_HELPER_INFO_FLAG_OK 1
#define CON_HELPER_INFO_FLAG_FAIL 2
extern "C" {
/**
* @deprecated Caller should make use of new concurrentPostWriteBarrierStore API
*/
void
J9ConcurrentWriteBarrierStore(OMR_VMThread *vmThread, omrobjectptr_t destinationObject, omrobjectptr_t storedObject)
{
concurrentPostWriteBarrierStore(vmThread, destinationObject, storedObject);
}
/**
* @deprecated Caller should make use of new concurrentPostWriteBarrierBatchStore API
*/
void
J9ConcurrentWriteBarrierBatchStore(OMR_VMThread *vmThread, omrobjectptr_t destinationObject)
{
concurrentPostWriteBarrierBatchStore(vmThread, destinationObject);
}
/**
* Concurrent helper thread procedure
*
* @parm info Address of ConHelperThreadInfo structure
*/
int J9THREAD_PROC
con_helper_thread_proc(void *info)
{
ConHelperThreadInfo *conHelperThreadInfo = (ConHelperThreadInfo *)info;
MM_ConcurrentGC *collector = conHelperThreadInfo->collector;
OMRPORT_ACCESS_FROM_OMRVM(conHelperThreadInfo->omrVM);
uintptr_t rc;
void *signalHandlerArg = NULL;
omrsig_handler_fn signalHandler = collector->_concurrentDelegate.getProtectedSignalHandler(&signalHandlerArg);
omrsig_protect(con_helper_thread_proc2, info, signalHandler, signalHandlerArg, (OMRPORT_SIG_FLAG_SIGALLSYNC | OMRPORT_SIG_FLAG_MAY_CONTINUE_EXECUTION), &rc);
return 0;
}
/**
* Concurrent helper thread procedure
*
* @parm info Address of ConHelperThreadInfo structure
* @return return code; always 0
*/
uintptr_t
con_helper_thread_proc2(OMRPortLibrary* portLib, void *info)
{
ConHelperThreadInfo *conHelperThreadInfo = (ConHelperThreadInfo *)info;
OMR_VM *omrVM = conHelperThreadInfo->omrVM;
uintptr_t threadID = conHelperThreadInfo->threadID;
MM_ConcurrentGC *collector = conHelperThreadInfo->collector;
/* Attach the thread as a system daemon thread */
/* You need a VM thread so that the stack walker can work */
OMR_VMThread *omrThread = MM_EnvironmentBase::attachVMThread(omrVM, "Concurrent Mark Helper", MM_EnvironmentBase::ATTACH_GC_HELPER_THREAD);
/* Signal that the concurrent helper thread has started (or not) */
conHelperThreadInfo->threadFlags = (NULL != omrThread) ? CON_HELPER_INFO_FLAG_OK : CON_HELPER_INFO_FLAG_FAIL;
omrthread_monitor_enter(collector->_conHelpersActivationMonitor);
omrthread_monitor_notify_all(collector->_conHelpersActivationMonitor);
omrthread_monitor_exit(collector->_conHelpersActivationMonitor);
/* If thread started invoke main entry point */
if (NULL != omrThread) {
collector->conHelperEntryPoint(omrThread, threadID);
}
return 0;
}
#if defined(OMR_GC_MODRON_SCAVENGER)
void oldToOldReferenceCreated(MM_EnvironmentBase *env, omrobjectptr_t objectPtr)
{
((MM_ConcurrentGC *)env->getExtensions()->getGlobalCollector())->oldToOldReferenceCreated(env, objectPtr);
}
#endif /* OMR_GC_MODRON_SCAVENGER */
} /* extern "C" */
void
MM_ConcurrentGC::reportConcurrentKickoff(MM_EnvironmentBase *env)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
Trc_MM_ConcurrentKickoff(env->getLanguageVMThread(),
_stats.getTraceSizeTarget(),
_stats.getKickoffThreshold(),
_stats.getRemainingFree()
);
MM_CommonGCData commonData;
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_KICKOFF(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_KICKOFF,
_extensions->getHeap()->initializeCommonGCData(env, &commonData),
_stats.getTraceSizeTarget(),
_stats.getKickoffThreshold(),
_stats.getRemainingFree(),
_stats.getKickoffReason(),
_languageKickoffReason
);
}
void
MM_ConcurrentGC::reportConcurrentAborted(MM_EnvironmentBase *env, CollectionAbortReason reason)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
Trc_MM_ConcurrentAborted(env->getLanguageVMThread());
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_ABORTED(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_ABORTED,
reason
);
}
void
MM_ConcurrentGC::reportConcurrentCollectionEnd(MM_EnvironmentBase *env, uint64_t duration)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
Trc_MM_ConcurrentCollectionEnd(env->getLanguageVMThread(),
_extensions->heap->getApproximateActiveFreeMemorySize(MEMORY_TYPE_NEW),
_extensions->heap->getActiveMemorySize(MEMORY_TYPE_NEW),
_extensions->heap->getApproximateActiveFreeMemorySize(MEMORY_TYPE_OLD),
_extensions->heap->getActiveMemorySize(MEMORY_TYPE_OLD),
(_extensions-> largeObjectArea ? _extensions->heap->getApproximateActiveFreeLOAMemorySize(MEMORY_TYPE_OLD) : 0 ),
(_extensions-> largeObjectArea ? _extensions->heap->getActiveLOAMemorySize(MEMORY_TYPE_OLD) : 0 )
);
if (J9_EVENT_IS_HOOKED(_extensions->privateHookInterface, J9HOOK_MM_PRIVATE_CONCURRENT_COLLECTION_END)) {
MM_CommonGCEndData commonData;
_extensions->heap->initializeCommonGCEndData(env, &commonData);
ALWAYS_TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_COLLECTION_END(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_COLLECTION_END,
duration,
env->getExclusiveAccessTime(),
&commonData
);
}
}
void
MM_ConcurrentGC::reportConcurrentBackgroundThreadActivated(MM_EnvironmentBase *env)
{
Trc_MM_ConcurrentBackgroundThreadActivated(env->getLanguageVMThread());
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_BACKGROUND_THREAD_ACTIVATED(_extensions->privateHookInterface, env->getOmrVMThread());
}
void
MM_ConcurrentGC::reportConcurrentBackgroundThreadFinished(MM_EnvironmentBase *env, uintptr_t traceTotal)
{
Trc_MM_ConcurrentBackgroundThreadFinished(env->getLanguageVMThread());
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_BACKGROUND_THREAD_FINISHED(_extensions->privateHookInterface, env->getOmrVMThread(), traceTotal);
}
void
MM_ConcurrentGC::reportConcurrentCompleteTracingStart(MM_EnvironmentBase *env)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
Trc_MM_ConcurrentCompleteTracingStart(env->getLanguageVMThread(),
_stats.getConcurrentWorkStackOverflowCount()
);
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_COMPLETE_TRACING_START(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_COMPLETE_TRACING_START,
_stats.getConcurrentWorkStackOverflowCount()
);
}
void
MM_ConcurrentGC::reportConcurrentCompleteTracingEnd(MM_EnvironmentBase *env, uint64_t duration)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
Trc_MM_ConcurrentCompleteTracingEnd(env->getLanguageVMThread(),
_stats.getCompleteTracingCount(),
_stats.getConcurrentWorkStackOverflowCount()
);
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_COMPLETE_TRACING_END(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_COMPLETE_TRACING_END,
duration,
_stats.getCompleteTracingCount(),
_stats.getConcurrentWorkStackOverflowCount()
);
}
void
MM_ConcurrentGC::reportConcurrentRememberedSetScanStart(MM_EnvironmentBase *env)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
Trc_MM_ConcurrentRememberedSetScanStart(env->getLanguageVMThread(),
_stats.getConcurrentWorkStackOverflowCount()
);
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_REMEMBERED_SET_SCAN_START(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_REMEMBERED_SET_SCAN_START,
_stats.getConcurrentWorkStackOverflowCount()
);
}
void
MM_ConcurrentGC::reportConcurrentRememberedSetScanEnd(MM_EnvironmentBase *env, uint64_t duration)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
Trc_MM_ConcurrentRememberedSetScanEnd(env->getLanguageVMThread(),
_stats.getRSObjectsFound(),
_stats.getRSScanTraceCount(),
_stats.getConcurrentWorkStackOverflowCount()
);
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_REMEMBERED_SET_SCAN_END(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_REMEMBERED_SET_SCAN_END,
duration,
_stats.getRSObjectsFound(),
_stats.getRSScanTraceCount(),
_stats.getConcurrentWorkStackOverflowCount()
);
}
void
MM_ConcurrentGC::preConcurrentInitializeStatsAndReport(MM_EnvironmentBase *env, MM_ConcurrentPhaseStatsBase *stats)
{
OMRPORT_ACCESS_FROM_OMRPORT(env->getPortLibrary());
_concurrentPhaseStats._cycleID = _concurrentCycleState._verboseContextID;
_concurrentPhaseStats._startTime = omrtime_hires_clock();
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_PHASE_START(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_PHASE_START,
&_concurrentPhaseStats);
}
void
MM_ConcurrentGC::postConcurrentUpdateStatsAndReport(MM_EnvironmentBase *env, MM_ConcurrentPhaseStatsBase *stats, UDATA bytesConcurrentlyScanned)
{
OMRPORT_ACCESS_FROM_OMRPORT(env->getPortLibrary());
_concurrentPhaseStats._cycleID = _concurrentCycleState._verboseContextID;
_concurrentPhaseStats._collectionStats = &_stats;
TRIGGER_J9HOOK_MM_PRIVATE_CONCURRENT_PHASE_END(
_extensions->privateHookInterface,
env->getOmrVMThread(),
omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_CONCURRENT_PHASE_END,
&_concurrentPhaseStats);
}
/**
* Aysnc callback routine to signal all threads that CM is active (Activate SATB Barrier or Start Dirtying Cards).
*
* @note Caller assumed to be at a safe point
*
*/
void
MM_ConcurrentGC::signalThreadsToActivateWriteBarrierAsyncEventHandler(OMR_VMThread *omrVMThread, void *userData)
{
MM_ConcurrentGC *collector = (MM_ConcurrentGC *)userData;
MM_EnvironmentBase *env = MM_EnvironmentBase::getEnvironment(omrVMThread);
collector->signalThreadsToActivateWriteBarrier(env);
}
/**
* Destroy instance of an ConcurrentGC object.
*
*/
void
MM_ConcurrentGC::kill(MM_EnvironmentBase *env)
{
tearDown(env);
env->getForge()->free(this);
}
/**
* Initialize a new ConcurrentGC object.
* Instantiate concurrent RAS objects(if required) and initialize all monitors required by concurrent.
* Allocate and initialize the concurrent helper thread table.
*
* @return TRUE if initialization completed OK; FALSE otherwise
*/
bool
MM_ConcurrentGC::initialize(MM_EnvironmentBase *env)
{
/* First call super class initialize */
if (!MM_ParallelGlobalGC::initialize(env)) {
goto error_no_memory;
}
if (!_concurrentDelegate.initialize(env, this)) {
goto error_no_memory;
}
if (_extensions->optimizeConcurrentWB) {
_callback = _concurrentDelegate.createSafepointCallback(env);
if (NULL == _callback) {
goto error_no_memory;
}
_callback->registerCallback(env, signalThreadsToActivateWriteBarrierAsyncEventHandler, this);
}
if (_conHelperThreads > 0) {
/* Get storage for concurrent helper thread table */
_conHelpersTable = (omrthread_t *)env->getForge()->allocate(_conHelperThreads * sizeof(omrthread_t), OMR::GC::AllocationCategory::FIXED, OMR_GET_CALLSITE());
if(!_conHelpersTable) {
goto error_no_memory;
}
/* Clear storage to zeroes */
memset(_conHelpersTable, 0, _conHelperThreads * sizeof(omrthread_t));
}
/* Init pointer to heap base; we will reset _heapAlloc in expanded as heap grows */
_heapBase= (void *)_extensions->heap->getHeapBase();
/* Initialize the concurrent helper thread monitors */
if (omrthread_monitor_init_with_name(&_conHelpersActivationMonitor, 0, "MM_ConcurrentGC::conHelpersActivation")) {
goto error_no_memory;
}
/* Initialize the initialisation work monitor */
if (omrthread_monitor_init_with_name(&_initWorkMonitor, 0, "MM_ConcurrentGC::initWork")) {
goto error_no_memory;
}
/* Initialize the tuning monitor monitor */
if (omrthread_monitor_init_with_name(&_concurrentTuningMonitor, 0, "MM_ConcurrentGC::concurrentTuning")) {
goto error_no_memory;
}
/* ..and the initialization work complete monitor */
if (omrthread_monitor_init_with_name(&_initWorkCompleteMonitor, 0, "MM_ConcurrentGC::initWorkComplete")) {
goto error_no_memory;
}
_allocToInitRate = _extensions->concurrentLevel * CONCURRENT_INIT_BOOST_FACTOR;
_allocToTraceRate = _extensions->concurrentLevel;
_allocToTraceRateNormal = _extensions->concurrentLevel;
_allocToTraceRateMinFactor = ((float)1) / interpolateInRange(MIN_ALLOC_2_TRACE_RATE_1, MIN_ALLOC_2_TRACE_RATE_8, MIN_ALLOC_2_TRACE_RATE_10, _allocToTraceRateNormal);
_allocToTraceRateMaxFactor = interpolateInRange(MAX_ALLOC_2_TRACE_RATE_1, MAX_ALLOC_2_TRACE_RATE_8, MAX_ALLOC_2_TRACE_RATE_10, _allocToTraceRateNormal);
#if defined(OMR_GC_LARGE_OBJECT_AREA)
/* Has user elected to run with an LOA ? */
if (_extensions->largeObjectArea) {
if (MM_GCExtensionsBase::METER_DYNAMIC == _extensions->concurrentMetering) {
/* Get storage for metering history table */
uintptr_t historySize = _meteringHistorySize * sizeof(MeteringHistory);
_meteringHistory = (MeteringHistory *)env->getForge()->allocate(historySize, OMR::GC::AllocationCategory::FIXED, OMR_GET_CALLSITE());
if(!_meteringHistory) {
goto error_no_memory;
}
/* Clear storage to zeroes */
memset(_meteringHistory, 0, historySize);
/* and initialize first free slot */
_currentMeteringHistory = 0;
} else if (MM_GCExtensionsBase::METER_BY_LOA == _extensions->concurrentMetering) {
_meteringType = LOA;
}
}
#endif /* OMR_GC_LARGE_OBJECT_AREA) */
return true;
error_no_memory:
return false;
}
/**
* Teardown a ConcurrentGC object
* Destroy referenced objects and release
* all allocated storage before ConcurrentGC object is freed.
*/
void
MM_ConcurrentGC::tearDown(MM_EnvironmentBase *env)
{
OMR::GC::Forge *forge = env->getForge();
if (NULL != _conHelpersTable) {
forge->free(_conHelpersTable);
_conHelpersTable = NULL;
}
if (NULL != _initRanges) {
forge->free(_initRanges);
_initRanges = NULL;
}
if (NULL != _callback) {
_callback->kill(env);
_callback = NULL;
}
/* ..and then tearDown our super class */
MM_ParallelGlobalGC::tearDown(env);
}
/**
* Determine concurrent initialization work
* Populate the _initRanges structure with the areas of storage which need
* initializing at each concurrent kickoff. Currently mark bits (and card table for Incremental CM).
* For mark bits we create one entry in _initRanges for each segment of heap.
* The mark bits for areas which are concurrently collectable, eg OLD, will be
* set OFF; but all mark bits areas not concurrent collectable, eg NEW, will be
* set ON so that concurrent does not trace into these areas.
*/
void
MM_ConcurrentGC::determineInitWork(MM_EnvironmentBase *env)
{
bool initDone = false;
Trc_MM_ConcurrentGC_determineInitWork_Entry(env->getLanguageVMThread());
while (!initDone) {
uint32_t i = 0;
_numInitRanges = 0;
/* Add init ranges for all old and new area segments */
MM_HeapRegionDescriptor *region = NULL;
MM_Heap *heap = _extensions->heap;
MM_HeapRegionManager *regionManager = heap->getHeapRegionManager();
GC_HeapRegionIterator regionIterator(regionManager);
while (NULL != (region = regionIterator.nextRegion())) {
if (0 == region->getSize()) {
continue;
}
/* Get reference to owning subspace */
MM_MemorySubSpace *subspace = region->getSubSpace();
/* If space in initRanges array add it */
if (_numInitRanges < _numPhysicalInitRanges) {
_initRanges[i].base = region->getLowAddress();
_initRanges[i].top = region->getHighAddress();
_initRanges[i].subspace = subspace;
_initRanges[i].current = _initRanges[i].base;
_initRanges[i].initBytes = _markingScheme->numMarkBitsInRange(env,_initRanges[i].base,_initRanges[i].top);
_initRanges[i].type = MARK_BITS;
_initRanges[i].chunkSize = INIT_CHUNK_SIZE * _markingScheme->numHeapBytesPerMarkMapByte();
i++;
}
_numInitRanges += numberOfInitRanages(subspace);
}
/* Any room left ? */
if (_numInitRanges > _numPhysicalInitRanges) {
/* We need to get a bigger initRanges array of i+1 elements but first free the one if have already, if any */
if (_initRanges) {
env->getForge()->free(_initRanges);
}
/* TODO: dynamically allocating this structure. Should the VM tear itself down in this scenario? */
_initRanges = (InitWorkItem *) env->getForge()->allocate(sizeof(InitWorkItem) * _numInitRanges, OMR::GC::AllocationCategory::FIXED, OMR_GET_CALLSITE());
if (NULL == _initRanges) {
initDone = true;
_numPhysicalInitRanges = 0;
_numInitRanges = 0;
} else {
_numPhysicalInitRanges = _numInitRanges;
}
} else {
determineInitWorkInternal(env, i);
_nextInitRange = 0;
initDone = true;
}
}
/* Now count total initialization work we have to do */
uintptr_t initWork = 0;
for (uint32_t i = 0; i < _numInitRanges; i++) {
if (NULL != _initRanges[i].base) {
initWork += _initRanges[i].initBytes;
}
}
_stats.setInitWorkRequired(initWork);
_rebuildInitWorkForAdd = false;
_rebuildInitWorkForRemove = false;
Trc_MM_ConcurrentGC_determineInitWork_Exit(env->getLanguageVMThread());
}
/**
* Reset initialization work ranges for concurrent KO.
* Reset all ranges in _initRanges structure prior to next concurrent kickoff,
* i.e reset "current" to "base" for all ranges.
*/
void
MM_ConcurrentGC::resetInitRangesForConcurrentKO()
{
for (uint32_t i = 0; i < _numInitRanges; i++) {
_initRanges[i].current = _initRanges[i].base;
}
/* Reset scan ptr */
_nextInitRange = 0;
}
void
MM_ConcurrentGC::resetConcurrentParameters(MM_EnvironmentBase *env)
{
/* Reset all ConcurrentStats for next cycle */
_stats.reset();
_initSetupDone = false;
_alloc2ConHelperTraceRate = 0;
_lastConHelperTraceSizeCount = 0;
_lastAverageAlloc2TraceRate = 0;
_maxAverageAlloc2TraceRate = 0;
_lastFreeSize = LAST_FREE_SIZE_NEEDS_INITIALIZING;
_lastTotalTraced = 0;
}
/**
* Reset initialization work ranges for STW collect.
* Reset any non concurrently collectbale heap ranges, eg new heap ranges,
* in _initRanges structure so we can reset their associated mark bits OFF
* prior to a full collection. We don't want to trace into such objects during
* the concurrent mark cycle but we must do so during a full collection.
*/
void
MM_ConcurrentGC::resetInitRangesForSTW()
{
for (uint32_t i = 0; i < _numInitRanges; i++) {
if ((MARK_BITS == _initRanges[i].type) && (!((_initRanges[i].subspace)->isConcurrentCollectable()))) {
_initRanges[i].current = _initRanges[i].base;
} else {
/* Set current == top so we don't bother doing any re-init of these areas */
_initRanges[i].current = _initRanges[i].top;
}
}
/* Reset scan ptr */
_nextInitRange = 0;
}
/**
* Get next initialization range
* Determine the next chunk of storage that need initializing. We break the
* work up into INIT_CHUNK_SIZE sized chunks although is remainder in range
* after taking INIT_CHUNK_SIZE is less than 1K we complete the whole range.
*
* @param from Pointer to start address of initialization chunk
* @param to Pointer to end address of initialization chunk
* @param type Identifier of type of range to be initialized
* @param concurrentCollectable TRUE if heap range is concurrently collectible;
* FALSE otherwise.
* @return TRUE if work left to be done, FALSE otherwise.
*/
bool
MM_ConcurrentGC::getInitRange(MM_EnvironmentBase *env, void **from, void **to, InitType *type, bool *concurrentCollectable)
{
/* Cache _numInitRanges as it may be changed by another thread */
uint32_t i = (uint32_t)_nextInitRange;
void *localFrom = NULL;
void *localTo = NULL;
Trc_MM_ConcurrentGC_getInitRange_Entry(env->getLanguageVMThread());
while (i < _numInitRanges) {
/* Cache ptr to next range */
localFrom = (void *)(_initRanges[i].current);
if (localFrom < _initRanges[i].top) {
uintptr_t chunkSize = _initRanges[i].chunkSize;
if (((uintptr_t)((uint8_t *)_initRanges[i].top - (uint8_t *)localFrom)) <= chunkSize) {
localTo = _initRanges[i].top;
} else {
localTo = (void *)((uint8_t *)localFrom + chunkSize);
/* Finish off range if remaining part is less than half a chunk. */
if (localTo >= (void *)((uint8_t *)_initRanges[i].top - (chunkSize/2))) {
localTo = _initRanges[i].top;
}
}
if(localFrom == (uint8_t *)MM_AtomicOperations::lockCompareExchange((volatile uintptr_t *)&(_initRanges[i].current), (uintptr_t)localFrom, (uintptr_t)localTo)) {
/* Got the range so return details */
*from = localFrom;
*to = localTo;
*type= _initRanges[i].type;
*concurrentCollectable = (_initRanges[i].subspace)->isConcurrentCollectable() ? true : false;
Trc_MM_ConcurrentGC_getInitRange_Succeed(env->getLanguageVMThread(), *from, *to, *type, *concurrentCollectable ? "true" : "false");
return true;
}
} else {
/* Get next range, if any */
uint32_t oldIndex = i;
uint32_t newIndex = oldIndex + 1;
/* Don't care if this fails, it just means another thread someone beat us to it */
MM_AtomicOperations::lockCompareExchangeU32(&_nextInitRange, oldIndex, newIndex);
/* ..and refresh local cached value, may have been changed by other threads */
i = (uint32_t)_nextInitRange;
}
}
Trc_MM_ConcurrentGC_getInitRange_Fail(env->getLanguageVMThread());
return false;
}
/**
* Determine if trace rate has dropped
* Determine if we have passed the peak of tracing activity, i.e
* majority of roots traced.
*
* @return TRUIE if we are past the peak; FALSE otherwise
*/
bool
MM_ConcurrentGC::tracingRateDropped(MM_EnvironmentBase *env)
{
/* Always return false for now until we understand how to fix this code to ensure
* we do not prematurely report that the rate has dropped and so start card cleaning
* too early.
*/
return false;
#if 0
/* TODO CRGTMP these two variable are never used since this code is no longer used. Should
* this function and those vaiables be removed?
*/
if (_lastAverageAlloc2TraceRate < (_maxAverageAlloc2TraceRate / 4)) {
return true;
} else {
return false;
}
#endif
}
MM_ConcurrentGC::ConHelperRequest
MM_ConcurrentGC::switchConHelperRequest(ConHelperRequest from, ConHelperRequest to)
{
ConHelperRequest result = to;
omrthread_monitor_enter(_conHelpersActivationMonitor);
if (from == _conHelpersRequest) {
_conHelpersRequest = to;
} else {
result = _conHelpersRequest;
}
omrthread_monitor_exit(_conHelpersActivationMonitor);
return result;
}
MM_ConcurrentGC::ConHelperRequest
MM_ConcurrentGC::getConHelperRequest(MM_EnvironmentBase *env)
{
ConHelperRequest result;
omrthread_monitor_enter(_conHelpersActivationMonitor);
if (env->isExclusiveAccessRequestWaiting()) {
if (CONCURRENT_HELPER_MARK == _conHelpersRequest) {
_conHelpersRequest = CONCURRENT_HELPER_WAIT;
}
}
result = _conHelpersRequest;
omrthread_monitor_exit(_conHelpersActivationMonitor);
return result;
}
void
MM_ConcurrentGC::conHelperEntryPoint(OMR_VMThread *omrThread, uintptr_t workerID)
{
MM_EnvironmentBase *env = MM_EnvironmentBase::getEnvironment(omrThread);
ConHelperRequest request = CONCURRENT_HELPER_WAIT;
uintptr_t sizeTraced = 0;
uintptr_t totalScanned = 0;
uintptr_t sizeToTrace = 0;
MM_SpinLimiter spinLimiter(env);
/* Thread not a mutator so identify its type */
env->initializeGCThread();
env->setThreadType(CON_MARK_HELPER_THREAD);
while (CONCURRENT_HELPER_SHUTDOWN != request) {
omrthread_monitor_enter(_conHelpersActivationMonitor);
while (CONCURRENT_HELPER_WAIT == (request = _conHelpersRequest)) {
omrthread_monitor_wait(_conHelpersActivationMonitor);
}
omrthread_monitor_exit(_conHelpersActivationMonitor);
if (CONCURRENT_HELPER_SHUTDOWN == request) {
continue;
}
env->acquireVMAccess();
request = getConHelperRequest(env);
if (CONCURRENT_HELPER_MARK != request) {
env->releaseVMAccess();
continue;
}
Assert_GC_true_with_message(env, (CONCURRENT_OFF != _stats.getExecutionMode()), "MM_ConcurrentStats::_executionMode = %zu\n", _stats.getExecutionMode());
sizeTraced = 0;
totalScanned = 0;
sizeToTrace = _tuningUpdateInterval;
reportConcurrentBackgroundThreadActivated(env);
spinLimiter.reset();
/* perform trace work */
while ((CONCURRENT_HELPER_MARK == request)
&& _markingScheme->getWorkPackets()->inputPacketAvailable(env)
&& spinLimiter.spin()) {
sizeTraced = localMark(env, sizeToTrace);
if (sizeTraced > 0) {
_stats.incConHelperTraceSizeCount(sizeTraced);
totalScanned += sizeTraced;
spinLimiter.reset();
}
request = getConHelperRequest(env);
}
/* Collector specific Con Helper Work */
conHelperDoWorkInternal(env, &request, &spinLimiter, &totalScanned);
if (CONCURRENT_HELPER_MARK == request) {
request = switchConHelperRequest(CONCURRENT_HELPER_MARK, CONCURRENT_HELPER_WAIT);
}
Assert_MM_true(CONCURRENT_HELPER_MARK != request);
reportConcurrentBackgroundThreadFinished(env, totalScanned);
env->releaseVMAccess();
} /* end while (SHUTDOWN != request) */
/* Must be no local work left at this point! */
Assert_MM_true(!env->_workStack.inputPacketAvailable());
Assert_MM_true(!env->_workStack.outputPacketAvailable());
Assert_MM_true(!env->_workStack.deferredPacketAvailable());
/* All done, so shutdown the helper threads */
shutdownAndExitConHelperThread(omrThread);
}
/**
* Shutdown and exit a concurrent helper
* Detach a concurrent helper. Notify _conHelpersActivationMonitor if this is
* last concurrent helper to shutdown.
*
*/
void
MM_ConcurrentGC::shutdownAndExitConHelperThread(OMR_VMThread *omrThread)
{
MM_EnvironmentBase::detachVMThread(_extensions->getOmrVM(), omrThread, MM_EnvironmentBase::ATTACH_GC_HELPER_THREAD);
omrthread_monitor_enter(_conHelpersActivationMonitor);
_conHelpersShutdownCount += 1;
/* The last thread to shut down must notify the main thread */
if (_conHelpersShutdownCount == _conHelpersStarted) {
omrthread_monitor_notify(_conHelpersActivationMonitor);
}
/* Clear the entry in _conHelpersTable containing the thread id,
* so that other parts of code know now this thread is gone.
* The thread itself does not know which entry in the table it is,
* so we search the table. */
for (uint32_t i = 0; i < _conHelpersStarted; i++) {
if (_conHelpersTable[i] == omrthread_self()) {
_conHelpersTable[i] = 0;
break;
}
}
/* Exit the monitor and terminate the thread */
omrthread_exit(_conHelpersActivationMonitor);
}
/**
* Initialize concurrent helper threads.
* Attach the required number of concurrent helper threads which are attached with
* minimum priority so they do not compete with application threads for use of processors;
* they are only intended to use up any spare cycles not used by application threads.
*
* @return TRUE if concurrent helper thread attached and initailzed OK;
* FALSE otherwise
*/
bool
MM_ConcurrentGC::initializeConcurrentHelpers(MM_GCExtensionsBase *extensions)
{
/* If user has elected to run without helpers then nothing to do */
if (0 == _conHelperThreads) {
return true;
}
uint32_t conHelperThreadCount = 0;
ConHelperThreadInfo conHelperThreadInfo;
/* Attach the concurrent helper thread threads */
conHelperThreadInfo.omrVM = extensions->getOmrVM();
omrthread_monitor_enter(_conHelpersActivationMonitor);
_conHelpersRequest = CONCURRENT_HELPER_WAIT;
for(conHelperThreadCount = 0; conHelperThreadCount < _conHelperThreads; conHelperThreadCount++) {
conHelperThreadInfo.threadFlags = 0;
conHelperThreadInfo.threadID = conHelperThreadCount;
conHelperThreadInfo.collector = this;
IDATA threadForkResult = createThreadWithCategory(&(_conHelpersTable[conHelperThreadCount]), OMR_OS_STACK_SIZE, J9THREAD_PRIORITY_MIN,
0, con_helper_thread_proc, (void *)&conHelperThreadInfo, J9THREAD_CATEGORY_SYSTEM_GC_THREAD);
if (threadForkResult != 0) {
break;
}
do {
omrthread_monitor_wait(_conHelpersActivationMonitor);
} while (!conHelperThreadInfo.threadFlags);
if (CON_HELPER_INFO_FLAG_OK != conHelperThreadInfo.threadFlags) {
break;
}
}
omrthread_monitor_exit(_conHelpersActivationMonitor);
_conHelpersStarted = conHelperThreadCount;
return ((_conHelpersStarted == _conHelperThreads) ? true : false);
}
/**
* Shutdown all concurrent helper threads.
* Ask all active concurrent helper threads to terminate.
*/
void
MM_ConcurrentGC::shutdownConHelperThreads(MM_GCExtensionsBase *extensions)
{
Trc_MM_shutdownConHelperThreads_Entry();
if (_conHelpersStarted > 0) {
omrthread_monitor_enter(_conHelpersActivationMonitor);
/* Set shutdown request flag */
_conHelpersRequest = CONCURRENT_HELPER_SHUTDOWN;
_conHelpersShutdownCount = 0;
omrthread_monitor_notify_all(_conHelpersActivationMonitor);
/* Now wait for all concurrent helper threads to terminate */
while (_conHelpersShutdownCount < _conHelpersStarted) {
omrthread_monitor_wait(_conHelpersActivationMonitor);
}
omrthread_monitor_exit(_conHelpersActivationMonitor);
}
Trc_MM_shutdownConHelperThreads_Exit();
}
/**
* Resume the concurrent helper threads.
* Concurrent kickoff point has been reached so wake up any Concurrent helper
* threads which are waiting on the _conHelpersActivationMonitor monitor.
*
*/
void
MM_ConcurrentGC::resumeConHelperThreads(MM_EnvironmentBase *env)
{
if (_conHelpersStarted > 0) {
omrthread_monitor_enter(_conHelpersActivationMonitor);
if (!env->isExclusiveAccessRequestWaiting()) {
if (CONCURRENT_HELPER_WAIT == _conHelpersRequest) {
_conHelpersRequest = CONCURRENT_HELPER_MARK;
omrthread_monitor_notify_all(_conHelpersActivationMonitor);
}