1 /*
   2  * Copyright (c) 2001, 2015, 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_implementation/g1/g1BlockOffsetTable.inline.hpp"
  28 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  29 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
  30 #include "gc_implementation/g1/heapRegion.inline.hpp"
  31 #include "gc_implementation/g1/heapRegionBounds.inline.hpp"
  32 #include "gc_implementation/g1/heapRegionRemSet.hpp"
  33 #include "gc_implementation/g1/heapRegionManager.inline.hpp"
  34 #include "gc_implementation/shared/liveRange.hpp"
  35 #include "memory/genOopClosures.inline.hpp"
  36 #include "memory/iterator.hpp"
  37 #include "memory/space.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "runtime/atomic.inline.hpp"
  40 #include "runtime/orderAccess.inline.hpp"
  41 
  42 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  43 
  44 int    HeapRegion::LogOfHRGrainBytes = 0;
  45 int    HeapRegion::LogOfHRGrainWords = 0;
  46 size_t HeapRegion::GrainBytes        = 0;
  47 size_t HeapRegion::GrainWords        = 0;
  48 size_t HeapRegion::CardsPerRegion    = 0;
  49 
  50 HeapRegionDCTOC::HeapRegionDCTOC(G1CollectedHeap* g1,
  51                                  HeapRegion* hr,
  52                                  G1ParPushHeapRSClosure* cl,
  53                                  CardTableModRefBS::PrecisionStyle precision) :
  54   DirtyCardToOopClosure(hr, cl, precision, NULL),
  55   _hr(hr), _rs_scan(cl), _g1(g1) { }
  56 
  57 FilterOutOfRegionClosure::FilterOutOfRegionClosure(HeapRegion* r,
  58                                                    OopClosure* oc) :
  59   _r_bottom(r->bottom()), _r_end(r->end()), _oc(oc) { }
  60 
  61 void HeapRegionDCTOC::walk_mem_region(MemRegion mr,
  62                                       HeapWord* bottom,
  63                                       HeapWord* top) {
  64   G1CollectedHeap* g1h = _g1;
  65   size_t oop_size;
  66   HeapWord* cur = bottom;
  67 
  68   // Start filtering what we add to the remembered set. If the object is
  69   // not considered dead, either because it is marked (in the mark bitmap)
  70   // or it was allocated after marking finished, then we add it. Otherwise
  71   // we can safely ignore the object.
  72   if (!g1h->is_obj_dead(oop(cur), _hr)) {
  73     oop_size = oop(cur)->oop_iterate(_rs_scan, mr);
  74   } else {
  75     oop_size = _hr->block_size(cur);
  76   }
  77 
  78   cur += oop_size;
  79 
  80   if (cur < top) {
  81     oop cur_oop = oop(cur);
  82     oop_size = _hr->block_size(cur);
  83     HeapWord* next_obj = cur + oop_size;
  84     while (next_obj < top) {
  85       // Keep filtering the remembered set.
  86       if (!g1h->is_obj_dead(cur_oop, _hr)) {
  87         // Bottom lies entirely below top, so we can call the
  88         // non-memRegion version of oop_iterate below.
  89         cur_oop->oop_iterate(_rs_scan);
  90       }
  91       cur = next_obj;
  92       cur_oop = oop(cur);
  93       oop_size = _hr->block_size(cur);
  94       next_obj = cur + oop_size;
  95     }
  96 
  97     // Last object. Need to do dead-obj filtering here too.
  98     if (!g1h->is_obj_dead(oop(cur), _hr)) {
  99       oop(cur)->oop_iterate(_rs_scan, mr);
 100     }
 101   }
 102 }
 103 
 104 size_t HeapRegion::max_region_size() {
 105   return HeapRegionBounds::max_size();
 106 }
 107 
 108 void HeapRegion::setup_heap_region_size(size_t initial_heap_size, size_t max_heap_size) {
 109   uintx region_size = G1HeapRegionSize;
 110   if (FLAG_IS_DEFAULT(G1HeapRegionSize)) {
 111     size_t average_heap_size = (initial_heap_size + max_heap_size) / 2;
 112     region_size = MAX2(average_heap_size / HeapRegionBounds::target_number(),
 113                        (uintx) HeapRegionBounds::min_size());
 114   }
 115 
 116   int region_size_log = log2_long((jlong) region_size);
 117   // Recalculate the region size to make sure it's a power of
 118   // 2. This means that region_size is the largest power of 2 that's
 119   // <= what we've calculated so far.
 120   region_size = ((uintx)1 << region_size_log);
 121 
 122   // Now make sure that we don't go over or under our limits.
 123   if (region_size < HeapRegionBounds::min_size()) {
 124     region_size = HeapRegionBounds::min_size();
 125   } else if (region_size > HeapRegionBounds::max_size()) {
 126     region_size = HeapRegionBounds::max_size();
 127   }
 128 
 129   // And recalculate the log.
 130   region_size_log = log2_long((jlong) region_size);
 131 
 132   // Now, set up the globals.
 133   guarantee(LogOfHRGrainBytes == 0, "we should only set it once");
 134   LogOfHRGrainBytes = region_size_log;
 135 
 136   guarantee(LogOfHRGrainWords == 0, "we should only set it once");
 137   LogOfHRGrainWords = LogOfHRGrainBytes - LogHeapWordSize;
 138 
 139   guarantee(GrainBytes == 0, "we should only set it once");
 140   // The cast to int is safe, given that we've bounded region_size by
 141   // MIN_REGION_SIZE and MAX_REGION_SIZE.
 142   GrainBytes = (size_t)region_size;
 143 
 144   guarantee(GrainWords == 0, "we should only set it once");
 145   GrainWords = GrainBytes >> LogHeapWordSize;
 146   guarantee((size_t) 1 << LogOfHRGrainWords == GrainWords, "sanity");
 147 
 148   guarantee(CardsPerRegion == 0, "we should only set it once");
 149   CardsPerRegion = GrainBytes >> CardTableModRefBS::card_shift;
 150 }
 151 
 152 void HeapRegion::reset_after_compaction() {
 153   G1OffsetTableContigSpace::reset_after_compaction();
 154   // After a compaction the mark bitmap is invalid, so we must
 155   // treat all objects as being inside the unmarked area.
 156   zero_marked_bytes();
 157   init_top_at_mark_start();
 158 }
 159 
 160 void HeapRegion::hr_clear(bool par, bool clear_space, bool locked) {
 161   assert(_humongous_start_region == NULL,
 162          "we should have already filtered out humongous regions");
 163   assert(_end == orig_end(),
 164          "we should have already filtered out humongous regions");
 165   assert(!in_collection_set(),
 166          err_msg("Should not clear heap region %u in the collection set", hrm_index()));
 167 
 168   set_allocation_context(AllocationContext::system());
 169   set_young_index_in_cset(-1);
 170   uninstall_surv_rate_group();
 171   set_free();
 172   reset_pre_dummy_top();
 173 
 174   if (!par) {
 175     // If this is parallel, this will be done later.
 176     HeapRegionRemSet* hrrs = rem_set();
 177     if (locked) {
 178       hrrs->clear_locked();
 179     } else {
 180       hrrs->clear();
 181     }
 182   }
 183   zero_marked_bytes();
 184 
 185   _offsets.resize(HeapRegion::GrainWords);
 186   init_top_at_mark_start();
 187   if (clear_space) clear(SpaceDecorator::Mangle);
 188 }
 189 
 190 void HeapRegion::par_clear() {
 191   assert(used() == 0, "the region should have been already cleared");
 192   assert(capacity() == HeapRegion::GrainBytes, "should be back to normal");
 193   HeapRegionRemSet* hrrs = rem_set();
 194   hrrs->clear();
 195   CardTableModRefBS* ct_bs =
 196     barrier_set_cast<CardTableModRefBS>(G1CollectedHeap::heap()->barrier_set());
 197   ct_bs->clear(MemRegion(bottom(), end()));
 198 }
 199 
 200 void HeapRegion::calc_gc_efficiency() {
 201   // GC efficiency is the ratio of how much space would be
 202   // reclaimed over how long we predict it would take to reclaim it.
 203   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 204   G1CollectorPolicy* g1p = g1h->g1_policy();
 205 
 206   // Retrieve a prediction of the elapsed time for this region for
 207   // a mixed gc because the region will only be evacuated during a
 208   // mixed gc.
 209   double region_elapsed_time_ms =
 210     g1p->predict_region_elapsed_time_ms(this, false /* for_young_gc */);
 211   _gc_efficiency = (double) reclaimable_bytes() / region_elapsed_time_ms;
 212 }
 213 
 214 void HeapRegion::set_starts_humongous(HeapWord* new_top, HeapWord* new_end) {
 215   assert(!is_humongous(), "sanity / pre-condition");
 216   assert(end() == orig_end(),
 217          "Should be normal before the humongous object allocation");
 218   assert(top() == bottom(), "should be empty");
 219   assert(bottom() <= new_top && new_top <= new_end, "pre-condition");
 220 
 221   _type.set_starts_humongous();
 222   _humongous_start_region = this;
 223 
 224   set_end(new_end);
 225   _offsets.set_for_starts_humongous(new_top);
 226 }
 227 
 228 void HeapRegion::set_continues_humongous(HeapRegion* first_hr) {
 229   assert(!is_humongous(), "sanity / pre-condition");
 230   assert(end() == orig_end(),
 231          "Should be normal before the humongous object allocation");
 232   assert(top() == bottom(), "should be empty");
 233   assert(first_hr->is_starts_humongous(), "pre-condition");
 234 
 235   _type.set_continues_humongous();
 236   _humongous_start_region = first_hr;
 237 }
 238 
 239 void HeapRegion::clear_humongous() {
 240   assert(is_humongous(), "pre-condition");
 241 
 242   if (is_starts_humongous()) {
 243     assert(top() <= end(), "pre-condition");
 244     set_end(orig_end());
 245     if (top() > end()) {
 246       // at least one "continues humongous" region after it
 247       set_top(end());
 248     }
 249   } else {
 250     // continues humongous
 251     assert(end() == orig_end(), "sanity");
 252   }
 253 
 254   assert(capacity() == HeapRegion::GrainBytes, "pre-condition");
 255   _humongous_start_region = NULL;
 256 }
 257 
 258 HeapRegion::HeapRegion(uint hrm_index,
 259                        G1BlockOffsetSharedArray* sharedOffsetArray,
 260                        MemRegion mr) :
 261     G1OffsetTableContigSpace(sharedOffsetArray, mr),
 262     _hrm_index(hrm_index),
 263     _allocation_context(AllocationContext::system()),
 264     _humongous_start_region(NULL),
 265     _next_in_special_set(NULL),
 266     _evacuation_failed(false),
 267     _prev_marked_bytes(0), _next_marked_bytes(0), _gc_efficiency(0.0),
 268     _next_young_region(NULL),
 269     _next_dirty_cards_region(NULL), _next(NULL), _prev(NULL),
 270 #ifdef ASSERT
 271     _containing_set(NULL),
 272 #endif // ASSERT
 273      _young_index_in_cset(-1), _surv_rate_group(NULL), _age_index(-1),
 274     _rem_set(NULL), _recorded_rs_length(0), _predicted_elapsed_time_ms(0),
 275     _predicted_bytes_to_copy(0)
 276 {
 277   _rem_set = new HeapRegionRemSet(sharedOffsetArray, this);
 278   assert(HeapRegionRemSet::num_par_rem_sets() > 0, "Invariant.");
 279 
 280   initialize(mr);
 281 }
 282 
 283 void HeapRegion::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
 284   assert(_rem_set->is_empty(), "Remembered set must be empty");
 285 
 286   G1OffsetTableContigSpace::initialize(mr, clear_space, mangle_space);
 287 
 288   hr_clear(false /*par*/, false /*clear_space*/);
 289   set_top(bottom());
 290   record_timestamp();
 291 
 292   assert(mr.end() == orig_end(),
 293          err_msg("Given region end address " PTR_FORMAT " should match exactly "
 294                  "bottom plus one region size, i.e. " PTR_FORMAT,
 295                  p2i(mr.end()), p2i(orig_end())));
 296 }
 297 
 298 CompactibleSpace* HeapRegion::next_compaction_space() const {
 299   return G1CollectedHeap::heap()->next_compaction_region(this);
 300 }
 301 
 302 void HeapRegion::note_self_forwarding_removal_start(bool during_initial_mark,
 303                                                     bool during_conc_mark) {
 304   // We always recreate the prev marking info and we'll explicitly
 305   // mark all objects we find to be self-forwarded on the prev
 306   // bitmap. So all objects need to be below PTAMS.
 307   _prev_marked_bytes = 0;
 308 
 309   if (during_initial_mark) {
 310     // During initial-mark, we'll also explicitly mark all objects
 311     // we find to be self-forwarded on the next bitmap. So all
 312     // objects need to be below NTAMS.
 313     _next_top_at_mark_start = top();
 314     _next_marked_bytes = 0;
 315   } else if (during_conc_mark) {
 316     // During concurrent mark, all objects in the CSet (including
 317     // the ones we find to be self-forwarded) are implicitly live.
 318     // So all objects need to be above NTAMS.
 319     _next_top_at_mark_start = bottom();
 320     _next_marked_bytes = 0;
 321   }
 322 }
 323 
 324 void HeapRegion::note_self_forwarding_removal_end(bool during_initial_mark,
 325                                                   bool during_conc_mark,
 326                                                   size_t marked_bytes) {
 327   assert(0 <= marked_bytes && marked_bytes <= used(),
 328          err_msg("marked: "SIZE_FORMAT" used: "SIZE_FORMAT,
 329                  marked_bytes, used()));
 330   _prev_top_at_mark_start = top();
 331   _prev_marked_bytes = marked_bytes;
 332 }
 333 
 334 HeapWord*
 335 HeapRegion::object_iterate_mem_careful(MemRegion mr,
 336                                                  ObjectClosure* cl) {
 337   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 338   // We used to use "block_start_careful" here.  But we're actually happy
 339   // to update the BOT while we do this...
 340   HeapWord* cur = block_start(mr.start());
 341   mr = mr.intersection(used_region());
 342   if (mr.is_empty()) return NULL;
 343   // Otherwise, find the obj that extends onto mr.start().
 344 
 345   assert(cur <= mr.start()
 346          && (oop(cur)->klass_or_null() == NULL ||
 347              cur + oop(cur)->size() > mr.start()),
 348          "postcondition of block_start");
 349   oop obj;
 350   while (cur < mr.end()) {
 351     obj = oop(cur);
 352     if (obj->klass_or_null() == NULL) {
 353       // Ran into an unparseable point.
 354       return cur;
 355     } else if (!g1h->is_obj_dead(obj)) {
 356       cl->do_object(obj);
 357     }
 358     cur += block_size(cur);
 359   }
 360   return NULL;
 361 }
 362 
 363 HeapWord*
 364 HeapRegion::
 365 oops_on_card_seq_iterate_careful(MemRegion mr,
 366                                  FilterOutOfRegionClosure* cl,
 367                                  bool filter_young,
 368                                  jbyte* card_ptr) {
 369   // Currently, we should only have to clean the card if filter_young
 370   // is true and vice versa.
 371   if (filter_young) {
 372     assert(card_ptr != NULL, "pre-condition");
 373   } else {
 374     assert(card_ptr == NULL, "pre-condition");
 375   }
 376   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 377 
 378   // If we're within a stop-world GC, then we might look at a card in a
 379   // GC alloc region that extends onto a GC LAB, which may not be
 380   // parseable.  Stop such at the "scan_top" of the region.
 381   if (g1h->is_gc_active()) {
 382     mr = mr.intersection(MemRegion(bottom(), scan_top()));
 383   } else {
 384     mr = mr.intersection(used_region());
 385   }
 386   if (mr.is_empty()) return NULL;
 387   // Otherwise, find the obj that extends onto mr.start().
 388 
 389   // The intersection of the incoming mr (for the card) and the
 390   // allocated part of the region is non-empty. This implies that
 391   // we have actually allocated into this region. The code in
 392   // G1CollectedHeap.cpp that allocates a new region sets the
 393   // is_young tag on the region before allocating. Thus we
 394   // safely know if this region is young.
 395   if (is_young() && filter_young) {
 396     return NULL;
 397   }
 398 
 399   assert(!is_young(), "check value of filter_young");
 400 
 401   // We can only clean the card here, after we make the decision that
 402   // the card is not young. And we only clean the card if we have been
 403   // asked to (i.e., card_ptr != NULL).
 404   if (card_ptr != NULL) {
 405     *card_ptr = CardTableModRefBS::clean_card_val();
 406     // We must complete this write before we do any of the reads below.
 407     OrderAccess::storeload();
 408   }
 409 
 410   // Cache the boundaries of the memory region in some const locals
 411   HeapWord* const start = mr.start();
 412   HeapWord* const end = mr.end();
 413 
 414   // We used to use "block_start_careful" here.  But we're actually happy
 415   // to update the BOT while we do this...
 416   HeapWord* cur = block_start(start);
 417   assert(cur <= start, "Postcondition");
 418 
 419   oop obj;
 420 
 421   HeapWord* next = cur;
 422   do {
 423     cur = next;
 424     obj = oop(cur);
 425     if (obj->klass_or_null() == NULL) {
 426       // Ran into an unparseable point.
 427       return cur;
 428     }
 429     // Otherwise...
 430     next = cur + block_size(cur);
 431   } while (next <= start);
 432 
 433   // If we finish the above loop...We have a parseable object that
 434   // begins on or before the start of the memory region, and ends
 435   // inside or spans the entire region.
 436   assert(cur <= start, "Loop postcondition");
 437   assert(obj->klass_or_null() != NULL, "Loop postcondition");
 438 
 439   do {
 440     obj = oop(cur);
 441     assert((cur + block_size(cur)) > (HeapWord*)obj, "Loop invariant");
 442     if (obj->klass_or_null() == NULL) {
 443       // Ran into an unparseable point.
 444       return cur;
 445     }
 446 
 447     // Advance the current pointer. "obj" still points to the object to iterate.
 448     cur = cur + block_size(cur);
 449 
 450     if (!g1h->is_obj_dead(obj)) {
 451       // Non-objArrays are sometimes marked imprecise at the object start. We
 452       // always need to iterate over them in full.
 453       // We only iterate over object arrays in full if they are completely contained
 454       // in the memory region.
 455       if (!obj->is_objArray() || (((HeapWord*)obj) >= start && cur <= end)) {
 456         obj->oop_iterate(cl);
 457       } else {
 458         obj->oop_iterate(cl, mr);
 459       }
 460     }
 461   } while (cur < end);
 462 
 463   return NULL;
 464 }
 465 
 466 // Code roots support
 467 
 468 void HeapRegion::add_strong_code_root(nmethod* nm) {
 469   HeapRegionRemSet* hrrs = rem_set();
 470   hrrs->add_strong_code_root(nm);
 471 }
 472 
 473 void HeapRegion::add_strong_code_root_locked(nmethod* nm) {
 474   assert_locked_or_safepoint(CodeCache_lock);
 475   HeapRegionRemSet* hrrs = rem_set();
 476   hrrs->add_strong_code_root_locked(nm);
 477 }
 478 
 479 void HeapRegion::remove_strong_code_root(nmethod* nm) {
 480   HeapRegionRemSet* hrrs = rem_set();
 481   hrrs->remove_strong_code_root(nm);
 482 }
 483 
 484 void HeapRegion::strong_code_roots_do(CodeBlobClosure* blk) const {
 485   HeapRegionRemSet* hrrs = rem_set();
 486   hrrs->strong_code_roots_do(blk);
 487 }
 488 
 489 class VerifyStrongCodeRootOopClosure: public OopClosure {
 490   const HeapRegion* _hr;
 491   nmethod* _nm;
 492   bool _failures;
 493   bool _has_oops_in_region;
 494 
 495   template <class T> void do_oop_work(T* p) {
 496     T heap_oop = oopDesc::load_heap_oop(p);
 497     if (!oopDesc::is_null(heap_oop)) {
 498       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 499 
 500       // Note: not all the oops embedded in the nmethod are in the
 501       // current region. We only look at those which are.
 502       if (_hr->is_in(obj)) {
 503         // Object is in the region. Check that its less than top
 504         if (_hr->top() <= (HeapWord*)obj) {
 505           // Object is above top
 506           gclog_or_tty->print_cr("Object "PTR_FORMAT" in region "
 507                                  "["PTR_FORMAT", "PTR_FORMAT") is above "
 508                                  "top "PTR_FORMAT,
 509                                  (void *)obj, _hr->bottom(), _hr->end(), _hr->top());
 510           _failures = true;
 511           return;
 512         }
 513         // Nmethod has at least one oop in the current region
 514         _has_oops_in_region = true;
 515       }
 516     }
 517   }
 518 
 519 public:
 520   VerifyStrongCodeRootOopClosure(const HeapRegion* hr, nmethod* nm):
 521     _hr(hr), _failures(false), _has_oops_in_region(false) {}
 522 
 523   void do_oop(narrowOop* p) { do_oop_work(p); }
 524   void do_oop(oop* p)       { do_oop_work(p); }
 525 
 526   bool failures()           { return _failures; }
 527   bool has_oops_in_region() { return _has_oops_in_region; }
 528 };
 529 
 530 class VerifyStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
 531   const HeapRegion* _hr;
 532   bool _failures;
 533 public:
 534   VerifyStrongCodeRootCodeBlobClosure(const HeapRegion* hr) :
 535     _hr(hr), _failures(false) {}
 536 
 537   void do_code_blob(CodeBlob* cb) {
 538     nmethod* nm = (cb == NULL) ? NULL : cb->as_nmethod_or_null();
 539     if (nm != NULL) {
 540       // Verify that the nemthod is live
 541       if (!nm->is_alive()) {
 542         gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] has dead nmethod "
 543                                PTR_FORMAT" in its strong code roots",
 544                                _hr->bottom(), _hr->end(), nm);
 545         _failures = true;
 546       } else {
 547         VerifyStrongCodeRootOopClosure oop_cl(_hr, nm);
 548         nm->oops_do(&oop_cl);
 549         if (!oop_cl.has_oops_in_region()) {
 550           gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] has nmethod "
 551                                  PTR_FORMAT" in its strong code roots "
 552                                  "with no pointers into region",
 553                                  _hr->bottom(), _hr->end(), nm);
 554           _failures = true;
 555         } else if (oop_cl.failures()) {
 556           gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] has other "
 557                                  "failures for nmethod "PTR_FORMAT,
 558                                  _hr->bottom(), _hr->end(), nm);
 559           _failures = true;
 560         }
 561       }
 562     }
 563   }
 564 
 565   bool failures()       { return _failures; }
 566 };
 567 
 568 void HeapRegion::verify_strong_code_roots(VerifyOption vo, bool* failures) const {
 569   if (!G1VerifyHeapRegionCodeRoots) {
 570     // We're not verifying code roots.
 571     return;
 572   }
 573   if (vo == VerifyOption_G1UseMarkWord) {
 574     // Marking verification during a full GC is performed after class
 575     // unloading, code cache unloading, etc so the strong code roots
 576     // attached to each heap region are in an inconsistent state. They won't
 577     // be consistent until the strong code roots are rebuilt after the
 578     // actual GC. Skip verifying the strong code roots in this particular
 579     // time.
 580     assert(VerifyDuringGC, "only way to get here");
 581     return;
 582   }
 583 
 584   HeapRegionRemSet* hrrs = rem_set();
 585   size_t strong_code_roots_length = hrrs->strong_code_roots_list_length();
 586 
 587   // if this region is empty then there should be no entries
 588   // on its strong code root list
 589   if (is_empty()) {
 590     if (strong_code_roots_length > 0) {
 591       gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] is empty "
 592                              "but has "SIZE_FORMAT" code root entries",
 593                              bottom(), end(), strong_code_roots_length);
 594       *failures = true;
 595     }
 596     return;
 597   }
 598 
 599   if (is_continues_humongous()) {
 600     if (strong_code_roots_length > 0) {
 601       gclog_or_tty->print_cr("region "HR_FORMAT" is a continuation of a humongous "
 602                              "region but has "SIZE_FORMAT" code root entries",
 603                              HR_FORMAT_PARAMS(this), strong_code_roots_length);
 604       *failures = true;
 605     }
 606     return;
 607   }
 608 
 609   VerifyStrongCodeRootCodeBlobClosure cb_cl(this);
 610   strong_code_roots_do(&cb_cl);
 611 
 612   if (cb_cl.failures()) {
 613     *failures = true;
 614   }
 615 }
 616 
 617 void HeapRegion::print() const { print_on(gclog_or_tty); }
 618 void HeapRegion::print_on(outputStream* st) const {
 619   st->print("AC%4u", allocation_context());
 620 
 621   st->print(" %2s", get_short_type_str());
 622   if (in_collection_set())
 623     st->print(" CS");
 624   else
 625     st->print("   ");
 626   st->print(" TS %5d", _gc_time_stamp);
 627   st->print(" PTAMS "PTR_FORMAT" NTAMS "PTR_FORMAT,
 628             prev_top_at_mark_start(), next_top_at_mark_start());
 629   G1OffsetTableContigSpace::print_on(st);
 630 }
 631 
 632 class VerifyLiveClosure: public OopClosure {
 633 private:
 634   G1CollectedHeap* _g1h;
 635   CardTableModRefBS* _bs;
 636   oop _containing_obj;
 637   bool _failures;
 638   int _n_failures;
 639   VerifyOption _vo;
 640 public:
 641   // _vo == UsePrevMarking -> use "prev" marking information,
 642   // _vo == UseNextMarking -> use "next" marking information,
 643   // _vo == UseMarkWord    -> use mark word from object header.
 644   VerifyLiveClosure(G1CollectedHeap* g1h, VerifyOption vo) :
 645     _g1h(g1h), _bs(barrier_set_cast<CardTableModRefBS>(g1h->barrier_set())),
 646     _containing_obj(NULL), _failures(false), _n_failures(0), _vo(vo)
 647   { }
 648 
 649   void set_containing_obj(oop obj) {
 650     _containing_obj = obj;
 651   }
 652 
 653   bool failures() { return _failures; }
 654   int n_failures() { return _n_failures; }
 655 
 656   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 657   virtual void do_oop(      oop* p) { do_oop_work(p); }
 658 
 659   void print_object(outputStream* out, oop obj) {
 660 #ifdef PRODUCT
 661     Klass* k = obj->klass();
 662     const char* class_name = InstanceKlass::cast(k)->external_name();
 663     out->print_cr("class name %s", class_name);
 664 #else // PRODUCT
 665     obj->print_on(out);
 666 #endif // PRODUCT
 667   }
 668 
 669   template <class T>
 670   void do_oop_work(T* p) {
 671     assert(_containing_obj != NULL, "Precondition");
 672     assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
 673            "Precondition");
 674     T heap_oop = oopDesc::load_heap_oop(p);
 675     if (!oopDesc::is_null(heap_oop)) {
 676       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 677       bool failed = false;
 678       if (!_g1h->is_in_closed_subset(obj) || _g1h->is_obj_dead_cond(obj, _vo)) {
 679         MutexLockerEx x(ParGCRareEvent_lock,
 680                         Mutex::_no_safepoint_check_flag);
 681 
 682         if (!_failures) {
 683           gclog_or_tty->cr();
 684           gclog_or_tty->print_cr("----------");
 685         }
 686         if (!_g1h->is_in_closed_subset(obj)) {
 687           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 688           gclog_or_tty->print_cr("Field "PTR_FORMAT
 689                                  " of live obj "PTR_FORMAT" in region "
 690                                  "["PTR_FORMAT", "PTR_FORMAT")",
 691                                  p, (void*) _containing_obj,
 692                                  from->bottom(), from->end());
 693           print_object(gclog_or_tty, _containing_obj);
 694           gclog_or_tty->print_cr("points to obj "PTR_FORMAT" not in the heap",
 695                                  (void*) obj);
 696         } else {
 697           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 698           HeapRegion* to   = _g1h->heap_region_containing((HeapWord*)obj);
 699           gclog_or_tty->print_cr("Field "PTR_FORMAT
 700                                  " of live obj "PTR_FORMAT" in region "
 701                                  "["PTR_FORMAT", "PTR_FORMAT")",
 702                                  p, (void*) _containing_obj,
 703                                  from->bottom(), from->end());
 704           print_object(gclog_or_tty, _containing_obj);
 705           gclog_or_tty->print_cr("points to dead obj "PTR_FORMAT" in region "
 706                                  "["PTR_FORMAT", "PTR_FORMAT")",
 707                                  (void*) obj, to->bottom(), to->end());
 708           print_object(gclog_or_tty, obj);
 709         }
 710         gclog_or_tty->print_cr("----------");
 711         gclog_or_tty->flush();
 712         _failures = true;
 713         failed = true;
 714         _n_failures++;
 715       }
 716 
 717       if (!_g1h->full_collection() || G1VerifyRSetsDuringFullGC) {
 718         HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 719         HeapRegion* to   = _g1h->heap_region_containing(obj);
 720         if (from != NULL && to != NULL &&
 721             from != to &&
 722             !to->is_humongous()) {
 723           jbyte cv_obj = *_bs->byte_for_const(_containing_obj);
 724           jbyte cv_field = *_bs->byte_for_const(p);
 725           const jbyte dirty = CardTableModRefBS::dirty_card_val();
 726 
 727           bool is_bad = !(from->is_young()
 728                           || to->rem_set()->contains_reference(p)
 729                           || !G1HRRSFlushLogBuffersOnVerify && // buffers were not flushed
 730                               (_containing_obj->is_objArray() ?
 731                                   cv_field == dirty
 732                                : cv_obj == dirty || cv_field == dirty));
 733           if (is_bad) {
 734             MutexLockerEx x(ParGCRareEvent_lock,
 735                             Mutex::_no_safepoint_check_flag);
 736 
 737             if (!_failures) {
 738               gclog_or_tty->cr();
 739               gclog_or_tty->print_cr("----------");
 740             }
 741             gclog_or_tty->print_cr("Missing rem set entry:");
 742             gclog_or_tty->print_cr("Field "PTR_FORMAT" "
 743                                    "of obj "PTR_FORMAT", "
 744                                    "in region "HR_FORMAT,
 745                                    p, (void*) _containing_obj,
 746                                    HR_FORMAT_PARAMS(from));
 747             _containing_obj->print_on(gclog_or_tty);
 748             gclog_or_tty->print_cr("points to obj "PTR_FORMAT" "
 749                                    "in region "HR_FORMAT,
 750                                    (void*) obj,
 751                                    HR_FORMAT_PARAMS(to));
 752             obj->print_on(gclog_or_tty);
 753             gclog_or_tty->print_cr("Obj head CTE = %d, field CTE = %d.",
 754                           cv_obj, cv_field);
 755             gclog_or_tty->print_cr("----------");
 756             gclog_or_tty->flush();
 757             _failures = true;
 758             if (!failed) _n_failures++;
 759           }
 760         }
 761       }
 762     }
 763   }
 764 };
 765 
 766 // This really ought to be commoned up into OffsetTableContigSpace somehow.
 767 // We would need a mechanism to make that code skip dead objects.
 768 
 769 void HeapRegion::verify(VerifyOption vo,
 770                         bool* failures) const {
 771   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 772   *failures = false;
 773   HeapWord* p = bottom();
 774   HeapWord* prev_p = NULL;
 775   VerifyLiveClosure vl_cl(g1, vo);
 776   bool is_region_humongous = is_humongous();
 777   size_t object_num = 0;
 778   while (p < top()) {
 779     oop obj = oop(p);
 780     size_t obj_size = block_size(p);
 781     object_num += 1;
 782 
 783     if (is_region_humongous != g1->is_humongous(obj_size) &&
 784         !g1->is_obj_dead(obj, this)) { // Dead objects may have bigger block_size since they span several objects.
 785       gclog_or_tty->print_cr("obj "PTR_FORMAT" is of %shumongous size ("
 786                              SIZE_FORMAT" words) in a %shumongous region",
 787                              p, g1->is_humongous(obj_size) ? "" : "non-",
 788                              obj_size, is_region_humongous ? "" : "non-");
 789        *failures = true;
 790        return;
 791     }
 792 
 793     if (!g1->is_obj_dead_cond(obj, this, vo)) {
 794       if (obj->is_oop()) {
 795         Klass* klass = obj->klass();
 796         bool is_metaspace_object = Metaspace::contains(klass) ||
 797                                    (vo == VerifyOption_G1UsePrevMarking &&
 798                                    ClassLoaderDataGraph::unload_list_contains(klass));
 799         if (!is_metaspace_object) {
 800           gclog_or_tty->print_cr("klass "PTR_FORMAT" of object "PTR_FORMAT" "
 801                                  "not metadata", klass, (void *)obj);
 802           *failures = true;
 803           return;
 804         } else if (!klass->is_klass()) {
 805           gclog_or_tty->print_cr("klass "PTR_FORMAT" of object "PTR_FORMAT" "
 806                                  "not a klass", klass, (void *)obj);
 807           *failures = true;
 808           return;
 809         } else {
 810           vl_cl.set_containing_obj(obj);
 811           obj->oop_iterate_no_header(&vl_cl);
 812           if (vl_cl.failures()) {
 813             *failures = true;
 814           }
 815           if (G1MaxVerifyFailures >= 0 &&
 816               vl_cl.n_failures() >= G1MaxVerifyFailures) {
 817             return;
 818           }
 819         }
 820       } else {
 821         gclog_or_tty->print_cr(PTR_FORMAT" no an oop", (void *)obj);
 822         *failures = true;
 823         return;
 824       }
 825     }
 826     prev_p = p;
 827     p += obj_size;
 828   }
 829 
 830   if (!is_young() && !is_empty()) {
 831     _offsets.verify();
 832   }
 833 
 834   if (p != top()) {
 835     gclog_or_tty->print_cr("end of last object "PTR_FORMAT" "
 836                            "does not match top "PTR_FORMAT, p, top());
 837     *failures = true;
 838     return;
 839   }
 840 
 841   HeapWord* the_end = end();
 842   assert(p == top(), "it should still hold");
 843   // Do some extra BOT consistency checking for addresses in the
 844   // range [top, end). BOT look-ups in this range should yield
 845   // top. No point in doing that if top == end (there's nothing there).
 846   if (p < the_end) {
 847     // Look up top
 848     HeapWord* addr_1 = p;
 849     HeapWord* b_start_1 = _offsets.block_start_const(addr_1);
 850     if (b_start_1 != p) {
 851       gclog_or_tty->print_cr("BOT look up for top: "PTR_FORMAT" "
 852                              " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
 853                              addr_1, b_start_1, p);
 854       *failures = true;
 855       return;
 856     }
 857 
 858     // Look up top + 1
 859     HeapWord* addr_2 = p + 1;
 860     if (addr_2 < the_end) {
 861       HeapWord* b_start_2 = _offsets.block_start_const(addr_2);
 862       if (b_start_2 != p) {
 863         gclog_or_tty->print_cr("BOT look up for top + 1: "PTR_FORMAT" "
 864                                " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
 865                                addr_2, b_start_2, p);
 866         *failures = true;
 867         return;
 868       }
 869     }
 870 
 871     // Look up an address between top and end
 872     size_t diff = pointer_delta(the_end, p) / 2;
 873     HeapWord* addr_3 = p + diff;
 874     if (addr_3 < the_end) {
 875       HeapWord* b_start_3 = _offsets.block_start_const(addr_3);
 876       if (b_start_3 != p) {
 877         gclog_or_tty->print_cr("BOT look up for top + diff: "PTR_FORMAT" "
 878                                " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
 879                                addr_3, b_start_3, p);
 880         *failures = true;
 881         return;
 882       }
 883     }
 884 
 885     // Look up end - 1
 886     HeapWord* addr_4 = the_end - 1;
 887     HeapWord* b_start_4 = _offsets.block_start_const(addr_4);
 888     if (b_start_4 != p) {
 889       gclog_or_tty->print_cr("BOT look up for end - 1: "PTR_FORMAT" "
 890                              " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
 891                              addr_4, b_start_4, p);
 892       *failures = true;
 893       return;
 894     }
 895   }
 896 
 897   if (is_region_humongous && object_num > 1) {
 898     gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] is humongous "
 899                            "but has "SIZE_FORMAT", objects",
 900                            bottom(), end(), object_num);
 901     *failures = true;
 902     return;
 903   }
 904 
 905   verify_strong_code_roots(vo, failures);
 906 }
 907 
 908 void HeapRegion::verify() const {
 909   bool dummy = false;
 910   verify(VerifyOption_G1UsePrevMarking, /* failures */ &dummy);
 911 }
 912 
 913 void HeapRegion::prepare_for_compaction(CompactPoint* cp) {
 914   scan_and_forward(this, cp);
 915 }
 916 
 917 // G1OffsetTableContigSpace code; copied from space.cpp.  Hope this can go
 918 // away eventually.
 919 
 920 void G1OffsetTableContigSpace::clear(bool mangle_space) {
 921   set_top(bottom());
 922   _scan_top = bottom();
 923   CompactibleSpace::clear(mangle_space);
 924   reset_bot();
 925 }
 926 
 927 void G1OffsetTableContigSpace::set_bottom(HeapWord* new_bottom) {
 928   Space::set_bottom(new_bottom);
 929   _offsets.set_bottom(new_bottom);
 930 }
 931 
 932 void G1OffsetTableContigSpace::set_end(HeapWord* new_end) {
 933   Space::set_end(new_end);
 934   _offsets.resize(new_end - bottom());
 935 }
 936 
 937 #ifndef PRODUCT
 938 void G1OffsetTableContigSpace::mangle_unused_area() {
 939   mangle_unused_area_complete();
 940 }
 941 
 942 void G1OffsetTableContigSpace::mangle_unused_area_complete() {
 943   SpaceMangler::mangle_region(MemRegion(top(), end()));
 944 }
 945 #endif
 946 
 947 void G1OffsetTableContigSpace::print() const {
 948   print_short();
 949   gclog_or_tty->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", "
 950                 INTPTR_FORMAT ", " INTPTR_FORMAT ")",
 951                 bottom(), top(), _offsets.threshold(), end());
 952 }
 953 
 954 HeapWord* G1OffsetTableContigSpace::initialize_threshold() {
 955   return _offsets.initialize_threshold();
 956 }
 957 
 958 HeapWord* G1OffsetTableContigSpace::cross_threshold(HeapWord* start,
 959                                                     HeapWord* end) {
 960   _offsets.alloc_block(start, end);
 961   return _offsets.threshold();
 962 }
 963 
 964 HeapWord* G1OffsetTableContigSpace::scan_top() const {
 965   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 966   HeapWord* local_top = top();
 967   OrderAccess::loadload();
 968   const unsigned local_time_stamp = _gc_time_stamp;
 969   assert(local_time_stamp <= g1h->get_gc_time_stamp(), "invariant");
 970   if (local_time_stamp < g1h->get_gc_time_stamp()) {
 971     return local_top;
 972   } else {
 973     return _scan_top;
 974   }
 975 }
 976 
 977 void G1OffsetTableContigSpace::record_timestamp() {
 978   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 979   unsigned curr_gc_time_stamp = g1h->get_gc_time_stamp();
 980 
 981   if (_gc_time_stamp < curr_gc_time_stamp) {
 982     // Setting the time stamp here tells concurrent readers to look at
 983     // scan_top to know the maximum allowed address to look at.
 984 
 985     // scan_top should be bottom for all regions except for the
 986     // retained old alloc region which should have scan_top == top
 987     HeapWord* st = _scan_top;
 988     guarantee(st == _bottom || st == _top, "invariant");
 989 
 990     _gc_time_stamp = curr_gc_time_stamp;
 991   }
 992 }
 993 
 994 void G1OffsetTableContigSpace::record_retained_region() {
 995   // scan_top is the maximum address where it's safe for the next gc to
 996   // scan this region.
 997   _scan_top = top();
 998 }
 999 
1000 void G1OffsetTableContigSpace::safe_object_iterate(ObjectClosure* blk) {
1001   object_iterate(blk);
1002 }
1003 
1004 void G1OffsetTableContigSpace::object_iterate(ObjectClosure* blk) {
1005   HeapWord* p = bottom();
1006   while (p < top()) {
1007     if (block_is_obj(p)) {
1008       blk->do_object(oop(p));
1009     }
1010     p += block_size(p);
1011   }
1012 }
1013 
1014 G1OffsetTableContigSpace::
1015 G1OffsetTableContigSpace(G1BlockOffsetSharedArray* sharedOffsetArray,
1016                          MemRegion mr) :
1017   _offsets(sharedOffsetArray, mr),
1018   _par_alloc_lock(Mutex::leaf, "OffsetTableContigSpace par alloc lock", true),
1019   _gc_time_stamp(0)
1020 {
1021   _offsets.set_space(this);
1022 }
1023 
1024 void G1OffsetTableContigSpace::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
1025   CompactibleSpace::initialize(mr, clear_space, mangle_space);
1026   _top = bottom();
1027   _scan_top = bottom();
1028   set_saved_mark_word(NULL);
1029   reset_bot();
1030 }
1031