-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
g1ConcurrentMark.cpp
3085 lines (2577 loc) · 113 KB
/
g1ConcurrentMark.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) 2001, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/classLoaderDataGraph.hpp"
#include "classfile/systemDictionary.hpp"
#include "code/codeCache.hpp"
#include "gc/g1/g1BarrierSet.hpp"
#include "gc/g1/g1BatchedTask.hpp"
#include "gc/g1/g1CardSetMemory.hpp"
#include "gc/g1/g1CollectedHeap.inline.hpp"
#include "gc/g1/g1CollectorState.hpp"
#include "gc/g1/g1ConcurrentMark.inline.hpp"
#include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
#include "gc/g1/g1DirtyCardQueue.hpp"
#include "gc/g1/g1HeapVerifier.hpp"
#include "gc/g1/g1OopClosures.inline.hpp"
#include "gc/g1/g1Policy.hpp"
#include "gc/g1/g1RegionMarkStatsCache.inline.hpp"
#include "gc/g1/g1ThreadLocalData.hpp"
#include "gc/g1/g1Trace.hpp"
#include "gc/g1/heapRegion.inline.hpp"
#include "gc/g1/heapRegionManager.hpp"
#include "gc/g1/heapRegionRemSet.inline.hpp"
#include "gc/g1/heapRegionSet.inline.hpp"
#include "gc/shared/gcId.hpp"
#include "gc/shared/gcTimer.hpp"
#include "gc/shared/gcTraceTime.inline.hpp"
#include "gc/shared/gcVMOperations.hpp"
#include "gc/shared/genOopClosures.inline.hpp"
#include "gc/shared/referencePolicy.hpp"
#include "gc/shared/strongRootsScope.hpp"
#include "gc/shared/suspendibleThreadSet.hpp"
#include "gc/shared/taskTerminator.hpp"
#include "gc/shared/taskqueue.inline.hpp"
#include "gc/shared/weakProcessor.inline.hpp"
#include "gc/shared/workerPolicy.hpp"
#include "include/jvm.h"
#include "logging/log.hpp"
#include "memory/allocation.hpp"
#include "memory/iterator.hpp"
#include "memory/metaspaceUtils.hpp"
#include "memory/resourceArea.hpp"
#include "memory/universe.hpp"
#include "oops/access.inline.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/atomic.hpp"
#include "runtime/continuation.hpp"
#include "runtime/globals_extension.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/orderAccess.hpp"
#include "runtime/prefetch.inline.hpp"
#include "services/memTracker.hpp"
#include "utilities/align.hpp"
#include "utilities/formatBuffer.hpp"
#include "utilities/growableArray.hpp"
bool G1CMBitMapClosure::do_addr(HeapWord* const addr) {
assert(addr < _cm->finger(), "invariant");
assert(addr >= _task->finger(), "invariant");
// We move that task's local finger along.
_task->move_finger_to(addr);
_task->scan_task_entry(G1TaskQueueEntry::from_oop(cast_to_oop(addr)));
// we only partially drain the local queue and global stack
_task->drain_local_queue(true);
_task->drain_global_stack(true);
// if the has_aborted flag has been raised, we need to bail out of
// the iteration
return !_task->has_aborted();
}
G1CMMarkStack::G1CMMarkStack() :
_max_chunk_capacity(0),
_base(NULL),
_chunk_capacity(0) {
set_empty();
}
bool G1CMMarkStack::resize(size_t new_capacity) {
assert(is_empty(), "Only resize when stack is empty.");
assert(new_capacity <= _max_chunk_capacity,
"Trying to resize stack to " SIZE_FORMAT " chunks when the maximum is " SIZE_FORMAT, new_capacity, _max_chunk_capacity);
TaskQueueEntryChunk* new_base = MmapArrayAllocator<TaskQueueEntryChunk>::allocate_or_null(new_capacity, mtGC);
if (new_base == NULL) {
log_warning(gc)("Failed to reserve memory for new overflow mark stack with " SIZE_FORMAT " chunks and size " SIZE_FORMAT "B.", new_capacity, new_capacity * sizeof(TaskQueueEntryChunk));
return false;
}
// Release old mapping.
if (_base != NULL) {
MmapArrayAllocator<TaskQueueEntryChunk>::free(_base, _chunk_capacity);
}
_base = new_base;
_chunk_capacity = new_capacity;
set_empty();
return true;
}
size_t G1CMMarkStack::capacity_alignment() {
return (size_t)lcm(os::vm_allocation_granularity(), sizeof(TaskQueueEntryChunk)) / sizeof(G1TaskQueueEntry);
}
bool G1CMMarkStack::initialize(size_t initial_capacity, size_t max_capacity) {
guarantee(_max_chunk_capacity == 0, "G1CMMarkStack already initialized.");
size_t const TaskEntryChunkSizeInVoidStar = sizeof(TaskQueueEntryChunk) / sizeof(G1TaskQueueEntry);
_max_chunk_capacity = align_up(max_capacity, capacity_alignment()) / TaskEntryChunkSizeInVoidStar;
size_t initial_chunk_capacity = align_up(initial_capacity, capacity_alignment()) / TaskEntryChunkSizeInVoidStar;
guarantee(initial_chunk_capacity <= _max_chunk_capacity,
"Maximum chunk capacity " SIZE_FORMAT " smaller than initial capacity " SIZE_FORMAT,
_max_chunk_capacity,
initial_chunk_capacity);
log_debug(gc)("Initialize mark stack with " SIZE_FORMAT " chunks, maximum " SIZE_FORMAT,
initial_chunk_capacity, _max_chunk_capacity);
return resize(initial_chunk_capacity);
}
void G1CMMarkStack::expand() {
if (_chunk_capacity == _max_chunk_capacity) {
log_debug(gc)("Can not expand overflow mark stack further, already at maximum capacity of " SIZE_FORMAT " chunks.", _chunk_capacity);
return;
}
size_t old_capacity = _chunk_capacity;
// Double capacity if possible
size_t new_capacity = MIN2(old_capacity * 2, _max_chunk_capacity);
if (resize(new_capacity)) {
log_debug(gc)("Expanded mark stack capacity from " SIZE_FORMAT " to " SIZE_FORMAT " chunks",
old_capacity, new_capacity);
} else {
log_warning(gc)("Failed to expand mark stack capacity from " SIZE_FORMAT " to " SIZE_FORMAT " chunks",
old_capacity, new_capacity);
}
}
G1CMMarkStack::~G1CMMarkStack() {
if (_base != NULL) {
MmapArrayAllocator<TaskQueueEntryChunk>::free(_base, _chunk_capacity);
}
}
void G1CMMarkStack::add_chunk_to_list(TaskQueueEntryChunk* volatile* list, TaskQueueEntryChunk* elem) {
elem->next = *list;
*list = elem;
}
void G1CMMarkStack::add_chunk_to_chunk_list(TaskQueueEntryChunk* elem) {
MutexLocker x(MarkStackChunkList_lock, Mutex::_no_safepoint_check_flag);
add_chunk_to_list(&_chunk_list, elem);
_chunks_in_chunk_list++;
}
void G1CMMarkStack::add_chunk_to_free_list(TaskQueueEntryChunk* elem) {
MutexLocker x(MarkStackFreeList_lock, Mutex::_no_safepoint_check_flag);
add_chunk_to_list(&_free_list, elem);
}
G1CMMarkStack::TaskQueueEntryChunk* G1CMMarkStack::remove_chunk_from_list(TaskQueueEntryChunk* volatile* list) {
TaskQueueEntryChunk* result = *list;
if (result != NULL) {
*list = (*list)->next;
}
return result;
}
G1CMMarkStack::TaskQueueEntryChunk* G1CMMarkStack::remove_chunk_from_chunk_list() {
MutexLocker x(MarkStackChunkList_lock, Mutex::_no_safepoint_check_flag);
TaskQueueEntryChunk* result = remove_chunk_from_list(&_chunk_list);
if (result != NULL) {
_chunks_in_chunk_list--;
}
return result;
}
G1CMMarkStack::TaskQueueEntryChunk* G1CMMarkStack::remove_chunk_from_free_list() {
MutexLocker x(MarkStackFreeList_lock, Mutex::_no_safepoint_check_flag);
return remove_chunk_from_list(&_free_list);
}
G1CMMarkStack::TaskQueueEntryChunk* G1CMMarkStack::allocate_new_chunk() {
// This dirty read of _hwm is okay because we only ever increase the _hwm in parallel code.
// Further this limits _hwm to a value of _chunk_capacity + #threads, avoiding
// wraparound of _hwm.
if (_hwm >= _chunk_capacity) {
return NULL;
}
size_t cur_idx = Atomic::fetch_and_add(&_hwm, 1u);
if (cur_idx >= _chunk_capacity) {
return NULL;
}
TaskQueueEntryChunk* result = ::new (&_base[cur_idx]) TaskQueueEntryChunk;
result->next = NULL;
return result;
}
bool G1CMMarkStack::par_push_chunk(G1TaskQueueEntry* ptr_arr) {
// Get a new chunk.
TaskQueueEntryChunk* new_chunk = remove_chunk_from_free_list();
if (new_chunk == NULL) {
// Did not get a chunk from the free list. Allocate from backing memory.
new_chunk = allocate_new_chunk();
if (new_chunk == NULL) {
return false;
}
}
Copy::conjoint_memory_atomic(ptr_arr, new_chunk->data, EntriesPerChunk * sizeof(G1TaskQueueEntry));
add_chunk_to_chunk_list(new_chunk);
return true;
}
bool G1CMMarkStack::par_pop_chunk(G1TaskQueueEntry* ptr_arr) {
TaskQueueEntryChunk* cur = remove_chunk_from_chunk_list();
if (cur == NULL) {
return false;
}
Copy::conjoint_memory_atomic(cur->data, ptr_arr, EntriesPerChunk * sizeof(G1TaskQueueEntry));
add_chunk_to_free_list(cur);
return true;
}
void G1CMMarkStack::set_empty() {
_chunks_in_chunk_list = 0;
_hwm = 0;
_chunk_list = NULL;
_free_list = NULL;
}
G1CMRootMemRegions::G1CMRootMemRegions(uint const max_regions) :
_root_regions(MemRegion::create_array(max_regions, mtGC)),
_max_regions(max_regions),
_num_root_regions(0),
_claimed_root_regions(0),
_scan_in_progress(false),
_should_abort(false) { }
G1CMRootMemRegions::~G1CMRootMemRegions() {
MemRegion::destroy_array(_root_regions, _max_regions);
}
void G1CMRootMemRegions::reset() {
_num_root_regions = 0;
}
void G1CMRootMemRegions::add(HeapWord* start, HeapWord* end) {
assert_at_safepoint();
size_t idx = Atomic::fetch_and_add(&_num_root_regions, 1u);
assert(idx < _max_regions, "Trying to add more root MemRegions than there is space " SIZE_FORMAT, _max_regions);
assert(start != NULL && end != NULL && start <= end, "Start (" PTR_FORMAT ") should be less or equal to "
"end (" PTR_FORMAT ")", p2i(start), p2i(end));
_root_regions[idx].set_start(start);
_root_regions[idx].set_end(end);
}
void G1CMRootMemRegions::prepare_for_scan() {
assert(!scan_in_progress(), "pre-condition");
_scan_in_progress = _num_root_regions > 0;
_claimed_root_regions = 0;
_should_abort = false;
}
const MemRegion* G1CMRootMemRegions::claim_next() {
if (_should_abort) {
// If someone has set the should_abort flag, we return NULL to
// force the caller to bail out of their loop.
return NULL;
}
if (_claimed_root_regions >= _num_root_regions) {
return NULL;
}
size_t claimed_index = Atomic::fetch_and_add(&_claimed_root_regions, 1u);
if (claimed_index < _num_root_regions) {
return &_root_regions[claimed_index];
}
return NULL;
}
uint G1CMRootMemRegions::num_root_regions() const {
return (uint)_num_root_regions;
}
void G1CMRootMemRegions::notify_scan_done() {
MutexLocker x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
_scan_in_progress = false;
RootRegionScan_lock->notify_all();
}
void G1CMRootMemRegions::cancel_scan() {
notify_scan_done();
}
void G1CMRootMemRegions::scan_finished() {
assert(scan_in_progress(), "pre-condition");
if (!_should_abort) {
assert(_claimed_root_regions >= num_root_regions(),
"we should have claimed all root regions, claimed " SIZE_FORMAT ", length = %u",
_claimed_root_regions, num_root_regions());
}
notify_scan_done();
}
bool G1CMRootMemRegions::wait_until_scan_finished() {
if (!scan_in_progress()) {
return false;
}
{
MonitorLocker ml(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
while (scan_in_progress()) {
ml.wait();
}
}
return true;
}
G1ConcurrentMark::G1ConcurrentMark(G1CollectedHeap* g1h,
G1RegionToSpaceMapper* prev_bitmap_storage,
G1RegionToSpaceMapper* next_bitmap_storage) :
// _cm_thread set inside the constructor
_g1h(g1h),
_mark_bitmap_1(),
_mark_bitmap_2(),
_prev_mark_bitmap(&_mark_bitmap_1),
_next_mark_bitmap(&_mark_bitmap_2),
_heap(_g1h->reserved()),
_root_regions(_g1h->max_regions()),
_global_mark_stack(),
// _finger set in set_non_marking_state
_worker_id_offset(G1DirtyCardQueueSet::num_par_ids() + G1ConcRefinementThreads),
_max_num_tasks(MAX2(ConcGCThreads, ParallelGCThreads)),
// _num_active_tasks set in set_non_marking_state()
// _tasks set inside the constructor
_task_queues(new G1CMTaskQueueSet((int) _max_num_tasks)),
_terminator((int) _max_num_tasks, _task_queues),
_first_overflow_barrier_sync(),
_second_overflow_barrier_sync(),
_has_overflown(false),
_concurrent(false),
_has_aborted(false),
_restart_for_overflow(false),
_gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
_gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()),
// _verbose_level set below
_init_times(),
_remark_times(),
_remark_mark_times(),
_remark_weak_ref_times(),
_cleanup_times(),
_total_cleanup_time(0.0),
_accum_task_vtime(NULL),
_concurrent_workers(NULL),
_num_concurrent_workers(0),
_max_concurrent_workers(0),
_region_mark_stats(NEW_C_HEAP_ARRAY(G1RegionMarkStats, _g1h->max_reserved_regions(), mtGC)),
_top_at_rebuild_starts(NEW_C_HEAP_ARRAY(HeapWord*, _g1h->max_reserved_regions(), mtGC)),
_needs_remembered_set_rebuild(false)
{
assert(CGC_lock != NULL, "CGC_lock must be initialized");
_mark_bitmap_1.initialize(g1h->reserved(), prev_bitmap_storage);
_mark_bitmap_2.initialize(g1h->reserved(), next_bitmap_storage);
// Create & start ConcurrentMark thread.
_cm_thread = new G1ConcurrentMarkThread(this);
if (_cm_thread->osthread() == NULL) {
vm_shutdown_during_initialization("Could not create ConcurrentMarkThread");
}
log_debug(gc)("ConcGCThreads: %u offset %u", ConcGCThreads, _worker_id_offset);
log_debug(gc)("ParallelGCThreads: %u", ParallelGCThreads);
_num_concurrent_workers = ConcGCThreads;
_max_concurrent_workers = _num_concurrent_workers;
_concurrent_workers = new WorkerThreads("G1 Conc", _max_concurrent_workers);
_concurrent_workers->initialize_workers();
if (!_global_mark_stack.initialize(MarkStackSize, MarkStackSizeMax)) {
vm_exit_during_initialization("Failed to allocate initial concurrent mark overflow mark stack.");
}
_tasks = NEW_C_HEAP_ARRAY(G1CMTask*, _max_num_tasks, mtGC);
_accum_task_vtime = NEW_C_HEAP_ARRAY(double, _max_num_tasks, mtGC);
// so that the assertion in MarkingTaskQueue::task_queue doesn't fail
_num_active_tasks = _max_num_tasks;
for (uint i = 0; i < _max_num_tasks; ++i) {
G1CMTaskQueue* task_queue = new G1CMTaskQueue();
_task_queues->register_queue(i, task_queue);
_tasks[i] = new G1CMTask(i, this, task_queue, _region_mark_stats);
_accum_task_vtime[i] = 0.0;
}
reset_at_marking_complete();
}
void G1ConcurrentMark::reset() {
_has_aborted = false;
reset_marking_for_restart();
// Reset all tasks, since different phases will use different number of active
// threads. So, it's easiest to have all of them ready.
for (uint i = 0; i < _max_num_tasks; ++i) {
_tasks[i]->reset(_next_mark_bitmap);
}
uint max_reserved_regions = _g1h->max_reserved_regions();
for (uint i = 0; i < max_reserved_regions; i++) {
_top_at_rebuild_starts[i] = NULL;
_region_mark_stats[i].clear();
}
_root_regions.reset();
}
void G1ConcurrentMark::clear_statistics_in_region(uint region_idx) {
for (uint j = 0; j < _max_num_tasks; ++j) {
_tasks[j]->clear_mark_stats_cache(region_idx);
}
_top_at_rebuild_starts[region_idx] = NULL;
_region_mark_stats[region_idx].clear();
}
void G1ConcurrentMark::clear_statistics(HeapRegion* r) {
uint const region_idx = r->hrm_index();
if (r->is_humongous()) {
assert(r->is_starts_humongous(), "Got humongous continues region here");
uint const size_in_regions = (uint)_g1h->humongous_obj_size_in_regions(cast_to_oop(r->humongous_start_region()->bottom())->size());
for (uint j = region_idx; j < (region_idx + size_in_regions); j++) {
clear_statistics_in_region(j);
}
} else {
clear_statistics_in_region(region_idx);
}
}
static void clear_mark_if_set(G1CMBitMap* bitmap, HeapWord* addr) {
if (bitmap->is_marked(addr)) {
bitmap->clear(addr);
}
}
void G1ConcurrentMark::humongous_object_eagerly_reclaimed(HeapRegion* r) {
assert_at_safepoint();
// Need to clear all mark bits of the humongous object.
clear_mark_if_set(_prev_mark_bitmap, r->bottom());
clear_mark_if_set(_next_mark_bitmap, r->bottom());
if (!_g1h->collector_state()->mark_or_rebuild_in_progress()) {
return;
}
// Clear any statistics about the region gathered so far.
clear_statistics(r);
}
void G1ConcurrentMark::reset_marking_for_restart() {
_global_mark_stack.set_empty();
// Expand the marking stack, if we have to and if we can.
if (has_overflown()) {
_global_mark_stack.expand();
uint max_reserved_regions = _g1h->max_reserved_regions();
for (uint i = 0; i < max_reserved_regions; i++) {
_region_mark_stats[i].clear_during_overflow();
}
}
clear_has_overflown();
_finger = _heap.start();
for (uint i = 0; i < _max_num_tasks; ++i) {
G1CMTaskQueue* queue = _task_queues->queue(i);
queue->set_empty();
}
}
void G1ConcurrentMark::set_concurrency(uint active_tasks) {
assert(active_tasks <= _max_num_tasks, "we should not have more");
_num_active_tasks = active_tasks;
// Need to update the three data structures below according to the
// number of active threads for this phase.
_terminator.reset_for_reuse(active_tasks);
_first_overflow_barrier_sync.set_n_workers((int) active_tasks);
_second_overflow_barrier_sync.set_n_workers((int) active_tasks);
}
void G1ConcurrentMark::set_concurrency_and_phase(uint active_tasks, bool concurrent) {
set_concurrency(active_tasks);
_concurrent = concurrent;
if (!concurrent) {
// At this point we should be in a STW phase, and completed marking.
assert_at_safepoint_on_vm_thread();
assert(out_of_regions(),
"only way to get here: _finger: " PTR_FORMAT ", _heap_end: " PTR_FORMAT,
p2i(_finger), p2i(_heap.end()));
}
}
void G1ConcurrentMark::reset_at_marking_complete() {
// We set the global marking state to some default values when we're
// not doing marking.
reset_marking_for_restart();
_num_active_tasks = 0;
}
G1ConcurrentMark::~G1ConcurrentMark() {
FREE_C_HEAP_ARRAY(HeapWord*, _top_at_rebuild_starts);
FREE_C_HEAP_ARRAY(G1RegionMarkStats, _region_mark_stats);
// The G1ConcurrentMark instance is never freed.
ShouldNotReachHere();
}
class G1ClearBitMapTask : public WorkerTask {
public:
static size_t chunk_size() { return M; }
private:
// Heap region closure used for clearing the _next_mark_bitmap.
class G1ClearBitmapHRClosure : public HeapRegionClosure {
private:
G1ConcurrentMark* _cm;
G1CMBitMap* _bitmap;
bool _suspendible; // If suspendible, do yield checks.
bool suspendible() {
return _suspendible;
}
bool is_clear_concurrent_undo() {
return suspendible() && _cm->cm_thread()->in_undo_mark();
}
bool has_aborted() {
if (suspendible()) {
_cm->do_yield_check();
return _cm->has_aborted();
}
return false;
}
HeapWord* region_clear_limit(HeapRegion* r) {
// During a Concurrent Undo Mark cycle, the _next_mark_bitmap is cleared
// without swapping with the _prev_mark_bitmap. Therefore, the per region
// next_top_at_mark_start and live_words data are current wrt
// _next_mark_bitmap. We use this information to only clear ranges of the
// bitmap that require clearing.
if (is_clear_concurrent_undo()) {
// No need to clear bitmaps for empty regions.
if (_cm->live_words(r->hrm_index()) == 0) {
assert(_bitmap->get_next_marked_addr(r->bottom(), r->end()) == r->end(), "Should not have marked bits");
return r->bottom();
}
assert(_bitmap->get_next_marked_addr(r->next_top_at_mark_start(), r->end()) == r->end(), "Should not have marked bits above ntams");
}
return r->end();
}
public:
G1ClearBitmapHRClosure(G1ConcurrentMark* cm, bool suspendible) :
HeapRegionClosure(),
_cm(cm),
_bitmap(cm->next_mark_bitmap()),
_suspendible(suspendible)
{ }
virtual bool do_heap_region(HeapRegion* r) {
if (has_aborted()) {
return true;
}
HeapWord* cur = r->bottom();
HeapWord* const end = region_clear_limit(r);
size_t const chunk_size_in_words = G1ClearBitMapTask::chunk_size() / HeapWordSize;
while (cur < end) {
MemRegion mr(cur, MIN2(cur + chunk_size_in_words, end));
_bitmap->clear_range(mr);
cur += chunk_size_in_words;
// Repeat the asserts from before the start of the closure. We will do them
// as asserts here to minimize their overhead on the product. However, we
// will have them as guarantees at the beginning / end of the bitmap
// clearing to get some checking in the product.
assert(!suspendible() || _cm->cm_thread()->in_progress(), "invariant");
assert(!suspendible() || !G1CollectedHeap::heap()->collector_state()->mark_or_rebuild_in_progress(), "invariant");
// Abort iteration if necessary.
if (has_aborted()) {
return true;
}
}
assert(cur >= end, "Must have completed iteration over the bitmap for region %u.", r->hrm_index());
return false;
}
};
G1ClearBitmapHRClosure _cl;
HeapRegionClaimer _hr_claimer;
bool _suspendible; // If the task is suspendible, workers must join the STS.
public:
G1ClearBitMapTask(G1ConcurrentMark* cm, uint n_workers, bool suspendible) :
WorkerTask("G1 Clear Bitmap"),
_cl(cm, suspendible),
_hr_claimer(n_workers),
_suspendible(suspendible)
{ }
void work(uint worker_id) {
SuspendibleThreadSetJoiner sts_join(_suspendible);
G1CollectedHeap::heap()->heap_region_par_iterate_from_worker_offset(&_cl, &_hr_claimer, worker_id);
}
bool is_complete() {
return _cl.is_complete();
}
};
void G1ConcurrentMark::clear_next_bitmap(WorkerThreads* workers, bool may_yield) {
assert(may_yield || SafepointSynchronize::is_at_safepoint(), "Non-yielding bitmap clear only allowed at safepoint.");
size_t const num_bytes_to_clear = (HeapRegion::GrainBytes * _g1h->num_regions()) / G1CMBitMap::heap_map_factor();
size_t const num_chunks = align_up(num_bytes_to_clear, G1ClearBitMapTask::chunk_size()) / G1ClearBitMapTask::chunk_size();
uint const num_workers = (uint)MIN2(num_chunks, (size_t)workers->active_workers());
G1ClearBitMapTask cl(this, num_workers, may_yield);
log_debug(gc, ergo)("Running %s with %u workers for " SIZE_FORMAT " work units.", cl.name(), num_workers, num_chunks);
workers->run_task(&cl, num_workers);
guarantee(may_yield || cl.is_complete(), "Must have completed iteration when not yielding.");
}
void G1ConcurrentMark::cleanup_for_next_mark() {
// Make sure that the concurrent mark thread looks to still be in
// the current cycle.
guarantee(cm_thread()->in_progress(), "invariant");
// We are finishing up the current cycle by clearing the next
// marking bitmap and getting it ready for the next cycle. During
// this time no other cycle can start. So, let's make sure that this
// is the case.
guarantee(!_g1h->collector_state()->mark_or_rebuild_in_progress(), "invariant");
clear_next_bitmap(_concurrent_workers, true);
// Repeat the asserts from above.
guarantee(cm_thread()->in_progress(), "invariant");
guarantee(!_g1h->collector_state()->mark_or_rebuild_in_progress(), "invariant");
}
void G1ConcurrentMark::clear_next_bitmap(WorkerThreads* workers) {
assert_at_safepoint_on_vm_thread();
// To avoid fragmentation the full collection requesting to clear the bitmap
// might use fewer workers than available. To ensure the bitmap is cleared
// as efficiently as possible the number of active workers are temporarily
// increased to include all currently created workers.
WithActiveWorkers update(workers, workers->created_workers());
clear_next_bitmap(workers, false);
}
class G1PreConcurrentStartTask : public G1BatchedTask {
// Concurrent start needs claim bits to keep track of the marked-through CLDs.
class CLDClearClaimedMarksTask;
// Reset marking state.
class ResetMarkingStateTask;
// For each region note start of marking.
class NoteStartOfMarkTask;
public:
G1PreConcurrentStartTask(GCCause::Cause cause, G1ConcurrentMark* cm);
};
class G1PreConcurrentStartTask::CLDClearClaimedMarksTask : public G1AbstractSubTask {
public:
CLDClearClaimedMarksTask() : G1AbstractSubTask(G1GCPhaseTimes::CLDClearClaimedMarks) { }
double worker_cost() const override { return 1.0; }
void do_work(uint worker_id) override;
};
class G1PreConcurrentStartTask::ResetMarkingStateTask : public G1AbstractSubTask {
G1ConcurrentMark* _cm;
public:
ResetMarkingStateTask(G1ConcurrentMark* cm) : G1AbstractSubTask(G1GCPhaseTimes::ResetMarkingState), _cm(cm) { }
double worker_cost() const override { return 1.0; }
void do_work(uint worker_id) override;
};
class G1PreConcurrentStartTask::NoteStartOfMarkTask : public G1AbstractSubTask {
HeapRegionClaimer _claimer;
public:
NoteStartOfMarkTask() : G1AbstractSubTask(G1GCPhaseTimes::NoteStartOfMark), _claimer(0) { }
double worker_cost() const override {
// The work done per region is very small, therefore we choose this magic number to cap the number
// of threads used when there are few regions.
const double regions_per_thread = 1000;
return _claimer.n_regions() / regions_per_thread;
}
void set_max_workers(uint max_workers) override;
void do_work(uint worker_id) override;
};
void G1PreConcurrentStartTask::CLDClearClaimedMarksTask::do_work(uint worker_id) {
ClassLoaderDataGraph::clear_claimed_marks();
}
void G1PreConcurrentStartTask::ResetMarkingStateTask::do_work(uint worker_id) {
// Reset marking state.
_cm->reset();
}
class NoteStartOfMarkHRClosure : public HeapRegionClosure {
public:
bool do_heap_region(HeapRegion* r) override {
r->note_start_of_marking();
return false;
}
};
void G1PreConcurrentStartTask::NoteStartOfMarkTask::do_work(uint worker_id) {
NoteStartOfMarkHRClosure start_cl;
G1CollectedHeap::heap()->heap_region_par_iterate_from_worker_offset(&start_cl, &_claimer, worker_id);
}
void G1PreConcurrentStartTask::NoteStartOfMarkTask::set_max_workers(uint max_workers) {
_claimer.set_n_workers(max_workers);
}
G1PreConcurrentStartTask::G1PreConcurrentStartTask(GCCause::Cause cause, G1ConcurrentMark* cm) :
G1BatchedTask("Pre Concurrent Start", G1CollectedHeap::heap()->phase_times()) {
add_serial_task(new CLDClearClaimedMarksTask());
add_serial_task(new ResetMarkingStateTask(cm));
add_parallel_task(new NoteStartOfMarkTask());
};
void G1ConcurrentMark::pre_concurrent_start(GCCause::Cause cause) {
assert_at_safepoint_on_vm_thread();
G1CollectedHeap::start_codecache_marking_cycle_if_inactive();
G1PreConcurrentStartTask cl(cause, this);
G1CollectedHeap::heap()->run_batch_task(&cl);
_gc_tracer_cm->set_gc_cause(cause);
}
void G1ConcurrentMark::post_concurrent_mark_start() {
// Start Concurrent Marking weak-reference discovery.
ReferenceProcessor* rp = _g1h->ref_processor_cm();
rp->start_discovery(false /* always_clear */);
SATBMarkQueueSet& satb_mq_set = G1BarrierSet::satb_mark_queue_set();
// This is the start of the marking cycle, we're expected all
// threads to have SATB queues with active set to false.
satb_mq_set.set_active_all_threads(true, /* new active value */
false /* expected_active */);
_root_regions.prepare_for_scan();
// update_g1_committed() will be called at the end of an evac pause
// when marking is on. So, it's also called at the end of the
// concurrent start pause to update the heap end, if the heap expands
// during it. No need to call it here.
}
void G1ConcurrentMark::post_concurrent_undo_start() {
root_regions()->cancel_scan();
}
/*
* Notice that in the next two methods, we actually leave the STS
* during the barrier sync and join it immediately afterwards. If we
* do not do this, the following deadlock can occur: one thread could
* be in the barrier sync code, waiting for the other thread to also
* sync up, whereas another one could be trying to yield, while also
* waiting for the other threads to sync up too.
*
* Note, however, that this code is also used during remark and in
* this case we should not attempt to leave / enter the STS, otherwise
* we'll either hit an assert (debug / fastdebug) or deadlock
* (product). So we should only leave / enter the STS if we are
* operating concurrently.
*
* Because the thread that does the sync barrier has left the STS, it
* is possible to be suspended for a Full GC or an evacuation pause
* could occur. This is actually safe, since the entering the sync
* barrier is one of the last things do_marking_step() does, and it
* doesn't manipulate any data structures afterwards.
*/
void G1ConcurrentMark::enter_first_sync_barrier(uint worker_id) {
bool barrier_aborted;
{
SuspendibleThreadSetLeaver sts_leave(concurrent());
barrier_aborted = !_first_overflow_barrier_sync.enter();
}
// at this point everyone should have synced up and not be doing any
// more work
if (barrier_aborted) {
// If the barrier aborted we ignore the overflow condition and
// just abort the whole marking phase as quickly as possible.
return;
}
}
void G1ConcurrentMark::enter_second_sync_barrier(uint worker_id) {
SuspendibleThreadSetLeaver sts_leave(concurrent());
_second_overflow_barrier_sync.enter();
// at this point everything should be re-initialized and ready to go
}
class G1CMConcurrentMarkingTask : public WorkerTask {
G1ConcurrentMark* _cm;
public:
void work(uint worker_id) {
ResourceMark rm;
double start_vtime = os::elapsedVTime();
{
SuspendibleThreadSetJoiner sts_join;
assert(worker_id < _cm->active_tasks(), "invariant");
G1CMTask* task = _cm->task(worker_id);
task->record_start_time();
if (!_cm->has_aborted()) {
do {
task->do_marking_step(G1ConcMarkStepDurationMillis,
true /* do_termination */,
false /* is_serial*/);
_cm->do_yield_check();
} while (!_cm->has_aborted() && task->has_aborted());
}
task->record_end_time();
guarantee(!task->has_aborted() || _cm->has_aborted(), "invariant");
}
double end_vtime = os::elapsedVTime();
_cm->update_accum_task_vtime(worker_id, end_vtime - start_vtime);
}
G1CMConcurrentMarkingTask(G1ConcurrentMark* cm) :
WorkerTask("Concurrent Mark"), _cm(cm) { }
~G1CMConcurrentMarkingTask() { }
};
uint G1ConcurrentMark::calc_active_marking_workers() {
uint result = 0;
if (!UseDynamicNumberOfGCThreads || !FLAG_IS_DEFAULT(ConcGCThreads)) {
result = _max_concurrent_workers;
} else {
result =
WorkerPolicy::calc_default_active_workers(_max_concurrent_workers,
1, /* Minimum workers */
_num_concurrent_workers,
Threads::number_of_non_daemon_threads());
// Don't scale the result down by scale_concurrent_workers() because
// that scaling has already gone into "_max_concurrent_workers".
}
assert(result > 0 && result <= _max_concurrent_workers,
"Calculated number of marking workers must be larger than zero and at most the maximum %u, but is %u",
_max_concurrent_workers, result);
return result;
}
void G1ConcurrentMark::scan_root_region(const MemRegion* region, uint worker_id) {
#ifdef ASSERT
HeapWord* last = region->last();
HeapRegion* hr = _g1h->heap_region_containing(last);
assert(hr->is_old() || hr->next_top_at_mark_start() == hr->bottom(),
"Root regions must be old or survivor/eden but region %u is %s", hr->hrm_index(), hr->get_type_str());
assert(hr->next_top_at_mark_start() == region->start(),
"MemRegion start should be equal to nTAMS");
#endif
G1RootRegionScanClosure cl(_g1h, this, worker_id);
const uintx interval = PrefetchScanIntervalInBytes;
HeapWord* curr = region->start();
const HeapWord* end = region->end();
while (curr < end) {
Prefetch::read(curr, interval);
oop obj = cast_to_oop(curr);
size_t size = obj->oop_iterate_size(&cl);
assert(size == obj->size(), "sanity");
curr += size;
}
}
class G1CMRootRegionScanTask : public WorkerTask {
G1ConcurrentMark* _cm;
public:
G1CMRootRegionScanTask(G1ConcurrentMark* cm) :
WorkerTask("G1 Root Region Scan"), _cm(cm) { }
void work(uint worker_id) {
G1CMRootMemRegions* root_regions = _cm->root_regions();
const MemRegion* region = root_regions->claim_next();
while (region != NULL) {
_cm->scan_root_region(region, worker_id);
region = root_regions->claim_next();
}
}
};
void G1ConcurrentMark::scan_root_regions() {
// scan_in_progress() will have been set to true only if there was
// at least one root region to scan. So, if it's false, we
// should not attempt to do any further work.
if (root_regions()->scan_in_progress()) {
assert(!has_aborted(), "Aborting before root region scanning is finished not supported.");
_num_concurrent_workers = MIN2(calc_active_marking_workers(),