1 /*
   2  * Copyright (c) 2012, 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 
  25 #ifndef SHARE_VM_SERVICES_MEM_TRACKER_HPP
  26 #define SHARE_VM_SERVICES_MEM_TRACKER_HPP
  27 
  28 #include "utilities/macros.hpp"
  29 
  30 #if !INCLUDE_NMT
  31 
  32 #include "utilities/ostream.hpp"
  33 
  34 class BaselineOutputer : public StackObj {
  35 
  36 };
  37 
  38 class BaselineTTYOutputer : public BaselineOutputer {
  39   public:
  40     BaselineTTYOutputer(outputStream* st) { }
  41 };
  42 
  43 class MemTracker : AllStatic {
  44   public:
  45    enum ShutdownReason {
  46       NMT_shutdown_none,     // no shutdown requested
  47       NMT_shutdown_user,     // user requested shutdown
  48       NMT_normal,            // normal shutdown, process exit
  49       NMT_out_of_memory,     // shutdown due to out of memory
  50       NMT_initialization,    // shutdown due to initialization failure
  51       NMT_use_malloc_only,   // can not combine NMT with UseMallocOnly flag
  52       NMT_error_reporting,   // shutdown by vmError::report_and_die()
  53       NMT_out_of_generation, // running out of generation queue
  54       NMT_sequence_overflow  // overflow the sequence number
  55    };
  56 
  57 
  58   public:
  59    static inline void init_tracking_options(const char* option_line) { }
  60    static inline bool is_on()   { return false; }
  61    static const char* reason()  { return "Native memory tracking is not implemented"; }
  62    static inline bool can_walk_stack() { return false; }
  63 
  64    static inline void bootstrap_single_thread() { }
  65    static inline void bootstrap_multi_thread() { }
  66    static inline void start() { }
  67 
  68    static inline void record_malloc(address addr, size_t size, MEMFLAGS flags,
  69         address pc = 0, Thread* thread = NULL) { }
  70    static inline void record_free(address addr, MEMFLAGS flags, Thread* thread = NULL) { }
  71    static inline void record_realloc(address old_addr, address new_addr, size_t size,
  72         MEMFLAGS flags, address pc = 0, Thread* thread = NULL) { }
  73    static inline void record_arena_size(address addr, size_t size) { }
  74    static inline void record_virtual_memory_reserve(address addr, size_t size,
  75         address pc = 0, Thread* thread = NULL) { }
  76    static inline void record_virtual_memory_commit(address addr, size_t size,
  77         address pc = 0, Thread* thread = NULL) { }
  78    static inline void record_virtual_memory_uncommit(address addr, size_t size,
  79         Thread* thread = NULL) { }
  80    static inline void record_virtual_memory_release(address addr, size_t size,
  81         Thread* thread = NULL) { }
  82    static inline void record_virtual_memory_type(address base, MEMFLAGS flags,
  83         Thread* thread = NULL) { }
  84    static inline bool baseline() { return false; }
  85    static inline bool has_baseline() { return false; }
  86 
  87    static void shutdown(ShutdownReason reason) { }
  88    static inline bool shutdown_in_progress() {  }
  89    static bool print_memory_usage(BaselineOutputer& out, size_t unit,
  90             bool summary_only = true) { }
  91    static bool compare_memory_usage(BaselineOutputer& out, size_t unit,
  92             bool summary_only = true) { }
  93 
  94    static bool wbtest_wait_for_data_merge() { }
  95 
  96    static inline void sync() { }
  97    static inline void thread_exiting(JavaThread* thread) { }
  98 };
  99 
 100 
 101 #else // !INCLUDE_NMT
 102 
 103 #include "memory/allocation.hpp"
 104 #include "runtime/globals.hpp"
 105 #include "runtime/mutex.hpp"
 106 #include "runtime/os.hpp"
 107 #include "runtime/thread.hpp"
 108 #include "services/memPtr.hpp"
 109 #include "services/memRecorder.hpp"
 110 #include "services/memSnapshot.hpp"
 111 #include "services/memTrackWorker.hpp"
 112 
 113 extern bool NMT_track_callsite;
 114 
 115 #ifndef MAX_UNSIGNED_LONG
 116 #define MAX_UNSIGNED_LONG    (unsigned long)(-1)
 117 #endif
 118 
 119 #ifdef ASSERT
 120   #define DEBUG_CALLER_PC  (NMT_track_callsite ? os::get_caller_pc(2) : 0)
 121 #else
 122   #define DEBUG_CALLER_PC  0
 123 #endif
 124 
 125 // The thread closure walks threads to collect per-thread
 126 // memory recorders at NMT sync point
 127 class SyncThreadRecorderClosure : public ThreadClosure {
 128  private:
 129   int _thread_count;
 130 
 131  public:
 132   SyncThreadRecorderClosure() {
 133     _thread_count =0;
 134   }
 135 
 136   void do_thread(Thread* thread);
 137   int  get_thread_count() const {
 138     return _thread_count;
 139   }
 140 };
 141 
 142 class BaselineOutputer;
 143 class MemSnapshot;
 144 class MemTrackWorker;
 145 class Thread;
 146 /*
 147  * MemTracker is the 'gate' class to native memory tracking runtime.
 148  */
 149 class MemTracker : AllStatic {
 150   friend class MemTrackWorker;
 151   friend class MemSnapshot;
 152   friend class SyncThreadRecorderClosure;
 153 
 154   // NMT state
 155   enum NMTStates {
 156     NMT_uninited,                        // not yet initialized
 157     NMT_bootstrapping_single_thread,     // bootstrapping, VM is in single thread mode
 158     NMT_bootstrapping_multi_thread,      // bootstrapping, VM is about to enter multi-thread mode
 159     NMT_started,                         // NMT fully started
 160     NMT_shutdown_pending,                // shutdown pending
 161     NMT_final_shutdown,                  // in final phase of shutdown
 162     NMT_shutdown                         // shutdown
 163   };
 164 
 165  public:
 166   // native memory tracking level
 167   enum NMTLevel {
 168     NMT_off,              // native memory tracking is off
 169     NMT_summary,          // don't track callsite
 170     NMT_detail            // track callsite also
 171   };
 172 
 173    enum ShutdownReason {
 174      NMT_shutdown_none,     // no shutdown requested
 175      NMT_shutdown_user,     // user requested shutdown
 176      NMT_normal,            // normal shutdown, process exit
 177      NMT_out_of_memory,     // shutdown due to out of memory
 178      NMT_initialization,    // shutdown due to initialization failure
 179      NMT_use_malloc_only,   // can not combine NMT with UseMallocOnly flag
 180      NMT_error_reporting,   // shutdown by vmError::report_and_die()
 181      NMT_out_of_generation, // running out of generation queue
 182      NMT_sequence_overflow  // overflow the sequence number
 183    };
 184 
 185  public:
 186   // initialize NMT tracking level from command line options, called
 187    // from VM command line parsing code
 188   static void init_tracking_options(const char* option_line);
 189 
 190   // if NMT is enabled to record memory activities
 191   static inline bool is_on() {
 192     return (_tracking_level >= NMT_summary &&
 193       _state >= NMT_bootstrapping_single_thread);
 194   }
 195 
 196   static inline enum NMTLevel tracking_level() {
 197     return _tracking_level;
 198   }
 199 
 200   // user readable reason for shutting down NMT
 201   static const char* reason() {
 202     switch(_reason) {
 203       case NMT_shutdown_none:
 204         return "Native memory tracking is not enabled";
 205       case NMT_shutdown_user:
 206         return "Native memory tracking has been shutdown by user";
 207       case NMT_normal:
 208         return "Native memory tracking has been shutdown due to process exiting";
 209       case NMT_out_of_memory:
 210         return "Native memory tracking has been shutdown due to out of native memory";
 211       case NMT_initialization:
 212         return "Native memory tracking failed to initialize";
 213       case NMT_error_reporting:
 214         return "Native memory tracking has been shutdown due to error reporting";
 215       case NMT_out_of_generation:
 216         return "Native memory tracking has been shutdown due to running out of generation buffer";
 217       case NMT_sequence_overflow:
 218         return "Native memory tracking has been shutdown due to overflow the sequence number";
 219       case NMT_use_malloc_only:
 220         return "Native memory tracking is not supported when UseMallocOnly is on";
 221       default:
 222         ShouldNotReachHere();
 223         return NULL;
 224     }
 225   }
 226 
 227   // test if we can walk native stack
 228   static bool can_walk_stack() {
 229   // native stack is not walkable during bootstrapping on sparc
 230 #if defined(SPARC)
 231     return (_state == NMT_started);
 232 #else
 233     return (_state >= NMT_bootstrapping_single_thread && _state  <= NMT_started);
 234 #endif
 235   }
 236 
 237   // if native memory tracking tracks callsite
 238   static inline bool track_callsite() { return _tracking_level == NMT_detail; }
 239 
 240   // shutdown native memory tracking capability. Native memory tracking
 241   // can be shutdown by VM when it encounters low memory scenarios.
 242   // Memory tracker should gracefully shutdown itself, and preserve the
 243   // latest memory statistics for post morten diagnosis.
 244   static void shutdown(ShutdownReason reason);
 245 
 246   // if there is shutdown requested
 247   static inline bool shutdown_in_progress() {
 248     return (_state >= NMT_shutdown_pending);
 249   }
 250 
 251   // bootstrap native memory tracking, so it can start to collect raw data
 252   // before worker thread can start
 253 
 254   // the first phase of bootstrapping, when VM still in single-threaded mode
 255   static void bootstrap_single_thread();
 256   // the second phase of bootstrapping, VM is about or already in multi-threaded mode
 257   static void bootstrap_multi_thread();
 258 
 259 
 260   // start() has to be called when VM still in single thread mode, but after
 261   // command line option parsing is done.
 262   static void start();
 263 
 264   // record a 'malloc' call
 265   static inline void record_malloc(address addr, size_t size, MEMFLAGS flags,
 266                             address pc = 0, Thread* thread = NULL) {
 267     if (is_on() && NMT_CAN_TRACK(flags)) {
 268       assert(size > 0, "Sanity check");
 269       create_memory_record(addr, (flags|MemPointerRecord::malloc_tag()), size, pc, thread);
 270     }
 271   }
 272   // record a 'free' call
 273   static inline void record_free(address addr, MEMFLAGS flags, Thread* thread = NULL) {
 274     if (is_on() && NMT_CAN_TRACK(flags)) {
 275       create_memory_record(addr, MemPointerRecord::free_tag(), 0, 0, thread);
 276     }
 277   }
 278   // record a 'realloc' call
 279   static inline void record_realloc(address old_addr, address new_addr, size_t size,
 280        MEMFLAGS flags, address pc = 0, Thread* thread = NULL) {
 281     if (is_on() && NMT_CAN_TRACK(flags)) {
 282       assert(size > 0, "Sanity check");
 283       record_free(old_addr, flags, thread);
 284       record_malloc(new_addr, size, flags, pc, thread);
 285     }
 286   }
 287 
 288   // record arena memory size
 289   static inline void record_arena_size(address addr, size_t size) {
 290     // we add a positive offset to arena address, so we can have arena memory record
 291     // sorted after arena record
 292     if (is_on() && !UseMallocOnly) {
 293       assert(addr != NULL, "Sanity check");
 294       create_memory_record((addr + sizeof(void*)), MemPointerRecord::arena_size_tag(), size,
 295         DEBUG_CALLER_PC, NULL);
 296     }
 297   }
 298 
 299   // record a virtual memory 'reserve' call
 300   static inline void record_virtual_memory_reserve(address addr, size_t size,
 301                             address pc = 0, Thread* thread = NULL) {
 302     if (is_on()) {
 303       assert(size > 0, "Sanity check");
 304       create_memory_record(addr, MemPointerRecord::virtual_memory_reserve_tag(),
 305                            size, pc, thread);
 306     }
 307   }
 308 
 309   static inline void record_thread_stack(address addr, size_t size, Thread* thr,
 310                            address pc = 0) {
 311     if (is_on()) {
 312       assert(size > 0 && thr != NULL, "Sanity check");
 313       create_memory_record(addr, MemPointerRecord::virtual_memory_reserve_tag() | mtThreadStack,
 314                           size, pc, thr);
 315       create_memory_record(addr, MemPointerRecord::virtual_memory_commit_tag() | mtThreadStack,
 316                           size, pc, thr);
 317     }
 318   }
 319 
 320   static inline void release_thread_stack(address addr, size_t size, Thread* thr) {
 321     if (is_on()) {
 322       assert(size > 0 && thr != NULL, "Sanity check");
 323       assert(!thr->is_Java_thread(), "too early");
 324       create_memory_record(addr, MemPointerRecord::virtual_memory_uncommit_tag() | mtThreadStack,
 325                           size, DEBUG_CALLER_PC, thr);
 326       create_memory_record(addr, MemPointerRecord::virtual_memory_release_tag() | mtThreadStack,
 327                           size, DEBUG_CALLER_PC, thr);
 328     }
 329   }
 330 
 331   // record a virtual memory 'commit' call
 332   static inline void record_virtual_memory_commit(address addr, size_t size,
 333                             address pc, Thread* thread = NULL) {
 334     if (is_on()) {
 335       assert(size > 0, "Sanity check");
 336       create_memory_record(addr, MemPointerRecord::virtual_memory_commit_tag(),
 337                            size, pc, thread);
 338     }
 339   }
 340 
 341   // record a virtual memory 'uncommit' call
 342   static inline void record_virtual_memory_uncommit(address addr, size_t size,
 343                             Thread* thread = NULL) {
 344     if (is_on()) {
 345       assert(size > 0, "Sanity check");
 346       create_memory_record(addr, MemPointerRecord::virtual_memory_uncommit_tag(),
 347                            size, DEBUG_CALLER_PC, thread);
 348     }
 349   }
 350 
 351   // record a virtual memory 'release' call
 352   static inline void record_virtual_memory_release(address addr, size_t size,
 353                             Thread* thread = NULL) {
 354     if (is_on()) {
 355       assert(size > 0, "Sanity check");
 356       create_memory_record(addr, MemPointerRecord::virtual_memory_release_tag(),
 357                            size, DEBUG_CALLER_PC, thread);
 358     }
 359   }
 360 
 361   // record memory type on virtual memory base address
 362   static inline void record_virtual_memory_type(address base, MEMFLAGS flags,
 363                             Thread* thread = NULL) {
 364     if (is_on()) {
 365       assert(base > 0, "wrong base address");
 366       assert((flags & (~mt_masks)) == 0, "memory type only");
 367       create_memory_record(base, (flags | MemPointerRecord::virtual_memory_type_tag()),
 368                            0, DEBUG_CALLER_PC, thread);
 369     }
 370   }
 371 
 372 
 373   // create memory baseline of current memory snapshot
 374   static bool baseline();
 375   // is there a memory baseline
 376   static bool has_baseline() {
 377     return _baseline.baselined();
 378   }
 379 
 380   // print memory usage from current snapshot
 381   static bool print_memory_usage(BaselineOutputer& out, size_t unit,
 382            bool summary_only = true);
 383   // compare memory usage between current snapshot and baseline
 384   static bool compare_memory_usage(BaselineOutputer& out, size_t unit,
 385            bool summary_only = true);
 386 
 387   // the version for whitebox testing support, it ensures that all memory
 388   // activities before this method call, are reflected in the snapshot
 389   // database.
 390   static bool wbtest_wait_for_data_merge();
 391 
 392   // sync is called within global safepoint to synchronize nmt data
 393   static void sync();
 394 
 395   // called when a thread is about to exit
 396   static void thread_exiting(JavaThread* thread);
 397 
 398   // retrieve global snapshot
 399   static MemSnapshot* get_snapshot() {
 400     if (shutdown_in_progress()) {
 401       return NULL;
 402     }
 403     return _snapshot;
 404   }
 405 
 406   // print tracker stats
 407   NOT_PRODUCT(static void print_tracker_stats(outputStream* st);)
 408   NOT_PRODUCT(static void walk_stack(int toSkip, char* buf, int len);)
 409 
 410  private:
 411   // start native memory tracking worker thread
 412   static bool start_worker();
 413 
 414   // called by worker thread to complete shutdown process
 415   static void final_shutdown();
 416 
 417  protected:
 418   // retrieve per-thread recorder of the specified thread.
 419   // if the recorder is full, it will be enqueued to overflow
 420   // queue, a new recorder is acquired from recorder pool or a
 421   // new instance is created.
 422   // when thread == NULL, it means global recorder
 423   static MemRecorder* get_thread_recorder(JavaThread* thread);
 424 
 425   // per-thread recorder pool
 426   static void release_thread_recorder(MemRecorder* rec);
 427   static void delete_all_pooled_recorders();
 428 
 429   // pending recorder queue. Recorders are queued to pending queue
 430   // when they are overflowed or collected at nmt sync point.
 431   static void enqueue_pending_recorder(MemRecorder* rec);
 432   static MemRecorder* get_pending_recorders();
 433   static void delete_all_pending_recorders();
 434 
 435  private:
 436   // retrieve a pooled memory record or create new one if there is not
 437   // one available
 438   static MemRecorder* get_new_or_pooled_instance();
 439   static void create_memory_record(address addr, MEMFLAGS type,
 440                    size_t size, address pc, Thread* thread);
 441   static void create_record_in_recorder(address addr, MEMFLAGS type,
 442                    size_t size, address pc, JavaThread* thread);
 443 
 444   static void set_current_processing_generation(unsigned long generation) {
 445     _worker_thread_idle = false;
 446     _processing_generation = generation;
 447   }
 448 
 449   static void report_worker_idle() {
 450     _worker_thread_idle = true;
 451   }
 452 
 453  private:
 454   // global memory snapshot
 455   static MemSnapshot*     _snapshot;
 456 
 457   // a memory baseline of snapshot
 458   static MemBaseline      _baseline;
 459 
 460   // query lock
 461   static Mutex*           _query_lock;
 462 
 463   // a thread can start to allocate memory before it is attached
 464   // to VM 'Thread', those memory activities are recorded here.
 465   // ThreadCritical is required to guard this global recorder.
 466   static MemRecorder*     _global_recorder;
 467 
 468   // main thread id
 469   debug_only(static intx   _main_thread_tid;)
 470 
 471   // pending recorders to be merged
 472   static volatile MemRecorder*      _merge_pending_queue;
 473 
 474   NOT_PRODUCT(static volatile jint   _pending_recorder_count;)
 475 
 476   // pooled memory recorders
 477   static volatile MemRecorder*      _pooled_recorders;
 478 
 479   // memory recorder pool management, uses following
 480   // counter to determine if a released memory recorder
 481   // should be pooled
 482 
 483   // latest thread count
 484   static int               _thread_count;
 485   // pooled recorder count
 486   static volatile jint     _pooled_recorder_count;
 487 
 488 
 489   // worker thread to merge pending recorders into snapshot
 490   static MemTrackWorker*  _worker_thread;
 491 
 492   // how many safepoints we skipped without entering sync point
 493   static int              _sync_point_skip_count;
 494 
 495   // if the tracker is properly intialized
 496   static bool             _is_tracker_ready;
 497   // tracking level (off, summary and detail)
 498   static enum NMTLevel    _tracking_level;
 499 
 500   // current nmt state
 501   static volatile enum NMTStates   _state;
 502   // the reason for shutting down nmt
 503   static enum ShutdownReason       _reason;
 504   // the generation that NMT is processing
 505   static volatile unsigned long    _processing_generation;
 506   // although NMT is still procesing current generation, but
 507   // there is not more recorder to process, set idle state
 508   static volatile bool             _worker_thread_idle;
 509 };
 510 
 511 #endif // !INCLUDE_NMT
 512 
 513 #endif // SHARE_VM_SERVICES_MEM_TRACKER_HPP