1 /*
   2  * Copyright (c) 2003, 2018, 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/systemDictionary.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "runtime/handles.inline.hpp"
  31 #include "runtime/javaCalls.hpp"
  32 #include "runtime/orderAccess.hpp"
  33 #include "services/lowMemoryDetector.hpp"
  34 #include "services/management.hpp"
  35 #include "services/memoryManager.hpp"
  36 #include "services/memoryPool.hpp"
  37 #include "services/memoryService.hpp"
  38 #include "services/gcNotifier.hpp"
  39 #include "utilities/dtrace.hpp"
  40 
  41 MemoryManager::MemoryManager(const char* name) : _name(name) {
  42   _num_pools = 0;
  43   (void)const_cast<instanceOop&>(_memory_mgr_obj = instanceOop(NULL));
  44 }
  45 
  46 int MemoryManager::add_pool(MemoryPool* pool) {
  47   int index = _num_pools;
  48   assert(index < MemoryManager::max_num_pools, "_num_pools exceeds the max");
  49   if (index < MemoryManager::max_num_pools) {
  50     _pools[index] = pool;
  51     _num_pools++;
  52   }
  53   pool->add_manager(this);
  54   return index;
  55 }
  56 
  57 MemoryManager* MemoryManager::get_code_cache_memory_manager() {
  58   return new MemoryManager("CodeCacheManager");
  59 }
  60 
  61 MemoryManager* MemoryManager::get_metaspace_memory_manager() {
  62   return new MemoryManager("Metaspace Manager");
  63 }
  64 
  65 instanceOop MemoryManager::get_memory_manager_instance(TRAPS) {
  66   // Must do an acquire so as to force ordering of subsequent
  67   // loads from anything _memory_mgr_obj points to or implies.
  68   instanceOop mgr_obj = OrderAccess::load_acquire(&_memory_mgr_obj);
  69   if (mgr_obj == NULL) {
  70     // It's ok for more than one thread to execute the code up to the locked region.
  71     // Extra manager instances will just be gc'ed.
  72     Klass* k = Management::sun_management_ManagementFactoryHelper_klass(CHECK_0);
  73 
  74     Handle mgr_name = java_lang_String::create_from_str(name(), CHECK_0);
  75 
  76     JavaValue result(T_OBJECT);
  77     JavaCallArguments args;
  78     args.push_oop(mgr_name);    // Argument 1
  79 
  80     Symbol* method_name = NULL;
  81     Symbol* signature = NULL;
  82     if (is_gc_memory_manager()) {
  83       Klass* extKlass = Management::com_sun_management_internal_GarbageCollectorExtImpl_klass(CHECK_0);
  84       // com.sun.management.GarbageCollectorMXBean is in jdk.management module which may not be present.
  85       if (extKlass != NULL) {
  86         k = extKlass;
  87       }
  88 
  89       method_name = vmSymbols::createGarbageCollector_name();
  90 
  91       signature = vmSymbols::createGarbageCollector_signature();
  92       args.push_oop(Handle());      // Argument 2 (for future extension)
  93     } else {
  94       method_name = vmSymbols::createMemoryManager_name();
  95       signature = vmSymbols::createMemoryManager_signature();
  96     }
  97 
  98     InstanceKlass* ik = InstanceKlass::cast(k);
  99 
 100     JavaCalls::call_static(&result,
 101                            ik,
 102                            method_name,
 103                            signature,
 104                            &args,
 105                            CHECK_0);
 106 
 107     instanceOop m = (instanceOop) result.get_jobject();
 108     instanceHandle mgr(THREAD, m);
 109 
 110     {
 111       // Get lock before setting _memory_mgr_obj
 112       // since another thread may have created the instance
 113       MutexLocker ml(Management_lock);
 114 
 115       // Check if another thread has created the management object.  We reload
 116       // _memory_mgr_obj here because some other thread may have initialized
 117       // it while we were executing the code before the lock.
 118       //
 119       // The lock has done an acquire, so the load can't float above it, but
 120       // we need to do a load_acquire as above.
 121       mgr_obj = OrderAccess::load_acquire(&_memory_mgr_obj);
 122       if (mgr_obj != NULL) {
 123          return mgr_obj;
 124       }
 125 
 126       // Get the address of the object we created via call_special.
 127       mgr_obj = mgr();
 128 
 129       // Use store barrier to make sure the memory accesses associated
 130       // with creating the management object are visible before publishing
 131       // its address.  The unlock will publish the store to _memory_mgr_obj
 132       // because it does a release first.
 133       OrderAccess::release_store(&_memory_mgr_obj, mgr_obj);
 134     }
 135   }
 136 
 137   return mgr_obj;
 138 }
 139 
 140 void MemoryManager::oops_do(OopClosure* f) {
 141   f->do_oop((oop*) &_memory_mgr_obj);
 142 }
 143 
 144 GCStatInfo::GCStatInfo(int num_pools) {
 145   // initialize the arrays for memory usage
 146   _before_gc_usage_array = (MemoryUsage*) NEW_C_HEAP_ARRAY(MemoryUsage, num_pools, mtInternal);
 147   _after_gc_usage_array  = (MemoryUsage*) NEW_C_HEAP_ARRAY(MemoryUsage, num_pools, mtInternal);
 148   _usage_array_size = num_pools;
 149   clear();
 150 }
 151 
 152 GCStatInfo::~GCStatInfo() {
 153   FREE_C_HEAP_ARRAY(MemoryUsage*, _before_gc_usage_array);
 154   FREE_C_HEAP_ARRAY(MemoryUsage*, _after_gc_usage_array);
 155 }
 156 
 157 void GCStatInfo::set_gc_usage(int pool_index, MemoryUsage usage, bool before_gc) {
 158   MemoryUsage* gc_usage_array;
 159   if (before_gc) {
 160     gc_usage_array = _before_gc_usage_array;
 161   } else {
 162     gc_usage_array = _after_gc_usage_array;
 163   }
 164   gc_usage_array[pool_index] = usage;
 165 }
 166 
 167 void GCStatInfo::clear() {
 168   _index = 0;
 169   _start_time = 0L;
 170   _end_time = 0L;
 171   size_t len = _usage_array_size * sizeof(MemoryUsage);
 172   memset(_before_gc_usage_array, 0, len);
 173   memset(_after_gc_usage_array, 0, len);
 174 }
 175 
 176 
 177 GCMemoryManager::GCMemoryManager(const char* name, const char* gc_end_message) :
 178   MemoryManager(name), _gc_end_message(gc_end_message) {
 179   _num_collections = 0;
 180   _last_gc_stat = NULL;
 181   _last_gc_lock = new Mutex(Mutex::leaf, "_last_gc_lock", true,
 182                             Monitor::_safepoint_check_never);
 183   _current_gc_stat = NULL;
 184   _num_gc_threads = 1;
 185   _notification_enabled = false;
 186 }
 187 
 188 GCMemoryManager::~GCMemoryManager() {
 189   delete _last_gc_stat;
 190   delete _last_gc_lock;
 191   delete _current_gc_stat;
 192 }
 193 
 194 void GCMemoryManager::add_pool(MemoryPool* pool) {
 195   add_pool(pool, true);
 196 }
 197 
 198 void GCMemoryManager::add_pool(MemoryPool* pool, bool always_affected_by_gc) {
 199   int index = MemoryManager::add_pool(pool);
 200   _pool_always_affected_by_gc[index] = always_affected_by_gc;
 201 }
 202 
 203 void GCMemoryManager::initialize_gc_stat_info() {
 204   assert(MemoryService::num_memory_pools() > 0, "should have one or more memory pools");
 205   _last_gc_stat = new(ResourceObj::C_HEAP, mtGC) GCStatInfo(MemoryService::num_memory_pools());
 206   _current_gc_stat = new(ResourceObj::C_HEAP, mtGC) GCStatInfo(MemoryService::num_memory_pools());
 207   // tracking concurrent collections we need two objects: one to update, and one to
 208   // hold the publicly available "last (completed) gc" information.
 209 }
 210 
 211 void GCMemoryManager::gc_begin(bool recordGCBeginTime, bool recordPreGCUsage,
 212                                bool recordAccumulatedGCTime) {
 213   // Inactive memory managers (concurrent in G1 legacy mode) will not be initialized.
 214   if (_last_gc_stat == NULL && _current_gc_stat == NULL) return;
 215 
 216   if (recordAccumulatedGCTime) {
 217     _accumulated_timer.start();
 218   }
 219   // _num_collections now increases in gc_end, to count completed collections
 220   if (recordGCBeginTime) {
 221     _current_gc_stat->set_index(_num_collections+1);
 222     _current_gc_stat->set_start_time(Management::timestamp());
 223   }
 224 
 225   if (recordPreGCUsage) {
 226     // Keep memory usage of all memory pools
 227     for (int i = 0; i < MemoryService::num_memory_pools(); i++) {
 228       MemoryPool* pool = MemoryService::get_memory_pool(i);
 229       MemoryUsage usage = pool->get_memory_usage();
 230       _current_gc_stat->set_before_gc_usage(i, usage);
 231       HOTSPOT_MEM_POOL_GC_BEGIN(
 232         (char *) name(), strlen(name()),
 233         (char *) pool->name(), strlen(pool->name()),
 234         usage.init_size(), usage.used(),
 235         usage.committed(), usage.max_size());
 236     }
 237   }
 238 }
 239 
 240 // A collector MUST, even if it does not complete for some reason,
 241 // make a TraceMemoryManagerStats object where countCollection is true,
 242 // to ensure the current gc stat is placed in _last_gc_stat.
 243 void GCMemoryManager::gc_end(bool recordPostGCUsage,
 244                              bool recordAccumulatedGCTime,
 245                              bool recordGCEndTime, bool countCollection,
 246                              GCCause::Cause cause,
 247                              bool allMemoryPoolsAffected) {
 248   if (_last_gc_stat == NULL && _current_gc_stat == NULL) return;
 249 
 250   if (recordAccumulatedGCTime) {
 251     _accumulated_timer.stop();
 252   }
 253   if (recordGCEndTime) {
 254     _current_gc_stat->set_end_time(Management::timestamp());
 255   }
 256 
 257   if (recordPostGCUsage) {
 258     int i;
 259     // keep the last gc statistics for all memory pools
 260     for (i = 0; i < MemoryService::num_memory_pools(); i++) {
 261       MemoryPool* pool = MemoryService::get_memory_pool(i);
 262       MemoryUsage usage = pool->get_memory_usage();
 263 
 264       HOTSPOT_MEM_POOL_GC_END(
 265         (char *) name(), strlen(name()),
 266         (char *) pool->name(), strlen(pool->name()),
 267         usage.init_size(), usage.used(),
 268         usage.committed(), usage.max_size());
 269 
 270       _current_gc_stat->set_after_gc_usage(i, usage);
 271     }
 272 
 273     // Set last collection usage of the memory pools managed by this collector
 274     for (i = 0; i < num_memory_pools(); i++) {
 275       MemoryPool* pool = get_memory_pool(i);
 276       MemoryUsage usage = pool->get_memory_usage();
 277 
 278       if (allMemoryPoolsAffected || pool_always_affected_by_gc(i)) {
 279         // Compare with GC usage threshold
 280         pool->set_last_collection_usage(usage);
 281         LowMemoryDetector::detect_after_gc_memory(pool);
 282       }
 283     }
 284   }
 285 
 286   if (countCollection) {
 287     _num_collections++;
 288     // alternately update two objects making one public when complete
 289     {
 290       MutexLockerEx ml(_last_gc_lock, Mutex::_no_safepoint_check_flag);
 291       GCStatInfo *tmp = _last_gc_stat;
 292       _last_gc_stat = _current_gc_stat;
 293       _current_gc_stat = tmp;
 294       // reset the current stat for diagnosability purposes
 295       _current_gc_stat->clear();
 296     }
 297 
 298     if (is_notification_enabled()) {
 299       GCNotifier::pushNotification(this, _gc_end_message, GCCause::to_string(cause));
 300     }
 301   }
 302 }
 303 
 304 size_t GCMemoryManager::get_last_gc_stat(GCStatInfo* dest) {
 305   MutexLockerEx ml(_last_gc_lock, Mutex::_no_safepoint_check_flag);
 306   if (_last_gc_stat->gc_index() != 0) {
 307     dest->set_index(_last_gc_stat->gc_index());
 308     dest->set_start_time(_last_gc_stat->start_time());
 309     dest->set_end_time(_last_gc_stat->end_time());
 310     assert(dest->usage_array_size() == _last_gc_stat->usage_array_size(),
 311            "Must have same array size");
 312     size_t len = dest->usage_array_size() * sizeof(MemoryUsage);
 313     memcpy(dest->before_gc_usage_array(), _last_gc_stat->before_gc_usage_array(), len);
 314     memcpy(dest->after_gc_usage_array(), _last_gc_stat->after_gc_usage_array(), len);
 315   }
 316   return _last_gc_stat->gc_index();
 317 }