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