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