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