1 /*
2  * Copyright (c) 2016, 2020, 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/g1CollectedHeap.inline.hpp"
29 #include "gc/g1/g1ConcurrentMarkThread.hpp"
30 #include "gc/g1/g1HeapVerifier.hpp"
31 #include "gc/g1/g1Policy.hpp"
32 #include "gc/g1/g1RemSet.hpp"
33 #include "gc/g1/g1RootProcessor.hpp"
34 #include "gc/g1/heapRegion.inline.hpp"
35 #include "gc/g1/heapRegionRemSet.hpp"
36 #include "gc/g1/g1StringDedup.hpp"
37 #include "logging/log.hpp"
38 #include "logging/logStream.hpp"
39 #include "memory/iterator.inline.hpp"
40 #include "memory/resourceArea.hpp"
41 #include "memory/universe.hpp"
42 #include "oops/access.inline.hpp"
43 #include "oops/compressedOops.inline.hpp"
44 #include "oops/oop.inline.hpp"
45 #include "runtime/handles.inline.hpp"
46 
47 int G1HeapVerifier::_enabled_verification_types = G1HeapVerifier::G1VerifyAll;
48 
49 class VerifyRootsClosure: public OopClosure {
50 private:
51   G1CollectedHeap* _g1h;
52   VerifyOption     _vo;
53   bool             _failures;
54 public:
55   // _vo == UsePrevMarking -> use "prev" marking information,
56   // _vo == UseNextMarking -> use "next" marking information,
57   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS
VerifyRootsClosure(VerifyOption vo)58   VerifyRootsClosure(VerifyOption vo) :
59     _g1h(G1CollectedHeap::heap()),
60     _vo(vo),
61     _failures(false) { }
62 
failures()63   bool failures() { return _failures; }
64 
do_oop_work(T * p)65   template <class T> void do_oop_work(T* p) {
66     T heap_oop = RawAccess<>::oop_load(p);
67     if (!CompressedOops::is_null(heap_oop)) {
68       oop obj = CompressedOops::decode_not_null(heap_oop);
69       if (_g1h->is_obj_dead_cond(obj, _vo)) {
70         Log(gc, verify) log;
71         log.error("Root location " PTR_FORMAT " points to dead obj " PTR_FORMAT " in region " HR_FORMAT,
72                   p2i(p), p2i(obj), HR_FORMAT_PARAMS(_g1h->heap_region_containing(obj)));
73         ResourceMark rm;
74         LogStream ls(log.error());
75         obj->print_on(&ls);
76         _failures = true;
77       }
78     }
79   }
80 
do_oop(oop * p)81   void do_oop(oop* p)       { do_oop_work(p); }
do_oop(narrowOop * p)82   void do_oop(narrowOop* p) { do_oop_work(p); }
83 };
84 
85 class G1VerifyCodeRootOopClosure: public OopClosure {
86   G1CollectedHeap* _g1h;
87   OopClosure* _root_cl;
88   nmethod* _nm;
89   VerifyOption _vo;
90   bool _failures;
91 
do_oop_work(T * p)92   template <class T> void do_oop_work(T* p) {
93     // First verify that this root is live
94     _root_cl->do_oop(p);
95 
96     if (!G1VerifyHeapRegionCodeRoots) {
97       // We're not verifying the code roots attached to heap region.
98       return;
99     }
100 
101     // Don't check the code roots during marking verification in a full GC
102     if (_vo == VerifyOption_G1UseFullMarking) {
103       return;
104     }
105 
106     // Now verify that the current nmethod (which contains p) is
107     // in the code root list of the heap region containing the
108     // object referenced by p.
109 
110     T heap_oop = RawAccess<>::oop_load(p);
111     if (!CompressedOops::is_null(heap_oop)) {
112       oop obj = CompressedOops::decode_not_null(heap_oop);
113 
114       // Now fetch the region containing the object
115       HeapRegion* hr = _g1h->heap_region_containing(obj);
116       HeapRegionRemSet* hrrs = hr->rem_set();
117       // Verify that the strong code root list for this region
118       // contains the nmethod
119       if (!hrrs->strong_code_roots_list_contains(_nm)) {
120         log_error(gc, verify)("Code root location " PTR_FORMAT " "
121                               "from nmethod " PTR_FORMAT " not in strong "
122                               "code roots for region [" PTR_FORMAT "," PTR_FORMAT ")",
123                               p2i(p), p2i(_nm), p2i(hr->bottom()), p2i(hr->end()));
124         _failures = true;
125       }
126     }
127   }
128 
129 public:
G1VerifyCodeRootOopClosure(G1CollectedHeap * g1h,OopClosure * root_cl,VerifyOption vo)130   G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
131     _g1h(g1h), _root_cl(root_cl), _nm(NULL), _vo(vo), _failures(false) {}
132 
do_oop(oop * p)133   void do_oop(oop* p) { do_oop_work(p); }
do_oop(narrowOop * p)134   void do_oop(narrowOop* p) { do_oop_work(p); }
135 
set_nmethod(nmethod * nm)136   void set_nmethod(nmethod* nm) { _nm = nm; }
failures()137   bool failures() { return _failures; }
138 };
139 
140 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
141   G1VerifyCodeRootOopClosure* _oop_cl;
142 
143 public:
G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure * oop_cl)144   G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
145     _oop_cl(oop_cl) {}
146 
do_code_blob(CodeBlob * cb)147   void do_code_blob(CodeBlob* cb) {
148     nmethod* nm = cb->as_nmethod_or_null();
149     if (nm != NULL) {
150       _oop_cl->set_nmethod(nm);
151       nm->oops_do(_oop_cl);
152     }
153   }
154 };
155 
156 class YoungRefCounterClosure : public OopClosure {
157   G1CollectedHeap* _g1h;
158   int              _count;
159  public:
YoungRefCounterClosure(G1CollectedHeap * g1h)160   YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
do_oop(oop * p)161   void do_oop(oop* p)       { if (_g1h->is_in_young(*p)) { _count++; } }
do_oop(narrowOop * p)162   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
163 
count()164   int count() { return _count; }
reset_count()165   void reset_count() { _count = 0; };
166 };
167 
168 class VerifyCLDClosure: public CLDClosure {
169   YoungRefCounterClosure _young_ref_counter_closure;
170   OopClosure *_oop_closure;
171  public:
VerifyCLDClosure(G1CollectedHeap * g1h,OopClosure * cl)172   VerifyCLDClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
do_cld(ClassLoaderData * cld)173   void do_cld(ClassLoaderData* cld) {
174     cld->oops_do(_oop_closure, ClassLoaderData::_claim_none);
175 
176     _young_ref_counter_closure.reset_count();
177     cld->oops_do(&_young_ref_counter_closure, ClassLoaderData::_claim_none);
178     if (_young_ref_counter_closure.count() > 0) {
179       guarantee(cld->has_modified_oops(), "CLD " PTR_FORMAT ", has young %d refs but is not dirty.", p2i(cld), _young_ref_counter_closure.count());
180     }
181   }
182 };
183 
184 class VerifyLivenessOopClosure: public BasicOopIterateClosure {
185   G1CollectedHeap* _g1h;
186   VerifyOption _vo;
187 public:
VerifyLivenessOopClosure(G1CollectedHeap * g1h,VerifyOption vo)188   VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
189     _g1h(g1h), _vo(vo)
190   { }
do_oop(narrowOop * p)191   void do_oop(narrowOop *p) { do_oop_work(p); }
do_oop(oop * p)192   void do_oop(      oop *p) { do_oop_work(p); }
193 
do_oop_work(T * p)194   template <class T> void do_oop_work(T *p) {
195     oop obj = RawAccess<>::oop_load(p);
196     guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
197               "Dead object referenced by a not dead object");
198   }
199 };
200 
201 class VerifyObjsInRegionClosure: public ObjectClosure {
202 private:
203   G1CollectedHeap* _g1h;
204   size_t _live_bytes;
205   HeapRegion *_hr;
206   VerifyOption _vo;
207 public:
208   // _vo == UsePrevMarking -> use "prev" marking information,
209   // _vo == UseNextMarking -> use "next" marking information,
210   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS.
VerifyObjsInRegionClosure(HeapRegion * hr,VerifyOption vo)211   VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
212     : _live_bytes(0), _hr(hr), _vo(vo) {
213     _g1h = G1CollectedHeap::heap();
214   }
do_object(oop o)215   void do_object(oop o) {
216     VerifyLivenessOopClosure isLive(_g1h, _vo);
217     assert(o != NULL, "Huh?");
218     if (!_g1h->is_obj_dead_cond(o, _vo)) {
219       // If the object is alive according to the full gc mark,
220       // then verify that the marking information agrees.
221       // Note we can't verify the contra-positive of the
222       // above: if the object is dead (according to the mark
223       // word), it may not be marked, or may have been marked
224       // but has since became dead, or may have been allocated
225       // since the last marking.
226       if (_vo == VerifyOption_G1UseFullMarking) {
227         guarantee(!_g1h->is_obj_dead(o), "Full GC marking and concurrent mark mismatch");
228       }
229 
230       o->oop_iterate(&isLive);
231       if (!_hr->obj_allocated_since_prev_marking(o)) {
232         size_t obj_size = o->size();    // Make sure we don't overflow
233         _live_bytes += (obj_size * HeapWordSize);
234       }
235     }
236   }
live_bytes()237   size_t live_bytes() { return _live_bytes; }
238 };
239 
240 class VerifyArchiveOopClosure: public BasicOopIterateClosure {
241   HeapRegion* _hr;
242 public:
VerifyArchiveOopClosure(HeapRegion * hr)243   VerifyArchiveOopClosure(HeapRegion *hr) : _hr(hr) { }
do_oop(narrowOop * p)244   void do_oop(narrowOop *p) { do_oop_work(p); }
do_oop(oop * p)245   void do_oop(      oop *p) { do_oop_work(p); }
246 
do_oop_work(T * p)247   template <class T> void do_oop_work(T *p) {
248     oop obj = RawAccess<>::oop_load(p);
249 
250     if (_hr->is_open_archive()) {
251       guarantee(obj == NULL || G1CollectedHeap::heap()->heap_region_containing(obj)->is_archive(),
252                 "Archive object at " PTR_FORMAT " references a non-archive object at " PTR_FORMAT,
253                 p2i(p), p2i(obj));
254     } else {
255       assert(_hr->is_closed_archive(), "should be closed archive region");
256       guarantee(obj == NULL || G1CollectedHeap::heap()->heap_region_containing(obj)->is_closed_archive(),
257                 "Archive object at " PTR_FORMAT " references a non-archive object at " PTR_FORMAT,
258                 p2i(p), p2i(obj));
259     }
260   }
261 };
262 
263 class VerifyObjectInArchiveRegionClosure: public ObjectClosure {
264   HeapRegion* _hr;
265 public:
VerifyObjectInArchiveRegionClosure(HeapRegion * hr,bool verbose)266   VerifyObjectInArchiveRegionClosure(HeapRegion *hr, bool verbose)
267     : _hr(hr) { }
268   // Verify that all object pointers are to archive regions.
do_object(oop o)269   void do_object(oop o) {
270     VerifyArchiveOopClosure checkOop(_hr);
271     assert(o != NULL, "Should not be here for NULL oops");
272     o->oop_iterate(&checkOop);
273   }
274 };
275 
276 // Should be only used at CDS dump time
277 class VerifyReadyForArchivingRegionClosure : public HeapRegionClosure {
278   bool _seen_free;
279   bool _has_holes;
280   bool _has_unexpected_holes;
281   bool _has_humongous;
282 public:
has_holes()283   bool has_holes() {return _has_holes;}
has_unexpected_holes()284   bool has_unexpected_holes() {return _has_unexpected_holes;}
has_humongous()285   bool has_humongous() {return _has_humongous;}
286 
VerifyReadyForArchivingRegionClosure()287   VerifyReadyForArchivingRegionClosure() : HeapRegionClosure() {
288     _seen_free = false;
289     _has_holes = false;
290     _has_unexpected_holes = false;
291     _has_humongous = false;
292   }
do_heap_region(HeapRegion * hr)293   virtual bool do_heap_region(HeapRegion* hr) {
294     const char* hole = "";
295 
296     if (hr->is_free()) {
297       _seen_free = true;
298     } else {
299       if (_seen_free) {
300         _has_holes = true;
301         if (hr->is_humongous()) {
302           hole = " hole";
303         } else {
304           _has_unexpected_holes = true;
305           hole = " hole **** unexpected ****";
306         }
307       }
308     }
309     if (hr->is_humongous()) {
310       _has_humongous = true;
311     }
312     log_info(gc, region, cds)("HeapRegion " INTPTR_FORMAT " %s%s", p2i(hr->bottom()), hr->get_type_str(), hole);
313     return false;
314   }
315 };
316 
317 // We want all used regions to be moved to the bottom-end of the heap, so we have
318 // a contiguous range of free regions at the top end of the heap. This way, we can
319 // avoid fragmentation while allocating the archive regions.
320 //
321 // Before calling this, a full GC should have been executed with a single worker thread,
322 // so that no old regions would be moved to the middle of the heap.
verify_ready_for_archiving()323 void G1HeapVerifier::verify_ready_for_archiving() {
324   VerifyReadyForArchivingRegionClosure cl;
325   G1CollectedHeap::heap()->heap_region_iterate(&cl);
326   if (cl.has_holes()) {
327     log_warning(gc, verify)("All free regions should be at the top end of the heap, but"
328                             " we found holes. This is probably caused by (unmovable) humongous"
329                             " allocations or active GCLocker, and may lead to fragmentation while"
330                             " writing archive heap memory regions.");
331   }
332   if (cl.has_humongous()) {
333     log_warning(gc, verify)("(Unmovable) humongous regions have been found and"
334                             " may lead to fragmentation while"
335                             " writing archive heap memory regions.");
336   }
337 }
338 
339 class VerifyArchivePointerRegionClosure: public HeapRegionClosure {
do_heap_region(HeapRegion * r)340   virtual bool do_heap_region(HeapRegion* r) {
341    if (r->is_archive()) {
342       VerifyObjectInArchiveRegionClosure verify_oop_pointers(r, false);
343       r->object_iterate(&verify_oop_pointers);
344     }
345     return false;
346   }
347 };
348 
verify_archive_regions()349 void G1HeapVerifier::verify_archive_regions() {
350   G1CollectedHeap*  g1h = G1CollectedHeap::heap();
351   VerifyArchivePointerRegionClosure cl;
352   g1h->heap_region_iterate(&cl);
353 }
354 
355 class VerifyRegionClosure: public HeapRegionClosure {
356 private:
357   bool             _par;
358   VerifyOption     _vo;
359   bool             _failures;
360 public:
361   // _vo == UsePrevMarking -> use "prev" marking information,
362   // _vo == UseNextMarking -> use "next" marking information,
363   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS
VerifyRegionClosure(bool par,VerifyOption vo)364   VerifyRegionClosure(bool par, VerifyOption vo)
365     : _par(par),
366       _vo(vo),
367       _failures(false) {}
368 
failures()369   bool failures() {
370     return _failures;
371   }
372 
do_heap_region(HeapRegion * r)373   bool do_heap_region(HeapRegion* r) {
374     guarantee(!r->has_index_in_opt_cset(), "Region %u still has opt collection set index %u", r->hrm_index(), r->index_in_opt_cset());
375     guarantee(!r->is_young() || r->rem_set()->is_complete(), "Remembered set for Young region %u must be complete, is %s", r->hrm_index(), r->rem_set()->get_state_str());
376     // Humongous and old regions regions might be of any state, so can't check here.
377     guarantee(!r->is_free() || !r->rem_set()->is_tracked(), "Remembered set for free region %u must be untracked, is %s", r->hrm_index(), r->rem_set()->get_state_str());
378     // Verify that the continues humongous regions' remembered set state matches the
379     // one from the starts humongous region.
380     if (r->is_continues_humongous()) {
381       if (r->rem_set()->get_state_str() != r->humongous_start_region()->rem_set()->get_state_str()) {
382          log_error(gc, verify)("Remset states differ: Region %u (%s) remset %s with starts region %u (%s) remset %s",
383                                r->hrm_index(),
384                                r->get_short_type_str(),
385                                r->rem_set()->get_state_str(),
386                                r->humongous_start_region()->hrm_index(),
387                                r->humongous_start_region()->get_short_type_str(),
388                                r->humongous_start_region()->rem_set()->get_state_str());
389          _failures = true;
390       }
391     }
392     // For archive regions, verify there are no heap pointers to
393     // non-pinned regions. For all others, verify liveness info.
394     if (r->is_closed_archive()) {
395       VerifyObjectInArchiveRegionClosure verify_oop_pointers(r, false);
396       r->object_iterate(&verify_oop_pointers);
397       return true;
398     } else if (r->is_open_archive()) {
399       VerifyObjsInRegionClosure verify_open_archive_oop(r, _vo);
400       r->object_iterate(&verify_open_archive_oop);
401       return true;
402     } else if (!r->is_continues_humongous()) {
403       bool failures = false;
404       r->verify(_vo, &failures);
405       if (failures) {
406         _failures = true;
407       } else if (!r->is_starts_humongous()) {
408         VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
409         r->object_iterate(&not_dead_yet_cl);
410         if (_vo != VerifyOption_G1UseNextMarking) {
411           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
412             log_error(gc, verify)("[" PTR_FORMAT "," PTR_FORMAT "] max_live_bytes " SIZE_FORMAT " < calculated " SIZE_FORMAT,
413                                   p2i(r->bottom()), p2i(r->end()), r->max_live_bytes(), not_dead_yet_cl.live_bytes());
414             _failures = true;
415           }
416         } else {
417           // When vo == UseNextMarking we cannot currently do a sanity
418           // check on the live bytes as the calculation has not been
419           // finalized yet.
420         }
421       }
422     }
423     return false; // stop the region iteration if we hit a failure
424   }
425 };
426 
427 // This is the task used for parallel verification of the heap regions
428 
429 class G1ParVerifyTask: public AbstractGangTask {
430 private:
431   G1CollectedHeap*  _g1h;
432   VerifyOption      _vo;
433   bool              _failures;
434   HeapRegionClaimer _hrclaimer;
435 
436 public:
437   // _vo == UsePrevMarking -> use "prev" marking information,
438   // _vo == UseNextMarking -> use "next" marking information,
439   // _vo == UseFullMarking -> use "next" marking bitmap but no TAMS
G1ParVerifyTask(G1CollectedHeap * g1h,VerifyOption vo)440   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
441       AbstractGangTask("Parallel verify task"),
442       _g1h(g1h),
443       _vo(vo),
444       _failures(false),
445       _hrclaimer(g1h->workers()->active_workers()) {}
446 
failures()447   bool failures() {
448     return _failures;
449   }
450 
work(uint worker_id)451   void work(uint worker_id) {
452     VerifyRegionClosure blk(true, _vo);
453     _g1h->heap_region_par_iterate_from_worker_offset(&blk, &_hrclaimer, worker_id);
454     if (blk.failures()) {
455       _failures = true;
456     }
457   }
458 };
459 
enable_verification_type(G1VerifyType type)460 void G1HeapVerifier::enable_verification_type(G1VerifyType type) {
461   // First enable will clear _enabled_verification_types.
462   if (_enabled_verification_types == G1VerifyAll) {
463     _enabled_verification_types = type;
464   } else {
465     _enabled_verification_types |= type;
466   }
467 }
468 
should_verify(G1VerifyType type)469 bool G1HeapVerifier::should_verify(G1VerifyType type) {
470   return (_enabled_verification_types & type) == type;
471 }
472 
verify(VerifyOption vo)473 void G1HeapVerifier::verify(VerifyOption vo) {
474   assert_at_safepoint_on_vm_thread();
475   assert(Heap_lock->is_locked(), "heap must be locked");
476 
477   log_debug(gc, verify)("Roots");
478   VerifyRootsClosure rootsCl(vo);
479   VerifyCLDClosure cldCl(_g1h, &rootsCl);
480 
481   // We apply the relevant closures to all the oops in the
482   // system dictionary, class loader data graph, the string table
483   // and the nmethods in the code cache.
484   G1VerifyCodeRootOopClosure codeRootsCl(_g1h, &rootsCl, vo);
485   G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
486 
487   {
488     G1RootProcessor root_processor(_g1h, 1);
489     root_processor.process_all_roots(&rootsCl, &cldCl, &blobsCl);
490   }
491 
492   bool failures = rootsCl.failures() || codeRootsCl.failures();
493 
494   if (!_g1h->policy()->collector_state()->in_full_gc()) {
495     // If we're verifying during a full GC then the region sets
496     // will have been torn down at the start of the GC. Therefore
497     // verifying the region sets will fail. So we only verify
498     // the region sets when not in a full GC.
499     log_debug(gc, verify)("HeapRegionSets");
500     verify_region_sets();
501   }
502 
503   log_debug(gc, verify)("HeapRegions");
504   if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
505 
506     G1ParVerifyTask task(_g1h, vo);
507     _g1h->workers()->run_task(&task);
508     if (task.failures()) {
509       failures = true;
510     }
511 
512   } else {
513     VerifyRegionClosure blk(false, vo);
514     _g1h->heap_region_iterate(&blk);
515     if (blk.failures()) {
516       failures = true;
517     }
518   }
519 
520   if (G1StringDedup::is_enabled()) {
521     log_debug(gc, verify)("StrDedup");
522     G1StringDedup::verify();
523   }
524 
525   if (failures) {
526     log_error(gc, verify)("Heap after failed verification (kind %d):", vo);
527     // It helps to have the per-region information in the output to
528     // help us track down what went wrong. This is why we call
529     // print_extended_on() instead of print_on().
530     Log(gc, verify) log;
531     ResourceMark rm;
532     LogStream ls(log.error());
533     _g1h->print_extended_on(&ls);
534   }
535   guarantee(!failures, "there should not have been any failures");
536 }
537 
538 // Heap region set verification
539 
540 class VerifyRegionListsClosure : public HeapRegionClosure {
541 private:
542   HeapRegionSet*   _old_set;
543   HeapRegionSet*   _archive_set;
544   HeapRegionSet*   _humongous_set;
545   HeapRegionManager* _hrm;
546 
547 public:
548   uint _old_count;
549   uint _archive_count;
550   uint _humongous_count;
551   uint _free_count;
552 
VerifyRegionListsClosure(HeapRegionSet * old_set,HeapRegionSet * archive_set,HeapRegionSet * humongous_set,HeapRegionManager * hrm)553   VerifyRegionListsClosure(HeapRegionSet* old_set,
554                            HeapRegionSet* archive_set,
555                            HeapRegionSet* humongous_set,
556                            HeapRegionManager* hrm) :
557     _old_set(old_set), _archive_set(archive_set), _humongous_set(humongous_set), _hrm(hrm),
558     _old_count(), _archive_count(), _humongous_count(), _free_count(){ }
559 
do_heap_region(HeapRegion * hr)560   bool do_heap_region(HeapRegion* hr) {
561     if (hr->is_young()) {
562       // TODO
563     } else if (hr->is_humongous()) {
564       assert(hr->containing_set() == _humongous_set, "Heap region %u is humongous but not in humongous set.", hr->hrm_index());
565       _humongous_count++;
566     } else if (hr->is_empty()) {
567       assert(_hrm->is_free(hr), "Heap region %u is empty but not on the free list.", hr->hrm_index());
568       _free_count++;
569     } else if (hr->is_archive()) {
570       assert(hr->containing_set() == _archive_set, "Heap region %u is archive but not in the archive set.", hr->hrm_index());
571       _archive_count++;
572     } else if (hr->is_old()) {
573       assert(hr->containing_set() == _old_set, "Heap region %u is old but not in the old set.", hr->hrm_index());
574       _old_count++;
575     } else {
576       // There are no other valid region types. Check for one invalid
577       // one we can identify: pinned without old or humongous set.
578       assert(!hr->is_pinned(), "Heap region %u is pinned but not old (archive) or humongous.", hr->hrm_index());
579       ShouldNotReachHere();
580     }
581     return false;
582   }
583 
verify_counts(HeapRegionSet * old_set,HeapRegionSet * archive_set,HeapRegionSet * humongous_set,HeapRegionManager * free_list)584   void verify_counts(HeapRegionSet* old_set, HeapRegionSet* archive_set, HeapRegionSet* humongous_set, HeapRegionManager* free_list) {
585     guarantee(old_set->length() == _old_count, "Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count);
586     guarantee(archive_set->length() == _archive_count, "Archive set count mismatch. Expected %u, actual %u.", archive_set->length(), _archive_count);
587     guarantee(humongous_set->length() == _humongous_count, "Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count);
588     guarantee(free_list->num_free_regions() == _free_count, "Free list count mismatch. Expected %u, actual %u.", free_list->num_free_regions(), _free_count);
589   }
590 };
591 
verify_region_sets()592 void G1HeapVerifier::verify_region_sets() {
593   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
594 
595   // First, check the explicit lists.
596   _g1h->_hrm.verify();
597 
598   // Finally, make sure that the region accounting in the lists is
599   // consistent with what we see in the heap.
600 
601   VerifyRegionListsClosure cl(&_g1h->_old_set, &_g1h->_archive_set, &_g1h->_humongous_set, &_g1h->_hrm);
602   _g1h->heap_region_iterate(&cl);
603   cl.verify_counts(&_g1h->_old_set, &_g1h->_archive_set, &_g1h->_humongous_set, &_g1h->_hrm);
604 }
605 
prepare_for_verify()606 void G1HeapVerifier::prepare_for_verify() {
607   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
608     _g1h->ensure_parsability(false);
609   }
610 }
611 
verify(G1VerifyType type,VerifyOption vo,const char * msg)612 double G1HeapVerifier::verify(G1VerifyType type, VerifyOption vo, const char* msg) {
613   double verify_time_ms = 0.0;
614 
615   if (should_verify(type) && _g1h->total_collections() >= VerifyGCStartAt) {
616     double verify_start = os::elapsedTime();
617     prepare_for_verify();
618     Universe::verify(vo, msg);
619     verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
620   }
621 
622   return verify_time_ms;
623 }
624 
verify_before_gc(G1VerifyType type)625 void G1HeapVerifier::verify_before_gc(G1VerifyType type) {
626   if (VerifyBeforeGC) {
627     double verify_time_ms = verify(type, VerifyOption_G1UsePrevMarking, "Before GC");
628     _g1h->phase_times()->record_verify_before_time_ms(verify_time_ms);
629   }
630 }
631 
verify_after_gc(G1VerifyType type)632 void G1HeapVerifier::verify_after_gc(G1VerifyType type) {
633   if (VerifyAfterGC) {
634     double verify_time_ms = verify(type, VerifyOption_G1UsePrevMarking, "After GC");
635     _g1h->phase_times()->record_verify_after_time_ms(verify_time_ms);
636   }
637 }
638 
639 
640 #ifndef PRODUCT
641 class G1VerifyCardTableCleanup: public HeapRegionClosure {
642   G1HeapVerifier* _verifier;
643 public:
G1VerifyCardTableCleanup(G1HeapVerifier * verifier)644   G1VerifyCardTableCleanup(G1HeapVerifier* verifier)
645     : _verifier(verifier) { }
do_heap_region(HeapRegion * r)646   virtual bool do_heap_region(HeapRegion* r) {
647     if (r->is_survivor()) {
648       _verifier->verify_dirty_region(r);
649     } else {
650       _verifier->verify_not_dirty_region(r);
651     }
652     return false;
653   }
654 };
655 
verify_card_table_cleanup()656 void G1HeapVerifier::verify_card_table_cleanup() {
657   if (G1VerifyCTCleanup || VerifyAfterGC) {
658     G1VerifyCardTableCleanup cleanup_verifier(this);
659     _g1h->heap_region_iterate(&cleanup_verifier);
660   }
661 }
662 
verify_not_dirty_region(HeapRegion * hr)663 void G1HeapVerifier::verify_not_dirty_region(HeapRegion* hr) {
664   // All of the region should be clean.
665   G1CardTable* ct = _g1h->card_table();
666   MemRegion mr(hr->bottom(), hr->end());
667   ct->verify_not_dirty_region(mr);
668 }
669 
verify_dirty_region(HeapRegion * hr)670 void G1HeapVerifier::verify_dirty_region(HeapRegion* hr) {
671   // We cannot guarantee that [bottom(),end()] is dirty.  Threads
672   // dirty allocated blocks as they allocate them. The thread that
673   // retires each region and replaces it with a new one will do a
674   // maximal allocation to fill in [pre_dummy_top(),end()] but will
675   // not dirty that area (one less thing to have to do while holding
676   // a lock). So we can only verify that [bottom(),pre_dummy_top()]
677   // is dirty.
678   G1CardTable* ct = _g1h->card_table();
679   MemRegion mr(hr->bottom(), hr->pre_dummy_top());
680   if (hr->is_young()) {
681     ct->verify_g1_young_region(mr);
682   } else {
683     ct->verify_dirty_region(mr);
684   }
685 }
686 
687 class G1VerifyDirtyYoungListClosure : public HeapRegionClosure {
688 private:
689   G1HeapVerifier* _verifier;
690 public:
G1VerifyDirtyYoungListClosure(G1HeapVerifier * verifier)691   G1VerifyDirtyYoungListClosure(G1HeapVerifier* verifier) : HeapRegionClosure(), _verifier(verifier) { }
do_heap_region(HeapRegion * r)692   virtual bool do_heap_region(HeapRegion* r) {
693     _verifier->verify_dirty_region(r);
694     return false;
695   }
696 };
697 
verify_dirty_young_regions()698 void G1HeapVerifier::verify_dirty_young_regions() {
699   G1VerifyDirtyYoungListClosure cl(this);
700   _g1h->collection_set()->iterate(&cl);
701 }
702 
verify_no_bits_over_tams(const char * bitmap_name,const G1CMBitMap * const bitmap,HeapWord * tams,HeapWord * end)703 bool G1HeapVerifier::verify_no_bits_over_tams(const char* bitmap_name, const G1CMBitMap* const bitmap,
704                                                HeapWord* tams, HeapWord* end) {
705   guarantee(tams <= end,
706             "tams: " PTR_FORMAT " end: " PTR_FORMAT, p2i(tams), p2i(end));
707   HeapWord* result = bitmap->get_next_marked_addr(tams, end);
708   if (result < end) {
709     log_error(gc, verify)("## wrong marked address on %s bitmap: " PTR_FORMAT, bitmap_name, p2i(result));
710     log_error(gc, verify)("## %s tams: " PTR_FORMAT " end: " PTR_FORMAT, bitmap_name, p2i(tams), p2i(end));
711     return false;
712   }
713   return true;
714 }
715 
verify_bitmaps(const char * caller,HeapRegion * hr)716 bool G1HeapVerifier::verify_bitmaps(const char* caller, HeapRegion* hr) {
717   const G1CMBitMap* const prev_bitmap = _g1h->concurrent_mark()->prev_mark_bitmap();
718   const G1CMBitMap* const next_bitmap = _g1h->concurrent_mark()->next_mark_bitmap();
719 
720   HeapWord* ptams  = hr->prev_top_at_mark_start();
721   HeapWord* ntams  = hr->next_top_at_mark_start();
722   HeapWord* end    = hr->end();
723 
724   bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);
725 
726   bool res_n = true;
727   // We cannot verify the next bitmap while we are about to clear it.
728   if (!_g1h->collector_state()->clearing_next_bitmap()) {
729     res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
730   }
731   if (!res_p || !res_n) {
732     log_error(gc, verify)("#### Bitmap verification failed for " HR_FORMAT, HR_FORMAT_PARAMS(hr));
733     log_error(gc, verify)("#### Caller: %s", caller);
734     return false;
735   }
736   return true;
737 }
738 
check_bitmaps(const char * caller,HeapRegion * hr)739 void G1HeapVerifier::check_bitmaps(const char* caller, HeapRegion* hr) {
740   if (!G1VerifyBitmaps) {
741     return;
742   }
743 
744   guarantee(verify_bitmaps(caller, hr), "bitmap verification");
745 }
746 
747 class G1VerifyBitmapClosure : public HeapRegionClosure {
748 private:
749   const char* _caller;
750   G1HeapVerifier* _verifier;
751   bool _failures;
752 
753 public:
G1VerifyBitmapClosure(const char * caller,G1HeapVerifier * verifier)754   G1VerifyBitmapClosure(const char* caller, G1HeapVerifier* verifier) :
755     _caller(caller), _verifier(verifier), _failures(false) { }
756 
failures()757   bool failures() { return _failures; }
758 
do_heap_region(HeapRegion * hr)759   virtual bool do_heap_region(HeapRegion* hr) {
760     bool result = _verifier->verify_bitmaps(_caller, hr);
761     if (!result) {
762       _failures = true;
763     }
764     return false;
765   }
766 };
767 
check_bitmaps(const char * caller)768 void G1HeapVerifier::check_bitmaps(const char* caller) {
769   if (!G1VerifyBitmaps) {
770     return;
771   }
772 
773   G1VerifyBitmapClosure cl(caller, this);
774   _g1h->heap_region_iterate(&cl);
775   guarantee(!cl.failures(), "bitmap verification");
776 }
777 
778 class G1CheckRegionAttrTableClosure : public HeapRegionClosure {
779 private:
780   bool _failures;
781 
782 public:
G1CheckRegionAttrTableClosure()783   G1CheckRegionAttrTableClosure() : HeapRegionClosure(), _failures(false) { }
784 
do_heap_region(HeapRegion * hr)785   virtual bool do_heap_region(HeapRegion* hr) {
786     uint i = hr->hrm_index();
787     G1HeapRegionAttr region_attr = (G1HeapRegionAttr) G1CollectedHeap::heap()->_region_attr.get_by_index(i);
788     if (hr->is_humongous()) {
789       if (hr->in_collection_set()) {
790         log_error(gc, verify)("## humongous region %u in CSet", i);
791         _failures = true;
792         return true;
793       }
794       if (region_attr.is_in_cset()) {
795         log_error(gc, verify)("## inconsistent region attr type %s for humongous region %u", region_attr.get_type_str(), i);
796         _failures = true;
797         return true;
798       }
799       if (hr->is_continues_humongous() && region_attr.is_humongous()) {
800         log_error(gc, verify)("## inconsistent region attr type %s for continues humongous region %u", region_attr.get_type_str(), i);
801         _failures = true;
802         return true;
803       }
804     } else {
805       if (region_attr.is_humongous()) {
806         log_error(gc, verify)("## inconsistent region attr type %s for non-humongous region %u", region_attr.get_type_str(), i);
807         _failures = true;
808         return true;
809       }
810       if (hr->in_collection_set() != region_attr.is_in_cset()) {
811         log_error(gc, verify)("## in CSet %d / region attr type %s inconsistency for region %u",
812                              hr->in_collection_set(), region_attr.get_type_str(), i);
813         _failures = true;
814         return true;
815       }
816       if (region_attr.is_in_cset()) {
817         if (hr->is_archive()) {
818           log_error(gc, verify)("## is_archive in collection set for region %u", i);
819           _failures = true;
820           return true;
821         }
822         if (hr->is_young() != (region_attr.is_young())) {
823           log_error(gc, verify)("## is_young %d / region attr type %s inconsistency for region %u",
824                                hr->is_young(), region_attr.get_type_str(), i);
825           _failures = true;
826           return true;
827         }
828         if (hr->is_old() != (region_attr.is_old())) {
829           log_error(gc, verify)("## is_old %d / region attr type %s inconsistency for region %u",
830                                hr->is_old(), region_attr.get_type_str(), i);
831           _failures = true;
832           return true;
833         }
834       }
835     }
836     return false;
837   }
838 
failures() const839   bool failures() const { return _failures; }
840 };
841 
check_region_attr_table()842 bool G1HeapVerifier::check_region_attr_table() {
843   G1CheckRegionAttrTableClosure cl;
844   _g1h->_hrm.iterate(&cl);
845   return !cl.failures();
846 }
847 #endif // PRODUCT
848