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