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