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