1 /*
2  * Copyright (c) 2013, 2019, Red Hat, Inc. All rights reserved.
3  *
4  * This code is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 only, as
6  * published by the Free Software Foundation.
7  *
8  * This code is distributed in the hope that it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11  * version 2 for more details (a copy is included in the LICENSE file that
12  * accompanied this code).
13  *
14  * You should have received a copy of the GNU General Public License version
15  * 2 along with this work; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
17  *
18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
19  * or visit www.oracle.com if you need additional information or have any
20  * questions.
21  *
22  */
23 
24 #include "precompiled.hpp"
25 #include "memory/allocation.hpp"
26 
27 #include "gc/shared/gcTimer.hpp"
28 #include "gc/shared/gcTraceTime.inline.hpp"
29 #include "gc/shared/memAllocator.hpp"
30 #include "gc/shared/parallelCleaning.hpp"
31 #include "gc/shared/plab.hpp"
32 
33 #include "gc/shenandoah/shenandoahAllocTracker.hpp"
34 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
35 #include "gc/shenandoah/shenandoahBrooksPointer.hpp"
36 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
37 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
38 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
39 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
40 #include "gc/shenandoah/shenandoahControlThread.hpp"
41 #include "gc/shenandoah/shenandoahFreeSet.hpp"
42 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
43 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
44 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
45 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
46 #include "gc/shenandoah/shenandoahMarkCompact.hpp"
47 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
48 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
49 #include "gc/shenandoah/shenandoahMetrics.hpp"
50 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
51 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
52 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
53 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
54 #include "gc/shenandoah/shenandoahStringDedup.hpp"
55 #include "gc/shenandoah/shenandoahTaskqueue.hpp"
56 #include "gc/shenandoah/shenandoahUtils.hpp"
57 #include "gc/shenandoah/shenandoahVerifier.hpp"
58 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
59 #include "gc/shenandoah/shenandoahVMOperations.hpp"
60 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
61 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
62 #include "gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.hpp"
63 #include "gc/shenandoah/heuristics/shenandoahAggressiveHeuristics.hpp"
64 #include "gc/shenandoah/heuristics/shenandoahCompactHeuristics.hpp"
65 #include "gc/shenandoah/heuristics/shenandoahPassiveHeuristics.hpp"
66 #include "gc/shenandoah/heuristics/shenandoahStaticHeuristics.hpp"
67 #include "gc/shenandoah/heuristics/shenandoahTraversalHeuristics.hpp"
68 
69 #include "memory/metaspace.hpp"
70 #include "runtime/vmThread.hpp"
71 #include "services/mallocTracker.hpp"
72 
73 #ifdef ASSERT
74 template <class T>
do_oop_work(T * p)75 void ShenandoahAssertToSpaceClosure::do_oop_work(T* p) {
76   T o = RawAccess<>::oop_load(p);
77   if (! CompressedOops::is_null(o)) {
78     oop obj = CompressedOops::decode_not_null(o);
79     shenandoah_assert_not_forwarded(p, obj);
80   }
81 }
82 
do_oop(narrowOop * p)83 void ShenandoahAssertToSpaceClosure::do_oop(narrowOop* p) { do_oop_work(p); }
do_oop(oop * p)84 void ShenandoahAssertToSpaceClosure::do_oop(oop* p)       { do_oop_work(p); }
85 #endif
86 
87 class ShenandoahPretouchHeapTask : public AbstractGangTask {
88 private:
89   ShenandoahRegionIterator _regions;
90   const size_t _page_size;
91 public:
ShenandoahPretouchHeapTask(size_t page_size)92   ShenandoahPretouchHeapTask(size_t page_size) :
93     AbstractGangTask("Shenandoah Pretouch Heap"),
94     _page_size(page_size) {}
95 
work(uint worker_id)96   virtual void work(uint worker_id) {
97     ShenandoahHeapRegion* r = _regions.next();
98     while (r != NULL) {
99       os::pretouch_memory(r->bottom(), r->end(), _page_size);
100       r = _regions.next();
101     }
102   }
103 };
104 
105 class ShenandoahPretouchBitmapTask : public AbstractGangTask {
106 private:
107   ShenandoahRegionIterator _regions;
108   char* _bitmap_base;
109   const size_t _bitmap_size;
110   const size_t _page_size;
111 public:
ShenandoahPretouchBitmapTask(char * bitmap_base,size_t bitmap_size,size_t page_size)112   ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
113     AbstractGangTask("Shenandoah Pretouch Bitmap"),
114     _bitmap_base(bitmap_base),
115     _bitmap_size(bitmap_size),
116     _page_size(page_size) {}
117 
work(uint worker_id)118   virtual void work(uint worker_id) {
119     ShenandoahHeapRegion* r = _regions.next();
120     while (r != NULL) {
121       size_t start = r->region_number()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
122       size_t end   = (r->region_number() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
123       assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);
124 
125       os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
126 
127       r = _regions.next();
128     }
129   }
130 };
131 
initialize()132 jint ShenandoahHeap::initialize() {
133   ShenandoahBrooksPointer::initial_checks();
134 
135   initialize_heuristics();
136 
137   //
138   // Figure out heap sizing
139   //
140 
141   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
142   size_t min_byte_size  = collector_policy()->min_heap_byte_size();
143   size_t max_byte_size  = collector_policy()->max_heap_byte_size();
144   size_t heap_alignment = collector_policy()->heap_alignment();
145 
146   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
147 
148   if (ShenandoahAlwaysPreTouch) {
149     // Enabled pre-touch means the entire heap is committed right away.
150     init_byte_size = max_byte_size;
151   }
152 
153   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
154   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
155 
156   _num_regions = ShenandoahHeapRegion::region_count();
157 
158   size_t num_committed_regions = init_byte_size / reg_size_bytes;
159   num_committed_regions = MIN2(num_committed_regions, _num_regions);
160   assert(num_committed_regions <= _num_regions, "sanity");
161   _initial_size = num_committed_regions * reg_size_bytes;
162 
163   size_t num_min_regions = min_byte_size / reg_size_bytes;
164   num_min_regions = MIN2(num_min_regions, _num_regions);
165   assert(num_min_regions <= _num_regions, "sanity");
166   _minimum_size = num_min_regions * reg_size_bytes;
167 
168   _committed = _initial_size;
169 
170   size_t heap_page_size   = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
171   size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
172 
173   //
174   // Reserve and commit memory for heap
175   //
176 
177   ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
178   initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*) (heap_rs.base() + heap_rs.size()));
179   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
180   _heap_region_special = heap_rs.special();
181 
182   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
183          "Misaligned heap: " PTR_FORMAT, p2i(base()));
184 
185 #if SHENANDOAH_OPTIMIZED_OBJTASK
186   // The optimized ObjArrayChunkedTask takes some bits away from the full object bits.
187   // Fail if we ever attempt to address more than we can.
188   if ((uintptr_t)heap_rs.end() >= ObjArrayChunkedTask::max_addressable()) {
189     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
190                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
191                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
192                 p2i(heap_rs.base()), p2i(heap_rs.end()), ObjArrayChunkedTask::max_addressable());
193     vm_exit_during_initialization("Fatal Error", buf);
194   }
195 #endif
196 
197   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
198   if (!_heap_region_special) {
199     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
200                               "Cannot commit heap memory");
201   }
202 
203   //
204   // Reserve and commit memory for bitmap(s)
205   //
206 
207   _bitmap_size = MarkBitMap::compute_size(heap_rs.size());
208   _bitmap_size = align_up(_bitmap_size, bitmap_page_size);
209 
210   size_t bitmap_bytes_per_region = reg_size_bytes / MarkBitMap::heap_map_factor();
211 
212   guarantee(bitmap_bytes_per_region != 0,
213             "Bitmap bytes per region should not be zero");
214   guarantee(is_power_of_2(bitmap_bytes_per_region),
215             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
216 
217   if (bitmap_page_size > bitmap_bytes_per_region) {
218     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
219     _bitmap_bytes_per_slice = bitmap_page_size;
220   } else {
221     _bitmap_regions_per_slice = 1;
222     _bitmap_bytes_per_slice = bitmap_bytes_per_region;
223   }
224 
225   guarantee(_bitmap_regions_per_slice >= 1,
226             "Should have at least one region per slice: " SIZE_FORMAT,
227             _bitmap_regions_per_slice);
228 
229   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
230             "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
231             _bitmap_bytes_per_slice, bitmap_page_size);
232 
233   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
234   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
235   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
236   _bitmap_region_special = bitmap.special();
237 
238   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
239                               align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
240   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
241   if (!_bitmap_region_special) {
242     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
243                               "Cannot commit bitmap memory");
244   }
245 
246   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
247 
248   if (ShenandoahVerify) {
249     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
250     if (!verify_bitmap.special()) {
251       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
252                                 "Cannot commit verification bitmap memory");
253     }
254     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
255     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
256     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
257     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
258   }
259 
260   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
261   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
262   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
263   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
264   _aux_bitmap_region_special = aux_bitmap.special();
265   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
266 
267   //
268   // Create regions and region sets
269   //
270 
271   _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
272   _free_set = new ShenandoahFreeSet(this, _num_regions);
273   _collection_set = new ShenandoahCollectionSet(this, sh_rs.base(), sh_rs.size());
274 
275   {
276     ShenandoahHeapLocker locker(lock());
277 
278     size_t size_words = ShenandoahHeapRegion::region_size_words();
279 
280     for (size_t i = 0; i < _num_regions; i++) {
281       HeapWord* start = (HeapWord*)sh_rs.base() + size_words * i;
282       bool is_committed = i < num_committed_regions;
283       ShenandoahHeapRegion* r = new ShenandoahHeapRegion(this, start, size_words, i, is_committed);
284 
285       _marking_context->initialize_top_at_mark_start(r);
286       _regions[i] = r;
287       assert(!collection_set()->is_in(i), "New region should not be in collection set");
288     }
289 
290     // Initialize to complete
291     _marking_context->mark_complete();
292 
293     _free_set->rebuild();
294   }
295 
296   if (ShenandoahAlwaysPreTouch) {
297     assert(!AlwaysPreTouch, "Should have been overridden");
298 
299     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
300     // before initialize() below zeroes it with initializing thread. For any given region,
301     // we touch the region and the corresponding bitmaps from the same thread.
302     ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
303 
304     size_t pretouch_heap_page_size = heap_page_size;
305     size_t pretouch_bitmap_page_size = bitmap_page_size;
306 
307 #ifdef LINUX
308     // UseTransparentHugePages would madvise that backing memory can be coalesced into huge
309     // pages. But, the kernel needs to know that every small page is used, in order to coalesce
310     // them into huge one. Therefore, we need to pretouch with smaller pages.
311     if (UseTransparentHugePages) {
312       pretouch_heap_page_size = (size_t)os::vm_page_size();
313       pretouch_bitmap_page_size = (size_t)os::vm_page_size();
314     }
315 #endif
316 
317     // OS memory managers may want to coalesce back-to-back pages. Make their jobs
318     // simpler by pre-touching continuous spaces (heap and bitmap) separately.
319 
320     log_info(gc, init)("Pretouch bitmap: " SIZE_FORMAT " regions, " SIZE_FORMAT " bytes page",
321                        _num_regions, pretouch_bitmap_page_size);
322     ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, pretouch_bitmap_page_size);
323     _workers->run_task(&bcl);
324 
325     log_info(gc, init)("Pretouch heap: " SIZE_FORMAT " regions, " SIZE_FORMAT " bytes page",
326                        _num_regions, pretouch_heap_page_size);
327     ShenandoahPretouchHeapTask hcl(pretouch_heap_page_size);
328     _workers->run_task(&hcl);
329   }
330 
331   //
332   // Initialize the rest of GC subsystems
333   //
334 
335   _liveness_cache = NEW_C_HEAP_ARRAY(jushort*, _max_workers, mtGC);
336   for (uint worker = 0; worker < _max_workers; worker++) {
337     _liveness_cache[worker] = NEW_C_HEAP_ARRAY(jushort, _num_regions, mtGC);
338     Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(jushort));
339   }
340 
341   // The call below uses stuff (the SATB* things) that are in G1, but probably
342   // belong into a shared location.
343   ShenandoahBarrierSet::satb_mark_queue_set().initialize(this,
344                                                          SATB_Q_CBL_mon,
345                                                          20 /*G1SATBProcessCompletedThreshold */,
346                                                          60 /* G1SATBBufferEnqueueingThresholdPercent */,
347                                                          Shared_SATB_Q_lock);
348 
349   _monitoring_support = new ShenandoahMonitoringSupport(this);
350   _phase_timings = new ShenandoahPhaseTimings();
351   ShenandoahStringDedup::initialize();
352   ShenandoahCodeRoots::initialize();
353 
354   if (ShenandoahAllocationTrace) {
355     _alloc_tracker = new ShenandoahAllocTracker();
356   }
357 
358   if (ShenandoahPacing) {
359     _pacer = new ShenandoahPacer(this);
360     _pacer->setup_for_idle();
361   } else {
362     _pacer = NULL;
363   }
364 
365   _traversal_gc = heuristics()->can_do_traversal_gc() ?
366                   new ShenandoahTraversalGC(this, _num_regions) :
367                   NULL;
368 
369   _control_thread = new ShenandoahControlThread();
370 
371   log_info(gc, init)("Initialize Shenandoah heap: " SIZE_FORMAT "%s initial, " SIZE_FORMAT "%s min, " SIZE_FORMAT "%s max",
372                      byte_size_in_proper_unit(_initial_size),  proper_unit_for_byte_size(_initial_size),
373                      byte_size_in_proper_unit(_minimum_size),  proper_unit_for_byte_size(_minimum_size),
374                      byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity())
375   );
376 
377   log_info(gc, init)("Safepointing mechanism: %s",
378                      SafepointMechanism::uses_thread_local_poll() ? "thread-local poll" :
379                      (SafepointMechanism::uses_global_page_poll() ? "global-page poll" : "unknown"));
380 
381   return JNI_OK;
382 }
383 
initialize_heuristics()384 void ShenandoahHeap::initialize_heuristics() {
385   if (ShenandoahGCHeuristics != NULL) {
386     if (strcmp(ShenandoahGCHeuristics, "aggressive") == 0) {
387       _heuristics = new ShenandoahAggressiveHeuristics();
388     } else if (strcmp(ShenandoahGCHeuristics, "static") == 0) {
389       _heuristics = new ShenandoahStaticHeuristics();
390     } else if (strcmp(ShenandoahGCHeuristics, "adaptive") == 0) {
391       _heuristics = new ShenandoahAdaptiveHeuristics();
392     } else if (strcmp(ShenandoahGCHeuristics, "passive") == 0) {
393       _heuristics = new ShenandoahPassiveHeuristics();
394     } else if (strcmp(ShenandoahGCHeuristics, "compact") == 0) {
395       _heuristics = new ShenandoahCompactHeuristics();
396     } else if (strcmp(ShenandoahGCHeuristics, "traversal") == 0) {
397       _heuristics = new ShenandoahTraversalHeuristics();
398     } else {
399       vm_exit_during_initialization("Unknown -XX:ShenandoahGCHeuristics option");
400     }
401 
402     if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
403       vm_exit_during_initialization(
404               err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
405                       _heuristics->name()));
406     }
407     if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
408       vm_exit_during_initialization(
409               err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
410                       _heuristics->name()));
411     }
412 
413     if (ShenandoahStoreValEnqueueBarrier && ShenandoahStoreValReadBarrier) {
414       vm_exit_during_initialization("Cannot use both ShenandoahStoreValEnqueueBarrier and ShenandoahStoreValReadBarrier");
415     }
416     log_info(gc, init)("Shenandoah heuristics: %s",
417                        _heuristics->name());
418   } else {
419       ShouldNotReachHere();
420   }
421 
422 }
423 
424 #ifdef _MSC_VER
425 #pragma warning( push )
426 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
427 #endif
428 
ShenandoahHeap(ShenandoahCollectorPolicy * policy)429 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
430   CollectedHeap(),
431   _initial_size(0),
432   _used(0),
433   _committed(0),
434   _bytes_allocated_since_gc_start(0),
435   _max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
436   _workers(NULL),
437   _safepoint_workers(NULL),
438   _heap_region_special(false),
439   _num_regions(0),
440   _regions(NULL),
441   _update_refs_iterator(this),
442   _control_thread(NULL),
443   _shenandoah_policy(policy),
444   _heuristics(NULL),
445   _free_set(NULL),
446   _scm(new ShenandoahConcurrentMark()),
447   _traversal_gc(NULL),
448   _full_gc(new ShenandoahMarkCompact()),
449   _pacer(NULL),
450   _verifier(NULL),
451   _alloc_tracker(NULL),
452   _phase_timings(NULL),
453   _monitoring_support(NULL),
454   _memory_pool(NULL),
455   _stw_memory_manager("Shenandoah Pauses", "end of GC pause"),
456   _cycle_memory_manager("Shenandoah Cycles", "end of GC cycle"),
457   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
458   _soft_ref_policy(),
459   _ref_processor(NULL),
460   _marking_context(NULL),
461   _bitmap_size(0),
462   _bitmap_regions_per_slice(0),
463   _bitmap_bytes_per_slice(0),
464   _bitmap_region_special(false),
465   _aux_bitmap_region_special(false),
466   _liveness_cache(NULL),
467   _collection_set(NULL)
468 {
469   log_info(gc, init)("GC threads: " UINT32_FORMAT " parallel, " UINT32_FORMAT " concurrent", ParallelGCThreads, ConcGCThreads);
470   log_info(gc, init)("Reference processing: %s", ParallelRefProcEnabled ? "parallel" : "serial");
471 
472   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this));
473 
474   _max_workers = MAX2(_max_workers, 1U);
475   _workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
476                             /* are_GC_task_threads */true,
477                             /* are_ConcurrentGC_threads */false);
478   if (_workers == NULL) {
479     vm_exit_during_initialization("Failed necessary allocation.");
480   } else {
481     _workers->initialize_workers();
482   }
483 
484   if (ShenandoahParallelSafepointThreads > 1) {
485     _safepoint_workers = new ShenandoahWorkGang("Safepoint Cleanup Thread",
486                                                 ShenandoahParallelSafepointThreads,
487                                                 false, false);
488     _safepoint_workers->initialize_workers();
489   }
490 }
491 
492 #ifdef _MSC_VER
493 #pragma warning( pop )
494 #endif
495 
496 class ShenandoahResetBitmapTask : public AbstractGangTask {
497 private:
498   ShenandoahRegionIterator _regions;
499 
500 public:
ShenandoahResetBitmapTask()501   ShenandoahResetBitmapTask() :
502     AbstractGangTask("Parallel Reset Bitmap Task") {}
503 
work(uint worker_id)504   void work(uint worker_id) {
505     ShenandoahHeapRegion* region = _regions.next();
506     ShenandoahHeap* heap = ShenandoahHeap::heap();
507     ShenandoahMarkingContext* const ctx = heap->marking_context();
508     while (region != NULL) {
509       if (heap->is_bitmap_slice_committed(region)) {
510         ctx->clear_bitmap(region);
511       }
512       region = _regions.next();
513     }
514   }
515 };
516 
reset_mark_bitmap()517 void ShenandoahHeap::reset_mark_bitmap() {
518   assert_gc_workers(_workers->active_workers());
519   mark_incomplete_marking_context();
520 
521   ShenandoahResetBitmapTask task;
522   _workers->run_task(&task);
523 }
524 
print_on(outputStream * st) const525 void ShenandoahHeap::print_on(outputStream* st) const {
526   st->print_cr("Shenandoah Heap");
527   st->print_cr(" " SIZE_FORMAT "K total, " SIZE_FORMAT "K committed, " SIZE_FORMAT "K used",
528                max_capacity() / K, committed() / K, used() / K);
529   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"K regions",
530                num_regions(), ShenandoahHeapRegion::region_size_bytes() / K);
531 
532   st->print("Status: ");
533   if (has_forwarded_objects())               st->print("has forwarded objects, ");
534   if (is_concurrent_mark_in_progress())      st->print("marking, ");
535   if (is_evacuation_in_progress())           st->print("evacuating, ");
536   if (is_update_refs_in_progress())          st->print("updating refs, ");
537   if (is_concurrent_traversal_in_progress()) st->print("traversal, ");
538   if (is_degenerated_gc_in_progress())       st->print("degenerated gc, ");
539   if (is_full_gc_in_progress())              st->print("full gc, ");
540   if (is_full_gc_move_in_progress())         st->print("full gc move, ");
541 
542   if (cancelled_gc()) {
543     st->print("cancelled");
544   } else {
545     st->print("not cancelled");
546   }
547   st->cr();
548 
549   st->print_cr("Reserved region:");
550   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
551                p2i(reserved_region().start()),
552                p2i(reserved_region().end()));
553 
554   ShenandoahCollectionSet* cset = collection_set();
555   st->print_cr("Collection set:");
556   if (cset != NULL) {
557     st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
558     st->print_cr(" - map (biased):  " PTR_FORMAT, p2i(cset->biased_map_address()));
559   } else {
560     st->print_cr(" (NULL)");
561   }
562 
563   st->cr();
564   MetaspaceUtils::print_on(st);
565 
566   if (Verbose) {
567     print_heap_regions_on(st);
568   }
569 }
570 
571 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
572 public:
do_thread(Thread * thread)573   void do_thread(Thread* thread) {
574     assert(thread != NULL, "Sanity");
575     assert(thread->is_Worker_thread(), "Only worker thread expected");
576     ShenandoahThreadLocalData::initialize_gclab(thread);
577   }
578 };
579 
post_initialize()580 void ShenandoahHeap::post_initialize() {
581   CollectedHeap::post_initialize();
582   MutexLocker ml(Threads_lock);
583 
584   ShenandoahInitWorkerGCLABClosure init_gclabs;
585   _workers->threads_do(&init_gclabs);
586 
587   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
588   // Now, we will let WorkGang to initialize gclab when new worker is created.
589   _workers->set_initialize_gclab();
590 
591   _scm->initialize(_max_workers);
592   _full_gc->initialize(_gc_timer);
593 
594   ref_processing_init();
595 
596   _heuristics->initialize();
597 }
598 
used() const599 size_t ShenandoahHeap::used() const {
600   return OrderAccess::load_acquire(&_used);
601 }
602 
committed() const603 size_t ShenandoahHeap::committed() const {
604   OrderAccess::acquire();
605   return _committed;
606 }
607 
increase_committed(size_t bytes)608 void ShenandoahHeap::increase_committed(size_t bytes) {
609   assert_heaplock_or_safepoint();
610   _committed += bytes;
611 }
612 
decrease_committed(size_t bytes)613 void ShenandoahHeap::decrease_committed(size_t bytes) {
614   assert_heaplock_or_safepoint();
615   _committed -= bytes;
616 }
617 
increase_used(size_t bytes)618 void ShenandoahHeap::increase_used(size_t bytes) {
619   Atomic::add(bytes, &_used);
620 }
621 
set_used(size_t bytes)622 void ShenandoahHeap::set_used(size_t bytes) {
623   OrderAccess::release_store_fence(&_used, bytes);
624 }
625 
decrease_used(size_t bytes)626 void ShenandoahHeap::decrease_used(size_t bytes) {
627   assert(used() >= bytes, "never decrease heap size by more than we've left");
628   Atomic::sub(bytes, &_used);
629 }
630 
increase_allocated(size_t bytes)631 void ShenandoahHeap::increase_allocated(size_t bytes) {
632   Atomic::add(bytes, &_bytes_allocated_since_gc_start);
633 }
634 
notify_mutator_alloc_words(size_t words,bool waste)635 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
636   size_t bytes = words * HeapWordSize;
637   if (!waste) {
638     increase_used(bytes);
639   }
640   increase_allocated(bytes);
641   if (ShenandoahPacing) {
642     control_thread()->pacing_notify_alloc(words);
643     if (waste) {
644       pacer()->claim_for_alloc(words, true);
645     }
646   }
647 }
648 
capacity() const649 size_t ShenandoahHeap::capacity() const {
650   return committed();
651 }
652 
max_capacity() const653 size_t ShenandoahHeap::max_capacity() const {
654   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
655 }
656 
min_capacity() const657 size_t ShenandoahHeap::min_capacity() const {
658   return _minimum_size;
659 }
660 
initial_capacity() const661 size_t ShenandoahHeap::initial_capacity() const {
662   return _initial_size;
663 }
664 
is_in(const void * p) const665 bool ShenandoahHeap::is_in(const void* p) const {
666   HeapWord* heap_base = (HeapWord*) base();
667   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
668   return p >= heap_base && p < last_region_end;
669 }
670 
op_uncommit(double shrink_before)671 void ShenandoahHeap::op_uncommit(double shrink_before) {
672   assert (ShenandoahUncommit, "should be enabled");
673 
674   // Application allocates from the beginning of the heap, and GC allocates at
675   // the end of it. It is more efficient to uncommit from the end, so that applications
676   // could enjoy the near committed regions. GC allocations are much less frequent,
677   // and therefore can accept the committing costs.
678 
679   size_t count = 0;
680   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
681     ShenandoahHeapRegion* r = get_region(i - 1);
682     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
683       ShenandoahHeapLocker locker(lock());
684       if (r->is_empty_committed()) {
685         // Do not uncommit below minimal capacity
686         if (committed() < min_capacity() + ShenandoahHeapRegion::region_size_bytes()) {
687           break;
688         }
689 
690         r->make_uncommitted();
691         count++;
692       }
693     }
694     SpinPause(); // allow allocators to take the lock
695   }
696 
697   if (count > 0) {
698     control_thread()->notify_heap_changed();
699   }
700 }
701 
allocate_from_gclab_slow(Thread * thread,size_t size)702 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
703   // New object should fit the GCLAB size
704   size_t min_size = MAX2(size, PLAB::min_size());
705 
706   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
707   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
708   new_size = MIN2(new_size, PLAB::max_size());
709   new_size = MAX2(new_size, PLAB::min_size());
710 
711   // Record new heuristic value even if we take any shortcut. This captures
712   // the case when moderately-sized objects always take a shortcut. At some point,
713   // heuristics should catch up with them.
714   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
715 
716   if (new_size < size) {
717     // New size still does not fit the object. Fall back to shared allocation.
718     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
719     return NULL;
720   }
721 
722   // Retire current GCLAB, and allocate a new one.
723   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
724   gclab->retire();
725 
726   size_t actual_size = 0;
727   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
728   if (gclab_buf == NULL) {
729     return NULL;
730   }
731 
732   assert (size <= actual_size, "allocation should fit");
733 
734   if (ZeroTLAB) {
735     // ..and clear it.
736     Copy::zero_to_words(gclab_buf, actual_size);
737   } else {
738     // ...and zap just allocated object.
739 #ifdef ASSERT
740     // Skip mangling the space corresponding to the object header to
741     // ensure that the returned space is not considered parsable by
742     // any concurrent GC thread.
743     size_t hdr_size = oopDesc::header_size();
744     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
745 #endif // ASSERT
746   }
747   gclab->set_buf(gclab_buf, actual_size);
748   return gclab->allocate(size);
749 }
750 
allocate_new_tlab(size_t min_size,size_t requested_size,size_t * actual_size)751 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
752                                             size_t requested_size,
753                                             size_t* actual_size) {
754   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
755   HeapWord* res = allocate_memory(req);
756   if (res != NULL) {
757     *actual_size = req.actual_size();
758   } else {
759     *actual_size = 0;
760   }
761   return res;
762 }
763 
allocate_new_gclab(size_t min_size,size_t word_size,size_t * actual_size)764 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
765                                              size_t word_size,
766                                              size_t* actual_size) {
767   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
768   HeapWord* res = allocate_memory(req);
769   if (res != NULL) {
770     *actual_size = req.actual_size();
771   } else {
772     *actual_size = 0;
773   }
774   return res;
775 }
776 
heap()777 ShenandoahHeap* ShenandoahHeap::heap() {
778   CollectedHeap* heap = Universe::heap();
779   assert(heap != NULL, "Unitialized access to ShenandoahHeap::heap()");
780   assert(heap->kind() == CollectedHeap::Shenandoah, "not a shenandoah heap");
781   return (ShenandoahHeap*) heap;
782 }
783 
heap_no_check()784 ShenandoahHeap* ShenandoahHeap::heap_no_check() {
785   CollectedHeap* heap = Universe::heap();
786   return (ShenandoahHeap*) heap;
787 }
788 
allocate_memory(ShenandoahAllocRequest & req)789 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
790   ShenandoahAllocTrace trace_alloc(req.size(), req.type());
791 
792   intptr_t pacer_epoch = 0;
793   bool in_new_region = false;
794   HeapWord* result = NULL;
795 
796   if (req.is_mutator_alloc()) {
797     if (ShenandoahPacing) {
798       pacer()->pace_for_alloc(req.size());
799       pacer_epoch = pacer()->epoch();
800     }
801 
802     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
803       result = allocate_memory_under_lock(req, in_new_region);
804     }
805 
806     // Allocation failed, block until control thread reacted, then retry allocation.
807     //
808     // It might happen that one of the threads requesting allocation would unblock
809     // way later after GC happened, only to fail the second allocation, because
810     // other threads have already depleted the free storage. In this case, a better
811     // strategy is to try again, as long as GC makes progress.
812     //
813     // Then, we need to make sure the allocation was retried after at least one
814     // Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
815 
816     size_t tries = 0;
817 
818     while (result == NULL && _progress_last_gc.is_set()) {
819       tries++;
820       control_thread()->handle_alloc_failure(req.size());
821       result = allocate_memory_under_lock(req, in_new_region);
822     }
823 
824     while (result == NULL && tries <= ShenandoahFullGCThreshold) {
825       tries++;
826       control_thread()->handle_alloc_failure(req.size());
827       result = allocate_memory_under_lock(req, in_new_region);
828     }
829 
830   } else {
831     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
832     result = allocate_memory_under_lock(req, in_new_region);
833     // Do not call handle_alloc_failure() here, because we cannot block.
834     // The allocation failure would be handled by the WB slowpath with handle_alloc_failure_evac().
835   }
836 
837   if (in_new_region) {
838     control_thread()->notify_heap_changed();
839   }
840 
841   if (result != NULL) {
842     size_t requested = req.size();
843     size_t actual = req.actual_size();
844 
845     assert (req.is_lab_alloc() || (requested == actual),
846             "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
847             ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
848 
849     if (req.is_mutator_alloc()) {
850       notify_mutator_alloc_words(actual, false);
851 
852       // If we requested more than we were granted, give the rest back to pacer.
853       // This only matters if we are in the same pacing epoch: do not try to unpace
854       // over the budget for the other phase.
855       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
856         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
857       }
858     } else {
859       increase_used(actual*HeapWordSize);
860     }
861   }
862 
863   return result;
864 }
865 
allocate_memory_under_lock(ShenandoahAllocRequest & req,bool & in_new_region)866 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {
867   ShenandoahHeapLocker locker(lock());
868   return _free_set->allocate(req, in_new_region);
869 }
870 
871 class ShenandoahMemAllocator : public MemAllocator {
872 private:
873   MemAllocator& _initializer;
874 public:
ShenandoahMemAllocator(MemAllocator & initializer,Klass * klass,size_t word_size,Thread * thread)875   ShenandoahMemAllocator(MemAllocator& initializer, Klass* klass, size_t word_size, Thread* thread) :
876   MemAllocator(klass, word_size + ShenandoahBrooksPointer::word_size(), thread),
877     _initializer(initializer) {}
878 
879 protected:
mem_allocate(Allocation & allocation) const880   virtual HeapWord* mem_allocate(Allocation& allocation) const {
881     HeapWord* result = MemAllocator::mem_allocate(allocation);
882     // Initialize brooks-pointer
883     if (result != NULL) {
884       result += ShenandoahBrooksPointer::word_size();
885       ShenandoahBrooksPointer::initialize(oop(result));
886       assert(! ShenandoahHeap::heap()->in_collection_set(result), "never allocate in targetted region");
887     }
888     return result;
889   }
890 
initialize(HeapWord * mem) const891   virtual oop initialize(HeapWord* mem) const {
892      return _initializer.initialize(mem);
893   }
894 };
895 
obj_allocate(Klass * klass,int size,TRAPS)896 oop ShenandoahHeap::obj_allocate(Klass* klass, int size, TRAPS) {
897   ObjAllocator initializer(klass, size, THREAD);
898   ShenandoahMemAllocator allocator(initializer, klass, size, THREAD);
899   return allocator.allocate();
900 }
901 
array_allocate(Klass * klass,int size,int length,bool do_zero,TRAPS)902 oop ShenandoahHeap::array_allocate(Klass* klass, int size, int length, bool do_zero, TRAPS) {
903   ObjArrayAllocator initializer(klass, size, length, do_zero, THREAD);
904   ShenandoahMemAllocator allocator(initializer, klass, size, THREAD);
905   return allocator.allocate();
906 }
907 
class_allocate(Klass * klass,int size,TRAPS)908 oop ShenandoahHeap::class_allocate(Klass* klass, int size, TRAPS) {
909   ClassAllocator initializer(klass, size, THREAD);
910   ShenandoahMemAllocator allocator(initializer, klass, size, THREAD);
911   return allocator.allocate();
912 }
913 
mem_allocate(size_t size,bool * gc_overhead_limit_was_exceeded)914 HeapWord* ShenandoahHeap::mem_allocate(size_t size,
915                                         bool*  gc_overhead_limit_was_exceeded) {
916   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
917   return allocate_memory(req);
918 }
919 
satisfy_failed_metadata_allocation(ClassLoaderData * loader_data,size_t size,Metaspace::MetadataType mdtype)920 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
921                                                              size_t size,
922                                                              Metaspace::MetadataType mdtype) {
923   MetaWord* result;
924 
925   // Inform metaspace OOM to GC heuristics if class unloading is possible.
926   if (heuristics()->can_unload_classes()) {
927     ShenandoahHeuristics* h = heuristics();
928     h->record_metaspace_oom();
929   }
930 
931   // Expand and retry allocation
932   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
933   if (result != NULL) {
934     return result;
935   }
936 
937   // Start full GC
938   collect(GCCause::_metadata_GC_clear_soft_refs);
939 
940   // Retry allocation
941   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
942   if (result != NULL) {
943     return result;
944   }
945 
946   // Expand and retry allocation
947   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
948   if (result != NULL) {
949     return result;
950   }
951 
952   // Out of memory
953   return NULL;
954 }
955 
fill_with_dummy_object(HeapWord * start,HeapWord * end,bool zap)956 void ShenandoahHeap::fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) {
957   HeapWord* obj = tlab_post_allocation_setup(start);
958   CollectedHeap::fill_with_object(obj, end);
959 }
960 
min_dummy_object_size() const961 size_t ShenandoahHeap::min_dummy_object_size() const {
962   return CollectedHeap::min_dummy_object_size() + ShenandoahBrooksPointer::word_size();
963 }
964 
965 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
966 private:
967   ShenandoahHeap* const _heap;
968   Thread* const _thread;
969 public:
ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap * heap)970   ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
971     _heap(heap), _thread(Thread::current()) {}
972 
do_object(oop p)973   void do_object(oop p) {
974     shenandoah_assert_marked(NULL, p);
975     if (oopDesc::equals_raw(p, ShenandoahBarrierSet::resolve_forwarded_not_null(p))) {
976       _heap->evacuate_object(p, _thread);
977     }
978   }
979 };
980 
981 class ShenandoahEvacuationTask : public AbstractGangTask {
982 private:
983   ShenandoahHeap* const _sh;
984   ShenandoahCollectionSet* const _cs;
985   bool _concurrent;
986 public:
ShenandoahEvacuationTask(ShenandoahHeap * sh,ShenandoahCollectionSet * cs,bool concurrent)987   ShenandoahEvacuationTask(ShenandoahHeap* sh,
988                            ShenandoahCollectionSet* cs,
989                            bool concurrent) :
990     AbstractGangTask("Parallel Evacuation Task"),
991     _sh(sh),
992     _cs(cs),
993     _concurrent(concurrent)
994   {}
995 
work(uint worker_id)996   void work(uint worker_id) {
997     if (_concurrent) {
998       ShenandoahConcurrentWorkerSession worker_session(worker_id);
999       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
1000       ShenandoahEvacOOMScope oom_evac_scope;
1001       do_work();
1002     } else {
1003       ShenandoahParallelWorkerSession worker_session(worker_id);
1004       ShenandoahEvacOOMScope oom_evac_scope;
1005       do_work();
1006     }
1007   }
1008 
1009 private:
do_work()1010   void do_work() {
1011     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
1012     ShenandoahHeapRegion* r;
1013     while ((r =_cs->claim_next()) != NULL) {
1014       assert(r->has_live(), "all-garbage regions are reclaimed early");
1015       _sh->marked_object_iterate(r, &cl);
1016 
1017       if (ShenandoahPacing) {
1018         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
1019       }
1020 
1021       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1022         break;
1023       }
1024     }
1025   }
1026 };
1027 
trash_cset_regions()1028 void ShenandoahHeap::trash_cset_regions() {
1029   ShenandoahHeapLocker locker(lock());
1030 
1031   ShenandoahCollectionSet* set = collection_set();
1032   ShenandoahHeapRegion* r;
1033   set->clear_current_index();
1034   while ((r = set->next()) != NULL) {
1035     r->make_trash();
1036   }
1037   collection_set()->clear();
1038 }
1039 
print_heap_regions_on(outputStream * st) const1040 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1041   st->print_cr("Heap Regions:");
1042   st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
1043   st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
1044   st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start (previous, next)");
1045   st->print_cr("SN=alloc sequence numbers (first mutator, last mutator, first gc, last gc)");
1046 
1047   for (size_t i = 0; i < num_regions(); i++) {
1048     get_region(i)->print_on(st);
1049   }
1050 }
1051 
trash_humongous_region_at(ShenandoahHeapRegion * start)1052 void ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
1053   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1054 
1055   oop humongous_obj = oop(start->bottom() + ShenandoahBrooksPointer::word_size());
1056   size_t size = humongous_obj->size() + ShenandoahBrooksPointer::word_size();
1057   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
1058   size_t index = start->region_number() + required_regions - 1;
1059 
1060   assert(!start->has_live(), "liveness must be zero");
1061 
1062   for(size_t i = 0; i < required_regions; i++) {
1063     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
1064     // as it expects that every region belongs to a humongous region starting with a humongous start region.
1065     ShenandoahHeapRegion* region = get_region(index --);
1066 
1067     assert(region->is_humongous(), "expect correct humongous start or continuation");
1068     assert(!region->is_cset(), "Humongous region should not be in collection set");
1069 
1070     region->make_trash_immediate();
1071   }
1072 }
1073 
1074 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1075 public:
do_thread(Thread * thread)1076   void do_thread(Thread* thread) {
1077     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1078     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1079     gclab->retire();
1080   }
1081 };
1082 
make_parsable(bool retire_tlabs)1083 void ShenandoahHeap::make_parsable(bool retire_tlabs) {
1084   if (UseTLAB) {
1085     CollectedHeap::ensure_parsability(retire_tlabs);
1086   }
1087   ShenandoahRetireGCLABClosure cl;
1088   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1089     cl.do_thread(t);
1090   }
1091   workers()->threads_do(&cl);
1092 }
1093 
resize_tlabs()1094 void ShenandoahHeap::resize_tlabs() {
1095   CollectedHeap::resize_all_tlabs();
1096 }
1097 
1098 class ShenandoahEvacuateUpdateRootsTask : public AbstractGangTask {
1099 private:
1100   ShenandoahRootEvacuator* _rp;
1101 
1102 public:
ShenandoahEvacuateUpdateRootsTask(ShenandoahRootEvacuator * rp)1103   ShenandoahEvacuateUpdateRootsTask(ShenandoahRootEvacuator* rp) :
1104     AbstractGangTask("Shenandoah evacuate and update roots"),
1105     _rp(rp) {}
1106 
work(uint worker_id)1107   void work(uint worker_id) {
1108     ShenandoahParallelWorkerSession worker_session(worker_id);
1109     ShenandoahEvacOOMScope oom_evac_scope;
1110     ShenandoahEvacuateUpdateRootsClosure cl;
1111 
1112     MarkingCodeBlobClosure blobsCl(&cl, CodeBlobToOopClosure::FixRelocations);
1113     _rp->process_evacuate_roots(&cl, &blobsCl, worker_id);
1114   }
1115 };
1116 
evacuate_and_update_roots()1117 void ShenandoahHeap::evacuate_and_update_roots() {
1118 #if defined(COMPILER2) || INCLUDE_JVMCI
1119   DerivedPointerTable::clear();
1120 #endif
1121   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only iterate roots while world is stopped");
1122 
1123   {
1124     ShenandoahRootEvacuator rp(this, workers()->active_workers(), ShenandoahPhaseTimings::init_evac);
1125     ShenandoahEvacuateUpdateRootsTask roots_task(&rp);
1126     workers()->run_task(&roots_task);
1127   }
1128 
1129 #if defined(COMPILER2) || INCLUDE_JVMCI
1130   DerivedPointerTable::update_pointers();
1131 #endif
1132 }
1133 
roots_iterate(OopClosure * cl)1134 void ShenandoahHeap::roots_iterate(OopClosure* cl) {
1135   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only iterate roots while world is stopped");
1136 
1137   CodeBlobToOopClosure blobsCl(cl, false);
1138   CLDToOopClosure cldCl(cl, ClassLoaderData::_claim_strong);
1139 
1140   ShenandoahRootProcessor rp(this, 1, ShenandoahPhaseTimings::_num_phases);
1141   rp.process_all_roots(cl, NULL, &cldCl, &blobsCl, NULL, 0);
1142 }
1143 
1144 // Returns size in bytes
unsafe_max_tlab_alloc(Thread * thread) const1145 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1146   if (ShenandoahElasticTLAB) {
1147     // With Elastic TLABs, return the max allowed size, and let the allocation path
1148     // figure out the safe size for current allocation.
1149     return ShenandoahHeapRegion::max_tlab_size_bytes();
1150   } else {
1151     return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1152   }
1153 }
1154 
max_tlab_size() const1155 size_t ShenandoahHeap::max_tlab_size() const {
1156   // Returns size in words
1157   return ShenandoahHeapRegion::max_tlab_size_words();
1158 }
1159 
1160 class ShenandoahRetireAndResetGCLABClosure : public ThreadClosure {
1161 public:
do_thread(Thread * thread)1162   void do_thread(Thread* thread) {
1163     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1164     gclab->retire();
1165     if (ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1166       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1167     }
1168   }
1169 };
1170 
retire_and_reset_gclabs()1171 void ShenandoahHeap::retire_and_reset_gclabs() {
1172   ShenandoahRetireAndResetGCLABClosure cl;
1173   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1174     cl.do_thread(t);
1175   }
1176   workers()->threads_do(&cl);
1177 }
1178 
collect(GCCause::Cause cause)1179 void ShenandoahHeap::collect(GCCause::Cause cause) {
1180   control_thread()->request_gc(cause);
1181 }
1182 
do_full_collection(bool clear_all_soft_refs)1183 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1184   //assert(false, "Shouldn't need to do full collections");
1185 }
1186 
collector_policy() const1187 CollectorPolicy* ShenandoahHeap::collector_policy() const {
1188   return _shenandoah_policy;
1189 }
1190 
block_start(const void * addr) const1191 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1192   Space* sp = heap_region_containing(addr);
1193   if (sp != NULL) {
1194     return sp->block_start(addr);
1195   }
1196   return NULL;
1197 }
1198 
block_size(const HeapWord * addr) const1199 size_t ShenandoahHeap::block_size(const HeapWord* addr) const {
1200   Space* sp = heap_region_containing(addr);
1201   assert(sp != NULL, "block_size of address outside of heap");
1202   return sp->block_size(addr);
1203 }
1204 
block_is_obj(const HeapWord * addr) const1205 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1206   Space* sp = heap_region_containing(addr);
1207   return sp->block_is_obj(addr);
1208 }
1209 
millis_since_last_gc()1210 jlong ShenandoahHeap::millis_since_last_gc() {
1211   double v = heuristics()->time_since_last_gc() * 1000;
1212   assert(0 <= v && v <= max_jlong, "value should fit: %f", v);
1213   return (jlong)v;
1214 }
1215 
prepare_for_verify()1216 void ShenandoahHeap::prepare_for_verify() {
1217   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1218     make_parsable(false);
1219   }
1220 }
1221 
print_gc_threads_on(outputStream * st) const1222 void ShenandoahHeap::print_gc_threads_on(outputStream* st) const {
1223   workers()->print_worker_threads_on(st);
1224   if (ShenandoahStringDedup::is_enabled()) {
1225     ShenandoahStringDedup::print_worker_threads_on(st);
1226   }
1227 }
1228 
gc_threads_do(ThreadClosure * tcl) const1229 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1230   workers()->threads_do(tcl);
1231   if (_safepoint_workers != NULL) {
1232     _safepoint_workers->threads_do(tcl);
1233   }
1234   if (ShenandoahStringDedup::is_enabled()) {
1235     ShenandoahStringDedup::threads_do(tcl);
1236   }
1237 }
1238 
print_tracing_info() const1239 void ShenandoahHeap::print_tracing_info() const {
1240   LogTarget(Info, gc, stats) lt;
1241   if (lt.is_enabled()) {
1242     ResourceMark rm;
1243     LogStream ls(lt);
1244 
1245     phase_timings()->print_on(&ls);
1246 
1247     ls.cr();
1248     ls.cr();
1249 
1250     shenandoah_policy()->print_gc_stats(&ls);
1251 
1252     ls.cr();
1253     ls.cr();
1254 
1255     if (ShenandoahPacing) {
1256       pacer()->print_on(&ls);
1257     }
1258 
1259     ls.cr();
1260     ls.cr();
1261 
1262     if (ShenandoahAllocationTrace) {
1263       assert(alloc_tracker() != NULL, "Must be");
1264       alloc_tracker()->print_on(&ls);
1265     } else {
1266       ls.print_cr("  Allocation tracing is disabled, use -XX:+ShenandoahAllocationTrace to enable.");
1267     }
1268   }
1269 }
1270 
verify(VerifyOption vo)1271 void ShenandoahHeap::verify(VerifyOption vo) {
1272   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1273     if (ShenandoahVerify) {
1274       verifier()->verify_generic(vo);
1275     } else {
1276       // TODO: Consider allocating verification bitmaps on demand,
1277       // and turn this on unconditionally.
1278     }
1279   }
1280 }
tlab_capacity(Thread * thr) const1281 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1282   return _free_set->capacity();
1283 }
1284 
1285 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1286 private:
1287   MarkBitMap* _bitmap;
1288   Stack<oop,mtGC>* _oop_stack;
1289 
1290   template <class T>
do_oop_work(T * p)1291   void do_oop_work(T* p) {
1292     T o = RawAccess<>::oop_load(p);
1293     if (!CompressedOops::is_null(o)) {
1294       oop obj = CompressedOops::decode_not_null(o);
1295       obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1296       assert(oopDesc::is_oop(obj), "must be a valid oop");
1297       if (!_bitmap->is_marked((HeapWord*) obj)) {
1298         _bitmap->mark((HeapWord*) obj);
1299         _oop_stack->push(obj);
1300       }
1301     }
1302   }
1303 public:
ObjectIterateScanRootClosure(MarkBitMap * bitmap,Stack<oop,mtGC> * oop_stack)1304   ObjectIterateScanRootClosure(MarkBitMap* bitmap, Stack<oop,mtGC>* oop_stack) :
1305     _bitmap(bitmap), _oop_stack(oop_stack) {}
do_oop(oop * p)1306   void do_oop(oop* p)       { do_oop_work(p); }
do_oop(narrowOop * p)1307   void do_oop(narrowOop* p) { do_oop_work(p); }
1308 };
1309 
1310 /*
1311  * This is public API, used in preparation of object_iterate().
1312  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1313  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1314  * control, we call SH::make_tlabs_parsable().
1315  */
ensure_parsability(bool retire_tlabs)1316 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1317   // No-op.
1318 }
1319 
1320 /*
1321  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1322  *
1323  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1324  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1325  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1326  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1327  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1328  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1329  * wiped the bitmap in preparation for next marking).
1330  *
1331  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1332  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1333  * is allowed to report dead objects, but is not required to do so.
1334  */
object_iterate(ObjectClosure * cl)1335 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1336   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1337   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1338     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1339     return;
1340   }
1341 
1342   // Reset bitmap
1343   _aux_bit_map.clear();
1344 
1345   Stack<oop,mtGC> oop_stack;
1346 
1347   // First, we process all GC roots. This populates the work stack with initial objects.
1348   ShenandoahRootProcessor rp(this, 1, ShenandoahPhaseTimings::_num_phases);
1349   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1350   CLDToOopClosure clds(&oops, ClassLoaderData::_claim_none);
1351   CodeBlobToOopClosure blobs(&oops, false);
1352   rp.process_all_roots(&oops, &oops, &clds, &blobs, NULL, 0);
1353 
1354   // Work through the oop stack to traverse heap.
1355   while (! oop_stack.is_empty()) {
1356     oop obj = oop_stack.pop();
1357     assert(oopDesc::is_oop(obj), "must be a valid oop");
1358     cl->do_object(obj);
1359     obj->oop_iterate(&oops);
1360   }
1361 
1362   assert(oop_stack.is_empty(), "should be empty");
1363 
1364   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1365     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1366   }
1367 }
1368 
safe_object_iterate(ObjectClosure * cl)1369 void ShenandoahHeap::safe_object_iterate(ObjectClosure* cl) {
1370   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1371   object_iterate(cl);
1372 }
1373 
heap_region_iterate(ShenandoahHeapRegionClosure * blk) const1374 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1375   for (size_t i = 0; i < num_regions(); i++) {
1376     ShenandoahHeapRegion* current = get_region(i);
1377     blk->heap_region_do(current);
1378   }
1379 }
1380 
1381 class ShenandoahParallelHeapRegionTask : public AbstractGangTask {
1382 private:
1383   ShenandoahHeap* const _heap;
1384   ShenandoahHeapRegionClosure* const _blk;
1385 
1386   DEFINE_PAD_MINUS_SIZE(0, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile size_t));
1387   volatile size_t _index;
1388   DEFINE_PAD_MINUS_SIZE(1, DEFAULT_CACHE_LINE_SIZE, 0);
1389 
1390 public:
ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure * blk)1391   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1392           AbstractGangTask("Parallel Region Task"),
1393           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1394 
work(uint worker_id)1395   void work(uint worker_id) {
1396     size_t stride = ShenandoahParallelRegionStride;
1397 
1398     size_t max = _heap->num_regions();
1399     while (_index < max) {
1400       size_t cur = Atomic::add(stride, &_index) - stride;
1401       size_t start = cur;
1402       size_t end = MIN2(cur + stride, max);
1403       if (start >= max) break;
1404 
1405       for (size_t i = cur; i < end; i++) {
1406         ShenandoahHeapRegion* current = _heap->get_region(i);
1407         _blk->heap_region_do(current);
1408       }
1409     }
1410   }
1411 };
1412 
parallel_heap_region_iterate(ShenandoahHeapRegionClosure * blk) const1413 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1414   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1415   if (num_regions() > ShenandoahParallelRegionStride) {
1416     ShenandoahParallelHeapRegionTask task(blk);
1417     workers()->run_task(&task);
1418   } else {
1419     heap_region_iterate(blk);
1420   }
1421 }
1422 
1423 class ShenandoahClearLivenessClosure : public ShenandoahHeapRegionClosure {
1424 private:
1425   ShenandoahMarkingContext* const _ctx;
1426 public:
ShenandoahClearLivenessClosure()1427   ShenandoahClearLivenessClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1428 
heap_region_do(ShenandoahHeapRegion * r)1429   void heap_region_do(ShenandoahHeapRegion* r) {
1430     if (r->is_active()) {
1431       r->clear_live_data();
1432       _ctx->capture_top_at_mark_start(r);
1433     } else {
1434       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1435       assert(_ctx->top_at_mark_start(r) == r->top(),
1436              "Region " SIZE_FORMAT " should already have correct TAMS", r->region_number());
1437     }
1438   }
1439 
is_thread_safe()1440   bool is_thread_safe() { return true; }
1441 };
1442 
op_init_mark()1443 void ShenandoahHeap::op_init_mark() {
1444   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1445   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
1446 
1447   assert(marking_context()->is_bitmap_clear(), "need clear marking bitmap");
1448   assert(!marking_context()->is_complete(), "should not be complete");
1449 
1450   if (ShenandoahVerify) {
1451     verifier()->verify_before_concmark();
1452   }
1453 
1454   if (VerifyBeforeGC) {
1455     Universe::verify();
1456   }
1457 
1458   set_concurrent_mark_in_progress(true);
1459   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1460   {
1461     ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable);
1462     make_parsable(true);
1463   }
1464 
1465   {
1466     ShenandoahGCPhase phase(ShenandoahPhaseTimings::clear_liveness);
1467     ShenandoahClearLivenessClosure clc;
1468     parallel_heap_region_iterate(&clc);
1469   }
1470 
1471   // Make above changes visible to worker threads
1472   OrderAccess::fence();
1473 
1474   concurrent_mark()->mark_roots(ShenandoahPhaseTimings::scan_roots);
1475 
1476   if (UseTLAB) {
1477     ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs);
1478     resize_tlabs();
1479   }
1480 
1481   if (ShenandoahPacing) {
1482     pacer()->setup_for_mark();
1483   }
1484 }
1485 
op_mark()1486 void ShenandoahHeap::op_mark() {
1487   concurrent_mark()->mark_from_roots();
1488 }
1489 
1490 class ShenandoahCompleteLivenessClosure : public ShenandoahHeapRegionClosure {
1491 private:
1492   ShenandoahMarkingContext* const _ctx;
1493 public:
ShenandoahCompleteLivenessClosure()1494   ShenandoahCompleteLivenessClosure() : _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
1495 
heap_region_do(ShenandoahHeapRegion * r)1496   void heap_region_do(ShenandoahHeapRegion* r) {
1497     if (r->is_active()) {
1498       HeapWord *tams = _ctx->top_at_mark_start(r);
1499       HeapWord *top = r->top();
1500       if (top > tams) {
1501         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1502       }
1503     } else {
1504       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1505       assert(_ctx->top_at_mark_start(r) == r->top(),
1506              "Region " SIZE_FORMAT " should have correct TAMS", r->region_number());
1507     }
1508   }
1509 
is_thread_safe()1510   bool is_thread_safe() { return true; }
1511 };
1512 
op_final_mark()1513 void ShenandoahHeap::op_final_mark() {
1514   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1515 
1516   // It is critical that we
1517   // evacuate roots right after finishing marking, so that we don't
1518   // get unmarked objects in the roots.
1519 
1520   if (!cancelled_gc()) {
1521     concurrent_mark()->finish_mark_from_roots(/* full_gc = */ false);
1522 
1523     if (has_forwarded_objects()) {
1524       concurrent_mark()->update_roots(ShenandoahPhaseTimings::update_roots);
1525     }
1526 
1527     stop_concurrent_marking();
1528 
1529     {
1530       ShenandoahGCPhase phase(ShenandoahPhaseTimings::complete_liveness);
1531 
1532       // All allocations past TAMS are implicitly live, adjust the region data.
1533       // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1534       ShenandoahCompleteLivenessClosure cl;
1535       parallel_heap_region_iterate(&cl);
1536     }
1537 
1538     {
1539       ShenandoahGCPhase prepare_evac(ShenandoahPhaseTimings::prepare_evac);
1540 
1541       make_parsable(true);
1542 
1543       trash_cset_regions();
1544 
1545       {
1546         ShenandoahHeapLocker locker(lock());
1547         _collection_set->clear();
1548         _free_set->clear();
1549 
1550         heuristics()->choose_collection_set(_collection_set);
1551 
1552         _free_set->rebuild();
1553       }
1554     }
1555 
1556     // If collection set has candidates, start evacuation.
1557     // Otherwise, bypass the rest of the cycle.
1558     if (!collection_set()->is_empty()) {
1559       ShenandoahGCPhase init_evac(ShenandoahPhaseTimings::init_evac);
1560 
1561       if (ShenandoahVerify) {
1562         verifier()->verify_before_evacuation();
1563       }
1564 
1565       set_evacuation_in_progress(true);
1566       // From here on, we need to update references.
1567       set_has_forwarded_objects(true);
1568 
1569       evacuate_and_update_roots();
1570 
1571       if (ShenandoahPacing) {
1572         pacer()->setup_for_evac();
1573       }
1574 
1575       if (ShenandoahVerify) {
1576         verifier()->verify_during_evacuation();
1577       }
1578     } else {
1579       if (ShenandoahVerify) {
1580         verifier()->verify_after_concmark();
1581       }
1582 
1583       if (VerifyAfterGC) {
1584         Universe::verify();
1585       }
1586     }
1587 
1588   } else {
1589     concurrent_mark()->cancel();
1590     stop_concurrent_marking();
1591 
1592     if (process_references()) {
1593       // Abandon reference processing right away: pre-cleaning must have failed.
1594       ReferenceProcessor *rp = ref_processor();
1595       rp->disable_discovery();
1596       rp->abandon_partial_discovery();
1597       rp->verify_no_references_recorded();
1598     }
1599   }
1600 }
1601 
op_final_evac()1602 void ShenandoahHeap::op_final_evac() {
1603   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1604 
1605   set_evacuation_in_progress(false);
1606 
1607   retire_and_reset_gclabs();
1608 
1609   if (ShenandoahVerify) {
1610     verifier()->verify_after_evacuation();
1611   }
1612 
1613   if (VerifyAfterGC) {
1614     Universe::verify();
1615   }
1616 }
1617 
op_conc_evac()1618 void ShenandoahHeap::op_conc_evac() {
1619   ShenandoahEvacuationTask task(this, _collection_set, true);
1620   workers()->run_task(&task);
1621 }
1622 
op_stw_evac()1623 void ShenandoahHeap::op_stw_evac() {
1624   ShenandoahEvacuationTask task(this, _collection_set, false);
1625   workers()->run_task(&task);
1626 }
1627 
op_updaterefs()1628 void ShenandoahHeap::op_updaterefs() {
1629   update_heap_references(true);
1630 }
1631 
op_cleanup()1632 void ShenandoahHeap::op_cleanup() {
1633   free_set()->recycle_trash();
1634 }
1635 
op_reset()1636 void ShenandoahHeap::op_reset() {
1637   reset_mark_bitmap();
1638 }
1639 
op_preclean()1640 void ShenandoahHeap::op_preclean() {
1641   concurrent_mark()->preclean_weak_refs();
1642 }
1643 
op_init_traversal()1644 void ShenandoahHeap::op_init_traversal() {
1645   traversal_gc()->init_traversal_collection();
1646 }
1647 
op_traversal()1648 void ShenandoahHeap::op_traversal() {
1649   traversal_gc()->concurrent_traversal_collection();
1650 }
1651 
op_final_traversal()1652 void ShenandoahHeap::op_final_traversal() {
1653   traversal_gc()->final_traversal_collection();
1654 }
1655 
op_full(GCCause::Cause cause)1656 void ShenandoahHeap::op_full(GCCause::Cause cause) {
1657   ShenandoahMetricsSnapshot metrics;
1658   metrics.snap_before();
1659 
1660   full_gc()->do_it(cause);
1661   if (UseTLAB) {
1662     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_resize_tlabs);
1663     resize_all_tlabs();
1664   }
1665 
1666   metrics.snap_after();
1667   metrics.print();
1668 
1669   if (metrics.is_good_progress("Full GC")) {
1670     _progress_last_gc.set();
1671   } else {
1672     // Nothing to do. Tell the allocation path that we have failed to make
1673     // progress, and it can finally fail.
1674     _progress_last_gc.unset();
1675   }
1676 }
1677 
op_degenerated(ShenandoahDegenPoint point)1678 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) {
1679   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
1680   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
1681   // some phase, we have to upgrade the Degenerate GC to Full GC.
1682 
1683   clear_cancelled_gc();
1684 
1685   ShenandoahMetricsSnapshot metrics;
1686   metrics.snap_before();
1687 
1688   switch (point) {
1689     case _degenerated_traversal:
1690       {
1691         // Drop the collection set. Note: this leaves some already forwarded objects
1692         // behind, which may be problematic, see comments for ShenandoahEvacAssist
1693         // workarounds in ShenandoahTraversalHeuristics.
1694 
1695         ShenandoahHeapLocker locker(lock());
1696         collection_set()->clear_current_index();
1697         for (size_t i = 0; i < collection_set()->count(); i++) {
1698           ShenandoahHeapRegion* r = collection_set()->next();
1699           r->make_regular_bypass();
1700         }
1701         collection_set()->clear();
1702       }
1703       op_final_traversal();
1704       op_cleanup();
1705       return;
1706 
1707     // The cases below form the Duff's-like device: it describes the actual GC cycle,
1708     // but enters it at different points, depending on which concurrent phase had
1709     // degenerated.
1710 
1711     case _degenerated_outside_cycle:
1712       // We have degenerated from outside the cycle, which means something is bad with
1713       // the heap, most probably heavy humongous fragmentation, or we are very low on free
1714       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
1715       // we can do the most aggressive degen cycle, which includes processing references and
1716       // class unloading, unless those features are explicitly disabled.
1717       //
1718       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
1719       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
1720       set_process_references(heuristics()->can_process_references());
1721       set_unload_classes(heuristics()->can_unload_classes());
1722 
1723       if (heuristics()->can_do_traversal_gc()) {
1724         // Not possible to degenerate from here, upgrade to Full GC right away.
1725         cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1726         op_degenerated_fail();
1727         return;
1728       }
1729 
1730       op_reset();
1731 
1732       op_init_mark();
1733       if (cancelled_gc()) {
1734         op_degenerated_fail();
1735         return;
1736       }
1737 
1738     case _degenerated_mark:
1739       op_final_mark();
1740       if (cancelled_gc()) {
1741         op_degenerated_fail();
1742         return;
1743       }
1744 
1745       op_cleanup();
1746 
1747     case _degenerated_evac:
1748       // If heuristics thinks we should do the cycle, this flag would be set,
1749       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
1750       if (is_evacuation_in_progress()) {
1751 
1752         // Degeneration under oom-evac protocol might have left some objects in
1753         // collection set un-evacuated. Restart evacuation from the beginning to
1754         // capture all objects. For all the objects that are already evacuated,
1755         // it would be a simple check, which is supposed to be fast. This is also
1756         // safe to do even without degeneration, as CSet iterator is at beginning
1757         // in preparation for evacuation anyway.
1758         collection_set()->clear_current_index();
1759 
1760         op_stw_evac();
1761         if (cancelled_gc()) {
1762           op_degenerated_fail();
1763           return;
1764         }
1765       }
1766 
1767       // If heuristics thinks we should do the cycle, this flag would be set,
1768       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
1769       if (has_forwarded_objects()) {
1770         op_init_updaterefs();
1771         if (cancelled_gc()) {
1772           op_degenerated_fail();
1773           return;
1774         }
1775       }
1776 
1777     case _degenerated_updaterefs:
1778       if (has_forwarded_objects()) {
1779         op_final_updaterefs();
1780         if (cancelled_gc()) {
1781           op_degenerated_fail();
1782           return;
1783         }
1784       }
1785 
1786       op_cleanup();
1787       break;
1788 
1789     default:
1790       ShouldNotReachHere();
1791   }
1792 
1793   if (ShenandoahVerify) {
1794     verifier()->verify_after_degenerated();
1795   }
1796 
1797   if (VerifyAfterGC) {
1798     Universe::verify();
1799   }
1800 
1801   metrics.snap_after();
1802   metrics.print();
1803 
1804   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
1805   // because that probably means the heap is overloaded and/or fragmented.
1806   if (!metrics.is_good_progress("Degenerated GC")) {
1807     _progress_last_gc.unset();
1808     cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1809     op_degenerated_futile();
1810   } else {
1811     _progress_last_gc.set();
1812   }
1813 }
1814 
op_degenerated_fail()1815 void ShenandoahHeap::op_degenerated_fail() {
1816   log_info(gc)("Cannot finish degeneration, upgrading to Full GC");
1817   shenandoah_policy()->record_degenerated_upgrade_to_full();
1818   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1819 }
1820 
op_degenerated_futile()1821 void ShenandoahHeap::op_degenerated_futile() {
1822   shenandoah_policy()->record_degenerated_upgrade_to_full();
1823   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1824 }
1825 
stop_concurrent_marking()1826 void ShenandoahHeap::stop_concurrent_marking() {
1827   assert(is_concurrent_mark_in_progress(), "How else could we get here?");
1828   if (!cancelled_gc()) {
1829     // If we needed to update refs, and concurrent marking has been cancelled,
1830     // we need to finish updating references.
1831     set_has_forwarded_objects(false);
1832     mark_complete_marking_context();
1833   }
1834   set_concurrent_mark_in_progress(false);
1835 }
1836 
force_satb_flush_all_threads()1837 void ShenandoahHeap::force_satb_flush_all_threads() {
1838   if (!is_concurrent_mark_in_progress() && !is_concurrent_traversal_in_progress()) {
1839     // No need to flush SATBs
1840     return;
1841   }
1842 
1843   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1844     ShenandoahThreadLocalData::set_force_satb_flush(t, true);
1845   }
1846   // The threads are not "acquiring" their thread-local data, but it does not
1847   // hurt to "release" the updates here anyway.
1848   OrderAccess::fence();
1849 }
1850 
set_gc_state_all_threads(char state)1851 void ShenandoahHeap::set_gc_state_all_threads(char state) {
1852   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1853     ShenandoahThreadLocalData::set_gc_state(t, state);
1854   }
1855 }
1856 
set_gc_state_mask(uint mask,bool value)1857 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1858   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1859   _gc_state.set_cond(mask, value);
1860   set_gc_state_all_threads(_gc_state.raw_value());
1861 }
1862 
set_concurrent_mark_in_progress(bool in_progress)1863 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1864   set_gc_state_mask(MARKING, in_progress);
1865   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1866 }
1867 
set_concurrent_traversal_in_progress(bool in_progress)1868 void ShenandoahHeap::set_concurrent_traversal_in_progress(bool in_progress) {
1869    set_gc_state_mask(TRAVERSAL | HAS_FORWARDED, in_progress);
1870    ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1871 }
1872 
set_evacuation_in_progress(bool in_progress)1873 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1874   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1875   set_gc_state_mask(EVACUATION, in_progress);
1876 }
1877 
tlab_post_allocation_setup(HeapWord * obj)1878 HeapWord* ShenandoahHeap::tlab_post_allocation_setup(HeapWord* obj) {
1879   // Initialize Brooks pointer for the next object
1880   HeapWord* result = obj + ShenandoahBrooksPointer::word_size();
1881   ShenandoahBrooksPointer::initialize(oop(result));
1882   return result;
1883 }
1884 
ref_processing_init()1885 void ShenandoahHeap::ref_processing_init() {
1886   assert(_max_workers > 0, "Sanity");
1887 
1888   _ref_processor =
1889     new ReferenceProcessor(&_subject_to_discovery,  // is_subject_to_discovery
1890                            ParallelRefProcEnabled,  // MT processing
1891                            _max_workers,            // Degree of MT processing
1892                            true,                    // MT discovery
1893                            _max_workers,            // Degree of MT discovery
1894                            false,                   // Reference discovery is not atomic
1895                            NULL,                    // No closure, should be installed before use
1896                            true);                   // Scale worker threads
1897 
1898   shenandoah_assert_rp_isalive_not_installed();
1899 }
1900 
tracer()1901 GCTracer* ShenandoahHeap::tracer() {
1902   return shenandoah_policy()->tracer();
1903 }
1904 
tlab_used(Thread * thread) const1905 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1906   return _free_set->used();
1907 }
1908 
cancel_gc(GCCause::Cause cause)1909 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1910   if (try_cancel_gc()) {
1911     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1912     log_info(gc)("%s", msg.buffer());
1913     Events::log(Thread::current(), "%s", msg.buffer());
1914   }
1915 }
1916 
max_workers()1917 uint ShenandoahHeap::max_workers() {
1918   return _max_workers;
1919 }
1920 
stop()1921 void ShenandoahHeap::stop() {
1922   // The shutdown sequence should be able to terminate when GC is running.
1923 
1924   // Step 0. Notify policy to disable event recording.
1925   _shenandoah_policy->record_shutdown();
1926 
1927   // Step 1. Notify control thread that we are in shutdown.
1928   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1929   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1930   control_thread()->prepare_for_graceful_shutdown();
1931 
1932   // Step 2. Notify GC workers that we are cancelling GC.
1933   cancel_gc(GCCause::_shenandoah_stop_vm);
1934 
1935   // Step 3. Wait until GC worker exits normally.
1936   control_thread()->stop();
1937 
1938   // Step 4. Stop String Dedup thread if it is active
1939   if (ShenandoahStringDedup::is_enabled()) {
1940     ShenandoahStringDedup::stop();
1941   }
1942 }
1943 
unload_classes_and_cleanup_tables(bool full_gc)1944 void ShenandoahHeap::unload_classes_and_cleanup_tables(bool full_gc) {
1945   assert(heuristics()->can_unload_classes(), "Class unloading should be enabled");
1946 
1947   ShenandoahGCPhase root_phase(full_gc ?
1948                                ShenandoahPhaseTimings::full_gc_purge :
1949                                ShenandoahPhaseTimings::purge);
1950 
1951   ShenandoahIsAliveSelector alive;
1952   BoolObjectClosure* is_alive = alive.is_alive_closure();
1953 
1954   bool purged_class;
1955 
1956   // Unload classes and purge SystemDictionary.
1957   {
1958     ShenandoahGCPhase phase(full_gc ?
1959                             ShenandoahPhaseTimings::full_gc_purge_class_unload :
1960                             ShenandoahPhaseTimings::purge_class_unload);
1961     purged_class = SystemDictionary::do_unloading(gc_timer());
1962   }
1963 
1964   {
1965     ShenandoahGCPhase phase(full_gc ?
1966                             ShenandoahPhaseTimings::full_gc_purge_par :
1967                             ShenandoahPhaseTimings::purge_par);
1968     uint active = _workers->active_workers();
1969     StringDedupUnlinkOrOopsDoClosure dedup_cl(is_alive, NULL);
1970     ParallelCleaningTask unlink_task(is_alive, &dedup_cl, active, purged_class);
1971     _workers->run_task(&unlink_task);
1972   }
1973 
1974   {
1975     ShenandoahGCPhase phase(full_gc ?
1976                       ShenandoahPhaseTimings::full_gc_purge_cldg :
1977                       ShenandoahPhaseTimings::purge_cldg);
1978     ClassLoaderDataGraph::purge();
1979   }
1980 }
1981 
set_has_forwarded_objects(bool cond)1982 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
1983   set_gc_state_mask(HAS_FORWARDED, cond);
1984 }
1985 
set_process_references(bool pr)1986 void ShenandoahHeap::set_process_references(bool pr) {
1987   _process_references.set_cond(pr);
1988 }
1989 
set_unload_classes(bool uc)1990 void ShenandoahHeap::set_unload_classes(bool uc) {
1991   _unload_classes.set_cond(uc);
1992 }
1993 
process_references() const1994 bool ShenandoahHeap::process_references() const {
1995   return _process_references.is_set();
1996 }
1997 
unload_classes() const1998 bool ShenandoahHeap::unload_classes() const {
1999   return _unload_classes.is_set();
2000 }
2001 
in_cset_fast_test_addr()2002 address ShenandoahHeap::in_cset_fast_test_addr() {
2003   ShenandoahHeap* heap = ShenandoahHeap::heap();
2004   assert(heap->collection_set() != NULL, "Sanity");
2005   return (address) heap->collection_set()->biased_map_address();
2006 }
2007 
cancelled_gc_addr()2008 address ShenandoahHeap::cancelled_gc_addr() {
2009   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
2010 }
2011 
gc_state_addr()2012 address ShenandoahHeap::gc_state_addr() {
2013   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
2014 }
2015 
bytes_allocated_since_gc_start()2016 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
2017   return OrderAccess::load_acquire(&_bytes_allocated_since_gc_start);
2018 }
2019 
reset_bytes_allocated_since_gc_start()2020 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2021   OrderAccess::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0);
2022 }
2023 
set_degenerated_gc_in_progress(bool in_progress)2024 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2025   _degenerated_gc_in_progress.set_cond(in_progress);
2026 }
2027 
set_full_gc_in_progress(bool in_progress)2028 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2029   _full_gc_in_progress.set_cond(in_progress);
2030 }
2031 
set_full_gc_move_in_progress(bool in_progress)2032 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2033   assert (is_full_gc_in_progress(), "should be");
2034   _full_gc_move_in_progress.set_cond(in_progress);
2035 }
2036 
set_update_refs_in_progress(bool in_progress)2037 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2038   set_gc_state_mask(UPDATEREFS, in_progress);
2039 }
2040 
register_nmethod(nmethod * nm)2041 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2042   ShenandoahCodeRoots::add_nmethod(nm);
2043 }
2044 
unregister_nmethod(nmethod * nm)2045 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2046   ShenandoahCodeRoots::remove_nmethod(nm);
2047 }
2048 
pin_object(JavaThread * thr,oop o)2049 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2050   o = ShenandoahBarrierSet::barrier_set()->write_barrier(o);
2051   ShenandoahHeapLocker locker(lock());
2052   heap_region_containing(o)->make_pinned();
2053   return o;
2054 }
2055 
unpin_object(JavaThread * thr,oop o)2056 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2057   o = ShenandoahBarrierSet::barrier_set()->read_barrier(o);
2058   ShenandoahHeapLocker locker(lock());
2059   heap_region_containing(o)->make_unpinned();
2060 }
2061 
gc_timer() const2062 GCTimer* ShenandoahHeap::gc_timer() const {
2063   return _gc_timer;
2064 }
2065 
2066 #ifdef ASSERT
assert_gc_workers(uint nworkers)2067 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2068   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2069 
2070   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2071     if (UseDynamicNumberOfGCThreads ||
2072         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
2073       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
2074     } else {
2075       // Use ParallelGCThreads inside safepoints
2076       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
2077     }
2078   } else {
2079     if (UseDynamicNumberOfGCThreads ||
2080         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
2081       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2082     } else {
2083       // Use ConcGCThreads outside safepoints
2084       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2085     }
2086   }
2087 }
2088 #endif
2089 
verifier()2090 ShenandoahVerifier* ShenandoahHeap::verifier() {
2091   guarantee(ShenandoahVerify, "Should be enabled");
2092   assert (_verifier != NULL, "sanity");
2093   return _verifier;
2094 }
2095 
2096 template<class T>
2097 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2098 private:
2099   T cl;
2100   ShenandoahHeap* _heap;
2101   ShenandoahRegionIterator* _regions;
2102   bool _concurrent;
2103 public:
ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator * regions,bool concurrent)2104   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) :
2105     AbstractGangTask("Concurrent Update References Task"),
2106     cl(T()),
2107     _heap(ShenandoahHeap::heap()),
2108     _regions(regions),
2109     _concurrent(concurrent) {
2110   }
2111 
work(uint worker_id)2112   void work(uint worker_id) {
2113     if (_concurrent) {
2114       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2115       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2116       do_work();
2117     } else {
2118       ShenandoahParallelWorkerSession worker_session(worker_id);
2119       do_work();
2120     }
2121   }
2122 
2123 private:
do_work()2124   void do_work() {
2125     ShenandoahHeapRegion* r = _regions->next();
2126     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2127     while (r != NULL) {
2128       HeapWord* top_at_start_ur = r->concurrent_iteration_safe_limit();
2129       assert (top_at_start_ur >= r->bottom(), "sanity");
2130       if (r->is_active() && !r->is_cset()) {
2131         _heap->marked_object_oop_iterate(r, &cl, top_at_start_ur);
2132       }
2133       if (ShenandoahPacing) {
2134         _heap->pacer()->report_updaterefs(pointer_delta(top_at_start_ur, r->bottom()));
2135       }
2136       if (_heap->check_cancelled_gc_and_yield(_concurrent)) {
2137         return;
2138       }
2139       r = _regions->next();
2140     }
2141   }
2142 };
2143 
update_heap_references(bool concurrent)2144 void ShenandoahHeap::update_heap_references(bool concurrent) {
2145   ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task(&_update_refs_iterator, concurrent);
2146   workers()->run_task(&task);
2147 }
2148 
op_init_updaterefs()2149 void ShenandoahHeap::op_init_updaterefs() {
2150   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2151 
2152   set_evacuation_in_progress(false);
2153 
2154   retire_and_reset_gclabs();
2155 
2156   if (ShenandoahVerify) {
2157     verifier()->verify_before_updaterefs();
2158   }
2159 
2160   set_update_refs_in_progress(true);
2161   make_parsable(true);
2162   for (uint i = 0; i < num_regions(); i++) {
2163     ShenandoahHeapRegion* r = get_region(i);
2164     r->set_concurrent_iteration_safe_limit(r->top());
2165   }
2166 
2167   // Reset iterator.
2168   _update_refs_iterator.reset();
2169 
2170   if (ShenandoahPacing) {
2171     pacer()->setup_for_updaterefs();
2172   }
2173 }
2174 
op_final_updaterefs()2175 void ShenandoahHeap::op_final_updaterefs() {
2176   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2177 
2178   // Check if there is left-over work, and finish it
2179   if (_update_refs_iterator.has_next()) {
2180     ShenandoahGCPhase final_work(ShenandoahPhaseTimings::final_update_refs_finish_work);
2181 
2182     // Finish updating references where we left off.
2183     clear_cancelled_gc();
2184     update_heap_references(false);
2185   }
2186 
2187   // Clear cancelled GC, if set. On cancellation path, the block before would handle
2188   // everything. On degenerated paths, cancelled gc would not be set anyway.
2189   if (cancelled_gc()) {
2190     clear_cancelled_gc();
2191   }
2192   assert(!cancelled_gc(), "Should have been done right before");
2193 
2194   concurrent_mark()->update_roots(is_degenerated_gc_in_progress() ?
2195                                  ShenandoahPhaseTimings::degen_gc_update_roots:
2196                                  ShenandoahPhaseTimings::final_update_refs_roots);
2197 
2198   ShenandoahGCPhase final_update_refs(ShenandoahPhaseTimings::final_update_refs_recycle);
2199 
2200   trash_cset_regions();
2201   set_has_forwarded_objects(false);
2202   set_update_refs_in_progress(false);
2203 
2204   if (ShenandoahVerify) {
2205     verifier()->verify_after_updaterefs();
2206   }
2207 
2208   if (VerifyAfterGC) {
2209     Universe::verify();
2210   }
2211 
2212   {
2213     ShenandoahHeapLocker locker(lock());
2214     _free_set->rebuild();
2215   }
2216 }
2217 
2218 #ifdef ASSERT
assert_heaplock_owned_by_current_thread()2219 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2220   _lock.assert_owned_by_current_thread();
2221 }
2222 
assert_heaplock_not_owned_by_current_thread()2223 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() {
2224   _lock.assert_not_owned_by_current_thread();
2225 }
2226 
assert_heaplock_or_safepoint()2227 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2228   _lock.assert_owned_by_current_thread_or_safepoint();
2229 }
2230 #endif
2231 
print_extended_on(outputStream * st) const2232 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2233   print_on(st);
2234   print_heap_regions_on(st);
2235 }
2236 
is_bitmap_slice_committed(ShenandoahHeapRegion * r,bool skip_self)2237 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2238   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2239 
2240   size_t regions_from = _bitmap_regions_per_slice * slice;
2241   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2242   for (size_t g = regions_from; g < regions_to; g++) {
2243     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2244     if (skip_self && g == r->region_number()) continue;
2245     if (get_region(g)->is_committed()) {
2246       return true;
2247     }
2248   }
2249   return false;
2250 }
2251 
commit_bitmap_slice(ShenandoahHeapRegion * r)2252 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2253   assert_heaplock_owned_by_current_thread();
2254 
2255   // Bitmaps in special regions do not need commits
2256   if (_bitmap_region_special) {
2257     return true;
2258   }
2259 
2260   if (is_bitmap_slice_committed(r, true)) {
2261     // Some other region from the group is already committed, meaning the bitmap
2262     // slice is already committed, we exit right away.
2263     return true;
2264   }
2265 
2266   // Commit the bitmap slice:
2267   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2268   size_t off = _bitmap_bytes_per_slice * slice;
2269   size_t len = _bitmap_bytes_per_slice;
2270   if (!os::commit_memory((char*)_bitmap_region.start() + off, len, false)) {
2271     return false;
2272   }
2273   return true;
2274 }
2275 
uncommit_bitmap_slice(ShenandoahHeapRegion * r)2276 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2277   assert_heaplock_owned_by_current_thread();
2278 
2279   // Bitmaps in special regions do not need uncommits
2280   if (_bitmap_region_special) {
2281     return true;
2282   }
2283 
2284   if (is_bitmap_slice_committed(r, true)) {
2285     // Some other region from the group is still committed, meaning the bitmap
2286     // slice is should stay committed, exit right away.
2287     return true;
2288   }
2289 
2290   // Uncommit the bitmap slice:
2291   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2292   size_t off = _bitmap_bytes_per_slice * slice;
2293   size_t len = _bitmap_bytes_per_slice;
2294   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2295     return false;
2296   }
2297   return true;
2298 }
2299 
safepoint_synchronize_begin()2300 void ShenandoahHeap::safepoint_synchronize_begin() {
2301   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2302     SuspendibleThreadSet::synchronize();
2303   }
2304 }
2305 
safepoint_synchronize_end()2306 void ShenandoahHeap::safepoint_synchronize_end() {
2307   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2308     SuspendibleThreadSet::desynchronize();
2309   }
2310 }
2311 
vmop_entry_init_mark()2312 void ShenandoahHeap::vmop_entry_init_mark() {
2313   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2314   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2315   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross);
2316 
2317   try_inject_alloc_failure();
2318   VM_ShenandoahInitMark op;
2319   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
2320 }
2321 
vmop_entry_final_mark()2322 void ShenandoahHeap::vmop_entry_final_mark() {
2323   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2324   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2325   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross);
2326 
2327   try_inject_alloc_failure();
2328   VM_ShenandoahFinalMarkStartEvac op;
2329   VMThread::execute(&op); // jump to entry_final_mark under safepoint
2330 }
2331 
vmop_entry_final_evac()2332 void ShenandoahHeap::vmop_entry_final_evac() {
2333   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2334   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2335   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_gross);
2336 
2337   VM_ShenandoahFinalEvac op;
2338   VMThread::execute(&op); // jump to entry_final_evac under safepoint
2339 }
2340 
vmop_entry_init_updaterefs()2341 void ShenandoahHeap::vmop_entry_init_updaterefs() {
2342   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2343   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2344   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross);
2345 
2346   try_inject_alloc_failure();
2347   VM_ShenandoahInitUpdateRefs op;
2348   VMThread::execute(&op);
2349 }
2350 
vmop_entry_final_updaterefs()2351 void ShenandoahHeap::vmop_entry_final_updaterefs() {
2352   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2353   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2354   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross);
2355 
2356   try_inject_alloc_failure();
2357   VM_ShenandoahFinalUpdateRefs op;
2358   VMThread::execute(&op);
2359 }
2360 
vmop_entry_init_traversal()2361 void ShenandoahHeap::vmop_entry_init_traversal() {
2362   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2363   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2364   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc_gross);
2365 
2366   try_inject_alloc_failure();
2367   VM_ShenandoahInitTraversalGC op;
2368   VMThread::execute(&op);
2369 }
2370 
vmop_entry_final_traversal()2371 void ShenandoahHeap::vmop_entry_final_traversal() {
2372   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2373   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2374   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc_gross);
2375 
2376   try_inject_alloc_failure();
2377   VM_ShenandoahFinalTraversalGC op;
2378   VMThread::execute(&op);
2379 }
2380 
vmop_entry_full(GCCause::Cause cause)2381 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) {
2382   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2383   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2384   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross);
2385 
2386   try_inject_alloc_failure();
2387   VM_ShenandoahFullGC op(cause);
2388   VMThread::execute(&op);
2389 }
2390 
vmop_degenerated(ShenandoahDegenPoint point)2391 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) {
2392   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2393   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2394   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross);
2395 
2396   VM_ShenandoahDegeneratedGC degenerated_gc((int)point);
2397   VMThread::execute(&degenerated_gc);
2398 }
2399 
entry_init_mark()2400 void ShenandoahHeap::entry_init_mark() {
2401   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2402   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark);
2403   const char* msg = init_mark_event_message();
2404   GCTraceTime(Info, gc) time(msg, gc_timer());
2405   EventMark em("%s", msg);
2406 
2407   ShenandoahWorkerScope scope(workers(),
2408                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
2409                               "init marking");
2410 
2411   op_init_mark();
2412 }
2413 
entry_final_mark()2414 void ShenandoahHeap::entry_final_mark() {
2415   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2416   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark);
2417   const char* msg = final_mark_event_message();
2418   GCTraceTime(Info, gc) time(msg, gc_timer());
2419   EventMark em("%s", msg);
2420 
2421   ShenandoahWorkerScope scope(workers(),
2422                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
2423                               "final marking");
2424 
2425   op_final_mark();
2426 }
2427 
entry_final_evac()2428 void ShenandoahHeap::entry_final_evac() {
2429   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2430   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac);
2431   static const char* msg = "Pause Final Evac";
2432   GCTraceTime(Info, gc) time(msg, gc_timer());
2433   EventMark em("%s", msg);
2434 
2435   op_final_evac();
2436 }
2437 
entry_init_updaterefs()2438 void ShenandoahHeap::entry_init_updaterefs() {
2439   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2440   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs);
2441 
2442   static const char* msg = "Pause Init Update Refs";
2443   GCTraceTime(Info, gc) time(msg, gc_timer());
2444   EventMark em("%s", msg);
2445 
2446   // No workers used in this phase, no setup required
2447 
2448   op_init_updaterefs();
2449 }
2450 
entry_final_updaterefs()2451 void ShenandoahHeap::entry_final_updaterefs() {
2452   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2453   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs);
2454 
2455   static const char* msg = "Pause Final Update Refs";
2456   GCTraceTime(Info, gc) time(msg, gc_timer());
2457   EventMark em("%s", msg);
2458 
2459   ShenandoahWorkerScope scope(workers(),
2460                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
2461                               "final reference update");
2462 
2463   op_final_updaterefs();
2464 }
2465 
entry_init_traversal()2466 void ShenandoahHeap::entry_init_traversal() {
2467   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2468   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc);
2469 
2470   static const char* msg = "Pause Init Traversal";
2471   GCTraceTime(Info, gc) time(msg, gc_timer());
2472   EventMark em("%s", msg);
2473 
2474   ShenandoahWorkerScope scope(workers(),
2475                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2476                               "init traversal");
2477 
2478   op_init_traversal();
2479 }
2480 
entry_final_traversal()2481 void ShenandoahHeap::entry_final_traversal() {
2482   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2483   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc);
2484 
2485   static const char* msg = "Pause Final Traversal";
2486   GCTraceTime(Info, gc) time(msg, gc_timer());
2487   EventMark em("%s", msg);
2488 
2489   ShenandoahWorkerScope scope(workers(),
2490                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2491                               "final traversal");
2492 
2493   op_final_traversal();
2494 }
2495 
entry_full(GCCause::Cause cause)2496 void ShenandoahHeap::entry_full(GCCause::Cause cause) {
2497   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2498   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc);
2499 
2500   static const char* msg = "Pause Full";
2501   GCTraceTime(Info, gc) time(msg, gc_timer(), cause, true);
2502   EventMark em("%s", msg);
2503 
2504   ShenandoahWorkerScope scope(workers(),
2505                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
2506                               "full gc");
2507 
2508   op_full(cause);
2509 }
2510 
entry_degenerated(int point)2511 void ShenandoahHeap::entry_degenerated(int point) {
2512   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2513   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc);
2514 
2515   ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point;
2516   const char* msg = degen_event_message(dpoint);
2517   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2518   EventMark em("%s", msg);
2519 
2520   ShenandoahWorkerScope scope(workers(),
2521                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
2522                               "stw degenerated gc");
2523 
2524   set_degenerated_gc_in_progress(true);
2525   op_degenerated(dpoint);
2526   set_degenerated_gc_in_progress(false);
2527 }
2528 
entry_mark()2529 void ShenandoahHeap::entry_mark() {
2530   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2531 
2532   const char* msg = conc_mark_event_message();
2533   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2534   EventMark em("%s", msg);
2535 
2536   ShenandoahWorkerScope scope(workers(),
2537                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
2538                               "concurrent marking");
2539 
2540   try_inject_alloc_failure();
2541   op_mark();
2542 }
2543 
entry_evac()2544 void ShenandoahHeap::entry_evac() {
2545   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
2546   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2547 
2548   static const char* msg = "Concurrent evacuation";
2549   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2550   EventMark em("%s", msg);
2551 
2552   ShenandoahWorkerScope scope(workers(),
2553                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
2554                               "concurrent evacuation");
2555 
2556   try_inject_alloc_failure();
2557   op_conc_evac();
2558 }
2559 
entry_updaterefs()2560 void ShenandoahHeap::entry_updaterefs() {
2561   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
2562 
2563   static const char* msg = "Concurrent update references";
2564   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2565   EventMark em("%s", msg);
2566 
2567   ShenandoahWorkerScope scope(workers(),
2568                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
2569                               "concurrent reference update");
2570 
2571   try_inject_alloc_failure();
2572   op_updaterefs();
2573 }
entry_cleanup()2574 void ShenandoahHeap::entry_cleanup() {
2575   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup);
2576 
2577   static const char* msg = "Concurrent cleanup";
2578   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2579   EventMark em("%s", msg);
2580 
2581   // This phase does not use workers, no need for setup
2582 
2583   try_inject_alloc_failure();
2584   op_cleanup();
2585 }
2586 
entry_reset()2587 void ShenandoahHeap::entry_reset() {
2588   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset);
2589 
2590   static const char* msg = "Concurrent reset";
2591   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2592   EventMark em("%s", msg);
2593 
2594   ShenandoahWorkerScope scope(workers(),
2595                               ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
2596                               "concurrent reset");
2597 
2598   try_inject_alloc_failure();
2599   op_reset();
2600 }
2601 
entry_preclean()2602 void ShenandoahHeap::entry_preclean() {
2603   if (ShenandoahPreclean && process_references()) {
2604     static const char* msg = "Concurrent precleaning";
2605     GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2606     EventMark em("%s", msg);
2607 
2608     ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean);
2609 
2610     ShenandoahWorkerScope scope(workers(),
2611                                 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(),
2612                                 "concurrent preclean",
2613                                 /* check_workers = */ false);
2614 
2615     try_inject_alloc_failure();
2616     op_preclean();
2617   }
2618 }
2619 
entry_traversal()2620 void ShenandoahHeap::entry_traversal() {
2621   static const char* msg = "Concurrent traversal";
2622   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2623   EventMark em("%s", msg);
2624 
2625   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2626 
2627   ShenandoahWorkerScope scope(workers(),
2628                               ShenandoahWorkerPolicy::calc_workers_for_conc_traversal(),
2629                               "concurrent traversal");
2630 
2631   try_inject_alloc_failure();
2632   op_traversal();
2633 }
2634 
entry_uncommit(double shrink_before)2635 void ShenandoahHeap::entry_uncommit(double shrink_before) {
2636   static const char *msg = "Concurrent uncommit";
2637   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2638   EventMark em("%s", msg);
2639 
2640   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit);
2641 
2642   op_uncommit(shrink_before);
2643 }
2644 
try_inject_alloc_failure()2645 void ShenandoahHeap::try_inject_alloc_failure() {
2646   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2647     _inject_alloc_failure.set();
2648     os::naked_short_sleep(1);
2649     if (cancelled_gc()) {
2650       log_info(gc)("Allocation failure was successfully injected");
2651     }
2652   }
2653 }
2654 
should_inject_alloc_failure()2655 bool ShenandoahHeap::should_inject_alloc_failure() {
2656   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2657 }
2658 
initialize_serviceability()2659 void ShenandoahHeap::initialize_serviceability() {
2660   _memory_pool = new ShenandoahMemoryPool(this);
2661   _cycle_memory_manager.add_pool(_memory_pool);
2662   _stw_memory_manager.add_pool(_memory_pool);
2663 }
2664 
memory_managers()2665 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2666   GrowableArray<GCMemoryManager*> memory_managers(2);
2667   memory_managers.append(&_cycle_memory_manager);
2668   memory_managers.append(&_stw_memory_manager);
2669   return memory_managers;
2670 }
2671 
memory_pools()2672 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2673   GrowableArray<MemoryPool*> memory_pools(1);
2674   memory_pools.append(_memory_pool);
2675   return memory_pools;
2676 }
2677 
memory_usage()2678 MemoryUsage ShenandoahHeap::memory_usage() {
2679   return _memory_pool->get_memory_usage();
2680 }
2681 
enter_evacuation()2682 void ShenandoahHeap::enter_evacuation() {
2683   _oom_evac_handler.enter_evacuation();
2684 }
2685 
leave_evacuation()2686 void ShenandoahHeap::leave_evacuation() {
2687   _oom_evac_handler.leave_evacuation();
2688 }
2689 
ShenandoahRegionIterator()2690 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2691   _heap(ShenandoahHeap::heap()),
2692   _index(0) {}
2693 
ShenandoahRegionIterator(ShenandoahHeap * heap)2694 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2695   _heap(heap),
2696   _index(0) {}
2697 
reset()2698 void ShenandoahRegionIterator::reset() {
2699   _index = 0;
2700 }
2701 
has_next() const2702 bool ShenandoahRegionIterator::has_next() const {
2703   return _index < _heap->num_regions();
2704 }
2705 
gc_state() const2706 char ShenandoahHeap::gc_state() const {
2707   return _gc_state.raw_value();
2708 }
2709 
deduplicate_string(oop str)2710 void ShenandoahHeap::deduplicate_string(oop str) {
2711   assert(java_lang_String::is_instance(str), "invariant");
2712 
2713   if (ShenandoahStringDedup::is_enabled()) {
2714     ShenandoahStringDedup::deduplicate(str);
2715   }
2716 }
2717 
init_mark_event_message() const2718 const char* ShenandoahHeap::init_mark_event_message() const {
2719   bool update_refs = has_forwarded_objects();
2720   bool proc_refs = process_references();
2721   bool unload_cls = unload_classes();
2722 
2723   if (update_refs && proc_refs && unload_cls) {
2724     return "Pause Init Mark (update refs) (process weakrefs) (unload classes)";
2725   } else if (update_refs && proc_refs) {
2726     return "Pause Init Mark (update refs) (process weakrefs)";
2727   } else if (update_refs && unload_cls) {
2728     return "Pause Init Mark (update refs) (unload classes)";
2729   } else if (proc_refs && unload_cls) {
2730     return "Pause Init Mark (process weakrefs) (unload classes)";
2731   } else if (update_refs) {
2732     return "Pause Init Mark (update refs)";
2733   } else if (proc_refs) {
2734     return "Pause Init Mark (process weakrefs)";
2735   } else if (unload_cls) {
2736     return "Pause Init Mark (unload classes)";
2737   } else {
2738     return "Pause Init Mark";
2739   }
2740 }
2741 
final_mark_event_message() const2742 const char* ShenandoahHeap::final_mark_event_message() const {
2743   bool update_refs = has_forwarded_objects();
2744   bool proc_refs = process_references();
2745   bool unload_cls = unload_classes();
2746 
2747   if (update_refs && proc_refs && unload_cls) {
2748     return "Pause Final Mark (update refs) (process weakrefs) (unload classes)";
2749   } else if (update_refs && proc_refs) {
2750     return "Pause Final Mark (update refs) (process weakrefs)";
2751   } else if (update_refs && unload_cls) {
2752     return "Pause Final Mark (update refs) (unload classes)";
2753   } else if (proc_refs && unload_cls) {
2754     return "Pause Final Mark (process weakrefs) (unload classes)";
2755   } else if (update_refs) {
2756     return "Pause Final Mark (update refs)";
2757   } else if (proc_refs) {
2758     return "Pause Final Mark (process weakrefs)";
2759   } else if (unload_cls) {
2760     return "Pause Final Mark (unload classes)";
2761   } else {
2762     return "Pause Final Mark";
2763   }
2764 }
2765 
conc_mark_event_message() const2766 const char* ShenandoahHeap::conc_mark_event_message() const {
2767   bool update_refs = has_forwarded_objects();
2768   bool proc_refs = process_references();
2769   bool unload_cls = unload_classes();
2770 
2771   if (update_refs && proc_refs && unload_cls) {
2772     return "Concurrent marking (update refs) (process weakrefs) (unload classes)";
2773   } else if (update_refs && proc_refs) {
2774     return "Concurrent marking (update refs) (process weakrefs)";
2775   } else if (update_refs && unload_cls) {
2776     return "Concurrent marking (update refs) (unload classes)";
2777   } else if (proc_refs && unload_cls) {
2778     return "Concurrent marking (process weakrefs) (unload classes)";
2779   } else if (update_refs) {
2780     return "Concurrent marking (update refs)";
2781   } else if (proc_refs) {
2782     return "Concurrent marking (process weakrefs)";
2783   } else if (unload_cls) {
2784     return "Concurrent marking (unload classes)";
2785   } else {
2786     return "Concurrent marking";
2787   }
2788 }
2789 
degen_event_message(ShenandoahDegenPoint point) const2790 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const {
2791   switch (point) {
2792     case _degenerated_unset:
2793       return "Pause Degenerated GC (<UNSET>)";
2794     case _degenerated_traversal:
2795       return "Pause Degenerated GC (Traversal)";
2796     case _degenerated_outside_cycle:
2797       return "Pause Degenerated GC (Outside of Cycle)";
2798     case _degenerated_mark:
2799       return "Pause Degenerated GC (Mark)";
2800     case _degenerated_evac:
2801       return "Pause Degenerated GC (Evacuation)";
2802     case _degenerated_updaterefs:
2803       return "Pause Degenerated GC (Update Refs)";
2804     default:
2805       ShouldNotReachHere();
2806       return "ERROR";
2807   }
2808 }
2809 
get_liveness_cache(uint worker_id)2810 jushort* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2811 #ifdef ASSERT
2812   assert(_liveness_cache != NULL, "sanity");
2813   assert(worker_id < _max_workers, "sanity");
2814   for (uint i = 0; i < num_regions(); i++) {
2815     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2816   }
2817 #endif
2818   return _liveness_cache[worker_id];
2819 }
2820 
flush_liveness_cache(uint worker_id)2821 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2822   assert(worker_id < _max_workers, "sanity");
2823   assert(_liveness_cache != NULL, "sanity");
2824   jushort* ld = _liveness_cache[worker_id];
2825   for (uint i = 0; i < num_regions(); i++) {
2826     ShenandoahHeapRegion* r = get_region(i);
2827     jushort live = ld[i];
2828     if (live > 0) {
2829       r->increase_live_data_gc_words(live);
2830       ld[i] = 0;
2831     }
2832   }
2833 }
2834 
obj_size(oop obj) const2835 size_t ShenandoahHeap::obj_size(oop obj) const {
2836   return CollectedHeap::obj_size(obj) + ShenandoahBrooksPointer::word_size();
2837 }
2838 
cell_header_size() const2839 ptrdiff_t ShenandoahHeap::cell_header_size() const {
2840   return ShenandoahBrooksPointer::byte_size();
2841 }
2842