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/shenandoahOldGeneration.hpp"
 37 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
 38 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
 39 #include "gc/shenandoah/shenandoahSTWMark.hpp"
 40 #include "gc/shenandoah/shenandoahUtils.hpp"
 41 #include "gc/shenandoah/shenandoahVerifier.hpp"
 42 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
 43 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
 44 #include "gc/shenandoah/shenandoahVMOperations.hpp"
 45 #include "runtime/vmThread.hpp"
 46 #include "utilities/events.hpp"
 47 
 48 ShenandoahDegenGC::ShenandoahDegenGC(ShenandoahDegenPoint degen_point, ShenandoahGeneration* generation) :
 49   ShenandoahGC(),
 50   _degen_point(degen_point),
 51   _generation(generation),
 52   _upgraded_to_full(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     size_t old_available = heap->old_generation()->available();
 60     size_t young_available = heap->young_generation()->available();
 61     log_info(gc, ergo)("At end of Degenerated GC, old_available: " SIZE_FORMAT "%s, young_available: " SIZE_FORMAT "%s",
 62                        byte_size_in_proper_unit(old_available), proper_unit_for_byte_size(old_available),
 63                        byte_size_in_proper_unit(young_available), proper_unit_for_byte_size(young_available));
 64   }
 65   return true;
 66 }
 67 
 68 void ShenandoahDegenGC::vmop_degenerated() {
 69   TraceCollectorStats tcs(ShenandoahHeap::heap()->monitoring_support()->full_stw_collection_counters());
 70   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::degen_gc_gross);
 71   VM_ShenandoahDegeneratedGC degenerated_gc(this);
 72   VMThread::execute(&degenerated_gc);
 73 }
 74 
 75 void ShenandoahDegenGC::entry_degenerated() {
 76   char msg[1024];
 77   degen_event_message(_degen_point, msg, sizeof(msg));
 78   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::degen_gc, true /* log_heap_usage */);
 79   EventMark em("%s", msg);
 80   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 81 
 82   // In case degenerated GC preempted evacuation or update-refs, clear the aging cycle now.  No harm in clearing it
 83   // redundantly if it is already clear.  We don't age during degenerated cycles.
 84   heap->set_aging_cycle(false);
 85 
 86   ShenandoahWorkerScope scope(heap->workers(),
 87                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
 88                               "stw degenerated gc");
 89 
 90   heap->set_degenerated_gc_in_progress(true);
 91   op_degenerated();
 92   heap->set_degenerated_gc_in_progress(false);
 93 }
 94 
 95 void ShenandoahDegenGC::op_degenerated() {
 96   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 97   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
 98   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
 99   // some phase, we have to upgrade the Degenerate GC to Full GC.
100   heap->clear_cancelled_gc(true /* clear oom handler */);
101 
102 #ifdef ASSERT
103   if (heap->mode()->is_generational()) {
104     if (_generation->generation_mode() == GenerationMode::GLOBAL) {
105       // We can only get to a degenerated global cycle _after_ a concurrent global cycle
106       // has been cancelled. In which case, we expect the concurrent global cycle to have
107       // cancelled the old gc already.
108       assert(!heap->is_old_gc_active(), "Old GC should not be active during global cycle.");
109     }
110 
111     if (!heap->is_concurrent_old_mark_in_progress()) {
112       // If we are not marking the old generation, there should be nothing in the old mark queues
113       assert(heap->old_generation()->task_queues()->is_empty(), "Old gen task queues should be empty.");
114     }
115   }
116 #endif
117 
118   ShenandoahMetricsSnapshot metrics;
119   metrics.snap_before();
120 
121   switch (_degen_point) {
122     // The cases below form the Duff's-like device: it describes the actual GC cycle,
123     // but enters it at different points, depending on which concurrent phase had
124     // degenerated.
125 
126     case _degenerated_outside_cycle:
127       // We have degenerated from outside the cycle, which means something is bad with
128       // the heap, most probably heavy humongous fragmentation, or we are very low on free
129       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
130       // we can do the most aggressive degen cycle, which includes processing references and
131       // class unloading, unless those features are explicitly disabled.
132 
133       if (heap->is_concurrent_old_mark_in_progress()) {
134         // We have come straight into a degenerated cycle without running a concurrent cycle
135         // first and the SATB barrier is enabled to support concurrent old marking. The SATB buffer
136         // may hold a mix of old and young pointers. The old pointers need to be transferred
137         // to the old generation mark queues and the young pointers are _not_ part of this
138         // snapshot, so they must be dropped here.
139         heap->transfer_old_pointers_from_satb();
140       }
141 
142       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
143       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
144       heap->set_unload_classes((!heap->mode()->is_generational() || _generation->generation_mode() == GLOBAL) && _generation->heuristics()->can_unload_classes());
145 
146       if (heap->mode()->is_generational() && (_generation->generation_mode() == YOUNG || (_generation->generation_mode() == GLOBAL && ShenandoahVerify))) {
147         // Swap remembered sets for young, or if the verifier will run during a global collect
148         _generation->swap_remembered_set();
149       }
150 
151     case _degenerated_roots:
152       // Degenerated from concurrent root mark, reset the flag for STW mark
153       if (!heap->mode()->is_generational()) {
154         if (heap->is_concurrent_mark_in_progress()) {
155           heap->cancel_concurrent_mark();
156         }
157       } else {
158         if (_generation->is_concurrent_mark_in_progress()) {
159           // We want to allow old generation marking to be punctuated by young collections
160           // (even if they have degenerated). If this is a global cycle, we'd have cancelled
161           // the entire old gc before coming into this switch.
162           _generation->cancel_marking();
163         }
164       }
165 
166       if (_degen_point == ShenandoahDegenPoint::_degenerated_roots) {
167         // We only need this if the concurrent cycle has already swapped the card tables.
168         // Marking will use the 'read' table, but interesting pointers may have been
169         // recorded in the 'write' table in the time between the cancelled concurrent cycle
170         // and this degenerated cycle. These pointers need to be included the 'read' table
171         // used to scan the remembered set during the STW mark which follows here.
172         _generation->merge_write_table();
173       }
174 
175       op_reset();
176 
177       // STW mark
178       op_mark();
179 
180     case _degenerated_mark:
181       // No fallthrough. Continue mark, handed over from concurrent mark if
182       // concurrent mark has yet completed
183       if (_degen_point == ShenandoahDegenPoint::_degenerated_mark &&
184           heap->is_concurrent_mark_in_progress()) {
185         op_finish_mark();
186       }
187       assert(!heap->cancelled_gc(), "STW mark can not OOM");
188 
189       /* Degen select Collection Set. etc. */
190       op_prepare_evacuation();
191 
192       op_cleanup_early();
193 
194     case _degenerated_evac:
195 
196       if (heap->mode()->is_generational() && _generation->generation_mode() == GLOBAL) {
197         op_global_coalesce_and_fill();
198       }
199 
200       // If heuristics thinks we should do the cycle, this flag would be set,
201       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
202       if (heap->is_evacuation_in_progress()) {
203 
204         if (_degen_point == _degenerated_evac) {
205           // Degeneration under oom-evac protocol allows the mutator LRB to expose
206           // references to from-space objects. This is okay, in theory, because we
207           // will come to the safepoint here to complete the evacuations and update
208           // the references. However, if the from-space reference is written to a
209           // region that was EC during final mark or was recycled after final mark
210           // it will not have TAMS or UWM updated. Such a region is effectively
211           // skipped during update references which can lead to crashes and corruption
212           // if the from-space reference is accessed.
213           if (UseTLAB) {
214             heap->labs_make_parsable();
215           }
216 
217           for (size_t i = 0; i < heap->num_regions(); i++) {
218             ShenandoahHeapRegion* r = heap->get_region(i);
219             if (r->is_active() && r->top() > r->get_update_watermark()) {
220               r->set_update_watermark_at_safepoint(r->top());
221             }
222           }
223         }
224 
225         // Degeneration under oom-evac protocol might have left some objects in
226         // collection set un-evacuated. Restart evacuation from the beginning to
227         // capture all objects. For all the objects that are already evacuated,
228         // it would be a simple check, which is supposed to be fast. This is also
229         // safe to do even without degeneration, as CSet iterator is at beginning
230         // in preparation for evacuation anyway.
231         //
232         // Before doing that, we need to make sure we never had any cset-pinned
233         // regions. This may happen if allocation failure happened when evacuating
234         // the about-to-be-pinned object, oom-evac protocol left the object in
235         // the collection set, and then the pin reached the cset region. If we continue
236         // the cycle here, we would trash the cset and alive objects in it. To avoid
237         // it, we fail degeneration right away and slide into Full GC to recover.
238 
239         {
240           heap->sync_pinned_region_status();
241           heap->collection_set()->clear_current_index();
242           ShenandoahHeapRegion* r;
243           while ((r = heap->collection_set()->next()) != NULL) {
244             if (r->is_pinned()) {
245               heap->cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
246               op_degenerated_fail();
247               return;
248             }
249           }
250 
251           heap->collection_set()->clear_current_index();
252         }
253         op_evacuate();
254         if (heap->cancelled_gc()) {
255           op_degenerated_fail();
256           return;
257         }
258       }
259 
260       // If heuristics thinks we should do the cycle, this flag would be set,
261       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
262       if (heap->has_forwarded_objects()) {
263         op_init_updaterefs();
264         assert(!heap->cancelled_gc(), "STW reference update can not OOM");
265       }
266 
267     case _degenerated_updaterefs:
268       if (heap->has_forwarded_objects()) {
269         op_updaterefs();
270         op_update_roots();
271         assert(!heap->cancelled_gc(), "STW reference update can not OOM");
272       }
273 
274       if (ClassUnloading) {
275          // Disarm nmethods that armed in concurrent cycle.
276          // In above case, update roots should disarm them
277          ShenandoahCodeRoots::disarm_nmethods();
278       }
279 
280       op_cleanup_complete();
281       break;
282     default:
283       ShouldNotReachHere();
284   }
285 
286   if (heap->mode()->is_generational()) {
287     // In case degeneration interrupted concurrent evacuation or update references, we need to clean up transient state.
288     // Otherwise, these actions have no effect.
289 
290     heap->young_generation()->unadjust_available();
291     heap->old_generation()->unadjust_available();
292     // No need to old_gen->increase_used().  That was done when plabs were allocated, accounting for both old evacs and promotions.
293 
294     heap->set_alloc_supplement_reserve(0);
295     heap->set_young_evac_reserve(0);
296     heap->set_old_evac_reserve(0);
297     heap->reset_old_evac_expended();
298     heap->set_promoted_reserve(0);
299   }
300 
301   if (ShenandoahVerify) {
302     heap->verifier()->verify_after_degenerated();
303   }
304 
305   if (VerifyAfterGC) {
306     Universe::verify();
307   }
308 
309   metrics.snap_after();
310 
311   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
312   // because that probably means the heap is overloaded and/or fragmented.
313   if (!metrics.is_good_progress()) {
314     heap->notify_gc_no_progress();
315     heap->cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
316     op_degenerated_futile();
317   } else {
318     heap->notify_gc_progress();
319   }
320 }
321 
322 void ShenandoahDegenGC::op_reset() {
323   _generation->prepare_gc();
324 }
325 
326 void ShenandoahDegenGC::op_mark() {
327   assert(!_generation->is_concurrent_mark_in_progress(), "Should be reset");
328   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_stw_mark);
329   ShenandoahSTWMark mark(_generation, false /*full gc*/);
330   mark.mark();
331 }
332 
333 void ShenandoahDegenGC::op_finish_mark() {
334   ShenandoahConcurrentMark mark(_generation);
335   mark.finish_mark();
336 }
337 
338 void ShenandoahDegenGC::op_prepare_evacuation() {
339   ShenandoahHeap* const heap = ShenandoahHeap::heap();
340   if (ShenandoahVerify) {
341     heap->verifier()->verify_roots_no_forwarded();
342   }
343 
344   // STW cleanup weak roots and unload classes
345   heap->parallel_cleaning(false /*full gc*/);
346 
347   // Prepare regions and collection set
348   _generation->prepare_regions_and_collection_set(false /*concurrent*/);
349 
350   // Retire the TLABs, which will force threads to reacquire their TLABs after the pause.
351   // This is needed for two reasons. Strong one: new allocations would be with new freeset,
352   // which would be outside the collection set, so no cset writes would happen there.
353   // Weaker one: new allocations would happen past update watermark, and so less work would
354   // be needed for reference updates (would update the large filler instead).
355   if (UseTLAB) {
356     ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_final_manage_labs);
357     heap->tlabs_retire(false);
358   }
359 
360   if (!heap->collection_set()->is_empty()) {
361     heap->set_evacuation_in_progress(true);
362     heap->set_has_forwarded_objects(true);
363 
364     if(ShenandoahVerify) {
365       heap->verifier()->verify_during_evacuation();
366     }
367   } else {
368     if (ShenandoahVerify) {
369       heap->verifier()->verify_after_concmark();
370     }
371 
372     if (VerifyAfterGC) {
373       Universe::verify();
374     }
375   }
376 }
377 
378 void ShenandoahDegenGC::op_cleanup_early() {
379   ShenandoahHeap::heap()->recycle_trash();
380 }
381 
382 void ShenandoahDegenGC::op_global_coalesce_and_fill() {
383   ShenandoahHeap::heap()->coalesce_and_fill_old_regions();
384 }
385 
386 void ShenandoahDegenGC::op_evacuate() {
387   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_stw_evac);
388   ShenandoahHeap::heap()->evacuate_collection_set(false /* concurrent*/);
389 }
390 
391 void ShenandoahDegenGC::op_init_updaterefs() {
392   // Evacuation has completed
393   ShenandoahHeap* const heap = ShenandoahHeap::heap();
394   heap->set_evacuation_in_progress(false);
395   heap->set_concurrent_weak_root_in_progress(false);
396   heap->set_concurrent_strong_root_in_progress(false);
397 
398   heap->prepare_update_heap_references(false /*concurrent*/);
399   heap->set_update_refs_in_progress(true);
400 }
401 
402 void ShenandoahDegenGC::op_updaterefs() {
403   ShenandoahHeap* const heap = ShenandoahHeap::heap();
404   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_updaterefs);
405   // Handed over from concurrent update references phase
406   heap->update_heap_references(false /*concurrent*/);
407 
408   heap->set_update_refs_in_progress(false);
409   heap->set_has_forwarded_objects(false);
410 }
411 
412 void ShenandoahDegenGC::op_update_roots() {
413   ShenandoahHeap* const heap = ShenandoahHeap::heap();
414 
415   update_roots(false /*full_gc*/);
416 
417   heap->update_heap_region_states(false /*concurrent*/);
418 
419   if (ShenandoahVerify) {
420     heap->verifier()->verify_after_updaterefs();
421   }
422 
423   if (VerifyAfterGC) {
424     Universe::verify();
425   }
426 
427   heap->rebuild_free_set(false /*concurrent*/);
428 }
429 
430 void ShenandoahDegenGC::op_cleanup_complete() {
431   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_cleanup_complete);
432   ShenandoahHeap::heap()->recycle_trash();
433 }
434 
435 void ShenandoahDegenGC::op_degenerated_fail() {
436   upgrade_to_full();
437   ShenandoahFullGC full_gc;
438   full_gc.op_full(GCCause::_shenandoah_upgrade_to_full_gc);
439 }
440 
441 void ShenandoahDegenGC::op_degenerated_futile() {
442   upgrade_to_full();
443   ShenandoahFullGC full_gc;
444   full_gc.op_full(GCCause::_shenandoah_upgrade_to_full_gc);
445 }
446 
447 void ShenandoahDegenGC::degen_event_message(ShenandoahDegenPoint point, char* buf, size_t len) const {
448   jio_snprintf(buf, len, "Pause Degenerated %s GC (%s)", _generation->name(), ShenandoahGC::degen_point_to_string(point));
449 }
450 
451 void ShenandoahDegenGC::upgrade_to_full() {
452   log_info(gc)("Degenerate GC upgrading to Full GC");
453   ShenandoahHeap::heap()->shenandoah_policy()->record_degenerated_upgrade_to_full();
454   _upgraded_to_full = true;
455 }
456 
457 bool ShenandoahDegenGC::upgraded_to_full() {
458   return _upgraded_to_full;
459 }