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