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