1 /*
  2  * Copyright (c) 2013, 2021, Red Hat, Inc. All rights reserved.
  3  * Copyright (C) 2022 THL A29 Limited, a Tencent company. 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 #include "precompiled.hpp"
 27 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
 28 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
 29 #include "gc/shenandoah/shenandoahControlThread.hpp"
 30 #include "gc/shenandoah/shenandoahDegeneratedGC.hpp"
 31 #include "gc/shenandoah/shenandoahFreeSet.hpp"
 32 #include "gc/shenandoah/shenandoahFullGC.hpp"
 33 #include "gc/shenandoah/shenandoahGeneration.hpp"
 34 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 35 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
 36 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
 37 #include "gc/shenandoah/shenandoahUtils.hpp"
 38 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
 39 #include "gc/shenandoah/mode/shenandoahMode.hpp"
 40 #include "logging/log.hpp"
 41 #include "memory/metaspaceUtils.hpp"
 42 #include "memory/metaspaceStats.hpp"
 43 
 44 ShenandoahControlThread::ShenandoahControlThread() :
 45   ShenandoahController(),
 46   _requested_gc_cause(GCCause::_no_cause_specified),
 47   _degen_point(ShenandoahGC::_degenerated_outside_cycle) {
 48   set_name("Shenandoah Control Thread");
 49   create_and_start();
 50 }
 51 
 52 void ShenandoahControlThread::run_service() {
 53   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 54   const GCMode default_mode = concurrent_normal;
 55   const GCCause::Cause default_cause = GCCause::_shenandoah_concurrent_gc;
 56   int sleep = ShenandoahControlIntervalMin;
 57 
 58   double last_sleep_adjust_time = os::elapsedTime();
 59 
 60   ShenandoahCollectorPolicy* const policy = heap->shenandoah_policy();
 61   ShenandoahHeuristics* const heuristics = heap->heuristics();
 62   while (!should_terminate()) {
 63     const GCCause::Cause cancelled_cause = heap->cancelled_cause();
 64     if (cancelled_cause == GCCause::_shenandoah_stop_vm) {
 65       break;
 66     }
 67 
 68     // Figure out if we have pending requests.
 69     const bool alloc_failure_pending = ShenandoahCollectorPolicy::is_allocation_failure(cancelled_cause);
 70     const bool is_gc_requested = _gc_requested.is_set();
 71     const GCCause::Cause requested_gc_cause = _requested_gc_cause;
 72 
 73     // This control loop iteration has seen this much allocation.
 74     const size_t allocs_seen = reset_allocs_seen();
 75 
 76     // Choose which GC mode to run in. The block below should select a single mode.
 77     GCMode mode = none;
 78     GCCause::Cause cause = GCCause::_last_gc_cause;
 79     ShenandoahGC::ShenandoahDegenPoint degen_point = ShenandoahGC::_degenerated_unset;
 80 
 81     if (alloc_failure_pending) {
 82       // Allocation failure takes precedence: we have to deal with it first thing
 83       heuristics->log_trigger("Handle Allocation Failure");
 84 
 85       cause = GCCause::_allocation_failure;
 86 
 87       // Consume the degen point, and seed it with default value
 88       degen_point = _degen_point;
 89       _degen_point = ShenandoahGC::_degenerated_outside_cycle;
 90 
 91       if (ShenandoahDegeneratedGC && heuristics->should_degenerate_cycle()) {
 92         heuristics->record_allocation_failure_gc();
 93         policy->record_alloc_failure_to_degenerated(degen_point);
 94         mode = stw_degenerated;
 95       } else {
 96         heuristics->record_allocation_failure_gc();
 97         policy->record_alloc_failure_to_full();
 98         mode = stw_full;
 99       }
100     } else if (is_gc_requested) {
101       cause = requested_gc_cause;
102       heuristics->log_trigger("GC request (%s)", GCCause::to_string(cause));
103       heuristics->record_requested_gc();
104 
105       if (ShenandoahCollectorPolicy::should_run_full_gc(cause)) {
106         mode = stw_full;
107       } else {
108         mode = default_mode;
109         // Unload and clean up everything
110         heap->set_unload_classes(heuristics->can_unload_classes());
111       }
112     } else {
113       // Potential normal cycle: ask heuristics if it wants to act
114       if (heuristics->should_start_gc()) {
115         mode = default_mode;
116         cause = default_cause;
117       }
118 
119       // Ask policy if this cycle wants to process references or unload classes
120       heap->set_unload_classes(heuristics->should_unload_classes());
121     }
122 
123     // Blow all soft references on this cycle, if handling allocation failure,
124     // either implicit or explicit GC request,  or we are requested to do so unconditionally.
125     if (alloc_failure_pending || is_gc_requested || ShenandoahAlwaysClearSoftRefs) {
126       heap->soft_ref_policy()->set_should_clear_all_soft_refs(true);
127     }
128 
129     const bool gc_requested = (mode != none);
130     assert (!gc_requested || cause != GCCause::_last_gc_cause, "GC cause should be set");
131 
132     if (gc_requested) {
133       // Cannot uncommit bitmap slices during concurrent reset
134       ShenandoahNoUncommitMark forbid_region_uncommit(heap);
135 
136       // GC is starting, bump the internal ID
137       update_gc_id();
138 
139       GCIdMark gc_id_mark;
140 
141       heuristics->cancel_trigger_request();
142 
143       heap->reset_bytes_allocated_since_gc_start();
144 
145       MetaspaceCombinedStats meta_sizes = MetaspaceUtils::get_combined_statistics();
146 
147       // If GC was requested, we are sampling the counters even without actual triggers
148       // from allocation machinery. This captures GC phases more accurately.
149       heap->set_forced_counters_update(true);
150 
151       // If GC was requested, we better dump freeset data for performance debugging
152       heap->free_set()->log_status_under_lock();
153 
154       switch (mode) {
155         case concurrent_normal:
156           service_concurrent_normal_cycle(cause);
157           break;
158         case stw_degenerated:
159           service_stw_degenerated_cycle(cause, degen_point);
160           break;
161         case stw_full:
162           service_stw_full_cycle(cause);
163           break;
164         default:
165           ShouldNotReachHere();
166       }
167 
168       // If this was the requested GC cycle, notify waiters about it
169       if (is_gc_requested) {
170         notify_gc_waiters();
171       }
172 
173       // If this cycle completed without being cancelled, notify waiters about it
174       if (!heap->cancelled_gc()) {
175         notify_alloc_failure_waiters();
176       }
177 
178       // Report current free set state at the end of cycle, whether
179       // it is a normal completion, or the abort.
180       heap->free_set()->log_status_under_lock();
181 
182       {
183         // Notify Universe about new heap usage. This has implications for
184         // global soft refs policy, and we better report it every time heap
185         // usage goes down.
186         ShenandoahHeapLocker locker(heap->lock());
187         heap->update_capacity_and_used_at_gc();
188       }
189 
190       // Signal that we have completed a visit to all live objects.
191       heap->record_whole_heap_examined_timestamp();
192 
193       // Disable forced counters update, and update counters one more time
194       // to capture the state at the end of GC session.
195       heap->handle_force_counters_update();
196       heap->set_forced_counters_update(false);
197 
198       // Retract forceful part of soft refs policy
199       heap->soft_ref_policy()->set_should_clear_all_soft_refs(false);
200 
201       // Clear metaspace oom flag, if current cycle unloaded classes
202       if (heap->unload_classes()) {
203         heuristics->clear_metaspace_oom();
204       }
205 
206       // Commit worker statistics to cycle data
207       heap->phase_timings()->flush_par_workers_to_cycle();
208       if (ShenandoahPacing) {
209         heap->pacer()->flush_stats_to_cycle();
210       }
211 
212       // Print GC stats for current cycle
213       {
214         LogTarget(Info, gc, stats) lt;
215         if (lt.is_enabled()) {
216           ResourceMark rm;
217           LogStream ls(lt);
218           heap->phase_timings()->print_cycle_on(&ls);
219           if (ShenandoahPacing) {
220             heap->pacer()->print_cycle_on(&ls);
221           }
222         }
223       }
224 
225       // Commit statistics to globals
226       heap->phase_timings()->flush_cycle_to_global();
227 
228       // Print Metaspace change following GC (if logging is enabled).
229       MetaspaceUtils::print_metaspace_change(meta_sizes);
230 
231       // GC is over, we are at idle now
232       if (ShenandoahPacing) {
233         heap->pacer()->setup_for_idle();
234       }
235     } else {
236       // Report to pacer that we have seen this many words allocated
237       if (ShenandoahPacing && (allocs_seen > 0)) {
238         heap->pacer()->report_alloc(allocs_seen);
239       }
240     }
241 
242     // Check if we have seen a new target for soft max heap size or if a gc was requested.
243     // Either of these conditions will attempt to uncommit regions.
244     if (ShenandoahUncommit) {
245       if (heap->check_soft_max_changed()) {
246         heap->notify_soft_max_changed();
247       } else if (is_gc_requested) {
248         heap->notify_explicit_gc_requested();
249       }
250     }
251 
252     // Wait before performing the next action. If allocation happened during this wait,
253     // we exit sooner, to let heuristics re-evaluate new conditions. If we are at idle,
254     // back off exponentially.
255     const double current = os::elapsedTime();
256     if (heap->has_changed()) {
257       sleep = ShenandoahControlIntervalMin;
258     } else if ((current - last_sleep_adjust_time) * 1000 > ShenandoahControlIntervalAdjustPeriod){
259       sleep = MIN2<int>(ShenandoahControlIntervalMax, MAX2(1, sleep * 2));
260       last_sleep_adjust_time = current;
261     }
262     os::naked_short_sleep(sleep);
263   }
264 }
265 
266 void ShenandoahControlThread::service_concurrent_normal_cycle(GCCause::Cause cause) {
267   // Normal cycle goes via all concurrent phases. If allocation failure (af) happens during
268   // any of the concurrent phases, it first degrades to Degenerated GC and completes GC there.
269   // If second allocation failure happens during Degenerated GC cycle (for example, when GC
270   // tries to evac something and no memory is available), cycle degrades to Full GC.
271   //
272   // There are also a shortcut through the normal cycle: immediate garbage shortcut, when
273   // heuristics says there are no regions to compact, and all the collection comes from immediately
274   // reclaimable regions.
275   //
276   // ................................................................................................
277   //
278   //                                    (immediate garbage shortcut)                Concurrent GC
279   //                             /-------------------------------------------\
280   //                             |                                           |
281   //                             |                                           |
282   //                             |                                           |
283   //                             |                                           v
284   // [START] ----> Conc Mark ----o----> Conc Evac --o--> Conc Update-Refs ---o----> [END]
285   //                   |                    |                 |              ^
286   //                   | (af)               | (af)            | (af)         |
287   // ..................|....................|.................|..............|.......................
288   //                   |                    |                 |              |
289   //                   |                    |                 |              |      Degenerated GC
290   //                   v                    v                 v              |
291   //               STW Mark ----------> STW Evac ----> STW Update-Refs ----->o
292   //                   |                    |                 |              ^
293   //                   | (af)               | (af)            | (af)         |
294   // ..................|....................|.................|..............|.......................
295   //                   |                    |                 |              |
296   //                   |                    v                 |              |      Full GC
297   //                   \------------------->o<----------------/              |
298   //                                        |                                |
299   //                                        v                                |
300   //                                      Full GC  --------------------------/
301   //
302   ShenandoahHeap* heap = ShenandoahHeap::heap();
303   if (check_cancellation_or_degen(ShenandoahGC::_degenerated_outside_cycle)) return;
304 
305   ShenandoahGCSession session(cause, heap->global_generation());
306 
307   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
308 
309   ShenandoahConcurrentGC gc(heap->global_generation(), false);
310   if (gc.collect(cause)) {
311     // Cycle is complete.  There were no failed allocation requests and no degeneration, so count this as good progress.
312     heap->notify_gc_progress();
313     heap->global_generation()->heuristics()->record_success_concurrent();
314     heap->shenandoah_policy()->record_success_concurrent(false, gc.abbreviated());
315     heap->log_heap_status("At end of GC");
316   } else {
317     assert(heap->cancelled_gc(), "Must have been cancelled");
318     check_cancellation_or_degen(gc.degen_point());
319     heap->log_heap_status("At end of cancelled GC");
320   }
321 }
322 
323 bool ShenandoahControlThread::check_cancellation_or_degen(ShenandoahGC::ShenandoahDegenPoint point) {
324   ShenandoahHeap* heap = ShenandoahHeap::heap();
325   if (heap->cancelled_gc()) {
326     if (heap->cancelled_cause() == GCCause::_shenandoah_stop_vm) {
327       return true;
328     }
329 
330     if (ShenandoahCollectorPolicy::is_allocation_failure(heap->cancelled_cause())) {
331       assert (_degen_point == ShenandoahGC::_degenerated_outside_cycle,
332               "Should not be set yet: %s", ShenandoahGC::degen_point_to_string(_degen_point));
333       _degen_point = point;
334       return true;
335     }
336 
337     fatal("Unexpected reason for cancellation: %s", GCCause::to_string(heap->cancelled_cause()));
338   }
339   return false;
340 }
341 
342 void ShenandoahControlThread::stop_service() {
343   ShenandoahHeap::heap()->cancel_gc(GCCause::_shenandoah_stop_vm);
344 }
345 
346 void ShenandoahControlThread::service_stw_full_cycle(GCCause::Cause cause) {
347   ShenandoahHeap* const heap = ShenandoahHeap::heap();
348   ShenandoahGCSession session(cause, heap->global_generation());
349 
350   ShenandoahFullGC gc;
351   gc.collect(cause);
352 }
353 
354 void ShenandoahControlThread::service_stw_degenerated_cycle(GCCause::Cause cause, ShenandoahGC::ShenandoahDegenPoint point) {
355   assert (point != ShenandoahGC::_degenerated_unset, "Degenerated point should be set");
356   ShenandoahHeap* const heap = ShenandoahHeap::heap();
357   ShenandoahGCSession session(cause, heap->global_generation());
358 
359   ShenandoahDegenGC gc(point, heap->global_generation());
360   gc.collect(cause);
361 }
362 
363 void ShenandoahControlThread::request_gc(GCCause::Cause cause) {
364   if (ShenandoahCollectorPolicy::should_handle_requested_gc(cause)) {
365     handle_requested_gc(cause);
366   }
367 }
368 
369 void ShenandoahControlThread::handle_requested_gc(GCCause::Cause cause) {
370   if (should_terminate()) {
371     log_info(gc)("Control thread is terminating, no more GCs");
372     return;
373   }
374 
375   // For normal requested GCs (System.gc) we want to block the caller. However,
376   // for whitebox requested GC, we want to initiate the GC and return immediately.
377   // The whitebox caller thread will arrange for itself to wait until the GC notifies
378   // it that has reached the requested breakpoint (phase in the GC).
379   if (cause == GCCause::_wb_breakpoint) {
380     _requested_gc_cause = cause;
381     _gc_requested.set();
382     return;
383   }
384 
385   // Make sure we have at least one complete GC cycle before unblocking
386   // from the explicit GC request.
387   //
388   // This is especially important for weak references cleanup and/or native
389   // resources (e.g. DirectByteBuffers) machinery: when explicit GC request
390   // comes very late in the already running cycle, it would miss lots of new
391   // opportunities for cleanup that were made available before the caller
392   // requested the GC.
393 
394   MonitorLocker ml(&_gc_waiters_lock);
395   size_t current_gc_id = get_gc_id();
396   size_t required_gc_id = current_gc_id + 1;
397   while (current_gc_id < required_gc_id && !should_terminate()) {
398     // Although setting gc request is under _gc_waiters_lock, but read side (run_service())
399     // does not take the lock. We need to enforce following order, so that read side sees
400     // latest requested gc cause when the flag is set.
401     _requested_gc_cause = cause;
402     _gc_requested.set();
403 
404     ml.wait();
405     current_gc_id = get_gc_id();
406   }
407 }
408 
409 void ShenandoahControlThread::notify_gc_waiters() {
410   _gc_requested.unset();
411   MonitorLocker ml(&_gc_waiters_lock);
412   ml.notify_all();
413 }