-
Notifications
You must be signed in to change notification settings - Fork 751
/
Copy pathScheduler.cpp
1123 lines (975 loc) · 36.8 KB
/
Scheduler.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 IBM Corp. and others 1991
*
* 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] https://openjdk.org/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR GPL-2.0-only WITH OpenJDK-assembly-exception-1.0
*******************************************************************************/
#include "omr.h"
#include "omrcfg.h"
#include "ModronAssertions.h"
#include <string.h>
#include "AtomicOperations.hpp"
#include "EnvironmentRealtime.hpp"
#include "GCCode.hpp"
#include "GCExtensionsBase.hpp"
#include "Heap.hpp"
#include "IncrementalParallelTask.hpp"
#include "MemoryPoolSegregated.hpp"
#include "MemorySubSpaceMetronome.hpp"
#include "Metronome.hpp"
#include "MetronomeAlarmThread.hpp"
#include "MetronomeDelegate.hpp"
#include "RealtimeGC.hpp"
#include "OSInterface.hpp"
#include "ParallelDispatcher.hpp"
#include "Scheduler.hpp"
#include "Timer.hpp"
#include "UtilizationTracker.hpp"
/**
* Initialization.
* @todo Provide method documentation
* @ingroup GC_Metronome methodGroup
*/
MM_Scheduler*
MM_Scheduler::newInstance(MM_EnvironmentBase *env, omrsig_handler_fn handler, void *handler_arg, uintptr_t defaultOSStackSize)
{
MM_Scheduler *scheduler = (MM_Scheduler *)env->getForge()->allocate(sizeof(MM_Scheduler), MM_AllocationCategory::FIXED, OMR_GET_CALLSITE());
if (NULL != scheduler) {
new(scheduler) MM_Scheduler(env, handler, handler_arg, defaultOSStackSize);
if (!scheduler->initialize(env)) {
scheduler->kill(env);
scheduler = NULL;
}
}
return scheduler;
}
/**
* Initialization.
* @todo Provide method documentation
* @ingroup GC_Metronome methodGroup
*/
void
MM_Scheduler::kill(MM_EnvironmentBase *env)
{
tearDown(env);
}
/**
* Teardown
* @todo Provide method documentation
* @ingroup GC_Metronome methodGroup
*/
void
MM_Scheduler::tearDown(MM_EnvironmentBase *env)
{
if (NULL != _mainThreadMonitor) {
omrthread_monitor_destroy(_mainThreadMonitor);
_mainThreadMonitor = NULL;
}
if (NULL != _threadResumedTable) {
env->getForge()->free(_threadResumedTable);
_threadResumedTable = NULL;
}
if (NULL != _utilTracker) {
_utilTracker->kill(env);
_utilTracker = NULL;
}
MM_ParallelDispatcher::kill(env);
}
uintptr_t
MM_Scheduler::getParameter(uintptr_t which, char *keyBuffer, int32_t keyBufferSize, char *valueBuffer, int32_t valueBufferSize)
{
OMRPORT_ACCESS_FROM_OMRVM(_vm);
switch (which) {
case 0: omrstr_printf(keyBuffer, keyBufferSize, "Verbose Level");
omrstr_printf(valueBuffer, valueBufferSize, "%d", verbose());
return 1;
case 1:
{
omrstr_printf(keyBuffer, keyBufferSize, "Scheduling Method");
int32_t len = (int32_t)omrstr_printf(valueBuffer, valueBufferSize, "TIME_BASED with ");
while ((NULL == _alarmThread) || (NULL == _alarmThread->_alarm)) {
/* Wait for GC to finish initializing */
omrthread_sleep(100);
}
_alarmThread->_alarm->describe(OMRPORTLIB, &valueBuffer[len], valueBufferSize - len);
return 1;
}
case 2:
omrstr_printf(keyBuffer, keyBufferSize, "Time Window");
omrstr_printf(valueBuffer, valueBufferSize, "%6.2f ms", _window * 1.0e3);
return 1;
case 3:
omrstr_printf(keyBuffer, keyBufferSize, "Target Utilization");
omrstr_printf(valueBuffer, valueBufferSize, "%4.1f%%", _utilTracker->getTargetUtilization() * 1.0e2);
return 1;
case 4:
omrstr_printf(keyBuffer, keyBufferSize, "Beat Size");
omrstr_printf(valueBuffer, valueBufferSize, "%4.2f ms", _beat * 1.0e3);
return 1;
case 5:
omrstr_printf(keyBuffer, keyBufferSize, "Heap Size");
omrstr_printf(valueBuffer, valueBufferSize, "%6.2f MB", ((double)(_extensions->memoryMax)) / (1 << 20));
return 1;
case 6:
omrstr_printf(keyBuffer, keyBufferSize, "GC Trigger");
omrstr_printf(valueBuffer, valueBufferSize, "%6.2f MB", _extensions->gcTrigger / (double) (1<<20));
return 1;
case 7:
omrstr_printf(keyBuffer, keyBufferSize, "Headroom");
omrstr_printf(valueBuffer, valueBufferSize, "%5.2f MB", _extensions->headRoom / (double) (1<<20));
return 1;
case 8:
omrstr_printf(keyBuffer, keyBufferSize, "Number of GC Threads");
omrstr_printf(valueBuffer, valueBufferSize, "%d", _extensions->gcThreadCount);
return 1;
case 9:
omrstr_printf(keyBuffer, keyBufferSize, "Regionsize");
omrstr_printf(valueBuffer, valueBufferSize, "%d", _extensions->regionSize);
return 1;
}
return 0;
}
void
MM_Scheduler::showParameters(MM_EnvironmentBase *env)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
omrtty_printf("****************************************************************************\n");
for (uintptr_t which = 0; ; which++) {
char keyBuffer[256], valBuffer[256];
uintptr_t rc = getParameter(which, keyBuffer, sizeof(keyBuffer), valBuffer, sizeof(valBuffer));
if (rc == 0) {
break;
}
if (rc == 1) {
omrtty_printf("%s: %s\n", keyBuffer, valBuffer);
}
}
omrtty_printf("****************************************************************************\n");
}
void
MM_Scheduler::initializeForVirtualSTW(MM_GCExtensionsBase *ext)
{
ext->gcInitialTrigger = (uintptr_t) - 1;
ext->gcTrigger = ext->gcInitialTrigger;
ext->targetUtilizationPercentage = 0;
}
/**
* Initialization.
* @todo Provide method documentation
* @ingroup GC_Metronome methodGroup
*/
bool
MM_Scheduler::initialize(MM_EnvironmentBase *env)
{
if (!MM_ParallelDispatcher::initialize(env)) {
return false;
}
if (_extensions->gcTrigger == 0) {
_extensions->gcTrigger = (_extensions->memoryMax / 2);
_extensions->gcInitialTrigger = (_extensions->memoryMax / 2);
}
_extensions->distanceToYieldTimeCheck = 0;
/* Maintain window-beat ratio of 20x, unless window specified explicitly */
if (METRONOME_DEFAULT_TIME_WINDOW_MICRO == _extensions->timeWindowMicro) {
_extensions->timeWindowMicro = 20 * _extensions->beatMicro;
}
/* Currently all supported SRT platforms - AIX and Linux, can only use HRT for alarm thread implementation.
* The default value for HRT period is 1/3 of the default quanta: 1 msec for HRT period and 3 msec quanta,
* we will attempt to adjust the HRT period to 1/3 of the specified quanta.
*/
uintptr_t hrtPeriodMicro = _extensions->beatMicro / 3;
if ((hrtPeriodMicro < METRONOME_DEFAULT_HRT_PERIOD_MICRO) && (METRONOME_DEFAULT_HRT_PERIOD_MICRO < _extensions->beatMicro)) {
/* If the adjusted value is too small for the hires clock resolution, we will use the default HRT period provided that
* the default period is smaller than the quanta time specified.
* Otherwise we fail to initialize the alarm thread with an error message.
*/
hrtPeriodMicro = METRONOME_DEFAULT_HRT_PERIOD_MICRO;
}
Assert_MM_true(0 != hrtPeriodMicro);
_extensions->hrtPeriodMicro = hrtPeriodMicro;
/* On Windows SRT we still use interrupt-based alarm. Set the interrupt period the same as hires timer period.
* We will fail to init the alarm if this is too small a resolution for Windows.
*/
_extensions->itPeriodMicro = _extensions->hrtPeriodMicro;
/* if the pause time user specified is larger than the default value, calculate if there is opportunity
* for the GC to do time checking less often inside condYieldFromGC.
*/
if (METRONOME_DEFAULT_BEAT_MICRO < _extensions->beatMicro) {
uintptr_t intervalToSkipYieldCheckMicro = _extensions->beatMicro - METRONOME_DEFAULT_BEAT_MICRO;
uintptr_t maxInterYieldTimeMicro = INTER_YIELD_MAX_NS / 1000;
_extensions->distanceToYieldTimeCheck = (uint32_t)(intervalToSkipYieldCheckMicro / maxInterYieldTimeMicro);
}
/* Show GC parameters here before we enter real execution */
_window = _extensions->timeWindowMicro / 1e6;
_beat = _extensions->beatMicro / 1e6;
_beatNanos = (uint64_t) (_extensions->beatMicro * 1e3);
_staticTargetUtilization = _extensions->targetUtilizationPercentage / 1e2;
_utilTracker = MM_UtilizationTracker::newInstance(env, _window, _beatNanos, _staticTargetUtilization);
if (NULL == _utilTracker) {
goto error_no_memory;
}
/* Set up the table used for keeping track of which threads were resumed from suspended */
_threadResumedTable = (bool*)env->getForge()->allocate(_threadCountMaximum * sizeof(bool), MM_AllocationCategory::FIXED, OMR_GET_CALLSITE());
if (NULL == _threadResumedTable) {
goto error_no_memory;
}
memset(_threadResumedTable, false, _threadCountMaximum * sizeof(bool));
if (omrthread_monitor_init_with_name(&_mainThreadMonitor, 0, "MainThread")) {
return false;
}
return true;
error_no_memory:
return false;
}
void
MM_Scheduler::collectorInitialized(MM_RealtimeGC *gc) {
_gc = gc;
_osInterface = _gc->_osInterface;
}
void
MM_Scheduler::checkStartGC(MM_EnvironmentRealtime *env)
{
uintptr_t bytesInUse = _gc->_memoryPool->getBytesInUse();
if (isInitialized() && !isGCOn() && (bytesInUse > _extensions->gcTrigger)) {
startGC(env);
}
}
/* Races with other startGC's are ok
*
*/
void
MM_Scheduler::startGC(MM_EnvironmentBase *env)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
if (verbose() >= 3) {
omrtty_printf("GC request: %d Mb in use\n", _gc->_memoryPool->getBytesInUse() >> 20);
}
if (METRONOME_GC_OFF == MM_AtomicOperations::lockCompareExchangeU32(&_gcOn, METRONOME_GC_OFF, METRONOME_GC_ON)) {
if (_gc->isPreviousCycleBelowTrigger()) {
_gc->setPreviousCycleBelowTrigger(false);
TRIGGER_J9HOOK_MM_PRIVATE_METRONOME_TRIGGER_START(_extensions->privateHookInterface,
env->getOmrVMThread(), omrtime_hires_clock(),
J9HOOK_MM_PRIVATE_METRONOME_TRIGGER_START
);
}
}
}
/* External synchronization to make sure this does not race with startGC
*/
void
MM_Scheduler::stopGC(MM_EnvironmentBase *env)
{
_gcOn = METRONOME_GC_OFF;
}
bool
MM_Scheduler::isGCOn()
{
return (METRONOME_GC_ON == _gcOn);
}
bool
MM_Scheduler::continueGC(MM_EnvironmentRealtime *env, GCReason reason, uintptr_t resonParameter, OMR_VMThread *thr, bool doRequestExclusiveVMAccess)
{
uintptr_t gcPriority = 0;
bool didGC = true;
assert1(isInitialized());
if (!isGCOn()) {
return false;
}
if (_extensions->trackMutatorThreadCategory) {
/* This thread is doing GC work, account for the time spent into the GC bucket */
omrthread_set_category(omrthread_self(), J9THREAD_CATEGORY_SYSTEM_GC_THREAD, J9THREAD_TYPE_SET_GC);
}
_gc->getRealtimeDelegate()->preRequestExclusiveVMAccess(thr);
/* Wake up only the main thread -- it is responsible for
* waking up any workers.
* Make sure _completeCurrentGCSynchronously and _mode are atomically changed.
*/
omrthread_monitor_enter(_mainThreadMonitor);
switch (reason) {
case OUT_OF_MEMORY_TRIGGER:
/* For now we assume that OUT_OF_MEMORY trigger means perform
* a synchronous GC, but maybe we want a mode where we try one
* more time slice before degrading to synchronous.
*/
if (!_extensions->synchronousGCOnOOM) {
break;
}
/* fall through */
case SYSTEM_GC_TRIGGER:
/* System garbage collects, if not disabled through the usual command lines,
* force a synchronous GC
*/
_completeCurrentGCSynchronously = true;
_completeCurrentGCSynchronouslyReason = reason;
_completeCurrentGCSynchronouslyReasonParameter = resonParameter;
break;
default: /* WORK_TRIGGER or TIME_TRIGGER */ {
if (NULL != _threadWaitingOnMainThreadMonitor) {
/* Check your timer again incase another thread beat you to checking for shouldMutatorDoubleBeat */
if (env->getTimer()->hasTimeElapsed(getStartTimeOfCurrentMutatorSlice(), _beatNanos)) {
if (shouldMutatorDoubleBeat(_threadWaitingOnMainThreadMonitor, env->getTimer())) {
/*
* Since the mutator should double beat signal the mutator threads to update their
* timer with the current time.
*/
setStartTimeOfCurrentMutatorSlice(env->getTimer()->getTimeInNanos());
didGC = false;
goto exit;
}
} else {
didGC = false;
goto exit;
}
}
break;
}
}
if (NULL == _threadWaitingOnMainThreadMonitor) {
/*
* The gc thread(s) are already awake and collecting (otherwise, the main
* gc thread would be waiting on the monitor).
* This also means that the application threads are already sleeping.
* So there is no need to put the application threads to sleep or to
* awaken the gc thread(s). However we return true to indicate that
* garbage collection is indeed taking place as requested.
*/
goto exit;
}
/* At this point main thread is blocked and cannot change _gcOn flag anymore.
* Check the flag again, since there is (a small) chance it may have changed since the last check
* (main thread, driven by mutators' could have finished the GC cycle)
*/
if (!isGCOn()) {
didGC = false;
goto exit;
}
_exclusiveVMAccessRequired = doRequestExclusiveVMAccess;
_mode = WAKING_GC;
if (_exclusiveVMAccessRequired) {
/* initiate the request for exclusive VM access; this function does not wait for exclusive access to occur,
* that will be done by the main gc thread when it resumes activity after the mainThreadMonitor is notified
* We do not block. It's best effort. If the request is success full TRUE is returned via requested flag.
*/
if (FALSE == _gc->getRealtimeDelegate()->requestExclusiveVMAccess(_threadWaitingOnMainThreadMonitor, FALSE /* do not block */, &gcPriority)) {
didGC = false;
goto exit;
}
_gc->setGCThreadPriority(env->getOmrVMThread(), gcPriority);
}
omrthread_monitor_notify(_mainThreadMonitor);
/* set the waiting thread to NULL while we are in the _mainThreadMonitor so that nobody else will notify the waiting thread */
_threadWaitingOnMainThreadMonitor = NULL;
exit:
if (_extensions->trackMutatorThreadCategory) {
/* Done doing GC, reset the category back to the old one */
omrthread_set_category(omrthread_self(), 0, J9THREAD_TYPE_SET_GC);
}
omrthread_monitor_exit(_mainThreadMonitor);
_gc->getRealtimeDelegate()->postRequestExclusiveVMAccess(thr);
return didGC;
}
uintptr_t
MM_Scheduler::getTaskThreadCount(MM_EnvironmentBase *env)
{
if (NULL == env->_currentTask) {
return 1;
}
return env->_currentTask->getThreadCount();
}
void
MM_Scheduler::waitForMutatorsToStop(MM_EnvironmentRealtime *env)
{
/* assumption: only main enters this */
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
/* we need to record how long it took to wait for the mutators to stop */
uint64_t exclusiveAccessTime = omrtime_hires_clock();
/* The time before acquiring exclusive VM access is charged to the mutator but the time
* during the acquisition is conservatively charged entirely to the GC. */
_utilTracker->addTimeSlice(env, env->getTimer(), true);
omrthread_monitor_enter(_mainThreadMonitor);
/* If main GC thread gets here without anybody requesting exclusive access for us
* (possible in a shutdown scenario after we kill alarm thread), the thread will request
* exclusive access for itself.
* requestExclusiveVMAccess is invoked atomically with _mode being set to WAKING_GC
* under mainThreadMonitor (see continueGC). Therefore, we check here if mode is not
* WAKING_GC, and only then we request exclusive assess for ourselves.
* TODO: This approach is just to fix some timing holes in shutdown. Consider removing this
* "if" statement and fix alarm thread not to die before requesting exclusive access for us.
*/
if (_mainThreadMustShutDown && (WAKING_GC != _mode)) {
uintptr_t gcPriority = 0;
_gc->getRealtimeDelegate()->requestExclusiveVMAccess(env, TRUE /* block */, &gcPriority);
_gc->setGCThreadPriority(env->getOmrVMThread(), gcPriority);
}
/* Avoid another attempt to start up GC increment */
_mode = STOP_MUTATOR;
omrthread_monitor_exit(_mainThreadMonitor);
_gc->getRealtimeDelegate()->waitForExclusiveVMAccess(env, _exclusiveVMAccessRequired);
_mode = RUNNING_GC;
_extensions->globalGCStats.metronomeStats._microsToStopMutators = omrtime_hires_delta(exclusiveAccessTime, omrtime_hires_clock(), OMRPORT_TIME_DELTA_IN_MICROSECONDS);
}
void
MM_Scheduler::startMutators(MM_EnvironmentRealtime *env) {
_mode = WAKING_MUTATOR;
_gc->getRealtimeDelegate()->releaseExclusiveVMAccess(env, _exclusiveVMAccessRequired);
}
void
MM_Scheduler::startGCTime(MM_EnvironmentRealtime *env, bool isDoubleBeat)
{
if (env->isMainThread()) {
setStartTimeOfCurrentGCSlice(_utilTracker->addTimeSlice(env, env->getTimer(), false));
}
}
void
MM_Scheduler::stopGCTime(MM_EnvironmentRealtime *env)
{
if (env->isMainThread()) {
setStartTimeOfCurrentMutatorSlice(_utilTracker->addTimeSlice(env, env->getTimer(), false));
}
}
bool
MM_Scheduler::shouldGCDoubleBeat(MM_EnvironmentRealtime *env)
{
double targetUtilization = _utilTracker->getTargetUtilization();
if (targetUtilization <= 0.0) {
return true;
}
int32_t maximumAllowedConsecutiveBeats = (int32_t) (1.0 / targetUtilization);
if (_currentConsecutiveBeats >= maximumAllowedConsecutiveBeats) {
return false;
}
/* Note that shouldGCDoubleBeat is only called by the main thread, this means we
* can call addTimeSlice without checking for isMainThread() */
_utilTracker->addTimeSlice(env, env->getTimer(), false);
double excessTime = (_utilTracker->getCurrentUtil() - targetUtilization) * _window;
double excessBeats = excessTime / _beat;
return (excessBeats >= 2.0);
}
bool
MM_Scheduler::shouldMutatorDoubleBeat(MM_EnvironmentRealtime *env, MM_Timer *timer)
{
_utilTracker->addTimeSlice(env, timer, true);
/* The call to currentUtil will modify the timeSlice array, so calls to shouldMutatorDoubleBeat
* must be protected by a mutex (which is indeed currently the case) */
double curUtil = _utilTracker->getCurrentUtil();
double excessTime = (curUtil - _utilTracker->getTargetUtilization()) * _window;
double excessBeats = excessTime / _beat;
return (excessBeats <= 1.0);
}
void
MM_Scheduler::reportStartGCIncrement(MM_EnvironmentRealtime *env)
{
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
if (_completeCurrentGCSynchronously) {
_completeCurrentGCSynchronouslyMainThreadCopy = true;
uint64_t exclusiveAccessTimeMicros = 0;
uint64_t meanExclusiveAccessIdleTimeMicros = 0;
Trc_MM_SystemGCStart(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 )
);
exclusiveAccessTimeMicros = omrtime_hires_delta(0, env->getExclusiveAccessTime(), OMRPORT_TIME_DELTA_IN_MICROSECONDS);
meanExclusiveAccessIdleTimeMicros = omrtime_hires_delta(0, env->getMeanExclusiveAccessIdleTime(), OMRPORT_TIME_DELTA_IN_MICROSECONDS);
Trc_MM_ExclusiveAccess(env->getLanguageVMThread(),
(uint32_t)(exclusiveAccessTimeMicros / 1000),
(uint32_t)(exclusiveAccessTimeMicros % 1000),
(uint32_t)(meanExclusiveAccessIdleTimeMicros / 1000),
(uint32_t)(meanExclusiveAccessIdleTimeMicros % 1000),
env->getExclusiveAccessHaltedThreads(),
env->getLastExclusiveAccessResponder(),
env->exclusiveAccessBeatenByOtherThread());
_gc->reportSyncGCStart(env, _completeCurrentGCSynchronouslyReason, _completeCurrentGCSynchronouslyReasonParameter);
}
/* GC start/end are reported at each GC increment,
* not at the beginning/end of a GC cycle,
* since no Java code is supposed to run between those two events */
_extensions->globalGCStats.metronomeStats.clearStart();
_gc->reportGCStart(env);
TRIGGER_J9HOOK_MM_PRIVATE_METRONOME_INCREMENT_START(_extensions->privateHookInterface, env->getOmrVMThread(), omrtime_hires_clock(), J9HOOK_MM_PRIVATE_METRONOME_INCREMENT_START, _extensions->globalGCStats.metronomeStats._microsToStopMutators);
_currentConsecutiveBeats = 1;
startGCTime(env, false);
_gc->flushCachesForGC(env);
}
void
MM_Scheduler::reportStopGCIncrement(MM_EnvironmentRealtime *env, bool isCycleEnd)
{
/* assumption: only main enters this */
stopGCTime(env);
/* This can not be combined with the reportGCCycleEnd below as it has to happen before
* the incrementEnd event is triggered.
*/
if (isCycleEnd) {
if (_completeCurrentGCSynchronously) {
/* The requests for Sync GC made at the very end of
* GC cycle might not had a chance to make the local copy
*/
if (_completeCurrentGCSynchronouslyMainThreadCopy) {
Trc_MM_SystemGCEnd(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 )
);
_gc->reportSyncGCEnd(env);
_completeCurrentGCSynchronouslyMainThreadCopy = false;
}
_completeCurrentGCSynchronously = false;
_completeCurrentGCSynchronouslyReason = UNKOWN_REASON;
}
}
OMRPORT_ACCESS_FROM_ENVIRONMENT(env);
TRIGGER_J9HOOK_MM_PRIVATE_METRONOME_INCREMENT_END(_extensions->privateHookInterface, env->getOmrVMThread(), omrtime_hires_clock(), J9HOOK_MM_PRIVATE_METRONOME_INCREMENT_END,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
);
/* GC start/end are reported at each GC increment,
* not at the beginning/end of a GC cycle,
* since no Java code is supposed to run between those two events */
_gc->reportGCEnd(env);
_extensions->globalGCStats.metronomeStats.clearEnd();
}
void
MM_Scheduler::restartMutatorsAndWait(MM_EnvironmentRealtime *env)
{
startMutators(env);
omrthread_monitor_enter(_mainThreadMonitor);
/* Atomically change mode to MUTATOR and set threadWaitingOnMainThreadMonitor
* (only after the main is fully stoped, we switch from WAKING_MUTATOR to MUTATOR) */
_mode = MUTATOR;
_threadWaitingOnMainThreadMonitor = env;
/* If we're shutting down, we don't want to wait. Note that this is safe
* since on shutdown, the only mutator thread left is the thread that is
* doing the shutdown.
*/
if (!_mainThreadMustShutDown) {
omrthread_monitor_wait(_mainThreadMonitor);
/* Main is awoken to either do another increment of GC or
* to shutdown (but never both)
*/
Assert_MM_true((isGCOn() && !_mainThreadMustShutDown) || (!_gcOn &&_mainThreadMustShutDown));
}
omrthread_monitor_exit(_mainThreadMonitor);
}
bool
MM_Scheduler::shouldGCYield(MM_EnvironmentRealtime *env, uint64_t timeSlack)
{
return internalShouldGCYield(env, timeSlack);
}
/**
* Test whether it's time for the GC to yield, and whether yielding is currently enabled.
* To enhance the generality of methods that may call this method, the call may occur on
* a non-GC thread, in which case this method does nothing.
* @param timeSlack a slack factor to apply to time-based scheduling
* @param location the phase of the GC during which this call is occurring (for tracing: in
* some cases may be approximate).
* @return true if the GC thread should yield, false otherwise
*/
MMINLINE bool
MM_Scheduler::internalShouldGCYield(MM_EnvironmentRealtime *env, uint64_t timeSlack)
{
if (_completeCurrentGCSynchronouslyMainThreadCopy) {
/* If we have degraded to a synchronous GC, don't yield until finished */
return false;
}
/* Be harmless when called indirectly on mutator thread */
if (MUTATOR_THREAD == env->getThreadType()) {
return false;
}
/* The GC does not have to yield when ConcurrentTracing or ConcurrentSweeping is
* enabled since the GC is not holding exclusive access.
*/
if (_gc->isCollectorConcurrentTracing() || _gc->isCollectorConcurrentSweeping()) {
return false;
}
/* If at least one thread thinks we should yield, than all should yield.
* Discrepancy may happen due different timeSlack that GC threads may have */
if (_shouldGCYield) {
return true;
}
if (env->hasDistanceToYieldTimeCheck()) {
return false;
}
int64_t nanosLeft = _utilTracker->getNanosLeft(env, getStartTimeOfCurrentGCSlice());
if (nanosLeft > 0) {
if ((uint64_t)nanosLeft > timeSlack) {
return false;
}
}
_shouldGCYield = true;
return true;
}
bool
MM_Scheduler::condYieldFromGCWrapper(MM_EnvironmentBase *env, uint64_t timeSlack)
{
return condYieldFromGC(env, timeSlack);
}
/**
* Test whether it's time for the GC to yield, and whether yielding is currently enabled, and
* if appropriate actually do the yielding. To enhance the generality of methods that may
* call this method, the call may occur on a non-GC thread, in which case this method does
* nothing.
* @param location the phase of the GC during which this call is occurring (for tracing: in
* some cases may be approximate).
* @param timeSlack a slack factor to apply to time-based scheduling
* @return true if yielding actually occurred, false otherwise
*/
bool
MM_Scheduler::condYieldFromGC(MM_EnvironmentBase *envBase, uint64_t timeSlack)
{
MM_EnvironmentRealtime *env = MM_EnvironmentRealtime::getEnvironment(envBase);
if (env->getYieldDisableDepth() > 0) {
return false;
}
if (!internalShouldGCYield(env, timeSlack)) {
return false;
}
yieldFromGC(env, true);
env->resetCurrentDistanceToYieldTimeCheck();
return true;
}
void MM_Scheduler::yieldFromGC(MM_EnvironmentRealtime *env, bool distanceChecked)
{
assert(!_gc->isCollectorConcurrentTracing());
assert(!_gc->isCollectorConcurrentSweeping());
if (env->isMainThread()) {
if (_yieldCollaborator) {
/* wait for workers to yield/sync */
_yieldCollaborator->yield(env);
}
_sharedBarrierState = shouldGCDoubleBeat(env);
if (_sharedBarrierState) {
_currentConsecutiveBeats += 1;
startGCTime(env, true);
} else {
reportStopGCIncrement(env);
env->reportScanningSuspended();
Assert_MM_true(isGCOn());
restartMutatorsAndWait(env);
waitForMutatorsToStop(env);
env->reportScanningResumed();
reportStartGCIncrement(env);
_shouldGCYield = false;
}
if (_yieldCollaborator) {
_yieldCollaborator->resumeWorkersFromYield(env);
}
} else {
/* Worker only running here. _yieldCollaborator instance exists for sure */
env->reportScanningSuspended();
_yieldCollaborator->yield(env);
env->reportScanningResumed();
}
}
void
MM_Scheduler::prepareThreadsForTask(MM_EnvironmentBase *env, MM_Task *task, uintptr_t threadCount)
{
omrthread_monitor_enter(_workerThreadMutex);
_workerThreadsReservedForGC = true;
uintptr_t activeThreads = recomputeActiveThreadCountForTask(env, task, threadCount);
task->mainSetup(env);
task->setSynchronizeMutex(_synchronizeMutex);
for (uintptr_t index = 0; index < activeThreads; index++) {
_statusTable[index] = worker_status_reserved;
_taskTable[index] = task;
}
wakeUpThreads(activeThreads);
omrthread_monitor_exit(_workerThreadMutex);
pushYieldCollaborator(((MM_IncrementalParallelTask *)task)->getYieldCollaborator());
}
void
MM_Scheduler::completeTask(MM_EnvironmentBase *env)
{
if (env->isMainThread()) {
popYieldCollaborator();
}
MM_ParallelDispatcher::completeTask(env);
}
bool
MM_Scheduler::startUpThreads()
{
OMRPORT_ACCESS_FROM_OMRVM(_vm);
MM_EnvironmentRealtime env(_vm);
if (_extensions->gcThreadCount > _osInterface->getNumbersOfProcessors()) {
omrtty_printf("Please specify fewer GC threads than the number of physical processors.\n");
return false;
}
/* Start up the GC threads */
if (!MM_ParallelDispatcher::startUpThreads()) {
return false;
}
/* At this point, all GC threads have signalled that they are ready.
* However, because Metronome uses omrthread_suspend/omrthread_resume to stop and
* start threads, there is a race: the thread may have been preempted after
* signalling but before suspending itself. An alternative may be to use
* omrthread_park/unpark.
*/
_isInitialized = true;
/* Now that the GC threads are started, it is safe to start the alarm thread */
_alarmThread = MM_MetronomeAlarmThread::newInstance(&env);
if (NULL == _alarmThread) {
omrtty_printf("Unable to initialize alarm thread for time-based GC scheduling\n");
omrtty_printf("Most likely cause is non-supported version of OS\n");
return false;
}
if (verbose() >= 1) {
showParameters(&env);
}
return true;
}
/**
* @copydoc MM_ParallelDispatcher::recomputeActiveThreadCount()
* This function is called at the start of a complete GC cycle to calculate the number of
* GC threads to use for the cycle.
*/
void
MM_Scheduler::recomputeActiveThreadCount(MM_EnvironmentBase *env)
{
_activeThreadCount = _threadCount;
}
/**
* @copydoc MM_ParallelDispatcher::getThreadPriority()
*/
uintptr_t
MM_Scheduler::getThreadPriority()
{
/* this is the priority that the threads are started with */
return J9THREAD_PRIORITY_USER_MAX + 1;
}
/**
* @copydoc MM_MetronomeDispatcher::workerEntryPoint()
*/
void
MM_Scheduler::workerEntryPoint(MM_EnvironmentBase *envModron)
{
MM_EnvironmentRealtime *env = MM_EnvironmentRealtime::getEnvironment(envModron);
uintptr_t workerID = env->getWorkerID();
setThreadInitializationComplete(env);
omrthread_monitor_enter(_workerThreadMutex);
while (worker_status_dying != _statusTable[workerID]) {
/* Wait for a task to be dispatched to the worker thread */
while (worker_status_waiting == _statusTable[workerID]) {
omrthread_monitor_wait(_workerThreadMutex);
}
if (worker_status_reserved == _statusTable[workerID]) {
/* Found a task to dispatch to - do prep work for dispatch */
acceptTask(env);
omrthread_monitor_exit(_workerThreadMutex);
env->_currentTask->run(env);
omrthread_monitor_enter(_workerThreadMutex);
/* Returned from task - do clean up work from dispatch */
completeTask(env);
}
}
omrthread_monitor_exit(_workerThreadMutex);
}
/**
* @copydoc MM_ParallelDispatcher::mainEntryPoint()
*/
void
MM_Scheduler::mainEntryPoint(MM_EnvironmentBase *envModron)
{
MM_EnvironmentRealtime *env = MM_EnvironmentRealtime::getEnvironment(envModron);
setThreadInitializationComplete(env);
omrthread_monitor_enter(_mainThreadMonitor);
_threadWaitingOnMainThreadMonitor = env;
omrthread_monitor_wait(_mainThreadMonitor);
omrthread_monitor_exit(_mainThreadMonitor);
/* We want to execute the body of the do-while (run a gc) if a shutdown has
* been requested at the same time as the first gc. In other words, we want
* a gc to complete before shutting down.
*
* We however do not want to execute a gc if it hasn't been requested. The
* outer while loop guarantees this. It is a while loop (as opposed to an
* if) to cover the case of simultaneous gc/shutdown while waiting in
* stopGCIntervalAndWait. Again, we want to complete the gc in that case.
*/
while (isGCOn()) {
do {
/* Before starting a new GC, recompute the number of threads to use */
recomputeActiveThreadCount(env);
waitForMutatorsToStop(env);
/* note that the cycle and increment start events will be posted from MM_RealtimeGC::internalPreCollect */
_gc->_memorySubSpace->collect(env, _gcCode);
restartMutatorsAndWait(env);
/* We must also check for the _mainThreadMustShutDown flag since if we
* try to shutdown while we're in a stopGCIntervalAndWait, the GC will
* continue potentially changing the status of the main thread
*/
} while ((worker_status_dying != _statusTable[env->getWorkerID()] && !_mainThreadMustShutDown));
}
/* TODO: tear down the thread before exiting */
}
/**
* If there is an ongoing GC cycle complete it
*/
void
MM_Scheduler::completeCurrentGCSynchronously(MM_EnvironmentRealtime *env)
{
omrthread_monitor_enter(_vm->_gcCycleOnMonitor);
if (_vm->_gcCycleOn || isGCOn()) {
_completeCurrentGCSynchronously = true;
_completeCurrentGCSynchronouslyReason = VM_SHUTDOWN;
/* wait till get notified by main that the cycle is finished */
omrthread_monitor_wait(_vm->_gcCycleOnMonitor);
}
omrthread_monitor_exit(_vm->_gcCycleOnMonitor);
}
/**
* @copydoc MM_ParallelDispatcher::wakeUpThreads()
*/
void
MM_Scheduler::wakeUpThreads(uintptr_t count)
{
assert1(count > 0);
/* Resume the main thread */
omrthread_monitor_enter(_mainThreadMonitor);
omrthread_monitor_notify(_mainThreadMonitor);
omrthread_monitor_exit(_mainThreadMonitor);
if (count > 1) {
wakeUpWorkerThreads(count - 1);
}
}
/**
* Wakes up `count` worker threads. This function will actually busy wait until
* `count` number of workers have been resumed from the suspended state.
*
* @param count Number of worker threads to wake up
*/
void
MM_Scheduler::wakeUpWorkerThreads(uintptr_t count)
{
omrthread_monitor_notify_all(_workerThreadMutex);
}
/**
* @copydoc MM_ParallelDispatcher::shutDownThreads()
*/
void
MM_Scheduler::shutDownThreads()
{
/* This will stop threads from requesting another GC cycle to start*/
_isInitialized = false;
/* If the GC is currently in a Cycle complete it before we shutdown */
completeCurrentGCSynchronously();