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