1 /*
   2  * Copyright (c) 2017, Oracle and/or its affiliates. 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 "code/codeCache.hpp"
  27 #include "gc/g1/g1CollectedHeap.hpp"
  28 #include "gc/g1/g1CollectorPolicy.hpp"
  29 #include "gc/g1/g1FullCollector.hpp"
  30 #include "gc/g1/g1FullGCAdjustTask.hpp"
  31 #include "gc/g1/g1FullGCCompactTask.hpp"
  32 #include "gc/g1/g1FullGCMarker.inline.hpp"
  33 #include "gc/g1/g1FullGCMarkTask.hpp"
  34 #include "gc/g1/g1FullGCPrepareTask.hpp"
  35 #include "gc/g1/g1FullGCReferenceProcessorExecutor.hpp"
  36 #include "gc/g1/g1FullGCScope.hpp"
  37 #include "gc/g1/g1OopClosures.hpp"
  38 #include "gc/g1/g1Policy.hpp"
  39 #include "gc/g1/g1StringDedup.hpp"
  40 #include "gc/shared/adaptiveSizePolicy.hpp"
  41 #include "gc/shared/gcTraceTime.inline.hpp"
  42 #include "gc/shared/preservedMarks.hpp"
  43 #include "gc/shared/referenceProcessor.hpp"
  44 #include "gc/shared/weakProcessor.hpp"
  45 #include "logging/log.hpp"
  46 #include "runtime/biasedLocking.hpp"
  47 #include "runtime/handles.inline.hpp"
  48 #include "utilities/debug.hpp"
  49 
  50 static void clear_and_activate_derived_pointers() {
  51 #if COMPILER2_OR_JVMCI
  52   DerivedPointerTable::clear();
  53 #endif
  54 }
  55 
  56 static void deactivate_derived_pointers() {
  57 #if COMPILER2_OR_JVMCI
  58   DerivedPointerTable::set_active(false);
  59 #endif
  60 }
  61 
  62 static void update_derived_pointers() {
  63 #if COMPILER2_OR_JVMCI
  64   DerivedPointerTable::update_pointers();
  65 #endif
  66 }
  67 
  68 G1CMBitMap* G1FullCollector::mark_bitmap() {
  69   return _heap->concurrent_mark()->next_mark_bitmap();
  70 }
  71 
  72 ReferenceProcessor* G1FullCollector::reference_processor() {
  73   return _heap->ref_processor_stw();
  74 }
  75 
  76 uint G1FullCollector::calc_active_workers() {
  77   G1CollectedHeap* heap = G1CollectedHeap::heap();
  78   uint max_worker_count = heap->workers()->total_workers();
  79   // Only calculate number of workers if UseDynamicNumberOfGCThreads
  80   // is enabled, otherwise use max.
  81   if (!UseDynamicNumberOfGCThreads) {
  82     return max_worker_count;
  83   }
  84 
  85   // Consider G1HeapWastePercent to decide max number of workers. Each worker
  86   // will in average cause half a region waste.
  87   uint max_wasted_regions_allowed = ((heap->num_regions() * G1HeapWastePercent) / 100);
  88   uint waste_worker_count = MAX2((max_wasted_regions_allowed * 2) , 1u);
  89   uint heap_waste_worker_limit = MIN2(waste_worker_count, max_worker_count);
  90 
  91   // Also consider HeapSizePerGCThread by calling AdaptiveSizePolicy to calculate
  92   // the number of workers.
  93   uint current_active_workers = heap->workers()->active_workers();
  94   uint adaptive_worker_limit = AdaptiveSizePolicy::calc_active_workers(max_worker_count, current_active_workers, 0);
  95 
  96   // Update active workers to the lower of the limits.
  97   uint worker_count = MIN2(heap_waste_worker_limit, adaptive_worker_limit);
  98   log_debug(gc, task)("Requesting %u active workers for full compaction (waste limited workers: %u, adaptive workers: %u)",
  99                       worker_count, heap_waste_worker_limit, adaptive_worker_limit);
 100   worker_count = heap->workers()->update_active_workers(worker_count);
 101   log_info(gc, task)("Using %u workers of %u for full compaction", worker_count, max_worker_count);
 102 
 103   return worker_count;
 104 }
 105 
 106 G1FullCollector::G1FullCollector(G1CollectedHeap* heap, GCMemoryManager* memory_manager, bool explicit_gc, bool clear_soft_refs) :
 107     _heap(heap),
 108     _scope(memory_manager, explicit_gc, clear_soft_refs),
 109     _num_workers(calc_active_workers()),
 110     _oop_queue_set(_num_workers),
 111     _array_queue_set(_num_workers),
 112     _preserved_marks_set(true),
 113     _serial_compaction_point(),
 114     _is_alive(heap->concurrent_mark()->next_mark_bitmap()),
 115     _is_alive_mutator(heap->ref_processor_stw(), &_is_alive) {
 116   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
 117 
 118   _preserved_marks_set.init(_num_workers);
 119   _markers = NEW_C_HEAP_ARRAY(G1FullGCMarker*, _num_workers, mtGC);
 120   _compaction_points = NEW_C_HEAP_ARRAY(G1FullGCCompactionPoint*, _num_workers, mtGC);
 121   for (uint i = 0; i < _num_workers; i++) {
 122     _markers[i] = new G1FullGCMarker(i, _preserved_marks_set.get(i), mark_bitmap());
 123     _compaction_points[i] = new G1FullGCCompactionPoint();
 124     _oop_queue_set.register_queue(i, marker(i)->oop_stack());
 125     _array_queue_set.register_queue(i, marker(i)->objarray_stack());
 126   }
 127 }
 128 
 129 G1FullCollector::~G1FullCollector() {
 130   for (uint i = 0; i < _num_workers; i++) {
 131     delete _markers[i];
 132     delete _compaction_points[i];
 133   }
 134   FREE_C_HEAP_ARRAY(G1FullGCMarker*, _markers);
 135   FREE_C_HEAP_ARRAY(G1FullGCCompactionPoint*, _compaction_points);
 136 }
 137 
 138 void G1FullCollector::prepare_collection() {
 139   _heap->g1_policy()->record_full_collection_start();
 140 
 141   _heap->print_heap_before_gc();
 142   _heap->print_heap_regions();
 143 
 144   _heap->abort_concurrent_cycle();
 145   _heap->verify_before_full_collection(scope()->is_explicit_gc());
 146 
 147   _heap->gc_prologue(true);
 148   _heap->prepare_heap_for_full_collection();
 149 
 150   reference_processor()->enable_discovery();
 151   reference_processor()->setup_policy(scope()->should_clear_soft_refs());
 152 
 153   // When collecting the permanent generation Method*s may be moving,
 154   // so we either have to flush all bcp data or convert it into bci.
 155   CodeCache::gc_prologue();
 156 
 157   // We should save the marks of the currently locked biased monitors.
 158   // The marking doesn't preserve the marks of biased objects.
 159   BiasedLocking::preserve_marks();
 160 
 161   // Clear and activate derived pointer collection.
 162   clear_and_activate_derived_pointers();
 163 }
 164 
 165 void G1FullCollector::collect() {
 166   phase1_mark_live_objects();
 167   verify_after_marking();
 168 
 169   // Don't add any more derived pointers during later phases
 170   deactivate_derived_pointers();
 171 
 172   phase2_prepare_compaction();
 173 
 174   phase3_adjust_pointers();
 175 
 176   phase4_do_compaction();
 177 }
 178 
 179 void G1FullCollector::complete_collection() {
 180   // Restore all marks.
 181   restore_marks();
 182 
 183   // When the pointers have been adjusted and moved, we can
 184   // update the derived pointer table.
 185   update_derived_pointers();
 186 
 187   BiasedLocking::restore_marks();
 188   CodeCache::gc_epilogue();
 189   JvmtiExport::gc_epilogue();
 190 
 191   _heap->prepare_heap_for_mutators();
 192 
 193   _heap->g1_policy()->record_full_collection_end();
 194   _heap->gc_epilogue(true);
 195 
 196   _heap->verify_after_full_collection();
 197 
 198   _heap->print_heap_after_full_collection(scope()->heap_transition());
 199 }
 200 
 201 void G1FullCollector::phase1_mark_live_objects() {
 202   // Recursively traverse all live objects and mark them.
 203   GCTraceTime(Info, gc, phases) info("Phase 1: Mark live objects", scope()->timer());
 204 
 205   // Do the actual marking.
 206   G1FullGCMarkTask marking_task(this);
 207   run_task(&marking_task);
 208 
 209   // Process references discovered during marking.
 210   G1FullGCReferenceProcessingExecutor reference_processing(this);
 211   reference_processing.execute(scope()->timer(), scope()->tracer());
 212 
 213   // Weak oops cleanup.
 214   {
 215     GCTraceTime(Debug, gc, phases) trace("Phase 1: Weak Processing", scope()->timer());
 216     WeakProcessor::weak_oops_do(&_is_alive, &do_nothing_cl);
 217   }
 218 
 219   // Class unloading and cleanup.
 220   if (ClassUnloading) {
 221     GCTraceTime(Debug, gc, phases) debug("Phase 1: Class Unloading and Cleanup", scope()->timer());
 222     // Unload classes and purge the SystemDictionary.
 223     bool purged_class = SystemDictionary::do_unloading(&_is_alive, scope()->timer());
 224     _heap->complete_cleaning(&_is_alive, purged_class);
 225   } else {
 226     GCTraceTime(Debug, gc, phases) debug("Phase 1: String and Symbol Tables Cleanup", scope()->timer());
 227     // If no class unloading just clean out strings and symbols.
 228     _heap->partial_cleaning(&_is_alive, true, true, G1StringDedup::is_enabled());
 229   }
 230 
 231   scope()->tracer()->report_object_count_after_gc(&_is_alive);
 232 }
 233 
 234 void G1FullCollector::phase2_prepare_compaction() {
 235   GCTraceTime(Info, gc, phases) info("Phase 2: Prepare for compaction", scope()->timer());
 236   G1FullGCPrepareTask task(this);
 237   run_task(&task);
 238 
 239   // To avoid OOM when there is memory left.
 240   if (!task.has_freed_regions()) {
 241     task.prepare_serial_compaction();
 242   }
 243 }
 244 
 245 void G1FullCollector::phase3_adjust_pointers() {
 246   // Adjust the pointers to reflect the new locations
 247   GCTraceTime(Info, gc, phases) info("Phase 3: Adjust pointers and remembered sets", scope()->timer());
 248 
 249   G1FullGCAdjustTask task(this);
 250   run_task(&task);
 251 }
 252 
 253 void G1FullCollector::phase4_do_compaction() {
 254   // Compact the heap using the compaction queues created in phase 2.
 255   GCTraceTime(Info, gc, phases) info("Phase 4: Compact heap", scope()->timer());
 256   G1FullGCCompactTask task(this);
 257   run_task(&task);
 258 
 259   // Serial compact to avoid OOM when very few free regions.
 260   if (serial_compaction_point()->has_regions()) {
 261     task.serial_compaction();
 262   }
 263 }
 264 
 265 void G1FullCollector::restore_marks() {
 266   SharedRestorePreservedMarksTaskExecutor task_executor(_heap->workers());
 267   _preserved_marks_set.restore(&task_executor);
 268   _preserved_marks_set.reclaim();
 269 }
 270 
 271 void G1FullCollector::run_task(AbstractGangTask* task) {
 272   _heap->workers()->run_task(task, _num_workers);
 273 }
 274 
 275 void G1FullCollector::verify_after_marking() {
 276   if (!VerifyDuringGC || !_heap->verifier()->should_verify(G1HeapVerifier::G1VerifyFull)) {
 277     // Only do verification if VerifyDuringGC and G1VerifyFull is set.
 278     return;
 279   }
 280 
 281   HandleMark hm;  // handle scope
 282 #if COMPILER2_OR_JVMCI
 283   DerivedPointerTableDeactivate dpt_deact;
 284 #endif
 285   _heap->prepare_for_verify();
 286   // Note: we can verify only the heap here. When an object is
 287   // marked, the previous value of the mark word (including
 288   // identity hash values, ages, etc) is preserved, and the mark
 289   // word is set to markOop::marked_value - effectively removing
 290   // any hash values from the mark word. These hash values are
 291   // used when verifying the dictionaries and so removing them
 292   // from the mark word can make verification of the dictionaries
 293   // fail. At the end of the GC, the original mark word values
 294   // (including hash values) are restored to the appropriate
 295   // objects.
 296   GCTraceTime(Info, gc, verify)("Verifying During GC (full)");
 297   _heap->verify(VerifyOption_G1UseFullMarking);
 298 }