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