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