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