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