< prev index next >

src/hotspot/share/gc/shenandoah/shenandoahVerifier.cpp

Print this page

   1 /*
   2  * Copyright (c) 2017, 2021, 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 #include "precompiled.hpp"
  26 #include "gc/shared/tlab_globals.hpp"
  27 #include "gc/shenandoah/shenandoahAsserts.hpp"
  28 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
  29 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"

  30 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  31 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"

  32 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  33 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp"
  34 #include "gc/shenandoah/shenandoahUtils.hpp"
  35 #include "gc/shenandoah/shenandoahVerifier.hpp"

  36 #include "memory/allocation.hpp"
  37 #include "memory/iterator.inline.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/compressedOops.inline.hpp"
  40 #include "runtime/atomic.hpp"
  41 #include "runtime/orderAccess.hpp"
  42 #include "runtime/threads.hpp"
  43 #include "utilities/align.hpp"
  44 
  45 // Avoid name collision on verify_oop (defined in macroAssembler_arm.hpp)
  46 #ifdef verify_oop
  47 #undef verify_oop
  48 #endif
  49 
  50 static bool is_instance_ref_klass(Klass* k) {
  51   return k->is_instance_klass() && InstanceKlass::cast(k)->reference_type() != REF_NONE;
  52 }
  53 
  54 class ShenandoahIgnoreReferenceDiscoverer : public ReferenceDiscoverer {
  55 public:
  56   virtual bool discover_reference(oop obj, ReferenceType type) {
  57     return true;
  58   }
  59 };
  60 
  61 class ShenandoahVerifyOopClosure : public BasicOopIterateClosure {
  62 private:
  63   const char* _phase;
  64   ShenandoahVerifier::VerifyOptions _options;
  65   ShenandoahVerifierStack* _stack;
  66   ShenandoahHeap* _heap;
  67   MarkBitMap* _map;
  68   ShenandoahLivenessData* _ld;
  69   void* _interior_loc;
  70   oop _loc;

  71 
  72 public:
  73   ShenandoahVerifyOopClosure(ShenandoahVerifierStack* stack, MarkBitMap* map, ShenandoahLivenessData* ld,
  74                              const char* phase, ShenandoahVerifier::VerifyOptions options) :
  75     _phase(phase),
  76     _options(options),
  77     _stack(stack),
  78     _heap(ShenandoahHeap::heap()),
  79     _map(map),
  80     _ld(ld),
  81     _interior_loc(nullptr),
  82     _loc(nullptr) {

  83     if (options._verify_marked == ShenandoahVerifier::_verify_marked_complete_except_references ||
  84         options._verify_marked == ShenandoahVerifier::_verify_marked_disable) {
  85       set_ref_discoverer_internal(new ShenandoahIgnoreReferenceDiscoverer());
  86     }





  87   }
  88 
  89 private:
  90   void check(ShenandoahAsserts::SafeLevel level, oop obj, bool test, const char* label) {
  91     if (!test) {
  92       ShenandoahAsserts::print_failure(level, obj, _interior_loc, _loc, _phase, label, __FILE__, __LINE__);
  93     }
  94   }
  95 
  96   template <class T>
  97   void do_oop_work(T* p) {
  98     T o = RawAccess<>::oop_load(p);
  99     if (!CompressedOops::is_null(o)) {
 100       oop obj = CompressedOops::decode_not_null(o);
 101       if (is_instance_ref_klass(obj->klass())) {
 102         obj = ShenandoahForwarding::get_forwardee(obj);
 103       }
 104       // Single threaded verification can use faster non-atomic stack and bitmap
 105       // methods.
 106       //
 107       // For performance reasons, only fully verify non-marked field values.
 108       // We are here when the host object for *p is already marked.
 109 
 110       if (_map->par_mark(obj)) {


 111         verify_oop_at(p, obj);
 112         _stack->push(ShenandoahVerifierTask(obj));
 113       }
 114     }
 115   }
 116 









 117   void verify_oop(oop obj) {
 118     // Perform consistency checks with gradually decreasing safety level. This guarantees
 119     // that failure report would not try to touch something that was not yet verified to be
 120     // safe to process.
 121 
 122     check(ShenandoahAsserts::_safe_unknown, obj, _heap->is_in(obj),
 123               "oop must be in heap");
 124     check(ShenandoahAsserts::_safe_unknown, obj, is_object_aligned(obj),
 125               "oop must be aligned");
 126 
 127     ShenandoahHeapRegion *obj_reg = _heap->heap_region_containing(obj);
 128     Klass* obj_klass = obj->klass_or_null();
 129 
 130     // Verify that obj is not in dead space:
 131     {
 132       // Do this before touching obj->size()
 133       check(ShenandoahAsserts::_safe_unknown, obj, obj_klass != nullptr,
 134              "Object klass pointer should not be null");
 135       check(ShenandoahAsserts::_safe_unknown, obj, Metaspace::contains(obj_klass),
 136              "Object klass pointer must go to metaspace");

 147         size_t humongous_end = humongous_start + (obj->size() >> ShenandoahHeapRegion::region_size_words_shift());
 148         for (size_t idx = humongous_start + 1; idx < humongous_end; idx++) {
 149           check(ShenandoahAsserts::_safe_unknown, obj, _heap->get_region(idx)->is_humongous_continuation(),
 150                  "Humongous object is in continuation that fits it");
 151         }
 152       }
 153 
 154       // ------------ obj is safe at this point --------------
 155 
 156       check(ShenandoahAsserts::_safe_oop, obj, obj_reg->is_active(),
 157             "Object should be in active region");
 158 
 159       switch (_options._verify_liveness) {
 160         case ShenandoahVerifier::_verify_liveness_disable:
 161           // skip
 162           break;
 163         case ShenandoahVerifier::_verify_liveness_complete:
 164           Atomic::add(&_ld[obj_reg->index()], (uint) obj->size(), memory_order_relaxed);
 165           // fallthrough for fast failure for un-live regions:
 166         case ShenandoahVerifier::_verify_liveness_conservative:
 167           check(ShenandoahAsserts::_safe_oop, obj, obj_reg->has_live(),

 168                    "Object must belong to region with live data");
 169           break;
 170         default:
 171           assert(false, "Unhandled liveness verification");
 172       }
 173     }
 174 
 175     oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
 176 
 177     ShenandoahHeapRegion* fwd_reg = nullptr;
 178 
 179     if (obj != fwd) {
 180       check(ShenandoahAsserts::_safe_oop, obj, _heap->is_in(fwd),
 181              "Forwardee must be in heap");
 182       check(ShenandoahAsserts::_safe_oop, obj, !CompressedOops::is_null(fwd),
 183              "Forwardee is set");
 184       check(ShenandoahAsserts::_safe_oop, obj, is_object_aligned(fwd),
 185              "Forwardee must be aligned");
 186 
 187       // Do this before touching fwd->size()

 196       fwd_reg = _heap->heap_region_containing(fwd);
 197 
 198       // Verify that forwardee is not in the dead space:
 199       check(ShenandoahAsserts::_safe_oop, obj, !fwd_reg->is_humongous(),
 200              "Should have no humongous forwardees");
 201 
 202       HeapWord *fwd_addr = cast_from_oop<HeapWord *>(fwd);
 203       check(ShenandoahAsserts::_safe_oop, obj, fwd_addr < fwd_reg->top(),
 204              "Forwardee start should be within the region");
 205       check(ShenandoahAsserts::_safe_oop, obj, (fwd_addr + fwd->size()) <= fwd_reg->top(),
 206              "Forwardee end should be within the region");
 207 
 208       oop fwd2 = ShenandoahForwarding::get_forwardee_raw_unchecked(fwd);
 209       check(ShenandoahAsserts::_safe_oop, obj, (fwd == fwd2),
 210              "Double forwarding");
 211     } else {
 212       fwd_reg = obj_reg;
 213     }
 214 
 215     // ------------ obj and fwd are safe at this point --------------
 216 







 217     switch (_options._verify_marked) {
 218       case ShenandoahVerifier::_verify_marked_disable:
 219         // skip
 220         break;
 221       case ShenandoahVerifier::_verify_marked_incomplete:
 222         check(ShenandoahAsserts::_safe_all, obj, _heap->marking_context()->is_marked(obj),
 223                "Must be marked in incomplete bitmap");
 224         break;
 225       case ShenandoahVerifier::_verify_marked_complete:
 226         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
 227                "Must be marked in complete bitmap");
 228         break;
 229       case ShenandoahVerifier::_verify_marked_complete_except_references:
 230         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
 231               "Must be marked in complete bitmap, except j.l.r.Reference referents");
 232         break;
 233       default:
 234         assert(false, "Unhandled mark verification");
 235     }
 236 
 237     switch (_options._verify_forwarded) {
 238       case ShenandoahVerifier::_verify_forwarded_disable:
 239         // skip
 240         break;
 241       case ShenandoahVerifier::_verify_forwarded_none: {
 242         check(ShenandoahAsserts::_safe_all, obj, (obj == fwd),
 243                "Should not be forwarded");
 244         break;
 245       }
 246       case ShenandoahVerifier::_verify_forwarded_allow: {
 247         if (obj != fwd) {
 248           check(ShenandoahAsserts::_safe_all, obj, obj_reg != fwd_reg,
 249                  "Forwardee should be in another region");
 250         }

 296   void verify_oop_standalone(oop obj) {
 297     _interior_loc = nullptr;
 298     verify_oop(obj);
 299     _interior_loc = nullptr;
 300   }
 301 
 302   /**
 303    * Verify oop fields from this object.
 304    * @param obj host object for verified fields
 305    */
 306   void verify_oops_from(oop obj) {
 307     _loc = obj;
 308     obj->oop_iterate(this);
 309     _loc = nullptr;
 310   }
 311 
 312   virtual void do_oop(oop* p) { do_oop_work(p); }
 313   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 314 };
 315 


 316 class ShenandoahCalculateRegionStatsClosure : public ShenandoahHeapRegionClosure {
 317 private:
 318   size_t _used, _committed, _garbage;
 319 public:
 320   ShenandoahCalculateRegionStatsClosure() : _used(0), _committed(0), _garbage(0) {};
 321 
 322   void heap_region_do(ShenandoahHeapRegion* r) {
 323     _used += r->used();
 324     _garbage += r->garbage();
 325     _committed += r->is_committed() ? ShenandoahHeapRegion::region_size_bytes() : 0;






 326   }
 327 
 328   size_t used() { return _used; }
 329   size_t committed() { return _committed; }
 330   size_t garbage() { return _garbage; }







































































 331 };
 332 
 333 class ShenandoahVerifyHeapRegionClosure : public ShenandoahHeapRegionClosure {
 334 private:
 335   ShenandoahHeap* _heap;
 336   const char* _phase;
 337   ShenandoahVerifier::VerifyRegions _regions;
 338 public:
 339   ShenandoahVerifyHeapRegionClosure(const char* phase, ShenandoahVerifier::VerifyRegions regions) :
 340     _heap(ShenandoahHeap::heap()),
 341     _phase(phase),
 342     _regions(regions) {};
 343 
 344   void print_failure(ShenandoahHeapRegion* r, const char* label) {
 345     ResourceMark rm;
 346 
 347     ShenandoahMessageBuffer msg("Shenandoah verification failed; %s: %s\n\n", _phase, label);
 348 
 349     stringStream ss;
 350     r->print_on(&ss);

 394            "Complete TAMS should not be larger than top");
 395 
 396     verify(r, r->get_live_data_bytes() <= r->capacity(),
 397            "Live data cannot be larger than capacity");
 398 
 399     verify(r, r->garbage() <= r->capacity(),
 400            "Garbage cannot be larger than capacity");
 401 
 402     verify(r, r->used() <= r->capacity(),
 403            "Used cannot be larger than capacity");
 404 
 405     verify(r, r->get_shared_allocs() <= r->capacity(),
 406            "Shared alloc count should not be larger than capacity");
 407 
 408     verify(r, r->get_tlab_allocs() <= r->capacity(),
 409            "TLAB alloc count should not be larger than capacity");
 410 
 411     verify(r, r->get_gclab_allocs() <= r->capacity(),
 412            "GCLAB alloc count should not be larger than capacity");
 413 
 414     verify(r, r->get_shared_allocs() + r->get_tlab_allocs() + r->get_gclab_allocs() == r->used(),
 415            "Accurate accounting: shared + TLAB + GCLAB = used");



 416 
 417     verify(r, !r->is_empty() || !r->has_live(),
 418            "Empty regions should not have live data");
 419 
 420     verify(r, r->is_cset() == _heap->collection_set()->is_in(r),
 421            "Transitional: region flags and collection set agree");
 422   }
 423 };
 424 
 425 class ShenandoahVerifierReachableTask : public WorkerTask {
 426 private:
 427   const char* _label;
 428   ShenandoahVerifier::VerifyOptions _options;
 429   ShenandoahHeap* _heap;
 430   ShenandoahLivenessData* _ld;
 431   MarkBitMap* _bitmap;
 432   volatile size_t _processed;
 433 
 434 public:
 435   ShenandoahVerifierReachableTask(MarkBitMap* bitmap,

 477       while (!stack.is_empty()) {
 478         processed++;
 479         ShenandoahVerifierTask task = stack.pop();
 480         cl.verify_oops_from(task.obj());
 481       }
 482     }
 483 
 484     Atomic::add(&_processed, processed, memory_order_relaxed);
 485   }
 486 };
 487 
 488 class ShenandoahVerifierMarkedRegionTask : public WorkerTask {
 489 private:
 490   const char* _label;
 491   ShenandoahVerifier::VerifyOptions _options;
 492   ShenandoahHeap *_heap;
 493   MarkBitMap* _bitmap;
 494   ShenandoahLivenessData* _ld;
 495   volatile size_t _claimed;
 496   volatile size_t _processed;

 497 
 498 public:
 499   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
 500                                      ShenandoahLivenessData* ld,
 501                                      const char* label,
 502                                      ShenandoahVerifier::VerifyOptions options) :
 503           WorkerTask("Shenandoah Verifier Marked Objects"),
 504           _label(label),
 505           _options(options),
 506           _heap(ShenandoahHeap::heap()),
 507           _bitmap(bitmap),
 508           _ld(ld),
 509           _claimed(0),
 510           _processed(0) {};






 511 
 512   size_t processed() {
 513     return Atomic::load(&_processed);
 514   }
 515 
 516   virtual void work(uint worker_id) {
 517     ShenandoahVerifierStack stack;
 518     ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 519                                   ShenandoahMessageBuffer("%s, Marked", _label),
 520                                   _options);
 521 
 522     while (true) {
 523       size_t v = Atomic::fetch_then_add(&_claimed, 1u, memory_order_relaxed);
 524       if (v < _heap->num_regions()) {
 525         ShenandoahHeapRegion* r = _heap->get_region(v);




 526         if (!r->is_humongous() && !r->is_trash()) {
 527           work_regular(r, stack, cl);
 528         } else if (r->is_humongous_start()) {
 529           work_humongous(r, stack, cl);
 530         }
 531       } else {
 532         break;
 533       }
 534     }
 535   }
 536 




 537   virtual void work_humongous(ShenandoahHeapRegion *r, ShenandoahVerifierStack& stack, ShenandoahVerifyOopClosure& cl) {
 538     size_t processed = 0;
 539     HeapWord* obj = r->bottom();
 540     if (_heap->complete_marking_context()->is_marked(cast_to_oop(obj))) {
 541       verify_and_follow(obj, stack, cl, &processed);
 542     }
 543     Atomic::add(&_processed, processed, memory_order_relaxed);
 544   }
 545 
 546   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
 547     size_t processed = 0;
 548     ShenandoahMarkingContext* ctx = _heap->complete_marking_context();
 549     HeapWord* tams = ctx->top_at_mark_start(r);
 550 
 551     // Bitmaps, before TAMS
 552     if (tams > r->bottom()) {
 553       HeapWord* start = r->bottom();
 554       HeapWord* addr = ctx->get_next_marked_addr(start, tams);
 555 
 556       while (addr < tams) {

 589       cl.verify_oops_from(obj);
 590       (*processed)++;
 591     }
 592     while (!stack.is_empty()) {
 593       ShenandoahVerifierTask task = stack.pop();
 594       cl.verify_oops_from(task.obj());
 595       (*processed)++;
 596     }
 597   }
 598 };
 599 
 600 class VerifyThreadGCState : public ThreadClosure {
 601 private:
 602   const char* const _label;
 603          char const _expected;
 604 
 605 public:
 606   VerifyThreadGCState(const char* label, char expected) : _label(label), _expected(expected) {}
 607   void do_thread(Thread* t) {
 608     char actual = ShenandoahThreadLocalData::gc_state(t);
 609     if (actual != _expected) {
 610       fatal("%s: Thread %s: expected gc-state %d, actual %d", _label, t->name(), _expected, actual);
 611     }
 612   }







 613 };
 614 
 615 void ShenandoahVerifier::verify_at_safepoint(const char *label,

 616                                              VerifyForwarded forwarded, VerifyMarked marked,
 617                                              VerifyCollectionSet cset,
 618                                              VerifyLiveness liveness, VerifyRegions regions,

 619                                              VerifyGCState gcstate) {
 620   guarantee(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "only when nothing else happens");
 621   guarantee(ShenandoahVerify, "only when enabled, and bitmap is initialized in ShenandoahHeap::initialize");
 622 
 623   // Avoid side-effect of changing workers' active thread count, but bypass concurrent/parallel protocol check
 624   ShenandoahPushWorkerScope verify_worker_scope(_heap->workers(), _heap->max_workers(), false /*bypass check*/);
 625 
 626   log_info(gc,start)("Verify %s, Level " INTX_FORMAT, label, ShenandoahVerifyLevel);
 627 
 628   // GC state checks
 629   {
 630     char expected = -1;
 631     bool enabled;
 632     switch (gcstate) {
 633       case _verify_gcstate_disable:
 634         enabled = false;
 635         break;
 636       case _verify_gcstate_forwarded:
 637         enabled = true;
 638         expected = ShenandoahHeap::HAS_FORWARDED;
 639         break;
 640       case _verify_gcstate_evacuation:
 641         enabled = true;
 642         expected = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::EVACUATION;
 643         if (!_heap->is_stw_gc_in_progress()) {
 644           // Only concurrent GC sets this.
 645           expected |= ShenandoahHeap::WEAK_ROOTS;
 646         }
 647         break;




 648       case _verify_gcstate_stable:
 649         enabled = true;
 650         expected = ShenandoahHeap::STABLE;
 651         break;
 652       case _verify_gcstate_stable_weakroots:
 653         enabled = true;
 654         expected = ShenandoahHeap::STABLE;
 655         if (!_heap->is_stw_gc_in_progress()) {
 656           // Only concurrent GC sets this.
 657           expected |= ShenandoahHeap::WEAK_ROOTS;
 658         }
 659         break;
 660       default:
 661         enabled = false;
 662         assert(false, "Unhandled gc-state verification");
 663     }
 664 
 665     if (enabled) {
 666       char actual = _heap->gc_state();
 667       if (actual != expected) {

 668         fatal("%s: Global gc-state: expected %d, actual %d", label, expected, actual);
 669       }
 670 
 671       VerifyThreadGCState vtgcs(label, expected);
 672       Threads::java_threads_do(&vtgcs);
 673     }
 674   }
 675 
 676   // Deactivate barriers temporarily: Verifier wants plain heap accesses
 677   ShenandoahGCStateResetter resetter;
 678 
 679   // Heap size checks
 680   {
 681     ShenandoahHeapLocker lock(_heap->lock());
 682 
 683     ShenandoahCalculateRegionStatsClosure cl;
 684     _heap->heap_region_iterate(&cl);
 685     size_t heap_used = _heap->used();
 686     guarantee(cl.used() == heap_used,
 687               "%s: heap used size must be consistent: heap-used = " SIZE_FORMAT "%s, regions-used = " SIZE_FORMAT "%s",
 688               label,
 689               byte_size_in_proper_unit(heap_used), proper_unit_for_byte_size(heap_used),
 690               byte_size_in_proper_unit(cl.used()), proper_unit_for_byte_size(cl.used()));
 691 







 692     size_t heap_committed = _heap->committed();
 693     guarantee(cl.committed() == heap_committed,
 694               "%s: heap committed size must be consistent: heap-committed = " SIZE_FORMAT "%s, regions-committed = " SIZE_FORMAT "%s",
 695               label,
 696               byte_size_in_proper_unit(heap_committed), proper_unit_for_byte_size(heap_committed),
 697               byte_size_in_proper_unit(cl.committed()), proper_unit_for_byte_size(cl.committed()));
 698   }
 699 






















































 700   // Internal heap region checks
 701   if (ShenandoahVerifyLevel >= 1) {
 702     ShenandoahVerifyHeapRegionClosure cl(label, regions);
 703     _heap->heap_region_iterate(&cl);




 704   }
 705 


 706   OrderAccess::fence();
 707 
 708   if (UseTLAB) {
 709     _heap->labs_make_parsable();
 710   }
 711 
 712   // Allocate temporary bitmap for storing marking wavefront:
 713   _verification_bit_map->clear();
 714 
 715   // Allocate temporary array for storing liveness data
 716   ShenandoahLivenessData* ld = NEW_C_HEAP_ARRAY(ShenandoahLivenessData, _heap->num_regions(), mtGC);
 717   Copy::fill_to_bytes((void*)ld, _heap->num_regions()*sizeof(ShenandoahLivenessData), 0);
 718 
 719   const VerifyOptions& options = ShenandoahVerifier::VerifyOptions(forwarded, marked, cset, liveness, regions, gcstate);
 720 
 721   // Steps 1-2. Scan root set to get initial reachable set. Finish walking the reachable heap.
 722   // This verifies what application can see, since it only cares about reachable objects.
 723   size_t count_reachable = 0;
 724   if (ShenandoahVerifyLevel >= 2) {
 725     ShenandoahVerifierReachableTask task(_verification_bit_map, ld, label, options);
 726     _heap->workers()->run_task(&task);
 727     count_reachable = task.processed();
 728   }
 729 


 730   // Step 3. Walk marked objects. Marked objects might be unreachable. This verifies what collector,
 731   // not the application, can see during the region scans. There is no reason to process the objects
 732   // that were already verified, e.g. those marked in verification bitmap. There is interaction with TAMS:
 733   // before TAMS, we verify the bitmaps, if available; after TAMS, we walk until the top(). It mimics
 734   // what marked_object_iterate is doing, without calling into that optimized (and possibly incorrect)
 735   // version
 736 
 737   size_t count_marked = 0;
 738   if (ShenandoahVerifyLevel >= 4 && (marked == _verify_marked_complete || marked == _verify_marked_complete_except_references)) {
 739     guarantee(_heap->marking_context()->is_complete(), "Marking context should be complete");
 740     ShenandoahVerifierMarkedRegionTask task(_verification_bit_map, ld, label, options);
 741     _heap->workers()->run_task(&task);
 742     count_marked = task.processed();
 743   } else {
 744     guarantee(ShenandoahVerifyLevel < 4 || marked == _verify_marked_incomplete || marked == _verify_marked_disable, "Should be");
 745   }
 746 


 747   // Step 4. Verify accumulated liveness data, if needed. Only reliable if verification level includes
 748   // marked objects.
 749 
 750   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete && liveness == _verify_liveness_complete) {
 751     for (size_t i = 0; i < _heap->num_regions(); i++) {
 752       ShenandoahHeapRegion* r = _heap->get_region(i);



 753 
 754       juint verf_live = 0;
 755       if (r->is_humongous()) {
 756         // For humongous objects, test if start region is marked live, and if so,
 757         // all humongous regions in that chain have live data equal to their "used".
 758         juint start_live = Atomic::load(&ld[r->humongous_start_region()->index()]);
 759         if (start_live > 0) {
 760           verf_live = (juint)(r->used() / HeapWordSize);
 761         }
 762       } else {
 763         verf_live = Atomic::load(&ld[r->index()]);
 764       }
 765 
 766       size_t reg_live = r->get_live_data_words();
 767       if (reg_live != verf_live) {
 768         stringStream ss;
 769         r->print_on(&ss);
 770         fatal("%s: Live data should match: region-live = " SIZE_FORMAT ", verifier-live = " UINT32_FORMAT "\n%s",
 771               label, reg_live, verf_live, ss.freeze());
 772       }
 773     }
 774   }
 775 



 776   log_info(gc)("Verify %s, Level " INTX_FORMAT " (" SIZE_FORMAT " reachable, " SIZE_FORMAT " marked)",
 777                label, ShenandoahVerifyLevel, count_reachable, count_marked);
 778 
 779   FREE_C_HEAP_ARRAY(ShenandoahLivenessData, ld);
 780 }
 781 
 782 void ShenandoahVerifier::verify_generic(VerifyOption vo) {
 783   verify_at_safepoint(
 784           "Generic Verification",

 785           _verify_forwarded_allow,     // conservatively allow forwarded
 786           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 787           _verify_cset_disable,        // cset may be inconsistent
 788           _verify_liveness_disable,    // no reliable liveness data
 789           _verify_regions_disable,     // no reliable region data

 790           _verify_gcstate_disable      // no data about gcstate
 791   );
 792 }
 793 
 794 void ShenandoahVerifier::verify_before_concmark() {
 795     verify_at_safepoint(
 796           "Before Mark",


 797           _verify_forwarded_none,      // UR should have fixed up
 798           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 799           _verify_cset_none,           // UR should have fixed this
 800           _verify_liveness_disable,    // no reliable liveness data
 801           _verify_regions_notrash,     // no trash regions

 802           _verify_gcstate_stable       // there are no forwarded objects
 803   );
 804 }
 805 
 806 void ShenandoahVerifier::verify_after_concmark() {
 807   verify_at_safepoint(
 808           "After Mark",

 809           _verify_forwarded_none,      // no forwarded references
 810           _verify_marked_complete_except_references, // bitmaps as precise as we can get, except dangling j.l.r.Refs

 811           _verify_cset_none,           // no references to cset anymore
 812           _verify_liveness_complete,   // liveness data must be complete here
 813           _verify_regions_disable,     // trash regions not yet recycled

 814           _verify_gcstate_stable_weakroots  // heap is still stable, weakroots are in progress
 815   );
 816 }
 817 
 818 void ShenandoahVerifier::verify_before_evacuation() {
 819   verify_at_safepoint(
 820           "Before Evacuation",

 821           _verify_forwarded_none,                    // no forwarded references
 822           _verify_marked_complete_except_references, // walk over marked objects too
 823           _verify_cset_disable,                      // non-forwarded references to cset expected
 824           _verify_liveness_complete,                 // liveness data must be complete here
 825           _verify_regions_disable,                   // trash regions not yet recycled


 826           _verify_gcstate_stable_weakroots           // heap is still stable, weakroots are in progress
 827   );
 828 }
 829 
 830 void ShenandoahVerifier::verify_during_evacuation() {
 831   verify_at_safepoint(
 832           "During Evacuation",

 833           _verify_forwarded_allow,    // some forwarded references are allowed
 834           _verify_marked_disable,     // walk only roots
 835           _verify_cset_disable,       // some cset references are not forwarded yet
 836           _verify_liveness_disable,   // liveness data might be already stale after pre-evacs
 837           _verify_regions_disable,    // trash regions not yet recycled

 838           _verify_gcstate_evacuation  // evacuation is in progress
 839   );
 840 }
 841 
 842 void ShenandoahVerifier::verify_after_evacuation() {
 843   verify_at_safepoint(
 844           "After Evacuation",

 845           _verify_forwarded_allow,     // objects are still forwarded
 846           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 847           _verify_cset_forwarded,      // all cset refs are fully forwarded
 848           _verify_liveness_disable,    // no reliable liveness data anymore
 849           _verify_regions_notrash,     // trash regions have been recycled already

 850           _verify_gcstate_forwarded    // evacuation produced some forwarded objects
 851   );
 852 }
 853 
 854 void ShenandoahVerifier::verify_before_updaterefs() {
 855   verify_at_safepoint(
 856           "Before Updating References",

 857           _verify_forwarded_allow,     // forwarded references allowed
 858           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 859           _verify_cset_forwarded,      // all cset refs are fully forwarded
 860           _verify_liveness_disable,    // no reliable liveness data anymore
 861           _verify_regions_notrash,     // trash regions have been recycled already
 862           _verify_gcstate_forwarded    // evacuation should have produced some forwarded objects

 863   );
 864 }
 865 

 866 void ShenandoahVerifier::verify_after_updaterefs() {
 867   verify_at_safepoint(
 868           "After Updating References",

 869           _verify_forwarded_none,      // no forwarded references
 870           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 871           _verify_cset_none,           // no cset references, all updated
 872           _verify_liveness_disable,    // no reliable liveness data anymore
 873           _verify_regions_nocset,      // no cset regions, trash regions have appeared

 874           _verify_gcstate_stable       // update refs had cleaned up forwarded objects
 875   );
 876 }
 877 
 878 void ShenandoahVerifier::verify_after_degenerated() {
 879   verify_at_safepoint(
 880           "After Degenerated GC",

 881           _verify_forwarded_none,      // all objects are non-forwarded
 882           _verify_marked_complete,     // all objects are marked in complete bitmap
 883           _verify_cset_none,           // no cset references
 884           _verify_liveness_disable,    // no reliable liveness data anymore
 885           _verify_regions_notrash_nocset, // no trash, no cset

 886           _verify_gcstate_stable       // degenerated refs had cleaned up forwarded objects
 887   );
 888 }
 889 
 890 void ShenandoahVerifier::verify_before_fullgc() {
 891   verify_at_safepoint(
 892           "Before Full GC",

 893           _verify_forwarded_allow,     // can have forwarded objects
 894           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 895           _verify_cset_disable,        // cset might be foobared
 896           _verify_liveness_disable,    // no reliable liveness data anymore
 897           _verify_regions_disable,     // no reliable region data here

 898           _verify_gcstate_disable      // no reliable gcstate data
 899   );
 900 }
 901 
 902 void ShenandoahVerifier::verify_after_fullgc() {
 903   verify_at_safepoint(
 904           "After Full GC",

 905           _verify_forwarded_none,      // all objects are non-forwarded
 906           _verify_marked_complete,     // all objects are marked in complete bitmap
 907           _verify_cset_none,           // no cset references
 908           _verify_liveness_disable,    // no reliable liveness data anymore
 909           _verify_regions_notrash_nocset, // no trash, no cset

 910           _verify_gcstate_stable        // full gc cleaned up everything
 911   );
 912 }
 913 
 914 class ShenandoahVerifyNoForwared : public OopClosure {

 915 private:
 916   template <class T>
 917   void do_oop_work(T* p) {
 918     T o = RawAccess<>::oop_load(p);
 919     if (!CompressedOops::is_null(o)) {
 920       oop obj = CompressedOops::decode_not_null(o);
 921       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
 922       if (obj != fwd) {
 923         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
 924                                          "Verify Roots", "Should not be forwarded", __FILE__, __LINE__);
 925       }
 926     }
 927   }
 928 
 929 public:
 930   void do_oop(narrowOop* p) { do_oop_work(p); }
 931   void do_oop(oop* p)       { do_oop_work(p); }
 932 };
 933 
 934 class ShenandoahVerifyInToSpaceClosure : public OopClosure {

 935 private:
 936   template <class T>
 937   void do_oop_work(T* p) {
 938     T o = RawAccess<>::oop_load(p);
 939     if (!CompressedOops::is_null(o)) {
 940       oop obj = CompressedOops::decode_not_null(o);
 941       ShenandoahHeap* heap = ShenandoahHeap::heap();
 942 
 943       if (!heap->marking_context()->is_marked(obj)) {
 944         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
 945                 "Verify Roots In To-Space", "Should be marked", __FILE__, __LINE__);
 946       }
 947 
 948       if (heap->in_collection_set(obj)) {
 949         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
 950                 "Verify Roots In To-Space", "Should not be in collection set", __FILE__, __LINE__);
 951       }
 952 
 953       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
 954       if (obj != fwd) {
 955         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
 956                 "Verify Roots In To-Space", "Should not be forwarded", __FILE__, __LINE__);
 957       }
 958     }
 959   }
 960 
 961 public:
 962   void do_oop(narrowOop* p) { do_oop_work(p); }
 963   void do_oop(oop* p)       { do_oop_work(p); }
 964 };
 965 
 966 void ShenandoahVerifier::verify_roots_in_to_space() {
 967   ShenandoahVerifyInToSpaceClosure cl;
 968   ShenandoahRootVerifier::roots_do(&cl);
 969 }
 970 
 971 void ShenandoahVerifier::verify_roots_no_forwarded() {
 972   ShenandoahVerifyNoForwared cl;
 973   ShenandoahRootVerifier::roots_do(&cl);
 974 }





















































































































































































































   1 /*
   2  * Copyright (c) 2017, 2021, Red Hat, Inc. All rights reserved.
   3  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "gc/shared/tlab_globals.hpp"
  28 #include "gc/shenandoah/shenandoahAsserts.hpp"
  29 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
  30 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  31 #include "gc/shenandoah/shenandoahGeneration.hpp"
  32 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  33 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  34 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  35 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  36 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp"
  37 #include "gc/shenandoah/shenandoahUtils.hpp"
  38 #include "gc/shenandoah/shenandoahVerifier.hpp"
  39 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  40 #include "memory/allocation.hpp"
  41 #include "memory/iterator.inline.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "oops/compressedOops.inline.hpp"
  44 #include "runtime/atomic.hpp"
  45 #include "runtime/orderAccess.hpp"
  46 #include "runtime/threads.hpp"
  47 #include "utilities/align.hpp"
  48 
  49 // Avoid name collision on verify_oop (defined in macroAssembler_arm.hpp)
  50 #ifdef verify_oop
  51 #undef verify_oop
  52 #endif
  53 
  54 static bool is_instance_ref_klass(Klass* k) {
  55   return k->is_instance_klass() && InstanceKlass::cast(k)->reference_type() != REF_NONE;
  56 }
  57 
  58 class ShenandoahIgnoreReferenceDiscoverer : public ReferenceDiscoverer {
  59 public:
  60   virtual bool discover_reference(oop obj, ReferenceType type) {
  61     return true;
  62   }
  63 };
  64 
  65 class ShenandoahVerifyOopClosure : public BasicOopIterateClosure {
  66 private:
  67   const char* _phase;
  68   ShenandoahVerifier::VerifyOptions _options;
  69   ShenandoahVerifierStack* _stack;
  70   ShenandoahHeap* _heap;
  71   MarkBitMap* _map;
  72   ShenandoahLivenessData* _ld;
  73   void* _interior_loc;
  74   oop _loc;
  75   ShenandoahGeneration* _generation;
  76 
  77 public:
  78   ShenandoahVerifyOopClosure(ShenandoahVerifierStack* stack, MarkBitMap* map, ShenandoahLivenessData* ld,
  79                              const char* phase, ShenandoahVerifier::VerifyOptions options) :
  80     _phase(phase),
  81     _options(options),
  82     _stack(stack),
  83     _heap(ShenandoahHeap::heap()),
  84     _map(map),
  85     _ld(ld),
  86     _interior_loc(nullptr),
  87     _loc(nullptr),
  88     _generation(nullptr) {
  89     if (options._verify_marked == ShenandoahVerifier::_verify_marked_complete_except_references ||
  90         options._verify_marked == ShenandoahVerifier::_verify_marked_disable) {
  91       set_ref_discoverer_internal(new ShenandoahIgnoreReferenceDiscoverer());
  92     }
  93 
  94     if (_heap->mode()->is_generational()) {
  95       _generation = _heap->active_generation();
  96       assert(_generation != nullptr, "Expected active generation in this mode");
  97     }
  98   }
  99 
 100 private:
 101   void check(ShenandoahAsserts::SafeLevel level, oop obj, bool test, const char* label) {
 102     if (!test) {
 103       ShenandoahAsserts::print_failure(level, obj, _interior_loc, _loc, _phase, label, __FILE__, __LINE__);
 104     }
 105   }
 106 
 107   template <class T>
 108   void do_oop_work(T* p) {
 109     T o = RawAccess<>::oop_load(p);
 110     if (!CompressedOops::is_null(o)) {
 111       oop obj = CompressedOops::decode_not_null(o);
 112       if (is_instance_ref_klass(obj->klass())) {
 113         obj = ShenandoahForwarding::get_forwardee(obj);
 114       }
 115       // Single threaded verification can use faster non-atomic stack and bitmap
 116       // methods.
 117       //
 118       // For performance reasons, only fully verify non-marked field values.
 119       // We are here when the host object for *p is already marked.
 120 
 121       // TODO: We should consider specializing this closure by generation ==/!= null,
 122       // to avoid in_generation check on fast path here for non-generational mode.
 123       if (in_generation(obj) && _map->par_mark(obj)) {
 124         verify_oop_at(p, obj);
 125         _stack->push(ShenandoahVerifierTask(obj));
 126       }
 127     }
 128   }
 129 
 130   bool in_generation(oop obj) {
 131     if (_generation == nullptr) {
 132       return true;
 133     }
 134 
 135     ShenandoahHeapRegion* region = _heap->heap_region_containing(obj);
 136     return _generation->contains(region);
 137   }
 138 
 139   void verify_oop(oop obj) {
 140     // Perform consistency checks with gradually decreasing safety level. This guarantees
 141     // that failure report would not try to touch something that was not yet verified to be
 142     // safe to process.
 143 
 144     check(ShenandoahAsserts::_safe_unknown, obj, _heap->is_in(obj),
 145               "oop must be in heap");
 146     check(ShenandoahAsserts::_safe_unknown, obj, is_object_aligned(obj),
 147               "oop must be aligned");
 148 
 149     ShenandoahHeapRegion *obj_reg = _heap->heap_region_containing(obj);
 150     Klass* obj_klass = obj->klass_or_null();
 151 
 152     // Verify that obj is not in dead space:
 153     {
 154       // Do this before touching obj->size()
 155       check(ShenandoahAsserts::_safe_unknown, obj, obj_klass != nullptr,
 156              "Object klass pointer should not be null");
 157       check(ShenandoahAsserts::_safe_unknown, obj, Metaspace::contains(obj_klass),
 158              "Object klass pointer must go to metaspace");

 169         size_t humongous_end = humongous_start + (obj->size() >> ShenandoahHeapRegion::region_size_words_shift());
 170         for (size_t idx = humongous_start + 1; idx < humongous_end; idx++) {
 171           check(ShenandoahAsserts::_safe_unknown, obj, _heap->get_region(idx)->is_humongous_continuation(),
 172                  "Humongous object is in continuation that fits it");
 173         }
 174       }
 175 
 176       // ------------ obj is safe at this point --------------
 177 
 178       check(ShenandoahAsserts::_safe_oop, obj, obj_reg->is_active(),
 179             "Object should be in active region");
 180 
 181       switch (_options._verify_liveness) {
 182         case ShenandoahVerifier::_verify_liveness_disable:
 183           // skip
 184           break;
 185         case ShenandoahVerifier::_verify_liveness_complete:
 186           Atomic::add(&_ld[obj_reg->index()], (uint) obj->size(), memory_order_relaxed);
 187           // fallthrough for fast failure for un-live regions:
 188         case ShenandoahVerifier::_verify_liveness_conservative:
 189           check(ShenandoahAsserts::_safe_oop, obj, obj_reg->has_live() ||
 190                 (obj_reg->is_old() && ShenandoahHeap::heap()->is_gc_generation_young()),
 191                    "Object must belong to region with live data");
 192           break;
 193         default:
 194           assert(false, "Unhandled liveness verification");
 195       }
 196     }
 197 
 198     oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
 199 
 200     ShenandoahHeapRegion* fwd_reg = nullptr;
 201 
 202     if (obj != fwd) {
 203       check(ShenandoahAsserts::_safe_oop, obj, _heap->is_in(fwd),
 204              "Forwardee must be in heap");
 205       check(ShenandoahAsserts::_safe_oop, obj, !CompressedOops::is_null(fwd),
 206              "Forwardee is set");
 207       check(ShenandoahAsserts::_safe_oop, obj, is_object_aligned(fwd),
 208              "Forwardee must be aligned");
 209 
 210       // Do this before touching fwd->size()

 219       fwd_reg = _heap->heap_region_containing(fwd);
 220 
 221       // Verify that forwardee is not in the dead space:
 222       check(ShenandoahAsserts::_safe_oop, obj, !fwd_reg->is_humongous(),
 223              "Should have no humongous forwardees");
 224 
 225       HeapWord *fwd_addr = cast_from_oop<HeapWord *>(fwd);
 226       check(ShenandoahAsserts::_safe_oop, obj, fwd_addr < fwd_reg->top(),
 227              "Forwardee start should be within the region");
 228       check(ShenandoahAsserts::_safe_oop, obj, (fwd_addr + fwd->size()) <= fwd_reg->top(),
 229              "Forwardee end should be within the region");
 230 
 231       oop fwd2 = ShenandoahForwarding::get_forwardee_raw_unchecked(fwd);
 232       check(ShenandoahAsserts::_safe_oop, obj, (fwd == fwd2),
 233              "Double forwarding");
 234     } else {
 235       fwd_reg = obj_reg;
 236     }
 237 
 238     // ------------ obj and fwd are safe at this point --------------
 239     // We allow for marked or old here for two reasons:
 240     //  1. If this is a young collect, old objects wouldn't be marked. We've
 241     //     recently change the verifier traversal to only follow young objects
 242     //     during a young collect so this _shouldn't_ be necessary.
 243     //  2. At present, we do not clear dead objects from the remembered set.
 244     //     Everything in the remembered set is old (ipso facto), so allowing for
 245     //     'marked_or_old' covers the case of stale objects in rset.
 246     // TODO: Just use 'is_marked' here.
 247     switch (_options._verify_marked) {
 248       case ShenandoahVerifier::_verify_marked_disable:
 249         // skip
 250         break;
 251       case ShenandoahVerifier::_verify_marked_incomplete:
 252         check(ShenandoahAsserts::_safe_all, obj, _heap->marking_context()->is_marked_or_old(obj),
 253                "Must be marked in incomplete bitmap");
 254         break;
 255       case ShenandoahVerifier::_verify_marked_complete:
 256         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked_or_old(obj),
 257                "Must be marked in complete bitmap");
 258         break;
 259       case ShenandoahVerifier::_verify_marked_complete_except_references:
 260         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked_or_old(obj),
 261               "Must be marked in complete bitmap, except j.l.r.Reference referents");
 262         break;
 263       default:
 264         assert(false, "Unhandled mark verification");
 265     }
 266 
 267     switch (_options._verify_forwarded) {
 268       case ShenandoahVerifier::_verify_forwarded_disable:
 269         // skip
 270         break;
 271       case ShenandoahVerifier::_verify_forwarded_none: {
 272         check(ShenandoahAsserts::_safe_all, obj, (obj == fwd),
 273                "Should not be forwarded");
 274         break;
 275       }
 276       case ShenandoahVerifier::_verify_forwarded_allow: {
 277         if (obj != fwd) {
 278           check(ShenandoahAsserts::_safe_all, obj, obj_reg != fwd_reg,
 279                  "Forwardee should be in another region");
 280         }

 326   void verify_oop_standalone(oop obj) {
 327     _interior_loc = nullptr;
 328     verify_oop(obj);
 329     _interior_loc = nullptr;
 330   }
 331 
 332   /**
 333    * Verify oop fields from this object.
 334    * @param obj host object for verified fields
 335    */
 336   void verify_oops_from(oop obj) {
 337     _loc = obj;
 338     obj->oop_iterate(this);
 339     _loc = nullptr;
 340   }
 341 
 342   virtual void do_oop(oop* p) { do_oop_work(p); }
 343   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 344 };
 345 
 346 // This closure computes the amounts of used, committed, and garbage memory and the number of regions contained within
 347 // a subset (e.g. the young generation or old generation) of the total heap.
 348 class ShenandoahCalculateRegionStatsClosure : public ShenandoahHeapRegionClosure {
 349 private:
 350   size_t _used, _committed, _garbage, _regions, _humongous_waste;
 351 public:
 352   ShenandoahCalculateRegionStatsClosure() : _used(0), _committed(0), _garbage(0), _regions(0), _humongous_waste(0) {};
 353 
 354   void heap_region_do(ShenandoahHeapRegion* r) {
 355     _used += r->used();
 356     _garbage += r->garbage();
 357     _committed += r->is_committed() ? ShenandoahHeapRegion::region_size_bytes() : 0;
 358     if (r->is_humongous()) {
 359       _humongous_waste += r->free();
 360     }
 361     _regions++;
 362     log_debug(gc)("ShenandoahCalculateRegionStatsClosure: adding " SIZE_FORMAT " for %s Region " SIZE_FORMAT ", yielding: " SIZE_FORMAT,
 363             r->used(), (r->is_humongous() ? "humongous" : "regular"), r->index(), _used);
 364   }
 365 
 366   size_t used() { return _used; }
 367   size_t committed() { return _committed; }
 368   size_t garbage() { return _garbage; }
 369   size_t regions() { return _regions; }
 370   size_t waste() { return _humongous_waste; }
 371 
 372   // span is the total memory affiliated with these stats (some of which is in use and other is available)
 373   size_t span() { return _regions * ShenandoahHeapRegion::region_size_bytes(); }
 374 };
 375 
 376 class ShenandoahGenerationStatsClosure : public ShenandoahHeapRegionClosure {
 377  public:
 378   ShenandoahCalculateRegionStatsClosure old;
 379   ShenandoahCalculateRegionStatsClosure young;
 380   ShenandoahCalculateRegionStatsClosure global;
 381 
 382   void heap_region_do(ShenandoahHeapRegion* r) override {
 383     switch (r->affiliation()) {
 384       case FREE:
 385         return;
 386       case YOUNG_GENERATION:
 387         young.heap_region_do(r);
 388         global.heap_region_do(r);
 389         break;
 390       case OLD_GENERATION:
 391         old.heap_region_do(r);
 392         global.heap_region_do(r);
 393         break;
 394       default:
 395         ShouldNotReachHere();
 396     }
 397   }
 398 
 399   static void log_usage(ShenandoahGeneration* generation, ShenandoahCalculateRegionStatsClosure& stats) {
 400     log_debug(gc)("Safepoint verification: %s verified usage: " SIZE_FORMAT "%s, recorded usage: " SIZE_FORMAT "%s",
 401                   generation->name(),
 402                   byte_size_in_proper_unit(generation->used()), proper_unit_for_byte_size(generation->used()),
 403                   byte_size_in_proper_unit(stats.used()),       proper_unit_for_byte_size(stats.used()));
 404   }
 405 
 406   static void validate_usage(const bool adjust_for_padding,
 407                              const char* label, ShenandoahGeneration* generation, ShenandoahCalculateRegionStatsClosure& stats) {
 408     ShenandoahHeap* heap = ShenandoahHeap::heap();
 409     size_t generation_used = generation->used();
 410     size_t generation_used_regions = generation->used_regions();
 411     if (adjust_for_padding && (generation->is_young() || generation->is_global())) {
 412       size_t pad = ShenandoahHeap::heap()->get_pad_for_promote_in_place();
 413       generation_used += pad;
 414     }
 415 
 416     guarantee(stats.used() == generation_used,
 417               "%s: generation (%s) used size must be consistent: generation-used: " SIZE_FORMAT "%s, regions-used: " SIZE_FORMAT "%s",
 418               label, generation->name(),
 419               byte_size_in_proper_unit(generation_used), proper_unit_for_byte_size(generation_used),
 420               byte_size_in_proper_unit(stats.used()),    proper_unit_for_byte_size(stats.used()));
 421 
 422     guarantee(stats.regions() == generation_used_regions,
 423               "%s: generation (%s) used regions (" SIZE_FORMAT ") must equal regions that are in use (" SIZE_FORMAT ")",
 424               label, generation->name(), generation->used_regions(), stats.regions());
 425 
 426     size_t generation_capacity = generation->max_capacity();
 427     size_t humongous_regions_promoted = 0;
 428     guarantee(stats.span() <= generation_capacity,
 429               "%s: generation (%s) size spanned by regions (" SIZE_FORMAT ") must not exceed current capacity (" SIZE_FORMAT "%s)",
 430               label, generation->name(), stats.regions(),
 431               byte_size_in_proper_unit(generation_capacity), proper_unit_for_byte_size(generation_capacity));
 432 
 433     size_t humongous_waste = generation->get_humongous_waste();
 434     guarantee(stats.waste() == humongous_waste,
 435               "%s: generation (%s) humongous waste must be consistent: generation: " SIZE_FORMAT "%s, regions: " SIZE_FORMAT "%s",
 436               label, generation->name(),
 437               byte_size_in_proper_unit(humongous_waste), proper_unit_for_byte_size(humongous_waste),
 438               byte_size_in_proper_unit(stats.waste()),   proper_unit_for_byte_size(stats.waste()));
 439   }
 440 };
 441 
 442 class ShenandoahVerifyHeapRegionClosure : public ShenandoahHeapRegionClosure {
 443 private:
 444   ShenandoahHeap* _heap;
 445   const char* _phase;
 446   ShenandoahVerifier::VerifyRegions _regions;
 447 public:
 448   ShenandoahVerifyHeapRegionClosure(const char* phase, ShenandoahVerifier::VerifyRegions regions) :
 449     _heap(ShenandoahHeap::heap()),
 450     _phase(phase),
 451     _regions(regions) {};
 452 
 453   void print_failure(ShenandoahHeapRegion* r, const char* label) {
 454     ResourceMark rm;
 455 
 456     ShenandoahMessageBuffer msg("Shenandoah verification failed; %s: %s\n\n", _phase, label);
 457 
 458     stringStream ss;
 459     r->print_on(&ss);

 503            "Complete TAMS should not be larger than top");
 504 
 505     verify(r, r->get_live_data_bytes() <= r->capacity(),
 506            "Live data cannot be larger than capacity");
 507 
 508     verify(r, r->garbage() <= r->capacity(),
 509            "Garbage cannot be larger than capacity");
 510 
 511     verify(r, r->used() <= r->capacity(),
 512            "Used cannot be larger than capacity");
 513 
 514     verify(r, r->get_shared_allocs() <= r->capacity(),
 515            "Shared alloc count should not be larger than capacity");
 516 
 517     verify(r, r->get_tlab_allocs() <= r->capacity(),
 518            "TLAB alloc count should not be larger than capacity");
 519 
 520     verify(r, r->get_gclab_allocs() <= r->capacity(),
 521            "GCLAB alloc count should not be larger than capacity");
 522 
 523     verify(r, r->get_plab_allocs() <= r->capacity(),
 524            "PLAB alloc count should not be larger than capacity");
 525 
 526     verify(r, r->get_shared_allocs() + r->get_tlab_allocs() + r->get_gclab_allocs() + r->get_plab_allocs() == r->used(),
 527            "Accurate accounting: shared + TLAB + GCLAB + PLAB = used");
 528 
 529     verify(r, !r->is_empty() || !r->has_live(),
 530            "Empty regions should not have live data");
 531 
 532     verify(r, r->is_cset() == _heap->collection_set()->is_in(r),
 533            "Transitional: region flags and collection set agree");
 534   }
 535 };
 536 
 537 class ShenandoahVerifierReachableTask : public WorkerTask {
 538 private:
 539   const char* _label;
 540   ShenandoahVerifier::VerifyOptions _options;
 541   ShenandoahHeap* _heap;
 542   ShenandoahLivenessData* _ld;
 543   MarkBitMap* _bitmap;
 544   volatile size_t _processed;
 545 
 546 public:
 547   ShenandoahVerifierReachableTask(MarkBitMap* bitmap,

 589       while (!stack.is_empty()) {
 590         processed++;
 591         ShenandoahVerifierTask task = stack.pop();
 592         cl.verify_oops_from(task.obj());
 593       }
 594     }
 595 
 596     Atomic::add(&_processed, processed, memory_order_relaxed);
 597   }
 598 };
 599 
 600 class ShenandoahVerifierMarkedRegionTask : public WorkerTask {
 601 private:
 602   const char* _label;
 603   ShenandoahVerifier::VerifyOptions _options;
 604   ShenandoahHeap *_heap;
 605   MarkBitMap* _bitmap;
 606   ShenandoahLivenessData* _ld;
 607   volatile size_t _claimed;
 608   volatile size_t _processed;
 609   ShenandoahGeneration* _generation;
 610 
 611 public:
 612   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
 613                                      ShenandoahLivenessData* ld,
 614                                      const char* label,
 615                                      ShenandoahVerifier::VerifyOptions options) :
 616           WorkerTask("Shenandoah Verifier Marked Objects"),
 617           _label(label),
 618           _options(options),
 619           _heap(ShenandoahHeap::heap()),
 620           _bitmap(bitmap),
 621           _ld(ld),
 622           _claimed(0),
 623           _processed(0),
 624           _generation(nullptr) {
 625     if (_heap->mode()->is_generational()) {
 626       _generation = _heap->active_generation();
 627       assert(_generation != nullptr, "Expected active generation in this mode.");
 628     }
 629   };
 630 
 631   size_t processed() {
 632     return Atomic::load(&_processed);
 633   }
 634 
 635   virtual void work(uint worker_id) {
 636     ShenandoahVerifierStack stack;
 637     ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 638                                   ShenandoahMessageBuffer("%s, Marked", _label),
 639                                   _options);
 640 
 641     while (true) {
 642       size_t v = Atomic::fetch_then_add(&_claimed, 1u, memory_order_relaxed);
 643       if (v < _heap->num_regions()) {
 644         ShenandoahHeapRegion* r = _heap->get_region(v);
 645         if (!in_generation(r)) {
 646           continue;
 647         }
 648 
 649         if (!r->is_humongous() && !r->is_trash()) {
 650           work_regular(r, stack, cl);
 651         } else if (r->is_humongous_start()) {
 652           work_humongous(r, stack, cl);
 653         }
 654       } else {
 655         break;
 656       }
 657     }
 658   }
 659 
 660   bool in_generation(ShenandoahHeapRegion* r) {
 661     return _generation == nullptr || _generation->contains(r);
 662   }
 663 
 664   virtual void work_humongous(ShenandoahHeapRegion *r, ShenandoahVerifierStack& stack, ShenandoahVerifyOopClosure& cl) {
 665     size_t processed = 0;
 666     HeapWord* obj = r->bottom();
 667     if (_heap->complete_marking_context()->is_marked(cast_to_oop(obj))) {
 668       verify_and_follow(obj, stack, cl, &processed);
 669     }
 670     Atomic::add(&_processed, processed, memory_order_relaxed);
 671   }
 672 
 673   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
 674     size_t processed = 0;
 675     ShenandoahMarkingContext* ctx = _heap->complete_marking_context();
 676     HeapWord* tams = ctx->top_at_mark_start(r);
 677 
 678     // Bitmaps, before TAMS
 679     if (tams > r->bottom()) {
 680       HeapWord* start = r->bottom();
 681       HeapWord* addr = ctx->get_next_marked_addr(start, tams);
 682 
 683       while (addr < tams) {

 716       cl.verify_oops_from(obj);
 717       (*processed)++;
 718     }
 719     while (!stack.is_empty()) {
 720       ShenandoahVerifierTask task = stack.pop();
 721       cl.verify_oops_from(task.obj());
 722       (*processed)++;
 723     }
 724   }
 725 };
 726 
 727 class VerifyThreadGCState : public ThreadClosure {
 728 private:
 729   const char* const _label;
 730          char const _expected;
 731 
 732 public:
 733   VerifyThreadGCState(const char* label, char expected) : _label(label), _expected(expected) {}
 734   void do_thread(Thread* t) {
 735     char actual = ShenandoahThreadLocalData::gc_state(t);
 736     if (!verify_gc_state(actual, _expected)) {
 737       fatal("%s: Thread %s: expected gc-state %d, actual %d", _label, t->name(), _expected, actual);
 738     }
 739   }
 740 
 741   static bool verify_gc_state(char actual, char expected) {
 742     // Old generation marking is allowed in all states.
 743     // TODO: This actually accepts more than just OLD_MARKING.
 744     // TODO: Also, only accept OLD_MARKING in generational mode.
 745     return (actual == expected) || (actual & ShenandoahHeap::OLD_MARKING);
 746   }
 747 };
 748 
 749 void ShenandoahVerifier::verify_at_safepoint(const char* label,
 750                                              VerifyRememberedSet remembered,
 751                                              VerifyForwarded forwarded, VerifyMarked marked,
 752                                              VerifyCollectionSet cset,
 753                                              VerifyLiveness liveness, VerifyRegions regions,
 754                                              VerifySize sizeness,
 755                                              VerifyGCState gcstate) {
 756   guarantee(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "only when nothing else happens");
 757   guarantee(ShenandoahVerify, "only when enabled, and bitmap is initialized in ShenandoahHeap::initialize");
 758 
 759   // Avoid side-effect of changing workers' active thread count, but bypass concurrent/parallel protocol check
 760   ShenandoahPushWorkerScope verify_worker_scope(_heap->workers(), _heap->max_workers(), false /*bypass check*/);
 761 
 762   log_info(gc,start)("Verify %s, Level " INTX_FORMAT, label, ShenandoahVerifyLevel);
 763 
 764   // GC state checks
 765   {
 766     char expected = -1;
 767     bool enabled;
 768     switch (gcstate) {
 769       case _verify_gcstate_disable:
 770         enabled = false;
 771         break;
 772       case _verify_gcstate_forwarded:
 773         enabled = true;
 774         expected = ShenandoahHeap::HAS_FORWARDED;
 775         break;
 776       case _verify_gcstate_evacuation:
 777         enabled = true;
 778         expected = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::EVACUATION;
 779         if (!_heap->is_stw_gc_in_progress()) {
 780           // Only concurrent GC sets this.
 781           expected |= ShenandoahHeap::WEAK_ROOTS;
 782         }
 783         break;
 784       case _verify_gcstate_updating:
 785         enabled = true;
 786         expected = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::UPDATEREFS;
 787         break;
 788       case _verify_gcstate_stable:
 789         enabled = true;
 790         expected = ShenandoahHeap::STABLE;
 791         break;
 792       case _verify_gcstate_stable_weakroots:
 793         enabled = true;
 794         expected = ShenandoahHeap::STABLE;
 795         if (!_heap->is_stw_gc_in_progress()) {
 796           // Only concurrent GC sets this.
 797           expected |= ShenandoahHeap::WEAK_ROOTS;
 798         }
 799         break;
 800       default:
 801         enabled = false;
 802         assert(false, "Unhandled gc-state verification");
 803     }
 804 
 805     if (enabled) {
 806       char actual = _heap->gc_state();
 807       // Old generation marking is allowed in all states.
 808       if (!VerifyThreadGCState::verify_gc_state(actual, expected)) {
 809         fatal("%s: Global gc-state: expected %d, actual %d", label, expected, actual);
 810       }
 811 
 812       VerifyThreadGCState vtgcs(label, expected);
 813       Threads::java_threads_do(&vtgcs);
 814     }
 815   }
 816 
 817   // Deactivate barriers temporarily: Verifier wants plain heap accesses
 818   ShenandoahGCStateResetter resetter;
 819 
 820   // Heap size checks
 821   {
 822     ShenandoahHeapLocker lock(_heap->lock());
 823 
 824     ShenandoahCalculateRegionStatsClosure cl;
 825     _heap->heap_region_iterate(&cl);
 826     size_t heap_used;
 827     if (_heap->mode()->is_generational() && (sizeness == _verify_size_adjusted_for_padding)) {
 828       // Prior to evacuation, regular regions that are to be evacuated in place are padded to prevent further allocations
 829       heap_used = _heap->used() + _heap->get_pad_for_promote_in_place();
 830     } else if (sizeness != _verify_size_disable) {
 831       heap_used = _heap->used();
 832     }
 833     if (sizeness != _verify_size_disable) {
 834       guarantee(cl.used() == heap_used,
 835                 "%s: heap used size must be consistent: heap-used = " SIZE_FORMAT "%s, regions-used = " SIZE_FORMAT "%s",
 836                 label,
 837                 byte_size_in_proper_unit(heap_used), proper_unit_for_byte_size(heap_used),
 838                 byte_size_in_proper_unit(cl.used()), proper_unit_for_byte_size(cl.used()));
 839     }
 840     size_t heap_committed = _heap->committed();
 841     guarantee(cl.committed() == heap_committed,
 842               "%s: heap committed size must be consistent: heap-committed = " SIZE_FORMAT "%s, regions-committed = " SIZE_FORMAT "%s",
 843               label,
 844               byte_size_in_proper_unit(heap_committed), proper_unit_for_byte_size(heap_committed),
 845               byte_size_in_proper_unit(cl.committed()), proper_unit_for_byte_size(cl.committed()));
 846   }
 847 
 848   log_debug(gc)("Safepoint verification finished heap usage verification");
 849 
 850   ShenandoahGeneration* generation;
 851   if (_heap->mode()->is_generational()) {
 852     generation = _heap->active_generation();
 853     guarantee(generation != nullptr, "Need to know which generation to verify.");
 854   } else {
 855     generation = nullptr;
 856   }
 857 
 858   if (generation != nullptr) {
 859     ShenandoahHeapLocker lock(_heap->lock());
 860 
 861     switch (remembered) {
 862       case _verify_remembered_disable:
 863         break;
 864       case _verify_remembered_before_marking:
 865         log_debug(gc)("Safepoint verification of remembered set at mark");
 866         verify_rem_set_before_mark();
 867         break;
 868       case _verify_remembered_before_updating_references:
 869         log_debug(gc)("Safepoint verification of remembered set at update ref");
 870         verify_rem_set_before_update_ref();
 871         break;
 872       case _verify_remembered_after_full_gc:
 873         log_debug(gc)("Safepoint verification of remembered set after full gc");
 874         verify_rem_set_after_full_gc();
 875         break;
 876       default:
 877         fatal("Unhandled remembered set verification mode");
 878     }
 879 
 880     ShenandoahGenerationStatsClosure cl;
 881     _heap->heap_region_iterate(&cl);
 882 
 883     if (LogTarget(Debug, gc)::is_enabled()) {
 884       ShenandoahGenerationStatsClosure::log_usage(_heap->old_generation(),    cl.old);
 885       ShenandoahGenerationStatsClosure::log_usage(_heap->young_generation(),  cl.young);
 886       ShenandoahGenerationStatsClosure::log_usage(_heap->global_generation(), cl.global);
 887     }
 888     if (sizeness == _verify_size_adjusted_for_padding) {
 889       ShenandoahGenerationStatsClosure::validate_usage(false, label, _heap->old_generation(), cl.old);
 890       ShenandoahGenerationStatsClosure::validate_usage(true, label, _heap->young_generation(), cl.young);
 891       ShenandoahGenerationStatsClosure::validate_usage(true, label, _heap->global_generation(), cl.global);
 892     } else if (sizeness == _verify_size_exact) {
 893       ShenandoahGenerationStatsClosure::validate_usage(false, label, _heap->old_generation(), cl.old);
 894       ShenandoahGenerationStatsClosure::validate_usage(false, label, _heap->young_generation(), cl.young);
 895       ShenandoahGenerationStatsClosure::validate_usage(false, label, _heap->global_generation(), cl.global);
 896     }
 897     // else: sizeness must equal _verify_size_disable
 898   }
 899 
 900   log_debug(gc)("Safepoint verification finished remembered set verification");
 901 
 902   // Internal heap region checks
 903   if (ShenandoahVerifyLevel >= 1) {
 904     ShenandoahVerifyHeapRegionClosure cl(label, regions);
 905     if (generation != nullptr) {
 906       generation->heap_region_iterate(&cl);
 907     } else {
 908       _heap->heap_region_iterate(&cl);
 909     }
 910   }
 911 
 912   log_debug(gc)("Safepoint verification finished heap region closure verification");
 913 
 914   OrderAccess::fence();
 915 
 916   if (UseTLAB) {
 917     _heap->labs_make_parsable();
 918   }
 919 
 920   // Allocate temporary bitmap for storing marking wavefront:
 921   _verification_bit_map->clear();
 922 
 923   // Allocate temporary array for storing liveness data
 924   ShenandoahLivenessData* ld = NEW_C_HEAP_ARRAY(ShenandoahLivenessData, _heap->num_regions(), mtGC);
 925   Copy::fill_to_bytes((void*)ld, _heap->num_regions()*sizeof(ShenandoahLivenessData), 0);
 926 
 927   const VerifyOptions& options = ShenandoahVerifier::VerifyOptions(forwarded, marked, cset, liveness, regions, gcstate);
 928 
 929   // Steps 1-2. Scan root set to get initial reachable set. Finish walking the reachable heap.
 930   // This verifies what application can see, since it only cares about reachable objects.
 931   size_t count_reachable = 0;
 932   if (ShenandoahVerifyLevel >= 2) {
 933     ShenandoahVerifierReachableTask task(_verification_bit_map, ld, label, options);
 934     _heap->workers()->run_task(&task);
 935     count_reachable = task.processed();
 936   }
 937 
 938   log_debug(gc)("Safepoint verification finished getting initial reachable set");
 939 
 940   // Step 3. Walk marked objects. Marked objects might be unreachable. This verifies what collector,
 941   // not the application, can see during the region scans. There is no reason to process the objects
 942   // that were already verified, e.g. those marked in verification bitmap. There is interaction with TAMS:
 943   // before TAMS, we verify the bitmaps, if available; after TAMS, we walk until the top(). It mimics
 944   // what marked_object_iterate is doing, without calling into that optimized (and possibly incorrect)
 945   // version
 946 
 947   size_t count_marked = 0;
 948   if (ShenandoahVerifyLevel >= 4 && (marked == _verify_marked_complete || marked == _verify_marked_complete_except_references)) {
 949     guarantee(_heap->marking_context()->is_complete(), "Marking context should be complete");
 950     ShenandoahVerifierMarkedRegionTask task(_verification_bit_map, ld, label, options);
 951     _heap->workers()->run_task(&task);
 952     count_marked = task.processed();
 953   } else {
 954     guarantee(ShenandoahVerifyLevel < 4 || marked == _verify_marked_incomplete || marked == _verify_marked_disable, "Should be");
 955   }
 956 
 957   log_debug(gc)("Safepoint verification finished walking marked objects");
 958 
 959   // Step 4. Verify accumulated liveness data, if needed. Only reliable if verification level includes
 960   // marked objects.
 961 
 962   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete && liveness == _verify_liveness_complete) {
 963     for (size_t i = 0; i < _heap->num_regions(); i++) {
 964       ShenandoahHeapRegion* r = _heap->get_region(i);
 965       if (generation != nullptr && !generation->contains(r)) {
 966         continue;
 967       }
 968 
 969       juint verf_live = 0;
 970       if (r->is_humongous()) {
 971         // For humongous objects, test if start region is marked live, and if so,
 972         // all humongous regions in that chain have live data equal to their "used".
 973         juint start_live = Atomic::load(&ld[r->humongous_start_region()->index()]);
 974         if (start_live > 0) {
 975           verf_live = (juint)(r->used() / HeapWordSize);
 976         }
 977       } else {
 978         verf_live = Atomic::load(&ld[r->index()]);
 979       }
 980 
 981       size_t reg_live = r->get_live_data_words();
 982       if (reg_live != verf_live) {
 983         stringStream ss;
 984         r->print_on(&ss);
 985         fatal("%s: Live data should match: region-live = " SIZE_FORMAT ", verifier-live = " UINT32_FORMAT "\n%s",
 986               label, reg_live, verf_live, ss.freeze());
 987       }
 988     }
 989   }
 990 
 991   log_debug(gc)("Safepoint verification finished accumulation of liveness data");
 992 
 993 
 994   log_info(gc)("Verify %s, Level " INTX_FORMAT " (" SIZE_FORMAT " reachable, " SIZE_FORMAT " marked)",
 995                label, ShenandoahVerifyLevel, count_reachable, count_marked);
 996 
 997   FREE_C_HEAP_ARRAY(ShenandoahLivenessData, ld);
 998 }
 999 
1000 void ShenandoahVerifier::verify_generic(VerifyOption vo) {
1001   verify_at_safepoint(
1002           "Generic Verification",
1003           _verify_remembered_disable,  // do not verify remembered set
1004           _verify_forwarded_allow,     // conservatively allow forwarded
1005           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
1006           _verify_cset_disable,        // cset may be inconsistent
1007           _verify_liveness_disable,    // no reliable liveness data
1008           _verify_regions_disable,     // no reliable region data
1009           _verify_size_exact,          // expect generation and heap sizes to match exactly
1010           _verify_gcstate_disable      // no data about gcstate
1011   );
1012 }
1013 
1014 void ShenandoahVerifier::verify_before_concmark() {
1015     verify_at_safepoint(
1016           "Before Mark",
1017           _verify_remembered_before_marking,
1018                                        // verify read-only remembered set from bottom() to top()
1019           _verify_forwarded_none,      // UR should have fixed up
1020           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
1021           _verify_cset_none,           // UR should have fixed this
1022           _verify_liveness_disable,    // no reliable liveness data
1023           _verify_regions_notrash,     // no trash regions
1024           _verify_size_exact,          // expect generation and heap sizes to match exactly
1025           _verify_gcstate_stable       // there are no forwarded objects
1026   );
1027 }
1028 
1029 void ShenandoahVerifier::verify_after_concmark() {
1030   verify_at_safepoint(
1031           "After Mark",
1032           _verify_remembered_disable,  // do not verify remembered set
1033           _verify_forwarded_none,      // no forwarded references
1034           _verify_marked_complete_except_references,
1035                                        // bitmaps as precise as we can get, except dangling j.l.r.Refs
1036           _verify_cset_none,           // no references to cset anymore
1037           _verify_liveness_complete,   // liveness data must be complete here
1038           _verify_regions_disable,     // trash regions not yet recycled
1039           _verify_size_exact,          // expect generation and heap sizes to match exactly
1040           _verify_gcstate_stable_weakroots  // heap is still stable, weakroots are in progress
1041   );
1042 }
1043 
1044 void ShenandoahVerifier::verify_before_evacuation() {
1045   verify_at_safepoint(
1046           "Before Evacuation",
1047           _verify_remembered_disable,                // do not verify remembered set
1048           _verify_forwarded_none,                    // no forwarded references
1049           _verify_marked_complete_except_references, // walk over marked objects too
1050           _verify_cset_disable,                      // non-forwarded references to cset expected
1051           _verify_liveness_complete,                 // liveness data must be complete here
1052           _verify_regions_disable,                   // trash regions not yet recycled
1053           _verify_size_adjusted_for_padding,         // expect generation and heap sizes to match after adjustments
1054                                                      //  for promote in place padding
1055           _verify_gcstate_stable_weakroots           // heap is still stable, weakroots are in progress
1056   );
1057 }
1058 
1059 void ShenandoahVerifier::verify_during_evacuation() {
1060   verify_at_safepoint(
1061           "During Evacuation",
1062           _verify_remembered_disable, // do not verify remembered set
1063           _verify_forwarded_allow,    // some forwarded references are allowed
1064           _verify_marked_disable,     // walk only roots
1065           _verify_cset_disable,       // some cset references are not forwarded yet
1066           _verify_liveness_disable,   // liveness data might be already stale after pre-evacs
1067           _verify_regions_disable,    // trash regions not yet recycled
1068           _verify_size_disable,       // we don't know how much of promote-in-place work has been completed
1069           _verify_gcstate_evacuation  // evacuation is in progress
1070   );
1071 }
1072 
1073 void ShenandoahVerifier::verify_after_evacuation() {
1074   verify_at_safepoint(
1075           "After Evacuation",
1076           _verify_remembered_disable,  // do not verify remembered set
1077           _verify_forwarded_allow,     // objects are still forwarded
1078           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
1079           _verify_cset_forwarded,      // all cset refs are fully forwarded
1080           _verify_liveness_disable,    // no reliable liveness data anymore
1081           _verify_regions_notrash,     // trash regions have been recycled already
1082           _verify_size_exact,          // expect generation and heap sizes to match exactly
1083           _verify_gcstate_forwarded    // evacuation produced some forwarded objects
1084   );
1085 }
1086 
1087 void ShenandoahVerifier::verify_before_updaterefs() {
1088   verify_at_safepoint(
1089           "Before Updating References",
1090           _verify_remembered_before_updating_references,  // verify read-write remembered set
1091           _verify_forwarded_allow,     // forwarded references allowed
1092           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
1093           _verify_cset_forwarded,      // all cset refs are fully forwarded
1094           _verify_liveness_disable,    // no reliable liveness data anymore
1095           _verify_regions_notrash,     // trash regions have been recycled already
1096           _verify_size_exact,          // expect generation and heap sizes to match exactly
1097           _verify_gcstate_updating     // evacuation should have produced some forwarded objects
1098   );
1099 }
1100 
1101 // We have not yet cleanup (reclaimed) the collection set
1102 void ShenandoahVerifier::verify_after_updaterefs() {
1103   verify_at_safepoint(
1104           "After Updating References",
1105           _verify_remembered_disable,  // do not verify remembered set
1106           _verify_forwarded_none,      // no forwarded references
1107           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
1108           _verify_cset_none,           // no cset references, all updated
1109           _verify_liveness_disable,    // no reliable liveness data anymore
1110           _verify_regions_nocset,      // no cset regions, trash regions have appeared
1111           _verify_size_exact,          // expect generation and heap sizes to match exactly
1112           _verify_gcstate_stable       // update refs had cleaned up forwarded objects
1113   );
1114 }
1115 
1116 void ShenandoahVerifier::verify_after_degenerated() {
1117   verify_at_safepoint(
1118           "After Degenerated GC",
1119           _verify_remembered_disable,  // do not verify remembered set
1120           _verify_forwarded_none,      // all objects are non-forwarded
1121           _verify_marked_complete,     // all objects are marked in complete bitmap
1122           _verify_cset_none,           // no cset references
1123           _verify_liveness_disable,    // no reliable liveness data anymore
1124           _verify_regions_notrash_nocset, // no trash, no cset
1125           _verify_size_exact,          // expect generation and heap sizes to match exactly
1126           _verify_gcstate_stable       // degenerated refs had cleaned up forwarded objects
1127   );
1128 }
1129 
1130 void ShenandoahVerifier::verify_before_fullgc() {
1131   verify_at_safepoint(
1132           "Before Full GC",
1133           _verify_remembered_disable,  // do not verify remembered set
1134           _verify_forwarded_allow,     // can have forwarded objects
1135           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
1136           _verify_cset_disable,        // cset might be foobared
1137           _verify_liveness_disable,    // no reliable liveness data anymore
1138           _verify_regions_disable,     // no reliable region data here
1139           _verify_size_disable,        // if we degenerate during evacuation, usage not valid: padding and deferred accounting
1140           _verify_gcstate_disable      // no reliable gcstate data
1141   );
1142 }
1143 
1144 void ShenandoahVerifier::verify_after_fullgc() {
1145   verify_at_safepoint(
1146           "After Full GC",
1147           _verify_remembered_after_full_gc,  // verify read-write remembered set
1148           _verify_forwarded_none,      // all objects are non-forwarded
1149           _verify_marked_complete,     // all objects are marked in complete bitmap
1150           _verify_cset_none,           // no cset references
1151           _verify_liveness_disable,    // no reliable liveness data anymore
1152           _verify_regions_notrash_nocset, // no trash, no cset
1153           _verify_size_exact,           // expect generation and heap sizes to match exactly
1154           _verify_gcstate_stable        // full gc cleaned up everything
1155   );
1156 }
1157 
1158 // TODO: Why this closure does not visit metadata?
1159 class ShenandoahVerifyNoForwared : public BasicOopIterateClosure {
1160 private:
1161   template <class T>
1162   void do_oop_work(T* p) {
1163     T o = RawAccess<>::oop_load(p);
1164     if (!CompressedOops::is_null(o)) {
1165       oop obj = CompressedOops::decode_not_null(o);
1166       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
1167       if (obj != fwd) {
1168         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
1169                                          "Verify Roots", "Should not be forwarded", __FILE__, __LINE__);
1170       }
1171     }
1172   }
1173 
1174 public:
1175   void do_oop(narrowOop* p) { do_oop_work(p); }
1176   void do_oop(oop* p)       { do_oop_work(p); }
1177 };
1178 
1179 // TODO: Why this closure does not visit metadata?
1180 class ShenandoahVerifyInToSpaceClosure : public BasicOopIterateClosure {
1181 private:
1182   template <class T>
1183   void do_oop_work(T* p) {
1184     T o = RawAccess<>::oop_load(p);
1185     if (!CompressedOops::is_null(o)) {
1186       oop obj = CompressedOops::decode_not_null(o);
1187       ShenandoahHeap* heap = ShenandoahHeap::heap();
1188 
1189       if (!heap->marking_context()->is_marked_or_old(obj)) {
1190         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
1191                 "Verify Roots In To-Space", "Should be marked", __FILE__, __LINE__);
1192       }
1193 
1194       if (heap->in_collection_set(obj)) {
1195         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
1196                 "Verify Roots In To-Space", "Should not be in collection set", __FILE__, __LINE__);
1197       }
1198 
1199       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
1200       if (obj != fwd) {
1201         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
1202                 "Verify Roots In To-Space", "Should not be forwarded", __FILE__, __LINE__);
1203       }
1204     }
1205   }
1206 
1207 public:
1208   void do_oop(narrowOop* p) { do_oop_work(p); }
1209   void do_oop(oop* p)       { do_oop_work(p); }
1210 };
1211 
1212 void ShenandoahVerifier::verify_roots_in_to_space() {
1213   ShenandoahVerifyInToSpaceClosure cl;
1214   ShenandoahRootVerifier::roots_do(&cl);
1215 }
1216 
1217 void ShenandoahVerifier::verify_roots_no_forwarded() {
1218   ShenandoahVerifyNoForwared cl;
1219   ShenandoahRootVerifier::roots_do(&cl);
1220 }
1221 
1222 class ShenandoahVerifyRemSetClosure : public BasicOopIterateClosure {
1223 protected:
1224   bool               const _init_mark;
1225   ShenandoahHeap*    const _heap;
1226   RememberedScanner* const _scanner;
1227 
1228 public:
1229   // Argument distinguishes between initial mark or start of update refs verification.
1230   ShenandoahVerifyRemSetClosure(bool init_mark) :
1231             _init_mark(init_mark),
1232             _heap(ShenandoahHeap::heap()),
1233             _scanner(_heap->card_scan()) {}
1234 
1235   template<class T>
1236   inline void work(T* p) {
1237     T o = RawAccess<>::oop_load(p);
1238     if (!CompressedOops::is_null(o)) {
1239       oop obj = CompressedOops::decode_not_null(o);
1240       if (_heap->is_in_young(obj)) {
1241         size_t card_index = _scanner->card_index_for_addr((HeapWord*) p);
1242         if (_init_mark && !_scanner->is_card_dirty(card_index)) {
1243           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
1244                                            "Verify init-mark remembered set violation", "clean card should be dirty", __FILE__, __LINE__);
1245         } else if (!_init_mark && !_scanner->is_write_card_dirty(card_index)) {
1246           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
1247                                            "Verify init-update-refs remembered set violation", "clean card should be dirty", __FILE__, __LINE__);
1248         }
1249       }
1250     }
1251   }
1252 
1253   virtual void do_oop(narrowOop* p) { work(p); }
1254   virtual void do_oop(oop* p)       { work(p); }
1255 };
1256 
1257 void ShenandoahVerifier::help_verify_region_rem_set(ShenandoahHeapRegion* r, ShenandoahMarkingContext* ctx, HeapWord* from,
1258                                                     HeapWord* top, HeapWord* registration_watermark, const char* message) {
1259   RememberedScanner* scanner = _heap->card_scan();
1260   ShenandoahVerifyRemSetClosure check_interesting_pointers(false);
1261 
1262   HeapWord* obj_addr = from;
1263   if (r->is_humongous_start()) {
1264     oop obj = cast_to_oop(obj_addr);
1265     if ((ctx == nullptr) || ctx->is_marked(obj)) {
1266       size_t card_index = scanner->card_index_for_addr(obj_addr);
1267       // For humongous objects, the typical object is an array, so the following checks may be overkill
1268       // For regular objects (not object arrays), if the card holding the start of the object is dirty,
1269       // we do not need to verify that cards spanning interesting pointers within this object are dirty.
1270       if (!scanner->is_write_card_dirty(card_index) || obj->is_objArray()) {
1271         obj->oop_iterate(&check_interesting_pointers);
1272       }
1273       // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
1274     }
1275     // else, this humongous object is not live so no need to verify its internal pointers
1276 
1277     if ((obj_addr < registration_watermark) && !scanner->verify_registration(obj_addr, ctx)) {
1278       ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, nullptr, message,
1279                                        "object not properly registered", __FILE__, __LINE__);
1280     }
1281   } else if (!r->is_humongous()) {
1282     while (obj_addr < top) {
1283       oop obj = cast_to_oop(obj_addr);
1284       // ctx->is_marked() returns true if mark bit set or if obj above TAMS.
1285       if ((ctx == nullptr) || ctx->is_marked(obj)) {
1286         size_t card_index = scanner->card_index_for_addr(obj_addr);
1287         // For regular objects (not object arrays), if the card holding the start of the object is dirty,
1288         // we do not need to verify that cards spanning interesting pointers within this object are dirty.
1289         if (!scanner->is_write_card_dirty(card_index) || obj->is_objArray()) {
1290           obj->oop_iterate(&check_interesting_pointers);
1291         }
1292         // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
1293 
1294         if ((obj_addr < registration_watermark) && !scanner->verify_registration(obj_addr, ctx)) {
1295           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, nullptr, message,
1296                                            "object not properly registered", __FILE__, __LINE__);
1297         }
1298         obj_addr += obj->size();
1299       } else {
1300         // This object is not live so we don't verify dirty cards contained therein
1301         HeapWord* tams = ctx->top_at_mark_start(r);
1302         obj_addr = ctx->get_next_marked_addr(obj_addr, tams);
1303       }
1304     }
1305   }
1306 }
1307 
1308 // Assure that the remember set has a dirty card everywhere there is an interesting pointer.
1309 // This examines the read_card_table between bottom() and top() since all PLABS are retired
1310 // before the safepoint for init_mark.  Actually, we retire them before update-references and don't
1311 // restore them until the start of evacuation.
1312 void ShenandoahVerifier::verify_rem_set_before_mark() {
1313   shenandoah_assert_safepoint();
1314   assert(_heap->mode()->is_generational(), "Only verify remembered set for generational operational modes");
1315 
1316   ShenandoahRegionIterator iterator;
1317   RememberedScanner* scanner = _heap->card_scan();
1318   ShenandoahVerifyRemSetClosure check_interesting_pointers(true);
1319   ShenandoahMarkingContext* ctx;
1320 
1321   log_debug(gc)("Verifying remembered set at %s mark", _heap->doing_mixed_evacuations()? "mixed": "young");
1322 
1323   if (_heap->is_old_bitmap_stable() || _heap->active_generation()->is_global()) {
1324     ctx = _heap->complete_marking_context();
1325   } else {
1326     ctx = nullptr;
1327   }
1328 
1329   while (iterator.has_next()) {
1330     ShenandoahHeapRegion* r = iterator.next();
1331     if (r == nullptr) {
1332       // TODO: Can this really happen?
1333       break;
1334     }
1335 
1336     HeapWord* tams = (ctx != nullptr) ? ctx->top_at_mark_start(r) : nullptr;
1337 
1338     // TODO: Is this replaceable with call to help_verify_region_rem_set?
1339 
1340     if (r->is_old() && r->is_active()) {
1341       HeapWord* obj_addr = r->bottom();
1342       if (r->is_humongous_start()) {
1343         oop obj = cast_to_oop(obj_addr);
1344         if ((ctx == nullptr) || ctx->is_marked(obj)) {
1345           // For humongous objects, the typical object is an array, so the following checks may be overkill
1346           // For regular objects (not object arrays), if the card holding the start of the object is dirty,
1347           // we do not need to verify that cards spanning interesting pointers within this object are dirty.
1348           if (!scanner->is_card_dirty(obj_addr) || obj->is_objArray()) {
1349             obj->oop_iterate(&check_interesting_pointers);
1350           }
1351           // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
1352         }
1353         // else, this humongous object is not marked so no need to verify its internal pointers
1354         if (!scanner->verify_registration(obj_addr, ctx)) {
1355           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, nullptr, nullptr,
1356                                            "Verify init-mark remembered set violation", "object not properly registered", __FILE__, __LINE__);
1357         }
1358       } else if (!r->is_humongous()) {
1359         HeapWord* top = r->top();
1360         while (obj_addr < top) {
1361           oop obj = cast_to_oop(obj_addr);
1362           // ctx->is_marked() returns true if mark bit set (TAMS not relevant during init mark)
1363           if ((ctx == nullptr) || ctx->is_marked(obj)) {
1364             // For regular objects (not object arrays), if the card holding the start of the object is dirty,
1365             // we do not need to verify that cards spanning interesting pointers within this object are dirty.
1366             if (!scanner->is_card_dirty(obj_addr) || obj->is_objArray()) {
1367               obj->oop_iterate(&check_interesting_pointers);
1368             }
1369             // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
1370             if (!scanner->verify_registration(obj_addr, ctx)) {
1371               ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, nullptr, nullptr,
1372                                                "Verify init-mark remembered set violation", "object not properly registered", __FILE__, __LINE__);
1373             }
1374             obj_addr += obj->size();
1375           } else {
1376             // This object is not live so we don't verify dirty cards contained therein
1377             assert(tams != nullptr, "If object is not live, ctx and tams should be non-null");
1378             obj_addr = ctx->get_next_marked_addr(obj_addr, tams);
1379           }
1380         }
1381       } // else, we ignore humongous continuation region
1382     } // else, this is not an OLD region so we ignore it
1383   } // all regions have been processed
1384 }
1385 
1386 void ShenandoahVerifier::verify_rem_set_after_full_gc() {
1387   shenandoah_assert_safepoint();
1388   assert(_heap->mode()->is_generational(), "Only verify remembered set for generational operational modes");
1389 
1390   ShenandoahRegionIterator iterator;
1391 
1392   while (iterator.has_next()) {
1393     ShenandoahHeapRegion* r = iterator.next();
1394     if (r == nullptr) {
1395       // TODO: Can this really happen?
1396       break;
1397     }
1398     if (r->is_old() && !r->is_cset()) {
1399       help_verify_region_rem_set(r, nullptr, r->bottom(), r->top(), r->top(), "Remembered set violation at end of Full GC");
1400     }
1401   }
1402 }
1403 
1404 // Assure that the remember set has a dirty card everywhere there is an interesting pointer.  Even though
1405 // the update-references scan of remembered set only examines cards up to update_watermark, the remembered
1406 // set should be valid through top.  This examines the write_card_table between bottom() and top() because
1407 // all PLABS are retired immediately before the start of update refs.
1408 void ShenandoahVerifier::verify_rem_set_before_update_ref() {
1409   shenandoah_assert_safepoint();
1410   assert(_heap->mode()->is_generational(), "Only verify remembered set for generational operational modes");
1411 
1412   ShenandoahRegionIterator iterator;
1413   ShenandoahMarkingContext* ctx;
1414 
1415   if (_heap->is_old_bitmap_stable() || _heap->active_generation()->is_global()) {
1416     ctx = _heap->complete_marking_context();
1417   } else {
1418     ctx = nullptr;
1419   }
1420 
1421   while (iterator.has_next()) {
1422     ShenandoahHeapRegion* r = iterator.next();
1423     if (r == nullptr) {
1424       // TODO: Can this really happen?
1425       break;
1426     }
1427     if (r->is_old() && !r->is_cset()) {
1428       help_verify_region_rem_set(r, ctx, r->bottom(), r->top(), r->get_update_watermark(),
1429                                  "Remembered set violation at init-update-references");
1430     }
1431   }
1432 }
< prev index next >