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