1 /*
   2  * Copyright (c) 2003, 2010, 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 "oops/oop.inline.hpp"
  29 #include "runtime/interfaceSupport.hpp"
  30 #include "runtime/java.hpp"
  31 #include "runtime/javaCalls.hpp"
  32 #include "runtime/mutex.hpp"
  33 #include "runtime/mutexLocker.hpp"
  34 #include "services/lowMemoryDetector.hpp"
  35 #include "services/management.hpp"
  36 
  37 LowMemoryDetectorThread* LowMemoryDetector::_detector_thread = NULL;
  38 volatile bool LowMemoryDetector::_enabled_for_collected_pools = false;
  39 volatile jint LowMemoryDetector::_disabled_count = 0;
  40 
  41 void LowMemoryDetector::initialize() {
  42   EXCEPTION_MARK;
  43 
  44   instanceKlassHandle klass (THREAD,  SystemDictionary::Thread_klass());
  45   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
  46 
  47   const char thread_name[] = "Low Memory Detector";
  48   Handle string = java_lang_String::create_from_str(thread_name, CHECK);
  49 
  50   // Initialize thread_oop to put it into the system threadGroup
  51   Handle thread_group (THREAD, Universe::system_thread_group());
  52   JavaValue result(T_VOID);
  53   JavaCalls::call_special(&result, thread_oop,
  54                           klass,
  55                           vmSymbolHandles::object_initializer_name(),
  56                           vmSymbolHandles::threadgroup_string_void_signature(),
  57                           thread_group,
  58                           string,
  59                           CHECK);
  60 
  61   {
  62     MutexLocker mu(Threads_lock);
  63     _detector_thread = new LowMemoryDetectorThread(&low_memory_detector_thread_entry);
  64 
  65     // At this point it may be possible that no osthread was created for the
  66     // JavaThread due to lack of memory. We would have to throw an exception
  67     // in that case. However, since this must work and we do not allow
  68     // exceptions anyway, check and abort if this fails.
  69     if (_detector_thread == NULL || _detector_thread->osthread() == NULL) {
  70       vm_exit_during_initialization("java.lang.OutOfMemoryError",
  71                                     "unable to create new native thread");
  72     }
  73 
  74     java_lang_Thread::set_thread(thread_oop(), _detector_thread);
  75     java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
  76     java_lang_Thread::set_daemon(thread_oop());
  77     _detector_thread->set_threadObj(thread_oop());
  78 
  79     Threads::add(_detector_thread);
  80     Thread::start(_detector_thread);
  81   }
  82 }
  83 
  84 bool LowMemoryDetector::has_pending_requests() {
  85   assert(LowMemory_lock->owned_by_self(), "Must own LowMemory_lock");
  86   bool has_requests = false;
  87   int num_memory_pools = MemoryService::num_memory_pools();
  88   for (int i = 0; i < num_memory_pools; i++) {
  89     MemoryPool* pool = MemoryService::get_memory_pool(i);
  90     SensorInfo* sensor = pool->usage_sensor();
  91     if (sensor != NULL) {
  92       has_requests = has_requests || sensor->has_pending_requests();
  93     }
  94 
  95     SensorInfo* gc_sensor = pool->gc_usage_sensor();
  96     if (gc_sensor != NULL) {
  97       has_requests = has_requests || gc_sensor->has_pending_requests();
  98     }
  99   }
 100   return has_requests;
 101 }
 102 
 103 void LowMemoryDetector::low_memory_detector_thread_entry(JavaThread* jt, TRAPS) {
 104   while (true) {
 105     bool   sensors_changed = false;
 106 
 107     {
 108       // _no_safepoint_check_flag is used here as LowMemory_lock is a
 109       // special lock and the VMThread may acquire this lock at safepoint.
 110       // Need state transition ThreadBlockInVM so that this thread
 111       // will be handled by safepoint correctly when this thread is
 112       // notified at a safepoint.
 113 
 114       // This ThreadBlockInVM object is not also considered to be
 115       // suspend-equivalent because LowMemoryDetector threads are
 116       // not visible to external suspension.
 117 
 118       ThreadBlockInVM tbivm(jt);
 119 
 120       MutexLockerEx ml(LowMemory_lock, Mutex::_no_safepoint_check_flag);
 121       while (!(sensors_changed = has_pending_requests())) {
 122         // wait until one of the sensors has pending requests
 123         LowMemory_lock->wait(Mutex::_no_safepoint_check_flag);
 124       }
 125     }
 126 
 127     {
 128       ResourceMark rm(THREAD);
 129       HandleMark hm(THREAD);
 130 
 131       // No need to hold LowMemory_lock to call out to Java
 132       int num_memory_pools = MemoryService::num_memory_pools();
 133       for (int i = 0; i < num_memory_pools; i++) {
 134         MemoryPool* pool = MemoryService::get_memory_pool(i);
 135         SensorInfo* sensor = pool->usage_sensor();
 136         SensorInfo* gc_sensor = pool->gc_usage_sensor();
 137         if (sensor != NULL && sensor->has_pending_requests()) {
 138           sensor->process_pending_requests(CHECK);
 139         }
 140         if (gc_sensor != NULL && gc_sensor->has_pending_requests()) {
 141           gc_sensor->process_pending_requests(CHECK);
 142         }
 143       }
 144     }
 145   }
 146 }
 147 
 148 // This method could be called from any Java threads
 149 // and also VMThread.
 150 void LowMemoryDetector::detect_low_memory() {
 151   MutexLockerEx ml(LowMemory_lock, Mutex::_no_safepoint_check_flag);
 152 
 153   bool has_pending_requests = false;
 154   int num_memory_pools = MemoryService::num_memory_pools();
 155   for (int i = 0; i < num_memory_pools; i++) {
 156     MemoryPool* pool = MemoryService::get_memory_pool(i);
 157     SensorInfo* sensor = pool->usage_sensor();
 158     if (sensor != NULL &&
 159         pool->usage_threshold()->is_high_threshold_supported() &&
 160         pool->usage_threshold()->high_threshold() != 0) {
 161       MemoryUsage usage = pool->get_memory_usage();
 162       sensor->set_gauge_sensor_level(usage,
 163                                      pool->usage_threshold());
 164       has_pending_requests = has_pending_requests || sensor->has_pending_requests();
 165     }
 166   }
 167 
 168   if (has_pending_requests) {
 169     LowMemory_lock->notify_all();
 170   }
 171 }
 172 
 173 // This method could be called from any Java threads
 174 // and also VMThread.
 175 void LowMemoryDetector::detect_low_memory(MemoryPool* pool) {
 176   SensorInfo* sensor = pool->usage_sensor();
 177   if (sensor == NULL ||
 178       !pool->usage_threshold()->is_high_threshold_supported() ||
 179       pool->usage_threshold()->high_threshold() == 0) {
 180     return;
 181   }
 182 
 183   {
 184     MutexLockerEx ml(LowMemory_lock, Mutex::_no_safepoint_check_flag);
 185 
 186     MemoryUsage usage = pool->get_memory_usage();
 187     sensor->set_gauge_sensor_level(usage,
 188                                    pool->usage_threshold());
 189     if (sensor->has_pending_requests()) {
 190       // notify sensor state update
 191       LowMemory_lock->notify_all();
 192     }
 193   }
 194 }
 195 
 196 // Only called by VMThread at GC time
 197 void LowMemoryDetector::detect_after_gc_memory(MemoryPool* pool) {
 198   SensorInfo* sensor = pool->gc_usage_sensor();
 199   if (sensor == NULL ||
 200       !pool->gc_usage_threshold()->is_high_threshold_supported() ||
 201       pool->gc_usage_threshold()->high_threshold() == 0) {
 202     return;
 203   }
 204 
 205   {
 206     MutexLockerEx ml(LowMemory_lock, Mutex::_no_safepoint_check_flag);
 207 
 208     MemoryUsage usage = pool->get_last_collection_usage();
 209     sensor->set_counter_sensor_level(usage, pool->gc_usage_threshold());
 210 
 211     if (sensor->has_pending_requests()) {
 212       // notify sensor state update
 213       LowMemory_lock->notify_all();
 214     }
 215   }
 216 }
 217 
 218 // recompute enabled flag
 219 void LowMemoryDetector::recompute_enabled_for_collected_pools() {
 220   bool enabled = false;
 221   int num_memory_pools = MemoryService::num_memory_pools();
 222   for (int i=0; i<num_memory_pools; i++) {
 223     MemoryPool* pool = MemoryService::get_memory_pool(i);
 224     if (pool->is_collected_pool() && is_enabled(pool)) {
 225       enabled = true;
 226       break;
 227     }
 228   }
 229   _enabled_for_collected_pools = enabled;
 230 }
 231 
 232 SensorInfo::SensorInfo() {
 233   _sensor_obj = NULL;
 234   _sensor_on = false;
 235   _sensor_count = 0;
 236   _pending_trigger_count = 0;
 237   _pending_clear_count = 0;
 238 }
 239 
 240 // When this method is used, the memory usage is monitored
 241 // as a gauge attribute.  Sensor notifications (trigger or
 242 // clear) is only emitted at the first time it crosses
 243 // a threshold.
 244 //
 245 // High and low thresholds are designed to provide a
 246 // hysteresis mechanism to avoid repeated triggering
 247 // of notifications when the attribute value makes small oscillations
 248 // around the high or low threshold value.
 249 //
 250 // The sensor will be triggered if:
 251 //  (1) the usage is crossing above the high threshold and
 252 //      the sensor is currently off and no pending
 253 //      trigger requests; or
 254 //  (2) the usage is crossing above the high threshold and
 255 //      the sensor will be off (i.e. sensor is currently on
 256 //      and has pending clear requests).
 257 //
 258 // Subsequent crossings of the high threshold value do not cause
 259 // any triggers unless the usage becomes less than the low threshold.
 260 //
 261 // The sensor will be cleared if:
 262 //  (1) the usage is crossing below the low threshold and
 263 //      the sensor is currently on and no pending
 264 //      clear requests; or
 265 //  (2) the usage is crossing below the low threshold and
 266 //      the sensor will be on (i.e. sensor is currently off
 267 //      and has pending trigger requests).
 268 //
 269 // Subsequent crossings of the low threshold value do not cause
 270 // any clears unless the usage becomes greater than or equal
 271 // to the high threshold.
 272 //
 273 // If the current level is between high and low threhsold, no change.
 274 //
 275 void SensorInfo::set_gauge_sensor_level(MemoryUsage usage, ThresholdSupport* high_low_threshold) {
 276   assert(high_low_threshold->is_high_threshold_supported(), "just checking");
 277 
 278   bool is_over_high = high_low_threshold->is_high_threshold_crossed(usage);
 279   bool is_below_low = high_low_threshold->is_low_threshold_crossed(usage);
 280 
 281   assert(!(is_over_high && is_below_low), "Can't be both true");
 282 
 283   if (is_over_high &&
 284         ((!_sensor_on && _pending_trigger_count == 0) ||
 285          _pending_clear_count > 0)) {
 286     // low memory detected and need to increment the trigger pending count
 287     // if the sensor is off or will be off due to _pending_clear_ > 0
 288     // Request to trigger the sensor
 289     _pending_trigger_count++;
 290     _usage = usage;
 291 
 292     if (_pending_clear_count > 0) {
 293       // non-zero pending clear requests indicates that there are
 294       // pending requests to clear this sensor.
 295       // This trigger request needs to clear this clear count
 296       // since the resulting sensor flag should be on.
 297       _pending_clear_count = 0;
 298     }
 299   } else if (is_below_low &&
 300                ((_sensor_on && _pending_clear_count == 0) ||
 301                 (_pending_trigger_count > 0 && _pending_clear_count == 0))) {
 302     // memory usage returns below the threshold
 303     // Request to clear the sensor if the sensor is on or will be on due to
 304     // _pending_trigger_count > 0 and also no clear request
 305     _pending_clear_count++;
 306   }
 307 }
 308 
 309 // When this method is used, the memory usage is monitored as a
 310 // simple counter attribute.  The sensor will be triggered
 311 // whenever the usage is crossing the threshold to keep track
 312 // of the number of times the VM detects such a condition occurs.
 313 //
 314 // High and low thresholds are designed to provide a
 315 // hysteresis mechanism to avoid repeated triggering
 316 // of notifications when the attribute value makes small oscillations
 317 // around the high or low threshold value.
 318 //
 319 // The sensor will be triggered if:
 320 //   - the usage is crossing above the high threshold regardless
 321 //     of the current sensor state.
 322 //
 323 // The sensor will be cleared if:
 324 //  (1) the usage is crossing below the low threshold and
 325 //      the sensor is currently on; or
 326 //  (2) the usage is crossing below the low threshold and
 327 //      the sensor will be on (i.e. sensor is currently off
 328 //      and has pending trigger requests).
 329 void SensorInfo::set_counter_sensor_level(MemoryUsage usage, ThresholdSupport* counter_threshold) {
 330   assert(counter_threshold->is_high_threshold_supported(), "just checking");
 331 
 332   bool is_over_high = counter_threshold->is_high_threshold_crossed(usage);
 333   bool is_below_low = counter_threshold->is_low_threshold_crossed(usage);
 334 
 335   assert(!(is_over_high && is_below_low), "Can't be both true");
 336 
 337   if (is_over_high) {
 338     _pending_trigger_count++;
 339     _usage = usage;
 340     _pending_clear_count = 0;
 341   } else if (is_below_low && (_sensor_on || _pending_trigger_count > 0)) {
 342     _pending_clear_count++;
 343   }
 344 }
 345 
 346 void SensorInfo::oops_do(OopClosure* f) {
 347   f->do_oop((oop*) &_sensor_obj);
 348 }
 349 
 350 void SensorInfo::process_pending_requests(TRAPS) {
 351   if (!has_pending_requests()) {
 352     return;
 353   }
 354 
 355   int pending_count = pending_trigger_count();
 356   if (pending_clear_count() > 0) {
 357     clear(pending_count, CHECK);
 358   } else {
 359     trigger(pending_count, CHECK);
 360   }
 361 
 362 }
 363 
 364 void SensorInfo::trigger(int count, TRAPS) {
 365   assert(count <= _pending_trigger_count, "just checking");
 366 
 367   if (_sensor_obj != NULL) {
 368     klassOop k = Management::sun_management_Sensor_klass(CHECK);
 369     instanceKlassHandle sensorKlass (THREAD, k);
 370     Handle sensor_h(THREAD, _sensor_obj);
 371     Handle usage_h = MemoryService::create_MemoryUsage_obj(_usage, CHECK);
 372 
 373     JavaValue result(T_VOID);
 374     JavaCallArguments args(sensor_h);
 375     args.push_int((int) count);
 376     args.push_oop(usage_h);
 377 
 378     JavaCalls::call_virtual(&result,
 379                             sensorKlass,
 380                             vmSymbolHandles::trigger_name(),
 381                             vmSymbolHandles::trigger_method_signature(),
 382                             &args,
 383                             CHECK);
 384   }
 385 
 386   {
 387     // Holds LowMemory_lock and update the sensor state
 388     MutexLockerEx ml(LowMemory_lock, Mutex::_no_safepoint_check_flag);
 389     _sensor_on = true;
 390     _sensor_count += count;
 391     _pending_trigger_count = _pending_trigger_count - count;
 392   }
 393 }
 394 
 395 void SensorInfo::clear(int count, TRAPS) {
 396   if (_sensor_obj != NULL) {
 397     klassOop k = Management::sun_management_Sensor_klass(CHECK);
 398     instanceKlassHandle sensorKlass (THREAD, k);
 399     Handle sensor(THREAD, _sensor_obj);
 400 
 401     JavaValue result(T_VOID);
 402     JavaCallArguments args(sensor);
 403     args.push_int((int) count);
 404     JavaCalls::call_virtual(&result,
 405                             sensorKlass,
 406                             vmSymbolHandles::clear_name(),
 407                             vmSymbolHandles::int_void_signature(),
 408                             &args,
 409                             CHECK);
 410   }
 411 
 412   {
 413     // Holds LowMemory_lock and update the sensor state
 414     MutexLockerEx ml(LowMemory_lock, Mutex::_no_safepoint_check_flag);
 415     _sensor_on = false;
 416     _pending_clear_count = 0;
 417     _pending_trigger_count = _pending_trigger_count - count;
 418   }
 419 }
 420 
 421 //--------------------------------------------------------------
 422 // Non-product code
 423 
 424 #ifndef PRODUCT
 425 void SensorInfo::print() {
 426   tty->print_cr("%s count = %ld pending_triggers = %ld pending_clears = %ld",
 427                 (_sensor_on ? "on" : "off"),
 428                 _sensor_count, _pending_trigger_count, _pending_clear_count);
 429 }
 430 
 431 #endif // PRODUCT