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