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