1 /*
  2  * Copyright (c) 2017, 2021, Red Hat, Inc. 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 "gc/shared/tlab_globals.hpp"
 27 #include "gc/shenandoah/shenandoahAsserts.hpp"
 28 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
 29 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
 30 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 31 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
 32 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
 33 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp"
 34 #include "gc/shenandoah/shenandoahUtils.hpp"
 35 #include "gc/shenandoah/shenandoahVerifier.hpp"
 36 #include "memory/allocation.hpp"
 37 #include "memory/iterator.inline.hpp"
 38 #include "memory/resourceArea.hpp"
 39 #include "oops/compressedOops.inline.hpp"
 40 #include "runtime/atomic.hpp"
 41 #include "runtime/orderAccess.hpp"
 42 #include "runtime/threads.hpp"
 43 #include "utilities/align.hpp"
 44 
 45 // Avoid name collision on verify_oop (defined in macroAssembler_arm.hpp)
 46 #ifdef verify_oop
 47 #undef verify_oop
 48 #endif
 49 
 50 static bool is_instance_ref_klass(Klass* k) {
 51   return k->is_instance_klass() && InstanceKlass::cast(k)->reference_type() != REF_NONE;
 52 }
 53 
 54 class ShenandoahIgnoreReferenceDiscoverer : public ReferenceDiscoverer {
 55 public:
 56   virtual bool discover_reference(oop obj, ReferenceType type) {
 57     return true;
 58   }
 59 };
 60 
 61 class ShenandoahVerifyOopClosure : public BasicOopIterateClosure {
 62 private:
 63   const char* _phase;
 64   ShenandoahVerifier::VerifyOptions _options;
 65   ShenandoahVerifierStack* _stack;
 66   ShenandoahHeap* _heap;
 67   MarkBitMap* _map;
 68   ShenandoahLivenessData* _ld;
 69   void* _interior_loc;
 70   oop _loc;
 71 
 72 public:
 73   ShenandoahVerifyOopClosure(ShenandoahVerifierStack* stack, MarkBitMap* map, ShenandoahLivenessData* ld,
 74                              const char* phase, ShenandoahVerifier::VerifyOptions options) :
 75     _phase(phase),
 76     _options(options),
 77     _stack(stack),
 78     _heap(ShenandoahHeap::heap()),
 79     _map(map),
 80     _ld(ld),
 81     _interior_loc(nullptr),
 82     _loc(nullptr) {
 83     if (options._verify_marked == ShenandoahVerifier::_verify_marked_complete_except_references ||
 84         options._verify_marked == ShenandoahVerifier::_verify_marked_disable) {
 85       set_ref_discoverer_internal(new ShenandoahIgnoreReferenceDiscoverer());
 86     }
 87   }
 88 
 89 private:
 90   void check(ShenandoahAsserts::SafeLevel level, oop obj, bool test, const char* label) {
 91     if (!test) {
 92       ShenandoahAsserts::print_failure(level, obj, _interior_loc, _loc, _phase, label, __FILE__, __LINE__);
 93     }
 94   }
 95 
 96   template <class T>
 97   void do_oop_work(T* p) {
 98     T o = RawAccess<>::oop_load(p);
 99     if (!CompressedOops::is_null(o)) {
100       oop obj = CompressedOops::decode_not_null(o);
101       if (is_instance_ref_klass(obj->forward_safe_klass())) {
102         obj = ShenandoahForwarding::get_forwardee(obj);
103       }
104       // Single threaded verification can use faster non-atomic stack and bitmap
105       // methods.
106       //
107       // For performance reasons, only fully verify non-marked field values.
108       // We are here when the host object for *p is already marked.
109 
110       if (_map->par_mark(obj)) {
111         verify_oop_at(p, obj);
112         _stack->push(ShenandoahVerifierTask(obj));
113       }
114     }
115   }
116 
117   void verify_oop(oop obj) {
118     // Perform consistency checks with gradually decreasing safety level. This guarantees
119     // that failure report would not try to touch something that was not yet verified to be
120     // safe to process.
121 
122     check(ShenandoahAsserts::_safe_unknown, obj, _heap->is_in(obj),
123               "oop must be in heap");
124     check(ShenandoahAsserts::_safe_unknown, obj, is_object_aligned(obj),
125               "oop must be aligned");
126 
127     ShenandoahHeapRegion *obj_reg = _heap->heap_region_containing(obj);
128     Klass* obj_klass = obj->forward_safe_klass();
129 
130     // Verify that obj is not in dead space:
131     {
132       // Do this before touching obj->size()
133       check(ShenandoahAsserts::_safe_unknown, obj, obj_klass != nullptr,
134              "Object klass pointer should not be null");
135       check(ShenandoahAsserts::_safe_unknown, obj, Metaspace::contains(obj_klass),
136              "Object klass pointer must go to metaspace");
137 
138       HeapWord *obj_addr = cast_from_oop<HeapWord*>(obj);
139       check(ShenandoahAsserts::_safe_unknown, obj, obj_addr < obj_reg->top(),
140              "Object start should be within the region");
141 
142       if (!obj_reg->is_humongous()) {
143         check(ShenandoahAsserts::_safe_unknown, obj, (obj_addr + obj->forward_safe_size()) <= obj_reg->top(),
144                "Object end should be within the region");
145       } else {
146         size_t humongous_start = obj_reg->index();
147         size_t humongous_end = humongous_start + (obj->forward_safe_size() >> ShenandoahHeapRegion::region_size_words_shift());
148         for (size_t idx = humongous_start + 1; idx < humongous_end; idx++) {
149           check(ShenandoahAsserts::_safe_unknown, obj, _heap->get_region(idx)->is_humongous_continuation(),
150                  "Humongous object is in continuation that fits it");
151         }
152       }
153 
154       // ------------ obj is safe at this point --------------
155 
156       check(ShenandoahAsserts::_safe_oop, obj, obj_reg->is_active(),
157             "Object should be in active region");
158 
159       switch (_options._verify_liveness) {
160         case ShenandoahVerifier::_verify_liveness_disable:
161           // skip
162           break;
163         case ShenandoahVerifier::_verify_liveness_complete:
164           Atomic::add(&_ld[obj_reg->index()], (uint) obj->forward_safe_size(), memory_order_relaxed);
165           // fallthrough for fast failure for un-live regions:
166         case ShenandoahVerifier::_verify_liveness_conservative:
167           check(ShenandoahAsserts::_safe_oop, obj, obj_reg->has_live(),
168                    "Object must belong to region with live data");
169           break;
170         default:
171           assert(false, "Unhandled liveness verification");
172       }
173     }
174 
175     oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
176 
177     ShenandoahHeapRegion* fwd_reg = nullptr;
178 
179     if (obj != fwd) {
180       check(ShenandoahAsserts::_safe_oop, obj, _heap->is_in(fwd),
181              "Forwardee must be in heap");
182       check(ShenandoahAsserts::_safe_oop, obj, !CompressedOops::is_null(fwd),
183              "Forwardee is set");
184       check(ShenandoahAsserts::_safe_oop, obj, is_object_aligned(fwd),
185              "Forwardee must be aligned");
186 
187       // Do this before touching fwd->size()
188       Klass* fwd_klass = fwd->klass_or_null();
189       check(ShenandoahAsserts::_safe_oop, obj, fwd_klass != nullptr,
190              "Forwardee klass pointer should not be null");
191       check(ShenandoahAsserts::_safe_oop, obj, Metaspace::contains(fwd_klass),
192              "Forwardee klass pointer must go to metaspace");
193       check(ShenandoahAsserts::_safe_oop, obj, obj_klass == fwd_klass,
194              "Forwardee klass pointer must go to metaspace");
195 
196       fwd_reg = _heap->heap_region_containing(fwd);
197 
198       // Verify that forwardee is not in the dead space:
199       check(ShenandoahAsserts::_safe_oop, obj, !fwd_reg->is_humongous(),
200              "Should have no humongous forwardees");
201 
202       HeapWord *fwd_addr = cast_from_oop<HeapWord *>(fwd);
203       check(ShenandoahAsserts::_safe_oop, obj, fwd_addr < fwd_reg->top(),
204              "Forwardee start should be within the region");
205       check(ShenandoahAsserts::_safe_oop, obj, (fwd_addr + fwd->forward_safe_size()) <= fwd_reg->top(),
206              "Forwardee end should be within the region");
207 
208       oop fwd2 = ShenandoahForwarding::get_forwardee_raw_unchecked(fwd);
209       check(ShenandoahAsserts::_safe_oop, obj, (fwd == fwd2),
210              "Double forwarding");
211     } else {
212       fwd_reg = obj_reg;
213     }
214 
215     // ------------ obj and fwd are safe at this point --------------
216 
217     switch (_options._verify_marked) {
218       case ShenandoahVerifier::_verify_marked_disable:
219         // skip
220         break;
221       case ShenandoahVerifier::_verify_marked_incomplete:
222         check(ShenandoahAsserts::_safe_all, obj, _heap->marking_context()->is_marked(obj),
223                "Must be marked in incomplete bitmap");
224         break;
225       case ShenandoahVerifier::_verify_marked_complete:
226         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
227                "Must be marked in complete bitmap");
228         break;
229       case ShenandoahVerifier::_verify_marked_complete_except_references:
230         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
231               "Must be marked in complete bitmap, except j.l.r.Reference referents");
232         break;
233       default:
234         assert(false, "Unhandled mark verification");
235     }
236 
237     switch (_options._verify_forwarded) {
238       case ShenandoahVerifier::_verify_forwarded_disable:
239         // skip
240         break;
241       case ShenandoahVerifier::_verify_forwarded_none: {
242         check(ShenandoahAsserts::_safe_all, obj, (obj == fwd),
243                "Should not be forwarded");
244         break;
245       }
246       case ShenandoahVerifier::_verify_forwarded_allow: {
247         if (obj != fwd) {
248           check(ShenandoahAsserts::_safe_all, obj, obj_reg != fwd_reg,
249                  "Forwardee should be in another region");
250         }
251         break;
252       }
253       default:
254         assert(false, "Unhandled forwarding verification");
255     }
256 
257     switch (_options._verify_cset) {
258       case ShenandoahVerifier::_verify_cset_disable:
259         // skip
260         break;
261       case ShenandoahVerifier::_verify_cset_none:
262         check(ShenandoahAsserts::_safe_all, obj, !_heap->in_collection_set(obj),
263                "Should not have references to collection set");
264         break;
265       case ShenandoahVerifier::_verify_cset_forwarded:
266         if (_heap->in_collection_set(obj)) {
267           check(ShenandoahAsserts::_safe_all, obj, (obj != fwd),
268                  "Object in collection set, should have forwardee");
269         }
270         break;
271       default:
272         assert(false, "Unhandled cset verification");
273     }
274 
275   }
276 
277 public:
278   /**
279    * Verify object with known interior reference.
280    * @param p interior reference where the object is referenced from; can be off-heap
281    * @param obj verified object
282    */
283   template <class T>
284   void verify_oop_at(T* p, oop obj) {
285     _interior_loc = p;
286     verify_oop(obj);
287     _interior_loc = nullptr;
288   }
289 
290   /**
291    * Verify object without known interior reference.
292    * Useful when picking up the object at known offset in heap,
293    * but without knowing what objects reference it.
294    * @param obj verified object
295    */
296   void verify_oop_standalone(oop obj) {
297     _interior_loc = nullptr;
298     verify_oop(obj);
299     _interior_loc = nullptr;
300   }
301 
302   /**
303    * Verify oop fields from this object.
304    * @param obj host object for verified fields
305    */
306   void verify_oops_from(oop obj) {
307     _loc = obj;
308     Klass* klass = obj->forward_safe_klass();
309     obj->oop_iterate_backwards(this, klass);
310     _loc = nullptr;
311   }
312 
313   virtual void do_oop(oop* p) { do_oop_work(p); }
314   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
315 };
316 
317 class ShenandoahCalculateRegionStatsClosure : public ShenandoahHeapRegionClosure {
318 private:
319   size_t _used, _committed, _garbage;
320 public:
321   ShenandoahCalculateRegionStatsClosure() : _used(0), _committed(0), _garbage(0) {};
322 
323   void heap_region_do(ShenandoahHeapRegion* r) {
324     _used += r->used();
325     _garbage += r->garbage();
326     _committed += r->is_committed() ? ShenandoahHeapRegion::region_size_bytes() : 0;
327   }
328 
329   size_t used() { return _used; }
330   size_t committed() { return _committed; }
331   size_t garbage() { return _garbage; }
332 };
333 
334 class ShenandoahVerifyHeapRegionClosure : public ShenandoahHeapRegionClosure {
335 private:
336   ShenandoahHeap* _heap;
337   const char* _phase;
338   ShenandoahVerifier::VerifyRegions _regions;
339 public:
340   ShenandoahVerifyHeapRegionClosure(const char* phase, ShenandoahVerifier::VerifyRegions regions) :
341     _heap(ShenandoahHeap::heap()),
342     _phase(phase),
343     _regions(regions) {};
344 
345   void print_failure(ShenandoahHeapRegion* r, const char* label) {
346     ResourceMark rm;
347 
348     ShenandoahMessageBuffer msg("Shenandoah verification failed; %s: %s\n\n", _phase, label);
349 
350     stringStream ss;
351     r->print_on(&ss);
352     msg.append("%s", ss.as_string());
353 
354     report_vm_error(__FILE__, __LINE__, msg.buffer());
355   }
356 
357   void verify(ShenandoahHeapRegion* r, bool test, const char* msg) {
358     if (!test) {
359       print_failure(r, msg);
360     }
361   }
362 
363   void heap_region_do(ShenandoahHeapRegion* r) {
364     switch (_regions) {
365       case ShenandoahVerifier::_verify_regions_disable:
366         break;
367       case ShenandoahVerifier::_verify_regions_notrash:
368         verify(r, !r->is_trash(),
369                "Should not have trash regions");
370         break;
371       case ShenandoahVerifier::_verify_regions_nocset:
372         verify(r, !r->is_cset(),
373                "Should not have cset regions");
374         break;
375       case ShenandoahVerifier::_verify_regions_notrash_nocset:
376         verify(r, !r->is_trash(),
377                "Should not have trash regions");
378         verify(r, !r->is_cset(),
379                "Should not have cset regions");
380         break;
381       default:
382         ShouldNotReachHere();
383     }
384 
385     verify(r, r->capacity() == ShenandoahHeapRegion::region_size_bytes(),
386            "Capacity should match region size");
387 
388     verify(r, r->bottom() <= r->top(),
389            "Region top should not be less than bottom");
390 
391     verify(r, r->bottom() <= _heap->marking_context()->top_at_mark_start(r),
392            "Region TAMS should not be less than bottom");
393 
394     verify(r, _heap->marking_context()->top_at_mark_start(r) <= r->top(),
395            "Complete TAMS should not be larger than top");
396 
397     verify(r, r->get_live_data_bytes() <= r->capacity(),
398            "Live data cannot be larger than capacity");
399 
400     verify(r, r->garbage() <= r->capacity(),
401            "Garbage cannot be larger than capacity");
402 
403     verify(r, r->used() <= r->capacity(),
404            "Used cannot be larger than capacity");
405 
406     verify(r, r->get_shared_allocs() <= r->capacity(),
407            "Shared alloc count should not be larger than capacity");
408 
409     verify(r, r->get_tlab_allocs() <= r->capacity(),
410            "TLAB alloc count should not be larger than capacity");
411 
412     verify(r, r->get_gclab_allocs() <= r->capacity(),
413            "GCLAB alloc count should not be larger than capacity");
414 
415     verify(r, r->get_shared_allocs() + r->get_tlab_allocs() + r->get_gclab_allocs() == r->used(),
416            "Accurate accounting: shared + TLAB + GCLAB = used");
417 
418     verify(r, !r->is_empty() || !r->has_live(),
419            "Empty regions should not have live data");
420 
421     verify(r, r->is_cset() == _heap->collection_set()->is_in(r),
422            "Transitional: region flags and collection set agree");
423   }
424 };
425 
426 class ShenandoahVerifierReachableTask : public WorkerTask {
427 private:
428   const char* _label;
429   ShenandoahVerifier::VerifyOptions _options;
430   ShenandoahHeap* _heap;
431   ShenandoahLivenessData* _ld;
432   MarkBitMap* _bitmap;
433   volatile size_t _processed;
434 
435 public:
436   ShenandoahVerifierReachableTask(MarkBitMap* bitmap,
437                                   ShenandoahLivenessData* ld,
438                                   const char* label,
439                                   ShenandoahVerifier::VerifyOptions options) :
440     WorkerTask("Shenandoah Verifier Reachable Objects"),
441     _label(label),
442     _options(options),
443     _heap(ShenandoahHeap::heap()),
444     _ld(ld),
445     _bitmap(bitmap),
446     _processed(0) {};
447 
448   size_t processed() {
449     return _processed;
450   }
451 
452   virtual void work(uint worker_id) {
453     ResourceMark rm;
454     ShenandoahVerifierStack stack;
455 
456     // On level 2, we need to only check the roots once.
457     // On level 3, we want to check the roots, and seed the local stack.
458     // It is a lesser evil to accept multiple root scans at level 3, because
459     // extended parallelism would buy us out.
460     if (((ShenandoahVerifyLevel == 2) && (worker_id == 0))
461         || (ShenandoahVerifyLevel >= 3)) {
462         ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
463                                       ShenandoahMessageBuffer("%s, Roots", _label),
464                                       _options);
465         if (_heap->unload_classes()) {
466           ShenandoahRootVerifier::strong_roots_do(&cl);
467         } else {
468           ShenandoahRootVerifier::roots_do(&cl);
469         }
470     }
471 
472     size_t processed = 0;
473 
474     if (ShenandoahVerifyLevel >= 3) {
475       ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
476                                     ShenandoahMessageBuffer("%s, Reachable", _label),
477                                     _options);
478       while (!stack.is_empty()) {
479         processed++;
480         ShenandoahVerifierTask task = stack.pop();
481         cl.verify_oops_from(task.obj());
482       }
483     }
484 
485     Atomic::add(&_processed, processed, memory_order_relaxed);
486   }
487 };
488 
489 class ShenandoahVerifierMarkedRegionTask : public WorkerTask {
490 private:
491   const char* _label;
492   ShenandoahVerifier::VerifyOptions _options;
493   ShenandoahHeap *_heap;
494   MarkBitMap* _bitmap;
495   ShenandoahLivenessData* _ld;
496   volatile size_t _claimed;
497   volatile size_t _processed;
498 
499 public:
500   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
501                                      ShenandoahLivenessData* ld,
502                                      const char* label,
503                                      ShenandoahVerifier::VerifyOptions options) :
504           WorkerTask("Shenandoah Verifier Marked Objects"),
505           _label(label),
506           _options(options),
507           _heap(ShenandoahHeap::heap()),
508           _bitmap(bitmap),
509           _ld(ld),
510           _claimed(0),
511           _processed(0) {};
512 
513   size_t processed() {
514     return Atomic::load(&_processed);
515   }
516 
517   virtual void work(uint worker_id) {
518     ShenandoahVerifierStack stack;
519     ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
520                                   ShenandoahMessageBuffer("%s, Marked", _label),
521                                   _options);
522 
523     while (true) {
524       size_t v = Atomic::fetch_then_add(&_claimed, 1u, memory_order_relaxed);
525       if (v < _heap->num_regions()) {
526         ShenandoahHeapRegion* r = _heap->get_region(v);
527         if (!r->is_humongous() && !r->is_trash()) {
528           work_regular(r, stack, cl);
529         } else if (r->is_humongous_start()) {
530           work_humongous(r, stack, cl);
531         }
532       } else {
533         break;
534       }
535     }
536   }
537 
538   virtual void work_humongous(ShenandoahHeapRegion *r, ShenandoahVerifierStack& stack, ShenandoahVerifyOopClosure& cl) {
539     size_t processed = 0;
540     HeapWord* obj = r->bottom();
541     if (_heap->complete_marking_context()->is_marked(cast_to_oop(obj))) {
542       verify_and_follow(obj, stack, cl, &processed);
543     }
544     Atomic::add(&_processed, processed, memory_order_relaxed);
545   }
546 
547   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
548     size_t processed = 0;
549     ShenandoahMarkingContext* ctx = _heap->complete_marking_context();
550     HeapWord* tams = ctx->top_at_mark_start(r);
551 
552     // Bitmaps, before TAMS
553     if (tams > r->bottom()) {
554       HeapWord* start = r->bottom();
555       HeapWord* addr = ctx->get_next_marked_addr(start, tams);
556 
557       while (addr < tams) {
558         verify_and_follow(addr, stack, cl, &processed);
559         addr += 1;
560         if (addr < tams) {
561           addr = ctx->get_next_marked_addr(addr, tams);
562         }
563       }
564     }
565 
566     // Size-based, after TAMS
567     {
568       HeapWord* limit = r->top();
569       HeapWord* addr = tams;
570 
571       while (addr < limit) {
572         verify_and_follow(addr, stack, cl, &processed);
573         addr += cast_to_oop(addr)->size();
574       }
575     }
576 
577     Atomic::add(&_processed, processed, memory_order_relaxed);
578   }
579 
580   void verify_and_follow(HeapWord *addr, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl, size_t *processed) {
581     if (!_bitmap->par_mark(addr)) return;
582 
583     // Verify the object itself:
584     oop obj = cast_to_oop(addr);
585     cl.verify_oop_standalone(obj);
586 
587     // Verify everything reachable from that object too, hopefully realizing
588     // everything was already marked, and never touching further:
589     if (!is_instance_ref_klass(obj->forward_safe_klass())) {
590       cl.verify_oops_from(obj);
591       (*processed)++;
592     }
593     while (!stack.is_empty()) {
594       ShenandoahVerifierTask task = stack.pop();
595       cl.verify_oops_from(task.obj());
596       (*processed)++;
597     }
598   }
599 };
600 
601 class VerifyThreadGCState : public ThreadClosure {
602 private:
603   const char* const _label;
604          char const _expected;
605 
606 public:
607   VerifyThreadGCState(const char* label, char expected) : _label(label), _expected(expected) {}
608   void do_thread(Thread* t) {
609     char actual = ShenandoahThreadLocalData::gc_state(t);
610     if (actual != _expected) {
611       fatal("%s: Thread %s: expected gc-state %d, actual %d", _label, t->name(), _expected, actual);
612     }
613   }
614 };
615 
616 void ShenandoahVerifier::verify_at_safepoint(const char *label,
617                                              VerifyForwarded forwarded, VerifyMarked marked,
618                                              VerifyCollectionSet cset,
619                                              VerifyLiveness liveness, VerifyRegions regions,
620                                              VerifyGCState gcstate) {
621   guarantee(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "only when nothing else happens");
622   guarantee(ShenandoahVerify, "only when enabled, and bitmap is initialized in ShenandoahHeap::initialize");
623 
624   ShenandoahHeap::heap()->propagate_gc_state_to_java_threads();
625 
626   // Avoid side-effect of changing workers' active thread count, but bypass concurrent/parallel protocol check
627   ShenandoahPushWorkerScope verify_worker_scope(_heap->workers(), _heap->max_workers(), false /*bypass check*/);
628 
629   log_info(gc,start)("Verify %s, Level " INTX_FORMAT, label, ShenandoahVerifyLevel);
630 
631   // GC state checks
632   {
633     char expected = -1;
634     bool enabled;
635     switch (gcstate) {
636       case _verify_gcstate_disable:
637         enabled = false;
638         break;
639       case _verify_gcstate_forwarded:
640         enabled = true;
641         expected = ShenandoahHeap::HAS_FORWARDED;
642         break;
643       case _verify_gcstate_evacuation:
644         enabled = true;
645         expected = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::EVACUATION;
646         if (!_heap->is_stw_gc_in_progress()) {
647           // Only concurrent GC sets this.
648           expected |= ShenandoahHeap::WEAK_ROOTS;
649         }
650         break;
651       case _verify_gcstate_stable:
652         enabled = true;
653         expected = ShenandoahHeap::STABLE;
654         break;
655       case _verify_gcstate_stable_weakroots:
656         enabled = true;
657         expected = ShenandoahHeap::STABLE;
658         if (!_heap->is_stw_gc_in_progress()) {
659           // Only concurrent GC sets this.
660           expected |= ShenandoahHeap::WEAK_ROOTS;
661         }
662         break;
663       default:
664         enabled = false;
665         assert(false, "Unhandled gc-state verification");
666     }
667 
668     if (enabled) {
669       char actual = _heap->gc_state();
670       if (actual != expected) {
671         fatal("%s: Global gc-state: expected %d, actual %d", label, expected, actual);
672       }
673 
674       VerifyThreadGCState vtgcs(label, expected);
675       Threads::java_threads_do(&vtgcs);
676     }
677   }
678 
679   // Deactivate barriers temporarily: Verifier wants plain heap accesses
680   ShenandoahGCStateResetter resetter;
681 
682   // Heap size checks
683   {
684     ShenandoahHeapLocker lock(_heap->lock());
685 
686     ShenandoahCalculateRegionStatsClosure cl;
687     _heap->heap_region_iterate(&cl);
688     size_t heap_used = _heap->used();
689     guarantee(cl.used() == heap_used,
690               "%s: heap used size must be consistent: heap-used = " SIZE_FORMAT "%s, regions-used = " SIZE_FORMAT "%s",
691               label,
692               byte_size_in_proper_unit(heap_used), proper_unit_for_byte_size(heap_used),
693               byte_size_in_proper_unit(cl.used()), proper_unit_for_byte_size(cl.used()));
694 
695     size_t heap_committed = _heap->committed();
696     guarantee(cl.committed() == heap_committed,
697               "%s: heap committed size must be consistent: heap-committed = " SIZE_FORMAT "%s, regions-committed = " SIZE_FORMAT "%s",
698               label,
699               byte_size_in_proper_unit(heap_committed), proper_unit_for_byte_size(heap_committed),
700               byte_size_in_proper_unit(cl.committed()), proper_unit_for_byte_size(cl.committed()));
701   }
702 
703   // Internal heap region checks
704   if (ShenandoahVerifyLevel >= 1) {
705     ShenandoahVerifyHeapRegionClosure cl(label, regions);
706     _heap->heap_region_iterate(&cl);
707   }
708 
709   OrderAccess::fence();
710 
711   if (UseTLAB) {
712     _heap->labs_make_parsable();
713   }
714 
715   // Allocate temporary bitmap for storing marking wavefront:
716   _verification_bit_map->clear();
717 
718   // Allocate temporary array for storing liveness data
719   ShenandoahLivenessData* ld = NEW_C_HEAP_ARRAY(ShenandoahLivenessData, _heap->num_regions(), mtGC);
720   Copy::fill_to_bytes((void*)ld, _heap->num_regions()*sizeof(ShenandoahLivenessData), 0);
721 
722   const VerifyOptions& options = ShenandoahVerifier::VerifyOptions(forwarded, marked, cset, liveness, regions, gcstate);
723 
724   // Steps 1-2. Scan root set to get initial reachable set. Finish walking the reachable heap.
725   // This verifies what application can see, since it only cares about reachable objects.
726   size_t count_reachable = 0;
727   if (ShenandoahVerifyLevel >= 2) {
728     ShenandoahVerifierReachableTask task(_verification_bit_map, ld, label, options);
729     _heap->workers()->run_task(&task);
730     count_reachable = task.processed();
731   }
732 
733   // Step 3. Walk marked objects. Marked objects might be unreachable. This verifies what collector,
734   // not the application, can see during the region scans. There is no reason to process the objects
735   // that were already verified, e.g. those marked in verification bitmap. There is interaction with TAMS:
736   // before TAMS, we verify the bitmaps, if available; after TAMS, we walk until the top(). It mimics
737   // what marked_object_iterate is doing, without calling into that optimized (and possibly incorrect)
738   // version
739 
740   size_t count_marked = 0;
741   if (ShenandoahVerifyLevel >= 4 && (marked == _verify_marked_complete || marked == _verify_marked_complete_except_references)) {
742     guarantee(_heap->marking_context()->is_complete(), "Marking context should be complete");
743     ShenandoahVerifierMarkedRegionTask task(_verification_bit_map, ld, label, options);
744     _heap->workers()->run_task(&task);
745     count_marked = task.processed();
746   } else {
747     guarantee(ShenandoahVerifyLevel < 4 || marked == _verify_marked_incomplete || marked == _verify_marked_disable, "Should be");
748   }
749 
750   // Step 4. Verify accumulated liveness data, if needed. Only reliable if verification level includes
751   // marked objects.
752 
753   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete && liveness == _verify_liveness_complete) {
754     for (size_t i = 0; i < _heap->num_regions(); i++) {
755       ShenandoahHeapRegion* r = _heap->get_region(i);
756 
757       juint verf_live = 0;
758       if (r->is_humongous()) {
759         // For humongous objects, test if start region is marked live, and if so,
760         // all humongous regions in that chain have live data equal to their "used".
761         juint start_live = Atomic::load(&ld[r->humongous_start_region()->index()]);
762         if (start_live > 0) {
763           verf_live = (juint)(r->used() / HeapWordSize);
764         }
765       } else {
766         verf_live = Atomic::load(&ld[r->index()]);
767       }
768 
769       size_t reg_live = r->get_live_data_words();
770       if (reg_live != verf_live) {
771         stringStream ss;
772         r->print_on(&ss);
773         fatal("%s: Live data should match: region-live = " SIZE_FORMAT ", verifier-live = " UINT32_FORMAT "\n%s",
774               label, reg_live, verf_live, ss.freeze());
775       }
776     }
777   }
778 
779   log_info(gc)("Verify %s, Level " INTX_FORMAT " (" SIZE_FORMAT " reachable, " SIZE_FORMAT " marked)",
780                label, ShenandoahVerifyLevel, count_reachable, count_marked);
781 
782   FREE_C_HEAP_ARRAY(ShenandoahLivenessData, ld);
783 }
784 
785 void ShenandoahVerifier::verify_generic(VerifyOption vo) {
786   verify_at_safepoint(
787           "Generic Verification",
788           _verify_forwarded_allow,     // conservatively allow forwarded
789           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
790           _verify_cset_disable,        // cset may be inconsistent
791           _verify_liveness_disable,    // no reliable liveness data
792           _verify_regions_disable,     // no reliable region data
793           _verify_gcstate_disable      // no data about gcstate
794   );
795 }
796 
797 void ShenandoahVerifier::verify_before_concmark() {
798     verify_at_safepoint(
799           "Before Mark",
800           _verify_forwarded_none,      // UR should have fixed up
801           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
802           _verify_cset_none,           // UR should have fixed this
803           _verify_liveness_disable,    // no reliable liveness data
804           _verify_regions_notrash,     // no trash regions
805           _verify_gcstate_stable       // there are no forwarded objects
806   );
807 }
808 
809 void ShenandoahVerifier::verify_after_concmark() {
810   verify_at_safepoint(
811           "After Mark",
812           _verify_forwarded_none,      // no forwarded references
813           _verify_marked_complete_except_references, // bitmaps as precise as we can get, except dangling j.l.r.Refs
814           _verify_cset_none,           // no references to cset anymore
815           _verify_liveness_complete,   // liveness data must be complete here
816           _verify_regions_disable,     // trash regions not yet recycled
817           _verify_gcstate_stable_weakroots  // heap is still stable, weakroots are in progress
818   );
819 }
820 
821 void ShenandoahVerifier::verify_before_evacuation() {
822   verify_at_safepoint(
823           "Before Evacuation",
824           _verify_forwarded_none,                    // no forwarded references
825           _verify_marked_complete_except_references, // walk over marked objects too
826           _verify_cset_disable,                      // non-forwarded references to cset expected
827           _verify_liveness_complete,                 // liveness data must be complete here
828           _verify_regions_disable,                   // trash regions not yet recycled
829           _verify_gcstate_stable_weakroots           // heap is still stable, weakroots are in progress
830   );
831 }
832 
833 void ShenandoahVerifier::verify_during_evacuation() {
834   verify_at_safepoint(
835           "During Evacuation",
836           _verify_forwarded_allow,    // some forwarded references are allowed
837           _verify_marked_disable,     // walk only roots
838           _verify_cset_disable,       // some cset references are not forwarded yet
839           _verify_liveness_disable,   // liveness data might be already stale after pre-evacs
840           _verify_regions_disable,    // trash regions not yet recycled
841           _verify_gcstate_evacuation  // evacuation is in progress
842   );
843 }
844 
845 void ShenandoahVerifier::verify_after_evacuation() {
846   verify_at_safepoint(
847           "After Evacuation",
848           _verify_forwarded_allow,     // objects are still forwarded
849           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
850           _verify_cset_forwarded,      // all cset refs are fully forwarded
851           _verify_liveness_disable,    // no reliable liveness data anymore
852           _verify_regions_notrash,     // trash regions have been recycled already
853           _verify_gcstate_forwarded    // evacuation produced some forwarded objects
854   );
855 }
856 
857 void ShenandoahVerifier::verify_before_updaterefs() {
858   verify_at_safepoint(
859           "Before Updating References",
860           _verify_forwarded_allow,     // forwarded references allowed
861           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
862           _verify_cset_forwarded,      // all cset refs are fully forwarded
863           _verify_liveness_disable,    // no reliable liveness data anymore
864           _verify_regions_notrash,     // trash regions have been recycled already
865           _verify_gcstate_forwarded    // evacuation should have produced some forwarded objects
866   );
867 }
868 
869 void ShenandoahVerifier::verify_after_updaterefs() {
870   verify_at_safepoint(
871           "After Updating References",
872           _verify_forwarded_none,      // no forwarded references
873           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
874           _verify_cset_none,           // no cset references, all updated
875           _verify_liveness_disable,    // no reliable liveness data anymore
876           _verify_regions_nocset,      // no cset regions, trash regions have appeared
877           _verify_gcstate_stable       // update refs had cleaned up forwarded objects
878   );
879 }
880 
881 void ShenandoahVerifier::verify_after_degenerated() {
882   verify_at_safepoint(
883           "After Degenerated GC",
884           _verify_forwarded_none,      // all objects are non-forwarded
885           _verify_marked_complete,     // all objects are marked in complete bitmap
886           _verify_cset_none,           // no cset references
887           _verify_liveness_disable,    // no reliable liveness data anymore
888           _verify_regions_notrash_nocset, // no trash, no cset
889           _verify_gcstate_stable       // degenerated refs had cleaned up forwarded objects
890   );
891 }
892 
893 void ShenandoahVerifier::verify_before_fullgc() {
894   verify_at_safepoint(
895           "Before Full GC",
896           _verify_forwarded_allow,     // can have forwarded objects
897           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
898           _verify_cset_disable,        // cset might be foobared
899           _verify_liveness_disable,    // no reliable liveness data anymore
900           _verify_regions_disable,     // no reliable region data here
901           _verify_gcstate_disable      // no reliable gcstate data
902   );
903 }
904 
905 void ShenandoahVerifier::verify_after_fullgc() {
906   verify_at_safepoint(
907           "After Full GC",
908           _verify_forwarded_none,      // all objects are non-forwarded
909           _verify_marked_complete,     // all objects are marked in complete bitmap
910           _verify_cset_none,           // no cset references
911           _verify_liveness_disable,    // no reliable liveness data anymore
912           _verify_regions_notrash_nocset, // no trash, no cset
913           _verify_gcstate_stable        // full gc cleaned up everything
914   );
915 }
916 
917 class ShenandoahVerifyNoForwared : public OopClosure {
918 private:
919   template <class T>
920   void do_oop_work(T* p) {
921     T o = RawAccess<>::oop_load(p);
922     if (!CompressedOops::is_null(o)) {
923       oop obj = CompressedOops::decode_not_null(o);
924       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
925       if (obj != fwd) {
926         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
927                                          "Verify Roots", "Should not be forwarded", __FILE__, __LINE__);
928       }
929     }
930   }
931 
932 public:
933   void do_oop(narrowOop* p) { do_oop_work(p); }
934   void do_oop(oop* p)       { do_oop_work(p); }
935 };
936 
937 class ShenandoahVerifyInToSpaceClosure : public OopClosure {
938 private:
939   template <class T>
940   void do_oop_work(T* p) {
941     T o = RawAccess<>::oop_load(p);
942     if (!CompressedOops::is_null(o)) {
943       oop obj = CompressedOops::decode_not_null(o);
944       ShenandoahHeap* heap = ShenandoahHeap::heap();
945 
946       if (!heap->marking_context()->is_marked(obj)) {
947         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
948                 "Verify Roots In To-Space", "Should be marked", __FILE__, __LINE__);
949       }
950 
951       if (heap->in_collection_set(obj)) {
952         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
953                 "Verify Roots In To-Space", "Should not be in collection set", __FILE__, __LINE__);
954       }
955 
956       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
957       if (obj != fwd) {
958         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
959                 "Verify Roots In To-Space", "Should not be forwarded", __FILE__, __LINE__);
960       }
961     }
962   }
963 
964 public:
965   void do_oop(narrowOop* p) { do_oop_work(p); }
966   void do_oop(oop* p)       { do_oop_work(p); }
967 };
968 
969 void ShenandoahVerifier::verify_roots_in_to_space() {
970   ShenandoahVerifyInToSpaceClosure cl;
971   ShenandoahRootVerifier::roots_do(&cl);
972 }
973 
974 void ShenandoahVerifier::verify_roots_no_forwarded() {
975   ShenandoahVerifyNoForwared cl;
976   ShenandoahRootVerifier::roots_do(&cl);
977 }