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