1 /*
  2  * Copyright (c) 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 
 27 #include "gc/shared/collectorCounters.hpp"
 28 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
 29 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
 30 #include "gc/shenandoah/shenandoahDegeneratedGC.hpp"
 31 #include "gc/shenandoah/shenandoahFullGC.hpp"
 32 #include "gc/shenandoah/shenandoahGeneration.hpp"
 33 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 34 #include "gc/shenandoah/shenandoahMetrics.hpp"
 35 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
 36 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
 37 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
 38 #include "gc/shenandoah/shenandoahSTWMark.hpp"
 39 #include "gc/shenandoah/shenandoahUtils.hpp"
 40 #include "gc/shenandoah/shenandoahVerifier.hpp"
 41 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
 42 #include "gc/shenandoah/shenandoahVMOperations.hpp"
 43 #include "runtime/vmThread.hpp"
 44 #include "utilities/events.hpp"
 45 
 46 ShenandoahDegenGC::ShenandoahDegenGC(ShenandoahDegenPoint degen_point, ShenandoahGeneration* generation) :
 47   ShenandoahGC(),
 48   _degen_point(degen_point),
 49   _generation(generation),
 50   _upgraded_to_full(false) {
 51 }
 52 
 53 bool ShenandoahDegenGC::collect(GCCause::Cause cause) {
 54   vmop_degenerated();
 55   return true;
 56 }
 57 
 58 void ShenandoahDegenGC::vmop_degenerated() {
 59   TraceCollectorStats tcs(ShenandoahHeap::heap()->monitoring_support()->full_stw_collection_counters());
 60   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::degen_gc_gross);
 61   VM_ShenandoahDegeneratedGC degenerated_gc(this);
 62   VMThread::execute(&degenerated_gc);
 63 }
 64 
 65 void ShenandoahDegenGC::entry_degenerated() {
 66   char msg[1024];
 67   degen_event_message(_degen_point, msg, sizeof(msg));
 68   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::degen_gc, true /* log_heap_usage */);
 69   EventMark em("%s", msg);
 70   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 71 
 72   // In case degenerated GC preempted evacuation or update-refs, clear the aging cycle now.  No harm in clearing it
 73   // redundantly if it is already clear.  We don't age during degenerated cycles.
 74   heap->set_aging_cycle(false);
 75 
 76   ShenandoahWorkerScope scope(heap->workers(),
 77                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
 78                               "stw degenerated gc");
 79 
 80   heap->set_degenerated_gc_in_progress(true);
 81   op_degenerated();
 82   heap->set_degenerated_gc_in_progress(false);
 83 }
 84 
 85 void ShenandoahDegenGC::op_degenerated() {
 86   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 87   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
 88   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
 89   // some phase, we have to upgrade the Degenerate GC to Full GC.
 90   heap->clear_cancelled_gc(true /* clear oom handler */);
 91 
 92   // We can't easily clear the old mark in progress flag because it must be done
 93   // on a safepoint (not sure if that is a hard requirement). At any rate, once
 94   // we are in a degenerated cycle, there should be no more old marking.
 95   if (heap->is_concurrent_old_mark_in_progress()) {
 96     heap->old_generation()->cancel_marking();
 97   }
 98   assert(heap->old_generation()->task_queues()->is_empty(), "Old gen task queues should be empty.");
 99 
100   ShenandoahMetricsSnapshot metrics;
101   metrics.snap_before();
102 
103   switch (_degen_point) {
104     // The cases below form the Duff's-like device: it describes the actual GC cycle,
105     // but enters it at different points, depending on which concurrent phase had
106     // degenerated.
107 
108     case _degenerated_outside_cycle:
109       // We have degenerated from outside the cycle, which means something is bad with
110       // the heap, most probably heavy humongous fragmentation, or we are very low on free
111       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
112       // we can do the most aggressive degen cycle, which includes processing references and
113       // class unloading, unless those features are explicitly disabled.
114 
115 
116       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
117       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
118       heap->set_unload_classes((!heap->mode()->is_generational() || _generation->generation_mode() == GLOBAL) && _generation->heuristics()->can_unload_classes());
119 
120       if (_generation->generation_mode() == YOUNG || (_generation->generation_mode() == GLOBAL && ShenandoahVerify)) {
121         // Swap remembered sets for young, or if the verifier will run during a global collect
122         _generation->swap_remembered_set();
123       }
124 
125     case _degenerated_roots:
126       // Degenerated from concurrent root mark, reset the flag for STW mark
127       if (heap->is_concurrent_mark_in_progress()) {
128         heap->cancel_concurrent_mark();
129       }
130 
131       op_reset();
132 
133       // STW mark
134       op_mark();
135 
136     case _degenerated_mark:
137       // No fallthrough. Continue mark, handed over from concurrent mark
138       if (_degen_point == ShenandoahDegenPoint::_degenerated_mark) {
139         op_finish_mark();
140       }
141       assert(!heap->cancelled_gc(), "STW mark can not OOM");
142 
143       /* Degen select Collection Set. etc. */
144       op_prepare_evacuation();
145 
146       op_cleanup_early();
147 
148       if (heap->mode()->is_generational() && _generation->generation_mode() == GLOBAL) {
149         op_global_coalesce_and_fill();
150       }
151 
152     case _degenerated_evac:
153       // If heuristics thinks we should do the cycle, this flag would be set,
154       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
155       if (heap->is_evacuation_in_progress()) {
156 
157         // Degeneration under oom-evac protocol might have left some objects in
158         // collection set un-evacuated. Restart evacuation from the beginning to
159         // capture all objects. For all the objects that are already evacuated,
160         // it would be a simple check, which is supposed to be fast. This is also
161         // safe to do even without degeneration, as CSet iterator is at beginning
162         // in preparation for evacuation anyway.
163         //
164         // Before doing that, we need to make sure we never had any cset-pinned
165         // regions. This may happen if allocation failure happened when evacuating
166         // the about-to-be-pinned object, oom-evac protocol left the object in
167         // the collection set, and then the pin reached the cset region. If we continue
168         // the cycle here, we would trash the cset and alive objects in it. To avoid
169         // it, we fail degeneration right away and slide into Full GC to recover.
170 
171         {
172           heap->sync_pinned_region_status();
173           heap->collection_set()->clear_current_index();
174           ShenandoahHeapRegion* r;
175           while ((r = heap->collection_set()->next()) != NULL) {
176             if (r->is_pinned()) {
177               heap->cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
178               op_degenerated_fail();
179               return;
180             }
181           }
182 
183           heap->collection_set()->clear_current_index();
184         }
185         op_evacuate();
186         if (heap->cancelled_gc()) {
187           op_degenerated_fail();
188           return;
189         }
190       }
191 
192       // If heuristics thinks we should do the cycle, this flag would be set,
193       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
194       if (heap->has_forwarded_objects()) {
195         op_init_updaterefs();
196         assert(!heap->cancelled_gc(), "STW reference update can not OOM");
197       }
198 
199     case _degenerated_updaterefs:
200       if (heap->has_forwarded_objects()) {
201         op_updaterefs();
202         op_update_roots();
203         assert(!heap->cancelled_gc(), "STW reference update can not OOM");
204       }
205 
206       if (ClassUnloading) {
207          // Disarm nmethods that armed in concurrent cycle.
208          // In above case, update roots should disarm them
209          ShenandoahCodeRoots::disarm_nmethods();
210       }
211 
212       op_cleanup_complete();
213       break;
214     default:
215       ShouldNotReachHere();
216   }
217 
218   if (ShenandoahVerify) {
219     heap->verifier()->verify_after_degenerated();
220   }
221 
222   if (VerifyAfterGC) {
223     Universe::verify();
224   }
225 
226   metrics.snap_after();
227 
228   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
229   // because that probably means the heap is overloaded and/or fragmented.
230   if (!metrics.is_good_progress()) {
231     heap->notify_gc_no_progress();
232     heap->cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
233     op_degenerated_futile();
234   } else {
235     heap->notify_gc_progress();
236   }
237 }
238 
239 void ShenandoahDegenGC::op_reset() {
240   _generation->prepare_gc(false);
241 }
242 
243 void ShenandoahDegenGC::op_mark() {
244   assert(!ShenandoahHeap::heap()->is_concurrent_mark_in_progress(), "Should be reset");
245   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_stw_mark);
246   ShenandoahSTWMark mark(_generation, false /*full gc*/);
247   mark.mark();
248 }
249 
250 void ShenandoahDegenGC::op_finish_mark() {
251   ShenandoahConcurrentMark mark(_generation);
252   mark.finish_mark();
253 }
254 
255 void ShenandoahDegenGC::op_prepare_evacuation() {
256   ShenandoahHeap* const heap = ShenandoahHeap::heap();
257   if (ShenandoahVerify) {
258     heap->verifier()->verify_roots_no_forwarded();
259   }
260 
261   // STW cleanup weak roots and unload classes
262   heap->parallel_cleaning(false /*full gc*/);
263 
264   // Prepare regions and collection set
265   _generation->prepare_regions_and_collection_set(false /*concurrent*/);
266 
267   // Retire the TLABs, which will force threads to reacquire their TLABs after the pause.
268   // This is needed for two reasons. Strong one: new allocations would be with new freeset,
269   // which would be outside the collection set, so no cset writes would happen there.
270   // Weaker one: new allocations would happen past update watermark, and so less work would
271   // be needed for reference updates (would update the large filler instead).
272   if (UseTLAB) {
273     ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_final_manage_labs);
274     heap->tlabs_retire(false);
275   }
276 
277   if (!heap->collection_set()->is_empty()) {
278     heap->set_evacuation_in_progress(true);
279     heap->set_has_forwarded_objects(true);
280 
281     if(ShenandoahVerify) {
282       heap->verifier()->verify_during_evacuation();
283     }
284   } else {
285     if (ShenandoahVerify) {
286       heap->verifier()->verify_after_concmark();
287     }
288 
289     if (VerifyAfterGC) {
290       Universe::verify();
291     }
292   }
293 }
294 
295 void ShenandoahDegenGC::op_cleanup_early() {
296   ShenandoahHeap::heap()->recycle_trash();
297 }
298 
299 void ShenandoahDegenGC::op_global_coalesce_and_fill() {
300   ShenandoahHeap::heap()->coalesce_and_fill_old_regions();
301 }
302 
303 void ShenandoahDegenGC::op_evacuate() {
304   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_stw_evac);
305   ShenandoahHeap::heap()->evacuate_collection_set(false /* concurrent*/);
306 }
307 
308 void ShenandoahDegenGC::op_init_updaterefs() {
309   // Evacuation has completed
310   ShenandoahHeap* const heap = ShenandoahHeap::heap();
311   heap->set_evacuation_in_progress(false);
312   heap->set_concurrent_weak_root_in_progress(false);
313   heap->set_concurrent_strong_root_in_progress(false);
314 
315   heap->prepare_update_heap_references(false /*concurrent*/);
316   heap->set_update_refs_in_progress(true);
317 }
318 
319 void ShenandoahDegenGC::op_updaterefs() {
320   ShenandoahHeap* const heap = ShenandoahHeap::heap();
321   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_updaterefs);
322   // Handed over from concurrent update references phase
323   heap->update_heap_references(false /*concurrent*/);
324 
325   heap->set_update_refs_in_progress(false);
326   heap->set_has_forwarded_objects(false);
327 }
328 
329 void ShenandoahDegenGC::op_update_roots() {
330   ShenandoahHeap* const heap = ShenandoahHeap::heap();
331 
332   update_roots(false /*full_gc*/);
333 
334   heap->update_heap_region_states(false /*concurrent*/);
335 
336   if (ShenandoahVerify) {
337     heap->verifier()->verify_after_updaterefs();
338   }
339 
340   if (VerifyAfterGC) {
341     Universe::verify();
342   }
343 
344   heap->rebuild_free_set(false /*concurrent*/);
345 }
346 
347 void ShenandoahDegenGC::op_cleanup_complete() {
348   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_cleanup_complete);
349   ShenandoahHeap::heap()->recycle_trash();
350 }
351 
352 void ShenandoahDegenGC::op_degenerated_fail() {
353   upgrade_to_full();
354   ShenandoahFullGC full_gc;
355   full_gc.op_full(GCCause::_shenandoah_upgrade_to_full_gc);
356 }
357 
358 void ShenandoahDegenGC::op_degenerated_futile() {
359   upgrade_to_full();
360   ShenandoahFullGC full_gc;
361   full_gc.op_full(GCCause::_shenandoah_upgrade_to_full_gc);
362 }
363 
364 void ShenandoahDegenGC::degen_event_message(ShenandoahDegenPoint point, char* buf, size_t len) const {
365   jio_snprintf(buf, len, "Pause Degenerated %s GC (%s)", _generation->name(), ShenandoahGC::degen_point_to_string(point));
366 }
367 
368 void ShenandoahDegenGC::upgrade_to_full() {
369   log_info(gc)("Degenerate GC upgrading to Full GC");
370   ShenandoahHeap::heap()->shenandoah_policy()->record_degenerated_upgrade_to_full();
371   _upgraded_to_full = true;
372 }
373 
374 bool ShenandoahDegenGC::upgraded_to_full() {
375   return _upgraded_to_full;
376 }