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