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