1 /*
   2  * Copyright (c) 2000, 2014, 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 "classfile/stringTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "gc_interface/collectedHeap.inline.hpp"
  30 #include "memory/sharedHeap.hpp"
  31 #include "oops/oop.inline.hpp"
  32 #include "runtime/atomic.inline.hpp"
  33 #include "runtime/fprofiler.hpp"
  34 #include "runtime/java.hpp"
  35 #include "services/management.hpp"
  36 #include "utilities/copy.hpp"
  37 #include "utilities/workgroup.hpp"
  38 
  39 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  40 
  41 SharedHeap* SharedHeap::_sh;
  42 
  43 // The set of potentially parallel tasks in root scanning.
  44 enum SH_process_roots_tasks {
  45   SH_PS_Universe_oops_do,
  46   SH_PS_JNIHandles_oops_do,
  47   SH_PS_ObjectSynchronizer_oops_do,
  48   SH_PS_FlatProfiler_oops_do,
  49   SH_PS_Management_oops_do,
  50   SH_PS_SystemDictionary_oops_do,
  51   SH_PS_ClassLoaderDataGraph_oops_do,
  52   SH_PS_jvmti_oops_do,
  53   SH_PS_CodeCache_oops_do,
  54   // Leave this one last.
  55   SH_PS_NumElements
  56 };
  57 
  58 SharedHeap::SharedHeap(CollectorPolicy* policy_) :
  59   CollectedHeap(),
  60   _collector_policy(policy_),
  61   _rem_set(NULL),
  62   _strong_roots_scope(NULL),
  63   _strong_roots_parity(0),
  64   _process_strong_tasks(new SubTasksDone(SH_PS_NumElements)),
  65   _workers(NULL)
  66 {
  67   if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
  68     vm_exit_during_initialization("Failed necessary allocation.");
  69   }
  70   _sh = this;  // ch is static, should be set only once.
  71   if (UseParNewGC ||
  72       UseG1GC ||
  73       (UseConcMarkSweepGC && (CMSParallelInitialMarkEnabled || CMSParallelRemarkEnabled) && use_parallel_gc_threads())) {
  74     _workers = new FlexibleWorkGang("Parallel GC Threads", ParallelGCThreads,
  75                             /* are_GC_task_threads */true,
  76                             /* are_ConcurrentGC_threads */false);
  77     if (_workers == NULL) {
  78       vm_exit_during_initialization("Failed necessary allocation.");
  79     } else {
  80       _workers->initialize_workers();
  81     }
  82   }
  83 }
  84 
  85 int SharedHeap::n_termination() {
  86   return _process_strong_tasks->n_threads();
  87 }
  88 
  89 void SharedHeap::set_n_termination(int t) {
  90   _process_strong_tasks->set_n_threads(t);
  91 }
  92 
  93 bool SharedHeap::heap_lock_held_for_gc() {
  94   Thread* t = Thread::current();
  95   return    Heap_lock->owned_by_self()
  96          || (   (t->is_GC_task_thread() ||  t->is_VM_thread())
  97              && _thread_holds_heap_lock_for_gc);
  98 }
  99 
 100 void SharedHeap::set_par_threads(uint t) {
 101   assert(t == 0 || !UseSerialGC, "Cannot have parallel threads");
 102   _n_par_threads = t;
 103   _process_strong_tasks->set_n_threads(t);
 104 }
 105 
 106 #ifdef ASSERT
 107 class AssertNonScavengableClosure: public OopClosure {
 108 public:
 109   virtual void do_oop(oop* p) {
 110     assert(!Universe::heap()->is_in_partial_collection(*p),
 111       "Referent should not be scavengable.");  }
 112   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
 113 };
 114 static AssertNonScavengableClosure assert_is_non_scavengable_closure;
 115 #endif
 116 
 117 SharedHeap::StrongRootsScope* SharedHeap::active_strong_roots_scope() const {
 118   return _strong_roots_scope;
 119 }
 120 void SharedHeap::register_strong_roots_scope(SharedHeap::StrongRootsScope* scope) {
 121   assert(_strong_roots_scope == NULL, "Should only have one StrongRootsScope active");
 122   assert(scope != NULL, "Illegal argument");
 123   _strong_roots_scope = scope;
 124 }
 125 void SharedHeap::unregister_strong_roots_scope(SharedHeap::StrongRootsScope* scope) {
 126   assert(_strong_roots_scope == scope, "Wrong scope unregistered");
 127   _strong_roots_scope = NULL;
 128 }
 129 
 130 void SharedHeap::change_strong_roots_parity() {
 131   // Also set the new collection parity.
 132   assert(_strong_roots_parity >= 0 && _strong_roots_parity <= 2,
 133          "Not in range.");
 134   _strong_roots_parity++;
 135   if (_strong_roots_parity == 3) _strong_roots_parity = 1;
 136   assert(_strong_roots_parity >= 1 && _strong_roots_parity <= 2,
 137          "Not in range.");
 138 }
 139 
 140 SharedHeap::StrongRootsScope::StrongRootsScope(SharedHeap* heap, bool activate)
 141   : MarkScope(activate), _sh(heap), _n_workers_done_with_threads(0)
 142 {
 143   if (_active) {
 144     _sh->register_strong_roots_scope(this);
 145     _sh->change_strong_roots_parity();
 146     // Zero the claimed high water mark in the StringTable
 147     StringTable::clear_parallel_claimed_index();
 148   }
 149 }
 150 
 151 SharedHeap::StrongRootsScope::~StrongRootsScope() {
 152   if (_active) {
 153     _sh->unregister_strong_roots_scope(this);
 154   }
 155 }
 156 
 157 Monitor* SharedHeap::StrongRootsScope::_lock = new Monitor(Mutex::leaf, "StrongRootsScope lock", false);
 158 
 159 void SharedHeap::StrongRootsScope::mark_worker_done_with_threads(uint n_workers) {
 160   // The Thread work barrier is only needed by G1 Class Unloading.
 161   // No need to use the barrier if this is single-threaded code.
 162   if (UseG1GC && ClassUnloadingWithConcurrentMark && n_workers > 0) {
 163     uint new_value = (uint)Atomic::add(1, &_n_workers_done_with_threads);
 164     if (new_value == n_workers) {
 165       // This thread is last. Notify the others.
 166       MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
 167       _lock->notify_all();
 168     }
 169   }
 170 }
 171 
 172 void SharedHeap::StrongRootsScope::wait_until_all_workers_done_with_threads(uint n_workers) {
 173   assert(UseG1GC,                          "Currently only used by G1");
 174   assert(ClassUnloadingWithConcurrentMark, "Currently only needed when doing G1 Class Unloading");
 175 
 176   // No need to use the barrier if this is single-threaded code.
 177   if (n_workers > 0 && (uint)_n_workers_done_with_threads != n_workers) {
 178     MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
 179     while ((uint)_n_workers_done_with_threads != n_workers) {
 180       _lock->wait(Mutex::_no_safepoint_check_flag, 0, false);
 181     }
 182   }
 183 }
 184 
 185 void SharedHeap::process_roots(bool activate_scope,
 186                                ScanningOption so,
 187                                OopClosure* strong_roots,
 188                                OopClosure* weak_roots,
 189                                CLDClosure* strong_cld_closure,
 190                                CLDClosure* weak_cld_closure,
 191                                CodeBlobClosure* code_roots) {
 192   StrongRootsScope srs(this, activate_scope);
 193 
 194   // General roots.
 195   assert(_strong_roots_parity != 0, "must have called prologue code");
 196   assert(code_roots != NULL, "code root closure should always be set");
 197   // _n_termination for _process_strong_tasks should be set up stream
 198   // in a method not running in a GC worker.  Otherwise the GC worker
 199   // could be trying to change the termination condition while the task
 200   // is executing in another GC worker.
 201 
 202   // Iterating over the CLDG and the Threads are done early to allow G1 to
 203   // first process the strong CLDs and nmethods and then, after a barrier,
 204   // let the thread process the weak CLDs and nmethods.
 205 
 206   if (!_process_strong_tasks->is_task_claimed(SH_PS_ClassLoaderDataGraph_oops_do)) {
 207     ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure);
 208   }
 209 
 210   // Some CLDs contained in the thread frames should be considered strong.
 211   // Don't process them if they will be processed during the ClassLoaderDataGraph phase.
 212   CLDClosure* roots_from_clds_p = (strong_cld_closure != weak_cld_closure) ? strong_cld_closure : NULL;
 213   // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway
 214   CodeBlobClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots;
 215 
 216   Threads::possibly_parallel_oops_do(strong_roots, roots_from_clds_p, roots_from_code_p);
 217 
 218   // This is the point where this worker thread will not find more strong CLDs/nmethods.
 219   // Report this so G1 can synchronize the strong and weak CLDs/nmethods processing.
 220   active_strong_roots_scope()->mark_worker_done_with_threads(n_par_threads());
 221 
 222   if (!_process_strong_tasks->is_task_claimed(SH_PS_Universe_oops_do)) {
 223     Universe::oops_do(strong_roots);
 224   }
 225   // Global (strong) JNI handles
 226   if (!_process_strong_tasks->is_task_claimed(SH_PS_JNIHandles_oops_do))
 227     JNIHandles::oops_do(strong_roots);
 228 
 229   if (!_process_strong_tasks-> is_task_claimed(SH_PS_ObjectSynchronizer_oops_do))
 230     ObjectSynchronizer::oops_do(strong_roots);
 231   if (!_process_strong_tasks->is_task_claimed(SH_PS_FlatProfiler_oops_do))
 232     FlatProfiler::oops_do(strong_roots);
 233   if (!_process_strong_tasks->is_task_claimed(SH_PS_Management_oops_do))
 234     Management::oops_do(strong_roots);
 235   if (!_process_strong_tasks->is_task_claimed(SH_PS_jvmti_oops_do))
 236     JvmtiExport::oops_do(strong_roots);
 237 
 238   if (!_process_strong_tasks->is_task_claimed(SH_PS_SystemDictionary_oops_do)) {
 239     SystemDictionary::roots_oops_do(strong_roots, weak_roots);
 240   }
 241 
 242   // All threads execute the following. A specific chunk of buckets
 243   // from the StringTable are the individual tasks.
 244   if (weak_roots != NULL) {
 245     if (CollectedHeap::use_parallel_gc_threads()) {
 246       StringTable::possibly_parallel_oops_do(weak_roots);
 247     } else {
 248       StringTable::oops_do(weak_roots);
 249     }
 250   }
 251 
 252   if (!_process_strong_tasks->is_task_claimed(SH_PS_CodeCache_oops_do)) {
 253     if (so & SO_ScavengeCodeCache) {
 254       assert(code_roots != NULL, "must supply closure for code cache");
 255 
 256       // We only visit parts of the CodeCache when scavenging.
 257       CodeCache::scavenge_root_nmethods_do(code_roots);
 258     }
 259     if (so & SO_AllCodeCache) {
 260       assert(code_roots != NULL, "must supply closure for code cache");
 261 
 262       // CMSCollector uses this to do intermediate-strength collections.
 263       // We scan the entire code cache, since CodeCache::do_unloading is not called.
 264       CodeCache::blobs_do(code_roots);
 265     }
 266     // Verify that the code cache contents are not subject to
 267     // movement by a scavenging collection.
 268     DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations));
 269     DEBUG_ONLY(CodeCache::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable));
 270   }
 271 
 272   _process_strong_tasks->all_tasks_completed();
 273 }
 274 
 275 void SharedHeap::process_all_roots(bool activate_scope,
 276                                    ScanningOption so,
 277                                    OopClosure* roots,
 278                                    CLDClosure* cld_closure,
 279                                    CodeBlobClosure* code_closure) {
 280   process_roots(activate_scope, so,
 281                 roots, roots,
 282                 cld_closure, cld_closure,
 283                 code_closure);
 284 }
 285 
 286 void SharedHeap::process_strong_roots(bool activate_scope,
 287                                       ScanningOption so,
 288                                       OopClosure* roots,
 289                                       CLDClosure* cld_closure,
 290                                       CodeBlobClosure* code_closure) {
 291   process_roots(activate_scope, so,
 292                 roots, NULL,
 293                 cld_closure, NULL,
 294                 code_closure);
 295 }
 296 
 297 
 298 class AlwaysTrueClosure: public BoolObjectClosure {
 299 public:
 300   bool do_object_b(oop p) { return true; }
 301 };
 302 static AlwaysTrueClosure always_true;
 303 
 304 void SharedHeap::process_weak_roots(OopClosure* root_closure) {
 305   // Global (weak) JNI handles
 306   JNIHandles::weak_oops_do(&always_true, root_closure);
 307 }
 308 
 309 void SharedHeap::set_barrier_set(BarrierSet* bs) {
 310   _barrier_set = bs;
 311   // Cached barrier set for fast access in oops
 312   oopDesc::set_bs(bs);
 313 }
 314 
 315 void SharedHeap::post_initialize() {
 316   CollectedHeap::post_initialize();
 317   ref_processing_init();
 318 }
 319 
 320 void SharedHeap::ref_processing_init() {}
 321 
 322 // Some utilities.
 323 void SharedHeap::print_size_transition(outputStream* out,
 324                                        size_t bytes_before,
 325                                        size_t bytes_after,
 326                                        size_t capacity) {
 327   out->print(" " SIZE_FORMAT "%s->" SIZE_FORMAT "%s(" SIZE_FORMAT "%s)",
 328              byte_size_in_proper_unit(bytes_before),
 329              proper_unit_for_byte_size(bytes_before),
 330              byte_size_in_proper_unit(bytes_after),
 331              proper_unit_for_byte_size(bytes_after),
 332              byte_size_in_proper_unit(capacity),
 333              proper_unit_for_byte_size(capacity));
 334 }