/
shenandoahHeap.cpp
3072 lines (2550 loc) · 102 KB
/
shenandoahHeap.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) 2013, 2019, Red Hat, Inc. All rights reserved.
*
* 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 "memory/allocation.hpp"
#include "memory/universe.hpp"
#include "gc/shared/gcArguments.hpp"
#include "gc/shared/gcTimer.hpp"
#include "gc/shared/gcTraceTime.inline.hpp"
#include "gc/shared/locationPrinter.inline.hpp"
#include "gc/shared/memAllocator.hpp"
#include "gc/shared/plab.hpp"
#include "gc/shenandoah/shenandoahAllocTracker.hpp"
#include "gc/shenandoah/shenandoahBarrierSet.hpp"
#include "gc/shenandoah/shenandoahClosures.inline.hpp"
#include "gc/shenandoah/shenandoahCollectionSet.hpp"
#include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
#include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
#include "gc/shenandoah/shenandoahConcurrentRoots.hpp"
#include "gc/shenandoah/shenandoahControlThread.hpp"
#include "gc/shenandoah/shenandoahFreeSet.hpp"
#include "gc/shenandoah/shenandoahPhaseTimings.hpp"
#include "gc/shenandoah/shenandoahHeap.inline.hpp"
#include "gc/shenandoah/shenandoahHeapRegion.hpp"
#include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
#include "gc/shenandoah/shenandoahMarkCompact.hpp"
#include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
#include "gc/shenandoah/shenandoahMemoryPool.hpp"
#include "gc/shenandoah/shenandoahMetrics.hpp"
#include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
#include "gc/shenandoah/shenandoahNormalMode.hpp"
#include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
#include "gc/shenandoah/shenandoahPacer.inline.hpp"
#include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
#include "gc/shenandoah/shenandoahPassiveMode.hpp"
#include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
#include "gc/shenandoah/shenandoahStringDedup.hpp"
#include "gc/shenandoah/shenandoahTaskqueue.hpp"
#include "gc/shenandoah/shenandoahTraversalMode.hpp"
#include "gc/shenandoah/shenandoahUtils.hpp"
#include "gc/shenandoah/shenandoahVerifier.hpp"
#include "gc/shenandoah/shenandoahCodeRoots.hpp"
#include "gc/shenandoah/shenandoahVMOperations.hpp"
#include "gc/shenandoah/shenandoahWorkGroup.hpp"
#include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
#if INCLUDE_JFR
#include "gc/shenandoah/shenandoahJfrSupport.hpp"
#endif
#include "memory/metaspace.hpp"
#include "oops/compressedOops.inline.hpp"
#include "runtime/atomic.hpp"
#include "runtime/globals.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/orderAccess.hpp"
#include "runtime/safepointMechanism.hpp"
#include "runtime/vmThread.hpp"
#include "services/mallocTracker.hpp"
#ifdef ASSERT
template <class T>
void ShenandoahAssertToSpaceClosure::do_oop_work(T* p) {
T o = RawAccess<>::oop_load(p);
if (! CompressedOops::is_null(o)) {
oop obj = CompressedOops::decode_not_null(o);
shenandoah_assert_not_forwarded(p, obj);
}
}
void ShenandoahAssertToSpaceClosure::do_oop(narrowOop* p) { do_oop_work(p); }
void ShenandoahAssertToSpaceClosure::do_oop(oop* p) { do_oop_work(p); }
#endif
class ShenandoahPretouchHeapTask : public AbstractGangTask {
private:
ShenandoahRegionIterator _regions;
const size_t _page_size;
public:
ShenandoahPretouchHeapTask(size_t page_size) :
AbstractGangTask("Shenandoah Pretouch Heap"),
_page_size(page_size) {}
virtual void work(uint worker_id) {
ShenandoahHeapRegion* r = _regions.next();
while (r != NULL) {
os::pretouch_memory(r->bottom(), r->end(), _page_size);
r = _regions.next();
}
}
};
class ShenandoahPretouchBitmapTask : public AbstractGangTask {
private:
ShenandoahRegionIterator _regions;
char* _bitmap_base;
const size_t _bitmap_size;
const size_t _page_size;
public:
ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
AbstractGangTask("Shenandoah Pretouch Bitmap"),
_bitmap_base(bitmap_base),
_bitmap_size(bitmap_size),
_page_size(page_size) {}
virtual void work(uint worker_id) {
ShenandoahHeapRegion* r = _regions.next();
while (r != NULL) {
size_t start = r->region_number() * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
size_t end = (r->region_number() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);
os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
r = _regions.next();
}
}
};
jint ShenandoahHeap::initialize() {
initialize_heuristics();
//
// Figure out heap sizing
//
size_t init_byte_size = InitialHeapSize;
size_t min_byte_size = MinHeapSize;
size_t max_byte_size = MaxHeapSize;
size_t heap_alignment = HeapAlignment;
size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
if (ShenandoahAlwaysPreTouch) {
// Enabled pre-touch means the entire heap is committed right away.
init_byte_size = max_byte_size;
}
Universe::check_alignment(max_byte_size, reg_size_bytes, "Shenandoah heap");
Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
_num_regions = ShenandoahHeapRegion::region_count();
size_t num_committed_regions = init_byte_size / reg_size_bytes;
num_committed_regions = MIN2(num_committed_regions, _num_regions);
assert(num_committed_regions <= _num_regions, "sanity");
_initial_size = num_committed_regions * reg_size_bytes;
size_t num_min_regions = min_byte_size / reg_size_bytes;
num_min_regions = MIN2(num_min_regions, _num_regions);
assert(num_min_regions <= _num_regions, "sanity");
_minimum_size = num_min_regions * reg_size_bytes;
_committed = _initial_size;
size_t heap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
//
// Reserve and commit memory for heap
//
ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
initialize_reserved_region(heap_rs);
_heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
_heap_region_special = heap_rs.special();
assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
"Misaligned heap: " PTR_FORMAT, p2i(base()));
#if SHENANDOAH_OPTIMIZED_OBJTASK
// The optimized ObjArrayChunkedTask takes some bits away from the full object bits.
// Fail if we ever attempt to address more than we can.
if ((uintptr_t)heap_rs.end() >= ObjArrayChunkedTask::max_addressable()) {
FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
"but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
"VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
p2i(heap_rs.base()), p2i(heap_rs.end()), ObjArrayChunkedTask::max_addressable());
vm_exit_during_initialization("Fatal Error", buf);
}
#endif
ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
if (!_heap_region_special) {
os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
"Cannot commit heap memory");
}
//
// Reserve and commit memory for bitmap(s)
//
_bitmap_size = MarkBitMap::compute_size(heap_rs.size());
_bitmap_size = align_up(_bitmap_size, bitmap_page_size);
size_t bitmap_bytes_per_region = reg_size_bytes / MarkBitMap::heap_map_factor();
guarantee(bitmap_bytes_per_region != 0,
"Bitmap bytes per region should not be zero");
guarantee(is_power_of_2(bitmap_bytes_per_region),
"Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
if (bitmap_page_size > bitmap_bytes_per_region) {
_bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
_bitmap_bytes_per_slice = bitmap_page_size;
} else {
_bitmap_regions_per_slice = 1;
_bitmap_bytes_per_slice = bitmap_bytes_per_region;
}
guarantee(_bitmap_regions_per_slice >= 1,
"Should have at least one region per slice: " SIZE_FORMAT,
_bitmap_regions_per_slice);
guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
"Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
_bitmap_bytes_per_slice, bitmap_page_size);
ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
_bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
_bitmap_region_special = bitmap.special();
size_t bitmap_init_commit = _bitmap_bytes_per_slice *
align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
if (!_bitmap_region_special) {
os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
"Cannot commit bitmap memory");
}
_marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
if (ShenandoahVerify) {
ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
if (!verify_bitmap.special()) {
os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
"Cannot commit verification bitmap memory");
}
MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
_verification_bit_map.initialize(_heap_region, verify_bitmap_region);
_verifier = new ShenandoahVerifier(this, &_verification_bit_map);
}
// Reserve aux bitmap for use in object_iterate(). We don't commit it here.
ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
_aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
_aux_bitmap_region_special = aux_bitmap.special();
_aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
//
// Create regions and region sets
//
_regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
_free_set = new ShenandoahFreeSet(this, _num_regions);
_collection_set = new ShenandoahCollectionSet(this, sh_rs.base(), sh_rs.size());
{
ShenandoahHeapLocker locker(lock());
size_t size_words = ShenandoahHeapRegion::region_size_words();
for (size_t i = 0; i < _num_regions; i++) {
HeapWord* start = (HeapWord*)sh_rs.base() + size_words * i;
bool is_committed = i < num_committed_regions;
ShenandoahHeapRegion* r = new ShenandoahHeapRegion(this, start, size_words, i, is_committed);
_marking_context->initialize_top_at_mark_start(r);
_regions[i] = r;
assert(!collection_set()->is_in(i), "New region should not be in collection set");
}
// Initialize to complete
_marking_context->mark_complete();
_free_set->rebuild();
}
if (ShenandoahAlwaysPreTouch) {
assert(!AlwaysPreTouch, "Should have been overridden");
// For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
// before initialize() below zeroes it with initializing thread. For any given region,
// we touch the region and the corresponding bitmaps from the same thread.
ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
size_t pretouch_heap_page_size = heap_page_size;
size_t pretouch_bitmap_page_size = bitmap_page_size;
#ifdef LINUX
// UseTransparentHugePages would madvise that backing memory can be coalesced into huge
// pages. But, the kernel needs to know that every small page is used, in order to coalesce
// them into huge one. Therefore, we need to pretouch with smaller pages.
if (UseTransparentHugePages) {
pretouch_heap_page_size = (size_t)os::vm_page_size();
pretouch_bitmap_page_size = (size_t)os::vm_page_size();
}
#endif
// OS memory managers may want to coalesce back-to-back pages. Make their jobs
// simpler by pre-touching continuous spaces (heap and bitmap) separately.
log_info(gc, init)("Pretouch bitmap: " SIZE_FORMAT " regions, " SIZE_FORMAT " bytes page",
_num_regions, pretouch_bitmap_page_size);
ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, pretouch_bitmap_page_size);
_workers->run_task(&bcl);
log_info(gc, init)("Pretouch heap: " SIZE_FORMAT " regions, " SIZE_FORMAT " bytes page",
_num_regions, pretouch_heap_page_size);
ShenandoahPretouchHeapTask hcl(pretouch_heap_page_size);
_workers->run_task(&hcl);
}
//
// Initialize the rest of GC subsystems
//
_liveness_cache = NEW_C_HEAP_ARRAY(jushort*, _max_workers, mtGC);
for (uint worker = 0; worker < _max_workers; worker++) {
_liveness_cache[worker] = NEW_C_HEAP_ARRAY(jushort, _num_regions, mtGC);
Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(jushort));
}
// There should probably be Shenandoah-specific options for these,
// just as there are G1-specific options.
{
ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
}
_monitoring_support = new ShenandoahMonitoringSupport(this);
_phase_timings = new ShenandoahPhaseTimings();
ShenandoahStringDedup::initialize();
ShenandoahCodeRoots::initialize();
if (ShenandoahAllocationTrace) {
_alloc_tracker = new ShenandoahAllocTracker();
}
if (ShenandoahPacing) {
_pacer = new ShenandoahPacer(this);
_pacer->setup_for_idle();
} else {
_pacer = NULL;
}
_traversal_gc = strcmp(ShenandoahGCMode, "traversal") == 0 ?
new ShenandoahTraversalGC(this, _num_regions) :
NULL;
_control_thread = new ShenandoahControlThread();
log_info(gc, init)("Initialize Shenandoah heap: " SIZE_FORMAT "%s initial, " SIZE_FORMAT "%s min, " SIZE_FORMAT "%s max",
byte_size_in_proper_unit(_initial_size), proper_unit_for_byte_size(_initial_size),
byte_size_in_proper_unit(_minimum_size), proper_unit_for_byte_size(_minimum_size),
byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity())
);
log_info(gc, init)("Safepointing mechanism: %s",
SafepointMechanism::uses_thread_local_poll() ? "thread-local poll" :
(SafepointMechanism::uses_global_page_poll() ? "global-page poll" : "unknown"));
return JNI_OK;
}
void ShenandoahHeap::initialize_heuristics() {
if (ShenandoahGCMode != NULL) {
if (strcmp(ShenandoahGCMode, "traversal") == 0) {
_gc_mode = new ShenandoahTraversalMode();
} else if (strcmp(ShenandoahGCMode, "normal") == 0) {
_gc_mode = new ShenandoahNormalMode();
} else if (strcmp(ShenandoahGCMode, "passive") == 0) {
_gc_mode = new ShenandoahPassiveMode();
} else {
vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
}
} else {
ShouldNotReachHere();
}
_gc_mode->initialize_flags();
_heuristics = _gc_mode->initialize_heuristics();
if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
vm_exit_during_initialization(
err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
_heuristics->name()));
}
if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
vm_exit_during_initialization(
err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
_heuristics->name()));
}
log_info(gc, init)("Shenandoah heuristics: %s",
_heuristics->name());
}
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable:4355 ) // 'this' : used in base member initializer list
#endif
ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
CollectedHeap(),
_initial_size(0),
_used(0),
_committed(0),
_bytes_allocated_since_gc_start(0),
_max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
_workers(NULL),
_safepoint_workers(NULL),
_heap_region_special(false),
_num_regions(0),
_regions(NULL),
_update_refs_iterator(this),
_control_thread(NULL),
_shenandoah_policy(policy),
_heuristics(NULL),
_free_set(NULL),
_scm(new ShenandoahConcurrentMark()),
_traversal_gc(NULL),
_full_gc(new ShenandoahMarkCompact()),
_pacer(NULL),
_verifier(NULL),
_alloc_tracker(NULL),
_phase_timings(NULL),
_monitoring_support(NULL),
_memory_pool(NULL),
_stw_memory_manager("Shenandoah Pauses", "end of GC pause"),
_cycle_memory_manager("Shenandoah Cycles", "end of GC cycle"),
_gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
_soft_ref_policy(),
_log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
_ref_processor(NULL),
_marking_context(NULL),
_bitmap_size(0),
_bitmap_regions_per_slice(0),
_bitmap_bytes_per_slice(0),
_bitmap_region_special(false),
_aux_bitmap_region_special(false),
_liveness_cache(NULL),
_collection_set(NULL)
{
log_info(gc, init)("GC threads: " UINT32_FORMAT " parallel, " UINT32_FORMAT " concurrent", ParallelGCThreads, ConcGCThreads);
log_info(gc, init)("Reference processing: %s", ParallelRefProcEnabled ? "parallel" : "serial");
BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this));
_max_workers = MAX2(_max_workers, 1U);
_workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
/* are_GC_task_threads */ true,
/* are_ConcurrentGC_threads */ true);
if (_workers == NULL) {
vm_exit_during_initialization("Failed necessary allocation.");
} else {
_workers->initialize_workers();
}
if (ShenandoahParallelSafepointThreads > 1) {
_safepoint_workers = new ShenandoahWorkGang("Safepoint Cleanup Thread",
ShenandoahParallelSafepointThreads,
/* are_GC_task_threads */ false,
/* are_ConcurrentGC_threads */ false);
_safepoint_workers->initialize_workers();
}
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif
class ShenandoahResetBitmapTask : public AbstractGangTask {
private:
ShenandoahRegionIterator _regions;
public:
ShenandoahResetBitmapTask() :
AbstractGangTask("Parallel Reset Bitmap Task") {}
void work(uint worker_id) {
ShenandoahHeapRegion* region = _regions.next();
ShenandoahHeap* heap = ShenandoahHeap::heap();
ShenandoahMarkingContext* const ctx = heap->marking_context();
while (region != NULL) {
if (heap->is_bitmap_slice_committed(region)) {
ctx->clear_bitmap(region);
}
region = _regions.next();
}
}
};
void ShenandoahHeap::reset_mark_bitmap() {
assert_gc_workers(_workers->active_workers());
mark_incomplete_marking_context();
ShenandoahResetBitmapTask task;
_workers->run_task(&task);
}
void ShenandoahHeap::print_on(outputStream* st) const {
st->print_cr("Shenandoah Heap");
st->print_cr(" " SIZE_FORMAT "%s total, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
byte_size_in_proper_unit(committed()), proper_unit_for_byte_size(committed()),
byte_size_in_proper_unit(used()), proper_unit_for_byte_size(used()));
st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
num_regions(),
byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
st->print("Status: ");
if (has_forwarded_objects()) st->print("has forwarded objects, ");
if (is_concurrent_mark_in_progress()) st->print("marking, ");
if (is_evacuation_in_progress()) st->print("evacuating, ");
if (is_update_refs_in_progress()) st->print("updating refs, ");
if (is_concurrent_traversal_in_progress()) st->print("traversal, ");
if (is_degenerated_gc_in_progress()) st->print("degenerated gc, ");
if (is_full_gc_in_progress()) st->print("full gc, ");
if (is_full_gc_move_in_progress()) st->print("full gc move, ");
if (is_concurrent_root_in_progress()) st->print("concurrent roots, ");
if (cancelled_gc()) {
st->print("cancelled");
} else {
st->print("not cancelled");
}
st->cr();
st->print_cr("Reserved region:");
st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
p2i(reserved_region().start()),
p2i(reserved_region().end()));
ShenandoahCollectionSet* cset = collection_set();
st->print_cr("Collection set:");
if (cset != NULL) {
st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
st->print_cr(" - map (biased): " PTR_FORMAT, p2i(cset->biased_map_address()));
} else {
st->print_cr(" (NULL)");
}
st->cr();
MetaspaceUtils::print_on(st);
if (Verbose) {
print_heap_regions_on(st);
}
}
class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
public:
void do_thread(Thread* thread) {
assert(thread != NULL, "Sanity");
assert(thread->is_Worker_thread(), "Only worker thread expected");
ShenandoahThreadLocalData::initialize_gclab(thread);
}
};
void ShenandoahHeap::post_initialize() {
CollectedHeap::post_initialize();
MutexLocker ml(Threads_lock);
ShenandoahInitWorkerGCLABClosure init_gclabs;
_workers->threads_do(&init_gclabs);
// gclab can not be initialized early during VM startup, as it can not determinate its max_size.
// Now, we will let WorkGang to initialize gclab when new worker is created.
_workers->set_initialize_gclab();
_scm->initialize(_max_workers);
_full_gc->initialize(_gc_timer);
ref_processing_init();
_heuristics->initialize();
JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());
}
size_t ShenandoahHeap::used() const {
return Atomic::load_acquire(&_used);
}
size_t ShenandoahHeap::committed() const {
OrderAccess::acquire();
return _committed;
}
void ShenandoahHeap::increase_committed(size_t bytes) {
assert_heaplock_or_safepoint();
_committed += bytes;
}
void ShenandoahHeap::decrease_committed(size_t bytes) {
assert_heaplock_or_safepoint();
_committed -= bytes;
}
void ShenandoahHeap::increase_used(size_t bytes) {
Atomic::add(&_used, bytes);
}
void ShenandoahHeap::set_used(size_t bytes) {
Atomic::release_store_fence(&_used, bytes);
}
void ShenandoahHeap::decrease_used(size_t bytes) {
assert(used() >= bytes, "never decrease heap size by more than we've left");
Atomic::sub(&_used, bytes);
}
void ShenandoahHeap::increase_allocated(size_t bytes) {
Atomic::add(&_bytes_allocated_since_gc_start, bytes);
}
void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
size_t bytes = words * HeapWordSize;
if (!waste) {
increase_used(bytes);
}
increase_allocated(bytes);
if (ShenandoahPacing) {
control_thread()->pacing_notify_alloc(words);
if (waste) {
pacer()->claim_for_alloc(words, true);
}
}
}
size_t ShenandoahHeap::capacity() const {
return committed();
}
size_t ShenandoahHeap::max_capacity() const {
return _num_regions * ShenandoahHeapRegion::region_size_bytes();
}
size_t ShenandoahHeap::min_capacity() const {
return _minimum_size;
}
size_t ShenandoahHeap::initial_capacity() const {
return _initial_size;
}
bool ShenandoahHeap::is_in(const void* p) const {
HeapWord* heap_base = (HeapWord*) base();
HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
return p >= heap_base && p < last_region_end;
}
void ShenandoahHeap::op_uncommit(double shrink_before) {
assert (ShenandoahUncommit, "should be enabled");
// Application allocates from the beginning of the heap, and GC allocates at
// the end of it. It is more efficient to uncommit from the end, so that applications
// could enjoy the near committed regions. GC allocations are much less frequent,
// and therefore can accept the committing costs.
size_t count = 0;
for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
ShenandoahHeapRegion* r = get_region(i - 1);
if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
ShenandoahHeapLocker locker(lock());
if (r->is_empty_committed()) {
// Do not uncommit below minimal capacity
if (committed() < min_capacity() + ShenandoahHeapRegion::region_size_bytes()) {
break;
}
r->make_uncommitted();
count++;
}
}
SpinPause(); // allow allocators to take the lock
}
if (count > 0) {
control_thread()->notify_heap_changed();
}
}
HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
// New object should fit the GCLAB size
size_t min_size = MAX2(size, PLAB::min_size());
// Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
new_size = MIN2(new_size, PLAB::max_size());
new_size = MAX2(new_size, PLAB::min_size());
// Record new heuristic value even if we take any shortcut. This captures
// the case when moderately-sized objects always take a shortcut. At some point,
// heuristics should catch up with them.
ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
if (new_size < size) {
// New size still does not fit the object. Fall back to shared allocation.
// This avoids retiring perfectly good GCLABs, when we encounter a large object.
return NULL;
}
// Retire current GCLAB, and allocate a new one.
PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
gclab->retire();
size_t actual_size = 0;
HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
if (gclab_buf == NULL) {
return NULL;
}
assert (size <= actual_size, "allocation should fit");
if (ZeroTLAB) {
// ..and clear it.
Copy::zero_to_words(gclab_buf, actual_size);
} else {
// ...and zap just allocated object.
#ifdef ASSERT
// Skip mangling the space corresponding to the object header to
// ensure that the returned space is not considered parsable by
// any concurrent GC thread.
size_t hdr_size = oopDesc::header_size();
Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
#endif // ASSERT
}
gclab->set_buf(gclab_buf, actual_size);
return gclab->allocate(size);
}
HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
size_t requested_size,
size_t* actual_size) {
ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
HeapWord* res = allocate_memory(req);
if (res != NULL) {
*actual_size = req.actual_size();
} else {
*actual_size = 0;
}
return res;
}
HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
size_t word_size,
size_t* actual_size) {
ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
HeapWord* res = allocate_memory(req);
if (res != NULL) {
*actual_size = req.actual_size();
} else {
*actual_size = 0;
}
return res;
}
ShenandoahHeap* ShenandoahHeap::heap() {
CollectedHeap* heap = Universe::heap();
assert(heap != NULL, "Unitialized access to ShenandoahHeap::heap()");
assert(heap->kind() == CollectedHeap::Shenandoah, "not a shenandoah heap");
return (ShenandoahHeap*) heap;
}
ShenandoahHeap* ShenandoahHeap::heap_no_check() {
CollectedHeap* heap = Universe::heap();
return (ShenandoahHeap*) heap;
}
HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
ShenandoahAllocTrace trace_alloc(req.size(), req.type());
intptr_t pacer_epoch = 0;
bool in_new_region = false;
HeapWord* result = NULL;
if (req.is_mutator_alloc()) {
if (ShenandoahPacing) {
pacer()->pace_for_alloc(req.size());
pacer_epoch = pacer()->epoch();
}
if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
result = allocate_memory_under_lock(req, in_new_region);
}
// Allocation failed, block until control thread reacted, then retry allocation.
//
// It might happen that one of the threads requesting allocation would unblock
// way later after GC happened, only to fail the second allocation, because
// other threads have already depleted the free storage. In this case, a better
// strategy is to try again, as long as GC makes progress.
//
// Then, we need to make sure the allocation was retried after at least one
// Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
size_t tries = 0;
while (result == NULL && _progress_last_gc.is_set()) {
tries++;
control_thread()->handle_alloc_failure(req.size());
result = allocate_memory_under_lock(req, in_new_region);
}
while (result == NULL && tries <= ShenandoahFullGCThreshold) {
tries++;
control_thread()->handle_alloc_failure(req.size());
result = allocate_memory_under_lock(req, in_new_region);
}
} else {
assert(req.is_gc_alloc(), "Can only accept GC allocs here");
result = allocate_memory_under_lock(req, in_new_region);
// Do not call handle_alloc_failure() here, because we cannot block.
// The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
}
if (in_new_region) {
control_thread()->notify_heap_changed();
}
if (result != NULL) {
size_t requested = req.size();
size_t actual = req.actual_size();
assert (req.is_lab_alloc() || (requested == actual),
"Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
if (req.is_mutator_alloc()) {
notify_mutator_alloc_words(actual, false);
// If we requested more than we were granted, give the rest back to pacer.
// This only matters if we are in the same pacing epoch: do not try to unpace
// over the budget for the other phase.
if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
}
} else {
increase_used(actual*HeapWordSize);
}
}
return result;
}
HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {
ShenandoahHeapLocker locker(lock());
return _free_set->allocate(req, in_new_region);
}
HeapWord* ShenandoahHeap::mem_allocate(size_t size,
bool* gc_overhead_limit_was_exceeded) {
ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
return allocate_memory(req);
}
MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
size_t size,
Metaspace::MetadataType mdtype) {
MetaWord* result;
// Inform metaspace OOM to GC heuristics if class unloading is possible.
if (heuristics()->can_unload_classes()) {
ShenandoahHeuristics* h = heuristics();
h->record_metaspace_oom();
}
// Expand and retry allocation
result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
if (result != NULL) {
return result;
}
// Start full GC
collect(GCCause::_metadata_GC_clear_soft_refs);
// Retry allocation
result = loader_data->metaspace_non_null()->allocate(size, mdtype);
if (result != NULL) {
return result;
}
// Expand and retry allocation
result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
if (result != NULL) {
return result;
}
// Out of memory
return NULL;
}
class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
private:
ShenandoahHeap* const _heap;
Thread* const _thread;
public:
ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
_heap(heap), _thread(Thread::current()) {}
void do_object(oop p) {
shenandoah_assert_marked(NULL, p);
if (!p->is_forwarded()) {
_heap->evacuate_object(p, _thread);
}
}
};
class ShenandoahEvacuationTask : public AbstractGangTask {
private:
ShenandoahHeap* const _sh;
ShenandoahCollectionSet* const _cs;
bool _concurrent;
public:
ShenandoahEvacuationTask(ShenandoahHeap* sh,
ShenandoahCollectionSet* cs,
bool concurrent) :
AbstractGangTask("Parallel Evacuation Task"),
_sh(sh),
_cs(cs),
_concurrent(concurrent)
{}
void work(uint worker_id) {
if (_concurrent) {
ShenandoahConcurrentWorkerSession worker_session(worker_id);
ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
ShenandoahEvacOOMScope oom_evac_scope;
do_work();
} else {
ShenandoahParallelWorkerSession worker_session(worker_id);
ShenandoahEvacOOMScope oom_evac_scope;
do_work();
}
}
private:
void do_work() {
ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
ShenandoahHeapRegion* r;
while ((r =_cs->claim_next()) != NULL) {
assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->region_number());
_sh->marked_object_iterate(r, &cl);
if (ShenandoahPacing) {
_sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
}
if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
break;
}
}
}
};
void ShenandoahHeap::trash_cset_regions() {
ShenandoahHeapLocker locker(lock());
ShenandoahCollectionSet* set = collection_set();
ShenandoahHeapRegion* r;
set->clear_current_index();
while ((r = set->next()) != NULL) {
r->make_trash();
}
collection_set()->clear();
}
void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
st->print_cr("Heap Regions:");
st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start (previous, next)");
st->print_cr("SN=alloc sequence numbers (first mutator, last mutator, first gc, last gc)");