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