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