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