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