1 /*
   2  * Copyright (c) 2017, 2019, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 
  26 #include "gc_implementation/shenandoah/shenandoahAsserts.hpp"
  27 #include "gc_implementation/shenandoah/shenandoahForwarding.hpp"
  28 #include "gc_implementation/shenandoah/shenandoahHeap.hpp"
  29 #include "gc_implementation/shenandoah/shenandoahHeap.inline.hpp"
  30 #include "gc_implementation/shenandoah/shenandoahRootProcessor.hpp"
  31 #include "gc_implementation/shenandoah/shenandoahUtils.hpp"
  32 #include "gc_implementation/shenandoah/shenandoahVerifier.hpp"
  33 #include "gc_implementation/shenandoah/shenandoahWorkGroup.hpp"
  34 #include "memory/allocation.hpp"
  35 #include "memory/resourceArea.hpp"
  36 
  37 // Avoid name collision on verify_oop (defined in macroAssembler_arm.hpp)
  38 #ifdef verify_oop
  39 #undef verify_oop
  40 #endif
  41 
  42 class ShenandoahVerifyOopClosure : public ExtendedOopClosure {
  43 private:
  44   const char* _phase;
  45   ShenandoahVerifier::VerifyOptions _options;
  46   ShenandoahVerifierStack* _stack;
  47   ShenandoahHeap* _heap;
  48   MarkBitMap* _map;
  49   ShenandoahLivenessData* _ld;
  50   void* _interior_loc;
  51   oop _loc;
  52 
  53 public:
  54   ShenandoahVerifyOopClosure(ShenandoahVerifierStack* stack, MarkBitMap* map, ShenandoahLivenessData* ld,
  55                              const char* phase, ShenandoahVerifier::VerifyOptions options) :
  56     _phase(phase),
  57     _options(options),
  58     _stack(stack),
  59     _heap(ShenandoahHeap::heap()),
  60     _map(map),
  61     _ld(ld),
  62     _interior_loc(NULL),
  63     _loc(NULL) { }
  64 
  65 private:
  66   void verify(ShenandoahAsserts::SafeLevel level, oop obj, bool test, const char* label) {
  67     if (!test) {
  68       ShenandoahAsserts::print_failure(level, obj, _interior_loc, _loc, _phase, label, __FILE__, __LINE__);
  69     }
  70   }
  71 
  72   template <class T>
  73   void do_oop_work(T* p) {
  74     T o = oopDesc::load_heap_oop(p);
  75     if (!oopDesc::is_null(o)) {
  76       oop obj = oopDesc::decode_heap_oop_not_null(o);
  77 
  78       // Single threaded verification can use faster non-atomic stack and bitmap
  79       // methods.
  80       //
  81       // For performance reasons, only fully verify non-marked field values.
  82       // We are here when the host object for *p is already marked.
  83 
  84       HeapWord* addr = (HeapWord*) obj;
  85       if (_map->parMark(addr)) {
  86         verify_oop_at(p, obj);
  87         _stack->push(ShenandoahVerifierTask(obj));
  88       }
  89     }
  90   }
  91 
  92   void verify_oop(oop obj) {
  93     // Perform consistency checks with gradually decreasing safety level. This guarantees
  94     // that failure report would not try to touch something that was not yet verified to be
  95     // safe to process.
  96 
  97     verify(ShenandoahAsserts::_safe_unknown, obj, _heap->is_in(obj),
  98            "oop must be in heap");
  99     verify(ShenandoahAsserts::_safe_unknown, obj, check_obj_alignment(obj),
 100            "oop must be aligned");
 101 
 102     ShenandoahHeapRegion *obj_reg = _heap->heap_region_containing(obj);
 103     Klass* obj_klass = obj->klass_or_null();
 104 
 105     // Verify that obj is not in dead space:
 106     {
 107       // Do this before touching obj->size()
 108       verify(ShenandoahAsserts::_safe_unknown, obj, obj_klass != NULL,
 109              "Object klass pointer should not be NULL");
 110       verify(ShenandoahAsserts::_safe_unknown, obj, Metaspace::contains(obj_klass),
 111              "Object klass pointer must go to metaspace");
 112 
 113       HeapWord *obj_addr = (HeapWord *) obj;
 114       verify(ShenandoahAsserts::_safe_unknown, obj, obj_addr < obj_reg->top(),
 115              "Object start should be within the region");
 116 
 117       if (!obj_reg->is_humongous()) {
 118         verify(ShenandoahAsserts::_safe_unknown, obj, (obj_addr + obj->size()) <= obj_reg->top(),
 119                "Object end should be within the region");
 120       } else {
 121         size_t humongous_start = obj_reg->region_number();
 122         size_t humongous_end = humongous_start + (obj->size() >> ShenandoahHeapRegion::region_size_words_shift());
 123         for (size_t idx = humongous_start + 1; idx < humongous_end; idx++) {
 124           verify(ShenandoahAsserts::_safe_unknown, obj, _heap->get_region(idx)->is_humongous_continuation(),
 125                  "Humongous object is in continuation that fits it");
 126         }
 127       }
 128 
 129       // ------------ obj is safe at this point --------------
 130 
 131       verify(ShenandoahAsserts::_safe_oop, obj, obj_reg->is_active(),
 132             "Object should be in active region");
 133 
 134       switch (_options._verify_liveness) {
 135         case ShenandoahVerifier::_verify_liveness_disable:
 136           // skip
 137           break;
 138         case ShenandoahVerifier::_verify_liveness_complete:
 139           Atomic::add((uint) obj->size(), &_ld[obj_reg->region_number()]);
 140           // fallthrough for fast failure for un-live regions:
 141         case ShenandoahVerifier::_verify_liveness_conservative:
 142           verify(ShenandoahAsserts::_safe_oop, obj, obj_reg->has_live(),
 143                    "Object must belong to region with live data");
 144           break;
 145         default:
 146           assert(false, "Unhandled liveness verification");
 147       }
 148     }
 149 
 150     oop fwd = (oop) ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
 151 
 152     ShenandoahHeapRegion* fwd_reg = NULL;
 153 
 154     if (obj != fwd) {
 155       verify(ShenandoahAsserts::_safe_oop, obj, _heap->is_in(fwd),
 156              "Forwardee must be in heap");
 157       verify(ShenandoahAsserts::_safe_oop, obj, !oopDesc::is_null(fwd),
 158              "Forwardee is set");
 159       verify(ShenandoahAsserts::_safe_oop, obj, check_obj_alignment(fwd),
 160              "Forwardee must be aligned");
 161 
 162       // Do this before touching fwd->size()
 163       Klass* fwd_klass = fwd->klass_or_null();
 164       verify(ShenandoahAsserts::_safe_oop, obj, fwd_klass != NULL,
 165              "Forwardee klass pointer should not be NULL");
 166       verify(ShenandoahAsserts::_safe_oop, obj, Metaspace::contains(fwd_klass),
 167              "Forwardee klass pointer must go to metaspace");
 168       verify(ShenandoahAsserts::_safe_oop, obj, obj_klass == fwd_klass,
 169              "Forwardee klass pointer must go to metaspace");
 170 
 171       fwd_reg = _heap->heap_region_containing(fwd);
 172 
 173       // Verify that forwardee is not in the dead space:
 174       verify(ShenandoahAsserts::_safe_oop, obj, !fwd_reg->is_humongous(),
 175              "Should have no humongous forwardees");
 176 
 177       HeapWord *fwd_addr = (HeapWord *) fwd;
 178       verify(ShenandoahAsserts::_safe_oop, obj, fwd_addr < fwd_reg->top(),
 179              "Forwardee start should be within the region");
 180       verify(ShenandoahAsserts::_safe_oop, obj, (fwd_addr + fwd->size()) <= fwd_reg->top(),
 181              "Forwardee end should be within the region");
 182 
 183       oop fwd2 = (oop) ShenandoahForwarding::get_forwardee_raw_unchecked(fwd);
 184       verify(ShenandoahAsserts::_safe_oop, obj, fwd == fwd2,
 185              "Double forwarding");
 186     } else {
 187       fwd_reg = obj_reg;
 188     }
 189 
 190     // ------------ obj and fwd are safe at this point --------------
 191 
 192     switch (_options._verify_marked) {
 193       case ShenandoahVerifier::_verify_marked_disable:
 194         // skip
 195         break;
 196       case ShenandoahVerifier::_verify_marked_incomplete:
 197         verify(ShenandoahAsserts::_safe_all, obj, _heap->marking_context()->is_marked(obj),
 198                "Must be marked in incomplete bitmap");
 199       case ShenandoahVerifier::_verify_marked_complete:
 200         verify(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
 201                "Must be marked in complete bitmap");
 202         break;
 203       default:
 204         assert(false, "Unhandled mark verification");
 205     }
 206 
 207     switch (_options._verify_forwarded) {
 208       case ShenandoahVerifier::_verify_forwarded_disable:
 209         // skip
 210         break;
 211       case ShenandoahVerifier::_verify_forwarded_none: {
 212         verify(ShenandoahAsserts::_safe_all, obj, obj == fwd,
 213                "Should not be forwarded");
 214         break;
 215       }
 216       case ShenandoahVerifier::_verify_forwarded_allow: {
 217         if (obj != fwd) {
 218           verify(ShenandoahAsserts::_safe_all, obj, obj_reg != fwd_reg,
 219                  "Forwardee should be in another region");
 220         }
 221         break;
 222       }
 223       default:
 224         assert(false, "Unhandled forwarding verification");
 225     }
 226 
 227     switch (_options._verify_cset) {
 228       case ShenandoahVerifier::_verify_cset_disable:
 229         // skip
 230         break;
 231       case ShenandoahVerifier::_verify_cset_none:
 232         verify(ShenandoahAsserts::_safe_all, obj, !_heap->in_collection_set(obj),
 233                "Should not have references to collection set");
 234         break;
 235       case ShenandoahVerifier::_verify_cset_forwarded:
 236         if (_heap->in_collection_set(obj)) {
 237           verify(ShenandoahAsserts::_safe_all, obj, obj != fwd,
 238                  "Object in collection set, should have forwardee");
 239         }
 240         break;
 241       default:
 242         assert(false, "Unhandled cset verification");
 243     }
 244   }
 245 
 246 public:
 247   /**
 248    * Verify object with known interior reference.
 249    * @param p interior reference where the object is referenced from; can be off-heap
 250    * @param obj verified object
 251    */
 252   template <class T>
 253   void verify_oop_at(T* p, oop obj) {
 254     _interior_loc = p;
 255     verify_oop(obj);
 256     _interior_loc = NULL;
 257   }
 258 
 259   /**
 260    * Verify object without known interior reference.
 261    * Useful when picking up the object at known offset in heap,
 262    * but without knowing what objects reference it.
 263    * @param obj verified object
 264    */
 265   void verify_oop_standalone(oop obj) {
 266     _interior_loc = NULL;
 267     verify_oop(obj);
 268     _interior_loc = NULL;
 269   }
 270 
 271   /**
 272    * Verify oop fields from this object.
 273    * @param obj host object for verified fields
 274    */
 275   void verify_oops_from(oop obj) {
 276     _loc = obj;
 277     obj->oop_iterate(this);
 278     _loc = NULL;
 279   }
 280 
 281   void do_oop(oop* p) { do_oop_work(p); }
 282   void do_oop(narrowOop* p) { do_oop_work(p); }
 283 };
 284 
 285 class ShenandoahCalculateRegionStatsClosure : public ShenandoahHeapRegionClosure {
 286 private:
 287   size_t _used, _committed, _garbage;
 288 public:
 289   ShenandoahCalculateRegionStatsClosure() : _used(0), _committed(0), _garbage(0) {};
 290 
 291   void heap_region_do(ShenandoahHeapRegion* r) {
 292     _used += r->used();
 293     _garbage += r->garbage();
 294     _committed += r->is_committed() ? ShenandoahHeapRegion::region_size_bytes() : 0;
 295   }
 296 
 297   size_t used() { return _used; }
 298   size_t committed() { return _committed; }
 299   size_t garbage() { return _garbage; }
 300 };
 301 
 302 class ShenandoahVerifyHeapRegionClosure : public ShenandoahHeapRegionClosure {
 303 private:
 304   ShenandoahHeap* _heap;
 305   const char* _phase;
 306   ShenandoahVerifier::VerifyRegions _regions;
 307 public:
 308   ShenandoahVerifyHeapRegionClosure(const char* phase, ShenandoahVerifier::VerifyRegions regions) :
 309     _heap(ShenandoahHeap::heap()),
 310     _phase(phase),
 311     _regions(regions) {};
 312 
 313   void print_failure(ShenandoahHeapRegion* r, const char* label) {
 314     ResourceMark rm;
 315 
 316     ShenandoahMessageBuffer msg("Shenandoah verification failed; %s: %s\n\n", _phase, label);
 317 
 318     stringStream ss;
 319     r->print_on(&ss);
 320     msg.append("%s", ss.as_string());
 321 
 322     report_vm_error(__FILE__, __LINE__, msg.buffer());
 323   }
 324 
 325   void verify(ShenandoahHeapRegion* r, bool test, const char* msg) {
 326     if (!test) {
 327       print_failure(r, msg);
 328     }
 329   }
 330 
 331   void heap_region_do(ShenandoahHeapRegion* r) {
 332     switch (_regions) {
 333       case ShenandoahVerifier::_verify_regions_disable:
 334         break;
 335       case ShenandoahVerifier::_verify_regions_notrash:
 336         verify(r, !r->is_trash(),
 337                "Should not have trash regions");
 338         break;
 339       case ShenandoahVerifier::_verify_regions_nocset:
 340         verify(r, !r->is_cset(),
 341                "Should not have cset regions");
 342         break;
 343       case ShenandoahVerifier::_verify_regions_notrash_nocset:
 344         verify(r, !r->is_trash(),
 345                "Should not have trash regions");
 346         verify(r, !r->is_cset(),
 347                "Should not have cset regions");
 348         break;
 349       default:
 350         ShouldNotReachHere();
 351     }
 352 
 353     verify(r, r->capacity() == ShenandoahHeapRegion::region_size_bytes(),
 354            "Capacity should match region size");
 355 
 356     verify(r, r->bottom() <= r->top(),
 357            "Region top should not be less than bottom");
 358 
 359     verify(r, r->bottom() <= _heap->marking_context()->top_at_mark_start(r),
 360            "Region TAMS should not be less than bottom");
 361 
 362     verify(r, _heap->marking_context()->top_at_mark_start(r) <= r->top(),
 363            "Complete TAMS should not be larger than top");
 364 
 365     verify(r, r->get_live_data_bytes() <= r->capacity(),
 366            "Live data cannot be larger than capacity");
 367 
 368     verify(r, r->garbage() <= r->capacity(),
 369            "Garbage cannot be larger than capacity");
 370 
 371     verify(r, r->used() <= r->capacity(),
 372            "Used cannot be larger than capacity");
 373 
 374     verify(r, r->get_shared_allocs() <= r->capacity(),
 375            "Shared alloc count should not be larger than capacity");
 376 
 377     verify(r, r->get_tlab_allocs() <= r->capacity(),
 378            "TLAB alloc count should not be larger than capacity");
 379 
 380     verify(r, r->get_gclab_allocs() <= r->capacity(),
 381            "GCLAB alloc count should not be larger than capacity");
 382 
 383     verify(r, r->get_shared_allocs() + r->get_tlab_allocs() + r->get_gclab_allocs() == r->used(),
 384            "Accurate accounting: shared + TLAB + GCLAB = used");
 385 
 386     verify(r, !r->is_empty() || !r->has_live(),
 387            "Empty regions should not have live data");
 388 
 389     verify(r, r->is_cset() == _heap->collection_set()->is_in(r),
 390            "Transitional: region flags and collection set agree");
 391 
 392     verify(r, r->is_empty() || r->seqnum_first_alloc() != 0,
 393            "Non-empty regions should have first seqnum set");
 394 
 395     verify(r, r->is_empty() || (r->seqnum_first_alloc_mutator() != 0 || r->seqnum_first_alloc_gc() != 0),
 396            "Non-empty regions should have first seqnum set to either GC or mutator");
 397 
 398     verify(r, r->is_empty() || r->seqnum_last_alloc() != 0,
 399            "Non-empty regions should have last seqnum set");
 400 
 401     verify(r, r->is_empty() || (r->seqnum_last_alloc_mutator() != 0 || r->seqnum_last_alloc_gc() != 0),
 402            "Non-empty regions should have last seqnum set to either GC or mutator");
 403 
 404     verify(r, r->seqnum_first_alloc() <= r->seqnum_last_alloc(),
 405            "First seqnum should not be greater than last timestamp");
 406 
 407     verify(r, r->seqnum_first_alloc_mutator() <= r->seqnum_last_alloc_mutator(),
 408            "First mutator seqnum should not be greater than last seqnum");
 409 
 410     verify(r, r->seqnum_first_alloc_gc() <= r->seqnum_last_alloc_gc(),
 411            "First GC seqnum should not be greater than last seqnum");
 412   }
 413 };
 414 
 415 class ShenandoahVerifierReachableTask : public AbstractGangTask {
 416 private:
 417   const char* _label;
 418   ShenandoahRootProcessor* _rp;
 419   ShenandoahVerifier::VerifyOptions _options;
 420   ShenandoahHeap* _heap;
 421   ShenandoahLivenessData* _ld;
 422   MarkBitMap* _bitmap;
 423   volatile jlong _processed;
 424 
 425 public:
 426   ShenandoahVerifierReachableTask(MarkBitMap* bitmap,
 427                                   ShenandoahLivenessData* ld,
 428                                   ShenandoahRootProcessor* rp,
 429                                   const char* label,
 430                                   ShenandoahVerifier::VerifyOptions options) :
 431     AbstractGangTask("Shenandoah Parallel Verifier Reachable Task"),
 432     _label(label),
 433     _rp(rp),
 434     _options(options),
 435     _heap(ShenandoahHeap::heap()),
 436     _ld(ld),
 437     _bitmap(bitmap),
 438     _processed(0) {};
 439 
 440   size_t processed() {
 441     return (size_t) _processed;
 442   }
 443 
 444   virtual void work(uint worker_id) {
 445     ResourceMark rm;
 446     ShenandoahVerifierStack stack;
 447 
 448     // On level 2, we need to only check the roots once.
 449     // On level 3, we want to check the roots, and seed the local stack.
 450     // It is a lesser evil to accept multiple root scans at level 3, because
 451     // extended parallelism would buy us out.
 452     if (((ShenandoahVerifyLevel == 2) && (worker_id == 0))
 453         || (ShenandoahVerifyLevel >= 3)) {
 454         ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 455                                       ShenandoahMessageBuffer("Shenandoah verification failed; %s, Roots", _label),
 456                                       _options);
 457         _rp->process_all_roots_slow(&cl);
 458     }
 459 
 460     jlong processed = 0;
 461 
 462     if (ShenandoahVerifyLevel >= 3) {
 463       ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 464                                     ShenandoahMessageBuffer("Shenandoah verification failed; %s, Reachable", _label),
 465                                     _options);
 466       while (!stack.is_empty()) {
 467         processed++;
 468         ShenandoahVerifierTask task = stack.pop();
 469         cl.verify_oops_from(task.obj());
 470       }
 471     }
 472 
 473     Atomic::add(processed, &_processed);
 474   }
 475 };
 476 
 477 class ShenandoahVerifierMarkedRegionTask : public AbstractGangTask {
 478 private:
 479   const char* _label;
 480   ShenandoahVerifier::VerifyOptions _options;
 481   ShenandoahHeap *_heap;
 482   ShenandoahLivenessData* _ld;
 483   MarkBitMap* _bitmap;
 484   volatile jint  _claimed;
 485   volatile jlong _processed;
 486 
 487 public:
 488   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
 489                                      ShenandoahLivenessData* ld,
 490                                      const char* label,
 491                                      ShenandoahVerifier::VerifyOptions options) :
 492           AbstractGangTask("Shenandoah Parallel Verifier Marked Region"),
 493           _label(label),
 494           _options(options),
 495           _heap(ShenandoahHeap::heap()),
 496           _bitmap(bitmap),
 497           _ld(ld),
 498           _claimed(0),
 499           _processed(0) {};
 500 
 501   size_t processed() {
 502     return (size_t) _processed;
 503   }
 504 
 505   virtual void work(uint worker_id) {
 506     ShenandoahVerifierStack stack;
 507     ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 508                                   ShenandoahMessageBuffer("Shenandoah verification failed; %s, Marked", _label),
 509                                   _options);
 510     assert((size_t)max_jint >= _heap->num_regions(), "Too many regions");
 511     while (true) {
 512       size_t v = (size_t) (Atomic::add(1, &_claimed) - 1);
 513       if (v < _heap->num_regions()) {
 514         ShenandoahHeapRegion* r = _heap->get_region(v);
 515         if (!r->is_humongous() && !r->is_trash()) {
 516           work_regular(r, stack, cl);
 517         } else if (r->is_humongous_start()) {
 518           work_humongous(r, stack, cl);
 519         }
 520       } else {
 521         break;
 522       }
 523     }
 524   }
 525 
 526   virtual void work_humongous(ShenandoahHeapRegion *r, ShenandoahVerifierStack& stack, ShenandoahVerifyOopClosure& cl) {
 527     jlong processed = 0;
 528     HeapWord* obj = r->bottom();
 529     if (_heap->complete_marking_context()->is_marked((oop)obj)) {
 530       verify_and_follow(obj, stack, cl, &processed);
 531     }
 532     Atomic::add(processed, &_processed);
 533   }
 534 
 535   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
 536     jlong processed = 0;
 537     MarkBitMap* mark_bit_map = _heap->complete_marking_context()->mark_bit_map();
 538     HeapWord* tams = _heap->complete_marking_context()->top_at_mark_start(r);
 539 
 540     // Bitmaps, before TAMS
 541     if (tams > r->bottom()) {
 542       HeapWord* start = r->bottom();
 543       HeapWord* addr = mark_bit_map->getNextMarkedWordAddress(start, tams);
 544 
 545       while (addr < tams) {
 546         verify_and_follow(addr, stack, cl, &processed);
 547         addr += 1;
 548         if (addr < tams) {
 549           addr = mark_bit_map->getNextMarkedWordAddress(addr, tams);
 550         }
 551       }
 552     }
 553 
 554     // Size-based, after TAMS
 555     {
 556       HeapWord* limit = r->top();
 557       HeapWord* addr = tams;
 558 
 559       while (addr < limit) {
 560         verify_and_follow(addr, stack, cl, &processed);
 561         addr += oop(addr)->size();
 562       }
 563     }
 564 
 565     Atomic::add(processed, &_processed);
 566   }
 567 
 568   void verify_and_follow(HeapWord *addr, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl, jlong *processed) {
 569     if (!_bitmap->parMark(addr)) return;
 570 
 571     // Verify the object itself:
 572     oop obj = oop(addr);
 573     cl.verify_oop_standalone(obj);
 574 
 575     // Verify everything reachable from that object too, hopefully realizing
 576     // everything was already marked, and never touching further:
 577     cl.verify_oops_from(obj);
 578     (*processed)++;
 579 
 580     while (!stack.is_empty()) {
 581       ShenandoahVerifierTask task = stack.pop();
 582       cl.verify_oops_from(task.obj());
 583       (*processed)++;
 584     }
 585   }
 586 };
 587 
 588 class VerifyThreadGCState : public ThreadClosure {
 589 private:
 590   const char* _label;
 591   char _expected;
 592 
 593 public:
 594   VerifyThreadGCState(const char* label, char expected) : _expected(expected) {}
 595   void do_thread(Thread* t) {
 596     assert(t->is_Java_thread(), "sanity");
 597     char actual = ((JavaThread*)t)->gc_state();
 598     if (actual != _expected) {
 599       fatal(err_msg("%s: Thread %s: expected gc-state %d, actual %d", _label, t->name(), _expected, actual));
 600     }
 601   }
 602 };
 603 
 604 void ShenandoahVerifier::verify_at_safepoint(const char *label,
 605                                              VerifyForwarded forwarded, VerifyMarked marked,
 606                                              VerifyCollectionSet cset,
 607                                              VerifyLiveness liveness, VerifyRegions regions,
 608                                              VerifyGCState gcstate) {
 609   guarantee(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "only when nothing else happens");
 610   guarantee(ShenandoahVerify, "only when enabled, and bitmap is initialized in ShenandoahHeap::initialize");
 611 
 612   // Avoid side-effect of changing workers' active thread count, but bypass concurrent/parallel protocol check
 613   ShenandoahPushWorkerScope verify_worker_scope(_heap->workers(), _heap->max_workers(), false /*bypass check*/);
 614 
 615   log_info(gc,start)("Verify %s, Level " INTX_FORMAT, label, ShenandoahVerifyLevel);
 616 
 617   // GC state checks
 618   {
 619     char expected = -1;
 620     bool enabled;
 621     switch (gcstate) {
 622       case _verify_gcstate_disable:
 623         enabled = false;
 624         break;
 625       case _verify_gcstate_forwarded:
 626         enabled = true;
 627         expected = ShenandoahHeap::HAS_FORWARDED;
 628         break;
 629       case _verify_gcstate_evacuation:
 630         enabled = true;
 631         expected = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::EVACUATION;
 632         break;
 633       case _verify_gcstate_stable:
 634         enabled = true;
 635         expected = ShenandoahHeap::STABLE;
 636         break;
 637       default:
 638         enabled = false;
 639         assert(false, "Unhandled gc-state verification");
 640     }
 641 
 642     if (enabled) {
 643       char actual = _heap->gc_state();
 644       if (actual != expected) {
 645         fatal(err_msg("%s: Global gc-state: expected %d, actual %d", label, expected, actual));
 646       }
 647 
 648       VerifyThreadGCState vtgcs(label, expected);
 649       Threads::java_threads_do(&vtgcs);
 650     }
 651   }
 652 
 653   // Heap size checks
 654   {
 655     ShenandoahHeapLocker lock(_heap->lock());
 656 
 657     ShenandoahCalculateRegionStatsClosure cl;
 658     _heap->heap_region_iterate(&cl);
 659     size_t heap_used = _heap->used();
 660     guarantee(cl.used() == heap_used,
 661               err_msg("%s: heap used size must be consistent: heap-used = " SIZE_FORMAT "%s, regions-used = " SIZE_FORMAT "%s",
 662                       label,
 663                       byte_size_in_proper_unit(heap_used), proper_unit_for_byte_size(heap_used),
 664                       byte_size_in_proper_unit(cl.used()), proper_unit_for_byte_size(cl.used())));
 665 
 666     size_t heap_committed = _heap->committed();
 667     guarantee(cl.committed() == heap_committed,
 668               err_msg("%s: heap committed size must be consistent: heap-committed = " SIZE_FORMAT "%s, regions-committed = " SIZE_FORMAT "%s",
 669                       label,
 670                       byte_size_in_proper_unit(heap_committed), proper_unit_for_byte_size(heap_committed),
 671                       byte_size_in_proper_unit(cl.committed()), proper_unit_for_byte_size(cl.committed())));
 672   }
 673 
 674   // Internal heap region checks
 675   if (ShenandoahVerifyLevel >= 1) {
 676     ShenandoahVerifyHeapRegionClosure cl(label, regions);
 677     _heap->heap_region_iterate(&cl);
 678   }
 679 
 680   OrderAccess::fence();
 681   _heap->make_parsable(false);
 682 
 683   // Allocate temporary bitmap for storing marking wavefront:
 684   _verification_bit_map->clear();
 685 
 686   // Allocate temporary array for storing liveness data
 687   ShenandoahLivenessData* ld = NEW_C_HEAP_ARRAY(ShenandoahLivenessData, _heap->num_regions(), mtGC);
 688   Copy::fill_to_bytes((void*)ld, _heap->num_regions()*sizeof(ShenandoahLivenessData), 0);
 689 
 690   const VerifyOptions& options = ShenandoahVerifier::VerifyOptions(forwarded, marked, cset, liveness, regions, gcstate);
 691 
 692   // Steps 1-2. Scan root set to get initial reachable set. Finish walking the reachable heap.
 693   // This verifies what application can see, since it only cares about reachable objects.
 694   size_t count_reachable = 0;
 695   if (ShenandoahVerifyLevel >= 2) {
 696     ShenandoahRootProcessor rp(_heap, _heap->workers()->active_workers(),
 697                                ShenandoahPhaseTimings::_num_phases); // no need for stats
 698 
 699     ShenandoahVerifierReachableTask task(_verification_bit_map, ld, &rp, label, options);
 700     _heap->workers()->run_task(&task);
 701     count_reachable = task.processed();
 702   }
 703 
 704   // Step 3. Walk marked objects. Marked objects might be unreachable. This verifies what collector,
 705   // not the application, can see during the region scans. There is no reason to process the objects
 706   // that were already verified, e.g. those marked in verification bitmap. There is interaction with TAMS:
 707   // before TAMS, we verify the bitmaps, if available; after TAMS, we walk until the top(). It mimics
 708   // what marked_object_iterate is doing, without calling into that optimized (and possibly incorrect)
 709   // version
 710 
 711   size_t count_marked = 0;
 712   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete) {
 713     guarantee(_heap->marking_context()->is_complete(), "Marking context should be complete");
 714     ShenandoahVerifierMarkedRegionTask task(_verification_bit_map, ld, label, options);
 715     _heap->workers()->run_task(&task);
 716     count_marked = task.processed();
 717   } else {
 718     guarantee(ShenandoahVerifyLevel < 4 || marked == _verify_marked_incomplete || marked == _verify_marked_disable, "Should be");
 719   }
 720 
 721   // Step 4. Verify accumulated liveness data, if needed. Only reliable if verification level includes
 722   // marked objects.
 723 
 724   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete && liveness == _verify_liveness_complete) {
 725     for (size_t i = 0; i < _heap->num_regions(); i++) {
 726       ShenandoahHeapRegion* r = _heap->get_region(i);
 727 
 728       jint verf_live = 0;
 729       if (r->is_humongous()) {
 730         // For humongous objects, test if start region is marked live, and if so,
 731         // all humongous regions in that chain have live data equal to their "used".
 732         jint start_live = OrderAccess::load_acquire(&ld[r->humongous_start_region()->region_number()]);
 733         if (start_live > 0) {
 734           verf_live = (jint)(r->used() / HeapWordSize);
 735         }
 736       } else {
 737         verf_live = OrderAccess::load_acquire(&ld[r->region_number()]);
 738       }
 739 
 740       size_t reg_live = r->get_live_data_words();
 741       if (reg_live != (size_t)verf_live) {
 742         ResourceMark rm;
 743         stringStream ss;
 744         r->print_on(&ss);
 745         fatal(err_msg("%s: Live data should match: region-live = " SIZE_FORMAT ", verifier-live = " INT32_FORMAT "\n%s",
 746                       label, reg_live, verf_live, ss.as_string()));
 747       }
 748     }
 749   }
 750 
 751   log_info(gc)("Verify %s, Level " INTX_FORMAT " (" SIZE_FORMAT " reachable, " SIZE_FORMAT " marked)",
 752                label, ShenandoahVerifyLevel, count_reachable, count_marked);
 753 
 754   FREE_C_HEAP_ARRAY(ShenandoahLivenessData, ld, mtGC);
 755 }
 756 
 757 void ShenandoahVerifier::verify_generic(VerifyOption vo) {
 758   verify_at_safepoint(
 759           "Generic Verification",
 760           _verify_forwarded_allow,     // conservatively allow forwarded
 761           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 762           _verify_cset_disable,        // cset may be inconsistent
 763           _verify_liveness_disable,    // no reliable liveness data
 764           _verify_regions_disable,     // no reliable region data
 765           _verify_gcstate_disable      // no data about gcstate
 766   );
 767 }
 768 
 769 void ShenandoahVerifier::verify_before_concmark() {
 770   if (_heap->has_forwarded_objects()) {
 771     verify_at_safepoint(
 772             "Before Mark",
 773             _verify_forwarded_allow,     // may have forwarded references
 774             _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 775             _verify_cset_forwarded,      // allow forwarded references to cset
 776             _verify_liveness_disable,    // no reliable liveness data
 777             _verify_regions_notrash,     // no trash regions
 778             _verify_gcstate_forwarded    // there are forwarded objects
 779     );
 780   } else {
 781     verify_at_safepoint(
 782             "Before Mark",
 783             _verify_forwarded_none,      // UR should have fixed up
 784             _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 785             _verify_cset_none,           // UR should have fixed this
 786             _verify_liveness_disable,    // no reliable liveness data
 787             _verify_regions_notrash,     // no trash regions
 788             _verify_gcstate_stable       // there are no forwarded objects
 789     );
 790   }
 791 }
 792 
 793 void ShenandoahVerifier::verify_after_concmark() {
 794   verify_at_safepoint(
 795           "After Mark",
 796           _verify_forwarded_none,      // no forwarded references
 797           _verify_marked_complete,     // bitmaps as precise as we can get
 798           _verify_cset_none,           // no references to cset anymore
 799           _verify_liveness_complete,   // liveness data must be complete here
 800           _verify_regions_disable,     // trash regions not yet recycled
 801           _verify_gcstate_stable       // mark should have stabilized the heap
 802   );
 803 }
 804 
 805 void ShenandoahVerifier::verify_before_evacuation() {
 806   verify_at_safepoint(
 807           "Before Evacuation",
 808           _verify_forwarded_none,    // no forwarded references
 809           _verify_marked_complete,   // walk over marked objects too
 810           _verify_cset_disable,      // non-forwarded references to cset expected
 811           _verify_liveness_complete, // liveness data must be complete here
 812           _verify_regions_disable,   // trash regions not yet recycled
 813           _verify_gcstate_stable     // mark should have stabilized the heap
 814   );
 815 }
 816 
 817 void ShenandoahVerifier::verify_during_evacuation() {
 818   verify_at_safepoint(
 819           "During Evacuation",
 820           _verify_forwarded_allow,   // some forwarded references are allowed
 821           _verify_marked_disable,    // walk only roots
 822           _verify_cset_disable,      // some cset references are not forwarded yet
 823           _verify_liveness_disable,  // liveness data might be already stale after pre-evacs
 824           _verify_regions_disable,   // trash regions not yet recycled
 825           _verify_gcstate_evacuation // evacuation is in progress
 826   );
 827 }
 828 
 829 void ShenandoahVerifier::verify_after_evacuation() {
 830   verify_at_safepoint(
 831           "After Evacuation",
 832           _verify_forwarded_allow,     // objects are still forwarded
 833           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 834           _verify_cset_forwarded,      // all cset refs are fully forwarded
 835           _verify_liveness_disable,    // no reliable liveness data anymore
 836           _verify_regions_notrash,     // trash regions have been recycled already
 837           _verify_gcstate_forwarded    // evacuation produced some forwarded objects
 838   );
 839 }
 840 
 841 void ShenandoahVerifier::verify_before_updaterefs() {
 842   verify_at_safepoint(
 843           "Before Updating References",
 844           _verify_forwarded_allow,     // forwarded references allowed
 845           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 846           _verify_cset_forwarded,      // all cset refs are fully forwarded
 847           _verify_liveness_disable,    // no reliable liveness data anymore
 848           _verify_regions_notrash,     // trash regions have been recycled already
 849           _verify_gcstate_forwarded    // evacuation should have produced some forwarded objects
 850   );
 851 }
 852 
 853 void ShenandoahVerifier::verify_after_updaterefs() {
 854   verify_at_safepoint(
 855           "After Updating References",
 856           _verify_forwarded_none,      // no forwarded references
 857           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 858           _verify_cset_none,           // no cset references, all updated
 859           _verify_liveness_disable,    // no reliable liveness data anymore
 860           _verify_regions_nocset,      // no cset regions, trash regions have appeared
 861           _verify_gcstate_stable       // update refs had cleaned up forwarded objects
 862   );
 863 }
 864 
 865 void ShenandoahVerifier::verify_before_fullgc() {
 866   verify_at_safepoint(
 867           "Before Full GC",
 868           _verify_forwarded_allow,     // can have forwarded objects
 869           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 870           _verify_cset_disable,        // cset might be foobared
 871           _verify_liveness_disable,    // no reliable liveness data anymore
 872           _verify_regions_disable,     // no reliable region data here
 873           _verify_gcstate_disable      // no reliable gcstate data
 874   );
 875 }
 876 
 877 void ShenandoahVerifier::verify_after_fullgc() {
 878   verify_at_safepoint(
 879           "After Full GC",
 880           _verify_forwarded_none,      // all objects are non-forwarded
 881           _verify_marked_complete,     // all objects are marked in complete bitmap
 882           _verify_cset_none,           // no cset references
 883           _verify_liveness_disable,    // no reliable liveness data anymore
 884           _verify_regions_notrash_nocset, // no trash, no cset
 885           _verify_gcstate_stable       // degenerated refs had cleaned up forwarded objects
 886   );
 887 }
 888 void ShenandoahVerifier::verify_after_degenerated() {
 889   verify_at_safepoint(
 890           "After Degenerated GC",
 891           _verify_forwarded_none,      // all objects are non-forwarded
 892           _verify_marked_complete,     // all objects are marked in complete bitmap
 893           _verify_cset_none,           // no cset references
 894           _verify_liveness_disable,    // no reliable liveness data anymore
 895           _verify_regions_notrash_nocset, // no trash, no cset
 896           _verify_gcstate_stable       // full gc cleaned up everything
 897   );
 898 }