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