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