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