1 /*
  2  * Copyright (c) 2021, Red Hat, Inc. All rights reserved.
  3  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  *
 24  */
 25 
 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/shenandoahGenerationalHeap.hpp"
 34 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 35 #include "gc/shenandoah/shenandoahMetrics.hpp"
 36 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
 37 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
 38 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
 39 #include "gc/shenandoah/shenandoahStackWatermark.hpp"
 40 #include "gc/shenandoah/shenandoahSTWMark.hpp"
 41 #include "gc/shenandoah/shenandoahUtils.hpp"
 42 #include "gc/shenandoah/shenandoahVerifier.hpp"
 43 #include "gc/shenandoah/shenandoahVMOperations.hpp"
 44 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
 45 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
 46 #include "runtime/vmThread.hpp"
 47 #include "utilities/events.hpp"
 48 
 49 ShenandoahDegenGC::ShenandoahDegenGC(ShenandoahDegenPoint degen_point, ShenandoahGeneration* generation) :
 50   ShenandoahGC(generation),
 51   _degen_point(degen_point),
 52   _abbreviated(false) {
 53 }
 54 
 55 bool ShenandoahDegenGC::collect(GCCause::Cause cause) {
 56   vmop_degenerated();
 57   ShenandoahHeap* heap = ShenandoahHeap::heap();
 58   if (heap->mode()->is_generational()) {
 59     bool is_bootstrap_gc = heap->old_generation()->is_bootstrapping();
 60     heap->mmu_tracker()->record_degenerated(GCId::current(), is_bootstrap_gc);
 61     const char* msg = is_bootstrap_gc? "At end of Degenerated Bootstrap Old GC": "At end of Degenerated Young GC";
 62     heap->log_heap_status(msg);
 63   }
 64   return true;
 65 }
 66 
 67 void ShenandoahDegenGC::vmop_degenerated() {
 68   TraceCollectorStats tcs(ShenandoahHeap::heap()->monitoring_support()->full_stw_collection_counters());
 69   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::degen_gc_gross);
 70   VM_ShenandoahDegeneratedGC degenerated_gc(this);
 71   VMThread::execute(&degenerated_gc);
 72 }
 73 
 74 void ShenandoahDegenGC::entry_degenerated() {
 75   const char* msg = degen_event_message(_degen_point);
 76   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::degen_gc, true /* log_heap_usage */);
 77   EventMark em("%s", msg);
 78   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 79   ShenandoahWorkerScope scope(heap->workers(),
 80                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
 81                               "stw degenerated gc");
 82 
 83   heap->set_degenerated_gc_in_progress(true);
 84   op_degenerated();
 85   heap->set_degenerated_gc_in_progress(false);
 86   {
 87     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::degen_gc_propagate_gc_state);
 88     heap->propagate_gc_state_to_all_threads();
 89   }
 90 }
 91 
 92 void ShenandoahDegenGC::op_degenerated() {
 93   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 94   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
 95   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
 96   // some phase, we have to upgrade the Degenerate GC to Full GC.
 97   heap->clear_cancelled_gc();
 98 
 99   // If it's passive mode with ShenandoahCardBarrier turned on: clean the write table
100   // without swapping the tables since no scan happens in passive mode anyway
101   if (ShenandoahCardBarrier && !heap->mode()->is_generational()) {
102     heap->old_generation()->card_scan()->mark_write_table_as_clean();
103   }
104 
105   if (heap->mode()->is_generational()) {
106     const ShenandoahOldGeneration* old_generation = heap->old_generation();
107     if (!heap->is_concurrent_old_mark_in_progress()) {
108       // If we are not marking the old generation, there should be nothing in the old mark queues
109       assert(old_generation->task_queues()->is_empty(), "Old gen task queues should be empty");
110     } else {
111       // This is still necessary for degenerated cycles because the degeneration point may occur
112       // after final mark of the young generation. See ShenandoahConcurrentGC::op_final_update_refs for
113       // a more detailed explanation.
114       old_generation->transfer_pointers_from_satb();
115     }
116 
117     if (_generation->is_global()) {
118       // If we are in a global cycle, the old generation should not be marking. It is, however,
119       // allowed to be holding regions for evacuation or coalescing.
120       assert(old_generation->is_idle()
121              || old_generation->is_doing_mixed_evacuations()
122              || old_generation->is_preparing_for_mark(),
123              "Old generation cannot be in state: %s", old_generation->state_name());
124     }
125   }
126 
127   ShenandoahMetricsSnapshot metrics(heap->free_set());
128 
129   switch (_degen_point) {
130     // The cases below form the Duff's-like device: it describes the actual GC cycle,
131     // but enters it at different points, depending on which concurrent phase had
132     // degenerated.
133 
134     case _degenerated_outside_cycle:
135       // We have degenerated from outside the cycle, which means something is bad with
136       // the heap, most probably heavy humongous fragmentation, or we are very low on free
137       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
138       // we can do the most aggressive degen cycle, which includes processing references and
139       // class unloading, unless those features are explicitly disabled.
140 
141       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
142       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
143       heap->set_unload_classes(_generation->heuristics()->can_unload_classes() &&
144                                 (!heap->mode()->is_generational() || _generation->is_global()));
145 
146       if (heap->mode()->is_generational()) {
147         // Clean the read table before swapping it. The end goal here is to have a clean
148         // write table, and to have the read table updated with the previous write table.
149         heap->old_generation()->card_scan()->mark_read_table_as_clean();
150 
151         if (_generation->is_young()) {
152           // Swap remembered sets for young
153           _generation->swap_card_tables();
154         }
155       }
156 
157     case _degenerated_roots:
158       // Degenerated from concurrent root mark, reset the flag for STW mark
159       if (!heap->mode()->is_generational()) {
160         if (heap->is_concurrent_mark_in_progress()) {
161           heap->cancel_concurrent_mark();
162         }
163       } else {
164         if (_generation->is_concurrent_mark_in_progress()) {
165           // We want to allow old generation marking to be punctuated by young collections
166           // (even if they have degenerated). If this is a global cycle, we'd have cancelled
167           // the entire old gc before coming into this switch. Note that cancel_marking on
168           // the generation does NOT abandon incomplete SATB buffers as cancel_concurrent_mark does.
169           // We need to separate out the old pointers which is done below.
170           _generation->cancel_marking();
171         }
172 
173         if (_degen_point == ShenandoahDegenPoint::_degenerated_roots) {
174           // We only need this if the concurrent cycle has already swapped the card tables.
175           // Marking will use the 'read' table, but interesting pointers may have been
176           // recorded in the 'write' table in the time between the cancelled concurrent cycle
177           // and this degenerated cycle. These pointers need to be included in the 'read' table
178           // used to scan the remembered set during the STW mark which follows here.
179           _generation->merge_write_table();
180         }
181       }
182 
183       op_reset();
184 
185       // STW mark
186       op_mark();
187 
188     case _degenerated_mark:
189       // No fallthrough. Continue mark, handed over from concurrent mark if
190       // concurrent mark has yet completed
191       if (_degen_point == ShenandoahDegenPoint::_degenerated_mark && heap->is_concurrent_mark_in_progress()) {
192         assert(!ShenandoahBarrierSet::satb_mark_queue_set().get_filter_out_young(),
193                "Should not be filtering out young pointers when concurrent mark degenerates");
194         op_finish_mark();
195       }
196       assert(!heap->cancelled_gc(), "STW mark can not OOM");
197 
198       /* Degen select Collection Set. etc. */
199       op_prepare_evacuation();
200 
201       op_cleanup_early();
202 
203     case _degenerated_evac:
204       // If heuristics thinks we should do the cycle, this flag would be set,
205       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
206       if (heap->is_evacuation_in_progress()) {
207 
208         if (_degen_point == _degenerated_evac) {
209           // Degeneration under oom-evac protocol allows the mutator LRB to expose
210           // references to from-space objects. This is okay, in theory, because we
211           // will come to the safepoint here to complete the evacuations and update
212           // the references. However, if the from-space reference is written to a
213           // region that was EC during final mark or was recycled after final mark
214           // it will not have TAMS or UWM updated. Such a region is effectively
215           // skipped during update references which can lead to crashes and corruption
216           // if the from-space reference is accessed.
217           if (UseTLAB) {
218             heap->labs_make_parsable();
219           }
220 
221           for (size_t i = 0; i < heap->num_regions(); i++) {
222             ShenandoahHeapRegion* r = heap->get_region(i);
223             if (r->is_active() && r->top() > r->get_update_watermark()) {
224               r->set_update_watermark_at_safepoint(r->top());
225             }
226           }
227         }
228 
229         // Degeneration under oom-evac protocol might have left some objects in
230         // collection set un-evacuated. Restart evacuation from the beginning to
231         // capture all objects. For all the objects that are already evacuated,
232         // it would be a simple check, which is supposed to be fast. This is also
233         // safe to do even without degeneration, as CSet iterator is at beginning
234         // in preparation for evacuation anyway.
235         //
236         // Before doing that, we need to make sure we never had any cset-pinned
237         // regions. This may happen if allocation failure happened when evacuating
238         // the about-to-be-pinned object, oom-evac protocol left the object in
239         // the collection set, and then the pin reached the cset region. If we continue
240         // the cycle here, we would trash the cset and alive objects in it. To avoid
241         // it, we fail degeneration right away and slide into Full GC to recover.
242 
243         {
244           heap->sync_pinned_region_status();
245           heap->collection_set()->clear_current_index();
246           ShenandoahHeapRegion* r;
247           while ((r = heap->collection_set()->next()) != nullptr) {
248             if (r->is_pinned()) {
249               op_degenerated_fail();
250               return;
251             }
252           }
253 
254           heap->collection_set()->clear_current_index();
255         }
256         op_evacuate();
257         if (heap->cancelled_gc()) {
258           op_degenerated_fail();
259           return;
260         }
261       } else if (has_in_place_promotions(heap)) {
262         // We have nothing to evacuate, but there are still regions to promote in place.
263         ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_promote_regions);
264         ShenandoahGenerationalHeap::heap()->promote_regions_in_place(_generation, false /* concurrent*/);
265       }
266 
267       // Update collector state regardless of whether there are forwarded objects
268       heap->set_evacuation_in_progress(false);
269       heap->set_concurrent_weak_root_in_progress(false);
270       heap->set_concurrent_strong_root_in_progress(false);
271 
272       // If heuristics thinks we should do the cycle, this flag would be set,
273       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
274       if (heap->has_forwarded_objects()) {
275         op_init_update_refs();
276         assert(!heap->cancelled_gc(), "STW reference update can not OOM");
277       } else {
278         _abbreviated = true;
279       }
280 
281     case _degenerated_update_refs:
282       if (heap->has_forwarded_objects()) {
283         op_update_refs();
284         op_update_roots();
285         assert(!heap->cancelled_gc(), "STW reference update can not OOM");
286       }
287 
288       if (ShenandoahGCStateCheckHotpatch) {
289         // Leaving degenerated GC, we need to flip barriers back to idle.
290         ShenandoahCodeRoots::arm_nmethods();
291         ShenandoahStackWatermark::change_epoch_id();
292       } else {
293         // Disarm nmethods that armed in concurrent cycle.
294         // In above case, update roots should disarm them
295         ShenandoahCodeRoots::disarm_nmethods();
296       }
297 
298       op_cleanup_complete();
299 
300       if (heap->mode()->is_generational()) {
301         ShenandoahGenerationalHeap::heap()->complete_degenerated_cycle();
302       }
303 
304       break;
305     default:
306       ShouldNotReachHere();
307   }
308 
309   if (ShenandoahVerify) {
310     heap->verifier()->verify_after_degenerated(_generation);
311   }
312 
313   if (VerifyAfterGC) {
314     Universe::verify();
315   }
316 
317   // Decide if this cycle made good progress, and, if not, should it upgrade to a full GC.
318   const bool progress = metrics.is_good_progress();
319   ShenandoahCollectorPolicy* policy = heap->shenandoah_policy();
320   policy->record_degenerated(_generation->is_young(), _abbreviated, progress);
321   if (progress) {
322     heap->notify_gc_progress();
323     _generation->heuristics()->record_degenerated();
324     heap->start_idle_span();
325   } else if (policy->should_upgrade_degenerated_gc()) {
326     // Upgrade to full GC, register full-GC impact on heuristics.
327     op_degenerated_futile();
328   } else {
329     _generation->heuristics()->record_degenerated();
330   }
331 }
332 
333 void ShenandoahDegenGC::op_reset() {
334   _generation->prepare_gc();
335 }
336 
337 void ShenandoahDegenGC::op_mark() {
338   assert(!_generation->is_concurrent_mark_in_progress(), "Should be reset");
339   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_stw_mark);
340   ShenandoahSTWMark mark(_generation, false /*full gc*/);
341   mark.mark();
342 }
343 
344 void ShenandoahDegenGC::op_finish_mark() {
345   ShenandoahConcurrentMark mark(_generation);
346   mark.finish_mark();
347 }
348 
349 void ShenandoahDegenGC::op_prepare_evacuation() {
350   ShenandoahHeap* const heap = ShenandoahHeap::heap();
351   if (ShenandoahVerify) {
352     heap->verifier()->verify_roots_no_forwarded(_generation);
353   }
354 
355   // STW cleanup weak roots and unload classes
356   heap->parallel_cleaning(_generation, false /*full gc*/);
357 
358   // Prepare regions and collection set
359   _generation->prepare_regions_and_collection_set(false /*concurrent*/);
360 
361   // Retire the TLABs, which will force threads to reacquire their TLABs after the pause.
362   // This is needed for two reasons. Strong one: new allocations would be with new freeset,
363   // which would be outside the collection set, so no cset writes would happen there.
364   // Weaker one: new allocations would happen past update watermark, and so less work would
365   // be needed for reference updates (would update the large filler instead).
366   if (UseTLAB) {
367     ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_final_manage_labs);
368     heap->tlabs_retire(false);
369   }
370 
371   if (!heap->collection_set()->is_empty()) {
372     if (ShenandoahVerify) {
373       heap->verifier()->verify_before_evacuation(_generation);
374     }
375 
376     heap->set_evacuation_in_progress(true);
377     heap->set_has_forwarded_objects(true);
378   } else {
379     if (ShenandoahVerify) {
380       if (has_in_place_promotions(heap)) {
381         heap->verifier()->verify_after_concmark_with_promotions(_generation);
382       } else {
383         heap->verifier()->verify_after_concmark(_generation);
384       }
385     }
386 
387     if (VerifyAfterGC) {
388       Universe::verify();
389     }
390   }
391 }
392 
393 bool ShenandoahDegenGC::has_in_place_promotions(const ShenandoahHeap* heap) const {
394   return heap->mode()->is_generational() && heap->old_generation()->has_in_place_promotions();
395 }
396 
397 void ShenandoahDegenGC::op_cleanup_early() {
398   ShenandoahHeap::heap()->recycle_trash();
399 }
400 
401 void ShenandoahDegenGC::op_evacuate() {
402   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_stw_evac);
403   ShenandoahHeap::heap()->evacuate_collection_set(_generation, false /* concurrent*/);
404 }
405 
406 void ShenandoahDegenGC::op_init_update_refs() {
407   // Evacuation has completed
408   ShenandoahHeap* const heap = ShenandoahHeap::heap();
409   heap->prepare_update_heap_references();
410   heap->set_update_refs_in_progress(true);
411 }
412 
413 void ShenandoahDegenGC::op_update_refs() {
414   ShenandoahHeap* const heap = ShenandoahHeap::heap();
415   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_update_refs);
416   // Handed over from concurrent update references phase
417   heap->update_heap_references(_generation, false /*concurrent*/);
418 
419   heap->set_update_refs_in_progress(false);
420   heap->set_has_forwarded_objects(false);
421 }
422 
423 void ShenandoahDegenGC::op_update_roots() {
424   ShenandoahHeap* const heap = ShenandoahHeap::heap();
425 
426   update_roots(false /*full_gc*/);
427 
428   heap->update_heap_region_states(false /*concurrent*/);
429 
430   if (ShenandoahVerify) {
431     heap->verifier()->verify_after_update_refs(_generation);
432   }
433 
434   if (VerifyAfterGC) {
435     Universe::verify();
436   }
437 
438   heap->rebuild_free_set(false /*concurrent*/);
439 }
440 
441 void ShenandoahDegenGC::op_cleanup_complete() {
442   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_cleanup_complete);
443   ShenandoahHeap::heap()->recycle_trash();
444 }
445 
446 void ShenandoahDegenGC::op_degenerated_fail() {
447   upgrade_to_full();
448 }
449 
450 void ShenandoahDegenGC::op_degenerated_futile() {
451   upgrade_to_full();
452 }
453 
454 const char* ShenandoahDegenGC::degen_event_message(ShenandoahDegenPoint point) const {
455   switch (point) {
456     case _degenerated_unset:
457       SHENANDOAH_RETURN_EVENT_MESSAGE(_generation->type(), "Pause Degenerated GC", " (<UNSET>)");
458     case _degenerated_outside_cycle:
459       SHENANDOAH_RETURN_EVENT_MESSAGE(_generation->type(), "Pause Degenerated GC", " (Outside of Cycle)");
460     case _degenerated_roots:
461       SHENANDOAH_RETURN_EVENT_MESSAGE(_generation->type(), "Pause Degenerated GC", " (Roots)");
462     case _degenerated_mark:
463       SHENANDOAH_RETURN_EVENT_MESSAGE(_generation->type(), "Pause Degenerated GC", " (Mark)");
464     case _degenerated_evac:
465       SHENANDOAH_RETURN_EVENT_MESSAGE(_generation->type(), "Pause Degenerated GC", " (Evacuation)");
466     case _degenerated_update_refs:
467       SHENANDOAH_RETURN_EVENT_MESSAGE(_generation->type(), "Pause Degenerated GC", " (Update Refs)");
468     default:
469       ShouldNotReachHere();
470       SHENANDOAH_RETURN_EVENT_MESSAGE(_generation->type(), "Pause Degenerated GC", " (?)");
471   }
472 }
473 
474 void ShenandoahDegenGC::upgrade_to_full() {
475   log_info(gc)("Degenerated GC upgrading to Full GC");
476   ShenandoahHeap* heap = ShenandoahHeap::heap();
477   heap->cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
478   heap->increment_total_collections(true);
479   heap->shenandoah_policy()->record_degenerated_upgrade_to_full();
480   ShenandoahFullGC full_gc;
481   full_gc.op_full(GCCause::_shenandoah_upgrade_to_full_gc);
482 }