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