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