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