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