1 /*
  2  * Copyright (c) 2015, 2020, Red Hat, Inc. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_GC_SHENANDOAH_SHENANDOAHHEAP_INLINE_HPP
 26 #define SHARE_GC_SHENANDOAH_SHENANDOAHHEAP_INLINE_HPP
 27 
 28 #include "gc/shenandoah/shenandoahHeap.hpp"
 29 
 30 #include "classfile/javaClasses.inline.hpp"
 31 #include "gc/shared/markBitMap.inline.hpp"
 32 #include "gc/shared/threadLocalAllocBuffer.inline.hpp"
 33 #include "gc/shared/suspendibleThreadSet.hpp"
 34 #include "gc/shared/tlab_globals.hpp"
 35 #include "gc/shenandoah/shenandoahAsserts.hpp"
 36 #include "gc/shenandoah/shenandoahBarrierSet.inline.hpp"
 37 #include "gc/shenandoah/shenandoahCollectionSet.inline.hpp"
 38 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
 39 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
 40 #include "gc/shenandoah/shenandoahHeapRegionSet.inline.hpp"
 41 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
 42 #include "gc/shenandoah/shenandoahControlThread.hpp"
 43 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
 44 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
 45 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
 46 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
 47 #include "gc/shenandoah/mode/shenandoahMode.hpp"
 48 #include "oops/compressedOops.inline.hpp"
 49 #include "oops/oop.inline.hpp"
 50 #include "runtime/atomic.hpp"
 51 #include "runtime/prefetch.inline.hpp"
 52 #include "runtime/thread.hpp"
 53 #include "utilities/copy.hpp"
 54 #include "utilities/globalDefinitions.hpp"
 55 
 56 inline ShenandoahHeap* ShenandoahHeap::heap() {
 57   return named_heap<ShenandoahHeap>(CollectedHeap::Shenandoah);
 58 }
 59 
 60 inline ShenandoahHeapRegion* ShenandoahRegionIterator::next() {
 61   size_t new_index = Atomic::add(&_index, (size_t) 1, memory_order_relaxed);
 62   // get_region() provides the bounds-check and returns NULL on OOB.
 63   return _heap->get_region(new_index - 1);
 64 }
 65 
 66 inline bool ShenandoahHeap::has_forwarded_objects() const {
 67   return _gc_state.is_set(HAS_FORWARDED);
 68 }
 69 
 70 inline WorkGang* ShenandoahHeap::workers() const {
 71   return _workers;
 72 }
 73 
 74 inline WorkGang* ShenandoahHeap::safepoint_workers() {
 75   return _safepoint_workers;
 76 }
 77 
 78 inline size_t ShenandoahHeap::heap_region_index_containing(const void* addr) const {
 79   uintptr_t region_start = ((uintptr_t) addr);
 80   uintptr_t index = (region_start - (uintptr_t) base()) >> ShenandoahHeapRegion::region_size_bytes_shift();
 81   assert(index < num_regions(), "Region index is in bounds: " PTR_FORMAT, p2i(addr));
 82   return index;
 83 }
 84 
 85 inline ShenandoahHeapRegion* const ShenandoahHeap::heap_region_containing(const void* addr) const {
 86   size_t index = heap_region_index_containing(addr);
 87   ShenandoahHeapRegion* const result = get_region(index);
 88   assert(addr >= result->bottom() && addr < result->end(), "Heap region contains the address: " PTR_FORMAT, p2i(addr));
 89   return result;
 90 }
 91 
 92 inline void ShenandoahHeap::enter_evacuation(Thread* t) {
 93   _oom_evac_handler.enter_evacuation(t);
 94 }
 95 
 96 inline void ShenandoahHeap::leave_evacuation(Thread* t) {
 97   _oom_evac_handler.leave_evacuation(t);
 98 }
 99 
100 template <class T>
101 inline void ShenandoahHeap::update_with_forwarded(T* p) {
102   T o = RawAccess<>::oop_load(p);
103   if (!CompressedOops::is_null(o)) {
104     oop obj = CompressedOops::decode_not_null(o);
105     if (in_collection_set(obj)) {
106       // Corner case: when evacuation fails, there are objects in collection
107       // set that are not really forwarded. We can still go and try and update them
108       // (uselessly) to simplify the common path.
109       shenandoah_assert_forwarded_except(p, obj, cancelled_gc());
110       oop fwd = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
111       shenandoah_assert_not_in_cset_except(p, fwd, cancelled_gc());
112 
113       // Unconditionally store the update: no concurrent updates expected.
114       RawAccess<IS_NOT_NULL>::oop_store(p, fwd);
115     }
116   }
117 }
118 
119 template <class T>
120 inline void ShenandoahHeap::conc_update_with_forwarded(T* p) {
121   T o = RawAccess<>::oop_load(p);
122   if (!CompressedOops::is_null(o)) {
123     oop obj = CompressedOops::decode_not_null(o);
124     if (in_collection_set(obj)) {
125       // Corner case: when evacuation fails, there are objects in collection
126       // set that are not really forwarded. We can still go and try CAS-update them
127       // (uselessly) to simplify the common path.
128       shenandoah_assert_forwarded_except(p, obj, cancelled_gc());
129       oop fwd = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
130       shenandoah_assert_not_in_cset_except(p, fwd, cancelled_gc());
131 
132       // Sanity check: we should not be updating the cset regions themselves,
133       // unless we are recovering from the evacuation failure.
134       shenandoah_assert_not_in_cset_loc_except(p, !is_in(p) || cancelled_gc());
135 
136       // Either we succeed in updating the reference, or something else gets in our way.
137       // We don't care if that is another concurrent GC update, or another mutator update.
138       atomic_update_oop(fwd, p, obj);
139     }
140   }
141 }
142 
143 // Atomic updates of heap location. This is only expected to work with updating the same
144 // logical object with its forwardee. The reason why we need stronger-than-relaxed memory
145 // ordering has to do with coordination with GC barriers and mutator accesses.
146 //
147 // In essence, stronger CAS access is required to maintain the transitive chains that mutator
148 // accesses build by themselves. To illustrate this point, consider the following example.
149 //
150 // Suppose "o" is the object that has a field "x" and the reference to "o" is stored
151 // to field at "addr", which happens to be Java volatile field. Normally, the accesses to volatile
152 // field at "addr" would be matched with release/acquire barriers. This changes when GC moves
153 // the object under mutator feet.
154 //
155 // Thread 1 (Java)
156 //         // --- previous access starts here
157 //         ...
158 //   T1.1: store(&o.x, 1, mo_relaxed)
159 //   T1.2: store(&addr, o, mo_release) // volatile store
160 //
161 //         // --- new access starts here
162 //         // LRB: copy and install the new copy to fwdptr
163 //   T1.3: var copy = copy(o)
164 //   T1.4: cas(&fwd, t, copy, mo_release) // pointer-mediated publication
165 //         <access continues>
166 //
167 // Thread 2 (GC updater)
168 //   T2.1: var f = load(&fwd, mo_{consume|acquire}) // pointer-mediated acquisition
169 //   T2.2: cas(&addr, o, f, mo_release) // this method
170 //
171 // Thread 3 (Java)
172 //   T3.1: var o = load(&addr, mo_acquire) // volatile read
173 //   T3.2: if (o != null)
174 //   T3.3:   var r = load(&o.x, mo_relaxed)
175 //
176 // r is guaranteed to contain "1".
177 //
178 // Without GC involvement, there is synchronizes-with edge from T1.2 to T3.1,
179 // which guarantees this. With GC involvement, when LRB copies the object and
180 // another thread updates the reference to it, we need to have the transitive edge
181 // from T1.4 to T2.1 (that one is guaranteed by forwarding accesses), plus the edge
182 // from T2.2 to T3.1 (which is brought by this CAS).
183 //
184 // Note that we do not need to "acquire" in these methods, because we do not read the
185 // failure witnesses contents on any path, and "release" is enough.
186 //
187 
188 inline void ShenandoahHeap::atomic_update_oop(oop update, oop* addr, oop compare) {
189   assert(is_aligned(addr, HeapWordSize), "Address should be aligned: " PTR_FORMAT, p2i(addr));
190   Atomic::cmpxchg(addr, compare, update, memory_order_release);
191 }
192 
193 inline void ShenandoahHeap::atomic_update_oop(oop update, narrowOop* addr, narrowOop compare) {
194   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
195   narrowOop u = CompressedOops::encode(update);
196   Atomic::cmpxchg(addr, compare, u, memory_order_release);
197 }
198 
199 inline void ShenandoahHeap::atomic_update_oop(oop update, narrowOop* addr, oop compare) {
200   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
201   narrowOop c = CompressedOops::encode(compare);
202   narrowOop u = CompressedOops::encode(update);
203   Atomic::cmpxchg(addr, c, u, memory_order_release);
204 }
205 
206 inline bool ShenandoahHeap::atomic_update_oop_check(oop update, oop* addr, oop compare) {
207   assert(is_aligned(addr, HeapWordSize), "Address should be aligned: " PTR_FORMAT, p2i(addr));
208   return (oop) Atomic::cmpxchg(addr, compare, update, memory_order_release) == compare;
209 }
210 
211 inline bool ShenandoahHeap::atomic_update_oop_check(oop update, narrowOop* addr, narrowOop compare) {
212   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
213   narrowOop u = CompressedOops::encode(update);
214   return (narrowOop) Atomic::cmpxchg(addr, compare, u, memory_order_release) == compare;
215 }
216 
217 inline bool ShenandoahHeap::atomic_update_oop_check(oop update, narrowOop* addr, oop compare) {
218   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
219   narrowOop c = CompressedOops::encode(compare);
220   narrowOop u = CompressedOops::encode(update);
221   return CompressedOops::decode(Atomic::cmpxchg(addr, c, u, memory_order_release)) == compare;
222 }
223 
224 // The memory ordering discussion above does not apply for methods that store NULLs:
225 // then, there is no transitive reads in mutator (as we see NULLs), and we can do
226 // relaxed memory ordering there.
227 
228 inline void ShenandoahHeap::atomic_clear_oop(oop* addr, oop compare) {
229   assert(is_aligned(addr, HeapWordSize), "Address should be aligned: " PTR_FORMAT, p2i(addr));
230   Atomic::cmpxchg(addr, compare, oop(), memory_order_relaxed);
231 }
232 
233 inline void ShenandoahHeap::atomic_clear_oop(narrowOop* addr, oop compare) {
234   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
235   narrowOop cmp = CompressedOops::encode(compare);
236   Atomic::cmpxchg(addr, cmp, narrowOop(), memory_order_relaxed);
237 }
238 
239 inline void ShenandoahHeap::atomic_clear_oop(narrowOop* addr, narrowOop compare) {
240   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
241   Atomic::cmpxchg(addr, compare, narrowOop(), memory_order_relaxed);
242 }
243 
244 inline bool ShenandoahHeap::cancelled_gc() const {
245   return _cancelled_gc.get() == CANCELLED;
246 }
247 
248 inline bool ShenandoahHeap::check_cancelled_gc_and_yield(bool sts_active) {
249   if (! (sts_active && ShenandoahSuspendibleWorkers)) {
250     return cancelled_gc();
251   }
252 
253   jbyte prev = _cancelled_gc.cmpxchg(NOT_CANCELLED, CANCELLABLE);
254   if (prev == CANCELLABLE || prev == NOT_CANCELLED) {
255     if (SuspendibleThreadSet::should_yield()) {
256       SuspendibleThreadSet::yield();
257     }
258 
259     // Back to CANCELLABLE. The thread that poked NOT_CANCELLED first gets
260     // to restore to CANCELLABLE.
261     if (prev == CANCELLABLE) {
262       _cancelled_gc.set(CANCELLABLE);
263     }
264     return false;
265   } else {
266     return true;
267   }
268 }
269 
270 inline void ShenandoahHeap::clear_cancelled_gc(bool clear_oom_handler) {
271   _cancelled_gc.set(CANCELLABLE);
272   if (_cancel_requested_time > 0) {
273     double cancel_time = os::elapsedTime() - _cancel_requested_time;
274     log_info(gc)("GC cancellation took %.3fs", cancel_time);
275     _cancel_requested_time = 0;
276   }
277 
278   if (clear_oom_handler) {
279     _oom_evac_handler.clear();
280   }
281 }
282 
283 inline HeapWord* ShenandoahHeap::allocate_from_gclab(Thread* thread, size_t size) {
284   assert(UseTLAB, "TLABs should be enabled");
285 
286   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
287   if (gclab == NULL) {
288     assert(!thread->is_Java_thread() && !thread->is_Worker_thread(),
289            "Performance: thread should have GCLAB: %s", thread->name());
290     // No GCLABs in this thread, fallback to shared allocation
291     return NULL;
292   }
293   HeapWord* obj = gclab->allocate(size);
294   if (obj != NULL) {
295     return obj;
296   }
297   return allocate_from_gclab_slow(thread, size);
298 }
299 
300 inline HeapWord* ShenandoahHeap::allocate_from_plab(Thread* thread, size_t size) {
301   assert(UseTLAB, "TLABs should be enabled");
302 
303   PLAB* plab = ShenandoahThreadLocalData::plab(thread);
304   if (plab == NULL) {
305     assert(!thread->is_Java_thread() && !thread->is_Worker_thread(),
306            "Performance: thread should have PLAB: %s", thread->name());
307     // No PLABs in this thread, fallback to shared allocation
308     return NULL;
309   }
310   HeapWord* obj = plab->allocate(size);
311   if (obj == NULL) {
312     obj = allocate_from_plab_slow(thread, size);
313   }
314   return obj;
315 }
316 
317 inline oop ShenandoahHeap::evacuate_object(oop p, Thread* thread) {
318   assert(thread == Thread::current(), "Expected thread parameter to be current thread.");
319   if (ShenandoahThreadLocalData::is_oom_during_evac(thread)) {
320     // This thread went through the OOM during evac protocol and it is safe to return
321     // the forward pointer. It must not attempt to evacuate any more.
322     return ShenandoahBarrierSet::resolve_forwarded(p);
323   }
324 
325   assert(ShenandoahThreadLocalData::is_evac_allowed(thread), "must be enclosed in oom-evac scope");
326 
327   ShenandoahHeapRegion* r = heap_region_containing(p);
328   assert(!r->is_humongous(), "never evacuate humongous objects");
329 
330   ShenandoahRegionAffiliation target_gen = r->affiliation();
331   if (mode()->is_generational() && ShenandoahHeap::heap()->is_gc_generation_young() &&
332       target_gen == YOUNG_GENERATION && ShenandoahPromoteTenuredObjects) {
333     markWord mark = p->mark();
334     if (mark.is_marked()) {
335       // Already forwarded.
336       return ShenandoahBarrierSet::resolve_forwarded(p);
337     }
338     if (mark.has_displaced_mark_helper()) {
339       // We don't want to deal with MT here just to ensure we read the right mark word.
340       // Skip the potential promotion attempt for this one.
341     } else if (mark.age() >= InitialTenuringThreshold) {
342       oop result = try_evacuate_object(p, thread, r, OLD_GENERATION);
343       if (result != NULL) {
344         return result;
345       }
346     }
347   }
348   return try_evacuate_object(p, thread, r, target_gen);
349 }
350 
351 // try_evacuate_object registers the object and dirties the associated remembered set information when evacuating
352 // to OLD_GENERATION.
353 inline oop ShenandoahHeap::try_evacuate_object(oop p, Thread* thread, ShenandoahHeapRegion* from_region, ShenandoahRegionAffiliation target_gen) {
354   bool alloc_from_lab = true;
355   HeapWord* copy = NULL;
356   size_t size = p->size();
357 
358 #ifdef ASSERT
359   if (ShenandoahOOMDuringEvacALot &&
360       (os::random() & 1) == 0) { // Simulate OOM every ~2nd slow-path call
361         copy = NULL;
362   } else {
363 #endif
364     if (UseTLAB) {
365       switch (target_gen) {
366         case YOUNG_GENERATION: {
367            copy = allocate_from_gclab(thread, size);
368            break;
369         }
370         case OLD_GENERATION: {
371            if (ShenandoahUsePLAB) {
372              copy = allocate_from_plab(thread, size);
373            }
374            break;
375         }
376         default: {
377           ShouldNotReachHere();
378           break;
379         }
380       }
381     }
382     if (copy == NULL) {
383       ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared_gc(size, target_gen);
384       copy = allocate_memory(req);
385       alloc_from_lab = false;
386     }
387 #ifdef ASSERT
388   }
389 #endif
390 
391   if (copy == NULL) {
392     if (target_gen == OLD_GENERATION) {
393       assert(mode()->is_generational(), "Should only be here in generational mode.");
394       if (from_region->is_young()) {
395         // Signal that promotion failed. Will evacuate this old object somewhere in young gen.
396         handle_promotion_failure();
397         return NULL;
398       } else {
399         // Remember that evacuation to old gen failed. We'll want to trigger a full gc to recover from this
400         // after the evacuation threads have finished.
401         handle_old_evacuation_failure();
402       }
403     }
404 
405     control_thread()->handle_alloc_failure_evac(size);
406 
407     _oom_evac_handler.handle_out_of_memory_during_evacuation();
408 
409     return ShenandoahBarrierSet::resolve_forwarded(p);
410   }
411 
412   // Copy the object:
413   Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(p), copy, size);
414 
415   oop copy_val = cast_to_oop(copy);
416 
417   // Try to install the new forwarding pointer.
418   oop result = ShenandoahForwarding::try_update_forwardee(p, copy_val);
419   if (result == copy_val) {
420     // Successfully evacuated. Our copy is now the public one!
421     if (mode()->is_generational()) {
422       if (target_gen == OLD_GENERATION) {
423         handle_old_evacuation(copy, size, from_region->is_young());
424       } else if (target_gen == YOUNG_GENERATION) {
425         if (is_aging_cycle()) {
426           ShenandoahHeap::increase_object_age(copy_val, from_region->age() + 1);
427         }
428       } else {
429         ShouldNotReachHere();
430       }
431     }
432     shenandoah_assert_correct(NULL, copy_val);
433     return copy_val;
434   }  else {
435     // Failed to evacuate. We need to deal with the object that is left behind. Since this
436     // new allocation is certainly after TAMS, it will be considered live in the next cycle.
437     // But if it happens to contain references to evacuated regions, those references would
438     // not get updated for this stale copy during this cycle, and we will crash while scanning
439     // it the next cycle.
440     if (alloc_from_lab) {
441        // For LAB allocations, it is enough to rollback the allocation ptr. Either the next
442        // object will overwrite this stale copy, or the filler object on LAB retirement will
443        // do this.
444        switch (target_gen) {
445          case YOUNG_GENERATION: {
446              ShenandoahThreadLocalData::gclab(thread)->undo_allocation(copy, size);
447             break;
448          }
449          case OLD_GENERATION: {
450             ShenandoahThreadLocalData::plab(thread)->undo_allocation(copy, size);
451             break;
452          }
453          default: {
454            ShouldNotReachHere();
455            break;
456          }
457        }
458     } else {
459       // For non-LAB allocations, we have no way to retract the allocation, and
460       // have to explicitly overwrite the copy with the filler object. With that overwrite,
461       // we have to keep the fwdptr initialized and pointing to our (stale) copy.
462       fill_with_object(copy, size);
463       shenandoah_assert_correct(NULL, copy_val);
464       // For non-LAB allocations, the object has already been registered
465     }
466     shenandoah_assert_correct(NULL, result);
467     return result;
468   }
469 }
470 
471 void ShenandoahHeap::increase_object_age(oop obj, uint additional_age) {
472   markWord w = obj->has_displaced_mark() ? obj->displaced_mark() : obj->mark();
473   w = w.set_age(MIN2(markWord::max_age, w.age() + additional_age));
474   if (obj->has_displaced_mark()) {
475     obj->set_displaced_mark(w);
476   } else {
477     obj->set_mark(w);
478   }
479 }
480 
481 inline bool ShenandoahHeap::clear_old_evacuation_failure() {
482   return _old_gen_oom_evac.try_unset();
483 }
484 
485 inline bool ShenandoahHeap::is_old(oop obj) const {
486   return is_gc_generation_young() && is_in_old(obj);
487 }
488 
489 inline bool ShenandoahHeap::requires_marking(const void* entry) const {
490   oop obj = cast_to_oop(entry);
491   return !_marking_context->is_marked_strong(obj);
492 }
493 
494 inline bool ShenandoahHeap::in_collection_set(oop p) const {
495   assert(collection_set() != NULL, "Sanity");
496   return collection_set()->is_in(p);
497 }
498 
499 inline bool ShenandoahHeap::in_collection_set_loc(void* p) const {
500   assert(collection_set() != NULL, "Sanity");
501   return collection_set()->is_in_loc(p);
502 }
503 
504 inline bool ShenandoahHeap::is_stable() const {
505   return _gc_state.is_clear();
506 }
507 
508 inline bool ShenandoahHeap::is_idle() const {
509   return _gc_state.is_unset(YOUNG_MARKING | OLD_MARKING | EVACUATION | UPDATEREFS);
510 }
511 
512 inline bool ShenandoahHeap::is_concurrent_mark_in_progress() const {
513   return _gc_state.is_set(YOUNG_MARKING | OLD_MARKING);
514 }
515 
516 inline bool ShenandoahHeap::is_concurrent_young_mark_in_progress() const {
517   return _gc_state.is_set(YOUNG_MARKING);
518 }
519 
520 inline bool ShenandoahHeap::is_concurrent_old_mark_in_progress() const {
521   return _gc_state.is_set(OLD_MARKING);
522 }
523 
524 inline bool ShenandoahHeap::is_evacuation_in_progress() const {
525   return _gc_state.is_set(EVACUATION);
526 }
527 
528 inline bool ShenandoahHeap::is_gc_in_progress_mask(uint mask) const {
529   return _gc_state.is_set(mask);
530 }
531 
532 inline bool ShenandoahHeap::is_degenerated_gc_in_progress() const {
533   return _degenerated_gc_in_progress.is_set();
534 }
535 
536 inline bool ShenandoahHeap::is_full_gc_in_progress() const {
537   return _full_gc_in_progress.is_set();
538 }
539 
540 inline bool ShenandoahHeap::is_full_gc_move_in_progress() const {
541   return _full_gc_move_in_progress.is_set();
542 }
543 
544 inline bool ShenandoahHeap::is_update_refs_in_progress() const {
545   return _gc_state.is_set(UPDATEREFS);
546 }
547 
548 inline bool ShenandoahHeap::is_stw_gc_in_progress() const {
549   return is_full_gc_in_progress() || is_degenerated_gc_in_progress();
550 }
551 
552 inline bool ShenandoahHeap::is_concurrent_strong_root_in_progress() const {
553   return _concurrent_strong_root_in_progress.is_set();
554 }
555 
556 inline bool ShenandoahHeap::is_concurrent_weak_root_in_progress() const {
557   return _gc_state.is_set(WEAK_ROOTS);
558 }
559 
560 inline bool ShenandoahHeap::is_aging_cycle() const {
561   return _is_aging_cycle.is_set();
562 }
563 
564 template<class T>
565 inline void ShenandoahHeap::marked_object_iterate(ShenandoahHeapRegion* region, T* cl) {
566   marked_object_iterate(region, cl, region->top());
567 }
568 
569 template<class T>
570 inline void ShenandoahHeap::marked_object_iterate(ShenandoahHeapRegion* region, T* cl, HeapWord* limit) {
571   assert(! region->is_humongous_continuation(), "no humongous continuation regions here");
572 
573   ShenandoahMarkingContext* const ctx = marking_context();
574 
575   HeapWord* tams = ctx->top_at_mark_start(region);
576 
577   size_t skip_bitmap_delta = 1;
578   HeapWord* start = region->bottom();
579   HeapWord* end = MIN2(tams, region->end());
580 
581   // Step 1. Scan below the TAMS based on bitmap data.
582   HeapWord* limit_bitmap = MIN2(limit, tams);
583 
584   // Try to scan the initial candidate. If the candidate is above the TAMS, it would
585   // fail the subsequent "< limit_bitmap" checks, and fall through to Step 2.
586   HeapWord* cb = ctx->get_next_marked_addr(start, end);
587 
588   intx dist = ShenandoahMarkScanPrefetch;
589   if (dist > 0) {
590     // Batched scan that prefetches the oop data, anticipating the access to
591     // either header, oop field, or forwarding pointer. Not that we cannot
592     // touch anything in oop, while it still being prefetched to get enough
593     // time for prefetch to work. This is why we try to scan the bitmap linearly,
594     // disregarding the object size. However, since we know forwarding pointer
595     // preceeds the object, we can skip over it. Once we cannot trust the bitmap,
596     // there is no point for prefetching the oop contents, as oop->size() will
597     // touch it prematurely.
598 
599     // No variable-length arrays in standard C++, have enough slots to fit
600     // the prefetch distance.
601     static const int SLOT_COUNT = 256;
602     guarantee(dist <= SLOT_COUNT, "adjust slot count");
603     HeapWord* slots[SLOT_COUNT];
604 
605     int avail;
606     do {
607       avail = 0;
608       for (int c = 0; (c < dist) && (cb < limit_bitmap); c++) {
609         Prefetch::read(cb, oopDesc::mark_offset_in_bytes());
610         slots[avail++] = cb;
611         cb += skip_bitmap_delta;
612         if (cb < limit_bitmap) {
613           cb = ctx->get_next_marked_addr(cb, limit_bitmap);
614         }
615       }
616 
617       for (int c = 0; c < avail; c++) {
618         assert (slots[c] < tams,  "only objects below TAMS here: "  PTR_FORMAT " (" PTR_FORMAT ")", p2i(slots[c]), p2i(tams));
619         assert (slots[c] < limit, "only objects below limit here: " PTR_FORMAT " (" PTR_FORMAT ")", p2i(slots[c]), p2i(limit));
620         oop obj = cast_to_oop(slots[c]);
621         assert(oopDesc::is_oop(obj), "sanity");
622         assert(ctx->is_marked(obj), "object expected to be marked");
623         cl->do_object(obj);
624       }
625     } while (avail > 0);
626   } else {
627     while (cb < limit_bitmap) {
628       assert (cb < tams,  "only objects below TAMS here: "  PTR_FORMAT " (" PTR_FORMAT ")", p2i(cb), p2i(tams));
629       assert (cb < limit, "only objects below limit here: " PTR_FORMAT " (" PTR_FORMAT ")", p2i(cb), p2i(limit));
630       oop obj = cast_to_oop(cb);
631       assert(oopDesc::is_oop(obj), "sanity");
632       assert(ctx->is_marked(obj), "object expected to be marked");
633       cl->do_object(obj);
634       cb += skip_bitmap_delta;
635       if (cb < limit_bitmap) {
636         cb = ctx->get_next_marked_addr(cb, limit_bitmap);
637       }
638     }
639   }
640 
641   // Step 2. Accurate size-based traversal, happens past the TAMS.
642   // This restarts the scan at TAMS, which makes sure we traverse all objects,
643   // regardless of what happened at Step 1.
644   HeapWord* cs = tams;
645   while (cs < limit) {
646     assert (cs >= tams, "only objects past TAMS here: "   PTR_FORMAT " (" PTR_FORMAT ")", p2i(cs), p2i(tams));
647     assert (cs < limit, "only objects below limit here: " PTR_FORMAT " (" PTR_FORMAT ")", p2i(cs), p2i(limit));
648     oop obj = cast_to_oop(cs);
649     assert(oopDesc::is_oop(obj), "sanity");
650     assert(ctx->is_marked(obj), "object expected to be marked");
651     int size = obj->size();
652     cl->do_object(obj);
653     cs += size;
654   }
655 }
656 
657 template <class T>
658 class ShenandoahObjectToOopClosure : public ObjectClosure {
659   T* _cl;
660 public:
661   ShenandoahObjectToOopClosure(T* cl) : _cl(cl) {}
662 
663   void do_object(oop obj) {
664     obj->oop_iterate(_cl);
665   }
666 };
667 
668 template <class T>
669 class ShenandoahObjectToOopBoundedClosure : public ObjectClosure {
670   T* _cl;
671   MemRegion _bounds;
672 public:
673   ShenandoahObjectToOopBoundedClosure(T* cl, HeapWord* bottom, HeapWord* top) :
674     _cl(cl), _bounds(bottom, top) {}
675 
676   void do_object(oop obj) {
677     obj->oop_iterate(_cl, _bounds);
678   }
679 };
680 
681 template<class T>
682 inline void ShenandoahHeap::marked_object_oop_iterate(ShenandoahHeapRegion* region, T* cl, HeapWord* top) {
683   if (region->is_humongous()) {
684     HeapWord* bottom = region->bottom();
685     if (top > bottom) {
686       region = region->humongous_start_region();
687       ShenandoahObjectToOopBoundedClosure<T> objs(cl, bottom, top);
688       marked_object_iterate(region, &objs);
689     }
690   } else {
691     ShenandoahObjectToOopClosure<T> objs(cl);
692     marked_object_iterate(region, &objs, top);
693   }
694 }
695 
696 inline ShenandoahHeapRegion* const ShenandoahHeap::get_region(size_t region_idx) const {
697   if (region_idx < _num_regions) {
698     return _regions[region_idx];
699   } else {
700     return NULL;
701   }
702 }
703 
704 inline ShenandoahMarkingContext* ShenandoahHeap::complete_marking_context() const {
705   assert (_marking_context->is_complete()," sanity");
706   return _marking_context;
707 }
708 
709 inline ShenandoahMarkingContext* ShenandoahHeap::marking_context() const {
710   return _marking_context;
711 }
712 
713 inline void ShenandoahHeap::clear_cards_for(ShenandoahHeapRegion* region) {
714   if (mode()->is_generational()) {
715     _card_scan->mark_range_as_empty(region->bottom(), pointer_delta(region->end(), region->bottom()));
716   }
717 }
718 
719 inline void ShenandoahHeap::dirty_cards(HeapWord* start, HeapWord* end) {
720   assert(mode()->is_generational(), "Should only be used for generational mode");
721   size_t words = pointer_delta(end, start);
722   _card_scan->mark_range_as_dirty(start, words);
723 }
724 
725 inline void ShenandoahHeap::clear_cards(HeapWord* start, HeapWord* end) {
726   assert(mode()->is_generational(), "Should only be used for generational mode");
727   size_t words = pointer_delta(end, start);
728   _card_scan->mark_range_as_clean(start, words);
729 }
730 
731 inline void ShenandoahHeap::mark_card_as_dirty(void* location) {
732   if (mode()->is_generational()) {
733     _card_scan->mark_card_as_dirty((HeapWord*)location);
734   }
735 }
736 
737 #endif // SHARE_GC_SHENANDOAH_SHENANDOAHHEAP_INLINE_HPP