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