1 /*
   2  * Copyright (c) 2001, 2017, 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 "logging/logStream.hpp"
  40 #include "memory/iterator.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "runtime/atomic.hpp"
  44 #include "runtime/orderAccess.inline.hpp"
  45 #include "utilities/growableArray.hpp"
  46 
  47 int    HeapRegion::LogOfHRGrainBytes = 0;
  48 int    HeapRegion::LogOfHRGrainWords = 0;
  49 size_t HeapRegion::GrainBytes        = 0;
  50 size_t HeapRegion::GrainWords        = 0;
  51 size_t HeapRegion::CardsPerRegion    = 0;
  52 
  53 size_t HeapRegion::max_region_size() {
  54   return HeapRegionBounds::max_size();
  55 }
  56 
  57 size_t HeapRegion::min_region_size_in_words() {
  58   return HeapRegionBounds::min_size() >> LogHeapWordSize;
  59 }
  60 
  61 void HeapRegion::setup_heap_region_size(size_t initial_heap_size, size_t max_heap_size) {
  62   size_t region_size = G1HeapRegionSize;
  63   if (FLAG_IS_DEFAULT(G1HeapRegionSize)) {
  64     size_t average_heap_size = (initial_heap_size + max_heap_size) / 2;
  65     region_size = MAX2(average_heap_size / HeapRegionBounds::target_number(),
  66                        HeapRegionBounds::min_size());
  67   }
  68 
  69   int region_size_log = log2_long((jlong) region_size);
  70   // Recalculate the region size to make sure it's a power of
  71   // 2. This means that region_size is the largest power of 2 that's
  72   // <= what we've calculated so far.
  73   region_size = ((size_t)1 << region_size_log);
  74 
  75   // Now make sure that we don't go over or under our limits.
  76   if (region_size < HeapRegionBounds::min_size()) {
  77     region_size = HeapRegionBounds::min_size();
  78   } else if (region_size > HeapRegionBounds::max_size()) {
  79     region_size = HeapRegionBounds::max_size();
  80   }
  81 
  82   // And recalculate the log.
  83   region_size_log = log2_long((jlong) region_size);
  84 
  85   // Now, set up the globals.
  86   guarantee(LogOfHRGrainBytes == 0, "we should only set it once");
  87   LogOfHRGrainBytes = region_size_log;
  88 
  89   guarantee(LogOfHRGrainWords == 0, "we should only set it once");
  90   LogOfHRGrainWords = LogOfHRGrainBytes - LogHeapWordSize;
  91 
  92   guarantee(GrainBytes == 0, "we should only set it once");
  93   // The cast to int is safe, given that we've bounded region_size by
  94   // MIN_REGION_SIZE and MAX_REGION_SIZE.
  95   GrainBytes = region_size;
  96   log_info(gc, heap)("Heap region size: " SIZE_FORMAT "M", GrainBytes / M);
  97 
  98   guarantee(GrainWords == 0, "we should only set it once");
  99   GrainWords = GrainBytes >> LogHeapWordSize;
 100   guarantee((size_t) 1 << LogOfHRGrainWords == GrainWords, "sanity");
 101 
 102   guarantee(CardsPerRegion == 0, "we should only set it once");
 103   CardsPerRegion = GrainBytes >> CardTableModRefBS::card_shift;
 104 
 105   if (G1HeapRegionSize != GrainBytes) {
 106     FLAG_SET_ERGO(size_t, G1HeapRegionSize, GrainBytes);
 107   }
 108 }
 109 
 110 void HeapRegion::hr_clear(bool keep_remset, bool clear_space, bool locked) {
 111   assert(_humongous_start_region == NULL,
 112          "we should have already filtered out humongous regions");
 113   assert(!in_collection_set(),
 114          "Should not clear heap region %u in the collection set", hrm_index());
 115 
 116   set_young_index_in_cset(-1);
 117   uninstall_surv_rate_group();
 118   set_free();
 119   reset_pre_dummy_top();
 120 
 121   if (!keep_remset) {
 122     if (locked) {
 123       rem_set()->clear_locked();
 124     } else {
 125       rem_set()->clear();
 126     }
 127   }
 128 
 129   zero_marked_bytes();
 130 
 131   init_top_at_mark_start();
 132   _gc_time_stamp = G1CollectedHeap::heap()->get_gc_time_stamp();
 133   if (clear_space) clear(SpaceDecorator::Mangle);
 134 }
 135 
 136 void HeapRegion::par_clear() {
 137   assert(used() == 0, "the region should have been already cleared");
 138   assert(capacity() == HeapRegion::GrainBytes, "should be back to normal");
 139   HeapRegionRemSet* hrrs = rem_set();
 140   hrrs->clear();
 141   CardTableModRefBS* ct_bs =
 142     barrier_set_cast<CardTableModRefBS>(G1CollectedHeap::heap()->barrier_set());
 143   ct_bs->clear(MemRegion(bottom(), end()));
 144 }
 145 
 146 void HeapRegion::calc_gc_efficiency() {
 147   // GC efficiency is the ratio of how much space would be
 148   // reclaimed over how long we predict it would take to reclaim it.
 149   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 150   G1Policy* g1p = g1h->g1_policy();
 151 
 152   // Retrieve a prediction of the elapsed time for this region for
 153   // a mixed gc because the region will only be evacuated during a
 154   // mixed gc.
 155   double region_elapsed_time_ms =
 156     g1p->predict_region_elapsed_time_ms(this, false /* for_young_gc */);
 157   _gc_efficiency = (double) reclaimable_bytes() / region_elapsed_time_ms;
 158 }
 159 
 160 void HeapRegion::set_free() {
 161   report_region_type_change(G1HeapRegionTraceType::Free);
 162   _type.set_free();
 163 }
 164 
 165 void HeapRegion::set_eden() {
 166   report_region_type_change(G1HeapRegionTraceType::Eden);
 167   _type.set_eden();
 168 }
 169 
 170 void HeapRegion::set_eden_pre_gc() {
 171   report_region_type_change(G1HeapRegionTraceType::Eden);
 172   _type.set_eden_pre_gc();
 173 }
 174 
 175 void HeapRegion::set_survivor() {
 176   report_region_type_change(G1HeapRegionTraceType::Survivor);
 177   _type.set_survivor();
 178 }
 179 
 180 void HeapRegion::move_to_old() {
 181   if (_type.relabel_as_old()) {
 182     report_region_type_change(G1HeapRegionTraceType::Old);
 183   }
 184 }
 185 
 186 void HeapRegion::set_old() {
 187   report_region_type_change(G1HeapRegionTraceType::Old);
 188   _type.set_old();
 189 }
 190 
 191 void HeapRegion::set_open_archive() {
 192   report_region_type_change(G1HeapRegionTraceType::OpenArchive);
 193   _type.set_open_archive();
 194 }
 195 
 196 void HeapRegion::set_closed_archive() {
 197   report_region_type_change(G1HeapRegionTraceType::ClosedArchive);
 198   _type.set_closed_archive();
 199 }
 200 
 201 void HeapRegion::set_starts_humongous(HeapWord* obj_top, size_t fill_size) {
 202   assert(!is_humongous(), "sanity / pre-condition");
 203   assert(top() == bottom(), "should be empty");
 204 
 205   report_region_type_change(G1HeapRegionTraceType::StartsHumongous);
 206   _type.set_starts_humongous();
 207   _humongous_start_region = this;
 208 
 209   _bot_part.set_for_starts_humongous(obj_top, fill_size);
 210 }
 211 
 212 void HeapRegion::set_continues_humongous(HeapRegion* first_hr) {
 213   assert(!is_humongous(), "sanity / pre-condition");
 214   assert(top() == bottom(), "should be empty");
 215   assert(first_hr->is_starts_humongous(), "pre-condition");
 216 
 217   report_region_type_change(G1HeapRegionTraceType::ContinuesHumongous);
 218   _type.set_continues_humongous();
 219   _humongous_start_region = first_hr;
 220 
 221   _bot_part.set_object_can_span(true);
 222 }
 223 
 224 void HeapRegion::clear_humongous() {
 225   assert(is_humongous(), "pre-condition");
 226 
 227   assert(capacity() == HeapRegion::GrainBytes, "pre-condition");
 228   _humongous_start_region = NULL;
 229 
 230   _bot_part.set_object_can_span(false);
 231 }
 232 
 233 HeapRegion::HeapRegion(uint hrm_index,
 234                        G1BlockOffsetTable* bot,
 235                        MemRegion mr) :
 236     G1ContiguousSpace(bot),
 237     _hrm_index(hrm_index),
 238     _humongous_start_region(NULL),
 239     _evacuation_failed(false),
 240     _prev_marked_bytes(0), _next_marked_bytes(0), _gc_efficiency(0.0),
 241     _next(NULL), _prev(NULL),
 242 #ifdef ASSERT
 243     _containing_set(NULL),
 244 #endif // ASSERT
 245      _young_index_in_cset(-1), _surv_rate_group(NULL), _age_index(-1),
 246     _rem_set(NULL), _recorded_rs_length(0), _predicted_elapsed_time_ms(0)
 247 {
 248   _rem_set = new HeapRegionRemSet(bot, this);
 249 
 250   initialize(mr);
 251 }
 252 
 253 void HeapRegion::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
 254   assert(_rem_set->is_empty(), "Remembered set must be empty");
 255 
 256   G1ContiguousSpace::initialize(mr, clear_space, mangle_space);
 257 
 258   hr_clear(false /*par*/, false /*clear_space*/);
 259   set_top(bottom());
 260   record_timestamp();
 261 }
 262 
 263 void HeapRegion::report_region_type_change(G1HeapRegionTraceType::Type to) {
 264   HeapRegionTracer::send_region_type_change(_hrm_index,
 265                                             get_trace_type(),
 266                                             to,
 267                                             (uintptr_t)bottom(),
 268                                             used());
 269 }
 270 
 271 void HeapRegion::note_self_forwarding_removal_start(bool during_initial_mark,
 272                                                     bool during_conc_mark) {
 273   // We always recreate the prev marking info and we'll explicitly
 274   // mark all objects we find to be self-forwarded on the prev
 275   // bitmap. So all objects need to be below PTAMS.
 276   _prev_marked_bytes = 0;
 277 
 278   if (during_initial_mark) {
 279     // During initial-mark, we'll also explicitly mark all objects
 280     // we find to be self-forwarded on the next bitmap. So all
 281     // objects need to be below NTAMS.
 282     _next_top_at_mark_start = top();
 283     _next_marked_bytes = 0;
 284   } else if (during_conc_mark) {
 285     // During concurrent mark, all objects in the CSet (including
 286     // the ones we find to be self-forwarded) are implicitly live.
 287     // So all objects need to be above NTAMS.
 288     _next_top_at_mark_start = bottom();
 289     _next_marked_bytes = 0;
 290   }
 291 }
 292 
 293 void HeapRegion::note_self_forwarding_removal_end(size_t marked_bytes) {
 294   assert(marked_bytes <= used(),
 295          "marked: " SIZE_FORMAT " used: " SIZE_FORMAT, marked_bytes, used());
 296   _prev_top_at_mark_start = top();
 297   _prev_marked_bytes = marked_bytes;
 298 }
 299 
 300 // Code roots support
 301 
 302 void HeapRegion::add_strong_code_root(nmethod* nm) {
 303   HeapRegionRemSet* hrrs = rem_set();
 304   hrrs->add_strong_code_root(nm);
 305 }
 306 
 307 void HeapRegion::add_strong_code_root_locked(nmethod* nm) {
 308   assert_locked_or_safepoint(CodeCache_lock);
 309   HeapRegionRemSet* hrrs = rem_set();
 310   hrrs->add_strong_code_root_locked(nm);
 311 }
 312 
 313 void HeapRegion::remove_strong_code_root(nmethod* nm) {
 314   HeapRegionRemSet* hrrs = rem_set();
 315   hrrs->remove_strong_code_root(nm);
 316 }
 317 
 318 void HeapRegion::strong_code_roots_do(CodeBlobClosure* blk) const {
 319   HeapRegionRemSet* hrrs = rem_set();
 320   hrrs->strong_code_roots_do(blk);
 321 }
 322 
 323 class VerifyStrongCodeRootOopClosure: public OopClosure {
 324   const HeapRegion* _hr;
 325   bool _failures;
 326   bool _has_oops_in_region;
 327 
 328   template <class T> void do_oop_work(T* p) {
 329     T heap_oop = oopDesc::load_heap_oop(p);
 330     if (!oopDesc::is_null(heap_oop)) {
 331       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 332 
 333       // Note: not all the oops embedded in the nmethod are in the
 334       // current region. We only look at those which are.
 335       if (_hr->is_in(obj)) {
 336         // Object is in the region. Check that its less than top
 337         if (_hr->top() <= (HeapWord*)obj) {
 338           // Object is above top
 339           log_error(gc, verify)("Object " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ") is above top " PTR_FORMAT,
 340                                p2i(obj), p2i(_hr->bottom()), p2i(_hr->end()), p2i(_hr->top()));
 341           _failures = true;
 342           return;
 343         }
 344         // Nmethod has at least one oop in the current region
 345         _has_oops_in_region = true;
 346       }
 347     }
 348   }
 349 
 350 public:
 351   VerifyStrongCodeRootOopClosure(const HeapRegion* hr):
 352     _hr(hr), _failures(false), _has_oops_in_region(false) {}
 353 
 354   void do_oop(narrowOop* p) { do_oop_work(p); }
 355   void do_oop(oop* p)       { do_oop_work(p); }
 356 
 357   bool failures()           { return _failures; }
 358   bool has_oops_in_region() { return _has_oops_in_region; }
 359 };
 360 
 361 class VerifyStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
 362   const HeapRegion* _hr;
 363   bool _failures;
 364 public:
 365   VerifyStrongCodeRootCodeBlobClosure(const HeapRegion* hr) :
 366     _hr(hr), _failures(false) {}
 367 
 368   void do_code_blob(CodeBlob* cb) {
 369     nmethod* nm = (cb == NULL) ? NULL : cb->as_compiled_method()->as_nmethod_or_null();
 370     if (nm != NULL) {
 371       // Verify that the nemthod is live
 372       if (!nm->is_alive()) {
 373         log_error(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has dead nmethod " PTR_FORMAT " in its strong code roots",
 374                               p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 375         _failures = true;
 376       } else {
 377         VerifyStrongCodeRootOopClosure oop_cl(_hr);
 378         nm->oops_do(&oop_cl);
 379         if (!oop_cl.has_oops_in_region()) {
 380           log_error(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has nmethod " PTR_FORMAT " in its strong code roots with no pointers into region",
 381                                 p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 382           _failures = true;
 383         } else if (oop_cl.failures()) {
 384           log_error(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] has other failures for nmethod " PTR_FORMAT,
 385                                 p2i(_hr->bottom()), p2i(_hr->end()), p2i(nm));
 386           _failures = true;
 387         }
 388       }
 389     }
 390   }
 391 
 392   bool failures()       { return _failures; }
 393 };
 394 
 395 void HeapRegion::verify_strong_code_roots(VerifyOption vo, bool* failures) const {
 396   if (!G1VerifyHeapRegionCodeRoots) {
 397     // We're not verifying code roots.
 398     return;
 399   }
 400   if (vo == VerifyOption_G1UseFullMarking) {
 401     // Marking verification during a full GC is performed after class
 402     // unloading, code cache unloading, etc so the strong code roots
 403     // attached to each heap region are in an inconsistent state. They won't
 404     // be consistent until the strong code roots are rebuilt after the
 405     // actual GC. Skip verifying the strong code roots in this particular
 406     // time.
 407     assert(VerifyDuringGC, "only way to get here");
 408     return;
 409   }
 410 
 411   HeapRegionRemSet* hrrs = rem_set();
 412   size_t strong_code_roots_length = hrrs->strong_code_roots_list_length();
 413 
 414   // if this region is empty then there should be no entries
 415   // on its strong code root list
 416   if (is_empty()) {
 417     if (strong_code_roots_length > 0) {
 418       log_error(gc, verify)("region [" PTR_FORMAT "," PTR_FORMAT "] is empty but has " SIZE_FORMAT " code root entries",
 419                             p2i(bottom()), p2i(end()), strong_code_roots_length);
 420       *failures = true;
 421     }
 422     return;
 423   }
 424 
 425   if (is_continues_humongous()) {
 426     if (strong_code_roots_length > 0) {
 427       log_error(gc, verify)("region " HR_FORMAT " is a continuation of a humongous region but has " SIZE_FORMAT " code root entries",
 428                             HR_FORMAT_PARAMS(this), strong_code_roots_length);
 429       *failures = true;
 430     }
 431     return;
 432   }
 433 
 434   VerifyStrongCodeRootCodeBlobClosure cb_cl(this);
 435   strong_code_roots_do(&cb_cl);
 436 
 437   if (cb_cl.failures()) {
 438     *failures = true;
 439   }
 440 }
 441 
 442 void HeapRegion::print() const { print_on(tty); }
 443 void HeapRegion::print_on(outputStream* st) const {
 444   st->print("|%4u", this->_hrm_index);
 445   st->print("|" PTR_FORMAT ", " PTR_FORMAT ", " PTR_FORMAT,
 446             p2i(bottom()), p2i(top()), p2i(end()));
 447   st->print("|%3d%%", (int) ((double) used() * 100 / capacity()));
 448   st->print("|%2s", get_short_type_str());
 449   if (in_collection_set()) {
 450     st->print("|CS");
 451   } else {
 452     st->print("|  ");
 453   }
 454   st->print("|TS%3u", _gc_time_stamp);
 455   st->print_cr("|TAMS " PTR_FORMAT ", " PTR_FORMAT "|",
 456                p2i(prev_top_at_mark_start()), p2i(next_top_at_mark_start()));
 457 }
 458 
 459 class G1VerificationClosure : public OopClosure {
 460 protected:
 461   G1CollectedHeap* _g1h;
 462   CardTableModRefBS* _bs;
 463   oop _containing_obj;
 464   bool _failures;
 465   int _n_failures;
 466   VerifyOption _vo;
 467 public:
 468   // _vo == UsePrevMarking -> use "prev" marking information,
 469   // _vo == UseNextMarking -> use "next" marking information,
 470   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS.
 471   G1VerificationClosure(G1CollectedHeap* g1h, VerifyOption vo) :
 472     _g1h(g1h), _bs(barrier_set_cast<CardTableModRefBS>(g1h->barrier_set())),
 473     _containing_obj(NULL), _failures(false), _n_failures(0), _vo(vo) {
 474   }
 475 
 476   void set_containing_obj(oop obj) {
 477     _containing_obj = obj;
 478   }
 479 
 480   bool failures() { return _failures; }
 481   int n_failures() { return _n_failures; }
 482 
 483   void print_object(outputStream* out, oop obj) {
 484 #ifdef PRODUCT
 485     Klass* k = obj->klass();
 486     const char* class_name = k->external_name();
 487     out->print_cr("class name %s", class_name);
 488 #else // PRODUCT
 489     obj->print_on(out);
 490 #endif // PRODUCT
 491   }
 492 };
 493 
 494 class VerifyLiveClosure : public G1VerificationClosure {
 495 public:
 496   VerifyLiveClosure(G1CollectedHeap* g1h, VerifyOption vo) : G1VerificationClosure(g1h, vo) {}
 497   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 498   virtual void do_oop(oop* p) { do_oop_work(p); }
 499 
 500   template <class T>
 501   void do_oop_work(T* p) {
 502     assert(_containing_obj != NULL, "Precondition");
 503     assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
 504       "Precondition");
 505     verify_liveness(p);
 506   }
 507 
 508   template <class T>
 509   void verify_liveness(T* p) {
 510     T heap_oop = oopDesc::load_heap_oop(p);
 511     Log(gc, verify) log;
 512     if (!oopDesc::is_null(heap_oop)) {
 513       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 514       bool failed = false;
 515       if (!_g1h->is_in_closed_subset(obj) || _g1h->is_obj_dead_cond(obj, _vo)) {
 516         MutexLockerEx x(ParGCRareEvent_lock,
 517           Mutex::_no_safepoint_check_flag);
 518 
 519         if (!_failures) {
 520           log.error("----------");
 521         }
 522         ResourceMark rm;
 523         if (!_g1h->is_in_closed_subset(obj)) {
 524           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 525           log.error("Field " PTR_FORMAT " of live obj " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ")",
 526             p2i(p), p2i(_containing_obj), p2i(from->bottom()), p2i(from->end()));
 527           LogStream ls(log.error());
 528           print_object(&ls, _containing_obj);
 529           log.error("points to obj " PTR_FORMAT " not in the heap", p2i(obj));
 530         } else {
 531           HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 532           HeapRegion* to = _g1h->heap_region_containing((HeapWord*)obj);
 533           log.error("Field " PTR_FORMAT " of live obj " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ")",
 534             p2i(p), p2i(_containing_obj), p2i(from->bottom()), p2i(from->end()));
 535           LogStream ls(log.error());
 536           print_object(&ls, _containing_obj);
 537           log.error("points to dead obj " PTR_FORMAT " in region [" PTR_FORMAT ", " PTR_FORMAT ")",
 538             p2i(obj), p2i(to->bottom()), p2i(to->end()));
 539           print_object(&ls, obj);
 540         }
 541         log.error("----------");
 542         _failures = true;
 543         failed = true;
 544         _n_failures++;
 545       }
 546     }
 547   }
 548 };
 549 
 550 class VerifyRemSetClosure : public G1VerificationClosure {
 551 public:
 552   VerifyRemSetClosure(G1CollectedHeap* g1h, VerifyOption vo) : G1VerificationClosure(g1h, vo) {}
 553   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 554   virtual void do_oop(oop* p) { do_oop_work(p); }
 555 
 556   template <class T>
 557   void do_oop_work(T* p) {
 558     assert(_containing_obj != NULL, "Precondition");
 559     assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
 560       "Precondition");
 561     verify_remembered_set(p);
 562   }
 563 
 564   template <class T>
 565   void verify_remembered_set(T* p) {
 566     T heap_oop = oopDesc::load_heap_oop(p);
 567     Log(gc, verify) log;
 568     if (!oopDesc::is_null(heap_oop)) {
 569       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 570       HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
 571       HeapRegion* to = _g1h->heap_region_containing(obj);
 572       if (from != NULL && to != NULL &&
 573         from != to &&
 574         !to->is_pinned()) {
 575         jbyte cv_obj = *_bs->byte_for_const(_containing_obj);
 576         jbyte cv_field = *_bs->byte_for_const(p);
 577         const jbyte dirty = CardTableModRefBS::dirty_card_val();
 578 
 579         bool is_bad = !(from->is_young()
 580           || to->rem_set()->contains_reference(p)
 581           || (_containing_obj->is_objArray() ?
 582                 cv_field == dirty :
 583                 cv_obj == dirty || cv_field == dirty));
 584         if (is_bad) {
 585           MutexLockerEx x(ParGCRareEvent_lock,
 586             Mutex::_no_safepoint_check_flag);
 587 
 588           if (!_failures) {
 589             log.error("----------");
 590           }
 591           log.error("Missing rem set entry:");
 592           log.error("Field " PTR_FORMAT " of obj " PTR_FORMAT ", in region " HR_FORMAT,
 593             p2i(p), p2i(_containing_obj), HR_FORMAT_PARAMS(from));
 594           ResourceMark rm;
 595           LogStream ls(log.error());
 596           _containing_obj->print_on(&ls);
 597           log.error("points to obj " PTR_FORMAT " in region " HR_FORMAT, p2i(obj), HR_FORMAT_PARAMS(to));
 598           if (oopDesc::is_oop(obj)) {
 599             obj->print_on(&ls);
 600           }
 601           log.error("Obj head CTE = %d, field CTE = %d.", cv_obj, cv_field);
 602           log.error("----------");
 603           _failures = true;
 604           _n_failures++;
 605         }
 606       }
 607     }
 608   }
 609 };
 610 
 611 // Closure that applies the given two closures in sequence.
 612 class G1Mux2Closure : public OopClosure {
 613   OopClosure* _c1;
 614   OopClosure* _c2;
 615 public:
 616   G1Mux2Closure(OopClosure *c1, OopClosure *c2) { _c1 = c1; _c2 = c2; }
 617   template <class T> inline void do_oop_work(T* p) {
 618     // Apply first closure; then apply the second.
 619     _c1->do_oop(p);
 620     _c2->do_oop(p);
 621   }
 622   virtual inline void do_oop(oop* p) { do_oop_work(p); }
 623   virtual inline void do_oop(narrowOop* p) { do_oop_work(p); }
 624 };
 625 
 626 // This really ought to be commoned up into OffsetTableContigSpace somehow.
 627 // We would need a mechanism to make that code skip dead objects.
 628 
 629 void HeapRegion::verify(VerifyOption vo,
 630                         bool* failures) const {
 631   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 632   *failures = false;
 633   HeapWord* p = bottom();
 634   HeapWord* prev_p = NULL;
 635   VerifyLiveClosure vl_cl(g1, vo);
 636   VerifyRemSetClosure vr_cl(g1, vo);
 637   bool is_region_humongous = is_humongous();
 638   size_t object_num = 0;
 639   while (p < top()) {
 640     oop obj = oop(p);
 641     size_t obj_size = block_size(p);
 642     object_num += 1;
 643 
 644     if (!g1->is_obj_dead_cond(obj, this, vo)) {
 645       if (oopDesc::is_oop(obj)) {
 646         Klass* klass = obj->klass();
 647         bool is_metaspace_object = Metaspace::contains(klass) ||
 648                                    (vo == VerifyOption_G1UsePrevMarking &&
 649                                    ClassLoaderDataGraph::unload_list_contains(klass));
 650         if (!is_metaspace_object) {
 651           log_error(gc, verify)("klass " PTR_FORMAT " of object " PTR_FORMAT " "
 652                                 "not metadata", p2i(klass), p2i(obj));
 653           *failures = true;
 654           return;
 655         } else if (!klass->is_klass()) {
 656           log_error(gc, verify)("klass " PTR_FORMAT " of object " PTR_FORMAT " "
 657                                 "not a klass", p2i(klass), p2i(obj));
 658           *failures = true;
 659           return;
 660         } else {
 661           vl_cl.set_containing_obj(obj);
 662           if (!g1->collector_state()->full_collection() || G1VerifyRSetsDuringFullGC) {
 663             // verify liveness and rem_set
 664             vr_cl.set_containing_obj(obj);
 665             G1Mux2Closure mux(&vl_cl, &vr_cl);
 666             obj->oop_iterate_no_header(&mux);
 667 
 668             if (vr_cl.failures()) {
 669               *failures = true;
 670             }
 671             if (G1MaxVerifyFailures >= 0 &&
 672               vr_cl.n_failures() >= G1MaxVerifyFailures) {
 673               return;
 674             }
 675           } else {
 676             // verify only liveness
 677             obj->oop_iterate_no_header(&vl_cl);
 678           }
 679           if (vl_cl.failures()) {
 680             *failures = true;
 681           }
 682           if (G1MaxVerifyFailures >= 0 &&
 683               vl_cl.n_failures() >= G1MaxVerifyFailures) {
 684             return;
 685           }
 686         }
 687       } else {
 688         log_error(gc, verify)(PTR_FORMAT " not an oop", p2i(obj));
 689         *failures = true;
 690         return;
 691       }
 692     }
 693     prev_p = p;
 694     p += obj_size;
 695   }
 696 
 697   if (!is_young() && !is_empty()) {
 698     _bot_part.verify();
 699   }
 700 
 701   if (is_region_humongous) {
 702     oop obj = oop(this->humongous_start_region()->bottom());
 703     if ((HeapWord*)obj > bottom() || (HeapWord*)obj + obj->size() < bottom()) {
 704       log_error(gc, verify)("this humongous region is not part of its' humongous object " PTR_FORMAT, p2i(obj));
 705       *failures = true;
 706       return;
 707     }
 708   }
 709 
 710   if (!is_region_humongous && p != top()) {
 711     log_error(gc, verify)("end of last object " PTR_FORMAT " "
 712                           "does not match top " PTR_FORMAT, p2i(p), p2i(top()));
 713     *failures = true;
 714     return;
 715   }
 716 
 717   HeapWord* the_end = end();
 718   // Do some extra BOT consistency checking for addresses in the
 719   // range [top, end). BOT look-ups in this range should yield
 720   // top. No point in doing that if top == end (there's nothing there).
 721   if (p < the_end) {
 722     // Look up top
 723     HeapWord* addr_1 = p;
 724     HeapWord* b_start_1 = _bot_part.block_start_const(addr_1);
 725     if (b_start_1 != p) {
 726       log_error(gc, verify)("BOT look up for top: " PTR_FORMAT " "
 727                             " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 728                             p2i(addr_1), p2i(b_start_1), p2i(p));
 729       *failures = true;
 730       return;
 731     }
 732 
 733     // Look up top + 1
 734     HeapWord* addr_2 = p + 1;
 735     if (addr_2 < the_end) {
 736       HeapWord* b_start_2 = _bot_part.block_start_const(addr_2);
 737       if (b_start_2 != p) {
 738         log_error(gc, verify)("BOT look up for top + 1: " PTR_FORMAT " "
 739                               " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 740                               p2i(addr_2), p2i(b_start_2), p2i(p));
 741         *failures = true;
 742         return;
 743       }
 744     }
 745 
 746     // Look up an address between top and end
 747     size_t diff = pointer_delta(the_end, p) / 2;
 748     HeapWord* addr_3 = p + diff;
 749     if (addr_3 < the_end) {
 750       HeapWord* b_start_3 = _bot_part.block_start_const(addr_3);
 751       if (b_start_3 != p) {
 752         log_error(gc, verify)("BOT look up for top + diff: " PTR_FORMAT " "
 753                               " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 754                               p2i(addr_3), p2i(b_start_3), p2i(p));
 755         *failures = true;
 756         return;
 757       }
 758     }
 759 
 760     // Look up end - 1
 761     HeapWord* addr_4 = the_end - 1;
 762     HeapWord* b_start_4 = _bot_part.block_start_const(addr_4);
 763     if (b_start_4 != p) {
 764       log_error(gc, verify)("BOT look up for end - 1: " PTR_FORMAT " "
 765                             " yielded " PTR_FORMAT ", expecting " PTR_FORMAT,
 766                             p2i(addr_4), p2i(b_start_4), p2i(p));
 767       *failures = true;
 768       return;
 769     }
 770   }
 771 
 772   verify_strong_code_roots(vo, failures);
 773 }
 774 
 775 void HeapRegion::verify() const {
 776   bool dummy = false;
 777   verify(VerifyOption_G1UsePrevMarking, /* failures */ &dummy);
 778 }
 779 
 780 void HeapRegion::verify_rem_set(VerifyOption vo, bool* failures) const {
 781   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 782   *failures = false;
 783   HeapWord* p = bottom();
 784   HeapWord* prev_p = NULL;
 785   VerifyRemSetClosure vr_cl(g1, vo);
 786   while (p < top()) {
 787     oop obj = oop(p);
 788     size_t obj_size = block_size(p);
 789 
 790     if (!g1->is_obj_dead_cond(obj, this, vo)) {
 791       if (oopDesc::is_oop(obj)) {
 792         vr_cl.set_containing_obj(obj);
 793         obj->oop_iterate_no_header(&vr_cl);
 794 
 795         if (vr_cl.failures()) {
 796           *failures = true;
 797         }
 798         if (G1MaxVerifyFailures >= 0 &&
 799           vr_cl.n_failures() >= G1MaxVerifyFailures) {
 800           return;
 801         }
 802       } else {
 803         log_error(gc, verify)(PTR_FORMAT " not an oop", p2i(obj));
 804         *failures = true;
 805         return;
 806       }
 807     }
 808 
 809     prev_p = p;
 810     p += obj_size;
 811   }
 812 }
 813 
 814 void HeapRegion::verify_rem_set() const {
 815   bool failures = false;
 816   verify_rem_set(VerifyOption_G1UsePrevMarking, &failures);
 817   guarantee(!failures, "HeapRegion RemSet verification failed");
 818 }
 819 
 820 void HeapRegion::prepare_for_compaction(CompactPoint* cp) {
 821   // Not used for G1 anymore, but pure virtual in Space.
 822   ShouldNotReachHere();
 823 }
 824 
 825 // G1OffsetTableContigSpace code; copied from space.cpp.  Hope this can go
 826 // away eventually.
 827 
 828 void G1ContiguousSpace::clear(bool mangle_space) {
 829   set_top(bottom());
 830   CompactibleSpace::clear(mangle_space);
 831   reset_bot();
 832 }
 833 
 834 #ifndef PRODUCT
 835 void G1ContiguousSpace::mangle_unused_area() {
 836   mangle_unused_area_complete();
 837 }
 838 
 839 void G1ContiguousSpace::mangle_unused_area_complete() {
 840   SpaceMangler::mangle_region(MemRegion(top(), end()));
 841 }
 842 #endif
 843 
 844 void G1ContiguousSpace::print() const {
 845   print_short();
 846   tty->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", "
 847                 INTPTR_FORMAT ", " INTPTR_FORMAT ")",
 848                 p2i(bottom()), p2i(top()), p2i(_bot_part.threshold()), p2i(end()));
 849 }
 850 
 851 HeapWord* G1ContiguousSpace::initialize_threshold() {
 852   return _bot_part.initialize_threshold();
 853 }
 854 
 855 HeapWord* G1ContiguousSpace::cross_threshold(HeapWord* start,
 856                                                     HeapWord* end) {
 857   _bot_part.alloc_block(start, end);
 858   return _bot_part.threshold();
 859 }
 860 
 861 void G1ContiguousSpace::record_timestamp() {
 862   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 863   uint curr_gc_time_stamp = g1h->get_gc_time_stamp();
 864 
 865   if (_gc_time_stamp < curr_gc_time_stamp) {
 866     _gc_time_stamp = curr_gc_time_stamp;
 867   }
 868 }
 869 
 870 void G1ContiguousSpace::safe_object_iterate(ObjectClosure* blk) {
 871   object_iterate(blk);
 872 }
 873 
 874 void G1ContiguousSpace::object_iterate(ObjectClosure* blk) {
 875   HeapWord* p = bottom();
 876   while (p < top()) {
 877     if (block_is_obj(p)) {
 878       blk->do_object(oop(p));
 879     }
 880     p += block_size(p);
 881   }
 882 }
 883 
 884 G1ContiguousSpace::G1ContiguousSpace(G1BlockOffsetTable* bot) :
 885   _bot_part(bot, this),
 886   _par_alloc_lock(Mutex::leaf, "OffsetTableContigSpace par alloc lock", true),
 887   _gc_time_stamp(0)
 888 {
 889 }
 890 
 891 void G1ContiguousSpace::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
 892   CompactibleSpace::initialize(mr, clear_space, mangle_space);
 893   _top = bottom();
 894   set_saved_mark_word(NULL);
 895   reset_bot();
 896 }