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 "classfile/javaClasses.inline.hpp"
  29 #include "gc/shared/markBitMap.inline.hpp"
  30 #include "gc/shared/threadLocalAllocBuffer.inline.hpp"
  31 #include "gc/shared/suspendibleThreadSet.hpp"
  32 #include "gc/shenandoah/shenandoahAsserts.hpp"
  33 #include "gc/shenandoah/shenandoahBarrierSet.inline.hpp"
  34 #include "gc/shenandoah/shenandoahCollectionSet.inline.hpp"
  35 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
  36 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  37 #include "gc/shenandoah/shenandoahHeap.hpp"
  38 #include "gc/shenandoah/shenandoahHeapRegionSet.inline.hpp"
  39 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  40 #include "gc/shenandoah/shenandoahControlThread.hpp"
  41 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  42 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  43 #include "oops/compressedOops.inline.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "runtime/atomic.hpp"
  46 #include "runtime/prefetch.inline.hpp"
  47 #include "runtime/thread.hpp"
  48 #include "utilities/copy.hpp"
  49 #include "utilities/globalDefinitions.hpp"
  50 
  51 inline ShenandoahHeap* ShenandoahHeap::heap() {
  52   assert(_heap != NULL, "Heap is not initialized yet");
  53   return _heap;
  54 }
  55 
  56 inline ShenandoahHeapRegion* ShenandoahRegionIterator::next() {
  57   size_t new_index = Atomic::add(&_index, (size_t) 1);
  58   // get_region() provides the bounds-check and returns NULL on OOB.
  59   return _heap->get_region(new_index - 1);
  60 }
  61 
  62 inline bool ShenandoahHeap::has_forwarded_objects() const {
  63   return _gc_state.is_set(HAS_FORWARDED);
  64 }
  65 
  66 inline WorkGang* ShenandoahHeap::workers() const {
  67   return _workers;
  68 }
  69 
  70 inline WorkGang* ShenandoahHeap::get_safepoint_workers() {
  71   return _safepoint_workers;
  72 }
  73 
  74 inline size_t ShenandoahHeap::heap_region_index_containing(const void* addr) const {
  75   uintptr_t region_start = ((uintptr_t) addr);
  76   uintptr_t index = (region_start - (uintptr_t) base()) >> ShenandoahHeapRegion::region_size_bytes_shift();
  77   assert(index < num_regions(), "Region index is in bounds: " PTR_FORMAT, p2i(addr));
  78   return index;
  79 }
  80 
  81 inline ShenandoahHeapRegion* const ShenandoahHeap::heap_region_containing(const void* addr) const {
  82   size_t index = heap_region_index_containing(addr);
  83   ShenandoahHeapRegion* const result = get_region(index);
  84   assert(addr >= result->bottom() && addr < result->end(), "Heap region contains the address: " PTR_FORMAT, p2i(addr));
  85   return result;
  86 }
  87 
  88 template <class T>
  89 inline oop ShenandoahHeap::update_with_forwarded_not_null(T* p, oop obj) {
  90   if (in_collection_set(obj)) {
  91     shenandoah_assert_forwarded_except(p, obj, is_full_gc_in_progress() || cancelled_gc() || is_degenerated_gc_in_progress());
  92     obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
  93     RawAccess<IS_NOT_NULL>::oop_store(p, obj);
  94   }
  95 #ifdef ASSERT
  96   else {
  97     shenandoah_assert_not_forwarded(p, obj);
  98   }
  99 #endif
 100   return obj;
 101 }
 102 
 103 template <class T>
 104 inline oop ShenandoahHeap::maybe_update_with_forwarded(T* p) {
 105   T o = RawAccess<>::oop_load(p);
 106   if (!CompressedOops::is_null(o)) {
 107     oop obj = CompressedOops::decode_not_null(o);
 108     return maybe_update_with_forwarded_not_null(p, obj);
 109   } else {
 110     return NULL;
 111   }
 112 }
 113 
 114 template <class T>
 115 inline oop ShenandoahHeap::evac_update_with_forwarded(T* p) {
 116   T o = RawAccess<>::oop_load(p);
 117   if (!CompressedOops::is_null(o)) {
 118     oop obj = CompressedOops::decode_not_null(o);
 119     if (in_collection_set(obj)) {
 120       oop fwd = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
 121       if (fwd == obj) {
 122         fwd = evacuate_object(obj, Thread::current());
 123       }
 124       if (fwd != obj) { // evac failure otherwise
 125         oop prev = cas_oop(fwd, p, obj);
 126         if (prev == obj) {
 127           return fwd;
 128         }
 129       }
 130     }
 131   }
 132   return NULL;
 133 }
 134 
 135 inline oop ShenandoahHeap::cas_oop(oop n, oop* addr, oop c) {
 136   assert(is_aligned(addr, HeapWordSize), "Address should be aligned: " PTR_FORMAT, p2i(addr));
 137   return (oop) Atomic::cmpxchg(addr, c, n);
 138 }
 139 
 140 inline oop ShenandoahHeap::cas_oop(oop n, narrowOop* addr, narrowOop c) {
 141   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
 142   narrowOop val = CompressedOops::encode(n);
 143   return CompressedOops::decode((narrowOop) Atomic::cmpxchg(addr, c, val));
 144 }
 145 
 146 inline oop ShenandoahHeap::cas_oop(oop n, narrowOop* addr, oop c) {
 147   assert(is_aligned(addr, sizeof(narrowOop)), "Address should be aligned: " PTR_FORMAT, p2i(addr));
 148   narrowOop cmp = CompressedOops::encode(c);
 149   narrowOop val = CompressedOops::encode(n);
 150   return CompressedOops::decode((narrowOop) Atomic::cmpxchg(addr, cmp, val));
 151 }
 152 
 153 template <class T>
 154 inline oop ShenandoahHeap::maybe_update_with_forwarded_not_null(T* p, oop heap_oop) {
 155   shenandoah_assert_not_in_cset_loc_except(p, !is_in(p) || is_full_gc_in_progress() || is_degenerated_gc_in_progress());
 156   shenandoah_assert_correct(p, heap_oop);
 157 
 158   if (in_collection_set(heap_oop)) {
 159     oop forwarded_oop = ShenandoahBarrierSet::resolve_forwarded_not_null(heap_oop);
 160     if (forwarded_oop == heap_oop) {
 161       // E.g. during evacuation.
 162       return forwarded_oop;
 163     }
 164 
 165     shenandoah_assert_forwarded_except(p, heap_oop, is_full_gc_in_progress() || is_degenerated_gc_in_progress());
 166     shenandoah_assert_not_forwarded(p, forwarded_oop);
 167     shenandoah_assert_not_in_cset_except(p, forwarded_oop, cancelled_gc());
 168 
 169     // If this fails, another thread wrote to p before us, it will be logged in SATB and the
 170     // reference be updated later.
 171     oop witness = cas_oop(forwarded_oop, p, heap_oop);
 172 
 173     if (witness != heap_oop) {
 174       // CAS failed, someone had beat us to it. Normally, we would return the failure witness,
 175       // because that would be the proper write of to-space object, enforced by strong barriers.
 176       // However, there is a corner case with arraycopy. It can happen that a Java thread
 177       // beats us with an arraycopy, which first copies the array, which potentially contains
 178       // from-space refs, and only afterwards updates all from-space refs to to-space refs,
 179       // which leaves a short window where the new array elements can be from-space.
 180       // In this case, we can just resolve the result again. As we resolve, we need to consider
 181       // the contended write might have been NULL.
 182       oop result = ShenandoahBarrierSet::resolve_forwarded(witness);
 183       shenandoah_assert_not_forwarded_except(p, result, (result == NULL));
 184       shenandoah_assert_not_in_cset_except(p, result, (result == NULL) || cancelled_gc());
 185       return result;
 186     } else {
 187       // Success! We have updated with known to-space copy. We have already asserted it is sane.
 188       return forwarded_oop;
 189     }
 190   } else {
 191     shenandoah_assert_not_forwarded(p, heap_oop);
 192     return heap_oop;
 193   }
 194 }
 195 
 196 inline bool ShenandoahHeap::cancelled_gc() const {
 197   return _cancelled_gc.get() == CANCELLED;
 198 }
 199 
 200 inline bool ShenandoahHeap::check_cancelled_gc_and_yield(bool sts_active) {
 201   if (! (sts_active && ShenandoahSuspendibleWorkers)) {
 202     return cancelled_gc();
 203   }
 204 
 205   jbyte prev = _cancelled_gc.cmpxchg(NOT_CANCELLED, CANCELLABLE);
 206   if (prev == CANCELLABLE || prev == NOT_CANCELLED) {
 207     if (SuspendibleThreadSet::should_yield()) {
 208       SuspendibleThreadSet::yield();
 209     }
 210 
 211     // Back to CANCELLABLE. The thread that poked NOT_CANCELLED first gets
 212     // to restore to CANCELLABLE.
 213     if (prev == CANCELLABLE) {
 214       _cancelled_gc.set(CANCELLABLE);
 215     }
 216     return false;
 217   } else {
 218     return true;
 219   }
 220 }
 221 
 222 inline void ShenandoahHeap::clear_cancelled_gc() {
 223   _cancelled_gc.set(CANCELLABLE);
 224   _oom_evac_handler.clear();
 225 }
 226 
 227 inline HeapWord* ShenandoahHeap::allocate_from_gclab(Thread* thread, size_t size) {
 228   assert(UseTLAB, "TLABs should be enabled");
 229 
 230   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 231   if (gclab == NULL) {
 232     assert(!thread->is_Java_thread() && !thread->is_Worker_thread(),
 233            "Performance: thread should have GCLAB: %s", thread->name());
 234     // No GCLABs in this thread, fallback to shared allocation
 235     return NULL;
 236   }
 237   HeapWord* obj = gclab->allocate(size);
 238   if (obj != NULL) {
 239     return obj;
 240   }
 241   // Otherwise...
 242   return allocate_from_gclab_slow(thread, size);
 243 }
 244 
 245 inline oop ShenandoahHeap::evacuate_object(oop p, Thread* thread) {
 246   if (ShenandoahThreadLocalData::is_oom_during_evac(Thread::current())) {
 247     // This thread went through the OOM during evac protocol and it is safe to return
 248     // the forward pointer. It must not attempt to evacuate any more.
 249     return ShenandoahBarrierSet::resolve_forwarded(p);
 250   }
 251 
 252   assert(ShenandoahThreadLocalData::is_evac_allowed(thread), "must be enclosed in oom-evac scope");
 253 
 254   size_t size = p->size();
 255 
 256   assert(!heap_region_containing(p)->is_humongous(), "never evacuate humongous objects");
 257 
 258   bool alloc_from_gclab = true;
 259   HeapWord* copy = NULL;
 260 
 261 #ifdef ASSERT
 262   if (ShenandoahOOMDuringEvacALot &&
 263       (os::random() & 1) == 0) { // Simulate OOM every ~2nd slow-path call
 264         copy = NULL;
 265   } else {
 266 #endif
 267     if (UseTLAB) {
 268       copy = allocate_from_gclab(thread, size);
 269     }
 270     if (copy == NULL) {
 271       ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared_gc(size);
 272       copy = allocate_memory(req);
 273       alloc_from_gclab = false;
 274     }
 275 #ifdef ASSERT
 276   }
 277 #endif
 278 
 279   if (copy == NULL) {
 280     control_thread()->handle_alloc_failure_evac(size);
 281 
 282     _oom_evac_handler.handle_out_of_memory_during_evacuation();
 283 
 284     return ShenandoahBarrierSet::resolve_forwarded(p);
 285   }
 286 
 287   // Copy the object:
 288   Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(p), copy, size);
 289 
 290   // Try to install the new forwarding pointer.
 291   oop copy_val = oop(copy);
 292   oop result = ShenandoahForwarding::try_update_forwardee(p, copy_val);
 293   if (result == copy_val) {
 294     // Successfully evacuated. Our copy is now the public one!
 295     shenandoah_assert_correct(NULL, copy_val);
 296     return copy_val;
 297   }  else {
 298     // Failed to evacuate. We need to deal with the object that is left behind. Since this
 299     // new allocation is certainly after TAMS, it will be considered live in the next cycle.
 300     // But if it happens to contain references to evacuated regions, those references would
 301     // not get updated for this stale copy during this cycle, and we will crash while scanning
 302     // it the next cycle.
 303     //
 304     // For GCLAB allocations, it is enough to rollback the allocation ptr. Either the next
 305     // object will overwrite this stale copy, or the filler object on LAB retirement will
 306     // do this. For non-GCLAB allocations, we have no way to retract the allocation, and
 307     // have to explicitly overwrite the copy with the filler object. With that overwrite,
 308     // we have to keep the fwdptr initialized and pointing to our (stale) copy.
 309     if (alloc_from_gclab) {
 310       ShenandoahThreadLocalData::gclab(thread)->undo_allocation(copy, size);
 311     } else {
 312       fill_with_object(copy, size);
 313       shenandoah_assert_correct(NULL, copy_val);
 314     }
 315     shenandoah_assert_correct(NULL, result);
 316     return result;
 317   }
 318 }
 319 
 320 template<bool RESOLVE>
 321 inline bool ShenandoahHeap::requires_marking(const void* entry) const {
 322   oop obj = oop(entry);
 323   if (RESOLVE) {
 324     obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
 325   }
 326   return !_marking_context->is_marked(obj);
 327 }
 328 
 329 inline bool ShenandoahHeap::in_collection_set(oop p) const {
 330   assert(collection_set() != NULL, "Sanity");
 331   return collection_set()->is_in(p);
 332 }
 333 
 334 inline bool ShenandoahHeap::in_collection_set_loc(void* p) const {
 335   assert(collection_set() != NULL, "Sanity");
 336   return collection_set()->is_in_loc(p);
 337 }
 338 
 339 inline bool ShenandoahHeap::is_stable() const {
 340   return _gc_state.is_clear();
 341 }
 342 
 343 inline bool ShenandoahHeap::is_idle() const {
 344   return _gc_state.is_unset(MARKING | EVACUATION | UPDATEREFS);
 345 }
 346 
 347 inline bool ShenandoahHeap::is_concurrent_mark_in_progress() const {
 348   return _gc_state.is_set(MARKING);
 349 }
 350 
 351 inline bool ShenandoahHeap::is_evacuation_in_progress() const {
 352   return _gc_state.is_set(EVACUATION);
 353 }
 354 
 355 inline bool ShenandoahHeap::is_gc_in_progress_mask(uint mask) const {
 356   return _gc_state.is_set(mask);
 357 }
 358 
 359 inline bool ShenandoahHeap::is_degenerated_gc_in_progress() const {
 360   return _degenerated_gc_in_progress.is_set();
 361 }
 362 
 363 inline bool ShenandoahHeap::is_full_gc_in_progress() const {
 364   return _full_gc_in_progress.is_set();
 365 }
 366 
 367 inline bool ShenandoahHeap::is_full_gc_move_in_progress() const {
 368   return _full_gc_move_in_progress.is_set();
 369 }
 370 
 371 inline bool ShenandoahHeap::is_update_refs_in_progress() const {
 372   return _gc_state.is_set(UPDATEREFS);
 373 }
 374 
 375 inline bool ShenandoahHeap::is_stw_gc_in_progress() const {
 376   return is_full_gc_in_progress() || is_degenerated_gc_in_progress();
 377 }
 378 
 379 inline bool ShenandoahHeap::is_concurrent_strong_root_in_progress() const {
 380   return _concurrent_strong_root_in_progress.is_set();
 381 }
 382 
 383 inline bool ShenandoahHeap::is_concurrent_weak_root_in_progress() const {
 384   return _concurrent_weak_root_in_progress.is_set();
 385 }
 386 
 387 template<class T>
 388 inline void ShenandoahHeap::marked_object_iterate(ShenandoahHeapRegion* region, T* cl) {
 389   marked_object_iterate(region, cl, region->top());
 390 }
 391 
 392 template<class T>
 393 inline void ShenandoahHeap::marked_object_iterate(ShenandoahHeapRegion* region, T* cl, HeapWord* limit) {
 394   assert(! region->is_humongous_continuation(), "no humongous continuation regions here");
 395 
 396   ShenandoahMarkingContext* const ctx = complete_marking_context();
 397   assert(ctx->is_complete(), "sanity");
 398 
 399   MarkBitMap* mark_bit_map = ctx->mark_bit_map();
 400   HeapWord* tams = ctx->top_at_mark_start(region);
 401 
 402   size_t skip_bitmap_delta = 1;
 403   HeapWord* start = region->bottom();
 404   HeapWord* end = MIN2(tams, region->end());
 405 
 406   // Step 1. Scan below the TAMS based on bitmap data.
 407   HeapWord* limit_bitmap = MIN2(limit, tams);
 408 
 409   // Try to scan the initial candidate. If the candidate is above the TAMS, it would
 410   // fail the subsequent "< limit_bitmap" checks, and fall through to Step 2.
 411   HeapWord* cb = mark_bit_map->get_next_marked_addr(start, end);
 412 
 413   intx dist = ShenandoahMarkScanPrefetch;
 414   if (dist > 0) {
 415     // Batched scan that prefetches the oop data, anticipating the access to
 416     // either header, oop field, or forwarding pointer. Not that we cannot
 417     // touch anything in oop, while it still being prefetched to get enough
 418     // time for prefetch to work. This is why we try to scan the bitmap linearly,
 419     // disregarding the object size. However, since we know forwarding pointer
 420     // preceeds the object, we can skip over it. Once we cannot trust the bitmap,
 421     // there is no point for prefetching the oop contents, as oop->size() will
 422     // touch it prematurely.
 423 
 424     // No variable-length arrays in standard C++, have enough slots to fit
 425     // the prefetch distance.
 426     static const int SLOT_COUNT = 256;
 427     guarantee(dist <= SLOT_COUNT, "adjust slot count");
 428     HeapWord* slots[SLOT_COUNT];
 429 
 430     int avail;
 431     do {
 432       avail = 0;
 433       for (int c = 0; (c < dist) && (cb < limit_bitmap); c++) {
 434         Prefetch::read(cb, oopDesc::mark_offset_in_bytes());
 435         slots[avail++] = cb;
 436         cb += skip_bitmap_delta;
 437         if (cb < limit_bitmap) {
 438           cb = mark_bit_map->get_next_marked_addr(cb, limit_bitmap);
 439         }
 440       }
 441 
 442       for (int c = 0; c < avail; c++) {
 443         assert (slots[c] < tams,  "only objects below TAMS here: "  PTR_FORMAT " (" PTR_FORMAT ")", p2i(slots[c]), p2i(tams));
 444         assert (slots[c] < limit, "only objects below limit here: " PTR_FORMAT " (" PTR_FORMAT ")", p2i(slots[c]), p2i(limit));
 445         oop obj = oop(slots[c]);
 446         assert(oopDesc::is_oop(obj), "sanity");
 447         assert(ctx->is_marked(obj), "object expected to be marked");
 448         cl->do_object(obj);
 449       }
 450     } while (avail > 0);
 451   } else {
 452     while (cb < limit_bitmap) {
 453       assert (cb < tams,  "only objects below TAMS here: "  PTR_FORMAT " (" PTR_FORMAT ")", p2i(cb), p2i(tams));
 454       assert (cb < limit, "only objects below limit here: " PTR_FORMAT " (" PTR_FORMAT ")", p2i(cb), p2i(limit));
 455       oop obj = oop(cb);
 456       assert(oopDesc::is_oop(obj), "sanity");
 457       assert(ctx->is_marked(obj), "object expected to be marked");
 458       cl->do_object(obj);
 459       cb += skip_bitmap_delta;
 460       if (cb < limit_bitmap) {
 461         cb = mark_bit_map->get_next_marked_addr(cb, limit_bitmap);
 462       }
 463     }
 464   }
 465 
 466   // Step 2. Accurate size-based traversal, happens past the TAMS.
 467   // This restarts the scan at TAMS, which makes sure we traverse all objects,
 468   // regardless of what happened at Step 1.
 469   HeapWord* cs = tams;
 470   while (cs < limit) {
 471     assert (cs >= tams, "only objects past TAMS here: "   PTR_FORMAT " (" PTR_FORMAT ")", p2i(cs), p2i(tams));
 472     assert (cs < limit, "only objects below limit here: " PTR_FORMAT " (" PTR_FORMAT ")", p2i(cs), p2i(limit));
 473     oop obj = oop(cs);
 474     assert(oopDesc::is_oop(obj), "sanity");
 475     assert(ctx->is_marked(obj), "object expected to be marked");
 476     int size = obj->size();
 477     cl->do_object(obj);
 478     cs += size;
 479   }
 480 }
 481 
 482 inline ShenandoahHeapRegion* const ShenandoahHeap::get_region(size_t region_idx) const {
 483   if (region_idx < _num_regions) {
 484     return _regions[region_idx];
 485   } else {
 486     return NULL;
 487   }
 488 }
 489 
 490 inline void ShenandoahHeap::mark_complete_marking_context() {
 491   _marking_context->mark_complete();
 492 }
 493 
 494 inline void ShenandoahHeap::mark_incomplete_marking_context() {
 495   _marking_context->mark_incomplete();
 496 }
 497 
 498 inline ShenandoahMarkingContext* ShenandoahHeap::complete_marking_context() const {
 499   assert (_marking_context->is_complete()," sanity");
 500   return _marking_context;
 501 }
 502 
 503 inline ShenandoahMarkingContext* ShenandoahHeap::marking_context() const {
 504   return _marking_context;
 505 }
 506 
 507 #endif // SHARE_GC_SHENANDOAH_SHENANDOAHHEAP_INLINE_HPP