1 /*
   2  * Copyright (c) 2012, 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 #include "precompiled.hpp"
  25 #include "jvm.h"
  26 
  27 #include "runtime/mutex.hpp"
  28 #include "runtime/vmThread.hpp"
  29 #include "runtime/vm_operations.hpp"
  30 #include "services/memBaseline.hpp"
  31 #include "services/memReporter.hpp"
  32 #include "services/mallocTracker.inline.hpp"
  33 #include "services/memTracker.hpp"
  34 #include "utilities/defaultStream.hpp"
  35 #include "utilities/vmError.hpp"
  36 
  37 #ifdef SOLARIS
  38   volatile bool NMT_stack_walkable = false;
  39 #else
  40   volatile bool NMT_stack_walkable = true;
  41 #endif
  42 
  43 volatile NMT_TrackingLevel MemTracker::_tracking_level = NMT_unknown;
  44 NMT_TrackingLevel MemTracker::_cmdline_tracking_level = NMT_unknown;
  45 
  46 MemBaseline MemTracker::_baseline;
  47 Mutex*      MemTracker::_query_lock = NULL;
  48 bool MemTracker::_is_nmt_env_valid = true;
  49 
  50 
  51 NMT_TrackingLevel MemTracker::init_tracking_level() {
  52   NMT_TrackingLevel level = NMT_off;
  53   char buf[64];
  54   jio_snprintf(buf, sizeof(buf), "NMT_LEVEL_%d", os::current_process_id());
  55   const char *nmt_option = ::getenv(buf);
  56   if (nmt_option != NULL) {
  57     if (strcmp(nmt_option, "summary") == 0) {
  58       level = NMT_summary;
  59     } else if (strcmp(nmt_option, "detail") == 0) {
  60       level = NMT_detail;
  61     } else if (strcmp(nmt_option, "off") != 0) {
  62       // The option value is invalid
  63       _is_nmt_env_valid = false;
  64     }
  65 
  66     // Remove the environment variable to avoid leaking to child processes
  67     os::unsetenv(buf);
  68   }
  69 
  70   // Construct NativeCallStack::EMPTY_STACK. It may get constructed twice,
  71   // but it is benign, the results are the same.
  72   ::new ((void*)&NativeCallStack::EMPTY_STACK) NativeCallStack(0, false);
  73 
  74   if (!MallocTracker::initialize(level) ||
  75       !VirtualMemoryTracker::initialize(level)) {
  76     level = NMT_off;
  77   }
  78   return level;
  79 }
  80 
  81 void MemTracker::init() {
  82   NMT_TrackingLevel level = tracking_level();
  83   if (level >= NMT_summary) {
  84     if (!VirtualMemoryTracker::late_initialize(level)) {
  85       shutdown();
  86       return;
  87     }
  88     _query_lock = new (std::nothrow) Mutex(Monitor::max_nonleaf, "NMT_queryLock");
  89     // Already OOM. It is unlikely, but still have to handle it.
  90     if (_query_lock == NULL) {
  91       shutdown();
  92     }
  93   }
  94 }
  95 
  96 bool MemTracker::check_launcher_nmt_support(const char* value) {
  97   if (strcmp(value, "=detail") == 0) {
  98     if (MemTracker::tracking_level() != NMT_detail) {
  99       return false;
 100     }
 101   } else if (strcmp(value, "=summary") == 0) {
 102     if (MemTracker::tracking_level() != NMT_summary) {
 103       return false;
 104     }
 105   } else if (strcmp(value, "=off") == 0) {
 106     if (MemTracker::tracking_level() != NMT_off) {
 107       return false;
 108     }
 109   } else {
 110     _is_nmt_env_valid = false;
 111   }
 112 
 113   return true;
 114 }
 115 
 116 bool MemTracker::verify_nmt_option() {
 117   return _is_nmt_env_valid;
 118 }
 119 
 120 void* MemTracker::malloc_base(void* memblock) {
 121   return MallocTracker::get_base(memblock);
 122 }
 123 
 124 void Tracker::record(address addr, size_t size) {
 125   if (MemTracker::tracking_level() < NMT_summary) return;
 126   switch(_type) {
 127     case uncommit:
 128       VirtualMemoryTracker::remove_uncommitted_region(addr, size);
 129       break;
 130     case release:
 131       VirtualMemoryTracker::remove_released_region(addr, size);
 132         break;
 133     default:
 134       ShouldNotReachHere();
 135   }
 136 }
 137 
 138 
 139 // Shutdown can only be issued via JCmd, and NMT JCmd is serialized by lock
 140 void MemTracker::shutdown() {
 141   // We can only shutdown NMT to minimal tracking level if it is ever on.
 142   if (tracking_level () > NMT_minimal) {
 143     transition_to(NMT_minimal);
 144   }
 145 }
 146 
 147 bool MemTracker::transition_to(NMT_TrackingLevel level) {
 148   NMT_TrackingLevel current_level = tracking_level();
 149 
 150   assert(level != NMT_off || current_level == NMT_off, "Cannot transition NMT to off");
 151 
 152   if (current_level == level) {
 153     return true;
 154   } else if (current_level > level) {
 155     // Downgrade tracking level, we want to lower the tracking level first
 156     _tracking_level = level;
 157     // Make _tracking_level visible immediately.
 158     OrderAccess::fence();
 159     VirtualMemoryTracker::transition(current_level, level);
 160     MallocTracker::transition(current_level, level);
 161   } else {
 162     // Upgrading tracking level is not supported and has never been supported.
 163     // Allocating and deallocating malloc tracking structures is not thread safe and
 164     // leads to inconsistencies unless a lot coarser locks are added.
 165   }
 166   return true;
 167 }
 168 
 169 void MemTracker::report(bool summary_only, outputStream* output) {
 170  assert(output != NULL, "No output stream");
 171   MemBaseline baseline;
 172   if (baseline.baseline(summary_only)) {
 173     if (summary_only) {
 174       MemSummaryReporter rpt(baseline, output);
 175       rpt.report();
 176     } else {
 177       MemDetailReporter rpt(baseline, output);
 178       rpt.report();
 179 
 180       // Metadata reporting requires a safepoint, so avoid it if VM is not in good state.
 181       assert(!VMError::fatal_error_in_progress(), "Do not report metadata in error report");
 182       VM_PrintMetadata vmop(output, K);
 183       VMThread::execute(&vmop);
 184     }
 185   }
 186 }
 187 
 188 // This is a walker to gather malloc site hashtable statistics,
 189 // the result is used for tuning.
 190 class StatisticsWalker : public MallocSiteWalker {
 191  private:
 192   enum Threshold {
 193     // aggregates statistics over this threshold into one
 194     // line item.
 195     report_threshold = 20
 196   };
 197 
 198  private:
 199   // Number of allocation sites that have all memory freed
 200   int   _empty_entries;
 201   // Total number of allocation sites, include empty sites
 202   int   _total_entries;
 203   // Number of captured call stack distribution
 204   int   _stack_depth_distribution[NMT_TrackingStackDepth];
 205   // Hash distribution
 206   int   _hash_distribution[report_threshold];
 207   // Number of hash buckets that have entries over the threshold
 208   int   _bucket_over_threshold;
 209 
 210   // The hash bucket that walker is currently walking
 211   int   _current_hash_bucket;
 212   // The length of current hash bucket
 213   int   _current_bucket_length;
 214   // Number of hash buckets that are not empty
 215   int   _used_buckets;
 216   // Longest hash bucket length
 217   int   _longest_bucket_length;
 218 
 219  public:
 220   StatisticsWalker() : _empty_entries(0), _total_entries(0) {
 221     int index = 0;
 222     for (index = 0; index < NMT_TrackingStackDepth; index ++) {
 223       _stack_depth_distribution[index] = 0;
 224     }
 225     for (index = 0; index < report_threshold; index ++) {
 226       _hash_distribution[index] = 0;
 227     }
 228     _bucket_over_threshold = 0;
 229     _longest_bucket_length = 0;
 230     _current_hash_bucket = -1;
 231     _current_bucket_length = 0;
 232     _used_buckets = 0;
 233   }
 234 
 235   virtual bool do_malloc_site(const MallocSite* e) {
 236     if (e->size() == 0) _empty_entries ++;
 237     _total_entries ++;
 238 
 239     // stack depth distrubution
 240     int frames = e->call_stack()->frames();
 241     _stack_depth_distribution[frames - 1] ++;
 242 
 243     // hash distribution
 244     int hash_bucket = e->hash() % MallocSiteTable::hash_buckets();
 245     if (_current_hash_bucket == -1) {
 246       _current_hash_bucket = hash_bucket;
 247       _current_bucket_length = 1;
 248     } else if (_current_hash_bucket == hash_bucket) {
 249       _current_bucket_length ++;
 250     } else {
 251       record_bucket_length(_current_bucket_length);
 252       _current_hash_bucket = hash_bucket;
 253       _current_bucket_length = 1;
 254     }
 255     return true;
 256   }
 257 
 258   // walk completed
 259   void completed() {
 260     record_bucket_length(_current_bucket_length);
 261   }
 262 
 263   void report_statistics(outputStream* out) {
 264     int index;
 265     out->print_cr("Malloc allocation site table:");
 266     out->print_cr("\tTotal entries: %d", _total_entries);
 267     out->print_cr("\tEmpty entries: %d (%2.2f%%)", _empty_entries, ((float)_empty_entries * 100) / _total_entries);
 268     out->print_cr(" ");
 269     out->print_cr("Hash distribution:");
 270     if (_used_buckets < MallocSiteTable::hash_buckets()) {
 271       out->print_cr("empty bucket: %d", (MallocSiteTable::hash_buckets() - _used_buckets));
 272     }
 273     for (index = 0; index < report_threshold; index ++) {
 274       if (_hash_distribution[index] != 0) {
 275         if (index == 0) {
 276           out->print_cr("  %d    entry: %d", 1, _hash_distribution[0]);
 277         } else if (index < 9) { // single digit
 278           out->print_cr("  %d  entries: %d", (index + 1), _hash_distribution[index]);
 279         } else {
 280           out->print_cr(" %d entries: %d", (index + 1), _hash_distribution[index]);
 281         }
 282       }
 283     }
 284     if (_bucket_over_threshold > 0) {
 285       out->print_cr(" >%d entries: %d", report_threshold,  _bucket_over_threshold);
 286     }
 287     out->print_cr("most entries: %d", _longest_bucket_length);
 288     out->print_cr(" ");
 289     out->print_cr("Call stack depth distribution:");
 290     for (index = 0; index < NMT_TrackingStackDepth; index ++) {
 291       if (_stack_depth_distribution[index] > 0) {
 292         out->print_cr("\t%d: %d", index + 1, _stack_depth_distribution[index]);
 293       }
 294     }
 295   }
 296 
 297  private:
 298   void record_bucket_length(int length) {
 299     _used_buckets ++;
 300     if (length <= report_threshold) {
 301       _hash_distribution[length - 1] ++;
 302     } else {
 303       _bucket_over_threshold ++;
 304     }
 305     _longest_bucket_length = MAX2(_longest_bucket_length, length);
 306   }
 307 };
 308 
 309 
 310 void MemTracker::tuning_statistics(outputStream* out) {
 311   // NMT statistics
 312   StatisticsWalker walker;
 313   MallocSiteTable::walk_malloc_site(&walker);
 314   walker.completed();
 315 
 316   out->print_cr("Native Memory Tracking Statistics:");
 317   out->print_cr("Malloc allocation site table size: %d", MallocSiteTable::hash_buckets());
 318   out->print_cr("             Tracking stack depth: %d", NMT_TrackingStackDepth);
 319   NOT_PRODUCT(out->print_cr("Peak concurrent access: %d", MallocSiteTable::access_peak_count());)
 320   out->print_cr(" ");
 321   walker.report_statistics(out);
 322 }