1 /*
   2  * Copyright (c) 2017, Red Hat, Inc. and/or its affiliates.
   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/shenandoah/brooksPointer.hpp"
  27 #include "gc/shenandoah/shenandoahAsserts.hpp"
  28 #include "gc/shenandoah/shenandoahConnectionMatrix.hpp"
  29 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  30 #include "gc/shenandoah/shenandoahHeap.hpp"
  31 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  32 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  33 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  34 #include "gc/shenandoah/shenandoahTaskqueue.hpp"
  35 #include "gc/shenandoah/shenandoahVerifier.hpp"
  36 #include "memory/allocation.hpp"
  37 #include "memory/iterator.inline.hpp"
  38 
  39 // Avoid name collision on verify_oop (defined in macroAssembler_arm.hpp)
  40 #ifdef verify_oop
  41 #undef verify_oop
  42 #endif
  43 
  44 class ShenandoahVerifyOopClosure : public BasicOopIterateClosure {
  45 private:
  46   const char* _phase;
  47   ShenandoahVerifier::VerifyOptions _options;
  48   ShenandoahVerifierStack* _stack;
  49   ShenandoahHeap* _heap;
  50   MarkBitMap* _map;
  51   ShenandoahLivenessData* _ld;
  52   void* _interior_loc;
  53   oop _loc;
  54 
  55 public:
  56   ShenandoahVerifyOopClosure(ShenandoahVerifierStack* stack, MarkBitMap* map, ShenandoahLivenessData* ld,
  57                              const char* phase, ShenandoahVerifier::VerifyOptions options) :
  58           _stack(stack), _heap(ShenandoahHeap::heap()), _map(map), _ld(ld), _loc(NULL), _interior_loc(NULL),
  59           _phase(phase), _options(options) {};
  60 
  61 private:
  62   void check(ShenandoahAsserts::SafeLevel level, oop obj, bool test, const char* label) {
  63     if (!test) {
  64       ShenandoahAsserts::print_failure(level, obj, _interior_loc, _loc, _phase, label, __FILE__, __LINE__);
  65     }
  66   }
  67 
  68   template <class T>
  69   void do_oop_work(T* p) {
  70     T o = RawAccess<>::oop_load(p);
  71     if (!CompressedOops::is_null(o)) {
  72       oop obj = CompressedOops::decode_not_null(o);
  73 
  74       // Single threaded verification can use faster non-atomic stack and bitmap
  75       // methods.
  76       //
  77       // For performance reasons, only fully verify non-marked field values.
  78       // We are here when the host object for *p is already marked. If field value
  79       // is marked already, then we have to verify the matrix connection between
  80       // host object and field value, regardless.
  81 
  82       HeapWord* addr = (HeapWord*) obj;
  83       if (_map->parMark(addr)) {
  84         verify_oop_at(p, obj);
  85         _stack->push(ShenandoahVerifierTask(obj));
  86       } else {
  87         verify_matrix(p, 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     check(ShenandoahAsserts::_safe_unknown, obj, _heap->is_in(obj),
  98               "oop must be in heap");
  99     check(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       check(ShenandoahAsserts::_safe_unknown, obj, obj_klass != NULL,
 109              "Object klass pointer should not be NULL");
 110       check(ShenandoahAsserts::_safe_unknown, obj, Metaspace::contains(obj_klass),
 111              "Object klass pointer must go to metaspace");
 112 
 113       HeapWord *obj_addr = (HeapWord *) obj;
 114       check(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         check(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           check(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       check(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(obj->size() + BrooksPointer::word_size(), &_ld[obj_reg->region_number()]);
 140           // fallthrough for fast failure for un-live regions:
 141         case ShenandoahVerifier::_verify_liveness_conservative:
 142           check(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) BrooksPointer::get_raw_unchecked(obj);
 151 
 152     ShenandoahHeapRegion* fwd_reg = NULL;
 153 
 154     if (!oopDesc::unsafe_equals(obj, fwd)) {
 155       check(ShenandoahAsserts::_safe_oop, obj, _heap->is_in(fwd),
 156              "Forwardee must be in heap");
 157       check(ShenandoahAsserts::_safe_oop, obj, !CompressedOops::is_null(fwd),
 158              "Forwardee is set");
 159       check(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       check(ShenandoahAsserts::_safe_oop, obj, fwd_klass != NULL,
 165              "Forwardee klass pointer should not be NULL");
 166       check(ShenandoahAsserts::_safe_oop, obj, Metaspace::contains(fwd_klass),
 167              "Forwardee klass pointer must go to metaspace");
 168       check(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       check(ShenandoahAsserts::_safe_oop, obj, !fwd_reg->is_humongous(),
 175              "Should have no humongous forwardees");
 176 
 177       HeapWord *fwd_addr = (HeapWord *) fwd;
 178       check(ShenandoahAsserts::_safe_oop, obj, fwd_addr < fwd_reg->top(),
 179              "Forwardee start should be within the region");
 180       check(ShenandoahAsserts::_safe_oop, obj, (fwd_addr + fwd->size()) <= fwd_reg->top(),
 181              "Forwardee end should be within the region");
 182 
 183       oop fwd2 = (oop) BrooksPointer::get_raw_unchecked(fwd);
 184       check(ShenandoahAsserts::_safe_oop, obj, oopDesc::unsafe_equals(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_next:
 197         check(ShenandoahAsserts::_safe_all, obj, _heap->next_marking_context()->is_marked(obj),
 198                "Must be marked in next bitmap");
 199         break;
 200       case ShenandoahVerifier::_verify_marked_complete:
 201         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
 202                "Must be marked in complete bitmap");
 203         break;
 204       default:
 205         assert(false, "Unhandled mark verification");
 206     }
 207 
 208     switch (_options._verify_forwarded) {
 209       case ShenandoahVerifier::_verify_forwarded_disable:
 210         // skip
 211         break;
 212       case ShenandoahVerifier::_verify_forwarded_none: {
 213         check(ShenandoahAsserts::_safe_all, obj, oopDesc::unsafe_equals(obj, fwd),
 214                "Should not be forwarded");
 215         break;
 216       }
 217       case ShenandoahVerifier::_verify_forwarded_allow: {
 218         if (!oopDesc::unsafe_equals(obj, fwd)) {
 219           check(ShenandoahAsserts::_safe_all, obj, obj_reg != fwd_reg,
 220                  "Forwardee should be in another region");
 221         }
 222         break;
 223       }
 224       default:
 225         assert(false, "Unhandled forwarding verification");
 226     }
 227 
 228     switch (_options._verify_cset) {
 229       case ShenandoahVerifier::_verify_cset_disable:
 230         // skip
 231         break;
 232       case ShenandoahVerifier::_verify_cset_none:
 233         check(ShenandoahAsserts::_safe_all, obj, !_heap->in_collection_set(obj),
 234                "Should not have references to collection set");
 235         break;
 236       case ShenandoahVerifier::_verify_cset_forwarded:
 237         if (_heap->in_collection_set(obj)) {
 238           check(ShenandoahAsserts::_safe_all, obj, !oopDesc::unsafe_equals(obj, fwd),
 239                  "Object in collection set, should have forwardee");
 240         }
 241         break;
 242       default:
 243         assert(false, "Unhandled cset verification");
 244     }
 245 
 246     verify_matrix(_interior_loc, obj);
 247   }
 248 
 249   void verify_matrix(void* interior, oop obj) {
 250     if (!UseShenandoahMatrix || !_heap->is_in(interior)) return;
 251     switch (_options._verify_matrix) {
 252       case ShenandoahVerifier::_verify_matrix_conservative: {
 253         size_t from_idx = _heap->heap_region_index_containing(interior);
 254         size_t to_idx   = _heap->heap_region_index_containing(obj);
 255         _interior_loc = interior;
 256         check(ShenandoahAsserts::_safe_all, obj, _heap->connection_matrix()->is_connected(from_idx, to_idx),
 257                "Must be connected");
 258         _interior_loc = NULL;
 259         break;
 260       }
 261       case ShenandoahVerifier::_verify_matrix_disable:
 262         break;
 263       default:
 264         assert(false, "Unhandled matrix verification");
 265     }
 266   }
 267 
 268 public:
 269 
 270   /**
 271    * Verify object with known interior reference.
 272    * @param p interior reference where the object is referenced from; can be off-heap
 273    * @param obj verified object
 274    */
 275   template <class T>
 276   void verify_oop_at(T* p, oop obj) {
 277     _interior_loc = p;
 278     verify_oop(obj);
 279     _interior_loc = NULL;
 280   }
 281 
 282   /**
 283    * Verify object without known interior reference.
 284    * Useful when picking up the object at known offset in heap,
 285    * but without knowing what objects reference it.
 286    * @param obj verified object
 287    */
 288   void verify_oop_standalone(oop obj) {
 289     _interior_loc = NULL;
 290     verify_oop(obj);
 291     _interior_loc = NULL;
 292   }
 293 
 294   /**
 295    * Verify oop fields from this object.
 296    * @param obj host object for verified fields
 297    */
 298   void verify_oops_from(oop obj) {
 299     _loc = obj;
 300     obj->oop_iterate(this);
 301     _loc = NULL;
 302   }
 303 
 304   virtual void do_oop(oop* p) { do_oop_work(p); }
 305   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 306 };
 307 
 308 class ShenandoahCalculateRegionStatsClosure : public ShenandoahHeapRegionClosure {
 309 private:
 310   size_t _used, _committed, _garbage;
 311 public:
 312   ShenandoahCalculateRegionStatsClosure() : _used(0), _committed(0), _garbage(0) {};
 313 
 314   bool heap_region_do(ShenandoahHeapRegion* r) {
 315     _used += r->used();
 316     _garbage += r->garbage();
 317     _committed += r->is_committed() ? ShenandoahHeapRegion::region_size_bytes() : 0;
 318     return false;
 319   }
 320 
 321   size_t used() { return _used; }
 322   size_t committed() { return _committed; }
 323   size_t garbage() { return _garbage; }
 324 };
 325 
 326 class ShenandoahVerifyHeapRegionClosure : public ShenandoahHeapRegionClosure {
 327 private:
 328   ShenandoahHeap* _heap;
 329   const char* _phase;
 330   ShenandoahVerifier::VerifyRegions _regions;
 331 public:
 332   ShenandoahVerifyHeapRegionClosure(const char* phase, ShenandoahVerifier::VerifyRegions regions) :
 333           _heap(ShenandoahHeap::heap()), _regions(regions), _phase(phase) {};
 334 
 335   void print_failure(ShenandoahHeapRegion* r, const char* label) {
 336     ResourceMark rm;
 337 
 338     ShenandoahMessageBuffer msg("Shenandoah verification failed; %s: %s\n\n", _phase, label);
 339 
 340     stringStream ss;
 341     r->print_on(&ss);
 342     msg.append("%s", ss.as_string());
 343 
 344     report_vm_error(__FILE__, __LINE__, msg.buffer());
 345   }
 346 
 347   void verify(ShenandoahHeapRegion* r, bool test, const char* msg) {
 348     if (!test) {
 349       print_failure(r, msg);
 350     }
 351   }
 352 
 353   bool heap_region_do(ShenandoahHeapRegion* r) {
 354     switch (_regions) {
 355       case ShenandoahVerifier::_verify_regions_disable:
 356         break;
 357       case ShenandoahVerifier::_verify_regions_notrash:
 358         verify(r, !r->is_trash(),
 359                "Should not have trash regions");
 360         break;
 361       case ShenandoahVerifier::_verify_regions_nocset:
 362         verify(r, !r->is_cset(),
 363                "Should not have cset regions");
 364         break;
 365       case ShenandoahVerifier::_verify_regions_notrash_nocset:
 366         verify(r, !r->is_trash(),
 367                "Should not have trash regions");
 368         verify(r, !r->is_cset(),
 369                "Should not have cset regions");
 370         break;
 371       default:
 372         ShouldNotReachHere();
 373     }
 374 
 375     verify(r, r->capacity() == ShenandoahHeapRegion::region_size_bytes(),
 376            "Capacity should match region size");
 377 
 378     verify(r, r->bottom() <= _heap->complete_marking_context()->top_at_mark_start(r->region_number()),
 379            "Region top should not be less than bottom");
 380 
 381     verify(r, _heap->complete_marking_context()->top_at_mark_start(r->region_number()) <= r->top(),
 382            "Complete TAMS should not be larger than top");
 383 
 384     verify(r, r->get_live_data_bytes() <= r->capacity(),
 385            "Live data cannot be larger than capacity");
 386 
 387     verify(r, r->garbage() <= r->capacity(),
 388            "Garbage cannot be larger than capacity");
 389 
 390     verify(r, r->used() <= r->capacity(),
 391            "Used cannot be larger than capacity");
 392 
 393     verify(r, r->get_shared_allocs() <= r->capacity(),
 394            "Shared alloc count should not be larger than capacity");
 395 
 396     verify(r, r->get_tlab_allocs() <= r->capacity(),
 397            "TLAB alloc count should not be larger than capacity");
 398 
 399     verify(r, r->get_gclab_allocs() <= r->capacity(),
 400            "GCLAB alloc count should not be larger than capacity");
 401 
 402     verify(r, r->get_shared_allocs() + r->get_tlab_allocs() + r->get_gclab_allocs() == r->used(),
 403            "Accurate accounting: shared + TLAB + GCLAB = used");
 404 
 405     verify(r, !r->is_empty() || !r->has_live(),
 406            "Empty regions should not have live data");
 407 
 408     verify(r, r->is_cset() == r->in_collection_set(),
 409            "Transitional: region flags and collection set agree");
 410 
 411     verify(r, r->is_empty() || r->seqnum_first_alloc() != 0,
 412            "Non-empty regions should have first seqnum set");
 413 
 414     verify(r, r->is_empty() || (r->seqnum_first_alloc_mutator() != 0 || r->seqnum_first_alloc_gc() != 0),
 415            "Non-empty regions should have first seqnum set to either GC or mutator");
 416 
 417     verify(r, r->is_empty() || r->seqnum_last_alloc() != 0,
 418            "Non-empty regions should have last seqnum set");
 419 
 420     verify(r, r->is_empty() || (r->seqnum_last_alloc_mutator() != 0 || r->seqnum_last_alloc_gc() != 0),
 421            "Non-empty regions should have last seqnum set to either GC or mutator");
 422 
 423     verify(r, r->seqnum_first_alloc() <= r->seqnum_last_alloc(),
 424            "First seqnum should not be greater than last timestamp");
 425 
 426     verify(r, r->seqnum_first_alloc_mutator() <= r->seqnum_last_alloc_mutator(),
 427            "First mutator seqnum should not be greater than last seqnum");
 428 
 429     verify(r, r->seqnum_first_alloc_gc() <= r->seqnum_last_alloc_gc(),
 430            "First GC seqnum should not be greater than last seqnum");
 431 
 432     return false;
 433   }
 434 };
 435 
 436 class ShenandoahVerifierReachableTask : public AbstractGangTask {
 437 private:
 438   const char* _label;
 439   ShenandoahRootProcessor* _rp;
 440   ShenandoahVerifier::VerifyOptions _options;
 441   ShenandoahHeap* _heap;
 442   ShenandoahLivenessData* _ld;
 443   MarkBitMap* _bitmap;
 444   volatile size_t _processed;
 445 
 446 public:
 447   ShenandoahVerifierReachableTask(MarkBitMap* bitmap,
 448                                   ShenandoahLivenessData* ld,
 449                                   ShenandoahRootProcessor* rp,
 450                                   const char* label,
 451                                   ShenandoahVerifier::VerifyOptions options) :
 452           AbstractGangTask("Shenandoah Parallel Verifier Reachable Task"),
 453           _heap(ShenandoahHeap::heap()), _rp(rp), _ld(ld), _bitmap(bitmap), _processed(0),
 454           _label(label), _options(options) {};
 455 
 456   size_t processed() {
 457     return _processed;
 458   }
 459 
 460   virtual void work(uint worker_id) {
 461     ResourceMark rm;
 462     ShenandoahVerifierStack stack;
 463 
 464     // On level 2, we need to only check the roots once.
 465     // On level 3, we want to check the roots, and seed the local stack.
 466     // It is a lesser evil to accept multiple root scans at level 3, because
 467     // extended parallelism would buy us out.
 468     if (((ShenandoahVerifyLevel == 2) && (worker_id == 0))
 469         || (ShenandoahVerifyLevel >= 3)) {
 470         ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 471                                       ShenandoahMessageBuffer("%s, Roots", _label),
 472                                       _options);
 473         _rp->process_all_roots_slow(&cl);
 474     }
 475 
 476     size_t processed = 0;
 477 
 478     if (ShenandoahVerifyLevel >= 3) {
 479       ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
 480                                     ShenandoahMessageBuffer("%s, Reachable", _label),
 481                                     _options);
 482       while (!stack.is_empty()) {
 483         processed++;
 484         ShenandoahVerifierTask task = stack.pop();
 485         cl.verify_oops_from(task.obj());
 486       }
 487     }
 488 
 489     Atomic::add(processed, &_processed);
 490   }
 491 };
 492 
 493 class ShenandoahVerifierMarkedRegionTask : public AbstractGangTask {
 494 private:
 495   const char* _label;
 496   ShenandoahVerifier::VerifyOptions _options;
 497   ShenandoahHeap *_heap;
 498   MarkBitMap* _bitmap;
 499   ShenandoahLivenessData* _ld;
 500   volatile size_t _claimed;
 501   volatile size_t _processed;
 502 
 503 public:
 504   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
 505                                      ShenandoahLivenessData* ld,
 506                                      const char* label,
 507                                      ShenandoahVerifier::VerifyOptions options) :
 508           AbstractGangTask("Shenandoah Parallel Verifier Marked Region"),
 509           _heap(ShenandoahHeap::heap()), _ld(ld), _bitmap(bitmap), _claimed(0), _processed(0),
 510           _label(label), _options(options) {};
 511 
 512   size_t processed() {
 513     return _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::add(1u, &_claimed) - 1;
 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() + BrooksPointer::word_size();
 540     if (_heap->complete_marking_context()->is_marked((oop)obj)) {
 541       verify_and_follow(obj, stack, cl, &processed);
 542     }
 543     Atomic::add(processed, &_processed);
 544   }
 545 
 546   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
 547     size_t processed = 0;
 548     MarkBitMap* mark_bit_map = _heap->complete_marking_context()->mark_bit_map();
 549     HeapWord* tams = _heap->complete_marking_context()->top_at_mark_start(r->region_number());
 550 
 551     // Bitmaps, before TAMS
 552     if (tams > r->bottom()) {
 553       HeapWord* start = r->bottom() + BrooksPointer::word_size();
 554       HeapWord* addr = mark_bit_map->getNextMarkedWordAddress(start, tams);
 555 
 556       while (addr < tams) {
 557         verify_and_follow(addr, stack, cl, &processed);
 558         addr += BrooksPointer::word_size();
 559         if (addr < tams) {
 560           addr = mark_bit_map->getNextMarkedWordAddress(addr, tams);
 561         }
 562       }
 563     }
 564 
 565     // Size-based, after TAMS
 566     {
 567       HeapWord* limit = r->top();
 568       HeapWord* addr = tams + BrooksPointer::word_size();
 569 
 570       while (addr < limit) {
 571         verify_and_follow(addr, stack, cl, &processed);
 572         addr += oop(addr)->size() + BrooksPointer::word_size();
 573       }
 574     }
 575 
 576     Atomic::add(processed, &_processed);
 577   }
 578 
 579   void verify_and_follow(HeapWord *addr, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl, size_t *processed) {
 580     if (!_bitmap->parMark(addr)) return;
 581 
 582     // Verify the object itself:
 583     oop obj = oop(addr);
 584     cl.verify_oop_standalone(obj);
 585 
 586     // Verify everything reachable from that object too, hopefully realizing
 587     // everything was already marked, and never touching further:
 588     cl.verify_oops_from(obj);
 589     (*processed)++;
 590 
 591     while (!stack.is_empty()) {
 592       ShenandoahVerifierTask task = stack.pop();
 593       cl.verify_oops_from(task.obj());
 594       (*processed)++;
 595     }
 596   }
 597 };
 598 
 599 class VerifyThreadGCState : public ThreadClosure {
 600 private:
 601   const char* _label;
 602   char _expected;
 603 
 604 public:
 605   VerifyThreadGCState(const char* label, char expected) : _expected(expected) {}
 606   void do_thread(Thread* t) {
 607     char actual = ShenandoahThreadLocalData::gc_state(t);
 608     if (actual != _expected) {
 609       fatal("%s: Thread %s: expected gc-state %d, actual %d", _label, t->name(), _expected, actual);
 610     }
 611   }
 612 };
 613 
 614 
 615 void ShenandoahVerifier::verify_at_safepoint(const char *label,
 616                                              VerifyForwarded forwarded, VerifyMarked marked,
 617                                              VerifyMatrix matrix, 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_stable:
 641         enabled = true;
 642         expected = ShenandoahHeap::STABLE;
 643         break;
 644       default:
 645         enabled = false;
 646         assert(false, "Unhandled gc-state verification");
 647     }
 648 
 649     if (enabled) {
 650       char actual = _heap->gc_state();
 651       if (actual != expected) {
 652         fatal("%s: Global gc-state: expected %d, actual %d", label, expected, actual);
 653       }
 654 
 655       VerifyThreadGCState vtgcs(label, expected);
 656       Threads::java_threads_do(&vtgcs);
 657     }
 658   }
 659 
 660   // Heap size checks
 661   {
 662     ShenandoahHeapLocker lock(_heap->lock());
 663 
 664     ShenandoahCalculateRegionStatsClosure cl;
 665     _heap->heap_region_iterate(&cl);
 666     size_t heap_used = _heap->used();
 667     guarantee(cl.used() == heap_used,
 668               "%s: heap used size must be consistent: heap-used = " SIZE_FORMAT "K, regions-used = " SIZE_FORMAT "K",
 669               label, heap_used/K, cl.used()/K);
 670 
 671     size_t heap_committed = _heap->committed();
 672     guarantee(cl.committed() == heap_committed,
 673               "%s: heap committed size must be consistent: heap-committed = " SIZE_FORMAT "K, regions-committed = " SIZE_FORMAT "K",
 674               label, heap_committed/K, cl.committed()/K);
 675   }
 676 
 677   // Internal heap region checks
 678   if (ShenandoahVerifyLevel >= 1) {
 679     ShenandoahVerifyHeapRegionClosure cl(label, regions);
 680     _heap->heap_region_iterate(&cl,
 681             /* skip_cset = */ false,
 682             /* skip_humongous_cont = */ false);
 683   }
 684 
 685   OrderAccess::fence();
 686   _heap->make_parsable(false);
 687 
 688   // Allocate temporary bitmap for storing marking wavefront:
 689   MemRegion mr = MemRegion(_verification_bit_map->startWord(), _verification_bit_map->endWord());
 690   _verification_bit_map->clear_range_large(mr);
 691 
 692   // Allocate temporary array for storing liveness data
 693   ShenandoahLivenessData* ld = NEW_C_HEAP_ARRAY(ShenandoahLivenessData, _heap->num_regions(), mtGC);
 694   Copy::fill_to_bytes((void*)ld, _heap->num_regions()*sizeof(ShenandoahLivenessData), 0);
 695 
 696   const VerifyOptions& options = ShenandoahVerifier::VerifyOptions(forwarded, marked, matrix, cset, liveness, regions, gcstate);
 697 
 698   // Steps 1-2. Scan root set to get initial reachable set. Finish walking the reachable heap.
 699   // This verifies what application can see, since it only cares about reachable objects.
 700   size_t count_reachable = 0;
 701   if (ShenandoahVerifyLevel >= 2) {
 702     ShenandoahRootProcessor rp(_heap, _heap->workers()->active_workers(),
 703                                ShenandoahPhaseTimings::_num_phases); // no need for stats
 704 
 705     ShenandoahVerifierReachableTask task(_verification_bit_map, ld, &rp, label, options);
 706     _heap->workers()->run_task(&task);
 707     count_reachable = task.processed();
 708   }
 709 
 710   // Step 3. Walk marked objects. Marked objects might be unreachable. This verifies what collector,
 711   // not the application, can see during the region scans. There is no reason to process the objects
 712   // that were already verified, e.g. those marked in verification bitmap. There is interaction with TAMS:
 713   // before TAMS, we verify the bitmaps, if available; after TAMS, we walk until the top(). It mimics
 714   // what marked_object_iterate is doing, without calling into that optimized (and possibly incorrect)
 715   // version
 716 
 717   size_t count_marked = 0;
 718   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete) {
 719     ShenandoahVerifierMarkedRegionTask task(_verification_bit_map, ld, label, options);
 720     _heap->workers()->run_task(&task);
 721     count_marked = task.processed();
 722   } else {
 723     guarantee(ShenandoahVerifyLevel < 4 || marked == _verify_marked_next || marked == _verify_marked_disable, "Should be");
 724   }
 725 
 726   // Step 4. Verify accumulated liveness data, if needed. Only reliable if verification level includes
 727   // marked objects.
 728 
 729   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete && liveness == _verify_liveness_complete) {
 730     for (size_t i = 0; i < _heap->num_regions(); i++) {
 731       ShenandoahHeapRegion* r = _heap->get_region(i);
 732 
 733       juint verf_live = 0;
 734       if (r->is_humongous()) {
 735         // For humongous objects, test if start region is marked live, and if so,
 736         // all humongous regions in that chain have live data equal to their "used".
 737         juint start_live = OrderAccess::load_acquire(&ld[r->humongous_start_region()->region_number()]);
 738         if (start_live > 0) {
 739           verf_live = (juint)(r->used() / HeapWordSize);
 740         }
 741       } else {
 742         verf_live = OrderAccess::load_acquire(&ld[r->region_number()]);
 743       }
 744 
 745       size_t reg_live = r->get_live_data_words();
 746       if (reg_live != verf_live) {
 747         ResourceMark rm;
 748         stringStream ss;
 749         r->print_on(&ss);
 750         fatal("%s: Live data should match: region-live = " SIZE_FORMAT ", verifier-live = " UINT32_FORMAT "\n%s",
 751               label, reg_live, verf_live, ss.as_string());
 752       }
 753     }
 754   }
 755 
 756   log_info(gc)("Verify %s, Level " INTX_FORMAT " (" SIZE_FORMAT " reachable, " SIZE_FORMAT " marked)",
 757                label, ShenandoahVerifyLevel, count_reachable, count_marked);
 758 
 759   FREE_C_HEAP_ARRAY(ShenandoahLivenessData, ld);
 760 }
 761 
 762 void ShenandoahVerifier::verify_generic(VerifyOption vo) {
 763   verify_at_safepoint(
 764           "Generic Verification",
 765           _verify_forwarded_allow,     // conservatively allow forwarded
 766           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 767           _verify_matrix_disable,      // matrix can be inconsistent here
 768           _verify_cset_disable,        // cset may be inconsistent
 769           _verify_liveness_disable,    // no reliable liveness data
 770           _verify_regions_disable,     // no reliable region data
 771           _verify_gcstate_disable      // no data about gcstate
 772   );
 773 }
 774 
 775 void ShenandoahVerifier::verify_before_concmark() {
 776   if (_heap->has_forwarded_objects()) {
 777     verify_at_safepoint(
 778             "Before Mark",
 779             _verify_forwarded_allow,     // may have forwarded references
 780             _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 781             _verify_matrix_disable,      // matrix is foobared
 782             _verify_cset_forwarded,      // allow forwarded references to cset
 783             _verify_liveness_disable,    // no reliable liveness data
 784             _verify_regions_notrash,     // no trash regions
 785             _verify_gcstate_forwarded    // there are forwarded objects
 786     );
 787   } else {
 788     verify_at_safepoint(
 789             "Before Mark",
 790             _verify_forwarded_none,      // UR should have fixed up
 791             _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 792             _verify_matrix_conservative, // UR should have fixed matrix
 793             _verify_cset_none,           // UR should have fixed this
 794             _verify_liveness_disable,    // no reliable liveness data
 795             _verify_regions_notrash,     // no trash regions
 796             _verify_gcstate_stable       // there are no forwarded objects
 797     );
 798   }
 799 }
 800 
 801 void ShenandoahVerifier::verify_after_concmark() {
 802   verify_at_safepoint(
 803           "After Mark",
 804           _verify_forwarded_none,      // no forwarded references
 805           _verify_marked_complete,     // bitmaps as precise as we can get
 806           _verify_matrix_disable,      // matrix might be foobared
 807           _verify_cset_none,           // no references to cset anymore
 808           _verify_liveness_complete,   // liveness data must be complete here
 809           _verify_regions_disable,     // trash regions not yet recycled
 810           _verify_gcstate_stable       // mark should have stabilized the heap
 811   );
 812 }
 813 
 814 void ShenandoahVerifier::verify_before_evacuation() {
 815   // Evacuation is always preceded by mark, but we want to have a sanity check after
 816   // selecting the collection set, and (immediate) regions recycling
 817   verify_at_safepoint(
 818           "Before Evacuation",
 819           _verify_forwarded_none,    // no forwarded references
 820           _verify_marked_complete,   // walk over marked objects too
 821           _verify_matrix_disable,    // skip, verified after mark
 822           _verify_cset_disable,      // skip, verified after mark
 823           _verify_liveness_disable,  // skip, verified after mark
 824           _verify_regions_disable,   // trash regions not yet recycled
 825           _verify_gcstate_stable     // mark should have stabilized the heap
 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_matrix_disable,      // matrix is inconsistent here
 835           _verify_cset_forwarded,      // all cset refs are fully forwarded
 836           _verify_liveness_disable,    // no reliable liveness data anymore
 837           _verify_regions_notrash,     // trash regions have been recycled already
 838           _verify_gcstate_forwarded    // evacuation produced some forwarded objects
 839   );
 840 }
 841 
 842 void ShenandoahVerifier::verify_before_updaterefs() {
 843   verify_at_safepoint(
 844           "Before Updating References",
 845           _verify_forwarded_allow,     // forwarded references allowed
 846           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 847           _verify_matrix_disable,      // matrix is inconsistent here
 848           _verify_cset_forwarded,      // all cset refs are fully forwarded
 849           _verify_liveness_disable,    // no reliable liveness data anymore
 850           _verify_regions_notrash,     // trash regions have been recycled already
 851           _verify_gcstate_forwarded    // evacuation should have produced some forwarded objects
 852   );
 853 }
 854 
 855 void ShenandoahVerifier::verify_after_updaterefs() {
 856   verify_at_safepoint(
 857           "After Updating References",
 858           _verify_forwarded_none,      // no forwarded references
 859           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
 860           _verify_matrix_conservative, // matrix is conservatively consistent
 861           _verify_cset_none,           // no cset references, all updated
 862           _verify_liveness_disable,    // no reliable liveness data anymore
 863           _verify_regions_nocset,      // no cset regions, trash regions have appeared
 864           _verify_gcstate_stable       // update refs had cleaned up forwarded objects
 865   );
 866 }
 867 
 868 void ShenandoahVerifier::verify_after_degenerated() {
 869   verify_at_safepoint(
 870           "After Degenerated GC",
 871           _verify_forwarded_none,      // all objects are non-forwarded
 872           _verify_marked_complete,     // all objects are marked in complete bitmap
 873           _verify_matrix_conservative, // matrix is conservatively consistent
 874           _verify_cset_none,           // no cset references
 875           _verify_liveness_disable,    // no reliable liveness data anymore
 876           _verify_regions_notrash_nocset, // no trash, no cset
 877           _verify_gcstate_stable       // degenerated refs had cleaned up forwarded objects
 878   );
 879 }
 880 
 881 void ShenandoahVerifier::verify_before_traversal() {
 882   verify_at_safepoint(
 883           "Before Traversal",
 884           _verify_forwarded_none,      // cannot have forwarded objects
 885           _verify_marked_disable,      // bitmaps are not relevant before traversal
 886           _verify_matrix_disable,      // matrix is not used in traversal
 887           _verify_cset_none,           // no cset references before traversal
 888           _verify_liveness_disable,    // no reliable liveness data anymore
 889           _verify_regions_notrash_nocset, // no trash and no cset regions
 890           _verify_gcstate_stable       // nothing forwarded before traversal
 891   );
 892 }
 893 
 894 void ShenandoahVerifier::verify_after_traversal() {
 895   verify_at_safepoint(
 896           "After Traversal",
 897           _verify_forwarded_none,      // cannot have forwarded objects
 898           _verify_marked_disable,      // We only have partial marking info after traversal
 899           _verify_matrix_disable,      // matrix is conservatively consistent
 900           _verify_cset_none,           // no cset references left after traversal
 901           _verify_liveness_disable,    // liveness data is not collected for new allocations
 902           _verify_regions_nocset,      // no cset regions, trash regions allowed
 903           _verify_gcstate_stable       // nothing forwarded after traversal
 904   );
 905 }
 906 
 907 void ShenandoahVerifier::verify_before_fullgc() {
 908   verify_at_safepoint(
 909           "Before Full GC",
 910           _verify_forwarded_allow,     // can have forwarded objects
 911           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
 912           _verify_matrix_disable,      // matrix might be foobared
 913           _verify_cset_disable,        // cset might be foobared
 914           _verify_liveness_disable,    // no reliable liveness data anymore
 915           _verify_regions_disable,     // no reliable region data here
 916           _verify_gcstate_disable      // no reliable gcstate data
 917   );
 918 }
 919 
 920 void ShenandoahVerifier::verify_after_fullgc() {
 921   verify_at_safepoint(
 922           "After Full GC",
 923           _verify_forwarded_none,      // all objects are non-forwarded
 924           _verify_marked_complete,     // all objects are marked in complete bitmap
 925           _verify_matrix_conservative, // matrix is conservatively consistent
 926           _verify_cset_none,           // no cset references
 927           _verify_liveness_disable,    // no reliable liveness data anymore
 928           _verify_regions_notrash_nocset, // no trash, no cset
 929           _verify_gcstate_stable       // full gc cleaned up everything
 930   );
 931 }
 932