1 /*
   2  * Copyright (c) 2016, 2019, 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 "code/nmethod.hpp"
  27 #include "gc/g1/g1Allocator.inline.hpp"
  28 #include "gc/g1/g1CollectedHeap.inline.hpp"
  29 #include "gc/g1/g1ConcurrentMarkThread.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.inline.hpp"
  35 #include "gc/g1/heapRegionRemSet.hpp"
  36 #include "gc/g1/g1StringDedup.hpp"
  37 #include "logging/log.hpp"
  38 #include "logging/logStream.hpp"
  39 #include "memory/iterator.inline.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "oops/access.inline.hpp"
  42 #include "oops/compressedOops.inline.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "runtime/handles.inline.hpp"
  45 
  46 int G1HeapVerifier::_enabled_verification_types = G1HeapVerifier::G1VerifyAll;
  47 
  48 class VerifyRootsClosure: public OopClosure {
  49 private:
  50   G1CollectedHeap* _g1h;
  51   VerifyOption     _vo;
  52   bool             _failures;
  53 public:
  54   // _vo == UsePrevMarking -> use "prev" marking information,
  55   // _vo == UseNextMarking -> use "next" marking information,
  56   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS
  57   VerifyRootsClosure(VerifyOption vo) :
  58     _g1h(G1CollectedHeap::heap()),
  59     _vo(vo),
  60     _failures(false) { }
  61 
  62   bool failures() { return _failures; }
  63 
  64   template <class T> void do_oop_work(T* p) {
  65     T heap_oop = RawAccess<>::oop_load(p);
  66     if (!CompressedOops::is_null(heap_oop)) {
  67       oop obj = CompressedOops::decode_not_null(heap_oop);
  68       if (_g1h->is_obj_dead_cond(obj, _vo)) {
  69         Log(gc, verify) log;
  70         log.error("Root location " PTR_FORMAT " points to dead obj " PTR_FORMAT, p2i(p), p2i(obj));
  71         ResourceMark rm;
  72         LogStream ls(log.error());
  73         obj->print_on(&ls);
  74         _failures = true;
  75       }
  76     }
  77   }
  78 
  79   void do_oop(oop* p)       { do_oop_work(p); }
  80   void do_oop(narrowOop* p) { do_oop_work(p); }
  81 };
  82 
  83 class G1VerifyCodeRootOopClosure: public OopClosure {
  84   G1CollectedHeap* _g1h;
  85   OopClosure* _root_cl;
  86   nmethod* _nm;
  87   VerifyOption _vo;
  88   bool _failures;
  89 
  90   template <class T> void do_oop_work(T* p) {
  91     // First verify that this root is live
  92     _root_cl->do_oop(p);
  93 
  94     if (!G1VerifyHeapRegionCodeRoots) {
  95       // We're not verifying the code roots attached to heap region.
  96       return;
  97     }
  98 
  99     // Don't check the code roots during marking verification in a full GC
 100     if (_vo == VerifyOption_G1UseFullMarking) {
 101       return;
 102     }
 103 
 104     // Now verify that the current nmethod (which contains p) is
 105     // in the code root list of the heap region containing the
 106     // object referenced by p.
 107 
 108     T heap_oop = RawAccess<>::oop_load(p);
 109     if (!CompressedOops::is_null(heap_oop)) {
 110       oop obj = CompressedOops::decode_not_null(heap_oop);
 111 
 112       // Now fetch the region containing the object
 113       HeapRegion* hr = _g1h->heap_region_containing(obj);
 114       HeapRegionRemSet* hrrs = hr->rem_set();
 115       // Verify that the strong code root list for this region
 116       // contains the nmethod
 117       if (!hrrs->strong_code_roots_list_contains(_nm)) {
 118         log_error(gc, verify)("Code root location " PTR_FORMAT " "
 119                               "from nmethod " PTR_FORMAT " not in strong "
 120                               "code roots for region [" PTR_FORMAT "," PTR_FORMAT ")",
 121                               p2i(p), p2i(_nm), p2i(hr->bottom()), p2i(hr->end()));
 122         _failures = true;
 123       }
 124     }
 125   }
 126 
 127 public:
 128   G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
 129     _g1h(g1h), _root_cl(root_cl), _nm(NULL), _vo(vo), _failures(false) {}
 130 
 131   void do_oop(oop* p) { do_oop_work(p); }
 132   void do_oop(narrowOop* p) { do_oop_work(p); }
 133 
 134   void set_nmethod(nmethod* nm) { _nm = nm; }
 135   bool failures() { return _failures; }
 136 };
 137 
 138 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
 139   G1VerifyCodeRootOopClosure* _oop_cl;
 140 
 141 public:
 142   G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
 143     _oop_cl(oop_cl) {}
 144 
 145   void do_code_blob(CodeBlob* cb) {
 146     nmethod* nm = cb->as_nmethod_or_null();
 147     if (nm != NULL) {
 148       _oop_cl->set_nmethod(nm);
 149       nm->oops_do(_oop_cl);
 150     }
 151   }
 152 };
 153 
 154 class YoungRefCounterClosure : public OopClosure {
 155   G1CollectedHeap* _g1h;
 156   int              _count;
 157  public:
 158   YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
 159   void do_oop(oop* p)       { if (_g1h->is_in_young(*p)) { _count++; } }
 160   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
 161 
 162   int count() { return _count; }
 163   void reset_count() { _count = 0; };
 164 };
 165 
 166 class VerifyCLDClosure: public CLDClosure {
 167   YoungRefCounterClosure _young_ref_counter_closure;
 168   OopClosure *_oop_closure;
 169  public:
 170   VerifyCLDClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
 171   void do_cld(ClassLoaderData* cld) {
 172     cld->oops_do(_oop_closure, ClassLoaderData::_claim_none);
 173 
 174     _young_ref_counter_closure.reset_count();
 175     cld->oops_do(&_young_ref_counter_closure, ClassLoaderData::_claim_none);
 176     if (_young_ref_counter_closure.count() > 0) {
 177       guarantee(cld->has_modified_oops(), "CLD " PTR_FORMAT ", has young %d refs but is not dirty.", p2i(cld), _young_ref_counter_closure.count());
 178     }
 179   }
 180 };
 181 
 182 class VerifyLivenessOopClosure: public BasicOopIterateClosure {
 183   G1CollectedHeap* _g1h;
 184   VerifyOption _vo;
 185 public:
 186   VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
 187     _g1h(g1h), _vo(vo)
 188   { }
 189   void do_oop(narrowOop *p) { do_oop_work(p); }
 190   void do_oop(      oop *p) { do_oop_work(p); }
 191 
 192   template <class T> void do_oop_work(T *p) {
 193     oop obj = RawAccess<>::oop_load(p);
 194     guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
 195               "Dead object referenced by a not dead object");
 196   }
 197 };
 198 
 199 class VerifyObjsInRegionClosure: public ObjectClosure {
 200 private:
 201   G1CollectedHeap* _g1h;
 202   size_t _live_bytes;
 203   HeapRegion *_hr;
 204   VerifyOption _vo;
 205 public:
 206   // _vo == UsePrevMarking -> use "prev" marking information,
 207   // _vo == UseNextMarking -> use "next" marking information,
 208   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS.
 209   VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
 210     : _live_bytes(0), _hr(hr), _vo(vo) {
 211     _g1h = G1CollectedHeap::heap();
 212   }
 213   void do_object(oop o) {
 214     VerifyLivenessOopClosure isLive(_g1h, _vo);
 215     assert(o != NULL, "Huh?");
 216     if (!_g1h->is_obj_dead_cond(o, _vo)) {
 217       // If the object is alive according to the full gc mark,
 218       // then verify that the marking information agrees.
 219       // Note we can't verify the contra-positive of the
 220       // above: if the object is dead (according to the mark
 221       // word), it may not be marked, or may have been marked
 222       // but has since became dead, or may have been allocated
 223       // since the last marking.
 224       if (_vo == VerifyOption_G1UseFullMarking) {
 225         guarantee(!_g1h->is_obj_dead(o), "Full GC marking and concurrent mark mismatch");
 226       }
 227 
 228       o->oop_iterate(&isLive);
 229       if (!_hr->obj_allocated_since_prev_marking(o)) {
 230         size_t obj_size = o->size();    // Make sure we don't overflow
 231         _live_bytes += (obj_size * HeapWordSize);
 232       }
 233     }
 234   }
 235   size_t live_bytes() { return _live_bytes; }
 236 };
 237 
 238 class VerifyArchiveOopClosure: public BasicOopIterateClosure {
 239   HeapRegion* _hr;
 240 public:
 241   VerifyArchiveOopClosure(HeapRegion *hr)
 242     : _hr(hr) { }
 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 = RawAccess<>::oop_load(p);
 248 
 249     if (_hr->is_open_archive()) {
 250       guarantee(obj == NULL || G1ArchiveAllocator::is_archived_object(obj),
 251                 "Archive object at " PTR_FORMAT " references a non-archive object at " PTR_FORMAT,
 252                 p2i(p), p2i(obj));
 253     } else {
 254       assert(_hr->is_closed_archive(), "should be closed archive region");
 255       guarantee(obj == NULL || G1ArchiveAllocator::is_closed_archive_object(obj),
 256                 "Archive object at " PTR_FORMAT " references a non-archive object at " PTR_FORMAT,
 257                 p2i(p), p2i(obj));
 258     }
 259   }
 260 };
 261 
 262 class VerifyObjectInArchiveRegionClosure: public ObjectClosure {
 263   HeapRegion* _hr;
 264 public:
 265   VerifyObjectInArchiveRegionClosure(HeapRegion *hr, bool verbose)
 266     : _hr(hr) { }
 267   // Verify that all object pointers are to archive regions.
 268   void do_object(oop o) {
 269     VerifyArchiveOopClosure checkOop(_hr);
 270     assert(o != NULL, "Should not be here for NULL oops");
 271     o->oop_iterate(&checkOop);
 272   }
 273 };
 274 
 275 // Should be only used at CDS dump time
 276 class VerifyReadyForArchivingRegionClosure : public HeapRegionClosure {
 277   bool _seen_free;
 278   bool _has_holes;
 279   bool _has_unexpected_holes;
 280   bool _has_humongous;
 281 public:
 282   bool has_holes() {return _has_holes;}
 283   bool has_unexpected_holes() {return _has_unexpected_holes;}
 284   bool has_humongous() {return _has_humongous;}
 285 
 286   VerifyReadyForArchivingRegionClosure() : HeapRegionClosure() {
 287     _seen_free = false;
 288     _has_holes = false;
 289     _has_unexpected_holes = false;
 290     _has_humongous = false;
 291   }
 292   virtual bool do_heap_region(HeapRegion* hr) {
 293     const char* hole = "";
 294 
 295     if (hr->is_free()) {
 296       _seen_free = true;
 297     } else {
 298       if (_seen_free) {
 299         _has_holes = true;
 300         if (hr->is_humongous()) {
 301           hole = " hole";
 302         } else {
 303           _has_unexpected_holes = true;
 304           hole = " hole **** unexpected ****";
 305         }
 306       }
 307     }
 308     if (hr->is_humongous()) {
 309       _has_humongous = true;
 310     }
 311     log_info(gc, region, cds)("HeapRegion " INTPTR_FORMAT " %s%s", p2i(hr->bottom()), hr->get_type_str(), hole);
 312     return false;
 313   }
 314 };
 315 
 316 // We want all used regions to be moved to the bottom-end of the heap, so we have
 317 // a contiguous range of free regions at the top end of the heap. This way, we can
 318 // avoid fragmentation while allocating the archive regions.
 319 //
 320 // Before calling this, a full GC should have been executed with a single worker thread,
 321 // so that no old regions would be moved to the middle of the heap.
 322 void G1HeapVerifier::verify_ready_for_archiving() {
 323   VerifyReadyForArchivingRegionClosure cl;
 324   G1CollectedHeap::heap()->heap_region_iterate(&cl);
 325   if (cl.has_holes()) {
 326     log_warning(gc, verify)("All free regions should be at the top end of the heap, but"
 327                             " we found holes. This is probably caused by (unmovable) humongous"
 328                             " allocations, and may lead to fragmentation while"
 329                             " writing archive heap memory regions.");
 330   }
 331   if (cl.has_humongous()) {
 332     log_warning(gc, verify)("(Unmovable) humongous regions have been found and"
 333                             " may lead to fragmentation while"
 334                             " writing archive heap memory regions.");
 335   }
 336   assert(!cl.has_unexpected_holes(), "all holes should have been caused by humongous regions");
 337 }
 338 
 339 class VerifyArchivePointerRegionClosure: public HeapRegionClosure {
 340   virtual bool do_heap_region(HeapRegion* r) {
 341    if (r->is_archive()) {
 342       VerifyObjectInArchiveRegionClosure verify_oop_pointers(r, false);
 343       r->object_iterate(&verify_oop_pointers);
 344     }
 345     return false;
 346   }
 347 };
 348 
 349 void G1HeapVerifier::verify_archive_regions() {
 350   G1CollectedHeap*  g1h = G1CollectedHeap::heap();
 351   VerifyArchivePointerRegionClosure cl;
 352   g1h->heap_region_iterate(&cl);
 353 }
 354 
 355 class VerifyRegionClosure: public HeapRegionClosure {
 356 private:
 357   bool             _par;
 358   VerifyOption     _vo;
 359   bool             _failures;
 360 public:
 361   // _vo == UsePrevMarking -> use "prev" marking information,
 362   // _vo == UseNextMarking -> use "next" marking information,
 363   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS
 364   VerifyRegionClosure(bool par, VerifyOption vo)
 365     : _par(par),
 366       _vo(vo),
 367       _failures(false) {}
 368 
 369   bool failures() {
 370     return _failures;
 371   }
 372 
 373   bool do_heap_region(HeapRegion* r) {
 374     guarantee(!r->has_index_in_opt_cset(), "Region %u still has opt collection set index %u", r->hrm_index(), r->index_in_opt_cset());
 375     guarantee(!r->is_young() || r->rem_set()->is_complete(), "Remembered set for Young region %u must be complete, is %s", r->hrm_index(), r->rem_set()->get_state_str());
 376     // Humongous and old regions regions might be of any state, so can't check here.
 377     guarantee(!r->is_free() || !r->rem_set()->is_tracked(), "Remembered set for free region %u must be untracked, is %s", r->hrm_index(), r->rem_set()->get_state_str());
 378     // Verify that the continues humongous regions' remembered set state matches the
 379     // one from the starts humongous region.
 380     if (r->is_continues_humongous()) {
 381       if (r->rem_set()->get_state_str() != r->humongous_start_region()->rem_set()->get_state_str()) {
 382          log_error(gc, verify)("Remset states differ: Region %u (%s) remset %s with starts region %u (%s) remset %s",
 383                                r->hrm_index(),
 384                                r->get_short_type_str(),
 385                                r->rem_set()->get_state_str(),
 386                                r->humongous_start_region()->hrm_index(),
 387                                r->humongous_start_region()->get_short_type_str(),
 388                                r->humongous_start_region()->rem_set()->get_state_str());
 389          _failures = true;
 390       }
 391     }
 392     // For archive regions, verify there are no heap pointers to
 393     // non-pinned regions. For all others, verify liveness info.
 394     if (r->is_closed_archive()) {
 395       VerifyObjectInArchiveRegionClosure verify_oop_pointers(r, false);
 396       r->object_iterate(&verify_oop_pointers);
 397       return true;
 398     } else if (r->is_open_archive()) {
 399       VerifyObjsInRegionClosure verify_open_archive_oop(r, _vo);
 400       r->object_iterate(&verify_open_archive_oop);
 401       return true;
 402     } else if (!r->is_continues_humongous()) {
 403       bool failures = false;
 404       r->verify(_vo, &failures);
 405       if (failures) {
 406         _failures = true;
 407       } else if (!r->is_starts_humongous()) {
 408         VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
 409         r->object_iterate(&not_dead_yet_cl);
 410         if (_vo != VerifyOption_G1UseNextMarking) {
 411           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
 412             log_error(gc, verify)("[" PTR_FORMAT "," PTR_FORMAT "] max_live_bytes " SIZE_FORMAT " < calculated " SIZE_FORMAT,
 413                                   p2i(r->bottom()), p2i(r->end()), r->max_live_bytes(), not_dead_yet_cl.live_bytes());
 414             _failures = true;
 415           }
 416         } else {
 417           // When vo == UseNextMarking we cannot currently do a sanity
 418           // check on the live bytes as the calculation has not been
 419           // finalized yet.
 420         }
 421       }
 422     }
 423     return false; // stop the region iteration if we hit a failure
 424   }
 425 };
 426 
 427 // This is the task used for parallel verification of the heap regions
 428 
 429 class G1ParVerifyTask: public AbstractGangTask {
 430 private:
 431   G1CollectedHeap*  _g1h;
 432   VerifyOption      _vo;
 433   bool              _failures;
 434   HeapRegionClaimer _hrclaimer;
 435 
 436 public:
 437   // _vo == UsePrevMarking -> use "prev" marking information,
 438   // _vo == UseNextMarking -> use "next" marking information,
 439   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS
 440   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
 441       AbstractGangTask("Parallel verify task"),
 442       _g1h(g1h),
 443       _vo(vo),
 444       _failures(false),
 445       _hrclaimer(g1h->workers()->active_workers()) {}
 446 
 447   bool failures() {
 448     return _failures;
 449   }
 450 
 451   void work(uint worker_id) {
 452     HandleMark hm;
 453     VerifyRegionClosure blk(true, _vo);
 454     _g1h->heap_region_par_iterate_from_worker_offset(&blk, &_hrclaimer, worker_id);
 455     if (blk.failures()) {
 456       _failures = true;
 457     }
 458   }
 459 };
 460 
 461 void G1HeapVerifier::enable_verification_type(G1VerifyType type) {
 462   // First enable will clear _enabled_verification_types.
 463   if (_enabled_verification_types == G1VerifyAll) {
 464     _enabled_verification_types = type;
 465   } else {
 466     _enabled_verification_types |= type;
 467   }
 468 }
 469 
 470 bool G1HeapVerifier::should_verify(G1VerifyType type) {
 471   return (_enabled_verification_types & type) == type;
 472 }
 473 
 474 void G1HeapVerifier::verify(VerifyOption vo) {
 475   if (!SafepointSynchronize::is_at_safepoint()) {
 476     log_info(gc, verify)("Skipping verification. Not at safepoint.");
 477   }
 478 
 479   assert(Thread::current()->is_VM_thread(),
 480          "Expected to be executed serially by the VM thread at this point");
 481 
 482   log_debug(gc, verify)("Roots");
 483   VerifyRootsClosure rootsCl(vo);
 484   VerifyCLDClosure cldCl(_g1h, &rootsCl);
 485 
 486   // We apply the relevant closures to all the oops in the
 487   // system dictionary, class loader data graph, the string table
 488   // and the nmethods in the code cache.
 489   G1VerifyCodeRootOopClosure codeRootsCl(_g1h, &rootsCl, vo);
 490   G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
 491 
 492   {
 493     G1RootProcessor root_processor(_g1h, 1);
 494     root_processor.process_all_roots(&rootsCl, &cldCl, &blobsCl);
 495   }
 496 
 497   bool failures = rootsCl.failures() || codeRootsCl.failures();
 498 
 499   if (!_g1h->policy()->collector_state()->in_full_gc()) {
 500     // If we're verifying during a full GC then the region sets
 501     // will have been torn down at the start of the GC. Therefore
 502     // verifying the region sets will fail. So we only verify
 503     // the region sets when not in a full GC.
 504     log_debug(gc, verify)("HeapRegionSets");
 505     verify_region_sets();
 506   }
 507 
 508   log_debug(gc, verify)("HeapRegions");
 509   if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
 510 
 511     G1ParVerifyTask task(_g1h, vo);
 512     _g1h->workers()->run_task(&task);
 513     if (task.failures()) {
 514       failures = true;
 515     }
 516 
 517   } else {
 518     VerifyRegionClosure blk(false, vo);
 519     _g1h->heap_region_iterate(&blk);
 520     if (blk.failures()) {
 521       failures = true;
 522     }
 523   }
 524 
 525   if (G1StringDedup::is_enabled()) {
 526     log_debug(gc, verify)("StrDedup");
 527     G1StringDedup::verify();
 528   }
 529 
 530   if (failures) {
 531     log_error(gc, verify)("Heap after failed verification (kind %d):", vo);
 532     // It helps to have the per-region information in the output to
 533     // help us track down what went wrong. This is why we call
 534     // print_extended_on() instead of print_on().
 535     Log(gc, verify) log;
 536     ResourceMark rm;
 537     LogStream ls(log.error());
 538     _g1h->print_extended_on(&ls);
 539   }
 540   guarantee(!failures, "there should not have been any failures");
 541 }
 542 
 543 // Heap region set verification
 544 
 545 class VerifyRegionListsClosure : public HeapRegionClosure {
 546 private:
 547   HeapRegionSet*   _old_set;
 548   HeapRegionSet*   _archive_set;
 549   HeapRegionSet*   _humongous_set;
 550   HeapRegionManager* _hrm;
 551 
 552 public:
 553   uint _old_count;
 554   uint _archive_count;
 555   uint _humongous_count;
 556   uint _free_count;
 557 
 558   VerifyRegionListsClosure(HeapRegionSet* old_set,
 559                            HeapRegionSet* archive_set,
 560                            HeapRegionSet* humongous_set,
 561                            HeapRegionManager* hrm) :
 562     _old_set(old_set), _archive_set(archive_set), _humongous_set(humongous_set), _hrm(hrm),
 563     _old_count(), _archive_count(), _humongous_count(), _free_count(){ }
 564 
 565   bool do_heap_region(HeapRegion* hr) {
 566     if (hr->is_young()) {
 567       // TODO
 568     } else if (hr->is_humongous()) {
 569       assert(hr->containing_set() == _humongous_set, "Heap region %u is humongous but not in humongous set.", hr->hrm_index());
 570       _humongous_count++;
 571     } else if (hr->is_empty()) {
 572       assert(_hrm->is_free(hr), "Heap region %u is empty but not on the free list.", hr->hrm_index());
 573       _free_count++;
 574     } else if (hr->is_archive()) {
 575       assert(hr->containing_set() == _archive_set, "Heap region %u is archive but not in the archive set.", hr->hrm_index());
 576       _archive_count++;
 577     } else if (hr->is_old()) {
 578       assert(hr->containing_set() == _old_set, "Heap region %u is old but not in the old set.", hr->hrm_index());
 579       _old_count++;
 580     } else {
 581       // There are no other valid region types. Check for one invalid
 582       // one we can identify: pinned without old or humongous set.
 583       assert(!hr->is_pinned(), "Heap region %u is pinned but not old (archive) or humongous.", hr->hrm_index());
 584       ShouldNotReachHere();
 585     }
 586     return false;
 587   }
 588 
 589   void verify_counts(HeapRegionSet* old_set, HeapRegionSet* archive_set, HeapRegionSet* humongous_set, HeapRegionManager* free_list) {
 590     guarantee(old_set->length() == _old_count, "Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count);
 591     guarantee(archive_set->length() == _archive_count, "Archive set count mismatch. Expected %u, actual %u.", archive_set->length(), _archive_count);
 592     guarantee(humongous_set->length() == _humongous_count, "Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count);
 593     guarantee(free_list->num_free_regions() == _free_count, "Free list count mismatch. Expected %u, actual %u.", free_list->num_free_regions(), _free_count);
 594   }
 595 };
 596 
 597 void G1HeapVerifier::verify_region_sets() {
 598   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
 599 
 600   // First, check the explicit lists.
 601   _g1h->_hrm->verify();
 602 
 603   // Finally, make sure that the region accounting in the lists is
 604   // consistent with what we see in the heap.
 605 
 606   VerifyRegionListsClosure cl(&_g1h->_old_set, &_g1h->_archive_set, &_g1h->_humongous_set, _g1h->_hrm);
 607   _g1h->heap_region_iterate(&cl);
 608   cl.verify_counts(&_g1h->_old_set, &_g1h->_archive_set, &_g1h->_humongous_set, _g1h->_hrm);
 609 }
 610 
 611 void G1HeapVerifier::prepare_for_verify() {
 612   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
 613     _g1h->ensure_parsability(false);
 614   }
 615 }
 616 
 617 double G1HeapVerifier::verify(G1VerifyType type, VerifyOption vo, const char* msg) {
 618   double verify_time_ms = 0.0;
 619 
 620   if (should_verify(type) && _g1h->total_collections() >= VerifyGCStartAt) {
 621     double verify_start = os::elapsedTime();
 622     HandleMark hm;  // Discard invalid handles created during verification
 623     prepare_for_verify();
 624     Universe::verify(vo, msg);
 625     verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
 626   }
 627 
 628   return verify_time_ms;
 629 }
 630 
 631 void G1HeapVerifier::verify_before_gc(G1VerifyType type) {
 632   if (VerifyBeforeGC) {
 633     double verify_time_ms = verify(type, VerifyOption_G1UsePrevMarking, "Before GC");
 634     _g1h->phase_times()->record_verify_before_time_ms(verify_time_ms);
 635   }
 636 }
 637 
 638 void G1HeapVerifier::verify_after_gc(G1VerifyType type) {
 639   if (VerifyAfterGC) {
 640     double verify_time_ms = verify(type, VerifyOption_G1UsePrevMarking, "After GC");
 641     _g1h->phase_times()->record_verify_after_time_ms(verify_time_ms);
 642   }
 643 }
 644 
 645 
 646 #ifndef PRODUCT
 647 class G1VerifyCardTableCleanup: public HeapRegionClosure {
 648   G1HeapVerifier* _verifier;
 649 public:
 650   G1VerifyCardTableCleanup(G1HeapVerifier* verifier)
 651     : _verifier(verifier) { }
 652   virtual bool do_heap_region(HeapRegion* r) {
 653     if (r->is_survivor()) {
 654       _verifier->verify_dirty_region(r);
 655     } else {
 656       _verifier->verify_not_dirty_region(r);
 657     }
 658     return false;
 659   }
 660 };
 661 
 662 void G1HeapVerifier::verify_card_table_cleanup() {
 663   if (G1VerifyCTCleanup || VerifyAfterGC) {
 664     G1VerifyCardTableCleanup cleanup_verifier(this);
 665     _g1h->heap_region_iterate(&cleanup_verifier);
 666   }
 667 }
 668 
 669 void G1HeapVerifier::verify_not_dirty_region(HeapRegion* hr) {
 670   // All of the region should be clean.
 671   G1CardTable* ct = _g1h->card_table();
 672   MemRegion mr(hr->bottom(), hr->end());
 673   ct->verify_not_dirty_region(mr);
 674 }
 675 
 676 void G1HeapVerifier::verify_dirty_region(HeapRegion* hr) {
 677   // We cannot guarantee that [bottom(),end()] is dirty.  Threads
 678   // dirty allocated blocks as they allocate them. The thread that
 679   // retires each region and replaces it with a new one will do a
 680   // maximal allocation to fill in [pre_dummy_top(),end()] but will
 681   // not dirty that area (one less thing to have to do while holding
 682   // a lock). So we can only verify that [bottom(),pre_dummy_top()]
 683   // is dirty.
 684   G1CardTable* ct = _g1h->card_table();
 685   MemRegion mr(hr->bottom(), hr->pre_dummy_top());
 686   if (hr->is_young()) {
 687     ct->verify_g1_young_region(mr);
 688   } else {
 689     ct->verify_dirty_region(mr);
 690   }
 691 }
 692 
 693 class G1VerifyDirtyYoungListClosure : public HeapRegionClosure {
 694 private:
 695   G1HeapVerifier* _verifier;
 696 public:
 697   G1VerifyDirtyYoungListClosure(G1HeapVerifier* verifier) : HeapRegionClosure(), _verifier(verifier) { }
 698   virtual bool do_heap_region(HeapRegion* r) {
 699     _verifier->verify_dirty_region(r);
 700     return false;
 701   }
 702 };
 703 
 704 void G1HeapVerifier::verify_dirty_young_regions() {
 705   G1VerifyDirtyYoungListClosure cl(this);
 706   _g1h->collection_set()->iterate(&cl);
 707 }
 708 
 709 bool G1HeapVerifier::verify_no_bits_over_tams(const char* bitmap_name, const G1CMBitMap* const bitmap,
 710                                                HeapWord* tams, HeapWord* end) {
 711   guarantee(tams <= end,
 712             "tams: " PTR_FORMAT " end: " PTR_FORMAT, p2i(tams), p2i(end));
 713   HeapWord* result = bitmap->get_next_marked_addr(tams, end);
 714   if (result < end) {
 715     log_error(gc, verify)("## wrong marked address on %s bitmap: " PTR_FORMAT, bitmap_name, p2i(result));
 716     log_error(gc, verify)("## %s tams: " PTR_FORMAT " end: " PTR_FORMAT, bitmap_name, p2i(tams), p2i(end));
 717     return false;
 718   }
 719   return true;
 720 }
 721 
 722 bool G1HeapVerifier::verify_bitmaps(const char* caller, HeapRegion* hr) {
 723   const G1CMBitMap* const prev_bitmap = _g1h->concurrent_mark()->prev_mark_bitmap();
 724   const G1CMBitMap* const next_bitmap = _g1h->concurrent_mark()->next_mark_bitmap();
 725 
 726   HeapWord* ptams  = hr->prev_top_at_mark_start();
 727   HeapWord* ntams  = hr->next_top_at_mark_start();
 728   HeapWord* end    = hr->end();
 729 
 730   bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);
 731 
 732   bool res_n = true;
 733   // We cannot verify the next bitmap while we are about to clear it.
 734   if (!_g1h->collector_state()->clearing_next_bitmap()) {
 735     res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
 736   }
 737   if (!res_p || !res_n) {
 738     log_error(gc, verify)("#### Bitmap verification failed for " HR_FORMAT, HR_FORMAT_PARAMS(hr));
 739     log_error(gc, verify)("#### Caller: %s", caller);
 740     return false;
 741   }
 742   return true;
 743 }
 744 
 745 void G1HeapVerifier::check_bitmaps(const char* caller, HeapRegion* hr) {
 746   if (!G1VerifyBitmaps) {
 747     return;
 748   }
 749 
 750   guarantee(verify_bitmaps(caller, hr), "bitmap verification");
 751 }
 752 
 753 class G1VerifyBitmapClosure : public HeapRegionClosure {
 754 private:
 755   const char* _caller;
 756   G1HeapVerifier* _verifier;
 757   bool _failures;
 758 
 759 public:
 760   G1VerifyBitmapClosure(const char* caller, G1HeapVerifier* verifier) :
 761     _caller(caller), _verifier(verifier), _failures(false) { }
 762 
 763   bool failures() { return _failures; }
 764 
 765   virtual bool do_heap_region(HeapRegion* hr) {
 766     bool result = _verifier->verify_bitmaps(_caller, hr);
 767     if (!result) {
 768       _failures = true;
 769     }
 770     return false;
 771   }
 772 };
 773 
 774 void G1HeapVerifier::check_bitmaps(const char* caller) {
 775   if (!G1VerifyBitmaps) {
 776     return;
 777   }
 778 
 779   G1VerifyBitmapClosure cl(caller, this);
 780   _g1h->heap_region_iterate(&cl);
 781   guarantee(!cl.failures(), "bitmap verification");
 782 }
 783 
 784 class G1CheckCSetFastTableClosure : public HeapRegionClosure {
 785  private:
 786   bool _failures;
 787  public:
 788   G1CheckCSetFastTableClosure() : HeapRegionClosure(), _failures(false) { }
 789 
 790   virtual bool do_heap_region(HeapRegion* hr) {
 791     uint i = hr->hrm_index();
 792     InCSetState cset_state = (InCSetState) G1CollectedHeap::heap()->_in_cset_fast_test.get_by_index(i);
 793     if (hr->is_humongous()) {
 794       if (hr->in_collection_set()) {
 795         log_error(gc, verify)("## humongous region %u in CSet", i);
 796         _failures = true;
 797         return true;
 798       }
 799       if (cset_state.is_in_cset()) {
 800         log_error(gc, verify)("## inconsistent cset state " CSETSTATE_FORMAT " for humongous region %u", cset_state.value(), i);
 801         _failures = true;
 802         return true;
 803       }
 804       if (hr->is_continues_humongous() && cset_state.is_humongous()) {
 805         log_error(gc, verify)("## inconsistent cset state " CSETSTATE_FORMAT " for continues humongous region %u", cset_state.value(), i);
 806         _failures = true;
 807         return true;
 808       }
 809     } else {
 810       if (cset_state.is_humongous()) {
 811         log_error(gc, verify)("## inconsistent cset state " CSETSTATE_FORMAT " for non-humongous region %u", cset_state.value(), i);
 812         _failures = true;
 813         return true;
 814       }
 815       if (hr->in_collection_set() != cset_state.is_in_cset()) {
 816         log_error(gc, verify)("## in CSet %d / cset state " CSETSTATE_FORMAT " inconsistency for region %u",
 817                              hr->in_collection_set(), cset_state.value(), i);
 818         _failures = true;
 819         return true;
 820       }
 821       if (cset_state.is_in_cset()) {
 822         if (hr->is_archive()) {
 823           log_error(gc, verify)("## is_archive in collection set for region %u", i);
 824           _failures = true;
 825           return true;
 826         }
 827         if (hr->is_young() != (cset_state.is_young())) {
 828           log_error(gc, verify)("## is_young %d / cset state " CSETSTATE_FORMAT " inconsistency for region %u",
 829                                hr->is_young(), cset_state.value(), i);
 830           _failures = true;
 831           return true;
 832         }
 833         if (hr->is_old() != (cset_state.is_old())) {
 834           log_error(gc, verify)("## is_old %d / cset state " CSETSTATE_FORMAT " inconsistency for region %u",
 835                                hr->is_old(), cset_state.value(), i);
 836           _failures = true;
 837           return true;
 838         }
 839       }
 840     }
 841     return false;
 842   }
 843 
 844   bool failures() const { return _failures; }
 845 };
 846 
 847 bool G1HeapVerifier::check_cset_fast_test() {
 848   G1CheckCSetFastTableClosure cl;
 849   _g1h->_hrm->iterate(&cl);
 850   return !cl.failures();
 851 }
 852 #endif // PRODUCT