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