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