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