1 /*
   2  * Copyright (c) 2001, 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/g1BlockOffsetTable.inline.hpp"
  28 #include "gc/g1/g1CollectedHeap.inline.hpp"
  29 #include "gc/g1/g1CollectionSet.hpp"
  30 #include "gc/g1/g1HeapRegionTraceType.hpp"
  31 #include "gc/g1/g1OopClosures.inline.hpp"
  32 #include "gc/g1/heapRegion.inline.hpp"
  33 #include "gc/g1/heapRegionBounds.inline.hpp"
  34 #include "gc/g1/heapRegionManager.inline.hpp"
  35 #include "gc/g1/heapRegionRemSet.hpp"
  36 #include "gc/g1/heapRegionTracer.hpp"
  37 #include "gc/shared/genOopClosures.inline.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/atomic.hpp"
  46 #include "runtime/orderAccess.hpp"
  47 
  48 int    HeapRegion::LogOfHRGrainBytes = 0;
  49 int    HeapRegion::LogOfHRGrainWords = 0;
  50 int    HeapRegion::LogCardsPerRegion = 0;
  51 size_t HeapRegion::GrainBytes        = 0;
  52 size_t HeapRegion::GrainWords        = 0;
  53 size_t HeapRegion::CardsPerRegion    = 0;
  54 
  55 size_t HeapRegion::max_region_size() {
  56   return HeapRegionBounds::max_size();
  57 }
  58 
  59 size_t HeapRegion::min_region_size_in_words() {
  60   return HeapRegionBounds::min_size() >> LogHeapWordSize;
  61 }
  62 
  63 void HeapRegion::setup_heap_region_size(size_t initial_heap_size, size_t max_heap_size) {
  64   size_t region_size = G1HeapRegionSize;
  65   if (FLAG_IS_DEFAULT(G1HeapRegionSize)) {
  66     size_t average_heap_size = (initial_heap_size + max_heap_size) / 2;
  67     region_size = MAX2(average_heap_size / HeapRegionBounds::target_number(),
  68                        HeapRegionBounds::min_size());
  69   }
  70 
  71   int region_size_log = log2_long((jlong) region_size);
  72   // Recalculate the region size to make sure it's a power of
  73   // 2. This means that region_size is the largest power of 2 that's
  74   // <= what we've calculated so far.
  75   region_size = ((size_t)1 << region_size_log);
  76 
  77   // Now make sure that we don't go over or under our limits.
  78   if (region_size < HeapRegionBounds::min_size()) {
  79     region_size = HeapRegionBounds::min_size();
  80   } else if (region_size > HeapRegionBounds::max_size()) {
  81     region_size = HeapRegionBounds::max_size();
  82   }
  83 
  84   // And recalculate the log.
  85   region_size_log = log2_long((jlong) region_size);
  86 
  87   // Now, set up the globals.
  88   guarantee(LogOfHRGrainBytes == 0, "we should only set it once");
  89   LogOfHRGrainBytes = region_size_log;
  90 
  91   guarantee(LogOfHRGrainWords == 0, "we should only set it once");
  92   LogOfHRGrainWords = LogOfHRGrainBytes - LogHeapWordSize;
  93 
  94   guarantee(GrainBytes == 0, "we should only set it once");
  95   // The cast to int is safe, given that we've bounded region_size by
  96   // MIN_REGION_SIZE and MAX_REGION_SIZE.
  97   GrainBytes = region_size;
  98   log_info(gc, heap)("Heap region size: " SIZE_FORMAT "M", GrainBytes / M);
  99 
 100   guarantee(GrainWords == 0, "we should only set it once");
 101   GrainWords = GrainBytes >> LogHeapWordSize;
 102   guarantee((size_t) 1 << LogOfHRGrainWords == GrainWords, "sanity");
 103 
 104   guarantee(CardsPerRegion == 0, "we should only set it once");
 105   CardsPerRegion = GrainBytes >> G1CardTable::card_shift;
 106 
 107   LogCardsPerRegion = log2_long((jlong) CardsPerRegion);
 108 
 109   if (G1HeapRegionSize != GrainBytes) {
 110     FLAG_SET_ERGO(G1HeapRegionSize, GrainBytes);
 111   }
 112 }
 113 
 114 void HeapRegion::hr_clear(bool keep_remset, bool clear_space, bool locked) {
 115   assert(_humongous_start_region == NULL,
 116          "we should have already filtered out humongous regions");
 117   assert(!in_collection_set(),
 118          "Should not clear heap region %u in the collection set", hrm_index());
 119 
 120   clear_young_index_in_cset();
 121   clear_index_in_opt_cset();
 122   uninstall_surv_rate_group();
 123   set_free();
 124   reset_pre_dummy_top();
 125 
 126   if (!keep_remset) {
 127     if (locked) {
 128       rem_set()->clear_locked();
 129     } else {
 130       rem_set()->clear();
 131     }
 132   }
 133 
 134   zero_marked_bytes();
 135 
 136   init_top_at_mark_start();
 137   if (clear_space) clear(SpaceDecorator::Mangle);
 138 }
 139 
 140 void HeapRegion::clear_cardtable() {
 141   G1CardTable* ct = G1CollectedHeap::heap()->card_table();
 142   ct->clear(MemRegion(bottom(), end()));
 143 }
 144 
 145 void HeapRegion::calc_gc_efficiency() {
 146   // GC efficiency is the ratio of how much space would be
 147   // reclaimed over how long we predict it would take to reclaim it.
 148   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 149   G1Policy* policy = g1h->policy();
 150 
 151   // Retrieve a prediction of the elapsed time for this region for
 152   // a mixed gc because the region will only be evacuated during a
 153   // mixed gc.
 154   double region_elapsed_time_ms =
 155     policy->predict_region_elapsed_time_ms(this, false /* for_young_gc */);
 156   _gc_efficiency = (double) reclaimable_bytes() / region_elapsed_time_ms;
 157 }
 158 
 159 void HeapRegion::set_free() {
 160   report_region_type_change(G1HeapRegionTraceType::Free);
 161   _type.set_free();
 162 }
 163 
 164 void HeapRegion::set_eden() {
 165   report_region_type_change(G1HeapRegionTraceType::Eden);
 166   _type.set_eden();
 167 }
 168 
 169 void HeapRegion::set_eden_pre_gc() {
 170   report_region_type_change(G1HeapRegionTraceType::Eden);
 171   _type.set_eden_pre_gc();
 172 }
 173 
 174 void HeapRegion::set_survivor() {
 175   report_region_type_change(G1HeapRegionTraceType::Survivor);
 176   _type.set_survivor();
 177 }
 178 
 179 void HeapRegion::move_to_old() {
 180   if (_type.relabel_as_old()) {
 181     report_region_type_change(G1HeapRegionTraceType::Old);
 182   }
 183 }
 184 
 185 void HeapRegion::set_old() {
 186   report_region_type_change(G1HeapRegionTraceType::Old);
 187   _type.set_old();
 188 }
 189 
 190 void HeapRegion::set_open_archive() {
 191   report_region_type_change(G1HeapRegionTraceType::OpenArchive);
 192   _type.set_open_archive();
 193 }
 194 
 195 void HeapRegion::set_closed_archive() {
 196   report_region_type_change(G1HeapRegionTraceType::ClosedArchive);
 197   _type.set_closed_archive();
 198 }
 199 
 200 void HeapRegion::set_starts_humongous(HeapWord* obj_top, size_t fill_size) {
 201   assert(!is_humongous(), "sanity / pre-condition");
 202   assert(top() == bottom(), "should be empty");
 203 
 204   report_region_type_change(G1HeapRegionTraceType::StartsHumongous);
 205   _type.set_starts_humongous();
 206   _humongous_start_region = this;
 207 
 208   _bot_part.set_for_starts_humongous(obj_top, fill_size);
 209 }
 210 
 211 void HeapRegion::set_continues_humongous(HeapRegion* first_hr) {
 212   assert(!is_humongous(), "sanity / pre-condition");
 213   assert(top() == bottom(), "should be empty");
 214   assert(first_hr->is_starts_humongous(), "pre-condition");
 215 
 216   report_region_type_change(G1HeapRegionTraceType::ContinuesHumongous);
 217   _type.set_continues_humongous();
 218   _humongous_start_region = first_hr;
 219 
 220   _bot_part.set_object_can_span(true);
 221 }
 222 
 223 void HeapRegion::clear_humongous() {
 224   assert(is_humongous(), "pre-condition");
 225 
 226   assert(capacity() == HeapRegion::GrainBytes, "pre-condition");
 227   _humongous_start_region = NULL;
 228 
 229   _bot_part.set_object_can_span(false);
 230 }
 231 
 232 HeapRegion::HeapRegion(uint hrm_index,
 233                        G1BlockOffsetTable* bot,
 234                        MemRegion mr) :
 235   _bottom(NULL),
 236   _end(NULL),
 237   _top(NULL),
 238   _compaction_top(NULL),
 239   _bot_part(bot, this),
 240   _par_alloc_lock(Mutex::leaf, "HeapRegion par alloc lock", true),
 241   _pre_dummy_top(NULL),
 242   _rem_set(NULL),
 243   _hrm_index(hrm_index),
 244   _type(),
 245   _humongous_start_region(NULL),
 246   _evacuation_failed(false),
 247   _next(NULL), _prev(NULL),
 248 #ifdef ASSERT
 249   _containing_set(NULL),
 250 #endif
 251   _prev_marked_bytes(0), _next_marked_bytes(0), _gc_efficiency(0.0),
 252   _index_in_opt_cset(InvalidCSetIndex), _young_index_in_cset(-1),
 253   _surv_rate_group(NULL), _age_index(-1),
 254   _prev_top_at_mark_start(NULL), _next_top_at_mark_start(NULL),
 255   _recorded_rs_length(0), _predicted_elapsed_time_ms(0)
 256 {
 257   _rem_set = new HeapRegionRemSet(bot, this);
 258 
 259   initialize(mr);
 260 }
 261 
 262 void HeapRegion::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
 263   assert(_rem_set->is_empty(), "Remembered set must be empty");
 264 
 265   assert(Universe::on_page_boundary(mr.start()) && Universe::on_page_boundary(mr.end()),
 266          "invalid space boundaries");
 267 
 268   set_bottom(mr.start());
 269   set_end(mr.end());
 270   if (clear_space) {
 271     clear(mangle_space);
 272   }
 273 
 274   set_top(bottom());
 275   set_compaction_top(bottom());
 276   reset_bot();
 277 
 278   hr_clear(false /*par*/, false /*clear_space*/);
 279 }
 280 
 281 void HeapRegion::report_region_type_change(G1HeapRegionTraceType::Type to) {
 282   HeapRegionTracer::send_region_type_change(_hrm_index,
 283                                             get_trace_type(),
 284                                             to,
 285                                             (uintptr_t)bottom(),
 286                                             used());
 287 }
 288 
 289 void HeapRegion::note_self_forwarding_removal_start(bool during_initial_mark,
 290                                                     bool during_conc_mark) {
 291   // We always recreate the prev marking info and we'll explicitly
 292   // mark all objects we find to be self-forwarded on the prev
 293   // bitmap. So all objects need to be below PTAMS.
 294   _prev_marked_bytes = 0;
 295 
 296   if (during_initial_mark) {
 297     // During initial-mark, we'll also explicitly mark all objects
 298     // we find to be self-forwarded on the next bitmap. So all
 299     // objects need to be below NTAMS.
 300     _next_top_at_mark_start = top();
 301     _next_marked_bytes = 0;
 302   } else if (during_conc_mark) {
 303     // During concurrent mark, all objects in the CSet (including
 304     // the ones we find to be self-forwarded) are implicitly live.
 305     // So all objects need to be above NTAMS.
 306     _next_top_at_mark_start = bottom();
 307     _next_marked_bytes = 0;
 308   }
 309 }
 310 
 311 void HeapRegion::note_self_forwarding_removal_end(size_t marked_bytes) {
 312   assert(marked_bytes <= used(),
 313          "marked: " SIZE_FORMAT " used: " SIZE_FORMAT, marked_bytes, used());
 314   _prev_top_at_mark_start = top();
 315   _prev_marked_bytes = marked_bytes;
 316 }
 317 
 318 // Code roots support
 319 
 320 void HeapRegion::add_strong_code_root(nmethod* nm) {
 321   HeapRegionRemSet* hrrs = rem_set();
 322   hrrs->add_strong_code_root(nm);
 323 }
 324 
 325 void HeapRegion::add_strong_code_root_locked(nmethod* nm) {
 326   assert_locked_or_safepoint(CodeCache_lock);
 327   HeapRegionRemSet* hrrs = rem_set();
 328   hrrs->add_strong_code_root_locked(nm);
 329 }
 330 
 331 void HeapRegion::remove_strong_code_root(nmethod* nm) {
 332   HeapRegionRemSet* hrrs = rem_set();
 333   hrrs->remove_strong_code_root(nm);
 334 }
 335 
 336 void HeapRegion::strong_code_roots_do(CodeBlobClosure* blk) const {
 337   HeapRegionRemSet* hrrs = rem_set();
 338   hrrs->strong_code_roots_do(blk);
 339 }
 340 
 341 class VerifyStrongCodeRootOopClosure: public OopClosure {
 342   const HeapRegion* _hr;
 343   bool _failures;
 344   bool _has_oops_in_region;
 345 
 346   template <class T> void do_oop_work(T* p) {
 347     T heap_oop = RawAccess<>::oop_load(p);
 348     if (!CompressedOops::is_null(heap_oop)) {
 349       oop obj = CompressedOops::decode_not_null(heap_oop);
 350 
 351       // Note: not all the oops embedded in the nmethod are in the
 352       // current region. We only look at those which are.
 353       if (_hr->is_in(obj)) {
 354         // Object is in the region. Check that its less than top
 355         if (_hr->top() <= (HeapWord*)obj) {
 356           // Object is above top
 357           log_error(gc, verify)("Object " PTR_FORMAT " in region " HR_FORMAT " is above top ",
 358                                 p2i(obj), HR_FORMAT_PARAMS(_hr));
 359           _failures = true;
 360           return;
 361         }
 362         // Nmethod has at least one oop in the current region
 363         _has_oops_in_region = true;
 364       }
 365     }
 366   }
 367 
 368 public:
 369   VerifyStrongCodeRootOopClosure(const HeapRegion* hr):
 370     _hr(hr), _failures(false), _has_oops_in_region(false) {}
 371 
 372   void do_oop(narrowOop* p) { do_oop_work(p); }
 373   void do_oop(oop* p)       { do_oop_work(p); }
 374 
 375   bool failures()           { return _failures; }
 376   bool has_oops_in_region() { return _has_oops_in_region; }
 377 };
 378 
 379 class VerifyStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
 380   const HeapRegion* _hr;
 381   bool _failures;
 382 public:
 383   VerifyStrongCodeRootCodeBlobClosure(const HeapRegion* hr) :
 384     _hr(hr), _failures(false) {}
 385 
 386   void do_code_blob(CodeBlob* cb) {
 387     nmethod* nm = (cb == NULL) ? NULL : cb->as_compiled_method()->as_nmethod_or_null();
 388     if (nm != NULL) {
 389       // Verify that the nemthod is live
 390       if (!nm->is_alive()) {
 391         log_error(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has dead nmethod " PTR_FORMAT " in its strong code roots",
 392                               p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 393         _failures = true;
 394       } else {
 395         VerifyStrongCodeRootOopClosure oop_cl(_hr);
 396         nm->oops_do(&oop_cl);
 397         if (!oop_cl.has_oops_in_region()) {
 398           log_error(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has nmethod " PTR_FORMAT " in its strong code roots with no pointers into region",
 399                                 p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 400           _failures = true;
 401         } else if (oop_cl.failures()) {
 402           log_error(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has other failures for nmethod " PTR_FORMAT,
 403                                 p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 404           _failures = true;
 405         }
 406       }
 407     }
 408   }
 409 
 410   bool failures()       { return _failures; }
 411 };
 412 
 413 void HeapRegion::verify_strong_code_roots(VerifyOption vo, bool* failures) const {
 414   if (!G1VerifyHeapRegionCodeRoots) {
 415     // We're not verifying code roots.
 416     return;
 417   }
 418   if (vo == VerifyOption_G1UseFullMarking) {
 419     // Marking verification during a full GC is performed after class
 420     // unloading, code cache unloading, etc so the strong code roots
 421     // attached to each heap region are in an inconsistent state. They won't
 422     // be consistent until the strong code roots are rebuilt after the
 423     // actual GC. Skip verifying the strong code roots in this particular
 424     // time.
 425     assert(VerifyDuringGC, "only way to get here");
 426     return;
 427   }
 428 
 429   HeapRegionRemSet* hrrs = rem_set();
 430   size_t strong_code_roots_length = hrrs->strong_code_roots_list_length();
 431 
 432   // if this region is empty then there should be no entries
 433   // on its strong code root list
 434   if (is_empty()) {
 435     if (strong_code_roots_length > 0) {
 436       log_error(gc, verify)("region " HR_FORMAT " is empty but has " SIZE_FORMAT " code root entries",
 437                             HR_FORMAT_PARAMS(this), strong_code_roots_length);
 438       *failures = true;
 439     }
 440     return;
 441   }
 442 
 443   if (is_continues_humongous()) {
 444     if (strong_code_roots_length > 0) {
 445       log_error(gc, verify)("region " HR_FORMAT " is a continuation of a humongous region but has " SIZE_FORMAT " code root entries",
 446                             HR_FORMAT_PARAMS(this), strong_code_roots_length);
 447       *failures = true;
 448     }
 449     return;
 450   }
 451 
 452   VerifyStrongCodeRootCodeBlobClosure cb_cl(this);
 453   strong_code_roots_do(&cb_cl);
 454 
 455   if (cb_cl.failures()) {
 456     *failures = true;
 457   }
 458 }
 459 
 460 void HeapRegion::print() const { print_on(tty); }
 461 
 462 void HeapRegion::print_on(outputStream* st) const {
 463   st->print("|%4u", this->_hrm_index);
 464   st->print("|" PTR_FORMAT ", " PTR_FORMAT ", " PTR_FORMAT,
 465             p2i(bottom()), p2i(top()), p2i(end()));
 466   st->print("|%3d%%", (int) ((double) used() * 100 / capacity()));
 467   st->print("|%2s", get_short_type_str());
 468   if (in_collection_set()) {
 469     st->print("|CS");
 470   } else {
 471     st->print("|  ");
 472   }
 473   st->print_cr("|TAMS " PTR_FORMAT ", " PTR_FORMAT "| %s ",
 474                p2i(prev_top_at_mark_start()), p2i(next_top_at_mark_start()), rem_set()->get_state_str());
 475 }
 476 
 477 class G1VerificationClosure : public BasicOopIterateClosure {
 478 protected:
 479   G1CollectedHeap* _g1h;
 480   G1CardTable *_ct;
 481   oop _containing_obj;
 482   bool _failures;
 483   int _n_failures;
 484   VerifyOption _vo;
 485 public:
 486   // _vo == UsePrevMarking -> use "prev" marking information,
 487   // _vo == UseNextMarking -> use "next" marking information,
 488   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS.
 489   G1VerificationClosure(G1CollectedHeap* g1h, VerifyOption vo) :
 490     _g1h(g1h), _ct(g1h->card_table()),
 491     _containing_obj(NULL), _failures(false), _n_failures(0), _vo(vo) {
 492   }
 493 
 494   void set_containing_obj(oop obj) {
 495     _containing_obj = obj;
 496   }
 497 
 498   bool failures() { return _failures; }
 499   int n_failures() { return _n_failures; }
 500 
 501   void print_object(outputStream* out, oop obj) {
 502 #ifdef PRODUCT
 503     Klass* k = obj->klass();
 504     const char* class_name = k->external_name();
 505     out->print_cr("class name %s", class_name);
 506 #else // PRODUCT
 507     obj->print_on(out);
 508 #endif // PRODUCT
 509   }
 510 
 511   // This closure provides its own oop verification code.
 512   debug_only(virtual bool should_verify_oops() { return false; })
 513 };
 514 
 515 class VerifyLiveClosure : public G1VerificationClosure {
 516 public:
 517   VerifyLiveClosure(G1CollectedHeap* g1h, VerifyOption vo) : G1VerificationClosure(g1h, vo) {}
 518   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 519   virtual void do_oop(oop* p) { do_oop_work(p); }
 520 
 521   template <class T>
 522   void do_oop_work(T* p) {
 523     assert(_containing_obj != NULL, "Precondition");
 524     assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
 525       "Precondition");
 526     verify_liveness(p);
 527   }
 528 
 529   template <class T>
 530   void verify_liveness(T* p) {
 531     T heap_oop = RawAccess<>::oop_load(p);
 532     Log(gc, verify) log;
 533     if (!CompressedOops::is_null(heap_oop)) {
 534       oop obj = CompressedOops::decode_not_null(heap_oop);
 535       bool failed = false;
 536       if (!_g1h->is_in(obj) || _g1h->is_obj_dead_cond(obj, _vo)) {
 537         MutexLocker x(ParGCRareEvent_lock,
 538           Mutex::_no_safepoint_check_flag);
 539 
 540         if (!_failures) {
 541           log.error("----------");
 542         }
 543         ResourceMark rm;
 544         if (!_g1h->is_in(obj)) {
 545           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 546           log.error("Field " PTR_FORMAT " of live obj " PTR_FORMAT " in region " HR_FORMAT,
 547                     p2i(p), p2i(_containing_obj), HR_FORMAT_PARAMS(from));
 548           LogStream ls(log.error());
 549           print_object(&ls, _containing_obj);
 550           HeapRegion* const to = _g1h->heap_region_containing(obj);
 551           log.error("points to obj " PTR_FORMAT " in region " HR_FORMAT " remset %s",
 552                     p2i(obj), HR_FORMAT_PARAMS(to), to->rem_set()->get_state_str());
 553         } else {
 554           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 555           HeapRegion* to = _g1h->heap_region_containing((HeapWord*)obj);
 556           log.error("Field " PTR_FORMAT " of live obj " PTR_FORMAT " in region " HR_FORMAT,
 557                     p2i(p), p2i(_containing_obj), HR_FORMAT_PARAMS(from));
 558           LogStream ls(log.error());
 559           print_object(&ls, _containing_obj);
 560           log.error("points to dead obj " PTR_FORMAT " in region " HR_FORMAT,
 561                     p2i(obj), HR_FORMAT_PARAMS(to));
 562           print_object(&ls, obj);
 563         }
 564         log.error("----------");
 565         _failures = true;
 566         failed = true;
 567         _n_failures++;
 568       }
 569     }
 570   }
 571 };
 572 
 573 class VerifyRemSetClosure : public G1VerificationClosure {
 574 public:
 575   VerifyRemSetClosure(G1CollectedHeap* g1h, VerifyOption vo) : G1VerificationClosure(g1h, vo) {}
 576   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 577   virtual void do_oop(oop* p) { do_oop_work(p); }
 578 
 579   template <class T>
 580   void do_oop_work(T* p) {
 581     assert(_containing_obj != NULL, "Precondition");
 582     assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
 583       "Precondition");
 584     verify_remembered_set(p);
 585   }
 586 
 587   template <class T>
 588   void verify_remembered_set(T* p) {
 589     T heap_oop = RawAccess<>::oop_load(p);
 590     Log(gc, verify) log;
 591     if (!CompressedOops::is_null(heap_oop)) {
 592       oop obj = CompressedOops::decode_not_null(heap_oop);
 593       HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 594       HeapRegion* to = _g1h->heap_region_containing(obj);
 595       if (from != NULL && to != NULL &&
 596         from != to &&
 597         !to->is_pinned() &&
 598         to->rem_set()->is_complete()) {
 599         jbyte cv_obj = *_ct->byte_for_const(_containing_obj);
 600         jbyte cv_field = *_ct->byte_for_const(p);
 601         const jbyte dirty = G1CardTable::dirty_card_val();
 602 
 603         bool is_bad = !(from->is_young()
 604           || to->rem_set()->contains_reference(p)
 605           || (_containing_obj->is_objArray() ?
 606                 cv_field == dirty :
 607                 cv_obj == dirty || cv_field == dirty));
 608         if (is_bad) {
 609           MutexLocker x(ParGCRareEvent_lock,
 610             Mutex::_no_safepoint_check_flag);
 611 
 612           if (!_failures) {
 613             log.error("----------");
 614           }
 615           log.error("Missing rem set entry:");
 616           log.error("Field " PTR_FORMAT " of obj " PTR_FORMAT " in region " HR_FORMAT,
 617                     p2i(p), p2i(_containing_obj), HR_FORMAT_PARAMS(from));
 618           ResourceMark rm;
 619           LogStream ls(log.error());
 620           _containing_obj->print_on(&ls);
 621           log.error("points to obj " PTR_FORMAT " in region " HR_FORMAT " remset %s",
 622                     p2i(obj), HR_FORMAT_PARAMS(to), to->rem_set()->get_state_str());
 623           if (oopDesc::is_oop(obj)) {
 624             obj->print_on(&ls);
 625           }
 626           log.error("Obj head CTE = %d, field CTE = %d.", cv_obj, cv_field);
 627           log.error("----------");
 628           _failures = true;
 629           _n_failures++;
 630         }
 631       }
 632     }
 633   }
 634 };
 635 
 636 // Closure that applies the given two closures in sequence.
 637 class G1Mux2Closure : public BasicOopIterateClosure {
 638   OopClosure* _c1;
 639   OopClosure* _c2;
 640 public:
 641   G1Mux2Closure(OopClosure *c1, OopClosure *c2) { _c1 = c1; _c2 = c2; }
 642   template <class T> inline void do_oop_work(T* p) {
 643     // Apply first closure; then apply the second.
 644     _c1->do_oop(p);
 645     _c2->do_oop(p);
 646   }
 647   virtual inline void do_oop(oop* p) { do_oop_work(p); }
 648   virtual inline void do_oop(narrowOop* p) { do_oop_work(p); }
 649 
 650   // This closure provides its own oop verification code.
 651   debug_only(virtual bool should_verify_oops() { return false; })
 652 };
 653 
 654 void HeapRegion::verify(VerifyOption vo,
 655                         bool* failures) const {
 656   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 657   *failures = false;
 658   HeapWord* p = bottom();
 659   HeapWord* prev_p = NULL;
 660   VerifyLiveClosure vl_cl(g1h, vo);
 661   VerifyRemSetClosure vr_cl(g1h, vo);
 662   bool is_region_humongous = is_humongous();
 663   size_t object_num = 0;
 664   while (p < top()) {
 665     oop obj = oop(p);
 666     size_t obj_size = block_size(p);
 667     object_num += 1;
 668 
 669     if (!g1h->is_obj_dead_cond(obj, this, vo)) {
 670       if (oopDesc::is_oop(obj)) {
 671         Klass* klass = obj->klass();
 672         bool is_metaspace_object = Metaspace::contains(klass);
 673         if (!is_metaspace_object) {
 674           log_error(gc, verify)("klass " PTR_FORMAT " of object " PTR_FORMAT " "
 675                                 "not metadata", p2i(klass), p2i(obj));
 676           *failures = true;
 677           return;
 678         } else if (!klass->is_klass()) {
 679           log_error(gc, verify)("klass " PTR_FORMAT " of object " PTR_FORMAT " "
 680                                 "not a klass", p2i(klass), p2i(obj));
 681           *failures = true;
 682           return;
 683         } else {
 684           vl_cl.set_containing_obj(obj);
 685           if (!g1h->collector_state()->in_full_gc() || G1VerifyRSetsDuringFullGC) {
 686             // verify liveness and rem_set
 687             vr_cl.set_containing_obj(obj);
 688             G1Mux2Closure mux(&vl_cl, &vr_cl);
 689             obj->oop_iterate(&mux);
 690 
 691             if (vr_cl.failures()) {
 692               *failures = true;
 693             }
 694             if (G1MaxVerifyFailures >= 0 &&
 695               vr_cl.n_failures() >= G1MaxVerifyFailures) {
 696               return;
 697             }
 698           } else {
 699             // verify only liveness
 700             obj->oop_iterate(&vl_cl);
 701           }
 702           if (vl_cl.failures()) {
 703             *failures = true;
 704           }
 705           if (G1MaxVerifyFailures >= 0 &&
 706               vl_cl.n_failures() >= G1MaxVerifyFailures) {
 707             return;
 708           }
 709         }
 710       } else {
 711         log_error(gc, verify)(PTR_FORMAT " not an oop", p2i(obj));
 712         *failures = true;
 713         return;
 714       }
 715     }
 716     prev_p = p;
 717     p += obj_size;
 718   }
 719 
 720   if (!is_young() && !is_empty()) {
 721     _bot_part.verify();
 722   }
 723 
 724   if (is_region_humongous) {
 725     oop obj = oop(this->humongous_start_region()->bottom());
 726     if ((HeapWord*)obj > bottom() || (HeapWord*)obj + obj->size() < bottom()) {
 727       log_error(gc, verify)("this humongous region is not part of its' humongous object " PTR_FORMAT, p2i(obj));
 728       *failures = true;
 729       return;
 730     }
 731   }
 732 
 733   if (!is_region_humongous && p != top()) {
 734     log_error(gc, verify)("end of last object " PTR_FORMAT " "
 735                           "does not match top " PTR_FORMAT, p2i(p), p2i(top()));
 736     *failures = true;
 737     return;
 738   }
 739 
 740   HeapWord* the_end = end();
 741   // Do some extra BOT consistency checking for addresses in the
 742   // range [top, end). BOT look-ups in this range should yield
 743   // top. No point in doing that if top == end (there's nothing there).
 744   if (p < the_end) {
 745     // Look up top
 746     HeapWord* addr_1 = p;
 747     HeapWord* b_start_1 = _bot_part.block_start_const(addr_1);
 748     if (b_start_1 != p) {
 749       log_error(gc, verify)("BOT look up for top: " PTR_FORMAT " "
 750                             " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 751                             p2i(addr_1), p2i(b_start_1), p2i(p));
 752       *failures = true;
 753       return;
 754     }
 755 
 756     // Look up top + 1
 757     HeapWord* addr_2 = p + 1;
 758     if (addr_2 < the_end) {
 759       HeapWord* b_start_2 = _bot_part.block_start_const(addr_2);
 760       if (b_start_2 != p) {
 761         log_error(gc, verify)("BOT look up for top + 1: " PTR_FORMAT " "
 762                               " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 763                               p2i(addr_2), p2i(b_start_2), p2i(p));
 764         *failures = true;
 765         return;
 766       }
 767     }
 768 
 769     // Look up an address between top and end
 770     size_t diff = pointer_delta(the_end, p) / 2;
 771     HeapWord* addr_3 = p + diff;
 772     if (addr_3 < the_end) {
 773       HeapWord* b_start_3 = _bot_part.block_start_const(addr_3);
 774       if (b_start_3 != p) {
 775         log_error(gc, verify)("BOT look up for top + diff: " PTR_FORMAT " "
 776                               " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 777                               p2i(addr_3), p2i(b_start_3), p2i(p));
 778         *failures = true;
 779         return;
 780       }
 781     }
 782 
 783     // Look up end - 1
 784     HeapWord* addr_4 = the_end - 1;
 785     HeapWord* b_start_4 = _bot_part.block_start_const(addr_4);
 786     if (b_start_4 != p) {
 787       log_error(gc, verify)("BOT look up for end - 1: " PTR_FORMAT " "
 788                             " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 789                             p2i(addr_4), p2i(b_start_4), p2i(p));
 790       *failures = true;
 791       return;
 792     }
 793   }
 794 
 795   verify_strong_code_roots(vo, failures);
 796 }
 797 
 798 void HeapRegion::verify() const {
 799   bool dummy = false;
 800   verify(VerifyOption_G1UsePrevMarking, /* failures */ &dummy);
 801 }
 802 
 803 void HeapRegion::verify_rem_set(VerifyOption vo, bool* failures) const {
 804   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 805   *failures = false;
 806   HeapWord* p = bottom();
 807   HeapWord* prev_p = NULL;
 808   VerifyRemSetClosure vr_cl(g1h, vo);
 809   while (p < top()) {
 810     oop obj = oop(p);
 811     size_t obj_size = block_size(p);
 812 
 813     if (!g1h->is_obj_dead_cond(obj, this, vo)) {
 814       if (oopDesc::is_oop(obj)) {
 815         vr_cl.set_containing_obj(obj);
 816         obj->oop_iterate(&vr_cl);
 817 
 818         if (vr_cl.failures()) {
 819           *failures = true;
 820         }
 821         if (G1MaxVerifyFailures >= 0 &&
 822           vr_cl.n_failures() >= G1MaxVerifyFailures) {
 823           return;
 824         }
 825       } else {
 826         log_error(gc, verify)(PTR_FORMAT " not an oop", p2i(obj));
 827         *failures = true;
 828         return;
 829       }
 830     }
 831 
 832     prev_p = p;
 833     p += obj_size;
 834   }
 835 }
 836 
 837 void HeapRegion::verify_rem_set() const {
 838   bool failures = false;
 839   verify_rem_set(VerifyOption_G1UsePrevMarking, &failures);
 840   guarantee(!failures, "HeapRegion RemSet verification failed");
 841 }
 842 
 843 void HeapRegion::clear(bool mangle_space) {
 844   set_top(bottom());
 845   set_compaction_top(bottom());
 846 
 847   if (ZapUnusedHeapArea && mangle_space) {
 848     mangle_unused_area();
 849   }
 850   reset_bot();
 851 }
 852 
 853 #ifndef PRODUCT
 854 void HeapRegion::mangle_unused_area() {
 855   SpaceMangler::mangle_region(MemRegion(top(), end()));
 856 }
 857 #endif
 858 
 859 HeapWord* HeapRegion::initialize_threshold() {
 860   return _bot_part.initialize_threshold();
 861 }
 862 
 863 HeapWord* HeapRegion::cross_threshold(HeapWord* start, HeapWord* end) {
 864   _bot_part.alloc_block(start, end);
 865   return _bot_part.threshold();
 866 }
 867 
 868 void HeapRegion::object_iterate(ObjectClosure* blk) {
 869   HeapWord* p = bottom();
 870   while (p < top()) {
 871     if (block_is_obj(p)) {
 872       blk->do_object(oop(p));
 873     }
 874     p += block_size(p);
 875   }
 876 }