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_free() {
 218   report_region_type_change(G1HeapRegionTraceType::Free);
 219   _type.set_free();
 220 }
 221 
 222 void HeapRegion::set_eden() {
 223   report_region_type_change(G1HeapRegionTraceType::Eden);
 224   _type.set_eden();
 225 }
 226 
 227 void HeapRegion::set_eden_pre_gc() {
 228   report_region_type_change(G1HeapRegionTraceType::Eden);
 229   _type.set_eden_pre_gc();
 230 }
 231 
 232 void HeapRegion::set_survivor() {
 233   report_region_type_change(G1HeapRegionTraceType::Survivor);
 234   _type.set_survivor();
 235 }
 236 
 237 void HeapRegion::set_old() {
 238   report_region_type_change(G1HeapRegionTraceType::Old);
 239   _type.set_old();
 240 }
 241 
 242 void HeapRegion::set_archive() {
 243   report_region_type_change(G1HeapRegionTraceType::Archive);
 244   _type.set_archive();
 245 }
 246 
 247 void HeapRegion::set_starts_humongous(HeapWord* obj_top, size_t fill_size) {
 248   assert(!is_humongous(), "sanity / pre-condition");
 249   assert(top() == bottom(), "should be empty");
 250 
 251   report_region_type_change(G1HeapRegionTraceType::StartsHumongous);
 252   _type.set_starts_humongous();
 253   _humongous_start_region = this;
 254 
 255   _bot_part.set_for_starts_humongous(obj_top, fill_size);
 256 }
 257 
 258 void HeapRegion::set_continues_humongous(HeapRegion* first_hr) {
 259   assert(!is_humongous(), "sanity / pre-condition");
 260   assert(top() == bottom(), "should be empty");
 261   assert(first_hr->is_starts_humongous(), "pre-condition");
 262 
 263   report_region_type_change(G1HeapRegionTraceType::ContinuesHumongous);
 264   _type.set_continues_humongous();
 265   _humongous_start_region = first_hr;
 266 }
 267 
 268 void HeapRegion::clear_humongous() {
 269   assert(is_humongous(), "pre-condition");
 270 
 271   assert(capacity() == HeapRegion::GrainBytes, "pre-condition");
 272   _humongous_start_region = NULL;
 273 }
 274 
 275 HeapRegion::HeapRegion(uint hrm_index,
 276                        G1BlockOffsetTable* bot,
 277                        MemRegion mr) :
 278     G1ContiguousSpace(bot),
 279     _hrm_index(hrm_index),
 280     _allocation_context(AllocationContext::system()),
 281     _humongous_start_region(NULL),
 282     _next_in_special_set(NULL),
 283     _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(bot, this);
 295 
 296   initialize(mr);
 297 }
 298 
 299 void HeapRegion::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
 300   assert(_rem_set->is_empty(), "Remembered set must be empty");
 301 
 302   G1ContiguousSpace::initialize(mr, clear_space, mangle_space);
 303 
 304   hr_clear(false /*par*/, false /*clear_space*/);
 305   set_top(bottom());
 306   record_timestamp();
 307 }
 308 
 309 void HeapRegion::report_region_type_change(G1HeapRegionTraceType::Type to) {
 310   HeapRegionTracer::send_region_type_change(_hrm_index,
 311                                             get_trace_type(),
 312                                             to,
 313                                             (uintptr_t)bottom(),
 314                                             used(),
 315                                             (uint)allocation_context());
 316 }
 317 
 318 CompactibleSpace* HeapRegion::next_compaction_space() const {
 319   return G1CollectedHeap::heap()->next_compaction_region(this);
 320 }
 321 
 322 void HeapRegion::note_self_forwarding_removal_start(bool during_initial_mark,
 323                                                     bool during_conc_mark) {
 324   // We always recreate the prev marking info and we'll explicitly
 325   // mark all objects we find to be self-forwarded on the prev
 326   // bitmap. So all objects need to be below PTAMS.
 327   _prev_marked_bytes = 0;
 328 
 329   if (during_initial_mark) {
 330     // During initial-mark, we'll also explicitly mark all objects
 331     // we find to be self-forwarded on the next bitmap. So all
 332     // objects need to be below NTAMS.
 333     _next_top_at_mark_start = top();
 334     _next_marked_bytes = 0;
 335   } else if (during_conc_mark) {
 336     // During concurrent mark, all objects in the CSet (including
 337     // the ones we find to be self-forwarded) are implicitly live.
 338     // So all objects need to be above NTAMS.
 339     _next_top_at_mark_start = bottom();
 340     _next_marked_bytes = 0;
 341   }
 342 }
 343 
 344 void HeapRegion::note_self_forwarding_removal_end(bool during_initial_mark,
 345                                                   bool during_conc_mark,
 346                                                   size_t marked_bytes) {
 347   assert(marked_bytes <= used(),
 348          "marked: " SIZE_FORMAT " used: " SIZE_FORMAT, marked_bytes, used());
 349   _prev_top_at_mark_start = top();
 350   _prev_marked_bytes = marked_bytes;
 351 }
 352 
 353 HeapWord*
 354 HeapRegion::object_iterate_mem_careful(MemRegion mr,
 355                                                  ObjectClosure* cl) {
 356   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 357   // We used to use "block_start_careful" here.  But we're actually happy
 358   // to update the BOT while we do this...
 359   HeapWord* cur = block_start(mr.start());
 360   mr = mr.intersection(used_region());
 361   if (mr.is_empty()) return NULL;
 362   // Otherwise, find the obj that extends onto mr.start().
 363 
 364   assert(cur <= mr.start()
 365          && (oop(cur)->klass_or_null() == NULL ||
 366              cur + oop(cur)->size() > mr.start()),
 367          "postcondition of block_start");
 368   oop obj;
 369   while (cur < mr.end()) {
 370     obj = oop(cur);
 371     if (obj->klass_or_null() == NULL) {
 372       // Ran into an unparseable point.
 373       return cur;
 374     } else if (!g1h->is_obj_dead(obj)) {
 375       cl->do_object(obj);
 376     }
 377     cur += block_size(cur);
 378   }
 379   return NULL;
 380 }
 381 
 382 HeapWord*
 383 HeapRegion::
 384 oops_on_card_seq_iterate_careful(MemRegion mr,
 385                                  FilterOutOfRegionClosure* cl,
 386                                  bool filter_young,
 387                                  jbyte* card_ptr) {
 388   // Currently, we should only have to clean the card if filter_young
 389   // is true and vice versa.
 390   if (filter_young) {
 391     assert(card_ptr != NULL, "pre-condition");
 392   } else {
 393     assert(card_ptr == NULL, "pre-condition");
 394   }
 395   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 396 
 397   // If we're within a stop-world GC, then we might look at a card in a
 398   // GC alloc region that extends onto a GC LAB, which may not be
 399   // parseable.  Stop such at the "scan_top" of the region.
 400   if (g1h->is_gc_active()) {
 401     mr = mr.intersection(MemRegion(bottom(), scan_top()));
 402   } else {
 403     mr = mr.intersection(used_region());
 404   }
 405   if (mr.is_empty()) return NULL;
 406   // Otherwise, find the obj that extends onto mr.start().
 407 
 408   // The intersection of the incoming mr (for the card) and the
 409   // allocated part of the region is non-empty. This implies that
 410   // we have actually allocated into this region. The code in
 411   // G1CollectedHeap.cpp that allocates a new region sets the
 412   // is_young tag on the region before allocating. Thus we
 413   // safely know if this region is young.
 414   if (is_young() && filter_young) {
 415     return NULL;
 416   }
 417 
 418   assert(!is_young(), "check value of filter_young");
 419 
 420   // We can only clean the card here, after we make the decision that
 421   // the card is not young. And we only clean the card if we have been
 422   // asked to (i.e., card_ptr != NULL).
 423   if (card_ptr != NULL) {
 424     *card_ptr = CardTableModRefBS::clean_card_val();
 425     // We must complete this write before we do any of the reads below.
 426     OrderAccess::storeload();
 427   }
 428 
 429   // Cache the boundaries of the memory region in some const locals
 430   HeapWord* const start = mr.start();
 431   HeapWord* const end = mr.end();
 432 
 433   // We used to use "block_start_careful" here.  But we're actually happy
 434   // to update the BOT while we do this...
 435   HeapWord* cur = block_start(start);
 436   assert(cur <= start, "Postcondition");
 437 
 438   oop obj;
 439 
 440   HeapWord* next = cur;
 441   do {
 442     cur = next;
 443     obj = oop(cur);
 444     if (obj->klass_or_null() == NULL) {
 445       // Ran into an unparseable point.
 446       return cur;
 447     }
 448     // Otherwise...
 449     next = cur + block_size(cur);
 450   } while (next <= start);
 451 
 452   // If we finish the above loop...We have a parseable object that
 453   // begins on or before the start of the memory region, and ends
 454   // inside or spans the entire region.
 455   assert(cur <= start, "Loop postcondition");
 456   assert(obj->klass_or_null() != NULL, "Loop postcondition");
 457 
 458   do {
 459     obj = oop(cur);
 460     assert((cur + block_size(cur)) > (HeapWord*)obj, "Loop invariant");
 461     if (obj->klass_or_null() == NULL) {
 462       // Ran into an unparseable point.
 463       return cur;
 464     }
 465 
 466     // Advance the current pointer. "obj" still points to the object to iterate.
 467     cur = cur + block_size(cur);
 468 
 469     if (!g1h->is_obj_dead(obj)) {
 470       // Non-objArrays are sometimes marked imprecise at the object start. We
 471       // always need to iterate over them in full.
 472       // We only iterate over object arrays in full if they are completely contained
 473       // in the memory region.
 474       if (!obj->is_objArray() || (((HeapWord*)obj) >= start && cur <= end)) {
 475         obj->oop_iterate(cl);
 476       } else {
 477         obj->oop_iterate(cl, mr);
 478       }
 479     }
 480   } while (cur < end);
 481 
 482   return NULL;
 483 }
 484 
 485 // Code roots support
 486 
 487 void HeapRegion::add_strong_code_root(nmethod* nm) {
 488   HeapRegionRemSet* hrrs = rem_set();
 489   hrrs->add_strong_code_root(nm);
 490 }
 491 
 492 void HeapRegion::add_strong_code_root_locked(nmethod* nm) {
 493   assert_locked_or_safepoint(CodeCache_lock);
 494   HeapRegionRemSet* hrrs = rem_set();
 495   hrrs->add_strong_code_root_locked(nm);
 496 }
 497 
 498 void HeapRegion::remove_strong_code_root(nmethod* nm) {
 499   HeapRegionRemSet* hrrs = rem_set();
 500   hrrs->remove_strong_code_root(nm);
 501 }
 502 
 503 void HeapRegion::strong_code_roots_do(CodeBlobClosure* blk) const {
 504   HeapRegionRemSet* hrrs = rem_set();
 505   hrrs->strong_code_roots_do(blk);
 506 }
 507 
 508 class VerifyStrongCodeRootOopClosure: public OopClosure {
 509   const HeapRegion* _hr;
 510   nmethod* _nm;
 511   bool _failures;
 512   bool _has_oops_in_region;
 513 
 514   template <class T> void do_oop_work(T* p) {
 515     T heap_oop = oopDesc::load_heap_oop(p);
 516     if (!oopDesc::is_null(heap_oop)) {
 517       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 518 
 519       // Note: not all the oops embedded in the nmethod are in the
 520       // current region. We only look at those which are.
 521       if (_hr->is_in(obj)) {
 522         // Object is in the region. Check that its less than top
 523         if (_hr->top() <= (HeapWord*)obj) {
 524           // Object is above top
 525           log_info(gc, verify)("Object " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ") is above top " PTR_FORMAT,
 526                                p2i(obj), p2i(_hr->bottom()), p2i(_hr->end()), p2i(_hr->top()));
 527           _failures = true;
 528           return;
 529         }
 530         // Nmethod has at least one oop in the current region
 531         _has_oops_in_region = true;
 532       }
 533     }
 534   }
 535 
 536 public:
 537   VerifyStrongCodeRootOopClosure(const HeapRegion* hr, nmethod* nm):
 538     _hr(hr), _failures(false), _has_oops_in_region(false) {}
 539 
 540   void do_oop(narrowOop* p) { do_oop_work(p); }
 541   void do_oop(oop* p)       { do_oop_work(p); }
 542 
 543   bool failures()           { return _failures; }
 544   bool has_oops_in_region() { return _has_oops_in_region; }
 545 };
 546 
 547 class VerifyStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
 548   const HeapRegion* _hr;
 549   bool _failures;
 550 public:
 551   VerifyStrongCodeRootCodeBlobClosure(const HeapRegion* hr) :
 552     _hr(hr), _failures(false) {}
 553 
 554   void do_code_blob(CodeBlob* cb) {
 555     nmethod* nm = (cb == NULL) ? NULL : cb->as_nmethod_or_null();
 556     if (nm != NULL) {
 557       // Verify that the nemthod is live
 558       if (!nm->is_alive()) {
 559         log_info(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has dead nmethod " PTR_FORMAT " in its strong code roots",
 560                              p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 561         _failures = true;
 562       } else {
 563         VerifyStrongCodeRootOopClosure oop_cl(_hr, nm);
 564         nm->oops_do(&oop_cl);
 565         if (!oop_cl.has_oops_in_region()) {
 566           log_info(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has nmethod " PTR_FORMAT " in its strong code roots with no pointers into region",
 567                                p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 568           _failures = true;
 569         } else if (oop_cl.failures()) {
 570           log_info(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has other failures for nmethod " PTR_FORMAT,
 571                                p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 572           _failures = true;
 573         }
 574       }
 575     }
 576   }
 577 
 578   bool failures()       { return _failures; }
 579 };
 580 
 581 void HeapRegion::verify_strong_code_roots(VerifyOption vo, bool* failures) const {
 582   if (!G1VerifyHeapRegionCodeRoots) {
 583     // We're not verifying code roots.
 584     return;
 585   }
 586   if (vo == VerifyOption_G1UseMarkWord) {
 587     // Marking verification during a full GC is performed after class
 588     // unloading, code cache unloading, etc so the strong code roots
 589     // attached to each heap region are in an inconsistent state. They won't
 590     // be consistent until the strong code roots are rebuilt after the
 591     // actual GC. Skip verifying the strong code roots in this particular
 592     // time.
 593     assert(VerifyDuringGC, "only way to get here");
 594     return;
 595   }
 596 
 597   HeapRegionRemSet* hrrs = rem_set();
 598   size_t strong_code_roots_length = hrrs->strong_code_roots_list_length();
 599 
 600   // if this region is empty then there should be no entries
 601   // on its strong code root list
 602   if (is_empty()) {
 603     if (strong_code_roots_length > 0) {
 604       log_info(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] is empty but has " SIZE_FORMAT " code root entries",
 605                            p2i(bottom()), p2i(end()), strong_code_roots_length);
 606       *failures = true;
 607     }
 608     return;
 609   }
 610 
 611   if (is_continues_humongous()) {
 612     if (strong_code_roots_length > 0) {
 613       log_info(gc, verify)("region " HR_FORMAT " is a continuation of a humongous region but has " SIZE_FORMAT " code root entries",
 614                            HR_FORMAT_PARAMS(this), strong_code_roots_length);
 615       *failures = true;
 616     }
 617     return;
 618   }
 619 
 620   VerifyStrongCodeRootCodeBlobClosure cb_cl(this);
 621   strong_code_roots_do(&cb_cl);
 622 
 623   if (cb_cl.failures()) {
 624     *failures = true;
 625   }
 626 }
 627 
 628 void HeapRegion::print() const { print_on(tty); }
 629 void HeapRegion::print_on(outputStream* st) const {
 630   st->print("|%4u", this->_hrm_index);
 631   st->print("|" PTR_FORMAT ", " PTR_FORMAT ", " PTR_FORMAT,
 632             p2i(bottom()), p2i(top()), p2i(end()));
 633   st->print("|%3d%%", (int) ((double) used() * 100 / capacity()));
 634   st->print("|%2s", get_short_type_str());
 635   if (in_collection_set()) {
 636     st->print("|CS");
 637   } else {
 638     st->print("|  ");
 639   }
 640   st->print("|TS%3u", _gc_time_stamp);
 641   st->print("|AC%3u", allocation_context());
 642   st->print_cr("|TAMS " PTR_FORMAT ", " PTR_FORMAT "|",
 643                p2i(prev_top_at_mark_start()), p2i(next_top_at_mark_start()));
 644 }
 645 
 646 class G1VerificationClosure : public OopClosure {
 647 protected:
 648   G1CollectedHeap* _g1h;
 649   CardTableModRefBS* _bs;
 650   oop _containing_obj;
 651   bool _failures;
 652   int _n_failures;
 653   VerifyOption _vo;
 654 public:
 655   // _vo == UsePrevMarking -> use "prev" marking information,
 656   // _vo == UseNextMarking -> use "next" marking information,
 657   // _vo == UseMarkWord    -> use mark word from object header.
 658   G1VerificationClosure(G1CollectedHeap* g1h, VerifyOption vo) :
 659     _g1h(g1h), _bs(barrier_set_cast<CardTableModRefBS>(g1h->barrier_set())),
 660     _containing_obj(NULL), _failures(false), _n_failures(0), _vo(vo) {
 661   }
 662 
 663   void set_containing_obj(oop obj) {
 664     _containing_obj = obj;
 665   }
 666 
 667   bool failures() { return _failures; }
 668   int n_failures() { return _n_failures; }
 669 
 670   void print_object(outputStream* out, oop obj) {
 671 #ifdef PRODUCT
 672     Klass* k = obj->klass();
 673     const char* class_name = k->external_name();
 674     out->print_cr("class name %s", class_name);
 675 #else // PRODUCT
 676     obj->print_on(out);
 677 #endif // PRODUCT
 678   }
 679 };
 680 
 681 class VerifyLiveClosure : public G1VerificationClosure {
 682 public:
 683   VerifyLiveClosure(G1CollectedHeap* g1h, VerifyOption vo) : G1VerificationClosure(g1h, vo) {}
 684   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 685   virtual void do_oop(oop* p) { do_oop_work(p); }
 686 
 687   template <class T>
 688   void do_oop_work(T* p) {
 689     assert(_containing_obj != NULL, "Precondition");
 690     assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
 691       "Precondition");
 692     verify_liveness(p);
 693   }
 694 
 695   template <class T>
 696   void verify_liveness(T* p) {
 697     T heap_oop = oopDesc::load_heap_oop(p);
 698     LogHandle(gc, verify) log;
 699     if (!oopDesc::is_null(heap_oop)) {
 700       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 701       bool failed = false;
 702       if (!_g1h->is_in_closed_subset(obj) || _g1h->is_obj_dead_cond(obj, _vo)) {
 703         MutexLockerEx x(ParGCRareEvent_lock,
 704           Mutex::_no_safepoint_check_flag);
 705 
 706         if (!_failures) {
 707           log.info("----------");
 708         }
 709         ResourceMark rm;
 710         if (!_g1h->is_in_closed_subset(obj)) {
 711           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 712           log.info("Field " PTR_FORMAT " of live obj " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ")",
 713             p2i(p), p2i(_containing_obj), p2i(from->bottom()), p2i(from->end()));
 714           print_object(log.info_stream(), _containing_obj);
 715           log.info("points to obj " PTR_FORMAT " not in the heap", p2i(obj));
 716         } else {
 717           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 718           HeapRegion* to = _g1h->heap_region_containing((HeapWord*)obj);
 719           log.info("Field " PTR_FORMAT " of live obj " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ")",
 720             p2i(p), p2i(_containing_obj), p2i(from->bottom()), p2i(from->end()));
 721           print_object(log.info_stream(), _containing_obj);
 722           log.info("points to dead obj " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ")",
 723             p2i(obj), p2i(to->bottom()), p2i(to->end()));
 724           print_object(log.info_stream(), obj);
 725         }
 726         log.info("----------");
 727         _failures = true;
 728         failed = true;
 729         _n_failures++;
 730       }
 731     }
 732   }
 733 };
 734 
 735 class VerifyRemSetClosure : public G1VerificationClosure {
 736 public:
 737   VerifyRemSetClosure(G1CollectedHeap* g1h, VerifyOption vo) : G1VerificationClosure(g1h, vo) {}
 738   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 739   virtual void do_oop(oop* p) { do_oop_work(p); }
 740 
 741   template <class T>
 742   void do_oop_work(T* p) {
 743     assert(_containing_obj != NULL, "Precondition");
 744     assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
 745       "Precondition");
 746     verify_remembered_set(p);
 747   }
 748 
 749   template <class T>
 750   void verify_remembered_set(T* p) {
 751     T heap_oop = oopDesc::load_heap_oop(p);
 752     LogHandle(gc, verify) log;
 753     if (!oopDesc::is_null(heap_oop)) {
 754       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 755       bool failed = false;
 756       HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 757       HeapRegion* to = _g1h->heap_region_containing(obj);
 758       if (from != NULL && to != NULL &&
 759         from != to &&
 760         !to->is_pinned()) {
 761         jbyte cv_obj = *_bs->byte_for_const(_containing_obj);
 762         jbyte cv_field = *_bs->byte_for_const(p);
 763         const jbyte dirty = CardTableModRefBS::dirty_card_val();
 764 
 765         bool is_bad = !(from->is_young()
 766           || to->rem_set()->contains_reference(p)
 767           || !G1HRRSFlushLogBuffersOnVerify && // buffers were not flushed
 768           (_containing_obj->is_objArray() ?
 769           cv_field == dirty
 770           : cv_obj == dirty || cv_field == dirty));
 771         if (is_bad) {
 772           MutexLockerEx x(ParGCRareEvent_lock,
 773             Mutex::_no_safepoint_check_flag);
 774 
 775           if (!_failures) {
 776             log.info("----------");
 777           }
 778           log.info("Missing rem set entry:");
 779           log.info("Field " PTR_FORMAT " of obj " PTR_FORMAT ", in region " HR_FORMAT,
 780             p2i(p), p2i(_containing_obj), HR_FORMAT_PARAMS(from));
 781           ResourceMark rm;
 782           _containing_obj->print_on(log.info_stream());
 783           log.info("points to obj " PTR_FORMAT " in region " HR_FORMAT, p2i(obj), HR_FORMAT_PARAMS(to));
 784           obj->print_on(log.info_stream());
 785           log.info("Obj head CTE = %d, field CTE = %d.", cv_obj, cv_field);
 786           log.info("----------");
 787           _failures = true;
 788           if (!failed) _n_failures++;
 789         }
 790       }
 791     }
 792   }
 793 };
 794 
 795 // This really ought to be commoned up into OffsetTableContigSpace somehow.
 796 // We would need a mechanism to make that code skip dead objects.
 797 
 798 void HeapRegion::verify(VerifyOption vo,
 799                         bool* failures) const {
 800   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 801   *failures = false;
 802   HeapWord* p = bottom();
 803   HeapWord* prev_p = NULL;
 804   VerifyLiveClosure vl_cl(g1, vo);
 805   VerifyRemSetClosure vr_cl(g1, vo);
 806   bool is_region_humongous = is_humongous();
 807   size_t object_num = 0;
 808   while (p < top()) {
 809     oop obj = oop(p);
 810     size_t obj_size = block_size(p);
 811     object_num += 1;
 812 
 813     if (!g1->is_obj_dead_cond(obj, this, vo)) {
 814       if (obj->is_oop()) {
 815         Klass* klass = obj->klass();
 816         bool is_metaspace_object = Metaspace::contains(klass) ||
 817                                    (vo == VerifyOption_G1UsePrevMarking &&
 818                                    ClassLoaderDataGraph::unload_list_contains(klass));
 819         if (!is_metaspace_object) {
 820           log_info(gc, verify)("klass " PTR_FORMAT " of object " PTR_FORMAT " "
 821                                "not metadata", p2i(klass), p2i(obj));
 822           *failures = true;
 823           return;
 824         } else if (!klass->is_klass()) {
 825           log_info(gc, verify)("klass " PTR_FORMAT " of object " PTR_FORMAT " "
 826                                "not a klass", p2i(klass), p2i(obj));
 827           *failures = true;
 828           return;
 829         } else {
 830           vl_cl.set_containing_obj(obj);
 831           if (!g1->collector_state()->full_collection() || G1VerifyRSetsDuringFullGC) {
 832             // verify liveness and rem_set
 833             vr_cl.set_containing_obj(obj);
 834             G1Mux2Closure mux(&vl_cl, &vr_cl);
 835             obj->oop_iterate_no_header(&mux);
 836 
 837             if (vr_cl.failures()) {
 838               *failures = true;
 839             }
 840             if (G1MaxVerifyFailures >= 0 &&
 841               vr_cl.n_failures() >= G1MaxVerifyFailures) {
 842               return;
 843             }
 844           } else {
 845             // verify only liveness
 846             obj->oop_iterate_no_header(&vl_cl);
 847           }
 848           if (vl_cl.failures()) {
 849             *failures = true;
 850           }
 851           if (G1MaxVerifyFailures >= 0 &&
 852               vl_cl.n_failures() >= G1MaxVerifyFailures) {
 853             return;
 854           }
 855         }
 856       } else {
 857         log_info(gc, verify)(PTR_FORMAT " not an oop", p2i(obj));
 858         *failures = true;
 859         return;
 860       }
 861     }
 862     prev_p = p;
 863     p += obj_size;
 864   }
 865 
 866   if (!is_young() && !is_empty()) {
 867     _bot_part.verify();
 868   }
 869 
 870   if (is_region_humongous) {
 871     oop obj = oop(this->humongous_start_region()->bottom());
 872     if ((HeapWord*)obj > bottom() || (HeapWord*)obj + obj->size() < bottom()) {
 873       log_info(gc, verify)("this humongous region is not part of its' humongous object " PTR_FORMAT, p2i(obj));
 874     }
 875   }
 876 
 877   if (!is_region_humongous && p != top()) {
 878     log_info(gc, verify)("end of last object " PTR_FORMAT " "
 879                          "does not match top " PTR_FORMAT, p2i(p), p2i(top()));
 880     *failures = true;
 881     return;
 882   }
 883 
 884   HeapWord* the_end = end();
 885   // Do some extra BOT consistency checking for addresses in the
 886   // range [top, end). BOT look-ups in this range should yield
 887   // top. No point in doing that if top == end (there's nothing there).
 888   if (p < the_end) {
 889     // Look up top
 890     HeapWord* addr_1 = p;
 891     HeapWord* b_start_1 = _bot_part.block_start_const(addr_1);
 892     if (b_start_1 != p) {
 893       log_info(gc, verify)("BOT look up for top: " PTR_FORMAT " "
 894                            " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 895                            p2i(addr_1), p2i(b_start_1), p2i(p));
 896       *failures = true;
 897       return;
 898     }
 899 
 900     // Look up top + 1
 901     HeapWord* addr_2 = p + 1;
 902     if (addr_2 < the_end) {
 903       HeapWord* b_start_2 = _bot_part.block_start_const(addr_2);
 904       if (b_start_2 != p) {
 905         log_info(gc, verify)("BOT look up for top + 1: " PTR_FORMAT " "
 906                              " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 907                              p2i(addr_2), p2i(b_start_2), p2i(p));
 908         *failures = true;
 909         return;
 910       }
 911     }
 912 
 913     // Look up an address between top and end
 914     size_t diff = pointer_delta(the_end, p) / 2;
 915     HeapWord* addr_3 = p + diff;
 916     if (addr_3 < the_end) {
 917       HeapWord* b_start_3 = _bot_part.block_start_const(addr_3);
 918       if (b_start_3 != p) {
 919         log_info(gc, verify)("BOT look up for top + diff: " PTR_FORMAT " "
 920                              " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 921                              p2i(addr_3), p2i(b_start_3), p2i(p));
 922         *failures = true;
 923         return;
 924       }
 925     }
 926 
 927     // Look up end - 1
 928     HeapWord* addr_4 = the_end - 1;
 929     HeapWord* b_start_4 = _bot_part.block_start_const(addr_4);
 930     if (b_start_4 != p) {
 931       log_info(gc, verify)("BOT look up for end - 1: " PTR_FORMAT " "
 932                            " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 933                            p2i(addr_4), p2i(b_start_4), p2i(p));
 934       *failures = true;
 935       return;
 936     }
 937   }
 938 
 939   verify_strong_code_roots(vo, failures);
 940 }
 941 
 942 void HeapRegion::verify() const {
 943   bool dummy = false;
 944   verify(VerifyOption_G1UsePrevMarking, /* failures */ &dummy);
 945 }
 946 
 947 void HeapRegion::verify_rem_set(VerifyOption vo, bool* failures) const {
 948   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 949   *failures = false;
 950   HeapWord* p = bottom();
 951   HeapWord* prev_p = NULL;
 952   VerifyRemSetClosure vr_cl(g1, vo);
 953   while (p < top()) {
 954     oop obj = oop(p);
 955     size_t obj_size = block_size(p);
 956 
 957     if (!g1->is_obj_dead_cond(obj, this, vo)) {
 958       if (obj->is_oop()) {
 959         vr_cl.set_containing_obj(obj);
 960         obj->oop_iterate_no_header(&vr_cl);
 961 
 962         if (vr_cl.failures()) {
 963           *failures = true;
 964         }
 965         if (G1MaxVerifyFailures >= 0 &&
 966           vr_cl.n_failures() >= G1MaxVerifyFailures) {
 967           return;
 968         }
 969       } else {
 970         log_info(gc, verify)(PTR_FORMAT " not an oop", p2i(obj));
 971         *failures = true;
 972         return;
 973       }
 974     }
 975 
 976     prev_p = p;
 977     p += obj_size;
 978   }
 979 }
 980 
 981 void HeapRegion::verify_rem_set() const {
 982   bool failures = false;
 983   verify_rem_set(VerifyOption_G1UsePrevMarking, &failures);
 984   guarantee(!failures, "HeapRegion RemSet verification failed");
 985 }
 986 
 987 void HeapRegion::prepare_for_compaction(CompactPoint* cp) {
 988   scan_and_forward(this, cp);
 989 }
 990 
 991 // G1OffsetTableContigSpace code; copied from space.cpp.  Hope this can go
 992 // away eventually.
 993 
 994 void G1ContiguousSpace::clear(bool mangle_space) {
 995   set_top(bottom());
 996   _scan_top = bottom();
 997   CompactibleSpace::clear(mangle_space);
 998   reset_bot();
 999 }
1000 
1001 #ifndef PRODUCT
1002 void G1ContiguousSpace::mangle_unused_area() {
1003   mangle_unused_area_complete();
1004 }
1005 
1006 void G1ContiguousSpace::mangle_unused_area_complete() {
1007   SpaceMangler::mangle_region(MemRegion(top(), end()));
1008 }
1009 #endif
1010 
1011 void G1ContiguousSpace::print() const {
1012   print_short();
1013   tty->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", "
1014                 INTPTR_FORMAT ", " INTPTR_FORMAT ")",
1015                 p2i(bottom()), p2i(top()), p2i(_bot_part.threshold()), p2i(end()));
1016 }
1017 
1018 HeapWord* G1ContiguousSpace::initialize_threshold() {
1019   return _bot_part.initialize_threshold();
1020 }
1021 
1022 HeapWord* G1ContiguousSpace::cross_threshold(HeapWord* start,
1023                                                     HeapWord* end) {
1024   _bot_part.alloc_block(start, end);
1025   return _bot_part.threshold();
1026 }
1027 
1028 HeapWord* G1ContiguousSpace::scan_top() const {
1029   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1030   HeapWord* local_top = top();
1031   OrderAccess::loadload();
1032   const unsigned local_time_stamp = _gc_time_stamp;
1033   assert(local_time_stamp <= g1h->get_gc_time_stamp(), "invariant");
1034   if (local_time_stamp < g1h->get_gc_time_stamp()) {
1035     return local_top;
1036   } else {
1037     return _scan_top;
1038   }
1039 }
1040 
1041 void G1ContiguousSpace::record_timestamp() {
1042   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1043   unsigned curr_gc_time_stamp = g1h->get_gc_time_stamp();
1044 
1045   if (_gc_time_stamp < curr_gc_time_stamp) {
1046     // Setting the time stamp here tells concurrent readers to look at
1047     // scan_top to know the maximum allowed address to look at.
1048 
1049     // scan_top should be bottom for all regions except for the
1050     // retained old alloc region which should have scan_top == top
1051     HeapWord* st = _scan_top;
1052     guarantee(st == _bottom || st == _top, "invariant");
1053 
1054     _gc_time_stamp = curr_gc_time_stamp;
1055   }
1056 }
1057 
1058 void G1ContiguousSpace::record_retained_region() {
1059   // scan_top is the maximum address where it's safe for the next gc to
1060   // scan this region.
1061   _scan_top = top();
1062 }
1063 
1064 void G1ContiguousSpace::safe_object_iterate(ObjectClosure* blk) {
1065   object_iterate(blk);
1066 }
1067 
1068 void G1ContiguousSpace::object_iterate(ObjectClosure* blk) {
1069   HeapWord* p = bottom();
1070   while (p < top()) {
1071     if (block_is_obj(p)) {
1072       blk->do_object(oop(p));
1073     }
1074     p += block_size(p);
1075   }
1076 }
1077 
1078 G1ContiguousSpace::G1ContiguousSpace(G1BlockOffsetTable* bot) :
1079   _bot_part(bot, this),
1080   _par_alloc_lock(Mutex::leaf, "OffsetTableContigSpace par alloc lock", true),
1081   _gc_time_stamp(0)
1082 {
1083 }
1084 
1085 void G1ContiguousSpace::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
1086   CompactibleSpace::initialize(mr, clear_space, mangle_space);
1087   _top = bottom();
1088   _scan_top = bottom();
1089   set_saved_mark_word(NULL);
1090   reset_bot();
1091 }
1092