< 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,

 468         }
 469     }
 470 
 471     size_t processed = 0;
 472 
 473     if (ShenandoahVerifyLevel >= 3) {
 474       ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 475                                     ShenandoahMessageBuffer("%s, Reachable", _label),
 476                                     _options);
 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_complete_satb_empty ||
  91         options._verify_marked == ShenandoahVerifier::_verify_marked_disable) {
  92       set_ref_discoverer_internal(new ShenandoahIgnoreReferenceDiscoverer());
  93     }
  94 
  95     if (_heap->mode()->is_generational()) {
  96       _generation = _heap->active_generation();
  97       assert(_generation != nullptr, "Expected active generation in this mode");
  98     }
  99   }
 100 
 101 private:
 102   void check(ShenandoahAsserts::SafeLevel level, oop obj, bool test, const char* label) {
 103     if (!test) {
 104       ShenandoahAsserts::print_failure(level, obj, _interior_loc, _loc, _phase, label, __FILE__, __LINE__);
 105     }
 106   }
 107 
 108   template <class T>
 109   void do_oop_work(T* p) {
 110     T o = RawAccess<>::oop_load(p);
 111     if (!CompressedOops::is_null(o)) {
 112       oop obj = CompressedOops::decode_not_null(o);
 113       if (is_instance_ref_klass(obj->klass())) {
 114         obj = ShenandoahForwarding::get_forwardee(obj);
 115       }
 116       // Single threaded verification can use faster non-atomic stack and bitmap
 117       // methods.
 118       //
 119       // For performance reasons, only fully verify non-marked field values.
 120       // We are here when the host object for *p is already marked.
 121 
 122       // TODO: We should consider specializing this closure by generation ==/!= null,
 123       // to avoid in_generation check on fast path here for non-generational mode.
 124       if (in_generation(obj) && _map->par_mark(obj)) {
 125         verify_oop_at(p, obj);
 126         _stack->push(ShenandoahVerifierTask(obj));
 127       }
 128     }
 129   }
 130 
 131   bool in_generation(oop obj) {
 132     if (_generation == nullptr) {
 133       return true;
 134     }
 135 
 136     ShenandoahHeapRegion* region = _heap->heap_region_containing(obj);
 137     return _generation->contains(region);
 138   }
 139 
 140   void verify_oop(oop obj) {
 141     // Perform consistency checks with gradually decreasing safety level. This guarantees
 142     // that failure report would not try to touch something that was not yet verified to be
 143     // safe to process.
 144 
 145     check(ShenandoahAsserts::_safe_unknown, obj, _heap->is_in(obj),
 146               "oop must be in heap");
 147     check(ShenandoahAsserts::_safe_unknown, obj, is_object_aligned(obj),
 148               "oop must be aligned");
 149 
 150     ShenandoahHeapRegion *obj_reg = _heap->heap_region_containing(obj);
 151     Klass* obj_klass = obj->klass_or_null();
 152 
 153     // Verify that obj is not in dead space:
 154     {
 155       // Do this before touching obj->size()
 156       check(ShenandoahAsserts::_safe_unknown, obj, obj_klass != nullptr,
 157              "Object klass pointer should not be null");
 158       check(ShenandoahAsserts::_safe_unknown, obj, Metaspace::contains(obj_klass),
 159              "Object klass pointer must go to metaspace");

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

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

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

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

 582         }
 583     }
 584 
 585     size_t processed = 0;
 586 
 587     if (ShenandoahVerifyLevel >= 3) {
 588       ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 589                                     ShenandoahMessageBuffer("%s, Reachable", _label),
 590                                     _options);
 591       while (!stack.is_empty()) {
 592         processed++;
 593         ShenandoahVerifierTask task = stack.pop();
 594         cl.verify_oops_from(task.obj());
 595       }
 596     }
 597 
 598     Atomic::add(&_processed, processed, memory_order_relaxed);
 599   }
 600 };
 601 
 602 class ShenandoahVerifyNoIncompleteSatbBuffers : public ThreadClosure {
 603 public:
 604   virtual void do_thread(Thread* thread) {
 605     SATBMarkQueue& queue = ShenandoahThreadLocalData::satb_mark_queue(thread);
 606     if (!is_empty(queue)) {
 607       fatal("All SATB buffers should have been flushed during mark");
 608     }
 609   }
 610 private:
 611   bool is_empty(SATBMarkQueue& queue) {
 612     return queue.buffer() == nullptr || queue.index() == queue.capacity();
 613   }
 614 };
 615 
 616 class ShenandoahVerifierMarkedRegionTask : public WorkerTask {
 617 private:
 618   const char* _label;
 619   ShenandoahVerifier::VerifyOptions _options;
 620   ShenandoahHeap *_heap;
 621   MarkBitMap* _bitmap;
 622   ShenandoahLivenessData* _ld;
 623   volatile size_t _claimed;
 624   volatile size_t _processed;
 625   ShenandoahGeneration* _generation;
 626 
 627 public:
 628   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
 629                                      ShenandoahLivenessData* ld,
 630                                      const char* label,
 631                                      ShenandoahVerifier::VerifyOptions options) :
 632           WorkerTask("Shenandoah Verifier Marked Objects"),
 633           _label(label),
 634           _options(options),
 635           _heap(ShenandoahHeap::heap()),
 636           _bitmap(bitmap),
 637           _ld(ld),
 638           _claimed(0),
 639           _processed(0),
 640           _generation(nullptr) {
 641     if (_options._verify_marked == ShenandoahVerifier::_verify_marked_complete_satb_empty) {
 642       Threads::change_thread_claim_token();
 643     }
 644 
 645     if (_heap->mode()->is_generational()) {
 646       _generation = _heap->active_generation();
 647       assert(_generation != nullptr, "Expected active generation in this mode.");
 648     }
 649   };
 650 
 651   size_t processed() {
 652     return Atomic::load(&_processed);
 653   }
 654 
 655   virtual void work(uint worker_id) {
 656     if (_options._verify_marked == ShenandoahVerifier::_verify_marked_complete_satb_empty) {
 657       ShenandoahVerifyNoIncompleteSatbBuffers verify_satb;
 658       Threads::possibly_parallel_threads_do(true, &verify_satb);
 659     }
 660 
 661     ShenandoahVerifierStack stack;
 662     ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 663                                   ShenandoahMessageBuffer("%s, Marked", _label),
 664                                   _options);
 665 
 666     while (true) {
 667       size_t v = Atomic::fetch_then_add(&_claimed, 1u, memory_order_relaxed);
 668       if (v < _heap->num_regions()) {
 669         ShenandoahHeapRegion* r = _heap->get_region(v);
 670         if (!in_generation(r)) {
 671           continue;
 672         }
 673 
 674         if (!r->is_humongous() && !r->is_trash()) {
 675           work_regular(r, stack, cl);
 676         } else if (r->is_humongous_start()) {
 677           work_humongous(r, stack, cl);
 678         }
 679       } else {
 680         break;
 681       }
 682     }
 683   }
 684 
 685   bool in_generation(ShenandoahHeapRegion* r) {
 686     return _generation == nullptr || _generation->contains(r);
 687   }
 688 
 689   virtual void work_humongous(ShenandoahHeapRegion *r, ShenandoahVerifierStack& stack, ShenandoahVerifyOopClosure& cl) {
 690     size_t processed = 0;
 691     HeapWord* obj = r->bottom();
 692     if (_heap->complete_marking_context()->is_marked(cast_to_oop(obj))) {
 693       verify_and_follow(obj, stack, cl, &processed);
 694     }
 695     Atomic::add(&_processed, processed, memory_order_relaxed);
 696   }
 697 
 698   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
 699     size_t processed = 0;
 700     ShenandoahMarkingContext* ctx = _heap->complete_marking_context();
 701     HeapWord* tams = ctx->top_at_mark_start(r);
 702 
 703     // Bitmaps, before TAMS
 704     if (tams > r->bottom()) {
 705       HeapWord* start = r->bottom();
 706       HeapWord* addr = ctx->get_next_marked_addr(start, tams);
 707 
 708       while (addr < tams) {

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