1 /*
   2  * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "logging/log.hpp"
  27 #include "gc/g1/concurrentMarkThread.hpp"
  28 #include "gc/g1/g1Allocator.inline.hpp"
  29 #include "gc/g1/g1CollectedHeap.hpp"
  30 #include "gc/g1/g1CollectedHeap.inline.hpp"
  31 #include "gc/g1/g1HeapVerifier.hpp"
  32 #include "gc/g1/g1Policy.hpp"
  33 #include "gc/g1/g1RemSet.hpp"
  34 #include "gc/g1/g1RootProcessor.hpp"
  35 #include "gc/g1/heapRegion.hpp"
  36 #include "gc/g1/heapRegion.inline.hpp"
  37 #include "gc/g1/heapRegionRemSet.hpp"
  38 #include "gc/g1/g1StringDedup.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "oops/oop.inline.hpp"
  41 
  42 class VerifyRootsClosure: public OopClosure {
  43 private:
  44   G1CollectedHeap* _g1h;
  45   VerifyOption     _vo;
  46   bool             _failures;
  47 public:
  48   // _vo == UsePrevMarking -> use "prev" marking information,
  49   // _vo == UseNextMarking -> use "next" marking information,
  50   // _vo == UseMarkWord    -> use mark word from object header.
  51   VerifyRootsClosure(VerifyOption vo) :
  52     _g1h(G1CollectedHeap::heap()),
  53     _vo(vo),
  54     _failures(false) { }
  55 
  56   bool failures() { return _failures; }
  57 
  58   template <class T> void do_oop_nv(T* p) {
  59     T heap_oop = oopDesc::load_heap_oop(p);
  60     if (!oopDesc::is_null(heap_oop)) {
  61       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  62       if (_g1h->is_obj_dead_cond(obj, _vo)) {
  63         Log(gc, verify) log;
  64         log.info("Root location " PTR_FORMAT " points to dead obj " PTR_FORMAT, p2i(p), p2i(obj));
  65         if (_vo == VerifyOption_G1UseMarkWord) {
  66           log.error("  Mark word: " PTR_FORMAT, p2i(obj->mark()));
  67         }
  68         ResourceMark rm;
  69         obj->print_on(log.error_stream());
  70         _failures = true;
  71       }
  72     }
  73   }
  74 
  75   void do_oop(oop* p)       { do_oop_nv(p); }
  76   void do_oop(narrowOop* p) { do_oop_nv(p); }
  77 };
  78 
  79 class G1VerifyCodeRootOopClosure: public OopClosure {
  80   G1CollectedHeap* _g1h;
  81   OopClosure* _root_cl;
  82   nmethod* _nm;
  83   VerifyOption _vo;
  84   bool _failures;
  85 
  86   template <class T> void do_oop_work(T* p) {
  87     // First verify that this root is live
  88     _root_cl->do_oop(p);
  89 
  90     if (!G1VerifyHeapRegionCodeRoots) {
  91       // We're not verifying the code roots attached to heap region.
  92       return;
  93     }
  94 
  95     // Don't check the code roots during marking verification in a full GC
  96     if (_vo == VerifyOption_G1UseMarkWord) {
  97       return;
  98     }
  99 
 100     // Now verify that the current nmethod (which contains p) is
 101     // in the code root list of the heap region containing the
 102     // object referenced by p.
 103 
 104     T heap_oop = oopDesc::load_heap_oop(p);
 105     if (!oopDesc::is_null(heap_oop)) {
 106       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 107 
 108       // Now fetch the region containing the object
 109       HeapRegion* hr = _g1h->heap_region_containing(obj);
 110       HeapRegionRemSet* hrrs = hr->rem_set();
 111       // Verify that the strong code root list for this region
 112       // contains the nmethod
 113       if (!hrrs->strong_code_roots_list_contains(_nm)) {
 114         log_error(gc, verify)("Code root location " PTR_FORMAT " "
 115                               "from nmethod " PTR_FORMAT " not in strong "
 116                               "code roots for region [" PTR_FORMAT "," PTR_FORMAT ")",
 117                               p2i(p), p2i(_nm), p2i(hr->bottom()), p2i(hr->end()));
 118         _failures = true;
 119       }
 120     }
 121   }
 122 
 123 public:
 124   G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
 125     _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}
 126 
 127   void do_oop(oop* p) { do_oop_work(p); }
 128   void do_oop(narrowOop* p) { do_oop_work(p); }
 129 
 130   void set_nmethod(nmethod* nm) { _nm = nm; }
 131   bool failures() { return _failures; }
 132 };
 133 
 134 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
 135   G1VerifyCodeRootOopClosure* _oop_cl;
 136 
 137 public:
 138   G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
 139     _oop_cl(oop_cl) {}
 140 
 141   void do_code_blob(CodeBlob* cb) {
 142     nmethod* nm = cb->as_nmethod_or_null();
 143     if (nm != NULL) {
 144       _oop_cl->set_nmethod(nm);
 145       nm->oops_do(_oop_cl);
 146     }
 147   }
 148 };
 149 
 150 class YoungRefCounterClosure : public OopClosure {
 151   G1CollectedHeap* _g1h;
 152   int              _count;
 153  public:
 154   YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
 155   void do_oop(oop* p)       { if (_g1h->is_in_young(*p)) { _count++; } }
 156   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
 157 
 158   int count() { return _count; }
 159   void reset_count() { _count = 0; };
 160 };
 161 
 162 class VerifyKlassClosure: public KlassClosure {
 163   YoungRefCounterClosure _young_ref_counter_closure;
 164   OopClosure *_oop_closure;
 165  public:
 166   VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
 167   void do_klass(Klass* k) {
 168     k->oops_do(_oop_closure);
 169 
 170     _young_ref_counter_closure.reset_count();
 171     k->oops_do(&_young_ref_counter_closure);
 172     if (_young_ref_counter_closure.count() > 0) {
 173       guarantee(k->has_modified_oops(), "Klass " PTR_FORMAT ", has young refs but is not dirty.", p2i(k));
 174     }
 175   }
 176 };
 177 
 178 class VerifyLivenessOopClosure: public OopClosure {
 179   G1CollectedHeap* _g1h;
 180   VerifyOption _vo;
 181 public:
 182   VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
 183     _g1h(g1h), _vo(vo)
 184   { }
 185   void do_oop(narrowOop *p) { do_oop_work(p); }
 186   void do_oop(      oop *p) { do_oop_work(p); }
 187 
 188   template <class T> void do_oop_work(T *p) {
 189     oop obj = oopDesc::load_decode_heap_oop(p);
 190     guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
 191               "Dead object referenced by a not dead object");
 192   }
 193 };
 194 
 195 class VerifyObjsInRegionClosure: public ObjectClosure {
 196 private:
 197   G1CollectedHeap* _g1h;
 198   size_t _live_bytes;
 199   HeapRegion *_hr;
 200   VerifyOption _vo;
 201 public:
 202   // _vo == UsePrevMarking -> use "prev" marking information,
 203   // _vo == UseNextMarking -> use "next" marking information,
 204   // _vo == UseMarkWord    -> use mark word from object header.
 205   VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
 206     : _live_bytes(0), _hr(hr), _vo(vo) {
 207     _g1h = G1CollectedHeap::heap();
 208   }
 209   void do_object(oop o) {
 210     VerifyLivenessOopClosure isLive(_g1h, _vo);
 211     assert(o != NULL, "Huh?");
 212     if (!_g1h->is_obj_dead_cond(o, _vo)) {
 213       // If the object is alive according to the mark word,
 214       // then verify that the marking information agrees.
 215       // Note we can't verify the contra-positive of the
 216       // above: if the object is dead (according to the mark
 217       // word), it may not be marked, or may have been marked
 218       // but has since became dead, or may have been allocated
 219       // since the last marking.
 220       if (_vo == VerifyOption_G1UseMarkWord) {
 221         guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
 222       }
 223 
 224       o->oop_iterate_no_header(&isLive);
 225       if (!_hr->obj_allocated_since_prev_marking(o)) {
 226         size_t obj_size = o->size();    // Make sure we don't overflow
 227         _live_bytes += (obj_size * HeapWordSize);
 228       }
 229     }
 230   }
 231   size_t live_bytes() { return _live_bytes; }
 232 };
 233 
 234 class VerifyArchiveOopClosure: public OopClosure {
 235 public:
 236   VerifyArchiveOopClosure(HeapRegion *hr) { }
 237   void do_oop(narrowOop *p) { do_oop_work(p); }
 238   void do_oop(      oop *p) { do_oop_work(p); }
 239 
 240   template <class T> void do_oop_work(T *p) {
 241     oop obj = oopDesc::load_decode_heap_oop(p);
 242     guarantee(obj == NULL || G1ArchiveAllocator::is_archive_object(obj),
 243               "Archive object at " PTR_FORMAT " references a non-archive object at " PTR_FORMAT,
 244               p2i(p), p2i(obj));
 245   }
 246 };
 247 
 248 class VerifyArchiveRegionClosure: public ObjectClosure {
 249 public:
 250   VerifyArchiveRegionClosure(HeapRegion *hr) { }
 251   // Verify that all object pointers are to archive regions.
 252   void do_object(oop o) {
 253     VerifyArchiveOopClosure checkOop(NULL);
 254     assert(o != NULL, "Should not be here for NULL oops");
 255     o->oop_iterate_no_header(&checkOop);
 256   }
 257 };
 258 
 259 class VerifyRegionClosure: public HeapRegionClosure {
 260 private:
 261   bool             _par;
 262   VerifyOption     _vo;
 263   bool             _failures;
 264 public:
 265   // _vo == UsePrevMarking -> use "prev" marking information,
 266   // _vo == UseNextMarking -> use "next" marking information,
 267   // _vo == UseMarkWord    -> use mark word from object header.
 268   VerifyRegionClosure(bool par, VerifyOption vo)
 269     : _par(par),
 270       _vo(vo),
 271       _failures(false) {}
 272 
 273   bool failures() {
 274     return _failures;
 275   }
 276 
 277   bool doHeapRegion(HeapRegion* r) {
 278     // For archive regions, verify there are no heap pointers to
 279     // non-pinned regions. For all others, verify liveness info.
 280     if (r->is_archive()) {
 281       VerifyArchiveRegionClosure verify_oop_pointers(r);
 282       r->object_iterate(&verify_oop_pointers);
 283       return true;
 284     }
 285     if (!r->is_continues_humongous()) {
 286       bool failures = false;
 287       r->verify(_vo, &failures);
 288       if (failures) {
 289         _failures = true;
 290       } else if (!r->is_starts_humongous()) {
 291         VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
 292         r->object_iterate(&not_dead_yet_cl);
 293         if (_vo != VerifyOption_G1UseNextMarking) {
 294           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
 295             log_error(gc, verify)("[" PTR_FORMAT "," PTR_FORMAT "] max_live_bytes " SIZE_FORMAT " < calculated " SIZE_FORMAT,
 296                                   p2i(r->bottom()), p2i(r->end()), r->max_live_bytes(), not_dead_yet_cl.live_bytes());
 297             _failures = true;
 298           }
 299         } else {
 300           // When vo == UseNextMarking we cannot currently do a sanity
 301           // check on the live bytes as the calculation has not been
 302           // finalized yet.
 303         }
 304       }
 305     }
 306     return false; // stop the region iteration if we hit a failure
 307   }
 308 };
 309 
 310 // This is the task used for parallel verification of the heap regions
 311 
 312 class G1ParVerifyTask: public AbstractGangTask {
 313 private:
 314   G1CollectedHeap*  _g1h;
 315   VerifyOption      _vo;
 316   bool              _failures;
 317   HeapRegionClaimer _hrclaimer;
 318 
 319 public:
 320   // _vo == UsePrevMarking -> use "prev" marking information,
 321   // _vo == UseNextMarking -> use "next" marking information,
 322   // _vo == UseMarkWord    -> use mark word from object header.
 323   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
 324       AbstractGangTask("Parallel verify task"),
 325       _g1h(g1h),
 326       _vo(vo),
 327       _failures(false),
 328       _hrclaimer(g1h->workers()->active_workers()) {}
 329 
 330   bool failures() {
 331     return _failures;
 332   }
 333 
 334   void work(uint worker_id) {
 335     HandleMark hm;
 336     VerifyRegionClosure blk(true, _vo);
 337     _g1h->heap_region_par_iterate(&blk, worker_id, &_hrclaimer);
 338     if (blk.failures()) {
 339       _failures = true;
 340     }
 341   }
 342 };
 343 
 344 
 345 void G1HeapVerifier::verify(VerifyOption vo) {
 346   if (!SafepointSynchronize::is_at_safepoint()) {
 347     log_info(gc, verify)("Skipping verification. Not at safepoint.");
 348   }
 349 
 350   assert(Thread::current()->is_VM_thread(),
 351          "Expected to be executed serially by the VM thread at this point");
 352 
 353   log_debug(gc, verify)("Roots");
 354   VerifyRootsClosure rootsCl(vo);
 355   VerifyKlassClosure klassCl(_g1h, &rootsCl);
 356   CLDToKlassAndOopClosure cldCl(&klassCl, &rootsCl, false);
 357 
 358   // We apply the relevant closures to all the oops in the
 359   // system dictionary, class loader data graph, the string table
 360   // and the nmethods in the code cache.
 361   G1VerifyCodeRootOopClosure codeRootsCl(_g1h, &rootsCl, vo);
 362   G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
 363 
 364   {
 365     G1RootProcessor root_processor(_g1h, 1);
 366     root_processor.process_all_roots(&rootsCl,
 367                                      &cldCl,
 368                                      &blobsCl);
 369   }
 370 
 371   bool failures = rootsCl.failures() || codeRootsCl.failures();
 372 
 373   if (vo != VerifyOption_G1UseMarkWord) {
 374     // If we're verifying during a full GC then the region sets
 375     // will have been torn down at the start of the GC. Therefore
 376     // verifying the region sets will fail. So we only verify
 377     // the region sets when not in a full GC.
 378     log_debug(gc, verify)("HeapRegionSets");
 379     verify_region_sets();
 380   }
 381 
 382   log_debug(gc, verify)("HeapRegions");
 383   if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
 384 
 385     G1ParVerifyTask task(_g1h, vo);
 386     _g1h->workers()->run_task(&task);
 387     if (task.failures()) {
 388       failures = true;
 389     }
 390 
 391   } else {
 392     VerifyRegionClosure blk(false, vo);
 393     _g1h->heap_region_iterate(&blk);
 394     if (blk.failures()) {
 395       failures = true;
 396     }
 397   }
 398 
 399   if (G1StringDedup::is_enabled()) {
 400     log_debug(gc, verify)("StrDedup");
 401     G1StringDedup::verify();
 402   }
 403 
 404   if (failures) {
 405     log_error(gc, verify)("Heap after failed verification:");
 406     // It helps to have the per-region information in the output to
 407     // help us track down what went wrong. This is why we call
 408     // print_extended_on() instead of print_on().
 409     Log(gc, verify) log;
 410     ResourceMark rm;
 411     _g1h->print_extended_on(log.error_stream());
 412   }
 413   guarantee(!failures, "there should not have been any failures");
 414 }
 415 
 416 // Heap region set verification
 417 
 418 class VerifyRegionListsClosure : public HeapRegionClosure {
 419 private:
 420   HeapRegionSet*   _old_set;
 421   HeapRegionSet*   _humongous_set;
 422   HeapRegionManager*   _hrm;
 423 
 424 public:
 425   uint _old_count;
 426   uint _humongous_count;
 427   uint _free_count;
 428 
 429   VerifyRegionListsClosure(HeapRegionSet* old_set,
 430                            HeapRegionSet* humongous_set,
 431                            HeapRegionManager* hrm) :
 432     _old_set(old_set), _humongous_set(humongous_set), _hrm(hrm),
 433     _old_count(), _humongous_count(), _free_count(){ }
 434 
 435   bool doHeapRegion(HeapRegion* hr) {
 436     if (hr->is_young()) {
 437       // TODO
 438     } else if (hr->is_humongous()) {
 439       assert(hr->containing_set() == _humongous_set, "Heap region %u is humongous but not in humongous set.", hr->hrm_index());
 440       _humongous_count++;
 441     } else if (hr->is_empty()) {
 442       assert(_hrm->is_free(hr), "Heap region %u is empty but not on the free list.", hr->hrm_index());
 443       _free_count++;
 444     } else if (hr->is_old()) {
 445       assert(hr->containing_set() == _old_set, "Heap region %u is old but not in the old set.", hr->hrm_index());
 446       _old_count++;
 447     } else {
 448       // There are no other valid region types. Check for one invalid
 449       // one we can identify: pinned without old or humongous set.
 450       assert(!hr->is_pinned(), "Heap region %u is pinned but not old (archive) or humongous.", hr->hrm_index());
 451       ShouldNotReachHere();
 452     }
 453     return false;
 454   }
 455 
 456   void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, HeapRegionManager* free_list) {
 457     guarantee(old_set->length() == _old_count, "Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count);
 458     guarantee(humongous_set->length() == _humongous_count, "Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count);
 459     guarantee(free_list->num_free_regions() == _free_count, "Free list count mismatch. Expected %u, actual %u.", free_list->num_free_regions(), _free_count);
 460   }
 461 };
 462 
 463 void G1HeapVerifier::verify_region_sets() {
 464   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
 465 
 466   // First, check the explicit lists.
 467   _g1h->_hrm.verify();
 468   {
 469     // Given that a concurrent operation might be adding regions to
 470     // the secondary free list we have to take the lock before
 471     // verifying it.
 472     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
 473     _g1h->_secondary_free_list.verify_list();
 474   }
 475 
 476   // If a concurrent region freeing operation is in progress it will
 477   // be difficult to correctly attributed any free regions we come
 478   // across to the correct free list given that they might belong to
 479   // one of several (free_list, secondary_free_list, any local lists,
 480   // etc.). So, if that's the case we will skip the rest of the
 481   // verification operation. Alternatively, waiting for the concurrent
 482   // operation to complete will have a non-trivial effect on the GC's
 483   // operation (no concurrent operation will last longer than the
 484   // interval between two calls to verification) and it might hide
 485   // any issues that we would like to catch during testing.
 486   if (_g1h->free_regions_coming()) {
 487     return;
 488   }
 489 
 490   // Make sure we append the secondary_free_list on the free_list so
 491   // that all free regions we will come across can be safely
 492   // attributed to the free_list.
 493   _g1h->append_secondary_free_list_if_not_empty_with_lock();
 494 
 495   // Finally, make sure that the region accounting in the lists is
 496   // consistent with what we see in the heap.
 497 
 498   VerifyRegionListsClosure cl(&_g1h->_old_set, &_g1h->_humongous_set, &_g1h->_hrm);
 499   _g1h->heap_region_iterate(&cl);
 500   cl.verify_counts(&_g1h->_old_set, &_g1h->_humongous_set, &_g1h->_hrm);
 501 }
 502 
 503 void G1HeapVerifier::prepare_for_verify() {
 504   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
 505     _g1h->ensure_parsability(false);
 506   }
 507 }
 508 
 509 double G1HeapVerifier::verify(bool guard, const char* msg) {
 510   double verify_time_ms = 0.0;
 511 
 512   if (guard && _g1h->total_collections() >= VerifyGCStartAt) {
 513     double verify_start = os::elapsedTime();
 514     HandleMark hm;  // Discard invalid handles created during verification
 515     prepare_for_verify();
 516     Universe::verify(VerifyOption_G1UsePrevMarking, msg);
 517     verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
 518   }
 519 
 520   return verify_time_ms;
 521 }
 522 
 523 void G1HeapVerifier::verify_before_gc() {
 524   double verify_time_ms = verify(VerifyBeforeGC, "Before GC");
 525   _g1h->g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);
 526 }
 527 
 528 void G1HeapVerifier::verify_after_gc() {
 529   double verify_time_ms = verify(VerifyAfterGC, "After GC");
 530   _g1h->g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);
 531 }
 532 
 533 
 534 #ifndef PRODUCT
 535 class G1VerifyCardTableCleanup: public HeapRegionClosure {
 536   G1HeapVerifier* _verifier;
 537   G1SATBCardTableModRefBS* _ct_bs;
 538 public:
 539   G1VerifyCardTableCleanup(G1HeapVerifier* verifier, G1SATBCardTableModRefBS* ct_bs)
 540     : _verifier(verifier), _ct_bs(ct_bs) { }
 541   virtual bool doHeapRegion(HeapRegion* r) {
 542     if (r->is_survivor()) {
 543       _verifier->verify_dirty_region(r);
 544     } else {
 545       _verifier->verify_not_dirty_region(r);
 546     }
 547     return false;
 548   }
 549 };
 550 
 551 void G1HeapVerifier::verify_card_table_cleanup() {
 552   if (G1VerifyCTCleanup || VerifyAfterGC) {
 553     G1VerifyCardTableCleanup cleanup_verifier(this, _g1h->g1_barrier_set());
 554     _g1h->heap_region_iterate(&cleanup_verifier);
 555   }
 556 }
 557 
 558 void G1HeapVerifier::verify_not_dirty_region(HeapRegion* hr) {
 559   // All of the region should be clean.
 560   G1SATBCardTableModRefBS* ct_bs = _g1h->g1_barrier_set();
 561   MemRegion mr(hr->bottom(), hr->end());
 562   ct_bs->verify_not_dirty_region(mr);
 563 }
 564 
 565 void G1HeapVerifier::verify_dirty_region(HeapRegion* hr) {
 566   // We cannot guarantee that [bottom(),end()] is dirty.  Threads
 567   // dirty allocated blocks as they allocate them. The thread that
 568   // retires each region and replaces it with a new one will do a
 569   // maximal allocation to fill in [pre_dummy_top(),end()] but will
 570   // not dirty that area (one less thing to have to do while holding
 571   // a lock). So we can only verify that [bottom(),pre_dummy_top()]
 572   // is dirty.
 573   G1SATBCardTableModRefBS* ct_bs = _g1h->g1_barrier_set();
 574   MemRegion mr(hr->bottom(), hr->pre_dummy_top());
 575   if (hr->is_young()) {
 576     ct_bs->verify_g1_young_region(mr);
 577   } else {
 578     ct_bs->verify_dirty_region(mr);
 579   }
 580 }
 581 
 582 class G1VerifyDirtyYoungListClosure : public HeapRegionClosure {
 583 private:
 584   G1HeapVerifier* _verifier;
 585 public:
 586   G1VerifyDirtyYoungListClosure(G1HeapVerifier* verifier) : HeapRegionClosure(), _verifier(verifier) { }
 587   virtual bool doHeapRegion(HeapRegion* r) {
 588     _verifier->verify_dirty_region(r);
 589     return false;
 590   }
 591 };
 592 
 593 void G1HeapVerifier::verify_dirty_young_regions() {
 594   G1VerifyDirtyYoungListClosure cl(this);
 595   _g1h->collection_set()->iterate(&cl);
 596 }
 597 
 598 bool G1HeapVerifier::verify_no_bits_over_tams(const char* bitmap_name, G1CMBitMapRO* bitmap,
 599                                                HeapWord* tams, HeapWord* end) {
 600   guarantee(tams <= end,
 601             "tams: " PTR_FORMAT " end: " PTR_FORMAT, p2i(tams), p2i(end));
 602   HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end);
 603   if (result < end) {
 604     log_error(gc, verify)("## wrong marked address on %s bitmap: " PTR_FORMAT, bitmap_name, p2i(result));
 605     log_error(gc, verify)("## %s tams: " PTR_FORMAT " end: " PTR_FORMAT, bitmap_name, p2i(tams), p2i(end));
 606     return false;
 607   }
 608   return true;
 609 }
 610 
 611 bool G1HeapVerifier::verify_bitmaps(const char* caller, HeapRegion* hr) {
 612   G1CMBitMapRO* prev_bitmap = _g1h->concurrent_mark()->prevMarkBitMap();
 613   G1CMBitMapRO* next_bitmap = (G1CMBitMapRO*) _g1h->concurrent_mark()->nextMarkBitMap();
 614 
 615   HeapWord* bottom = hr->bottom();
 616   HeapWord* ptams  = hr->prev_top_at_mark_start();
 617   HeapWord* ntams  = hr->next_top_at_mark_start();
 618   HeapWord* end    = hr->end();
 619 
 620   bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);
 621 
 622   bool res_n = true;
 623   // We reset mark_in_progress() before we reset _cmThread->in_progress() and in this window
 624   // we do the clearing of the next bitmap concurrently. Thus, we can not verify the bitmap
 625   // if we happen to be in that state.
 626   if (_g1h->collector_state()->mark_in_progress() || !_g1h->_cmThread->in_progress()) {
 627     res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
 628   }
 629   if (!res_p || !res_n) {
 630     log_error(gc, verify)("#### Bitmap verification failed for " HR_FORMAT, HR_FORMAT_PARAMS(hr));
 631     log_error(gc, verify)("#### Caller: %s", caller);
 632     return false;
 633   }
 634   return true;
 635 }
 636 
 637 void G1HeapVerifier::check_bitmaps(const char* caller, HeapRegion* hr) {
 638   if (!G1VerifyBitmaps) return;
 639 
 640   guarantee(verify_bitmaps(caller, hr), "bitmap verification");
 641 }
 642 
 643 class G1VerifyBitmapClosure : public HeapRegionClosure {
 644 private:
 645   const char* _caller;
 646   G1HeapVerifier* _verifier;
 647   bool _failures;
 648 
 649 public:
 650   G1VerifyBitmapClosure(const char* caller, G1HeapVerifier* verifier) :
 651     _caller(caller), _verifier(verifier), _failures(false) { }
 652 
 653   bool failures() { return _failures; }
 654 
 655   virtual bool doHeapRegion(HeapRegion* hr) {
 656     bool result = _verifier->verify_bitmaps(_caller, hr);
 657     if (!result) {
 658       _failures = true;
 659     }
 660     return false;
 661   }
 662 };
 663 
 664 void G1HeapVerifier::check_bitmaps(const char* caller) {
 665   if (!G1VerifyBitmaps) return;
 666 
 667   G1VerifyBitmapClosure cl(caller, this);
 668   _g1h->heap_region_iterate(&cl);
 669   guarantee(!cl.failures(), "bitmap verification");
 670 }
 671 
 672 class G1CheckCSetFastTableClosure : public HeapRegionClosure {
 673  private:
 674   bool _failures;
 675  public:
 676   G1CheckCSetFastTableClosure() : HeapRegionClosure(), _failures(false) { }
 677 
 678   virtual bool doHeapRegion(HeapRegion* hr) {
 679     uint i = hr->hrm_index();
 680     InCSetState cset_state = (InCSetState) G1CollectedHeap::heap()->_in_cset_fast_test.get_by_index(i);
 681     if (hr->is_humongous()) {
 682       if (hr->in_collection_set()) {
 683         log_error(gc, verify)("## humongous region %u in CSet", i);
 684         _failures = true;
 685         return true;
 686       }
 687       if (cset_state.is_in_cset()) {
 688         log_error(gc, verify)("## inconsistent cset state " CSETSTATE_FORMAT " for humongous region %u", cset_state.value(), i);
 689         _failures = true;
 690         return true;
 691       }
 692       if (hr->is_continues_humongous() && cset_state.is_humongous()) {
 693         log_error(gc, verify)("## inconsistent cset state " CSETSTATE_FORMAT " for continues humongous region %u", cset_state.value(), i);
 694         _failures = true;
 695         return true;
 696       }
 697     } else {
 698       if (cset_state.is_humongous()) {
 699         log_error(gc, verify)("## inconsistent cset state " CSETSTATE_FORMAT " for non-humongous region %u", cset_state.value(), i);
 700         _failures = true;
 701         return true;
 702       }
 703       if (hr->in_collection_set() != cset_state.is_in_cset()) {
 704         log_error(gc, verify)("## in CSet %d / cset state " CSETSTATE_FORMAT " inconsistency for region %u",
 705                              hr->in_collection_set(), cset_state.value(), i);
 706         _failures = true;
 707         return true;
 708       }
 709       if (cset_state.is_in_cset()) {
 710         if (hr->is_young() != (cset_state.is_young())) {
 711           log_error(gc, verify)("## is_young %d / cset state " CSETSTATE_FORMAT " inconsistency for region %u",
 712                                hr->is_young(), cset_state.value(), i);
 713           _failures = true;
 714           return true;
 715         }
 716         if (hr->is_old() != (cset_state.is_old())) {
 717           log_error(gc, verify)("## is_old %d / cset state " CSETSTATE_FORMAT " inconsistency for region %u",
 718                                hr->is_old(), cset_state.value(), i);
 719           _failures = true;
 720           return true;
 721         }
 722       }
 723     }
 724     return false;
 725   }
 726 
 727   bool failures() const { return _failures; }
 728 };
 729 
 730 bool G1HeapVerifier::check_cset_fast_test() {
 731   G1CheckCSetFastTableClosure cl;
 732   _g1h->_hrm.iterate(&cl);
 733   return !cl.failures();
 734 }
 735 #endif // PRODUCT