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