1 /*
   2  * Copyright (c) 2003, 2016, 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/resourceArea.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "runtime/interfaceSupport.hpp"
  31 #include "runtime/java.hpp"
  32 #include "runtime/javaCalls.hpp"
  33 #include "runtime/mutex.hpp"
  34 #include "runtime/mutexLocker.hpp"
  35 #include "services/lowMemoryDetector.hpp"
  36 #include "services/management.hpp"
  37 
  38 volatile bool LowMemoryDetector::_enabled_for_collected_pools = false;
  39 volatile jint LowMemoryDetector::_disabled_count = 0;
  40 
  41 bool LowMemoryDetector::has_pending_requests() {
  42   assert(Service_lock->owned_by_self(), "Must own Service_lock");
  43   bool has_requests = false;
  44   int num_memory_pools = MemoryService::num_memory_pools();
  45   for (int i = 0; i < num_memory_pools; i++) {
  46     MemoryPool* pool = MemoryService::get_memory_pool(i);
  47     SensorInfo* sensor = pool->usage_sensor();
  48     if (sensor != NULL) {
  49       has_requests = has_requests || sensor->has_pending_requests();
  50     }
  51 
  52     SensorInfo* gc_sensor = pool->gc_usage_sensor();
  53     if (gc_sensor != NULL) {
  54       has_requests = has_requests || gc_sensor->has_pending_requests();
  55     }
  56   }
  57   return has_requests;
  58 }
  59 
  60 void LowMemoryDetector::process_sensor_changes(TRAPS) {
  61   ResourceMark rm(THREAD);
  62   HandleMark hm(THREAD);
  63 
  64   // No need to hold Service_lock to call out to Java
  65   int num_memory_pools = MemoryService::num_memory_pools();
  66   for (int i = 0; i < num_memory_pools; i++) {
  67     MemoryPool* pool = MemoryService::get_memory_pool(i);
  68     SensorInfo* sensor = pool->usage_sensor();
  69     SensorInfo* gc_sensor = pool->gc_usage_sensor();
  70     if (sensor != NULL && sensor->has_pending_requests()) {
  71       sensor->process_pending_requests(CHECK);
  72     }
  73     if (gc_sensor != NULL && gc_sensor->has_pending_requests()) {
  74       gc_sensor->process_pending_requests(CHECK);
  75     }
  76   }
  77 }
  78 
  79 // This method could be called from any Java threads
  80 // and also VMThread.
  81 void LowMemoryDetector::detect_low_memory() {
  82   MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
  83 
  84   bool has_pending_requests = false;
  85   int num_memory_pools = MemoryService::num_memory_pools();
  86   for (int i = 0; i < num_memory_pools; i++) {
  87     MemoryPool* pool = MemoryService::get_memory_pool(i);
  88     SensorInfo* sensor = pool->usage_sensor();
  89     if (sensor != NULL &&
  90         pool->usage_threshold()->is_high_threshold_supported() &&
  91         pool->usage_threshold()->high_threshold() != 0) {
  92       MemoryUsage usage = pool->get_memory_usage();
  93       sensor->set_gauge_sensor_level(usage,
  94                                      pool->usage_threshold());
  95       has_pending_requests = has_pending_requests || sensor->has_pending_requests();
  96     }
  97   }
  98 
  99   if (has_pending_requests) {
 100     Service_lock->notify_all();
 101   }
 102 }
 103 
 104 // This method could be called from any Java threads
 105 // and also VMThread.
 106 void LowMemoryDetector::detect_low_memory(MemoryPool* pool) {
 107   SensorInfo* sensor = pool->usage_sensor();
 108   if (sensor == NULL ||
 109       !pool->usage_threshold()->is_high_threshold_supported() ||
 110       pool->usage_threshold()->high_threshold() == 0) {
 111     return;
 112   }
 113 
 114   {
 115     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
 116 
 117     MemoryUsage usage = pool->get_memory_usage();
 118     sensor->set_gauge_sensor_level(usage,
 119                                    pool->usage_threshold());
 120     if (sensor->has_pending_requests()) {
 121       // notify sensor state update
 122       Service_lock->notify_all();
 123     }
 124   }
 125 }
 126 
 127 // Only called by VMThread at GC time
 128 void LowMemoryDetector::detect_after_gc_memory(MemoryPool* pool) {
 129   SensorInfo* sensor = pool->gc_usage_sensor();
 130   if (sensor == NULL ||
 131       !pool->gc_usage_threshold()->is_high_threshold_supported() ||
 132       pool->gc_usage_threshold()->high_threshold() == 0) {
 133     return;
 134   }
 135 
 136   {
 137     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
 138 
 139     MemoryUsage usage = pool->get_last_collection_usage();
 140     sensor->set_counter_sensor_level(usage, pool->gc_usage_threshold());
 141 
 142     if (sensor->has_pending_requests()) {
 143       // notify sensor state update
 144       Service_lock->notify_all();
 145     }
 146   }
 147 }
 148 
 149 // recompute enabled flag
 150 void LowMemoryDetector::recompute_enabled_for_collected_pools() {
 151   bool enabled = false;
 152   int num_memory_pools = MemoryService::num_memory_pools();
 153   for (int i=0; i<num_memory_pools; i++) {
 154     MemoryPool* pool = MemoryService::get_memory_pool(i);
 155     if (pool->is_collected_pool() && is_enabled(pool)) {
 156       enabled = true;
 157       break;
 158     }
 159   }
 160   _enabled_for_collected_pools = enabled;
 161 }
 162 
 163 SensorInfo::SensorInfo() {
 164   _sensor_obj = NULL;
 165   _sensor_on = false;
 166   _sensor_count = 0;
 167   _pending_trigger_count = 0;
 168   _pending_clear_count = 0;
 169 }
 170 
 171 // When this method is used, the memory usage is monitored
 172 // as a gauge attribute.  Sensor notifications (trigger or
 173 // clear) is only emitted at the first time it crosses
 174 // a threshold.
 175 //
 176 // High and low thresholds are designed to provide a
 177 // hysteresis mechanism to avoid repeated triggering
 178 // of notifications when the attribute value makes small oscillations
 179 // around the high or low threshold value.
 180 //
 181 // The sensor will be triggered if:
 182 //  (1) the usage is crossing above the high threshold and
 183 //      the sensor is currently off and no pending
 184 //      trigger requests; or
 185 //  (2) the usage is crossing above the high threshold and
 186 //      the sensor will be off (i.e. sensor is currently on
 187 //      and has pending clear requests).
 188 //
 189 // Subsequent crossings of the high threshold value do not cause
 190 // any triggers unless the usage becomes less than the low threshold.
 191 //
 192 // The sensor will be cleared if:
 193 //  (1) the usage is crossing below the low threshold and
 194 //      the sensor is currently on and no pending
 195 //      clear requests; or
 196 //  (2) the usage is crossing below the low threshold and
 197 //      the sensor will be on (i.e. sensor is currently off
 198 //      and has pending trigger requests).
 199 //
 200 // Subsequent crossings of the low threshold value do not cause
 201 // any clears unless the usage becomes greater than or equal
 202 // to the high threshold.
 203 //
 204 // If the current level is between high and low threshold, no change.
 205 //
 206 void SensorInfo::set_gauge_sensor_level(MemoryUsage usage, ThresholdSupport* high_low_threshold) {
 207   assert(Service_lock->owned_by_self(), "Must own Service_lock");
 208   assert(high_low_threshold->is_high_threshold_supported(), "just checking");
 209 
 210   bool is_over_high = high_low_threshold->is_high_threshold_crossed(usage);
 211   bool is_below_low = high_low_threshold->is_low_threshold_crossed(usage);
 212 
 213   assert(!(is_over_high && is_below_low), "Can't be both true");
 214 
 215   if (is_over_high &&
 216         ((!_sensor_on && _pending_trigger_count == 0) ||
 217          _pending_clear_count > 0)) {
 218     // low memory detected and need to increment the trigger pending count
 219     // if the sensor is off or will be off due to _pending_clear_ > 0
 220     // Request to trigger the sensor
 221     _pending_trigger_count++;
 222     _usage = usage;
 223 
 224     if (_pending_clear_count > 0) {
 225       // non-zero pending clear requests indicates that there are
 226       // pending requests to clear this sensor.
 227       // This trigger request needs to clear this clear count
 228       // since the resulting sensor flag should be on.
 229       _pending_clear_count = 0;
 230     }
 231   } else if (is_below_low &&
 232                ((_sensor_on && _pending_clear_count == 0) ||
 233                 (_pending_trigger_count > 0 && _pending_clear_count == 0))) {
 234     // memory usage returns below the threshold
 235     // Request to clear the sensor if the sensor is on or will be on due to
 236     // _pending_trigger_count > 0 and also no clear request
 237     _pending_clear_count++;
 238   }
 239 }
 240 
 241 // When this method is used, the memory usage is monitored as a
 242 // simple counter attribute.  The sensor will be triggered
 243 // whenever the usage is crossing the threshold to keep track
 244 // of the number of times the VM detects such a condition occurs.
 245 //
 246 // High and low thresholds are designed to provide a
 247 // hysteresis mechanism to avoid repeated triggering
 248 // of notifications when the attribute value makes small oscillations
 249 // around the high or low threshold value.
 250 //
 251 // The sensor will be triggered if:
 252 //   - the usage is crossing above the high threshold regardless
 253 //     of the current sensor state.
 254 //
 255 // The sensor will be cleared if:
 256 //  (1) the usage is crossing below the low threshold and
 257 //      the sensor is currently on; or
 258 //  (2) the usage is crossing below the low threshold and
 259 //      the sensor will be on (i.e. sensor is currently off
 260 //      and has pending trigger requests).
 261 void SensorInfo::set_counter_sensor_level(MemoryUsage usage, ThresholdSupport* counter_threshold) {
 262   assert(Service_lock->owned_by_self(), "Must own Service_lock");
 263   assert(counter_threshold->is_high_threshold_supported(), "just checking");
 264 
 265   bool is_over_high = counter_threshold->is_high_threshold_crossed(usage);
 266   bool is_below_low = counter_threshold->is_low_threshold_crossed(usage);
 267 
 268   assert(!(is_over_high && is_below_low), "Can't be both true");
 269 
 270   if (is_over_high) {
 271     _pending_trigger_count++;
 272     _usage = usage;
 273     _pending_clear_count = 0;
 274   } else if (is_below_low && (_sensor_on || _pending_trigger_count > 0)) {
 275     _pending_clear_count++;
 276   }
 277 }
 278 
 279 void SensorInfo::oops_do(OopClosure* f) {
 280   f->do_oop((oop*) &_sensor_obj);
 281 }
 282 
 283 void SensorInfo::process_pending_requests(TRAPS) {
 284   assert(has_pending_requests(), "Must have pending request");
 285 
 286   int pending_count = pending_trigger_count();
 287   if (pending_clear_count() > 0) {
 288     clear(pending_count, CHECK);
 289   } else {
 290     trigger(pending_count, CHECK);
 291   }
 292 
 293 }
 294 
 295 void SensorInfo::trigger(int count, TRAPS) {
 296   assert(count <= _pending_trigger_count, "just checking");
 297   if (_sensor_obj != NULL) {
 298     Klass* k = Management::sun_management_Sensor_klass(CHECK);
 299     instanceKlassHandle sensorKlass (THREAD, k);
 300     Handle sensor_h(THREAD, _sensor_obj);
 301     Handle usage_h = MemoryService::create_MemoryUsage_obj(_usage, CHECK);
 302 
 303     JavaValue result(T_VOID);
 304     JavaCallArguments args(sensor_h);
 305     args.push_int((int) count);
 306     args.push_oop(usage_h);
 307 
 308     JavaCalls::call_virtual(&result,
 309                             sensorKlass,
 310                             vmSymbols::trigger_name(),
 311                             vmSymbols::trigger_method_signature(),
 312                             &args,
 313                             CHECK);
 314   }
 315 
 316   {
 317     // Holds Service_lock and update the sensor state
 318     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
 319     assert(_pending_trigger_count > 0, "Must have pending trigger");
 320     _sensor_on = true;
 321     _sensor_count += count;
 322     _pending_trigger_count = _pending_trigger_count - count;
 323   }
 324 }
 325 
 326 void SensorInfo::clear(int count, TRAPS) {
 327   {
 328     // Holds Service_lock and update the sensor state
 329     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
 330     if (_pending_clear_count == 0) {
 331       // Bail out if we lost a race to set_*_sensor_level() which may have
 332       // reactivated the sensor in the meantime because it was triggered again.
 333       return;
 334     }
 335     _sensor_on = false;
 336     _sensor_count += count;
 337     _pending_clear_count = 0;
 338     _pending_trigger_count = _pending_trigger_count - count;
 339   }
 340 
 341   if (_sensor_obj != NULL) {
 342     Klass* k = Management::sun_management_Sensor_klass(CHECK);
 343     instanceKlassHandle sensorKlass (THREAD, k);
 344     Handle sensor(THREAD, _sensor_obj);
 345 
 346     JavaValue result(T_VOID);
 347     JavaCallArguments args(sensor);
 348     args.push_int((int) count);
 349     JavaCalls::call_virtual(&result,
 350                             sensorKlass,
 351                             vmSymbols::clear_name(),
 352                             vmSymbols::int_void_signature(),
 353                             &args,
 354                             CHECK);
 355   }
 356 }
 357 
 358 //--------------------------------------------------------------
 359 // Non-product code
 360 
 361 #ifndef PRODUCT
 362 void SensorInfo::print() {
 363   tty->print_cr("%s count = " SIZE_FORMAT " pending_triggers = %d pending_clears = %d",
 364                 (_sensor_on ? "on" : "off"),
 365                 _sensor_count, _pending_trigger_count, _pending_clear_count);
 366 }
 367 
 368 #endif // PRODUCT