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