1 /*
2 * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2013, 2022, Red Hat, Inc. All rights reserved.
4 * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
5 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 *
7 * This code is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License version 2 only, as
9 * published by the Free Software Foundation.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 *
25 */
26
27
28 #include "cds/aotMappedHeapWriter.hpp"
29 #include "classfile/systemDictionary.hpp"
30 #include "gc/shared/classUnloadingContext.hpp"
31 #include "gc/shared/fullGCForwarding.hpp"
32 #include "gc/shared/gc_globals.hpp"
33 #include "gc/shared/gcArguments.hpp"
34 #include "gc/shared/gcTimer.hpp"
35 #include "gc/shared/gcTraceTime.inline.hpp"
36 #include "gc/shared/locationPrinter.inline.hpp"
37 #include "gc/shared/memAllocator.hpp"
38 #include "gc/shared/plab.hpp"
39 #include "gc/shared/tlab_globals.hpp"
40 #include "gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp"
41 #include "gc/shenandoah/heuristics/shenandoahYoungHeuristics.hpp"
42 #include "gc/shenandoah/mode/shenandoahGenerationalMode.hpp"
43 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"
44 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp"
45 #include "gc/shenandoah/shenandoahAllocRequest.hpp"
46 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
47 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
48 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
49 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
50 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
51 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
52 #include "gc/shenandoah/shenandoahControlThread.hpp"
53 #include "gc/shenandoah/shenandoahFreeSet.hpp"
54 #include "gc/shenandoah/shenandoahGenerationalEvacuationTask.hpp"
55 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
56 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp"
57 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
58 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
59 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
60 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
61 #include "gc/shenandoah/shenandoahInitLogger.hpp"
62 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
63 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
64 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
65 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
66 #include "gc/shenandoah/shenandoahPadding.hpp"
67 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
68 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
69 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
70 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
71 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
72 #include "gc/shenandoah/shenandoahSTWMark.hpp"
73 #include "gc/shenandoah/shenandoahUncommitThread.hpp"
74 #include "gc/shenandoah/shenandoahUtils.hpp"
75 #include "gc/shenandoah/shenandoahVerifier.hpp"
76 #include "gc/shenandoah/shenandoahVMOperations.hpp"
77 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
78 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
79 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
80 #include "memory/allocation.hpp"
81 #include "memory/classLoaderMetaspace.hpp"
82 #include "memory/memoryReserver.hpp"
83 #include "memory/metaspaceUtils.hpp"
84 #include "memory/universe.hpp"
85 #include "nmt/mallocTracker.hpp"
86 #include "nmt/memTracker.hpp"
87 #include "oops/compressedOops.inline.hpp"
88 #include "prims/jvmtiTagMap.hpp"
89 #include "runtime/atomicAccess.hpp"
90 #include "runtime/globals.hpp"
91 #include "runtime/interfaceSupport.inline.hpp"
92 #include "runtime/java.hpp"
93 #include "runtime/orderAccess.hpp"
94 #include "runtime/safepointMechanism.hpp"
95 #include "runtime/stackWatermarkSet.hpp"
96 #include "runtime/threads.hpp"
97 #include "runtime/vmThread.hpp"
98 #include "utilities/events.hpp"
99 #include "utilities/globalDefinitions.hpp"
100 #include "utilities/powerOfTwo.hpp"
101 #if INCLUDE_JVMCI
102 #include "jvmci/jvmci.hpp"
103 #endif
104 #if INCLUDE_JFR
105 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
106 #endif
107
108 class ShenandoahPretouchHeapTask : public WorkerTask {
109 private:
110 ShenandoahRegionIterator _regions;
111 const size_t _page_size;
112 public:
113 ShenandoahPretouchHeapTask(size_t page_size) :
114 WorkerTask("Shenandoah Pretouch Heap"),
115 _page_size(page_size) {}
116
117 virtual void work(uint worker_id) {
118 ShenandoahHeapRegion* r = _regions.next();
119 while (r != nullptr) {
120 if (r->is_committed()) {
121 os::pretouch_memory(r->bottom(), r->end(), _page_size);
122 }
123 r = _regions.next();
124 }
125 }
126 };
127
128 class ShenandoahPretouchBitmapTask : public WorkerTask {
129 private:
130 ShenandoahRegionIterator _regions;
131 char* _bitmap_base;
132 const size_t _bitmap_size;
133 const size_t _page_size;
134 public:
135 ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
136 WorkerTask("Shenandoah Pretouch Bitmap"),
137 _bitmap_base(bitmap_base),
138 _bitmap_size(bitmap_size),
139 _page_size(page_size) {}
140
141 virtual void work(uint worker_id) {
142 ShenandoahHeapRegion* r = _regions.next();
143 while (r != nullptr) {
144 size_t start = r->index() * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
145 size_t end = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
146 assert (end <= _bitmap_size, "end is sane: %zu < %zu", end, _bitmap_size);
147
148 if (r->is_committed()) {
149 os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
150 }
151
152 r = _regions.next();
153 }
154 }
155 };
156
157 static ReservedSpace reserve(size_t size, size_t preferred_page_size) {
158 // When a page size is given we don't want to mix large
159 // and normal pages. If the size is not a multiple of the
160 // page size it will be aligned up to achieve this.
161 size_t alignment = os::vm_allocation_granularity();
162 if (preferred_page_size != os::vm_page_size()) {
163 alignment = MAX2(preferred_page_size, alignment);
164 size = align_up(size, alignment);
165 }
166
167 const ReservedSpace reserved = MemoryReserver::reserve(size, alignment, preferred_page_size, mtGC);
168 if (!reserved.is_reserved()) {
169 vm_exit_during_initialization("Could not reserve space");
170 }
171 return reserved;
172 }
173
174 jint ShenandoahHeap::initialize() {
175 //
176 // Figure out heap sizing
177 //
178
179 size_t init_byte_size = InitialHeapSize;
180 size_t min_byte_size = MinHeapSize;
181 size_t max_byte_size = MaxHeapSize;
182 size_t heap_alignment = HeapAlignment;
183
184 size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
185
186 Universe::check_alignment(max_byte_size, reg_size_bytes, "Shenandoah heap");
187 Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
188
189 _num_regions = ShenandoahHeapRegion::region_count();
190 assert(_num_regions == (max_byte_size / reg_size_bytes),
191 "Regions should cover entire heap exactly: %zu != %zu/%zu",
192 _num_regions, max_byte_size, reg_size_bytes);
193
194 size_t num_committed_regions = init_byte_size / reg_size_bytes;
195 num_committed_regions = MIN2(num_committed_regions, _num_regions);
196 assert(num_committed_regions <= _num_regions, "sanity");
197 _initial_size = num_committed_regions * reg_size_bytes;
198
199 size_t num_min_regions = min_byte_size / reg_size_bytes;
200 num_min_regions = MIN2(num_min_regions, _num_regions);
201 assert(num_min_regions <= _num_regions, "sanity");
202 _minimum_size = num_min_regions * reg_size_bytes;
203
204 _soft_max_size = clamp(SoftMaxHeapSize, min_capacity(), max_capacity());
205
206 _committed = _initial_size;
207
208 size_t heap_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
209 size_t bitmap_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
210 size_t region_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
211
212 //
213 // Reserve and commit memory for heap
214 //
215
216 ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
217 initialize_reserved_region(heap_rs);
218 _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
219 _heap_region_special = heap_rs.special();
220
221 assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
222 "Misaligned heap: " PTR_FORMAT, p2i(base()));
223 os::trace_page_sizes_for_requested_size("Heap",
224 max_byte_size, heap_alignment,
225 heap_rs.base(),
226 heap_rs.size(), heap_rs.page_size());
227
228 #if SHENANDOAH_OPTIMIZED_MARKTASK
229 // The optimized ShenandoahMarkTask takes some bits away from the full object bits.
230 // Fail if we ever attempt to address more than we can.
231 if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {
232 FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
233 "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
234 "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
235 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());
236 vm_exit_during_initialization("Fatal Error", buf);
237 }
238 #endif
239
240 ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
241 if (!_heap_region_special) {
242 os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
243 "Cannot commit heap memory");
244 }
245
246 BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this, _heap_region));
247
248 // Now we know the number of regions and heap sizes, initialize the heuristics.
249 initialize_heuristics();
250
251 // If ShenandoahCardBarrier is enabled but it's not generational mode
252 // it means we're under passive mode and we have to initialize old gen
253 // for the purpose of having card table.
254 if (ShenandoahCardBarrier && !(mode()->is_generational())) {
255 _old_generation = new ShenandoahOldGeneration(max_workers());
256 }
257
258 assert(_heap_region.byte_size() == heap_rs.size(), "Need to know reserved size for card table");
259
260 //
261 // Worker threads must be initialized after the barrier is configured
262 //
263 _workers = new ShenandoahWorkerThreads("Shenandoah GC Threads", _max_workers);
264 if (_workers == nullptr) {
265 vm_exit_during_initialization("Failed necessary allocation.");
266 } else {
267 _workers->initialize_workers();
268 }
269
270 if (ParallelGCThreads > 1) {
271 _safepoint_workers = new ShenandoahWorkerThreads("Safepoint Cleanup Thread", ParallelGCThreads);
272 _safepoint_workers->initialize_workers();
273 }
274
275 //
276 // Reserve and commit memory for bitmap(s)
277 //
278
279 size_t bitmap_size_orig = ShenandoahMarkBitMap::compute_size(heap_rs.size());
280 _bitmap_size = align_up(bitmap_size_orig, bitmap_page_size);
281
282 size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();
283
284 guarantee(bitmap_bytes_per_region != 0,
285 "Bitmap bytes per region should not be zero");
286 guarantee(is_power_of_2(bitmap_bytes_per_region),
287 "Bitmap bytes per region should be power of two: %zu", bitmap_bytes_per_region);
288
289 if (bitmap_page_size > bitmap_bytes_per_region) {
290 _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
291 _bitmap_bytes_per_slice = bitmap_page_size;
292 } else {
293 _bitmap_regions_per_slice = 1;
294 _bitmap_bytes_per_slice = bitmap_bytes_per_region;
295 }
296
297 guarantee(_bitmap_regions_per_slice >= 1,
298 "Should have at least one region per slice: %zu",
299 _bitmap_regions_per_slice);
300
301 guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
302 "Bitmap slices should be page-granular: bps = %zu, page size = %zu",
303 _bitmap_bytes_per_slice, bitmap_page_size);
304
305 ReservedSpace bitmap = reserve(_bitmap_size, bitmap_page_size);
306 os::trace_page_sizes_for_requested_size("Mark Bitmap",
307 bitmap_size_orig, bitmap_page_size,
308 bitmap.base(),
309 bitmap.size(), bitmap.page_size());
310 MemTracker::record_virtual_memory_tag(bitmap, mtGC);
311 _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
312 _bitmap_region_special = bitmap.special();
313
314 size_t bitmap_init_commit = _bitmap_bytes_per_slice *
315 align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
316 bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
317 if (!_bitmap_region_special) {
318 os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
319 "Cannot commit bitmap memory");
320 }
321
322 _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
323
324 if (ShenandoahVerify) {
325 ReservedSpace verify_bitmap = reserve(_bitmap_size, bitmap_page_size);
326 os::trace_page_sizes_for_requested_size("Verify Bitmap",
327 bitmap_size_orig, bitmap_page_size,
328 verify_bitmap.base(),
329 verify_bitmap.size(), verify_bitmap.page_size());
330 if (!verify_bitmap.special()) {
331 os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
332 "Cannot commit verification bitmap memory");
333 }
334 MemTracker::record_virtual_memory_tag(verify_bitmap, mtGC);
335 MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
336 _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
337 _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
338 }
339
340 // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
341 size_t aux_bitmap_page_size = bitmap_page_size;
342
343 ReservedSpace aux_bitmap = reserve(_bitmap_size, aux_bitmap_page_size);
344 os::trace_page_sizes_for_requested_size("Aux Bitmap",
345 bitmap_size_orig, aux_bitmap_page_size,
346 aux_bitmap.base(),
347 aux_bitmap.size(), aux_bitmap.page_size());
348 MemTracker::record_virtual_memory_tag(aux_bitmap, mtGC);
349 _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
350 _aux_bitmap_region_special = aux_bitmap.special();
351 _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
352
353 //
354 // Create regions and region sets
355 //
356 size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
357 size_t region_storage_size_orig = region_align * _num_regions;
358 size_t region_storage_size = align_up(region_storage_size_orig,
359 MAX2(region_page_size, os::vm_allocation_granularity()));
360
361 ReservedSpace region_storage = reserve(region_storage_size, region_page_size);
362 os::trace_page_sizes_for_requested_size("Region Storage",
363 region_storage_size_orig, region_page_size,
364 region_storage.base(),
365 region_storage.size(), region_storage.page_size());
366 MemTracker::record_virtual_memory_tag(region_storage, mtGC);
367 if (!region_storage.special()) {
368 os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false,
369 "Cannot commit region memory");
370 }
371
372 // Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks.
373 // Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there.
374 // If not successful, bite a bullet and allocate at whatever address.
375 {
376 const size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity());
377 const size_t cset_size = align_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align);
378 const size_t cset_page_size = os::vm_page_size();
379
380 uintptr_t min = round_up_power_of_2(cset_align);
381 uintptr_t max = (1u << 30u);
382 ReservedSpace cset_rs;
383
384 for (uintptr_t addr = min; addr <= max; addr <<= 1u) {
385 char* req_addr = (char*)addr;
386 assert(is_aligned(req_addr, cset_align), "Should be aligned");
387 cset_rs = MemoryReserver::reserve(req_addr, cset_size, cset_align, cset_page_size, mtGC);
388 if (cset_rs.is_reserved()) {
389 assert(cset_rs.base() == req_addr, "Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr);
390 _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
391 break;
392 }
393 }
394
395 if (_collection_set == nullptr) {
396 cset_rs = MemoryReserver::reserve(cset_size, cset_align, os::vm_page_size(), mtGC);
397 if (!cset_rs.is_reserved()) {
398 vm_exit_during_initialization("Cannot reserve memory for collection set");
399 }
400
401 _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
402 }
403 os::trace_page_sizes_for_requested_size("Collection Set",
404 cset_size, cset_page_size,
405 cset_rs.base(),
406 cset_rs.size(), cset_rs.page_size());
407 }
408
409 _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
410 _affiliations = NEW_C_HEAP_ARRAY(uint8_t, _num_regions, mtGC);
411
412 {
413 ShenandoahHeapLocker locker(lock());
414 for (size_t i = 0; i < _num_regions; i++) {
415 HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;
416 bool is_committed = i < num_committed_regions;
417 void* loc = region_storage.base() + i * region_align;
418
419 ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);
420 assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");
421
422 _marking_context->initialize_top_at_mark_start(r);
423 _regions[i] = r;
424 assert(!collection_set()->is_in(i), "New region should not be in collection set");
425
426 _affiliations[i] = ShenandoahAffiliation::FREE;
427 }
428 _free_set = new ShenandoahFreeSet(this, _num_regions);
429
430
431 post_initialize_heuristics();
432 // We are initializing free set. We ignore cset region tallies.
433 size_t young_cset_regions, old_cset_regions, first_old, last_old, num_old;
434 _free_set->prepare_to_rebuild(young_cset_regions, old_cset_regions, first_old, last_old, num_old);
435 if (mode()->is_generational()) {
436 ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap();
437 // We cannot call
438 // gen_heap->young_generation()->heuristics()->bytes_of_allocation_runway_before_gc_trigger(young_cset_regions)
439 // until after the heap is fully initialized. So we make up a safe value here.
440 size_t allocation_runway = InitialHeapSize / 2;
441 gen_heap->compute_old_generation_balance(allocation_runway, old_cset_regions);
442 }
443 _free_set->finish_rebuild(young_cset_regions, old_cset_regions, num_old);
444 }
445
446 if (AlwaysPreTouch) {
447 // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
448 // before initialize() below zeroes it with initializing thread. For any given region,
449 // we touch the region and the corresponding bitmaps from the same thread.
450 ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
451
452 _pretouch_heap_page_size = heap_page_size;
453 _pretouch_bitmap_page_size = bitmap_page_size;
454
455 // OS memory managers may want to coalesce back-to-back pages. Make their jobs
456 // simpler by pre-touching continuous spaces (heap and bitmap) separately.
457
458 ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size);
459 _workers->run_task(&bcl);
460
461 ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size);
462 _workers->run_task(&hcl);
463 }
464
465 //
466 // Initialize the rest of GC subsystems
467 //
468
469 _liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC);
470 for (uint worker = 0; worker < _max_workers; worker++) {
471 _liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC);
472 Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData));
473 }
474
475 // There should probably be Shenandoah-specific options for these,
476 // just as there are G1-specific options.
477 {
478 ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
479 satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
480 satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
481 }
482
483 _monitoring_support = new ShenandoahMonitoringSupport(this);
484 _phase_timings = new ShenandoahPhaseTimings(max_workers());
485 ShenandoahCodeRoots::initialize();
486
487 initialize_controller();
488
489 if (ShenandoahUncommit) {
490 _uncommit_thread = new ShenandoahUncommitThread(this);
491 }
492
493 print_init_logger();
494
495 FullGCForwarding::initialize(_heap_region);
496
497 return JNI_OK;
498 }
499
500 void ShenandoahHeap::initialize_controller() {
501 _control_thread = new ShenandoahControlThread();
502 }
503
504 void ShenandoahHeap::print_init_logger() const {
505 ShenandoahInitLogger::print();
506 }
507
508 void ShenandoahHeap::initialize_mode() {
509 if (ShenandoahGCMode != nullptr) {
510 if (strcmp(ShenandoahGCMode, "satb") == 0) {
511 _gc_mode = new ShenandoahSATBMode();
512 } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
513 _gc_mode = new ShenandoahPassiveMode();
514 } else if (strcmp(ShenandoahGCMode, "generational") == 0) {
515 _gc_mode = new ShenandoahGenerationalMode();
516 } else {
517 vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
518 }
519 } else {
520 vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)");
521 }
522 _gc_mode->initialize_flags();
523 if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
524 vm_exit_during_initialization(
525 err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
526 _gc_mode->name()));
527 }
528 if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
529 vm_exit_during_initialization(
530 err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
531 _gc_mode->name()));
532 }
533 }
534
535 void ShenandoahHeap::initialize_heuristics() {
536 _global_generation = new ShenandoahGlobalGeneration(mode()->is_generational(), max_workers());
537 _global_generation->initialize_heuristics(mode());
538 }
539
540 void ShenandoahHeap::post_initialize_heuristics() {
541 _global_generation->post_initialize(this);
542 }
543
544 #ifdef _MSC_VER
545 #pragma warning( push )
546 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
547 #endif
548
549 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
550 CollectedHeap(),
551 _active_generation(nullptr),
552 _initial_size(0),
553 _committed(0),
554 _max_workers(MAX3(ConcGCThreads, ParallelGCThreads, 1U)),
555 _workers(nullptr),
556 _safepoint_workers(nullptr),
557 _heap_region_special(false),
558 _num_regions(0),
559 _regions(nullptr),
560 _affiliations(nullptr),
561 _gc_state_changed(false),
562 _gc_no_progress_count(0),
563 _cancel_requested_time(0),
564 _update_refs_iterator(this),
565 _global_generation(nullptr),
566 _control_thread(nullptr),
567 _uncommit_thread(nullptr),
568 _young_generation(nullptr),
569 _old_generation(nullptr),
570 _shenandoah_policy(policy),
571 _gc_mode(nullptr),
572 _free_set(nullptr),
573 _verifier(nullptr),
574 _phase_timings(nullptr),
575 _monitoring_support(nullptr),
576 _memory_pool(nullptr),
577 _stw_memory_manager("Shenandoah Pauses"),
578 _cycle_memory_manager("Shenandoah Cycles"),
579 _gc_timer(new ConcurrentGCTimer()),
580 _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
581 _marking_context(nullptr),
582 _bitmap_size(0),
583 _bitmap_regions_per_slice(0),
584 _bitmap_bytes_per_slice(0),
585 _bitmap_region_special(false),
586 _aux_bitmap_region_special(false),
587 _liveness_cache(nullptr),
588 _collection_set(nullptr),
589 _evac_tracker(new ShenandoahEvacuationTracker())
590 {
591 // Initialize GC mode early, many subsequent initialization procedures depend on it
592 initialize_mode();
593 _cancelled_gc.set(GCCause::_no_gc);
594 }
595
596 #ifdef _MSC_VER
597 #pragma warning( pop )
598 #endif
599
600 void ShenandoahHeap::print_heap_on(outputStream* st) const {
601 const bool is_generational = mode()->is_generational();
602 const char* front_spacing = "";
603 if (is_generational) {
604 st->print_cr("Generational Shenandoah Heap");
605 st->print_cr(" Young:");
606 st->print_cr(" " PROPERFMT " max, " PROPERFMT " used", PROPERFMTARGS(young_generation()->max_capacity()), PROPERFMTARGS(young_generation()->used()));
607 st->print_cr(" Old:");
608 st->print_cr(" " PROPERFMT " max, " PROPERFMT " used", PROPERFMTARGS(old_generation()->max_capacity()), PROPERFMTARGS(old_generation()->used()));
609 st->print_cr(" Entire heap:");
610 st->print_cr(" " PROPERFMT " soft max, " PROPERFMT " committed",
611 PROPERFMTARGS(soft_max_capacity()), PROPERFMTARGS(committed()));
612 front_spacing = " ";
613 } else {
614 st->print_cr("Shenandoah Heap");
615 st->print_cr(" " PROPERFMT " max, " PROPERFMT " soft max, " PROPERFMT " committed, " PROPERFMT " used",
616 PROPERFMTARGS(max_capacity()),
617 PROPERFMTARGS(soft_max_capacity()),
618 PROPERFMTARGS(committed()),
619 PROPERFMTARGS(used())
620 );
621 }
622 st->print_cr("%s %zu x " PROPERFMT " regions",
623 front_spacing,
624 num_regions(),
625 PROPERFMTARGS(ShenandoahHeapRegion::region_size_bytes()));
626
627 st->print("Status: ");
628 if (has_forwarded_objects()) st->print("has forwarded objects, ");
629 if (!is_generational) {
630 if (is_concurrent_mark_in_progress()) st->print("marking,");
631 } else {
632 if (is_concurrent_old_mark_in_progress()) st->print("old marking, ");
633 if (is_concurrent_young_mark_in_progress()) st->print("young marking, ");
634 }
635 if (is_evacuation_in_progress()) st->print("evacuating, ");
636 if (is_update_refs_in_progress()) st->print("updating refs, ");
637 if (is_degenerated_gc_in_progress()) st->print("degenerated gc, ");
638 if (is_full_gc_in_progress()) st->print("full gc, ");
639 if (is_full_gc_move_in_progress()) st->print("full gc move, ");
640 if (is_concurrent_weak_root_in_progress()) st->print("concurrent weak roots, ");
641 if (is_concurrent_strong_root_in_progress() &&
642 !is_concurrent_weak_root_in_progress()) st->print("concurrent strong roots, ");
643
644 if (cancelled_gc()) {
645 st->print("cancelled");
646 } else {
647 st->print("not cancelled");
648 }
649 st->cr();
650
651 st->print_cr("Reserved region:");
652 st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
653 p2i(reserved_region().start()),
654 p2i(reserved_region().end()));
655
656 ShenandoahCollectionSet* cset = collection_set();
657 st->print_cr("Collection set:");
658 if (cset != nullptr) {
659 st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
660 st->print_cr(" - map (biased): " PTR_FORMAT, p2i(cset->biased_map_address()));
661 } else {
662 st->print_cr(" (null)");
663 }
664
665 st->cr();
666
667 if (Verbose) {
668 st->cr();
669 print_heap_regions_on(st);
670 }
671 }
672
673 void ShenandoahHeap::print_gc_on(outputStream* st) const {
674 print_heap_regions_on(st);
675 }
676
677 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
678 public:
679 void do_thread(Thread* thread) {
680 assert(thread != nullptr, "Sanity");
681 ShenandoahThreadLocalData::initialize_gclab(thread);
682 }
683 };
684
685 void ShenandoahHeap::post_initialize() {
686 CollectedHeap::post_initialize();
687
688 check_soft_max_changed();
689
690 // Schedule periodic task to report on gc thread CPU utilization
691 _mmu_tracker.initialize();
692
693 MutexLocker ml(Threads_lock);
694
695 ShenandoahInitWorkerGCLABClosure init_gclabs;
696 _workers->threads_do(&init_gclabs);
697
698 // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
699 // Now, we will let WorkerThreads to initialize gclab when new worker is created.
700 _workers->set_initialize_gclab();
701
702 // Note that the safepoint workers may require gclabs if the threads are used to create a heap dump
703 // during a concurrent evacuation phase.
704 if (_safepoint_workers != nullptr) {
705 _safepoint_workers->threads_do(&init_gclabs);
706 _safepoint_workers->set_initialize_gclab();
707 }
708
709 JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers();)
710 }
711
712 ShenandoahHeuristics* ShenandoahHeap::heuristics() {
713 return _global_generation->heuristics();
714 }
715
716 size_t ShenandoahHeap::used() const {
717 return global_generation()->used();
718 }
719
720 size_t ShenandoahHeap::committed() const {
721 return AtomicAccess::load(&_committed);
722 }
723
724 void ShenandoahHeap::increase_committed(size_t bytes) {
725 shenandoah_assert_heaplocked_or_safepoint();
726 _committed += bytes;
727 }
728
729 void ShenandoahHeap::decrease_committed(size_t bytes) {
730 shenandoah_assert_heaplocked_or_safepoint();
731 _committed -= bytes;
732 }
733
734 size_t ShenandoahHeap::capacity() const {
735 return committed();
736 }
737
738 size_t ShenandoahHeap::max_capacity() const {
739 return _num_regions * ShenandoahHeapRegion::region_size_bytes();
740 }
741
742 size_t ShenandoahHeap::soft_max_capacity() const {
743 size_t v = AtomicAccess::load(&_soft_max_size);
744 assert(min_capacity() <= v && v <= max_capacity(),
745 "Should be in bounds: %zu <= %zu <= %zu",
746 min_capacity(), v, max_capacity());
747 return v;
748 }
749
750 void ShenandoahHeap::set_soft_max_capacity(size_t v) {
751 assert(min_capacity() <= v && v <= max_capacity(),
752 "Should be in bounds: %zu <= %zu <= %zu",
753 min_capacity(), v, max_capacity());
754 AtomicAccess::store(&_soft_max_size, v);
755 }
756
757 size_t ShenandoahHeap::min_capacity() const {
758 return _minimum_size;
759 }
760
761 size_t ShenandoahHeap::initial_capacity() const {
762 return _initial_size;
763 }
764
765 bool ShenandoahHeap::is_in(const void* p) const {
766 if (!is_in_reserved(p)) {
767 return false;
768 }
769
770 if (is_full_gc_move_in_progress()) {
771 // Full GC move is running, we do not have a consistent region
772 // information yet. But we know the pointer is in heap.
773 return true;
774 }
775
776 // Now check if we point to a live section in active region.
777 const ShenandoahHeapRegion* r = heap_region_containing(p);
778 if (p >= r->top()) {
779 return false;
780 }
781
782 if (r->is_active()) {
783 return true;
784 }
785
786 // The region is trash, but won't be recycled until after concurrent weak
787 // roots. We also don't allow mutators to allocate from trash regions
788 // during weak roots. Concurrent class unloading may access unmarked oops
789 // in trash regions.
790 return r->is_trash() && is_concurrent_weak_root_in_progress();
791 }
792
793 void ShenandoahHeap::notify_soft_max_changed() {
794 if (_uncommit_thread != nullptr) {
795 _uncommit_thread->notify_soft_max_changed();
796 }
797 }
798
799 void ShenandoahHeap::notify_explicit_gc_requested() {
800 if (_uncommit_thread != nullptr) {
801 _uncommit_thread->notify_explicit_gc_requested();
802 }
803 }
804
805 bool ShenandoahHeap::check_soft_max_changed() {
806 size_t new_soft_max = AtomicAccess::load(&SoftMaxHeapSize);
807 size_t old_soft_max = soft_max_capacity();
808 if (new_soft_max != old_soft_max) {
809 new_soft_max = MAX2(min_capacity(), new_soft_max);
810 new_soft_max = MIN2(max_capacity(), new_soft_max);
811 if (new_soft_max != old_soft_max) {
812 log_info(gc)("Soft Max Heap Size: %zu%s -> %zu%s",
813 byte_size_in_proper_unit(old_soft_max), proper_unit_for_byte_size(old_soft_max),
814 byte_size_in_proper_unit(new_soft_max), proper_unit_for_byte_size(new_soft_max)
815 );
816 set_soft_max_capacity(new_soft_max);
817 return true;
818 }
819 }
820 return false;
821 }
822
823 void ShenandoahHeap::notify_heap_changed() {
824 // Update monitoring counters when we took a new region. This amortizes the
825 // update costs on slow path.
826 monitoring_support()->notify_heap_changed();
827 _heap_changed.try_set();
828 }
829
830 void ShenandoahHeap::set_forced_counters_update(bool value) {
831 monitoring_support()->set_forced_counters_update(value);
832 }
833
834 void ShenandoahHeap::handle_force_counters_update() {
835 monitoring_support()->handle_force_counters_update();
836 }
837
838 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
839 // New object should fit the GCLAB size
840 size_t min_size = MAX2(size, PLAB::min_size());
841
842 // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
843 size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
844
845 new_size = MIN2(new_size, PLAB::max_size());
846 new_size = MAX2(new_size, PLAB::min_size());
847
848 // Record new heuristic value even if we take any shortcut. This captures
849 // the case when moderately-sized objects always take a shortcut. At some point,
850 // heuristics should catch up with them.
851 log_debug(gc, free)("Set new GCLAB size: %zu", new_size);
852 ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
853
854 if (new_size < size) {
855 // New size still does not fit the object. Fall back to shared allocation.
856 // This avoids retiring perfectly good GCLABs, when we encounter a large object.
857 log_debug(gc, free)("New gclab size (%zu) is too small for %zu", new_size, size);
858 return nullptr;
859 }
860
861 // Retire current GCLAB, and allocate a new one.
862 PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
863 gclab->retire();
864
865 size_t actual_size = 0;
866 HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
867 if (gclab_buf == nullptr) {
868 return nullptr;
869 }
870
871 assert (size <= actual_size, "allocation should fit");
872
873 // ...and clear or zap just allocated TLAB, if needed.
874 if (ZeroTLAB) {
875 Copy::zero_to_words(gclab_buf, actual_size);
876 } else if (ZapTLAB) {
877 // Skip mangling the space corresponding to the object header to
878 // ensure that the returned space is not considered parsable by
879 // any concurrent GC thread.
880 size_t hdr_size = oopDesc::header_size();
881 Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
882 }
883 gclab->set_buf(gclab_buf, actual_size);
884 return gclab->allocate(size);
885 }
886
887 // Called from stubs in JIT code or interpreter
888 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
889 size_t requested_size,
890 size_t* actual_size) {
891 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
892 HeapWord* res = allocate_memory(req);
893 if (res != nullptr) {
894 *actual_size = req.actual_size();
895 } else {
896 *actual_size = 0;
897 }
898 return res;
899 }
900
901 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
902 size_t word_size,
903 size_t* actual_size) {
904 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
905 HeapWord* res = allocate_memory(req);
906 if (res != nullptr) {
907 *actual_size = req.actual_size();
908 } else {
909 *actual_size = 0;
910 }
911 return res;
912 }
913
914 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
915 bool in_new_region = false;
916 HeapWord* result = nullptr;
917
918 if (req.is_mutator_alloc()) {
919
920 if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
921 result = allocate_memory_under_lock(req, in_new_region);
922 }
923
924 // Check that gc overhead is not exceeded.
925 //
926 // Shenandoah will grind along for quite a while allocating one
927 // object at a time using shared (non-tlab) allocations. This check
928 // is testing that the GC overhead limit has not been exceeded.
929 // This will notify the collector to start a cycle, but will raise
930 // an OOME to the mutator if the last Full GCs have not made progress.
931 // gc_no_progress_count is incremented following each degen or full GC that fails to achieve is_good_progress().
932 if (result == nullptr && !req.is_lab_alloc() && get_gc_no_progress_count() > ShenandoahNoProgressThreshold) {
933 control_thread()->handle_alloc_failure(req, false);
934 req.set_actual_size(0);
935 return nullptr;
936 }
937
938 if (result == nullptr) {
939 // Block until control thread reacted, then retry allocation.
940 //
941 // It might happen that one of the threads requesting allocation would unblock
942 // way later after GC happened, only to fail the second allocation, because
943 // other threads have already depleted the free storage. In this case, a better
944 // strategy is to try again, until at least one full GC has completed.
945 //
946 // Stop retrying and return nullptr to cause OOMError exception if our allocation failed even after:
947 // a) We experienced a GC that had good progress, or
948 // b) We experienced at least one Full GC (whether or not it had good progress)
949
950 const size_t original_count = shenandoah_policy()->full_gc_count();
951 while (result == nullptr && should_retry_allocation(original_count)) {
952 control_thread()->handle_alloc_failure(req, true);
953 result = allocate_memory_under_lock(req, in_new_region);
954 }
955 if (result != nullptr) {
956 // If our allocation request has been satisfied after it initially failed, we count this as good gc progress
957 notify_gc_progress();
958 }
959 if (log_develop_is_enabled(Debug, gc, alloc)) {
960 ResourceMark rm;
961 log_debug(gc, alloc)("Thread: %s, Result: " PTR_FORMAT ", Request: %s, Size: %zu"
962 ", Original: %zu, Latest: %zu",
963 Thread::current()->name(), p2i(result), req.type_string(), req.size(),
964 original_count, get_gc_no_progress_count());
965 }
966 }
967 } else {
968 assert(req.is_gc_alloc(), "Can only accept GC allocs here");
969 result = allocate_memory_under_lock(req, in_new_region);
970 // Do not call handle_alloc_failure() here, because we cannot block.
971 // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
972 }
973
974 if (in_new_region) {
975 notify_heap_changed();
976 }
977
978 if (result == nullptr) {
979 req.set_actual_size(0);
980 }
981
982 if (result != nullptr) {
983 size_t requested = req.size();
984 size_t actual = req.actual_size();
985
986 assert (req.is_lab_alloc() || (requested == actual),
987 "Only LAB allocations are elastic: %s, requested = %zu, actual = %zu",
988 ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
989 }
990
991 return result;
992 }
993
994 inline bool ShenandoahHeap::should_retry_allocation(size_t original_full_gc_count) const {
995 return shenandoah_policy()->full_gc_count() == original_full_gc_count
996 && !shenandoah_policy()->is_at_shutdown();
997 }
998
999 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {
1000 // If we are dealing with mutator allocation, then we may need to block for safepoint.
1001 // We cannot block for safepoint for GC allocations, because there is a high chance
1002 // we are already running at safepoint or from stack watermark machinery, and we cannot
1003 // block again.
1004 ShenandoahHeapLocker locker(lock(), req.is_mutator_alloc());
1005
1006 // Make sure the old generation has room for either evacuations or promotions before trying to allocate.
1007 if (req.is_old() && !old_generation()->can_allocate(req)) {
1008 return nullptr;
1009 }
1010
1011 // If TLAB request size is greater than available, allocate() will attempt to downsize request to fit within available
1012 // memory.
1013 HeapWord* result = _free_set->allocate(req, in_new_region);
1014
1015 // Record the plab configuration for this result and register the object.
1016 if (result != nullptr && req.is_old()) {
1017 old_generation()->configure_plab_for_current_thread(req);
1018 if (req.type() == ShenandoahAllocRequest::_alloc_shared_gc) {
1019 // Register the newly allocated object while we're holding the global lock since there's no synchronization
1020 // built in to the implementation of register_object(). There are potential races when multiple independent
1021 // threads are allocating objects, some of which might span the same card region. For example, consider
1022 // a card table's memory region within which three objects are being allocated by three different threads:
1023 //
1024 // objects being "concurrently" allocated:
1025 // [-----a------][-----b-----][--------------c------------------]
1026 // [---- card table memory range --------------]
1027 //
1028 // Before any objects are allocated, this card's memory range holds no objects. Note that allocation of object a
1029 // wants to set the starts-object, first-start, and last-start attributes of the preceding card region.
1030 // Allocation of object b wants to set the starts-object, first-start, and last-start attributes of this card region.
1031 // Allocation of object c also wants to set the starts-object, first-start, and last-start attributes of this
1032 // card region.
1033 //
1034 // The thread allocating b and the thread allocating c can "race" in various ways, resulting in confusion, such as
1035 // last-start representing object b while first-start represents object c. This is why we need to require all
1036 // register_object() invocations to be "mutually exclusive" with respect to each card's memory range.
1037 old_generation()->card_scan()->register_object(result);
1038 }
1039 }
1040
1041 return result;
1042 }
1043
1044 HeapWord* ShenandoahHeap::mem_allocate(size_t size) {
1045 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
1046 return allocate_memory(req);
1047 }
1048
1049 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
1050 size_t size,
1051 Metaspace::MetadataType mdtype) {
1052 MetaWord* result;
1053
1054 // Inform metaspace OOM to GC heuristics if class unloading is possible.
1055 ShenandoahHeuristics* h = global_generation()->heuristics();
1056 if (h->can_unload_classes()) {
1057 h->record_metaspace_oom();
1058 }
1059
1060 // Expand and retry allocation
1061 result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
1062 if (result != nullptr) {
1063 return result;
1064 }
1065
1066 // Start full GC
1067 collect(GCCause::_metadata_GC_clear_soft_refs);
1068
1069 // Retry allocation
1070 result = loader_data->metaspace_non_null()->allocate(size, mdtype);
1071 if (result != nullptr) {
1072 return result;
1073 }
1074
1075 // Expand and retry allocation
1076 result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
1077 if (result != nullptr) {
1078 return result;
1079 }
1080
1081 // Out of memory
1082 return nullptr;
1083 }
1084
1085 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
1086 private:
1087 ShenandoahHeap* const _heap;
1088 Thread* const _thread;
1089 public:
1090 ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
1091 _heap(heap), _thread(Thread::current()) {}
1092
1093 void do_object(oop p) {
1094 shenandoah_assert_marked(nullptr, p);
1095 if (!p->is_forwarded()) {
1096 _heap->evacuate_object(p, _thread);
1097 }
1098 }
1099 };
1100
1101 class ShenandoahEvacuationTask : public WorkerTask {
1102 private:
1103 ShenandoahHeap* const _sh;
1104 ShenandoahCollectionSet* const _cs;
1105 bool _concurrent;
1106 public:
1107 ShenandoahEvacuationTask(ShenandoahHeap* sh,
1108 ShenandoahCollectionSet* cs,
1109 bool concurrent) :
1110 WorkerTask("Shenandoah Evacuation"),
1111 _sh(sh),
1112 _cs(cs),
1113 _concurrent(concurrent)
1114 {}
1115
1116 void work(uint worker_id) {
1117 if (_concurrent) {
1118 ShenandoahConcurrentWorkerSession worker_session(worker_id);
1119 ShenandoahSuspendibleThreadSetJoiner stsj;
1120 ShenandoahEvacOOMScope oom_evac_scope;
1121 do_work();
1122 } else {
1123 ShenandoahParallelWorkerSession worker_session(worker_id);
1124 ShenandoahEvacOOMScope oom_evac_scope;
1125 do_work();
1126 }
1127 }
1128
1129 private:
1130 void do_work() {
1131 ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
1132 ShenandoahHeapRegion* r;
1133 while ((r =_cs->claim_next()) != nullptr) {
1134 assert(r->has_live(), "Region %zu should have been reclaimed early", r->index());
1135 _sh->marked_object_iterate(r, &cl);
1136
1137 if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1138 break;
1139 }
1140 }
1141 }
1142 };
1143
1144 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1145 private:
1146 bool const _resize;
1147 public:
1148 explicit ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}
1149 void do_thread(Thread* thread) override {
1150 PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1151 assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name());
1152 gclab->retire();
1153 if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1154 ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1155 }
1156
1157 if (ShenandoahHeap::heap()->mode()->is_generational()) {
1158 PLAB* plab = ShenandoahThreadLocalData::plab(thread);
1159 assert(plab != nullptr, "PLAB should be initialized for %s", thread->name());
1160
1161 // There are two reasons to retire all plabs between old-gen evacuation passes.
1162 // 1. We need to make the plab memory parsable by remembered-set scanning.
1163 // 2. We need to establish a trustworthy UpdateWaterMark value within each old-gen heap region
1164 ShenandoahGenerationalHeap::heap()->retire_plab(plab, thread);
1165
1166 // Re-enable promotions for the next evacuation phase.
1167 ShenandoahThreadLocalData::enable_plab_promotions(thread);
1168
1169 // Reset the fill size for next evacuation phase.
1170 if (_resize && ShenandoahThreadLocalData::plab_size(thread) > 0) {
1171 ShenandoahThreadLocalData::set_plab_size(thread, 0);
1172 }
1173 }
1174 }
1175 };
1176
1177 class ShenandoahGCStatePropagatorHandshakeClosure : public HandshakeClosure {
1178 public:
1179 explicit ShenandoahGCStatePropagatorHandshakeClosure(char gc_state) :
1180 HandshakeClosure("Shenandoah GC State Change"),
1181 _gc_state(gc_state) {}
1182
1183 void do_thread(Thread* thread) override {
1184 ShenandoahThreadLocalData::set_gc_state(thread, _gc_state);
1185 }
1186 private:
1187 char _gc_state;
1188 };
1189
1190 class ShenandoahPrepareForUpdateRefsHandshakeClosure : public HandshakeClosure {
1191 public:
1192 explicit ShenandoahPrepareForUpdateRefsHandshakeClosure(char gc_state) :
1193 HandshakeClosure("Shenandoah Prepare for Update Refs"),
1194 _retire(ResizeTLAB), _propagator(gc_state) {}
1195
1196 void do_thread(Thread* thread) override {
1197 _propagator.do_thread(thread);
1198 if (ShenandoahThreadLocalData::gclab(thread) != nullptr) {
1199 _retire.do_thread(thread);
1200 }
1201 }
1202 private:
1203 ShenandoahRetireGCLABClosure _retire;
1204 ShenandoahGCStatePropagatorHandshakeClosure _propagator;
1205 };
1206
1207 void ShenandoahHeap::evacuate_collection_set(ShenandoahGeneration* generation, bool concurrent) {
1208 assert(generation->is_global(), "Only global generation expected here");
1209 ShenandoahEvacuationTask task(this, _collection_set, concurrent);
1210 workers()->run_task(&task);
1211 }
1212
1213 void ShenandoahHeap::concurrent_prepare_for_update_refs() {
1214 {
1215 // Java threads take this lock while they are being attached and added to the list of threads.
1216 // If another thread holds this lock before we update the gc state, it will receive a stale
1217 // gc state, but they will have been added to the list of java threads and so will be corrected
1218 // by the following handshake.
1219 MutexLocker lock(Threads_lock);
1220
1221 // A cancellation at this point means the degenerated cycle must resume from update-refs.
1222 set_gc_state_concurrent(EVACUATION, false);
1223 set_gc_state_concurrent(WEAK_ROOTS, false);
1224 set_gc_state_concurrent(UPDATE_REFS, true);
1225 }
1226
1227 // This will propagate the gc state and retire gclabs and plabs for threads that require it.
1228 ShenandoahPrepareForUpdateRefsHandshakeClosure prepare_for_update_refs(_gc_state.raw_value());
1229
1230 // The handshake won't touch worker threads (or control thread, or VM thread), so do those separately.
1231 Threads::non_java_threads_do(&prepare_for_update_refs);
1232
1233 // Now retire gclabs and plabs and propagate gc_state for mutator threads
1234 Handshake::execute(&prepare_for_update_refs);
1235
1236 _update_refs_iterator.reset();
1237 }
1238
1239 class ShenandoahCompositeHandshakeClosure : public HandshakeClosure {
1240 HandshakeClosure* _handshake_1;
1241 HandshakeClosure* _handshake_2;
1242 public:
1243 ShenandoahCompositeHandshakeClosure(HandshakeClosure* handshake_1, HandshakeClosure* handshake_2) :
1244 HandshakeClosure(handshake_2->name()),
1245 _handshake_1(handshake_1), _handshake_2(handshake_2) {}
1246
1247 void do_thread(Thread* thread) override {
1248 _handshake_1->do_thread(thread);
1249 _handshake_2->do_thread(thread);
1250 }
1251 };
1252
1253 void ShenandoahHeap::concurrent_final_roots(HandshakeClosure* handshake_closure) {
1254 {
1255 assert(!is_evacuation_in_progress(), "Should not evacuate for abbreviated or old cycles");
1256 MutexLocker lock(Threads_lock);
1257 set_gc_state_concurrent(WEAK_ROOTS, false);
1258 }
1259
1260 ShenandoahGCStatePropagatorHandshakeClosure propagator(_gc_state.raw_value());
1261 Threads::non_java_threads_do(&propagator);
1262 if (handshake_closure == nullptr) {
1263 Handshake::execute(&propagator);
1264 } else {
1265 ShenandoahCompositeHandshakeClosure composite(&propagator, handshake_closure);
1266 Handshake::execute(&composite);
1267 }
1268 }
1269
1270 oop ShenandoahHeap::evacuate_object(oop p, Thread* thread) {
1271 assert(thread == Thread::current(), "Expected thread parameter to be current thread.");
1272 if (ShenandoahThreadLocalData::is_oom_during_evac(thread)) {
1273 // This thread went through the OOM during evac protocol. It is safe to return
1274 // the forward pointer. It must not attempt to evacuate any other objects.
1275 return ShenandoahBarrierSet::resolve_forwarded(p);
1276 }
1277
1278 assert(ShenandoahThreadLocalData::is_evac_allowed(thread), "must be enclosed in oom-evac scope");
1279
1280 ShenandoahHeapRegion* r = heap_region_containing(p);
1281 assert(!r->is_humongous(), "never evacuate humongous objects");
1282
1283 ShenandoahAffiliation target_gen = r->affiliation();
1284 return try_evacuate_object(p, thread, r, target_gen);
1285 }
1286
1287 oop ShenandoahHeap::try_evacuate_object(oop p, Thread* thread, ShenandoahHeapRegion* from_region,
1288 ShenandoahAffiliation target_gen) {
1289 assert(target_gen == YOUNG_GENERATION, "Only expect evacuations to young in this mode");
1290 assert(from_region->is_young(), "Only expect evacuations from young in this mode");
1291 bool alloc_from_lab = true;
1292 HeapWord* copy = nullptr;
1293 size_t size = ShenandoahForwarding::size(p);
1294
1295 #ifdef ASSERT
1296 if (ShenandoahOOMDuringEvacALot &&
1297 (os::random() & 1) == 0) { // Simulate OOM every ~2nd slow-path call
1298 copy = nullptr;
1299 } else {
1300 #endif
1301 if (UseTLAB) {
1302 copy = allocate_from_gclab(thread, size);
1303 }
1304 if (copy == nullptr) {
1305 // If we failed to allocate in LAB, we'll try a shared allocation.
1306 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared_gc(size, target_gen);
1307 copy = allocate_memory(req);
1308 alloc_from_lab = false;
1309 }
1310 #ifdef ASSERT
1311 }
1312 #endif
1313
1314 if (copy == nullptr) {
1315 control_thread()->handle_alloc_failure_evac(size);
1316
1317 _oom_evac_handler.handle_out_of_memory_during_evacuation();
1318
1319 return ShenandoahBarrierSet::resolve_forwarded(p);
1320 }
1321
1322 if (ShenandoahEvacTracking) {
1323 evac_tracker()->begin_evacuation(thread, size * HeapWordSize, from_region->affiliation(), target_gen);
1324 }
1325
1326 // Copy the object:
1327 Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(p), copy, size);
1328
1329 // Try to install the new forwarding pointer.
1330 oop copy_val = cast_to_oop(copy);
1331 oop result = ShenandoahForwarding::try_update_forwardee(p, copy_val);
1332 if (result == copy_val) {
1333 // Successfully evacuated. Our copy is now the public one!
1334 ContinuationGCSupport::relativize_stack_chunk(copy_val);
1335 shenandoah_assert_correct(nullptr, copy_val);
1336 if (ShenandoahEvacTracking) {
1337 evac_tracker()->end_evacuation(thread, size * HeapWordSize, from_region->affiliation(), target_gen);
1338 }
1339 return copy_val;
1340 } else {
1341 // Failed to evacuate. We need to deal with the object that is left behind. Since this
1342 // new allocation is certainly after TAMS, it will be considered live in the next cycle.
1343 // But if it happens to contain references to evacuated regions, those references would
1344 // not get updated for this stale copy during this cycle, and we will crash while scanning
1345 // it the next cycle.
1346 if (alloc_from_lab) {
1347 // For LAB allocations, it is enough to rollback the allocation ptr. Either the next
1348 // object will overwrite this stale copy, or the filler object on LAB retirement will
1349 // do this.
1350 ShenandoahThreadLocalData::gclab(thread)->undo_allocation(copy, size);
1351 } else {
1352 // For non-LAB allocations, we have no way to retract the allocation, and
1353 // have to explicitly overwrite the copy with the filler object. With that overwrite,
1354 // we have to keep the fwdptr initialized and pointing to our (stale) copy.
1355 assert(size >= ShenandoahHeap::min_fill_size(), "previously allocated object known to be larger than min_size");
1356 fill_with_object(copy, size);
1357 shenandoah_assert_correct(nullptr, copy_val);
1358 // For non-LAB allocations, the object has already been registered
1359 }
1360 shenandoah_assert_correct(nullptr, result);
1361 return result;
1362 }
1363 }
1364
1365 void ShenandoahHeap::trash_cset_regions() {
1366 ShenandoahHeapLocker locker(lock());
1367
1368 ShenandoahCollectionSet* set = collection_set();
1369 ShenandoahHeapRegion* r;
1370 set->clear_current_index();
1371 while ((r = set->next()) != nullptr) {
1372 r->make_trash();
1373 }
1374 collection_set()->clear();
1375 }
1376
1377 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1378 st->print_cr("Heap Regions:");
1379 st->print_cr("Region state: EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HP=pinned humongous start");
1380 st->print_cr(" HC=humongous continuation, CS=collection set, TR=trash, P=pinned, CSP=pinned collection set");
1381 st->print_cr("BTE=bottom/top/end, TAMS=top-at-mark-start");
1382 st->print_cr("UWM=update watermark, U=used");
1383 st->print_cr("T=TLAB allocs, G=GCLAB allocs");
1384 st->print_cr("S=shared allocs, L=live data");
1385 st->print_cr("CP=critical pins");
1386
1387 for (size_t i = 0; i < num_regions(); i++) {
1388 get_region(i)->print_on(st);
1389 }
1390 }
1391
1392 void ShenandoahHeap::process_gc_stats() const {
1393 // Commit worker statistics to cycle data
1394 phase_timings()->flush_par_workers_to_cycle();
1395
1396 // Print GC stats for current cycle
1397 LogTarget(Info, gc, stats) lt;
1398 if (lt.is_enabled()) {
1399 ResourceMark rm;
1400 LogStream ls(lt);
1401 phase_timings()->print_cycle_on(&ls);
1402 if (ShenandoahEvacTracking) {
1403 ShenandoahCycleStats evac_stats = evac_tracker()->flush_cycle_to_global();
1404 evac_tracker()->print_evacuations_on(&ls, &evac_stats.workers,
1405 &evac_stats.mutators);
1406 }
1407 }
1408
1409 // Commit statistics to globals
1410 phase_timings()->flush_cycle_to_global();
1411 }
1412
1413 size_t ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) const {
1414 assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1415 assert(!start->has_live(), "liveness must be zero");
1416
1417 // Do not try to get the size of this humongous object. STW collections will
1418 // have already unloaded classes, so an unmarked object may have a bad klass pointer.
1419 ShenandoahHeapRegion* region = start;
1420 size_t index = region->index();
1421 do {
1422 assert(region->is_humongous(), "Expect correct humongous start or continuation");
1423 assert(!region->is_cset(), "Humongous region should not be in collection set");
1424 region->make_trash_immediate();
1425 region = get_region(++index);
1426 } while (region != nullptr && region->is_humongous_continuation());
1427
1428 // Return number of regions trashed
1429 return index - start->index();
1430 }
1431
1432 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {
1433 public:
1434 ShenandoahCheckCleanGCLABClosure() {}
1435 void do_thread(Thread* thread) {
1436 PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1437 assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name());
1438 assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");
1439
1440 if (ShenandoahHeap::heap()->mode()->is_generational()) {
1441 PLAB* plab = ShenandoahThreadLocalData::plab(thread);
1442 assert(plab != nullptr, "PLAB should be initialized for %s", thread->name());
1443 assert(plab->words_remaining() == 0, "PLAB should not need retirement");
1444 }
1445 }
1446 };
1447
1448 void ShenandoahHeap::labs_make_parsable() {
1449 assert(UseTLAB, "Only call with UseTLAB");
1450
1451 ShenandoahRetireGCLABClosure cl(false);
1452
1453 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1454 ThreadLocalAllocBuffer& tlab = t->tlab();
1455 tlab.make_parsable();
1456 if (ZeroTLAB) {
1457 t->retire_tlab();
1458 }
1459 cl.do_thread(t);
1460 }
1461
1462 workers()->threads_do(&cl);
1463
1464 if (safepoint_workers() != nullptr) {
1465 safepoint_workers()->threads_do(&cl);
1466 }
1467 }
1468
1469 void ShenandoahHeap::tlabs_retire(bool resize) {
1470 assert(UseTLAB, "Only call with UseTLAB");
1471 assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1472
1473 ThreadLocalAllocStats stats;
1474
1475 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1476 t->retire_tlab(&stats);
1477 if (resize) {
1478 t->tlab().resize();
1479 }
1480 }
1481
1482 stats.publish();
1483
1484 #ifdef ASSERT
1485 ShenandoahCheckCleanGCLABClosure cl;
1486 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1487 cl.do_thread(t);
1488 }
1489 workers()->threads_do(&cl);
1490 #endif
1491 }
1492
1493 void ShenandoahHeap::gclabs_retire(bool resize) {
1494 assert(UseTLAB, "Only call with UseTLAB");
1495 assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1496
1497 ShenandoahRetireGCLABClosure cl(resize);
1498 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1499 cl.do_thread(t);
1500 }
1501
1502 workers()->threads_do(&cl);
1503
1504 if (safepoint_workers() != nullptr) {
1505 safepoint_workers()->threads_do(&cl);
1506 }
1507 }
1508
1509 // Returns size in bytes
1510 size_t ShenandoahHeap::unsafe_max_tlab_alloc() const {
1511 // Return the max allowed size, and let the allocation path
1512 // figure out the safe size for current allocation.
1513 return ShenandoahHeapRegion::max_tlab_size_bytes();
1514 }
1515
1516 size_t ShenandoahHeap::max_tlab_size() const {
1517 // Returns size in words
1518 return ShenandoahHeapRegion::max_tlab_size_words();
1519 }
1520
1521 void ShenandoahHeap::collect_as_vm_thread(GCCause::Cause cause) {
1522 // These requests are ignored because we can't easily have Shenandoah jump into
1523 // a synchronous (degenerated or full) cycle while it is in the middle of a concurrent
1524 // cycle. We _could_ cancel the concurrent cycle and then try to run a cycle directly
1525 // on the VM thread, but this would confuse the control thread mightily and doesn't
1526 // seem worth the trouble. Instead, we will have the caller thread run (and wait for) a
1527 // concurrent cycle in the prologue of the heap inspect/dump operation (see VM_HeapDumper::doit_prologue).
1528 // This is how other concurrent collectors in the JVM handle this scenario as well.
1529 assert(Thread::current()->is_VM_thread(), "Should be the VM thread");
1530 guarantee(cause == GCCause::_heap_dump || cause == GCCause::_heap_inspection, "Invalid cause");
1531 }
1532
1533 void ShenandoahHeap::collect(GCCause::Cause cause) {
1534 control_thread()->request_gc(cause);
1535 }
1536
1537 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1538 // This method is only called by `CollectedHeap::collect_as_vm_thread`, which we have
1539 // overridden to do nothing. See the comment there for an explanation of how heap inspections
1540 // work for Shenandoah.
1541 ShouldNotReachHere();
1542 }
1543
1544 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1545 ShenandoahHeapRegion* r = heap_region_containing(addr);
1546 if (r != nullptr) {
1547 return r->block_start(addr);
1548 }
1549 return nullptr;
1550 }
1551
1552 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1553 ShenandoahHeapRegion* r = heap_region_containing(addr);
1554 return r->block_is_obj(addr);
1555 }
1556
1557 bool ShenandoahHeap::print_location(outputStream* st, void* addr) const {
1558 return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr);
1559 }
1560
1561 void ShenandoahHeap::prepare_for_verify() {
1562 if (SafepointSynchronize::is_at_safepoint() && UseTLAB) {
1563 labs_make_parsable();
1564 }
1565 }
1566
1567 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1568 if (_shenandoah_policy->is_at_shutdown()) {
1569 return;
1570 }
1571
1572 if (_control_thread != nullptr) {
1573 tcl->do_thread(_control_thread);
1574 }
1575
1576 if (_uncommit_thread != nullptr) {
1577 tcl->do_thread(_uncommit_thread);
1578 }
1579
1580 workers()->threads_do(tcl);
1581 if (_safepoint_workers != nullptr) {
1582 _safepoint_workers->threads_do(tcl);
1583 }
1584 }
1585
1586 void ShenandoahHeap::print_tracing_info() const {
1587 LogTarget(Info, gc, stats) lt;
1588 if (lt.is_enabled()) {
1589 ResourceMark rm;
1590 LogStream ls(lt);
1591
1592 if (ShenandoahEvacTracking) {
1593 evac_tracker()->print_global_on(&ls);
1594 ls.cr();
1595 ls.cr();
1596 }
1597
1598 phase_timings()->print_global_on(&ls);
1599
1600 ls.cr();
1601 ls.cr();
1602
1603 shenandoah_policy()->print_gc_stats(&ls);
1604
1605 ls.cr();
1606 ls.cr();
1607 }
1608 }
1609
1610 // Active generation may only be set by the VM thread at a safepoint.
1611 void ShenandoahHeap::set_active_generation(ShenandoahGeneration* generation) {
1612 assert(Thread::current()->is_VM_thread(), "Only the VM Thread");
1613 assert(SafepointSynchronize::is_at_safepoint(), "Only at a safepoint!");
1614 _active_generation = generation;
1615 }
1616
1617 void ShenandoahHeap::on_cycle_start(GCCause::Cause cause, ShenandoahGeneration* generation) {
1618 shenandoah_policy()->record_collection_cause(cause);
1619
1620 const GCCause::Cause current = gc_cause();
1621 assert(current == GCCause::_no_gc, "Over-writing cause: %s, with: %s",
1622 GCCause::to_string(current), GCCause::to_string(cause));
1623
1624 set_gc_cause(cause);
1625
1626 generation->heuristics()->record_cycle_start();
1627 }
1628
1629 void ShenandoahHeap::on_cycle_end(ShenandoahGeneration* generation) {
1630 assert(gc_cause() != GCCause::_no_gc, "cause wasn't set");
1631
1632 generation->heuristics()->record_cycle_end();
1633 if (mode()->is_generational() && generation->is_global()) {
1634 // If we just completed a GLOBAL GC, claim credit for completion of young-gen and old-gen GC as well
1635 young_generation()->heuristics()->record_cycle_end();
1636 old_generation()->heuristics()->record_cycle_end();
1637 }
1638
1639 set_gc_cause(GCCause::_no_gc);
1640 }
1641
1642 void ShenandoahHeap::verify(VerifyOption vo) {
1643 if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1644 if (ShenandoahVerify) {
1645 verifier()->verify_generic(active_generation(), vo);
1646 } else {
1647 // TODO: Consider allocating verification bitmaps on demand,
1648 // and turn this on unconditionally.
1649 }
1650 }
1651 }
1652 size_t ShenandoahHeap::tlab_capacity() const {
1653 return _free_set->capacity();
1654 }
1655
1656 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1657 private:
1658 MarkBitMap* _bitmap;
1659 ShenandoahScanObjectStack* _oop_stack;
1660 ShenandoahHeap* const _heap;
1661 ShenandoahMarkingContext* const _marking_context;
1662
1663 template <class T>
1664 void do_oop_work(T* p) {
1665 T o = RawAccess<>::oop_load(p);
1666 if (!CompressedOops::is_null(o)) {
1667 oop obj = CompressedOops::decode_not_null(o);
1668 if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1669 // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1670 return;
1671 }
1672 obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1673
1674 assert(oopDesc::is_oop(obj), "must be a valid oop");
1675 if (!_bitmap->is_marked(obj)) {
1676 _bitmap->mark(obj);
1677 _oop_stack->push(obj);
1678 }
1679 }
1680 }
1681 public:
1682 ObjectIterateScanRootClosure(MarkBitMap* bitmap, ShenandoahScanObjectStack* oop_stack) :
1683 _bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()),
1684 _marking_context(_heap->marking_context()) {}
1685 void do_oop(oop* p) { do_oop_work(p); }
1686 void do_oop(narrowOop* p) { do_oop_work(p); }
1687 };
1688
1689 /*
1690 * This is public API, used in preparation of object_iterate().
1691 * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1692 * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1693 * control, we call SH::tlabs_retire, SH::gclabs_retire.
1694 */
1695 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1696 // No-op.
1697 }
1698
1699 /*
1700 * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1701 *
1702 * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1703 * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1704 * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1705 * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1706 * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1707 * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1708 * wiped the bitmap in preparation for next marking).
1709 *
1710 * For all those reasons, we implement object iteration as a single marking traversal, reporting
1711 * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1712 * is allowed to report dead objects, but is not required to do so.
1713 */
1714 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1715 // Reset bitmap
1716 if (!prepare_aux_bitmap_for_iteration())
1717 return;
1718
1719 ShenandoahScanObjectStack oop_stack;
1720 ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1721 // Seed the stack with root scan
1722 scan_roots_for_iteration(&oop_stack, &oops);
1723
1724 // Work through the oop stack to traverse heap
1725 while (! oop_stack.is_empty()) {
1726 oop obj = oop_stack.pop();
1727 assert(oopDesc::is_oop(obj), "must be a valid oop");
1728 cl->do_object(obj);
1729 obj->oop_iterate(&oops);
1730 }
1731
1732 assert(oop_stack.is_empty(), "should be empty");
1733 // Reclaim bitmap
1734 reclaim_aux_bitmap_for_iteration();
1735 }
1736
1737 bool ShenandoahHeap::prepare_aux_bitmap_for_iteration() {
1738 assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1739 if (!_aux_bitmap_region_special) {
1740 bool success = os::commit_memory((char *) _aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false);
1741 if (!success) {
1742 log_warning(gc)("Auxiliary marking bitmap commit failed: " PTR_FORMAT " (%zu bytes)",
1743 p2i(_aux_bitmap_region.start()), _aux_bitmap_region.byte_size());
1744 return false;
1745 }
1746 }
1747 _aux_bit_map.clear();
1748 return true;
1749 }
1750
1751 void ShenandoahHeap::scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops) {
1752 // Process GC roots according to current GC cycle
1753 // This populates the work stack with initial objects
1754 // It is important to relinquish the associated locks before diving
1755 // into heap dumper
1756 uint n_workers = safepoint_workers() != nullptr ? safepoint_workers()->active_workers() : 1;
1757 ShenandoahHeapIterationRootScanner rp(n_workers);
1758 rp.roots_do(oops);
1759 }
1760
1761 void ShenandoahHeap::reclaim_aux_bitmap_for_iteration() {
1762 if (!_aux_bitmap_region_special) {
1763 bool success = os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size());
1764 if (!success) {
1765 log_warning(gc)("Auxiliary marking bitmap uncommit failed: " PTR_FORMAT " (%zu bytes)",
1766 p2i(_aux_bitmap_region.start()), _aux_bitmap_region.byte_size());
1767 assert(false, "Auxiliary marking bitmap uncommit should always succeed");
1768 }
1769 }
1770 }
1771
1772 // Closure for parallelly iterate objects
1773 class ShenandoahObjectIterateParScanClosure : public BasicOopIterateClosure {
1774 private:
1775 MarkBitMap* _bitmap;
1776 ShenandoahObjToScanQueue* _queue;
1777 ShenandoahHeap* const _heap;
1778 ShenandoahMarkingContext* const _marking_context;
1779
1780 template <class T>
1781 void do_oop_work(T* p) {
1782 T o = RawAccess<>::oop_load(p);
1783 if (!CompressedOops::is_null(o)) {
1784 oop obj = CompressedOops::decode_not_null(o);
1785 if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1786 // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1787 return;
1788 }
1789 obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1790
1791 assert(oopDesc::is_oop(obj), "Must be a valid oop");
1792 if (_bitmap->par_mark(obj)) {
1793 _queue->push(ShenandoahMarkTask(obj));
1794 }
1795 }
1796 }
1797 public:
1798 ShenandoahObjectIterateParScanClosure(MarkBitMap* bitmap, ShenandoahObjToScanQueue* q) :
1799 _bitmap(bitmap), _queue(q), _heap(ShenandoahHeap::heap()),
1800 _marking_context(_heap->marking_context()) {}
1801 void do_oop(oop* p) { do_oop_work(p); }
1802 void do_oop(narrowOop* p) { do_oop_work(p); }
1803 };
1804
1805 // Object iterator for parallel heap iteraion.
1806 // The root scanning phase happenes in construction as a preparation of
1807 // parallel marking queues.
1808 // Every worker processes it's own marking queue. work-stealing is used
1809 // to balance workload.
1810 class ShenandoahParallelObjectIterator : public ParallelObjectIteratorImpl {
1811 private:
1812 uint _num_workers;
1813 bool _init_ready;
1814 MarkBitMap* _aux_bit_map;
1815 ShenandoahHeap* _heap;
1816 ShenandoahScanObjectStack _roots_stack; // global roots stack
1817 ShenandoahObjToScanQueueSet* _task_queues;
1818 public:
1819 ShenandoahParallelObjectIterator(uint num_workers, MarkBitMap* bitmap) :
1820 _num_workers(num_workers),
1821 _init_ready(false),
1822 _aux_bit_map(bitmap),
1823 _heap(ShenandoahHeap::heap()) {
1824 // Initialize bitmap
1825 _init_ready = _heap->prepare_aux_bitmap_for_iteration();
1826 if (!_init_ready) {
1827 return;
1828 }
1829
1830 ObjectIterateScanRootClosure oops(_aux_bit_map, &_roots_stack);
1831 _heap->scan_roots_for_iteration(&_roots_stack, &oops);
1832
1833 _init_ready = prepare_worker_queues();
1834 }
1835
1836 ~ShenandoahParallelObjectIterator() {
1837 // Reclaim bitmap
1838 _heap->reclaim_aux_bitmap_for_iteration();
1839 // Reclaim queue for workers
1840 if (_task_queues!= nullptr) {
1841 for (uint i = 0; i < _num_workers; ++i) {
1842 ShenandoahObjToScanQueue* q = _task_queues->queue(i);
1843 if (q != nullptr) {
1844 delete q;
1845 _task_queues->register_queue(i, nullptr);
1846 }
1847 }
1848 delete _task_queues;
1849 _task_queues = nullptr;
1850 }
1851 }
1852
1853 virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
1854 if (_init_ready) {
1855 object_iterate_parallel(cl, worker_id, _task_queues);
1856 }
1857 }
1858
1859 private:
1860 // Divide global root_stack into worker queues
1861 bool prepare_worker_queues() {
1862 _task_queues = new ShenandoahObjToScanQueueSet((int) _num_workers);
1863 // Initialize queues for every workers
1864 for (uint i = 0; i < _num_workers; ++i) {
1865 ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();
1866 _task_queues->register_queue(i, task_queue);
1867 }
1868 // Divide roots among the workers. Assume that object referencing distribution
1869 // is related with root kind, use round-robin to make every worker have same chance
1870 // to process every kind of roots
1871 size_t roots_num = _roots_stack.size();
1872 if (roots_num == 0) {
1873 // No work to do
1874 return false;
1875 }
1876
1877 for (uint j = 0; j < roots_num; j++) {
1878 uint stack_id = j % _num_workers;
1879 oop obj = _roots_stack.pop();
1880 _task_queues->queue(stack_id)->push(ShenandoahMarkTask(obj));
1881 }
1882 return true;
1883 }
1884
1885 void object_iterate_parallel(ObjectClosure* cl,
1886 uint worker_id,
1887 ShenandoahObjToScanQueueSet* queue_set) {
1888 assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1889 assert(queue_set != nullptr, "task queue must not be null");
1890
1891 ShenandoahObjToScanQueue* q = queue_set->queue(worker_id);
1892 assert(q != nullptr, "object iterate queue must not be null");
1893
1894 ShenandoahMarkTask t;
1895 ShenandoahObjectIterateParScanClosure oops(_aux_bit_map, q);
1896
1897 // Work through the queue to traverse heap.
1898 // Steal when there is no task in queue.
1899 while (q->pop(t) || queue_set->steal(worker_id, t)) {
1900 oop obj = t.obj();
1901 assert(oopDesc::is_oop(obj), "must be a valid oop");
1902 cl->do_object(obj);
1903 obj->oop_iterate(&oops);
1904 }
1905 assert(q->is_empty(), "should be empty");
1906 }
1907 };
1908
1909 ParallelObjectIteratorImpl* ShenandoahHeap::parallel_object_iterator(uint workers) {
1910 return new ShenandoahParallelObjectIterator(workers, &_aux_bit_map);
1911 }
1912
1913 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1914 void ShenandoahHeap::keep_alive(oop obj) {
1915 if (is_concurrent_mark_in_progress() && (obj != nullptr)) {
1916 ShenandoahBarrierSet::barrier_set()->enqueue(obj);
1917 }
1918 }
1919
1920 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1921 for (size_t i = 0; i < num_regions(); i++) {
1922 ShenandoahHeapRegion* current = get_region(i);
1923 blk->heap_region_do(current);
1924 }
1925 }
1926
1927 class ShenandoahParallelHeapRegionTask : public WorkerTask {
1928 private:
1929 ShenandoahHeap* const _heap;
1930 ShenandoahHeapRegionClosure* const _blk;
1931 size_t const _stride;
1932
1933 shenandoah_padding(0);
1934 volatile size_t _index;
1935 shenandoah_padding(1);
1936
1937 public:
1938 ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk, size_t stride) :
1939 WorkerTask("Shenandoah Parallel Region Operation"),
1940 _heap(ShenandoahHeap::heap()), _blk(blk), _stride(stride), _index(0) {}
1941
1942 void work(uint worker_id) {
1943 ShenandoahParallelWorkerSession worker_session(worker_id);
1944 size_t stride = _stride;
1945
1946 size_t max = _heap->num_regions();
1947 while (AtomicAccess::load(&_index) < max) {
1948 size_t cur = AtomicAccess::fetch_then_add(&_index, stride, memory_order_relaxed);
1949 size_t start = cur;
1950 size_t end = MIN2(cur + stride, max);
1951 if (start >= max) break;
1952
1953 for (size_t i = cur; i < end; i++) {
1954 ShenandoahHeapRegion* current = _heap->get_region(i);
1955 _blk->heap_region_do(current);
1956 }
1957 }
1958 }
1959 };
1960
1961 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1962 assert(blk->is_thread_safe(), "Only thread-safe closures here");
1963 const uint active_workers = workers()->active_workers();
1964 const size_t n_regions = num_regions();
1965 size_t stride = ShenandoahParallelRegionStride;
1966 if (stride == 0 && active_workers > 1) {
1967 // Automatically derive the stride to balance the work between threads
1968 // evenly. Do not try to split work if below the reasonable threshold.
1969 constexpr size_t threshold = 4096;
1970 stride = n_regions <= threshold ?
1971 threshold :
1972 (n_regions + active_workers - 1) / active_workers;
1973 }
1974
1975 if (n_regions > stride && active_workers > 1) {
1976 ShenandoahParallelHeapRegionTask task(blk, stride);
1977 workers()->run_task(&task);
1978 } else {
1979 heap_region_iterate(blk);
1980 }
1981 }
1982
1983 class ShenandoahRendezvousHandshakeClosure : public HandshakeClosure {
1984 public:
1985 inline ShenandoahRendezvousHandshakeClosure(const char* name) : HandshakeClosure(name) {}
1986 inline void do_thread(Thread* thread) {}
1987 };
1988
1989 void ShenandoahHeap::rendezvous_threads(const char* name) {
1990 ShenandoahRendezvousHandshakeClosure cl(name);
1991 Handshake::execute(&cl);
1992 }
1993
1994 void ShenandoahHeap::recycle_trash() {
1995 free_set()->recycle_trash();
1996 }
1997
1998 void ShenandoahHeap::do_class_unloading() {
1999 _unloader.unload();
2000 if (mode()->is_generational()) {
2001 old_generation()->set_parsable(false);
2002 }
2003 }
2004
2005 void ShenandoahHeap::stw_weak_refs(ShenandoahGeneration* generation, bool full_gc) {
2006 // Weak refs processing
2007 ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs
2008 : ShenandoahPhaseTimings::degen_gc_weakrefs;
2009 ShenandoahTimingsTracker t(phase);
2010 ShenandoahGCWorkerPhase worker_phase(phase);
2011 generation->ref_processor()->process_references(phase, workers(), false /* concurrent */);
2012 }
2013
2014 void ShenandoahHeap::prepare_update_heap_references() {
2015 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2016
2017 // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to
2018 // make them parsable for update code to work correctly. Plus, we can compute new sizes
2019 // for future GCLABs here.
2020 if (UseTLAB) {
2021 ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);
2022 gclabs_retire(ResizeTLAB);
2023 }
2024
2025 _update_refs_iterator.reset();
2026 }
2027
2028 void ShenandoahHeap::propagate_gc_state_to_all_threads() {
2029 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at Shenandoah safepoint");
2030 if (_gc_state_changed) {
2031 // If we are only marking old, we do not need to process young pointers
2032 ShenandoahBarrierSet::satb_mark_queue_set().set_filter_out_young(
2033 is_concurrent_old_mark_in_progress() && !is_concurrent_young_mark_in_progress()
2034 );
2035 ShenandoahGCStatePropagatorHandshakeClosure propagator(_gc_state.raw_value());
2036 Threads::threads_do(&propagator);
2037 _gc_state_changed = false;
2038 }
2039 }
2040
2041 void ShenandoahHeap::set_gc_state_at_safepoint(uint mask, bool value) {
2042 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at Shenandoah safepoint");
2043 _gc_state.set_cond(mask, value);
2044 _gc_state_changed = true;
2045 }
2046
2047 void ShenandoahHeap::set_gc_state_concurrent(uint mask, bool value) {
2048 // Holding the thread lock here assures that any thread created after we change the gc
2049 // state will have the correct state. It also prevents attaching threads from seeing
2050 // an inconsistent state. See ShenandoahBarrierSet::on_thread_attach for reference. Established
2051 // threads will use their thread local copy of the gc state (changed by a handshake, or on a
2052 // safepoint).
2053 assert(Threads_lock->is_locked(), "Must hold thread lock for concurrent gc state change");
2054 _gc_state.set_cond(mask, value);
2055 }
2056
2057 void ShenandoahHeap::set_concurrent_young_mark_in_progress(bool in_progress) {
2058 uint mask;
2059 assert(!has_forwarded_objects(), "Young marking is not concurrent with evacuation");
2060 if (!in_progress && is_concurrent_old_mark_in_progress()) {
2061 assert(mode()->is_generational(), "Only generational GC has old marking");
2062 assert(_gc_state.is_set(MARKING), "concurrent_old_marking_in_progress implies MARKING");
2063 // If old-marking is in progress when we turn off YOUNG_MARKING, leave MARKING (and OLD_MARKING) on
2064 mask = YOUNG_MARKING;
2065 } else {
2066 mask = MARKING | YOUNG_MARKING;
2067 }
2068 set_gc_state_at_safepoint(mask, in_progress);
2069 manage_satb_barrier(in_progress);
2070 }
2071
2072 void ShenandoahHeap::set_concurrent_old_mark_in_progress(bool in_progress) {
2073 #ifdef ASSERT
2074 // has_forwarded_objects() iff UPDATE_REFS or EVACUATION
2075 bool has_forwarded = has_forwarded_objects();
2076 bool updating_or_evacuating = _gc_state.is_set(UPDATE_REFS | EVACUATION);
2077 bool evacuating = _gc_state.is_set(EVACUATION);
2078 assert ((has_forwarded == updating_or_evacuating) || (evacuating && !has_forwarded && collection_set()->is_empty()),
2079 "Updating or evacuating iff has forwarded objects, or if evacuation phase is promoting in place without forwarding");
2080 #endif
2081 if (!in_progress && is_concurrent_young_mark_in_progress()) {
2082 // If young-marking is in progress when we turn off OLD_MARKING, leave MARKING (and YOUNG_MARKING) on
2083 assert(_gc_state.is_set(MARKING), "concurrent_young_marking_in_progress implies MARKING");
2084 set_gc_state_at_safepoint(OLD_MARKING, in_progress);
2085 } else {
2086 set_gc_state_at_safepoint(MARKING | OLD_MARKING, in_progress);
2087 }
2088 manage_satb_barrier(in_progress);
2089 }
2090
2091 bool ShenandoahHeap::is_prepare_for_old_mark_in_progress() const {
2092 return old_generation()->is_preparing_for_mark();
2093 }
2094
2095 void ShenandoahHeap::manage_satb_barrier(bool active) {
2096 if (is_concurrent_mark_in_progress()) {
2097 // Ignore request to deactivate barrier while concurrent mark is in progress.
2098 // Do not attempt to re-activate the barrier if it is already active.
2099 if (active && !ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2100 ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2101 }
2102 } else {
2103 // No concurrent marking is in progress so honor request to deactivate,
2104 // but only if the barrier is already active.
2105 if (!active && ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2106 ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2107 }
2108 }
2109 }
2110
2111 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
2112 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
2113 set_gc_state_at_safepoint(EVACUATION, in_progress);
2114 }
2115
2116 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {
2117 if (in_progress) {
2118 _concurrent_strong_root_in_progress.set();
2119 } else {
2120 _concurrent_strong_root_in_progress.unset();
2121 }
2122 }
2123
2124 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {
2125 set_gc_state_at_safepoint(WEAK_ROOTS, cond);
2126 }
2127
2128 GCTracer* ShenandoahHeap::tracer() {
2129 return shenandoah_policy()->tracer();
2130 }
2131
2132 size_t ShenandoahHeap::tlab_used() const {
2133 return _free_set->used();
2134 }
2135
2136 bool ShenandoahHeap::try_cancel_gc(GCCause::Cause cause) {
2137 const GCCause::Cause prev = _cancelled_gc.xchg(cause);
2138 return prev == GCCause::_no_gc || prev == GCCause::_shenandoah_concurrent_gc;
2139 }
2140
2141 void ShenandoahHeap::cancel_concurrent_mark() {
2142 if (mode()->is_generational()) {
2143 young_generation()->cancel_marking();
2144 old_generation()->cancel_marking();
2145 }
2146
2147 global_generation()->cancel_marking();
2148
2149 ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking();
2150 }
2151
2152 bool ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
2153 if (try_cancel_gc(cause)) {
2154 FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
2155 log_info(gc,thread)("%s", msg.buffer());
2156 Events::log(Thread::current(), "%s", msg.buffer());
2157 _cancel_requested_time = os::elapsedTime();
2158 return true;
2159 }
2160 return false;
2161 }
2162
2163 uint ShenandoahHeap::max_workers() {
2164 return _max_workers;
2165 }
2166
2167 void ShenandoahHeap::stop() {
2168 // The shutdown sequence should be able to terminate when GC is running.
2169
2170 // Step 0. Notify policy to disable event recording and prevent visiting gc threads during shutdown
2171 _shenandoah_policy->record_shutdown();
2172
2173 // Step 1. Stop reporting on gc thread cpu utilization
2174 mmu_tracker()->stop();
2175
2176 // Step 2. Wait until GC worker exits normally (this will cancel any ongoing GC).
2177 control_thread()->stop();
2178
2179 // Stop 4. Shutdown uncommit thread.
2180 if (_uncommit_thread != nullptr) {
2181 _uncommit_thread->stop();
2182 }
2183 }
2184
2185 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
2186 if (!unload_classes()) return;
2187 ClassUnloadingContext ctx(_workers->active_workers(),
2188 true /* unregister_nmethods_during_purge */,
2189 false /* lock_nmethod_free_separately */);
2190
2191 // Unload classes and purge SystemDictionary.
2192 {
2193 ShenandoahPhaseTimings::Phase phase = full_gc ?
2194 ShenandoahPhaseTimings::full_gc_purge_class_unload :
2195 ShenandoahPhaseTimings::degen_gc_purge_class_unload;
2196 ShenandoahIsAliveSelector is_alive;
2197 {
2198 CodeCache::UnlinkingScope scope(is_alive.is_alive_closure());
2199 ShenandoahGCPhase gc_phase(phase);
2200 ShenandoahGCWorkerPhase worker_phase(phase);
2201 bool unloading_occurred = SystemDictionary::do_unloading(gc_timer());
2202
2203 // Clean JVMCI metadata handles.
2204 JVMCI_ONLY(JVMCI::do_unloading(unloading_occurred));
2205
2206 ShenandoahClassUnloadingTask unlink_task(phase, unloading_occurred);
2207 _workers->run_task(&unlink_task);
2208 }
2209 // Release unloaded nmethods's memory.
2210 ClassUnloadingContext::context()->purge_and_free_nmethods();
2211 }
2212
2213 {
2214 ShenandoahGCPhase phase(full_gc ?
2215 ShenandoahPhaseTimings::full_gc_purge_cldg :
2216 ShenandoahPhaseTimings::degen_gc_purge_cldg);
2217 ClassLoaderDataGraph::purge(true /* at_safepoint */);
2218 }
2219 // Resize and verify metaspace
2220 MetaspaceGC::compute_new_size();
2221 DEBUG_ONLY(MetaspaceUtils::verify();)
2222 }
2223
2224 // Weak roots are either pre-evacuated (final mark) or updated (final update refs),
2225 // so they should not have forwarded oops.
2226 // However, we do need to "null" dead oops in the roots, if can not be done
2227 // in concurrent cycles.
2228 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
2229 uint num_workers = _workers->active_workers();
2230 ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
2231 ShenandoahPhaseTimings::full_gc_purge_weak_par :
2232 ShenandoahPhaseTimings::degen_gc_purge_weak_par;
2233 ShenandoahGCPhase phase(timing_phase);
2234 ShenandoahGCWorkerPhase worker_phase(timing_phase);
2235 // Cleanup weak roots
2236 if (has_forwarded_objects()) {
2237 ShenandoahForwardedIsAliveClosure is_alive;
2238 ShenandoahNonConcUpdateRefsClosure keep_alive;
2239 ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahNonConcUpdateRefsClosure>
2240 cleaning_task(timing_phase, &is_alive, &keep_alive, num_workers);
2241 _workers->run_task(&cleaning_task);
2242 } else {
2243 ShenandoahIsAliveClosure is_alive;
2244 #ifdef ASSERT
2245 ShenandoahAssertNotForwardedClosure verify_cl;
2246 ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
2247 cleaning_task(timing_phase, &is_alive, &verify_cl, num_workers);
2248 #else
2249 ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
2250 cleaning_task(timing_phase, &is_alive, &do_nothing_cl, num_workers);
2251 #endif
2252 _workers->run_task(&cleaning_task);
2253 }
2254 }
2255
2256 void ShenandoahHeap::parallel_cleaning(ShenandoahGeneration* generation, bool full_gc) {
2257 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2258 assert(is_stw_gc_in_progress(), "Only for Degenerated and Full GC");
2259 ShenandoahGCPhase phase(full_gc ?
2260 ShenandoahPhaseTimings::full_gc_purge :
2261 ShenandoahPhaseTimings::degen_gc_purge);
2262 stw_weak_refs(generation, full_gc);
2263 stw_process_weak_roots(full_gc);
2264 stw_unload_classes(full_gc);
2265 }
2266
2267 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2268 set_gc_state_at_safepoint(HAS_FORWARDED, cond);
2269 }
2270
2271 void ShenandoahHeap::set_unload_classes(bool uc) {
2272 _unload_classes.set_cond(uc);
2273 }
2274
2275 bool ShenandoahHeap::unload_classes() const {
2276 return _unload_classes.is_set();
2277 }
2278
2279 address ShenandoahHeap::in_cset_fast_test_addr() {
2280 ShenandoahHeap* heap = ShenandoahHeap::heap();
2281 assert(heap->collection_set() != nullptr, "Sanity");
2282 return (address) heap->collection_set()->biased_map_address();
2283 }
2284
2285 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2286 // It is important to force_alloc_rate_sample() before the associated generation's bytes_allocated has been reset.
2287 // Note that there is no lock to prevent additional alloations between sampling bytes_allocated_since_gc_start() and
2288 // reset_bytes_allocated_since_gc_start(). If additional allocations happen, they will be ignored in the average
2289 // allocation rate computations. This effect is considered to be be negligible.
2290
2291 // unaccounted_bytes is the bytes not accounted for by our forced sample. If the sample interval is too short,
2292 // the "forced sample" will not happen, and any recently allocated bytes are "unaccounted for". We pretend these
2293 // bytes are allocated after the start of subsequent gc.
2294 size_t unaccounted_bytes;
2295 ShenandoahFreeSet* _free_set = free_set();
2296 size_t bytes_allocated = _free_set->get_bytes_allocated_since_gc_start();
2297 if (mode()->is_generational()) {
2298 unaccounted_bytes = young_generation()->heuristics()->force_alloc_rate_sample(bytes_allocated);
2299 } else {
2300 // Single-gen Shenandoah uses global heuristics.
2301 unaccounted_bytes = heuristics()->force_alloc_rate_sample(bytes_allocated);
2302 }
2303 ShenandoahHeapLocker locker(lock());
2304 _free_set->reset_bytes_allocated_since_gc_start(unaccounted_bytes);
2305 }
2306
2307 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2308 _degenerated_gc_in_progress.set_cond(in_progress);
2309 }
2310
2311 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2312 _full_gc_in_progress.set_cond(in_progress);
2313 }
2314
2315 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2316 assert (is_full_gc_in_progress(), "should be");
2317 _full_gc_move_in_progress.set_cond(in_progress);
2318 }
2319
2320 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2321 set_gc_state_at_safepoint(UPDATE_REFS, in_progress);
2322 }
2323
2324 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2325 ShenandoahCodeRoots::register_nmethod(nm);
2326 }
2327
2328 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2329 ShenandoahCodeRoots::unregister_nmethod(nm);
2330 }
2331
2332 void ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2333 heap_region_containing(o)->record_pin();
2334 }
2335
2336 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2337 ShenandoahHeapRegion* r = heap_region_containing(o);
2338 assert(r != nullptr, "Sanity");
2339 assert(r->pin_count() > 0, "Region %zu should have non-zero pins", r->index());
2340 r->record_unpin();
2341 }
2342
2343 void ShenandoahHeap::sync_pinned_region_status() {
2344 ShenandoahHeapLocker locker(lock());
2345
2346 for (size_t i = 0; i < num_regions(); i++) {
2347 ShenandoahHeapRegion *r = get_region(i);
2348 if (r->is_active()) {
2349 if (r->is_pinned()) {
2350 if (r->pin_count() == 0) {
2351 r->make_unpinned();
2352 }
2353 } else {
2354 if (r->pin_count() > 0) {
2355 r->make_pinned();
2356 }
2357 }
2358 }
2359 }
2360
2361 assert_pinned_region_status();
2362 }
2363
2364 #ifdef ASSERT
2365 void ShenandoahHeap::assert_pinned_region_status() const {
2366 assert_pinned_region_status(global_generation());
2367 }
2368
2369 void ShenandoahHeap::assert_pinned_region_status(ShenandoahGeneration* generation) const {
2370 for (size_t i = 0; i < num_regions(); i++) {
2371 ShenandoahHeapRegion* r = get_region(i);
2372 if (generation->contains(r)) {
2373 assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
2374 "Region %zu pinning status is inconsistent", i);
2375 }
2376 }
2377 }
2378 #endif
2379
2380 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {
2381 return _gc_timer;
2382 }
2383
2384 void ShenandoahHeap::prepare_concurrent_roots() {
2385 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2386 assert(!is_stw_gc_in_progress(), "Only concurrent GC");
2387 set_concurrent_strong_root_in_progress(!collection_set()->is_empty());
2388 set_concurrent_weak_root_in_progress(true);
2389 if (unload_classes()) {
2390 _unloader.prepare();
2391 }
2392 }
2393
2394 void ShenandoahHeap::finish_concurrent_roots() {
2395 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2396 assert(!is_stw_gc_in_progress(), "Only concurrent GC");
2397 if (unload_classes()) {
2398 _unloader.finish();
2399 }
2400 }
2401
2402 #ifdef ASSERT
2403 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2404 assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2405
2406 if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2407 // Use ParallelGCThreads inside safepoints
2408 assert(nworkers == ParallelGCThreads, "Use ParallelGCThreads (%u) within safepoint, not %u",
2409 ParallelGCThreads, nworkers);
2410 } else {
2411 // Use ConcGCThreads outside safepoints
2412 assert(nworkers == ConcGCThreads, "Use ConcGCThreads (%u) outside safepoints, %u",
2413 ConcGCThreads, nworkers);
2414 }
2415 }
2416 #endif
2417
2418 ShenandoahVerifier* ShenandoahHeap::verifier() {
2419 guarantee(ShenandoahVerify, "Should be enabled");
2420 assert (_verifier != nullptr, "sanity");
2421 return _verifier;
2422 }
2423
2424 template<bool CONCURRENT>
2425 class ShenandoahUpdateHeapRefsTask : public WorkerTask {
2426 private:
2427 ShenandoahHeap* _heap;
2428 ShenandoahRegionIterator* _regions;
2429 public:
2430 explicit ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :
2431 WorkerTask("Shenandoah Update References"),
2432 _heap(ShenandoahHeap::heap()),
2433 _regions(regions) {
2434 }
2435
2436 void work(uint worker_id) {
2437 if (CONCURRENT) {
2438 ShenandoahConcurrentWorkerSession worker_session(worker_id);
2439 ShenandoahSuspendibleThreadSetJoiner stsj;
2440 do_work<ShenandoahConcUpdateRefsClosure>(worker_id);
2441 } else {
2442 ShenandoahParallelWorkerSession worker_session(worker_id);
2443 do_work<ShenandoahNonConcUpdateRefsClosure>(worker_id);
2444 }
2445 }
2446
2447 private:
2448 template<class T>
2449 void do_work(uint worker_id) {
2450 if (CONCURRENT && (worker_id == 0)) {
2451 // We ask the first worker to replenish the Mutator free set by moving regions previously reserved to hold the
2452 // results of evacuation. These reserves are no longer necessary because evacuation has completed.
2453 size_t cset_regions = _heap->collection_set()->count();
2454
2455 // Now that evacuation is done, we can reassign any regions that had been reserved to hold the results of evacuation
2456 // to the mutator free set. At the end of GC, we will have cset_regions newly evacuated fully empty regions from
2457 // which we will be able to replenish the Collector free set and the OldCollector free set in preparation for the
2458 // next GC cycle.
2459 _heap->free_set()->move_regions_from_collector_to_mutator(cset_regions);
2460 }
2461 // If !CONCURRENT, there's no value in expanding Mutator free set
2462 T cl;
2463 ShenandoahHeapRegion* r = _regions->next();
2464 while (r != nullptr) {
2465 HeapWord* update_watermark = r->get_update_watermark();
2466 assert (update_watermark >= r->bottom(), "sanity");
2467 if (r->is_active() && !r->is_cset()) {
2468 _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2469 }
2470 if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
2471 return;
2472 }
2473 r = _regions->next();
2474 }
2475 }
2476 };
2477
2478 void ShenandoahHeap::update_heap_references(ShenandoahGeneration* generation, bool concurrent) {
2479 assert(generation->is_global(), "Should only get global generation here");
2480 assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2481
2482 if (concurrent) {
2483 ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);
2484 workers()->run_task(&task);
2485 } else {
2486 ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);
2487 workers()->run_task(&task);
2488 }
2489 }
2490
2491 void ShenandoahHeap::update_heap_region_states(bool concurrent) {
2492 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2493 assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2494
2495 {
2496 ShenandoahGCPhase phase(concurrent ?
2497 ShenandoahPhaseTimings::final_update_refs_update_region_states :
2498 ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);
2499
2500 final_update_refs_update_region_states();
2501
2502 assert_pinned_region_status();
2503 }
2504
2505 {
2506 ShenandoahGCPhase phase(concurrent ?
2507 ShenandoahPhaseTimings::final_update_refs_trash_cset :
2508 ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);
2509 trash_cset_regions();
2510 }
2511 }
2512
2513 void ShenandoahHeap::final_update_refs_update_region_states() {
2514 ShenandoahSynchronizePinnedRegionStates cl;
2515 parallel_heap_region_iterate(&cl);
2516 }
2517
2518 void ShenandoahHeap::rebuild_free_set(bool concurrent) {
2519 ShenandoahGCPhase phase(concurrent ?
2520 ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :
2521 ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);
2522 ShenandoahHeapLocker locker(lock());
2523 size_t young_cset_regions, old_cset_regions;
2524 size_t first_old_region, last_old_region, old_region_count;
2525 _free_set->prepare_to_rebuild(young_cset_regions, old_cset_regions, first_old_region, last_old_region, old_region_count);
2526 // If there are no old regions, first_old_region will be greater than last_old_region
2527 assert((first_old_region > last_old_region) ||
2528 ((last_old_region + 1 - first_old_region >= old_region_count) &&
2529 get_region(first_old_region)->is_old() && get_region(last_old_region)->is_old()),
2530 "sanity: old_region_count: %zu, first_old_region: %zu, last_old_region: %zu",
2531 old_region_count, first_old_region, last_old_region);
2532
2533 if (mode()->is_generational()) {
2534 #ifdef ASSERT
2535 if (ShenandoahVerify) {
2536 verifier()->verify_before_rebuilding_free_set();
2537 }
2538 #endif
2539
2540 // The computation of bytes_of_allocation_runway_before_gc_trigger is quite conservative so consider all of this
2541 // available for transfer to old. Note that transfer of humongous regions does not impact available.
2542 ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap();
2543 size_t allocation_runway = gen_heap->young_generation()->heuristics()->bytes_of_allocation_runway_before_gc_trigger(young_cset_regions);
2544 gen_heap->compute_old_generation_balance(allocation_runway, old_cset_regions);
2545
2546 // Total old_available may have been expanded to hold anticipated promotions. We trigger if the fragmented available
2547 // memory represents more than 16 regions worth of data. Note that fragmentation may increase when we promote regular
2548 // regions in place when many of these regular regions have an abundant amount of available memory within them. Fragmentation
2549 // will decrease as promote-by-copy consumes the available memory within these partially consumed regions.
2550 //
2551 // We consider old-gen to have excessive fragmentation if more than 12.5% of old-gen is free memory that resides
2552 // within partially consumed regions of memory.
2553 }
2554 // Rebuild free set based on adjusted generation sizes.
2555 _free_set->finish_rebuild(young_cset_regions, old_cset_regions, old_region_count);
2556
2557 if (mode()->is_generational()) {
2558 ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap();
2559 ShenandoahOldGeneration* old_gen = gen_heap->old_generation();
2560 old_gen->heuristics()->evaluate_triggers(first_old_region, last_old_region, old_region_count, num_regions());
2561 }
2562 }
2563
2564 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2565 size_t slice = r->index() / _bitmap_regions_per_slice;
2566
2567 size_t regions_from = _bitmap_regions_per_slice * slice;
2568 size_t regions_to = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2569 for (size_t g = regions_from; g < regions_to; g++) {
2570 assert (g / _bitmap_regions_per_slice == slice, "same slice");
2571 if (skip_self && g == r->index()) continue;
2572 if (get_region(g)->is_committed()) {
2573 return true;
2574 }
2575 }
2576 return false;
2577 }
2578
2579 void ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2580 shenandoah_assert_heaplocked();
2581 assert(!is_bitmap_region_special(), "Not for special memory");
2582
2583 if (is_bitmap_slice_committed(r, true)) {
2584 // Some other region from the group is already committed, meaning the bitmap
2585 // slice is already committed, we exit right away.
2586 return;
2587 }
2588
2589 // Commit the bitmap slice:
2590 size_t slice = r->index() / _bitmap_regions_per_slice;
2591 size_t off = _bitmap_bytes_per_slice * slice;
2592 size_t len = _bitmap_bytes_per_slice;
2593 char* start = (char*) _bitmap_region.start() + off;
2594
2595 os::commit_memory_or_exit(start, len, false, "Unable to commit bitmap slice");
2596
2597 if (AlwaysPreTouch) {
2598 os::pretouch_memory(start, start + len, _pretouch_bitmap_page_size);
2599 }
2600 }
2601
2602 void ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2603 shenandoah_assert_heaplocked();
2604 assert(!is_bitmap_region_special(), "Not for special memory");
2605
2606 if (is_bitmap_slice_committed(r, true)) {
2607 // Some other region from the group is still committed, meaning the bitmap
2608 // slice should stay committed, exit right away.
2609 return;
2610 }
2611
2612 // Uncommit the bitmap slice:
2613 size_t slice = r->index() / _bitmap_regions_per_slice;
2614 size_t off = _bitmap_bytes_per_slice * slice;
2615 size_t len = _bitmap_bytes_per_slice;
2616
2617 char* addr = (char*) _bitmap_region.start() + off;
2618 bool success = os::uncommit_memory(addr, len);
2619 if (!success) {
2620 log_warning(gc)("Bitmap slice uncommit failed: " PTR_FORMAT " (%zu bytes)", p2i(addr), len);
2621 assert(false, "Bitmap slice uncommit should always succeed");
2622 }
2623 }
2624
2625 void ShenandoahHeap::forbid_uncommit() {
2626 if (_uncommit_thread != nullptr) {
2627 _uncommit_thread->forbid_uncommit();
2628 }
2629 }
2630
2631 void ShenandoahHeap::allow_uncommit() {
2632 if (_uncommit_thread != nullptr) {
2633 _uncommit_thread->allow_uncommit();
2634 }
2635 }
2636
2637 #ifdef ASSERT
2638 bool ShenandoahHeap::is_uncommit_in_progress() {
2639 if (_uncommit_thread != nullptr) {
2640 return _uncommit_thread->is_uncommit_in_progress();
2641 }
2642 return false;
2643 }
2644 #endif
2645
2646 void ShenandoahHeap::safepoint_synchronize_begin() {
2647 StackWatermarkSet::safepoint_synchronize_begin();
2648 SuspendibleThreadSet::synchronize();
2649 }
2650
2651 void ShenandoahHeap::safepoint_synchronize_end() {
2652 SuspendibleThreadSet::desynchronize();
2653 }
2654
2655 void ShenandoahHeap::try_inject_alloc_failure() {
2656 if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2657 _inject_alloc_failure.set();
2658 os::naked_short_sleep(1);
2659 if (cancelled_gc()) {
2660 log_info(gc)("Allocation failure was successfully injected");
2661 }
2662 }
2663 }
2664
2665 bool ShenandoahHeap::should_inject_alloc_failure() {
2666 return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2667 }
2668
2669 void ShenandoahHeap::initialize_serviceability() {
2670 _memory_pool = new ShenandoahMemoryPool(this);
2671 _cycle_memory_manager.add_pool(_memory_pool);
2672 _stw_memory_manager.add_pool(_memory_pool);
2673 }
2674
2675 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2676 GrowableArray<GCMemoryManager*> memory_managers(2);
2677 memory_managers.append(&_cycle_memory_manager);
2678 memory_managers.append(&_stw_memory_manager);
2679 return memory_managers;
2680 }
2681
2682 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2683 GrowableArray<MemoryPool*> memory_pools(1);
2684 memory_pools.append(_memory_pool);
2685 return memory_pools;
2686 }
2687
2688 MemoryUsage ShenandoahHeap::memory_usage() {
2689 assert(_initial_size <= ShenandoahHeap::heap()->max_capacity(), "sanity");
2690 assert(used() <= ShenandoahHeap::heap()->max_capacity(), "sanity");
2691 assert(committed() <= ShenandoahHeap::heap()->max_capacity(), "sanity");
2692 return MemoryUsage(_initial_size, used(), committed(), max_capacity());
2693 }
2694
2695 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2696 _heap(ShenandoahHeap::heap()),
2697 _index(0) {}
2698
2699 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2700 _heap(heap),
2701 _index(0) {}
2702
2703 void ShenandoahRegionIterator::reset() {
2704 _index = 0;
2705 }
2706
2707 bool ShenandoahRegionIterator::has_next() const {
2708 return _index < _heap->num_regions();
2709 }
2710
2711 char ShenandoahHeap::gc_state() const {
2712 return _gc_state.raw_value();
2713 }
2714
2715 bool ShenandoahHeap::is_gc_state(GCState state) const {
2716 // If the global gc state has been changed, but hasn't yet been propagated to all threads, then
2717 // the global gc state is the correct value. Once the gc state has been synchronized with all threads,
2718 // _gc_state_changed will be toggled to false and we need to use the thread local state.
2719 return _gc_state_changed ? _gc_state.is_set(state) : ShenandoahThreadLocalData::is_gc_state(state);
2720 }
2721
2722
2723 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2724 #ifdef ASSERT
2725 assert(_liveness_cache != nullptr, "sanity");
2726 assert(worker_id < _max_workers, "sanity");
2727 for (uint i = 0; i < num_regions(); i++) {
2728 assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2729 }
2730 #endif
2731 return _liveness_cache[worker_id];
2732 }
2733
2734 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2735 assert(worker_id < _max_workers, "sanity");
2736 assert(_liveness_cache != nullptr, "sanity");
2737 ShenandoahLiveData* ld = _liveness_cache[worker_id];
2738 for (uint i = 0; i < num_regions(); i++) {
2739 ShenandoahLiveData live = ld[i];
2740 if (live > 0) {
2741 ShenandoahHeapRegion* r = get_region(i);
2742 r->increase_live_data_gc_words(live);
2743 ld[i] = 0;
2744 }
2745 }
2746 }
2747
2748 bool ShenandoahHeap::requires_barriers(stackChunkOop obj) const {
2749 if (is_idle()) return false;
2750
2751 // Objects allocated after marking start are implicitly alive, don't need any barriers during
2752 // marking phase.
2753 if (is_concurrent_mark_in_progress() &&
2754 !marking_context()->allocated_after_mark_start(obj)) {
2755 return true;
2756 }
2757
2758 // Can not guarantee obj is deeply good.
2759 if (has_forwarded_objects()) {
2760 return true;
2761 }
2762
2763 return false;
2764 }
2765
2766 HeapWord* ShenandoahHeap::allocate_loaded_archive_space(size_t size) {
2767 #if INCLUDE_CDS_JAVA_HEAP
2768 // CDS wants a raw continuous memory range to load a bunch of objects itself.
2769 // This is an unusual request, since all requested regions should be regular, not humongous.
2770 //
2771 // CDS would guarantee no objects straddle multiple regions, as long as regions are as large
2772 // as MIN_GC_REGION_ALIGNMENT.
2773 guarantee(ShenandoahHeapRegion::region_size_bytes() >= AOTMappedHeapWriter::MIN_GC_REGION_ALIGNMENT, "Must be");
2774
2775 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_cds(size);
2776 return allocate_memory(req);
2777 #else
2778 assert(false, "Archive heap loader should not be available, should not be here");
2779 return nullptr;
2780 #endif // INCLUDE_CDS_JAVA_HEAP
2781 }
2782
2783 void ShenandoahHeap::complete_loaded_archive_space(MemRegion archive_space) {
2784 // Nothing to do here, except checking that heap looks fine.
2785 #ifdef ASSERT
2786 HeapWord* start = archive_space.start();
2787 HeapWord* end = archive_space.end();
2788
2789 // No unclaimed space between the objects.
2790 // Objects are properly allocated in correct regions.
2791 HeapWord* cur = start;
2792 while (cur < end) {
2793 oop oop = cast_to_oop(cur);
2794 shenandoah_assert_in_correct_region(nullptr, oop);
2795 cur += oop->size();
2796 }
2797
2798 // No unclaimed tail at the end of archive space.
2799 assert(cur == end,
2800 "Archive space should be fully used: " PTR_FORMAT " " PTR_FORMAT,
2801 p2i(cur), p2i(end));
2802
2803 // All regions in contiguous space have good state.
2804 size_t begin_reg_idx = heap_region_index_containing(start);
2805 size_t end_reg_idx = heap_region_index_containing(end);
2806
2807 for (size_t idx = begin_reg_idx; idx <= end_reg_idx; idx++) {
2808 ShenandoahHeapRegion* r = get_region(idx);
2809 assert(r->is_regular(), "Must be regular");
2810 assert(r->is_young(), "Must be young");
2811 assert(idx == end_reg_idx || r->top() == r->end(),
2812 "All regions except the last one should be full: " PTR_FORMAT " " PTR_FORMAT,
2813 p2i(r->top()), p2i(r->end()));
2814 assert(idx != begin_reg_idx || r->bottom() == start,
2815 "Archive space start should be at the bottom of first region: " PTR_FORMAT " " PTR_FORMAT,
2816 p2i(r->bottom()), p2i(start));
2817 assert(idx != end_reg_idx || r->top() == end,
2818 "Archive space end should be at the top of last region: " PTR_FORMAT " " PTR_FORMAT,
2819 p2i(r->top()), p2i(end));
2820 }
2821
2822 #endif
2823 }
2824
2825 ShenandoahGeneration* ShenandoahHeap::generation_for(ShenandoahAffiliation affiliation) const {
2826 if (!mode()->is_generational()) {
2827 return global_generation();
2828 } else if (affiliation == YOUNG_GENERATION) {
2829 return young_generation();
2830 } else if (affiliation == OLD_GENERATION) {
2831 return old_generation();
2832 }
2833
2834 ShouldNotReachHere();
2835 return nullptr;
2836 }
2837
2838 void ShenandoahHeap::log_heap_status(const char* msg) const {
2839 if (mode()->is_generational()) {
2840 young_generation()->log_status(msg);
2841 old_generation()->log_status(msg);
2842 } else {
2843 global_generation()->log_status(msg);
2844 }
2845 }