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