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