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